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 *buf, size_t len)
196 ssize_t r;
197 uint8_t *d = buf;
199 while (len != 0) {
200 if (ctx == NULL) {
201 r = read(sock, d, len);
202 if (r == 0 || r == -1)
203 errx(1, "EOF");
204 } else {
205 r = tls_read(ctx, d, len);
206 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
207 continue;
208 if (r == -1)
209 errx(1, "tls: %s", tls_error(ctx));
212 d += r;
213 len -= r;
217 static void
218 recv_msg(void)
220 uint32_t len, l;
221 char tmp[BUFSIZ];
223 mustread(&len, sizeof(len));
224 len = le32toh(len);
225 if (len < HEADERSIZE)
226 errx(1, "read message of invalid length %d", len);
228 len -= 4; /* skip the length just read */
230 while (len != 0) {
231 l = MIN(len, sizeof(tmp));
232 mustread(tmp, l);
233 len -= l;
234 evbuffer_add(buf, tmp, l);
237 if (xdump)
238 hexdump("incoming packet", EVBUFFER_DATA(buf),
239 EVBUFFER_LENGTH(buf));
242 static uint64_t
243 np_read64(struct evbuffer *buf)
245 uint64_t n;
247 evbuffer_remove(buf, &n, sizeof(n));
248 return le64toh(n);
251 static uint32_t
252 np_read32(struct evbuffer *buf)
254 uint32_t n;
256 evbuffer_remove(buf, &n, sizeof(n));
257 return le32toh(n);
260 static uint16_t
261 np_read16(struct evbuffer *buf)
263 uint16_t n;
265 evbuffer_remove(buf, &n, sizeof(n));
266 return le16toh(n);
269 static uint16_t
270 np_read8(struct evbuffer *buf)
272 uint8_t n;
274 evbuffer_remove(buf, &n, sizeof(n));
275 return n;
278 static char *
279 np_readstr(struct evbuffer *buf)
281 uint16_t len;
282 char *str;
284 len = np_read16(buf);
285 assert(EVBUFFER_LENGTH(buf) >= len);
287 if ((str = calloc(1, len+1)) == NULL)
288 err(1, "calloc");
289 evbuffer_remove(buf, str, len);
290 return str;
293 static void
294 np_read_qid(struct evbuffer *buf, struct qid *qid)
296 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
298 qid->type = np_read8(buf);
299 qid->vers = np_read32(buf);
300 qid->path = np_read64(buf);
303 static int
304 np_read_stat(struct evbuffer *buf, struct np_stat *st)
306 uint16_t size;
308 memset(st, 0, sizeof(*st));
310 size = np_read16(buf);
311 if (size > EVBUFFER_LENGTH(buf))
312 return -1;
314 st->type = np_read16(buf);
315 st->dev = np_read32(buf);
316 np_read_qid(buf, &st->qid);
317 st->mode = np_read32(buf);
318 st->atime = np_read32(buf);
319 st->mtime = np_read32(buf);
320 st->length = np_read64(buf);
321 st->name = np_readstr(buf);
322 st->uid = np_readstr(buf);
323 st->gid = np_readstr(buf);
324 st->muid = np_readstr(buf);
326 return 0;
329 static void
330 expect(uint8_t type)
332 uint8_t t;
334 t = np_read8(buf);
335 if (t == type)
336 return;
338 if (t == Rerror) {
339 char *err;
341 /* skip tag */
342 np_read16(buf);
344 err = np_readstr(buf);
345 errx(1, "expected %s, got error %s",
346 pp_msg_type(type), err);
349 errx(1, "expected %s, got msg type %s",
350 pp_msg_type(type), pp_msg_type(t));
353 static void
354 expect2(uint8_t type, uint16_t tag)
356 uint16_t t;
358 expect(type);
360 t = np_read16(buf);
361 if (t == tag)
362 return;
364 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
367 static char *
368 check(uint8_t type, uint16_t tag)
370 uint16_t rtag;
371 uint8_t rtype;
373 rtype = np_read8(buf);
374 rtag = np_read16(buf);
375 if (rtype == type) {
376 if (rtag != tag)
377 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
378 return NULL;
381 if (rtype == Rerror)
382 return np_readstr(buf);
384 errx(1, "expected %s, got msg type %s",
385 pp_msg_type(type), pp_msg_type(rtype));
388 static void
389 do_version(void)
391 char *version;
393 tversion(VERSION9P, MSIZE9P);
394 do_send();
395 recv_msg();
396 expect2(Rversion, NOTAG);
398 msize = np_read32(buf);
399 version = np_readstr(buf);
401 if (msize > MSIZE9P || msize < 256)
402 errx(1, "got unexpected msize: %d", msize);
403 if (strcmp(version, VERSION9P))
404 errx(1, "unexpected 9p version: %s", version);
406 free(version);
407 ASSERT_EMPTYBUF();
410 static void
411 do_attach(const char *user)
413 struct qid qid;
415 tattach(pwdfid, NOFID, user, "/");
416 do_send();
417 recv_msg();
418 expect2(Rattach, iota_tag);
419 np_read_qid(buf, &qid);
421 ASSERT_EMPTYBUF();
424 static uint32_t
425 do_open(uint32_t fid, uint8_t mode)
427 struct qid qid;
428 uint32_t iounit;
430 topen(fid, mode);
431 do_send();
432 recv_msg();
433 expect2(Ropen, iota_tag);
435 np_read_qid(buf, &qid);
436 iounit = np_read32(buf);
438 ASSERT_EMPTYBUF();
440 return iounit;
443 static uint32_t
444 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
446 struct qid qid;
447 uint32_t iounit;
449 tcreate(fid, name, perm, mode);
450 do_send();
451 recv_msg();
452 expect2(Rcreate, iota_tag);
454 np_read_qid(buf, &qid);
455 iounit = np_read32(buf);
457 ASSERT_EMPTYBUF();
459 return iounit;
462 static void
463 do_clunk(uint32_t fid)
465 tclunk(fid);
466 do_send();
467 recv_msg();
468 expect2(Rclunk, iota_tag);
470 ASSERT_EMPTYBUF();
473 static char *
474 dup_fid(int fid, int nfid)
476 uint16_t nwqid;
477 char *errstr;
479 twalk(fid, nfid, NULL, 0);
480 do_send();
481 recv_msg();
483 if ((errstr = check(Rwalk, iota_tag)) != NULL)
484 return errstr;
486 nwqid = np_read16(buf);
487 assert(nwqid == 0);
489 ASSERT_EMPTYBUF();
491 return NULL;
494 static char *
495 walk_path(int fid, int newfid, const char *path, int *missing,
496 struct qid *qid)
498 char *wnames[MAXWELEM], *p, *t, *errstr;
499 size_t nwname, i;
500 uint16_t nwqid;
502 if ((p = strdup(path)) == NULL)
503 err(1, "strdup");
504 t = p;
506 /* strip initial ./ */
507 if (t[0] == '.' && t[1] == '/')
508 t += 2;
510 for (nwname = 0; nwname < nitems(wnames) &&
511 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
512 if (*wnames[nwname] != '\0')
513 nwname++;
516 twalk(fid, newfid, (const char **)wnames, nwname);
517 do_send();
518 recv_msg();
520 *missing = nwname;
521 if ((errstr = check(Rwalk, iota_tag)) != NULL) {
522 free(p);
523 return errstr;
526 nwqid = np_read16(buf);
527 assert(nwqid <= nwname);
529 /* consume all qids */
530 for (i = 0; i < nwqid; ++i)
531 np_read_qid(buf, qid);
533 free(p);
535 *missing = nwname - nwqid;
536 return NULL;
539 static void
540 do_stat(int fid, struct np_stat *st)
542 tstat(fid);
543 do_send();
544 recv_msg();
545 expect2(Rstat, iota_tag);
547 /* eat up the first two byte length */
548 np_read16(buf);
550 if (np_read_stat(buf, st) == -1)
551 errx(1, "invalid stat struct read");
553 ASSERT_EMPTYBUF();
556 static char *
557 do_wstat(int fid, const struct np_stat *st)
559 char *errstr;
561 twstat(fid, st);
562 do_send();
563 recv_msg();
565 if ((errstr = check(Rwstat, iota_tag)) != NULL)
566 return errstr;
568 ASSERT_EMPTYBUF();
570 return NULL;
573 static char *
574 do_remove(int fid)
576 char *errstr;
578 tremove(fid);
579 do_send();
580 recv_msg();
581 if ((errstr = check(Rremove, iota_tag)) != NULL)
582 return errstr;
584 ASSERT_EMPTYBUF();
586 return NULL;
589 static size_t
590 do_read(int fid, uint64_t off, uint32_t count, void *data)
592 uint32_t r;
594 tread(fid, off, count);
595 do_send();
596 recv_msg();
597 expect2(Rread, iota_tag);
599 r = np_read32(buf);
600 assert(r == EVBUFFER_LENGTH(buf));
601 assert(r <= count);
602 evbuffer_remove(buf, data, r);
604 ASSERT_EMPTYBUF();
606 return r;
609 static size_t
610 do_write(int fid, uint64_t off, uint32_t count, void *data)
612 uint32_t r;
614 twrite(fid, off, data, count);
615 do_send();
616 recv_msg();
617 expect2(Rwrite, iota_tag);
619 r = np_read32(buf);
620 assert(r <= count);
622 ASSERT_EMPTYBUF();
624 return r;
627 static void
628 draw_progress(const char *pre, const struct progress *p)
630 struct winsize ws;
631 int i, l, w;
632 double perc;
634 if (xdump)
635 return;
637 perc = 100.0 * p->done / p->max;
638 if (!tty_p) {
639 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
640 return;
643 if (resized) {
644 resized = 0;
646 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
647 return;
648 tty_width = ws.ws_col;
650 w = tty_width;
652 if (pre == NULL ||
653 ((l = fprintf(stderr, "\r%s ", pre)) == -1 || l >= w))
654 return;
656 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
657 if (w < 0) {
658 fprintf(stderr, "%4d%%\n", (int)perc);
659 return;
662 fprintf(stderr, "|");
664 l = w * MIN(100.0, perc) / 100.0;
665 for (i = 0; i < l; i++)
666 fprintf(stderr, "*");
667 for (; i < w; i++)
668 fprintf(stderr, " ");
669 fprintf(stderr, "|%4d%%", (int)perc);
672 static int
673 fetch_fid(int fid, int fd, const char *name)
675 static char buf[MSIZE9P];
676 struct progress p = {0};
677 struct np_stat st;
678 size_t r;
679 int ret = 0;
681 do_stat(fid, &st);
682 do_open(fid, KOREAD);
684 p.max = st.length;
685 for (;;) {
686 size_t len, off;
687 ssize_t nw;
689 len = MIN(sizeof(buf), msize);
690 len -= IOHDRSZ; /* for the request' fields */
692 r = do_read(fid, p.done, len, buf);
693 if (r == 0)
694 break;
696 for (off = 0; off < r; off += nw)
697 if ((nw = write(fd, buf + off, r - off)) == 0 ||
698 nw == -1) {
699 ret = -1;
700 goto end;
703 p.done += r;
704 draw_progress(name, &p);
706 #if 0
707 /* throttle, for debugging purpose */
709 struct timespec ts = { 0, 500000000 };
710 nanosleep(&ts, NULL);
712 #endif
715 end:
716 putchar('\n');
718 do_clunk(fid);
719 return ret;
722 static void
723 send_fid(int fid, const char *fnam, int open_flags, int fd, const char *name)
725 static char buf[MSIZE9P];
726 struct progress p = {0};
727 struct stat sb;
728 ssize_t r;
729 size_t w, len;
731 if (fstat(fd, &sb) == -1)
732 err(1, "fstat");
734 if (fnam != NULL)
735 do_create(fid, fnam, 0644, KOWRITE);
736 else
737 do_open(fid, open_flags | KOWRITE);
739 p.max = sb.st_size;
740 for (;;) {
741 len = MIN(sizeof(buf), msize);
742 len -= HEADERSIZE + 4 + 4 + 8; /* for the request' fields */
744 r = read(fd, buf, len);
745 if (r == 0)
746 break;
747 if (r == -1)
748 err(1, "read");
750 w = do_write(fid, p.done, r, buf);
751 p.done += w;
753 draw_progress(name, &p);
755 #if 0
756 /* throttle, for debugging purpose */
758 struct timespec ts = { 0, 500000000 };
759 nanosleep(&ts, NULL);
761 #endif
764 putchar('\n');
765 do_clunk(fid);
768 static int
769 woc_file(int fd, const char *prompt, const char *path)
771 struct qid qid;
772 const char *n = NULL;
773 char *errstr;
774 int nfid, miss;
776 nfid = nextfid();
777 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
778 if (errstr != NULL && miss > 1) {
779 fprintf(stderr, "%s: %s\n", path, errstr);
780 free(errstr);
781 return -1;
784 if (errstr != NULL || miss == 1) {
785 char p[PATH_MAX], *dn;
787 /*
788 * If it's only one component missing (the file name), walk
789 * to the parent directory and try to create the file.
790 */
792 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
793 fprintf(stderr, "path too long: %s\n", path);
794 return -1;
796 dn = dirname(p);
798 if (!strcmp(dn, ".")) {
799 errstr = dup_fid(pwdfid, nfid);
800 miss = 0;
801 } else
802 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
804 if (errstr != NULL) {
805 fprintf(stderr, "%s: %s\n", dn, errstr);
806 free(errstr);
807 return -1;
810 if (miss != 0) {
811 fprintf(stderr, "%s: not a directory\n", dn);
812 return -1;
815 if ((n = strrchr(path, '/')) != NULL)
816 n++;
817 else
818 n = path;
821 free(errstr);
823 if (miss > 1) {
824 fprintf(stderr, "can't create %s: missing %d path"
825 " component(s)\n", path, miss);
826 return -1;
829 send_fid(nfid, n, KOTRUNC, fd, prompt);
830 return 0;
833 static void
834 do_tls_connect(const char *host, const char *port)
836 int handshake;
838 if ((tlsconf = tls_config_new()) == NULL)
839 fatalx("tls_config_new");
840 tls_config_insecure_noverifycert(tlsconf);
841 tls_config_insecure_noverifyname(tlsconf);
843 if (keypath == NULL)
844 keypath = crtpath;
846 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
847 fatalx("can't load certs (%s, %s)", crtpath, keypath);
849 if ((ctx = tls_client()) == NULL)
850 fatal("tls_client");
851 if (tls_configure(ctx, tlsconf) == -1)
852 fatalx("tls_configure: %s", tls_error(ctx));
854 if (tls_connect(ctx, host, port) == -1)
855 fatalx("can't connect to %s:%s: %s", host, port,
856 tls_error(ctx));
858 for (handshake = 0; !handshake;) {
859 switch (tls_handshake(ctx)) {
860 case -1:
861 fatalx("tls_handshake: %s", tls_error(ctx));
862 case 0:
863 handshake = 1;
864 break;
869 static void
870 do_ctxt_connect(const char *host, const char *port)
872 struct addrinfo hints, *res, *res0;
873 int error, saved_errno;
874 const char *cause = NULL;
876 memset(&hints, 0, sizeof(hints));
877 hints.ai_family = AF_UNSPEC;
878 hints.ai_socktype = SOCK_STREAM;
879 error = getaddrinfo(host, port, &hints, &res0);
880 if (error)
881 errx(1, "%s", gai_strerror(error));
883 sock = -1;
884 for (res = res0; res != NULL; res = res->ai_next) {
885 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
886 res->ai_protocol);
887 if (sock == -1) {
888 cause = "socket";
889 continue;
892 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
893 cause = "connect";
894 saved_errno = errno;
895 close(sock);
896 errno = saved_errno;
897 sock = -1;
898 continue;
901 break;
904 if (sock == -1)
905 err(1, "%s", cause);
906 freeaddrinfo(res0);
909 static void
910 do_connect(const char *host, const char *port, const char *user)
912 struct qid qid;
913 int nfid, miss, fd;
914 char *errstr;
916 fprintf(stderr, "connecting to %s:%s...", host, port);
918 if (tls)
919 do_tls_connect(host, port);
920 else
921 do_ctxt_connect(host, port);
923 fprintf(stderr, " done!\n");
925 do_version();
926 do_attach(user);
929 static int
930 tmp_file(char sfn[TMPFSTRLEN])
932 int tmpfd;
934 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
935 if ((tmpfd = mkstemp(sfn)) == -1) {
936 warn("mkstemp %s", sfn);
937 return -1;
940 /* set the close-on-exec flag */
941 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
942 warn("fcntl");
943 close(tmpfd);
944 return -1;
947 return tmpfd;
950 static inline const char *
951 pp_perm(uint8_t x)
953 switch (x & 0x7) {
954 case 0x0:
955 return "---";
956 case 0x1:
957 return "--x";
958 case 0x2:
959 return "-w-";
960 case 0x3:
961 return "-wx";
962 case 0x4:
963 return "r--";
964 case 0x5:
965 return "r-x";
966 case 0x6:
967 return "rw-";
968 case 0x7:
969 return "rwx";
970 default:
971 /* unreachable, just for the compiler' happiness */
972 return "???";
976 static inline void
977 prepare_wstat(struct np_stat *st)
979 memset(st, 0xFF, sizeof(*st));
980 st->name = NULL;
981 st->uid = NULL;
982 st->gid = NULL;
983 st->muid = NULL;
986 static int
987 print_dirent(const struct np_stat *st)
989 time_t mtime;
990 struct tm *tm;
991 const char *timfmt;
992 char fmt[FMT_SCALED_STRSIZE], tim[13];
994 if (fmt_scaled(st->length, fmt) == -1)
995 strlcpy(fmt, "xxx", sizeof(fmt));
997 mtime = st->mtime;
999 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
1000 timfmt = "%b %e %R";
1001 else
1002 timfmt = "%b %e %Y";
1004 if ((tm = localtime(&mtime)) == NULL ||
1005 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1006 strlcpy(tim, "unknown", sizeof(tim));
1008 if (st->qid.type & QTDIR)
1009 printf("d");
1010 else
1011 printf("-");
1012 printf("%s", pp_perm(st->mode >> 6));
1013 printf("%s", pp_perm(st->mode >> 3));
1014 printf("%s", pp_perm(st->mode));
1015 printf(" %8s %12s %s%s\n", fmt, tim, st->name,
1016 st->qid.type & QTDIR ? "/" : "");
1018 return 0;
1021 int
1022 dir_listing(const char *path, int (*fn)(const struct np_stat *),
1023 int printerr)
1025 struct qid qid = {0, 0, QTDIR};
1026 struct np_stat st;
1027 uint64_t off = 0;
1028 uint32_t len;
1029 int nfid, r, miss = 0;
1030 char *errstr;
1032 now = time(NULL);
1033 nfid = nextfid();
1035 if (!strcmp(path, "."))
1036 errstr = dup_fid(pwdfid, nfid);
1037 else
1038 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
1039 if (errstr != NULL) {
1040 if (printerr)
1041 printf("%s: %s\n", path, errstr);
1042 free(errstr);
1043 return -1;
1045 if (miss) {
1046 if (printerr)
1047 printf("%s: No such file or directory\n", path);
1048 return -1;
1050 if (!(qid.type & QTDIR)) {
1051 if (printerr)
1052 printf("%s: not a directory\n", path);
1053 do_clunk(nfid);
1054 return -1;
1057 do_open(nfid, KOREAD);
1058 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1060 for (;;) {
1061 tread(nfid, off, msize - IOHDRSZ);
1062 do_send();
1063 recv_msg();
1064 expect2(Rread, iota_tag);
1066 len = np_read32(buf);
1067 if (len == 0)
1068 break;
1070 evbuffer_add_buffer(dirbuf, buf);
1071 off += len;
1073 ASSERT_EMPTYBUF();
1076 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1077 if (np_read_stat(dirbuf, &st) == -1)
1078 errx(1, "invalid stat struct read");
1080 r = fn(&st);
1082 free(st.name);
1083 free(st.uid);
1084 free(st.gid);
1085 free(st.muid);
1087 if (r == -1)
1088 break;
1091 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1092 do_clunk(nfid);
1093 return 0;
1096 void
1097 cmd_bell(int argc, const char **argv)
1099 if (argc == 0) {
1100 bell = !bell;
1101 if (bell)
1102 puts("bell mode enabled");
1103 else
1104 puts("bell mode disabled");
1105 return;
1108 if (argc != 1)
1109 goto usage;
1111 if (!strcmp(*argv, "on")) {
1112 bell = 1;
1113 puts("bell mode enabled");
1114 return;
1117 if (!strcmp(*argv, "off")) {
1118 bell = 0;
1119 puts("bell mode disabled");
1120 return;
1123 usage:
1124 printf("bell [on | off]\n");
1127 void
1128 cmd_bye(int argc, const char **argv)
1130 log_warnx("bye\n");
1131 exit(0);
1134 void
1135 cmd_cd(int argc, const char **argv)
1137 struct qid qid;
1138 int nfid, miss;
1139 char *errstr;
1141 if (argc != 1) {
1142 printf("usage: cd remote-path\n");
1143 return;
1146 nfid = nextfid();
1147 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1148 if (errstr != NULL) {
1149 printf("%s: %s\n", argv[0], errstr);
1150 free(errstr);
1151 return;
1154 if (miss != 0 || !(qid.type & QTDIR)) {
1155 printf("%s: not a directory\n", argv[0]);
1156 if (miss == 0)
1157 do_clunk(nfid);
1158 return;
1161 do_clunk(pwdfid);
1162 pwdfid = nfid;
1165 void
1166 cmd_edit(int argc, const char **argv)
1168 struct qid qid;
1169 int nfid, tmpfd, miss;
1170 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1171 const char *ed;
1173 if (argc != 1) {
1174 puts("usage: edit file");
1175 return;
1178 if ((ed = getenv("VISUAL")) == NULL &&
1179 (ed = getenv("EDITOR")) == NULL)
1180 ed = "ed";
1182 nfid = nextfid();
1183 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1184 if (errstr != NULL) {
1185 printf("%s: %s\n", *argv, errstr);
1186 free(errstr);
1187 return;
1190 if (miss != 0 || qid.type != 0) {
1191 printf("%s: not a file\n", *argv);
1192 if (miss == 0)
1193 do_clunk(nfid);
1194 return;
1197 if ((tmpfd = tmp_file(sfn)) == -1) {
1198 do_clunk(nfid);
1199 return;
1202 strlcpy(p, *argv, sizeof(p));
1203 name = basename(p);
1205 if (fetch_fid(nfid, tmpfd, name)) {
1206 warn("failed fetch or can't write %s", sfn);
1207 goto end;
1209 close(tmpfd);
1211 spawn(ed, sfn, NULL);
1214 * Re-open the file because it's not guaranteed that the
1215 * file descriptor tmpfd is still associated with the file
1216 * pointed by sfn: it's not uncommon for editor to write
1217 * a backup file and then rename(2) it to the file name.
1219 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1220 warn("can't open %s", sfn);
1221 goto end;
1224 woc_file(tmpfd, *argv, name);
1225 close(tmpfd);
1227 end:
1228 unlink(sfn);
1231 void
1232 cmd_get(int argc, const char **argv)
1234 struct qid qid;
1235 const char *l;
1236 char *errstr;
1237 int nfid, fd, miss;
1239 if (argc != 1 && argc != 2) {
1240 printf("usage: get remote-file [local-file]\n");
1241 return;
1244 if (argc == 2)
1245 l = argv[1];
1246 else if ((l = strrchr(argv[0], '/')) != NULL)
1247 l++; /* skip / */
1248 else
1249 l = argv[0];
1251 nfid = nextfid();
1252 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1253 if (errstr != NULL) {
1254 printf("%s: %s\n", argv[0], errstr);
1255 free(errstr);
1256 return;
1259 if (miss != 0 || qid.type != 0) {
1260 printf("%s: not a file\n", argv[0]);
1261 if (miss == 0)
1262 do_clunk(nfid);
1263 return;
1266 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1267 warn("can't open %s", l);
1268 do_clunk(nfid);
1269 return;
1272 if (fetch_fid(nfid, fd, l) == -1)
1273 warn("write %s", l);
1274 close(fd);
1277 void
1278 cmd_hexdump(int argc, const char **argv)
1280 if (argc == 0) {
1281 xdump = !xdump;
1282 if (xdump)
1283 puts("hexdump mode enabled");
1284 else
1285 puts("hexdump mode disabled");
1286 return;
1289 if (argc > 1)
1290 goto usage;
1292 if (!strcmp(*argv, "on")) {
1293 xdump = 1;
1294 puts("hexdump mode enabled");
1295 return;
1298 if (!strcmp(*argv, "off")) {
1299 xdump = 0;
1300 puts("hexdump mode disabled");
1301 return;
1304 usage:
1305 puts("usage: hexdump [on | off]");
1308 void
1309 cmd_lcd(int argc, const char **argv)
1311 const char *dir;
1313 if (argc > 1) {
1314 printf("usage: lcd [local-directory]\n");
1315 return;
1318 if (argc == 1)
1319 dir = *argv;
1321 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1322 printf("HOME is not defined\n");
1323 return;
1326 if (chdir(dir) == -1)
1327 printf("cd: %s: %s\n", dir, strerror(errno));
1330 void
1331 cmd_lpwd(int argc, const char **argv)
1333 char path[PATH_MAX];
1335 if (argc != 0) {
1336 printf("usage: lpwd\n");
1337 return;
1340 if (getcwd(path, sizeof(path)) == NULL) {
1341 printf("lpwd: %s\n", strerror(errno));
1342 return;
1345 printf("%s\n", path);
1348 void
1349 cmd_ls(int argc, const char **argv)
1351 if (argc > 1) {
1352 puts("usage: ls [path]");
1353 return;
1356 dir_listing(argc == 0 ? "." : argv[0], print_dirent, 1);
1359 void
1360 cmd_page(int argc, const char **argv)
1362 struct qid qid;
1363 int nfid, tmpfd, miss, r;
1364 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1365 const char *pager;
1367 if (argc != 1) {
1368 puts("usage: page file");
1369 return;
1372 if ((pager = getenv("PAGER")) == NULL)
1373 pager = "less";
1375 nfid = nextfid();
1376 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1377 if (errstr != NULL) {
1378 printf("%s: %s\n", *argv, errstr);
1379 free(errstr);
1380 return;
1383 if (miss != 0 || qid.type != 0) {
1384 printf("%s: not a file\n", *argv);
1385 if (miss == 0)
1386 do_clunk(nfid);
1387 return;
1390 if ((tmpfd = tmp_file(sfn)) == -1) {
1391 do_clunk(nfid);
1392 return;
1395 strlcpy(p, *argv, sizeof(p));
1396 name = basename(p);
1397 if ((r = fetch_fid(nfid, tmpfd, name)) == -1)
1398 warn("write %s", sfn);
1399 close(tmpfd);
1400 if (r != -1)
1401 spawn(pager, sfn, NULL);
1402 unlink(sfn);
1405 void
1406 cmd_pipe(int argc, const char **argv)
1408 struct qid qid;
1409 pid_t pid;
1410 int nfid, tmpfd, miss, status;
1411 int filedes[2]; /* read end, write end */
1412 char *errstr;
1414 if (argc < 2) {
1415 puts("usage: pipe remote-file cmd [args...]");
1416 return;
1419 nfid = nextfid();
1420 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1421 if (errstr != NULL) {
1422 printf("%s: %s\n", *argv, errstr);
1423 free(errstr);
1424 return;
1427 if (miss != 0 || qid.type != 0) {
1428 printf("%s: not a file\n", *argv);
1429 if (miss == 0)
1430 do_clunk(nfid);
1431 return;
1434 if (pipe(filedes) == -1)
1435 err(1, "pipe");
1437 switch (pid = vfork()) {
1438 case -1:
1439 err(1, "vfork");
1440 case 0:
1441 close(filedes[1]);
1442 if (dup2(filedes[0], 0) == -1)
1443 err(1, "dup2");
1444 execvp(argv[1], (char *const *)argv + 1);
1445 err(1, "execvp");
1448 close(filedes[0]);
1449 if (fetch_fid(nfid, filedes[1], *argv) == -1)
1450 warnx("failed to fetch all the file");
1451 close(filedes[1]);
1453 waitpid(pid, &status, 0);
1456 void
1457 cmd_put(int argc, const char **argv)
1459 struct qid qid;
1460 const char *l;
1461 int fd;
1463 if (argc != 1 && argc != 2) {
1464 printf("usage: put local-file [remote-file]\n");
1465 return;
1468 if (argc == 2)
1469 l = argv[1];
1470 else if ((l = strrchr(argv[0], '/')) != NULL)
1471 l++; /* skip / */
1472 else
1473 l = argv[0];
1475 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1476 warn("%s", argv[0]);
1477 return;
1480 woc_file(fd, argv[0], l);
1481 close(fd);
1484 void
1485 cmd_rename(int argc, const char **argv)
1487 struct np_stat st;
1488 struct qid qid;
1489 char *errstr;
1490 int nfid, miss;
1492 if (argc != 2) {
1493 puts("usage: rename remote-file new-remote-name");
1494 return;
1497 nfid = nextfid();
1498 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1499 if (errstr != NULL) {
1500 printf("%s: %s\n", argv[0], errstr);
1501 free(errstr);
1502 return;
1505 if (miss != 0) {
1506 printf("%s: not such file or directory\n", argv[0]);
1507 return;
1510 prepare_wstat(&st);
1511 st.name = (char *)argv[1];
1512 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1513 printf("rename: %s\n", errstr);
1514 free(errstr);
1517 do_clunk(nfid);
1520 void
1521 cmd_rm(int argc, const char **argv)
1523 struct qid qid;
1524 char *errstr;
1525 int nfid, miss;
1527 if (argc == 0) {
1528 puts("usage: rm file ...");
1529 return;
1532 for (; *argv; ++argv, --argc) {
1533 nfid = nextfid();
1534 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1535 if (errstr != NULL) {
1536 printf("%s: %s\n", *argv, errstr);
1537 free(errstr);
1538 continue;
1540 if (miss) {
1541 printf("%s: not such file or directory\n", *argv);
1542 continue;
1545 if ((errstr = do_remove(nfid)) != NULL) {
1546 printf("%s: %s\n", *argv, errstr);
1547 free(errstr);
1548 continue;
1553 void
1554 cmd_verbose(int argc, const char **argv)
1556 if (argc == 0) {
1557 log_setverbose(!log_getverbose());
1558 if (log_getverbose())
1559 puts("verbose mode enabled");
1560 else
1561 puts("verbose mode disabled");
1562 return;
1565 if (argc != 1)
1566 goto usage;
1568 if (!strcmp(*argv, "on")) {
1569 log_setverbose(1);
1570 puts("verbose mode enabled");
1571 return;
1574 if (!strcmp(*argv, "off")) {
1575 log_setverbose(0);
1576 puts("verbose mode disabled");
1577 return;
1580 usage:
1581 printf("verbose [on | off]\n");
1584 static void
1585 excmd(int argc, const char **argv)
1587 size_t i;
1589 if (argc == 0)
1590 return;
1592 for (i = 0; i < nitems(cmds); ++i) {
1593 if (!strcmp(cmds[i].name, *argv)) {
1594 cmds[i].fn(argc-1, argv+1);
1595 return;
1599 log_warnx("unknown command %s", *argv);
1602 static int
1603 parsecmd(char *cmd, char **argv, int len)
1605 int escape, quote;
1606 int argc = 0;
1608 memset(argv, 0, sizeof(*argv) * len);
1610 while (argc < len) {
1611 while (isspace((unsigned char)*cmd))
1612 cmd++;
1613 if (*cmd == '\0')
1614 break;
1616 argv[argc++] = cmd;
1617 escape = quote = 0;
1618 for (; *cmd != '\0'; ++cmd) {
1619 if (escape) {
1620 escape = 0;
1621 continue;
1623 if (*cmd == '\\') {
1624 escape = 1;
1625 memmove(cmd, cmd + 1, strlen(cmd));
1626 cmd--;
1627 continue;
1629 if (*cmd == quote) {
1630 quote = 0;
1631 memmove(cmd, cmd + 1, strlen(cmd));
1632 cmd--;
1633 continue;
1635 if (*cmd == '\'' || *cmd == '"') {
1636 quote = *cmd;
1637 memmove(cmd, cmd + 1, strlen(cmd));
1638 cmd--;
1639 continue;
1641 if (quote)
1642 continue;
1644 if (isspace((unsigned char)*cmd))
1645 break;
1648 if (*cmd == '\0' && (escape || quote)) {
1649 fprintf(stderr, "unterminated %s\n",
1650 escape ? "escape" : "quote");
1651 return -1;
1654 if (*cmd == '\0')
1655 break;
1656 *cmd++ = '\0';
1659 if (*cmd != '\0') {
1660 fprintf(stderr, "too many arguments\n");
1661 return -1;
1663 return argc;
1666 static void
1667 cd_or_fetch(const char *path, const char *outfile)
1669 struct qid qid;
1670 char *errstr;
1671 int fd, nfid, miss;
1673 while (*path == '/')
1674 path++;
1675 if (*path == '\0')
1676 return;
1678 nfid = nextfid();
1679 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
1680 if (errstr)
1681 errx(1, "walk %s: %s", path, errstr);
1682 if (miss)
1683 errc(1, ENOENT, "walk %s", path);
1685 if (qid.type & QTDIR) {
1686 if (outfile)
1687 errx(1, "can't fetch directory %s", path);
1688 do_clunk(pwdfid);
1689 pwdfid = nfid;
1690 return;
1693 if (outfile == NULL) {
1694 if ((outfile = strrchr(path, '/')) == NULL)
1695 outfile = path;
1696 else
1697 outfile++;
1698 if (*outfile == '\0')
1699 errx(1, "invalid path: missing file name: %s",
1700 path);
1703 if (strcmp(outfile, "-") != 0) {
1704 fd = open(outfile, O_WRONLY|O_CREAT, 0644);
1705 if (fd == -1)
1706 err(1, "can't open for writing %s", outfile);
1707 } else
1708 fd = 1;
1710 if (fetch_fid(nfid, fd, outfile) == -1)
1711 err(1, "write %s", outfile);
1712 close(fd);
1713 exit(0);
1716 static const char *
1717 parse_addr(const char *url, const char **user,
1718 const char **port, const char **path)
1720 static char buf[PATH_MAX];
1721 char *host, *t;
1723 *user = *port = *path = NULL;
1724 host = buf;
1726 if (strlcpy(buf, url, sizeof(buf)) >= sizeof(buf))
1727 errx(1, "connection string too long");
1729 if (!strncmp(host, "9p://", 5))
1730 host += 5;
1732 if ((t = strchr(host, '/')) != NULL) {
1733 if (t == host)
1734 errx(1, "invalid connection string: %s", url);
1735 *t++ = '\0';
1736 if (*t != '\0')
1737 *path = t;
1740 if ((t = strchr(host, '@')) != NULL) {
1741 if (t == host)
1742 errx(1, "invalid connection string: %s", url);
1743 *t++ = '\0';
1744 *user = host;
1745 host = t;
1746 } else if ((*user = getenv("USER")) == NULL)
1747 errx(1, "USER not defined");
1749 if ((t = strchr(host, ':')) != NULL) {
1750 *t++ = '\0';
1751 if (*t != '\0')
1752 *port = t;
1754 if (*port == NULL)
1755 *port = "1337";
1757 return host;
1760 int
1761 main(int argc, char **argv)
1763 const char *user, *host, *port, *path;
1764 const char *outfile = NULL;
1765 int ch;
1767 log_init(1, LOG_DAEMON);
1768 log_setverbose(0);
1769 log_procinit(getprogname());
1771 while ((ch = getopt(argc, argv, "C:cK:o:")) != -1) {
1772 switch (ch) {
1773 case 'C':
1774 tls = 1;
1775 crtpath = optarg;
1776 break;
1777 case 'c': /* deprecated, remove after 0.3 */
1778 tls = 1;
1779 break;
1780 case 'K':
1781 tls = 1;
1782 keypath = optarg;
1783 break;
1784 case 'o':
1785 outfile = optarg;
1786 break;
1787 default:
1788 usage(1);
1791 argc -= optind;
1792 argv += optind;
1794 if (argc == 0 || (tls && crtpath == NULL))
1795 usage(1);
1797 host = parse_addr(argv[0], &user, &port, &path);
1798 if (path == NULL && argv[1] != NULL) /* drop argv[1] after 0.3 */
1799 path = argv[1];
1800 if (outfile && path == NULL)
1801 usage(1);
1803 signal(SIGPIPE, SIG_IGN);
1804 if (isatty(1)) {
1805 tty_p = 1;
1806 resized = 1;
1807 signal(SIGWINCH, tty_resized);
1810 if ((evb = evbuffer_new()) == NULL)
1811 fatal("evbuffer_new");
1813 if ((buf = evbuffer_new()) == NULL)
1814 fatal("evbuffer_new");
1816 if ((dirbuf = evbuffer_new()) == NULL)
1817 fatal("evbuferr_new");
1819 do_connect(host, port, user);
1820 if (path)
1821 cd_or_fetch(path, outfile);
1823 compl_setup();
1824 for (;;) {
1825 int argc;
1826 char *line, *argv[16] = {0}, **ap;
1828 if ((line = read_line("kamiftp> ")) == NULL)
1829 break;
1831 if ((argc = parsecmd(line, argv, nitems(argv) - 1)) == -1) {
1832 free(line);
1833 continue;
1836 argv[argc] = NULL;
1837 excmd(argc, (const char **)argv);
1839 if (bell)
1840 fprintf(stderr, "\a");
1842 free(line);
1845 printf("\n");