Blob


1 /*
2 * Copyright (c) 2021, 2022 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "compat.h"
19 #include <sys/ioctl.h>
20 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <assert.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <inttypes.h>
29 #include <netdb.h>
30 #include <libgen.h>
31 #include <limits.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <syslog.h>
37 #include <tls.h>
38 #include <unistd.h>
40 #ifdef HAVE_READLINE
41 #include <readline/readline.h>
42 #include <readline/history.h>
43 #endif
45 #include "kami.h"
46 #include "utils.h"
47 #include "log.h"
48 #include "9pclib.h"
50 #include "kamiftp.h"
52 #define TMPFSTR "/tmp/kamiftp.XXXXXXXXXX"
53 #define TMPFSTRLEN sizeof(TMPFSTR)
55 /* flags */
56 int tls;
57 const char *crtpath;
58 const char *keypath;
60 /* state */
61 struct tls_config *tlsconf;
62 struct tls *ctx;
63 int sock;
64 struct evbuffer *buf;
65 struct evbuffer *dirbuf;
66 uint32_t msize;
67 int bell;
68 time_t now;
70 volatile sig_atomic_t resized;
71 int tty_p;
72 int tty_width;
73 int xdump;
75 struct progress {
76 uint64_t max;
77 uint64_t done;
78 };
80 int pwdfid;
82 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
84 static char *
85 read_line(const char *prompt)
86 {
87 char *line;
89 again:
90 if ((line = readline(prompt)) == NULL)
91 return NULL;
92 /* XXX: trim spaces? */
93 if (*line == '\0') {
94 free(line);
95 goto again;
96 }
98 add_history(line);
99 return line;
102 static void
103 spawn(const char *argv0, ...)
105 pid_t pid;
106 size_t i;
107 int status;
108 const char *argv[16], *last;
109 va_list ap;
111 memset(argv, 0, sizeof(argv));
113 va_start(ap, argv0);
114 argv[0] = argv0;
115 for (i = 1; i < nitems(argv); ++i) {
116 last = va_arg(ap, const char *);
117 if (last == NULL)
118 break;
119 argv[i] = last;
121 va_end(ap);
123 assert(last == NULL);
125 switch (pid = fork()) {
126 case -1:
127 err(1, "fork");
128 case 0: /* child */
129 execvp(argv[0], (char *const *)argv);
130 err(1, "execvp");
131 default:
132 waitpid(pid, &status, 0);
136 static void
137 tty_resized(int signo)
139 resized = 1;
142 static __dead void
143 usage(int ret)
145 fprintf(stderr, "usage: %s [-C cert] [-K key] [-o output] "
146 "[9p://][user@]host[:port][/path]\n", getprogname());
147 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
148 exit(ret);
151 static int
152 nextfid(void)
154 int i;
156 for (i = 0; ; ++i) {
157 if (i != pwdfid)
158 return i;
162 static void
163 do_send(void)
165 const void *buf;
166 size_t nbytes;
167 ssize_t r;
169 if (xdump)
170 hexdump("outgoing message", EVBUFFER_DATA(evb),
171 EVBUFFER_LENGTH(evb));
173 while (EVBUFFER_LENGTH(evb) != 0) {
174 buf = EVBUFFER_DATA(evb);
175 nbytes = EVBUFFER_LENGTH(evb);
177 if (ctx == NULL) {
178 r = write(sock, buf, nbytes);
179 if (r == 0 || r == -1)
180 errx(1, "EOF");
181 } else {
182 r = tls_write(ctx, buf, nbytes);
183 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
184 continue;
185 if (r == -1)
186 errx(1, "tls: %s", tls_error(ctx));
189 evbuffer_drain(evb, r);
193 static void
194 mustread(void *d, size_t len)
196 ssize_t r;
198 while (len != 0) {
199 if (ctx == NULL) {
200 r = read(sock, d, len);
201 if (r == 0 || r == -1)
202 errx(1, "EOF");
203 } else {
204 r = tls_read(ctx, d, len);
205 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
206 continue;
207 if (r == -1)
208 errx(1, "tls: %s", tls_error(ctx));
211 d += r;
212 len -= r;
216 static void
217 recv_msg(void)
219 uint32_t len, l;
220 char tmp[BUFSIZ];
222 mustread(&len, sizeof(len));
223 len = le32toh(len);
224 if (len < HEADERSIZE)
225 errx(1, "read message of invalid length %d", len);
227 len -= 4; /* skip the length just read */
229 while (len != 0) {
230 l = MIN(len, sizeof(tmp));
231 mustread(tmp, l);
232 len -= l;
233 evbuffer_add(buf, tmp, l);
236 if (xdump)
237 hexdump("incoming packet", EVBUFFER_DATA(buf),
238 EVBUFFER_LENGTH(buf));
241 static uint64_t
242 np_read64(struct evbuffer *buf)
244 uint64_t n;
246 evbuffer_remove(buf, &n, sizeof(n));
247 return le64toh(n);
250 static uint32_t
251 np_read32(struct evbuffer *buf)
253 uint32_t n;
255 evbuffer_remove(buf, &n, sizeof(n));
256 return le32toh(n);
259 static uint16_t
260 np_read16(struct evbuffer *buf)
262 uint16_t n;
264 evbuffer_remove(buf, &n, sizeof(n));
265 return le16toh(n);
268 static uint16_t
269 np_read8(struct evbuffer *buf)
271 uint8_t n;
273 evbuffer_remove(buf, &n, sizeof(n));
274 return n;
277 static char *
278 np_readstr(struct evbuffer *buf)
280 uint16_t len;
281 char *str;
283 len = np_read16(buf);
284 assert(EVBUFFER_LENGTH(buf) >= len);
286 if ((str = calloc(1, len+1)) == NULL)
287 err(1, "calloc");
288 evbuffer_remove(buf, str, len);
289 return str;
292 static void
293 np_read_qid(struct evbuffer *buf, struct qid *qid)
295 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
297 qid->type = np_read8(buf);
298 qid->vers = np_read32(buf);
299 qid->path = np_read64(buf);
302 static int
303 np_read_stat(struct evbuffer *buf, struct np_stat *st)
305 uint16_t size;
307 memset(st, 0, sizeof(*st));
309 size = np_read16(buf);
310 if (size > EVBUFFER_LENGTH(buf))
311 return -1;
313 st->type = np_read16(buf);
314 st->dev = np_read32(buf);
315 np_read_qid(buf, &st->qid);
316 st->mode = np_read32(buf);
317 st->atime = np_read32(buf);
318 st->mtime = np_read32(buf);
319 st->length = np_read64(buf);
320 st->name = np_readstr(buf);
321 st->uid = np_readstr(buf);
322 st->gid = np_readstr(buf);
323 st->muid = np_readstr(buf);
325 return 0;
328 static void
329 expect(uint8_t type)
331 uint8_t t;
333 t = np_read8(buf);
334 if (t == type)
335 return;
337 if (t == Rerror) {
338 char *err;
340 /* skip tag */
341 np_read16(buf);
343 err = np_readstr(buf);
344 errx(1, "expected %s, got error %s",
345 pp_msg_type(type), err);
348 errx(1, "expected %s, got msg type %s",
349 pp_msg_type(type), pp_msg_type(t));
352 static void
353 expect2(uint8_t type, uint16_t tag)
355 uint16_t t;
357 expect(type);
359 t = np_read16(buf);
360 if (t == tag)
361 return;
363 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
366 static char *
367 check(uint8_t type, uint16_t tag)
369 uint16_t rtag;
370 uint8_t rtype;
372 rtype = np_read8(buf);
373 rtag = np_read16(buf);
374 if (rtype == type) {
375 if (rtag != tag)
376 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
377 return NULL;
380 if (rtype == Rerror)
381 return np_readstr(buf);
383 errx(1, "expected %s, got msg type %s",
384 pp_msg_type(type), pp_msg_type(rtype));
387 static void
388 do_version(void)
390 char *version;
392 tversion(VERSION9P, MSIZE9P);
393 do_send();
394 recv_msg();
395 expect2(Rversion, NOTAG);
397 msize = np_read32(buf);
398 version = np_readstr(buf);
400 if (msize > MSIZE9P || msize < 256)
401 errx(1, "got unexpected msize: %d", msize);
402 if (strcmp(version, VERSION9P))
403 errx(1, "unexpected 9p version: %s", version);
405 free(version);
406 ASSERT_EMPTYBUF();
409 static void
410 do_attach(const char *user)
412 struct qid qid;
414 tattach(pwdfid, NOFID, user, "/");
415 do_send();
416 recv_msg();
417 expect2(Rattach, iota_tag);
418 np_read_qid(buf, &qid);
420 ASSERT_EMPTYBUF();
423 static uint32_t
424 do_open(uint32_t fid, uint8_t mode)
426 struct qid qid;
427 uint32_t iounit;
429 topen(fid, mode);
430 do_send();
431 recv_msg();
432 expect2(Ropen, iota_tag);
434 np_read_qid(buf, &qid);
435 iounit = np_read32(buf);
437 ASSERT_EMPTYBUF();
439 return iounit;
442 static uint32_t
443 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
445 struct qid qid;
446 uint32_t iounit;
448 tcreate(fid, name, perm, mode);
449 do_send();
450 recv_msg();
451 expect2(Rcreate, iota_tag);
453 np_read_qid(buf, &qid);
454 iounit = np_read32(buf);
456 ASSERT_EMPTYBUF();
458 return iounit;
461 static void
462 do_clunk(uint32_t fid)
464 tclunk(fid);
465 do_send();
466 recv_msg();
467 expect2(Rclunk, iota_tag);
469 ASSERT_EMPTYBUF();
472 static char *
473 dup_fid(int fid, int nfid)
475 uint16_t nwqid;
476 char *errstr;
478 twalk(fid, nfid, NULL, 0);
479 do_send();
480 recv_msg();
482 if ((errstr = check(Rwalk, iota_tag)) != NULL)
483 return errstr;
485 nwqid = np_read16(buf);
486 assert(nwqid == 0);
488 ASSERT_EMPTYBUF();
490 return NULL;
493 static char *
494 walk_path(int fid, int newfid, const char *path, int *missing,
495 struct qid *qid)
497 char *wnames[MAXWELEM], *p, *t, *errstr;
498 size_t nwname, i;
499 uint16_t nwqid;
501 if ((p = strdup(path)) == NULL)
502 err(1, "strdup");
503 t = p;
505 /* strip initial ./ */
506 if (t[0] == '.' && t[1] == '/')
507 t += 2;
509 for (nwname = 0; nwname < nitems(wnames) &&
510 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
511 if (*wnames[nwname] != '\0')
512 nwname++;
515 twalk(fid, newfid, (const char **)wnames, nwname);
516 do_send();
517 recv_msg();
519 *missing = nwname;
520 if ((errstr = check(Rwalk, iota_tag)) != NULL) {
521 free(p);
522 return errstr;
525 nwqid = np_read16(buf);
526 assert(nwqid <= nwname);
528 /* consume all qids */
529 for (i = 0; i < nwqid; ++i)
530 np_read_qid(buf, qid);
532 free(p);
534 *missing = nwname - nwqid;
535 return NULL;
538 static void
539 do_stat(int fid, struct np_stat *st)
541 tstat(fid);
542 do_send();
543 recv_msg();
544 expect2(Rstat, iota_tag);
546 /* eat up the first two byte length */
547 np_read16(buf);
549 if (np_read_stat(buf, st) == -1)
550 errx(1, "invalid stat struct read");
552 ASSERT_EMPTYBUF();
555 static char *
556 do_wstat(int fid, const struct np_stat *st)
558 char *errstr;
560 twstat(fid, st);
561 do_send();
562 recv_msg();
564 if ((errstr = check(Rwstat, iota_tag)) != NULL)
565 return errstr;
567 ASSERT_EMPTYBUF();
569 return NULL;
572 static char *
573 do_remove(int fid)
575 char *errstr;
577 tremove(fid);
578 do_send();
579 recv_msg();
580 if ((errstr = check(Rremove, iota_tag)) != NULL)
581 return errstr;
583 ASSERT_EMPTYBUF();
585 return NULL;
588 static size_t
589 do_read(int fid, uint64_t off, uint32_t count, void *data)
591 uint32_t r;
593 tread(fid, off, count);
594 do_send();
595 recv_msg();
596 expect2(Rread, iota_tag);
598 r = np_read32(buf);
599 assert(r == EVBUFFER_LENGTH(buf));
600 assert(r <= count);
601 evbuffer_remove(buf, data, r);
603 ASSERT_EMPTYBUF();
605 return r;
608 static size_t
609 do_write(int fid, uint64_t off, uint32_t count, void *data)
611 uint32_t r;
613 twrite(fid, off, data, count);
614 do_send();
615 recv_msg();
616 expect2(Rwrite, iota_tag);
618 r = np_read32(buf);
619 assert(r <= count);
621 ASSERT_EMPTYBUF();
623 return r;
626 static void
627 draw_progress(const char *pre, const struct progress *p)
629 struct winsize ws;
630 int i, l, w;
631 double perc;
633 if (xdump)
634 return;
636 perc = 100.0 * p->done / p->max;
637 if (!tty_p) {
638 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
639 return;
642 if (resized) {
643 resized = 0;
645 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
646 return;
647 tty_width = ws.ws_col;
649 w = tty_width;
651 if (pre == NULL ||
652 ((l = fprintf(stderr, "\r%s ", pre)) == -1 || l >= w))
653 return;
655 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
656 if (w < 0) {
657 fprintf(stderr, "%4d%%\n", (int)perc);
658 return;
661 fprintf(stderr, "|");
663 l = w * MIN(100.0, perc) / 100.0;
664 for (i = 0; i < l; i++)
665 fprintf(stderr, "*");
666 for (; i < w; i++)
667 fprintf(stderr, " ");
668 fprintf(stderr, "|%4d%%", (int)perc);
671 static int
672 fetch_fid(int fid, int fd, const char *name)
674 static char buf[MSIZE9P];
675 struct progress p = {0};
676 struct np_stat st;
677 size_t r;
678 int ret = 0;
680 do_stat(fid, &st);
681 do_open(fid, KOREAD);
683 p.max = st.length;
684 for (;;) {
685 size_t len, off;
686 ssize_t nw;
688 len = MIN(sizeof(buf), msize);
689 len -= IOHDRSZ; /* for the request' fields */
691 r = do_read(fid, p.done, len, buf);
692 if (r == 0)
693 break;
695 for (off = 0; off < r; off += nw)
696 if ((nw = write(fd, buf + off, r - off)) == 0 ||
697 nw == -1) {
698 ret = -1;
699 goto end;
702 p.done += r;
703 draw_progress(name, &p);
705 #if 0
706 /* throttle, for debugging purpose */
708 struct timespec ts = { 0, 500000000 };
709 nanosleep(&ts, NULL);
711 #endif
714 end:
715 putchar('\n');
717 do_clunk(fid);
718 return ret;
721 static void
722 send_fid(int fid, const char *fnam, int open_flags, int fd, const char *name)
724 static char buf[MSIZE9P];
725 struct progress p = {0};
726 struct stat sb;
727 ssize_t r;
728 size_t w, len;
730 if (fstat(fd, &sb) == -1)
731 err(1, "fstat");
733 if (fnam != NULL)
734 do_create(fid, fnam, 0644, KOWRITE);
735 else
736 do_open(fid, open_flags | KOWRITE);
738 p.max = sb.st_size;
739 for (;;) {
740 len = MIN(sizeof(buf), msize);
741 len -= HEADERSIZE + 4 + 4 + 8; /* for the request' fields */
743 r = read(fd, buf, len);
744 if (r == 0)
745 break;
746 if (r == -1)
747 err(1, "read");
749 w = do_write(fid, p.done, r, buf);
750 p.done += w;
752 draw_progress(name, &p);
754 #if 0
755 /* throttle, for debugging purpose */
757 struct timespec ts = { 0, 500000000 };
758 nanosleep(&ts, NULL);
760 #endif
763 putchar('\n');
764 do_clunk(fid);
767 static int
768 woc_file(int fd, const char *prompt, const char *path)
770 struct qid qid;
771 const char *n = NULL;
772 char *errstr;
773 int nfid, miss;
775 nfid = nextfid();
776 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
777 if (errstr != NULL && miss > 1) {
778 fprintf(stderr, "%s: %s\n", path, errstr);
779 free(errstr);
780 return -1;
783 if (errstr != NULL || miss == 1) {
784 char p[PATH_MAX], *dn;
786 /*
787 * If it's only one component missing (the file name), walk
788 * to the parent directory and try to create the file.
789 */
791 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
792 fprintf(stderr, "path too long: %s\n", path);
793 return -1;
795 dn = dirname(p);
797 if (!strcmp(dn, ".")) {
798 errstr = dup_fid(pwdfid, nfid);
799 miss = 0;
800 } else
801 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
803 if (errstr != NULL) {
804 fprintf(stderr, "%s: %s\n", dn, errstr);
805 free(errstr);
806 return -1;
809 if (miss != 0) {
810 fprintf(stderr, "%s: not a directory\n", dn);
811 return -1;
814 if ((n = strrchr(path, '/')) != NULL)
815 n++;
816 else
817 n = path;
820 free(errstr);
822 if (miss > 1) {
823 fprintf(stderr, "can't create %s: missing %d path"
824 " component(s)\n", path, miss);
825 return -1;
828 send_fid(nfid, n, KOTRUNC, fd, prompt);
829 return 0;
832 static void
833 do_tls_connect(const char *host, const char *port)
835 int handshake;
837 if ((tlsconf = tls_config_new()) == NULL)
838 fatalx("tls_config_new");
839 tls_config_insecure_noverifycert(tlsconf);
840 tls_config_insecure_noverifyname(tlsconf);
842 if (keypath == NULL)
843 keypath = crtpath;
845 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
846 fatalx("can't load certs (%s, %s)", crtpath, keypath);
848 if ((ctx = tls_client()) == NULL)
849 fatal("tls_client");
850 if (tls_configure(ctx, tlsconf) == -1)
851 fatalx("tls_configure: %s", tls_error(ctx));
853 if (tls_connect(ctx, host, port) == -1)
854 fatalx("can't connect to %s:%s: %s", host, port,
855 tls_error(ctx));
857 for (handshake = 0; !handshake;) {
858 switch (tls_handshake(ctx)) {
859 case -1:
860 fatalx("tls_handshake: %s", tls_error(ctx));
861 case 0:
862 handshake = 1;
863 break;
868 static void
869 do_ctxt_connect(const char *host, const char *port)
871 struct addrinfo hints, *res, *res0;
872 int error, saved_errno;
873 const char *cause = NULL;
875 memset(&hints, 0, sizeof(hints));
876 hints.ai_family = AF_UNSPEC;
877 hints.ai_socktype = SOCK_STREAM;
878 error = getaddrinfo(host, port, &hints, &res0);
879 if (error)
880 errx(1, "%s", gai_strerror(error));
882 sock = -1;
883 for (res = res0; res != NULL; res = res->ai_next) {
884 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
885 res->ai_protocol);
886 if (sock == -1) {
887 cause = "socket";
888 continue;
891 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
892 cause = "connect";
893 saved_errno = errno;
894 close(sock);
895 errno = saved_errno;
896 sock = -1;
897 continue;
900 break;
903 if (sock == -1)
904 err(1, "%s", cause);
905 freeaddrinfo(res0);
908 static void
909 do_connect(const char *host, const char *port, const char *user)
911 struct qid qid;
912 int nfid, miss, fd;
913 char *errstr;
915 fprintf(stderr, "connecting to %s:%s...", host, port);
917 if (tls)
918 do_tls_connect(host, port);
919 else
920 do_ctxt_connect(host, port);
922 fprintf(stderr, " done!\n");
924 do_version();
925 do_attach(user);
928 static int
929 tmp_file(char sfn[TMPFSTRLEN])
931 int tmpfd;
933 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
934 if ((tmpfd = mkstemp(sfn)) == -1) {
935 warn("mkstemp %s", sfn);
936 return -1;
939 /* set the close-on-exec flag */
940 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
941 warn("fcntl");
942 close(tmpfd);
943 return -1;
946 return tmpfd;
949 static inline const char *
950 pp_perm(uint8_t x)
952 switch (x & 0x7) {
953 case 0x0:
954 return "---";
955 case 0x1:
956 return "--x";
957 case 0x2:
958 return "-w-";
959 case 0x3:
960 return "-wx";
961 case 0x4:
962 return "r--";
963 case 0x5:
964 return "r-x";
965 case 0x6:
966 return "rw-";
967 case 0x7:
968 return "rwx";
969 default:
970 /* unreachable, just for the compiler' happiness */
971 return "???";
975 static inline void
976 prepare_wstat(struct np_stat *st)
978 memset(st, 0xFF, sizeof(*st));
979 st->name = NULL;
980 st->uid = NULL;
981 st->gid = NULL;
982 st->muid = NULL;
985 static int
986 print_dirent(const struct np_stat *st)
988 time_t mtime;
989 struct tm *tm;
990 const char *timfmt;
991 char fmt[FMT_SCALED_STRSIZE], tim[13];
993 if (fmt_scaled(st->length, fmt) == -1)
994 strlcpy(fmt, "xxx", sizeof(fmt));
996 mtime = st->mtime;
998 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
999 timfmt = "%b %e %R";
1000 else
1001 timfmt = "%b %e %Y";
1003 if ((tm = localtime(&mtime)) == NULL ||
1004 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1005 strlcpy(tim, "unknown", sizeof(tim));
1007 if (st->qid.type & QTDIR)
1008 printf("d");
1009 else
1010 printf("-");
1011 printf("%s", pp_perm(st->mode >> 6));
1012 printf("%s", pp_perm(st->mode >> 3));
1013 printf("%s", pp_perm(st->mode));
1014 printf(" %8s %12s %s%s\n", fmt, tim, st->name,
1015 st->qid.type & QTDIR ? "/" : "");
1017 return 0;
1020 int
1021 dir_listing(const char *path, int (*fn)(const struct np_stat *),
1022 int printerr)
1024 struct qid qid = {0, 0, QTDIR};
1025 struct np_stat st;
1026 uint64_t off = 0;
1027 uint32_t len;
1028 int nfid, r, miss = 0;
1029 char *errstr;
1031 now = time(NULL);
1032 nfid = nextfid();
1034 if (!strcmp(path, "."))
1035 errstr = dup_fid(pwdfid, nfid);
1036 else
1037 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
1038 if (errstr != NULL) {
1039 if (printerr)
1040 printf("%s: %s\n", path, errstr);
1041 free(errstr);
1042 return -1;
1044 if (miss) {
1045 if (printerr)
1046 printf("%s: No such file or directory\n", path);
1047 return -1;
1049 if (!(qid.type & QTDIR)) {
1050 if (printerr)
1051 printf("%s: not a directory\n", path);
1052 do_clunk(nfid);
1053 return -1;
1056 do_open(nfid, KOREAD);
1057 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1059 for (;;) {
1060 tread(nfid, off, msize - IOHDRSZ);
1061 do_send();
1062 recv_msg();
1063 expect2(Rread, iota_tag);
1065 len = np_read32(buf);
1066 if (len == 0)
1067 break;
1069 evbuffer_add_buffer(dirbuf, buf);
1070 off += len;
1072 ASSERT_EMPTYBUF();
1075 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1076 if (np_read_stat(dirbuf, &st) == -1)
1077 errx(1, "invalid stat struct read");
1079 r = fn(&st);
1081 free(st.name);
1082 free(st.uid);
1083 free(st.gid);
1084 free(st.muid);
1086 if (r == -1)
1087 break;
1090 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1091 do_clunk(nfid);
1092 return 0;
1095 void
1096 cmd_bell(int argc, const char **argv)
1098 if (argc == 0) {
1099 bell = !bell;
1100 if (bell)
1101 puts("bell mode enabled");
1102 else
1103 puts("bell mode disabled");
1104 return;
1107 if (argc != 1)
1108 goto usage;
1110 if (!strcmp(*argv, "on")) {
1111 bell = 1;
1112 puts("bell mode enabled");
1113 return;
1116 if (!strcmp(*argv, "off")) {
1117 bell = 0;
1118 puts("bell mode disabled");
1119 return;
1122 usage:
1123 printf("bell [on | off]\n");
1126 void
1127 cmd_bye(int argc, const char **argv)
1129 log_warnx("bye\n");
1130 exit(0);
1133 void
1134 cmd_cd(int argc, const char **argv)
1136 struct qid qid;
1137 int nfid, miss;
1138 char *errstr;
1140 if (argc != 1) {
1141 printf("usage: cd remote-path\n");
1142 return;
1145 nfid = nextfid();
1146 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1147 if (errstr != NULL) {
1148 printf("%s: %s\n", argv[0], errstr);
1149 free(errstr);
1150 return;
1153 if (miss != 0 || !(qid.type & QTDIR)) {
1154 printf("%s: not a directory\n", argv[0]);
1155 if (miss == 0)
1156 do_clunk(nfid);
1157 return;
1160 do_clunk(pwdfid);
1161 pwdfid = nfid;
1164 void
1165 cmd_edit(int argc, const char **argv)
1167 struct qid qid;
1168 int nfid, tmpfd, miss;
1169 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1170 const char *ed;
1172 if (argc != 1) {
1173 puts("usage: edit file");
1174 return;
1177 if ((ed = getenv("VISUAL")) == NULL &&
1178 (ed = getenv("EDITOR")) == NULL)
1179 ed = "ed";
1181 nfid = nextfid();
1182 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1183 if (errstr != NULL) {
1184 printf("%s: %s\n", *argv, errstr);
1185 free(errstr);
1186 return;
1189 if (miss != 0 || qid.type != 0) {
1190 printf("%s: not a file\n", *argv);
1191 if (miss == 0)
1192 do_clunk(nfid);
1193 return;
1196 if ((tmpfd = tmp_file(sfn)) == -1) {
1197 do_clunk(nfid);
1198 return;
1201 strlcpy(p, *argv, sizeof(p));
1202 name = basename(p);
1204 if (fetch_fid(nfid, tmpfd, name)) {
1205 warn("failed fetch or can't write %s", sfn);
1206 goto end;
1208 close(tmpfd);
1210 spawn(ed, sfn, NULL);
1213 * Re-open the file because it's not guaranteed that the
1214 * file descriptor tmpfd is still associated with the file
1215 * pointed by sfn: it's not uncommon for editor to write
1216 * a backup file and then rename(2) it to the file name.
1218 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1219 warn("can't open %s", sfn);
1220 goto end;
1223 woc_file(tmpfd, *argv, name);
1224 close(tmpfd);
1226 end:
1227 unlink(sfn);
1230 void
1231 cmd_get(int argc, const char **argv)
1233 struct qid qid;
1234 const char *l;
1235 char *errstr;
1236 int nfid, fd, miss;
1238 if (argc != 1 && argc != 2) {
1239 printf("usage: get remote-file [local-file]\n");
1240 return;
1243 if (argc == 2)
1244 l = argv[1];
1245 else if ((l = strrchr(argv[0], '/')) != NULL)
1246 l++; /* skip / */
1247 else
1248 l = argv[0];
1250 nfid = nextfid();
1251 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1252 if (errstr != NULL) {
1253 printf("%s: %s\n", argv[0], errstr);
1254 free(errstr);
1255 return;
1258 if (miss != 0 || qid.type != 0) {
1259 printf("%s: not a file\n", argv[0]);
1260 if (miss == 0)
1261 do_clunk(nfid);
1262 return;
1265 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1266 warn("can't open %s", l);
1267 do_clunk(nfid);
1268 return;
1271 if (fetch_fid(nfid, fd, l) == -1)
1272 warn("write %s", l);
1273 close(fd);
1276 void
1277 cmd_hexdump(int argc, const char **argv)
1279 if (argc == 0) {
1280 xdump = !xdump;
1281 if (xdump)
1282 puts("hexdump mode enabled");
1283 else
1284 puts("hexdump mode disabled");
1285 return;
1288 if (argc > 1)
1289 goto usage;
1291 if (!strcmp(*argv, "on")) {
1292 xdump = 1;
1293 puts("hexdump mode enabled");
1294 return;
1297 if (!strcmp(*argv, "off")) {
1298 xdump = 0;
1299 puts("hexdump mode disabled");
1300 return;
1303 usage:
1304 puts("usage: hexdump [on | off]");
1307 void
1308 cmd_lcd(int argc, const char **argv)
1310 const char *dir;
1312 if (argc > 1) {
1313 printf("usage: lcd [local-directory]\n");
1314 return;
1317 if (argc == 1)
1318 dir = *argv;
1320 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1321 printf("HOME is not defined\n");
1322 return;
1325 if (chdir(dir) == -1)
1326 printf("cd: %s: %s\n", dir, strerror(errno));
1329 void
1330 cmd_lpwd(int argc, const char **argv)
1332 char path[PATH_MAX];
1334 if (argc != 0) {
1335 printf("usage: lpwd\n");
1336 return;
1339 if (getcwd(path, sizeof(path)) == NULL) {
1340 printf("lpwd: %s\n", strerror(errno));
1341 return;
1344 printf("%s\n", path);
1347 void
1348 cmd_ls(int argc, const char **argv)
1350 if (argc > 1) {
1351 puts("usage: ls [path]");
1352 return;
1355 dir_listing(argc == 0 ? "." : argv[0], print_dirent, 1);
1358 void
1359 cmd_page(int argc, const char **argv)
1361 struct qid qid;
1362 int nfid, tmpfd, miss, r;
1363 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1364 const char *pager;
1366 if (argc != 1) {
1367 puts("usage: page file");
1368 return;
1371 if ((pager = getenv("PAGER")) == NULL)
1372 pager = "less";
1374 nfid = nextfid();
1375 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1376 if (errstr != NULL) {
1377 printf("%s: %s\n", *argv, errstr);
1378 free(errstr);
1379 return;
1382 if (miss != 0 || qid.type != 0) {
1383 printf("%s: not a file\n", *argv);
1384 if (miss == 0)
1385 do_clunk(nfid);
1386 return;
1389 if ((tmpfd = tmp_file(sfn)) == -1) {
1390 do_clunk(nfid);
1391 return;
1394 strlcpy(p, *argv, sizeof(p));
1395 name = basename(p);
1396 if ((r = fetch_fid(nfid, tmpfd, name)) == -1)
1397 warn("write %s", sfn);
1398 close(tmpfd);
1399 if (r != -1)
1400 spawn(pager, sfn, NULL);
1401 unlink(sfn);
1404 void
1405 cmd_pipe(int argc, const char **argv)
1407 struct qid qid;
1408 pid_t pid;
1409 int nfid, tmpfd, miss, status;
1410 int filedes[2]; /* read end, write end */
1411 char *errstr;
1413 if (argc < 2) {
1414 puts("usage: pipe remote-file cmd [args...]");
1415 return;
1418 nfid = nextfid();
1419 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1420 if (errstr != NULL) {
1421 printf("%s: %s\n", *argv, errstr);
1422 free(errstr);
1423 return;
1426 if (miss != 0 || qid.type != 0) {
1427 printf("%s: not a file\n", *argv);
1428 if (miss == 0)
1429 do_clunk(nfid);
1430 return;
1433 if (pipe(filedes) == -1)
1434 err(1, "pipe");
1436 switch (pid = vfork()) {
1437 case -1:
1438 err(1, "vfork");
1439 case 0:
1440 close(filedes[1]);
1441 if (dup2(filedes[0], 0) == -1)
1442 err(1, "dup2");
1443 execvp(argv[1], (char *const *)argv + 1);
1444 err(1, "execvp");
1447 close(filedes[0]);
1448 if (fetch_fid(nfid, filedes[1], *argv) == -1)
1449 warnx("failed to fetch all the file");
1450 close(filedes[1]);
1452 waitpid(pid, &status, 0);
1455 void
1456 cmd_put(int argc, const char **argv)
1458 struct qid qid;
1459 const char *l;
1460 int fd;
1462 if (argc != 1 && argc != 2) {
1463 printf("usage: put local-file [remote-file]\n");
1464 return;
1467 if (argc == 2)
1468 l = argv[1];
1469 else if ((l = strrchr(argv[0], '/')) != NULL)
1470 l++; /* skip / */
1471 else
1472 l = argv[0];
1474 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1475 warn("%s", argv[0]);
1476 return;
1479 woc_file(fd, argv[0], l);
1480 close(fd);
1483 void
1484 cmd_rename(int argc, const char **argv)
1486 struct np_stat st;
1487 struct qid qid;
1488 char *errstr;
1489 int nfid, miss;
1491 if (argc != 2) {
1492 puts("usage: rename remote-file new-remote-name");
1493 return;
1496 nfid = nextfid();
1497 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1498 if (errstr != NULL) {
1499 printf("%s: %s\n", argv[0], errstr);
1500 free(errstr);
1501 return;
1504 if (miss != 0) {
1505 printf("%s: not such file or directory\n", argv[0]);
1506 return;
1509 prepare_wstat(&st);
1510 st.name = (char *)argv[1];
1511 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1512 printf("rename: %s\n", errstr);
1513 free(errstr);
1516 do_clunk(nfid);
1519 void
1520 cmd_rm(int argc, const char **argv)
1522 struct qid qid;
1523 char *errstr;
1524 int nfid, miss;
1526 if (argc == 0) {
1527 puts("usage: rm file ...");
1528 return;
1531 for (; *argv; ++argv, --argc) {
1532 nfid = nextfid();
1533 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1534 if (errstr != NULL) {
1535 printf("%s: %s\n", *argv, errstr);
1536 free(errstr);
1537 continue;
1539 if (miss) {
1540 printf("%s: not such file or directory\n", *argv);
1541 continue;
1544 if ((errstr = do_remove(nfid)) != NULL) {
1545 printf("%s: %s\n", *argv, errstr);
1546 free(errstr);
1547 continue;
1552 void
1553 cmd_verbose(int argc, const char **argv)
1555 if (argc == 0) {
1556 log_setverbose(!log_getverbose());
1557 if (log_getverbose())
1558 puts("verbose mode enabled");
1559 else
1560 puts("verbose mode disabled");
1561 return;
1564 if (argc != 1)
1565 goto usage;
1567 if (!strcmp(*argv, "on")) {
1568 log_setverbose(1);
1569 puts("verbose mode enabled");
1570 return;
1573 if (!strcmp(*argv, "off")) {
1574 log_setverbose(0);
1575 puts("verbose mode disabled");
1576 return;
1579 usage:
1580 printf("verbose [on | off]\n");
1583 static void
1584 excmd(int argc, const char **argv)
1586 size_t i;
1588 if (argc == 0)
1589 return;
1591 for (i = 0; i < nitems(cmds); ++i) {
1592 if (!strcmp(cmds[i].name, *argv)) {
1593 cmds[i].fn(argc-1, argv+1);
1594 return;
1598 log_warnx("unknown command %s", *argv);
1601 static int
1602 parsecmd(char *cmd, char **argv, int len)
1604 int escape, quote;
1605 int argc = 0;
1607 memset(argv, 0, sizeof(*argv) * len);
1609 while (argc < len) {
1610 while (isspace((unsigned char)*cmd))
1611 cmd++;
1612 if (*cmd == '\0')
1613 break;
1615 argv[argc++] = cmd;
1616 escape = quote = 0;
1617 for (; *cmd != '\0'; ++cmd) {
1618 if (escape) {
1619 escape = 0;
1620 continue;
1622 if (*cmd == '\\') {
1623 escape = 1;
1624 memmove(cmd, cmd + 1, strlen(cmd));
1625 cmd--;
1626 continue;
1628 if (*cmd == quote) {
1629 quote = 0;
1630 memmove(cmd, cmd + 1, strlen(cmd));
1631 cmd--;
1632 continue;
1634 if (*cmd == '\'' || *cmd == '"') {
1635 quote = *cmd;
1636 memmove(cmd, cmd + 1, strlen(cmd));
1637 cmd--;
1638 continue;
1640 if (quote)
1641 continue;
1643 if (isspace((unsigned char)*cmd))
1644 break;
1647 if (*cmd == '\0' && (escape || quote)) {
1648 fprintf(stderr, "unterminated %s\n",
1649 escape ? "escape" : "quote");
1650 return -1;
1653 if (*cmd == '\0')
1654 break;
1655 *cmd++ = '\0';
1658 if (*cmd != '\0') {
1659 fprintf(stderr, "too many arguments\n");
1660 return -1;
1662 return argc;
1665 static void
1666 cd_or_fetch(const char *path, const char *outfile)
1668 struct qid qid;
1669 char *errstr;
1670 int fd, nfid, miss;
1672 while (*path == '/')
1673 path++;
1674 if (*path == '\0')
1675 return;
1677 nfid = nextfid();
1678 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
1679 if (errstr)
1680 errx(1, "walk %s: %s", path, errstr);
1681 if (miss)
1682 errc(1, ENOENT, "walk %s", path);
1684 if (qid.type & QTDIR) {
1685 if (outfile)
1686 errx(1, "can't fetch directory %s", path);
1687 do_clunk(pwdfid);
1688 pwdfid = nfid;
1689 return;
1692 if (outfile == NULL) {
1693 if ((outfile = strrchr(path, '/')) == NULL)
1694 outfile = path;
1695 else
1696 outfile++;
1697 if (*outfile == '\0')
1698 errx(1, "invalid path: missing file name: %s",
1699 path);
1702 if (strcmp(outfile, "-") != 0) {
1703 fd = open(outfile, O_WRONLY|O_CREAT, 0644);
1704 if (fd == -1)
1705 err(1, "can't open for writing %s", outfile);
1706 } else
1707 fd = 1;
1709 if (fetch_fid(nfid, fd, outfile) == -1)
1710 err(1, "write %s", outfile);
1711 close(fd);
1712 exit(0);
1715 static const char *
1716 parse_addr(const char *url, const char **user,
1717 const char **port, const char **path)
1719 static char buf[PATH_MAX];
1720 char *host, *t;
1722 *user = *port = *path = NULL;
1723 host = buf;
1725 if (strlcpy(buf, url, sizeof(buf)) >= sizeof(buf))
1726 errx(1, "connection string too long");
1728 if (!strncmp(host, "9p://", 5))
1729 host += 5;
1731 if ((t = strchr(host, '/')) != NULL) {
1732 if (t == host)
1733 errx(1, "invalid connection string: %s", url);
1734 *t++ = '\0';
1735 if (*t != '\0')
1736 *path = t;
1739 if ((t = strchr(host, '@')) != NULL) {
1740 if (t == host)
1741 errx(1, "invalid connection string: %s", url);
1742 *t++ = '\0';
1743 *user = host;
1744 host = t;
1745 } else if ((*user = getenv("USER")) == NULL)
1746 errx(1, "USER not defined");
1748 if ((t = strchr(host, ':')) != NULL) {
1749 *t++ = '\0';
1750 if (*t != '\0')
1751 *port = t;
1753 if (*port == NULL)
1754 *port = "1337";
1756 return host;
1759 int
1760 main(int argc, char **argv)
1762 const char *user, *host, *port, *path;
1763 const char *outfile = NULL;
1764 int ch;
1766 log_init(1, LOG_DAEMON);
1767 log_setverbose(0);
1768 log_procinit(getprogname());
1770 while ((ch = getopt(argc, argv, "C:cK:o:")) != -1) {
1771 switch (ch) {
1772 case 'C':
1773 tls = 1;
1774 crtpath = optarg;
1775 break;
1776 case 'c': /* deprecated, remove after 0.3 */
1777 tls = 1;
1778 break;
1779 case 'K':
1780 tls = 1;
1781 keypath = optarg;
1782 break;
1783 case 'o':
1784 outfile = optarg;
1785 break;
1786 default:
1787 usage(1);
1790 argc -= optind;
1791 argv += optind;
1793 if (argc == 0 || (tls && crtpath == NULL))
1794 usage(1);
1796 host = parse_addr(argv[0], &user, &port, &path);
1797 if (path == NULL && argv[1] != NULL) /* drop argv[1] after 0.3 */
1798 path = argv[1];
1799 if (outfile && path == NULL)
1800 usage(1);
1802 signal(SIGPIPE, SIG_IGN);
1803 if (isatty(1)) {
1804 tty_p = 1;
1805 resized = 1;
1806 signal(SIGWINCH, tty_resized);
1809 if ((evb = evbuffer_new()) == NULL)
1810 fatal("evbuffer_new");
1812 if ((buf = evbuffer_new()) == NULL)
1813 fatal("evbuffer_new");
1815 if ((dirbuf = evbuffer_new()) == NULL)
1816 fatal("evbuferr_new");
1818 do_connect(host, port, user);
1819 if (path)
1820 cd_or_fetch(path, outfile);
1822 compl_setup();
1823 for (;;) {
1824 int argc;
1825 char *line, *argv[16] = {0}, **ap;
1827 if ((line = read_line("kamiftp> ")) == NULL)
1828 break;
1830 if ((argc = parsecmd(line, argv, nitems(argv) - 1)) == -1) {
1831 free(line);
1832 continue;
1835 argv[argc] = NULL;
1836 excmd(argc, (const char **)argv);
1838 if (bell)
1839 fprintf(stderr, "\a");
1841 free(line);
1844 printf("\n");