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");
187 hexdump("outgoing message", EVBUFFER_DATA(evb),
188 EVBUFFER_LENGTH(evb));
190 while (EVBUFFER_LENGTH(evb) != 0) {
191 buf = EVBUFFER_DATA(evb);
192 nbytes = EVBUFFER_LENGTH(evb);
195 r = write(sock, buf, nbytes);
196 if (r == 0 || r == -1)
199 r = tls_write(ctx, buf, nbytes);
200 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
203 errx(1, "tls: %s", tls_error(ctx));
206 evbuffer_drain(evb, r);
211 mustread(void *d, size_t len)
217 r = read(sock, d, len);
218 if (r == 0 || r == -1)
221 r = tls_read(ctx, d, len);
222 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
225 errx(1, "tls: %s", tls_error(ctx));
239 mustread(&len, sizeof(len));
241 if (len < HEADERSIZE)
242 errx(1, "read message of invalid length %d", len);
244 len -= 4; /* skip the length just read */
247 l = MIN(len, sizeof(tmp));
250 evbuffer_add(buf, tmp, l);
254 hexdump("incoming packet", EVBUFFER_DATA(buf),
255 EVBUFFER_LENGTH(buf));
259 np_read64(struct evbuffer *buf)
263 evbuffer_remove(buf, &n, sizeof(n));
268 np_read32(struct evbuffer *buf)
272 evbuffer_remove(buf, &n, sizeof(n));
277 np_read16(struct evbuffer *buf)
281 evbuffer_remove(buf, &n, sizeof(n));
286 np_read8(struct evbuffer *buf)
290 evbuffer_remove(buf, &n, sizeof(n));
295 np_readstr(struct evbuffer *buf)
300 len = np_read16(buf);
301 assert(EVBUFFER_LENGTH(buf) >= len);
303 if ((str = calloc(1, len+1)) == NULL)
305 evbuffer_remove(buf, str, len);
310 np_read_qid(struct evbuffer *buf, struct qid *qid)
312 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
314 qid->type = np_read8(buf);
315 qid->vers = np_read32(buf);
316 qid->path = np_read64(buf);
320 np_read_stat(struct evbuffer *buf, struct np_stat *st)
324 memset(st, 0, sizeof(*st));
326 size = np_read16(buf);
327 if (size > EVBUFFER_LENGTH(buf))
330 st->type = np_read16(buf);
331 st->dev = np_read32(buf);
332 np_read_qid(buf, &st->qid);
333 st->mode = np_read32(buf);
334 st->atime = np_read32(buf);
335 st->mtime = np_read32(buf);
336 st->length = np_read64(buf);
337 st->name = np_readstr(buf);
338 st->uid = np_readstr(buf);
339 st->gid = np_readstr(buf);
340 st->muid = np_readstr(buf);
360 err = np_readstr(buf);
361 errx(1, "expected %s, got error %s",
362 pp_msg_type(type), err);
365 errx(1, "expected %s, got msg type %s",
366 pp_msg_type(type), pp_msg_type(t));
370 expect2(uint8_t type, uint16_t tag)
380 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
384 check(uint8_t type, uint16_t tag)
389 rtype = np_read8(buf);
390 rtag = np_read16(buf);
393 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
398 return np_readstr(buf);
400 errx(1, "expected %s, got msg type %s",
401 pp_msg_type(type), pp_msg_type(rtype));
409 tversion(VERSION9P, MSIZE9P);
412 expect2(Rversion, NOTAG);
414 msize = np_read32(buf);
415 version = np_readstr(buf);
418 errx(1, "got unexpected msize: %d", msize);
419 if (strcmp(version, VERSION9P))
420 errx(1, "unexpected 9p version: %s", version);
427 do_attach(const char *path)
434 if ((user = getenv("USER")) == NULL)
437 tattach(pwdfid, NOFID, user, path);
440 expect2(Rattach, iota_tag);
441 np_read_qid(buf, &qid);
447 do_open(uint32_t fid, uint8_t mode)
455 expect2(Ropen, iota_tag);
457 np_read_qid(buf, &qid);
458 iounit = np_read32(buf);
466 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
471 tcreate(fid, name, perm, mode);
474 expect2(Rcreate, iota_tag);
476 np_read_qid(buf, &qid);
477 iounit = np_read32(buf);
485 do_clunk(uint32_t fid)
490 expect2(Rclunk, iota_tag);
496 dup_fid(int fid, int nfid)
501 twalk(fid, nfid, NULL, 0);
505 if ((errstr = check(Rwalk, iota_tag)) != NULL)
508 nwqid = np_read16(buf);
517 walk_path(int fid, int newfid, const char *path, int *missing,
520 char *wnames[MAXWELEM], *p, *t, *errstr;
524 if ((p = strdup(path)) == NULL)
528 /* strip initial ./ */
529 if (t[0] == '.' && t[1] == '/')
532 for (nwname = 0; nwname < nitems(wnames) &&
533 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
534 if (*wnames[nwname] != '\0')
538 twalk(fid, newfid, (const char **)wnames, nwname);
543 if ((errstr = check(Rwalk, iota_tag)) != NULL)
546 nwqid = np_read16(buf);
547 assert(nwqid <= nwname);
549 /* consume all qids */
550 for (i = 0; i < nwqid; ++i)
551 np_read_qid(buf, qid);
555 *missing = nwname - nwqid;
560 do_stat(int fid, struct np_stat *st)
565 expect2(Rstat, iota_tag);
567 if (np_read_stat(buf, st) == -1)
568 errx(1, "invalid stat struct read");
574 do_wstat(int fid, const struct np_stat *st)
582 if ((errstr = check(Rwstat, iota_tag)) != NULL)
591 do_read(int fid, uint64_t off, uint32_t count, void *data)
595 tread(fid, off, count);
598 expect2(Rread, iota_tag);
601 assert(r == EVBUFFER_LENGTH(buf));
603 evbuffer_remove(buf, data, r);
611 do_write(int fid, uint64_t off, uint32_t count, void *data)
615 twrite(fid, off, data, count);
618 expect2(Rwrite, iota_tag);
629 draw_progress(const char *pre, const struct progress *p)
638 perc = 100.0 * p->done / p->max;
640 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
647 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
649 tty_width = ws.ws_col;
654 ((l = printf("\r%s ", pre)) == -1 || l >= w))
657 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
659 printf("%4d%%\n", (int)perc);
665 l = w * MIN(100.0, perc) / 100.0;
666 for (i = 0; i < l; i++)
670 printf("|%4d%%", (int)perc);
676 fetch_fid(int fid, int fd, const char *name)
678 struct progress p = {0};
684 do_open(fid, KOREAD);
691 r = do_read(fid, p.done, sizeof(buf), buf);
695 for (off = 0; off < r; off += nw)
696 if ((nw = write(fd, buf + off, r - off)) == 0 ||
701 draw_progress(name, &p);
704 /* throttle, for debugging purpose */
706 struct timespec ts = { 0, 500000000 };
707 nanosleep(&ts, NULL);
718 send_fid(int fid, const char *fnam, int fd, const char *name)
720 struct progress p = {0};
726 if (fstat(fd, &sb) == -1)
730 do_create(fid, fnam, 0644, KOWRITE);
732 do_open(fid, KOWRITE);
736 r = read(fd, buf, sizeof(buf));
742 w = do_write(fid, p.done, r, buf);
745 draw_progress(name, &p);
748 /* throttle, for debugging purpose */
750 struct timespec ts = { 0, 500000000 };
751 nanosleep(&ts, NULL);
761 woc_file(int fd, const char *prompt, const char *path)
764 const char *n = NULL;
769 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
770 if (errstr != NULL && miss > 1) {
771 printf("%s: %s\n", path, errstr);
776 if (errstr != NULL || miss == 1) {
777 char p[PATH_MAX], *dn;
780 * If it's only one component missing (the file name), walk
781 * to the parent directory and try to create the file.
784 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
785 printf("path too long: %s\n", path);
790 if (!strcmp(dn, ".")) {
791 errstr = dup_fid(pwdfid, nfid);
794 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
796 if (errstr != NULL) {
797 printf("%s: %s\n", dn, errstr);
803 printf("%s: not a directory\n", dn);
807 if ((n = strrchr(path, '/')) != NULL)
816 printf("can't create %s: missing %d path component(s)\n",
821 send_fid(nfid, n, fd, prompt);
826 do_tls_connect(const char *host, const char *port)
830 if ((tlsconf = tls_config_new()) == NULL)
831 fatalx("tls_config_new");
832 tls_config_insecure_noverifycert(tlsconf);
833 tls_config_insecure_noverifyname(tlsconf);
834 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
835 fatalx("can't load certs (%s, %s)", crtpath, keypath);
837 if ((ctx = tls_client()) == NULL)
839 if (tls_configure(ctx, tlsconf) == -1)
840 fatalx("tls_configure: %s", tls_error(ctx));
842 if (tls_connect(ctx, host, port) == -1)
843 fatalx("can't connect to %s:%s: %s", host, port,
846 for (handshake = 0; !handshake;) {
847 switch (tls_handshake(ctx)) {
849 fatalx("tls_handshake: %s", tls_error(ctx));
858 do_ctxt_connect(const char *host, const char *port)
860 struct addrinfo hints, *res, *res0;
861 int error, saved_errno;
862 const char *cause = NULL;
864 memset(&hints, 0, sizeof(hints));
865 hints.ai_family = AF_UNSPEC;
866 hints.ai_socktype = SOCK_STREAM;
867 error = getaddrinfo(host, port, &hints, &res0);
869 errx(1, "%s", gai_strerror(error));
872 for (res = res0; res != NULL; res = res->ai_next) {
873 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
880 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
898 do_connect(const char *connspec, const char *path)
903 host = xstrdup(connspec);
904 if ((colon = strchr(host, ':')) != NULL) {
910 printf("connecting to %s:%s...", host, port);
914 do_tls_connect(host, port);
916 do_ctxt_connect(host, port);
927 tmp_file(char sfn[TMPFSTRLEN])
931 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
932 if ((tmpfd = mkstemp(sfn)) == -1) {
933 warn("mkstemp %s", sfn);
937 /* set the close-on-exec flag */
938 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
947 static inline const char *
968 /* unreachable, just for the compiler' happiness */
974 prepare_wstat(struct np_stat *st)
976 memset(st, 0xFF, sizeof(*st));
984 cmd_bell(int argc, const char **argv)
989 puts("bell mode enabled");
991 puts("bell mode disabled");
998 if (!strcmp(*argv, "on")) {
1000 puts("bell mode enabled");
1004 if (!strcmp(*argv, "off")) {
1006 puts("bell mode disabled");
1011 printf("bell [on | off]\n");
1015 cmd_bye(int argc, const char **argv)
1022 cmd_cd(int argc, const char **argv)
1029 printf("usage: cd remote-path\n");
1034 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1035 if (errstr != NULL) {
1036 printf("%s: %s\n", argv[0], errstr);
1041 if (miss != 0 || !(qid.type & QTDIR)) {
1042 printf("%s: not a directory\n", argv[0]);
1053 cmd_edit(int argc, const char **argv)
1056 int nfid, tmpfd, miss;
1057 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1061 puts("usage: edit file");
1065 if ((ed = getenv("VISUAL")) == NULL &&
1066 (ed = getenv("EDITOR")) == NULL)
1070 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1071 if (errstr != NULL) {
1072 printf("%s: %s\n", *argv, errstr);
1077 if (miss != 0 || qid.type != 0) {
1078 printf("%s: not a file\n", *argv);
1084 if ((tmpfd = tmp_file(sfn)) == -1) {
1089 strlcpy(p, *argv, sizeof(p));
1092 fetch_fid(nfid, tmpfd, name);
1095 spawn(ed, sfn, NULL);
1098 * Re-open the file because it's not guaranteed that the
1099 * file descriptor tmpfd is still associated with the file
1100 * pointed by sfn: it's not uncommon for editor to write
1101 * a backup file and then rename(2) it to the file name.
1103 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1104 warn("can't open %s", sfn);
1108 woc_file(tmpfd, *argv, name);
1116 cmd_get(int argc, const char **argv)
1123 if (argc != 1 && argc != 2) {
1124 printf("usage: get remote-file [local-file]\n");
1130 else if ((l = strrchr(argv[0], '/')) != NULL)
1136 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1137 if (errstr != NULL) {
1138 printf("%s: %s\n", argv[0], errstr);
1143 if (miss != 0 || qid.type != 0) {
1144 printf("%s: not a file\n", argv[0]);
1150 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1151 warn("can't open %s", l);
1156 fetch_fid(nfid, fd, l);
1161 cmd_hexdump(int argc, const char **argv)
1166 puts("hexdump mode enabled");
1168 puts("hexdump mode disabled");
1175 if (!strcmp(*argv, "on")) {
1177 puts("hexdump mode enabled");
1181 if (!strcmp(*argv, "off")) {
1183 puts("hexdump mode disabled");
1188 puts("usage: hexdump [on | off]");
1192 cmd_lcd(int argc, const char **argv)
1197 printf("usage: lcd [local-directory]\n");
1204 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1205 printf("HOME is not defined\n");
1209 if (chdir(dir) == -1)
1210 printf("cd: %s: %s\n", dir, strerror(errno));
1214 cmd_lpwd(int argc, const char **argv)
1216 char path[PATH_MAX];
1219 printf("usage: lpwd\n");
1223 if (getcwd(path, sizeof(path)) == NULL) {
1224 printf("lpwd: %s\n", strerror(errno));
1228 printf("%s\n", path);
1232 cmd_ls(int argc, const char **argv)
1240 char fmt[FMT_SCALED_STRSIZE], tim[13], *errstr;
1243 printf("ls don't take arguments (yet)\n");
1249 if ((errstr = dup_fid(pwdfid, 1)) != NULL) {
1250 printf(".: %s\n", errstr);
1257 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1260 tread(1, off, BUFSIZ);
1263 expect2(Rread, iota_tag);
1265 len = np_read32(buf);
1269 evbuffer_add_buffer(dirbuf, buf);
1275 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1276 if (np_read_stat(dirbuf, &st) == -1)
1277 errx(1, "invalid stat struct read");
1279 if (fmt_scaled(st.length, fmt) == -1)
1280 strlcpy(fmt, "xxx", sizeof(fmt));
1284 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
1285 timfmt = "%b %e %R";
1287 timfmt = "%b %e %Y";
1289 if ((tm = localtime(&mtime)) == NULL ||
1290 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1291 strlcpy(tim, "unknown", sizeof(tim));
1293 if (st.qid.type & QTDIR)
1297 printf("%s", pp_perm(st.mode >> 6));
1298 printf("%s", pp_perm(st.mode >> 3));
1299 printf("%s", pp_perm(st.mode));
1300 printf(" %8s %12s %s%s\n", fmt, tim, st.name,
1301 st.qid.type & QTDIR ? "/" : "");
1313 cmd_page(int argc, const char **argv)
1316 int nfid, tmpfd, miss;
1317 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1321 puts("usage: page file");
1325 if ((pager = getenv("PAGER")) == NULL)
1329 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1330 if (errstr != NULL) {
1331 printf("%s: %s\n", *argv, errstr);
1336 if (miss != 0 || qid.type != 0) {
1337 printf("%s: not a file\n", *argv);
1343 if ((tmpfd = tmp_file(sfn)) == -1) {
1348 strlcpy(p, *argv, sizeof(p));
1350 fetch_fid(nfid, tmpfd, name);
1352 spawn(pager, sfn, NULL);
1357 cmd_put(int argc, const char **argv)
1363 if (argc != 1 && argc != 2) {
1364 printf("usage: put local-file [remote-file]\n");
1370 else if ((l = strrchr(argv[0], '/')) != NULL)
1375 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1376 warn("%s", argv[0]);
1380 woc_file(fd, argv[0], l);
1385 cmd_rename(int argc, const char **argv)
1393 puts("usage: rename remote-file new-remote-name");
1398 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1399 if (errstr != NULL) {
1400 printf("%s: %s\n", argv[0], errstr);
1406 printf("%s: not such file or directory\n", argv[0]);
1411 st.name = (char *)argv[1];
1412 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1413 printf("rename: %s\n", errstr);
1421 cmd_verbose(int argc, const char **argv)
1424 log_setverbose(!log_getverbose());
1425 if (log_getverbose())
1426 puts("verbose mode enabled");
1428 puts("verbose mode disabled");
1435 if (!strcmp(*argv, "on")) {
1437 puts("verbose mode enabled");
1441 if (!strcmp(*argv, "off")) {
1443 puts("verbose mode disabled");
1448 printf("verbose [on | off]\n");
1452 excmd(int argc, const char **argv)
1456 void (*fn)(int, const char **);
1463 {"hexdump", cmd_hexdump},
1470 {"rename", cmd_rename},
1471 {"verbose", cmd_verbose},
1477 for (i = 0; i < nitems(cmds); ++i) {
1478 if (!strcmp(cmds[i].name, *argv)) {
1479 cmds[i].fn(argc-1, argv+1);
1484 log_warnx("unknown command %s", *argv);
1488 main(int argc, char **argv)
1492 log_init(1, LOG_DAEMON);
1494 log_procinit(getprogname());
1496 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
1520 signal(SIGWINCH, tty_resized);
1523 if ((evb = evbuffer_new()) == NULL)
1524 fatal("evbuffer_new");
1526 if ((buf = evbuffer_new()) == NULL)
1527 fatal("evbuffer_new");
1529 if ((dirbuf = evbuffer_new()) == NULL)
1530 fatal("evbuferr_new");
1532 do_connect(argv[0], argv[1]);
1536 char *line, *argv[16] = {0}, **ap;
1538 if ((line = read_line("kamiftp> ")) == NULL)
1541 for (argc = 0, ap = argv; ap < &argv[15] &&
1542 (*ap = strsep(&line, " \t")) != NULL;) {
1546 excmd(argc, (const char **)argv);