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 struct tls_config *tlsconf;
68 struct tls *ctx;
69 int sock;
70 struct evbuffer *buf;
71 struct evbuffer *dirbuf;
72 uint32_t msize;
73 int bell;
75 volatile sig_atomic_t resized;
76 int tty_p;
77 int tty_width;
78 int xdump;
80 struct progress {
81 uint64_t max;
82 uint64_t done;
83 };
85 int pwdfid;
87 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
89 #if !HAVE_READLINE
90 char *
91 readline(const char *prompt)
92 {
93 char *ch, *line = NULL;
94 size_t linesize = 0;
95 ssize_t linelen;
97 printf("%s", prompt);
98 fflush(stdout);
100 linelen = getline(&line, &linesize, stdin);
101 if (linelen == -1)
102 return NULL;
104 if ((ch = strchr(line, '\n')) != NULL)
105 *ch = '\0';
106 return line;
109 void
110 add_history(const char *line)
112 return;
114 #endif
116 static char *
117 read_line(const char *prompt)
119 char *line;
121 again:
122 if ((line = readline(prompt)) == NULL)
123 return NULL;
124 /* XXX: trim spaces? */
125 if (*line == '\0') {
126 free(line);
127 goto again;
130 add_history(line);
131 return line;
134 static void
135 spawn(const char *argv0, ...)
137 pid_t pid;
138 size_t i;
139 int status;
140 const char *argv[16], *last;
141 va_list ap;
143 memset(argv, 0, sizeof(argv));
145 va_start(ap, argv0);
146 argv[0] = argv0;
147 for (i = 1; i < nitems(argv); ++i) {
148 last = va_arg(ap, const char *);
149 if (last == NULL)
150 break;
151 argv[i] = last;
153 va_end(ap);
155 assert(last == NULL);
157 switch (pid = fork()) {
158 case -1:
159 err(1, "fork");
160 case 0: /* child */
161 execvp(argv[0], (char *const *)argv);
162 err(1, "execvp");
163 default:
164 waitpid(pid, &status, 0);
168 static void
169 tty_resized(int signo)
171 resized = 1;
174 static void __dead
175 usage(int ret)
177 fprintf(stderr, "usage: %s [-c] [-C cert] [-K key] "
178 "host[:port] [path]\n", getprogname());
179 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
180 exit(ret);
183 static int
184 nextfid(void)
186 uint32_t i;
188 for (i = 0; ; ++i) {
189 if (i != pwdfid)
190 return i;
194 static void
195 do_send(void)
197 const void *buf;
198 size_t nbytes;
199 ssize_t r;
201 if (xdump)
202 hexdump("outgoing message", EVBUFFER_DATA(evb),
203 EVBUFFER_LENGTH(evb));
205 while (EVBUFFER_LENGTH(evb) != 0) {
206 buf = EVBUFFER_DATA(evb);
207 nbytes = EVBUFFER_LENGTH(evb);
209 if (ctx == NULL) {
210 r = write(sock, buf, nbytes);
211 if (r == 0 || r == -1)
212 errx(1, "EOF");
213 } else {
214 r = tls_write(ctx, buf, nbytes);
215 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
216 continue;
217 if (r == -1)
218 errx(1, "tls: %s", tls_error(ctx));
221 evbuffer_drain(evb, r);
225 static void
226 mustread(void *d, size_t len)
228 ssize_t r;
230 while (len != 0) {
231 if (ctx == NULL) {
232 r = read(sock, d, len);
233 if (r == 0 || r == -1)
234 errx(1, "EOF");
235 } else {
236 r = tls_read(ctx, d, len);
237 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
238 continue;
239 if (r == -1)
240 errx(1, "tls: %s", tls_error(ctx));
243 d += r;
244 len -= r;
248 static void
249 recv_msg(void)
251 uint32_t len, l;
252 char tmp[BUFSIZ];
254 mustread(&len, sizeof(len));
255 len = le32toh(len);
256 if (len < HEADERSIZE)
257 errx(1, "read message of invalid length %d", len);
259 len -= 4; /* skip the length just read */
261 while (len != 0) {
262 l = MIN(len, sizeof(tmp));
263 mustread(tmp, l);
264 len -= l;
265 evbuffer_add(buf, tmp, l);
268 if (xdump)
269 hexdump("incoming packet", EVBUFFER_DATA(buf),
270 EVBUFFER_LENGTH(buf));
273 static uint64_t
274 np_read64(struct evbuffer *buf)
276 uint64_t n;
278 evbuffer_remove(buf, &n, sizeof(n));
279 return le64toh(n);
282 static uint32_t
283 np_read32(struct evbuffer *buf)
285 uint32_t n;
287 evbuffer_remove(buf, &n, sizeof(n));
288 return le32toh(n);
291 static uint16_t
292 np_read16(struct evbuffer *buf)
294 uint16_t n;
296 evbuffer_remove(buf, &n, sizeof(n));
297 return le16toh(n);
300 static uint16_t
301 np_read8(struct evbuffer *buf)
303 uint8_t n;
305 evbuffer_remove(buf, &n, sizeof(n));
306 return n;
309 static char *
310 np_readstr(struct evbuffer *buf)
312 uint16_t len;
313 char *str;
315 len = np_read16(buf);
316 assert(EVBUFFER_LENGTH(buf) >= len);
318 if ((str = calloc(1, len+1)) == NULL)
319 err(1, "calloc");
320 evbuffer_remove(buf, str, len);
321 return str;
324 static void
325 np_read_qid(struct evbuffer *buf, struct qid *qid)
327 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
329 qid->type = np_read8(buf);
330 qid->vers = np_read32(buf);
331 qid->path = np_read64(buf);
334 static int
335 np_read_stat(struct evbuffer *buf, struct np_stat *st)
337 uint16_t size;
339 memset(st, 0, sizeof(*st));
341 size = np_read16(buf);
342 if (size > EVBUFFER_LENGTH(buf))
343 return -1;
345 st->type = np_read16(buf);
346 st->dev = np_read32(buf);
347 np_read_qid(buf, &st->qid);
348 st->mode = np_read32(buf);
349 st->atime = np_read32(buf);
350 st->mtime = np_read32(buf);
351 st->length = np_read64(buf);
352 st->name = np_readstr(buf);
353 st->uid = np_readstr(buf);
354 st->gid = np_readstr(buf);
355 st->muid = np_readstr(buf);
357 return 0;
360 static void
361 expect(uint8_t type)
363 uint8_t t;
365 t = np_read8(buf);
366 if (t == type)
367 return;
369 if (t == Rerror) {
370 char *err;
372 /* skip tag */
373 np_read16(buf);
375 err = np_readstr(buf);
376 errx(1, "expected %s, got error %s",
377 pp_msg_type(type), err);
380 errx(1, "expected %s, got msg type %s",
381 pp_msg_type(type), pp_msg_type(t));
384 static void
385 expect2(uint8_t type, uint16_t tag)
387 uint16_t t;
389 expect(type);
391 t = np_read16(buf);
392 if (t == tag)
393 return;
395 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
398 static char *
399 check(uint8_t type, uint16_t tag)
401 uint16_t rtag;
402 uint8_t rtype;
404 rtype = np_read8(buf);
405 rtag = np_read16(buf);
406 if (rtype == type) {
407 if (rtag != tag)
408 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
409 return NULL;
412 if (rtype == Rerror)
413 return np_readstr(buf);
415 errx(1, "expected %s, got msg type %s",
416 pp_msg_type(type), pp_msg_type(rtype));
419 static void
420 do_version(void)
422 char *version;
424 tversion(VERSION9P, MSIZE9P);
425 do_send();
426 recv_msg();
427 expect2(Rversion, NOTAG);
429 msize = np_read32(buf);
430 version = np_readstr(buf);
432 if (msize > MSIZE9P || msize < 256)
433 errx(1, "got unexpected msize: %d", msize);
434 if (strcmp(version, VERSION9P))
435 errx(1, "unexpected 9p version: %s", version);
437 free(version);
438 ASSERT_EMPTYBUF();
441 static void
442 do_attach(const char *path)
444 struct qid qid;
446 if (path == NULL)
447 path = "/";
449 tattach(pwdfid, NOFID, user, path);
450 do_send();
451 recv_msg();
452 expect2(Rattach, iota_tag);
453 np_read_qid(buf, &qid);
455 ASSERT_EMPTYBUF();
458 static uint32_t
459 do_open(uint32_t fid, uint8_t mode)
461 struct qid qid;
462 uint32_t iounit;
464 topen(fid, mode);
465 do_send();
466 recv_msg();
467 expect2(Ropen, iota_tag);
469 np_read_qid(buf, &qid);
470 iounit = np_read32(buf);
472 ASSERT_EMPTYBUF();
474 return iounit;
477 static uint32_t
478 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
480 struct qid qid;
481 uint32_t iounit;
483 tcreate(fid, name, perm, mode);
484 do_send();
485 recv_msg();
486 expect2(Rcreate, iota_tag);
488 np_read_qid(buf, &qid);
489 iounit = np_read32(buf);
491 ASSERT_EMPTYBUF();
493 return iounit;
496 static void
497 do_clunk(uint32_t fid)
499 tclunk(fid);
500 do_send();
501 recv_msg();
502 expect2(Rclunk, iota_tag);
504 ASSERT_EMPTYBUF();
507 static char *
508 dup_fid(int fid, int nfid)
510 uint16_t nwqid;
511 char *errstr;
513 twalk(fid, nfid, NULL, 0);
514 do_send();
515 recv_msg();
517 if ((errstr = check(Rwalk, iota_tag)) != NULL)
518 return errstr;
520 nwqid = np_read16(buf);
521 assert(nwqid == 0);
523 ASSERT_EMPTYBUF();
525 return NULL;
528 static char *
529 walk_path(int fid, int newfid, const char *path, int *missing,
530 struct qid *qid)
532 char *wnames[MAXWELEM], *p, *t, *errstr;
533 size_t nwname, i;
534 uint16_t nwqid;
536 if ((p = strdup(path)) == NULL)
537 err(1, "strdup");
538 t = p;
540 /* strip initial ./ */
541 if (t[0] == '.' && t[1] == '/')
542 t += 2;
544 for (nwname = 0; nwname < nitems(wnames) &&
545 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
546 if (*wnames[nwname] != '\0')
547 nwname++;
550 twalk(fid, newfid, (const char **)wnames, nwname);
551 do_send();
552 recv_msg();
554 *missing = nwname;
555 if ((errstr = check(Rwalk, iota_tag)) != NULL) {
556 free(p);
557 return errstr;
560 nwqid = np_read16(buf);
561 assert(nwqid <= nwname);
563 /* consume all qids */
564 for (i = 0; i < nwqid; ++i)
565 np_read_qid(buf, qid);
567 free(p);
569 *missing = nwname - nwqid;
570 return NULL;
573 static void
574 do_stat(int fid, struct np_stat *st)
576 tstat(fid);
577 do_send();
578 recv_msg();
579 expect2(Rstat, iota_tag);
581 /* eat up the first two byte length */
582 np_read16(buf);
584 if (np_read_stat(buf, st) == -1)
585 errx(1, "invalid stat struct read");
587 ASSERT_EMPTYBUF();
590 static char *
591 do_wstat(int fid, const struct np_stat *st)
593 char *errstr;
595 twstat(fid, st);
596 do_send();
597 recv_msg();
599 if ((errstr = check(Rwstat, iota_tag)) != NULL)
600 return errstr;
602 ASSERT_EMPTYBUF();
604 return NULL;
607 static size_t
608 do_read(int fid, uint64_t off, uint32_t count, void *data)
610 uint32_t r;
612 tread(fid, off, count);
613 do_send();
614 recv_msg();
615 expect2(Rread, iota_tag);
617 r = np_read32(buf);
618 assert(r == EVBUFFER_LENGTH(buf));
619 assert(r <= count);
620 evbuffer_remove(buf, data, r);
622 ASSERT_EMPTYBUF();
624 return r;
627 static size_t
628 do_write(int fid, uint64_t off, uint32_t count, void *data)
630 uint32_t r;
632 twrite(fid, off, data, count);
633 do_send();
634 recv_msg();
635 expect2(Rwrite, iota_tag);
637 r = np_read32(buf);
638 assert(r <= count);
640 ASSERT_EMPTYBUF();
642 return r;
645 static void
646 draw_progress(const char *pre, const struct progress *p)
648 struct winsize ws;
649 int i, l, w;
650 double perc;
652 if (xdump)
653 return;
655 perc = 100.0 * p->done / p->max;
656 if (!tty_p) {
657 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
658 return;
661 if (resized) {
662 resized = 0;
664 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
665 return;
666 tty_width = ws.ws_col;
668 w = tty_width;
670 if (pre == NULL ||
671 ((l = printf("\r%s ", pre)) == -1 || l >= w))
672 return;
674 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
675 if (w < 0) {
676 printf("%4d%%\n", (int)perc);
677 return;
680 printf("|");
682 l = w * MIN(100.0, perc) / 100.0;
683 for (i = 0; i < l; i++)
684 printf("*");
685 for (; i < w; i++)
686 printf(" ");
687 printf("|%4d%%", (int)perc);
689 fflush(stdout);
692 static int
693 fetch_fid(int fid, int fd, const char *name)
695 static char buf[MSIZE9P];
696 struct progress p = {0};
697 struct np_stat st;
698 size_t r;
699 int ret = 0;
701 do_stat(fid, &st);
702 do_open(fid, KOREAD);
704 p.max = st.length;
705 for (;;) {
706 size_t len, off;
707 ssize_t nw;
709 len = MIN(sizeof(buf), msize);
710 len -= IOHDRSZ; /* for the request' fields */
712 r = do_read(fid, p.done, len, buf);
713 if (r == 0)
714 break;
716 for (off = 0; off < r; off += nw)
717 if ((nw = write(fd, buf + off, r - off)) == 0 ||
718 nw == -1) {
719 ret = -1;
720 goto end;
723 p.done += r;
724 draw_progress(name, &p);
726 #if 0
727 /* throttle, for debugging purpose */
729 struct timespec ts = { 0, 500000000 };
730 nanosleep(&ts, NULL);
732 #endif
735 end:
736 putchar('\n');
738 do_clunk(fid);
739 return ret;
742 static void
743 send_fid(int fid, const char *fnam, int open_flags, int fd, const char *name)
745 static char buf[MSIZE9P];
746 struct progress p = {0};
747 struct stat sb;
748 ssize_t r;
749 size_t w, len;
751 if (fstat(fd, &sb) == -1)
752 err(1, "fstat");
754 if (fnam != NULL)
755 do_create(fid, fnam, 0644, KOWRITE);
756 else
757 do_open(fid, open_flags | KOWRITE);
759 p.max = sb.st_size;
760 for (;;) {
761 len = MIN(sizeof(buf), msize);
762 len -= HEADERSIZE + 4 + 4 + 8; /* for the request' fields */
764 r = read(fd, buf, len);
765 if (r == 0)
766 break;
767 if (r == -1)
768 err(1, "read");
770 w = do_write(fid, p.done, r, buf);
771 p.done += w;
773 draw_progress(name, &p);
775 #if 0
776 /* throttle, for debugging purpose */
778 struct timespec ts = { 0, 500000000 };
779 nanosleep(&ts, NULL);
781 #endif
784 putchar('\n');
785 do_clunk(fid);
788 static int
789 woc_file(int fd, const char *prompt, const char *path)
791 struct qid qid;
792 const char *n = NULL;
793 char *errstr;
794 int nfid, miss;
796 nfid = nextfid();
797 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
798 if (errstr != NULL && miss > 1) {
799 printf("%s: %s\n", path, errstr);
800 free(errstr);
801 return -1;
804 if (errstr != NULL || miss == 1) {
805 char p[PATH_MAX], *dn;
807 /*
808 * If it's only one component missing (the file name), walk
809 * to the parent directory and try to create the file.
810 */
812 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
813 printf("path too long: %s\n", path);
814 return -1;
816 dn = dirname(p);
818 if (!strcmp(dn, ".")) {
819 errstr = dup_fid(pwdfid, nfid);
820 miss = 0;
821 } else
822 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
824 if (errstr != NULL) {
825 printf("%s: %s\n", dn, errstr);
826 free(errstr);
827 return -1;
830 if (miss != 0) {
831 printf("%s: not a directory\n", dn);
832 return -1;
835 if ((n = strrchr(path, '/')) != NULL)
836 n++;
837 else
838 n = path;
841 free(errstr);
843 if (miss > 1) {
844 printf("can't create %s: missing %d path component(s)\n",
845 path, miss);
846 return -1;
849 send_fid(nfid, n, KOTRUNC, fd, prompt);
850 return 0;
853 static void
854 do_tls_connect(const char *host, const char *port)
856 int handshake;
858 if ((tlsconf = tls_config_new()) == NULL)
859 fatalx("tls_config_new");
860 tls_config_insecure_noverifycert(tlsconf);
861 tls_config_insecure_noverifyname(tlsconf);
863 if (keypath == NULL)
864 keypath = crtpath;
866 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
867 fatalx("can't load certs (%s, %s)", crtpath, keypath);
869 if ((ctx = tls_client()) == NULL)
870 fatal("tls_client");
871 if (tls_configure(ctx, tlsconf) == -1)
872 fatalx("tls_configure: %s", tls_error(ctx));
874 if (tls_connect(ctx, host, port) == -1)
875 fatalx("can't connect to %s:%s: %s", host, port,
876 tls_error(ctx));
878 for (handshake = 0; !handshake;) {
879 switch (tls_handshake(ctx)) {
880 case -1:
881 fatalx("tls_handshake: %s", tls_error(ctx));
882 case 0:
883 handshake = 1;
884 break;
889 static void
890 do_ctxt_connect(const char *host, const char *port)
892 struct addrinfo hints, *res, *res0;
893 int error, saved_errno;
894 const char *cause = NULL;
896 memset(&hints, 0, sizeof(hints));
897 hints.ai_family = AF_UNSPEC;
898 hints.ai_socktype = SOCK_STREAM;
899 error = getaddrinfo(host, port, &hints, &res0);
900 if (error)
901 errx(1, "%s", gai_strerror(error));
903 sock = -1;
904 for (res = res0; res != NULL; res = res->ai_next) {
905 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
906 res->ai_protocol);
907 if (sock == -1) {
908 cause = "socket";
909 continue;
912 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
913 cause = "connect";
914 saved_errno = errno;
915 close(sock);
916 errno = saved_errno;
917 sock = -1;
918 continue;
921 break;
924 if (sock == -1)
925 err(1, "%s", cause);
926 freeaddrinfo(res0);
929 static void
930 do_connect(const char *connspec, const char *path)
932 char *t;
933 const char *port;
935 host = xstrdup(connspec);
936 if ((t = strchr(host, '@')) != NULL) {
937 if (t == host)
938 errx(1, "invalid connection string: %s", connspec);
939 *t = '\0';
940 user = host;
941 host = ++t;
942 } else if ((user = getenv("USER")) == NULL)
943 errx(1, "USER not defined");
945 if ((t = strchr(host, ':')) != NULL) {
946 *t = '\0';
947 port = ++t;
948 if (*port == '\0')
949 errx(1, "invalid connection string: %s", connspec);
950 } else
951 port = "1337";
953 printf("connecting to %s:%s...", host, port);
954 fflush(stdout);
956 if (tls)
957 do_tls_connect(host, port);
958 else
959 do_ctxt_connect(host, port);
961 printf(" done!\n");
963 do_version();
964 do_attach(path);
967 static int
968 tmp_file(char sfn[TMPFSTRLEN])
970 int tmpfd;
972 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
973 if ((tmpfd = mkstemp(sfn)) == -1) {
974 warn("mkstemp %s", sfn);
975 return -1;
978 /* set the close-on-exec flag */
979 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
980 warn("fcntl");
981 close(tmpfd);
982 return -1;
985 return tmpfd;
988 static inline const char *
989 pp_perm(uint8_t x)
991 switch (x & 0x7) {
992 case 0x0:
993 return "---";
994 case 0x1:
995 return "--x";
996 case 0x2:
997 return "-w-";
998 case 0x3:
999 return "-wx";
1000 case 0x4:
1001 return "r--";
1002 case 0x5:
1003 return "r-x";
1004 case 0x6:
1005 return "rw-";
1006 case 0x7:
1007 return "rwx";
1008 default:
1009 /* unreachable, just for the compiler' happiness */
1010 return "???";
1014 static inline void
1015 prepare_wstat(struct np_stat *st)
1017 memset(st, 0xFF, sizeof(*st));
1018 st->name = NULL;
1019 st->uid = NULL;
1020 st->gid = NULL;
1021 st->muid = NULL;
1024 static void
1025 cmd_bell(int argc, const char **argv)
1027 if (argc == 0) {
1028 bell = !bell;
1029 if (bell)
1030 puts("bell mode enabled");
1031 else
1032 puts("bell mode disabled");
1033 return;
1036 if (argc != 1)
1037 goto usage;
1039 if (!strcmp(*argv, "on")) {
1040 bell = 1;
1041 puts("bell mode enabled");
1042 return;
1045 if (!strcmp(*argv, "off")) {
1046 bell = 0;
1047 puts("bell mode disabled");
1048 return;
1051 usage:
1052 printf("bell [on | off]\n");
1055 static void
1056 cmd_bye(int argc, const char **argv)
1058 log_warnx("bye\n");
1059 exit(0);
1062 static void
1063 cmd_cd(int argc, const char **argv)
1065 struct qid qid;
1066 int nfid, miss;
1067 char *errstr;
1069 if (argc != 1) {
1070 printf("usage: cd remote-path\n");
1071 return;
1074 nfid = nextfid();
1075 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1076 if (errstr != NULL) {
1077 printf("%s: %s\n", argv[0], errstr);
1078 free(errstr);
1079 return;
1082 if (miss != 0 || !(qid.type & QTDIR)) {
1083 printf("%s: not a directory\n", argv[0]);
1084 if (miss == 0)
1085 do_clunk(nfid);
1086 return;
1089 do_clunk(pwdfid);
1090 pwdfid = nfid;
1093 static void
1094 cmd_edit(int argc, const char **argv)
1096 struct qid qid;
1097 int nfid, tmpfd, miss;
1098 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1099 const char *ed;
1101 if (argc != 1) {
1102 puts("usage: edit file");
1103 return;
1106 if ((ed = getenv("VISUAL")) == NULL &&
1107 (ed = getenv("EDITOR")) == NULL)
1108 ed = "ed";
1110 nfid = nextfid();
1111 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1112 if (errstr != NULL) {
1113 printf("%s: %s\n", *argv, errstr);
1114 free(errstr);
1115 return;
1118 if (miss != 0 || qid.type != 0) {
1119 printf("%s: not a file\n", *argv);
1120 if (miss == 0)
1121 do_clunk(nfid);
1122 return;
1125 if ((tmpfd = tmp_file(sfn)) == -1) {
1126 do_clunk(nfid);
1127 return;
1130 strlcpy(p, *argv, sizeof(p));
1131 name = basename(p);
1133 if (fetch_fid(nfid, tmpfd, name)) {
1134 warn("failed fetch or can't write %s", sfn);
1135 goto end;
1137 close(tmpfd);
1139 spawn(ed, sfn, NULL);
1142 * Re-open the file because it's not guaranteed that the
1143 * file descriptor tmpfd is still associated with the file
1144 * pointed by sfn: it's not uncommon for editor to write
1145 * a backup file and then rename(2) it to the file name.
1147 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1148 warn("can't open %s", sfn);
1149 goto end;
1152 woc_file(tmpfd, *argv, name);
1153 close(tmpfd);
1155 end:
1156 unlink(sfn);
1159 static void
1160 cmd_get(int argc, const char **argv)
1162 struct qid qid;
1163 const char *l;
1164 char *errstr;
1165 int nfid, fd, miss;
1167 if (argc != 1 && argc != 2) {
1168 printf("usage: get remote-file [local-file]\n");
1169 return;
1172 if (argc == 2)
1173 l = argv[1];
1174 else if ((l = strrchr(argv[0], '/')) != NULL)
1175 l++; /* skip / */
1176 else
1177 l = argv[0];
1179 nfid = nextfid();
1180 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1181 if (errstr != NULL) {
1182 printf("%s: %s\n", argv[0], errstr);
1183 free(errstr);
1184 return;
1187 if (miss != 0 || qid.type != 0) {
1188 printf("%s: not a file\n", argv[0]);
1189 if (miss == 0)
1190 do_clunk(nfid);
1191 return;
1194 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1195 warn("can't open %s", l);
1196 do_clunk(nfid);
1197 return;
1200 if (fetch_fid(nfid, fd, l) == -1)
1201 warn("write %s", l);
1202 close(fd);
1205 static void
1206 cmd_hexdump(int argc, const char **argv)
1208 if (argc == 0) {
1209 xdump = !xdump;
1210 if (xdump)
1211 puts("hexdump mode enabled");
1212 else
1213 puts("hexdump mode disabled");
1214 return;
1217 if (argc > 1)
1218 goto usage;
1220 if (!strcmp(*argv, "on")) {
1221 xdump = 1;
1222 puts("hexdump mode enabled");
1223 return;
1226 if (!strcmp(*argv, "off")) {
1227 xdump = 0;
1228 puts("hexdump mode disabled");
1229 return;
1232 usage:
1233 puts("usage: hexdump [on | off]");
1236 static void
1237 cmd_lcd(int argc, const char **argv)
1239 const char *dir;
1241 if (argc > 1) {
1242 printf("usage: lcd [local-directory]\n");
1243 return;
1246 if (argc == 1)
1247 dir = *argv;
1249 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1250 printf("HOME is not defined\n");
1251 return;
1254 if (chdir(dir) == -1)
1255 printf("cd: %s: %s\n", dir, strerror(errno));
1258 static void
1259 cmd_lpwd(int argc, const char **argv)
1261 char path[PATH_MAX];
1263 if (argc != 0) {
1264 printf("usage: lpwd\n");
1265 return;
1268 if (getcwd(path, sizeof(path)) == NULL) {
1269 printf("lpwd: %s\n", strerror(errno));
1270 return;
1273 printf("%s\n", path);
1276 static void
1277 cmd_ls(int argc, const char **argv)
1279 struct np_stat st;
1280 time_t now, mtime;
1281 struct tm *tm;
1282 uint64_t off = 0;
1283 uint32_t len;
1284 int nfid;
1285 const char *timfmt;
1286 char fmt[FMT_SCALED_STRSIZE], tim[13], *errstr;
1288 if (argc != 0) {
1289 printf("ls don't take arguments (yet)\n");
1290 return;
1293 now = time(NULL);
1295 nfid = nextfid();
1296 if ((errstr = dup_fid(pwdfid, nfid)) != NULL) {
1297 printf(".: %s\n", errstr);
1298 free(errstr);
1299 return;
1302 do_open(nfid, KOREAD);
1304 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1306 for (;;) {
1307 tread(nfid, off, msize - IOHDRSZ);
1308 do_send();
1309 recv_msg();
1310 expect2(Rread, iota_tag);
1312 len = np_read32(buf);
1313 if (len == 0)
1314 break;
1316 evbuffer_add_buffer(dirbuf, buf);
1317 off += len;
1319 ASSERT_EMPTYBUF();
1322 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1323 if (np_read_stat(dirbuf, &st) == -1)
1324 errx(1, "invalid stat struct read");
1326 if (fmt_scaled(st.length, fmt) == -1)
1327 strlcpy(fmt, "xxx", sizeof(fmt));
1329 mtime = st.mtime;
1331 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
1332 timfmt = "%b %e %R";
1333 else
1334 timfmt = "%b %e %Y";
1336 if ((tm = localtime(&mtime)) == NULL ||
1337 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1338 strlcpy(tim, "unknown", sizeof(tim));
1340 if (st.qid.type & QTDIR)
1341 printf("d");
1342 else
1343 printf("-");
1344 printf("%s", pp_perm(st.mode >> 6));
1345 printf("%s", pp_perm(st.mode >> 3));
1346 printf("%s", pp_perm(st.mode));
1347 printf(" %8s %12s %s%s\n", fmt, tim, st.name,
1348 st.qid.type & QTDIR ? "/" : "");
1350 free(st.name);
1351 free(st.uid);
1352 free(st.gid);
1353 free(st.muid);
1356 do_clunk(nfid);
1359 static void
1360 cmd_page(int argc, const char **argv)
1362 struct qid qid;
1363 int nfid, tmpfd, miss, r;
1364 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1365 const char *pager;
1367 if (argc != 1) {
1368 puts("usage: page file");
1369 return;
1372 if ((pager = getenv("PAGER")) == NULL)
1373 pager = "less";
1375 nfid = nextfid();
1376 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1377 if (errstr != NULL) {
1378 printf("%s: %s\n", *argv, errstr);
1379 free(errstr);
1380 return;
1383 if (miss != 0 || qid.type != 0) {
1384 printf("%s: not a file\n", *argv);
1385 if (miss == 0)
1386 do_clunk(nfid);
1387 return;
1390 if ((tmpfd = tmp_file(sfn)) == -1) {
1391 do_clunk(nfid);
1392 return;
1395 strlcpy(p, *argv, sizeof(p));
1396 name = basename(p);
1397 if ((r = fetch_fid(nfid, tmpfd, name)) == -1)
1398 warn("write %s", sfn);
1399 close(tmpfd);
1400 if (r != -1)
1401 spawn(pager, sfn, NULL);
1402 unlink(sfn);
1405 static void
1406 cmd_pipe(int argc, const char **argv)
1408 struct qid qid;
1409 pid_t pid;
1410 int nfid, tmpfd, miss, status;
1411 int filedes[2]; /* read end, write end */
1412 char *errstr;
1414 if (argc < 2) {
1415 puts("usage: pipe remote-file cmd [args...]");
1416 return;
1419 nfid = nextfid();
1420 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1421 if (errstr != NULL) {
1422 printf("%s: %s\n", *argv, errstr);
1423 free(errstr);
1424 return;
1427 if (miss != 0 || qid.type != 0) {
1428 printf("%s: not a file\n", *argv);
1429 if (miss == 0)
1430 do_clunk(nfid);
1431 return;
1434 if (pipe(filedes) == -1)
1435 err(1, "pipe");
1437 switch (pid = vfork()) {
1438 case -1:
1439 err(1, "vfork");
1440 case 0:
1441 close(filedes[1]);
1442 if (dup2(filedes[0], 0) == -1)
1443 err(1, "dup2");
1444 execvp(argv[1], (char *const *)argv + 1);
1445 err(1, "execvp");
1448 close(filedes[0]);
1449 if (fetch_fid(nfid, filedes[1], *argv) == -1)
1450 warnx("failed to fetch all the file");
1451 close(filedes[1]);
1453 waitpid(pid, &status, 0);
1456 static void
1457 cmd_put(int argc, const char **argv)
1459 struct qid qid;
1460 const char *l;
1461 int fd;
1463 if (argc != 1 && argc != 2) {
1464 printf("usage: put local-file [remote-file]\n");
1465 return;
1468 if (argc == 2)
1469 l = argv[1];
1470 else if ((l = strrchr(argv[0], '/')) != NULL)
1471 l++; /* skip / */
1472 else
1473 l = argv[0];
1475 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1476 warn("%s", argv[0]);
1477 return;
1480 woc_file(fd, argv[0], l);
1481 close(fd);
1484 static void
1485 cmd_rename(int argc, const char **argv)
1487 struct np_stat st;
1488 struct qid qid;
1489 char *errstr;
1490 int nfid, miss;
1492 if (argc != 2) {
1493 puts("usage: rename remote-file new-remote-name");
1494 return;
1497 nfid = nextfid();
1498 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1499 if (errstr != NULL) {
1500 printf("%s: %s\n", argv[0], errstr);
1501 free(errstr);
1502 return;
1505 if (miss != 0) {
1506 printf("%s: not such file or directory\n", argv[0]);
1507 return;
1510 prepare_wstat(&st);
1511 st.name = (char *)argv[1];
1512 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1513 printf("rename: %s\n", errstr);
1514 free(errstr);
1517 do_clunk(nfid);
1520 static void
1521 cmd_verbose(int argc, const char **argv)
1523 if (argc == 0) {
1524 log_setverbose(!log_getverbose());
1525 if (log_getverbose())
1526 puts("verbose mode enabled");
1527 else
1528 puts("verbose mode disabled");
1529 return;
1532 if (argc != 1)
1533 goto usage;
1535 if (!strcmp(*argv, "on")) {
1536 log_setverbose(1);
1537 puts("verbose mode enabled");
1538 return;
1541 if (!strcmp(*argv, "off")) {
1542 log_setverbose(0);
1543 puts("verbose mode disabled");
1544 return;
1547 usage:
1548 printf("verbose [on | off]\n");
1551 static void
1552 excmd(int argc, const char **argv)
1554 struct cmd {
1555 const char *name;
1556 void (*fn)(int, const char **);
1557 } cmds[] = {
1558 {"bell", cmd_bell},
1559 {"bye", cmd_bye},
1560 {"cd", cmd_cd},
1561 {"edit", cmd_edit},
1562 {"get", cmd_get},
1563 {"hexdump", cmd_hexdump},
1564 {"lcd", cmd_lcd},
1565 {"lpwd", cmd_lpwd},
1566 {"ls", cmd_ls},
1567 {"page", cmd_page},
1568 {"pipe", cmd_pipe},
1569 {"put", cmd_put},
1570 {"quit", cmd_bye},
1571 {"rename", cmd_rename},
1572 {"verbose", cmd_verbose},
1574 size_t i;
1576 if (argc == 0)
1577 return;
1578 for (i = 0; i < nitems(cmds); ++i) {
1579 if (!strcmp(cmds[i].name, *argv)) {
1580 cmds[i].fn(argc-1, argv+1);
1581 return;
1585 log_warnx("unknown command %s", *argv);
1588 int
1589 main(int argc, char **argv)
1591 int ch;
1593 log_init(1, LOG_DAEMON);
1594 log_setverbose(0);
1595 log_procinit(getprogname());
1597 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
1598 switch (ch) {
1599 case 'C':
1600 tls = 1;
1601 crtpath = optarg;
1602 break;
1603 case 'c':
1604 tls = 1;
1605 break;
1606 case 'K':
1607 tls = 1;
1608 keypath = optarg;
1609 break;
1610 default:
1611 usage(1);
1614 argc -= optind;
1615 argv += optind;
1617 if (argc == 0 || (tls && crtpath == NULL))
1618 usage(1);
1620 signal(SIGPIPE, SIG_IGN);
1621 if (isatty(1)) {
1622 tty_p = 1;
1623 resized = 1;
1624 signal(SIGWINCH, tty_resized);
1627 if ((evb = evbuffer_new()) == NULL)
1628 fatal("evbuffer_new");
1630 if ((buf = evbuffer_new()) == NULL)
1631 fatal("evbuffer_new");
1633 if ((dirbuf = evbuffer_new()) == NULL)
1634 fatal("evbuferr_new");
1636 do_connect(argv[0], argv[1]);
1638 for (;;) {
1639 int argc = 0;
1640 char *line, *argv[16] = {0}, **ap;
1642 if ((line = read_line("kamiftp> ")) == NULL)
1643 break;
1645 for (argc = 0, ap = argv; ap < &argv[15] &&
1646 (*ap = strsep(&line, " \t")) != NULL;) {
1647 if (**ap != '\0')
1648 ap++, argc++;
1650 excmd(argc, (const char **)argv);
1652 if (bell) {
1653 printf("\a");
1654 fflush(stdout);
1657 free(line);
1660 printf("\n");