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 "compat.h"
19 #include <sys/ioctl.h>
20 #include <sys/types.h>
21 #include <sys/socket.h>
23 #include <assert.h>
24 #include <errno.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>
37 #ifdef HAVE_READLINE
38 #include <readline/readline.h>
39 #include <readline/history.h>
40 #endif
42 #ifndef nitems
43 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
44 #endif
46 #include "9pclib.h"
47 #include "kami.h"
48 #include "utils.h"
49 #include "log.h"
51 /* flags */
52 int tls;
53 const char *crtpath;
54 const char *keypath;
56 /* state */
57 struct tls_config *tlsconf;
58 struct tls *ctx;
59 int sock;
60 struct evbuffer *buf;
61 struct evbuffer *dirbuf;
62 uint32_t msize;
63 int bell;
65 volatile sig_atomic_t resized;
66 int tty_p;
67 int tty_width;
69 struct np_stat {
70 uint16_t type;
71 uint32_t dev;
72 struct qid qid;
73 uint32_t mode;
74 uint32_t atime;
75 uint32_t mtime;
76 uint64_t length;
77 char *name;
78 char *uid;
79 char *gid;
80 char *muid;
81 };
83 struct progress {
84 uint64_t max;
85 uint64_t done;
86 };
88 int pwdfid;
90 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
92 #if !HAVE_READLINE
93 char *
94 readline(const char *prompt)
95 {
96 char *ch, *line = NULL;
97 size_t linesize = 0;
98 ssize_t linelen;
100 printf("%s", prompt);
101 fflush(stdout);
103 linelen = getline(&line, &linesize, stdin);
104 if (linelen == -1)
105 return NULL;
107 if ((ch = strchr(line, '\n')) != NULL)
108 *ch = '\0';
109 return line;
112 void
113 add_history(const char *line)
115 return;
117 #endif
119 static char *
120 read_line(const char *prompt)
122 char *line;
124 again:
125 if ((line = readline(prompt)) == NULL)
126 return NULL;
127 /* XXX: trim spaces? */
128 if (*line == '\0') {
129 free(line);
130 goto again;
133 add_history(line);
134 return line;
137 static void
138 tty_resized(int signo)
140 resized = 1;
143 static void __dead
144 usage(int ret)
146 fprintf(stderr, "usage: %s [-c] host[:port] [path]\n",
147 getprogname());
148 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
149 exit(ret);
152 static void
153 do_send(void)
155 const void *buf;
156 size_t nbytes;
157 ssize_t r;
159 while (EVBUFFER_LENGTH(evb) != 0) {
160 buf = EVBUFFER_DATA(evb);
161 nbytes = EVBUFFER_LENGTH(evb);
163 if (ctx == NULL) {
164 r = write(sock, buf, nbytes);
165 if (r == 0 || r == -1)
166 errx(1, "EOF");
167 } else {
168 r = tls_write(ctx, buf, nbytes);
169 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
170 continue;
171 if (r == -1)
172 errx(1, "tls: %s", tls_error(ctx));
175 evbuffer_drain(evb, r);
179 static void
180 mustread(void *d, size_t len)
182 ssize_t r;
184 while (len != 0) {
185 if (ctx == NULL) {
186 r = read(sock, d, len);
187 if (r == 0 || r == -1)
188 errx(1, "EOF");
189 } else {
190 r = tls_read(ctx, d, len);
191 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
192 continue;
193 if (r == -1)
194 errx(1, "tls: %s", tls_error(ctx));
197 d += r;
198 len -= r;
202 static void
203 recv_msg(void)
205 uint32_t len, l;
206 char tmp[BUFSIZ];
208 mustread(&len, sizeof(len));
209 len = le32toh(len);
210 if (len < HEADERSIZE)
211 errx(1, "read message of invalid length %d", len);
213 len -= 4; /* skip the length just read */
215 while (len != 0) {
216 l = MIN(len, sizeof(tmp));
217 mustread(tmp, l);
218 len -= l;
219 evbuffer_add(buf, tmp, l);
223 static uint64_t
224 np_read64(struct evbuffer *buf)
226 uint64_t n;
228 evbuffer_remove(buf, &n, sizeof(n));
229 return le64toh(n);
232 static uint32_t
233 np_read32(struct evbuffer *buf)
235 uint32_t n;
237 evbuffer_remove(buf, &n, sizeof(n));
238 return le32toh(n);
241 static uint16_t
242 np_read16(struct evbuffer *buf)
244 uint16_t n;
246 evbuffer_remove(buf, &n, sizeof(n));
247 return le16toh(n);
250 static uint16_t
251 np_read8(struct evbuffer *buf)
253 uint8_t n;
255 evbuffer_remove(buf, &n, sizeof(n));
256 return n;
259 static char *
260 np_readstr(struct evbuffer *buf)
262 uint16_t len;
263 char *str;
265 len = np_read16(buf);
266 assert(EVBUFFER_LENGTH(buf) >= len);
268 if ((str = calloc(1, len+1)) == NULL)
269 err(1, "calloc");
270 evbuffer_remove(buf, str, len);
271 return str;
274 static void
275 np_read_qid(struct evbuffer *buf, struct qid *qid)
277 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
279 qid->type = np_read8(buf);
280 qid->vers = np_read32(buf);
281 qid->path = np_read64(buf);
284 static int
285 np_read_stat(struct evbuffer *buf, struct np_stat *st)
287 uint16_t size;
289 memset(st, 0, sizeof(*st));
291 size = np_read16(buf);
292 if (size > EVBUFFER_LENGTH(buf))
293 return -1;
295 st->type = np_read16(buf);
296 st->dev = np_read32(buf);
297 np_read_qid(buf, &st->qid);
298 st->mode = np_read32(buf);
299 st->atime = np_read32(buf);
300 st->mtime = np_read32(buf);
301 st->length = np_read64(buf);
302 st->name = np_readstr(buf);
303 st->uid = np_readstr(buf);
304 st->gid = np_readstr(buf);
305 st->muid = np_readstr(buf);
307 return 0;
310 static void
311 expect(uint8_t type)
313 uint8_t t;
315 t = np_read8(buf);
316 if (t == type)
317 return;
319 if (t == Rerror) {
320 char *err;
322 /* skip tag */
323 np_read16(buf);
325 err = np_readstr(buf);
326 errx(1, "expected %s, got error %s",
327 pp_msg_type(type), err);
330 errx(1, "expected %s, got msg type %s",
331 pp_msg_type(type), pp_msg_type(t));
334 static void
335 expect2(uint8_t type, uint16_t tag)
337 uint16_t t;
339 expect(type);
341 t = np_read16(buf);
342 if (t == tag)
343 return;
345 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
348 static void
349 do_version(void)
351 char *version;
353 tversion(VERSION9P, MSIZE9P);
354 do_send();
355 recv_msg();
356 expect2(Rversion, NOTAG);
358 msize = np_read32(buf);
359 version = np_readstr(buf);
361 if (msize > MSIZE9P)
362 errx(1, "got unexpected msize: %d", msize);
363 if (strcmp(version, VERSION9P))
364 errx(1, "unexpected 9p version: %s", version);
366 free(version);
367 ASSERT_EMPTYBUF();
370 static void
371 do_attach(const char *path)
373 const char *user;
374 struct qid qid;
376 if (path == NULL)
377 path = "/";
378 if ((user = getenv("USER")) == NULL)
379 user = "flan";
381 tattach(pwdfid, NOFID, user, path);
382 do_send();
383 recv_msg();
384 expect2(Rattach, iota_tag);
385 np_read_qid(buf, &qid);
387 ASSERT_EMPTYBUF();
390 static uint32_t
391 do_open(uint32_t fid, uint8_t mode)
393 struct qid qid;
394 uint32_t iounit;
396 topen(fid, mode);
397 do_send();
398 recv_msg();
399 expect2(Ropen, iota_tag);
401 np_read_qid(buf, &qid);
402 iounit = np_read32(buf);
404 ASSERT_EMPTYBUF();
406 return iounit;
409 static void
410 do_clunk(uint32_t fid)
412 tclunk(fid);
413 do_send();
414 recv_msg();
415 expect2(Rclunk, iota_tag);
417 ASSERT_EMPTYBUF();
420 static void
421 dup_fid(int fid, int nfid)
423 uint16_t nwqid;
425 twalk(fid, nfid, NULL, 0);
426 do_send();
427 recv_msg();
428 expect2(Rwalk, iota_tag);
430 nwqid = np_read16(buf);
431 assert(nwqid == 0);
433 ASSERT_EMPTYBUF();
436 static int
437 walk_path(int fid, int newfid, const char *path, struct qid *qid)
439 char *wnames[MAXWELEM], *p, *t;
440 size_t nwname, i;
441 uint16_t nwqid;
443 if ((p = strdup(path)) == NULL)
444 err(1, "strdup");
445 t = p;
447 /* strip initial ./ */
448 if (t[0] == '.' && t[1] == '/')
449 t += 2;
451 for (nwname = 0; nwname < nitems(wnames) &&
452 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
453 if (*wnames[nwname] != '\0')
454 nwname++;
457 twalk(fid, newfid, (const char **)wnames, nwname);
458 do_send();
459 recv_msg();
460 expect2(Rwalk, iota_tag);
462 nwqid = np_read16(buf);
463 assert(nwqid <= nwname);
465 /* consume all qids */
466 for (i = 0; i < nwname; ++i)
467 np_read_qid(buf, qid);
469 free(p);
471 return nwqid == nwname;
474 static void
475 do_stat(int fid, struct np_stat *st)
477 tstat(fid);
478 do_send();
479 recv_msg();
480 expect2(Rstat, iota_tag);
482 if (np_read_stat(buf, st) == -1)
483 errx(1, "invalid stat struct read");
485 ASSERT_EMPTYBUF();
488 static size_t
489 do_read(int fid, uint64_t off, uint32_t count, void *data)
491 uint32_t r;
493 tread(fid, off, count);
494 do_send();
495 recv_msg();
496 expect2(Rread, iota_tag);
498 r = np_read32(buf);
499 assert(r == EVBUFFER_LENGTH(buf));
500 assert(r <= count);
501 evbuffer_remove(buf, data, r);
503 ASSERT_EMPTYBUF();
505 return r;
508 static void
509 draw_progress(const char *pre, const struct progress *p)
511 struct winsize ws;
512 int i, l, w;
513 double perc;
515 perc = 100.0 * p->done / p->max;
516 if (!tty_p) {
517 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
518 return;
521 if (resized) {
522 resized = 0;
524 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
525 return;
526 tty_width = ws.ws_col;
528 w = tty_width;
530 if (pre == NULL ||
531 ((l = printf("\r%s ", pre)) == -1 || l >= w))
532 return;
534 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
535 if (w < 0) {
536 printf("%4d%%\n", (int)perc);
537 return;
540 printf("|");
542 l = w * MIN(100.0, perc) / 100.0;
543 for (i = 0; i < l; i++)
544 printf("*");
545 for (; i < w; i++)
546 printf(" ");
547 printf("|%4d%%", (int)perc);
549 fflush(stdout);
552 static int
553 fetch_fid(int fid, const char *path)
555 struct progress p = {0};
556 struct np_stat st;
557 size_t r;
558 int fd;
559 char buf[BUFSIZ];
561 do_stat(fid, &st);
562 do_open(fid, KOREAD);
564 if ((fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1) {
565 warn("can't open %s", path);
566 return -1;
569 p.max = st.length;
570 for (;;) {
571 size_t siz, off;
572 ssize_t nw;
574 r = do_read(fid, p.done, sizeof(buf), buf);
575 if (r == 0)
576 break;
578 siz = sizeof(buf);
579 for (off = 0; off < siz; off += nw)
580 if ((nw = write(fd, buf + off, siz - off)) == 0 ||
581 nw == -1)
582 err(1, "write");
584 p.done += r;
585 draw_progress(path, &p);
587 #if 0
588 /* throttle, for debugging purpose */
590 struct timespec ts = { 0, 500000000 };
591 nanosleep(&ts, NULL);
593 #endif
596 putchar('\n');
598 close(fd);
599 do_clunk(fid);
600 return 0;
603 static void
604 do_tls_connect(const char *host, const char *port)
606 int handshake;
608 if ((tlsconf = tls_config_new()) == NULL)
609 fatalx("tls_config_new");
610 tls_config_insecure_noverifycert(tlsconf);
611 tls_config_insecure_noverifyname(tlsconf);
612 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
613 fatalx("can't load certs (%s, %s)", crtpath, keypath);
615 if ((ctx = tls_client()) == NULL)
616 fatal("tls_client");
617 if (tls_configure(ctx, tlsconf) == -1)
618 fatalx("tls_configure: %s", tls_error(ctx));
620 if (tls_connect(ctx, host, port) == -1)
621 fatalx("can't connect to %s:%s: %s", host, port,
622 tls_error(ctx));
624 for (handshake = 0; !handshake;) {
625 switch (tls_handshake(ctx)) {
626 case -1:
627 fatalx("tls_handshake: %s", tls_error(ctx));
628 case 0:
629 handshake = 1;
630 break;
635 static void
636 do_ctxt_connect(const char *host, const char *port)
638 struct addrinfo hints, *res, *res0;
639 int error, saved_errno;
640 const char *cause = NULL;
642 memset(&hints, 0, sizeof(hints));
643 hints.ai_family = AF_UNSPEC;
644 hints.ai_socktype = SOCK_STREAM;
645 error = getaddrinfo(host, port, &hints, &res0);
646 if (error)
647 errx(1, "%s", gai_strerror(error));
649 sock = -1;
650 for (res = res0; res != NULL; res = res->ai_next) {
651 sock = socket(res->ai_family, res->ai_socktype,
652 res->ai_protocol);
653 if (sock == -1) {
654 cause = "socket";
655 continue;
658 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
659 cause = "connect";
660 saved_errno = errno;
661 close(sock);
662 errno = saved_errno;
663 sock = -1;
664 continue;
667 break;
670 if (sock == -1)
671 err(1, "%s", cause);
672 freeaddrinfo(res0);
675 static void
676 do_connect(const char *connspec, const char *path)
678 char *host, *colon;
679 const char *port;
681 host = xstrdup(connspec);
682 if ((colon = strchr(host, ':')) != NULL) {
683 *colon = '\0';
684 port = ++colon;
685 } else
686 port = "1337";
688 printf("connecting to %s:%s...", host, port);
689 fflush(stdout);
691 if (tls)
692 do_tls_connect(host, port);
693 else
694 do_ctxt_connect(host, port);
696 printf(" done!\n");
698 do_version();
699 do_attach(path);
701 free(host);
704 static void
705 cmd_bell(int argc, const char **argv)
707 if (argc == 0) {
708 bell = !bell;
709 if (bell)
710 puts("bell mode enabled");
711 else
712 puts("bell mode disabled");
713 return;
716 if (argc != 1)
717 goto usage;
719 if (!strcmp(*argv, "on")) {
720 bell = 1;
721 puts("bell mode enabled");
722 return;
725 if (!strcmp(*argv, "off")) {
726 bell = 0;
727 puts("bell mode disabled");
728 return;
731 usage:
732 printf("bell [on | off]\n");
735 static void
736 cmd_bye(int argc, const char **argv)
738 log_warnx("bye\n");
739 exit(0);
742 static void
743 cmd_cd(int argc, const char **argv)
745 struct qid qid;
746 int nfid;
748 if (argc != 1) {
749 printf("usage: cd remote-path\n");
750 return;
753 nfid = pwdfid+1;
754 if (walk_path(pwdfid, nfid, argv[0], &qid) == -1 ||
755 !(qid.type & QTDIR)) {
756 printf("can't cd %s\n", argv[0]);
757 do_clunk(nfid);
758 } else {
759 do_clunk(pwdfid);
760 pwdfid = nfid;
764 static void
765 cmd_get(int argc, const char **argv)
767 struct qid qid;
768 const char *l;
769 int nfid;
771 if (argc != 1 && argc != 2) {
772 printf("usage: get remote-file [local-file]\n");
773 return;
776 if (argc == 2)
777 l = argv[1];
778 else if ((l = strrchr(argv[0], '/')) != NULL)
779 l++; /* skip / */
780 else
781 l = argv[1];
783 nfid = pwdfid+1;
784 if (walk_path(pwdfid, nfid, argv[0], &qid) == -1) {
785 printf("can't fetch %s\n", argv[0]);
786 return;
789 if (qid.type != 0) {
790 printf("can't fetch %s\n", argv[0]);
791 do_clunk(nfid);
792 return;
795 fetch_fid(nfid, l);
798 static void
799 cmd_lcd(int argc, const char **argv)
801 const char *dir;
803 if (argc > 1) {
804 printf("lcd takes only one argument\n");
805 return;
808 if (argc == 1)
809 dir = *argv;
811 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
812 printf("HOME is not defined\n");
813 return;
816 if (chdir(dir) == -1)
817 printf("cd: %s: %s\n", dir, strerror(errno));
820 static void
821 cmd_lpwd(int argc, const char **argv)
823 char path[PATH_MAX];
825 if (getcwd(path, sizeof(path)) == NULL) {
826 printf("lpwd: %s\n", strerror(errno));
827 return;
830 printf("%s\n", path);
833 static void
834 cmd_ls(int argc, const char **argv)
836 struct np_stat st;
837 uint64_t off = 0;
838 uint32_t len;
839 char fmt[FMT_SCALED_STRSIZE];
841 if (argc != 0) {
842 printf("ls don't take arguments (yet)\n");
843 return;
846 dup_fid(pwdfid, 1);
847 do_open(1, KOREAD);
849 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
851 for (;;) {
852 tread(1, off, BUFSIZ);
853 do_send();
854 recv_msg();
855 expect2(Rread, iota_tag);
857 len = np_read32(buf);
858 if (len == 0)
859 break;
861 evbuffer_add_buffer(dirbuf, buf);
862 off += len;
864 ASSERT_EMPTYBUF();
867 while (EVBUFFER_LENGTH(dirbuf) != 0) {
868 if (np_read_stat(dirbuf, &st) == -1)
869 errx(1, "invalid stat struct read");
871 if (fmt_scaled(st.length, fmt) == -1)
872 strlcpy(fmt, "xxx", sizeof(fmt));
874 printf("%4s %8s %s\n", pp_qid_type(st.qid.type), fmt, st.name);
876 free(st.name);
877 free(st.uid);
878 free(st.gid);
879 free(st.muid);
882 do_clunk(1);
885 static void
886 cmd_verbose(int argc, const char **argv)
888 if (argc == 0) {
889 log_setverbose(!log_getverbose());
890 if (log_getverbose())
891 puts("verbose mode enabled");
892 else
893 puts("verbose mode disabled");
894 return;
897 if (argc != 1)
898 goto usage;
900 if (!strcmp(*argv, "on")) {
901 log_setverbose(1);
902 puts("verbose mode enabled");
903 return;
906 if (!strcmp(*argv, "off")) {
907 log_setverbose(0);
908 puts("verbose mode disabled");
909 return;
912 usage:
913 printf("verbose [on | off]\n");
916 static void
917 excmd(int argc, const char **argv)
919 struct cmd {
920 const char *name;
921 void (*fn)(int, const char **);
922 } cmds[] = {
923 {"bell", cmd_bell},
924 {"bye", cmd_bye},
925 {"cd", cmd_cd},
926 {"get", cmd_get},
927 {"lcd", cmd_lcd},
928 {"lpwd", cmd_lpwd},
929 {"ls", cmd_ls},
930 {"quit", cmd_bye},
931 {"verbose", cmd_verbose},
932 };
933 size_t i;
935 if (argc == 0)
936 return;
937 for (i = 0; i < nitems(cmds); ++i) {
938 if (!strcmp(cmds[i].name, *argv)) {
939 cmds[i].fn(argc-1, argv+1);
940 return;
944 log_warnx("unknown command %s", *argv);
947 int
948 main(int argc, char **argv)
950 int ch;
952 log_init(1, LOG_DAEMON);
953 log_setverbose(0);
954 log_procinit(getprogname());
956 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
957 switch (ch) {
958 case 'C':
959 crtpath = optarg;
960 break;
961 case 'c':
962 tls = 1;
963 break;
964 case 'K':
965 keypath = optarg;
966 break;
967 default:
968 usage(1);
971 argc -= optind;
972 argv += optind;
974 if (argc == 0)
975 usage(1);
977 if (isatty(1)) {
978 tty_p = 1;
979 resized = 1;
980 signal(SIGWINCH, tty_resized);
983 if ((evb = evbuffer_new()) == NULL)
984 fatal("evbuffer_new");
986 if ((buf = evbuffer_new()) == NULL)
987 fatal("evbuffer_new");
989 if ((dirbuf = evbuffer_new()) == NULL)
990 fatal("evbuferr_new");
992 do_connect(argv[0], argv[1]);
994 for (;;) {
995 int argc = 0;
996 char *line, *argv[16] = {0}, **ap;
998 if ((line = read_line("kamiftp> ")) == NULL)
999 break;
1001 for (argc = 0, ap = argv; ap < &argv[15] &&
1002 (*ap = strsep(&line, " \t")) != NULL;) {
1003 if (**ap != '\0')
1004 ap++, argc++;
1006 excmd(argc, (const char **)argv);
1008 if (bell) {
1009 printf("\a");
1010 fflush(stdout);
1013 free(line);
1016 printf("\n");