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 FILE *fp;
62 struct evbuffer *buf;
63 struct evbuffer *dirbuf;
64 uint32_t msize;
65 int bell;
66 time_t now;
68 volatile sig_atomic_t resized;
69 int tty_p;
70 int tty_width;
71 int xdump;
73 struct progress {
74 uint64_t max;
75 uint64_t done;
76 };
78 int pwdfid;
80 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
82 static char *
83 read_line(const char *prompt)
84 {
85 char *line;
87 again:
88 if ((line = readline(prompt)) == NULL)
89 return NULL;
90 /* XXX: trim spaces? */
91 if (*line == '\0') {
92 free(line);
93 goto again;
94 }
96 add_history(line);
97 return line;
98 }
100 static void
101 spawn(const char *argv0, ...)
103 pid_t pid;
104 size_t i;
105 int status;
106 const char *argv[16], *last;
107 va_list ap;
109 memset(argv, 0, sizeof(argv));
111 va_start(ap, argv0);
112 argv[0] = argv0;
113 for (i = 1; i < nitems(argv); ++i) {
114 last = va_arg(ap, const char *);
115 if (last == NULL)
116 break;
117 argv[i] = last;
119 va_end(ap);
121 assert(last == NULL);
123 switch (pid = fork()) {
124 case -1:
125 err(1, "fork");
126 case 0: /* child */
127 execvp(argv[0], (char *const *)argv);
128 err(1, "execvp");
129 default:
130 waitpid(pid, &status, 0);
134 static int
135 stdio_tls_write(void *arg, const char *buf, int len)
137 struct tls *ctx = arg;
138 ssize_t ret;
140 do {
141 ret = tls_write(ctx, buf, len);
142 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
144 if (ret == -1)
145 warn("tls_write: %s", tls_error(ctx));
147 return ret;
150 static int
151 stdio_tls_read(void *arg, char *buf, int len)
153 struct tls *ctx = arg;
154 ssize_t ret;
156 do {
157 ret = tls_read(ctx, buf, len);
158 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
160 if (ret == -1)
161 warn("tls_read: %s", tls_error(ctx));
163 return ret;
166 static int
167 stdio_tls_close(void *arg)
169 struct tls *ctx = arg;
170 int ret;
172 do {
173 ret = tls_close(ctx);
174 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
176 return ret;
179 static void
180 tty_resized(int signo)
182 resized = 1;
185 static __dead void
186 usage(int ret)
188 fprintf(stderr, "usage: %s [-C cert] [-K key] [-o output] "
189 "[9p://][user@]host[:port][/path]\n", getprogname());
190 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
191 exit(ret);
194 static int
195 nextfid(void)
197 uint32_t i;
199 for (i = 0; ; ++i) {
200 if (i != pwdfid)
201 return i;
205 static void
206 do_send(void)
208 size_t r;
210 if (xdump)
211 hexdump("outgoing message", EVBUFFER_DATA(evb),
212 EVBUFFER_LENGTH(evb));
214 while (EVBUFFER_LENGTH(evb) != 0) {
215 r = fwrite(EVBUFFER_DATA(evb), 1, EVBUFFER_LENGTH(evb), fp);
216 if (r == 0)
217 fatalx("unexpected EOF");
218 evbuffer_drain(evb, r);
222 static void
223 mustread(void *d, size_t len)
225 size_t r;
227 r = fread(d, 1, len, fp);
228 if (r != len)
229 errx(1, "unexpected EOF");
232 static void
233 recv_msg(void)
235 size_t r;
236 uint32_t len, l;
237 char tmp[BUFSIZ];
239 r = fread(&len, 1, sizeof(len), fp);
240 if (r != sizeof(len))
241 errx(1, "unexpected EOF");
243 len = le32toh(len);
244 if (len < HEADERSIZE)
245 errx(1, "read message of invalid length %d", len);
247 len -= 4; /* skip the length just read */
249 while (len != 0) {
250 l = MIN(len, sizeof(tmp));
252 r = fread(tmp, 1, l, fp);
253 if (r != l)
254 errx(1, "unexpected EOF");
255 len -= r;
256 evbuffer_add(buf, tmp, r);
259 if (xdump)
260 hexdump("incoming packet", EVBUFFER_DATA(buf),
261 EVBUFFER_LENGTH(buf));
264 static uint64_t
265 np_read64(struct evbuffer *buf)
267 uint64_t n;
269 evbuffer_remove(buf, &n, sizeof(n));
270 return le64toh(n);
273 static uint32_t
274 np_read32(struct evbuffer *buf)
276 uint32_t n;
278 evbuffer_remove(buf, &n, sizeof(n));
279 return le32toh(n);
282 static uint16_t
283 np_read16(struct evbuffer *buf)
285 uint16_t n;
287 evbuffer_remove(buf, &n, sizeof(n));
288 return le16toh(n);
291 static uint16_t
292 np_read8(struct evbuffer *buf)
294 uint8_t n;
296 evbuffer_remove(buf, &n, sizeof(n));
297 return n;
300 static char *
301 np_readstr(struct evbuffer *buf)
303 uint16_t len;
304 char *str;
306 len = np_read16(buf);
307 assert(EVBUFFER_LENGTH(buf) >= len);
309 if ((str = calloc(1, len+1)) == NULL)
310 err(1, "calloc");
311 evbuffer_remove(buf, str, len);
312 return str;
315 static void
316 np_read_qid(struct evbuffer *buf, struct qid *qid)
318 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
320 qid->type = np_read8(buf);
321 qid->vers = np_read32(buf);
322 qid->path = np_read64(buf);
325 static int
326 np_read_stat(struct evbuffer *buf, struct np_stat *st)
328 uint16_t size;
330 memset(st, 0, sizeof(*st));
332 size = np_read16(buf);
333 if (size > EVBUFFER_LENGTH(buf))
334 return -1;
336 st->type = np_read16(buf);
337 st->dev = np_read32(buf);
338 np_read_qid(buf, &st->qid);
339 st->mode = np_read32(buf);
340 st->atime = np_read32(buf);
341 st->mtime = np_read32(buf);
342 st->length = np_read64(buf);
343 st->name = np_readstr(buf);
344 st->uid = np_readstr(buf);
345 st->gid = np_readstr(buf);
346 st->muid = np_readstr(buf);
348 return 0;
351 static void
352 expect(uint8_t type)
354 uint8_t t;
356 t = np_read8(buf);
357 if (t == type)
358 return;
360 if (t == Rerror) {
361 char *err;
363 /* skip tag */
364 np_read16(buf);
366 err = np_readstr(buf);
367 errx(1, "expected %s, got error %s",
368 pp_msg_type(type), err);
371 errx(1, "expected %s, got msg type %s",
372 pp_msg_type(type), pp_msg_type(t));
375 static void
376 expect2(uint8_t type, uint16_t tag)
378 uint16_t t;
380 expect(type);
382 t = np_read16(buf);
383 if (t == tag)
384 return;
386 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
389 static char *
390 check(uint8_t type, uint16_t tag)
392 uint16_t rtag;
393 uint8_t rtype;
395 rtype = np_read8(buf);
396 rtag = np_read16(buf);
397 if (rtype == type) {
398 if (rtag != tag)
399 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
400 return NULL;
403 if (rtype == Rerror)
404 return np_readstr(buf);
406 errx(1, "expected %s, got msg type %s",
407 pp_msg_type(type), pp_msg_type(rtype));
410 static void
411 do_version(void)
413 char *version;
415 tversion(VERSION9P, MSIZE9P);
416 do_send();
417 recv_msg();
418 expect2(Rversion, NOTAG);
420 msize = np_read32(buf);
421 version = np_readstr(buf);
423 if (msize > MSIZE9P || msize < 256)
424 errx(1, "got unexpected msize: %d", msize);
425 if (strcmp(version, VERSION9P))
426 errx(1, "unexpected 9p version: %s", version);
428 free(version);
429 ASSERT_EMPTYBUF();
432 static void
433 do_attach(const char *user)
435 struct qid qid;
437 tattach(pwdfid, NOFID, user, "/");
438 do_send();
439 recv_msg();
440 expect2(Rattach, iota_tag);
441 np_read_qid(buf, &qid);
443 ASSERT_EMPTYBUF();
446 static uint32_t
447 do_open(uint32_t fid, uint8_t mode)
449 struct qid qid;
450 uint32_t iounit;
452 topen(fid, mode);
453 do_send();
454 recv_msg();
455 expect2(Ropen, iota_tag);
457 np_read_qid(buf, &qid);
458 iounit = np_read32(buf);
460 ASSERT_EMPTYBUF();
462 return iounit;
465 static uint32_t
466 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
468 struct qid qid;
469 uint32_t iounit;
471 tcreate(fid, name, perm, mode);
472 do_send();
473 recv_msg();
474 expect2(Rcreate, iota_tag);
476 np_read_qid(buf, &qid);
477 iounit = np_read32(buf);
479 ASSERT_EMPTYBUF();
481 return iounit;
484 static void
485 do_clunk(uint32_t fid)
487 tclunk(fid);
488 do_send();
489 recv_msg();
490 expect2(Rclunk, iota_tag);
492 ASSERT_EMPTYBUF();
495 static char *
496 dup_fid(int fid, int nfid)
498 uint16_t nwqid;
499 char *errstr;
501 twalk(fid, nfid, NULL, 0);
502 do_send();
503 recv_msg();
505 if ((errstr = check(Rwalk, iota_tag)) != NULL)
506 return errstr;
508 nwqid = np_read16(buf);
509 assert(nwqid == 0);
511 ASSERT_EMPTYBUF();
513 return NULL;
516 static char *
517 walk_path(int fid, int newfid, const char *path, int *missing,
518 struct qid *qid)
520 char *wnames[MAXWELEM], *p, *t, *errstr;
521 size_t nwname, i;
522 uint16_t nwqid;
524 if ((p = strdup(path)) == NULL)
525 err(1, "strdup");
526 t = p;
528 /* strip initial ./ */
529 if (t[0] == '.' && t[1] == '/')
530 t += 2;
532 for (nwname = 0; nwname < nitems(wnames) &&
533 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
534 if (*wnames[nwname] != '\0')
535 nwname++;
538 twalk(fid, newfid, (const char **)wnames, nwname);
539 do_send();
540 recv_msg();
542 *missing = nwname;
543 if ((errstr = check(Rwalk, iota_tag)) != NULL) {
544 free(p);
545 return errstr;
548 nwqid = np_read16(buf);
549 assert(nwqid <= nwname);
551 /* consume all qids */
552 for (i = 0; i < nwqid; ++i)
553 np_read_qid(buf, qid);
555 free(p);
557 *missing = nwname - nwqid;
558 return NULL;
561 static void
562 do_stat(int fid, struct np_stat *st)
564 tstat(fid);
565 do_send();
566 recv_msg();
567 expect2(Rstat, iota_tag);
569 /* eat up the first two byte length */
570 np_read16(buf);
572 if (np_read_stat(buf, st) == -1)
573 errx(1, "invalid stat struct read");
575 ASSERT_EMPTYBUF();
578 static char *
579 do_wstat(int fid, const struct np_stat *st)
581 char *errstr;
583 twstat(fid, st);
584 do_send();
585 recv_msg();
587 if ((errstr = check(Rwstat, iota_tag)) != NULL)
588 return errstr;
590 ASSERT_EMPTYBUF();
592 return NULL;
595 static char *
596 do_remove(int fid)
598 char *errstr;
600 tremove(fid);
601 do_send();
602 recv_msg();
603 if ((errstr = check(Rremove, iota_tag)) != NULL)
604 return errstr;
606 ASSERT_EMPTYBUF();
608 return NULL;
611 static size_t
612 do_read(int fid, uint64_t off, uint32_t count, void *data)
614 uint32_t r;
616 tread(fid, off, count);
617 do_send();
618 recv_msg();
619 expect2(Rread, iota_tag);
621 r = np_read32(buf);
622 assert(r == EVBUFFER_LENGTH(buf));
623 assert(r <= count);
624 evbuffer_remove(buf, data, r);
626 ASSERT_EMPTYBUF();
628 return r;
631 static size_t
632 do_write(int fid, uint64_t off, uint32_t count, void *data)
634 uint32_t r;
636 twrite(fid, off, data, count);
637 do_send();
638 recv_msg();
639 expect2(Rwrite, iota_tag);
641 r = np_read32(buf);
642 assert(r <= count);
644 ASSERT_EMPTYBUF();
646 return r;
649 static void
650 draw_progress(const char *pre, const struct progress *p)
652 struct winsize ws;
653 int i, l, w;
654 double perc;
656 if (xdump)
657 return;
659 perc = 100.0 * p->done / p->max;
660 if (!tty_p) {
661 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
662 return;
665 if (resized) {
666 resized = 0;
668 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
669 return;
670 tty_width = ws.ws_col;
672 w = tty_width;
674 if (pre == NULL ||
675 ((l = fprintf(stderr, "\r%s ", pre)) == -1 || l >= w))
676 return;
678 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
679 if (w < 0) {
680 fprintf(stderr, "%4d%%\n", (int)perc);
681 return;
684 fprintf(stderr, "|");
686 l = w * MIN(100.0, perc) / 100.0;
687 for (i = 0; i < l; i++)
688 fprintf(stderr, "*");
689 for (; i < w; i++)
690 fprintf(stderr, " ");
691 fprintf(stderr, "|%4d%%", (int)perc);
694 static int
695 fetch_fid(int fid, int fd, const char *name)
697 static char buf[MSIZE9P];
698 struct progress p = {0};
699 struct np_stat st;
700 size_t r;
701 int ret = 0;
703 do_stat(fid, &st);
704 do_open(fid, KOREAD);
706 p.max = st.length;
707 for (;;) {
708 size_t len, off;
709 ssize_t nw;
711 len = MIN(sizeof(buf), msize);
712 len -= IOHDRSZ; /* for the request' fields */
714 r = do_read(fid, p.done, len, buf);
715 if (r == 0)
716 break;
718 for (off = 0; off < r; off += nw)
719 if ((nw = write(fd, buf + off, r - off)) == 0 ||
720 nw == -1) {
721 ret = -1;
722 goto end;
725 p.done += r;
726 draw_progress(name, &p);
728 #if 0
729 /* throttle, for debugging purpose */
731 struct timespec ts = { 0, 500000000 };
732 nanosleep(&ts, NULL);
734 #endif
737 end:
738 putchar('\n');
740 do_clunk(fid);
741 return ret;
744 static void
745 send_fid(int fid, const char *fnam, int open_flags, int fd, const char *name)
747 static char buf[MSIZE9P];
748 struct progress p = {0};
749 struct stat sb;
750 ssize_t r;
751 size_t w, len;
753 if (fstat(fd, &sb) == -1)
754 err(1, "fstat");
756 if (fnam != NULL)
757 do_create(fid, fnam, 0644, KOWRITE);
758 else
759 do_open(fid, open_flags | KOWRITE);
761 p.max = sb.st_size;
762 for (;;) {
763 len = MIN(sizeof(buf), msize);
764 len -= HEADERSIZE + 4 + 4 + 8; /* for the request' fields */
766 r = read(fd, buf, len);
767 if (r == 0)
768 break;
769 if (r == -1)
770 err(1, "read");
772 w = do_write(fid, p.done, r, buf);
773 p.done += w;
775 draw_progress(name, &p);
777 #if 0
778 /* throttle, for debugging purpose */
780 struct timespec ts = { 0, 500000000 };
781 nanosleep(&ts, NULL);
783 #endif
786 putchar('\n');
787 do_clunk(fid);
790 static int
791 woc_file(int fd, const char *prompt, const char *path)
793 struct qid qid;
794 const char *n = NULL;
795 char *errstr;
796 int nfid, miss;
798 nfid = nextfid();
799 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
800 if (errstr != NULL && miss > 1) {
801 fprintf(stderr, "%s: %s\n", path, errstr);
802 free(errstr);
803 return -1;
806 if (errstr != NULL || miss == 1) {
807 char p[PATH_MAX], *dn;
809 /*
810 * If it's only one component missing (the file name), walk
811 * to the parent directory and try to create the file.
812 */
814 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
815 fprintf(stderr, "path too long: %s\n", path);
816 return -1;
818 dn = dirname(p);
820 if (!strcmp(dn, ".")) {
821 errstr = dup_fid(pwdfid, nfid);
822 miss = 0;
823 } else
824 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
826 if (errstr != NULL) {
827 fprintf(stderr, "%s: %s\n", dn, errstr);
828 free(errstr);
829 return -1;
832 if (miss != 0) {
833 fprintf(stderr, "%s: not a directory\n", dn);
834 return -1;
837 if ((n = strrchr(path, '/')) != NULL)
838 n++;
839 else
840 n = path;
843 free(errstr);
845 if (miss > 1) {
846 fprintf(stderr, "can't create %s: missing %d path"
847 " component(s)\n", path, miss);
848 return -1;
851 send_fid(nfid, n, KOTRUNC, fd, prompt);
852 return 0;
855 static int
856 dial(const char *host, const char *port)
858 struct addrinfo hints, *res, *res0;
859 int sock, error, saved_errno;
860 const char *cause = NULL;
862 memset(&hints, 0, sizeof(hints));
863 hints.ai_family = AF_UNSPEC;
864 hints.ai_socktype = SOCK_STREAM;
865 error = getaddrinfo(host, port, &hints, &res0);
866 if (error)
867 errx(1, "%s", gai_strerror(error));
869 sock = -1;
870 for (res = res0; res != NULL; res = res->ai_next) {
871 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
872 res->ai_protocol);
873 if (sock == -1) {
874 cause = "socket";
875 continue;
878 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
879 cause = "connect";
880 saved_errno = errno;
881 close(sock);
882 errno = saved_errno;
883 sock = -1;
884 continue;
887 break;
889 freeaddrinfo(res0);
890 if (sock == -1)
891 err(1, "%s", cause);
892 return sock;
895 static void
896 do_connect(const char *host, const char *port, const char *user)
898 struct qid qid;
899 int nfid, miss, fd;
900 char *errstr;
902 fprintf(stderr, "connecting to %s:%s...", host, port);
904 if (tls) {
905 struct tls_config *conf;
906 struct tls *ctx;
907 int r;
909 if ((conf = tls_config_new()) == NULL)
910 fatalx("failed to create TLS config");
911 tls_config_insecure_noverifycert(conf);
912 tls_config_insecure_noverifyname(conf);
914 if (keypath == NULL)
915 keypath = crtpath;
917 if (tls_config_set_keypair_file(conf, crtpath, keypath) == -1)
918 fatalx("failed to load certs: (%s, %s)", crtpath,
919 keypath);
921 if ((ctx = tls_client()) == NULL)
922 fatalx("failed to create TLS client");
923 if (tls_configure(ctx, conf) == -1)
924 fatalx("failed to configure TLS client");
925 tls_config_free(conf);
927 if (tls_connect(ctx, host, port) == -1)
928 fatalx("failed to connect to %s:%s: %s", host, port,
929 tls_error(ctx));
931 do {
932 r = tls_handshake(ctx);
933 } while (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT);
934 fp = funopen(ctx, stdio_tls_read, stdio_tls_write, NULL,
935 stdio_tls_close);
936 if (fp == NULL)
937 fatal("funopen");
938 } else {
939 int fd;
941 fd = dial(host, port);
942 if ((fp = fdopen(fd, "r+")) == NULL)
943 fatal("fdopen");
946 fprintf(stderr, " done!\n");
948 do_version();
949 do_attach(user);
952 static int
953 tmp_file(char sfn[TMPFSTRLEN])
955 int tmpfd;
957 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
958 if ((tmpfd = mkstemp(sfn)) == -1) {
959 warn("mkstemp %s", sfn);
960 return -1;
963 /* set the close-on-exec flag */
964 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
965 warn("fcntl");
966 close(tmpfd);
967 return -1;
970 return tmpfd;
973 static inline const char *
974 pp_perm(uint8_t x)
976 switch (x & 0x7) {
977 case 0x0:
978 return "---";
979 case 0x1:
980 return "--x";
981 case 0x2:
982 return "-w-";
983 case 0x3:
984 return "-wx";
985 case 0x4:
986 return "r--";
987 case 0x5:
988 return "r-x";
989 case 0x6:
990 return "rw-";
991 case 0x7:
992 return "rwx";
993 default:
994 /* unreachable, just for the compiler' happiness */
995 return "???";
999 static inline void
1000 prepare_wstat(struct np_stat *st)
1002 memset(st, 0xFF, sizeof(*st));
1003 st->name = NULL;
1004 st->uid = NULL;
1005 st->gid = NULL;
1006 st->muid = NULL;
1009 static int
1010 print_dirent(const struct np_stat *st)
1012 time_t mtime;
1013 struct tm *tm;
1014 const char *timfmt;
1015 char fmt[FMT_SCALED_STRSIZE], tim[13];
1017 if (fmt_scaled(st->length, fmt) == -1)
1018 strlcpy(fmt, "xxx", sizeof(fmt));
1020 mtime = st->mtime;
1022 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
1023 timfmt = "%b %e %R";
1024 else
1025 timfmt = "%b %e %Y";
1027 if ((tm = localtime(&mtime)) == NULL ||
1028 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1029 strlcpy(tim, "unknown", sizeof(tim));
1031 if (st->qid.type & QTDIR)
1032 printf("d");
1033 else
1034 printf("-");
1035 printf("%s", pp_perm(st->mode >> 6));
1036 printf("%s", pp_perm(st->mode >> 3));
1037 printf("%s", pp_perm(st->mode));
1038 printf(" %8s %12s %s%s\n", fmt, tim, st->name,
1039 st->qid.type & QTDIR ? "/" : "");
1041 return 0;
1044 int
1045 dir_listing(const char *path, int (*fn)(const struct np_stat *),
1046 int printerr)
1048 struct qid qid;
1049 struct np_stat st;
1050 uint64_t off = 0;
1051 uint32_t len;
1052 int nfid, miss, r;
1053 char *errstr;
1055 now = time(NULL);
1056 nfid = nextfid();
1058 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
1059 if (errstr != NULL) {
1060 if (printerr)
1061 printf("%s: %s\n", path, errstr);
1062 free(errstr);
1063 return -1;
1065 if (miss) {
1066 if (printerr)
1067 printf("%s: No such file or directory\n", path);
1068 return -1;
1070 if (!(qid.type & QTDIR)) {
1071 if (printerr)
1072 printf("%s: not a directory\n", path);
1073 do_clunk(nfid);
1074 return -1;
1077 do_open(nfid, KOREAD);
1078 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1080 for (;;) {
1081 tread(nfid, off, msize - IOHDRSZ);
1082 do_send();
1083 recv_msg();
1084 expect2(Rread, iota_tag);
1086 len = np_read32(buf);
1087 if (len == 0)
1088 break;
1090 evbuffer_add_buffer(dirbuf, buf);
1091 off += len;
1093 ASSERT_EMPTYBUF();
1096 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1097 if (np_read_stat(dirbuf, &st) == -1)
1098 errx(1, "invalid stat struct read");
1100 r = fn(&st);
1102 free(st.name);
1103 free(st.uid);
1104 free(st.gid);
1105 free(st.muid);
1107 if (r == -1)
1108 break;
1111 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1112 do_clunk(nfid);
1113 return 0;
1116 void
1117 cmd_bell(int argc, const char **argv)
1119 if (argc == 0) {
1120 bell = !bell;
1121 if (bell)
1122 puts("bell mode enabled");
1123 else
1124 puts("bell mode disabled");
1125 return;
1128 if (argc != 1)
1129 goto usage;
1131 if (!strcmp(*argv, "on")) {
1132 bell = 1;
1133 puts("bell mode enabled");
1134 return;
1137 if (!strcmp(*argv, "off")) {
1138 bell = 0;
1139 puts("bell mode disabled");
1140 return;
1143 usage:
1144 printf("bell [on | off]\n");
1147 void
1148 cmd_bye(int argc, const char **argv)
1150 log_warnx("bye\n");
1151 fclose(fp);
1152 exit(0);
1155 void
1156 cmd_cd(int argc, const char **argv)
1158 struct qid qid;
1159 int nfid, miss;
1160 char *errstr;
1162 if (argc != 1) {
1163 printf("usage: cd remote-path\n");
1164 return;
1167 nfid = nextfid();
1168 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1169 if (errstr != NULL) {
1170 printf("%s: %s\n", argv[0], errstr);
1171 free(errstr);
1172 return;
1175 if (miss != 0 || !(qid.type & QTDIR)) {
1176 printf("%s: not a directory\n", argv[0]);
1177 if (miss == 0)
1178 do_clunk(nfid);
1179 return;
1182 do_clunk(pwdfid);
1183 pwdfid = nfid;
1186 void
1187 cmd_edit(int argc, const char **argv)
1189 struct qid qid;
1190 int nfid, tmpfd, miss;
1191 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1192 const char *ed;
1194 if (argc != 1) {
1195 puts("usage: edit file");
1196 return;
1199 if ((ed = getenv("VISUAL")) == NULL &&
1200 (ed = getenv("EDITOR")) == NULL)
1201 ed = "ed";
1203 nfid = nextfid();
1204 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1205 if (errstr != NULL) {
1206 printf("%s: %s\n", *argv, errstr);
1207 free(errstr);
1208 return;
1211 if (miss != 0 || qid.type != 0) {
1212 printf("%s: not a file\n", *argv);
1213 if (miss == 0)
1214 do_clunk(nfid);
1215 return;
1218 if ((tmpfd = tmp_file(sfn)) == -1) {
1219 do_clunk(nfid);
1220 return;
1223 strlcpy(p, *argv, sizeof(p));
1224 name = basename(p);
1226 if (fetch_fid(nfid, tmpfd, name)) {
1227 warn("failed fetch or can't write %s", sfn);
1228 goto end;
1230 close(tmpfd);
1232 spawn(ed, sfn, NULL);
1235 * Re-open the file because it's not guaranteed that the
1236 * file descriptor tmpfd is still associated with the file
1237 * pointed by sfn: it's not uncommon for editor to write
1238 * a backup file and then rename(2) it to the file name.
1240 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1241 warn("can't open %s", sfn);
1242 goto end;
1245 woc_file(tmpfd, *argv, name);
1246 close(tmpfd);
1248 end:
1249 unlink(sfn);
1252 void
1253 cmd_get(int argc, const char **argv)
1255 struct qid qid;
1256 const char *l;
1257 char *errstr;
1258 int nfid, fd, miss;
1260 if (argc != 1 && argc != 2) {
1261 printf("usage: get remote-file [local-file]\n");
1262 return;
1265 if (argc == 2)
1266 l = argv[1];
1267 else if ((l = strrchr(argv[0], '/')) != NULL)
1268 l++; /* skip / */
1269 else
1270 l = argv[0];
1272 nfid = nextfid();
1273 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1274 if (errstr != NULL) {
1275 printf("%s: %s\n", argv[0], errstr);
1276 free(errstr);
1277 return;
1280 if (miss != 0 || qid.type != 0) {
1281 printf("%s: not a file\n", argv[0]);
1282 if (miss == 0)
1283 do_clunk(nfid);
1284 return;
1287 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1288 warn("can't open %s", l);
1289 do_clunk(nfid);
1290 return;
1293 if (fetch_fid(nfid, fd, l) == -1)
1294 warn("write %s", l);
1295 close(fd);
1298 void
1299 cmd_hexdump(int argc, const char **argv)
1301 if (argc == 0) {
1302 xdump = !xdump;
1303 if (xdump)
1304 puts("hexdump mode enabled");
1305 else
1306 puts("hexdump mode disabled");
1307 return;
1310 if (argc > 1)
1311 goto usage;
1313 if (!strcmp(*argv, "on")) {
1314 xdump = 1;
1315 puts("hexdump mode enabled");
1316 return;
1319 if (!strcmp(*argv, "off")) {
1320 xdump = 0;
1321 puts("hexdump mode disabled");
1322 return;
1325 usage:
1326 puts("usage: hexdump [on | off]");
1329 void
1330 cmd_lcd(int argc, const char **argv)
1332 const char *dir;
1334 if (argc > 1) {
1335 printf("usage: lcd [local-directory]\n");
1336 return;
1339 if (argc == 1)
1340 dir = *argv;
1342 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1343 printf("HOME is not defined\n");
1344 return;
1347 if (chdir(dir) == -1)
1348 printf("cd: %s: %s\n", dir, strerror(errno));
1351 void
1352 cmd_lpwd(int argc, const char **argv)
1354 char path[PATH_MAX];
1356 if (argc != 0) {
1357 printf("usage: lpwd\n");
1358 return;
1361 if (getcwd(path, sizeof(path)) == NULL) {
1362 printf("lpwd: %s\n", strerror(errno));
1363 return;
1366 printf("%s\n", path);
1369 void
1370 cmd_ls(int argc, const char **argv)
1372 if (argc > 1) {
1373 puts("usage: ls [path]");
1374 return;
1377 dir_listing(argc == 0 ? "." : argv[0], print_dirent, 1);
1380 void
1381 cmd_page(int argc, const char **argv)
1383 struct qid qid;
1384 int nfid, tmpfd, miss, r;
1385 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1386 const char *pager;
1388 if (argc != 1) {
1389 puts("usage: page file");
1390 return;
1393 if ((pager = getenv("PAGER")) == NULL)
1394 pager = "less";
1396 nfid = nextfid();
1397 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1398 if (errstr != NULL) {
1399 printf("%s: %s\n", *argv, errstr);
1400 free(errstr);
1401 return;
1404 if (miss != 0 || qid.type != 0) {
1405 printf("%s: not a file\n", *argv);
1406 if (miss == 0)
1407 do_clunk(nfid);
1408 return;
1411 if ((tmpfd = tmp_file(sfn)) == -1) {
1412 do_clunk(nfid);
1413 return;
1416 strlcpy(p, *argv, sizeof(p));
1417 name = basename(p);
1418 if ((r = fetch_fid(nfid, tmpfd, name)) == -1)
1419 warn("write %s", sfn);
1420 close(tmpfd);
1421 if (r != -1)
1422 spawn(pager, sfn, NULL);
1423 unlink(sfn);
1426 void
1427 cmd_pipe(int argc, const char **argv)
1429 struct qid qid;
1430 pid_t pid;
1431 int nfid, tmpfd, miss, status;
1432 int filedes[2]; /* read end, write end */
1433 char *errstr;
1435 if (argc < 2) {
1436 puts("usage: pipe remote-file cmd [args...]");
1437 return;
1440 nfid = nextfid();
1441 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1442 if (errstr != NULL) {
1443 printf("%s: %s\n", *argv, errstr);
1444 free(errstr);
1445 return;
1448 if (miss != 0 || qid.type != 0) {
1449 printf("%s: not a file\n", *argv);
1450 if (miss == 0)
1451 do_clunk(nfid);
1452 return;
1455 if (pipe(filedes) == -1)
1456 err(1, "pipe");
1458 switch (pid = vfork()) {
1459 case -1:
1460 err(1, "vfork");
1461 case 0:
1462 close(filedes[1]);
1463 if (dup2(filedes[0], 0) == -1)
1464 err(1, "dup2");
1465 execvp(argv[1], (char *const *)argv + 1);
1466 err(1, "execvp");
1469 close(filedes[0]);
1470 if (fetch_fid(nfid, filedes[1], *argv) == -1)
1471 warnx("failed to fetch all the file");
1472 close(filedes[1]);
1474 waitpid(pid, &status, 0);
1477 void
1478 cmd_put(int argc, const char **argv)
1480 struct qid qid;
1481 const char *l;
1482 int fd;
1484 if (argc != 1 && argc != 2) {
1485 printf("usage: put local-file [remote-file]\n");
1486 return;
1489 if (argc == 2)
1490 l = argv[1];
1491 else if ((l = strrchr(argv[0], '/')) != NULL)
1492 l++; /* skip / */
1493 else
1494 l = argv[0];
1496 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1497 warn("%s", argv[0]);
1498 return;
1501 woc_file(fd, argv[0], l);
1502 close(fd);
1505 void
1506 cmd_rename(int argc, const char **argv)
1508 struct np_stat st;
1509 struct qid qid;
1510 char *errstr;
1511 int nfid, miss;
1513 if (argc != 2) {
1514 puts("usage: rename remote-file new-remote-name");
1515 return;
1518 nfid = nextfid();
1519 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1520 if (errstr != NULL) {
1521 printf("%s: %s\n", argv[0], errstr);
1522 free(errstr);
1523 return;
1526 if (miss != 0) {
1527 printf("%s: not such file or directory\n", argv[0]);
1528 return;
1531 prepare_wstat(&st);
1532 st.name = (char *)argv[1];
1533 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1534 printf("rename: %s\n", errstr);
1535 free(errstr);
1538 do_clunk(nfid);
1541 void
1542 cmd_rm(int argc, const char **argv)
1544 struct qid qid;
1545 char *errstr;
1546 int nfid, miss;
1548 if (argc == 0) {
1549 puts("usage: rm file ...");
1550 return;
1553 for (; *argv; ++argv, --argc) {
1554 nfid = nextfid();
1555 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1556 if (errstr != NULL) {
1557 printf("%s: %s\n", *argv, errstr);
1558 free(errstr);
1559 continue;
1561 if (miss) {
1562 printf("%s: not such file or directory\n", *argv);
1563 continue;
1566 if ((errstr = do_remove(nfid)) != NULL) {
1567 printf("%s: %s\n", *argv, errstr);
1568 free(errstr);
1569 continue;
1574 void
1575 cmd_verbose(int argc, const char **argv)
1577 if (argc == 0) {
1578 log_setverbose(!log_getverbose());
1579 if (log_getverbose())
1580 puts("verbose mode enabled");
1581 else
1582 puts("verbose mode disabled");
1583 return;
1586 if (argc != 1)
1587 goto usage;
1589 if (!strcmp(*argv, "on")) {
1590 log_setverbose(1);
1591 puts("verbose mode enabled");
1592 return;
1595 if (!strcmp(*argv, "off")) {
1596 log_setverbose(0);
1597 puts("verbose mode disabled");
1598 return;
1601 usage:
1602 printf("verbose [on | off]\n");
1605 static void
1606 excmd(int argc, const char **argv)
1608 size_t i;
1610 if (argc == 0)
1611 return;
1613 for (i = 0; i < nitems(cmds); ++i) {
1614 if (!strcmp(cmds[i].name, *argv)) {
1615 cmds[i].fn(argc-1, argv+1);
1616 return;
1620 log_warnx("unknown command %s", *argv);
1623 static int
1624 parsecmd(char *cmd, char **argv, size_t len)
1626 int escape, quote;
1627 int argc = 0;
1629 memset(argv, 0, sizeof(*argv) * len);
1631 while (argc < len) {
1632 while (isspace((unsigned char)*cmd))
1633 cmd++;
1634 if (*cmd == '\0')
1635 break;
1637 argv[argc++] = cmd;
1638 escape = quote = 0;
1639 for (; *cmd != '\0'; ++cmd) {
1640 if (escape) {
1641 escape = 0;
1642 continue;
1644 if (*cmd == '\\') {
1645 escape = 1;
1646 memmove(cmd, cmd + 1, strlen(cmd));
1647 cmd--;
1648 continue;
1650 if (*cmd == quote) {
1651 quote = 0;
1652 memmove(cmd, cmd + 1, strlen(cmd));
1653 cmd--;
1654 continue;
1656 if (*cmd == '\'' || *cmd == '"') {
1657 quote = *cmd;
1658 memmove(cmd, cmd + 1, strlen(cmd));
1659 cmd--;
1660 continue;
1662 if (quote)
1663 continue;
1665 if (isspace((unsigned char)*cmd))
1666 break;
1669 if (*cmd == '\0' && (escape || quote)) {
1670 fprintf(stderr, "unterminated %s\n",
1671 escape ? "escape" : "quote");
1672 return -1;
1675 if (*cmd == '\0')
1676 break;
1677 *cmd++ = '\0';
1680 if (*cmd != '\0') {
1681 fprintf(stderr, "too many arguments\n");
1682 return -1;
1684 return argc;
1687 static void
1688 cd_or_fetch(const char *path, const char *outfile)
1690 struct qid qid;
1691 char *errstr;
1692 int fd, nfid, miss;
1694 while (*path == '/')
1695 path++;
1696 if (*path == '\0')
1697 return;
1699 nfid = nextfid();
1700 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
1701 if (errstr)
1702 errx(1, "walk %s: %s", path, errstr);
1703 if (miss)
1704 errc(1, ENOENT, "walk %s", path);
1706 if (qid.type & QTDIR) {
1707 if (outfile)
1708 errx(1, "can't fetch directory %s", path);
1709 do_clunk(pwdfid);
1710 pwdfid = nfid;
1711 return;
1714 if (outfile == NULL) {
1715 if ((outfile = strrchr(path, '/')) == NULL)
1716 outfile = path;
1717 else
1718 outfile++;
1719 if (*outfile == '\0')
1720 errx(1, "invalid path: missing file name: %s",
1721 path);
1724 if (strcmp(outfile, "-") != 0) {
1725 fd = open(outfile, O_WRONLY|O_CREAT, 0644);
1726 if (fd == -1)
1727 err(1, "can't open for writing %s", outfile);
1728 } else
1729 fd = 1;
1731 if (fetch_fid(nfid, fd, outfile) == -1)
1732 err(1, "write %s", outfile);
1733 close(fd);
1734 fclose(fp);
1735 exit(0);
1738 static const char *
1739 parse_addr(const char *url, const char **user,
1740 const char **port, const char **path)
1742 static char buf[PATH_MAX];
1743 char *host, *t;
1745 *user = *port = *path = NULL;
1746 host = buf;
1748 if (strlcpy(buf, url, sizeof(buf)) >= sizeof(buf))
1749 errx(1, "connection string too long");
1751 if (!strncmp(host, "9p://", 5))
1752 host += 5;
1754 if ((t = strchr(host, '/')) != NULL) {
1755 if (t == host)
1756 errx(1, "invalid connection string: %s", url);
1757 *t++ = '\0';
1758 if (*t != '\0')
1759 *path = t;
1762 if ((t = strchr(host, '@')) != NULL) {
1763 if (t == host)
1764 errx(1, "invalid connection string: %s", url);
1765 *t++ = '\0';
1766 *user = host;
1767 host = t;
1768 } else if ((*user = getenv("USER")) == NULL)
1769 errx(1, "USER not defined");
1771 if ((t = strchr(host, ':')) != NULL) {
1772 *t++ = '\0';
1773 if (*t != '\0')
1774 *port = t;
1776 if (*port == NULL)
1777 *port = "1337";
1779 return host;
1782 int
1783 main(int argc, char **argv)
1785 const char *user, *host, *port, *path;
1786 const char *outfile = NULL;
1787 int ch;
1789 log_init(1, LOG_DAEMON);
1790 log_setverbose(0);
1791 log_procinit(getprogname());
1793 while ((ch = getopt(argc, argv, "C:cK:o:")) != -1) {
1794 switch (ch) {
1795 case 'C':
1796 tls = 1;
1797 crtpath = optarg;
1798 break;
1799 case 'c': /* deprecated, remove after 0.3 */
1800 tls = 1;
1801 break;
1802 case 'K':
1803 tls = 1;
1804 keypath = optarg;
1805 break;
1806 case 'o':
1807 outfile = optarg;
1808 break;
1809 default:
1810 usage(1);
1813 argc -= optind;
1814 argv += optind;
1816 if (argc == 0 || (tls && crtpath == NULL))
1817 usage(1);
1819 host = parse_addr(argv[0], &user, &port, &path);
1820 if (path == NULL && argv[1] != NULL) /* drop argv[1] after 0.3 */
1821 path = argv[1];
1822 if (outfile && path == NULL)
1823 usage(1);
1825 signal(SIGPIPE, SIG_IGN);
1826 if (isatty(1)) {
1827 tty_p = 1;
1828 resized = 1;
1829 signal(SIGWINCH, tty_resized);
1832 if ((evb = evbuffer_new()) == NULL)
1833 fatal("evbuffer_new");
1835 if ((buf = evbuffer_new()) == NULL)
1836 fatal("evbuffer_new");
1838 if ((dirbuf = evbuffer_new()) == NULL)
1839 fatal("evbuferr_new");
1841 do_connect(host, port, user);
1842 if (path)
1843 cd_or_fetch(path, outfile);
1845 compl_setup();
1846 for (;;) {
1847 int argc;
1848 char *line, *argv[16] = {0}, **ap;
1850 if ((line = read_line("kamiftp> ")) == NULL)
1851 break;
1853 if ((argc = parsecmd(line, argv, nitems(argv) - 1)) == -1) {
1854 free(line);
1855 continue;
1858 argv[argc] = NULL;
1859 excmd(argc, (const char **)argv);
1861 if (bell)
1862 fprintf(stderr, "\a");
1864 free(line);
1867 printf("\n");
1868 fclose(fp);