Blob


1 /*
2 * Copyright (c) 2021 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 <sys/ioctl.h>
18 #include <sys/types.h>
19 #include <sys/socket.h>
21 #include <assert.h>
22 #include <err.h>
23 #include <errno.h>
24 #include <event.h>
25 #include <fcntl.h>
26 #include <inttypes.h>
27 #include <netdb.h>
28 #include <limits.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <syslog.h>
34 #include <tls.h>
35 #include <unistd.h>
36 #include <util.h>
38 #include <readline/readline.h>
39 #include <readline/history.h>
41 #ifndef nitems
42 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
43 #endif
45 #include "9pclib.h"
46 #include "kami.h"
47 #include "utils.h"
48 #include "log.h"
50 /* flags */
51 int tls;
52 const char *crtpath;
53 const char *keypath;
55 /* state */
56 struct tls_config *tlsconf;
57 struct tls *ctx;
58 int sock;
59 struct evbuffer *buf;
60 struct evbuffer *dirbuf;
61 uint32_t msize;
62 int bell;
64 volatile sig_atomic_t resized;
65 int tty_p;
66 int tty_width;
68 struct np_stat {
69 uint16_t type;
70 uint32_t dev;
71 struct qid qid;
72 uint32_t mode;
73 uint32_t atime;
74 uint32_t mtime;
75 uint64_t length;
76 char *name;
77 char *uid;
78 char *gid;
79 char *muid;
80 };
82 struct progress {
83 uint64_t max;
84 uint64_t done;
85 };
87 int pwdfid;
89 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
91 static char *
92 read_line(const char *prompt)
93 {
94 char *line;
96 again:
97 if ((line = readline(prompt)) == NULL)
98 return NULL;
99 /* XXX: trim spaces? */
100 if (*line == '\0') {
101 free(line);
102 goto again;
105 add_history(line);
106 return line;
109 static void
110 tty_resized(int signo)
112 resized = 1;
115 static void __dead
116 usage(int ret)
118 fprintf(stderr, "usage: %s [-c] host[:port] [path]\n",
119 getprogname());
120 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
121 exit(ret);
124 static void
125 do_send(void)
127 const void *buf;
128 size_t nbytes;
129 ssize_t r;
131 while (EVBUFFER_LENGTH(evb) != 0) {
132 buf = EVBUFFER_DATA(evb);
133 nbytes = EVBUFFER_LENGTH(evb);
135 if (ctx == NULL) {
136 r = write(sock, buf, nbytes);
137 if (r == 0 || r == -1)
138 errx(1, "EOF");
139 } else {
140 r = tls_write(ctx, buf, nbytes);
141 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
142 continue;
143 if (r == -1)
144 errx(1, "tls: %s", tls_error(ctx));
147 evbuffer_drain(evb, r);
151 static void
152 mustread(void *d, size_t len)
154 ssize_t r;
156 while (len != 0) {
157 if (ctx == NULL) {
158 r = read(sock, d, len);
159 if (r == 0 || r == -1)
160 errx(1, "EOF");
161 } else {
162 r = tls_read(ctx, d, len);
163 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
164 continue;
165 if (r == -1)
166 errx(1, "tls: %s", tls_error(ctx));
169 d += r;
170 len -= r;
174 static void
175 recv_msg(void)
177 uint32_t len, l;
178 char tmp[BUFSIZ];
180 mustread(&len, sizeof(len));
181 len = le32toh(len);
182 if (len < HEADERSIZE)
183 errx(1, "read message of invalid length %d", len);
185 len -= 4; /* skip the length just read */
187 while (len != 0) {
188 l = MIN(len, sizeof(tmp));
189 mustread(tmp, l);
190 len -= l;
191 evbuffer_add(buf, tmp, l);
195 static uint64_t
196 np_read64(struct evbuffer *buf)
198 uint64_t n;
200 evbuffer_remove(buf, &n, sizeof(n));
201 return le64toh(n);
204 static uint32_t
205 np_read32(struct evbuffer *buf)
207 uint32_t n;
209 evbuffer_remove(buf, &n, sizeof(n));
210 return le32toh(n);
213 static uint16_t
214 np_read16(struct evbuffer *buf)
216 uint16_t n;
218 evbuffer_remove(buf, &n, sizeof(n));
219 return le16toh(n);
222 static uint16_t
223 np_read8(struct evbuffer *buf)
225 uint8_t n;
227 evbuffer_remove(buf, &n, sizeof(n));
228 return n;
231 static char *
232 np_readstr(struct evbuffer *buf)
234 uint16_t len;
235 char *str;
237 len = np_read16(buf);
238 assert(EVBUFFER_LENGTH(buf) >= len);
240 if ((str = calloc(1, len+1)) == NULL)
241 err(1, "calloc");
242 evbuffer_remove(buf, str, len);
243 return str;
246 static void
247 np_read_qid(struct evbuffer *buf, struct qid *qid)
249 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
251 qid->type = np_read8(buf);
252 qid->vers = np_read32(buf);
253 qid->path = np_read64(buf);
256 static int
257 np_read_stat(struct evbuffer *buf, struct np_stat *st)
259 uint16_t size;
261 memset(st, 0, sizeof(*st));
263 size = np_read16(buf);
264 if (size > EVBUFFER_LENGTH(buf))
265 return -1;
267 st->type = np_read16(buf);
268 st->dev = np_read32(buf);
269 np_read_qid(buf, &st->qid);
270 st->mode = np_read32(buf);
271 st->atime = np_read32(buf);
272 st->mtime = np_read32(buf);
273 st->length = np_read64(buf);
274 st->name = np_readstr(buf);
275 st->uid = np_readstr(buf);
276 st->gid = np_readstr(buf);
277 st->muid = np_readstr(buf);
279 return 0;
282 static void
283 expect(uint8_t type)
285 uint8_t t;
287 t = np_read8(buf);
288 if (t == type)
289 return;
291 if (t == Rerror) {
292 char *err;
294 /* skip tag */
295 np_read16(buf);
297 err = np_readstr(buf);
298 errx(1, "expected %s, got error %s",
299 pp_msg_type(type), err);
302 errx(1, "expected %s, got msg type %s",
303 pp_msg_type(type), pp_msg_type(t));
306 static void
307 expect2(uint8_t type, uint16_t tag)
309 uint16_t t;
311 expect(type);
313 t = np_read16(buf);
314 if (t == tag)
315 return;
317 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
320 static void
321 do_version(void)
323 char *version;
325 tversion(VERSION9P, MSIZE9P);
326 do_send();
327 recv_msg();
328 expect2(Rversion, NOTAG);
330 msize = np_read32(buf);
331 version = np_readstr(buf);
333 if (msize > MSIZE9P)
334 errx(1, "got unexpected msize: %d", msize);
335 if (strcmp(version, VERSION9P))
336 errx(1, "unexpected 9p version: %s", version);
338 free(version);
339 ASSERT_EMPTYBUF();
342 static void
343 do_attach(const char *path)
345 const char *user;
346 struct qid qid;
348 if (path == NULL)
349 path = "/";
350 if ((user = getenv("USER")) == NULL)
351 user = "flan";
353 tattach(pwdfid, NOFID, user, path);
354 do_send();
355 recv_msg();
356 expect2(Rattach, iota_tag);
357 np_read_qid(buf, &qid);
359 ASSERT_EMPTYBUF();
362 static uint32_t
363 do_open(uint32_t fid, uint8_t mode)
365 struct qid qid;
366 uint32_t iounit;
368 topen(fid, mode);
369 do_send();
370 recv_msg();
371 expect2(Ropen, iota_tag);
373 np_read_qid(buf, &qid);
374 iounit = np_read32(buf);
376 ASSERT_EMPTYBUF();
378 return iounit;
381 static void
382 do_clunk(uint32_t fid)
384 tclunk(fid);
385 do_send();
386 recv_msg();
387 expect2(Rclunk, iota_tag);
389 ASSERT_EMPTYBUF();
392 static void
393 dup_fid(int fid, int nfid)
395 uint16_t nwqid;
397 twalk(fid, nfid, NULL, 0);
398 do_send();
399 recv_msg();
400 expect2(Rwalk, iota_tag);
402 nwqid = np_read16(buf);
403 assert(nwqid == 0);
405 ASSERT_EMPTYBUF();
408 static int
409 walk_path(int fid, int newfid, const char *path, struct qid *qid)
411 char *wnames[MAXWELEM], *p, *t;
412 size_t nwname, i;
413 uint16_t nwqid;
415 if ((p = strdup(path)) == NULL)
416 err(1, "strdup");
417 t = p;
419 /* strip initial ./ */
420 if (t[0] == '.' && t[1] == '/')
421 t += 2;
423 for (nwname = 0; nwname < nitems(wnames) &&
424 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
425 if (*wnames[nwname] != '\0')
426 nwname++;
429 twalk(fid, newfid, (const char **)wnames, nwname);
430 do_send();
431 recv_msg();
432 expect2(Rwalk, iota_tag);
434 nwqid = np_read16(buf);
435 assert(nwqid <= nwname);
437 /* consume all qids */
438 for (i = 0; i < nwname; ++i)
439 np_read_qid(buf, qid);
441 free(p);
443 return nwqid == nwname;
446 static void
447 do_stat(int fid, struct np_stat *st)
449 tstat(fid);
450 do_send();
451 recv_msg();
452 expect2(Rstat, iota_tag);
454 if (np_read_stat(buf, st) == -1)
455 errx(1, "invalid stat struct read");
457 ASSERT_EMPTYBUF();
460 static size_t
461 do_read(int fid, uint64_t off, uint32_t count, void *data)
463 uint32_t r;
465 tread(fid, off, count);
466 do_send();
467 recv_msg();
468 expect2(Rread, iota_tag);
470 r = np_read32(buf);
471 assert(r == EVBUFFER_LENGTH(buf));
472 assert(r <= count);
473 evbuffer_remove(buf, data, r);
475 ASSERT_EMPTYBUF();
477 return r;
480 static void
481 draw_progress(const char *pre, const struct progress *p)
483 struct winsize ws;
484 int i, l, w;
485 double perc;
487 perc = 100.0 * p->done / p->max;
488 if (!tty_p) {
489 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
490 return;
493 if (resized) {
494 resized = 0;
496 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
497 return;
498 tty_width = ws.ws_col;
500 w = tty_width;
502 if (pre == NULL ||
503 ((l = printf("\r%s ", pre)) == -1 || l >= w))
504 return;
506 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
507 if (w < 0) {
508 printf("%4d%%\n", (int)perc);
509 return;
512 printf("|");
514 l = w * MIN(100.0, perc) / 100.0;
515 for (i = 0; i < l; i++)
516 printf("*");
517 for (; i < w; i++)
518 printf(" ");
519 printf("|%4d%%", (int)perc);
521 fflush(stdout);
524 static int
525 fetch_fid(int fid, const char *path)
527 struct progress p = {0};
528 struct np_stat st;
529 size_t r;
530 int fd;
531 char buf[BUFSIZ];
533 do_stat(fid, &st);
534 do_open(fid, KOREAD);
536 if ((fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1) {
537 warn("can't open %s", path);
538 return -1;
541 p.max = st.length;
542 for (;;) {
543 size_t siz, off;
544 ssize_t nw;
546 r = do_read(fid, p.done, sizeof(buf), buf);
547 if (r == 0)
548 break;
550 siz = sizeof(buf);
551 for (off = 0; off < siz; off += nw)
552 if ((nw = write(fd, buf + off, siz - off)) == 0 ||
553 nw == -1)
554 err(1, "write");
556 p.done += r;
557 draw_progress(path, &p);
559 #if 0
560 /* throttle, for debugging purpose */
562 struct timespec ts = { 0, 500000000 };
563 nanosleep(&ts, NULL);
565 #endif
568 putchar('\n');
570 close(fd);
571 do_clunk(fid);
572 return 0;
575 static void
576 do_tls_connect(const char *host, const char *port)
578 int handshake;
580 if ((tlsconf = tls_config_new()) == NULL)
581 fatalx("tls_config_new");
582 tls_config_insecure_noverifycert(tlsconf);
583 tls_config_insecure_noverifyname(tlsconf);
584 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
585 fatalx("can't load certs (%s, %s)", crtpath, keypath);
587 if ((ctx = tls_client()) == NULL)
588 fatal("tls_client");
589 if (tls_configure(ctx, tlsconf) == -1)
590 fatalx("tls_configure: %s", tls_error(ctx));
592 if (tls_connect(ctx, host, port) == -1)
593 fatalx("can't connect to %s:%s: %s", host, port,
594 tls_error(ctx));
596 for (handshake = 0; !handshake;) {
597 switch (tls_handshake(ctx)) {
598 case -1:
599 fatalx("tls_handshake: %s", tls_error(ctx));
600 case 0:
601 handshake = 1;
602 break;
607 static void
608 do_ctxt_connect(const char *host, const char *port)
610 struct addrinfo hints, *res, *res0;
611 int error, saved_errno;
612 const char *cause = NULL;
614 memset(&hints, 0, sizeof(hints));
615 hints.ai_family = AF_UNSPEC;
616 hints.ai_socktype = SOCK_STREAM;
617 error = getaddrinfo(host, port, &hints, &res0);
618 if (error)
619 errx(1, "%s", gai_strerror(error));
621 sock = -1;
622 for (res = res0; res != NULL; res = res->ai_next) {
623 sock = socket(res->ai_family, res->ai_socktype,
624 res->ai_protocol);
625 if (sock == -1) {
626 cause = "socket";
627 continue;
630 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
631 cause = "connect";
632 saved_errno = errno;
633 close(sock);
634 errno = saved_errno;
635 sock = -1;
636 continue;
639 break;
642 if (sock == -1)
643 err(1, "%s", cause);
644 freeaddrinfo(res0);
647 static void
648 do_connect(const char *connspec, const char *path)
650 char *host, *colon;
651 const char *port;
653 host = xstrdup(connspec);
654 if ((colon = strchr(host, ':')) != NULL) {
655 *colon = '\0';
656 port = ++colon;
657 } else
658 port = "1337";
660 printf("connecting to %s:%s...", host, port);
661 fflush(stdout);
663 if (tls)
664 do_tls_connect(host, port);
665 else
666 do_ctxt_connect(host, port);
668 printf(" done!\n");
670 do_version();
671 do_attach(path);
673 free(host);
676 static void
677 cmd_bell(int argc, const char **argv)
679 if (argc == 0) {
680 bell = !bell;
681 if (bell)
682 puts("bell mode enabled");
683 else
684 puts("bell mode disabled");
685 return;
688 if (argc != 1)
689 goto usage;
691 if (!strcmp(*argv, "on")) {
692 bell = 1;
693 puts("bell mode enabled");
694 return;
697 if (!strcmp(*argv, "off")) {
698 bell = 0;
699 puts("bell mode disabled");
700 return;
703 usage:
704 printf("bell [on | off]\n");
707 static void
708 cmd_bye(int argc, const char **argv)
710 log_warnx("bye\n");
711 exit(0);
714 static void
715 cmd_cd(int argc, const char **argv)
717 struct qid qid;
718 int nfid;
720 if (argc != 1) {
721 printf("usage: cd remote-path\n");
722 return;
725 nfid = pwdfid+1;
726 if (walk_path(pwdfid, nfid, argv[0], &qid) == -1 ||
727 !(qid.type & QTDIR)) {
728 printf("can't cd %s\n", argv[0]);
729 do_clunk(nfid);
730 } else {
731 do_clunk(pwdfid);
732 pwdfid = nfid;
736 static void
737 cmd_get(int argc, const char **argv)
739 struct qid qid;
740 const char *l;
741 int nfid;
743 if (argc != 1 && argc != 2) {
744 printf("usage: get remote-file [local-file]\n");
745 return;
748 if (argc == 2)
749 l = argv[1];
750 else if ((l = strrchr(argv[0], '/')) != NULL)
751 l++; /* skip / */
752 else
753 l = argv[1];
755 nfid = pwdfid+1;
756 if (walk_path(pwdfid, nfid, argv[0], &qid) == -1) {
757 printf("can't fetch %s\n", argv[0]);
758 return;
761 if (qid.type != 0) {
762 printf("can't fetch %s\n", argv[0]);
763 do_clunk(nfid);
764 return;
767 fetch_fid(nfid, l);
770 static void
771 cmd_lcd(int argc, const char **argv)
773 const char *dir;
775 if (argc > 1) {
776 printf("lcd takes only one argument\n");
777 return;
780 if (argc == 1)
781 dir = *argv;
783 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
784 printf("HOME is not defined\n");
785 return;
788 if (chdir(dir) == -1)
789 printf("cd: %s: %s\n", dir, strerror(errno));
792 static void
793 cmd_lpwd(int argc, const char **argv)
795 char path[PATH_MAX];
797 if (getcwd(path, sizeof(path)) == NULL) {
798 printf("lpwd: %s\n", strerror(errno));
799 return;
802 printf("%s\n", path);
805 static void
806 cmd_ls(int argc, const char **argv)
808 struct np_stat st;
809 uint64_t off = 0;
810 uint32_t len;
811 char fmt[FMT_SCALED_STRSIZE];
813 if (argc != 0) {
814 printf("ls don't take arguments (yet)\n");
815 return;
818 dup_fid(pwdfid, 1);
819 do_open(1, KOREAD);
821 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
823 for (;;) {
824 tread(1, off, BUFSIZ);
825 do_send();
826 recv_msg();
827 expect2(Rread, iota_tag);
829 len = np_read32(buf);
830 if (len == 0)
831 break;
833 evbuffer_add_buffer(dirbuf, buf);
834 off += len;
836 ASSERT_EMPTYBUF();
839 while (EVBUFFER_LENGTH(dirbuf) != 0) {
840 if (np_read_stat(dirbuf, &st) == -1)
841 errx(1, "invalid stat struct read");
843 if (fmt_scaled(st.length, fmt) == -1)
844 strlcpy(fmt, "xxx", sizeof(fmt));
846 printf("%4s %8s %s\n", pp_qid_type(st.qid.type), fmt, st.name);
848 free(st.name);
849 free(st.uid);
850 free(st.gid);
851 free(st.muid);
854 do_clunk(1);
857 static void
858 cmd_verbose(int argc, const char **argv)
860 if (argc == 0) {
861 log_setverbose(!log_getverbose());
862 if (log_getverbose())
863 puts("verbose mode enabled");
864 else
865 puts("verbose mode disabled");
866 return;
869 if (argc != 1)
870 goto usage;
872 if (!strcmp(*argv, "on")) {
873 log_setverbose(1);
874 puts("verbose mode enabled");
875 return;
878 if (!strcmp(*argv, "off")) {
879 log_setverbose(0);
880 puts("verbose mode disabled");
881 return;
884 usage:
885 printf("verbose [on | off]\n");
888 static void
889 excmd(int argc, const char **argv)
891 struct cmd {
892 const char *name;
893 void (*fn)(int, const char **);
894 } cmds[] = {
895 {"bell", cmd_bell},
896 {"bye", cmd_bye},
897 {"cd", cmd_cd},
898 {"get", cmd_get},
899 {"lcd", cmd_lcd},
900 {"lpwd", cmd_lpwd},
901 {"ls", cmd_ls},
902 {"quit", cmd_bye},
903 {"verbose", cmd_verbose},
904 };
905 size_t i;
907 if (argc == 0)
908 return;
909 for (i = 0; i < nitems(cmds); ++i) {
910 if (!strcmp(cmds[i].name, *argv)) {
911 cmds[i].fn(argc-1, argv+1);
912 return;
916 log_warnx("unknown command %s", *argv);
919 int
920 main(int argc, char **argv)
922 int ch;
924 log_init(1, LOG_DAEMON);
925 log_setverbose(0);
926 log_procinit(getprogname());
928 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
929 switch (ch) {
930 case 'C':
931 crtpath = optarg;
932 break;
933 case 'c':
934 tls = 1;
935 break;
936 case 'K':
937 keypath = optarg;
938 break;
939 default:
940 usage(1);
943 argc -= optind;
944 argv += optind;
946 if (argc == 0)
947 usage(1);
949 if (isatty(1)) {
950 tty_p = 1;
951 resized = 1;
952 signal(SIGWINCH, tty_resized);
955 if ((evb = evbuffer_new()) == NULL)
956 fatal("evbuffer_new");
958 if ((buf = evbuffer_new()) == NULL)
959 fatal("evbuffer_new");
961 if ((dirbuf = evbuffer_new()) == NULL)
962 fatal("evbuferr_new");
964 do_connect(argv[0], argv[1]);
966 for (;;) {
967 int argc = 0;
968 char *line, *argv[16] = {0}, **ap;
970 if ((line = read_line("kamiftp> ")) == NULL)
971 break;
973 for (argc = 0, ap = argv; ap < &argv[15] &&
974 (*ap = strsep(&line, " \t")) != NULL;) {
975 if (**ap != '\0')
976 ap++, argc++;
978 excmd(argc, (const char **)argv);
980 if (bell) {
981 printf("\a");
982 fflush(stdout);
985 free(line);
988 printf("\n");