Blob


1 /*
2 * Copyright (c) 2021 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/stat.h>
20 #include <sys/types.h>
21 #include <sys/uio.h>
23 #include <dirent.h>
24 #include <endian.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <pwd.h>
28 #include <signal.h>
29 #include <stdint.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <syslog.h>
33 #include <unistd.h>
35 #include "client.h"
36 #include "kami.h"
37 #include "kamid.h"
38 #include "log.h"
39 #include "sandbox.h"
40 #include "utils.h"
42 /*
43 * XXX: atm is difficult to accept messages bigger than MAX_IMSGSIZE
44 * minus IMSG_HEADER_SIZE, we need something to split messages into
45 * chunks and receive them one by the other.
46 *
47 * CLIENT_MSIZE is thus the maximum message size we can handle now.
48 */
49 #define CLIENT_MSIZE (MAX_IMSGSIZE - IMSG_HEADER_SIZE)
51 #define DEBUG_PACKETS 0
53 /* straight outta /src/usr.bin/ssh/scp.c */
54 #define TYPE_OVERFLOW(type, val) \
55 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
56 (sizeof(type) == 8 && (val) > INT64_MAX) || \
57 (sizeof(type) != 4 && sizeof(type) != 8))
59 STAILQ_HEAD(dirhead, dir) dirs;
60 struct dir {
61 int refcount;
62 int fd;
63 STAILQ_ENTRY(dir) entries;
64 };
66 STAILQ_HEAD(fidhead, fid) fids;
67 struct fid {
68 uint32_t fid;
70 char fpath[PATH_MAX];
72 /*
73 * the flags passed to open(2). O_CLOEXEC means ORCLOSE, that
74 * is to unlink the file upon Tclunk.
75 */
76 int iomode;
78 /*
79 * if fd is not -1 this fid was opened, fd represents its
80 * file descriptor and iomode the flags passed to open(2).
81 */
82 int fd;
83 DIR *d;
84 struct evbuffer *evb;
86 /*
87 * expected offset for Tread against a directory.
88 */
89 uint64_t offset;
91 struct qid qid;
92 struct dir *dir;
93 STAILQ_ENTRY(fid) entries;
94 };
96 static struct imsgev *iev_listener;
97 static struct evbuffer *evb;
98 static uint32_t peerid;
100 static int handshaked;
101 uint32_t msize;
103 static __dead void client_shutdown(void);
104 static void client_sig_handler(int, short, void *);
105 static void client_dispatch_listener(int, short, void *);
106 static void client_privdrop(const char *, const char *);
108 static int client_send_listener(int, const void *, uint16_t);
110 static void qid_update_from_sb(struct qid *, struct stat *);
112 static struct dir *new_dir(int);
113 static struct dir *dir_incref(struct dir *);
114 static void dir_decref(struct dir *);
116 static struct fid *new_fid(struct dir *, uint32_t, const char *, struct qid *);
117 static struct fid *fid_by_id(uint32_t);
118 static void free_fid(struct fid *);
120 static void parse_message(const uint8_t *, size_t,
121 struct np_msg_header *, uint8_t **);
123 static void np_write16(struct evbuffer *, uint16_t);
124 static void np_write32(struct evbuffer *, uint32_t);
125 static void np_write64(struct evbuffer *, uint64_t);
126 static void np_header(uint32_t, uint8_t, uint16_t);
127 static void np_string(struct evbuffer *, uint16_t, const char *);
128 static void np_qid(struct evbuffer *, struct qid *);
129 static void do_send(void);
131 static void np_version(uint16_t, uint32_t, const char *);
132 static void np_attach(uint16_t, struct qid *);
133 static void np_clunk(uint16_t);
134 static void np_flush(uint16_t);
135 static void np_walk(uint16_t, int, struct qid *);
136 static void np_open(uint16_t, struct qid *, uint32_t);
137 static void np_create(uint16_t, struct qid *, uint32_t);
138 static void np_read(uint16_t, uint32_t, void *);
139 static void np_write(uint16_t, uint32_t);
140 static void np_stat(uint16_t, uint32_t, void *);
141 static void np_remove(uint16_t);
142 static void np_error(uint16_t, const char *);
143 static void np_errno(uint16_t);
145 static int np_read8(const char *, const char *, uint8_t *,
146 const uint8_t **, size_t *);
147 static int np_read16(const char *, const char *, uint16_t *,
148 const uint8_t **, size_t *);
149 static int np_read32(const char *, const char *, uint32_t *,
150 const uint8_t **, size_t *);
151 static int np_read64(const char *, const char *, uint64_t *,
152 const uint8_t **, size_t *);
154 #define READSTRERR -1
155 #define READSTRTRUNC -2
156 static int np_readstr(const char *, const char *, char *, size_t,
157 const uint8_t **, size_t *);
159 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
160 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
161 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
162 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
164 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
166 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
167 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
168 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
169 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
170 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
171 static void topen(struct np_msg_header *, const uint8_t *, size_t);
172 static void tcreate(struct np_msg_header *, const uint8_t *, size_t);
173 static void tread(struct np_msg_header *, const uint8_t *, size_t);
174 static void twrite(struct np_msg_header *, const uint8_t *, size_t);
175 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
176 static void tremove(struct np_msg_header *, const uint8_t *, size_t);
177 static void handle_message(struct imsg *, size_t);
179 __dead void
180 client(int debug, int verbose)
182 struct event ev_sigint, ev_sigterm;
184 log_init(debug, LOG_DAEMON);
185 log_setverbose(verbose);
187 setproctitle("client");
188 log_procinit("client");
190 log_debug("warming up");
192 event_init();
194 /* Setup signal handlers */
195 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
196 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
198 signal_add(&ev_sigint, NULL);
199 signal_add(&ev_sigterm, NULL);
201 signal(SIGPIPE, SIG_IGN);
202 signal(SIGHUP, SIG_IGN);
204 /* Setup pipe and event handler to the listener process */
205 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
206 fatal(NULL);
208 imsg_init(&iev_listener->ibuf, 3);
209 iev_listener->handler = client_dispatch_listener;
211 /* Setup event handlers. */
212 iev_listener->events = EV_READ;
213 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
214 iev_listener->events, iev_listener->handler, iev_listener);
215 event_add(&iev_listener->ev, NULL);
217 event_dispatch();
218 client_shutdown();
221 static __dead void
222 client_shutdown(void)
224 if (evb != NULL)
225 evbuffer_free(evb);
227 msgbuf_clear(&iev_listener->ibuf.w);
228 close(iev_listener->ibuf.fd);
230 free(iev_listener);
232 log_debug("client exiting");
233 exit(0);
236 static void
237 client_sig_handler(int sig, short event, void *d)
239 /*
240 * Normal signal handler rules don't apply because libevent
241 * decouples for us.
242 */
244 switch (sig) {
245 case SIGINT:
246 case SIGTERM:
247 client_shutdown();
248 default:
249 fatalx("unexpected signal %d", sig);
253 #define AUTH_NONE 0
254 #define AUTH_USER 1
255 #define AUTH_DONE 2
257 static void
258 client_dispatch_listener(int fd, short event, void *d)
260 static int auth = AUTH_NONE;
261 static char username[64] = {0};
262 static char dir[PATH_MAX] = {0};
263 struct imsg imsg;
264 struct imsgev *iev = d;
265 struct imsgbuf *ibuf;
266 ssize_t n;
267 int shut = 0;
269 ibuf = &iev->ibuf;
271 if (event & EV_READ) {
272 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
273 fatal("imsg_read error");
274 if (n == 0) /* Connection closed */
275 shut = 1;
277 if (event & EV_WRITE) {
278 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
279 fatal("msgbuf_write");
280 if (n == 0) /* Connection closed */
281 shut = 1;
284 for (;;) {
285 if ((n = imsg_get(ibuf, &imsg)) == -1)
286 fatal("%s: imsg_get error", __func__);
287 if (n == 0) /* No more messages. */
288 break;
290 switch (imsg.hdr.type) {
291 case IMSG_AUTH:
292 peerid = imsg.hdr.peerid;
293 if (auth)
294 fatalx("%s: IMSG_AUTH already done", __func__);
295 auth = AUTH_USER;
296 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
297 strlcpy(username, imsg.data, sizeof(username));
298 break;
299 case IMSG_AUTH_DIR:
300 if (auth != AUTH_USER)
301 fatalx("%s: IMSG_AUTH_DIR not after IMSG_AUTH",
302 __func__);
303 auth = AUTH_DONE;
304 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
305 strlcpy(dir, imsg.data, sizeof(dir));
306 client_privdrop(username, dir);
307 memset(username, 0, sizeof(username));
308 memset(dir, 0, sizeof(username));
309 break;
310 case IMSG_BUF:
311 /* echo! */
312 if (!auth)
313 fatalx("%s: can't handle messages before"
314 " doing the auth", __func__);
315 handle_message(&imsg, IMSG_DATA_SIZE(imsg));
316 break;
317 case IMSG_CONN_GONE:
318 log_debug("closing");
319 shut = 1;
320 break;
321 default:
322 log_debug("%s: unexpected imsg %d",
323 __func__, imsg.hdr.type);
324 break;
326 imsg_free(&imsg);
329 if (!shut)
330 imsg_event_add(iev);
331 else {
332 /* This pipe is dead. Remove its event handler. */
333 event_del(&iev->ev);
334 log_debug("pipe closed, shutting down...");
335 event_loopexit(NULL);
339 static void
340 client_privdrop(const char *username, const char *dir)
342 struct passwd *pw;
344 setproctitle("client %s", username);
346 if ((pw = getpwnam(username)) == NULL)
347 fatalx("getpwnam(%s) failed", username);
349 if (chroot(dir) == -1)
350 fatal("chroot");
351 if (chdir("/") == -1)
352 fatal("chdir(\"/\")");
354 if (setgroups(1, &pw->pw_gid) ||
355 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
356 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
357 fatal("can't drop privileges");
359 sandbox_client();
360 log_debug("client ready; user=%s dir=%s", username, dir);
362 if ((evb = evbuffer_new()) == NULL)
363 fatal("evbuffer_new");
366 static int
367 client_send_listener(int type, const void *data, uint16_t len)
369 int ret;
371 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
372 data, len)) != -1)
373 imsg_event_add(iev_listener);
375 return ret;
378 /* set qid fields from sb */
379 static void
380 qid_update_from_sb(struct qid *qid, struct stat *sb)
382 qid->path = sb->st_ino;
384 /*
385 * Theoretically (and hopefully!) this should be a 64 bit
386 * number. Unfortunately, 9P uses 32 bit timestamps.
387 */
388 qid->vers = sb->st_mtim.tv_sec;
390 if (S_ISREG(sb->st_mode))
391 qid->type = QTFILE;
392 else if (S_ISDIR(sb->st_mode))
393 qid->type = QTDIR;
394 else if (S_ISLNK(sb->st_mode))
395 qid->type = QTSYMLINK;
398 /* creates a qid given a fd */
399 static struct dir *
400 new_dir(int fd)
402 struct dir *dir;
404 if ((dir = calloc(1, sizeof(*dir))) == NULL)
405 return NULL;
407 dir->fd = fd;
408 STAILQ_INSERT_HEAD(&dirs, dir, entries);
409 return dir;
412 static struct dir *
413 dir_incref(struct dir *dir)
415 dir->refcount++;
416 return dir;
419 static void
420 dir_decref(struct dir *dir)
422 if (--dir->refcount > 0)
423 return;
425 STAILQ_REMOVE(&dirs, dir, dir, entries);
427 close(dir->fd);
428 free(dir);
431 static struct fid *
432 new_fid(struct dir *dir, uint32_t fid, const char *path, struct qid *qid)
434 struct fid *f;
435 struct qid q;
436 struct stat sb;
438 if (qid == NULL) {
439 if (fstatat(dir->fd, path, &sb, 0)) {
440 log_warn("fstatat(%s)", path);
441 return NULL;
443 qid_update_from_sb(&q, &sb);
444 qid = &q;
447 if ((f = calloc(1, sizeof(*f))) == NULL)
448 return NULL;
450 f->dir = dir_incref(dir);
451 f->fid = fid;
452 f->fd = -1;
454 strlcpy(f->fpath, path, sizeof(f->fpath));
456 memcpy(&f->qid, qid, sizeof(f->qid));
458 STAILQ_INSERT_HEAD(&fids, f, entries);
460 return f;
463 static struct fid *
464 fid_by_id(uint32_t fid)
466 struct fid *f;
468 STAILQ_FOREACH(f, &fids, entries) {
469 if (f->fid == fid)
470 return f;
473 return NULL;
476 static void
477 free_fid(struct fid *f)
479 int r;
481 if (f->fd != -1) {
482 if (f->d != NULL)
483 r = closedir(f->d);
484 else
485 r = close(f->fd);
487 if (r == -1)
488 fatal("can't close fid %d", f->fid);
490 if (f->evb != NULL)
491 evbuffer_free(f->evb);
493 /* try to honour ORCLOSE if requested */
494 if (f->iomode & O_CLOEXEC)
495 unlinkat(f->dir->fd, f->fpath, 0);
498 dir_decref(f->dir);
500 STAILQ_REMOVE(&fids, f, fid, entries);
501 free(f);
504 static void
505 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
506 uint8_t **cnt)
508 size_t olen = len;
510 if (!NPREAD32("len", &hdr->len, &data, &len) ||
511 !NPREAD8("type", &hdr->type, &data, &len) ||
512 !NPREAD16("tag", &hdr->tag, &data, &len))
513 goto err;
515 if (olen != hdr->len)
516 goto err;
518 if (hdr->type < Tversion ||
519 hdr->type >= Tmax ||
520 hdr->type == Terror ||
521 (hdr->type & 0x1) != 0) /* cannot recv a R* */
522 goto err;
524 hdr->tag = le32toh(hdr->tag);
526 *cnt = (uint8_t *)data;
527 return;
529 err:
530 /* TODO: send a proper message to terminate the connection. */
531 fatalx("got invalid message");
534 static void
535 np_write16(struct evbuffer *e, uint16_t x)
537 x = htole16(x);
538 evbuffer_add(e, &x, sizeof(x));
541 static void
542 np_write32(struct evbuffer *e, uint32_t x)
544 x = htole32(x);
545 evbuffer_add(e, &x, sizeof(x));
548 static void
549 np_write64(struct evbuffer *e, uint64_t x)
551 x = htole64(x);
552 evbuffer_add(e, &x, sizeof(x));
555 static void
556 np_writebuf(struct evbuffer *e, size_t len, void *data)
558 evbuffer_add(e, data, len);
561 static void
562 np_header(uint32_t len, uint8_t type, uint16_t tag)
564 len += HEADERSIZE;
566 len = htole32(len);
567 tag = htole16(tag);
569 evbuffer_add(evb, &len, sizeof(len));
570 evbuffer_add(evb, &type, sizeof(type));
571 evbuffer_add(evb, &tag, sizeof(tag));
574 static void
575 np_string(struct evbuffer *e, uint16_t len, const char *str)
577 uint16_t l = len;
579 len = htole16(len);
580 evbuffer_add(e, &len, sizeof(len));
581 evbuffer_add(e, str, l);
584 static void
585 np_qid(struct evbuffer *e, struct qid *qid)
587 uint64_t path;
588 uint32_t vers;
590 path = htole64(qid->path);
591 vers = htole32(qid->vers);
593 evbuffer_add(e, &qid->type, sizeof(qid->type));
594 evbuffer_add(e, &vers, sizeof(vers));
595 evbuffer_add(e, &path, sizeof(path));
598 static void
599 do_send(void)
601 size_t len;
602 void *data;
604 len = EVBUFFER_LENGTH(evb);
605 data = EVBUFFER_DATA(evb);
607 #if DEBUG_PACKETS
608 hexdump("outgoing packet", data, len);
609 #endif
610 client_send_listener(IMSG_BUF, data, len);
611 evbuffer_drain(evb, len);
614 static void
615 np_version(uint16_t tag, uint32_t msize, const char *version)
617 uint16_t l;
619 l = strlen(version);
621 msize = htole32(msize);
623 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
624 evbuffer_add(evb, &msize, sizeof(msize));
625 np_string(evb, l, version);
626 do_send();
629 static void
630 np_attach(uint16_t tag, struct qid *qid)
632 np_header(QIDSIZE, Rattach, tag);
633 np_qid(evb, qid);
634 do_send();
637 static void
638 np_clunk(uint16_t tag)
640 np_header(0, Rclunk, tag);
641 do_send();
644 static void
645 np_flush(uint16_t tag)
647 np_header(0, Rflush, tag);
648 do_send();
651 static void
652 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
654 int i;
656 /* two bytes for the counter */
657 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
658 np_write16(evb, nwqid);
659 for (i = 0; i < nwqid; ++i)
660 np_qid(evb, wqid + i);
662 do_send();
665 static void
666 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
668 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
669 np_qid(evb, qid);
670 np_write32(evb, iounit);
671 do_send();
674 static void
675 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
677 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
678 np_qid(evb, qid);
679 np_write32(evb, iounit);
680 do_send();
683 static void
684 np_read(uint16_t tag, uint32_t count, void *data)
686 if (sizeof(count) + count + HEADERSIZE >= msize) {
687 np_error(tag, "Rread would overflow");
688 return;
691 np_header(sizeof(count) + count, Rread, tag);
692 np_write32(evb, count);
693 np_writebuf(evb, count, data);
694 do_send();
697 static void
698 np_write(uint16_t tag, uint32_t count)
700 np_header(sizeof(count), Rwrite, tag);
701 np_write32(evb, count);
702 do_send();
705 static void
706 np_stat(uint16_t tag, uint32_t count, void *data)
708 if (sizeof(count) + count + HEADERSIZE >= msize) {
709 np_error(tag, "Rstat would overflow");
710 return;
713 np_header(count, Rstat, tag);
714 np_writebuf(evb, count, data);
715 do_send();
718 static void
719 np_remove(uint16_t tag)
721 np_header(0, Rremove, tag);
722 do_send();
725 static void
726 np_error(uint16_t tag, const char *errstr)
728 uint16_t l;
730 l = strlen(errstr);
732 np_header(sizeof(l) + l, Rerror, tag);
733 np_string(evb, l, errstr);
734 do_send();
737 static void
738 np_errno(uint16_t tag)
740 int saved_errno;
741 char buf[NL_TEXTMAX] = {0};
743 saved_errno = errno;
745 strerror_r(errno, buf, sizeof(buf));
746 np_error(tag, buf);
748 errno = saved_errno;
751 static int
752 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
753 size_t *len)
755 if (*len < sizeof(*dst)) {
756 log_warnx("%s: wanted %zu bytes for the %s field but only "
757 "%zu are available.", t, sizeof(*dst), f, *len);
758 return -1;
761 memcpy(dst, *src, sizeof(*dst));
762 *src += sizeof(*dst);
763 *len -= sizeof(*dst);
765 return 1;
768 static int
769 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
770 size_t *len)
772 if (*len < sizeof(*dst)) {
773 log_warnx("%s: wanted %zu bytes for the %s field but only "
774 "%zu are available.", t, sizeof(*dst), f, *len);
775 return -1;
778 memcpy(dst, *src, sizeof(*dst));
779 *src += sizeof(*dst);
780 *len -= sizeof(*dst);
781 *dst = le16toh(*dst);
783 return 1;
786 static int
787 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
788 size_t *len)
790 if (*len < sizeof(*dst)) {
791 log_warnx("%s: wanted %zu bytes for the %s field but only "
792 "%zu are available.", t, sizeof(*dst), f, *len);
793 return -1;
796 memcpy(dst, *src, sizeof(*dst));
797 *src += sizeof(*dst);
798 *len -= sizeof(*dst);
799 *dst = le32toh(*dst);
801 return 1;
804 static int
805 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
806 size_t *len)
808 if (*len < sizeof(*dst)) {
809 log_warnx("%s: wanted %zu bytes for the %s field but only "
810 "%zu are available.", t, sizeof(*dst), f, *len);
811 return -1;
814 memcpy(dst, *src, sizeof(*dst));
815 *src += sizeof(*dst);
816 *len -= sizeof(*dst);
817 *dst = le64toh(*dst);
819 return 1;
822 static int
823 np_readstr(const char *t, const char *f, char *res, size_t reslen,
824 const uint8_t **src, size_t *len)
826 uint16_t sl;
827 char buf[32];
829 strlcpy(buf, f, sizeof(buf));
830 strlcat(buf, "-len", sizeof(buf));
832 if (!np_read16(t, buf, &sl, src, len))
833 return READSTRERR;
835 if (*len < sl) {
836 log_warnx("%s: wanted %d bytes for the %s field but only "
837 "%zu are available.", t, sl, f, *len);
838 return READSTRERR;
841 if (*len > reslen-1)
842 return READSTRTRUNC;
844 memcpy(res, *src, sl);
845 res[sl] = '\0';
846 *src += sl;
847 *len -= sl;
849 return 0;
852 static void
853 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
855 char *dot, version[32];
857 if (handshaked)
858 goto err;
860 /* msize[4] version[s] */
861 if (!NPREAD32("msize", &msize, &data, &len))
862 goto err;
864 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
865 case READSTRERR:
866 goto err;
867 case READSTRTRUNC:
868 log_warnx("9P version string too long, truncated");
869 goto mismatch;
872 if ((dot = strchr(version, '.')) != NULL)
873 *dot = '\0';
875 if (strcmp(version, VERSION9P) != 0 ||
876 msize == 0)
877 goto mismatch;
879 /* version matched */
880 handshaked = 1;
881 msize = MIN(msize, CLIENT_MSIZE);
882 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
883 np_version(hdr->tag, msize, VERSION9P);
884 return;
886 mismatch:
887 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
888 version);
889 np_version(hdr->tag, MSIZE9P, "unknown");
890 return;
892 err:
893 client_send_listener(IMSG_CLOSE, NULL, 0);
894 client_shutdown();
897 static void
898 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
900 struct dir *dir;
901 struct fid *f;
902 uint32_t fid, afid;
903 int fd;
904 char aname[PATH_MAX];
906 /* fid[4] afid[4] uname[s] aname[s] */
908 if (!NPREAD32("fid", &fid, &data, &len) ||
909 !NPREAD32("afid", &afid, &data, &len))
910 goto err;
912 /* read the uname but don't actually use it */
913 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
914 case READSTRERR:
915 goto err;
916 case READSTRTRUNC:
917 np_error(hdr->tag, "name too long");
918 return;
921 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
922 case READSTRERR:
923 goto err;
924 case READSTRTRUNC:
925 np_error(hdr->tag, "name too long");
926 return;
929 if (fid_by_id(fid) != NULL || afid != NOFID) {
930 np_error(hdr->tag, "invalid fid or afid");
931 return;
934 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
935 goto fail;
937 if ((dir = new_dir(fd)) == NULL)
938 goto fail;
940 log_debug("attached %s to %d", aname, fid);
942 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
943 dir_decref(dir);
944 goto fail;
947 np_attach(hdr->tag, &f->qid);
948 return;
950 fail:
951 np_errno(hdr->tag);
952 log_warn("failed to attach %s", aname);
953 return;
955 err:
956 client_send_listener(IMSG_CLOSE, NULL, 0);
957 client_shutdown();
960 static void
961 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
963 struct fid *f;
964 uint32_t fid;
966 /* fid[4] */
967 if (!NPREAD32("fid", &fid, &data, &len)) {
968 client_send_listener(IMSG_CLOSE, NULL, 0);
969 client_shutdown();
970 return;
973 if ((f = fid_by_id(fid)) == NULL) {
974 np_error(hdr->tag, "invalid fid");
975 return;
978 free_fid(f);
979 np_clunk(hdr->tag);
982 static void
983 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
985 uint16_t oldtag;
987 /*
988 * We're doing only synchronous I/O. Tflush is implemented
989 * only because it's illegal to reply with a Rerror.
990 */
992 /* oldtag[2] */
993 if (len != sizeof(oldtag)) {
994 log_warnx("Tflush with the wrong size: got %zu want %zu",
995 len, sizeof(oldtag));
996 client_send_listener(IMSG_CLOSE, NULL, 0);
997 client_shutdown();
998 return;
1001 np_flush(hdr->tag);
1004 static void
1005 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1007 struct stat sb;
1008 struct dir *dir;
1009 struct qid wqid[MAXWELEM] = {0};
1010 struct fid *f, *nf;
1011 uint32_t fid, newfid;
1012 uint16_t nwname;
1013 int fd, oldfd, no, nwqid = 0;
1014 char wnam[PATH_MAX];
1016 if (!NPREAD32("fid", &fid, &data, &len) ||
1017 !NPREAD32("newfid", &newfid, &data, &len) ||
1018 !NPREAD16("nwname", &nwname, &data, &len))
1019 goto err;
1021 if (nwname > MAXWELEM) {
1022 log_warnx("Twalk: more than %d path elements: %d",
1023 MAXWELEM, nwname);
1024 goto err;
1027 if ((f = fid_by_id(fid)) == NULL) {
1028 np_error(hdr->tag, "invalid fid");
1029 return;
1032 if (f->fd != -1) {
1033 np_error(hdr->tag, "fid already opened for I/O");
1034 return;
1037 if (fid == newfid)
1038 nf = f;
1039 else if ((nf = fid_by_id(newfid)) != NULL) {
1040 np_error(hdr->tag, "newfid already in use");
1041 return;
1042 } else
1043 nf = NULL;
1045 /* special case: fid duplication */
1046 if (nwname == 0) {
1048 * TODO: should we forbid fids duplication when fid ==
1049 * newfid?
1051 if (nf == NULL &&
1052 (nf = new_fid(f->dir, newfid, f->fpath, &f->qid)) == NULL)
1053 fatal("new_fid duplication");
1055 np_walk(hdr->tag, 0, NULL);
1056 return;
1059 if (!(f->qid.type & QTDIR)) {
1060 np_error(hdr->tag, "fid doesn't represent a directory");
1061 return;
1064 oldfd = f->dir->fd;
1066 for (nwqid = 0; nwqid < nwname; nwqid++) {
1067 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1068 case READSTRERR:
1069 goto err;
1070 case READSTRTRUNC:
1071 np_error(hdr->tag, "wname too long");
1072 return;
1075 if (*wnam == '\0' ||
1076 strchr(wnam, '/') != NULL ||
1077 !strcmp(wnam, ".")) {
1078 errno = EINVAL;
1079 goto cantopen;
1082 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1083 errno != ENOTDIR)
1084 goto cantopen;
1086 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1087 (fd != -1 && fstat(fd, &sb) == -1))
1088 goto cantopen;
1090 qid_update_from_sb(&wqid[nwqid], &sb);
1092 /* reached a file but we still have other components */
1093 if (fd == -1 && nwqid+1 < nwname)
1094 goto cantopen;
1096 /* reached the end and found a file */
1097 if (fd == -1 && nwqid+1 == nwname)
1098 continue;
1100 if (oldfd != f->dir->fd)
1101 close(oldfd);
1102 oldfd = fd;
1106 * If fd is -1 we've reached a file, otherwise we've just
1107 * reached another directory. We must pay attention to what
1108 * file descriptor we use to create the dir, because if we've
1109 * reached a file and oldfd is f->dir->fd then we *must* share
1110 * the same dir (it was a walk of one path from a directory to a
1111 * file, otherwise fun is bound to happen as soon as the client
1112 * closes the fid for the directory but keeps the one for the
1113 * file.
1115 if (fd == -1 && oldfd == f->dir->fd)
1116 dir = f->dir;
1117 else if (fd == -1)
1118 dir = new_dir(oldfd);
1119 else
1120 dir = new_dir(fd);
1122 if (dir == NULL)
1123 fatal("new_dir");
1125 if (nf == NULL) {
1126 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1127 fatal("new fid");
1128 } else {
1129 /* update the dir */
1130 dir_decref(nf->dir);
1131 nf->dir = dir_incref(dir);
1134 np_walk(hdr->tag, nwqid, wqid);
1135 return;
1137 cantopen:
1138 if (oldfd != f->dir->fd)
1139 close(oldfd);
1140 no = errno;
1141 if (nwqid == 0)
1142 np_error(hdr->tag, strerror(no));
1143 else
1144 np_walk(hdr->tag, nwqid, wqid);
1145 return;
1147 err:
1148 client_send_listener(IMSG_CLOSE, NULL, 0);
1149 client_shutdown();
1152 static inline int
1153 npmode_to_unix(uint8_t mode, int *flags)
1155 switch (mode & 0x0F) {
1156 case KOREAD:
1157 *flags = O_RDONLY;
1158 break;
1159 case KOWRITE:
1160 *flags = O_WRONLY;
1161 break;
1162 case KORDWR:
1163 *flags = O_RDWR;
1164 break;
1165 case KOEXEC:
1166 log_warnx("tried to open something with KOEXEC");
1167 /* fallthrough */
1168 default:
1169 return -1;
1172 if (mode & KOTRUNC)
1173 *flags |= O_TRUNC;
1174 if (mode & KORCLOSE)
1175 *flags |= O_CLOEXEC;
1177 return 0;
1180 static void
1181 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1183 struct stat sb;
1184 struct qid qid;
1185 struct fid *f;
1186 uint32_t fid;
1187 uint8_t mode;
1188 const char *path;
1190 /* fid[4] mode[1] */
1191 if (!NPREAD32("fid", &fid, &data, &len) ||
1192 !NPREAD8("mode", &mode, &data, &len)) {
1193 client_send_listener(IMSG_CLOSE, NULL, 0);
1194 client_shutdown();
1195 return;
1198 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1199 np_error(hdr->tag, "invalid fid");
1200 return;
1203 if (npmode_to_unix(mode, &f->iomode) == -1) {
1204 np_error(hdr->tag, "invalid mode");
1205 return;
1208 path = f->fpath;
1209 if (f->qid.type & QTDIR)
1210 path = ".";
1212 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1213 np_error(hdr->tag, strerror(errno));
1214 return;
1217 if (fstat(f->fd, &sb) == -1)
1218 fatal("fstat");
1220 if (S_ISDIR(sb.st_mode)) {
1221 if ((f->d = fdopendir(f->fd)) == NULL) {
1222 np_errno(hdr->tag);
1223 close(f->fd);
1224 f->fd = -1;
1225 return;
1228 if ((f->evb = evbuffer_new()) == NULL) {
1229 np_errno(hdr->tag);
1230 closedir(f->d);
1231 f->d = NULL;
1232 f->fd = -1;
1236 f->offset = 0;
1238 qid_update_from_sb(&qid, &sb);
1239 np_open(hdr->tag, &qid, sb.st_blksize);
1242 static void
1243 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1245 struct stat sb;
1246 struct qid qid;
1247 struct fid *f;
1248 uint32_t fid, perm;
1249 uint8_t mode;
1250 char name[PATH_MAX];
1252 /* fid[4] name[s] perm[4] mode[1] */
1253 if (!NPREAD32("fid", &fid, &data, &len))
1254 goto err;
1255 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1256 case READSTRERR:
1257 goto err;
1258 case READSTRTRUNC:
1259 np_error(hdr->tag, "name too long");
1260 return;
1262 if (!NPREAD32("perm", &perm, &data, &len) ||
1263 !NPREAD8("mode", &mode, &data, &len))
1264 goto err;
1266 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1267 strchr(name, '/') != NULL) {
1268 np_error(hdr->tag, "invalid name");
1269 return;
1272 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1273 np_error(hdr->tag, "invalid fid");
1274 return;
1277 if (!(f->qid.type & QTDIR)) {
1278 np_error(hdr->tag, "fid doesn't identify a directory");
1279 return;
1282 if (npmode_to_unix(mode, &f->iomode) == -1) {
1283 np_error(hdr->tag, "invalid mode");
1284 return;
1287 if (f->iomode & O_RDONLY) {
1288 np_error(hdr->tag, "can't create a read-only file");
1289 return;
1292 /* TODO: parse the mode */
1294 if (perm & 0x80000000) {
1295 /* create a directory */
1296 f->fd = mkdirat(f->dir->fd, name, 0755);
1297 } else {
1298 /* create a file */
1299 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1300 0644);
1303 if (f->fd == -1) {
1304 np_errno(hdr->tag);
1305 return;
1308 if (fstat(f->fd, &sb) == -1)
1309 fatal("fstat");
1311 if (S_ISDIR(sb.st_mode)) {
1312 if ((f->d = fdopendir(f->fd)) == NULL) {
1313 np_errno(hdr->tag);
1314 close(f->fd);
1315 f->fd = -1;
1316 return;
1319 if ((f->evb = evbuffer_new()) == NULL) {
1320 np_errno(hdr->tag);
1321 closedir(f->d);
1322 f->d = NULL;
1323 f->fd = -1;
1327 f->offset = 0;
1329 qid_update_from_sb(&qid, &sb);
1330 np_create(hdr->tag, &qid, sb.st_blksize);
1332 return;
1334 err:
1335 client_send_listener(IMSG_CLOSE, NULL, 0);
1336 client_shutdown();
1339 static inline void
1340 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1342 struct qid qid;
1343 const char *uid, *gid, *muid;
1344 size_t tot;
1345 uint16_t namlen, uidlen, gidlen, ulen;
1347 qid_update_from_sb(&qid, sb);
1349 /* TODO: fill these fields */
1350 uid = "";
1351 gid = "";
1352 muid = "";
1354 namlen = strlen(fname);
1355 uidlen = strlen(uid);
1356 gidlen = strlen(gid);
1357 ulen = strlen(muid);
1359 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1360 if (tot > UINT32_MAX) {
1361 log_warnx("stat info for dir entry %s would overflow",
1362 fname);
1363 return;
1366 np_write16(evb, tot); /* size[2] */
1367 np_write16(evb, sb->st_rdev); /* type[2] */
1368 np_write32(evb, sb->st_dev); /* dev[4] */
1369 np_qid(evb, &qid); /* qid[13] */
1371 /* XXX: translate? */
1372 np_write32(evb, sb->st_mode); /* mode[4] */
1374 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1375 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1376 np_write64(evb, sb->st_size); /* length[8] */
1377 np_string(evb, namlen, fname); /* name[s] */
1378 np_string(evb, uidlen, uid); /* uid[s] */
1379 np_string(evb, gidlen, gid); /* gid[s] */
1380 np_string(evb, ulen, muid); /* muid[s] */
1383 static void
1384 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1386 struct fid *f;
1387 ssize_t r;
1388 size_t howmuch;
1389 uint64_t off;
1390 uint32_t fid, count;
1391 char buf[2048];
1393 /* fid[4] offset[8] count[4] */
1394 if (!NPREAD32("fid", &fid, &data, &len) ||
1395 !NPREAD64("offset", &off, &data, &len) ||
1396 !NPREAD32("count", &count, &data, &len)) {
1397 client_send_listener(IMSG_CLOSE, NULL, 0);
1398 client_shutdown();
1399 return;
1402 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1403 np_error(hdr->tag, "invalid fid");
1404 return;
1407 if (TYPE_OVERFLOW(off_t, off)) {
1408 log_warnx("unexpected off_t size");
1409 np_error(hdr->tag, "invalid offset");
1410 return;
1413 if (f->d == NULL) {
1414 /* read a file */
1415 howmuch = MIN(sizeof(buf), count);
1416 r = pread(f->fd, buf, howmuch, (off_t)off);
1417 if (r == -1)
1418 np_errno(hdr->tag);
1419 else
1420 np_read(hdr->tag, r, buf);
1421 } else {
1422 if (off == 0 && f->offset != 0) {
1423 rewinddir(f->d);
1424 f->offset = 0;
1425 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1428 if (off != f->offset) {
1429 np_error(hdr->tag, "can't seek in directories");
1430 return;
1433 while (EVBUFFER_LENGTH(f->evb) < count) {
1434 struct dirent *d;
1435 struct stat sb;
1437 if ((d = readdir(f->d)) == NULL)
1438 break;
1439 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1440 warn("fstatat");
1441 continue;
1443 serialize_stat(d->d_name, &sb, f->evb);
1446 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1447 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1448 evbuffer_drain(f->evb, count);
1450 f->offset += count;
1454 static void
1455 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1457 struct fid *f;
1458 ssize_t r;
1459 uint64_t off;
1460 uint32_t fid, count;
1462 /* fid[4] offset[8] count[4] data[count] */
1463 if (!NPREAD32("fid", &fid, &data, &len) ||
1464 !NPREAD64("off", &off, &data, &len) ||
1465 !NPREAD32("count", &count, &data, &len) ||
1466 len != count) {
1467 client_send_listener(IMSG_CLOSE, NULL, 0);
1468 client_shutdown();
1469 return;
1472 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1473 np_error(hdr->tag, "invalid fid");
1474 return;
1477 if (!(f->iomode & O_WRONLY) &&
1478 !(f->iomode & O_RDWR)) {
1479 np_error(hdr->tag, "fid not opened for writing");
1480 return;
1483 if (TYPE_OVERFLOW(off_t, off)) {
1484 log_warnx("unexpected off_t size");
1485 np_error(hdr->tag, "invalid offset");
1486 return;
1489 if ((r = pwrite(f->fd, data, len, off)) == -1)
1490 np_errno(hdr->tag);
1491 else
1492 np_write(hdr->tag, r);
1495 static void
1496 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1498 struct evbuffer *evb;
1499 struct stat sb;
1500 struct fid *f;
1501 int r;
1502 uint32_t fid;
1504 /* fid[4] */
1505 if (!NPREAD32("fid", &fid, &data, &len)) {
1506 client_send_listener(IMSG_CLOSE, NULL, 0);
1507 client_shutdown();
1508 return;
1512 * plan9' stat(9P) is not clear on whether the stat is allowed
1513 * on opened fids or not. We're allowing stat regardless of the
1514 * status of the fid.
1517 if ((f = fid_by_id(fid)) == NULL) {
1518 np_error(hdr->tag, "invalid fid");
1519 return;
1522 if ((evb = evbuffer_new()) == NULL)
1523 fatal("evbuffer_new");
1525 if (f->fd != -1)
1526 r = fstat(f->fd, &sb);
1527 else if (f->qid.type & QTDIR)
1528 r = fstat(f->dir->fd, &sb);
1529 else
1530 r = fstatat(f->dir->fd, f->fpath, &sb, 0);
1532 if (r == -1) {
1533 np_errno(hdr->tag);
1534 evbuffer_free(evb);
1535 return;
1538 serialize_stat(f->fpath, &sb, evb);
1539 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1540 evbuffer_free(evb);
1543 static void
1544 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1546 struct fid *f;
1547 uint32_t fid;
1548 int r;
1549 char dirpath[PATH_MAX + 3];
1551 /* fid[4] */
1552 if (!NPREAD32("fid", &fid, &data, &len)) {
1553 client_send_listener(IMSG_CLOSE, NULL, 0);
1554 client_shutdown();
1555 return;
1558 if ((f = fid_by_id(fid)) == NULL) {
1559 np_error(hdr->tag, "invalid fid");
1560 return;
1563 if (f->qid.type & QTDIR) { /* directory */
1564 strlcpy(dirpath, "../", sizeof(dirpath));
1565 strlcat(dirpath, f->fpath, sizeof(dirpath));
1566 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1567 } else /* file */
1568 r = unlinkat(f->dir->fd, f->fpath, 0);
1570 if (r == -1)
1571 np_errno(hdr->tag);
1572 else
1573 np_remove(hdr->tag);
1575 free_fid(f);
1578 static void
1579 handle_message(struct imsg *imsg, size_t len)
1581 struct msg {
1582 uint8_t type;
1583 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1584 } msgs[] = {
1585 {Tversion, tversion},
1586 {Tattach, tattach},
1587 {Tclunk, tclunk},
1588 {Tflush, tflush},
1589 {Twalk, twalk},
1590 {Topen, topen},
1591 {Tcreate, tcreate},
1592 {Tread, tread},
1593 {Twrite, twrite},
1594 {Tstat, tstat},
1595 {Tremove, tremove},
1597 struct np_msg_header hdr;
1598 size_t i;
1599 uint8_t *data;
1601 #if DEBUG_PACKETS
1602 hexdump("incoming packet", imsg->data, len);
1603 #endif
1605 parse_message(imsg->data, len, &hdr, &data);
1606 len -= HEADERSIZE;
1608 log_debug("got request: len=%d type=%d[%s] tag=%d",
1609 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1611 if (!handshaked && hdr.type != Tversion) {
1612 client_send_listener(IMSG_CLOSE, NULL, 0);
1613 client_shutdown();
1614 return;
1617 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1618 if (msgs[i].type != hdr.type)
1619 continue;
1621 msgs[i].fn(&hdr, data, len);
1622 return;
1625 np_error(hdr.tag, "Not supported.");