Blob


1 /*
2 * Copyright (c) 2021, 2022 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>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <assert.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <inttypes.h>
29 #include <netdb.h>
30 #include <libgen.h>
31 #include <limits.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <syslog.h>
37 #include <tls.h>
38 #include <unistd.h>
40 #ifdef HAVE_READLINE
41 #include <readline/readline.h>
42 #include <readline/history.h>
43 #endif
45 #ifndef nitems
46 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
47 #endif
49 #include "kami.h"
50 #include "utils.h"
51 #include "log.h"
52 #include "9pclib.h"
54 #define TMPFSTR "/tmp/kamiftp.XXXXXXXXXX"
55 #define TMPFSTRLEN sizeof(TMPFSTR)
57 /* flags */
58 int tls;
59 const char *crtpath;
60 const char *keypath;
62 char *user;
63 char *host;
64 char *port;
66 /* state */
67 FILE *fp;
68 struct evbuffer *buf;
69 struct evbuffer *dirbuf;
70 uint32_t msize;
71 int bell;
73 volatile sig_atomic_t resized;
74 int tty_p;
75 int tty_width;
76 int xdump;
78 struct progress {
79 uint64_t max;
80 uint64_t done;
81 };
83 int pwdfid;
85 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
87 #if !HAVE_READLINE
88 char *
89 readline(const char *prompt)
90 {
91 char *ch, *line = NULL;
92 size_t linesize = 0;
93 ssize_t linelen;
95 printf("%s", prompt);
96 fflush(stdout);
98 linelen = getline(&line, &linesize, stdin);
99 if (linelen == -1)
100 return NULL;
102 if ((ch = strchr(line, '\n')) != NULL)
103 *ch = '\0';
104 return line;
107 void
108 add_history(const char *line)
110 return;
112 #endif
114 static char *
115 read_line(const char *prompt)
117 char *line;
119 again:
120 if ((line = readline(prompt)) == NULL)
121 return NULL;
122 /* XXX: trim spaces? */
123 if (*line == '\0') {
124 free(line);
125 goto again;
128 add_history(line);
129 return line;
132 static void
133 spawn(const char *argv0, ...)
135 pid_t pid;
136 size_t i;
137 int status;
138 const char *argv[16], *last;
139 va_list ap;
141 memset(argv, 0, sizeof(argv));
143 va_start(ap, argv0);
144 argv[0] = argv0;
145 for (i = 1; i < nitems(argv); ++i) {
146 last = va_arg(ap, const char *);
147 if (last == NULL)
148 break;
149 argv[i] = last;
151 va_end(ap);
153 assert(last == NULL);
155 switch (pid = fork()) {
156 case -1:
157 err(1, "fork");
158 case 0: /* child */
159 execvp(argv[0], (char *const *)argv);
160 err(1, "execvp");
161 default:
162 waitpid(pid, &status, 0);
166 static int
167 stdio_tls_write(void *arg, const char *buf, int len)
169 struct tls *ctx = arg;
170 ssize_t ret;
172 do {
173 ret = tls_write(ctx, buf, len);
174 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
176 if (ret == -1)
177 warn("tls_write: %s", tls_error(ctx));
179 return ret;
182 static int
183 stdio_tls_read(void *arg, char *buf, int len)
185 struct tls *ctx = arg;
186 ssize_t ret;
188 do {
189 ret = tls_read(ctx, buf, len);
190 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
192 if (ret == -1)
193 warn("tls_read: %s", tls_error(ctx));
195 return ret;
198 static int
199 stdio_tls_close(void *arg)
201 struct tls *ctx = arg;
202 int ret;
204 do {
205 ret = tls_close(ctx);
206 } while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
208 return ret;
211 static void
212 tty_resized(int signo)
214 resized = 1;
217 static void __dead
218 usage(int ret)
220 fprintf(stderr, "usage: %s [-c] [-C cert] [-K key] "
221 "host[:port] [path]\n", getprogname());
222 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
223 exit(ret);
226 static int
227 nextfid(void)
229 uint32_t i;
231 for (i = 0; ; ++i) {
232 if (i != pwdfid)
233 return i;
237 static void
238 do_send(void)
240 size_t r;
242 if (xdump)
243 hexdump("outgoing message", EVBUFFER_DATA(evb),
244 EVBUFFER_LENGTH(evb));
246 while (EVBUFFER_LENGTH(evb) != 0) {
247 r = fwrite(EVBUFFER_DATA(evb), 1, EVBUFFER_LENGTH(evb), fp);
248 if (r == 0)
249 fatalx("unexpected EOF");
250 evbuffer_drain(evb, r);
254 static void
255 mustread(void *d, size_t len)
257 size_t r;
259 r = fread(d, 1, len, fp);
260 if (r != len)
261 errx(1, "unexpected EOF");
264 static void
265 recv_msg(void)
267 size_t r;
268 uint32_t len, l;
269 char tmp[BUFSIZ];
271 r = fread(&len, 1, sizeof(len), fp);
272 if (r != sizeof(len))
273 errx(1, "unexpected EOF");
275 len = le32toh(len);
276 if (len < HEADERSIZE)
277 errx(1, "read message of invalid length %d", len);
279 len -= 4; /* skip the length just read */
281 while (len != 0) {
282 l = MIN(len, sizeof(tmp));
284 r = fread(tmp, 1, l, fp);
285 if (r != l)
286 errx(1, "unexpected EOF");
287 len -= r;
288 evbuffer_add(buf, tmp, r);
291 if (xdump)
292 hexdump("incoming packet", EVBUFFER_DATA(buf),
293 EVBUFFER_LENGTH(buf));
296 static uint64_t
297 np_read64(struct evbuffer *buf)
299 uint64_t n;
301 evbuffer_remove(buf, &n, sizeof(n));
302 return le64toh(n);
305 static uint32_t
306 np_read32(struct evbuffer *buf)
308 uint32_t n;
310 evbuffer_remove(buf, &n, sizeof(n));
311 return le32toh(n);
314 static uint16_t
315 np_read16(struct evbuffer *buf)
317 uint16_t n;
319 evbuffer_remove(buf, &n, sizeof(n));
320 return le16toh(n);
323 static uint16_t
324 np_read8(struct evbuffer *buf)
326 uint8_t n;
328 evbuffer_remove(buf, &n, sizeof(n));
329 return n;
332 static char *
333 np_readstr(struct evbuffer *buf)
335 uint16_t len;
336 char *str;
338 len = np_read16(buf);
339 assert(EVBUFFER_LENGTH(buf) >= len);
341 if ((str = calloc(1, len+1)) == NULL)
342 err(1, "calloc");
343 evbuffer_remove(buf, str, len);
344 return str;
347 static void
348 np_read_qid(struct evbuffer *buf, struct qid *qid)
350 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
352 qid->type = np_read8(buf);
353 qid->vers = np_read32(buf);
354 qid->path = np_read64(buf);
357 static int
358 np_read_stat(struct evbuffer *buf, struct np_stat *st)
360 uint16_t size;
362 memset(st, 0, sizeof(*st));
364 size = np_read16(buf);
365 if (size > EVBUFFER_LENGTH(buf))
366 return -1;
368 st->type = np_read16(buf);
369 st->dev = np_read32(buf);
370 np_read_qid(buf, &st->qid);
371 st->mode = np_read32(buf);
372 st->atime = np_read32(buf);
373 st->mtime = np_read32(buf);
374 st->length = np_read64(buf);
375 st->name = np_readstr(buf);
376 st->uid = np_readstr(buf);
377 st->gid = np_readstr(buf);
378 st->muid = np_readstr(buf);
380 return 0;
383 static void
384 expect(uint8_t type)
386 uint8_t t;
388 t = np_read8(buf);
389 if (t == type)
390 return;
392 if (t == Rerror) {
393 char *err;
395 /* skip tag */
396 np_read16(buf);
398 err = np_readstr(buf);
399 errx(1, "expected %s, got error %s",
400 pp_msg_type(type), err);
403 errx(1, "expected %s, got msg type %s",
404 pp_msg_type(type), pp_msg_type(t));
407 static void
408 expect2(uint8_t type, uint16_t tag)
410 uint16_t t;
412 expect(type);
414 t = np_read16(buf);
415 if (t == tag)
416 return;
418 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
421 static char *
422 check(uint8_t type, uint16_t tag)
424 uint16_t rtag;
425 uint8_t rtype;
427 rtype = np_read8(buf);
428 rtag = np_read16(buf);
429 if (rtype == type) {
430 if (rtag != tag)
431 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
432 return NULL;
435 if (rtype == Rerror)
436 return np_readstr(buf);
438 errx(1, "expected %s, got msg type %s",
439 pp_msg_type(type), pp_msg_type(rtype));
442 static void
443 do_version(void)
445 char *version;
447 tversion(VERSION9P, MSIZE9P);
448 do_send();
449 recv_msg();
450 expect2(Rversion, NOTAG);
452 msize = np_read32(buf);
453 version = np_readstr(buf);
455 if (msize > MSIZE9P || msize < 256)
456 errx(1, "got unexpected msize: %d", msize);
457 if (strcmp(version, VERSION9P))
458 errx(1, "unexpected 9p version: %s", version);
460 free(version);
461 ASSERT_EMPTYBUF();
464 static void
465 do_attach(const char *path)
467 struct qid qid;
469 if (path == NULL)
470 path = "/";
472 tattach(pwdfid, NOFID, user, path);
473 do_send();
474 recv_msg();
475 expect2(Rattach, iota_tag);
476 np_read_qid(buf, &qid);
478 ASSERT_EMPTYBUF();
481 static uint32_t
482 do_open(uint32_t fid, uint8_t mode)
484 struct qid qid;
485 uint32_t iounit;
487 topen(fid, mode);
488 do_send();
489 recv_msg();
490 expect2(Ropen, iota_tag);
492 np_read_qid(buf, &qid);
493 iounit = np_read32(buf);
495 ASSERT_EMPTYBUF();
497 return iounit;
500 static uint32_t
501 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
503 struct qid qid;
504 uint32_t iounit;
506 tcreate(fid, name, perm, mode);
507 do_send();
508 recv_msg();
509 expect2(Rcreate, iota_tag);
511 np_read_qid(buf, &qid);
512 iounit = np_read32(buf);
514 ASSERT_EMPTYBUF();
516 return iounit;
519 static void
520 do_clunk(uint32_t fid)
522 tclunk(fid);
523 do_send();
524 recv_msg();
525 expect2(Rclunk, iota_tag);
527 ASSERT_EMPTYBUF();
530 static char *
531 dup_fid(int fid, int nfid)
533 uint16_t nwqid;
534 char *errstr;
536 twalk(fid, nfid, NULL, 0);
537 do_send();
538 recv_msg();
540 if ((errstr = check(Rwalk, iota_tag)) != NULL)
541 return errstr;
543 nwqid = np_read16(buf);
544 assert(nwqid == 0);
546 ASSERT_EMPTYBUF();
548 return NULL;
551 static char *
552 walk_path(int fid, int newfid, const char *path, int *missing,
553 struct qid *qid)
555 char *wnames[MAXWELEM], *p, *t, *errstr;
556 size_t nwname, i;
557 uint16_t nwqid;
559 if ((p = strdup(path)) == NULL)
560 err(1, "strdup");
561 t = p;
563 /* strip initial ./ */
564 if (t[0] == '.' && t[1] == '/')
565 t += 2;
567 for (nwname = 0; nwname < nitems(wnames) &&
568 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
569 if (*wnames[nwname] != '\0')
570 nwname++;
573 twalk(fid, newfid, (const char **)wnames, nwname);
574 do_send();
575 recv_msg();
577 *missing = nwname;
578 if ((errstr = check(Rwalk, iota_tag)) != NULL) {
579 free(p);
580 return errstr;
583 nwqid = np_read16(buf);
584 assert(nwqid <= nwname);
586 /* consume all qids */
587 for (i = 0; i < nwqid; ++i)
588 np_read_qid(buf, qid);
590 free(p);
592 *missing = nwname - nwqid;
593 return NULL;
596 static void
597 do_stat(int fid, struct np_stat *st)
599 tstat(fid);
600 do_send();
601 recv_msg();
602 expect2(Rstat, iota_tag);
604 /* eat up the first two byte length */
605 np_read16(buf);
607 if (np_read_stat(buf, st) == -1)
608 errx(1, "invalid stat struct read");
610 ASSERT_EMPTYBUF();
613 static char *
614 do_wstat(int fid, const struct np_stat *st)
616 char *errstr;
618 twstat(fid, st);
619 do_send();
620 recv_msg();
622 if ((errstr = check(Rwstat, iota_tag)) != NULL)
623 return errstr;
625 ASSERT_EMPTYBUF();
627 return NULL;
630 static size_t
631 do_read(int fid, uint64_t off, uint32_t count, void *data)
633 uint32_t r;
635 tread(fid, off, count);
636 do_send();
637 recv_msg();
638 expect2(Rread, iota_tag);
640 r = np_read32(buf);
641 assert(r == EVBUFFER_LENGTH(buf));
642 assert(r <= count);
643 evbuffer_remove(buf, data, r);
645 ASSERT_EMPTYBUF();
647 return r;
650 static size_t
651 do_write(int fid, uint64_t off, uint32_t count, void *data)
653 uint32_t r;
655 twrite(fid, off, data, count);
656 do_send();
657 recv_msg();
658 expect2(Rwrite, iota_tag);
660 r = np_read32(buf);
661 assert(r <= count);
663 ASSERT_EMPTYBUF();
665 return r;
668 static void
669 draw_progress(const char *pre, const struct progress *p)
671 struct winsize ws;
672 int i, l, w;
673 double perc;
675 if (xdump)
676 return;
678 perc = 100.0 * p->done / p->max;
679 if (!tty_p) {
680 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
681 return;
684 if (resized) {
685 resized = 0;
687 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
688 return;
689 tty_width = ws.ws_col;
691 w = tty_width;
693 if (pre == NULL ||
694 ((l = printf("\r%s ", pre)) == -1 || l >= w))
695 return;
697 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
698 if (w < 0) {
699 printf("%4d%%\n", (int)perc);
700 return;
703 printf("|");
705 l = w * MIN(100.0, perc) / 100.0;
706 for (i = 0; i < l; i++)
707 printf("*");
708 for (; i < w; i++)
709 printf(" ");
710 printf("|%4d%%", (int)perc);
712 fflush(stdout);
715 static int
716 fetch_fid(int fid, int fd, const char *name)
718 static char buf[MSIZE9P];
719 struct progress p = {0};
720 struct np_stat st;
721 size_t r;
722 int ret = 0;
724 do_stat(fid, &st);
725 do_open(fid, KOREAD);
727 p.max = st.length;
728 for (;;) {
729 size_t len, off;
730 ssize_t nw;
732 len = MIN(sizeof(buf), msize);
733 len -= IOHDRSZ; /* for the request' fields */
735 r = do_read(fid, p.done, len, buf);
736 if (r == 0)
737 break;
739 for (off = 0; off < r; off += nw)
740 if ((nw = write(fd, buf + off, r - off)) == 0 ||
741 nw == -1) {
742 ret = -1;
743 goto end;
746 p.done += r;
747 draw_progress(name, &p);
749 #if 0
750 /* throttle, for debugging purpose */
752 struct timespec ts = { 0, 500000000 };
753 nanosleep(&ts, NULL);
755 #endif
758 end:
759 putchar('\n');
761 do_clunk(fid);
762 return ret;
765 static void
766 send_fid(int fid, const char *fnam, int open_flags, int fd, const char *name)
768 static char buf[MSIZE9P];
769 struct progress p = {0};
770 struct stat sb;
771 ssize_t r;
772 size_t w, len;
774 if (fstat(fd, &sb) == -1)
775 err(1, "fstat");
777 if (fnam != NULL)
778 do_create(fid, fnam, 0644, KOWRITE);
779 else
780 do_open(fid, open_flags | KOWRITE);
782 p.max = sb.st_size;
783 for (;;) {
784 len = MIN(sizeof(buf), msize);
785 len -= HEADERSIZE + 4 + 4 + 8; /* for the request' fields */
787 r = read(fd, buf, len);
788 if (r == 0)
789 break;
790 if (r == -1)
791 err(1, "read");
793 w = do_write(fid, p.done, r, buf);
794 p.done += w;
796 draw_progress(name, &p);
798 #if 0
799 /* throttle, for debugging purpose */
801 struct timespec ts = { 0, 500000000 };
802 nanosleep(&ts, NULL);
804 #endif
807 putchar('\n');
808 do_clunk(fid);
811 static int
812 woc_file(int fd, const char *prompt, const char *path)
814 struct qid qid;
815 const char *n = NULL;
816 char *errstr;
817 int nfid, miss;
819 nfid = nextfid();
820 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
821 if (errstr != NULL && miss > 1) {
822 printf("%s: %s\n", path, errstr);
823 free(errstr);
824 return -1;
827 if (errstr != NULL || miss == 1) {
828 char p[PATH_MAX], *dn;
830 /*
831 * If it's only one component missing (the file name), walk
832 * to the parent directory and try to create the file.
833 */
835 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
836 printf("path too long: %s\n", path);
837 return -1;
839 dn = dirname(p);
841 if (!strcmp(dn, ".")) {
842 errstr = dup_fid(pwdfid, nfid);
843 miss = 0;
844 } else
845 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
847 if (errstr != NULL) {
848 printf("%s: %s\n", dn, errstr);
849 free(errstr);
850 return -1;
853 if (miss != 0) {
854 printf("%s: not a directory\n", dn);
855 return -1;
858 if ((n = strrchr(path, '/')) != NULL)
859 n++;
860 else
861 n = path;
864 free(errstr);
866 if (miss > 1) {
867 printf("can't create %s: missing %d path component(s)\n",
868 path, miss);
869 return -1;
872 send_fid(nfid, n, KOTRUNC, fd, prompt);
873 return 0;
876 static int
877 dial(const char *host, const char *port)
879 struct addrinfo hints, *res, *res0;
880 int sock, error, saved_errno;
881 const char *cause = NULL;
883 memset(&hints, 0, sizeof(hints));
884 hints.ai_family = AF_UNSPEC;
885 hints.ai_socktype = SOCK_STREAM;
886 error = getaddrinfo(host, port, &hints, &res0);
887 if (error)
888 errx(1, "%s", gai_strerror(error));
890 sock = -1;
891 for (res = res0; res != NULL; res = res->ai_next) {
892 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
893 res->ai_protocol);
894 if (sock == -1) {
895 cause = "socket";
896 continue;
899 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
900 cause = "connect";
901 saved_errno = errno;
902 close(sock);
903 errno = saved_errno;
904 sock = -1;
905 continue;
908 break;
910 freeaddrinfo(res0);
911 if (sock == -1)
912 err(1, "%s", cause);
913 return sock;
916 static void
917 do_connect(const char *connspec, const char *path)
919 char *t;
920 const char *port;
922 host = xstrdup(connspec);
923 if ((t = strchr(host, '@')) != NULL) {
924 if (t == host)
925 errx(1, "invalid connection string: %s", connspec);
926 *t = '\0';
927 user = host;
928 host = ++t;
929 } else if ((user = getenv("USER")) == NULL)
930 errx(1, "USER not defined");
932 if ((t = strchr(host, ':')) != NULL) {
933 *t = '\0';
934 port = ++t;
935 if (*port == '\0')
936 errx(1, "invalid connection string: %s", connspec);
937 } else
938 port = "1337";
940 printf("connecting to %s:%s...", host, port);
941 fflush(stdout);
943 if (tls) {
944 struct tls_config *conf;
945 struct tls *ctx;
946 int r;
948 if ((conf = tls_config_new()) == NULL)
949 fatalx("failed to create TLS config");
950 tls_config_insecure_noverifycert(conf);
951 tls_config_insecure_noverifyname(conf);
953 if (keypath == NULL)
954 keypath = crtpath;
956 if (tls_config_set_keypair_file(conf, crtpath, keypath) == -1)
957 fatalx("failed to load certs: (%s, %s)", crtpath,
958 keypath);
960 if ((ctx = tls_client()) == NULL)
961 fatalx("failed to create TLS client");
962 if (tls_configure(ctx, conf) == -1)
963 fatalx("failed to configure TLS client");
964 tls_config_free(conf);
966 if (tls_connect(ctx, host, port) == -1)
967 fatalx("failed to connect to %s:%s: %s", host, port,
968 tls_error(ctx));
970 do {
971 r = tls_handshake(ctx);
972 } while (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT);
973 fp = funopen(ctx, stdio_tls_read, stdio_tls_write, NULL,
974 stdio_tls_close);
975 if (fp == NULL)
976 fatal("funopen");
977 } else {
978 int fd;
980 fd = dial(host, port);
981 if ((fp = fdopen(fd, "r+")) == NULL)
982 fatal("fdopen");
985 printf(" done!\n");
987 do_version();
988 do_attach(path);
991 static int
992 tmp_file(char sfn[TMPFSTRLEN])
994 int tmpfd;
996 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
997 if ((tmpfd = mkstemp(sfn)) == -1) {
998 warn("mkstemp %s", sfn);
999 return -1;
1002 /* set the close-on-exec flag */
1003 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
1004 warn("fcntl");
1005 close(tmpfd);
1006 return -1;
1009 return tmpfd;
1012 static inline const char *
1013 pp_perm(uint8_t x)
1015 switch (x & 0x7) {
1016 case 0x0:
1017 return "---";
1018 case 0x1:
1019 return "--x";
1020 case 0x2:
1021 return "-w-";
1022 case 0x3:
1023 return "-wx";
1024 case 0x4:
1025 return "r--";
1026 case 0x5:
1027 return "r-x";
1028 case 0x6:
1029 return "rw-";
1030 case 0x7:
1031 return "rwx";
1032 default:
1033 /* unreachable, just for the compiler' happiness */
1034 return "???";
1038 static inline void
1039 prepare_wstat(struct np_stat *st)
1041 memset(st, 0xFF, sizeof(*st));
1042 st->name = NULL;
1043 st->uid = NULL;
1044 st->gid = NULL;
1045 st->muid = NULL;
1048 static void
1049 cmd_bell(int argc, const char **argv)
1051 if (argc == 0) {
1052 bell = !bell;
1053 if (bell)
1054 puts("bell mode enabled");
1055 else
1056 puts("bell mode disabled");
1057 return;
1060 if (argc != 1)
1061 goto usage;
1063 if (!strcmp(*argv, "on")) {
1064 bell = 1;
1065 puts("bell mode enabled");
1066 return;
1069 if (!strcmp(*argv, "off")) {
1070 bell = 0;
1071 puts("bell mode disabled");
1072 return;
1075 usage:
1076 printf("bell [on | off]\n");
1079 static void
1080 cmd_bye(int argc, const char **argv)
1082 log_warnx("bye\n");
1083 fclose(fp);
1084 exit(0);
1087 static void
1088 cmd_cd(int argc, const char **argv)
1090 struct qid qid;
1091 int nfid, miss;
1092 char *errstr;
1094 if (argc != 1) {
1095 printf("usage: cd remote-path\n");
1096 return;
1099 nfid = nextfid();
1100 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1101 if (errstr != NULL) {
1102 printf("%s: %s\n", argv[0], errstr);
1103 free(errstr);
1104 return;
1107 if (miss != 0 || !(qid.type & QTDIR)) {
1108 printf("%s: not a directory\n", argv[0]);
1109 if (miss == 0)
1110 do_clunk(nfid);
1111 return;
1114 do_clunk(pwdfid);
1115 pwdfid = nfid;
1118 static void
1119 cmd_edit(int argc, const char **argv)
1121 struct qid qid;
1122 int nfid, tmpfd, miss;
1123 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1124 const char *ed;
1126 if (argc != 1) {
1127 puts("usage: edit file");
1128 return;
1131 if ((ed = getenv("VISUAL")) == NULL &&
1132 (ed = getenv("EDITOR")) == NULL)
1133 ed = "ed";
1135 nfid = nextfid();
1136 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1137 if (errstr != NULL) {
1138 printf("%s: %s\n", *argv, errstr);
1139 free(errstr);
1140 return;
1143 if (miss != 0 || qid.type != 0) {
1144 printf("%s: not a file\n", *argv);
1145 if (miss == 0)
1146 do_clunk(nfid);
1147 return;
1150 if ((tmpfd = tmp_file(sfn)) == -1) {
1151 do_clunk(nfid);
1152 return;
1155 strlcpy(p, *argv, sizeof(p));
1156 name = basename(p);
1158 if (fetch_fid(nfid, tmpfd, name)) {
1159 warn("failed fetch or can't write %s", sfn);
1160 goto end;
1162 close(tmpfd);
1164 spawn(ed, sfn, NULL);
1167 * Re-open the file because it's not guaranteed that the
1168 * file descriptor tmpfd is still associated with the file
1169 * pointed by sfn: it's not uncommon for editor to write
1170 * a backup file and then rename(2) it to the file name.
1172 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1173 warn("can't open %s", sfn);
1174 goto end;
1177 woc_file(tmpfd, *argv, name);
1178 close(tmpfd);
1180 end:
1181 unlink(sfn);
1184 static void
1185 cmd_get(int argc, const char **argv)
1187 struct qid qid;
1188 const char *l;
1189 char *errstr;
1190 int nfid, fd, miss;
1192 if (argc != 1 && argc != 2) {
1193 printf("usage: get remote-file [local-file]\n");
1194 return;
1197 if (argc == 2)
1198 l = argv[1];
1199 else if ((l = strrchr(argv[0], '/')) != NULL)
1200 l++; /* skip / */
1201 else
1202 l = argv[0];
1204 nfid = nextfid();
1205 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1206 if (errstr != NULL) {
1207 printf("%s: %s\n", argv[0], errstr);
1208 free(errstr);
1209 return;
1212 if (miss != 0 || qid.type != 0) {
1213 printf("%s: not a file\n", argv[0]);
1214 if (miss == 0)
1215 do_clunk(nfid);
1216 return;
1219 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1220 warn("can't open %s", l);
1221 do_clunk(nfid);
1222 return;
1225 if (fetch_fid(nfid, fd, l) == -1)
1226 warn("write %s", l);
1227 close(fd);
1230 static void
1231 cmd_hexdump(int argc, const char **argv)
1233 if (argc == 0) {
1234 xdump = !xdump;
1235 if (xdump)
1236 puts("hexdump mode enabled");
1237 else
1238 puts("hexdump mode disabled");
1239 return;
1242 if (argc > 1)
1243 goto usage;
1245 if (!strcmp(*argv, "on")) {
1246 xdump = 1;
1247 puts("hexdump mode enabled");
1248 return;
1251 if (!strcmp(*argv, "off")) {
1252 xdump = 0;
1253 puts("hexdump mode disabled");
1254 return;
1257 usage:
1258 puts("usage: hexdump [on | off]");
1261 static void
1262 cmd_lcd(int argc, const char **argv)
1264 const char *dir;
1266 if (argc > 1) {
1267 printf("usage: lcd [local-directory]\n");
1268 return;
1271 if (argc == 1)
1272 dir = *argv;
1274 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1275 printf("HOME is not defined\n");
1276 return;
1279 if (chdir(dir) == -1)
1280 printf("cd: %s: %s\n", dir, strerror(errno));
1283 static void
1284 cmd_lpwd(int argc, const char **argv)
1286 char path[PATH_MAX];
1288 if (argc != 0) {
1289 printf("usage: lpwd\n");
1290 return;
1293 if (getcwd(path, sizeof(path)) == NULL) {
1294 printf("lpwd: %s\n", strerror(errno));
1295 return;
1298 printf("%s\n", path);
1301 static void
1302 cmd_ls(int argc, const char **argv)
1304 struct np_stat st;
1305 time_t now, mtime;
1306 struct tm *tm;
1307 uint64_t off = 0;
1308 uint32_t len;
1309 int nfid;
1310 const char *timfmt;
1311 char fmt[FMT_SCALED_STRSIZE], tim[13], *errstr;
1313 if (argc != 0) {
1314 printf("ls don't take arguments (yet)\n");
1315 return;
1318 now = time(NULL);
1320 nfid = nextfid();
1321 if ((errstr = dup_fid(pwdfid, nfid)) != NULL) {
1322 printf(".: %s\n", errstr);
1323 free(errstr);
1324 return;
1327 do_open(nfid, KOREAD);
1329 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1331 for (;;) {
1332 tread(nfid, off, msize - IOHDRSZ);
1333 do_send();
1334 recv_msg();
1335 expect2(Rread, iota_tag);
1337 len = np_read32(buf);
1338 if (len == 0)
1339 break;
1341 evbuffer_add_buffer(dirbuf, buf);
1342 off += len;
1344 ASSERT_EMPTYBUF();
1347 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1348 if (np_read_stat(dirbuf, &st) == -1)
1349 errx(1, "invalid stat struct read");
1351 if (fmt_scaled(st.length, fmt) == -1)
1352 strlcpy(fmt, "xxx", sizeof(fmt));
1354 mtime = st.mtime;
1356 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
1357 timfmt = "%b %e %R";
1358 else
1359 timfmt = "%b %e %Y";
1361 if ((tm = localtime(&mtime)) == NULL ||
1362 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1363 strlcpy(tim, "unknown", sizeof(tim));
1365 if (st.qid.type & QTDIR)
1366 printf("d");
1367 else
1368 printf("-");
1369 printf("%s", pp_perm(st.mode >> 6));
1370 printf("%s", pp_perm(st.mode >> 3));
1371 printf("%s", pp_perm(st.mode));
1372 printf(" %8s %12s %s%s\n", fmt, tim, st.name,
1373 st.qid.type & QTDIR ? "/" : "");
1375 free(st.name);
1376 free(st.uid);
1377 free(st.gid);
1378 free(st.muid);
1381 do_clunk(nfid);
1384 static void
1385 cmd_page(int argc, const char **argv)
1387 struct qid qid;
1388 int nfid, tmpfd, miss, r;
1389 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1390 const char *pager;
1392 if (argc != 1) {
1393 puts("usage: page file");
1394 return;
1397 if ((pager = getenv("PAGER")) == NULL)
1398 pager = "less";
1400 nfid = nextfid();
1401 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1402 if (errstr != NULL) {
1403 printf("%s: %s\n", *argv, errstr);
1404 free(errstr);
1405 return;
1408 if (miss != 0 || qid.type != 0) {
1409 printf("%s: not a file\n", *argv);
1410 if (miss == 0)
1411 do_clunk(nfid);
1412 return;
1415 if ((tmpfd = tmp_file(sfn)) == -1) {
1416 do_clunk(nfid);
1417 return;
1420 strlcpy(p, *argv, sizeof(p));
1421 name = basename(p);
1422 if ((r = fetch_fid(nfid, tmpfd, name)) == -1)
1423 warn("write %s", sfn);
1424 close(tmpfd);
1425 if (r != -1)
1426 spawn(pager, sfn, NULL);
1427 unlink(sfn);
1430 static void
1431 cmd_pipe(int argc, const char **argv)
1433 struct qid qid;
1434 pid_t pid;
1435 int nfid, tmpfd, miss, status;
1436 int filedes[2]; /* read end, write end */
1437 char *errstr;
1439 if (argc < 2) {
1440 puts("usage: pipe remote-file cmd [args...]");
1441 return;
1444 nfid = nextfid();
1445 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1446 if (errstr != NULL) {
1447 printf("%s: %s\n", *argv, errstr);
1448 free(errstr);
1449 return;
1452 if (miss != 0 || qid.type != 0) {
1453 printf("%s: not a file\n", *argv);
1454 if (miss == 0)
1455 do_clunk(nfid);
1456 return;
1459 if (pipe(filedes) == -1)
1460 err(1, "pipe");
1462 switch (pid = vfork()) {
1463 case -1:
1464 err(1, "vfork");
1465 case 0:
1466 close(filedes[1]);
1467 if (dup2(filedes[0], 0) == -1)
1468 err(1, "dup2");
1469 execvp(argv[1], (char *const *)argv + 1);
1470 err(1, "execvp");
1473 close(filedes[0]);
1474 if (fetch_fid(nfid, filedes[1], *argv) == -1)
1475 warnx("failed to fetch all the file");
1476 close(filedes[1]);
1478 waitpid(pid, &status, 0);
1481 static void
1482 cmd_put(int argc, const char **argv)
1484 struct qid qid;
1485 const char *l;
1486 int fd;
1488 if (argc != 1 && argc != 2) {
1489 printf("usage: put local-file [remote-file]\n");
1490 return;
1493 if (argc == 2)
1494 l = argv[1];
1495 else if ((l = strrchr(argv[0], '/')) != NULL)
1496 l++; /* skip / */
1497 else
1498 l = argv[0];
1500 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1501 warn("%s", argv[0]);
1502 return;
1505 woc_file(fd, argv[0], l);
1506 close(fd);
1509 static void
1510 cmd_rename(int argc, const char **argv)
1512 struct np_stat st;
1513 struct qid qid;
1514 char *errstr;
1515 int nfid, miss;
1517 if (argc != 2) {
1518 puts("usage: rename remote-file new-remote-name");
1519 return;
1522 nfid = nextfid();
1523 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1524 if (errstr != NULL) {
1525 printf("%s: %s\n", argv[0], errstr);
1526 free(errstr);
1527 return;
1530 if (miss != 0) {
1531 printf("%s: not such file or directory\n", argv[0]);
1532 return;
1535 prepare_wstat(&st);
1536 st.name = (char *)argv[1];
1537 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1538 printf("rename: %s\n", errstr);
1539 free(errstr);
1542 do_clunk(nfid);
1545 static void
1546 cmd_verbose(int argc, const char **argv)
1548 if (argc == 0) {
1549 log_setverbose(!log_getverbose());
1550 if (log_getverbose())
1551 puts("verbose mode enabled");
1552 else
1553 puts("verbose mode disabled");
1554 return;
1557 if (argc != 1)
1558 goto usage;
1560 if (!strcmp(*argv, "on")) {
1561 log_setverbose(1);
1562 puts("verbose mode enabled");
1563 return;
1566 if (!strcmp(*argv, "off")) {
1567 log_setverbose(0);
1568 puts("verbose mode disabled");
1569 return;
1572 usage:
1573 printf("verbose [on | off]\n");
1576 static void
1577 excmd(int argc, const char **argv)
1579 struct cmd {
1580 const char *name;
1581 void (*fn)(int, const char **);
1582 } cmds[] = {
1583 {"bell", cmd_bell},
1584 {"bye", cmd_bye},
1585 {"cd", cmd_cd},
1586 {"edit", cmd_edit},
1587 {"get", cmd_get},
1588 {"hexdump", cmd_hexdump},
1589 {"lcd", cmd_lcd},
1590 {"lpwd", cmd_lpwd},
1591 {"ls", cmd_ls},
1592 {"page", cmd_page},
1593 {"pipe", cmd_pipe},
1594 {"put", cmd_put},
1595 {"quit", cmd_bye},
1596 {"rename", cmd_rename},
1597 {"verbose", cmd_verbose},
1599 size_t i;
1601 if (argc == 0)
1602 return;
1603 for (i = 0; i < nitems(cmds); ++i) {
1604 if (!strcmp(cmds[i].name, *argv)) {
1605 cmds[i].fn(argc-1, argv+1);
1606 return;
1610 log_warnx("unknown command %s", *argv);
1613 int
1614 main(int argc, char **argv)
1616 int ch;
1618 log_init(1, LOG_DAEMON);
1619 log_setverbose(0);
1620 log_procinit(getprogname());
1622 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
1623 switch (ch) {
1624 case 'C':
1625 tls = 1;
1626 crtpath = optarg;
1627 break;
1628 case 'c':
1629 tls = 1;
1630 break;
1631 case 'K':
1632 tls = 1;
1633 keypath = optarg;
1634 break;
1635 default:
1636 usage(1);
1639 argc -= optind;
1640 argv += optind;
1642 if (argc == 0 || (tls && crtpath == NULL))
1643 usage(1);
1645 signal(SIGPIPE, SIG_IGN);
1646 if (isatty(1)) {
1647 tty_p = 1;
1648 resized = 1;
1649 signal(SIGWINCH, tty_resized);
1652 if ((evb = evbuffer_new()) == NULL)
1653 fatal("evbuffer_new");
1655 if ((buf = evbuffer_new()) == NULL)
1656 fatal("evbuffer_new");
1658 if ((dirbuf = evbuffer_new()) == NULL)
1659 fatal("evbuferr_new");
1661 do_connect(argv[0], argv[1]);
1663 for (;;) {
1664 int argc = 0;
1665 char *line, *argv[16] = {0}, **ap;
1667 if ((line = read_line("kamiftp> ")) == NULL)
1668 break;
1670 for (argc = 0, ap = argv; ap < &argv[15] &&
1671 (*ap = strsep(&line, " \t")) != NULL;) {
1672 if (**ap != '\0')
1673 ap++, argc++;
1675 excmd(argc, (const char **)argv);
1677 if (bell) {
1678 printf("\a");
1679 fflush(stdout);
1682 free(line);
1685 printf("\n");
1686 fclose(fp);