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>
21 #include <dirent.h>
22 #include <endian.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <pwd.h>
26 #include <signal.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <syslog.h>
30 #include <unistd.h>
32 #include "client.h"
33 #include "kamid.h"
34 #include "log.h"
35 #include "sandbox.h"
36 #include "utils.h"
38 /*
39 * XXX: atm is difficult to accept messages bigger than MAX_IMSGSIZE
40 * minus IMSG_HEADER_SIZE, we need something to split messages into
41 * chunks and receive them one by the other.
42 *
43 * CLIENT_MSIZE is thus the maximum message size we can handle now.
44 */
45 #define CLIENT_MSIZE (MAX_IMSGSIZE - IMSG_HEADER_SIZE)
47 #define DEBUG_PACKETS 0
49 /* straight outta /src/usr.bin/ssh/scp.c */
50 #define TYPE_OVERFLOW(type, val) \
51 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
52 (sizeof(type) == 8 && (val) > INT64_MAX) || \
53 (sizeof(type) != 4 && sizeof(type) != 8))
55 STAILQ_HEAD(dirhead, dir) dirs;
56 struct dir {
57 int refcount;
58 int fd;
59 STAILQ_ENTRY(dir) entries;
60 };
62 STAILQ_HEAD(fidhead, fid) fids;
63 struct fid {
64 uint32_t fid;
66 char fpath[PATH_MAX];
68 /*
69 * the flags passed to open(2). O_CLOEXEC means ORCLOSE, that
70 * is to unlink the file upon Tclunk.
71 */
72 int iomode;
74 /*
75 * if fd is not -1 this fid was opened, fd represents its
76 * file descriptor and iomode the flags passed to open(2).
77 */
78 int fd;
79 DIR *d;
80 struct evbuffer *evb;
82 /*
83 * expected offset for Tread against a directory.
84 */
85 uint64_t offset;
87 struct qid qid;
88 struct dir *dir;
89 STAILQ_ENTRY(fid) entries;
90 };
92 static struct imsgev *iev_listener;
93 static struct evbuffer *evb;
94 static uint32_t peerid;
96 static int handshaked;
97 uint32_t msize;
99 static __dead void client_shutdown(void);
100 static void client_sig_handler(int, short, void *);
101 static void client_dispatch_listener(int, short, void *);
102 static void client_privdrop(const char *, const char *);
104 static int client_send_listener(int, const void *, uint16_t);
106 static void qid_update_from_sb(struct qid *, struct stat *);
108 static struct dir *new_dir(int);
109 static struct dir *dir_incref(struct dir *);
110 static void dir_decref(struct dir *);
112 static struct fid *new_fid(struct dir *, uint32_t, const char *, struct qid *);
113 static struct fid *fid_by_id(uint32_t);
114 static void free_fid(struct fid *);
116 static void parse_message(const uint8_t *, size_t,
117 struct np_msg_header *, uint8_t **);
119 static void np_write16(struct evbuffer *, uint16_t);
120 static void np_write32(struct evbuffer *, uint32_t);
121 static void np_write64(struct evbuffer *, uint64_t);
122 static void np_header(uint32_t, uint8_t, uint16_t);
123 static void np_string(struct evbuffer *, uint16_t, const char *);
124 static void np_qid(struct evbuffer *, struct qid *);
125 static void do_send(void);
127 static void np_version(uint16_t, uint32_t, const char *);
128 static void np_attach(uint16_t, struct qid *);
129 static void np_clunk(uint16_t);
130 static void np_flush(uint16_t);
131 static void np_walk(uint16_t, int, struct qid *);
132 static void np_open(uint16_t, struct qid *, uint32_t);
133 static void np_create(uint16_t, struct qid *, uint32_t);
134 static void np_read(uint16_t, uint32_t, void *);
135 static void np_write(uint16_t, uint32_t);
136 static void np_stat(uint16_t, uint32_t, void *);
137 static void np_remove(uint16_t);
138 static void np_error(uint16_t, const char *);
139 static void np_errno(uint16_t);
141 static int np_read8(const char *, const char *, uint8_t *,
142 const uint8_t **, size_t *);
143 static int np_read16(const char *, const char *, uint16_t *,
144 const uint8_t **, size_t *);
145 static int np_read32(const char *, const char *, uint32_t *,
146 const uint8_t **, size_t *);
147 static int np_read64(const char *, const char *, uint64_t *,
148 const uint8_t **, size_t *);
150 #define READSTRERR -1
151 #define READSTRTRUNC -2
152 static int np_readstr(const char *, const char *, char *, size_t,
153 const uint8_t **, size_t *);
155 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
156 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
157 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
158 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
160 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
162 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
163 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
164 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
165 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
166 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
167 static void topen(struct np_msg_header *, const uint8_t *, size_t);
168 static void tcreate(struct np_msg_header *, const uint8_t *, size_t);
169 static void tread(struct np_msg_header *, const uint8_t *, size_t);
170 static void twrite(struct np_msg_header *, const uint8_t *, size_t);
171 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
172 static void tremove(struct np_msg_header *, const uint8_t *, size_t);
173 static void handle_message(struct imsg *, size_t);
175 __dead void
176 client(int debug, int verbose)
178 struct event ev_sigint, ev_sigterm;
180 log_init(debug, LOG_DAEMON);
181 log_setverbose(verbose);
183 setproctitle("client");
184 log_procinit("client");
186 log_debug("warming up");
188 event_init();
190 /* Setup signal handlers */
191 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
192 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
194 signal_add(&ev_sigint, NULL);
195 signal_add(&ev_sigterm, NULL);
197 signal(SIGPIPE, SIG_IGN);
198 signal(SIGHUP, SIG_IGN);
200 /* Setup pipe and event handler to the listener process */
201 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
202 fatal(NULL);
204 imsg_init(&iev_listener->ibuf, 3);
205 iev_listener->handler = client_dispatch_listener;
207 /* Setup event handlers. */
208 iev_listener->events = EV_READ;
209 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
210 iev_listener->events, iev_listener->handler, iev_listener);
211 event_add(&iev_listener->ev, NULL);
213 event_dispatch();
214 client_shutdown();
217 static __dead void
218 client_shutdown(void)
220 if (evb != NULL)
221 evbuffer_free(evb);
223 msgbuf_clear(&iev_listener->ibuf.w);
224 close(iev_listener->ibuf.fd);
226 free(iev_listener);
228 log_debug("client exiting");
229 exit(0);
232 static void
233 client_sig_handler(int sig, short event, void *d)
235 /*
236 * Normal signal handler rules don't apply because libevent
237 * decouples for us.
238 */
240 switch (sig) {
241 case SIGINT:
242 case SIGTERM:
243 client_shutdown();
244 default:
245 fatalx("unexpected signal %d", sig);
249 #define AUTH_NONE 0
250 #define AUTH_USER 1
251 #define AUTH_DONE 2
253 static void
254 client_dispatch_listener(int fd, short event, void *d)
256 static int auth = AUTH_NONE;
257 static char username[64] = {0};
258 static char dir[PATH_MAX] = {0};
259 struct imsg imsg;
260 struct imsgev *iev = d;
261 struct imsgbuf *ibuf;
262 ssize_t n;
263 int shut = 0;
265 ibuf = &iev->ibuf;
267 if (event & EV_READ) {
268 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
269 fatal("imsg_read error");
270 if (n == 0) /* Connection closed */
271 shut = 1;
273 if (event & EV_WRITE) {
274 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
275 fatal("msgbuf_write");
276 if (n == 0) /* Connection closed */
277 shut = 1;
280 for (;;) {
281 if ((n = imsg_get(ibuf, &imsg)) == -1)
282 fatal("%s: imsg_get error", __func__);
283 if (n == 0) /* No more messages. */
284 break;
286 switch (imsg.hdr.type) {
287 case IMSG_AUTH:
288 peerid = imsg.hdr.peerid;
289 if (auth)
290 fatalx("%s: IMSG_AUTH already done", __func__);
291 auth = AUTH_USER;
292 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
293 strlcpy(username, imsg.data, sizeof(username));
294 break;
295 case IMSG_AUTH_DIR:
296 if (auth != AUTH_USER)
297 fatalx("%s: IMSG_AUTH_DIR not after IMSG_AUTH",
298 __func__);
299 auth = AUTH_DONE;
300 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
301 strlcpy(dir, imsg.data, sizeof(dir));
302 client_privdrop(username, dir);
303 memset(username, 0, sizeof(username));
304 memset(dir, 0, sizeof(username));
305 break;
306 case IMSG_BUF:
307 /* echo! */
308 if (!auth)
309 fatalx("%s: can't handle messages before"
310 " doing the auth", __func__);
311 handle_message(&imsg, IMSG_DATA_SIZE(imsg));
312 break;
313 case IMSG_CONN_GONE:
314 log_debug("closing");
315 shut = 1;
316 break;
317 default:
318 log_debug("%s: unexpected imsg %d",
319 __func__, imsg.hdr.type);
320 break;
322 imsg_free(&imsg);
325 if (!shut)
326 imsg_event_add(iev);
327 else {
328 /* This pipe is dead. Remove its event handler. */
329 event_del(&iev->ev);
330 log_debug("pipe closed, shutting down...");
331 event_loopexit(NULL);
335 static void
336 client_privdrop(const char *username, const char *dir)
338 struct passwd *pw;
340 setproctitle("client %s", username);
342 if ((pw = getpwnam(username)) == NULL)
343 fatalx("getpwnam(%s) failed", username);
345 if (chroot(dir) == -1)
346 fatal("chroot");
347 if (chdir("/") == -1)
348 fatal("chdir(\"/\")");
350 if (setgroups(1, &pw->pw_gid) ||
351 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
352 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
353 fatal("can't drop privileges");
355 sandbox_client();
356 log_debug("client ready; user=%s dir=%s", username, dir);
358 if ((evb = evbuffer_new()) == NULL)
359 fatal("evbuffer_new");
362 static int
363 client_send_listener(int type, const void *data, uint16_t len)
365 int ret;
367 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
368 data, len)) != -1)
369 imsg_event_add(iev_listener);
371 return ret;
374 /* set qid fields from sb */
375 static void
376 qid_update_from_sb(struct qid *qid, struct stat *sb)
378 qid->path = sb->st_ino;
380 /*
381 * Theoretically (and hopefully!) this should be a 64 bit
382 * number. Unfortunately, 9P uses 32 bit timestamps.
383 */
384 qid->vers = sb->st_mtim.tv_sec;
386 if (S_ISREG(sb->st_mode))
387 qid->type = QTFILE;
388 else if (S_ISDIR(sb->st_mode))
389 qid->type = QTDIR;
390 else if (S_ISLNK(sb->st_mode))
391 qid->type = QTSYMLINK;
394 /* creates a qid given a fd */
395 static struct dir *
396 new_dir(int fd)
398 struct dir *dir;
400 if ((dir = calloc(1, sizeof(*dir))) == NULL)
401 return NULL;
403 dir->fd = fd;
404 STAILQ_INSERT_HEAD(&dirs, dir, entries);
405 return dir;
408 static struct dir *
409 dir_incref(struct dir *dir)
411 dir->refcount++;
412 return dir;
415 static void
416 dir_decref(struct dir *dir)
418 if (--dir->refcount > 0)
419 return;
421 STAILQ_REMOVE(&dirs, dir, dir, entries);
423 close(dir->fd);
424 free(dir);
427 static struct fid *
428 new_fid(struct dir *dir, uint32_t fid, const char *path, struct qid *qid)
430 struct fid *f;
431 struct qid q;
432 struct stat sb;
434 if (qid == NULL) {
435 if (fstatat(dir->fd, path, &sb, 0)) {
436 log_warn("fstatat(%s)", path);
437 return NULL;
439 qid_update_from_sb(&q, &sb);
440 qid = &q;
443 if ((f = calloc(1, sizeof(*f))) == NULL)
444 return NULL;
446 f->dir = dir_incref(dir);
447 f->fid = fid;
448 f->fd = -1;
450 strlcpy(f->fpath, path, sizeof(f->fpath));
452 memcpy(&f->qid, qid, sizeof(f->qid));
454 STAILQ_INSERT_HEAD(&fids, f, entries);
456 return f;
459 static struct fid *
460 fid_by_id(uint32_t fid)
462 struct fid *f;
464 STAILQ_FOREACH(f, &fids, entries) {
465 if (f->fid == fid)
466 return f;
469 return NULL;
472 static void
473 free_fid(struct fid *f)
475 int r;
477 if (f->fd != -1) {
478 if (f->d != NULL)
479 r = closedir(f->d);
480 else
481 r = close(f->fd);
483 if (r == -1)
484 fatal("can't close fid %d", f->fid);
486 if (f->evb != NULL)
487 evbuffer_free(f->evb);
489 /* try to honour ORCLOSE if requested */
490 if (f->iomode & O_CLOEXEC)
491 unlinkat(f->dir->fd, f->fpath, 0);
494 dir_decref(f->dir);
496 STAILQ_REMOVE(&fids, f, fid, entries);
497 free(f);
500 static void
501 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
502 uint8_t **cnt)
504 size_t olen = len;
506 if (!NPREAD32("len", &hdr->len, &data, &len) ||
507 !NPREAD8("type", &hdr->type, &data, &len) ||
508 !NPREAD16("tag", &hdr->tag, &data, &len))
509 goto err;
511 if (olen != hdr->len)
512 goto err;
514 if (hdr->type < Tversion ||
515 hdr->type >= Tmax ||
516 hdr->type == Terror ||
517 (hdr->type & 0x1) != 0) /* cannot recv a R* */
518 goto err;
520 hdr->tag = le32toh(hdr->tag);
522 *cnt = (uint8_t *)data;
523 return;
525 err:
526 /* TODO: send a proper message to terminate the connection. */
527 fatalx("got invalid message");
530 static void
531 np_write16(struct evbuffer *e, uint16_t x)
533 x = htole16(x);
534 evbuffer_add(e, &x, sizeof(x));
537 static void
538 np_write32(struct evbuffer *e, uint32_t x)
540 x = htole32(x);
541 evbuffer_add(e, &x, sizeof(x));
544 static void
545 np_write64(struct evbuffer *e, uint64_t x)
547 x = htole64(x);
548 evbuffer_add(e, &x, sizeof(x));
551 static void
552 np_writebuf(struct evbuffer *e, size_t len, void *data)
554 evbuffer_add(e, data, len);
557 static void
558 np_header(uint32_t len, uint8_t type, uint16_t tag)
560 len += HEADERSIZE;
562 len = htole32(len);
563 tag = htole16(tag);
565 evbuffer_add(evb, &len, sizeof(len));
566 evbuffer_add(evb, &type, sizeof(type));
567 evbuffer_add(evb, &tag, sizeof(tag));
570 static void
571 np_string(struct evbuffer *e, uint16_t len, const char *str)
573 uint16_t l = len;
575 len = htole16(len);
576 evbuffer_add(e, &len, sizeof(len));
577 evbuffer_add(e, str, l);
580 static void
581 np_qid(struct evbuffer *e, struct qid *qid)
583 uint64_t path;
584 uint32_t vers;
586 path = htole64(qid->path);
587 vers = htole32(qid->vers);
589 evbuffer_add(e, &qid->type, sizeof(qid->type));
590 evbuffer_add(e, &vers, sizeof(vers));
591 evbuffer_add(e, &path, sizeof(path));
594 static void
595 do_send(void)
597 size_t len;
598 void *data;
600 len = EVBUFFER_LENGTH(evb);
601 data = EVBUFFER_DATA(evb);
603 #if DEBUG_PACKETS
604 hexdump("outgoing packet", data, len);
605 #endif
606 client_send_listener(IMSG_BUF, data, len);
607 evbuffer_drain(evb, len);
610 static void
611 np_version(uint16_t tag, uint32_t msize, const char *version)
613 uint16_t l;
615 l = strlen(version);
617 msize = htole32(msize);
619 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
620 evbuffer_add(evb, &msize, sizeof(msize));
621 np_string(evb, l, version);
622 do_send();
625 static void
626 np_attach(uint16_t tag, struct qid *qid)
628 np_header(QIDSIZE, Rattach, tag);
629 np_qid(evb, qid);
630 do_send();
633 static void
634 np_clunk(uint16_t tag)
636 np_header(0, Rclunk, tag);
637 do_send();
640 static void
641 np_flush(uint16_t tag)
643 np_header(0, Rflush, tag);
644 do_send();
647 static void
648 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
650 int i;
652 /* two bytes for the counter */
653 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
654 np_write16(evb, nwqid);
655 for (i = 0; i < nwqid; ++i)
656 np_qid(evb, wqid + i);
658 do_send();
661 static void
662 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
664 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
665 np_qid(evb, qid);
666 np_write32(evb, iounit);
667 do_send();
670 static void
671 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
673 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
674 np_qid(evb, qid);
675 np_write32(evb, iounit);
676 do_send();
679 static void
680 np_read(uint16_t tag, uint32_t count, void *data)
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 np_header(count, Rstat, tag);
700 np_writebuf(evb, count, data);
701 do_send();
704 static void
705 np_remove(uint16_t tag)
707 np_header(0, Rremove, tag);
708 do_send();
711 static void
712 np_error(uint16_t tag, const char *errstr)
714 uint16_t l;
716 l = strlen(errstr);
718 np_header(sizeof(l) + l, Rerror, tag);
719 np_string(evb, l, errstr);
720 do_send();
723 static void
724 np_errno(uint16_t tag)
726 int saved_errno;
727 char buf[64];
729 saved_errno = errno;
731 strerror_r(errno, buf, sizeof(buf));
732 np_error(tag, buf);
734 errno = saved_errno;
737 static int
738 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
739 size_t *len)
741 if (*len < sizeof(*dst)) {
742 log_warnx("%s: wanted %zu bytes for the %s field but only "
743 "%zu are available.", t, sizeof(*dst), f, *len);
744 return -1;
747 memcpy(dst, *src, sizeof(*dst));
748 *src += sizeof(*dst);
749 *len -= sizeof(*dst);
751 return 1;
754 static int
755 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
756 size_t *len)
758 if (*len < sizeof(*dst)) {
759 log_warnx("%s: wanted %zu bytes for the %s field but only "
760 "%zu are available.", t, sizeof(*dst), f, *len);
761 return -1;
764 memcpy(dst, *src, sizeof(*dst));
765 *src += sizeof(*dst);
766 *len -= sizeof(*dst);
767 *dst = le16toh(*dst);
769 return 1;
772 static int
773 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
774 size_t *len)
776 if (*len < sizeof(*dst)) {
777 log_warnx("%s: wanted %zu bytes for the %s field but only "
778 "%zu are available.", t, sizeof(*dst), f, *len);
779 return -1;
782 memcpy(dst, *src, sizeof(*dst));
783 *src += sizeof(*dst);
784 *len -= sizeof(*dst);
785 *dst = le32toh(*dst);
787 return 1;
790 static int
791 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
792 size_t *len)
794 if (*len < sizeof(*dst)) {
795 log_warnx("%s: wanted %zu bytes for the %s field but only "
796 "%zu are available.", t, sizeof(*dst), f, *len);
797 return -1;
800 memcpy(dst, *src, sizeof(*dst));
801 *src += sizeof(*dst);
802 *len -= sizeof(*dst);
803 *dst = le64toh(*dst);
805 return 1;
808 static int
809 np_readstr(const char *t, const char *f, char *res, size_t reslen,
810 const uint8_t **src, size_t *len)
812 uint16_t sl;
813 char buf[32];
815 strlcpy(buf, f, sizeof(buf));
816 strlcat(buf, "-len", sizeof(buf));
818 if (!np_read16(t, buf, &sl, src, len))
819 return READSTRERR;
821 if (*len < sl) {
822 log_warnx("%s: wanted %d bytes for the %s field but only "
823 "%zu are available.", t, sl, f, *len);
824 return READSTRERR;
827 if (*len > reslen-1)
828 return READSTRTRUNC;
830 memcpy(res, *src, sl);
831 res[sl] = '\0';
832 *src += sl;
833 *len -= sl;
835 return 0;
838 static void
839 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
841 char *dot, version[32];
843 if (handshaked)
844 goto err;
846 /* msize[4] version[s] */
847 if (!NPREAD32("msize", &msize, &data, &len))
848 goto err;
850 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
851 case READSTRERR:
852 goto err;
853 case READSTRTRUNC:
854 log_warnx("9P version string too long, truncated");
855 goto mismatch;
858 if ((dot = strchr(version, '.')) != NULL)
859 *dot = '\0';
861 if (strcmp(version, VERSION9P) != 0 ||
862 msize == 0)
863 goto mismatch;
865 /* version matched */
866 handshaked = 1;
867 msize = MIN(msize, CLIENT_MSIZE);
868 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
869 np_version(hdr->tag, msize, VERSION9P);
870 return;
872 mismatch:
873 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
874 version);
875 np_version(hdr->tag, MSIZE9P, "unknown");
876 return;
878 err:
879 client_send_listener(IMSG_CLOSE, NULL, 0);
880 client_shutdown();
883 static void
884 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
886 struct dir *dir;
887 struct fid *f;
888 uint32_t fid, afid;
889 int fd;
890 char aname[PATH_MAX];
892 /* fid[4] afid[4] uname[s] aname[s] */
894 if (!NPREAD32("fid", &fid, &data, &len) ||
895 !NPREAD32("afid", &afid, &data, &len))
896 goto err;
898 /* read the uname but don't actually use it */
899 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
900 case READSTRERR:
901 goto err;
902 case READSTRTRUNC:
903 np_error(hdr->tag, "name too long");
904 return;
907 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
908 case READSTRERR:
909 goto err;
910 case READSTRTRUNC:
911 np_error(hdr->tag, "name too long");
912 return;
915 if (fid_by_id(fid) != NULL || afid != NOFID) {
916 np_error(hdr->tag, "invalid fid or afid");
917 return;
920 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
921 goto fail;
923 if ((dir = new_dir(fd)) == NULL)
924 goto fail;
926 log_debug("attached %s to %d", aname, fid);
928 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
929 dir_decref(dir);
930 goto fail;
933 np_attach(hdr->tag, &f->qid);
934 return;
936 fail:
937 np_errno(hdr->tag);
938 log_warn("failed to attach %s", aname);
939 return;
941 err:
942 client_send_listener(IMSG_CLOSE, NULL, 0);
943 client_shutdown();
946 static void
947 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
949 struct fid *f;
950 uint32_t fid;
952 /* fid[4] */
953 if (!NPREAD32("fid", &fid, &data, &len)) {
954 client_send_listener(IMSG_CLOSE, NULL, 0);
955 client_shutdown();
956 return;
959 if ((f = fid_by_id(fid)) == NULL) {
960 np_error(hdr->tag, "invalid fid");
961 return;
964 free_fid(f);
965 np_clunk(hdr->tag);
968 static void
969 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
971 uint16_t oldtag;
973 /*
974 * We're doing only synchronous I/O. Tflush is implemented
975 * only because it's illegal to reply with a Rerror.
976 */
978 /* oldtag[2] */
979 if (len != sizeof(oldtag)) {
980 log_warnx("Tflush with the wrong size: got %zu want %zu",
981 len, sizeof(oldtag));
982 client_send_listener(IMSG_CLOSE, NULL, 0);
983 client_shutdown();
984 return;
987 np_flush(hdr->tag);
990 static void
991 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
993 struct stat sb;
994 struct dir *dir;
995 struct qid wqid[MAXWELEM] = {0};
996 struct fid *f, *nf;
997 uint32_t fid, newfid;
998 uint16_t nwname;
999 int fd, oldfd, no, nwqid = 0;
1000 char wnam[PATH_MAX];
1002 if (!NPREAD32("fid", &fid, &data, &len) ||
1003 !NPREAD32("newfid", &newfid, &data, &len) ||
1004 !NPREAD16("nwname", &nwname, &data, &len))
1005 goto err;
1007 if (nwname > MAXWELEM) {
1008 log_warnx("Twalk: more than %d path elements: %d",
1009 MAXWELEM, nwname);
1010 goto err;
1013 if ((f = fid_by_id(fid)) == NULL) {
1014 np_error(hdr->tag, "invalid fid");
1015 return;
1018 if (f->fd != -1) {
1019 np_error(hdr->tag, "fid already opened for I/O");
1020 return;
1023 if (fid == newfid)
1024 nf = f;
1025 else if ((nf = fid_by_id(newfid)) != NULL) {
1026 np_error(hdr->tag, "newfid already in use");
1027 return;
1028 } else
1029 nf = NULL;
1031 /* special case: fid duplication */
1032 if (nwname == 0) {
1034 * TODO: should we forbid fids duplication when fid ==
1035 * newfid?
1037 if (nf == NULL &&
1038 (nf = new_fid(f->dir, newfid, f->fpath, &f->qid)) == NULL)
1039 fatal("new_fid duplication");
1041 np_walk(hdr->tag, 0, NULL);
1042 return;
1045 if (!(f->qid.type & QTDIR)) {
1046 np_error(hdr->tag, "fid doesn't represent a directory");
1047 return;
1050 oldfd = f->dir->fd;
1052 for (nwqid = 0; nwqid < nwname; nwqid++) {
1053 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1054 case READSTRERR:
1055 goto err;
1056 case READSTRTRUNC:
1057 np_error(hdr->tag, "wname too long");
1058 return;
1061 if (*wnam == '\0' ||
1062 strchr(wnam, '/') != NULL ||
1063 !strcmp(wnam, ".")) {
1064 errno = EINVAL;
1065 goto cantopen;
1068 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1069 errno != ENOTDIR)
1070 goto cantopen;
1072 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1073 (fd != -1 && fstat(fd, &sb) == -1))
1074 goto cantopen;
1076 qid_update_from_sb(&wqid[nwqid], &sb);
1078 /* reached a file but we still have other components */
1079 if (fd == -1 && nwqid+1 < nwname)
1080 goto cantopen;
1082 /* reached the end and found a file */
1083 if (fd == -1 && nwqid+1 == nwname)
1084 continue;
1086 if (oldfd != f->dir->fd)
1087 close(oldfd);
1088 oldfd = fd;
1092 * If fd is -1 we've reached a file, otherwise we've just
1093 * reached another directory. We must pay attention to what
1094 * file descriptor we use to create the dir, because if we've
1095 * reached a file and oldfd is f->dir->fd then we *must* share
1096 * the same dir (it was a walk of one path from a directory to a
1097 * file, otherwise fun is bound to happen as soon as the client
1098 * closes the fid for the directory but keeps the one for the
1099 * file.
1101 if (fd == -1 && oldfd == f->dir->fd)
1102 dir = f->dir;
1103 else if (fd == -1)
1104 dir = new_dir(oldfd);
1105 else
1106 dir = new_dir(fd);
1108 if (dir == NULL)
1109 fatal("new_dir");
1111 if (nf == NULL) {
1112 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1113 fatal("new fid");
1114 } else {
1115 /* update the dir */
1116 dir_decref(nf->dir);
1117 nf->dir = dir_incref(dir);
1120 np_walk(hdr->tag, nwqid, wqid);
1121 return;
1123 cantopen:
1124 if (oldfd != f->dir->fd)
1125 close(oldfd);
1126 no = errno;
1127 if (nwqid == 0)
1128 np_error(hdr->tag, strerror(no));
1129 else
1130 np_walk(hdr->tag, nwqid, wqid);
1131 return;
1133 err:
1134 client_send_listener(IMSG_CLOSE, NULL, 0);
1135 client_shutdown();
1138 static inline int
1139 npmode_to_unix(uint8_t mode, int *flags)
1141 switch (mode & 0x0F) {
1142 case KOREAD:
1143 *flags = O_RDONLY;
1144 break;
1145 case KOWRITE:
1146 *flags = O_WRONLY;
1147 break;
1148 case KORDWR:
1149 *flags = O_RDWR;
1150 break;
1151 case KOEXEC:
1152 log_warnx("tried to open something with KOEXEC");
1153 /* fallthrough */
1154 default:
1155 return -1;
1158 if (mode & KOTRUNC)
1159 *flags |= O_TRUNC;
1160 if (mode & KORCLOSE)
1161 *flags |= O_CLOEXEC;
1163 return 0;
1166 static void
1167 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1169 struct stat sb;
1170 struct qid qid;
1171 struct fid *f;
1172 uint32_t fid;
1173 uint8_t mode;
1174 const char *path;
1176 /* fid[4] mode[1] */
1177 if (!NPREAD32("fid", &fid, &data, &len) ||
1178 !NPREAD8("mode", &mode, &data, &len)) {
1179 client_send_listener(IMSG_CLOSE, NULL, 0);
1180 client_shutdown();
1181 return;
1184 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1185 np_error(hdr->tag, "invalid fid");
1186 return;
1189 if (npmode_to_unix(mode, &f->iomode) == -1) {
1190 np_error(hdr->tag, "invalid mode");
1191 return;
1194 path = f->fpath;
1195 if (f->qid.type & QTDIR)
1196 path = ".";
1198 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1199 np_error(hdr->tag, strerror(errno));
1200 return;
1203 if (fstat(f->fd, &sb) == -1)
1204 fatal("fstat");
1206 if (S_ISDIR(sb.st_mode)) {
1207 if ((f->d = fdopendir(f->fd)) == NULL) {
1208 np_errno(hdr->tag);
1209 close(f->fd);
1210 f->fd = -1;
1211 return;
1214 if ((f->evb = evbuffer_new()) == NULL) {
1215 np_errno(hdr->tag);
1216 closedir(f->d);
1217 f->d = NULL;
1218 f->fd = -1;
1222 f->offset = 0;
1224 qid_update_from_sb(&qid, &sb);
1225 np_open(hdr->tag, &qid, sb.st_blksize);
1228 static void
1229 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1231 struct stat sb;
1232 struct qid qid;
1233 struct fid *f;
1234 uint32_t fid, perm;
1235 uint8_t mode;
1236 char name[PATH_MAX];
1238 /* fid[4] name[s] perm[4] mode[1] */
1239 if (!NPREAD32("fid", &fid, &data, &len))
1240 goto err;
1241 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1242 case READSTRERR:
1243 goto err;
1244 case READSTRTRUNC:
1245 np_error(hdr->tag, "name too long");
1246 return;
1248 if (!NPREAD32("perm", &perm, &data, &len) ||
1249 !NPREAD8("mode", &mode, &data, &len))
1250 goto err;
1252 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1253 strchr(name, '/') != NULL) {
1254 np_error(hdr->tag, "invalid name");
1255 return;
1258 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1259 np_error(hdr->tag, "invalid fid");
1260 return;
1263 if (!(f->qid.type & QTDIR)) {
1264 np_error(hdr->tag, "fid doesn't identify a directory");
1265 return;
1268 if (npmode_to_unix(mode, &f->iomode) == -1) {
1269 np_error(hdr->tag, "invalid mode");
1270 return;
1273 if (f->iomode & O_RDONLY) {
1274 np_error(hdr->tag, "can't create a read-only file");
1275 return;
1278 /* TODO: parse the mode */
1280 if (perm & 0x80000000) {
1281 /* create a directory */
1282 f->fd = mkdirat(f->dir->fd, name, 0755);
1283 } else {
1284 /* create a file */
1285 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1286 0644);
1289 if (f->fd == -1) {
1290 np_errno(hdr->tag);
1291 return;
1294 if (fstat(f->fd, &sb) == -1)
1295 fatal("fstat");
1297 if (S_ISDIR(sb.st_mode)) {
1298 if ((f->d = fdopendir(f->fd)) == NULL) {
1299 np_errno(hdr->tag);
1300 close(f->fd);
1301 f->fd = -1;
1302 return;
1305 if ((f->evb = evbuffer_new()) == NULL) {
1306 np_errno(hdr->tag);
1307 closedir(f->d);
1308 f->d = NULL;
1309 f->fd = -1;
1313 f->offset = 0;
1315 qid_update_from_sb(&qid, &sb);
1316 np_create(hdr->tag, &qid, sb.st_blksize);
1318 return;
1320 err:
1321 client_send_listener(IMSG_CLOSE, NULL, 0);
1322 client_shutdown();
1325 static inline void
1326 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1328 struct qid qid;
1329 const char *uid, *gid, *muid;
1330 size_t tot;
1331 uint16_t namlen, uidlen, gidlen, ulen;
1333 qid_update_from_sb(&qid, sb);
1335 /* TODO: fill these fields */
1336 uid = "";
1337 gid = "";
1338 muid = "";
1340 namlen = strlen(fname);
1341 uidlen = strlen(uid);
1342 gidlen = strlen(gid);
1343 ulen = strlen(muid);
1345 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1346 if (tot > UINT32_MAX) {
1347 log_warnx("stat info for dir entry %s would overflow",
1348 fname);
1349 return;
1352 np_write16(evb, tot); /* size[2] */
1353 np_write16(evb, sb->st_rdev); /* type[2] */
1354 np_write32(evb, sb->st_dev); /* dev[4] */
1355 np_qid(evb, &qid); /* qid[13] */
1357 /* XXX: translate? */
1358 np_write32(evb, sb->st_mode); /* mode[4] */
1360 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1361 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1362 np_write64(evb, sb->st_size); /* length[8] */
1363 np_string(evb, namlen, fname); /* name[s] */
1364 np_string(evb, uidlen, uid); /* uid[s] */
1365 np_string(evb, gidlen, gid); /* gid[s] */
1366 np_string(evb, ulen, muid); /* muid[s] */
1369 static void
1370 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1372 struct fid *f;
1373 ssize_t r;
1374 uint64_t off;
1375 uint32_t fid, count;
1376 char buf[2048];
1378 /* fid[4] offset[8] count[4] */
1379 if (!NPREAD32("fid", &fid, &data, &len) ||
1380 !NPREAD64("offset", &off, &data, &len) ||
1381 !NPREAD32("count", &count, &data, &len)) {
1382 client_send_listener(IMSG_CLOSE, NULL, 0);
1383 client_shutdown();
1384 return;
1387 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1388 np_error(hdr->tag, "invalid fid");
1389 return;
1392 if (TYPE_OVERFLOW(off_t, off)) {
1393 log_warnx("unexpected off_t size");
1394 np_error(hdr->tag, "invalid offset");
1395 return;
1398 if (f->d == NULL) {
1399 /* read a file */
1400 r = pread(f->fd, buf, sizeof(buf), (off_t)off);
1401 if (r == -1)
1402 np_errno(hdr->tag);
1403 else
1404 np_read(hdr->tag, r, buf);
1405 } else {
1406 if (off == 0 && f->offset != 0) {
1407 rewinddir(f->d);
1408 f->offset = 0;
1409 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1412 if (off != f->offset) {
1413 np_error(hdr->tag, "can't seek in directories");
1414 return;
1417 while (EVBUFFER_LENGTH(f->evb) < count) {
1418 struct dirent *d;
1419 struct stat sb;
1421 if ((d = readdir(f->d)) == NULL)
1422 break;
1423 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1424 warn("fstatat");
1425 continue;
1427 serialize_stat(d->d_name, &sb, f->evb);
1430 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1431 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1432 evbuffer_drain(f->evb, count);
1434 f->offset += count;
1438 static void
1439 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1441 struct fid *f;
1442 ssize_t r;
1443 uint64_t off;
1444 uint32_t fid, count;
1446 /* fid[4] offset[8] count[4] data[count] */
1447 if (!NPREAD32("fid", &fid, &data, &len) ||
1448 !NPREAD64("off", &off, &data, &len) ||
1449 !NPREAD32("count", &count, &data, &len) ||
1450 len != count) {
1451 client_send_listener(IMSG_CLOSE, NULL, 0);
1452 client_shutdown();
1453 return;
1456 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1457 np_error(hdr->tag, "invalid fid");
1458 return;
1461 if (!(f->iomode & O_WRONLY) &&
1462 !(f->iomode & O_RDWR)) {
1463 np_error(hdr->tag, "fid not opened for writing");
1464 return;
1467 if (TYPE_OVERFLOW(off_t, off)) {
1468 log_warnx("unexpected off_t size");
1469 np_error(hdr->tag, "invalid offset");
1470 return;
1473 if ((r = pwrite(f->fd, data, len, off)) == -1)
1474 np_errno(hdr->tag);
1475 else
1476 np_write(hdr->tag, r);
1479 static void
1480 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1482 struct evbuffer *evb;
1483 struct stat sb;
1484 struct fid *f;
1485 int r;
1486 uint32_t fid;
1488 /* fid[4] */
1489 if (!NPREAD32("fid", &fid, &data, &len)) {
1490 client_send_listener(IMSG_CLOSE, NULL, 0);
1491 client_shutdown();
1492 return;
1496 * plan9' stat(9P) is not clear on whether the stat is allowed
1497 * on opened fids or not.
1499 if ((f = fid_by_id(fid)) == NULL) {
1500 np_error(hdr->tag, "invalid fid");
1501 return;
1504 if ((evb = evbuffer_new()) == NULL)
1505 fatal("evbuffer_new");
1507 if (f->fd != -1)
1508 r = fstat(f->fd, &sb);
1509 else
1510 r = fstatat(f->dir->fd, f->fpath, &sb, 0);
1512 if (r == -1) {
1513 np_errno(hdr->tag);
1514 evbuffer_free(evb);
1515 return;
1518 serialize_stat(f->fpath, &sb, evb);
1519 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1520 evbuffer_free(evb);
1523 static void
1524 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1526 struct fid *f;
1527 uint32_t fid;
1528 int r;
1529 char dirpath[PATH_MAX + 3];
1531 /* fid[4] */
1532 if (!NPREAD32("fid", &fid, &data, &len)) {
1533 client_send_listener(IMSG_CLOSE, NULL, 0);
1534 client_shutdown();
1535 return;
1538 if ((f = fid_by_id(fid)) == NULL) {
1539 np_error(hdr->tag, "invalid fid");
1540 return;
1543 if (f->qid.type & QTDIR) { /* directory */
1544 strlcpy(dirpath, "../", sizeof(dirpath));
1545 strlcat(dirpath, f->fpath, sizeof(dirpath));
1546 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1547 } else /* file */
1548 r = unlinkat(f->dir->fd, f->fpath, 0);
1550 if (r == -1)
1551 np_errno(hdr->tag);
1552 else
1553 np_remove(hdr->tag);
1555 free_fid(f);
1558 static void
1559 handle_message(struct imsg *imsg, size_t len)
1561 struct msg {
1562 uint8_t type;
1563 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1564 } msgs[] = {
1565 {Tversion, tversion},
1566 {Tattach, tattach},
1567 {Tclunk, tclunk},
1568 {Tflush, tflush},
1569 {Twalk, twalk},
1570 {Topen, topen},
1571 {Tcreate, tcreate},
1572 {Tread, tread},
1573 {Twrite, twrite},
1574 {Tstat, tstat},
1575 {Tremove, tremove},
1577 struct np_msg_header hdr;
1578 size_t i;
1579 uint8_t *data;
1581 #if DEBUG_PACKETS
1582 hexdump("incoming packet", imsg->data, len);
1583 #endif
1585 parse_message(imsg->data, len, &hdr, &data);
1586 len -= HEADERSIZE;
1588 log_debug("got request: len=%d type=%d[%s] tag=%d",
1589 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1591 if (!handshaked && hdr.type != Tversion) {
1592 client_send_listener(IMSG_CLOSE, NULL, 0);
1593 client_shutdown();
1594 return;
1597 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1598 if (msgs[i].type != hdr.type)
1599 continue;
1601 msgs[i].fn(&hdr, data, len);
1602 return;
1605 np_error(hdr.tag, "Not supported.");