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 /* state */
63 struct tls_config *tlsconf;
64 struct tls *ctx;
65 int sock;
66 struct evbuffer *buf;
67 struct evbuffer *dirbuf;
68 uint32_t msize;
69 int bell;
71 volatile sig_atomic_t resized;
72 int tty_p;
73 int tty_width;
74 int xdump;
76 struct progress {
77 uint64_t max;
78 uint64_t done;
79 };
81 int pwdfid;
83 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
85 #if !HAVE_READLINE
86 char *
87 readline(const char *prompt)
88 {
89 char *ch, *line = NULL;
90 size_t linesize = 0;
91 ssize_t linelen;
93 printf("%s", prompt);
94 fflush(stdout);
96 linelen = getline(&line, &linesize, stdin);
97 if (linelen == -1)
98 return NULL;
100 if ((ch = strchr(line, '\n')) != NULL)
101 *ch = '\0';
102 return line;
105 void
106 add_history(const char *line)
108 return;
110 #endif
112 static char *
113 read_line(const char *prompt)
115 char *line;
117 again:
118 if ((line = readline(prompt)) == NULL)
119 return NULL;
120 /* XXX: trim spaces? */
121 if (*line == '\0') {
122 free(line);
123 goto again;
126 add_history(line);
127 return line;
130 static void
131 spawn(const char *argv0, ...)
133 pid_t pid;
134 size_t i;
135 int status;
136 const char *argv[16], *last;
137 va_list ap;
139 memset(argv, 0, sizeof(argv));
141 va_start(ap, argv0);
142 argv[0] = argv0;
143 for (i = 1; i < nitems(argv); ++i) {
144 last = va_arg(ap, const char *);
145 if (last == NULL)
146 break;
147 argv[i] = last;
149 va_end(ap);
151 assert(last == NULL);
153 switch (pid = fork()) {
154 case -1:
155 err(1, "fork");
156 case 0: /* child */
157 execvp(argv[0], (char *const *)argv);
158 err(1, "execvp");
159 default:
160 waitpid(pid, &status, 0);
164 static void
165 tty_resized(int signo)
167 resized = 1;
170 static void __dead
171 usage(int ret)
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");
176 exit(ret);
179 static int
180 nextfid(void)
182 uint32_t i;
184 for (i = 0; ; ++i) {
185 if (i != pwdfid)
186 return i;
190 static void
191 do_send(void)
193 const void *buf;
194 size_t nbytes;
195 ssize_t r;
197 if (xdump)
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);
205 if (ctx == NULL) {
206 r = write(sock, buf, nbytes);
207 if (r == 0 || r == -1)
208 errx(1, "EOF");
209 } else {
210 r = tls_write(ctx, buf, nbytes);
211 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
212 continue;
213 if (r == -1)
214 errx(1, "tls: %s", tls_error(ctx));
217 evbuffer_drain(evb, r);
221 static void
222 mustread(void *d, size_t len)
224 ssize_t r;
226 while (len != 0) {
227 if (ctx == NULL) {
228 r = read(sock, d, len);
229 if (r == 0 || r == -1)
230 errx(1, "EOF");
231 } else {
232 r = tls_read(ctx, d, len);
233 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
234 continue;
235 if (r == -1)
236 errx(1, "tls: %s", tls_error(ctx));
239 d += r;
240 len -= r;
244 static void
245 recv_msg(void)
247 uint32_t len, l;
248 char tmp[BUFSIZ];
250 mustread(&len, sizeof(len));
251 len = le32toh(len);
252 if (len < HEADERSIZE)
253 errx(1, "read message of invalid length %d", len);
255 len -= 4; /* skip the length just read */
257 while (len != 0) {
258 l = MIN(len, sizeof(tmp));
259 mustread(tmp, l);
260 len -= l;
261 evbuffer_add(buf, tmp, l);
264 if (xdump)
265 hexdump("incoming packet", EVBUFFER_DATA(buf),
266 EVBUFFER_LENGTH(buf));
269 static uint64_t
270 np_read64(struct evbuffer *buf)
272 uint64_t n;
274 evbuffer_remove(buf, &n, sizeof(n));
275 return le64toh(n);
278 static uint32_t
279 np_read32(struct evbuffer *buf)
281 uint32_t n;
283 evbuffer_remove(buf, &n, sizeof(n));
284 return le32toh(n);
287 static uint16_t
288 np_read16(struct evbuffer *buf)
290 uint16_t n;
292 evbuffer_remove(buf, &n, sizeof(n));
293 return le16toh(n);
296 static uint16_t
297 np_read8(struct evbuffer *buf)
299 uint8_t n;
301 evbuffer_remove(buf, &n, sizeof(n));
302 return n;
305 static char *
306 np_readstr(struct evbuffer *buf)
308 uint16_t len;
309 char *str;
311 len = np_read16(buf);
312 assert(EVBUFFER_LENGTH(buf) >= len);
314 if ((str = calloc(1, len+1)) == NULL)
315 err(1, "calloc");
316 evbuffer_remove(buf, str, len);
317 return str;
320 static void
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);
330 static int
331 np_read_stat(struct evbuffer *buf, struct np_stat *st)
333 uint16_t size;
335 memset(st, 0, sizeof(*st));
337 size = np_read16(buf);
338 if (size > EVBUFFER_LENGTH(buf))
339 return -1;
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);
353 return 0;
356 static void
357 expect(uint8_t type)
359 uint8_t t;
361 t = np_read8(buf);
362 if (t == type)
363 return;
365 if (t == Rerror) {
366 char *err;
368 /* skip tag */
369 np_read16(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));
380 static void
381 expect2(uint8_t type, uint16_t tag)
383 uint16_t t;
385 expect(type);
387 t = np_read16(buf);
388 if (t == tag)
389 return;
391 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
394 static char *
395 check(uint8_t type, uint16_t tag)
397 uint16_t rtag;
398 uint8_t rtype;
400 rtype = np_read8(buf);
401 rtag = np_read16(buf);
402 if (rtype == type) {
403 if (rtag != tag)
404 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
405 return NULL;
408 if (rtype == Rerror)
409 return np_readstr(buf);
411 errx(1, "expected %s, got msg type %s",
412 pp_msg_type(type), pp_msg_type(rtype));
415 static void
416 do_version(void)
418 char *version;
420 tversion(VERSION9P, MSIZE9P);
421 do_send();
422 recv_msg();
423 expect2(Rversion, NOTAG);
425 msize = np_read32(buf);
426 version = np_readstr(buf);
428 if (msize > MSIZE9P)
429 errx(1, "got unexpected msize: %d", msize);
430 if (strcmp(version, VERSION9P))
431 errx(1, "unexpected 9p version: %s", version);
433 free(version);
434 ASSERT_EMPTYBUF();
437 static void
438 do_attach(const char *path)
440 const char *user;
441 struct qid qid;
443 if (path == NULL)
444 path = "/";
445 if ((user = getenv("USER")) == NULL)
446 user = "flan";
448 tattach(pwdfid, NOFID, user, path);
449 do_send();
450 recv_msg();
451 expect2(Rattach, iota_tag);
452 np_read_qid(buf, &qid);
454 ASSERT_EMPTYBUF();
457 static uint32_t
458 do_open(uint32_t fid, uint8_t mode)
460 struct qid qid;
461 uint32_t iounit;
463 topen(fid, mode);
464 do_send();
465 recv_msg();
466 expect2(Ropen, iota_tag);
468 np_read_qid(buf, &qid);
469 iounit = np_read32(buf);
471 ASSERT_EMPTYBUF();
473 return iounit;
476 static uint32_t
477 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
479 struct qid qid;
480 uint32_t iounit;
482 tcreate(fid, name, perm, mode);
483 do_send();
484 recv_msg();
485 expect2(Rcreate, iota_tag);
487 np_read_qid(buf, &qid);
488 iounit = np_read32(buf);
490 ASSERT_EMPTYBUF();
492 return iounit;
495 static void
496 do_clunk(uint32_t fid)
498 tclunk(fid);
499 do_send();
500 recv_msg();
501 expect2(Rclunk, iota_tag);
503 ASSERT_EMPTYBUF();
506 static char *
507 dup_fid(int fid, int nfid)
509 uint16_t nwqid;
510 char *errstr;
512 twalk(fid, nfid, NULL, 0);
513 do_send();
514 recv_msg();
516 if ((errstr = check(Rwalk, iota_tag)) != NULL)
517 return errstr;
519 nwqid = np_read16(buf);
520 assert(nwqid == 0);
522 ASSERT_EMPTYBUF();
524 return NULL;
527 static char *
528 walk_path(int fid, int newfid, const char *path, int *missing,
529 struct qid *qid)
531 char *wnames[MAXWELEM], *p, *t, *errstr;
532 size_t nwname, i;
533 uint16_t nwqid;
535 if ((p = strdup(path)) == NULL)
536 err(1, "strdup");
537 t = p;
539 /* strip initial ./ */
540 if (t[0] == '.' && t[1] == '/')
541 t += 2;
543 for (nwname = 0; nwname < nitems(wnames) &&
544 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
545 if (*wnames[nwname] != '\0')
546 nwname++;
549 twalk(fid, newfid, (const char **)wnames, nwname);
550 do_send();
551 recv_msg();
553 *missing = nwname;
554 if ((errstr = check(Rwalk, iota_tag)) != NULL) {
555 free(p);
556 return errstr;
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);
566 free(p);
568 *missing = nwname - nwqid;
569 return NULL;
572 static void
573 do_stat(int fid, struct np_stat *st)
575 tstat(fid);
576 do_send();
577 recv_msg();
578 expect2(Rstat, iota_tag);
580 if (np_read_stat(buf, st) == -1)
581 errx(1, "invalid stat struct read");
583 ASSERT_EMPTYBUF();
586 static char *
587 do_wstat(int fid, const struct np_stat *st)
589 char *errstr;
591 twstat(fid, st);
592 do_send();
593 recv_msg();
595 if ((errstr = check(Rwstat, iota_tag)) != NULL)
596 return errstr;
598 ASSERT_EMPTYBUF();
600 return NULL;
603 static size_t
604 do_read(int fid, uint64_t off, uint32_t count, void *data)
606 uint32_t r;
608 tread(fid, off, count);
609 do_send();
610 recv_msg();
611 expect2(Rread, iota_tag);
613 r = np_read32(buf);
614 assert(r == EVBUFFER_LENGTH(buf));
615 assert(r <= count);
616 evbuffer_remove(buf, data, r);
618 ASSERT_EMPTYBUF();
620 return r;
623 static size_t
624 do_write(int fid, uint64_t off, uint32_t count, void *data)
626 uint32_t r;
628 twrite(fid, off, data, count);
629 do_send();
630 recv_msg();
631 expect2(Rwrite, iota_tag);
633 r = np_read32(buf);
634 assert(r <= count);
636 ASSERT_EMPTYBUF();
638 return r;
641 static void
642 draw_progress(const char *pre, const struct progress *p)
644 struct winsize ws;
645 int i, l, w;
646 double perc;
648 if (xdump)
649 return;
651 perc = 100.0 * p->done / p->max;
652 if (!tty_p) {
653 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
654 return;
657 if (resized) {
658 resized = 0;
660 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
661 return;
662 tty_width = ws.ws_col;
664 w = tty_width;
666 if (pre == NULL ||
667 ((l = printf("\r%s ", pre)) == -1 || l >= w))
668 return;
670 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
671 if (w < 0) {
672 printf("%4d%%\n", (int)perc);
673 return;
676 printf("|");
678 l = w * MIN(100.0, perc) / 100.0;
679 for (i = 0; i < l; i++)
680 printf("*");
681 for (; i < w; i++)
682 printf(" ");
683 printf("|%4d%%", (int)perc);
685 fflush(stdout);
688 static int
689 fetch_fid(int fid, int fd, const char *name)
691 struct progress p = {0};
692 struct np_stat st;
693 size_t r;
694 int ret = 0;
695 char buf[BUFSIZ];
697 do_stat(fid, &st);
698 do_open(fid, KOREAD);
700 p.max = st.length;
701 for (;;) {
702 size_t off;
703 ssize_t nw;
705 r = do_read(fid, p.done, sizeof(buf), buf);
706 if (r == 0)
707 break;
709 for (off = 0; off < r; off += nw)
710 if ((nw = write(fd, buf + off, r - off)) == 0 ||
711 nw == -1) {
712 ret = -1;
713 goto end;
716 p.done += r;
717 draw_progress(name, &p);
719 #if 0
720 /* throttle, for debugging purpose */
722 struct timespec ts = { 0, 500000000 };
723 nanosleep(&ts, NULL);
725 #endif
728 end:
729 putchar('\n');
731 do_clunk(fid);
732 return ret;
735 static void
736 send_fid(int fid, const char *fnam, int open_flags, int fd, const char *name)
738 struct progress p = {0};
739 struct stat sb;
740 ssize_t r;
741 size_t w;
742 char buf[BUFSIZ];
744 if (fstat(fd, &sb) == -1)
745 err(1, "fstat");
747 if (fnam != NULL)
748 do_create(fid, fnam, 0644, KOWRITE);
749 else
750 do_open(fid, open_flags | KOWRITE);
752 p.max = sb.st_size;
753 for (;;) {
754 r = read(fd, buf, sizeof(buf));
755 if (r == 0)
756 break;
757 if (r == -1)
758 err(1, "read");
760 w = do_write(fid, p.done, r, buf);
761 p.done += w;
763 draw_progress(name, &p);
765 #if 0
766 /* throttle, for debugging purpose */
768 struct timespec ts = { 0, 500000000 };
769 nanosleep(&ts, NULL);
771 #endif
774 putchar('\n');
775 do_clunk(fid);
778 static int
779 woc_file(int fd, const char *prompt, const char *path)
781 struct qid qid;
782 const char *n = NULL;
783 char *errstr;
784 int nfid, miss;
786 nfid = nextfid();
787 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
788 if (errstr != NULL && miss > 1) {
789 printf("%s: %s\n", path, errstr);
790 free(errstr);
791 return -1;
794 if (errstr != NULL || miss == 1) {
795 char p[PATH_MAX], *dn;
797 /*
798 * If it's only one component missing (the file name), walk
799 * to the parent directory and try to create the file.
800 */
802 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
803 printf("path too long: %s\n", path);
804 return -1;
806 dn = dirname(p);
808 if (!strcmp(dn, ".")) {
809 errstr = dup_fid(pwdfid, nfid);
810 miss = 0;
811 } else
812 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
814 if (errstr != NULL) {
815 printf("%s: %s\n", dn, errstr);
816 free(errstr);
817 return -1;
820 if (miss != 0) {
821 printf("%s: not a directory\n", dn);
822 return -1;
825 if ((n = strrchr(path, '/')) != NULL)
826 n++;
827 else
828 n = path;
831 free(errstr);
833 if (miss > 1) {
834 printf("can't create %s: missing %d path component(s)\n",
835 path, miss);
836 return -1;
839 send_fid(nfid, n, KOTRUNC, fd, prompt);
840 return 0;
843 static void
844 do_tls_connect(const char *host, const char *port)
846 int handshake;
848 if ((tlsconf = tls_config_new()) == NULL)
849 fatalx("tls_config_new");
850 tls_config_insecure_noverifycert(tlsconf);
851 tls_config_insecure_noverifyname(tlsconf);
853 if (keypath == NULL)
854 keypath = crtpath;
856 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
857 fatalx("can't load certs (%s, %s)", crtpath, keypath);
859 if ((ctx = tls_client()) == NULL)
860 fatal("tls_client");
861 if (tls_configure(ctx, tlsconf) == -1)
862 fatalx("tls_configure: %s", tls_error(ctx));
864 if (tls_connect(ctx, host, port) == -1)
865 fatalx("can't connect to %s:%s: %s", host, port,
866 tls_error(ctx));
868 for (handshake = 0; !handshake;) {
869 switch (tls_handshake(ctx)) {
870 case -1:
871 fatalx("tls_handshake: %s", tls_error(ctx));
872 case 0:
873 handshake = 1;
874 break;
879 static void
880 do_ctxt_connect(const char *host, const char *port)
882 struct addrinfo hints, *res, *res0;
883 int error, saved_errno;
884 const char *cause = NULL;
886 memset(&hints, 0, sizeof(hints));
887 hints.ai_family = AF_UNSPEC;
888 hints.ai_socktype = SOCK_STREAM;
889 error = getaddrinfo(host, port, &hints, &res0);
890 if (error)
891 errx(1, "%s", gai_strerror(error));
893 sock = -1;
894 for (res = res0; res != NULL; res = res->ai_next) {
895 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
896 res->ai_protocol);
897 if (sock == -1) {
898 cause = "socket";
899 continue;
902 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
903 cause = "connect";
904 saved_errno = errno;
905 close(sock);
906 errno = saved_errno;
907 sock = -1;
908 continue;
911 break;
914 if (sock == -1)
915 err(1, "%s", cause);
916 freeaddrinfo(res0);
919 static void
920 do_connect(const char *connspec, const char *path)
922 char *host, *colon;
923 const char *port;
925 host = xstrdup(connspec);
926 if ((colon = strchr(host, ':')) != NULL) {
927 *colon = '\0';
928 port = ++colon;
929 } else
930 port = "1337";
932 printf("connecting to %s:%s...", host, port);
933 fflush(stdout);
935 if (tls)
936 do_tls_connect(host, port);
937 else
938 do_ctxt_connect(host, port);
940 printf(" done!\n");
942 do_version();
943 do_attach(path);
945 free(host);
948 static int
949 tmp_file(char sfn[TMPFSTRLEN])
951 int tmpfd;
953 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
954 if ((tmpfd = mkstemp(sfn)) == -1) {
955 warn("mkstemp %s", sfn);
956 return -1;
959 /* set the close-on-exec flag */
960 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
961 warn("fcntl");
962 close(tmpfd);
963 return -1;
966 return tmpfd;
969 static inline const char *
970 pp_perm(uint8_t x)
972 switch (x & 0x7) {
973 case 0x0:
974 return "---";
975 case 0x1:
976 return "--x";
977 case 0x2:
978 return "-w-";
979 case 0x3:
980 return "-wx";
981 case 0x4:
982 return "r--";
983 case 0x5:
984 return "r-x";
985 case 0x6:
986 return "rw-";
987 case 0x7:
988 return "rwx";
989 default:
990 /* unreachable, just for the compiler' happiness */
991 return "???";
995 static inline void
996 prepare_wstat(struct np_stat *st)
998 memset(st, 0xFF, sizeof(*st));
999 st->name = NULL;
1000 st->uid = NULL;
1001 st->gid = NULL;
1002 st->muid = NULL;
1005 static void
1006 cmd_bell(int argc, const char **argv)
1008 if (argc == 0) {
1009 bell = !bell;
1010 if (bell)
1011 puts("bell mode enabled");
1012 else
1013 puts("bell mode disabled");
1014 return;
1017 if (argc != 1)
1018 goto usage;
1020 if (!strcmp(*argv, "on")) {
1021 bell = 1;
1022 puts("bell mode enabled");
1023 return;
1026 if (!strcmp(*argv, "off")) {
1027 bell = 0;
1028 puts("bell mode disabled");
1029 return;
1032 usage:
1033 printf("bell [on | off]\n");
1036 static void
1037 cmd_bye(int argc, const char **argv)
1039 log_warnx("bye\n");
1040 exit(0);
1043 static void
1044 cmd_cd(int argc, const char **argv)
1046 struct qid qid;
1047 int nfid, miss;
1048 char *errstr;
1050 if (argc != 1) {
1051 printf("usage: cd remote-path\n");
1052 return;
1055 nfid = nextfid();
1056 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1057 if (errstr != NULL) {
1058 printf("%s: %s\n", argv[0], errstr);
1059 free(errstr);
1060 return;
1063 if (miss != 0 || !(qid.type & QTDIR)) {
1064 printf("%s: not a directory\n", argv[0]);
1065 if (miss == 0)
1066 do_clunk(nfid);
1067 return;
1070 do_clunk(pwdfid);
1071 pwdfid = nfid;
1074 static void
1075 cmd_edit(int argc, const char **argv)
1077 struct qid qid;
1078 int nfid, tmpfd, miss;
1079 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1080 const char *ed;
1082 if (argc != 1) {
1083 puts("usage: edit file");
1084 return;
1087 if ((ed = getenv("VISUAL")) == NULL &&
1088 (ed = getenv("EDITOR")) == NULL)
1089 ed = "ed";
1091 nfid = nextfid();
1092 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1093 if (errstr != NULL) {
1094 printf("%s: %s\n", *argv, errstr);
1095 free(errstr);
1096 return;
1099 if (miss != 0 || qid.type != 0) {
1100 printf("%s: not a file\n", *argv);
1101 if (miss == 0)
1102 do_clunk(nfid);
1103 return;
1106 if ((tmpfd = tmp_file(sfn)) == -1) {
1107 do_clunk(nfid);
1108 return;
1111 strlcpy(p, *argv, sizeof(p));
1112 name = basename(p);
1114 if (fetch_fid(nfid, tmpfd, name)) {
1115 warn("failed fetch or can't write %s", sfn);
1116 goto end;
1118 close(tmpfd);
1120 spawn(ed, sfn, NULL);
1123 * Re-open the file because it's not guaranteed that the
1124 * file descriptor tmpfd is still associated with the file
1125 * pointed by sfn: it's not uncommon for editor to write
1126 * a backup file and then rename(2) it to the file name.
1128 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1129 warn("can't open %s", sfn);
1130 goto end;
1133 woc_file(tmpfd, *argv, name);
1134 close(tmpfd);
1136 end:
1137 unlink(sfn);
1140 static void
1141 cmd_get(int argc, const char **argv)
1143 struct qid qid;
1144 const char *l;
1145 char *errstr;
1146 int nfid, fd, miss;
1148 if (argc != 1 && argc != 2) {
1149 printf("usage: get remote-file [local-file]\n");
1150 return;
1153 if (argc == 2)
1154 l = argv[1];
1155 else if ((l = strrchr(argv[0], '/')) != NULL)
1156 l++; /* skip / */
1157 else
1158 l = argv[0];
1160 nfid = nextfid();
1161 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1162 if (errstr != NULL) {
1163 printf("%s: %s\n", argv[0], errstr);
1164 free(errstr);
1165 return;
1168 if (miss != 0 || qid.type != 0) {
1169 printf("%s: not a file\n", argv[0]);
1170 if (miss == 0)
1171 do_clunk(nfid);
1172 return;
1175 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1176 warn("can't open %s", l);
1177 do_clunk(nfid);
1178 return;
1181 if (fetch_fid(nfid, fd, l) == -1)
1182 warn("write %s", l);
1183 close(fd);
1186 static void
1187 cmd_hexdump(int argc, const char **argv)
1189 if (argc == 0) {
1190 xdump = !xdump;
1191 if (xdump)
1192 puts("hexdump mode enabled");
1193 else
1194 puts("hexdump mode disabled");
1195 return;
1198 if (argc > 1)
1199 goto usage;
1201 if (!strcmp(*argv, "on")) {
1202 xdump = 1;
1203 puts("hexdump mode enabled");
1204 return;
1207 if (!strcmp(*argv, "off")) {
1208 xdump = 0;
1209 puts("hexdump mode disabled");
1210 return;
1213 usage:
1214 puts("usage: hexdump [on | off]");
1217 static void
1218 cmd_lcd(int argc, const char **argv)
1220 const char *dir;
1222 if (argc > 1) {
1223 printf("usage: lcd [local-directory]\n");
1224 return;
1227 if (argc == 1)
1228 dir = *argv;
1230 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1231 printf("HOME is not defined\n");
1232 return;
1235 if (chdir(dir) == -1)
1236 printf("cd: %s: %s\n", dir, strerror(errno));
1239 static void
1240 cmd_lpwd(int argc, const char **argv)
1242 char path[PATH_MAX];
1244 if (argc != 0) {
1245 printf("usage: lpwd\n");
1246 return;
1249 if (getcwd(path, sizeof(path)) == NULL) {
1250 printf("lpwd: %s\n", strerror(errno));
1251 return;
1254 printf("%s\n", path);
1257 static void
1258 cmd_ls(int argc, const char **argv)
1260 struct np_stat st;
1261 time_t now, mtime;
1262 struct tm *tm;
1263 uint64_t off = 0;
1264 uint32_t len;
1265 int nfid;
1266 const char *timfmt;
1267 char fmt[FMT_SCALED_STRSIZE], tim[13], *errstr;
1269 if (argc != 0) {
1270 printf("ls don't take arguments (yet)\n");
1271 return;
1274 now = time(NULL);
1276 nfid = nextfid();
1277 if ((errstr = dup_fid(pwdfid, nfid)) != NULL) {
1278 printf(".: %s\n", errstr);
1279 free(errstr);
1280 return;
1283 do_open(nfid, KOREAD);
1285 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1287 for (;;) {
1288 tread(nfid, off, BUFSIZ);
1289 do_send();
1290 recv_msg();
1291 expect2(Rread, iota_tag);
1293 len = np_read32(buf);
1294 if (len == 0)
1295 break;
1297 evbuffer_add_buffer(dirbuf, buf);
1298 off += len;
1300 ASSERT_EMPTYBUF();
1303 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1304 if (np_read_stat(dirbuf, &st) == -1)
1305 errx(1, "invalid stat struct read");
1307 if (fmt_scaled(st.length, fmt) == -1)
1308 strlcpy(fmt, "xxx", sizeof(fmt));
1310 mtime = st.mtime;
1312 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
1313 timfmt = "%b %e %R";
1314 else
1315 timfmt = "%b %e %Y";
1317 if ((tm = localtime(&mtime)) == NULL ||
1318 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1319 strlcpy(tim, "unknown", sizeof(tim));
1321 if (st.qid.type & QTDIR)
1322 printf("d");
1323 else
1324 printf("-");
1325 printf("%s", pp_perm(st.mode >> 6));
1326 printf("%s", pp_perm(st.mode >> 3));
1327 printf("%s", pp_perm(st.mode));
1328 printf(" %8s %12s %s%s\n", fmt, tim, st.name,
1329 st.qid.type & QTDIR ? "/" : "");
1331 free(st.name);
1332 free(st.uid);
1333 free(st.gid);
1334 free(st.muid);
1337 do_clunk(nfid);
1340 static void
1341 cmd_page(int argc, const char **argv)
1343 struct qid qid;
1344 int nfid, tmpfd, miss, r;
1345 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1346 const char *pager;
1348 if (argc != 1) {
1349 puts("usage: page file");
1350 return;
1353 if ((pager = getenv("PAGER")) == NULL)
1354 pager = "less";
1356 nfid = nextfid();
1357 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1358 if (errstr != NULL) {
1359 printf("%s: %s\n", *argv, errstr);
1360 free(errstr);
1361 return;
1364 if (miss != 0 || qid.type != 0) {
1365 printf("%s: not a file\n", *argv);
1366 if (miss == 0)
1367 do_clunk(nfid);
1368 return;
1371 if ((tmpfd = tmp_file(sfn)) == -1) {
1372 do_clunk(nfid);
1373 return;
1376 strlcpy(p, *argv, sizeof(p));
1377 name = basename(p);
1378 if ((r = fetch_fid(nfid, tmpfd, name)) == -1)
1379 warn("write %s", sfn);
1380 close(tmpfd);
1381 if (r != -1)
1382 spawn(pager, sfn, NULL);
1383 unlink(sfn);
1386 static void
1387 cmd_pipe(int argc, const char **argv)
1389 struct qid qid;
1390 pid_t pid;
1391 int nfid, tmpfd, miss, status;
1392 int filedes[2]; /* read end, write end */
1393 char *errstr;
1395 if (argc < 2) {
1396 puts("usage: pipe remote-file cmd [args...]");
1397 return;
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 (pipe(filedes) == -1)
1416 err(1, "pipe");
1418 switch (pid = vfork()) {
1419 case -1:
1420 err(1, "vfork");
1421 case 0:
1422 close(filedes[1]);
1423 if (dup2(filedes[0], 0) == -1)
1424 err(1, "dup2");
1425 execvp(argv[1], (char *const *)argv + 1);
1426 err(1, "execvp");
1429 close(filedes[0]);
1430 if (fetch_fid(nfid, filedes[1], *argv) == -1)
1431 warnx("failed to fetch all the file");
1432 close(filedes[1]);
1434 waitpid(pid, &status, 0);
1437 static void
1438 cmd_put(int argc, const char **argv)
1440 struct qid qid;
1441 const char *l;
1442 int fd;
1444 if (argc != 1 && argc != 2) {
1445 printf("usage: put local-file [remote-file]\n");
1446 return;
1449 if (argc == 2)
1450 l = argv[1];
1451 else if ((l = strrchr(argv[0], '/')) != NULL)
1452 l++; /* skip / */
1453 else
1454 l = argv[0];
1456 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1457 warn("%s", argv[0]);
1458 return;
1461 woc_file(fd, argv[0], l);
1462 close(fd);
1465 static void
1466 cmd_rename(int argc, const char **argv)
1468 struct np_stat st;
1469 struct qid qid;
1470 char *errstr;
1471 int nfid, miss;
1473 if (argc != 2) {
1474 puts("usage: rename remote-file new-remote-name");
1475 return;
1478 nfid = nextfid();
1479 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1480 if (errstr != NULL) {
1481 printf("%s: %s\n", argv[0], errstr);
1482 free(errstr);
1483 return;
1486 if (miss != 0) {
1487 printf("%s: not such file or directory\n", argv[0]);
1488 return;
1491 prepare_wstat(&st);
1492 st.name = (char *)argv[1];
1493 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1494 printf("rename: %s\n", errstr);
1495 free(errstr);
1498 do_clunk(nfid);
1501 static void
1502 cmd_verbose(int argc, const char **argv)
1504 if (argc == 0) {
1505 log_setverbose(!log_getverbose());
1506 if (log_getverbose())
1507 puts("verbose mode enabled");
1508 else
1509 puts("verbose mode disabled");
1510 return;
1513 if (argc != 1)
1514 goto usage;
1516 if (!strcmp(*argv, "on")) {
1517 log_setverbose(1);
1518 puts("verbose mode enabled");
1519 return;
1522 if (!strcmp(*argv, "off")) {
1523 log_setverbose(0);
1524 puts("verbose mode disabled");
1525 return;
1528 usage:
1529 printf("verbose [on | off]\n");
1532 static void
1533 excmd(int argc, const char **argv)
1535 struct cmd {
1536 const char *name;
1537 void (*fn)(int, const char **);
1538 } cmds[] = {
1539 {"bell", cmd_bell},
1540 {"bye", cmd_bye},
1541 {"cd", cmd_cd},
1542 {"edit", cmd_edit},
1543 {"get", cmd_get},
1544 {"hexdump", cmd_hexdump},
1545 {"lcd", cmd_lcd},
1546 {"lpwd", cmd_lpwd},
1547 {"ls", cmd_ls},
1548 {"page", cmd_page},
1549 {"pipe", cmd_pipe},
1550 {"put", cmd_put},
1551 {"quit", cmd_bye},
1552 {"rename", cmd_rename},
1553 {"verbose", cmd_verbose},
1555 size_t i;
1557 if (argc == 0)
1558 return;
1559 for (i = 0; i < nitems(cmds); ++i) {
1560 if (!strcmp(cmds[i].name, *argv)) {
1561 cmds[i].fn(argc-1, argv+1);
1562 return;
1566 log_warnx("unknown command %s", *argv);
1569 int
1570 main(int argc, char **argv)
1572 int ch;
1574 log_init(1, LOG_DAEMON);
1575 log_setverbose(0);
1576 log_procinit(getprogname());
1578 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
1579 switch (ch) {
1580 case 'C':
1581 tls = 1;
1582 crtpath = optarg;
1583 break;
1584 case 'c':
1585 tls = 1;
1586 break;
1587 case 'K':
1588 tls = 1;
1589 keypath = optarg;
1590 break;
1591 default:
1592 usage(1);
1595 argc -= optind;
1596 argv += optind;
1598 if (argc == 0 || (tls && crtpath == NULL))
1599 usage(1);
1601 signal(SIGPIPE, SIG_IGN);
1602 if (isatty(1)) {
1603 tty_p = 1;
1604 resized = 1;
1605 signal(SIGWINCH, tty_resized);
1608 if ((evb = evbuffer_new()) == NULL)
1609 fatal("evbuffer_new");
1611 if ((buf = evbuffer_new()) == NULL)
1612 fatal("evbuffer_new");
1614 if ((dirbuf = evbuffer_new()) == NULL)
1615 fatal("evbuferr_new");
1617 do_connect(argv[0], argv[1]);
1619 for (;;) {
1620 int argc = 0;
1621 char *line, *argv[16] = {0}, **ap;
1623 if ((line = read_line("kamiftp> ")) == NULL)
1624 break;
1626 for (argc = 0, ap = argv; ap < &argv[15] &&
1627 (*ap = strsep(&line, " \t")) != NULL;) {
1628 if (**ap != '\0')
1629 ap++, argc++;
1631 excmd(argc, (const char **)argv);
1633 if (bell) {
1634 printf("\a");
1635 fflush(stdout);
1638 free(line);
1641 printf("\n");