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 /* eat up the first two byte length */
581 np_read16(buf);
583 if (np_read_stat(buf, st) == -1)
584 errx(1, "invalid stat struct read");
586 ASSERT_EMPTYBUF();
589 static char *
590 do_wstat(int fid, const struct np_stat *st)
592 char *errstr;
594 twstat(fid, st);
595 do_send();
596 recv_msg();
598 if ((errstr = check(Rwstat, iota_tag)) != NULL)
599 return errstr;
601 ASSERT_EMPTYBUF();
603 return NULL;
606 static size_t
607 do_read(int fid, uint64_t off, uint32_t count, void *data)
609 uint32_t r;
611 tread(fid, off, count);
612 do_send();
613 recv_msg();
614 expect2(Rread, iota_tag);
616 r = np_read32(buf);
617 assert(r == EVBUFFER_LENGTH(buf));
618 assert(r <= count);
619 evbuffer_remove(buf, data, r);
621 ASSERT_EMPTYBUF();
623 return r;
626 static size_t
627 do_write(int fid, uint64_t off, uint32_t count, void *data)
629 uint32_t r;
631 twrite(fid, off, data, count);
632 do_send();
633 recv_msg();
634 expect2(Rwrite, iota_tag);
636 r = np_read32(buf);
637 assert(r <= count);
639 ASSERT_EMPTYBUF();
641 return r;
644 static void
645 draw_progress(const char *pre, const struct progress *p)
647 struct winsize ws;
648 int i, l, w;
649 double perc;
651 if (xdump)
652 return;
654 perc = 100.0 * p->done / p->max;
655 if (!tty_p) {
656 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
657 return;
660 if (resized) {
661 resized = 0;
663 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
664 return;
665 tty_width = ws.ws_col;
667 w = tty_width;
669 if (pre == NULL ||
670 ((l = printf("\r%s ", pre)) == -1 || l >= w))
671 return;
673 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
674 if (w < 0) {
675 printf("%4d%%\n", (int)perc);
676 return;
679 printf("|");
681 l = w * MIN(100.0, perc) / 100.0;
682 for (i = 0; i < l; i++)
683 printf("*");
684 for (; i < w; i++)
685 printf(" ");
686 printf("|%4d%%", (int)perc);
688 fflush(stdout);
691 static int
692 fetch_fid(int fid, int fd, const char *name)
694 struct progress p = {0};
695 struct np_stat st;
696 size_t r;
697 int ret = 0;
698 char buf[BUFSIZ];
700 do_stat(fid, &st);
701 do_open(fid, KOREAD);
703 p.max = st.length;
704 for (;;) {
705 size_t off;
706 ssize_t nw;
708 r = do_read(fid, p.done, sizeof(buf), buf);
709 if (r == 0)
710 break;
712 for (off = 0; off < r; off += nw)
713 if ((nw = write(fd, buf + off, r - off)) == 0 ||
714 nw == -1) {
715 ret = -1;
716 goto end;
719 p.done += r;
720 draw_progress(name, &p);
722 #if 0
723 /* throttle, for debugging purpose */
725 struct timespec ts = { 0, 500000000 };
726 nanosleep(&ts, NULL);
728 #endif
731 end:
732 putchar('\n');
734 do_clunk(fid);
735 return ret;
738 static void
739 send_fid(int fid, const char *fnam, int open_flags, int fd, const char *name)
741 struct progress p = {0};
742 struct stat sb;
743 ssize_t r;
744 size_t w;
745 char buf[BUFSIZ];
747 if (fstat(fd, &sb) == -1)
748 err(1, "fstat");
750 if (fnam != NULL)
751 do_create(fid, fnam, 0644, KOWRITE);
752 else
753 do_open(fid, open_flags | KOWRITE);
755 p.max = sb.st_size;
756 for (;;) {
757 r = read(fd, buf, sizeof(buf));
758 if (r == 0)
759 break;
760 if (r == -1)
761 err(1, "read");
763 w = do_write(fid, p.done, r, buf);
764 p.done += w;
766 draw_progress(name, &p);
768 #if 0
769 /* throttle, for debugging purpose */
771 struct timespec ts = { 0, 500000000 };
772 nanosleep(&ts, NULL);
774 #endif
777 putchar('\n');
778 do_clunk(fid);
781 static int
782 woc_file(int fd, const char *prompt, const char *path)
784 struct qid qid;
785 const char *n = NULL;
786 char *errstr;
787 int nfid, miss;
789 nfid = nextfid();
790 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
791 if (errstr != NULL && miss > 1) {
792 printf("%s: %s\n", path, errstr);
793 free(errstr);
794 return -1;
797 if (errstr != NULL || miss == 1) {
798 char p[PATH_MAX], *dn;
800 /*
801 * If it's only one component missing (the file name), walk
802 * to the parent directory and try to create the file.
803 */
805 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
806 printf("path too long: %s\n", path);
807 return -1;
809 dn = dirname(p);
811 if (!strcmp(dn, ".")) {
812 errstr = dup_fid(pwdfid, nfid);
813 miss = 0;
814 } else
815 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
817 if (errstr != NULL) {
818 printf("%s: %s\n", dn, errstr);
819 free(errstr);
820 return -1;
823 if (miss != 0) {
824 printf("%s: not a directory\n", dn);
825 return -1;
828 if ((n = strrchr(path, '/')) != NULL)
829 n++;
830 else
831 n = path;
834 free(errstr);
836 if (miss > 1) {
837 printf("can't create %s: missing %d path component(s)\n",
838 path, miss);
839 return -1;
842 send_fid(nfid, n, KOTRUNC, fd, prompt);
843 return 0;
846 static void
847 do_tls_connect(const char *host, const char *port)
849 int handshake;
851 if ((tlsconf = tls_config_new()) == NULL)
852 fatalx("tls_config_new");
853 tls_config_insecure_noverifycert(tlsconf);
854 tls_config_insecure_noverifyname(tlsconf);
856 if (keypath == NULL)
857 keypath = crtpath;
859 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
860 fatalx("can't load certs (%s, %s)", crtpath, keypath);
862 if ((ctx = tls_client()) == NULL)
863 fatal("tls_client");
864 if (tls_configure(ctx, tlsconf) == -1)
865 fatalx("tls_configure: %s", tls_error(ctx));
867 if (tls_connect(ctx, host, port) == -1)
868 fatalx("can't connect to %s:%s: %s", host, port,
869 tls_error(ctx));
871 for (handshake = 0; !handshake;) {
872 switch (tls_handshake(ctx)) {
873 case -1:
874 fatalx("tls_handshake: %s", tls_error(ctx));
875 case 0:
876 handshake = 1;
877 break;
882 static void
883 do_ctxt_connect(const char *host, const char *port)
885 struct addrinfo hints, *res, *res0;
886 int error, saved_errno;
887 const char *cause = NULL;
889 memset(&hints, 0, sizeof(hints));
890 hints.ai_family = AF_UNSPEC;
891 hints.ai_socktype = SOCK_STREAM;
892 error = getaddrinfo(host, port, &hints, &res0);
893 if (error)
894 errx(1, "%s", gai_strerror(error));
896 sock = -1;
897 for (res = res0; res != NULL; res = res->ai_next) {
898 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
899 res->ai_protocol);
900 if (sock == -1) {
901 cause = "socket";
902 continue;
905 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
906 cause = "connect";
907 saved_errno = errno;
908 close(sock);
909 errno = saved_errno;
910 sock = -1;
911 continue;
914 break;
917 if (sock == -1)
918 err(1, "%s", cause);
919 freeaddrinfo(res0);
922 static void
923 do_connect(const char *connspec, const char *path)
925 char *host, *colon;
926 const char *port;
928 host = xstrdup(connspec);
929 if ((colon = strchr(host, ':')) != NULL) {
930 *colon = '\0';
931 port = ++colon;
932 } else
933 port = "1337";
935 printf("connecting to %s:%s...", host, port);
936 fflush(stdout);
938 if (tls)
939 do_tls_connect(host, port);
940 else
941 do_ctxt_connect(host, port);
943 printf(" done!\n");
945 do_version();
946 do_attach(path);
948 free(host);
951 static int
952 tmp_file(char sfn[TMPFSTRLEN])
954 int tmpfd;
956 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
957 if ((tmpfd = mkstemp(sfn)) == -1) {
958 warn("mkstemp %s", sfn);
959 return -1;
962 /* set the close-on-exec flag */
963 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
964 warn("fcntl");
965 close(tmpfd);
966 return -1;
969 return tmpfd;
972 static inline const char *
973 pp_perm(uint8_t x)
975 switch (x & 0x7) {
976 case 0x0:
977 return "---";
978 case 0x1:
979 return "--x";
980 case 0x2:
981 return "-w-";
982 case 0x3:
983 return "-wx";
984 case 0x4:
985 return "r--";
986 case 0x5:
987 return "r-x";
988 case 0x6:
989 return "rw-";
990 case 0x7:
991 return "rwx";
992 default:
993 /* unreachable, just for the compiler' happiness */
994 return "???";
998 static inline void
999 prepare_wstat(struct np_stat *st)
1001 memset(st, 0xFF, sizeof(*st));
1002 st->name = NULL;
1003 st->uid = NULL;
1004 st->gid = NULL;
1005 st->muid = NULL;
1008 static void
1009 cmd_bell(int argc, const char **argv)
1011 if (argc == 0) {
1012 bell = !bell;
1013 if (bell)
1014 puts("bell mode enabled");
1015 else
1016 puts("bell mode disabled");
1017 return;
1020 if (argc != 1)
1021 goto usage;
1023 if (!strcmp(*argv, "on")) {
1024 bell = 1;
1025 puts("bell mode enabled");
1026 return;
1029 if (!strcmp(*argv, "off")) {
1030 bell = 0;
1031 puts("bell mode disabled");
1032 return;
1035 usage:
1036 printf("bell [on | off]\n");
1039 static void
1040 cmd_bye(int argc, const char **argv)
1042 log_warnx("bye\n");
1043 exit(0);
1046 static void
1047 cmd_cd(int argc, const char **argv)
1049 struct qid qid;
1050 int nfid, miss;
1051 char *errstr;
1053 if (argc != 1) {
1054 printf("usage: cd remote-path\n");
1055 return;
1058 nfid = nextfid();
1059 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1060 if (errstr != NULL) {
1061 printf("%s: %s\n", argv[0], errstr);
1062 free(errstr);
1063 return;
1066 if (miss != 0 || !(qid.type & QTDIR)) {
1067 printf("%s: not a directory\n", argv[0]);
1068 if (miss == 0)
1069 do_clunk(nfid);
1070 return;
1073 do_clunk(pwdfid);
1074 pwdfid = nfid;
1077 static void
1078 cmd_edit(int argc, const char **argv)
1080 struct qid qid;
1081 int nfid, tmpfd, miss;
1082 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1083 const char *ed;
1085 if (argc != 1) {
1086 puts("usage: edit file");
1087 return;
1090 if ((ed = getenv("VISUAL")) == NULL &&
1091 (ed = getenv("EDITOR")) == NULL)
1092 ed = "ed";
1094 nfid = nextfid();
1095 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1096 if (errstr != NULL) {
1097 printf("%s: %s\n", *argv, errstr);
1098 free(errstr);
1099 return;
1102 if (miss != 0 || qid.type != 0) {
1103 printf("%s: not a file\n", *argv);
1104 if (miss == 0)
1105 do_clunk(nfid);
1106 return;
1109 if ((tmpfd = tmp_file(sfn)) == -1) {
1110 do_clunk(nfid);
1111 return;
1114 strlcpy(p, *argv, sizeof(p));
1115 name = basename(p);
1117 if (fetch_fid(nfid, tmpfd, name)) {
1118 warn("failed fetch or can't write %s", sfn);
1119 goto end;
1121 close(tmpfd);
1123 spawn(ed, sfn, NULL);
1126 * Re-open the file because it's not guaranteed that the
1127 * file descriptor tmpfd is still associated with the file
1128 * pointed by sfn: it's not uncommon for editor to write
1129 * a backup file and then rename(2) it to the file name.
1131 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1132 warn("can't open %s", sfn);
1133 goto end;
1136 woc_file(tmpfd, *argv, name);
1137 close(tmpfd);
1139 end:
1140 unlink(sfn);
1143 static void
1144 cmd_get(int argc, const char **argv)
1146 struct qid qid;
1147 const char *l;
1148 char *errstr;
1149 int nfid, fd, miss;
1151 if (argc != 1 && argc != 2) {
1152 printf("usage: get remote-file [local-file]\n");
1153 return;
1156 if (argc == 2)
1157 l = argv[1];
1158 else if ((l = strrchr(argv[0], '/')) != NULL)
1159 l++; /* skip / */
1160 else
1161 l = argv[0];
1163 nfid = nextfid();
1164 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1165 if (errstr != NULL) {
1166 printf("%s: %s\n", argv[0], errstr);
1167 free(errstr);
1168 return;
1171 if (miss != 0 || qid.type != 0) {
1172 printf("%s: not a file\n", argv[0]);
1173 if (miss == 0)
1174 do_clunk(nfid);
1175 return;
1178 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1179 warn("can't open %s", l);
1180 do_clunk(nfid);
1181 return;
1184 if (fetch_fid(nfid, fd, l) == -1)
1185 warn("write %s", l);
1186 close(fd);
1189 static void
1190 cmd_hexdump(int argc, const char **argv)
1192 if (argc == 0) {
1193 xdump = !xdump;
1194 if (xdump)
1195 puts("hexdump mode enabled");
1196 else
1197 puts("hexdump mode disabled");
1198 return;
1201 if (argc > 1)
1202 goto usage;
1204 if (!strcmp(*argv, "on")) {
1205 xdump = 1;
1206 puts("hexdump mode enabled");
1207 return;
1210 if (!strcmp(*argv, "off")) {
1211 xdump = 0;
1212 puts("hexdump mode disabled");
1213 return;
1216 usage:
1217 puts("usage: hexdump [on | off]");
1220 static void
1221 cmd_lcd(int argc, const char **argv)
1223 const char *dir;
1225 if (argc > 1) {
1226 printf("usage: lcd [local-directory]\n");
1227 return;
1230 if (argc == 1)
1231 dir = *argv;
1233 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1234 printf("HOME is not defined\n");
1235 return;
1238 if (chdir(dir) == -1)
1239 printf("cd: %s: %s\n", dir, strerror(errno));
1242 static void
1243 cmd_lpwd(int argc, const char **argv)
1245 char path[PATH_MAX];
1247 if (argc != 0) {
1248 printf("usage: lpwd\n");
1249 return;
1252 if (getcwd(path, sizeof(path)) == NULL) {
1253 printf("lpwd: %s\n", strerror(errno));
1254 return;
1257 printf("%s\n", path);
1260 static void
1261 cmd_ls(int argc, const char **argv)
1263 struct np_stat st;
1264 time_t now, mtime;
1265 struct tm *tm;
1266 uint64_t off = 0;
1267 uint32_t len;
1268 int nfid;
1269 const char *timfmt;
1270 char fmt[FMT_SCALED_STRSIZE], tim[13], *errstr;
1272 if (argc != 0) {
1273 printf("ls don't take arguments (yet)\n");
1274 return;
1277 now = time(NULL);
1279 nfid = nextfid();
1280 if ((errstr = dup_fid(pwdfid, nfid)) != NULL) {
1281 printf(".: %s\n", errstr);
1282 free(errstr);
1283 return;
1286 do_open(nfid, KOREAD);
1288 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1290 for (;;) {
1291 tread(nfid, off, BUFSIZ);
1292 do_send();
1293 recv_msg();
1294 expect2(Rread, iota_tag);
1296 len = np_read32(buf);
1297 if (len == 0)
1298 break;
1300 evbuffer_add_buffer(dirbuf, buf);
1301 off += len;
1303 ASSERT_EMPTYBUF();
1306 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1307 if (np_read_stat(dirbuf, &st) == -1)
1308 errx(1, "invalid stat struct read");
1310 if (fmt_scaled(st.length, fmt) == -1)
1311 strlcpy(fmt, "xxx", sizeof(fmt));
1313 mtime = st.mtime;
1315 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
1316 timfmt = "%b %e %R";
1317 else
1318 timfmt = "%b %e %Y";
1320 if ((tm = localtime(&mtime)) == NULL ||
1321 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1322 strlcpy(tim, "unknown", sizeof(tim));
1324 if (st.qid.type & QTDIR)
1325 printf("d");
1326 else
1327 printf("-");
1328 printf("%s", pp_perm(st.mode >> 6));
1329 printf("%s", pp_perm(st.mode >> 3));
1330 printf("%s", pp_perm(st.mode));
1331 printf(" %8s %12s %s%s\n", fmt, tim, st.name,
1332 st.qid.type & QTDIR ? "/" : "");
1334 free(st.name);
1335 free(st.uid);
1336 free(st.gid);
1337 free(st.muid);
1340 do_clunk(nfid);
1343 static void
1344 cmd_page(int argc, const char **argv)
1346 struct qid qid;
1347 int nfid, tmpfd, miss, r;
1348 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1349 const char *pager;
1351 if (argc != 1) {
1352 puts("usage: page file");
1353 return;
1356 if ((pager = getenv("PAGER")) == NULL)
1357 pager = "less";
1359 nfid = nextfid();
1360 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1361 if (errstr != NULL) {
1362 printf("%s: %s\n", *argv, errstr);
1363 free(errstr);
1364 return;
1367 if (miss != 0 || qid.type != 0) {
1368 printf("%s: not a file\n", *argv);
1369 if (miss == 0)
1370 do_clunk(nfid);
1371 return;
1374 if ((tmpfd = tmp_file(sfn)) == -1) {
1375 do_clunk(nfid);
1376 return;
1379 strlcpy(p, *argv, sizeof(p));
1380 name = basename(p);
1381 if ((r = fetch_fid(nfid, tmpfd, name)) == -1)
1382 warn("write %s", sfn);
1383 close(tmpfd);
1384 if (r != -1)
1385 spawn(pager, sfn, NULL);
1386 unlink(sfn);
1389 static void
1390 cmd_pipe(int argc, const char **argv)
1392 struct qid qid;
1393 pid_t pid;
1394 int nfid, tmpfd, miss, status;
1395 int filedes[2]; /* read end, write end */
1396 char *errstr;
1398 if (argc < 2) {
1399 puts("usage: pipe remote-file cmd [args...]");
1400 return;
1403 nfid = nextfid();
1404 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1405 if (errstr != NULL) {
1406 printf("%s: %s\n", *argv, errstr);
1407 free(errstr);
1408 return;
1411 if (miss != 0 || qid.type != 0) {
1412 printf("%s: not a file\n", *argv);
1413 if (miss == 0)
1414 do_clunk(nfid);
1415 return;
1418 if (pipe(filedes) == -1)
1419 err(1, "pipe");
1421 switch (pid = vfork()) {
1422 case -1:
1423 err(1, "vfork");
1424 case 0:
1425 close(filedes[1]);
1426 if (dup2(filedes[0], 0) == -1)
1427 err(1, "dup2");
1428 execvp(argv[1], (char *const *)argv + 1);
1429 err(1, "execvp");
1432 close(filedes[0]);
1433 if (fetch_fid(nfid, filedes[1], *argv) == -1)
1434 warnx("failed to fetch all the file");
1435 close(filedes[1]);
1437 waitpid(pid, &status, 0);
1440 static void
1441 cmd_put(int argc, const char **argv)
1443 struct qid qid;
1444 const char *l;
1445 int fd;
1447 if (argc != 1 && argc != 2) {
1448 printf("usage: put local-file [remote-file]\n");
1449 return;
1452 if (argc == 2)
1453 l = argv[1];
1454 else if ((l = strrchr(argv[0], '/')) != NULL)
1455 l++; /* skip / */
1456 else
1457 l = argv[0];
1459 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1460 warn("%s", argv[0]);
1461 return;
1464 woc_file(fd, argv[0], l);
1465 close(fd);
1468 static void
1469 cmd_rename(int argc, const char **argv)
1471 struct np_stat st;
1472 struct qid qid;
1473 char *errstr;
1474 int nfid, miss;
1476 if (argc != 2) {
1477 puts("usage: rename remote-file new-remote-name");
1478 return;
1481 nfid = nextfid();
1482 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1483 if (errstr != NULL) {
1484 printf("%s: %s\n", argv[0], errstr);
1485 free(errstr);
1486 return;
1489 if (miss != 0) {
1490 printf("%s: not such file or directory\n", argv[0]);
1491 return;
1494 prepare_wstat(&st);
1495 st.name = (char *)argv[1];
1496 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1497 printf("rename: %s\n", errstr);
1498 free(errstr);
1501 do_clunk(nfid);
1504 static void
1505 cmd_verbose(int argc, const char **argv)
1507 if (argc == 0) {
1508 log_setverbose(!log_getverbose());
1509 if (log_getverbose())
1510 puts("verbose mode enabled");
1511 else
1512 puts("verbose mode disabled");
1513 return;
1516 if (argc != 1)
1517 goto usage;
1519 if (!strcmp(*argv, "on")) {
1520 log_setverbose(1);
1521 puts("verbose mode enabled");
1522 return;
1525 if (!strcmp(*argv, "off")) {
1526 log_setverbose(0);
1527 puts("verbose mode disabled");
1528 return;
1531 usage:
1532 printf("verbose [on | off]\n");
1535 static void
1536 excmd(int argc, const char **argv)
1538 struct cmd {
1539 const char *name;
1540 void (*fn)(int, const char **);
1541 } cmds[] = {
1542 {"bell", cmd_bell},
1543 {"bye", cmd_bye},
1544 {"cd", cmd_cd},
1545 {"edit", cmd_edit},
1546 {"get", cmd_get},
1547 {"hexdump", cmd_hexdump},
1548 {"lcd", cmd_lcd},
1549 {"lpwd", cmd_lpwd},
1550 {"ls", cmd_ls},
1551 {"page", cmd_page},
1552 {"pipe", cmd_pipe},
1553 {"put", cmd_put},
1554 {"quit", cmd_bye},
1555 {"rename", cmd_rename},
1556 {"verbose", cmd_verbose},
1558 size_t i;
1560 if (argc == 0)
1561 return;
1562 for (i = 0; i < nitems(cmds); ++i) {
1563 if (!strcmp(cmds[i].name, *argv)) {
1564 cmds[i].fn(argc-1, argv+1);
1565 return;
1569 log_warnx("unknown command %s", *argv);
1572 int
1573 main(int argc, char **argv)
1575 int ch;
1577 log_init(1, LOG_DAEMON);
1578 log_setverbose(0);
1579 log_procinit(getprogname());
1581 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
1582 switch (ch) {
1583 case 'C':
1584 tls = 1;
1585 crtpath = optarg;
1586 break;
1587 case 'c':
1588 tls = 1;
1589 break;
1590 case 'K':
1591 tls = 1;
1592 keypath = optarg;
1593 break;
1594 default:
1595 usage(1);
1598 argc -= optind;
1599 argv += optind;
1601 if (argc == 0 || (tls && crtpath == NULL))
1602 usage(1);
1604 signal(SIGPIPE, SIG_IGN);
1605 if (isatty(1)) {
1606 tty_p = 1;
1607 resized = 1;
1608 signal(SIGWINCH, tty_resized);
1611 if ((evb = evbuffer_new()) == NULL)
1612 fatal("evbuffer_new");
1614 if ((buf = evbuffer_new()) == NULL)
1615 fatal("evbuffer_new");
1617 if ((dirbuf = evbuffer_new()) == NULL)
1618 fatal("evbuferr_new");
1620 do_connect(argv[0], argv[1]);
1622 for (;;) {
1623 int argc = 0;
1624 char *line, *argv[16] = {0}, **ap;
1626 if ((line = read_line("kamiftp> ")) == NULL)
1627 break;
1629 for (argc = 0, ap = argv; ap < &argv[15] &&
1630 (*ap = strsep(&line, " \t")) != NULL;) {
1631 if (**ap != '\0')
1632 ap++, argc++;
1634 excmd(argc, (const char **)argv);
1636 if (bell) {
1637 printf("\a");
1638 fflush(stdout);
1641 free(line);
1644 printf("\n");