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 uint32_t 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;
1025 struct np_stat st;
1026 uint64_t off = 0;
1027 uint32_t len;
1028 int nfid, miss, r;
1029 char *errstr;
1031 now = time(NULL);
1032 nfid = nextfid();
1034 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
1035 if (errstr != NULL) {
1036 if (printerr)
1037 printf("%s: %s\n", path, errstr);
1038 free(errstr);
1039 return -1;
1041 if (miss) {
1042 if (printerr)
1043 printf("%s: No such file or directory\n", path);
1044 return -1;
1046 if (!(qid.type & QTDIR)) {
1047 if (printerr)
1048 printf("%s: not a directory\n", path);
1049 do_clunk(nfid);
1050 return -1;
1053 do_open(nfid, KOREAD);
1054 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1056 for (;;) {
1057 tread(nfid, off, msize - IOHDRSZ);
1058 do_send();
1059 recv_msg();
1060 expect2(Rread, iota_tag);
1062 len = np_read32(buf);
1063 if (len == 0)
1064 break;
1066 evbuffer_add_buffer(dirbuf, buf);
1067 off += len;
1069 ASSERT_EMPTYBUF();
1072 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1073 if (np_read_stat(dirbuf, &st) == -1)
1074 errx(1, "invalid stat struct read");
1076 r = fn(&st);
1078 free(st.name);
1079 free(st.uid);
1080 free(st.gid);
1081 free(st.muid);
1083 if (r == -1)
1084 break;
1087 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1088 do_clunk(nfid);
1089 return 0;
1092 void
1093 cmd_bell(int argc, const char **argv)
1095 if (argc == 0) {
1096 bell = !bell;
1097 if (bell)
1098 puts("bell mode enabled");
1099 else
1100 puts("bell mode disabled");
1101 return;
1104 if (argc != 1)
1105 goto usage;
1107 if (!strcmp(*argv, "on")) {
1108 bell = 1;
1109 puts("bell mode enabled");
1110 return;
1113 if (!strcmp(*argv, "off")) {
1114 bell = 0;
1115 puts("bell mode disabled");
1116 return;
1119 usage:
1120 printf("bell [on | off]\n");
1123 void
1124 cmd_bye(int argc, const char **argv)
1126 log_warnx("bye\n");
1127 exit(0);
1130 void
1131 cmd_cd(int argc, const char **argv)
1133 struct qid qid;
1134 int nfid, miss;
1135 char *errstr;
1137 if (argc != 1) {
1138 printf("usage: cd remote-path\n");
1139 return;
1142 nfid = nextfid();
1143 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1144 if (errstr != NULL) {
1145 printf("%s: %s\n", argv[0], errstr);
1146 free(errstr);
1147 return;
1150 if (miss != 0 || !(qid.type & QTDIR)) {
1151 printf("%s: not a directory\n", argv[0]);
1152 if (miss == 0)
1153 do_clunk(nfid);
1154 return;
1157 do_clunk(pwdfid);
1158 pwdfid = nfid;
1161 void
1162 cmd_edit(int argc, const char **argv)
1164 struct qid qid;
1165 int nfid, tmpfd, miss;
1166 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1167 const char *ed;
1169 if (argc != 1) {
1170 puts("usage: edit file");
1171 return;
1174 if ((ed = getenv("VISUAL")) == NULL &&
1175 (ed = getenv("EDITOR")) == NULL)
1176 ed = "ed";
1178 nfid = nextfid();
1179 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1180 if (errstr != NULL) {
1181 printf("%s: %s\n", *argv, errstr);
1182 free(errstr);
1183 return;
1186 if (miss != 0 || qid.type != 0) {
1187 printf("%s: not a file\n", *argv);
1188 if (miss == 0)
1189 do_clunk(nfid);
1190 return;
1193 if ((tmpfd = tmp_file(sfn)) == -1) {
1194 do_clunk(nfid);
1195 return;
1198 strlcpy(p, *argv, sizeof(p));
1199 name = basename(p);
1201 if (fetch_fid(nfid, tmpfd, name)) {
1202 warn("failed fetch or can't write %s", sfn);
1203 goto end;
1205 close(tmpfd);
1207 spawn(ed, sfn, NULL);
1210 * Re-open the file because it's not guaranteed that the
1211 * file descriptor tmpfd is still associated with the file
1212 * pointed by sfn: it's not uncommon for editor to write
1213 * a backup file and then rename(2) it to the file name.
1215 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1216 warn("can't open %s", sfn);
1217 goto end;
1220 woc_file(tmpfd, *argv, name);
1221 close(tmpfd);
1223 end:
1224 unlink(sfn);
1227 void
1228 cmd_get(int argc, const char **argv)
1230 struct qid qid;
1231 const char *l;
1232 char *errstr;
1233 int nfid, fd, miss;
1235 if (argc != 1 && argc != 2) {
1236 printf("usage: get remote-file [local-file]\n");
1237 return;
1240 if (argc == 2)
1241 l = argv[1];
1242 else if ((l = strrchr(argv[0], '/')) != NULL)
1243 l++; /* skip / */
1244 else
1245 l = argv[0];
1247 nfid = nextfid();
1248 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1249 if (errstr != NULL) {
1250 printf("%s: %s\n", argv[0], errstr);
1251 free(errstr);
1252 return;
1255 if (miss != 0 || qid.type != 0) {
1256 printf("%s: not a file\n", argv[0]);
1257 if (miss == 0)
1258 do_clunk(nfid);
1259 return;
1262 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1263 warn("can't open %s", l);
1264 do_clunk(nfid);
1265 return;
1268 if (fetch_fid(nfid, fd, l) == -1)
1269 warn("write %s", l);
1270 close(fd);
1273 void
1274 cmd_hexdump(int argc, const char **argv)
1276 if (argc == 0) {
1277 xdump = !xdump;
1278 if (xdump)
1279 puts("hexdump mode enabled");
1280 else
1281 puts("hexdump mode disabled");
1282 return;
1285 if (argc > 1)
1286 goto usage;
1288 if (!strcmp(*argv, "on")) {
1289 xdump = 1;
1290 puts("hexdump mode enabled");
1291 return;
1294 if (!strcmp(*argv, "off")) {
1295 xdump = 0;
1296 puts("hexdump mode disabled");
1297 return;
1300 usage:
1301 puts("usage: hexdump [on | off]");
1304 void
1305 cmd_lcd(int argc, const char **argv)
1307 const char *dir;
1309 if (argc > 1) {
1310 printf("usage: lcd [local-directory]\n");
1311 return;
1314 if (argc == 1)
1315 dir = *argv;
1317 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1318 printf("HOME is not defined\n");
1319 return;
1322 if (chdir(dir) == -1)
1323 printf("cd: %s: %s\n", dir, strerror(errno));
1326 void
1327 cmd_lpwd(int argc, const char **argv)
1329 char path[PATH_MAX];
1331 if (argc != 0) {
1332 printf("usage: lpwd\n");
1333 return;
1336 if (getcwd(path, sizeof(path)) == NULL) {
1337 printf("lpwd: %s\n", strerror(errno));
1338 return;
1341 printf("%s\n", path);
1344 void
1345 cmd_ls(int argc, const char **argv)
1347 if (argc > 1) {
1348 puts("usage: ls [path]");
1349 return;
1352 dir_listing(argc == 0 ? "." : argv[0], print_dirent, 1);
1355 void
1356 cmd_page(int argc, const char **argv)
1358 struct qid qid;
1359 int nfid, tmpfd, miss, r;
1360 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1361 const char *pager;
1363 if (argc != 1) {
1364 puts("usage: page file");
1365 return;
1368 if ((pager = getenv("PAGER")) == NULL)
1369 pager = "less";
1371 nfid = nextfid();
1372 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1373 if (errstr != NULL) {
1374 printf("%s: %s\n", *argv, errstr);
1375 free(errstr);
1376 return;
1379 if (miss != 0 || qid.type != 0) {
1380 printf("%s: not a file\n", *argv);
1381 if (miss == 0)
1382 do_clunk(nfid);
1383 return;
1386 if ((tmpfd = tmp_file(sfn)) == -1) {
1387 do_clunk(nfid);
1388 return;
1391 strlcpy(p, *argv, sizeof(p));
1392 name = basename(p);
1393 if ((r = fetch_fid(nfid, tmpfd, name)) == -1)
1394 warn("write %s", sfn);
1395 close(tmpfd);
1396 if (r != -1)
1397 spawn(pager, sfn, NULL);
1398 unlink(sfn);
1401 void
1402 cmd_pipe(int argc, const char **argv)
1404 struct qid qid;
1405 pid_t pid;
1406 int nfid, tmpfd, miss, status;
1407 int filedes[2]; /* read end, write end */
1408 char *errstr;
1410 if (argc < 2) {
1411 puts("usage: pipe remote-file cmd [args...]");
1412 return;
1415 nfid = nextfid();
1416 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1417 if (errstr != NULL) {
1418 printf("%s: %s\n", *argv, errstr);
1419 free(errstr);
1420 return;
1423 if (miss != 0 || qid.type != 0) {
1424 printf("%s: not a file\n", *argv);
1425 if (miss == 0)
1426 do_clunk(nfid);
1427 return;
1430 if (pipe(filedes) == -1)
1431 err(1, "pipe");
1433 switch (pid = vfork()) {
1434 case -1:
1435 err(1, "vfork");
1436 case 0:
1437 close(filedes[1]);
1438 if (dup2(filedes[0], 0) == -1)
1439 err(1, "dup2");
1440 execvp(argv[1], (char *const *)argv + 1);
1441 err(1, "execvp");
1444 close(filedes[0]);
1445 if (fetch_fid(nfid, filedes[1], *argv) == -1)
1446 warnx("failed to fetch all the file");
1447 close(filedes[1]);
1449 waitpid(pid, &status, 0);
1452 void
1453 cmd_put(int argc, const char **argv)
1455 struct qid qid;
1456 const char *l;
1457 int fd;
1459 if (argc != 1 && argc != 2) {
1460 printf("usage: put local-file [remote-file]\n");
1461 return;
1464 if (argc == 2)
1465 l = argv[1];
1466 else if ((l = strrchr(argv[0], '/')) != NULL)
1467 l++; /* skip / */
1468 else
1469 l = argv[0];
1471 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1472 warn("%s", argv[0]);
1473 return;
1476 woc_file(fd, argv[0], l);
1477 close(fd);
1480 void
1481 cmd_rename(int argc, const char **argv)
1483 struct np_stat st;
1484 struct qid qid;
1485 char *errstr;
1486 int nfid, miss;
1488 if (argc != 2) {
1489 puts("usage: rename remote-file new-remote-name");
1490 return;
1493 nfid = nextfid();
1494 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1495 if (errstr != NULL) {
1496 printf("%s: %s\n", argv[0], errstr);
1497 free(errstr);
1498 return;
1501 if (miss != 0) {
1502 printf("%s: not such file or directory\n", argv[0]);
1503 return;
1506 prepare_wstat(&st);
1507 st.name = (char *)argv[1];
1508 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1509 printf("rename: %s\n", errstr);
1510 free(errstr);
1513 do_clunk(nfid);
1516 void
1517 cmd_rm(int argc, const char **argv)
1519 struct qid qid;
1520 char *errstr;
1521 int nfid, miss;
1523 if (argc == 0) {
1524 puts("usage: rm file ...");
1525 return;
1528 for (; *argv; ++argv, --argc) {
1529 nfid = nextfid();
1530 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1531 if (errstr != NULL) {
1532 printf("%s: %s\n", *argv, errstr);
1533 free(errstr);
1534 continue;
1536 if (miss) {
1537 printf("%s: not such file or directory\n", *argv);
1538 continue;
1541 if ((errstr = do_remove(nfid)) != NULL) {
1542 printf("%s: %s\n", *argv, errstr);
1543 free(errstr);
1544 continue;
1549 void
1550 cmd_verbose(int argc, const char **argv)
1552 if (argc == 0) {
1553 log_setverbose(!log_getverbose());
1554 if (log_getverbose())
1555 puts("verbose mode enabled");
1556 else
1557 puts("verbose mode disabled");
1558 return;
1561 if (argc != 1)
1562 goto usage;
1564 if (!strcmp(*argv, "on")) {
1565 log_setverbose(1);
1566 puts("verbose mode enabled");
1567 return;
1570 if (!strcmp(*argv, "off")) {
1571 log_setverbose(0);
1572 puts("verbose mode disabled");
1573 return;
1576 usage:
1577 printf("verbose [on | off]\n");
1580 static void
1581 excmd(int argc, const char **argv)
1583 size_t i;
1585 if (argc == 0)
1586 return;
1588 for (i = 0; i < nitems(cmds); ++i) {
1589 if (!strcmp(cmds[i].name, *argv)) {
1590 cmds[i].fn(argc-1, argv+1);
1591 return;
1595 log_warnx("unknown command %s", *argv);
1598 static int
1599 parsecmd(char *cmd, char **argv, size_t len)
1601 int escape, quote;
1602 int argc = 0;
1604 memset(argv, 0, sizeof(*argv) * len);
1606 while (argc < len) {
1607 while (isspace((unsigned char)*cmd))
1608 cmd++;
1609 if (*cmd == '\0')
1610 break;
1612 argv[argc++] = cmd;
1613 escape = quote = 0;
1614 for (; *cmd != '\0'; ++cmd) {
1615 if (escape) {
1616 escape = 0;
1617 continue;
1619 if (*cmd == '\\') {
1620 escape = 1;
1621 memmove(cmd, cmd + 1, strlen(cmd));
1622 cmd--;
1623 continue;
1625 if (*cmd == quote) {
1626 quote = 0;
1627 memmove(cmd, cmd + 1, strlen(cmd));
1628 cmd--;
1629 continue;
1631 if (*cmd == '\'' || *cmd == '"') {
1632 quote = *cmd;
1633 memmove(cmd, cmd + 1, strlen(cmd));
1634 cmd--;
1635 continue;
1637 if (quote)
1638 continue;
1640 if (isspace((unsigned char)*cmd))
1641 break;
1644 if (*cmd == '\0' && (escape || quote)) {
1645 fprintf(stderr, "unterminated %s\n",
1646 escape ? "escape" : "quote");
1647 return -1;
1650 if (*cmd == '\0')
1651 break;
1652 *cmd++ = '\0';
1655 if (*cmd != '\0') {
1656 fprintf(stderr, "too many arguments\n");
1657 return -1;
1659 return argc;
1662 static void
1663 cd_or_fetch(const char *path, const char *outfile)
1665 struct qid qid;
1666 char *errstr;
1667 int fd, nfid, miss;
1669 while (*path == '/')
1670 path++;
1671 if (*path == '\0')
1672 return;
1674 nfid = nextfid();
1675 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
1676 if (errstr)
1677 errx(1, "walk %s: %s", path, errstr);
1678 if (miss)
1679 errc(1, ENOENT, "walk %s", path);
1681 if (qid.type & QTDIR) {
1682 if (outfile)
1683 errx(1, "can't fetch directory %s", path);
1684 do_clunk(pwdfid);
1685 pwdfid = nfid;
1686 return;
1689 if (outfile == NULL) {
1690 if ((outfile = strrchr(path, '/')) == NULL)
1691 outfile = path;
1692 else
1693 outfile++;
1694 if (*outfile == '\0')
1695 errx(1, "invalid path: missing file name: %s",
1696 path);
1699 if (strcmp(outfile, "-") != 0) {
1700 fd = open(outfile, O_WRONLY|O_CREAT, 0644);
1701 if (fd == -1)
1702 err(1, "can't open for writing %s", outfile);
1703 } else
1704 fd = 1;
1706 if (fetch_fid(nfid, fd, outfile) == -1)
1707 err(1, "write %s", outfile);
1708 close(fd);
1709 exit(0);
1712 static const char *
1713 parse_addr(const char *url, const char **user,
1714 const char **port, const char **path)
1716 static char buf[PATH_MAX];
1717 char *host, *t;
1719 *user = *port = *path = NULL;
1720 host = buf;
1722 if (strlcpy(buf, url, sizeof(buf)) >= sizeof(buf))
1723 errx(1, "connection string too long");
1725 if (!strncmp(host, "9p://", 5))
1726 host += 5;
1728 if ((t = strchr(host, '/')) != NULL) {
1729 if (t == host)
1730 errx(1, "invalid connection string: %s", url);
1731 *t++ = '\0';
1732 if (*t != '\0')
1733 *path = t;
1736 if ((t = strchr(host, '@')) != NULL) {
1737 if (t == host)
1738 errx(1, "invalid connection string: %s", url);
1739 *t++ = '\0';
1740 *user = host;
1741 host = t;
1742 } else if ((*user = getenv("USER")) == NULL)
1743 errx(1, "USER not defined");
1745 if ((t = strchr(host, ':')) != NULL) {
1746 *t++ = '\0';
1747 if (*t != '\0')
1748 *port = t;
1750 if (*port == NULL)
1751 *port = "1337";
1753 return host;
1756 int
1757 main(int argc, char **argv)
1759 const char *user, *host, *port, *path;
1760 const char *outfile = NULL;
1761 int ch;
1763 log_init(1, LOG_DAEMON);
1764 log_setverbose(0);
1765 log_procinit(getprogname());
1767 while ((ch = getopt(argc, argv, "C:cK:o:")) != -1) {
1768 switch (ch) {
1769 case 'C':
1770 tls = 1;
1771 crtpath = optarg;
1772 break;
1773 case 'c': /* deprecated, remove after 0.3 */
1774 tls = 1;
1775 break;
1776 case 'K':
1777 tls = 1;
1778 keypath = optarg;
1779 break;
1780 case 'o':
1781 outfile = optarg;
1782 break;
1783 default:
1784 usage(1);
1787 argc -= optind;
1788 argv += optind;
1790 if (argc == 0 || (tls && crtpath == NULL))
1791 usage(1);
1793 host = parse_addr(argv[0], &user, &port, &path);
1794 if (path == NULL && argv[1] != NULL) /* drop argv[1] after 0.3 */
1795 path = argv[1];
1796 if (outfile && path == NULL)
1797 usage(1);
1799 signal(SIGPIPE, SIG_IGN);
1800 if (isatty(1)) {
1801 tty_p = 1;
1802 resized = 1;
1803 signal(SIGWINCH, tty_resized);
1806 if ((evb = evbuffer_new()) == NULL)
1807 fatal("evbuffer_new");
1809 if ((buf = evbuffer_new()) == NULL)
1810 fatal("evbuffer_new");
1812 if ((dirbuf = evbuffer_new()) == NULL)
1813 fatal("evbuferr_new");
1815 do_connect(host, port, user);
1816 if (path)
1817 cd_or_fetch(path, outfile);
1819 compl_setup();
1820 for (;;) {
1821 int argc;
1822 char *line, *argv[16] = {0}, **ap;
1824 if ((line = read_line("kamiftp> ")) == NULL)
1825 break;
1827 if ((argc = parsecmd(line, argv, nitems(argv) - 1)) == -1) {
1828 free(line);
1829 continue;
1832 argv[argc] = NULL;
1833 excmd(argc, (const char **)argv);
1835 if (bell)
1836 fprintf(stderr, "\a");
1838 free(line);
1841 printf("\n");