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;
96 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
100 readline(const char *prompt)
102 char *ch, *line = NULL;
106 printf("%s", prompt);
109 linelen = getline(&line, &linesize, stdin);
113 if ((ch = strchr(line, '\n')) != NULL)
119 add_history(const char *line)
126 read_line(const char *prompt)
131 if ((line = readline(prompt)) == NULL)
133 /* XXX: trim spaces? */
144 spawn(const char *argv0, ...)
149 const char *argv[16], *last;
152 memset(argv, 0, sizeof(argv));
156 for (i = 1; i < nitems(argv); ++i) {
157 last = va_arg(ap, const char *);
164 assert(last == NULL);
166 switch (pid = fork()) {
170 execvp(argv[0], (char *const *)argv);
173 waitpid(pid, &status, 0);
178 tty_resized(int signo)
186 fprintf(stderr, "usage: %s [-c] [-C cert] [-K key] "
187 "host[:port] [path]\n", getprogname());
188 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
199 while (EVBUFFER_LENGTH(evb) != 0) {
200 buf = EVBUFFER_DATA(evb);
201 nbytes = EVBUFFER_LENGTH(evb);
204 r = write(sock, buf, nbytes);
205 if (r == 0 || r == -1)
208 r = tls_write(ctx, buf, nbytes);
209 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
212 errx(1, "tls: %s", tls_error(ctx));
215 evbuffer_drain(evb, r);
220 mustread(void *d, size_t len)
226 r = read(sock, d, len);
227 if (r == 0 || r == -1)
230 r = tls_read(ctx, d, len);
231 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
234 errx(1, "tls: %s", tls_error(ctx));
248 mustread(&len, sizeof(len));
250 if (len < HEADERSIZE)
251 errx(1, "read message of invalid length %d", len);
253 len -= 4; /* skip the length just read */
256 l = MIN(len, sizeof(tmp));
259 evbuffer_add(buf, tmp, l);
264 np_read64(struct evbuffer *buf)
268 evbuffer_remove(buf, &n, sizeof(n));
273 np_read32(struct evbuffer *buf)
277 evbuffer_remove(buf, &n, sizeof(n));
282 np_read16(struct evbuffer *buf)
286 evbuffer_remove(buf, &n, sizeof(n));
291 np_read8(struct evbuffer *buf)
295 evbuffer_remove(buf, &n, sizeof(n));
300 np_readstr(struct evbuffer *buf)
305 len = np_read16(buf);
306 assert(EVBUFFER_LENGTH(buf) >= len);
308 if ((str = calloc(1, len+1)) == NULL)
310 evbuffer_remove(buf, str, len);
315 np_read_qid(struct evbuffer *buf, struct qid *qid)
317 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
319 qid->type = np_read8(buf);
320 qid->vers = np_read32(buf);
321 qid->path = np_read64(buf);
325 np_read_stat(struct evbuffer *buf, struct np_stat *st)
329 memset(st, 0, sizeof(*st));
331 size = np_read16(buf);
332 if (size > EVBUFFER_LENGTH(buf))
335 st->type = np_read16(buf);
336 st->dev = np_read32(buf);
337 np_read_qid(buf, &st->qid);
338 st->mode = np_read32(buf);
339 st->atime = np_read32(buf);
340 st->mtime = np_read32(buf);
341 st->length = np_read64(buf);
342 st->name = np_readstr(buf);
343 st->uid = np_readstr(buf);
344 st->gid = np_readstr(buf);
345 st->muid = np_readstr(buf);
365 err = np_readstr(buf);
366 errx(1, "expected %s, got error %s",
367 pp_msg_type(type), err);
370 errx(1, "expected %s, got msg type %s",
371 pp_msg_type(type), pp_msg_type(t));
375 expect2(uint8_t type, uint16_t tag)
385 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
389 check(uint8_t type, uint16_t tag)
394 rtype = np_read8(buf);
395 rtag = np_read16(buf);
398 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
403 return np_readstr(buf);
405 errx(1, "expected %s, got msg type %s",
406 pp_msg_type(type), pp_msg_type(rtype));
414 tversion(VERSION9P, MSIZE9P);
417 expect2(Rversion, NOTAG);
419 msize = np_read32(buf);
420 version = np_readstr(buf);
423 errx(1, "got unexpected msize: %d", msize);
424 if (strcmp(version, VERSION9P))
425 errx(1, "unexpected 9p version: %s", version);
432 do_attach(const char *path)
439 if ((user = getenv("USER")) == NULL)
442 tattach(pwdfid, NOFID, user, path);
445 expect2(Rattach, iota_tag);
446 np_read_qid(buf, &qid);
452 do_open(uint32_t fid, uint8_t mode)
460 expect2(Ropen, iota_tag);
462 np_read_qid(buf, &qid);
463 iounit = np_read32(buf);
471 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
476 tcreate(fid, name, perm, mode);
479 expect2(Rcreate, iota_tag);
481 np_read_qid(buf, &qid);
482 iounit = np_read32(buf);
490 do_clunk(uint32_t fid)
495 expect2(Rclunk, iota_tag);
501 dup_fid(int fid, int nfid)
506 twalk(fid, nfid, NULL, 0);
510 if ((errstr = check(Rwalk, iota_tag)) != NULL)
513 nwqid = np_read16(buf);
522 walk_path(int fid, int newfid, const char *path, int *missing,
525 char *wnames[MAXWELEM], *p, *t, *errstr;
529 if ((p = strdup(path)) == NULL)
533 /* strip initial ./ */
534 if (t[0] == '.' && t[1] == '/')
537 for (nwname = 0; nwname < nitems(wnames) &&
538 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
539 if (*wnames[nwname] != '\0')
543 twalk(fid, newfid, (const char **)wnames, nwname);
548 if ((errstr = check(Rwalk, iota_tag)) != NULL)
551 nwqid = np_read16(buf);
552 assert(nwqid <= nwname);
554 /* consume all qids */
555 for (i = 0; i < nwqid; ++i)
556 np_read_qid(buf, qid);
560 *missing = nwname - nwqid;
565 do_stat(int fid, struct np_stat *st)
570 expect2(Rstat, iota_tag);
572 if (np_read_stat(buf, st) == -1)
573 errx(1, "invalid stat struct read");
579 do_read(int fid, uint64_t off, uint32_t count, void *data)
583 tread(fid, off, count);
586 expect2(Rread, iota_tag);
589 assert(r == EVBUFFER_LENGTH(buf));
591 evbuffer_remove(buf, data, r);
599 do_write(int fid, uint64_t off, uint32_t count, void *data)
603 twrite(fid, off, data, count);
606 expect2(Rwrite, iota_tag);
617 draw_progress(const char *pre, const struct progress *p)
623 perc = 100.0 * p->done / p->max;
625 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
632 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
634 tty_width = ws.ws_col;
639 ((l = printf("\r%s ", pre)) == -1 || l >= w))
642 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
644 printf("%4d%%\n", (int)perc);
650 l = w * MIN(100.0, perc) / 100.0;
651 for (i = 0; i < l; i++)
655 printf("|%4d%%", (int)perc);
661 fetch_fid(int fid, int fd, const char *name)
663 struct progress p = {0};
669 do_open(fid, KOREAD);
676 r = do_read(fid, p.done, sizeof(buf), buf);
680 for (off = 0; off < r; off += nw)
681 if ((nw = write(fd, buf + off, r - off)) == 0 ||
686 draw_progress(name, &p);
689 /* throttle, for debugging purpose */
691 struct timespec ts = { 0, 500000000 };
692 nanosleep(&ts, NULL);
703 send_fid(int fid, const char *fnam, int fd, const char *name)
705 struct progress p = {0};
711 if (fstat(fd, &sb) == -1)
715 do_create(fid, fnam, 0644, KOWRITE);
717 do_open(fid, KOWRITE);
721 r = read(fd, buf, sizeof(buf));
727 w = do_write(fid, p.done, r, buf);
730 draw_progress(name, &p);
733 /* throttle, for debugging purpose */
735 struct timespec ts = { 0, 500000000 };
736 nanosleep(&ts, NULL);
746 woc_file(int fd, const char *prompt, const char *path)
749 const char *n = NULL;
754 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
755 if (errstr != NULL && miss > 1) {
756 printf("%s: %s\n", path, errstr);
761 if (errstr != NULL || miss == 1) {
762 char p[PATH_MAX], *dn;
765 * If it's only one component missing (the file name), walk
766 * to the parent directory and try to create the file.
769 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
770 printf("path too long: %s\n", path);
775 if (!strcmp(dn, ".")) {
776 errstr = dup_fid(pwdfid, nfid);
779 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
781 if (errstr != NULL) {
782 printf("%s: %s\n", dn, errstr);
788 printf("%s: not a directory\n", dn);
792 if ((n = strrchr(path, '/')) != NULL)
801 printf("can't create %s: missing %d path component(s)\n",
806 send_fid(nfid, n, fd, prompt);
811 do_tls_connect(const char *host, const char *port)
815 if ((tlsconf = tls_config_new()) == NULL)
816 fatalx("tls_config_new");
817 tls_config_insecure_noverifycert(tlsconf);
818 tls_config_insecure_noverifyname(tlsconf);
819 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
820 fatalx("can't load certs (%s, %s)", crtpath, keypath);
822 if ((ctx = tls_client()) == NULL)
824 if (tls_configure(ctx, tlsconf) == -1)
825 fatalx("tls_configure: %s", tls_error(ctx));
827 if (tls_connect(ctx, host, port) == -1)
828 fatalx("can't connect to %s:%s: %s", host, port,
831 for (handshake = 0; !handshake;) {
832 switch (tls_handshake(ctx)) {
834 fatalx("tls_handshake: %s", tls_error(ctx));
843 do_ctxt_connect(const char *host, const char *port)
845 struct addrinfo hints, *res, *res0;
846 int error, saved_errno;
847 const char *cause = NULL;
849 memset(&hints, 0, sizeof(hints));
850 hints.ai_family = AF_UNSPEC;
851 hints.ai_socktype = SOCK_STREAM;
852 error = getaddrinfo(host, port, &hints, &res0);
854 errx(1, "%s", gai_strerror(error));
857 for (res = res0; res != NULL; res = res->ai_next) {
858 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
865 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
883 do_connect(const char *connspec, const char *path)
888 host = xstrdup(connspec);
889 if ((colon = strchr(host, ':')) != NULL) {
895 printf("connecting to %s:%s...", host, port);
899 do_tls_connect(host, port);
901 do_ctxt_connect(host, port);
912 tmp_file(char sfn[TMPFSTRLEN])
916 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
917 if ((tmpfd = mkstemp(sfn)) == -1) {
918 warn("mkstemp %s", sfn);
926 cmd_bell(int argc, const char **argv)
931 puts("bell mode enabled");
933 puts("bell mode disabled");
940 if (!strcmp(*argv, "on")) {
942 puts("bell mode enabled");
946 if (!strcmp(*argv, "off")) {
948 puts("bell mode disabled");
953 printf("bell [on | off]\n");
957 cmd_bye(int argc, const char **argv)
964 cmd_cd(int argc, const char **argv)
971 printf("usage: cd remote-path\n");
976 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
977 if (errstr != NULL) {
978 printf("%s: %s\n", argv[0], errstr);
983 if (miss != 0 || !(qid.type & QTDIR)) {
984 printf("%s: not a directory\n", argv[0]);
995 cmd_edit(int argc, const char **argv)
998 int nfid, tmpfd, miss;
999 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1003 puts("usage: edit file");
1007 if ((ed = getenv("VISUAL")) == NULL &&
1008 (ed = getenv("EDITOR")) == NULL)
1012 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1013 if (errstr != NULL) {
1014 printf("%s: %s\n", *argv, errstr);
1019 if (miss != 0 || qid.type != 0) {
1020 printf("%s: not a file\n", *argv);
1026 if ((tmpfd = tmp_file(sfn)) == -1) {
1031 strlcpy(p, *argv, sizeof(p));
1034 fetch_fid(nfid, tmpfd, name);
1037 spawn(ed, sfn, NULL);
1040 * Re-open the file because it's not guaranteed that the
1041 * file descriptor tmpfd is still associated with the file
1042 * pointed by sfn: it's not uncommon for editor to write
1043 * a backup file and then rename(2) it to the file name.
1045 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1046 warn("can't open %s", sfn);
1050 woc_file(tmpfd, *argv, name);
1058 cmd_get(int argc, const char **argv)
1065 if (argc != 1 && argc != 2) {
1066 printf("usage: get remote-file [local-file]\n");
1072 else if ((l = strrchr(argv[0], '/')) != NULL)
1078 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1079 if (errstr != NULL) {
1080 printf("%s: %s\n", argv[0], errstr);
1085 if (miss != 0 || qid.type != 0) {
1086 printf("%s: not a file\n", argv[0]);
1092 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1093 warn("can't open %s", l);
1098 fetch_fid(nfid, fd, l);
1103 cmd_lcd(int argc, const char **argv)
1108 printf("lcd takes only one argument\n");
1115 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1116 printf("HOME is not defined\n");
1120 if (chdir(dir) == -1)
1121 printf("cd: %s: %s\n", dir, strerror(errno));
1125 cmd_lpwd(int argc, const char **argv)
1127 char path[PATH_MAX];
1129 if (getcwd(path, sizeof(path)) == NULL) {
1130 printf("lpwd: %s\n", strerror(errno));
1134 printf("%s\n", path);
1138 cmd_ls(int argc, const char **argv)
1143 char fmt[FMT_SCALED_STRSIZE], *errstr;
1146 printf("ls don't take arguments (yet)\n");
1150 if ((errstr = dup_fid(pwdfid, 1)) != NULL) {
1151 printf(".: %s\n", errstr);
1158 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1161 tread(1, off, BUFSIZ);
1164 expect2(Rread, iota_tag);
1166 len = np_read32(buf);
1170 evbuffer_add_buffer(dirbuf, buf);
1176 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1177 if (np_read_stat(dirbuf, &st) == -1)
1178 errx(1, "invalid stat struct read");
1180 if (fmt_scaled(st.length, fmt) == -1)
1181 strlcpy(fmt, "xxx", sizeof(fmt));
1183 printf("%4s %8s %s\n", pp_qid_type(st.qid.type), fmt, st.name);
1195 cmd_page(int argc, const char **argv)
1198 int nfid, tmpfd, miss;
1199 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1202 puts("usage: page file");
1207 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1208 if (errstr != NULL) {
1209 printf("%s: %s\n", *argv, errstr);
1214 if (miss != 0 || qid.type != 0) {
1215 printf("%s: not a file\n", *argv);
1221 if ((tmpfd = tmp_file(sfn)) == -1) {
1226 strlcpy(p, *argv, sizeof(p));
1228 fetch_fid(nfid, tmpfd, name);
1230 spawn("less", sfn, NULL);
1235 cmd_put(int argc, const char **argv)
1241 if (argc != 1 && argc != 2) {
1242 printf("usage: put local-file [remote-file]\n");
1248 else if ((l = strrchr(argv[0], '/')) != NULL)
1253 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1254 warn("%s", argv[0]);
1258 woc_file(fd, argv[0], l);
1263 cmd_verbose(int argc, const char **argv)
1266 log_setverbose(!log_getverbose());
1267 if (log_getverbose())
1268 puts("verbose mode enabled");
1270 puts("verbose mode disabled");
1277 if (!strcmp(*argv, "on")) {
1279 puts("verbose mode enabled");
1283 if (!strcmp(*argv, "off")) {
1285 puts("verbose mode disabled");
1290 printf("verbose [on | off]\n");
1294 excmd(int argc, const char **argv)
1298 void (*fn)(int, const char **);
1311 {"verbose", cmd_verbose},
1317 for (i = 0; i < nitems(cmds); ++i) {
1318 if (!strcmp(cmds[i].name, *argv)) {
1319 cmds[i].fn(argc-1, argv+1);
1324 log_warnx("unknown command %s", *argv);
1328 main(int argc, char **argv)
1332 log_init(1, LOG_DAEMON);
1334 log_procinit(getprogname());
1336 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
1360 signal(SIGWINCH, tty_resized);
1363 if ((evb = evbuffer_new()) == NULL)
1364 fatal("evbuffer_new");
1366 if ((buf = evbuffer_new()) == NULL)
1367 fatal("evbuffer_new");
1369 if ((dirbuf = evbuffer_new()) == NULL)
1370 fatal("evbuferr_new");
1372 do_connect(argv[0], argv[1]);
1376 char *line, *argv[16] = {0}, **ap;
1378 if ((line = read_line("kamiftp> ")) == NULL)
1381 for (argc = 0, ap = argv; ap < &argv[15] &&
1382 (*ap = strsep(&line, " \t")) != NULL;) {
1386 excmd(argc, (const char **)argv);