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 return errstr;
557 nwqid = np_read16(buf);
558 assert(nwqid <= nwname);
560 /* consume all qids */
561 for (i = 0; i < nwqid; ++i)
562 np_read_qid(buf, qid);
564 free(p);
566 *missing = nwname - nwqid;
567 return NULL;
570 static void
571 do_stat(int fid, struct np_stat *st)
573 tstat(fid);
574 do_send();
575 recv_msg();
576 expect2(Rstat, iota_tag);
578 if (np_read_stat(buf, st) == -1)
579 errx(1, "invalid stat struct read");
581 ASSERT_EMPTYBUF();
584 static char *
585 do_wstat(int fid, const struct np_stat *st)
587 char *errstr;
589 twstat(fid, st);
590 do_send();
591 recv_msg();
593 if ((errstr = check(Rwstat, iota_tag)) != NULL)
594 return errstr;
596 ASSERT_EMPTYBUF();
598 return NULL;
601 static size_t
602 do_read(int fid, uint64_t off, uint32_t count, void *data)
604 uint32_t r;
606 tread(fid, off, count);
607 do_send();
608 recv_msg();
609 expect2(Rread, iota_tag);
611 r = np_read32(buf);
612 assert(r == EVBUFFER_LENGTH(buf));
613 assert(r <= count);
614 evbuffer_remove(buf, data, r);
616 ASSERT_EMPTYBUF();
618 return r;
621 static size_t
622 do_write(int fid, uint64_t off, uint32_t count, void *data)
624 uint32_t r;
626 twrite(fid, off, data, count);
627 do_send();
628 recv_msg();
629 expect2(Rwrite, iota_tag);
631 r = np_read32(buf);
632 assert(r <= count);
634 ASSERT_EMPTYBUF();
636 return r;
639 static void
640 draw_progress(const char *pre, const struct progress *p)
642 struct winsize ws;
643 int i, l, w;
644 double perc;
646 if (xdump)
647 return;
649 perc = 100.0 * p->done / p->max;
650 if (!tty_p) {
651 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
652 return;
655 if (resized) {
656 resized = 0;
658 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
659 return;
660 tty_width = ws.ws_col;
662 w = tty_width;
664 if (pre == NULL ||
665 ((l = printf("\r%s ", pre)) == -1 || l >= w))
666 return;
668 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
669 if (w < 0) {
670 printf("%4d%%\n", (int)perc);
671 return;
674 printf("|");
676 l = w * MIN(100.0, perc) / 100.0;
677 for (i = 0; i < l; i++)
678 printf("*");
679 for (; i < w; i++)
680 printf(" ");
681 printf("|%4d%%", (int)perc);
683 fflush(stdout);
686 static void
687 fetch_fid(int fid, int fd, const char *name)
689 struct progress p = {0};
690 struct np_stat st;
691 size_t r;
692 char buf[BUFSIZ];
694 do_stat(fid, &st);
695 do_open(fid, KOREAD);
697 p.max = st.length;
698 for (;;) {
699 size_t off;
700 ssize_t nw;
702 r = do_read(fid, p.done, sizeof(buf), buf);
703 if (r == 0)
704 break;
706 for (off = 0; off < r; off += nw)
707 if ((nw = write(fd, buf + off, r - off)) == 0 ||
708 nw == -1)
709 err(1, "write");
711 p.done += r;
712 draw_progress(name, &p);
714 #if 0
715 /* throttle, for debugging purpose */
717 struct timespec ts = { 0, 500000000 };
718 nanosleep(&ts, NULL);
720 #endif
723 putchar('\n');
725 do_clunk(fid);
728 static void
729 send_fid(int fid, const char *fnam, int fd, const char *name)
731 struct progress p = {0};
732 struct stat sb;
733 ssize_t r;
734 size_t w;
735 char buf[BUFSIZ];
737 if (fstat(fd, &sb) == -1)
738 err(1, "fstat");
740 if (fnam != NULL)
741 do_create(fid, fnam, 0644, KOWRITE);
742 else
743 do_open(fid, KOWRITE);
745 p.max = sb.st_size;
746 for (;;) {
747 r = read(fd, buf, sizeof(buf));
748 if (r == 0)
749 break;
750 if (r == -1)
751 err(1, "read");
753 w = do_write(fid, p.done, r, buf);
754 p.done += w;
756 draw_progress(name, &p);
758 #if 0
759 /* throttle, for debugging purpose */
761 struct timespec ts = { 0, 500000000 };
762 nanosleep(&ts, NULL);
764 #endif
767 putchar('\n');
768 do_clunk(fid);
771 static int
772 woc_file(int fd, const char *prompt, const char *path)
774 struct qid qid;
775 const char *n = NULL;
776 char *errstr;
777 int nfid, miss;
779 nfid = nextfid();
780 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
781 if (errstr != NULL && miss > 1) {
782 printf("%s: %s\n", path, errstr);
783 free(errstr);
784 return -1;
787 if (errstr != NULL || miss == 1) {
788 char p[PATH_MAX], *dn;
790 /*
791 * If it's only one component missing (the file name), walk
792 * to the parent directory and try to create the file.
793 */
795 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
796 printf("path too long: %s\n", path);
797 return -1;
799 dn = dirname(p);
801 if (!strcmp(dn, ".")) {
802 errstr = dup_fid(pwdfid, nfid);
803 miss = 0;
804 } else
805 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
807 if (errstr != NULL) {
808 printf("%s: %s\n", dn, errstr);
809 free(errstr);
810 return -1;
813 if (miss != 0) {
814 printf("%s: not a directory\n", dn);
815 return -1;
818 if ((n = strrchr(path, '/')) != NULL)
819 n++;
820 else
821 n = path;
824 free(errstr);
826 if (miss > 1) {
827 printf("can't create %s: missing %d path component(s)\n",
828 path, miss);
829 return -1;
832 send_fid(nfid, n, fd, prompt);
833 return 0;
836 static void
837 do_tls_connect(const char *host, const char *port)
839 int handshake;
841 if ((tlsconf = tls_config_new()) == NULL)
842 fatalx("tls_config_new");
843 tls_config_insecure_noverifycert(tlsconf);
844 tls_config_insecure_noverifyname(tlsconf);
845 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
846 fatalx("can't load certs (%s, %s)", crtpath, keypath);
848 if ((ctx = tls_client()) == NULL)
849 fatal("tls_client");
850 if (tls_configure(ctx, tlsconf) == -1)
851 fatalx("tls_configure: %s", tls_error(ctx));
853 if (tls_connect(ctx, host, port) == -1)
854 fatalx("can't connect to %s:%s: %s", host, port,
855 tls_error(ctx));
857 for (handshake = 0; !handshake;) {
858 switch (tls_handshake(ctx)) {
859 case -1:
860 fatalx("tls_handshake: %s", tls_error(ctx));
861 case 0:
862 handshake = 1;
863 break;
868 static void
869 do_ctxt_connect(const char *host, const char *port)
871 struct addrinfo hints, *res, *res0;
872 int error, saved_errno;
873 const char *cause = NULL;
875 memset(&hints, 0, sizeof(hints));
876 hints.ai_family = AF_UNSPEC;
877 hints.ai_socktype = SOCK_STREAM;
878 error = getaddrinfo(host, port, &hints, &res0);
879 if (error)
880 errx(1, "%s", gai_strerror(error));
882 sock = -1;
883 for (res = res0; res != NULL; res = res->ai_next) {
884 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
885 res->ai_protocol);
886 if (sock == -1) {
887 cause = "socket";
888 continue;
891 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
892 cause = "connect";
893 saved_errno = errno;
894 close(sock);
895 errno = saved_errno;
896 sock = -1;
897 continue;
900 break;
903 if (sock == -1)
904 err(1, "%s", cause);
905 freeaddrinfo(res0);
908 static void
909 do_connect(const char *connspec, const char *path)
911 char *host, *colon;
912 const char *port;
914 host = xstrdup(connspec);
915 if ((colon = strchr(host, ':')) != NULL) {
916 *colon = '\0';
917 port = ++colon;
918 } else
919 port = "1337";
921 printf("connecting to %s:%s...", host, port);
922 fflush(stdout);
924 if (tls)
925 do_tls_connect(host, port);
926 else
927 do_ctxt_connect(host, port);
929 printf(" done!\n");
931 do_version();
932 do_attach(path);
934 free(host);
937 static int
938 tmp_file(char sfn[TMPFSTRLEN])
940 int tmpfd;
942 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
943 if ((tmpfd = mkstemp(sfn)) == -1) {
944 warn("mkstemp %s", sfn);
945 return -1;
948 /* set the close-on-exec flag */
949 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
950 warn("fcntl");
951 close(tmpfd);
952 return -1;
955 return tmpfd;
958 static inline const char *
959 pp_perm(uint8_t x)
961 switch (x & 0x7) {
962 case 0x0:
963 return "---";
964 case 0x1:
965 return "--x";
966 case 0x2:
967 return "-w-";
968 case 0x3:
969 return "-wx";
970 case 0x4:
971 return "r--";
972 case 0x5:
973 return "r-x";
974 case 0x6:
975 return "rw-";
976 case 0x7:
977 return "rwx";
978 default:
979 /* unreachable, just for the compiler' happiness */
980 return "???";
984 static inline void
985 prepare_wstat(struct np_stat *st)
987 memset(st, 0xFF, sizeof(*st));
988 st->name = NULL;
989 st->uid = NULL;
990 st->gid = NULL;
991 st->muid = NULL;
994 static void
995 cmd_bell(int argc, const char **argv)
997 if (argc == 0) {
998 bell = !bell;
999 if (bell)
1000 puts("bell mode enabled");
1001 else
1002 puts("bell mode disabled");
1003 return;
1006 if (argc != 1)
1007 goto usage;
1009 if (!strcmp(*argv, "on")) {
1010 bell = 1;
1011 puts("bell mode enabled");
1012 return;
1015 if (!strcmp(*argv, "off")) {
1016 bell = 0;
1017 puts("bell mode disabled");
1018 return;
1021 usage:
1022 printf("bell [on | off]\n");
1025 static void
1026 cmd_bye(int argc, const char **argv)
1028 log_warnx("bye\n");
1029 exit(0);
1032 static void
1033 cmd_cd(int argc, const char **argv)
1035 struct qid qid;
1036 int nfid, miss;
1037 char *errstr;
1039 if (argc != 1) {
1040 printf("usage: cd remote-path\n");
1041 return;
1044 nfid = nextfid();
1045 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1046 if (errstr != NULL) {
1047 printf("%s: %s\n", argv[0], errstr);
1048 free(errstr);
1049 return;
1052 if (miss != 0 || !(qid.type & QTDIR)) {
1053 printf("%s: not a directory\n", argv[0]);
1054 if (miss == 0)
1055 do_clunk(nfid);
1056 return;
1059 do_clunk(pwdfid);
1060 pwdfid = nfid;
1063 static void
1064 cmd_edit(int argc, const char **argv)
1066 struct qid qid;
1067 int nfid, tmpfd, miss;
1068 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1069 const char *ed;
1071 if (argc != 1) {
1072 puts("usage: edit file");
1073 return;
1076 if ((ed = getenv("VISUAL")) == NULL &&
1077 (ed = getenv("EDITOR")) == NULL)
1078 ed = "ed";
1080 nfid = nextfid();
1081 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1082 if (errstr != NULL) {
1083 printf("%s: %s\n", *argv, errstr);
1084 free(errstr);
1085 return;
1088 if (miss != 0 || qid.type != 0) {
1089 printf("%s: not a file\n", *argv);
1090 if (miss == 0)
1091 do_clunk(nfid);
1092 return;
1095 if ((tmpfd = tmp_file(sfn)) == -1) {
1096 do_clunk(nfid);
1097 return;
1100 strlcpy(p, *argv, sizeof(p));
1101 name = basename(p);
1103 fetch_fid(nfid, tmpfd, name);
1104 close(tmpfd);
1106 spawn(ed, sfn, NULL);
1109 * Re-open the file because it's not guaranteed that the
1110 * file descriptor tmpfd is still associated with the file
1111 * pointed by sfn: it's not uncommon for editor to write
1112 * a backup file and then rename(2) it to the file name.
1114 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1115 warn("can't open %s", sfn);
1116 goto end;
1119 woc_file(tmpfd, *argv, name);
1120 close(tmpfd);
1122 end:
1123 unlink(sfn);
1126 static void
1127 cmd_get(int argc, const char **argv)
1129 struct qid qid;
1130 const char *l;
1131 char *errstr;
1132 int nfid, fd, miss;
1134 if (argc != 1 && argc != 2) {
1135 printf("usage: get remote-file [local-file]\n");
1136 return;
1139 if (argc == 2)
1140 l = argv[1];
1141 else if ((l = strrchr(argv[0], '/')) != NULL)
1142 l++; /* skip / */
1143 else
1144 l = argv[0];
1146 nfid = nextfid();
1147 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1148 if (errstr != NULL) {
1149 printf("%s: %s\n", argv[0], errstr);
1150 free(errstr);
1151 return;
1154 if (miss != 0 || qid.type != 0) {
1155 printf("%s: not a file\n", argv[0]);
1156 if (miss == 0)
1157 do_clunk(nfid);
1158 return;
1161 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1162 warn("can't open %s", l);
1163 do_clunk(nfid);
1164 return;
1167 fetch_fid(nfid, fd, l);
1168 close(fd);
1171 static void
1172 cmd_hexdump(int argc, const char **argv)
1174 if (argc == 0) {
1175 xdump = !xdump;
1176 if (xdump)
1177 puts("hexdump mode enabled");
1178 else
1179 puts("hexdump mode disabled");
1180 return;
1183 if (argc > 1)
1184 goto usage;
1186 if (!strcmp(*argv, "on")) {
1187 xdump = 1;
1188 puts("hexdump mode enabled");
1189 return;
1192 if (!strcmp(*argv, "off")) {
1193 xdump = 0;
1194 puts("hexdump mode disabled");
1195 return;
1198 usage:
1199 puts("usage: hexdump [on | off]");
1202 static void
1203 cmd_lcd(int argc, const char **argv)
1205 const char *dir;
1207 if (argc > 1) {
1208 printf("usage: lcd [local-directory]\n");
1209 return;
1212 if (argc == 1)
1213 dir = *argv;
1215 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1216 printf("HOME is not defined\n");
1217 return;
1220 if (chdir(dir) == -1)
1221 printf("cd: %s: %s\n", dir, strerror(errno));
1224 static void
1225 cmd_lpwd(int argc, const char **argv)
1227 char path[PATH_MAX];
1229 if (argc != 0) {
1230 printf("usage: lpwd\n");
1231 return;
1234 if (getcwd(path, sizeof(path)) == NULL) {
1235 printf("lpwd: %s\n", strerror(errno));
1236 return;
1239 printf("%s\n", path);
1242 static void
1243 cmd_ls(int argc, const char **argv)
1245 struct np_stat st;
1246 time_t now, mtime;
1247 struct tm *tm;
1248 uint64_t off = 0;
1249 uint32_t len;
1250 int nfid;
1251 const char *timfmt;
1252 char fmt[FMT_SCALED_STRSIZE], tim[13], *errstr;
1254 if (argc != 0) {
1255 printf("ls don't take arguments (yet)\n");
1256 return;
1259 now = time(NULL);
1261 nfid = nextfid();
1262 if ((errstr = dup_fid(pwdfid, nfid)) != NULL) {
1263 printf(".: %s\n", errstr);
1264 free(errstr);
1265 return;
1268 do_open(nfid, KOREAD);
1270 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1272 for (;;) {
1273 tread(nfid, off, BUFSIZ);
1274 do_send();
1275 recv_msg();
1276 expect2(Rread, iota_tag);
1278 len = np_read32(buf);
1279 if (len == 0)
1280 break;
1282 evbuffer_add_buffer(dirbuf, buf);
1283 off += len;
1285 ASSERT_EMPTYBUF();
1288 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1289 if (np_read_stat(dirbuf, &st) == -1)
1290 errx(1, "invalid stat struct read");
1292 if (fmt_scaled(st.length, fmt) == -1)
1293 strlcpy(fmt, "xxx", sizeof(fmt));
1295 mtime = st.mtime;
1297 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
1298 timfmt = "%b %e %R";
1299 else
1300 timfmt = "%b %e %Y";
1302 if ((tm = localtime(&mtime)) == NULL ||
1303 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1304 strlcpy(tim, "unknown", sizeof(tim));
1306 if (st.qid.type & QTDIR)
1307 printf("d");
1308 else
1309 printf("-");
1310 printf("%s", pp_perm(st.mode >> 6));
1311 printf("%s", pp_perm(st.mode >> 3));
1312 printf("%s", pp_perm(st.mode));
1313 printf(" %8s %12s %s%s\n", fmt, tim, st.name,
1314 st.qid.type & QTDIR ? "/" : "");
1316 free(st.name);
1317 free(st.uid);
1318 free(st.gid);
1319 free(st.muid);
1322 do_clunk(nfid);
1325 static void
1326 cmd_page(int argc, const char **argv)
1328 struct qid qid;
1329 int nfid, tmpfd, miss;
1330 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1331 const char *pager;
1333 if (argc != 1) {
1334 puts("usage: page file");
1335 return;
1338 if ((pager = getenv("PAGER")) == NULL)
1339 pager = "less";
1341 nfid = nextfid();
1342 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1343 if (errstr != NULL) {
1344 printf("%s: %s\n", *argv, errstr);
1345 free(errstr);
1346 return;
1349 if (miss != 0 || qid.type != 0) {
1350 printf("%s: not a file\n", *argv);
1351 if (miss == 0)
1352 do_clunk(nfid);
1353 return;
1356 if ((tmpfd = tmp_file(sfn)) == -1) {
1357 do_clunk(nfid);
1358 return;
1361 strlcpy(p, *argv, sizeof(p));
1362 name = basename(p);
1363 fetch_fid(nfid, tmpfd, name);
1364 close(tmpfd);
1365 spawn(pager, sfn, NULL);
1366 unlink(sfn);
1369 static void
1370 cmd_put(int argc, const char **argv)
1372 struct qid qid;
1373 const char *l;
1374 int fd;
1376 if (argc != 1 && argc != 2) {
1377 printf("usage: put local-file [remote-file]\n");
1378 return;
1381 if (argc == 2)
1382 l = argv[1];
1383 else if ((l = strrchr(argv[0], '/')) != NULL)
1384 l++; /* skip / */
1385 else
1386 l = argv[0];
1388 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1389 warn("%s", argv[0]);
1390 return;
1393 woc_file(fd, argv[0], l);
1394 close(fd);
1397 static void
1398 cmd_rename(int argc, const char **argv)
1400 struct np_stat st;
1401 struct qid qid;
1402 char *errstr;
1403 int nfid, miss;
1405 if (argc != 2) {
1406 puts("usage: rename remote-file new-remote-name");
1407 return;
1410 nfid = nextfid();
1411 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1412 if (errstr != NULL) {
1413 printf("%s: %s\n", argv[0], errstr);
1414 free(errstr);
1415 return;
1418 if (miss != 0) {
1419 printf("%s: not such file or directory\n", argv[0]);
1420 return;
1423 prepare_wstat(&st);
1424 st.name = (char *)argv[1];
1425 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1426 printf("rename: %s\n", errstr);
1427 free(errstr);
1430 do_clunk(nfid);
1433 static void
1434 cmd_verbose(int argc, const char **argv)
1436 if (argc == 0) {
1437 log_setverbose(!log_getverbose());
1438 if (log_getverbose())
1439 puts("verbose mode enabled");
1440 else
1441 puts("verbose mode disabled");
1442 return;
1445 if (argc != 1)
1446 goto usage;
1448 if (!strcmp(*argv, "on")) {
1449 log_setverbose(1);
1450 puts("verbose mode enabled");
1451 return;
1454 if (!strcmp(*argv, "off")) {
1455 log_setverbose(0);
1456 puts("verbose mode disabled");
1457 return;
1460 usage:
1461 printf("verbose [on | off]\n");
1464 static void
1465 excmd(int argc, const char **argv)
1467 struct cmd {
1468 const char *name;
1469 void (*fn)(int, const char **);
1470 } cmds[] = {
1471 {"bell", cmd_bell},
1472 {"bye", cmd_bye},
1473 {"cd", cmd_cd},
1474 {"edit", cmd_edit},
1475 {"get", cmd_get},
1476 {"hexdump", cmd_hexdump},
1477 {"lcd", cmd_lcd},
1478 {"lpwd", cmd_lpwd},
1479 {"ls", cmd_ls},
1480 {"page", cmd_page},
1481 {"put", cmd_put},
1482 {"quit", cmd_bye},
1483 {"rename", cmd_rename},
1484 {"verbose", cmd_verbose},
1486 size_t i;
1488 if (argc == 0)
1489 return;
1490 for (i = 0; i < nitems(cmds); ++i) {
1491 if (!strcmp(cmds[i].name, *argv)) {
1492 cmds[i].fn(argc-1, argv+1);
1493 return;
1497 log_warnx("unknown command %s", *argv);
1500 int
1501 main(int argc, char **argv)
1503 int ch;
1505 log_init(1, LOG_DAEMON);
1506 log_setverbose(0);
1507 log_procinit(getprogname());
1509 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
1510 switch (ch) {
1511 case 'C':
1512 crtpath = optarg;
1513 break;
1514 case 'c':
1515 tls = 1;
1516 break;
1517 case 'K':
1518 keypath = optarg;
1519 break;
1520 default:
1521 usage(1);
1524 argc -= optind;
1525 argv += optind;
1527 if (argc == 0)
1528 usage(1);
1530 if (isatty(1)) {
1531 tty_p = 1;
1532 resized = 1;
1533 signal(SIGWINCH, tty_resized);
1536 if ((evb = evbuffer_new()) == NULL)
1537 fatal("evbuffer_new");
1539 if ((buf = evbuffer_new()) == NULL)
1540 fatal("evbuffer_new");
1542 if ((dirbuf = evbuffer_new()) == NULL)
1543 fatal("evbuferr_new");
1545 do_connect(argv[0], argv[1]);
1547 for (;;) {
1548 int argc = 0;
1549 char *line, *argv[16] = {0}, **ap;
1551 if ((line = read_line("kamiftp> ")) == NULL)
1552 break;
1554 for (argc = 0, ap = argv; ap < &argv[15] &&
1555 (*ap = strsep(&line, " \t")) != NULL;) {
1556 if (**ap != '\0')
1557 ap++, argc++;
1559 excmd(argc, (const char **)argv);
1561 if (bell) {
1562 printf("\a");
1563 fflush(stdout);
1566 free(line);
1569 printf("\n");