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 #if HAVE_LIBREADLINE
39 #include <readline/readline.h>
40 #include <readline/history.h>
41 #endif
43 #ifndef nitems
44 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
45 #endif
47 #include "9pclib.h"
48 #include "kami.h"
49 #include "utils.h"
50 #include "log.h"
52 /* flags */
53 int tls;
54 const char *crtpath;
55 const char *keypath;
57 /* state */
58 struct tls_config *tlsconf;
59 struct tls *ctx;
60 int sock;
61 struct evbuffer *buf;
62 struct evbuffer *dirbuf;
63 uint32_t msize;
64 int bell;
66 volatile sig_atomic_t resized;
67 int tty_p;
68 int tty_width;
70 struct np_stat {
71 uint16_t type;
72 uint32_t dev;
73 struct qid qid;
74 uint32_t mode;
75 uint32_t atime;
76 uint32_t mtime;
77 uint64_t length;
78 char *name;
79 char *uid;
80 char *gid;
81 char *muid;
82 };
84 struct progress {
85 uint64_t max;
86 uint64_t done;
87 };
89 int pwdfid;
91 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
93 #if HAVE_LIBREADLINE
94 static char *
95 read_line(const char *prompt)
96 {
97 char *line;
99 again:
100 if ((line = readline(prompt)) == NULL)
101 return NULL;
102 /* XXX: trim spaces? */
103 if (*line == '\0') {
104 free(line);
105 goto again;
108 add_history(line);
109 return line;
111 #else
112 static char *
113 read_line(const char *prompt)
115 char *ch, *line = NULL;
116 size_t linesize = 0;
117 ssize_t linelen;
119 printf("%s", prompt);
120 fflush(stdout);
122 linelen = getline(&line, &linesize, stdin);
123 if (linelen == -1)
124 return NULL;
126 if ((ch = strchr(line, '\n')) != NULL)
127 *ch = '\0';
128 return line;
130 #endif
132 static void
133 tty_resized(int signo)
135 resized = 1;
138 static void __dead
139 usage(int ret)
141 fprintf(stderr, "usage: %s [-c] host[:port] [path]\n",
142 getprogname());
143 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
144 exit(ret);
147 static void
148 do_send(void)
150 const void *buf;
151 size_t nbytes;
152 ssize_t r;
154 while (EVBUFFER_LENGTH(evb) != 0) {
155 buf = EVBUFFER_DATA(evb);
156 nbytes = EVBUFFER_LENGTH(evb);
158 if (ctx == NULL) {
159 r = write(sock, buf, nbytes);
160 if (r == 0 || r == -1)
161 errx(1, "EOF");
162 } else {
163 r = tls_write(ctx, buf, nbytes);
164 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
165 continue;
166 if (r == -1)
167 errx(1, "tls: %s", tls_error(ctx));
170 evbuffer_drain(evb, r);
174 static void
175 mustread(void *d, size_t len)
177 ssize_t r;
179 while (len != 0) {
180 if (ctx == NULL) {
181 r = read(sock, d, len);
182 if (r == 0 || r == -1)
183 errx(1, "EOF");
184 } else {
185 r = tls_read(ctx, d, len);
186 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
187 continue;
188 if (r == -1)
189 errx(1, "tls: %s", tls_error(ctx));
192 d += r;
193 len -= r;
197 static void
198 recv_msg(void)
200 uint32_t len, l;
201 char tmp[BUFSIZ];
203 mustread(&len, sizeof(len));
204 len = le32toh(len);
205 if (len < HEADERSIZE)
206 errx(1, "read message of invalid length %d", len);
208 len -= 4; /* skip the length just read */
210 while (len != 0) {
211 l = MIN(len, sizeof(tmp));
212 mustread(tmp, l);
213 len -= l;
214 evbuffer_add(buf, tmp, l);
218 static uint64_t
219 np_read64(struct evbuffer *buf)
221 uint64_t n;
223 evbuffer_remove(buf, &n, sizeof(n));
224 return le64toh(n);
227 static uint32_t
228 np_read32(struct evbuffer *buf)
230 uint32_t n;
232 evbuffer_remove(buf, &n, sizeof(n));
233 return le32toh(n);
236 static uint16_t
237 np_read16(struct evbuffer *buf)
239 uint16_t n;
241 evbuffer_remove(buf, &n, sizeof(n));
242 return le16toh(n);
245 static uint16_t
246 np_read8(struct evbuffer *buf)
248 uint8_t n;
250 evbuffer_remove(buf, &n, sizeof(n));
251 return n;
254 static char *
255 np_readstr(struct evbuffer *buf)
257 uint16_t len;
258 char *str;
260 len = np_read16(buf);
261 assert(EVBUFFER_LENGTH(buf) >= len);
263 if ((str = calloc(1, len+1)) == NULL)
264 err(1, "calloc");
265 evbuffer_remove(buf, str, len);
266 return str;
269 static void
270 np_read_qid(struct evbuffer *buf, struct qid *qid)
272 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
274 qid->type = np_read8(buf);
275 qid->vers = np_read32(buf);
276 qid->path = np_read64(buf);
279 static int
280 np_read_stat(struct evbuffer *buf, struct np_stat *st)
282 uint16_t size;
284 memset(st, 0, sizeof(*st));
286 size = np_read16(buf);
287 if (size > EVBUFFER_LENGTH(buf))
288 return -1;
290 st->type = np_read16(buf);
291 st->dev = np_read32(buf);
292 np_read_qid(buf, &st->qid);
293 st->mode = np_read32(buf);
294 st->atime = np_read32(buf);
295 st->mtime = np_read32(buf);
296 st->length = np_read64(buf);
297 st->name = np_readstr(buf);
298 st->uid = np_readstr(buf);
299 st->gid = np_readstr(buf);
300 st->muid = np_readstr(buf);
302 return 0;
305 static void
306 expect(uint8_t type)
308 uint8_t t;
310 t = np_read8(buf);
311 if (t == type)
312 return;
314 if (t == Rerror) {
315 char *err;
317 /* skip tag */
318 np_read16(buf);
320 err = np_readstr(buf);
321 errx(1, "expected %s, got error %s",
322 pp_msg_type(type), err);
325 errx(1, "expected %s, got msg type %s",
326 pp_msg_type(type), pp_msg_type(t));
329 static void
330 expect2(uint8_t type, uint16_t tag)
332 uint16_t t;
334 expect(type);
336 t = np_read16(buf);
337 if (t == tag)
338 return;
340 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
343 static void
344 do_version(void)
346 char *version;
348 tversion(VERSION9P, MSIZE9P);
349 do_send();
350 recv_msg();
351 expect2(Rversion, NOTAG);
353 msize = np_read32(buf);
354 version = np_readstr(buf);
356 if (msize > MSIZE9P)
357 errx(1, "got unexpected msize: %d", msize);
358 if (strcmp(version, VERSION9P))
359 errx(1, "unexpected 9p version: %s", version);
361 free(version);
362 ASSERT_EMPTYBUF();
365 static void
366 do_attach(const char *path)
368 const char *user;
369 struct qid qid;
371 if (path == NULL)
372 path = "/";
373 if ((user = getenv("USER")) == NULL)
374 user = "flan";
376 tattach(pwdfid, NOFID, user, path);
377 do_send();
378 recv_msg();
379 expect2(Rattach, iota_tag);
380 np_read_qid(buf, &qid);
382 ASSERT_EMPTYBUF();
385 static uint32_t
386 do_open(uint32_t fid, uint8_t mode)
388 struct qid qid;
389 uint32_t iounit;
391 topen(fid, mode);
392 do_send();
393 recv_msg();
394 expect2(Ropen, iota_tag);
396 np_read_qid(buf, &qid);
397 iounit = np_read32(buf);
399 ASSERT_EMPTYBUF();
401 return iounit;
404 static void
405 do_clunk(uint32_t fid)
407 tclunk(fid);
408 do_send();
409 recv_msg();
410 expect2(Rclunk, iota_tag);
412 ASSERT_EMPTYBUF();
415 static void
416 dup_fid(int fid, int nfid)
418 uint16_t nwqid;
420 twalk(fid, nfid, NULL, 0);
421 do_send();
422 recv_msg();
423 expect2(Rwalk, iota_tag);
425 nwqid = np_read16(buf);
426 assert(nwqid == 0);
428 ASSERT_EMPTYBUF();
431 static int
432 walk_path(int fid, int newfid, const char *path, struct qid *qid)
434 char *wnames[MAXWELEM], *p, *t;
435 size_t nwname, i;
436 uint16_t nwqid;
438 if ((p = strdup(path)) == NULL)
439 err(1, "strdup");
440 t = p;
442 /* strip initial ./ */
443 if (t[0] == '.' && t[1] == '/')
444 t += 2;
446 for (nwname = 0; nwname < nitems(wnames) &&
447 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
448 if (*wnames[nwname] != '\0')
449 nwname++;
452 twalk(fid, newfid, (const char **)wnames, nwname);
453 do_send();
454 recv_msg();
455 expect2(Rwalk, iota_tag);
457 nwqid = np_read16(buf);
458 assert(nwqid <= nwname);
460 /* consume all qids */
461 for (i = 0; i < nwname; ++i)
462 np_read_qid(buf, qid);
464 free(p);
466 return nwqid == nwname;
469 static void
470 do_stat(int fid, struct np_stat *st)
472 tstat(fid);
473 do_send();
474 recv_msg();
475 expect2(Rstat, iota_tag);
477 if (np_read_stat(buf, st) == -1)
478 errx(1, "invalid stat struct read");
480 ASSERT_EMPTYBUF();
483 static size_t
484 do_read(int fid, uint64_t off, uint32_t count, void *data)
486 uint32_t r;
488 tread(fid, off, count);
489 do_send();
490 recv_msg();
491 expect2(Rread, iota_tag);
493 r = np_read32(buf);
494 assert(r == EVBUFFER_LENGTH(buf));
495 assert(r <= count);
496 evbuffer_remove(buf, data, r);
498 ASSERT_EMPTYBUF();
500 return r;
503 static void
504 draw_progress(const char *pre, const struct progress *p)
506 struct winsize ws;
507 int i, l, w;
508 double perc;
510 perc = 100.0 * p->done / p->max;
511 if (!tty_p) {
512 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
513 return;
516 if (resized) {
517 resized = 0;
519 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
520 return;
521 tty_width = ws.ws_col;
523 w = tty_width;
525 if (pre == NULL ||
526 ((l = printf("\r%s ", pre)) == -1 || l >= w))
527 return;
529 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
530 if (w < 0) {
531 printf("%4d%%\n", (int)perc);
532 return;
535 printf("|");
537 l = w * MIN(100.0, perc) / 100.0;
538 for (i = 0; i < l; i++)
539 printf("*");
540 for (; i < w; i++)
541 printf(" ");
542 printf("|%4d%%", (int)perc);
544 fflush(stdout);
547 static int
548 fetch_fid(int fid, const char *path)
550 struct progress p = {0};
551 struct np_stat st;
552 size_t r;
553 int fd;
554 char buf[BUFSIZ];
556 do_stat(fid, &st);
557 do_open(fid, KOREAD);
559 if ((fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1) {
560 warn("can't open %s", path);
561 return -1;
564 p.max = st.length;
565 for (;;) {
566 size_t siz, off;
567 ssize_t nw;
569 r = do_read(fid, p.done, sizeof(buf), buf);
570 if (r == 0)
571 break;
573 siz = sizeof(buf);
574 for (off = 0; off < siz; off += nw)
575 if ((nw = write(fd, buf + off, siz - off)) == 0 ||
576 nw == -1)
577 err(1, "write");
579 p.done += r;
580 draw_progress(path, &p);
582 #if 0
583 /* throttle, for debugging purpose */
585 struct timespec ts = { 0, 500000000 };
586 nanosleep(&ts, NULL);
588 #endif
591 putchar('\n');
593 close(fd);
594 do_clunk(fid);
595 return 0;
598 static void
599 do_tls_connect(const char *host, const char *port)
601 int handshake;
603 if ((tlsconf = tls_config_new()) == NULL)
604 fatalx("tls_config_new");
605 tls_config_insecure_noverifycert(tlsconf);
606 tls_config_insecure_noverifyname(tlsconf);
607 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
608 fatalx("can't load certs (%s, %s)", crtpath, keypath);
610 if ((ctx = tls_client()) == NULL)
611 fatal("tls_client");
612 if (tls_configure(ctx, tlsconf) == -1)
613 fatalx("tls_configure: %s", tls_error(ctx));
615 if (tls_connect(ctx, host, port) == -1)
616 fatalx("can't connect to %s:%s: %s", host, port,
617 tls_error(ctx));
619 for (handshake = 0; !handshake;) {
620 switch (tls_handshake(ctx)) {
621 case -1:
622 fatalx("tls_handshake: %s", tls_error(ctx));
623 case 0:
624 handshake = 1;
625 break;
630 static void
631 do_ctxt_connect(const char *host, const char *port)
633 struct addrinfo hints, *res, *res0;
634 int error, saved_errno;
635 const char *cause = NULL;
637 memset(&hints, 0, sizeof(hints));
638 hints.ai_family = AF_UNSPEC;
639 hints.ai_socktype = SOCK_STREAM;
640 error = getaddrinfo(host, port, &hints, &res0);
641 if (error)
642 errx(1, "%s", gai_strerror(error));
644 sock = -1;
645 for (res = res0; res != NULL; res = res->ai_next) {
646 sock = socket(res->ai_family, res->ai_socktype,
647 res->ai_protocol);
648 if (sock == -1) {
649 cause = "socket";
650 continue;
653 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
654 cause = "connect";
655 saved_errno = errno;
656 close(sock);
657 errno = saved_errno;
658 sock = -1;
659 continue;
662 break;
665 if (sock == -1)
666 err(1, "%s", cause);
667 freeaddrinfo(res0);
670 static void
671 do_connect(const char *connspec, const char *path)
673 char *host, *colon;
674 const char *port;
676 host = xstrdup(connspec);
677 if ((colon = strchr(host, ':')) != NULL) {
678 *colon = '\0';
679 port = ++colon;
680 } else
681 port = "1337";
683 printf("connecting to %s:%s...", host, port);
684 fflush(stdout);
686 if (tls)
687 do_tls_connect(host, port);
688 else
689 do_ctxt_connect(host, port);
691 printf(" done!\n");
693 do_version();
694 do_attach(path);
696 free(host);
699 static void
700 cmd_bell(int argc, const char **argv)
702 if (argc == 0) {
703 bell = !bell;
704 if (bell)
705 puts("bell mode enabled");
706 else
707 puts("bell mode disabled");
708 return;
711 if (argc != 1)
712 goto usage;
714 if (!strcmp(*argv, "on")) {
715 bell = 1;
716 puts("bell mode enabled");
717 return;
720 if (!strcmp(*argv, "off")) {
721 bell = 0;
722 puts("bell mode disabled");
723 return;
726 usage:
727 printf("bell [on | off]\n");
730 static void
731 cmd_bye(int argc, const char **argv)
733 log_warnx("bye\n");
734 exit(0);
737 static void
738 cmd_cd(int argc, const char **argv)
740 struct qid qid;
741 int nfid;
743 if (argc != 1) {
744 printf("usage: cd remote-path\n");
745 return;
748 nfid = pwdfid+1;
749 if (walk_path(pwdfid, nfid, argv[0], &qid) == -1 ||
750 !(qid.type & QTDIR)) {
751 printf("can't cd %s\n", argv[0]);
752 do_clunk(nfid);
753 } else {
754 do_clunk(pwdfid);
755 pwdfid = nfid;
759 static void
760 cmd_get(int argc, const char **argv)
762 struct qid qid;
763 const char *l;
764 int nfid;
766 if (argc != 1 && argc != 2) {
767 printf("usage: get remote-file [local-file]\n");
768 return;
771 if (argc == 2)
772 l = argv[1];
773 else if ((l = strrchr(argv[0], '/')) != NULL)
774 l++; /* skip / */
775 else
776 l = argv[1];
778 nfid = pwdfid+1;
779 if (walk_path(pwdfid, nfid, argv[0], &qid) == -1) {
780 printf("can't fetch %s\n", argv[0]);
781 return;
784 if (qid.type != 0) {
785 printf("can't fetch %s\n", argv[0]);
786 do_clunk(nfid);
787 return;
790 fetch_fid(nfid, l);
793 static void
794 cmd_lcd(int argc, const char **argv)
796 const char *dir;
798 if (argc > 1) {
799 printf("lcd takes only one argument\n");
800 return;
803 if (argc == 1)
804 dir = *argv;
806 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
807 printf("HOME is not defined\n");
808 return;
811 if (chdir(dir) == -1)
812 printf("cd: %s: %s\n", dir, strerror(errno));
815 static void
816 cmd_lpwd(int argc, const char **argv)
818 char path[PATH_MAX];
820 if (getcwd(path, sizeof(path)) == NULL) {
821 printf("lpwd: %s\n", strerror(errno));
822 return;
825 printf("%s\n", path);
828 static void
829 cmd_ls(int argc, const char **argv)
831 struct np_stat st;
832 uint64_t off = 0;
833 uint32_t len;
834 char fmt[FMT_SCALED_STRSIZE];
836 if (argc != 0) {
837 printf("ls don't take arguments (yet)\n");
838 return;
841 dup_fid(pwdfid, 1);
842 do_open(1, KOREAD);
844 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
846 for (;;) {
847 tread(1, off, BUFSIZ);
848 do_send();
849 recv_msg();
850 expect2(Rread, iota_tag);
852 len = np_read32(buf);
853 if (len == 0)
854 break;
856 evbuffer_add_buffer(dirbuf, buf);
857 off += len;
859 ASSERT_EMPTYBUF();
862 while (EVBUFFER_LENGTH(dirbuf) != 0) {
863 if (np_read_stat(dirbuf, &st) == -1)
864 errx(1, "invalid stat struct read");
866 if (fmt_scaled(st.length, fmt) == -1)
867 strlcpy(fmt, "xxx", sizeof(fmt));
869 printf("%4s %8s %s\n", pp_qid_type(st.qid.type), fmt, st.name);
871 free(st.name);
872 free(st.uid);
873 free(st.gid);
874 free(st.muid);
877 do_clunk(1);
880 static void
881 cmd_verbose(int argc, const char **argv)
883 if (argc == 0) {
884 log_setverbose(!log_getverbose());
885 if (log_getverbose())
886 puts("verbose mode enabled");
887 else
888 puts("verbose mode disabled");
889 return;
892 if (argc != 1)
893 goto usage;
895 if (!strcmp(*argv, "on")) {
896 log_setverbose(1);
897 puts("verbose mode enabled");
898 return;
901 if (!strcmp(*argv, "off")) {
902 log_setverbose(0);
903 puts("verbose mode disabled");
904 return;
907 usage:
908 printf("verbose [on | off]\n");
911 static void
912 excmd(int argc, const char **argv)
914 struct cmd {
915 const char *name;
916 void (*fn)(int, const char **);
917 } cmds[] = {
918 {"bell", cmd_bell},
919 {"bye", cmd_bye},
920 {"cd", cmd_cd},
921 {"get", cmd_get},
922 {"lcd", cmd_lcd},
923 {"lpwd", cmd_lpwd},
924 {"ls", cmd_ls},
925 {"quit", cmd_bye},
926 {"verbose", cmd_verbose},
927 };
928 size_t i;
930 if (argc == 0)
931 return;
932 for (i = 0; i < nitems(cmds); ++i) {
933 if (!strcmp(cmds[i].name, *argv)) {
934 cmds[i].fn(argc-1, argv+1);
935 return;
939 log_warnx("unknown command %s", *argv);
942 int
943 main(int argc, char **argv)
945 int ch;
947 log_init(1, LOG_DAEMON);
948 log_setverbose(0);
949 log_procinit(getprogname());
951 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
952 switch (ch) {
953 case 'C':
954 crtpath = optarg;
955 break;
956 case 'c':
957 tls = 1;
958 break;
959 case 'K':
960 keypath = optarg;
961 break;
962 default:
963 usage(1);
966 argc -= optind;
967 argv += optind;
969 if (argc == 0)
970 usage(1);
972 if (isatty(1)) {
973 tty_p = 1;
974 resized = 1;
975 signal(SIGWINCH, tty_resized);
978 if ((evb = evbuffer_new()) == NULL)
979 fatal("evbuffer_new");
981 if ((buf = evbuffer_new()) == NULL)
982 fatal("evbuffer_new");
984 if ((dirbuf = evbuffer_new()) == NULL)
985 fatal("evbuferr_new");
987 do_connect(argv[0], argv[1]);
989 for (;;) {
990 int argc = 0;
991 char *line, *argv[16] = {0}, **ap;
993 if ((line = read_line("kamiftp> ")) == NULL)
994 break;
996 for (argc = 0, ap = argv; ap < &argv[15] &&
997 (*ap = strsep(&line, " \t")) != NULL;) {
998 if (**ap != '\0')
999 ap++, argc++;
1001 excmd(argc, (const char **)argv);
1003 if (bell) {
1004 printf("\a");
1005 fflush(stdout);
1008 free(line);
1011 printf("\n");