2 * Copyright (c) 2021, 2022 Omar Polo <op@omarpolo.com>
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.
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.
19 #include <sys/ioctl.h>
20 #include <sys/types.h>
21 #include <sys/socket.h>
40 #include <readline/readline.h>
41 #include <readline/history.h>
45 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
59 struct tls_config *tlsconf;
63 struct evbuffer *dirbuf;
67 volatile sig_atomic_t resized;
92 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
96 readline(const char *prompt)
98 char *ch, *line = NULL;
102 printf("%s", prompt);
105 linelen = getline(&line, &linesize, stdin);
109 if ((ch = strchr(line, '\n')) != NULL)
115 add_history(const char *line)
122 read_line(const char *prompt)
127 if ((line = readline(prompt)) == NULL)
129 /* XXX: trim spaces? */
140 spawn(const char *argv0, ...)
145 const char *argv[16], *last;
148 memset(argv, 0, sizeof(argv));
152 for (i = 1; i < nitems(argv); ++i) {
153 last = va_arg(ap, const char *);
160 assert(last == NULL);
162 switch (pid = fork()) {
166 execvp(argv[0], (char *const *)argv);
169 waitpid(pid, &status, 0);
174 tty_resized(int signo)
182 fprintf(stderr, "usage: %s [-c] [-C cert] [-K key] "
183 "host[:port] [path]\n", getprogname());
184 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
195 while (EVBUFFER_LENGTH(evb) != 0) {
196 buf = EVBUFFER_DATA(evb);
197 nbytes = EVBUFFER_LENGTH(evb);
200 r = write(sock, buf, nbytes);
201 if (r == 0 || r == -1)
204 r = tls_write(ctx, buf, nbytes);
205 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
208 errx(1, "tls: %s", tls_error(ctx));
211 evbuffer_drain(evb, r);
216 mustread(void *d, size_t len)
222 r = read(sock, d, len);
223 if (r == 0 || r == -1)
226 r = tls_read(ctx, d, len);
227 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
230 errx(1, "tls: %s", tls_error(ctx));
244 mustread(&len, sizeof(len));
246 if (len < HEADERSIZE)
247 errx(1, "read message of invalid length %d", len);
249 len -= 4; /* skip the length just read */
252 l = MIN(len, sizeof(tmp));
255 evbuffer_add(buf, tmp, l);
260 np_read64(struct evbuffer *buf)
264 evbuffer_remove(buf, &n, sizeof(n));
269 np_read32(struct evbuffer *buf)
273 evbuffer_remove(buf, &n, sizeof(n));
278 np_read16(struct evbuffer *buf)
282 evbuffer_remove(buf, &n, sizeof(n));
287 np_read8(struct evbuffer *buf)
291 evbuffer_remove(buf, &n, sizeof(n));
296 np_readstr(struct evbuffer *buf)
301 len = np_read16(buf);
302 assert(EVBUFFER_LENGTH(buf) >= len);
304 if ((str = calloc(1, len+1)) == NULL)
306 evbuffer_remove(buf, str, len);
311 np_read_qid(struct evbuffer *buf, struct qid *qid)
313 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
315 qid->type = np_read8(buf);
316 qid->vers = np_read32(buf);
317 qid->path = np_read64(buf);
321 np_read_stat(struct evbuffer *buf, struct np_stat *st)
325 memset(st, 0, sizeof(*st));
327 size = np_read16(buf);
328 if (size > EVBUFFER_LENGTH(buf))
331 st->type = np_read16(buf);
332 st->dev = np_read32(buf);
333 np_read_qid(buf, &st->qid);
334 st->mode = np_read32(buf);
335 st->atime = np_read32(buf);
336 st->mtime = np_read32(buf);
337 st->length = np_read64(buf);
338 st->name = np_readstr(buf);
339 st->uid = np_readstr(buf);
340 st->gid = np_readstr(buf);
341 st->muid = np_readstr(buf);
361 err = np_readstr(buf);
362 errx(1, "expected %s, got error %s",
363 pp_msg_type(type), err);
366 errx(1, "expected %s, got msg type %s",
367 pp_msg_type(type), pp_msg_type(t));
371 expect2(uint8_t type, uint16_t tag)
381 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
385 check(uint8_t type, uint16_t tag)
390 rtype = np_read8(buf);
391 rtag = np_read16(buf);
394 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
399 return np_readstr(buf);
401 errx(1, "expected %s, got msg type %s",
402 pp_msg_type(type), pp_msg_type(rtype));
410 tversion(VERSION9P, MSIZE9P);
413 expect2(Rversion, NOTAG);
415 msize = np_read32(buf);
416 version = np_readstr(buf);
419 errx(1, "got unexpected msize: %d", msize);
420 if (strcmp(version, VERSION9P))
421 errx(1, "unexpected 9p version: %s", version);
428 do_attach(const char *path)
435 if ((user = getenv("USER")) == NULL)
438 tattach(pwdfid, NOFID, user, path);
441 expect2(Rattach, iota_tag);
442 np_read_qid(buf, &qid);
448 do_open(uint32_t fid, uint8_t mode)
456 expect2(Ropen, iota_tag);
458 np_read_qid(buf, &qid);
459 iounit = np_read32(buf);
467 do_clunk(uint32_t fid)
472 expect2(Rclunk, iota_tag);
478 dup_fid(int fid, int nfid)
482 twalk(fid, nfid, NULL, 0);
485 expect2(Rwalk, iota_tag);
487 nwqid = np_read16(buf);
494 walk_path(int fid, int newfid, const char *path, int *missing,
497 char *wnames[MAXWELEM], *p, *t, *errstr;
501 if ((p = strdup(path)) == NULL)
505 /* strip initial ./ */
506 if (t[0] == '.' && t[1] == '/')
509 for (nwname = 0; nwname < nitems(wnames) &&
510 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
511 if (*wnames[nwname] != '\0')
515 twalk(fid, newfid, (const char **)wnames, nwname);
520 if ((errstr = check(Rwalk, iota_tag)) != NULL)
523 nwqid = np_read16(buf);
524 assert(nwqid <= nwname);
526 /* consume all qids */
527 for (i = 0; i < nwname; ++i)
528 np_read_qid(buf, qid);
532 *missing = nwname - nwqid;
537 do_stat(int fid, struct np_stat *st)
542 expect2(Rstat, iota_tag);
544 if (np_read_stat(buf, st) == -1)
545 errx(1, "invalid stat struct read");
551 do_read(int fid, uint64_t off, uint32_t count, void *data)
555 tread(fid, off, count);
558 expect2(Rread, iota_tag);
561 assert(r == EVBUFFER_LENGTH(buf));
563 evbuffer_remove(buf, data, r);
571 draw_progress(const char *pre, const struct progress *p)
577 perc = 100.0 * p->done / p->max;
579 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
586 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
588 tty_width = ws.ws_col;
593 ((l = printf("\r%s ", pre)) == -1 || l >= w))
596 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
598 printf("%4d%%\n", (int)perc);
604 l = w * MIN(100.0, perc) / 100.0;
605 for (i = 0; i < l; i++)
609 printf("|%4d%%", (int)perc);
615 fetch_fid(int fid, int fd, const char *name)
617 struct progress p = {0};
623 do_open(fid, KOREAD);
630 r = do_read(fid, p.done, sizeof(buf), buf);
634 for (off = 0; off < r; off += nw)
635 if ((nw = write(fd, buf + off, r - off)) == 0 ||
640 draw_progress(name, &p);
643 /* throttle, for debugging purpose */
645 struct timespec ts = { 0, 500000000 };
646 nanosleep(&ts, NULL);
657 do_tls_connect(const char *host, const char *port)
661 if ((tlsconf = tls_config_new()) == NULL)
662 fatalx("tls_config_new");
663 tls_config_insecure_noverifycert(tlsconf);
664 tls_config_insecure_noverifyname(tlsconf);
665 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
666 fatalx("can't load certs (%s, %s)", crtpath, keypath);
668 if ((ctx = tls_client()) == NULL)
670 if (tls_configure(ctx, tlsconf) == -1)
671 fatalx("tls_configure: %s", tls_error(ctx));
673 if (tls_connect(ctx, host, port) == -1)
674 fatalx("can't connect to %s:%s: %s", host, port,
677 for (handshake = 0; !handshake;) {
678 switch (tls_handshake(ctx)) {
680 fatalx("tls_handshake: %s", tls_error(ctx));
689 do_ctxt_connect(const char *host, const char *port)
691 struct addrinfo hints, *res, *res0;
692 int error, saved_errno;
693 const char *cause = NULL;
695 memset(&hints, 0, sizeof(hints));
696 hints.ai_family = AF_UNSPEC;
697 hints.ai_socktype = SOCK_STREAM;
698 error = getaddrinfo(host, port, &hints, &res0);
700 errx(1, "%s", gai_strerror(error));
703 for (res = res0; res != NULL; res = res->ai_next) {
704 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
711 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
729 do_connect(const char *connspec, const char *path)
734 host = xstrdup(connspec);
735 if ((colon = strchr(host, ':')) != NULL) {
741 printf("connecting to %s:%s...", host, port);
745 do_tls_connect(host, port);
747 do_ctxt_connect(host, port);
758 cmd_bell(int argc, const char **argv)
763 puts("bell mode enabled");
765 puts("bell mode disabled");
772 if (!strcmp(*argv, "on")) {
774 puts("bell mode enabled");
778 if (!strcmp(*argv, "off")) {
780 puts("bell mode disabled");
785 printf("bell [on | off]\n");
789 cmd_bye(int argc, const char **argv)
796 cmd_cd(int argc, const char **argv)
803 printf("usage: cd remote-path\n");
808 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
809 if (errstr != NULL) {
810 printf("%s: %s\n", argv[0], errstr);
815 if (miss != 0 || !(qid.type & QTDIR)) {
816 printf("%s: not a directory\n", argv[0]);
826 cmd_get(int argc, const char **argv)
833 if (argc != 1 && argc != 2) {
834 printf("usage: get remote-file [local-file]\n");
840 else if ((l = strrchr(argv[0], '/')) != NULL)
846 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
847 if (errstr != NULL) {
848 printf("%s: %s\n", argv[0], errstr);
853 if (miss != 0 || qid.type != 0) {
854 printf("%s: not a file\n", argv[0]);
859 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
860 warn("can't open %s", l);
865 fetch_fid(nfid, fd, l);
870 cmd_lcd(int argc, const char **argv)
875 printf("lcd takes only one argument\n");
882 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
883 printf("HOME is not defined\n");
887 if (chdir(dir) == -1)
888 printf("cd: %s: %s\n", dir, strerror(errno));
892 cmd_lpwd(int argc, const char **argv)
896 if (getcwd(path, sizeof(path)) == NULL) {
897 printf("lpwd: %s\n", strerror(errno));
901 printf("%s\n", path);
905 cmd_ls(int argc, const char **argv)
910 char fmt[FMT_SCALED_STRSIZE];
913 printf("ls don't take arguments (yet)\n");
920 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
923 tread(1, off, BUFSIZ);
926 expect2(Rread, iota_tag);
928 len = np_read32(buf);
932 evbuffer_add_buffer(dirbuf, buf);
938 while (EVBUFFER_LENGTH(dirbuf) != 0) {
939 if (np_read_stat(dirbuf, &st) == -1)
940 errx(1, "invalid stat struct read");
942 if (fmt_scaled(st.length, fmt) == -1)
943 strlcpy(fmt, "xxx", sizeof(fmt));
945 printf("%4s %8s %s\n", pp_qid_type(st.qid.type), fmt, st.name);
957 cmd_page(int argc, const char **argv)
960 int nfid, tmpfd, miss;
961 char sfn[24], p[PATH_MAX], *name, *errstr;
964 puts("usage: page file");
969 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
970 if (errstr != NULL) {
971 printf("%s: %s\n", *argv, errstr);
976 if (miss != 0 || qid.type != 0) {
977 printf("%s: not a file\n", *argv);
982 strlcpy(sfn, "/tmp/kamiftp.XXXXXXXXXX", sizeof(sfn));
983 if ((tmpfd = mkstemp(sfn)) == -1) {
984 warn("mkstemp %s", sfn);
989 strlcpy(p, *argv, sizeof(p));
991 fetch_fid(nfid, tmpfd, name);
993 spawn("less", sfn, NULL);
998 cmd_verbose(int argc, const char **argv)
1001 log_setverbose(!log_getverbose());
1002 if (log_getverbose())
1003 puts("verbose mode enabled");
1005 puts("verbose mode disabled");
1012 if (!strcmp(*argv, "on")) {
1014 puts("verbose mode enabled");
1018 if (!strcmp(*argv, "off")) {
1020 puts("verbose mode disabled");
1025 printf("verbose [on | off]\n");
1029 excmd(int argc, const char **argv)
1033 void (*fn)(int, const char **);
1044 {"verbose", cmd_verbose},
1050 for (i = 0; i < nitems(cmds); ++i) {
1051 if (!strcmp(cmds[i].name, *argv)) {
1052 cmds[i].fn(argc-1, argv+1);
1057 log_warnx("unknown command %s", *argv);
1061 main(int argc, char **argv)
1065 log_init(1, LOG_DAEMON);
1067 log_procinit(getprogname());
1069 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
1093 signal(SIGWINCH, tty_resized);
1096 if ((evb = evbuffer_new()) == NULL)
1097 fatal("evbuffer_new");
1099 if ((buf = evbuffer_new()) == NULL)
1100 fatal("evbuffer_new");
1102 if ((dirbuf = evbuffer_new()) == NULL)
1103 fatal("evbuferr_new");
1105 do_connect(argv[0], argv[1]);
1109 char *line, *argv[16] = {0}, **ap;
1111 if ((line = read_line("kamiftp> ")) == NULL)
1114 for (argc = 0, ap = argv; ap < &argv[15] &&
1115 (*ap = strsep(&line, " \t")) != NULL;) {
1119 excmd(argc, (const char **)argv);