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>
41 #include <readline/readline.h>
42 #include <readline/history.h>
46 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
54 #define TMPFSTR "/tmp/kamiftp.XXXXXXXXXX"
55 #define TMPFSTRLEN sizeof(TMPFSTR)
63 struct tls_config *tlsconf;
67 struct evbuffer *dirbuf;
71 volatile sig_atomic_t resized;
83 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
87 readline(const char *prompt)
89 char *ch, *line = NULL;
96 linelen = getline(&line, &linesize, stdin);
100 if ((ch = strchr(line, '\n')) != NULL)
106 add_history(const char *line)
113 read_line(const char *prompt)
118 if ((line = readline(prompt)) == NULL)
120 /* XXX: trim spaces? */
131 spawn(const char *argv0, ...)
136 const char *argv[16], *last;
139 memset(argv, 0, sizeof(argv));
143 for (i = 1; i < nitems(argv); ++i) {
144 last = va_arg(ap, const char *);
151 assert(last == NULL);
153 switch (pid = fork()) {
157 execvp(argv[0], (char *const *)argv);
160 waitpid(pid, &status, 0);
165 tty_resized(int signo)
173 fprintf(stderr, "usage: %s [-c] [-C cert] [-K key] "
174 "host[:port] [path]\n", getprogname());
175 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
198 hexdump("outgoing message", EVBUFFER_DATA(evb),
199 EVBUFFER_LENGTH(evb));
201 while (EVBUFFER_LENGTH(evb) != 0) {
202 buf = EVBUFFER_DATA(evb);
203 nbytes = EVBUFFER_LENGTH(evb);
206 r = write(sock, buf, nbytes);
207 if (r == 0 || r == -1)
210 r = tls_write(ctx, buf, nbytes);
211 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
214 errx(1, "tls: %s", tls_error(ctx));
217 evbuffer_drain(evb, r);
222 mustread(void *d, size_t len)
228 r = read(sock, d, len);
229 if (r == 0 || r == -1)
232 r = tls_read(ctx, d, len);
233 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
236 errx(1, "tls: %s", tls_error(ctx));
250 mustread(&len, sizeof(len));
252 if (len < HEADERSIZE)
253 errx(1, "read message of invalid length %d", len);
255 len -= 4; /* skip the length just read */
258 l = MIN(len, sizeof(tmp));
261 evbuffer_add(buf, tmp, l);
265 hexdump("incoming packet", EVBUFFER_DATA(buf),
266 EVBUFFER_LENGTH(buf));
270 np_read64(struct evbuffer *buf)
274 evbuffer_remove(buf, &n, sizeof(n));
279 np_read32(struct evbuffer *buf)
283 evbuffer_remove(buf, &n, sizeof(n));
288 np_read16(struct evbuffer *buf)
292 evbuffer_remove(buf, &n, sizeof(n));
297 np_read8(struct evbuffer *buf)
301 evbuffer_remove(buf, &n, sizeof(n));
306 np_readstr(struct evbuffer *buf)
311 len = np_read16(buf);
312 assert(EVBUFFER_LENGTH(buf) >= len);
314 if ((str = calloc(1, len+1)) == NULL)
316 evbuffer_remove(buf, str, len);
321 np_read_qid(struct evbuffer *buf, struct qid *qid)
323 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
325 qid->type = np_read8(buf);
326 qid->vers = np_read32(buf);
327 qid->path = np_read64(buf);
331 np_read_stat(struct evbuffer *buf, struct np_stat *st)
335 memset(st, 0, sizeof(*st));
337 size = np_read16(buf);
338 if (size > EVBUFFER_LENGTH(buf))
341 st->type = np_read16(buf);
342 st->dev = np_read32(buf);
343 np_read_qid(buf, &st->qid);
344 st->mode = np_read32(buf);
345 st->atime = np_read32(buf);
346 st->mtime = np_read32(buf);
347 st->length = np_read64(buf);
348 st->name = np_readstr(buf);
349 st->uid = np_readstr(buf);
350 st->gid = np_readstr(buf);
351 st->muid = np_readstr(buf);
371 err = np_readstr(buf);
372 errx(1, "expected %s, got error %s",
373 pp_msg_type(type), err);
376 errx(1, "expected %s, got msg type %s",
377 pp_msg_type(type), pp_msg_type(t));
381 expect2(uint8_t type, uint16_t tag)
391 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
395 check(uint8_t type, uint16_t tag)
400 rtype = np_read8(buf);
401 rtag = np_read16(buf);
404 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
409 return np_readstr(buf);
411 errx(1, "expected %s, got msg type %s",
412 pp_msg_type(type), pp_msg_type(rtype));
420 tversion(VERSION9P, MSIZE9P);
423 expect2(Rversion, NOTAG);
425 msize = np_read32(buf);
426 version = np_readstr(buf);
428 if (msize > MSIZE9P || msize < 256)
429 errx(1, "got unexpected msize: %d", msize);
430 if (strcmp(version, VERSION9P))
431 errx(1, "unexpected 9p version: %s", version);
438 do_attach(const char *path)
445 if ((user = getenv("USER")) == NULL)
448 tattach(pwdfid, NOFID, user, path);
451 expect2(Rattach, iota_tag);
452 np_read_qid(buf, &qid);
458 do_open(uint32_t fid, uint8_t mode)
466 expect2(Ropen, iota_tag);
468 np_read_qid(buf, &qid);
469 iounit = np_read32(buf);
477 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
482 tcreate(fid, name, perm, mode);
485 expect2(Rcreate, iota_tag);
487 np_read_qid(buf, &qid);
488 iounit = np_read32(buf);
496 do_clunk(uint32_t fid)
501 expect2(Rclunk, iota_tag);
507 dup_fid(int fid, int nfid)
512 twalk(fid, nfid, NULL, 0);
516 if ((errstr = check(Rwalk, iota_tag)) != NULL)
519 nwqid = np_read16(buf);
528 walk_path(int fid, int newfid, const char *path, int *missing,
531 char *wnames[MAXWELEM], *p, *t, *errstr;
535 if ((p = strdup(path)) == NULL)
539 /* strip initial ./ */
540 if (t[0] == '.' && t[1] == '/')
543 for (nwname = 0; nwname < nitems(wnames) &&
544 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
545 if (*wnames[nwname] != '\0')
549 twalk(fid, newfid, (const char **)wnames, nwname);
554 if ((errstr = check(Rwalk, iota_tag)) != NULL) {
559 nwqid = np_read16(buf);
560 assert(nwqid <= nwname);
562 /* consume all qids */
563 for (i = 0; i < nwqid; ++i)
564 np_read_qid(buf, qid);
568 *missing = nwname - nwqid;
573 do_stat(int fid, struct np_stat *st)
578 expect2(Rstat, iota_tag);
580 /* eat up the first two byte length */
583 if (np_read_stat(buf, st) == -1)
584 errx(1, "invalid stat struct read");
590 do_wstat(int fid, const struct np_stat *st)
598 if ((errstr = check(Rwstat, iota_tag)) != NULL)
607 do_read(int fid, uint64_t off, uint32_t count, void *data)
611 tread(fid, off, count);
614 expect2(Rread, iota_tag);
617 assert(r == EVBUFFER_LENGTH(buf));
619 evbuffer_remove(buf, data, r);
627 do_write(int fid, uint64_t off, uint32_t count, void *data)
631 twrite(fid, off, data, count);
634 expect2(Rwrite, iota_tag);
645 draw_progress(const char *pre, const struct progress *p)
654 perc = 100.0 * p->done / p->max;
656 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
663 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
665 tty_width = ws.ws_col;
670 ((l = printf("\r%s ", pre)) == -1 || l >= w))
673 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
675 printf("%4d%%\n", (int)perc);
681 l = w * MIN(100.0, perc) / 100.0;
682 for (i = 0; i < l; i++)
686 printf("|%4d%%", (int)perc);
692 fetch_fid(int fid, int fd, const char *name)
694 static char buf[MSIZE9P];
695 struct progress p = {0};
701 do_open(fid, KOREAD);
708 len = MIN(sizeof(buf), msize);
709 len -= HEADERSIZE + 4; /* for the request' fields */
711 r = do_read(fid, p.done, len, buf);
715 for (off = 0; off < r; off += nw)
716 if ((nw = write(fd, buf + off, r - off)) == 0 ||
723 draw_progress(name, &p);
726 /* throttle, for debugging purpose */
728 struct timespec ts = { 0, 500000000 };
729 nanosleep(&ts, NULL);
742 send_fid(int fid, const char *fnam, int open_flags, int fd, const char *name)
744 static char buf[MSIZE9P];
745 struct progress p = {0};
750 if (fstat(fd, &sb) == -1)
754 do_create(fid, fnam, 0644, KOWRITE);
756 do_open(fid, open_flags | KOWRITE);
760 len = MIN(sizeof(buf), msize);
761 len -= HEADERSIZE + 4 + 4 + 8; /* for the request' fields */
763 r = read(fd, buf, len);
769 w = do_write(fid, p.done, r, buf);
772 draw_progress(name, &p);
775 /* throttle, for debugging purpose */
777 struct timespec ts = { 0, 500000000 };
778 nanosleep(&ts, NULL);
788 woc_file(int fd, const char *prompt, const char *path)
791 const char *n = NULL;
796 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
797 if (errstr != NULL && miss > 1) {
798 printf("%s: %s\n", path, errstr);
803 if (errstr != NULL || miss == 1) {
804 char p[PATH_MAX], *dn;
807 * If it's only one component missing (the file name), walk
808 * to the parent directory and try to create the file.
811 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
812 printf("path too long: %s\n", path);
817 if (!strcmp(dn, ".")) {
818 errstr = dup_fid(pwdfid, nfid);
821 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
823 if (errstr != NULL) {
824 printf("%s: %s\n", dn, errstr);
830 printf("%s: not a directory\n", dn);
834 if ((n = strrchr(path, '/')) != NULL)
843 printf("can't create %s: missing %d path component(s)\n",
848 send_fid(nfid, n, KOTRUNC, fd, prompt);
853 do_tls_connect(const char *host, const char *port)
857 if ((tlsconf = tls_config_new()) == NULL)
858 fatalx("tls_config_new");
859 tls_config_insecure_noverifycert(tlsconf);
860 tls_config_insecure_noverifyname(tlsconf);
865 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
866 fatalx("can't load certs (%s, %s)", crtpath, keypath);
868 if ((ctx = tls_client()) == NULL)
870 if (tls_configure(ctx, tlsconf) == -1)
871 fatalx("tls_configure: %s", tls_error(ctx));
873 if (tls_connect(ctx, host, port) == -1)
874 fatalx("can't connect to %s:%s: %s", host, port,
877 for (handshake = 0; !handshake;) {
878 switch (tls_handshake(ctx)) {
880 fatalx("tls_handshake: %s", tls_error(ctx));
889 do_ctxt_connect(const char *host, const char *port)
891 struct addrinfo hints, *res, *res0;
892 int error, saved_errno;
893 const char *cause = NULL;
895 memset(&hints, 0, sizeof(hints));
896 hints.ai_family = AF_UNSPEC;
897 hints.ai_socktype = SOCK_STREAM;
898 error = getaddrinfo(host, port, &hints, &res0);
900 errx(1, "%s", gai_strerror(error));
903 for (res = res0; res != NULL; res = res->ai_next) {
904 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
911 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
929 do_connect(const char *connspec, const char *path)
934 host = xstrdup(connspec);
935 if ((colon = strchr(host, ':')) != NULL) {
941 printf("connecting to %s:%s...", host, port);
945 do_tls_connect(host, port);
947 do_ctxt_connect(host, port);
958 tmp_file(char sfn[TMPFSTRLEN])
962 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
963 if ((tmpfd = mkstemp(sfn)) == -1) {
964 warn("mkstemp %s", sfn);
968 /* set the close-on-exec flag */
969 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
978 static inline const char *
999 /* unreachable, just for the compiler' happiness */
1005 prepare_wstat(struct np_stat *st)
1007 memset(st, 0xFF, sizeof(*st));
1015 cmd_bell(int argc, const char **argv)
1020 puts("bell mode enabled");
1022 puts("bell mode disabled");
1029 if (!strcmp(*argv, "on")) {
1031 puts("bell mode enabled");
1035 if (!strcmp(*argv, "off")) {
1037 puts("bell mode disabled");
1042 printf("bell [on | off]\n");
1046 cmd_bye(int argc, const char **argv)
1053 cmd_cd(int argc, const char **argv)
1060 printf("usage: cd remote-path\n");
1065 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1066 if (errstr != NULL) {
1067 printf("%s: %s\n", argv[0], errstr);
1072 if (miss != 0 || !(qid.type & QTDIR)) {
1073 printf("%s: not a directory\n", argv[0]);
1084 cmd_edit(int argc, const char **argv)
1087 int nfid, tmpfd, miss;
1088 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1092 puts("usage: edit file");
1096 if ((ed = getenv("VISUAL")) == NULL &&
1097 (ed = getenv("EDITOR")) == NULL)
1101 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1102 if (errstr != NULL) {
1103 printf("%s: %s\n", *argv, errstr);
1108 if (miss != 0 || qid.type != 0) {
1109 printf("%s: not a file\n", *argv);
1115 if ((tmpfd = tmp_file(sfn)) == -1) {
1120 strlcpy(p, *argv, sizeof(p));
1123 if (fetch_fid(nfid, tmpfd, name)) {
1124 warn("failed fetch or can't write %s", sfn);
1129 spawn(ed, sfn, NULL);
1132 * Re-open the file because it's not guaranteed that the
1133 * file descriptor tmpfd is still associated with the file
1134 * pointed by sfn: it's not uncommon for editor to write
1135 * a backup file and then rename(2) it to the file name.
1137 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1138 warn("can't open %s", sfn);
1142 woc_file(tmpfd, *argv, name);
1150 cmd_get(int argc, const char **argv)
1157 if (argc != 1 && argc != 2) {
1158 printf("usage: get remote-file [local-file]\n");
1164 else if ((l = strrchr(argv[0], '/')) != NULL)
1170 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1171 if (errstr != NULL) {
1172 printf("%s: %s\n", argv[0], errstr);
1177 if (miss != 0 || qid.type != 0) {
1178 printf("%s: not a file\n", argv[0]);
1184 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1185 warn("can't open %s", l);
1190 if (fetch_fid(nfid, fd, l) == -1)
1191 warn("write %s", l);
1196 cmd_hexdump(int argc, const char **argv)
1201 puts("hexdump mode enabled");
1203 puts("hexdump mode disabled");
1210 if (!strcmp(*argv, "on")) {
1212 puts("hexdump mode enabled");
1216 if (!strcmp(*argv, "off")) {
1218 puts("hexdump mode disabled");
1223 puts("usage: hexdump [on | off]");
1227 cmd_lcd(int argc, const char **argv)
1232 printf("usage: lcd [local-directory]\n");
1239 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1240 printf("HOME is not defined\n");
1244 if (chdir(dir) == -1)
1245 printf("cd: %s: %s\n", dir, strerror(errno));
1249 cmd_lpwd(int argc, const char **argv)
1251 char path[PATH_MAX];
1254 printf("usage: lpwd\n");
1258 if (getcwd(path, sizeof(path)) == NULL) {
1259 printf("lpwd: %s\n", strerror(errno));
1263 printf("%s\n", path);
1267 cmd_ls(int argc, const char **argv)
1276 char fmt[FMT_SCALED_STRSIZE], tim[13], *errstr;
1279 printf("ls don't take arguments (yet)\n");
1286 if ((errstr = dup_fid(pwdfid, nfid)) != NULL) {
1287 printf(".: %s\n", errstr);
1292 do_open(nfid, KOREAD);
1294 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1297 tread(nfid, off, msize - 4);
1300 expect2(Rread, iota_tag);
1302 len = np_read32(buf);
1306 evbuffer_add_buffer(dirbuf, buf);
1312 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1313 if (np_read_stat(dirbuf, &st) == -1)
1314 errx(1, "invalid stat struct read");
1316 if (fmt_scaled(st.length, fmt) == -1)
1317 strlcpy(fmt, "xxx", sizeof(fmt));
1321 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
1322 timfmt = "%b %e %R";
1324 timfmt = "%b %e %Y";
1326 if ((tm = localtime(&mtime)) == NULL ||
1327 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1328 strlcpy(tim, "unknown", sizeof(tim));
1330 if (st.qid.type & QTDIR)
1334 printf("%s", pp_perm(st.mode >> 6));
1335 printf("%s", pp_perm(st.mode >> 3));
1336 printf("%s", pp_perm(st.mode));
1337 printf(" %8s %12s %s%s\n", fmt, tim, st.name,
1338 st.qid.type & QTDIR ? "/" : "");
1350 cmd_page(int argc, const char **argv)
1353 int nfid, tmpfd, miss, r;
1354 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1358 puts("usage: page file");
1362 if ((pager = getenv("PAGER")) == NULL)
1366 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1367 if (errstr != NULL) {
1368 printf("%s: %s\n", *argv, errstr);
1373 if (miss != 0 || qid.type != 0) {
1374 printf("%s: not a file\n", *argv);
1380 if ((tmpfd = tmp_file(sfn)) == -1) {
1385 strlcpy(p, *argv, sizeof(p));
1387 if ((r = fetch_fid(nfid, tmpfd, name)) == -1)
1388 warn("write %s", sfn);
1391 spawn(pager, sfn, NULL);
1396 cmd_pipe(int argc, const char **argv)
1400 int nfid, tmpfd, miss, status;
1401 int filedes[2]; /* read end, write end */
1405 puts("usage: pipe remote-file cmd [args...]");
1410 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1411 if (errstr != NULL) {
1412 printf("%s: %s\n", *argv, errstr);
1417 if (miss != 0 || qid.type != 0) {
1418 printf("%s: not a file\n", *argv);
1424 if (pipe(filedes) == -1)
1427 switch (pid = vfork()) {
1432 if (dup2(filedes[0], 0) == -1)
1434 execvp(argv[1], (char *const *)argv + 1);
1439 if (fetch_fid(nfid, filedes[1], *argv) == -1)
1440 warnx("failed to fetch all the file");
1443 waitpid(pid, &status, 0);
1447 cmd_put(int argc, const char **argv)
1453 if (argc != 1 && argc != 2) {
1454 printf("usage: put local-file [remote-file]\n");
1460 else if ((l = strrchr(argv[0], '/')) != NULL)
1465 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1466 warn("%s", argv[0]);
1470 woc_file(fd, argv[0], l);
1475 cmd_rename(int argc, const char **argv)
1483 puts("usage: rename remote-file new-remote-name");
1488 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1489 if (errstr != NULL) {
1490 printf("%s: %s\n", argv[0], errstr);
1496 printf("%s: not such file or directory\n", argv[0]);
1501 st.name = (char *)argv[1];
1502 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1503 printf("rename: %s\n", errstr);
1511 cmd_verbose(int argc, const char **argv)
1514 log_setverbose(!log_getverbose());
1515 if (log_getverbose())
1516 puts("verbose mode enabled");
1518 puts("verbose mode disabled");
1525 if (!strcmp(*argv, "on")) {
1527 puts("verbose mode enabled");
1531 if (!strcmp(*argv, "off")) {
1533 puts("verbose mode disabled");
1538 printf("verbose [on | off]\n");
1542 excmd(int argc, const char **argv)
1546 void (*fn)(int, const char **);
1553 {"hexdump", cmd_hexdump},
1561 {"rename", cmd_rename},
1562 {"verbose", cmd_verbose},
1568 for (i = 0; i < nitems(cmds); ++i) {
1569 if (!strcmp(cmds[i].name, *argv)) {
1570 cmds[i].fn(argc-1, argv+1);
1575 log_warnx("unknown command %s", *argv);
1579 main(int argc, char **argv)
1583 log_init(1, LOG_DAEMON);
1585 log_procinit(getprogname());
1587 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
1607 if (argc == 0 || (tls && crtpath == NULL))
1610 signal(SIGPIPE, SIG_IGN);
1614 signal(SIGWINCH, tty_resized);
1617 if ((evb = evbuffer_new()) == NULL)
1618 fatal("evbuffer_new");
1620 if ((buf = evbuffer_new()) == NULL)
1621 fatal("evbuffer_new");
1623 if ((dirbuf = evbuffer_new()) == NULL)
1624 fatal("evbuferr_new");
1626 do_connect(argv[0], argv[1]);
1630 char *line, *argv[16] = {0}, **ap;
1632 if ((line = read_line("kamiftp> ")) == NULL)
1635 for (argc = 0, ap = argv; ap < &argv[15] &&
1636 (*ap = strsep(&line, " \t")) != NULL;) {
1640 excmd(argc, (const char **)argv);