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 "9pclib.h"
50 #include "kami.h"
51 #include "utils.h"
52 #include "log.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;
75 struct np_stat {
76 uint16_t type;
77 uint32_t dev;
78 struct qid qid;
79 uint32_t mode;
80 uint32_t atime;
81 uint32_t mtime;
82 uint64_t length;
83 char *name;
84 char *uid;
85 char *gid;
86 char *muid;
87 };
89 struct progress {
90 uint64_t max;
91 uint64_t done;
92 };
94 int pwdfid;
96 #define ASSERT_EMPTYBUF() assert(EVBUFFER_LENGTH(buf) == 0)
98 #if !HAVE_READLINE
99 char *
100 readline(const char *prompt)
102 char *ch, *line = NULL;
103 size_t linesize = 0;
104 ssize_t linelen;
106 printf("%s", prompt);
107 fflush(stdout);
109 linelen = getline(&line, &linesize, stdin);
110 if (linelen == -1)
111 return NULL;
113 if ((ch = strchr(line, '\n')) != NULL)
114 *ch = '\0';
115 return line;
118 void
119 add_history(const char *line)
121 return;
123 #endif
125 static char *
126 read_line(const char *prompt)
128 char *line;
130 again:
131 if ((line = readline(prompt)) == NULL)
132 return NULL;
133 /* XXX: trim spaces? */
134 if (*line == '\0') {
135 free(line);
136 goto again;
139 add_history(line);
140 return line;
143 static void
144 spawn(const char *argv0, ...)
146 pid_t pid;
147 size_t i;
148 int status;
149 const char *argv[16], *last;
150 va_list ap;
152 memset(argv, 0, sizeof(argv));
154 va_start(ap, argv0);
155 argv[0] = argv0;
156 for (i = 1; i < nitems(argv); ++i) {
157 last = va_arg(ap, const char *);
158 if (last == NULL)
159 break;
160 argv[i] = last;
162 va_end(ap);
164 assert(last == NULL);
166 switch (pid = fork()) {
167 case -1:
168 err(1, "fork");
169 case 0: /* child */
170 execvp(argv[0], (char *const *)argv);
171 err(1, "execvp");
172 default:
173 waitpid(pid, &status, 0);
177 static void
178 tty_resized(int signo)
180 resized = 1;
183 static void __dead
184 usage(int ret)
186 fprintf(stderr, "usage: %s [-c] [-C cert] [-K key] "
187 "host[:port] [path]\n", getprogname());
188 fprintf(stderr, "kamid suite version " KAMID_VERSION "\n");
189 exit(ret);
192 static void
193 do_send(void)
195 const void *buf;
196 size_t nbytes;
197 ssize_t r;
199 while (EVBUFFER_LENGTH(evb) != 0) {
200 buf = EVBUFFER_DATA(evb);
201 nbytes = EVBUFFER_LENGTH(evb);
203 if (ctx == NULL) {
204 r = write(sock, buf, nbytes);
205 if (r == 0 || r == -1)
206 errx(1, "EOF");
207 } else {
208 r = tls_write(ctx, buf, nbytes);
209 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
210 continue;
211 if (r == -1)
212 errx(1, "tls: %s", tls_error(ctx));
215 evbuffer_drain(evb, r);
219 static void
220 mustread(void *d, size_t len)
222 ssize_t r;
224 while (len != 0) {
225 if (ctx == NULL) {
226 r = read(sock, d, len);
227 if (r == 0 || r == -1)
228 errx(1, "EOF");
229 } else {
230 r = tls_read(ctx, d, len);
231 if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
232 continue;
233 if (r == -1)
234 errx(1, "tls: %s", tls_error(ctx));
237 d += r;
238 len -= r;
242 static void
243 recv_msg(void)
245 uint32_t len, l;
246 char tmp[BUFSIZ];
248 mustread(&len, sizeof(len));
249 len = le32toh(len);
250 if (len < HEADERSIZE)
251 errx(1, "read message of invalid length %d", len);
253 len -= 4; /* skip the length just read */
255 while (len != 0) {
256 l = MIN(len, sizeof(tmp));
257 mustread(tmp, l);
258 len -= l;
259 evbuffer_add(buf, tmp, l);
263 static uint64_t
264 np_read64(struct evbuffer *buf)
266 uint64_t n;
268 evbuffer_remove(buf, &n, sizeof(n));
269 return le64toh(n);
272 static uint32_t
273 np_read32(struct evbuffer *buf)
275 uint32_t n;
277 evbuffer_remove(buf, &n, sizeof(n));
278 return le32toh(n);
281 static uint16_t
282 np_read16(struct evbuffer *buf)
284 uint16_t n;
286 evbuffer_remove(buf, &n, sizeof(n));
287 return le16toh(n);
290 static uint16_t
291 np_read8(struct evbuffer *buf)
293 uint8_t n;
295 evbuffer_remove(buf, &n, sizeof(n));
296 return n;
299 static char *
300 np_readstr(struct evbuffer *buf)
302 uint16_t len;
303 char *str;
305 len = np_read16(buf);
306 assert(EVBUFFER_LENGTH(buf) >= len);
308 if ((str = calloc(1, len+1)) == NULL)
309 err(1, "calloc");
310 evbuffer_remove(buf, str, len);
311 return str;
314 static void
315 np_read_qid(struct evbuffer *buf, struct qid *qid)
317 assert(EVBUFFER_LENGTH(buf) >= QIDSIZE);
319 qid->type = np_read8(buf);
320 qid->vers = np_read32(buf);
321 qid->path = np_read64(buf);
324 static int
325 np_read_stat(struct evbuffer *buf, struct np_stat *st)
327 uint16_t size;
329 memset(st, 0, sizeof(*st));
331 size = np_read16(buf);
332 if (size > EVBUFFER_LENGTH(buf))
333 return -1;
335 st->type = np_read16(buf);
336 st->dev = np_read32(buf);
337 np_read_qid(buf, &st->qid);
338 st->mode = np_read32(buf);
339 st->atime = np_read32(buf);
340 st->mtime = np_read32(buf);
341 st->length = np_read64(buf);
342 st->name = np_readstr(buf);
343 st->uid = np_readstr(buf);
344 st->gid = np_readstr(buf);
345 st->muid = np_readstr(buf);
347 return 0;
350 static void
351 expect(uint8_t type)
353 uint8_t t;
355 t = np_read8(buf);
356 if (t == type)
357 return;
359 if (t == Rerror) {
360 char *err;
362 /* skip tag */
363 np_read16(buf);
365 err = np_readstr(buf);
366 errx(1, "expected %s, got error %s",
367 pp_msg_type(type), err);
370 errx(1, "expected %s, got msg type %s",
371 pp_msg_type(type), pp_msg_type(t));
374 static void
375 expect2(uint8_t type, uint16_t tag)
377 uint16_t t;
379 expect(type);
381 t = np_read16(buf);
382 if (t == tag)
383 return;
385 errx(1, "expected tag 0x%x, got 0x%x", tag, t);
388 static char *
389 check(uint8_t type, uint16_t tag)
391 uint16_t rtag;
392 uint8_t rtype;
394 rtype = np_read8(buf);
395 rtag = np_read16(buf);
396 if (rtype == type) {
397 if (rtag != tag)
398 errx(1, "expected tag 0x%x, got 0x%x", tag, rtag);
399 return NULL;
402 if (rtype == Rerror)
403 return np_readstr(buf);
405 errx(1, "expected %s, got msg type %s",
406 pp_msg_type(type), pp_msg_type(rtype));
409 static void
410 do_version(void)
412 char *version;
414 tversion(VERSION9P, MSIZE9P);
415 do_send();
416 recv_msg();
417 expect2(Rversion, NOTAG);
419 msize = np_read32(buf);
420 version = np_readstr(buf);
422 if (msize > MSIZE9P)
423 errx(1, "got unexpected msize: %d", msize);
424 if (strcmp(version, VERSION9P))
425 errx(1, "unexpected 9p version: %s", version);
427 free(version);
428 ASSERT_EMPTYBUF();
431 static void
432 do_attach(const char *path)
434 const char *user;
435 struct qid qid;
437 if (path == NULL)
438 path = "/";
439 if ((user = getenv("USER")) == NULL)
440 user = "flan";
442 tattach(pwdfid, NOFID, user, path);
443 do_send();
444 recv_msg();
445 expect2(Rattach, iota_tag);
446 np_read_qid(buf, &qid);
448 ASSERT_EMPTYBUF();
451 static uint32_t
452 do_open(uint32_t fid, uint8_t mode)
454 struct qid qid;
455 uint32_t iounit;
457 topen(fid, mode);
458 do_send();
459 recv_msg();
460 expect2(Ropen, iota_tag);
462 np_read_qid(buf, &qid);
463 iounit = np_read32(buf);
465 ASSERT_EMPTYBUF();
467 return iounit;
470 static uint32_t
471 do_create(uint32_t fid, const char *name, uint32_t perm, uint8_t mode)
473 struct qid qid;
474 uint32_t iounit;
476 tcreate(fid, name, perm, mode);
477 do_send();
478 recv_msg();
479 expect2(Rcreate, iota_tag);
481 np_read_qid(buf, &qid);
482 iounit = np_read32(buf);
484 ASSERT_EMPTYBUF();
486 return iounit;
489 static void
490 do_clunk(uint32_t fid)
492 tclunk(fid);
493 do_send();
494 recv_msg();
495 expect2(Rclunk, iota_tag);
497 ASSERT_EMPTYBUF();
500 static char *
501 dup_fid(int fid, int nfid)
503 uint16_t nwqid;
504 char *errstr;
506 twalk(fid, nfid, NULL, 0);
507 do_send();
508 recv_msg();
510 if ((errstr = check(Rwalk, iota_tag)) != NULL)
511 return errstr;
513 nwqid = np_read16(buf);
514 assert(nwqid == 0);
516 ASSERT_EMPTYBUF();
518 return NULL;
521 static char *
522 walk_path(int fid, int newfid, const char *path, int *missing,
523 struct qid *qid)
525 char *wnames[MAXWELEM], *p, *t, *errstr;
526 size_t nwname, i;
527 uint16_t nwqid;
529 if ((p = strdup(path)) == NULL)
530 err(1, "strdup");
531 t = p;
533 /* strip initial ./ */
534 if (t[0] == '.' && t[1] == '/')
535 t += 2;
537 for (nwname = 0; nwname < nitems(wnames) &&
538 (wnames[nwname] = strsep(&t, "/")) != NULL;) {
539 if (*wnames[nwname] != '\0')
540 nwname++;
543 twalk(fid, newfid, (const char **)wnames, nwname);
544 do_send();
545 recv_msg();
547 *missing = nwname;
548 if ((errstr = check(Rwalk, iota_tag)) != NULL)
549 return errstr;
551 nwqid = np_read16(buf);
552 assert(nwqid <= nwname);
554 /* consume all qids */
555 for (i = 0; i < nwqid; ++i)
556 np_read_qid(buf, qid);
558 free(p);
560 *missing = nwname - nwqid;
561 return NULL;
564 static void
565 do_stat(int fid, struct np_stat *st)
567 tstat(fid);
568 do_send();
569 recv_msg();
570 expect2(Rstat, iota_tag);
572 if (np_read_stat(buf, st) == -1)
573 errx(1, "invalid stat struct read");
575 ASSERT_EMPTYBUF();
578 static size_t
579 do_read(int fid, uint64_t off, uint32_t count, void *data)
581 uint32_t r;
583 tread(fid, off, count);
584 do_send();
585 recv_msg();
586 expect2(Rread, iota_tag);
588 r = np_read32(buf);
589 assert(r == EVBUFFER_LENGTH(buf));
590 assert(r <= count);
591 evbuffer_remove(buf, data, r);
593 ASSERT_EMPTYBUF();
595 return r;
598 static size_t
599 do_write(int fid, uint64_t off, uint32_t count, void *data)
601 uint32_t r;
603 twrite(fid, off, data, count);
604 do_send();
605 recv_msg();
606 expect2(Rwrite, iota_tag);
608 r = np_read32(buf);
609 assert(r <= count);
611 ASSERT_EMPTYBUF();
613 return r;
616 static void
617 draw_progress(const char *pre, const struct progress *p)
619 struct winsize ws;
620 int i, l, w;
621 double perc;
623 perc = 100.0 * p->done / p->max;
624 if (!tty_p) {
625 fprintf(stderr, "%s: %d%%\n", pre, (int)perc);
626 return;
629 if (resized) {
630 resized = 0;
632 if (ioctl(0, TIOCGWINSZ, &ws) == -1)
633 return;
634 tty_width = ws.ws_col;
636 w = tty_width;
638 if (pre == NULL ||
639 ((l = printf("\r%s ", pre)) == -1 || l >= w))
640 return;
642 w -= l + 2 + 5; /* 2 for |, 5 for percentage + \n */
643 if (w < 0) {
644 printf("%4d%%\n", (int)perc);
645 return;
648 printf("|");
650 l = w * MIN(100.0, perc) / 100.0;
651 for (i = 0; i < l; i++)
652 printf("*");
653 for (; i < w; i++)
654 printf(" ");
655 printf("|%4d%%", (int)perc);
657 fflush(stdout);
660 static void
661 fetch_fid(int fid, int fd, const char *name)
663 struct progress p = {0};
664 struct np_stat st;
665 size_t r;
666 char buf[BUFSIZ];
668 do_stat(fid, &st);
669 do_open(fid, KOREAD);
671 p.max = st.length;
672 for (;;) {
673 size_t off;
674 ssize_t nw;
676 r = do_read(fid, p.done, sizeof(buf), buf);
677 if (r == 0)
678 break;
680 for (off = 0; off < r; off += nw)
681 if ((nw = write(fd, buf + off, r - off)) == 0 ||
682 nw == -1)
683 err(1, "write");
685 p.done += r;
686 draw_progress(name, &p);
688 #if 0
689 /* throttle, for debugging purpose */
691 struct timespec ts = { 0, 500000000 };
692 nanosleep(&ts, NULL);
694 #endif
697 putchar('\n');
699 do_clunk(fid);
702 static void
703 send_fid(int fid, const char *fnam, int fd, const char *name)
705 struct progress p = {0};
706 struct stat sb;
707 ssize_t r;
708 size_t w;
709 char buf[BUFSIZ];
711 if (fstat(fd, &sb) == -1)
712 err(1, "fstat");
714 if (fnam != NULL)
715 do_create(fid, fnam, 0644, KOWRITE);
716 else
717 do_open(fid, KOWRITE);
719 p.max = sb.st_size;
720 for (;;) {
721 r = read(fd, buf, sizeof(buf));
722 if (r == 0)
723 break;
724 if (r == -1)
725 err(1, "read");
727 w = do_write(fid, p.done, r, buf);
728 p.done += w;
730 draw_progress(name, &p);
732 #if 0
733 /* throttle, for debugging purpose */
735 struct timespec ts = { 0, 500000000 };
736 nanosleep(&ts, NULL);
738 #endif
741 putchar('\n');
742 do_clunk(fid);
745 static int
746 woc_file(int fd, const char *prompt, const char *path)
748 struct qid qid;
749 const char *n = NULL;
750 char *errstr;
751 int nfid, miss;
753 nfid = pwdfid+1;
754 errstr = walk_path(pwdfid, nfid, path, &miss, &qid);
755 if (errstr != NULL && miss > 1) {
756 printf("%s: %s\n", path, errstr);
757 free(errstr);
758 return -1;
761 if (errstr != NULL || miss == 1) {
762 char p[PATH_MAX], *dn;
764 /*
765 * If it's only one component missing (the file name), walk
766 * to the parent directory and try to create the file.
767 */
769 if (strlcpy(p, path, sizeof(p)) >= sizeof(p)) {
770 printf("path too long: %s\n", path);
771 return -1;
773 dn = dirname(p);
775 if (!strcmp(dn, ".")) {
776 errstr = dup_fid(pwdfid, nfid);
777 miss = 0;
778 } else
779 errstr = walk_path(pwdfid, nfid, dn, &miss, &qid);
781 if (errstr != NULL) {
782 printf("%s: %s\n", dn, errstr);
783 free(errstr);
784 return -1;
787 if (miss != 0) {
788 printf("%s: not a directory\n", dn);
789 return -1;
792 if ((n = strrchr(path, '/')) != NULL)
793 n++;
794 else
795 n = path;
798 free(errstr);
800 if (miss > 1) {
801 printf("can't create %s: missing %d path component(s)\n",
802 path, miss);
803 return -1;
806 send_fid(nfid, n, fd, prompt);
807 return 0;
810 static void
811 do_tls_connect(const char *host, const char *port)
813 int handshake;
815 if ((tlsconf = tls_config_new()) == NULL)
816 fatalx("tls_config_new");
817 tls_config_insecure_noverifycert(tlsconf);
818 tls_config_insecure_noverifyname(tlsconf);
819 if (tls_config_set_keypair_file(tlsconf, crtpath, keypath) == -1)
820 fatalx("can't load certs (%s, %s)", crtpath, keypath);
822 if ((ctx = tls_client()) == NULL)
823 fatal("tls_client");
824 if (tls_configure(ctx, tlsconf) == -1)
825 fatalx("tls_configure: %s", tls_error(ctx));
827 if (tls_connect(ctx, host, port) == -1)
828 fatalx("can't connect to %s:%s: %s", host, port,
829 tls_error(ctx));
831 for (handshake = 0; !handshake;) {
832 switch (tls_handshake(ctx)) {
833 case -1:
834 fatalx("tls_handshake: %s", tls_error(ctx));
835 case 0:
836 handshake = 1;
837 break;
842 static void
843 do_ctxt_connect(const char *host, const char *port)
845 struct addrinfo hints, *res, *res0;
846 int error, saved_errno;
847 const char *cause = NULL;
849 memset(&hints, 0, sizeof(hints));
850 hints.ai_family = AF_UNSPEC;
851 hints.ai_socktype = SOCK_STREAM;
852 error = getaddrinfo(host, port, &hints, &res0);
853 if (error)
854 errx(1, "%s", gai_strerror(error));
856 sock = -1;
857 for (res = res0; res != NULL; res = res->ai_next) {
858 sock = socket(res->ai_family, res->ai_socktype|SOCK_CLOEXEC,
859 res->ai_protocol);
860 if (sock == -1) {
861 cause = "socket";
862 continue;
865 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
866 cause = "connect";
867 saved_errno = errno;
868 close(sock);
869 errno = saved_errno;
870 sock = -1;
871 continue;
874 break;
877 if (sock == -1)
878 err(1, "%s", cause);
879 freeaddrinfo(res0);
882 static void
883 do_connect(const char *connspec, const char *path)
885 char *host, *colon;
886 const char *port;
888 host = xstrdup(connspec);
889 if ((colon = strchr(host, ':')) != NULL) {
890 *colon = '\0';
891 port = ++colon;
892 } else
893 port = "1337";
895 printf("connecting to %s:%s...", host, port);
896 fflush(stdout);
898 if (tls)
899 do_tls_connect(host, port);
900 else
901 do_ctxt_connect(host, port);
903 printf(" done!\n");
905 do_version();
906 do_attach(path);
908 free(host);
911 static int
912 tmp_file(char sfn[TMPFSTRLEN])
914 int tmpfd;
916 strlcpy(sfn, TMPFSTR, TMPFSTRLEN);
917 if ((tmpfd = mkstemp(sfn)) == -1) {
918 warn("mkstemp %s", sfn);
919 return -1;
922 return tmpfd;
925 static void
926 cmd_bell(int argc, const char **argv)
928 if (argc == 0) {
929 bell = !bell;
930 if (bell)
931 puts("bell mode enabled");
932 else
933 puts("bell mode disabled");
934 return;
937 if (argc != 1)
938 goto usage;
940 if (!strcmp(*argv, "on")) {
941 bell = 1;
942 puts("bell mode enabled");
943 return;
946 if (!strcmp(*argv, "off")) {
947 bell = 0;
948 puts("bell mode disabled");
949 return;
952 usage:
953 printf("bell [on | off]\n");
956 static void
957 cmd_bye(int argc, const char **argv)
959 log_warnx("bye\n");
960 exit(0);
963 static void
964 cmd_cd(int argc, const char **argv)
966 struct qid qid;
967 int nfid, miss;
968 char *errstr;
970 if (argc != 1) {
971 printf("usage: cd remote-path\n");
972 return;
975 nfid = pwdfid+1;
976 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
977 if (errstr != NULL) {
978 printf("%s: %s\n", argv[0], errstr);
979 free(errstr);
980 return;
983 if (miss != 0 || !(qid.type & QTDIR)) {
984 printf("%s: not a directory\n", argv[0]);
985 if (miss == 0)
986 do_clunk(nfid);
987 return;
990 do_clunk(pwdfid);
991 pwdfid = nfid;
994 static void
995 cmd_edit(int argc, const char **argv)
997 struct qid qid;
998 int nfid, tmpfd, miss;
999 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1000 const char *ed;
1002 if (argc != 1) {
1003 puts("usage: edit file");
1004 return;
1007 if ((ed = getenv("VISUAL")) == NULL &&
1008 (ed = getenv("EDITOR")) == NULL)
1009 ed = "ed";
1011 nfid = pwdfid+1;
1012 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1013 if (errstr != NULL) {
1014 printf("%s: %s\n", *argv, errstr);
1015 free(errstr);
1016 return;
1019 if (miss != 0 || qid.type != 0) {
1020 printf("%s: not a file\n", *argv);
1021 if (miss == 0)
1022 do_clunk(nfid);
1023 return;
1026 if ((tmpfd = tmp_file(sfn)) == -1) {
1027 do_clunk(nfid);
1028 return;
1031 strlcpy(p, *argv, sizeof(p));
1032 name = basename(p);
1034 fetch_fid(nfid, tmpfd, name);
1035 close(tmpfd);
1037 spawn(ed, sfn, NULL);
1040 * Re-open the file because it's not guaranteed that the
1041 * file descriptor tmpfd is still associated with the file
1042 * pointed by sfn: it's not uncommon for editor to write
1043 * a backup file and then rename(2) it to the file name.
1045 if ((tmpfd = open(sfn, O_RDONLY)) == -1) {
1046 warn("can't open %s", sfn);
1047 goto end;
1050 woc_file(tmpfd, *argv, name);
1051 close(tmpfd);
1053 end:
1054 unlink(sfn);
1057 static void
1058 cmd_get(int argc, const char **argv)
1060 struct qid qid;
1061 const char *l;
1062 char *errstr;
1063 int nfid, fd, miss;
1065 if (argc != 1 && argc != 2) {
1066 printf("usage: get remote-file [local-file]\n");
1067 return;
1070 if (argc == 2)
1071 l = argv[1];
1072 else if ((l = strrchr(argv[0], '/')) != NULL)
1073 l++; /* skip / */
1074 else
1075 l = argv[0];
1077 nfid = pwdfid+1;
1078 errstr = walk_path(pwdfid, nfid, argv[0], &miss, &qid);
1079 if (errstr != NULL) {
1080 printf("%s: %s\n", argv[0], errstr);
1081 free(errstr);
1082 return;
1085 if (miss != 0 || qid.type != 0) {
1086 printf("%s: not a file\n", argv[0]);
1087 if (miss == 0)
1088 do_clunk(nfid);
1089 return;
1092 if ((fd = open(l, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644)) == -1) {
1093 warn("can't open %s", l);
1094 do_clunk(nfid);
1095 return;
1098 fetch_fid(nfid, fd, l);
1099 close(fd);
1102 static void
1103 cmd_lcd(int argc, const char **argv)
1105 const char *dir;
1107 if (argc > 1) {
1108 printf("lcd takes only one argument\n");
1109 return;
1112 if (argc == 1)
1113 dir = *argv;
1115 if (argc == 0 && (dir = getenv("HOME")) == NULL) {
1116 printf("HOME is not defined\n");
1117 return;
1120 if (chdir(dir) == -1)
1121 printf("cd: %s: %s\n", dir, strerror(errno));
1124 static void
1125 cmd_lpwd(int argc, const char **argv)
1127 char path[PATH_MAX];
1129 if (getcwd(path, sizeof(path)) == NULL) {
1130 printf("lpwd: %s\n", strerror(errno));
1131 return;
1134 printf("%s\n", path);
1137 static void
1138 cmd_ls(int argc, const char **argv)
1140 struct np_stat st;
1141 uint64_t off = 0;
1142 uint32_t len;
1143 char fmt[FMT_SCALED_STRSIZE], *errstr;
1145 if (argc != 0) {
1146 printf("ls don't take arguments (yet)\n");
1147 return;
1150 if ((errstr = dup_fid(pwdfid, 1)) != NULL) {
1151 printf(".: %s\n", errstr);
1152 free(errstr);
1153 return;
1156 do_open(1, KOREAD);
1158 evbuffer_drain(dirbuf, EVBUFFER_LENGTH(dirbuf));
1160 for (;;) {
1161 tread(1, off, BUFSIZ);
1162 do_send();
1163 recv_msg();
1164 expect2(Rread, iota_tag);
1166 len = np_read32(buf);
1167 if (len == 0)
1168 break;
1170 evbuffer_add_buffer(dirbuf, buf);
1171 off += len;
1173 ASSERT_EMPTYBUF();
1176 while (EVBUFFER_LENGTH(dirbuf) != 0) {
1177 if (np_read_stat(dirbuf, &st) == -1)
1178 errx(1, "invalid stat struct read");
1180 if (fmt_scaled(st.length, fmt) == -1)
1181 strlcpy(fmt, "xxx", sizeof(fmt));
1183 printf("%4s %8s %s\n", pp_qid_type(st.qid.type), fmt, st.name);
1185 free(st.name);
1186 free(st.uid);
1187 free(st.gid);
1188 free(st.muid);
1191 do_clunk(1);
1194 static void
1195 cmd_page(int argc, const char **argv)
1197 struct qid qid;
1198 int nfid, tmpfd, miss;
1199 char sfn[TMPFSTRLEN], p[PATH_MAX], *name, *errstr;
1201 if (argc != 1) {
1202 puts("usage: page file");
1203 return;
1206 nfid = pwdfid+1;
1207 errstr = walk_path(pwdfid, nfid, *argv, &miss, &qid);
1208 if (errstr != NULL) {
1209 printf("%s: %s\n", *argv, errstr);
1210 free(errstr);
1211 return;
1214 if (miss != 0 || qid.type != 0) {
1215 printf("%s: not a file\n", *argv);
1216 if (miss == 0)
1217 do_clunk(nfid);
1218 return;
1221 if ((tmpfd = tmp_file(sfn)) == -1) {
1222 do_clunk(nfid);
1223 return;
1226 strlcpy(p, *argv, sizeof(p));
1227 name = basename(p);
1228 fetch_fid(nfid, tmpfd, name);
1229 close(tmpfd);
1230 spawn("less", sfn, NULL);
1231 unlink(sfn);
1234 static void
1235 cmd_put(int argc, const char **argv)
1237 struct qid qid;
1238 const char *l;
1239 int fd;
1241 if (argc != 1 && argc != 2) {
1242 printf("usage: put local-file [remote-file]\n");
1243 return;
1246 if (argc == 2)
1247 l = argv[1];
1248 else if ((l = strrchr(argv[0], '/')) != NULL)
1249 l++; /* skip / */
1250 else
1251 l = argv[0];
1253 if ((fd = open(argv[0], O_RDONLY)) == -1) {
1254 warn("%s", argv[0]);
1255 return;
1258 woc_file(fd, argv[0], l);
1259 close(fd);
1262 static void
1263 cmd_verbose(int argc, const char **argv)
1265 if (argc == 0) {
1266 log_setverbose(!log_getverbose());
1267 if (log_getverbose())
1268 puts("verbose mode enabled");
1269 else
1270 puts("verbose mode disabled");
1271 return;
1274 if (argc != 1)
1275 goto usage;
1277 if (!strcmp(*argv, "on")) {
1278 log_setverbose(1);
1279 puts("verbose mode enabled");
1280 return;
1283 if (!strcmp(*argv, "off")) {
1284 log_setverbose(0);
1285 puts("verbose mode disabled");
1286 return;
1289 usage:
1290 printf("verbose [on | off]\n");
1293 static void
1294 excmd(int argc, const char **argv)
1296 struct cmd {
1297 const char *name;
1298 void (*fn)(int, const char **);
1299 } cmds[] = {
1300 {"bell", cmd_bell},
1301 {"bye", cmd_bye},
1302 {"cd", cmd_cd},
1303 {"edit", cmd_edit},
1304 {"get", cmd_get},
1305 {"lcd", cmd_lcd},
1306 {"lpwd", cmd_lpwd},
1307 {"ls", cmd_ls},
1308 {"page", cmd_page},
1309 {"put", cmd_put},
1310 {"quit", cmd_bye},
1311 {"verbose", cmd_verbose},
1313 size_t i;
1315 if (argc == 0)
1316 return;
1317 for (i = 0; i < nitems(cmds); ++i) {
1318 if (!strcmp(cmds[i].name, *argv)) {
1319 cmds[i].fn(argc-1, argv+1);
1320 return;
1324 log_warnx("unknown command %s", *argv);
1327 int
1328 main(int argc, char **argv)
1330 int ch;
1332 log_init(1, LOG_DAEMON);
1333 log_setverbose(0);
1334 log_procinit(getprogname());
1336 while ((ch = getopt(argc, argv, "C:cK:")) != -1) {
1337 switch (ch) {
1338 case 'C':
1339 crtpath = optarg;
1340 break;
1341 case 'c':
1342 tls = 1;
1343 break;
1344 case 'K':
1345 keypath = optarg;
1346 break;
1347 default:
1348 usage(1);
1351 argc -= optind;
1352 argv += optind;
1354 if (argc == 0)
1355 usage(1);
1357 if (isatty(1)) {
1358 tty_p = 1;
1359 resized = 1;
1360 signal(SIGWINCH, tty_resized);
1363 if ((evb = evbuffer_new()) == NULL)
1364 fatal("evbuffer_new");
1366 if ((buf = evbuffer_new()) == NULL)
1367 fatal("evbuffer_new");
1369 if ((dirbuf = evbuffer_new()) == NULL)
1370 fatal("evbuferr_new");
1372 do_connect(argv[0], argv[1]);
1374 for (;;) {
1375 int argc = 0;
1376 char *line, *argv[16] = {0}, **ap;
1378 if ((line = read_line("kamiftp> ")) == NULL)
1379 break;
1381 for (argc = 0, ap = argv; ap < &argv[15] &&
1382 (*ap = strsep(&line, " \t")) != NULL;) {
1383 if (**ap != '\0')
1384 ap++, argc++;
1386 excmd(argc, (const char **)argv);
1388 if (bell) {
1389 printf("\a");
1390 fflush(stdout);
1393 free(line);
1396 printf("\n");