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 void
180 do_send(void)
182 const void *buf;
183 size_t nbytes;
184 ssize_t r;
186 if (xdump)
187 hexdump("outgoing message", EVBUFFER_DATA(evb),
188 EVBUFFER_LENGTH(evb));
190 while (EVBUFFER_LENGTH(evb) != 0) {
191 buf = EVBUFFER_DATA(evb);
192 nbytes = EVBUFFER_LENGTH(evb);
194 if (ctx == NULL) {
195 r = write(sock, buf, nbytes);
196 if (r == 0 || r == -1)
197 errx(1, "EOF");
198 } else {
199 r = tls_write(ctx, buf, nbytes);
200 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
201 continue;
202 if (r == -1)
203 errx(1, "tls: %s", tls_error(ctx));
206 evbuffer_drain(evb, r);
210 static void
211 mustread(void *d, size_t len)
213 ssize_t r;
215 while (len != 0) {
216 if (ctx == NULL) {
217 r = read(sock, d, len);
218 if (r == 0 || r == -1)
219 errx(1, "EOF");
220 } else {
221 r = tls_read(ctx, d, len);
222 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
223 continue;
224 if (r == -1)
225 errx(1, "tls: %s", tls_error(ctx));
228 d += r;
229 len -= r;
233 static void
234 recv_msg(void)
236 uint32_t len, l;
237 char tmp[BUFSIZ];
239 mustread(&len, sizeof(len));
240 len = le32toh(len);
241 if (len < HEADERSIZE)
242 errx(1, "read message of invalid length %d", len);
244 len -= 4; /* skip the length just read */
246 while (len != 0) {
247 l = MIN(len, sizeof(tmp));
248 mustread(tmp, l);
249 len -= l;
250 evbuffer_add(buf, tmp, l);
253 if (xdump)
254 hexdump("incoming packet", EVBUFFER_DATA(buf),
255 EVBUFFER_LENGTH(buf));
258 static uint64_t
259 np_read64(struct evbuffer *buf)
261 uint64_t n;
263 evbuffer_remove(buf, &n, sizeof(n));
264 return le64toh(n);
267 static uint32_t
268 np_read32(struct evbuffer *buf)
270 uint32_t n;
272 evbuffer_remove(buf, &n, sizeof(n));
273 return le32toh(n);
276 static uint16_t
277 np_read16(struct evbuffer *buf)
279 uint16_t n;
281 evbuffer_remove(buf, &n, sizeof(n));
282 return le16toh(n);
285 static uint16_t
286 np_read8(struct evbuffer *buf)
288 uint8_t n;
290 evbuffer_remove(buf, &n, sizeof(n));
291 return n;
294 static char *
295 np_readstr(struct evbuffer *buf)
297 uint16_t len;
298 char *str;
300 len = np_read16(buf);
301 assert(EVBUFFER_LENGTH(buf) >= len);
303 if ((str = calloc(1, len+1)) == NULL)
304 err(1, "calloc");
305 evbuffer_remove(buf, str, len);
306 return str;
309 static void
310 np_read_qid(struct evbuffer *buf, struct qid *qid)
312 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
314 qid->type = np_read8(buf);
315 qid->vers = np_read32(buf);
316 qid->path = np_read64(buf);
319 static int
320 np_read_stat(struct evbuffer *buf, struct np_stat *st)
322 uint16_t size;
324 memset(st, 0, sizeof(*st));
326 size = np_read16(buf);
327 if (size > EVBUFFER_LENGTH(buf))
328 return -1;
330 st->type = np_read16(buf);
331 st->dev = np_read32(buf);
332 np_read_qid(buf, &st->qid);
333 st->mode = np_read32(buf);
334 st->atime = np_read32(buf);
335 st->mtime = np_read32(buf);
336 st->length = np_read64(buf);
337 st->name = np_readstr(buf);
338 st->uid = np_readstr(buf);
339 st->gid = np_readstr(buf);
340 st->muid = np_readstr(buf);
342 return 0;
345 static void
346 expect(uint8_t type)
348 uint8_t t;
350 t = np_read8(buf);
351 if (t == type)
352 return;
354 if (t == Rerror) {
355 char *err;
357 /* skip tag */
358 np_read16(buf);
360 err = np_readstr(buf);
361 errx(1, "expected %s, got error %s",
362 pp_msg_type(type), err);
365 errx(1, "expected %s, got msg type %s",
366 pp_msg_type(type), pp_msg_type(t));
369 static void
370 expect2(uint8_t type, uint16_t tag)
372 uint16_t t;
374 expect(type);
376 t = np_read16(buf);
377 if (t == tag)
378 return;
380 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
383 static char *
384 check(uint8_t type, uint16_t tag)
386 uint16_t rtag;
387 uint8_t rtype;
389 rtype = np_read8(buf);
390 rtag = np_read16(buf);
391 if (rtype == type) {
392 if (rtag != tag)
393 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
394 return NULL;
397 if (rtype == Rerror)
398 return np_readstr(buf);
400 errx(1, "expected %s, got msg type %s",
401 pp_msg_type(type), pp_msg_type(rtype));
404 static void
405 do_version(void)
407 char *version;
409 tversion(VERSION9P, MSIZE9P);
410 do_send();
411 recv_msg();
412 expect2(Rversion, NOTAG);
414 msize = np_read32(buf);
415 version = np_readstr(buf);
417 if (msize > MSIZE9P)
418 errx(1, "got unexpected msize: %d", msize);
419 if (strcmp(version, VERSION9P))
420 errx(1, "unexpected 9p version: %s", version);
422 free(version);
423 ASSERT_EMPTYBUF();
426 static void
427 do_attach(const char *path)
429 const char *user;
430 struct qid qid;
432 if (path == NULL)
433 path = "/";
434 if ((user = getenv("USER")) == NULL)
435 user = "flan";
437 tattach(pwdfid, NOFID, user, path);
438 do_send();
439 recv_msg();
440 expect2(Rattach, iota_tag);
441 np_read_qid(buf, &qid);
443 ASSERT_EMPTYBUF();
446 static uint32_t
447 do_open(uint32_t fid, uint8_t mode)
449 struct qid qid;
450 uint32_t iounit;
452 topen(fid, mode);
453 do_send();
454 recv_msg();
455 expect2(Ropen, iota_tag);
457 np_read_qid(buf, &qid);
458 iounit = np_read32(buf);
460 ASSERT_EMPTYBUF();
462 return iounit;
465 static uint32_t
466 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
468 struct qid qid;
469 uint32_t iounit;
471 tcreate(fid, name, perm, mode);
472 do_send();
473 recv_msg();
474 expect2(Rcreate, iota_tag);
476 np_read_qid(buf, &qid);
477 iounit = np_read32(buf);
479 ASSERT_EMPTYBUF();
481 return iounit;
484 static void
485 do_clunk(uint32_t fid)
487 tclunk(fid);
488 do_send();
489 recv_msg();
490 expect2(Rclunk, iota_tag);
492 ASSERT_EMPTYBUF();
495 static char *
496 dup_fid(int fid, int nfid)
498 uint16_t nwqid;
499 char *errstr;
501 twalk(fid, nfid, NULL, 0);
502 do_send();
503 recv_msg();
505 if ((errstr = check(Rwalk, iota_tag)) != NULL)
506 return errstr;
508 nwqid = np_read16(buf);
509 assert(nwqid == 0);
511 ASSERT_EMPTYBUF();
513 return NULL;
516 static char *
517 walk_path(int fid, int newfid, const char *path, int *missing,
518 struct qid *qid)
520 char *wnames[MAXWELEM], *p, *t, *errstr;
521 size_t nwname, i;
522 uint16_t nwqid;
524 if ((p = strdup(path)) == NULL)
525 err(1, "strdup");
526 t = p;
528 /* strip initial ./ */
529 if (t[0] == '.' && t[1] == '/')
530 t += 2;
532 for (nwname = 0; nwname < nitems(wnames) &&
533 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
534 if (*wnames[nwname] != '\0')
535 nwname++;
538 twalk(fid, newfid, (const char **)wnames, nwname);
539 do_send();
540 recv_msg();
542 *missing = nwname;
543 if ((errstr = check(Rwalk, iota_tag)) != NULL)
544 return errstr;
546 nwqid = np_read16(buf);
547 assert(nwqid <= nwname);
549 /* consume all qids */
550 for (i = 0; i < nwqid; ++i)
551 np_read_qid(buf, qid);
553 free(p);
555 *missing = nwname - nwqid;
556 return NULL;
559 static void
560 do_stat(int fid, struct np_stat *st)
562 tstat(fid);
563 do_send();
564 recv_msg();
565 expect2(Rstat, iota_tag);
567 if (np_read_stat(buf, st) == -1)
568 errx(1, "invalid stat struct read");
570 ASSERT_EMPTYBUF();
573 static char *
574 do_wstat(int fid, const struct np_stat *st)
576 char *errstr;
578 twstat(fid, st);
579 do_send();
580 recv_msg();
582 if ((errstr = check(Rwstat, iota_tag)) != NULL)
583 return errstr;
585 ASSERT_EMPTYBUF();
587 return NULL;
590 static size_t
591 do_read(int fid, uint64_t off, uint32_t count, void *data)
593 uint32_t r;
595 tread(fid, off, count);
596 do_send();
597 recv_msg();
598 expect2(Rread, iota_tag);
600 r = np_read32(buf);
601 assert(r == EVBUFFER_LENGTH(buf));
602 assert(r <= count);
603 evbuffer_remove(buf, data, r);
605 ASSERT_EMPTYBUF();
607 return r;
610 static size_t
611 do_write(int fid, uint64_t off, uint32_t count, void *data)
613 uint32_t r;
615 twrite(fid, off, data, count);
616 do_send();
617 recv_msg();
618 expect2(Rwrite, iota_tag);
620 r = np_read32(buf);
621 assert(r <= count);
623 ASSERT_EMPTYBUF();
625 return r;
628 static void
629 draw_progress(const char *pre, const struct progress *p)
631 struct winsize ws;
632 int i, l, w;
633 double perc;
635 if (xdump)
636 return;
638 perc = 100.0 * p->done / p->max;
639 if (!tty_p) {
640 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
641 return;
644 if (resized) {
645 resized = 0;
647 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
648 return;
649 tty_width = ws.ws_col;
651 w = tty_width;
653 if (pre == NULL ||
654 ((l = printf("\r%s ", pre)) == -1 || l >= w))
655 return;
657 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
658 if (w < 0) {
659 printf("%4d%%\n", (int)perc);
660 return;
663 printf("|");
665 l = w * MIN(100.0, perc) / 100.0;
666 for (i = 0; i < l; i++)
667 printf("*");
668 for (; i < w; i++)
669 printf(" ");
670 printf("|%4d%%", (int)perc);
672 fflush(stdout);
675 static void
676 fetch_fid(int fid, int fd, const char *name)
678 struct progress p = {0};
679 struct np_stat st;
680 size_t r;
681 char buf[BUFSIZ];
683 do_stat(fid, &st);
684 do_open(fid, KOREAD);
686 p.max = st.length;
687 for (;;) {
688 size_t off;
689 ssize_t nw;
691 r = do_read(fid, p.done, sizeof(buf), buf);
692 if (r == 0)
693 break;
695 for (off = 0; off < r; off += nw)
696 if ((nw = write(fd, buf + off, r - off)) == 0 ||
697 nw == -1)
698 err(1, "write");
700 p.done += r;
701 draw_progress(name, &p);
703 #if 0
704 /* throttle, for debugging purpose */
706 struct timespec ts = { 0, 500000000 };
707 nanosleep(&ts, NULL);
709 #endif
712 putchar('\n');
714 do_clunk(fid);
717 static void
718 send_fid(int fid, const char *fnam, int fd, const char *name)
720 struct progress p = {0};
721 struct stat sb;
722 ssize_t r;
723 size_t w;
724 char buf[BUFSIZ];
726 if (fstat(fd, &sb) == -1)
727 err(1, "fstat");
729 if (fnam != NULL)
730 do_create(fid, fnam, 0644, KOWRITE);
731 else
732 do_open(fid, KOWRITE);
734 p.max = sb.st_size;
735 for (;;) {
736 r = read(fd, buf, sizeof(buf));
737 if (r == 0)
738 break;
739 if (r == -1)
740 err(1, "read");
742 w = do_write(fid, p.done, r, buf);
743 p.done += w;
745 draw_progress(name, &p);
747 #if 0
748 /* throttle, for debugging purpose */
750 struct timespec ts = { 0, 500000000 };
751 nanosleep(&ts, NULL);
753 #endif
756 putchar('\n');
757 do_clunk(fid);
760 static int
761 woc_file(int fd, const char *prompt, const char *path)
763 struct qid qid;
764 const char *n = NULL;
765 char *errstr;
766 int nfid, miss;
768 nfid = pwdfid+1;
769 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
770 if (errstr != NULL && miss > 1) {
771 printf("%s: %s\n", path, errstr);
772 free(errstr);
773 return -1;
776 if (errstr != NULL || miss == 1) {
777 char p[PATH_MAX], *dn;
779 /*
780 * If it's only one component missing (the file name), walk
781 * to the parent directory and try to create the file.
782 */
784 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
785 printf("path too long: %s\n", path);
786 return -1;
788 dn = dirname(p);
790 if (!strcmp(dn, ".")) {
791 errstr = dup_fid(pwdfid, nfid);
792 miss = 0;
793 } else
794 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
796 if (errstr != NULL) {
797 printf("%s: %s\n", dn, errstr);
798 free(errstr);
799 return -1;
802 if (miss != 0) {
803 printf("%s: not a directory\n", dn);
804 return -1;
807 if ((n = strrchr(path, '/')) != NULL)
808 n++;
809 else
810 n = path;
813 free(errstr);
815 if (miss > 1) {
816 printf("can't create %s: missing %d path component(s)\n",
817 path, miss);
818 return -1;
821 send_fid(nfid, n, fd, prompt);
822 return 0;
825 static void
826 do_tls_connect(const char *host, const char *port)
828 int handshake;
830 if ((tlsconf = tls_config_new()) == NULL)
831 fatalx("tls_config_new");
832 tls_config_insecure_noverifycert(tlsconf);
833 tls_config_insecure_noverifyname(tlsconf);
834 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
835 fatalx("can't load certs (%s, %s)", crtpath, keypath);
837 if ((ctx = tls_client()) == NULL)
838 fatal("tls_client");
839 if (tls_configure(ctx, tlsconf) == -1)
840 fatalx("tls_configure: %s", tls_error(ctx));
842 if (tls_connect(ctx, host, port) == -1)
843 fatalx("can't connect to %s:%s: %s", host, port,
844 tls_error(ctx));
846 for (handshake = 0; !handshake;) {
847 switch (tls_handshake(ctx)) {
848 case -1:
849 fatalx("tls_handshake: %s", tls_error(ctx));
850 case 0:
851 handshake = 1;
852 break;
857 static void
858 do_ctxt_connect(const char *host, const char *port)
860 struct addrinfo hints, *res, *res0;
861 int error, saved_errno;
862 const char *cause = NULL;
864 memset(&hints, 0, sizeof(hints));
865 hints.ai_family = AF_UNSPEC;
866 hints.ai_socktype = SOCK_STREAM;
867 error = getaddrinfo(host, port, &hints, &res0);
868 if (error)
869 errx(1, "%s", gai_strerror(error));
871 sock = -1;
872 for (res = res0; res != NULL; res = res->ai_next) {
873 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
874 res->ai_protocol);
875 if (sock == -1) {
876 cause = "socket";
877 continue;
880 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
881 cause = "connect";
882 saved_errno = errno;
883 close(sock);
884 errno = saved_errno;
885 sock = -1;
886 continue;
889 break;
892 if (sock == -1)
893 err(1, "%s", cause);
894 freeaddrinfo(res0);
897 static void
898 do_connect(const char *connspec, const char *path)
900 char *host, *colon;
901 const char *port;
903 host = xstrdup(connspec);
904 if ((colon = strchr(host, ':')) != NULL) {
905 *colon = '\0';
906 port = ++colon;
907 } else
908 port = "1337";
910 printf("connecting to %s:%s...", host, port);
911 fflush(stdout);
913 if (tls)
914 do_tls_connect(host, port);
915 else
916 do_ctxt_connect(host, port);
918 printf(" done!\n");
920 do_version();
921 do_attach(path);
923 free(host);
926 static int
927 tmp_file(char sfn[TMPFSTRLEN])
929 int tmpfd;
931 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
932 if ((tmpfd = mkstemp(sfn)) == -1) {
933 warn("mkstemp %s", sfn);
934 return -1;
937 /* set the close-on-exec flag */
938 if (fcntl(tmpfd, F_SETFD, FD_CLOEXEC) == -1) {
939 warn("fcntl");
940 close(tmpfd);
941 return -1;
944 return tmpfd;
947 static inline const char *
948 pp_perm(uint8_t x)
950 switch (x & 0x7) {
951 case 0x0:
952 return "---";
953 case 0x1:
954 return "--x";
955 case 0x2:
956 return "-w-";
957 case 0x3:
958 return "-wx";
959 case 0x4:
960 return "r--";
961 case 0x5:
962 return "r-x";
963 case 0x6:
964 return "rw-";
965 case 0x7:
966 return "rwx";
967 default:
968 /* unreachable, just for the compiler' happiness */
969 return "???";
973 static inline void
974 prepare_wstat(struct np_stat *st)
976 memset(st, 0xFF, sizeof(*st));
977 st->name = NULL;
978 st->uid = NULL;
979 st->gid = NULL;
980 st->muid = NULL;
983 static void
984 cmd_bell(int argc, const char **argv)
986 if (argc == 0) {
987 bell = !bell;
988 if (bell)
989 puts("bell mode enabled");
990 else
991 puts("bell mode disabled");
992 return;
995 if (argc != 1)
996 goto usage;
998 if (!strcmp(*argv, "on")) {
999 bell = 1;
1000 puts("bell mode enabled");
1001 return;
1004 if (!strcmp(*argv, "off")) {
1005 bell = 0;
1006 puts("bell mode disabled");
1007 return;
1010 usage:
1011 printf("bell [on | off]\n");
1014 static void
1015 cmd_bye(int argc, const char **argv)
1017 log_warnx("bye\n");
1018 exit(0);
1021 static void
1022 cmd_cd(int argc, const char **argv)
1024 struct qid qid;
1025 int nfid, miss;
1026 char *errstr;
1028 if (argc != 1) {
1029 printf("usage: cd remote-path\n");
1030 return;
1033 nfid = pwdfid+1;
1034 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1035 if (errstr != NULL) {
1036 printf("%s: %s\n", argv[0], errstr);
1037 free(errstr);
1038 return;
1041 if (miss != 0 || !(qid.type & QTDIR)) {
1042 printf("%s: not a directory\n", argv[0]);
1043 if (miss == 0)
1044 do_clunk(nfid);
1045 return;
1048 do_clunk(pwdfid);
1049 pwdfid = nfid;
1052 static void
1053 cmd_edit(int argc, const char **argv)
1055 struct qid qid;
1056 int nfid, tmpfd, miss;
1057 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1058 const char *ed;
1060 if (argc != 1) {
1061 puts("usage: edit file");
1062 return;
1065 if ((ed = getenv("VISUAL")) == NULL &&
1066 (ed = getenv("EDITOR")) == NULL)
1067 ed = "ed";
1069 nfid = pwdfid+1;
1070 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1071 if (errstr != NULL) {
1072 printf("%s: %s\n", *argv, errstr);
1073 free(errstr);
1074 return;
1077 if (miss != 0 || qid.type != 0) {
1078 printf("%s: not a file\n", *argv);
1079 if (miss == 0)
1080 do_clunk(nfid);
1081 return;
1084 if ((tmpfd = tmp_file(sfn)) == -1) {
1085 do_clunk(nfid);
1086 return;
1089 strlcpy(p, *argv, sizeof(p));
1090 name = basename(p);
1092 fetch_fid(nfid, tmpfd, name);
1093 close(tmpfd);
1095 spawn(ed, sfn, NULL);
1098 * Re-open the file because it's not guaranteed that the
1099 * file descriptor tmpfd is still associated with the file
1100 * pointed by sfn: it's not uncommon for editor to write
1101 * a backup file and then rename(2) it to the file name.
1103 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1104 warn("can't open %s", sfn);
1105 goto end;
1108 woc_file(tmpfd, *argv, name);
1109 close(tmpfd);
1111 end:
1112 unlink(sfn);
1115 static void
1116 cmd_get(int argc, const char **argv)
1118 struct qid qid;
1119 const char *l;
1120 char *errstr;
1121 int nfid, fd, miss;
1123 if (argc != 1 && argc != 2) {
1124 printf("usage: get remote-file [local-file]\n");
1125 return;
1128 if (argc == 2)
1129 l = argv[1];
1130 else if ((l = strrchr(argv[0], '/')) != NULL)
1131 l++; /* skip / */
1132 else
1133 l = argv[0];
1135 nfid = pwdfid+1;
1136 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1137 if (errstr != NULL) {
1138 printf("%s: %s\n", argv[0], errstr);
1139 free(errstr);
1140 return;
1143 if (miss != 0 || qid.type != 0) {
1144 printf("%s: not a file\n", argv[0]);
1145 if (miss == 0)
1146 do_clunk(nfid);
1147 return;
1150 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1151 warn("can't open %s", l);
1152 do_clunk(nfid);
1153 return;
1156 fetch_fid(nfid, fd, l);
1157 close(fd);
1160 static void
1161 cmd_hexdump(int argc, const char **argv)
1163 if (argc == 0) {
1164 xdump = !xdump;
1165 if (xdump)
1166 puts("hexdump mode enabled");
1167 else
1168 puts("hexdump mode disabled");
1169 return;
1172 if (argc > 1)
1173 goto usage;
1175 if (!strcmp(*argv, "on")) {
1176 xdump = 1;
1177 puts("hexdump mode enabled");
1178 return;
1181 if (!strcmp(*argv, "off")) {
1182 xdump = 0;
1183 puts("hexdump mode disabled");
1184 return;
1187 usage:
1188 puts("usage: hexdump [on | off]");
1191 static void
1192 cmd_lcd(int argc, const char **argv)
1194 const char *dir;
1196 if (argc > 1) {
1197 printf("usage: lcd [local-directory]\n");
1198 return;
1201 if (argc == 1)
1202 dir = *argv;
1204 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1205 printf("HOME is not defined\n");
1206 return;
1209 if (chdir(dir) == -1)
1210 printf("cd: %s: %s\n", dir, strerror(errno));
1213 static void
1214 cmd_lpwd(int argc, const char **argv)
1216 char path[PATH_MAX];
1218 if (argc != 0) {
1219 printf("usage: lpwd\n");
1220 return;
1223 if (getcwd(path, sizeof(path)) == NULL) {
1224 printf("lpwd: %s\n", strerror(errno));
1225 return;
1228 printf("%s\n", path);
1231 static void
1232 cmd_ls(int argc, const char **argv)
1234 struct np_stat st;
1235 time_t now, mtime;
1236 struct tm *tm;
1237 uint64_t off = 0;
1238 uint32_t len;
1239 const char *timfmt;
1240 char fmt[FMT_SCALED_STRSIZE], tim[13], *errstr;
1242 if (argc != 0) {
1243 printf("ls don't take arguments (yet)\n");
1244 return;
1247 now = time(NULL);
1249 if ((errstr = dup_fid(pwdfid, 1)) != NULL) {
1250 printf(".: %s\n", errstr);
1251 free(errstr);
1252 return;
1255 do_open(1, KOREAD);
1257 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1259 for (;;) {
1260 tread(1, off, BUFSIZ);
1261 do_send();
1262 recv_msg();
1263 expect2(Rread, iota_tag);
1265 len = np_read32(buf);
1266 if (len == 0)
1267 break;
1269 evbuffer_add_buffer(dirbuf, buf);
1270 off += len;
1272 ASSERT_EMPTYBUF();
1275 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1276 if (np_read_stat(dirbuf, &st) == -1)
1277 errx(1, "invalid stat struct read");
1279 if (fmt_scaled(st.length, fmt) == -1)
1280 strlcpy(fmt, "xxx", sizeof(fmt));
1282 mtime = st.mtime;
1284 if (now > mtime && (now - mtime) < 365/2 * 24 * 12 * 60)
1285 timfmt = "%b %e %R";
1286 else
1287 timfmt = "%b %e %Y";
1289 if ((tm = localtime(&mtime)) == NULL ||
1290 strftime(tim, sizeof(tim), timfmt, tm) == 0)
1291 strlcpy(tim, "unknown", sizeof(tim));
1293 if (st.qid.type & QTDIR)
1294 printf("d");
1295 else
1296 printf("-");
1297 printf("%s", pp_perm(st.mode >> 6));
1298 printf("%s", pp_perm(st.mode >> 3));
1299 printf("%s", pp_perm(st.mode));
1300 printf(" %8s %12s %s%s\n", fmt, tim, st.name,
1301 st.qid.type & QTDIR ? "/" : "");
1303 free(st.name);
1304 free(st.uid);
1305 free(st.gid);
1306 free(st.muid);
1309 do_clunk(1);
1312 static void
1313 cmd_page(int argc, const char **argv)
1315 struct qid qid;
1316 int nfid, tmpfd, miss;
1317 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1318 const char *pager;
1320 if (argc != 1) {
1321 puts("usage: page file");
1322 return;
1325 if ((pager = getenv("PAGER")) == NULL)
1326 pager = "less";
1328 nfid = pwdfid+1;
1329 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1330 if (errstr != NULL) {
1331 printf("%s: %s\n", *argv, errstr);
1332 free(errstr);
1333 return;
1336 if (miss != 0 || qid.type != 0) {
1337 printf("%s: not a file\n", *argv);
1338 if (miss == 0)
1339 do_clunk(nfid);
1340 return;
1343 if ((tmpfd = tmp_file(sfn)) == -1) {
1344 do_clunk(nfid);
1345 return;
1348 strlcpy(p, *argv, sizeof(p));
1349 name = basename(p);
1350 fetch_fid(nfid, tmpfd, name);
1351 close(tmpfd);
1352 spawn(pager, sfn, NULL);
1353 unlink(sfn);
1356 static void
1357 cmd_put(int argc, const char **argv)
1359 struct qid qid;
1360 const char *l;
1361 int fd;
1363 if (argc != 1 && argc != 2) {
1364 printf("usage: put local-file [remote-file]\n");
1365 return;
1368 if (argc == 2)
1369 l = argv[1];
1370 else if ((l = strrchr(argv[0], '/')) != NULL)
1371 l++; /* skip / */
1372 else
1373 l = argv[0];
1375 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1376 warn("%s", argv[0]);
1377 return;
1380 woc_file(fd, argv[0], l);
1381 close(fd);
1384 static void
1385 cmd_rename(int argc, const char **argv)
1387 struct np_stat st;
1388 struct qid qid;
1389 char *errstr;
1390 int nfid, miss;
1392 if (argc != 2) {
1393 puts("usage: rename remote-file new-remote-name");
1394 return;
1397 nfid = pwdfid+1;
1398 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1399 if (errstr != NULL) {
1400 printf("%s: %s\n", argv[0], errstr);
1401 free(errstr);
1402 return;
1405 if (miss != 0) {
1406 printf("%s: not such file or directory\n", argv[0]);
1407 return;
1410 prepare_wstat(&st);
1411 st.name = (char *)argv[1];
1412 if ((errstr = do_wstat(nfid, &st)) != NULL) {
1413 printf("rename: %s\n", errstr);
1414 free(errstr);
1417 do_clunk(nfid);
1420 static void
1421 cmd_verbose(int argc, const char **argv)
1423 if (argc == 0) {
1424 log_setverbose(!log_getverbose());
1425 if (log_getverbose())
1426 puts("verbose mode enabled");
1427 else
1428 puts("verbose mode disabled");
1429 return;
1432 if (argc != 1)
1433 goto usage;
1435 if (!strcmp(*argv, "on")) {
1436 log_setverbose(1);
1437 puts("verbose mode enabled");
1438 return;
1441 if (!strcmp(*argv, "off")) {
1442 log_setverbose(0);
1443 puts("verbose mode disabled");
1444 return;
1447 usage:
1448 printf("verbose [on | off]\n");
1451 static void
1452 excmd(int argc, const char **argv)
1454 struct cmd {
1455 const char *name;
1456 void (*fn)(int, const char **);
1457 } cmds[] = {
1458 {"bell", cmd_bell},
1459 {"bye", cmd_bye},
1460 {"cd", cmd_cd},
1461 {"edit", cmd_edit},
1462 {"get", cmd_get},
1463 {"hexdump", cmd_hexdump},
1464 {"lcd", cmd_lcd},
1465 {"lpwd", cmd_lpwd},
1466 {"ls", cmd_ls},
1467 {"page", cmd_page},
1468 {"put", cmd_put},
1469 {"quit", cmd_bye},
1470 {"rename", cmd_rename},
1471 {"verbose", cmd_verbose},
1473 size_t i;
1475 if (argc == 0)
1476 return;
1477 for (i = 0; i < nitems(cmds); ++i) {
1478 if (!strcmp(cmds[i].name, *argv)) {
1479 cmds[i].fn(argc-1, argv+1);
1480 return;
1484 log_warnx("unknown command %s", *argv);
1487 int
1488 main(int argc, char **argv)
1490 int ch;
1492 log_init(1, LOG_DAEMON);
1493 log_setverbose(0);
1494 log_procinit(getprogname());
1496 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
1497 switch (ch) {
1498 case 'C':
1499 crtpath = optarg;
1500 break;
1501 case 'c':
1502 tls = 1;
1503 break;
1504 case 'K':
1505 keypath = optarg;
1506 break;
1507 default:
1508 usage(1);
1511 argc -= optind;
1512 argv += optind;
1514 if (argc == 0)
1515 usage(1);
1517 if (isatty(1)) {
1518 tty_p = 1;
1519 resized = 1;
1520 signal(SIGWINCH, tty_resized);
1523 if ((evb = evbuffer_new()) == NULL)
1524 fatal("evbuffer_new");
1526 if ((buf = evbuffer_new()) == NULL)
1527 fatal("evbuffer_new");
1529 if ((dirbuf = evbuffer_new()) == NULL)
1530 fatal("evbuferr_new");
1532 do_connect(argv[0], argv[1]);
1534 for (;;) {
1535 int argc = 0;
1536 char *line, *argv[16] = {0}, **ap;
1538 if ((line = read_line("kamiftp> ")) == NULL)
1539 break;
1541 for (argc = 0, ap = argv; ap < &argv[15] &&
1542 (*ap = strsep(&line, " \t")) != NULL;) {
1543 if (**ap != '\0')
1544 ap++, argc++;
1546 excmd(argc, (const char **)argv);
1548 if (bell) {
1549 printf("\a");
1550 fflush(stdout);
1553 free(line);
1556 printf("\n");