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 <sys/stat.h>
18 #include <sys/types.h>
19 #include <sys/queue.h>
20 #include <sys/uio.h>
22 #include <dirent.h>
23 #include <endian.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <event.h>
27 #include <fcntl.h>
28 #include <pwd.h>
29 #include <signal.h>
30 #include <stdint.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <syslog.h>
34 #include <unistd.h>
35 #include <imsg.h>
37 #include "client.h"
38 #include "kami.h"
39 #include "kamid.h"
40 #include "log.h"
41 #include "sandbox.h"
42 #include "utils.h"
44 /*
45 * XXX: atm is difficult to accept messages bigger than MAX_IMSGSIZE
46 * minus IMSG_HEADER_SIZE, we need something to split messages into
47 * chunks and receive them one by the other.
48 *
49 * CLIENT_MSIZE is thus the maximum message size we can handle now.
50 */
51 #define CLIENT_MSIZE (MAX_IMSGSIZE - IMSG_HEADER_SIZE)
53 #define DEBUG_PACKETS 0
55 /* straight outta /src/usr.bin/ssh/scp.c */
56 #define TYPE_OVERFLOW(type, val) \
57 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
58 (sizeof(type) == 8 && (val) > INT64_MAX) || \
59 (sizeof(type) != 4 && sizeof(type) != 8))
61 STAILQ_HEAD(dirhead, dir) dirs;
62 struct dir {
63 int refcount;
64 int fd;
65 STAILQ_ENTRY(dir) entries;
66 };
68 STAILQ_HEAD(fidhead, fid) fids;
69 struct fid {
70 uint32_t fid;
72 char fpath[PATH_MAX];
74 /*
75 * the flags passed to open(2). O_CLOEXEC means ORCLOSE, that
76 * is to unlink the file upon Tclunk.
77 */
78 int iomode;
80 /*
81 * if fd is not -1 this fid was opened, fd represents its
82 * file descriptor and iomode the flags passed to open(2).
83 */
84 int fd;
85 DIR *d;
86 struct evbuffer *evb;
88 /*
89 * expected offset for Tread against a directory.
90 */
91 uint64_t offset;
93 struct qid qid;
94 struct dir *dir;
95 STAILQ_ENTRY(fid) entries;
96 };
98 static struct imsgev *iev_listener;
99 static struct evbuffer *evb;
100 static uint32_t peerid;
102 static int handshaked;
103 uint32_t msize;
105 static __dead void client_shutdown(void);
106 static void client_sig_handler(int, short, void *);
107 static void client_dispatch_listener(int, short, void *);
108 static void client_privdrop(const char *, const char *);
110 static int client_send_listener(int, const void *, uint16_t);
112 static void qid_update_from_sb(struct qid *, struct stat *);
114 static struct dir *new_dir(int);
115 static struct dir *dir_incref(struct dir *);
116 static void dir_decref(struct dir *);
118 static struct fid *new_fid(struct dir *, uint32_t, const char *, struct qid *);
119 static struct fid *fid_by_id(uint32_t);
120 static void free_fid(struct fid *);
122 static void parse_message(const uint8_t *, size_t,
123 struct np_msg_header *, uint8_t **);
125 static void np_write16(struct evbuffer *, uint16_t);
126 static void np_write32(struct evbuffer *, uint32_t);
127 static void np_write64(struct evbuffer *, uint64_t);
128 static void np_header(uint32_t, uint8_t, uint16_t);
129 static void np_string(struct evbuffer *, uint16_t, const char *);
130 static void np_qid(struct evbuffer *, struct qid *);
131 static void do_send(void);
133 static void np_version(uint16_t, uint32_t, const char *);
134 static void np_attach(uint16_t, struct qid *);
135 static void np_clunk(uint16_t);
136 static void np_flush(uint16_t);
137 static void np_walk(uint16_t, int, struct qid *);
138 static void np_open(uint16_t, struct qid *, uint32_t);
139 static void np_create(uint16_t, struct qid *, uint32_t);
140 static void np_read(uint16_t, uint32_t, void *);
141 static void np_write(uint16_t, uint32_t);
142 static void np_stat(uint16_t, uint32_t, void *);
143 static void np_remove(uint16_t);
144 static void np_error(uint16_t, const char *);
145 static void np_errno(uint16_t);
147 static int np_read8(const char *, const char *, uint8_t *,
148 const uint8_t **, size_t *);
149 static int np_read16(const char *, const char *, uint16_t *,
150 const uint8_t **, size_t *);
151 static int np_read32(const char *, const char *, uint32_t *,
152 const uint8_t **, size_t *);
153 static int np_read64(const char *, const char *, uint64_t *,
154 const uint8_t **, size_t *);
156 #define READSTRERR -1
157 #define READSTRTRUNC -2
158 static int np_readstr(const char *, const char *, char *, size_t,
159 const uint8_t **, size_t *);
161 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
162 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
163 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
164 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
166 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
168 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
169 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
170 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
171 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
172 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
173 static void topen(struct np_msg_header *, const uint8_t *, size_t);
174 static void tcreate(struct np_msg_header *, const uint8_t *, size_t);
175 static void tread(struct np_msg_header *, const uint8_t *, size_t);
176 static void twrite(struct np_msg_header *, const uint8_t *, size_t);
177 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
178 static void tremove(struct np_msg_header *, const uint8_t *, size_t);
179 static void handle_message(struct imsg *, size_t);
181 __dead void
182 client(int debug, int verbose)
184 struct event ev_sigint, ev_sigterm;
186 log_init(debug, LOG_DAEMON);
187 log_setverbose(verbose);
189 setproctitle("client");
190 log_procinit("client");
192 log_debug("warming up");
194 event_init();
196 /* Setup signal handlers */
197 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
198 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
200 signal_add(&ev_sigint, NULL);
201 signal_add(&ev_sigterm, NULL);
203 signal(SIGPIPE, SIG_IGN);
204 signal(SIGHUP, SIG_IGN);
206 /* Setup pipe and event handler to the listener process */
207 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
208 fatal(NULL);
210 imsg_init(&iev_listener->ibuf, 3);
211 iev_listener->handler = client_dispatch_listener;
213 /* Setup event handlers. */
214 iev_listener->events = EV_READ;
215 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
216 iev_listener->events, iev_listener->handler, iev_listener);
217 event_add(&iev_listener->ev, NULL);
219 event_dispatch();
220 client_shutdown();
223 static __dead void
224 client_shutdown(void)
226 if (evb != NULL)
227 evbuffer_free(evb);
229 msgbuf_clear(&iev_listener->ibuf.w);
230 close(iev_listener->ibuf.fd);
232 free(iev_listener);
234 log_debug("client exiting");
235 exit(0);
238 static void
239 client_sig_handler(int sig, short event, void *d)
241 /*
242 * Normal signal handler rules don't apply because libevent
243 * decouples for us.
244 */
246 switch (sig) {
247 case SIGINT:
248 case SIGTERM:
249 client_shutdown();
250 default:
251 fatalx("unexpected signal %d", sig);
255 #define AUTH_NONE 0
256 #define AUTH_USER 1
257 #define AUTH_DONE 2
259 static void
260 client_dispatch_listener(int fd, short event, void *d)
262 static int auth = AUTH_NONE;
263 static char username[64] = {0};
264 static char dir[PATH_MAX] = {0};
265 struct imsg imsg;
266 struct imsgev *iev = d;
267 struct imsgbuf *ibuf;
268 ssize_t n;
269 int shut = 0;
271 ibuf = &iev->ibuf;
273 if (event & EV_READ) {
274 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
275 fatal("imsg_read error");
276 if (n == 0) /* Connection closed */
277 shut = 1;
279 if (event & EV_WRITE) {
280 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
281 fatal("msgbuf_write");
282 if (n == 0) /* Connection closed */
283 shut = 1;
286 for (;;) {
287 if ((n = imsg_get(ibuf, &imsg)) == -1)
288 fatal("%s: imsg_get error", __func__);
289 if (n == 0) /* No more messages. */
290 break;
292 switch (imsg.hdr.type) {
293 case IMSG_AUTH:
294 peerid = imsg.hdr.peerid;
295 if (auth)
296 fatalx("%s: IMSG_AUTH already done", __func__);
297 auth = AUTH_USER;
298 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
299 strlcpy(username, imsg.data, sizeof(username));
300 break;
301 case IMSG_AUTH_DIR:
302 if (auth != AUTH_USER)
303 fatalx("%s: IMSG_AUTH_DIR not after IMSG_AUTH",
304 __func__);
305 auth = AUTH_DONE;
306 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
307 strlcpy(dir, imsg.data, sizeof(dir));
308 client_privdrop(username, dir);
309 memset(username, 0, sizeof(username));
310 memset(dir, 0, sizeof(username));
311 break;
312 case IMSG_BUF:
313 /* echo! */
314 if (!auth)
315 fatalx("%s: can't handle messages before"
316 " doing the auth", __func__);
317 handle_message(&imsg, IMSG_DATA_SIZE(imsg));
318 break;
319 case IMSG_CONN_GONE:
320 log_debug("closing");
321 shut = 1;
322 break;
323 default:
324 log_debug("%s: unexpected imsg %d",
325 __func__, imsg.hdr.type);
326 break;
328 imsg_free(&imsg);
331 if (!shut)
332 imsg_event_add(iev);
333 else {
334 /* This pipe is dead. Remove its event handler. */
335 event_del(&iev->ev);
336 log_debug("pipe closed, shutting down...");
337 event_loopexit(NULL);
341 static void
342 client_privdrop(const char *username, const char *dir)
344 struct passwd *pw;
346 setproctitle("client %s", username);
348 if ((pw = getpwnam(username)) == NULL)
349 fatalx("getpwnam(%s) failed", username);
351 if (chroot(dir) == -1)
352 fatal("chroot");
353 if (chdir("/") == -1)
354 fatal("chdir(\"/\")");
356 if (setgroups(1, &pw->pw_gid) ||
357 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
358 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
359 fatal("can't drop privileges");
361 sandbox_client();
362 log_debug("client ready; user=%s dir=%s", username, dir);
364 if ((evb = evbuffer_new()) == NULL)
365 fatal("evbuffer_new");
368 static int
369 client_send_listener(int type, const void *data, uint16_t len)
371 int ret;
373 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
374 data, len)) != -1)
375 imsg_event_add(iev_listener);
377 return ret;
380 /* set qid fields from sb */
381 static void
382 qid_update_from_sb(struct qid *qid, struct stat *sb)
384 qid->path = sb->st_ino;
386 /*
387 * Theoretically (and hopefully!) this should be a 64 bit
388 * number. Unfortunately, 9P uses 32 bit timestamps.
389 */
390 qid->vers = sb->st_mtim.tv_sec;
392 if (S_ISREG(sb->st_mode))
393 qid->type = QTFILE;
394 else if (S_ISDIR(sb->st_mode))
395 qid->type = QTDIR;
396 else if (S_ISLNK(sb->st_mode))
397 qid->type = QTSYMLINK;
400 /* creates a qid given a fd */
401 static struct dir *
402 new_dir(int fd)
404 struct dir *dir;
406 if ((dir = calloc(1, sizeof(*dir))) == NULL)
407 return NULL;
409 dir->fd = fd;
410 STAILQ_INSERT_HEAD(&dirs, dir, entries);
411 return dir;
414 static struct dir *
415 dir_incref(struct dir *dir)
417 dir->refcount++;
418 return dir;
421 static void
422 dir_decref(struct dir *dir)
424 if (--dir->refcount > 0)
425 return;
427 STAILQ_REMOVE(&dirs, dir, dir, entries);
429 close(dir->fd);
430 free(dir);
433 static struct fid *
434 new_fid(struct dir *dir, uint32_t fid, const char *path, struct qid *qid)
436 struct fid *f;
437 struct qid q;
438 struct stat sb;
440 if (qid == NULL) {
441 if (fstatat(dir->fd, path, &sb, 0)) {
442 log_warn("fstatat(%s)", path);
443 return NULL;
445 qid_update_from_sb(&q, &sb);
446 qid = &q;
449 if ((f = calloc(1, sizeof(*f))) == NULL)
450 return NULL;
452 f->dir = dir_incref(dir);
453 f->fid = fid;
454 f->fd = -1;
456 strlcpy(f->fpath, path, sizeof(f->fpath));
458 memcpy(&f->qid, qid, sizeof(f->qid));
460 STAILQ_INSERT_HEAD(&fids, f, entries);
462 return f;
465 static struct fid *
466 fid_by_id(uint32_t fid)
468 struct fid *f;
470 STAILQ_FOREACH(f, &fids, entries) {
471 if (f->fid == fid)
472 return f;
475 return NULL;
478 static void
479 free_fid(struct fid *f)
481 int r;
483 if (f->fd != -1) {
484 if (f->d != NULL)
485 r = closedir(f->d);
486 else
487 r = close(f->fd);
489 if (r == -1)
490 fatal("can't close fid %d", f->fid);
492 if (f->evb != NULL)
493 evbuffer_free(f->evb);
495 /* try to honour ORCLOSE if requested */
496 if (f->iomode & O_CLOEXEC)
497 unlinkat(f->dir->fd, f->fpath, 0);
500 dir_decref(f->dir);
502 STAILQ_REMOVE(&fids, f, fid, entries);
503 free(f);
506 static void
507 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
508 uint8_t **cnt)
510 size_t olen = len;
512 if (!NPREAD32("len", &hdr->len, &data, &len) ||
513 !NPREAD8("type", &hdr->type, &data, &len) ||
514 !NPREAD16("tag", &hdr->tag, &data, &len))
515 goto err;
517 if (olen != hdr->len)
518 goto err;
520 if (hdr->type < Tversion ||
521 hdr->type >= Tmax ||
522 hdr->type == Terror ||
523 (hdr->type & 0x1) != 0) /* cannot recv a R* */
524 goto err;
526 hdr->tag = le32toh(hdr->tag);
528 *cnt = (uint8_t *)data;
529 return;
531 err:
532 /* TODO: send a proper message to terminate the connection. */
533 fatalx("got invalid message");
536 static void
537 np_write16(struct evbuffer *e, uint16_t x)
539 x = htole16(x);
540 evbuffer_add(e, &x, sizeof(x));
543 static void
544 np_write32(struct evbuffer *e, uint32_t x)
546 x = htole32(x);
547 evbuffer_add(e, &x, sizeof(x));
550 static void
551 np_write64(struct evbuffer *e, uint64_t x)
553 x = htole64(x);
554 evbuffer_add(e, &x, sizeof(x));
557 static void
558 np_writebuf(struct evbuffer *e, size_t len, void *data)
560 evbuffer_add(e, data, len);
563 static void
564 np_header(uint32_t len, uint8_t type, uint16_t tag)
566 len += HEADERSIZE;
568 len = htole32(len);
569 tag = htole16(tag);
571 evbuffer_add(evb, &len, sizeof(len));
572 evbuffer_add(evb, &type, sizeof(type));
573 evbuffer_add(evb, &tag, sizeof(tag));
576 static void
577 np_string(struct evbuffer *e, uint16_t len, const char *str)
579 uint16_t l = len;
581 len = htole16(len);
582 evbuffer_add(e, &len, sizeof(len));
583 evbuffer_add(e, str, l);
586 static void
587 np_qid(struct evbuffer *e, struct qid *qid)
589 uint64_t path;
590 uint32_t vers;
592 path = htole64(qid->path);
593 vers = htole32(qid->vers);
595 evbuffer_add(e, &qid->type, sizeof(qid->type));
596 evbuffer_add(e, &vers, sizeof(vers));
597 evbuffer_add(e, &path, sizeof(path));
600 static void
601 do_send(void)
603 size_t len;
604 void *data;
606 len = EVBUFFER_LENGTH(evb);
607 data = EVBUFFER_DATA(evb);
609 #if DEBUG_PACKETS
610 hexdump("outgoing packet", data, len);
611 #endif
612 client_send_listener(IMSG_BUF, data, len);
613 evbuffer_drain(evb, len);
616 static void
617 np_version(uint16_t tag, uint32_t msize, const char *version)
619 uint16_t l;
621 l = strlen(version);
623 msize = htole32(msize);
625 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
626 evbuffer_add(evb, &msize, sizeof(msize));
627 np_string(evb, l, version);
628 do_send();
631 static void
632 np_attach(uint16_t tag, struct qid *qid)
634 np_header(QIDSIZE, Rattach, tag);
635 np_qid(evb, qid);
636 do_send();
639 static void
640 np_clunk(uint16_t tag)
642 np_header(0, Rclunk, tag);
643 do_send();
646 static void
647 np_flush(uint16_t tag)
649 np_header(0, Rflush, tag);
650 do_send();
653 static void
654 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
656 int i;
658 /* two bytes for the counter */
659 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
660 np_write16(evb, nwqid);
661 for (i = 0; i < nwqid; ++i)
662 np_qid(evb, wqid + i);
664 do_send();
667 static void
668 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
670 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
671 np_qid(evb, qid);
672 np_write32(evb, iounit);
673 do_send();
676 static void
677 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
679 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
680 np_qid(evb, qid);
681 np_write32(evb, iounit);
682 do_send();
685 static void
686 np_read(uint16_t tag, uint32_t count, void *data)
688 if (sizeof(count) + count + HEADERSIZE >= msize) {
689 np_error(tag, "Rread would overflow");
690 return;
693 np_header(sizeof(count) + count, Rread, tag);
694 np_write32(evb, count);
695 np_writebuf(evb, count, data);
696 do_send();
699 static void
700 np_write(uint16_t tag, uint32_t count)
702 np_header(sizeof(count), Rwrite, tag);
703 np_write32(evb, count);
704 do_send();
707 static void
708 np_stat(uint16_t tag, uint32_t count, void *data)
710 if (sizeof(count) + count + HEADERSIZE >= msize) {
711 np_error(tag, "Rstat would overflow");
712 return;
715 np_header(count, Rstat, tag);
716 np_writebuf(evb, count, data);
717 do_send();
720 static void
721 np_remove(uint16_t tag)
723 np_header(0, Rremove, tag);
724 do_send();
727 static void
728 np_error(uint16_t tag, const char *errstr)
730 uint16_t l;
732 l = strlen(errstr);
734 np_header(sizeof(l) + l, Rerror, tag);
735 np_string(evb, l, errstr);
736 do_send();
739 static void
740 np_errno(uint16_t tag)
742 int saved_errno;
743 char buf[NL_TEXTMAX] = {0};
745 saved_errno = errno;
747 strerror_r(errno, buf, sizeof(buf));
748 np_error(tag, buf);
750 errno = saved_errno;
753 static int
754 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
755 size_t *len)
757 if (*len < sizeof(*dst)) {
758 log_warnx("%s: wanted %zu bytes for the %s field but only "
759 "%zu are available.", t, sizeof(*dst), f, *len);
760 return -1;
763 memcpy(dst, *src, sizeof(*dst));
764 *src += sizeof(*dst);
765 *len -= sizeof(*dst);
767 return 1;
770 static int
771 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
772 size_t *len)
774 if (*len < sizeof(*dst)) {
775 log_warnx("%s: wanted %zu bytes for the %s field but only "
776 "%zu are available.", t, sizeof(*dst), f, *len);
777 return -1;
780 memcpy(dst, *src, sizeof(*dst));
781 *src += sizeof(*dst);
782 *len -= sizeof(*dst);
783 *dst = le16toh(*dst);
785 return 1;
788 static int
789 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
790 size_t *len)
792 if (*len < sizeof(*dst)) {
793 log_warnx("%s: wanted %zu bytes for the %s field but only "
794 "%zu are available.", t, sizeof(*dst), f, *len);
795 return -1;
798 memcpy(dst, *src, sizeof(*dst));
799 *src += sizeof(*dst);
800 *len -= sizeof(*dst);
801 *dst = le32toh(*dst);
803 return 1;
806 static int
807 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
808 size_t *len)
810 if (*len < sizeof(*dst)) {
811 log_warnx("%s: wanted %zu bytes for the %s field but only "
812 "%zu are available.", t, sizeof(*dst), f, *len);
813 return -1;
816 memcpy(dst, *src, sizeof(*dst));
817 *src += sizeof(*dst);
818 *len -= sizeof(*dst);
819 *dst = le64toh(*dst);
821 return 1;
824 static int
825 np_readstr(const char *t, const char *f, char *res, size_t reslen,
826 const uint8_t **src, size_t *len)
828 uint16_t sl;
829 char buf[32];
831 strlcpy(buf, f, sizeof(buf));
832 strlcat(buf, "-len", sizeof(buf));
834 if (!np_read16(t, buf, &sl, src, len))
835 return READSTRERR;
837 if (*len < sl) {
838 log_warnx("%s: wanted %d bytes for the %s field but only "
839 "%zu are available.", t, sl, f, *len);
840 return READSTRERR;
843 if (*len > reslen-1)
844 return READSTRTRUNC;
846 memcpy(res, *src, sl);
847 res[sl] = '\0';
848 *src += sl;
849 *len -= sl;
851 return 0;
854 static void
855 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
857 char *dot, version[32];
859 if (handshaked)
860 goto err;
862 /* msize[4] version[s] */
863 if (!NPREAD32("msize", &msize, &data, &len))
864 goto err;
866 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
867 case READSTRERR:
868 goto err;
869 case READSTRTRUNC:
870 log_warnx("9P version string too long, truncated");
871 goto mismatch;
874 if ((dot = strchr(version, '.')) != NULL)
875 *dot = '\0';
877 if (strcmp(version, VERSION9P) != 0 ||
878 msize == 0)
879 goto mismatch;
881 /* version matched */
882 handshaked = 1;
883 msize = MIN(msize, CLIENT_MSIZE);
884 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
885 np_version(hdr->tag, msize, VERSION9P);
886 return;
888 mismatch:
889 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
890 version);
891 np_version(hdr->tag, MSIZE9P, "unknown");
892 return;
894 err:
895 client_send_listener(IMSG_CLOSE, NULL, 0);
896 client_shutdown();
899 static void
900 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
902 struct dir *dir;
903 struct fid *f;
904 uint32_t fid, afid;
905 int fd;
906 char aname[PATH_MAX];
908 /* fid[4] afid[4] uname[s] aname[s] */
910 if (!NPREAD32("fid", &fid, &data, &len) ||
911 !NPREAD32("afid", &afid, &data, &len))
912 goto err;
914 /* read the uname but don't actually use it */
915 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
916 case READSTRERR:
917 goto err;
918 case READSTRTRUNC:
919 np_error(hdr->tag, "name too long");
920 return;
923 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
924 case READSTRERR:
925 goto err;
926 case READSTRTRUNC:
927 np_error(hdr->tag, "name too long");
928 return;
931 if (fid_by_id(fid) != NULL || afid != NOFID) {
932 np_error(hdr->tag, "invalid fid or afid");
933 return;
936 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
937 goto fail;
939 if ((dir = new_dir(fd)) == NULL)
940 goto fail;
942 log_debug("attached %s to %d", aname, fid);
944 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
945 dir_decref(dir);
946 goto fail;
949 np_attach(hdr->tag, &f->qid);
950 return;
952 fail:
953 np_errno(hdr->tag);
954 log_warn("failed to attach %s", aname);
955 return;
957 err:
958 client_send_listener(IMSG_CLOSE, NULL, 0);
959 client_shutdown();
962 static void
963 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
965 struct fid *f;
966 uint32_t fid;
968 /* fid[4] */
969 if (!NPREAD32("fid", &fid, &data, &len)) {
970 client_send_listener(IMSG_CLOSE, NULL, 0);
971 client_shutdown();
972 return;
975 if ((f = fid_by_id(fid)) == NULL) {
976 np_error(hdr->tag, "invalid fid");
977 return;
980 free_fid(f);
981 np_clunk(hdr->tag);
984 static void
985 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
987 uint16_t oldtag;
989 /*
990 * We're doing only synchronous I/O. Tflush is implemented
991 * only because it's illegal to reply with a Rerror.
992 */
994 /* oldtag[2] */
995 if (len != sizeof(oldtag)) {
996 log_warnx("Tflush with the wrong size: got %zu want %zu",
997 len, sizeof(oldtag));
998 client_send_listener(IMSG_CLOSE, NULL, 0);
999 client_shutdown();
1000 return;
1003 np_flush(hdr->tag);
1006 static void
1007 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1009 struct stat sb;
1010 struct dir *dir;
1011 struct qid wqid[MAXWELEM] = {0};
1012 struct fid *f, *nf;
1013 uint32_t fid, newfid;
1014 uint16_t nwname;
1015 int fd, oldfd, no, nwqid = 0;
1016 char wnam[PATH_MAX];
1018 if (!NPREAD32("fid", &fid, &data, &len) ||
1019 !NPREAD32("newfid", &newfid, &data, &len) ||
1020 !NPREAD16("nwname", &nwname, &data, &len))
1021 goto err;
1023 if (nwname > MAXWELEM) {
1024 log_warnx("Twalk: more than %d path elements: %d",
1025 MAXWELEM, nwname);
1026 goto err;
1029 if ((f = fid_by_id(fid)) == NULL) {
1030 np_error(hdr->tag, "invalid fid");
1031 return;
1034 if (f->fd != -1) {
1035 np_error(hdr->tag, "fid already opened for I/O");
1036 return;
1039 if (fid == newfid)
1040 nf = f;
1041 else if ((nf = fid_by_id(newfid)) != NULL) {
1042 np_error(hdr->tag, "newfid already in use");
1043 return;
1044 } else
1045 nf = NULL;
1047 /* special case: fid duplication */
1048 if (nwname == 0) {
1050 * TODO: should we forbid fids duplication when fid ==
1051 * newfid?
1053 if (nf == NULL &&
1054 (nf = new_fid(f->dir, newfid, f->fpath, &f->qid)) == NULL)
1055 fatal("new_fid duplication");
1057 np_walk(hdr->tag, 0, NULL);
1058 return;
1061 if (!(f->qid.type & QTDIR)) {
1062 np_error(hdr->tag, "fid doesn't represent a directory");
1063 return;
1066 oldfd = f->dir->fd;
1068 for (nwqid = 0; nwqid < nwname; nwqid++) {
1069 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1070 case READSTRERR:
1071 goto err;
1072 case READSTRTRUNC:
1073 np_error(hdr->tag, "wname too long");
1074 return;
1077 if (*wnam == '\0' ||
1078 strchr(wnam, '/') != NULL ||
1079 !strcmp(wnam, ".")) {
1080 errno = EINVAL;
1081 goto cantopen;
1084 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1085 errno != ENOTDIR)
1086 goto cantopen;
1088 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1089 (fd != -1 && fstat(fd, &sb) == -1))
1090 goto cantopen;
1092 qid_update_from_sb(&wqid[nwqid], &sb);
1094 /* reached a file but we still have other components */
1095 if (fd == -1 && nwqid+1 < nwname)
1096 goto cantopen;
1098 /* reached the end and found a file */
1099 if (fd == -1 && nwqid+1 == nwname)
1100 continue;
1102 if (oldfd != f->dir->fd)
1103 close(oldfd);
1104 oldfd = fd;
1108 * If fd is -1 we've reached a file, otherwise we've just
1109 * reached another directory. We must pay attention to what
1110 * file descriptor we use to create the dir, because if we've
1111 * reached a file and oldfd is f->dir->fd then we *must* share
1112 * the same dir (it was a walk of one path from a directory to a
1113 * file, otherwise fun is bound to happen as soon as the client
1114 * closes the fid for the directory but keeps the one for the
1115 * file.
1117 if (fd == -1 && oldfd == f->dir->fd)
1118 dir = f->dir;
1119 else if (fd == -1)
1120 dir = new_dir(oldfd);
1121 else
1122 dir = new_dir(fd);
1124 if (dir == NULL)
1125 fatal("new_dir");
1127 if (nf == NULL) {
1128 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1129 fatal("new fid");
1130 } else {
1131 /* update the dir */
1132 dir_decref(nf->dir);
1133 nf->dir = dir_incref(dir);
1136 np_walk(hdr->tag, nwqid, wqid);
1137 return;
1139 cantopen:
1140 if (oldfd != f->dir->fd)
1141 close(oldfd);
1142 no = errno;
1143 if (nwqid == 0)
1144 np_error(hdr->tag, strerror(no));
1145 else
1146 np_walk(hdr->tag, nwqid, wqid);
1147 return;
1149 err:
1150 client_send_listener(IMSG_CLOSE, NULL, 0);
1151 client_shutdown();
1154 static inline int
1155 npmode_to_unix(uint8_t mode, int *flags)
1157 switch (mode & 0x0F) {
1158 case KOREAD:
1159 *flags = O_RDONLY;
1160 break;
1161 case KOWRITE:
1162 *flags = O_WRONLY;
1163 break;
1164 case KORDWR:
1165 *flags = O_RDWR;
1166 break;
1167 case KOEXEC:
1168 log_warnx("tried to open something with KOEXEC");
1169 /* fallthrough */
1170 default:
1171 return -1;
1174 if (mode & KOTRUNC)
1175 *flags |= O_TRUNC;
1176 if (mode & KORCLOSE)
1177 *flags |= O_CLOEXEC;
1179 return 0;
1182 static void
1183 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1185 struct stat sb;
1186 struct qid qid;
1187 struct fid *f;
1188 uint32_t fid;
1189 uint8_t mode;
1190 const char *path;
1192 /* fid[4] mode[1] */
1193 if (!NPREAD32("fid", &fid, &data, &len) ||
1194 !NPREAD8("mode", &mode, &data, &len)) {
1195 client_send_listener(IMSG_CLOSE, NULL, 0);
1196 client_shutdown();
1197 return;
1200 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1201 np_error(hdr->tag, "invalid fid");
1202 return;
1205 if (npmode_to_unix(mode, &f->iomode) == -1) {
1206 np_error(hdr->tag, "invalid mode");
1207 return;
1210 path = f->fpath;
1211 if (f->qid.type & QTDIR)
1212 path = ".";
1214 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1215 np_error(hdr->tag, strerror(errno));
1216 return;
1219 if (fstat(f->fd, &sb) == -1)
1220 fatal("fstat");
1222 if (S_ISDIR(sb.st_mode)) {
1223 if ((f->d = fdopendir(f->fd)) == NULL) {
1224 np_errno(hdr->tag);
1225 close(f->fd);
1226 f->fd = -1;
1227 return;
1230 if ((f->evb = evbuffer_new()) == NULL) {
1231 np_errno(hdr->tag);
1232 closedir(f->d);
1233 f->d = NULL;
1234 f->fd = -1;
1238 f->offset = 0;
1240 qid_update_from_sb(&qid, &sb);
1241 np_open(hdr->tag, &qid, sb.st_blksize);
1244 static void
1245 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1247 struct stat sb;
1248 struct qid qid;
1249 struct fid *f;
1250 uint32_t fid, perm;
1251 uint8_t mode;
1252 char name[PATH_MAX];
1254 /* fid[4] name[s] perm[4] mode[1] */
1255 if (!NPREAD32("fid", &fid, &data, &len))
1256 goto err;
1257 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1258 case READSTRERR:
1259 goto err;
1260 case READSTRTRUNC:
1261 np_error(hdr->tag, "name too long");
1262 return;
1264 if (!NPREAD32("perm", &perm, &data, &len) ||
1265 !NPREAD8("mode", &mode, &data, &len))
1266 goto err;
1268 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1269 strchr(name, '/') != NULL) {
1270 np_error(hdr->tag, "invalid name");
1271 return;
1274 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1275 np_error(hdr->tag, "invalid fid");
1276 return;
1279 if (!(f->qid.type & QTDIR)) {
1280 np_error(hdr->tag, "fid doesn't identify a directory");
1281 return;
1284 if (npmode_to_unix(mode, &f->iomode) == -1) {
1285 np_error(hdr->tag, "invalid mode");
1286 return;
1289 if (f->iomode & O_RDONLY) {
1290 np_error(hdr->tag, "can't create a read-only file");
1291 return;
1294 /* TODO: parse the mode */
1296 if (perm & 0x80000000) {
1297 /* create a directory */
1298 f->fd = mkdirat(f->dir->fd, name, 0755);
1299 } else {
1300 /* create a file */
1301 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1302 0644);
1305 if (f->fd == -1) {
1306 np_errno(hdr->tag);
1307 return;
1310 if (fstat(f->fd, &sb) == -1)
1311 fatal("fstat");
1313 if (S_ISDIR(sb.st_mode)) {
1314 if ((f->d = fdopendir(f->fd)) == NULL) {
1315 np_errno(hdr->tag);
1316 close(f->fd);
1317 f->fd = -1;
1318 return;
1321 if ((f->evb = evbuffer_new()) == NULL) {
1322 np_errno(hdr->tag);
1323 closedir(f->d);
1324 f->d = NULL;
1325 f->fd = -1;
1329 f->offset = 0;
1331 qid_update_from_sb(&qid, &sb);
1332 np_create(hdr->tag, &qid, sb.st_blksize);
1334 return;
1336 err:
1337 client_send_listener(IMSG_CLOSE, NULL, 0);
1338 client_shutdown();
1341 static inline void
1342 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1344 struct qid qid;
1345 const char *uid, *gid, *muid;
1346 size_t tot;
1347 uint16_t namlen, uidlen, gidlen, ulen;
1349 qid_update_from_sb(&qid, sb);
1351 /* TODO: fill these fields */
1352 uid = "";
1353 gid = "";
1354 muid = "";
1356 namlen = strlen(fname);
1357 uidlen = strlen(uid);
1358 gidlen = strlen(gid);
1359 ulen = strlen(muid);
1361 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1362 if (tot > UINT32_MAX) {
1363 log_warnx("stat info for dir entry %s would overflow",
1364 fname);
1365 return;
1368 np_write16(evb, tot); /* size[2] */
1369 np_write16(evb, sb->st_rdev); /* type[2] */
1370 np_write32(evb, sb->st_dev); /* dev[4] */
1371 np_qid(evb, &qid); /* qid[13] */
1373 /* XXX: translate? */
1374 np_write32(evb, sb->st_mode); /* mode[4] */
1376 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1377 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1378 np_write64(evb, sb->st_size); /* length[8] */
1379 np_string(evb, namlen, fname); /* name[s] */
1380 np_string(evb, uidlen, uid); /* uid[s] */
1381 np_string(evb, gidlen, gid); /* gid[s] */
1382 np_string(evb, ulen, muid); /* muid[s] */
1385 static void
1386 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1388 struct fid *f;
1389 ssize_t r;
1390 size_t howmuch;
1391 uint64_t off;
1392 uint32_t fid, count;
1393 char buf[2048];
1395 /* fid[4] offset[8] count[4] */
1396 if (!NPREAD32("fid", &fid, &data, &len) ||
1397 !NPREAD64("offset", &off, &data, &len) ||
1398 !NPREAD32("count", &count, &data, &len)) {
1399 client_send_listener(IMSG_CLOSE, NULL, 0);
1400 client_shutdown();
1401 return;
1404 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1405 np_error(hdr->tag, "invalid fid");
1406 return;
1409 if (TYPE_OVERFLOW(off_t, off)) {
1410 log_warnx("unexpected off_t size");
1411 np_error(hdr->tag, "invalid offset");
1412 return;
1415 if (f->d == NULL) {
1416 /* read a file */
1417 howmuch = MIN(sizeof(buf), count);
1418 r = pread(f->fd, buf, howmuch, (off_t)off);
1419 if (r == -1)
1420 np_errno(hdr->tag);
1421 else
1422 np_read(hdr->tag, r, buf);
1423 } else {
1424 if (off == 0 && f->offset != 0) {
1425 rewinddir(f->d);
1426 f->offset = 0;
1427 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1430 if (off != f->offset) {
1431 np_error(hdr->tag, "can't seek in directories");
1432 return;
1435 while (EVBUFFER_LENGTH(f->evb) < count) {
1436 struct dirent *d;
1437 struct stat sb;
1439 if ((d = readdir(f->d)) == NULL)
1440 break;
1441 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1442 warn("fstatat");
1443 continue;
1445 serialize_stat(d->d_name, &sb, f->evb);
1448 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1449 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1450 evbuffer_drain(f->evb, count);
1452 f->offset += count;
1456 static void
1457 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1459 struct fid *f;
1460 ssize_t r;
1461 uint64_t off;
1462 uint32_t fid, count;
1464 /* fid[4] offset[8] count[4] data[count] */
1465 if (!NPREAD32("fid", &fid, &data, &len) ||
1466 !NPREAD64("off", &off, &data, &len) ||
1467 !NPREAD32("count", &count, &data, &len) ||
1468 len != count) {
1469 client_send_listener(IMSG_CLOSE, NULL, 0);
1470 client_shutdown();
1471 return;
1474 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1475 np_error(hdr->tag, "invalid fid");
1476 return;
1479 if (!(f->iomode & O_WRONLY) &&
1480 !(f->iomode & O_RDWR)) {
1481 np_error(hdr->tag, "fid not opened for writing");
1482 return;
1485 if (TYPE_OVERFLOW(off_t, off)) {
1486 log_warnx("unexpected off_t size");
1487 np_error(hdr->tag, "invalid offset");
1488 return;
1491 if ((r = pwrite(f->fd, data, len, off)) == -1)
1492 np_errno(hdr->tag);
1493 else
1494 np_write(hdr->tag, r);
1497 static void
1498 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1500 struct evbuffer *evb;
1501 struct stat sb;
1502 struct fid *f;
1503 int r;
1504 uint32_t fid;
1506 /* fid[4] */
1507 if (!NPREAD32("fid", &fid, &data, &len)) {
1508 client_send_listener(IMSG_CLOSE, NULL, 0);
1509 client_shutdown();
1510 return;
1514 * plan9' stat(9P) is not clear on whether the stat is allowed
1515 * on opened fids or not. We're allowing stat regardless of the
1516 * status of the fid.
1519 if ((f = fid_by_id(fid)) == NULL) {
1520 np_error(hdr->tag, "invalid fid");
1521 return;
1524 if ((evb = evbuffer_new()) == NULL)
1525 fatal("evbuffer_new");
1527 if (f->fd != -1)
1528 r = fstat(f->fd, &sb);
1529 else if (f->qid.type & QTDIR)
1530 r = fstat(f->dir->fd, &sb);
1531 else
1532 r = fstatat(f->dir->fd, f->fpath, &sb, 0);
1534 if (r == -1) {
1535 np_errno(hdr->tag);
1536 evbuffer_free(evb);
1537 return;
1540 serialize_stat(f->fpath, &sb, evb);
1541 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1542 evbuffer_free(evb);
1545 static void
1546 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1548 struct fid *f;
1549 uint32_t fid;
1550 int r;
1551 char dirpath[PATH_MAX + 3];
1553 /* fid[4] */
1554 if (!NPREAD32("fid", &fid, &data, &len)) {
1555 client_send_listener(IMSG_CLOSE, NULL, 0);
1556 client_shutdown();
1557 return;
1560 if ((f = fid_by_id(fid)) == NULL) {
1561 np_error(hdr->tag, "invalid fid");
1562 return;
1565 if (f->qid.type & QTDIR) { /* directory */
1566 strlcpy(dirpath, "../", sizeof(dirpath));
1567 strlcat(dirpath, f->fpath, sizeof(dirpath));
1568 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1569 } else /* file */
1570 r = unlinkat(f->dir->fd, f->fpath, 0);
1572 if (r == -1)
1573 np_errno(hdr->tag);
1574 else
1575 np_remove(hdr->tag);
1577 free_fid(f);
1580 static void
1581 handle_message(struct imsg *imsg, size_t len)
1583 struct msg {
1584 uint8_t type;
1585 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1586 } msgs[] = {
1587 {Tversion, tversion},
1588 {Tattach, tattach},
1589 {Tclunk, tclunk},
1590 {Tflush, tflush},
1591 {Twalk, twalk},
1592 {Topen, topen},
1593 {Tcreate, tcreate},
1594 {Tread, tread},
1595 {Twrite, twrite},
1596 {Tstat, tstat},
1597 {Tremove, tremove},
1599 struct np_msg_header hdr;
1600 size_t i;
1601 uint8_t *data;
1603 #if DEBUG_PACKETS
1604 hexdump("incoming packet", imsg->data, len);
1605 #endif
1607 parse_message(imsg->data, len, &hdr, &data);
1608 len -= HEADERSIZE;
1610 log_debug("got request: len=%d type=%d[%s] tag=%d",
1611 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1613 if (!handshaked && hdr.type != Tversion) {
1614 client_send_listener(IMSG_CLOSE, NULL, 0);
1615 client_shutdown();
1616 return;
1619 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1620 if (msgs[i].type != hdr.type)
1621 continue;
1623 msgs[i].fn(&hdr, data, len);
1624 return;
1627 np_error(hdr.tag, "Not supported.");