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/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 static void
254 client_dispatch_listener(int fd, short event, void *d)
256 static int auth = 0;
257 struct kd_auth_proc rauth;
258 struct imsg imsg;
259 struct imsgev *iev = d;
260 struct imsgbuf *ibuf;
261 ssize_t n;
262 int shut = 0;
264 ibuf = &iev->ibuf;
266 if (event & EV_READ) {
267 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
268 fatal("imsg_read error");
269 if (n == 0) /* Connection closed */
270 shut = 1;
272 if (event & EV_WRITE) {
273 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
274 fatal("msgbuf_write");
275 if (n == 0) /* Connection closed */
276 shut = 1;
279 for (;;) {
280 if ((n = imsg_get(ibuf, &imsg)) == -1)
281 fatal("%s: imsg_get error", __func__);
282 if (n == 0) /* No more messages. */
283 break;
285 switch (imsg.hdr.type) {
286 case IMSG_AUTH:
287 peerid = imsg.hdr.peerid;
288 if (auth)
289 fatalx("%s: IMSG_AUTH already done", __func__);
290 auth = 1;
292 if (IMSG_DATA_SIZE(imsg) != sizeof(rauth))
293 fatalx("mismatching size for IMSG_AUTH");
294 memcpy(&rauth, imsg.data, sizeof(rauth));
295 if (rauth.uname[sizeof(rauth.uname)-1] != '\0' ||
296 rauth.dir[sizeof(rauth.dir)-1] != '\0')
297 fatalx("IMSG_AUTH strings not NUL-terminated");
299 client_privdrop(rauth.uname, rauth.dir);
300 explicit_bzero(&rauth, sizeof(rauth));
301 break;
302 case IMSG_BUF:
303 if (!auth)
304 fatalx("%s: can't handle messages before"
305 " doing the auth", __func__);
306 handle_message(&imsg, IMSG_DATA_SIZE(imsg));
307 break;
308 case IMSG_CONN_GONE:
309 log_debug("closing");
310 shut = 1;
311 break;
312 default:
313 log_debug("%s: unexpected imsg %d",
314 __func__, imsg.hdr.type);
315 break;
317 imsg_free(&imsg);
320 if (!shut)
321 imsg_event_add(iev);
322 else {
323 /* This pipe is dead. Remove its event handler. */
324 event_del(&iev->ev);
325 log_debug("pipe closed, shutting down...");
326 event_loopexit(NULL);
330 static void
331 client_privdrop(const char *username, const char *dir)
333 struct passwd *pw;
335 setproctitle("client %s", username);
337 if ((pw = getpwnam(username)) == NULL)
338 fatalx("getpwnam(%s) failed", username);
340 if (chroot(dir) == -1)
341 fatal("chroot");
342 if (chdir("/") == -1)
343 fatal("chdir(\"/\")");
345 if (setgroups(1, &pw->pw_gid) ||
346 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
347 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
348 fatal("can't drop privileges");
350 sandbox_client();
351 log_debug("client ready; user=%s dir=%s", username, dir);
353 if ((evb = evbuffer_new()) == NULL)
354 fatal("evbuffer_new");
357 static int
358 client_send_listener(int type, const void *data, uint16_t len)
360 int ret;
362 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
363 data, len)) != -1)
364 imsg_event_add(iev_listener);
366 return ret;
369 /* set qid fields from sb */
370 static void
371 qid_update_from_sb(struct qid *qid, struct stat *sb)
373 qid->path = sb->st_ino;
375 /*
376 * Theoretically (and hopefully!) this should be a 64 bit
377 * number. Unfortunately, 9P uses 32 bit timestamps.
378 */
379 qid->vers = sb->st_mtim.tv_sec;
381 if (S_ISREG(sb->st_mode))
382 qid->type = QTFILE;
383 else if (S_ISDIR(sb->st_mode))
384 qid->type = QTDIR;
385 else if (S_ISLNK(sb->st_mode))
386 qid->type = QTSYMLINK;
389 /* creates a qid given a fd */
390 static struct dir *
391 new_dir(int fd)
393 struct dir *dir;
395 if ((dir = calloc(1, sizeof(*dir))) == NULL)
396 return NULL;
398 dir->fd = fd;
399 STAILQ_INSERT_HEAD(&dirs, dir, entries);
400 return dir;
403 static struct dir *
404 dir_incref(struct dir *dir)
406 dir->refcount++;
407 return dir;
410 static void
411 dir_decref(struct dir *dir)
413 if (--dir->refcount > 0)
414 return;
416 STAILQ_REMOVE(&dirs, dir, dir, entries);
418 close(dir->fd);
419 free(dir);
422 static struct fid *
423 new_fid(struct dir *dir, uint32_t fid, const char *path, struct qid *qid)
425 struct fid *f;
426 struct qid q;
427 struct stat sb;
429 if (qid == NULL) {
430 if (fstatat(dir->fd, path, &sb, 0)) {
431 log_warn("fstatat(%s)", path);
432 return NULL;
434 qid_update_from_sb(&q, &sb);
435 qid = &q;
438 if ((f = calloc(1, sizeof(*f))) == NULL)
439 return NULL;
441 f->dir = dir_incref(dir);
442 f->fid = fid;
443 f->fd = -1;
445 strlcpy(f->fpath, path, sizeof(f->fpath));
447 memcpy(&f->qid, qid, sizeof(f->qid));
449 STAILQ_INSERT_HEAD(&fids, f, entries);
451 return f;
454 static struct fid *
455 fid_by_id(uint32_t fid)
457 struct fid *f;
459 STAILQ_FOREACH(f, &fids, entries) {
460 if (f->fid == fid)
461 return f;
464 return NULL;
467 static void
468 free_fid(struct fid *f)
470 int r;
472 if (f->fd != -1) {
473 if (f->d != NULL)
474 r = closedir(f->d);
475 else
476 r = close(f->fd);
478 if (r == -1)
479 fatal("can't close fid %d", f->fid);
481 if (f->evb != NULL)
482 evbuffer_free(f->evb);
484 /* try to honour ORCLOSE if requested */
485 if (f->iomode & O_CLOEXEC)
486 unlinkat(f->dir->fd, f->fpath, 0);
489 dir_decref(f->dir);
491 STAILQ_REMOVE(&fids, f, fid, entries);
492 free(f);
495 static void
496 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
497 uint8_t **cnt)
499 size_t olen = len;
501 if (!NPREAD32("len", &hdr->len, &data, &len) ||
502 !NPREAD8("type", &hdr->type, &data, &len) ||
503 !NPREAD16("tag", &hdr->tag, &data, &len))
504 goto err;
506 if (olen != hdr->len)
507 goto err;
509 if (hdr->type < Tversion ||
510 hdr->type >= Tmax ||
511 hdr->type == Terror ||
512 (hdr->type & 0x1) != 0) /* cannot recv a R* */
513 goto err;
515 hdr->tag = le32toh(hdr->tag);
517 *cnt = (uint8_t *)data;
518 return;
520 err:
521 /* TODO: send a proper message to terminate the connection. */
522 fatalx("got invalid message");
525 static void
526 np_write16(struct evbuffer *e, uint16_t x)
528 x = htole16(x);
529 evbuffer_add(e, &x, sizeof(x));
532 static void
533 np_write32(struct evbuffer *e, uint32_t x)
535 x = htole32(x);
536 evbuffer_add(e, &x, sizeof(x));
539 static void
540 np_write64(struct evbuffer *e, uint64_t x)
542 x = htole64(x);
543 evbuffer_add(e, &x, sizeof(x));
546 static void
547 np_writebuf(struct evbuffer *e, size_t len, void *data)
549 evbuffer_add(e, data, len);
552 static void
553 np_header(uint32_t len, uint8_t type, uint16_t tag)
555 len += HEADERSIZE;
557 len = htole32(len);
558 tag = htole16(tag);
560 evbuffer_add(evb, &len, sizeof(len));
561 evbuffer_add(evb, &type, sizeof(type));
562 evbuffer_add(evb, &tag, sizeof(tag));
565 static void
566 np_string(struct evbuffer *e, uint16_t len, const char *str)
568 uint16_t l = len;
570 len = htole16(len);
571 evbuffer_add(e, &len, sizeof(len));
572 evbuffer_add(e, str, l);
575 static void
576 np_qid(struct evbuffer *e, struct qid *qid)
578 uint64_t path;
579 uint32_t vers;
581 path = htole64(qid->path);
582 vers = htole32(qid->vers);
584 evbuffer_add(e, &qid->type, sizeof(qid->type));
585 evbuffer_add(e, &vers, sizeof(vers));
586 evbuffer_add(e, &path, sizeof(path));
589 static void
590 do_send(void)
592 size_t len;
593 void *data;
595 len = EVBUFFER_LENGTH(evb);
596 data = EVBUFFER_DATA(evb);
598 #if DEBUG_PACKETS
599 hexdump("outgoing packet", data, len);
600 #endif
601 client_send_listener(IMSG_BUF, data, len);
602 evbuffer_drain(evb, len);
605 static void
606 np_version(uint16_t tag, uint32_t msize, const char *version)
608 uint16_t l;
610 l = strlen(version);
612 msize = htole32(msize);
614 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
615 evbuffer_add(evb, &msize, sizeof(msize));
616 np_string(evb, l, version);
617 do_send();
620 static void
621 np_attach(uint16_t tag, struct qid *qid)
623 np_header(QIDSIZE, Rattach, tag);
624 np_qid(evb, qid);
625 do_send();
628 static void
629 np_clunk(uint16_t tag)
631 np_header(0, Rclunk, tag);
632 do_send();
635 static void
636 np_flush(uint16_t tag)
638 np_header(0, Rflush, tag);
639 do_send();
642 static void
643 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
645 int i;
647 /* two bytes for the counter */
648 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
649 np_write16(evb, nwqid);
650 for (i = 0; i < nwqid; ++i)
651 np_qid(evb, wqid + i);
653 do_send();
656 static void
657 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
659 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
660 np_qid(evb, qid);
661 np_write32(evb, iounit);
662 do_send();
665 static void
666 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
668 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
669 np_qid(evb, qid);
670 np_write32(evb, iounit);
671 do_send();
674 static void
675 np_read(uint16_t tag, uint32_t count, void *data)
677 if (sizeof(count) + count + HEADERSIZE >= msize) {
678 np_error(tag, "Rread would overflow");
679 return;
682 np_header(sizeof(count) + count, Rread, tag);
683 np_write32(evb, count);
684 np_writebuf(evb, count, data);
685 do_send();
688 static void
689 np_write(uint16_t tag, uint32_t count)
691 np_header(sizeof(count), Rwrite, tag);
692 np_write32(evb, count);
693 do_send();
696 static void
697 np_stat(uint16_t tag, uint32_t count, void *data)
699 if (sizeof(count) + count + HEADERSIZE >= msize) {
700 np_error(tag, "Rstat would overflow");
701 return;
704 np_header(count, Rstat, tag);
705 np_writebuf(evb, count, data);
706 do_send();
709 static void
710 np_remove(uint16_t tag)
712 np_header(0, Rremove, tag);
713 do_send();
716 static void
717 np_error(uint16_t tag, const char *errstr)
719 uint16_t l;
721 l = strlen(errstr);
723 np_header(sizeof(l) + l, Rerror, tag);
724 np_string(evb, l, errstr);
725 do_send();
728 static void
729 np_errno(uint16_t tag)
731 int saved_errno;
732 char buf[NL_TEXTMAX] = {0};
734 saved_errno = errno;
736 strerror_r(errno, buf, sizeof(buf));
737 np_error(tag, buf);
739 errno = saved_errno;
742 static int
743 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
744 size_t *len)
746 if (*len < sizeof(*dst)) {
747 log_warnx("%s: wanted %zu bytes for the %s field but only "
748 "%zu are available.", t, sizeof(*dst), f, *len);
749 return -1;
752 memcpy(dst, *src, sizeof(*dst));
753 *src += sizeof(*dst);
754 *len -= sizeof(*dst);
756 return 1;
759 static int
760 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
761 size_t *len)
763 if (*len < sizeof(*dst)) {
764 log_warnx("%s: wanted %zu bytes for the %s field but only "
765 "%zu are available.", t, sizeof(*dst), f, *len);
766 return -1;
769 memcpy(dst, *src, sizeof(*dst));
770 *src += sizeof(*dst);
771 *len -= sizeof(*dst);
772 *dst = le16toh(*dst);
774 return 1;
777 static int
778 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
779 size_t *len)
781 if (*len < sizeof(*dst)) {
782 log_warnx("%s: wanted %zu bytes for the %s field but only "
783 "%zu are available.", t, sizeof(*dst), f, *len);
784 return -1;
787 memcpy(dst, *src, sizeof(*dst));
788 *src += sizeof(*dst);
789 *len -= sizeof(*dst);
790 *dst = le32toh(*dst);
792 return 1;
795 static int
796 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
797 size_t *len)
799 if (*len < sizeof(*dst)) {
800 log_warnx("%s: wanted %zu bytes for the %s field but only "
801 "%zu are available.", t, sizeof(*dst), f, *len);
802 return -1;
805 memcpy(dst, *src, sizeof(*dst));
806 *src += sizeof(*dst);
807 *len -= sizeof(*dst);
808 *dst = le64toh(*dst);
810 return 1;
813 static int
814 np_readstr(const char *t, const char *f, char *res, size_t reslen,
815 const uint8_t **src, size_t *len)
817 uint16_t sl;
818 char buf[32];
820 strlcpy(buf, f, sizeof(buf));
821 strlcat(buf, "-len", sizeof(buf));
823 if (!np_read16(t, buf, &sl, src, len))
824 return READSTRERR;
826 if (*len < sl) {
827 log_warnx("%s: wanted %d bytes for the %s field but only "
828 "%zu are available.", t, sl, f, *len);
829 return READSTRERR;
832 if (*len > reslen-1)
833 return READSTRTRUNC;
835 memcpy(res, *src, sl);
836 res[sl] = '\0';
837 *src += sl;
838 *len -= sl;
840 return 0;
843 static void
844 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
846 char *dot, version[32];
848 if (handshaked)
849 goto err;
851 /* msize[4] version[s] */
852 if (!NPREAD32("msize", &msize, &data, &len))
853 goto err;
855 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
856 case READSTRERR:
857 goto err;
858 case READSTRTRUNC:
859 log_warnx("9P version string too long, truncated");
860 goto mismatch;
863 if ((dot = strchr(version, '.')) != NULL)
864 *dot = '\0';
866 if (strcmp(version, VERSION9P) != 0 ||
867 msize == 0)
868 goto mismatch;
870 /* version matched */
871 handshaked = 1;
872 msize = MIN(msize, CLIENT_MSIZE);
873 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
874 np_version(hdr->tag, msize, VERSION9P);
875 return;
877 mismatch:
878 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
879 version);
880 np_version(hdr->tag, MSIZE9P, "unknown");
881 return;
883 err:
884 client_send_listener(IMSG_CLOSE, NULL, 0);
885 client_shutdown();
888 static void
889 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
891 struct dir *dir;
892 struct fid *f;
893 uint32_t fid, afid;
894 int fd;
895 char aname[PATH_MAX];
897 /* fid[4] afid[4] uname[s] aname[s] */
899 if (!NPREAD32("fid", &fid, &data, &len) ||
900 !NPREAD32("afid", &afid, &data, &len))
901 goto err;
903 /* read the uname but don't actually use it */
904 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
905 case READSTRERR:
906 goto err;
907 case READSTRTRUNC:
908 np_error(hdr->tag, "name too long");
909 return;
912 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
913 case READSTRERR:
914 goto err;
915 case READSTRTRUNC:
916 np_error(hdr->tag, "name too long");
917 return;
920 if (fid_by_id(fid) != NULL || afid != NOFID) {
921 np_error(hdr->tag, "invalid fid or afid");
922 return;
925 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
926 goto fail;
928 if ((dir = new_dir(fd)) == NULL)
929 goto fail;
931 log_debug("attached %s to %d", aname, fid);
933 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
934 dir_decref(dir);
935 goto fail;
938 np_attach(hdr->tag, &f->qid);
939 return;
941 fail:
942 np_errno(hdr->tag);
943 log_warn("failed to attach %s", aname);
944 return;
946 err:
947 client_send_listener(IMSG_CLOSE, NULL, 0);
948 client_shutdown();
951 static void
952 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
954 struct fid *f;
955 uint32_t fid;
957 /* fid[4] */
958 if (!NPREAD32("fid", &fid, &data, &len)) {
959 client_send_listener(IMSG_CLOSE, NULL, 0);
960 client_shutdown();
961 return;
964 if ((f = fid_by_id(fid)) == NULL) {
965 np_error(hdr->tag, "invalid fid");
966 return;
969 free_fid(f);
970 np_clunk(hdr->tag);
973 static void
974 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
976 uint16_t oldtag;
978 /*
979 * We're doing only synchronous I/O. Tflush is implemented
980 * only because it's illegal to reply with a Rerror.
981 */
983 /* oldtag[2] */
984 if (len != sizeof(oldtag)) {
985 log_warnx("Tflush with the wrong size: got %zu want %zu",
986 len, sizeof(oldtag));
987 client_send_listener(IMSG_CLOSE, NULL, 0);
988 client_shutdown();
989 return;
992 np_flush(hdr->tag);
995 static void
996 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
998 struct stat sb;
999 struct dir *dir;
1000 struct qid wqid[MAXWELEM] = {0};
1001 struct fid *f, *nf;
1002 uint32_t fid, newfid;
1003 uint16_t nwname;
1004 int fd, oldfd, no, nwqid = 0;
1005 char wnam[PATH_MAX];
1007 if (!NPREAD32("fid", &fid, &data, &len) ||
1008 !NPREAD32("newfid", &newfid, &data, &len) ||
1009 !NPREAD16("nwname", &nwname, &data, &len))
1010 goto err;
1012 if (nwname > MAXWELEM) {
1013 log_warnx("Twalk: more than %d path elements: %d",
1014 MAXWELEM, nwname);
1015 goto err;
1018 if ((f = fid_by_id(fid)) == NULL) {
1019 np_error(hdr->tag, "invalid fid");
1020 return;
1023 if (f->fd != -1) {
1024 np_error(hdr->tag, "fid already opened for I/O");
1025 return;
1028 if (fid == newfid)
1029 nf = f;
1030 else if ((nf = fid_by_id(newfid)) != NULL) {
1031 np_error(hdr->tag, "newfid already in use");
1032 return;
1033 } else
1034 nf = NULL;
1036 /* special case: fid duplication */
1037 if (nwname == 0) {
1039 * TODO: should we forbid fids duplication when fid ==
1040 * newfid?
1042 if (nf == NULL &&
1043 (nf = new_fid(f->dir, newfid, f->fpath, &f->qid)) == NULL)
1044 fatal("new_fid duplication");
1046 np_walk(hdr->tag, 0, NULL);
1047 return;
1050 if (!(f->qid.type & QTDIR)) {
1051 np_error(hdr->tag, "fid doesn't represent a directory");
1052 return;
1055 oldfd = f->dir->fd;
1057 for (nwqid = 0; nwqid < nwname; nwqid++) {
1058 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1059 case READSTRERR:
1060 goto err;
1061 case READSTRTRUNC:
1062 np_error(hdr->tag, "wname too long");
1063 return;
1066 if (*wnam == '\0' ||
1067 strchr(wnam, '/') != NULL ||
1068 !strcmp(wnam, ".")) {
1069 errno = EINVAL;
1070 goto cantopen;
1073 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1074 errno != ENOTDIR)
1075 goto cantopen;
1077 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1078 (fd != -1 && fstat(fd, &sb) == -1))
1079 goto cantopen;
1081 qid_update_from_sb(&wqid[nwqid], &sb);
1083 /* reached a file but we still have other components */
1084 if (fd == -1 && nwqid+1 < nwname)
1085 goto cantopen;
1087 /* reached the end and found a file */
1088 if (fd == -1 && nwqid+1 == nwname)
1089 continue;
1091 if (oldfd != f->dir->fd)
1092 close(oldfd);
1093 oldfd = fd;
1097 * If fd is -1 we've reached a file, otherwise we've just
1098 * reached another directory. We must pay attention to what
1099 * file descriptor we use to create the dir, because if we've
1100 * reached a file and oldfd is f->dir->fd then we *must* share
1101 * the same dir (it was a walk of one path from a directory to a
1102 * file, otherwise fun is bound to happen as soon as the client
1103 * closes the fid for the directory but keeps the one for the
1104 * file.
1106 if (fd == -1 && oldfd == f->dir->fd)
1107 dir = f->dir;
1108 else if (fd == -1)
1109 dir = new_dir(oldfd);
1110 else
1111 dir = new_dir(fd);
1113 if (dir == NULL)
1114 fatal("new_dir");
1116 if (nf == NULL) {
1117 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1118 fatal("new fid");
1119 } else {
1120 /* update the dir */
1121 dir_decref(nf->dir);
1122 nf->dir = dir_incref(dir);
1125 np_walk(hdr->tag, nwqid, wqid);
1126 return;
1128 cantopen:
1129 if (oldfd != f->dir->fd)
1130 close(oldfd);
1131 no = errno;
1132 if (nwqid == 0)
1133 np_error(hdr->tag, strerror(no));
1134 else
1135 np_walk(hdr->tag, nwqid, wqid);
1136 return;
1138 err:
1139 client_send_listener(IMSG_CLOSE, NULL, 0);
1140 client_shutdown();
1143 static inline int
1144 npmode_to_unix(uint8_t mode, int *flags)
1146 switch (mode & 0x0F) {
1147 case KOREAD:
1148 *flags = O_RDONLY;
1149 break;
1150 case KOWRITE:
1151 *flags = O_WRONLY;
1152 break;
1153 case KORDWR:
1154 *flags = O_RDWR;
1155 break;
1156 case KOEXEC:
1157 log_warnx("tried to open something with KOEXEC");
1158 /* fallthrough */
1159 default:
1160 return -1;
1163 if (mode & KOTRUNC)
1164 *flags |= O_TRUNC;
1165 if (mode & KORCLOSE)
1166 *flags |= O_CLOEXEC;
1168 return 0;
1171 static void
1172 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1174 struct stat sb;
1175 struct qid qid;
1176 struct fid *f;
1177 uint32_t fid;
1178 uint8_t mode;
1179 const char *path;
1181 /* fid[4] mode[1] */
1182 if (!NPREAD32("fid", &fid, &data, &len) ||
1183 !NPREAD8("mode", &mode, &data, &len)) {
1184 client_send_listener(IMSG_CLOSE, NULL, 0);
1185 client_shutdown();
1186 return;
1189 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1190 np_error(hdr->tag, "invalid fid");
1191 return;
1194 if (npmode_to_unix(mode, &f->iomode) == -1) {
1195 np_error(hdr->tag, "invalid mode");
1196 return;
1199 path = f->fpath;
1200 if (f->qid.type & QTDIR)
1201 path = ".";
1203 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1204 np_error(hdr->tag, strerror(errno));
1205 return;
1208 if (fstat(f->fd, &sb) == -1)
1209 fatal("fstat");
1211 if (S_ISDIR(sb.st_mode)) {
1212 if ((f->d = fdopendir(f->fd)) == NULL) {
1213 np_errno(hdr->tag);
1214 close(f->fd);
1215 f->fd = -1;
1216 return;
1219 if ((f->evb = evbuffer_new()) == NULL) {
1220 np_errno(hdr->tag);
1221 closedir(f->d);
1222 f->d = NULL;
1223 f->fd = -1;
1227 f->offset = 0;
1229 qid_update_from_sb(&qid, &sb);
1230 np_open(hdr->tag, &qid, sb.st_blksize);
1233 static void
1234 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1236 struct stat sb;
1237 struct qid qid;
1238 struct fid *f;
1239 uint32_t fid, perm;
1240 uint8_t mode;
1241 char name[PATH_MAX];
1243 /* fid[4] name[s] perm[4] mode[1] */
1244 if (!NPREAD32("fid", &fid, &data, &len))
1245 goto err;
1246 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1247 case READSTRERR:
1248 goto err;
1249 case READSTRTRUNC:
1250 np_error(hdr->tag, "name too long");
1251 return;
1253 if (!NPREAD32("perm", &perm, &data, &len) ||
1254 !NPREAD8("mode", &mode, &data, &len))
1255 goto err;
1257 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1258 strchr(name, '/') != NULL) {
1259 np_error(hdr->tag, "invalid name");
1260 return;
1263 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1264 np_error(hdr->tag, "invalid fid");
1265 return;
1268 if (!(f->qid.type & QTDIR)) {
1269 np_error(hdr->tag, "fid doesn't identify a directory");
1270 return;
1273 if (npmode_to_unix(mode, &f->iomode) == -1) {
1274 np_error(hdr->tag, "invalid mode");
1275 return;
1278 if (f->iomode & O_RDONLY) {
1279 np_error(hdr->tag, "can't create a read-only file");
1280 return;
1283 /* TODO: parse the mode */
1285 if (perm & 0x80000000) {
1286 /* create a directory */
1287 f->fd = mkdirat(f->dir->fd, name, 0755);
1288 } else {
1289 /* create a file */
1290 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1291 0644);
1294 if (f->fd == -1) {
1295 np_errno(hdr->tag);
1296 return;
1299 if (fstat(f->fd, &sb) == -1)
1300 fatal("fstat");
1302 if (S_ISDIR(sb.st_mode)) {
1303 if ((f->d = fdopendir(f->fd)) == NULL) {
1304 np_errno(hdr->tag);
1305 close(f->fd);
1306 f->fd = -1;
1307 return;
1310 if ((f->evb = evbuffer_new()) == NULL) {
1311 np_errno(hdr->tag);
1312 closedir(f->d);
1313 f->d = NULL;
1314 f->fd = -1;
1318 f->offset = 0;
1320 qid_update_from_sb(&qid, &sb);
1321 np_create(hdr->tag, &qid, sb.st_blksize);
1323 return;
1325 err:
1326 client_send_listener(IMSG_CLOSE, NULL, 0);
1327 client_shutdown();
1330 static inline void
1331 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1333 struct qid qid;
1334 const char *uid, *gid, *muid;
1335 size_t tot;
1336 uint16_t namlen, uidlen, gidlen, ulen;
1338 qid_update_from_sb(&qid, sb);
1340 /* TODO: fill these fields */
1341 uid = "";
1342 gid = "";
1343 muid = "";
1345 namlen = strlen(fname);
1346 uidlen = strlen(uid);
1347 gidlen = strlen(gid);
1348 ulen = strlen(muid);
1350 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1351 if (tot > UINT32_MAX) {
1352 log_warnx("stat info for dir entry %s would overflow",
1353 fname);
1354 return;
1357 np_write16(evb, tot); /* size[2] */
1358 np_write16(evb, sb->st_rdev); /* type[2] */
1359 np_write32(evb, sb->st_dev); /* dev[4] */
1360 np_qid(evb, &qid); /* qid[13] */
1362 /* XXX: translate? */
1363 np_write32(evb, sb->st_mode); /* mode[4] */
1365 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1366 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1367 np_write64(evb, sb->st_size); /* length[8] */
1368 np_string(evb, namlen, fname); /* name[s] */
1369 np_string(evb, uidlen, uid); /* uid[s] */
1370 np_string(evb, gidlen, gid); /* gid[s] */
1371 np_string(evb, ulen, muid); /* muid[s] */
1374 static void
1375 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1377 struct fid *f;
1378 ssize_t r;
1379 size_t howmuch;
1380 uint64_t off;
1381 uint32_t fid, count;
1382 char buf[2048];
1384 /* fid[4] offset[8] count[4] */
1385 if (!NPREAD32("fid", &fid, &data, &len) ||
1386 !NPREAD64("offset", &off, &data, &len) ||
1387 !NPREAD32("count", &count, &data, &len)) {
1388 client_send_listener(IMSG_CLOSE, NULL, 0);
1389 client_shutdown();
1390 return;
1393 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1394 np_error(hdr->tag, "invalid fid");
1395 return;
1398 if (TYPE_OVERFLOW(off_t, off)) {
1399 log_warnx("unexpected off_t size");
1400 np_error(hdr->tag, "invalid offset");
1401 return;
1404 if (f->d == NULL) {
1405 /* read a file */
1406 howmuch = MIN(sizeof(buf), count);
1407 r = pread(f->fd, buf, howmuch, (off_t)off);
1408 if (r == -1)
1409 np_errno(hdr->tag);
1410 else
1411 np_read(hdr->tag, r, buf);
1412 } else {
1413 if (off == 0 && f->offset != 0) {
1414 rewinddir(f->d);
1415 f->offset = 0;
1416 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1419 if (off != f->offset) {
1420 np_error(hdr->tag, "can't seek in directories");
1421 return;
1424 while (EVBUFFER_LENGTH(f->evb) < count) {
1425 struct dirent *d;
1426 struct stat sb;
1428 if ((d = readdir(f->d)) == NULL)
1429 break;
1430 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1431 warn("fstatat");
1432 continue;
1434 serialize_stat(d->d_name, &sb, f->evb);
1437 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1438 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1439 evbuffer_drain(f->evb, count);
1441 f->offset += count;
1445 static void
1446 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1448 struct fid *f;
1449 ssize_t r;
1450 uint64_t off;
1451 uint32_t fid, count;
1453 /* fid[4] offset[8] count[4] data[count] */
1454 if (!NPREAD32("fid", &fid, &data, &len) ||
1455 !NPREAD64("off", &off, &data, &len) ||
1456 !NPREAD32("count", &count, &data, &len) ||
1457 len != count) {
1458 client_send_listener(IMSG_CLOSE, NULL, 0);
1459 client_shutdown();
1460 return;
1463 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1464 np_error(hdr->tag, "invalid fid");
1465 return;
1468 if (!(f->iomode & O_WRONLY) &&
1469 !(f->iomode & O_RDWR)) {
1470 np_error(hdr->tag, "fid not opened for writing");
1471 return;
1474 if (TYPE_OVERFLOW(off_t, off)) {
1475 log_warnx("unexpected off_t size");
1476 np_error(hdr->tag, "invalid offset");
1477 return;
1480 if ((r = pwrite(f->fd, data, len, off)) == -1)
1481 np_errno(hdr->tag);
1482 else
1483 np_write(hdr->tag, r);
1486 static void
1487 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1489 struct evbuffer *evb;
1490 struct stat sb;
1491 struct fid *f;
1492 int r;
1493 uint32_t fid;
1495 /* fid[4] */
1496 if (!NPREAD32("fid", &fid, &data, &len)) {
1497 client_send_listener(IMSG_CLOSE, NULL, 0);
1498 client_shutdown();
1499 return;
1503 * plan9' stat(9P) is not clear on whether the stat is allowed
1504 * on opened fids or not. We're allowing stat regardless of the
1505 * status of the fid.
1508 if ((f = fid_by_id(fid)) == NULL) {
1509 np_error(hdr->tag, "invalid fid");
1510 return;
1513 if ((evb = evbuffer_new()) == NULL)
1514 fatal("evbuffer_new");
1516 if (f->fd != -1)
1517 r = fstat(f->fd, &sb);
1518 else if (f->qid.type & QTDIR)
1519 r = fstat(f->dir->fd, &sb);
1520 else
1521 r = fstatat(f->dir->fd, f->fpath, &sb, 0);
1523 if (r == -1) {
1524 np_errno(hdr->tag);
1525 evbuffer_free(evb);
1526 return;
1529 serialize_stat(f->fpath, &sb, evb);
1530 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1531 evbuffer_free(evb);
1534 static void
1535 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1537 struct fid *f;
1538 uint32_t fid;
1539 int r;
1540 char dirpath[PATH_MAX + 3];
1542 /* fid[4] */
1543 if (!NPREAD32("fid", &fid, &data, &len)) {
1544 client_send_listener(IMSG_CLOSE, NULL, 0);
1545 client_shutdown();
1546 return;
1549 if ((f = fid_by_id(fid)) == NULL) {
1550 np_error(hdr->tag, "invalid fid");
1551 return;
1554 if (f->qid.type & QTDIR) { /* directory */
1555 strlcpy(dirpath, "../", sizeof(dirpath));
1556 strlcat(dirpath, f->fpath, sizeof(dirpath));
1557 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1558 } else /* file */
1559 r = unlinkat(f->dir->fd, f->fpath, 0);
1561 if (r == -1)
1562 np_errno(hdr->tag);
1563 else
1564 np_remove(hdr->tag);
1566 free_fid(f);
1569 static void
1570 handle_message(struct imsg *imsg, size_t len)
1572 struct msg {
1573 uint8_t type;
1574 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1575 } msgs[] = {
1576 {Tversion, tversion},
1577 {Tattach, tattach},
1578 {Tclunk, tclunk},
1579 {Tflush, tflush},
1580 {Twalk, twalk},
1581 {Topen, topen},
1582 {Tcreate, tcreate},
1583 {Tread, tread},
1584 {Twrite, twrite},
1585 {Tstat, tstat},
1586 {Tremove, tremove},
1588 struct np_msg_header hdr;
1589 size_t i;
1590 uint8_t *data;
1592 #if DEBUG_PACKETS
1593 hexdump("incoming packet", imsg->data, len);
1594 #endif
1596 parse_message(imsg->data, len, &hdr, &data);
1597 len -= HEADERSIZE;
1599 log_debug("got request: len=%d type=%d[%s] tag=%d",
1600 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1602 if (!handshaked && hdr.type != Tversion) {
1603 client_send_listener(IMSG_CLOSE, NULL, 0);
1604 client_shutdown();
1605 return;
1608 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1609 if (msgs[i].type != hdr.type)
1610 continue;
1612 msgs[i].fn(&hdr, data, len);
1613 return;
1616 np_error(hdr.tag, "Not supported.");