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 #ifndef nitems
46 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
47 #endif
49 #include "kami.h"
50 #include "utils.h"
51 #include "log.h"
52 #include "9pclib.h"
54 #define TMPFSTR "/tmp/kamiftp.XXXXXXXXXX"
55 #define TMPFSTRLEN sizeof(TMPFSTR)
57 /* flags */
58 int tls;
59 const char *crtpath;
60 const char *keypath;
62 /* state */
63 FILE *fp;
64 struct evbuffer *buf;
65 struct evbuffer *dirbuf;
66 uint32_t msize;
67 int bell;
69 volatile sig_atomic_t resized;
70 int tty_p;
71 int tty_width;
72 int xdump;
74 struct progress {
75 uint64_t max;
76 uint64_t done;
77 };
79 int pwdfid;
81 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
83 #if !HAVE_READLINE
84 char *
85 readline(const char *prompt)
86 {
87 char *ch, *line = NULL;
88 size_t linesize = 0;
89 ssize_t linelen;
91 printf("%s", prompt);
92 fflush(stdout);
94 linelen = getline(&line, &linesize, stdin);
95 if (linelen == -1)
96 return NULL;
98 if ((ch = strchr(line, '\n')) != NULL)
99 *ch = '\0';
100 return line;
103 void
104 add_history(const char *line)
106 return;
108 #endif
110 static char *
111 read_line(const char *prompt)
113 char *line;
115 again:
116 if ((line = readline(prompt)) == NULL)
117 return NULL;
118 /* XXX: trim spaces? */
119 if (*line == '\0') {
120 free(line);
121 goto again;
124 add_history(line);
125 return line;
128 static void
129 spawn(const char *argv0, ...)
131 pid_t pid;
132 size_t i;
133 int status;
134 const char *argv[16], *last;
135 va_list ap;
137 memset(argv, 0, sizeof(argv));
139 va_start(ap, argv0);
140 argv[0] = argv0;
141 for (i = 1; i < nitems(argv); ++i) {
142 last = va_arg(ap, const char *);
143 if (last == NULL)
144 break;
145 argv[i] = last;
147 va_end(ap);
149 assert(last == NULL);
151 switch (pid = fork()) {
152 case -1:
153 err(1, "fork");
154 case 0: /* child */
155 execvp(argv[0], (char *const *)argv);
156 err(1, "execvp");
157 default:
158 waitpid(pid, &status, 0);
162 static int
163 stdio_tls_write(void *arg, const char *buf, int len)
165 struct tls *ctx = arg;
166 ssize_t ret;
168 do {
169 ret = tls_write(ctx, buf, len);
170 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
172 if (ret == -1)
173 warn("tls_write: %s", tls_error(ctx));
175 return ret;
178 static int
179 stdio_tls_read(void *arg, char *buf, int len)
181 struct tls *ctx = arg;
182 ssize_t ret;
184 do {
185 ret = tls_read(ctx, buf, len);
186 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
188 if (ret == -1)
189 warn("tls_read: %s", tls_error(ctx));
191 return ret;
194 static int
195 stdio_tls_close(void *arg)
197 struct tls *ctx = arg;
198 int ret;
200 do {
201 ret = tls_close(ctx);
202 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
204 return ret;
207 static void
208 tty_resized(int signo)
210 resized = 1;
213 static void __dead
214 usage(int ret)
216 fprintf(stderr, "usage: %s [-C cert] [-K key] [-o output] "
217 "[user@]host[:port][/path]\n", getprogname());
218 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
219 exit(ret);
222 static int
223 nextfid(void)
225 uint32_t i;
227 for (i = 0; ; ++i) {
228 if (i != pwdfid)
229 return i;
233 static void
234 do_send(void)
236 size_t r;
238 if (xdump)
239 hexdump("outgoing message", EVBUFFER_DATA(evb),
240 EVBUFFER_LENGTH(evb));
242 while (EVBUFFER_LENGTH(evb) != 0) {
243 r = fwrite(EVBUFFER_DATA(evb), 1, EVBUFFER_LENGTH(evb), fp);
244 if (r == 0)
245 fatalx("unexpected EOF");
246 evbuffer_drain(evb, r);
250 static void
251 mustread(void *d, size_t len)
253 size_t r;
255 r = fread(d, 1, len, fp);
256 if (r != len)
257 errx(1, "unexpected EOF");
260 static void
261 recv_msg(void)
263 size_t r;
264 uint32_t len, l;
265 char tmp[BUFSIZ];
267 r = fread(&len, 1, sizeof(len), fp);
268 if (r != sizeof(len))
269 errx(1, "unexpected EOF");
271 len = le32toh(len);
272 if (len < HEADERSIZE)
273 errx(1, "read message of invalid length %d", len);
275 len -= 4; /* skip the length just read */
277 while (len != 0) {
278 l = MIN(len, sizeof(tmp));
280 r = fread(tmp, 1, l, fp);
281 if (r != l)
282 errx(1, "unexpected EOF");
283 len -= r;
284 evbuffer_add(buf, tmp, r);
287 if (xdump)
288 hexdump("incoming packet", EVBUFFER_DATA(buf),
289 EVBUFFER_LENGTH(buf));
292 static uint64_t
293 np_read64(struct evbuffer *buf)
295 uint64_t n;
297 evbuffer_remove(buf, &n, sizeof(n));
298 return le64toh(n);
301 static uint32_t
302 np_read32(struct evbuffer *buf)
304 uint32_t n;
306 evbuffer_remove(buf, &n, sizeof(n));
307 return le32toh(n);
310 static uint16_t
311 np_read16(struct evbuffer *buf)
313 uint16_t n;
315 evbuffer_remove(buf, &n, sizeof(n));
316 return le16toh(n);
319 static uint16_t
320 np_read8(struct evbuffer *buf)
322 uint8_t n;
324 evbuffer_remove(buf, &n, sizeof(n));
325 return n;
328 static char *
329 np_readstr(struct evbuffer *buf)
331 uint16_t len;
332 char *str;
334 len = np_read16(buf);
335 assert(EVBUFFER_LENGTH(buf) >= len);
337 if ((str = calloc(1, len+1)) == NULL)
338 err(1, "calloc");
339 evbuffer_remove(buf, str, len);
340 return str;
343 static void
344 np_read_qid(struct evbuffer *buf, struct qid *qid)
346 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
348 qid->type = np_read8(buf);
349 qid->vers = np_read32(buf);
350 qid->path = np_read64(buf);
353 static int
354 np_read_stat(struct evbuffer *buf, struct np_stat *st)
356 uint16_t size;
358 memset(st, 0, sizeof(*st));
360 size = np_read16(buf);
361 if (size > EVBUFFER_LENGTH(buf))
362 return -1;
364 st->type = np_read16(buf);
365 st->dev = np_read32(buf);
366 np_read_qid(buf, &st->qid);
367 st->mode = np_read32(buf);
368 st->atime = np_read32(buf);
369 st->mtime = np_read32(buf);
370 st->length = np_read64(buf);
371 st->name = np_readstr(buf);
372 st->uid = np_readstr(buf);
373 st->gid = np_readstr(buf);
374 st->muid = np_readstr(buf);
376 return 0;
379 static void
380 expect(uint8_t type)
382 uint8_t t;
384 t = np_read8(buf);
385 if (t == type)
386 return;
388 if (t == Rerror) {
389 char *err;
391 /* skip tag */
392 np_read16(buf);
394 err = np_readstr(buf);
395 errx(1, "expected %s, got error %s",
396 pp_msg_type(type), err);
399 errx(1, "expected %s, got msg type %s",
400 pp_msg_type(type), pp_msg_type(t));
403 static void
404 expect2(uint8_t type, uint16_t tag)
406 uint16_t t;
408 expect(type);
410 t = np_read16(buf);
411 if (t == tag)
412 return;
414 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
417 static char *
418 check(uint8_t type, uint16_t tag)
420 uint16_t rtag;
421 uint8_t rtype;
423 rtype = np_read8(buf);
424 rtag = np_read16(buf);
425 if (rtype == type) {
426 if (rtag != tag)
427 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
428 return NULL;
431 if (rtype == Rerror)
432 return np_readstr(buf);
434 errx(1, "expected %s, got msg type %s",
435 pp_msg_type(type), pp_msg_type(rtype));
438 static void
439 do_version(void)
441 char *version;
443 tversion(VERSION9P, MSIZE9P);
444 do_send();
445 recv_msg();
446 expect2(Rversion, NOTAG);
448 msize = np_read32(buf);
449 version = np_readstr(buf);
451 if (msize > MSIZE9P || msize < 256)
452 errx(1, "got unexpected msize: %d", msize);
453 if (strcmp(version, VERSION9P))
454 errx(1, "unexpected 9p version: %s", version);
456 free(version);
457 ASSERT_EMPTYBUF();
460 static void
461 do_attach(const char *user)
463 struct qid qid;
465 tattach(pwdfid, NOFID, user, "/");
466 do_send();
467 recv_msg();
468 expect2(Rattach, iota_tag);
469 np_read_qid(buf, &qid);
471 ASSERT_EMPTYBUF();
474 static uint32_t
475 do_open(uint32_t fid, uint8_t mode)
477 struct qid qid;
478 uint32_t iounit;
480 topen(fid, mode);
481 do_send();
482 recv_msg();
483 expect2(Ropen, iota_tag);
485 np_read_qid(buf, &qid);
486 iounit = np_read32(buf);
488 ASSERT_EMPTYBUF();
490 return iounit;
493 static uint32_t
494 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
496 struct qid qid;
497 uint32_t iounit;
499 tcreate(fid, name, perm, mode);
500 do_send();
501 recv_msg();
502 expect2(Rcreate, iota_tag);
504 np_read_qid(buf, &qid);
505 iounit = np_read32(buf);
507 ASSERT_EMPTYBUF();
509 return iounit;
512 static void
513 do_clunk(uint32_t fid)
515 tclunk(fid);
516 do_send();
517 recv_msg();
518 expect2(Rclunk, iota_tag);
520 ASSERT_EMPTYBUF();
523 static char *
524 dup_fid(int fid, int nfid)
526 uint16_t nwqid;
527 char *errstr;
529 twalk(fid, nfid, NULL, 0);
530 do_send();
531 recv_msg();
533 if ((errstr = check(Rwalk, iota_tag)) != NULL)
534 return errstr;
536 nwqid = np_read16(buf);
537 assert(nwqid == 0);
539 ASSERT_EMPTYBUF();
541 return NULL;
544 static char *
545 walk_path(int fid, int newfid, const char *path, int *missing,
546 struct qid *qid)
548 char *wnames[MAXWELEM], *p, *t, *errstr;
549 size_t nwname, i;
550 uint16_t nwqid;
552 if ((p = strdup(path)) == NULL)
553 err(1, "strdup");
554 t = p;
556 /* strip initial ./ */
557 if (t[0] == '.' && t[1] == '/')
558 t += 2;
560 for (nwname = 0; nwname < nitems(wnames) &&
561 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
562 if (*wnames[nwname] != '\0')
563 nwname++;
566 twalk(fid, newfid, (const char **)wnames, nwname);
567 do_send();
568 recv_msg();
570 *missing = nwname;
571 if ((errstr = check(Rwalk, iota_tag)) != NULL) {
572 free(p);
573 return errstr;
576 nwqid = np_read16(buf);
577 assert(nwqid <= nwname);
579 /* consume all qids */
580 for (i = 0; i < nwqid; ++i)
581 np_read_qid(buf, qid);
583 free(p);
585 *missing = nwname - nwqid;
586 return NULL;
589 static void
590 do_stat(int fid, struct np_stat *st)
592 tstat(fid);
593 do_send();
594 recv_msg();
595 expect2(Rstat, iota_tag);
597 /* eat up the first two byte length */
598 np_read16(buf);
600 if (np_read_stat(buf, st) == -1)
601 errx(1, "invalid stat struct read");
603 ASSERT_EMPTYBUF();
606 static char *
607 do_wstat(int fid, const struct np_stat *st)
609 char *errstr;
611 twstat(fid, st);
612 do_send();
613 recv_msg();
615 if ((errstr = check(Rwstat, iota_tag)) != NULL)
616 return errstr;
618 ASSERT_EMPTYBUF();
620 return NULL;
623 static size_t
624 do_read(int fid, uint64_t off, uint32_t count, void *data)
626 uint32_t r;
628 tread(fid, off, count);
629 do_send();
630 recv_msg();
631 expect2(Rread, iota_tag);
633 r = np_read32(buf);
634 assert(r == EVBUFFER_LENGTH(buf));
635 assert(r <= count);
636 evbuffer_remove(buf, data, r);
638 ASSERT_EMPTYBUF();
640 return r;
643 static size_t
644 do_write(int fid, uint64_t off, uint32_t count, void *data)
646 uint32_t r;
648 twrite(fid, off, data, count);
649 do_send();
650 recv_msg();
651 expect2(Rwrite, iota_tag);
653 r = np_read32(buf);
654 assert(r <= count);
656 ASSERT_EMPTYBUF();
658 return r;
661 static void
662 draw_progress(const char *pre, const struct progress *p)
664 struct winsize ws;
665 int i, l, w;
666 double perc;
668 if (xdump)
669 return;
671 perc = 100.0 * p->done / p->max;
672 if (!tty_p) {
673 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
674 return;
677 if (resized) {
678 resized = 0;
680 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
681 return;
682 tty_width = ws.ws_col;
684 w = tty_width;
686 if (pre == NULL ||
687 ((l = fprintf(stderr, "\r%s ", pre)) == -1 || l >= w))
688 return;
690 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
691 if (w < 0) {
692 fprintf(stderr, "%4d%%\n", (int)perc);
693 return;
696 fprintf(stderr, "|");
698 l = w * MIN(100.0, perc) / 100.0;
699 for (i = 0; i < l; i++)
700 fprintf(stderr, "*");
701 for (; i < w; i++)
702 fprintf(stderr, " ");
703 fprintf(stderr, "|%4d%%", (int)perc);
706 static int
707 fetch_fid(int fid, int fd, const char *name)
709 static char buf[MSIZE9P];
710 struct progress p = {0};
711 struct np_stat st;
712 size_t r;
713 int ret = 0;
715 do_stat(fid, &st);
716 do_open(fid, KOREAD);
718 p.max = st.length;
719 for (;;) {
720 size_t len, off;
721 ssize_t nw;
723 len = MIN(sizeof(buf), msize);
724 len -= IOHDRSZ; /* for the request' fields */
726 r = do_read(fid, p.done, len, buf);
727 if (r == 0)
728 break;
730 for (off = 0; off < r; off += nw)
731 if ((nw = write(fd, buf + off, r - off)) == 0 ||
732 nw == -1) {
733 ret = -1;
734 goto end;
737 p.done += r;
738 draw_progress(name, &p);
740 #if 0
741 /* throttle, for debugging purpose */
743 struct timespec ts = { 0, 500000000 };
744 nanosleep(&ts, NULL);
746 #endif
749 end:
750 putchar('\n');
752 do_clunk(fid);
753 return ret;
756 static void
757 send_fid(int fid, const char *fnam, int open_flags, int fd, const char *name)
759 static char buf[MSIZE9P];
760 struct progress p = {0};
761 struct stat sb;
762 ssize_t r;
763 size_t w, len;
765 if (fstat(fd, &sb) == -1)
766 err(1, "fstat");
768 if (fnam != NULL)
769 do_create(fid, fnam, 0644, KOWRITE);
770 else
771 do_open(fid, open_flags | KOWRITE);
773 p.max = sb.st_size;
774 for (;;) {
775 len = MIN(sizeof(buf), msize);
776 len -= HEADERSIZE + 4 + 4 + 8; /* for the request' fields */
778 r = read(fd, buf, len);
779 if (r == 0)
780 break;
781 if (r == -1)
782 err(1, "read");
784 w = do_write(fid, p.done, r, buf);
785 p.done += w;
787 draw_progress(name, &p);
789 #if 0
790 /* throttle, for debugging purpose */
792 struct timespec ts = { 0, 500000000 };
793 nanosleep(&ts, NULL);
795 #endif
798 putchar('\n');
799 do_clunk(fid);
802 static int
803 woc_file(int fd, const char *prompt, const char *path)
805 struct qid qid;
806 const char *n = NULL;
807 char *errstr;
808 int nfid, miss;
810 nfid = nextfid();
811 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
812 if (errstr != NULL && miss > 1) {
813 fprintf(stderr, "%s: %s\n", path, errstr);
814 free(errstr);
815 return -1;
818 if (errstr != NULL || miss == 1) {
819 char p[PATH_MAX], *dn;
821 /*
822 * If it's only one component missing (the file name), walk
823 * to the parent directory and try to create the file.
824 */
826 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
827 fprintf(stderr, "path too long: %s\n", path);
828 return -1;
830 dn = dirname(p);
832 if (!strcmp(dn, ".")) {
833 errstr = dup_fid(pwdfid, nfid);
834 miss = 0;
835 } else
836 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
838 if (errstr != NULL) {
839 fprintf(stderr, "%s: %s\n", dn, errstr);
840 free(errstr);
841 return -1;
844 if (miss != 0) {
845 fprintf(stderr, "%s: not a directory\n", dn);
846 return -1;
849 if ((n = strrchr(path, '/')) != NULL)
850 n++;
851 else
852 n = path;
855 free(errstr);
857 if (miss > 1) {
858 fprintf(stderr, "can't create %s: missing %d path"
859 " component(s)\n", path, miss);
860 return -1;
863 send_fid(nfid, n, KOTRUNC, fd, prompt);
864 return 0;
867 static int
868 dial(const char *host, const char *port)
870 struct addrinfo hints, *res, *res0;
871 int sock, error, saved_errno;
872 const char *cause = NULL;
874 memset(&hints, 0, sizeof(hints));
875 hints.ai_family = AF_UNSPEC;
876 hints.ai_socktype = SOCK_STREAM;
877 error = getaddrinfo(host, port, &hints, &res0);
878 if (error)
879 errx(1, "%s", gai_strerror(error));
881 sock = -1;
882 for (res = res0; res != NULL; res = res->ai_next) {
883 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
884 res->ai_protocol);
885 if (sock == -1) {
886 cause = "socket";
887 continue;
890 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
891 cause = "connect";
892 saved_errno = errno;
893 close(sock);
894 errno = saved_errno;
895 sock = -1;
896 continue;
899 break;
901 freeaddrinfo(res0);
902 if (sock == -1)
903 err(1, "%s", cause);
904 return sock;
907 static void
908 do_connect(const char *host, const char *port, const char *user)
910 struct qid qid;
911 int nfid, miss, fd;
912 char *errstr;
914 fprintf(stderr, "connecting to %s:%s...", host, port);
916 if (tls) {
917 struct tls_config *conf;
918 struct tls *ctx;
919 int r;
921 if ((conf = tls_config_new()) == NULL)
922 fatalx("failed to create TLS config");
923 tls_config_insecure_noverifycert(conf);
924 tls_config_insecure_noverifyname(conf);
926 if (keypath == NULL)
927 keypath = crtpath;
929 if (tls_config_set_keypair_file(conf, crtpath, keypath) == -1)
930 fatalx("failed to load certs: (%s, %s)", crtpath,
931 keypath);
933 if ((ctx = tls_client()) == NULL)
934 fatalx("failed to create TLS client");
935 if (tls_configure(ctx, conf) == -1)
936 fatalx("failed to configure TLS client");
937 tls_config_free(conf);
939 if (tls_connect(ctx, host, port) == -1)
940 fatalx("failed to connect to %s:%s: %s", host, port,
941 tls_error(ctx));
943 do {
944 r = tls_handshake(ctx);
945 } while (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT);
946 fp = funopen(ctx, stdio_tls_read, stdio_tls_write, NULL,
947 stdio_tls_close);
948 if (fp == NULL)
949 fatal("funopen");
950 } else {
951 int fd;
953 fd = dial(host, port);
954 if ((fp = fdopen(fd, "r+")) == NULL)
955 fatal("fdopen");
958 fprintf(stderr, " done!\n");
960 do_version();
961 do_attach(user);
964 static int
965 tmp_file(char sfn[TMPFSTRLEN])
967 int tmpfd;
969 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
970 if ((tmpfd = mkstemp(sfn)) == -1) {
971 warn("mkstemp %s", sfn);
972 return -1;
975 /* set the close-on-exec flag */
976 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
977 warn("fcntl");
978 close(tmpfd);
979 return -1;
982 return tmpfd;
985 static inline const char *
986 pp_perm(uint8_t x)
988 switch (x & 0x7) {
989 case 0x0:
990 return "---";
991 case 0x1:
992 return "--x";
993 case 0x2:
994 return "-w-";
995 case 0x3:
996 return "-wx";
997 case 0x4:
998 return "r--";
999 case 0x5:
1000 return "r-x";
1001 case 0x6:
1002 return "rw-";
1003 case 0x7:
1004 return "rwx";
1005 default:
1006 /* unreachable, just for the compiler' happiness */
1007 return "???";
1011 static inline void
1012 prepare_wstat(struct np_stat *st)
1014 memset(st, 0xFF, sizeof(*st));
1015 st->name = NULL;
1016 st->uid = NULL;
1017 st->gid = NULL;
1018 st->muid = NULL;
1021 static void
1022 cmd_bell(int argc, const char **argv)
1024 if (argc == 0) {
1025 bell = !bell;
1026 if (bell)
1027 puts("bell mode enabled");
1028 else
1029 puts("bell mode disabled");
1030 return;
1033 if (argc != 1)
1034 goto usage;
1036 if (!strcmp(*argv, "on")) {
1037 bell = 1;
1038 puts("bell mode enabled");
1039 return;
1042 if (!strcmp(*argv, "off")) {
1043 bell = 0;
1044 puts("bell mode disabled");
1045 return;
1048 usage:
1049 printf("bell [on | off]\n");
1052 static void
1053 cmd_bye(int argc, const char **argv)
1055 log_warnx("bye\n");
1056 fclose(fp);
1057 exit(0);
1060 static void
1061 cmd_cd(int argc, const char **argv)
1063 struct qid qid;
1064 int nfid, miss;
1065 char *errstr;
1067 if (argc != 1) {
1068 printf("usage: cd remote-path\n");
1069 return;
1072 nfid = nextfid();
1073 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1074 if (errstr != NULL) {
1075 printf("%s: %s\n", argv[0], errstr);
1076 free(errstr);
1077 return;
1080 if (miss != 0 || !(qid.type & QTDIR)) {
1081 printf("%s: not a directory\n", argv[0]);
1082 if (miss == 0)
1083 do_clunk(nfid);
1084 return;
1087 do_clunk(pwdfid);
1088 pwdfid = nfid;
1091 static void
1092 cmd_edit(int argc, const char **argv)
1094 struct qid qid;
1095 int nfid, tmpfd, miss;
1096 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1097 const char *ed;
1099 if (argc != 1) {
1100 puts("usage: edit file");
1101 return;
1104 if ((ed = getenv("VISUAL")) == NULL &&
1105 (ed = getenv("EDITOR")) == NULL)
1106 ed = "ed";
1108 nfid = nextfid();
1109 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1110 if (errstr != NULL) {
1111 printf("%s: %s\n", *argv, errstr);
1112 free(errstr);
1113 return;
1116 if (miss != 0 || qid.type != 0) {
1117 printf("%s: not a file\n", *argv);
1118 if (miss == 0)
1119 do_clunk(nfid);
1120 return;
1123 if ((tmpfd = tmp_file(sfn)) == -1) {
1124 do_clunk(nfid);
1125 return;
1128 strlcpy(p, *argv, sizeof(p));
1129 name = basename(p);
1131 if (fetch_fid(nfid, tmpfd, name)) {
1132 warn("failed fetch or can't write %s", sfn);
1133 goto end;
1135 close(tmpfd);
1137 spawn(ed, sfn, NULL);
1140 * Re-open the file because it's not guaranteed that the
1141 * file descriptor tmpfd is still associated with the file
1142 * pointed by sfn: it's not uncommon for editor to write
1143 * a backup file and then rename(2) it to the file name.
1145 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1146 warn("can't open %s", sfn);
1147 goto end;
1150 woc_file(tmpfd, *argv, name);
1151 close(tmpfd);
1153 end:
1154 unlink(sfn);
1157 static void
1158 cmd_get(int argc, const char **argv)
1160 struct qid qid;
1161 const char *l;
1162 char *errstr;
1163 int nfid, fd, miss;
1165 if (argc != 1 && argc != 2) {
1166 printf("usage: get remote-file [local-file]\n");
1167 return;
1170 if (argc == 2)
1171 l = argv[1];
1172 else if ((l = strrchr(argv[0], '/')) != NULL)
1173 l++; /* skip / */
1174 else
1175 l = argv[0];
1177 nfid = nextfid();
1178 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1179 if (errstr != NULL) {
1180 printf("%s: %s\n", argv[0], errstr);
1181 free(errstr);
1182 return;
1185 if (miss != 0 || qid.type != 0) {
1186 printf("%s: not a file\n", argv[0]);
1187 if (miss == 0)
1188 do_clunk(nfid);
1189 return;
1192 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1193 warn("can't open %s", l);
1194 do_clunk(nfid);
1195 return;
1198 if (fetch_fid(nfid, fd, l) == -1)
1199 warn("write %s", l);
1200 close(fd);
1203 static void
1204 cmd_hexdump(int argc, const char **argv)
1206 if (argc == 0) {
1207 xdump = !xdump;
1208 if (xdump)
1209 puts("hexdump mode enabled");
1210 else
1211 puts("hexdump mode disabled");
1212 return;
1215 if (argc > 1)
1216 goto usage;
1218 if (!strcmp(*argv, "on")) {
1219 xdump = 1;
1220 puts("hexdump mode enabled");
1221 return;
1224 if (!strcmp(*argv, "off")) {
1225 xdump = 0;
1226 puts("hexdump mode disabled");
1227 return;
1230 usage:
1231 puts("usage: hexdump [on | off]");
1234 static void
1235 cmd_lcd(int argc, const char **argv)
1237 const char *dir;
1239 if (argc > 1) {
1240 printf("usage: lcd [local-directory]\n");
1241 return;
1244 if (argc == 1)
1245 dir = *argv;
1247 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1248 printf("HOME is not defined\n");
1249 return;
1252 if (chdir(dir) == -1)
1253 printf("cd: %s: %s\n", dir, strerror(errno));
1256 static void
1257 cmd_lpwd(int argc, const char **argv)
1259 char path[PATH_MAX];
1261 if (argc != 0) {
1262 printf("usage: lpwd\n");
1263 return;
1266 if (getcwd(path, sizeof(path)) == NULL) {
1267 printf("lpwd: %s\n", strerror(errno));
1268 return;
1271 printf("%s\n", path);
1274 static void
1275 cmd_ls(int argc, const char **argv)
1277 struct np_stat st;
1278 time_t now, mtime;
1279 struct tm *tm;
1280 uint64_t off = 0;
1281 uint32_t len;
1282 int nfid;
1283 const char *timfmt;
1284 char fmt[FMT_SCALED_STRSIZE], tim[13], *errstr;
1286 if (argc != 0) {
1287 printf("ls don't take arguments (yet)\n");
1288 return;
1291 now = time(NULL);
1293 nfid = nextfid();
1294 if ((errstr = dup_fid(pwdfid, nfid)) != NULL) {
1295 printf(".: %s\n", errstr);
1296 free(errstr);
1297 return;
1300 do_open(nfid, KOREAD);
1302 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1304 for (;;) {
1305 tread(nfid, off, msize - IOHDRSZ);
1306 do_send();
1307 recv_msg();
1308 expect2(Rread, iota_tag);
1310 len = np_read32(buf);
1311 if (len == 0)
1312 break;
1314 evbuffer_add_buffer(dirbuf, buf);
1315 off += len;
1317 ASSERT_EMPTYBUF();
1320 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1321 if (np_read_stat(dirbuf, &st) == -1)
1322 errx(1, "invalid stat struct read");
1324 if (fmt_scaled(st.length, fmt) == -1)
1325 strlcpy(fmt, "xxx", sizeof(fmt));
1327 mtime = st.mtime;
1329 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
1330 timfmt = "%b %e %R";
1331 else
1332 timfmt = "%b %e %Y";
1334 if ((tm = localtime(&mtime)) == NULL ||
1335 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1336 strlcpy(tim, "unknown", sizeof(tim));
1338 if (st.qid.type & QTDIR)
1339 printf("d");
1340 else
1341 printf("-");
1342 printf("%s", pp_perm(st.mode >> 6));
1343 printf("%s", pp_perm(st.mode >> 3));
1344 printf("%s", pp_perm(st.mode));
1345 printf(" %8s %12s %s%s\n", fmt, tim, st.name,
1346 st.qid.type & QTDIR ? "/" : "");
1348 free(st.name);
1349 free(st.uid);
1350 free(st.gid);
1351 free(st.muid);
1354 do_clunk(nfid);
1357 static void
1358 cmd_page(int argc, const char **argv)
1360 struct qid qid;
1361 int nfid, tmpfd, miss, r;
1362 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1363 const char *pager;
1365 if (argc != 1) {
1366 puts("usage: page file");
1367 return;
1370 if ((pager = getenv("PAGER")) == NULL)
1371 pager = "less";
1373 nfid = nextfid();
1374 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1375 if (errstr != NULL) {
1376 printf("%s: %s\n", *argv, errstr);
1377 free(errstr);
1378 return;
1381 if (miss != 0 || qid.type != 0) {
1382 printf("%s: not a file\n", *argv);
1383 if (miss == 0)
1384 do_clunk(nfid);
1385 return;
1388 if ((tmpfd = tmp_file(sfn)) == -1) {
1389 do_clunk(nfid);
1390 return;
1393 strlcpy(p, *argv, sizeof(p));
1394 name = basename(p);
1395 if ((r = fetch_fid(nfid, tmpfd, name)) == -1)
1396 warn("write %s", sfn);
1397 close(tmpfd);
1398 if (r != -1)
1399 spawn(pager, sfn, NULL);
1400 unlink(sfn);
1403 static void
1404 cmd_pipe(int argc, const char **argv)
1406 struct qid qid;
1407 pid_t pid;
1408 int nfid, tmpfd, miss, status;
1409 int filedes[2]; /* read end, write end */
1410 char *errstr;
1412 if (argc < 2) {
1413 puts("usage: pipe remote-file cmd [args...]");
1414 return;
1417 nfid = nextfid();
1418 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1419 if (errstr != NULL) {
1420 printf("%s: %s\n", *argv, errstr);
1421 free(errstr);
1422 return;
1425 if (miss != 0 || qid.type != 0) {
1426 printf("%s: not a file\n", *argv);
1427 if (miss == 0)
1428 do_clunk(nfid);
1429 return;
1432 if (pipe(filedes) == -1)
1433 err(1, "pipe");
1435 switch (pid = vfork()) {
1436 case -1:
1437 err(1, "vfork");
1438 case 0:
1439 close(filedes[1]);
1440 if (dup2(filedes[0], 0) == -1)
1441 err(1, "dup2");
1442 execvp(argv[1], (char *const *)argv + 1);
1443 err(1, "execvp");
1446 close(filedes[0]);
1447 if (fetch_fid(nfid, filedes[1], *argv) == -1)
1448 warnx("failed to fetch all the file");
1449 close(filedes[1]);
1451 waitpid(pid, &status, 0);
1454 static void
1455 cmd_put(int argc, const char **argv)
1457 struct qid qid;
1458 const char *l;
1459 int fd;
1461 if (argc != 1 && argc != 2) {
1462 printf("usage: put local-file [remote-file]\n");
1463 return;
1466 if (argc == 2)
1467 l = argv[1];
1468 else if ((l = strrchr(argv[0], '/')) != NULL)
1469 l++; /* skip / */
1470 else
1471 l = argv[0];
1473 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1474 warn("%s", argv[0]);
1475 return;
1478 woc_file(fd, argv[0], l);
1479 close(fd);
1482 static void
1483 cmd_rename(int argc, const char **argv)
1485 struct np_stat st;
1486 struct qid qid;
1487 char *errstr;
1488 int nfid, miss;
1490 if (argc != 2) {
1491 puts("usage: rename remote-file new-remote-name");
1492 return;
1495 nfid = nextfid();
1496 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1497 if (errstr != NULL) {
1498 printf("%s: %s\n", argv[0], errstr);
1499 free(errstr);
1500 return;
1503 if (miss != 0) {
1504 printf("%s: not such file or directory\n", argv[0]);
1505 return;
1508 prepare_wstat(&st);
1509 st.name = (char *)argv[1];
1510 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1511 printf("rename: %s\n", errstr);
1512 free(errstr);
1515 do_clunk(nfid);
1518 static void
1519 cmd_verbose(int argc, const char **argv)
1521 if (argc == 0) {
1522 log_setverbose(!log_getverbose());
1523 if (log_getverbose())
1524 puts("verbose mode enabled");
1525 else
1526 puts("verbose mode disabled");
1527 return;
1530 if (argc != 1)
1531 goto usage;
1533 if (!strcmp(*argv, "on")) {
1534 log_setverbose(1);
1535 puts("verbose mode enabled");
1536 return;
1539 if (!strcmp(*argv, "off")) {
1540 log_setverbose(0);
1541 puts("verbose mode disabled");
1542 return;
1545 usage:
1546 printf("verbose [on | off]\n");
1549 static void
1550 excmd(int argc, const char **argv)
1552 struct cmd {
1553 const char *name;
1554 void (*fn)(int, const char **);
1555 } cmds[] = {
1556 {"bell", cmd_bell},
1557 {"bye", cmd_bye},
1558 {"cd", cmd_cd},
1559 {"edit", cmd_edit},
1560 {"get", cmd_get},
1561 {"hexdump", cmd_hexdump},
1562 {"lcd", cmd_lcd},
1563 {"lpwd", cmd_lpwd},
1564 {"ls", cmd_ls},
1565 {"page", cmd_page},
1566 {"pipe", cmd_pipe},
1567 {"put", cmd_put},
1568 {"quit", cmd_bye},
1569 {"rename", cmd_rename},
1570 {"verbose", cmd_verbose},
1572 size_t i;
1574 if (argc == 0)
1575 return;
1576 for (i = 0; i < nitems(cmds); ++i) {
1577 if (!strcmp(cmds[i].name, *argv)) {
1578 cmds[i].fn(argc-1, argv+1);
1579 return;
1583 log_warnx("unknown command %s", *argv);
1586 static void
1587 cd_or_fetch(const char *path, const char *outfile)
1589 struct qid qid;
1590 char *errstr;
1591 int fd, nfid, miss;
1593 while (*path == '/')
1594 path++;
1595 if (*path == '\0')
1596 return;
1598 nfid = nextfid();
1599 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
1600 if (errstr)
1601 errx(1, "walk %s: %s", path, errstr);
1602 if (miss)
1603 errc(1, ENOENT, "walk %s", path);
1605 if (qid.type & QTDIR) {
1606 if (outfile)
1607 errx(1, "can't fetch directory %s", path);
1608 do_clunk(pwdfid);
1609 pwdfid = nfid;
1610 return;
1613 if (outfile == NULL) {
1614 if ((outfile = strrchr(path, '/')) == NULL)
1615 outfile = path;
1616 else
1617 outfile++;
1618 if (*outfile == '\0')
1619 errx(1, "invalid path: missing file name: %s",
1620 path);
1623 if (strcmp(outfile, "-") != 0) {
1624 fd = open(outfile, O_WRONLY|O_CREAT, 0644);
1625 if (fd == -1)
1626 err(1, "can't open for writing %s", outfile);
1627 } else
1628 fd = 1;
1630 if (fetch_fid(nfid, fd, outfile) == -1)
1631 err(1, "write %s", outfile);
1632 close(fd);
1633 fclose(fp);
1634 exit(0);
1637 static const char *
1638 parse_addr(const char *url, const char **user,
1639 const char **port, const char **path)
1641 static char buf[PATH_MAX];
1642 char *host, *t;
1644 *user = *port = *path = NULL;
1645 host = buf;
1647 if (strlcpy(buf, url, sizeof(buf)) >= sizeof(buf))
1648 errx(1, "connection string too long");
1650 if ((t = strchr(host, '/')) != NULL) {
1651 if (t == host)
1652 errx(1, "invalid connection string: %s", url);
1653 *t++ = '\0';
1654 if (*t != '\0')
1655 *path = t;
1658 if ((t = strchr(host, '@')) != NULL) {
1659 if (t == host)
1660 errx(1, "invalid connection string: %s", url);
1661 *t++ = '\0';
1662 *user = host;
1663 host = t;
1664 } else if ((*user = getenv("USER")) == NULL)
1665 errx(1, "USER not defined");
1667 if ((t = strchr(host, ':')) != NULL) {
1668 *t++ = '\0';
1669 if (*t != '\0')
1670 *port = t;
1672 if (*port == NULL)
1673 *port = "1337";
1675 return host;
1678 int
1679 main(int argc, char **argv)
1681 const char *user, *host, *port, *path;
1682 const char *outfile = NULL;
1683 int ch;
1685 log_init(1, LOG_DAEMON);
1686 log_setverbose(0);
1687 log_procinit(getprogname());
1689 while ((ch = getopt(argc, argv, "C:cK:o:")) != -1) {
1690 switch (ch) {
1691 case 'C':
1692 tls = 1;
1693 crtpath = optarg;
1694 break;
1695 case 'c': /* deprecated, remove after 0.3 */
1696 tls = 1;
1697 break;
1698 case 'K':
1699 tls = 1;
1700 keypath = optarg;
1701 break;
1702 case 'o':
1703 outfile = optarg;
1704 break;
1705 default:
1706 usage(1);
1709 argc -= optind;
1710 argv += optind;
1712 if (argc == 0 || (tls && crtpath == NULL))
1713 usage(1);
1715 host = parse_addr(argv[0], &user, &port, &path);
1716 if (path == NULL && argv[1] != NULL)
1717 path = argv[1];
1718 if (outfile && path == NULL)
1719 usage(1);
1721 signal(SIGPIPE, SIG_IGN);
1722 if (isatty(1)) {
1723 tty_p = 1;
1724 resized = 1;
1725 signal(SIGWINCH, tty_resized);
1728 if ((evb = evbuffer_new()) == NULL)
1729 fatal("evbuffer_new");
1731 if ((buf = evbuffer_new()) == NULL)
1732 fatal("evbuffer_new");
1734 if ((dirbuf = evbuffer_new()) == NULL)
1735 fatal("evbuferr_new");
1737 do_connect(host, port, user);
1738 if (path)
1739 cd_or_fetch(path, outfile);
1741 for (;;) {
1742 int argc = 0;
1743 char *line, *argv[16] = {0}, **ap;
1745 if ((line = read_line("kamiftp> ")) == NULL)
1746 break;
1748 for (argc = 0, ap = argv; ap < &argv[15] &&
1749 (*ap = strsep(&line, " \t")) != NULL;) {
1750 if (**ap != '\0')
1751 ap++, argc++;
1753 excmd(argc, (const char **)argv);
1755 if (bell) {
1756 printf("\a");
1757 fflush(stdout);
1760 free(line);
1763 printf("\n");
1764 fclose(fp);