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 if (sizeof(count) + count + HEADERSIZE >= msize) {
683 np_error(tag, "Rread would overflow");
684 return;
687 np_header(sizeof(count) + count, Rread, tag);
688 np_write32(evb, count);
689 np_writebuf(evb, count, data);
690 do_send();
693 static void
694 np_write(uint16_t tag, uint32_t count)
696 np_header(sizeof(count), Rwrite, tag);
697 np_write32(evb, count);
698 do_send();
701 static void
702 np_stat(uint16_t tag, uint32_t count, void *data)
704 if (sizeof(count) + count + HEADERSIZE >= msize) {
705 np_error(tag, "Rstat would overflow");
706 return;
709 np_header(count, Rstat, tag);
710 np_writebuf(evb, count, data);
711 do_send();
714 static void
715 np_remove(uint16_t tag)
717 np_header(0, Rremove, tag);
718 do_send();
721 static void
722 np_error(uint16_t tag, const char *errstr)
724 uint16_t l;
726 l = strlen(errstr);
728 np_header(sizeof(l) + l, Rerror, tag);
729 np_string(evb, l, errstr);
730 do_send();
733 static void
734 np_errno(uint16_t tag)
736 int saved_errno;
737 char buf[NL_TEXTMAX] = {0};
739 saved_errno = errno;
741 strerror_r(errno, buf, sizeof(buf));
742 np_error(tag, buf);
744 errno = saved_errno;
747 static int
748 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
749 size_t *len)
751 if (*len < sizeof(*dst)) {
752 log_warnx("%s: wanted %zu bytes for the %s field but only "
753 "%zu are available.", t, sizeof(*dst), f, *len);
754 return -1;
757 memcpy(dst, *src, sizeof(*dst));
758 *src += sizeof(*dst);
759 *len -= sizeof(*dst);
761 return 1;
764 static int
765 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
766 size_t *len)
768 if (*len < sizeof(*dst)) {
769 log_warnx("%s: wanted %zu bytes for the %s field but only "
770 "%zu are available.", t, sizeof(*dst), f, *len);
771 return -1;
774 memcpy(dst, *src, sizeof(*dst));
775 *src += sizeof(*dst);
776 *len -= sizeof(*dst);
777 *dst = le16toh(*dst);
779 return 1;
782 static int
783 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
784 size_t *len)
786 if (*len < sizeof(*dst)) {
787 log_warnx("%s: wanted %zu bytes for the %s field but only "
788 "%zu are available.", t, sizeof(*dst), f, *len);
789 return -1;
792 memcpy(dst, *src, sizeof(*dst));
793 *src += sizeof(*dst);
794 *len -= sizeof(*dst);
795 *dst = le32toh(*dst);
797 return 1;
800 static int
801 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
802 size_t *len)
804 if (*len < sizeof(*dst)) {
805 log_warnx("%s: wanted %zu bytes for the %s field but only "
806 "%zu are available.", t, sizeof(*dst), f, *len);
807 return -1;
810 memcpy(dst, *src, sizeof(*dst));
811 *src += sizeof(*dst);
812 *len -= sizeof(*dst);
813 *dst = le64toh(*dst);
815 return 1;
818 static int
819 np_readstr(const char *t, const char *f, char *res, size_t reslen,
820 const uint8_t **src, size_t *len)
822 uint16_t sl;
823 char buf[32];
825 strlcpy(buf, f, sizeof(buf));
826 strlcat(buf, "-len", sizeof(buf));
828 if (!np_read16(t, buf, &sl, src, len))
829 return READSTRERR;
831 if (*len < sl) {
832 log_warnx("%s: wanted %d bytes for the %s field but only "
833 "%zu are available.", t, sl, f, *len);
834 return READSTRERR;
837 if (*len > reslen-1)
838 return READSTRTRUNC;
840 memcpy(res, *src, sl);
841 res[sl] = '\0';
842 *src += sl;
843 *len -= sl;
845 return 0;
848 static void
849 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
851 char *dot, version[32];
853 if (handshaked)
854 goto err;
856 /* msize[4] version[s] */
857 if (!NPREAD32("msize", &msize, &data, &len))
858 goto err;
860 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
861 case READSTRERR:
862 goto err;
863 case READSTRTRUNC:
864 log_warnx("9P version string too long, truncated");
865 goto mismatch;
868 if ((dot = strchr(version, '.')) != NULL)
869 *dot = '\0';
871 if (strcmp(version, VERSION9P) != 0 ||
872 msize == 0)
873 goto mismatch;
875 /* version matched */
876 handshaked = 1;
877 msize = MIN(msize, CLIENT_MSIZE);
878 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
879 np_version(hdr->tag, msize, VERSION9P);
880 return;
882 mismatch:
883 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
884 version);
885 np_version(hdr->tag, MSIZE9P, "unknown");
886 return;
888 err:
889 client_send_listener(IMSG_CLOSE, NULL, 0);
890 client_shutdown();
893 static void
894 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
896 struct dir *dir;
897 struct fid *f;
898 uint32_t fid, afid;
899 int fd;
900 char aname[PATH_MAX];
902 /* fid[4] afid[4] uname[s] aname[s] */
904 if (!NPREAD32("fid", &fid, &data, &len) ||
905 !NPREAD32("afid", &afid, &data, &len))
906 goto err;
908 /* read the uname but don't actually use it */
909 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
910 case READSTRERR:
911 goto err;
912 case READSTRTRUNC:
913 np_error(hdr->tag, "name too long");
914 return;
917 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
918 case READSTRERR:
919 goto err;
920 case READSTRTRUNC:
921 np_error(hdr->tag, "name too long");
922 return;
925 if (fid_by_id(fid) != NULL || afid != NOFID) {
926 np_error(hdr->tag, "invalid fid or afid");
927 return;
930 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
931 goto fail;
933 if ((dir = new_dir(fd)) == NULL)
934 goto fail;
936 log_debug("attached %s to %d", aname, fid);
938 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
939 dir_decref(dir);
940 goto fail;
943 np_attach(hdr->tag, &f->qid);
944 return;
946 fail:
947 np_errno(hdr->tag);
948 log_warn("failed to attach %s", aname);
949 return;
951 err:
952 client_send_listener(IMSG_CLOSE, NULL, 0);
953 client_shutdown();
956 static void
957 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
959 struct fid *f;
960 uint32_t fid;
962 /* fid[4] */
963 if (!NPREAD32("fid", &fid, &data, &len)) {
964 client_send_listener(IMSG_CLOSE, NULL, 0);
965 client_shutdown();
966 return;
969 if ((f = fid_by_id(fid)) == NULL) {
970 np_error(hdr->tag, "invalid fid");
971 return;
974 free_fid(f);
975 np_clunk(hdr->tag);
978 static void
979 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
981 uint16_t oldtag;
983 /*
984 * We're doing only synchronous I/O. Tflush is implemented
985 * only because it's illegal to reply with a Rerror.
986 */
988 /* oldtag[2] */
989 if (len != sizeof(oldtag)) {
990 log_warnx("Tflush with the wrong size: got %zu want %zu",
991 len, sizeof(oldtag));
992 client_send_listener(IMSG_CLOSE, NULL, 0);
993 client_shutdown();
994 return;
997 np_flush(hdr->tag);
1000 static void
1001 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1003 struct stat sb;
1004 struct dir *dir;
1005 struct qid wqid[MAXWELEM] = {0};
1006 struct fid *f, *nf;
1007 uint32_t fid, newfid;
1008 uint16_t nwname;
1009 int fd, oldfd, no, nwqid = 0;
1010 char wnam[PATH_MAX];
1012 if (!NPREAD32("fid", &fid, &data, &len) ||
1013 !NPREAD32("newfid", &newfid, &data, &len) ||
1014 !NPREAD16("nwname", &nwname, &data, &len))
1015 goto err;
1017 if (nwname > MAXWELEM) {
1018 log_warnx("Twalk: more than %d path elements: %d",
1019 MAXWELEM, nwname);
1020 goto err;
1023 if ((f = fid_by_id(fid)) == NULL) {
1024 np_error(hdr->tag, "invalid fid");
1025 return;
1028 if (f->fd != -1) {
1029 np_error(hdr->tag, "fid already opened for I/O");
1030 return;
1033 if (fid == newfid)
1034 nf = f;
1035 else if ((nf = fid_by_id(newfid)) != NULL) {
1036 np_error(hdr->tag, "newfid already in use");
1037 return;
1038 } else
1039 nf = NULL;
1041 /* special case: fid duplication */
1042 if (nwname == 0) {
1044 * TODO: should we forbid fids duplication when fid ==
1045 * newfid?
1047 if (nf == NULL &&
1048 (nf = new_fid(f->dir, newfid, f->fpath, &f->qid)) == NULL)
1049 fatal("new_fid duplication");
1051 np_walk(hdr->tag, 0, NULL);
1052 return;
1055 if (!(f->qid.type & QTDIR)) {
1056 np_error(hdr->tag, "fid doesn't represent a directory");
1057 return;
1060 oldfd = f->dir->fd;
1062 for (nwqid = 0; nwqid < nwname; nwqid++) {
1063 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1064 case READSTRERR:
1065 goto err;
1066 case READSTRTRUNC:
1067 np_error(hdr->tag, "wname too long");
1068 return;
1071 if (*wnam == '\0' ||
1072 strchr(wnam, '/') != NULL ||
1073 !strcmp(wnam, ".")) {
1074 errno = EINVAL;
1075 goto cantopen;
1078 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1079 errno != ENOTDIR)
1080 goto cantopen;
1082 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1083 (fd != -1 && fstat(fd, &sb) == -1))
1084 goto cantopen;
1086 qid_update_from_sb(&wqid[nwqid], &sb);
1088 /* reached a file but we still have other components */
1089 if (fd == -1 && nwqid+1 < nwname)
1090 goto cantopen;
1092 /* reached the end and found a file */
1093 if (fd == -1 && nwqid+1 == nwname)
1094 continue;
1096 if (oldfd != f->dir->fd)
1097 close(oldfd);
1098 oldfd = fd;
1102 * If fd is -1 we've reached a file, otherwise we've just
1103 * reached another directory. We must pay attention to what
1104 * file descriptor we use to create the dir, because if we've
1105 * reached a file and oldfd is f->dir->fd then we *must* share
1106 * the same dir (it was a walk of one path from a directory to a
1107 * file, otherwise fun is bound to happen as soon as the client
1108 * closes the fid for the directory but keeps the one for the
1109 * file.
1111 if (fd == -1 && oldfd == f->dir->fd)
1112 dir = f->dir;
1113 else if (fd == -1)
1114 dir = new_dir(oldfd);
1115 else
1116 dir = new_dir(fd);
1118 if (dir == NULL)
1119 fatal("new_dir");
1121 if (nf == NULL) {
1122 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1123 fatal("new fid");
1124 } else {
1125 /* update the dir */
1126 dir_decref(nf->dir);
1127 nf->dir = dir_incref(dir);
1130 np_walk(hdr->tag, nwqid, wqid);
1131 return;
1133 cantopen:
1134 if (oldfd != f->dir->fd)
1135 close(oldfd);
1136 no = errno;
1137 if (nwqid == 0)
1138 np_error(hdr->tag, strerror(no));
1139 else
1140 np_walk(hdr->tag, nwqid, wqid);
1141 return;
1143 err:
1144 client_send_listener(IMSG_CLOSE, NULL, 0);
1145 client_shutdown();
1148 static inline int
1149 npmode_to_unix(uint8_t mode, int *flags)
1151 switch (mode & 0x0F) {
1152 case KOREAD:
1153 *flags = O_RDONLY;
1154 break;
1155 case KOWRITE:
1156 *flags = O_WRONLY;
1157 break;
1158 case KORDWR:
1159 *flags = O_RDWR;
1160 break;
1161 case KOEXEC:
1162 log_warnx("tried to open something with KOEXEC");
1163 /* fallthrough */
1164 default:
1165 return -1;
1168 if (mode & KOTRUNC)
1169 *flags |= O_TRUNC;
1170 if (mode & KORCLOSE)
1171 *flags |= O_CLOEXEC;
1173 return 0;
1176 static void
1177 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1179 struct stat sb;
1180 struct qid qid;
1181 struct fid *f;
1182 uint32_t fid;
1183 uint8_t mode;
1184 const char *path;
1186 /* fid[4] mode[1] */
1187 if (!NPREAD32("fid", &fid, &data, &len) ||
1188 !NPREAD8("mode", &mode, &data, &len)) {
1189 client_send_listener(IMSG_CLOSE, NULL, 0);
1190 client_shutdown();
1191 return;
1194 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1195 np_error(hdr->tag, "invalid fid");
1196 return;
1199 if (npmode_to_unix(mode, &f->iomode) == -1) {
1200 np_error(hdr->tag, "invalid mode");
1201 return;
1204 path = f->fpath;
1205 if (f->qid.type & QTDIR)
1206 path = ".";
1208 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1209 np_error(hdr->tag, strerror(errno));
1210 return;
1213 if (fstat(f->fd, &sb) == -1)
1214 fatal("fstat");
1216 if (S_ISDIR(sb.st_mode)) {
1217 if ((f->d = fdopendir(f->fd)) == NULL) {
1218 np_errno(hdr->tag);
1219 close(f->fd);
1220 f->fd = -1;
1221 return;
1224 if ((f->evb = evbuffer_new()) == NULL) {
1225 np_errno(hdr->tag);
1226 closedir(f->d);
1227 f->d = NULL;
1228 f->fd = -1;
1232 f->offset = 0;
1234 qid_update_from_sb(&qid, &sb);
1235 np_open(hdr->tag, &qid, sb.st_blksize);
1238 static void
1239 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1241 struct stat sb;
1242 struct qid qid;
1243 struct fid *f;
1244 uint32_t fid, perm;
1245 uint8_t mode;
1246 char name[PATH_MAX];
1248 /* fid[4] name[s] perm[4] mode[1] */
1249 if (!NPREAD32("fid", &fid, &data, &len))
1250 goto err;
1251 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1252 case READSTRERR:
1253 goto err;
1254 case READSTRTRUNC:
1255 np_error(hdr->tag, "name too long");
1256 return;
1258 if (!NPREAD32("perm", &perm, &data, &len) ||
1259 !NPREAD8("mode", &mode, &data, &len))
1260 goto err;
1262 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1263 strchr(name, '/') != NULL) {
1264 np_error(hdr->tag, "invalid name");
1265 return;
1268 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1269 np_error(hdr->tag, "invalid fid");
1270 return;
1273 if (!(f->qid.type & QTDIR)) {
1274 np_error(hdr->tag, "fid doesn't identify a directory");
1275 return;
1278 if (npmode_to_unix(mode, &f->iomode) == -1) {
1279 np_error(hdr->tag, "invalid mode");
1280 return;
1283 if (f->iomode & O_RDONLY) {
1284 np_error(hdr->tag, "can't create a read-only file");
1285 return;
1288 /* TODO: parse the mode */
1290 if (perm & 0x80000000) {
1291 /* create a directory */
1292 f->fd = mkdirat(f->dir->fd, name, 0755);
1293 } else {
1294 /* create a file */
1295 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1296 0644);
1299 if (f->fd == -1) {
1300 np_errno(hdr->tag);
1301 return;
1304 if (fstat(f->fd, &sb) == -1)
1305 fatal("fstat");
1307 if (S_ISDIR(sb.st_mode)) {
1308 if ((f->d = fdopendir(f->fd)) == NULL) {
1309 np_errno(hdr->tag);
1310 close(f->fd);
1311 f->fd = -1;
1312 return;
1315 if ((f->evb = evbuffer_new()) == NULL) {
1316 np_errno(hdr->tag);
1317 closedir(f->d);
1318 f->d = NULL;
1319 f->fd = -1;
1323 f->offset = 0;
1325 qid_update_from_sb(&qid, &sb);
1326 np_create(hdr->tag, &qid, sb.st_blksize);
1328 return;
1330 err:
1331 client_send_listener(IMSG_CLOSE, NULL, 0);
1332 client_shutdown();
1335 static inline void
1336 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1338 struct qid qid;
1339 const char *uid, *gid, *muid;
1340 size_t tot;
1341 uint16_t namlen, uidlen, gidlen, ulen;
1343 qid_update_from_sb(&qid, sb);
1345 /* TODO: fill these fields */
1346 uid = "";
1347 gid = "";
1348 muid = "";
1350 namlen = strlen(fname);
1351 uidlen = strlen(uid);
1352 gidlen = strlen(gid);
1353 ulen = strlen(muid);
1355 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1356 if (tot > UINT32_MAX) {
1357 log_warnx("stat info for dir entry %s would overflow",
1358 fname);
1359 return;
1362 np_write16(evb, tot); /* size[2] */
1363 np_write16(evb, sb->st_rdev); /* type[2] */
1364 np_write32(evb, sb->st_dev); /* dev[4] */
1365 np_qid(evb, &qid); /* qid[13] */
1367 /* XXX: translate? */
1368 np_write32(evb, sb->st_mode); /* mode[4] */
1370 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1371 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1372 np_write64(evb, sb->st_size); /* length[8] */
1373 np_string(evb, namlen, fname); /* name[s] */
1374 np_string(evb, uidlen, uid); /* uid[s] */
1375 np_string(evb, gidlen, gid); /* gid[s] */
1376 np_string(evb, ulen, muid); /* muid[s] */
1379 static void
1380 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1382 struct fid *f;
1383 ssize_t r;
1384 size_t howmuch;
1385 uint64_t off;
1386 uint32_t fid, count;
1387 char buf[2048];
1389 /* fid[4] offset[8] count[4] */
1390 if (!NPREAD32("fid", &fid, &data, &len) ||
1391 !NPREAD64("offset", &off, &data, &len) ||
1392 !NPREAD32("count", &count, &data, &len)) {
1393 client_send_listener(IMSG_CLOSE, NULL, 0);
1394 client_shutdown();
1395 return;
1398 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1399 np_error(hdr->tag, "invalid fid");
1400 return;
1403 if (TYPE_OVERFLOW(off_t, off)) {
1404 log_warnx("unexpected off_t size");
1405 np_error(hdr->tag, "invalid offset");
1406 return;
1409 if (f->d == NULL) {
1410 /* read a file */
1411 howmuch = MIN(sizeof(buf), count);
1412 r = pread(f->fd, buf, howmuch, (off_t)off);
1413 if (r == -1)
1414 np_errno(hdr->tag);
1415 else
1416 np_read(hdr->tag, r, buf);
1417 } else {
1418 if (off == 0 && f->offset != 0) {
1419 rewinddir(f->d);
1420 f->offset = 0;
1421 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1424 if (off != f->offset) {
1425 np_error(hdr->tag, "can't seek in directories");
1426 return;
1429 while (EVBUFFER_LENGTH(f->evb) < count) {
1430 struct dirent *d;
1431 struct stat sb;
1433 if ((d = readdir(f->d)) == NULL)
1434 break;
1435 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1436 warn("fstatat");
1437 continue;
1439 serialize_stat(d->d_name, &sb, f->evb);
1442 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1443 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1444 evbuffer_drain(f->evb, count);
1446 f->offset += count;
1450 static void
1451 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1453 struct fid *f;
1454 ssize_t r;
1455 uint64_t off;
1456 uint32_t fid, count;
1458 /* fid[4] offset[8] count[4] data[count] */
1459 if (!NPREAD32("fid", &fid, &data, &len) ||
1460 !NPREAD64("off", &off, &data, &len) ||
1461 !NPREAD32("count", &count, &data, &len) ||
1462 len != count) {
1463 client_send_listener(IMSG_CLOSE, NULL, 0);
1464 client_shutdown();
1465 return;
1468 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1469 np_error(hdr->tag, "invalid fid");
1470 return;
1473 if (!(f->iomode & O_WRONLY) &&
1474 !(f->iomode & O_RDWR)) {
1475 np_error(hdr->tag, "fid not opened for writing");
1476 return;
1479 if (TYPE_OVERFLOW(off_t, off)) {
1480 log_warnx("unexpected off_t size");
1481 np_error(hdr->tag, "invalid offset");
1482 return;
1485 if ((r = pwrite(f->fd, data, len, off)) == -1)
1486 np_errno(hdr->tag);
1487 else
1488 np_write(hdr->tag, r);
1491 static void
1492 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1494 struct evbuffer *evb;
1495 struct stat sb;
1496 struct fid *f;
1497 int r;
1498 uint32_t fid;
1500 /* fid[4] */
1501 if (!NPREAD32("fid", &fid, &data, &len)) {
1502 client_send_listener(IMSG_CLOSE, NULL, 0);
1503 client_shutdown();
1504 return;
1508 * plan9' stat(9P) is not clear on whether the stat is allowed
1509 * on opened fids or not. We're allowing stat regardless of the
1510 * status of the fid.
1513 if ((f = fid_by_id(fid)) == NULL) {
1514 np_error(hdr->tag, "invalid fid");
1515 return;
1518 if ((evb = evbuffer_new()) == NULL)
1519 fatal("evbuffer_new");
1521 if (f->fd != -1)
1522 r = fstat(f->fd, &sb);
1523 else if (f->qid.type & QTDIR)
1524 r = fstat(f->dir->fd, &sb);
1525 else
1526 r = fstatat(f->dir->fd, f->fpath, &sb, 0);
1528 if (r == -1) {
1529 np_errno(hdr->tag);
1530 evbuffer_free(evb);
1531 return;
1534 serialize_stat(f->fpath, &sb, evb);
1535 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1536 evbuffer_free(evb);
1539 static void
1540 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1542 struct fid *f;
1543 uint32_t fid;
1544 int r;
1545 char dirpath[PATH_MAX + 3];
1547 /* fid[4] */
1548 if (!NPREAD32("fid", &fid, &data, &len)) {
1549 client_send_listener(IMSG_CLOSE, NULL, 0);
1550 client_shutdown();
1551 return;
1554 if ((f = fid_by_id(fid)) == NULL) {
1555 np_error(hdr->tag, "invalid fid");
1556 return;
1559 if (f->qid.type & QTDIR) { /* directory */
1560 strlcpy(dirpath, "../", sizeof(dirpath));
1561 strlcat(dirpath, f->fpath, sizeof(dirpath));
1562 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1563 } else /* file */
1564 r = unlinkat(f->dir->fd, f->fpath, 0);
1566 if (r == -1)
1567 np_errno(hdr->tag);
1568 else
1569 np_remove(hdr->tag);
1571 free_fid(f);
1574 static void
1575 handle_message(struct imsg *imsg, size_t len)
1577 struct msg {
1578 uint8_t type;
1579 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1580 } msgs[] = {
1581 {Tversion, tversion},
1582 {Tattach, tattach},
1583 {Tclunk, tclunk},
1584 {Tflush, tflush},
1585 {Twalk, twalk},
1586 {Topen, topen},
1587 {Tcreate, tcreate},
1588 {Tread, tread},
1589 {Twrite, twrite},
1590 {Tstat, tstat},
1591 {Tremove, tremove},
1593 struct np_msg_header hdr;
1594 size_t i;
1595 uint8_t *data;
1597 #if DEBUG_PACKETS
1598 hexdump("incoming packet", imsg->data, len);
1599 #endif
1601 parse_message(imsg->data, len, &hdr, &data);
1602 len -= HEADERSIZE;
1604 log_debug("got request: len=%d type=%d[%s] tag=%d",
1605 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1607 if (!handshaked && hdr.type != Tversion) {
1608 client_send_listener(IMSG_CLOSE, NULL, 0);
1609 client_shutdown();
1610 return;
1613 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1614 if (msgs[i].type != hdr.type)
1615 continue;
1617 msgs[i].fn(&hdr, data, len);
1618 return;
1621 np_error(hdr.tag, "Not supported.");