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 <assert.h>
22 #include <dirent.h>
23 #include <endian.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <pwd.h>
27 #include <signal.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <syslog.h>
31 #include <unistd.h>
33 #include "client.h"
34 #include "kamid.h"
35 #include "log.h"
36 #include "sandbox.h"
37 #include "utils.h"
39 #define DEBUG_PACKETS 0
41 /* straight outta /src/usr.bin/ssh/scp.c */
42 #define TYPE_OVERFLOW(type, val) \
43 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
44 (sizeof(type) == 8 && (val) > INT64_MAX) || \
45 (sizeof(type) != 4 && sizeof(type) != 8))
47 STAILQ_HEAD(qidhead, qid) qids;
48 struct qid {
49 /* definition of a qid */
50 uint64_t path;
51 uint32_t vers;
52 uint8_t type;
54 int refcount;
56 int fd;
57 char fpath[PATH_MAX];
59 STAILQ_ENTRY(qid) entries;
60 };
62 STAILQ_HEAD(fidhead, fid) fids;
63 struct fid {
64 uint32_t fid;
66 /*
67 * 0 when the fid was not yet opened for I/O otherwise set to
68 * the flags passed to open(2). O_CLOEXEC means ORCLOSE, that
69 * is to unlink the file upon Tclunk.
70 */
71 int iomode;
73 /*
74 * if iomode is set, this fid was opened and fd represents its
75 * file descriptor.
76 */
77 int fd;
78 DIR *dir;
79 struct evbuffer *evb;
81 /*
82 * expected offset for Tread against a directory.
83 */
84 uint64_t offset;
86 struct qid *qid;
87 STAILQ_ENTRY(fid) entries;
88 };
90 static struct imsgev *iev_listener;
91 static struct evbuffer *evb;
92 static uint32_t peerid;
94 static int handshaked;
95 uint32_t msize;
97 static ATTR_DEAD void client_shutdown(void);
98 static void client_sig_handler(int, short, void *);
99 static void client_dispatch_listener(int, short, void *);
100 static void client_privdrop(const char *, const char *);
102 static int client_send_listener(int, const void *, uint16_t);
104 static void qid_update_from_sb(struct qid *, struct stat *);
105 static struct qid *qid_from_fd(int, const char *, struct stat *);
106 static struct qid *qid_incref(struct qid *);
107 static void qid_decref(struct qid *);
109 static struct fid *new_fid(struct qid *, uint32_t);
110 static struct fid *fid_by_id(uint32_t);
111 static void free_fid(struct fid *);
113 static void parse_message(const uint8_t *, size_t,
114 struct np_msg_header *, uint8_t **);
116 static void np_write16(struct evbuffer *, uint16_t);
117 static void np_write32(struct evbuffer *, uint32_t);
118 static void np_write64(struct evbuffer *, uint64_t);
119 static void np_header(uint32_t, uint8_t, uint16_t);
120 static void np_string(struct evbuffer *, uint16_t, const char *);
121 static void np_qid(struct evbuffer *, struct qid *);
122 static void do_send(void);
124 static void np_version(uint16_t, uint32_t, const char *);
125 static void np_attach(uint16_t, struct qid *);
126 static void np_clunk(uint16_t);
127 static void np_flush(uint16_t);
128 static void np_walk(uint16_t, int, struct qid *);
129 static void np_open(uint16_t, struct qid *, uint32_t);
130 static void np_read(uint16_t, uint32_t, void *);
131 static void np_write(uint16_t, uint32_t);
132 static void np_stat(uint16_t, uint32_t, void *);
133 static void np_error(uint16_t, const char *);
134 static void np_errno(uint16_t);
136 static int np_read8(const char *, const char *, uint8_t *,
137 const uint8_t **, size_t *);
138 static int np_read16(const char *, const char *, uint16_t *,
139 const uint8_t **, size_t *);
140 static int np_read32(const char *, const char *, uint32_t *,
141 const uint8_t **, size_t *);
142 static int np_read64(const char *, const char *, uint64_t *,
143 const uint8_t **, size_t *);
145 #define READSTRERR -1
146 #define READSTRTRUNC -2
147 static int np_readstr(const char *, const char *, char *, size_t,
148 const uint8_t **, size_t *);
150 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
151 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
152 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
153 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
155 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
157 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
158 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
159 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
160 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
161 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
162 static void topen(struct np_msg_header *, const uint8_t *, size_t);
163 static void tread(struct np_msg_header *, const uint8_t *, size_t);
164 static void twrite(struct np_msg_header *, const uint8_t *, size_t);
165 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
166 static void handle_message(struct imsg *, size_t);
168 ATTR_DEAD void
169 client(int debug, int verbose)
171 struct event ev_sigint, ev_sigterm;
173 log_init(debug, LOG_DAEMON);
174 log_setverbose(verbose);
176 setproctitle("client");
177 log_procinit("client");
179 log_debug("warming up");
181 event_init();
183 /* Setup signal handlers */
184 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
185 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
187 signal_add(&ev_sigint, NULL);
188 signal_add(&ev_sigterm, NULL);
190 signal(SIGPIPE, SIG_IGN);
191 signal(SIGHUP, SIG_IGN);
193 /* Setup pipe and event handler to the listener process */
194 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
195 fatal(NULL);
197 imsg_init(&iev_listener->ibuf, 3);
198 iev_listener->handler = client_dispatch_listener;
200 /* Setup event handlers. */
201 iev_listener->events = EV_READ;
202 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
203 iev_listener->events, iev_listener->handler, iev_listener);
204 event_add(&iev_listener->ev, NULL);
206 event_dispatch();
207 client_shutdown();
210 static ATTR_DEAD void
211 client_shutdown(void)
213 if (evb != NULL)
214 evbuffer_free(evb);
216 msgbuf_clear(&iev_listener->ibuf.w);
217 close(iev_listener->ibuf.fd);
219 free(iev_listener);
221 log_debug("client exiting");
222 exit(0);
225 static void
226 client_sig_handler(int sig, short event, void *d)
228 /*
229 * Normal signal handler rules don't apply because libevent
230 * decouples for us.
231 */
233 switch (sig) {
234 case SIGINT:
235 case SIGTERM:
236 client_shutdown();
237 default:
238 fatalx("unexpected signal %d", sig);
242 #define AUTH_NONE 0
243 #define AUTH_USER 1
244 #define AUTH_DONE 2
246 static void
247 client_dispatch_listener(int fd, short event, void *d)
249 static int auth = AUTH_NONE;
250 static char username[64] = {0};
251 static char dir[PATH_MAX] = {0};
252 struct imsg imsg;
253 struct imsgev *iev = d;
254 struct imsgbuf *ibuf;
255 ssize_t n;
256 int shut = 0;
258 ibuf = &iev->ibuf;
260 if (event & EV_READ) {
261 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
262 fatal("imsg_read error");
263 if (n == 0) /* Connection closed */
264 shut = 1;
266 if (event & EV_WRITE) {
267 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
268 fatal("msgbuf_write");
269 if (n == 0) /* Connection closed */
270 shut = 1;
273 for (;;) {
274 if ((n = imsg_get(ibuf, &imsg)) == -1)
275 fatal("%s: imsg_get error", __func__);
276 if (n == 0) /* No more messages. */
277 break;
279 switch (imsg.hdr.type) {
280 case IMSG_AUTH:
281 peerid = imsg.hdr.peerid;
282 if (auth)
283 fatalx("%s: IMSG_AUTH already done", __func__);
284 auth = AUTH_USER;
285 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
286 strlcpy(username, imsg.data, sizeof(username));
287 break;
288 case IMSG_AUTH_DIR:
289 if (auth != AUTH_USER)
290 fatalx("%s: IMSG_AUTH_DIR not after IMSG_AUTH",
291 __func__);
292 auth = AUTH_DONE;
293 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
294 strlcpy(dir, imsg.data, sizeof(dir));
295 client_privdrop(username, dir);
296 memset(username, 0, sizeof(username));
297 memset(dir, 0, sizeof(username));
298 break;
299 case IMSG_BUF:
300 /* echo! */
301 if (!auth)
302 fatalx("%s: can't handle messages before"
303 " doing the auth", __func__);
304 handle_message(&imsg, IMSG_DATA_SIZE(imsg));
305 break;
306 case IMSG_CONN_GONE:
307 log_debug("closing");
308 shut = 1;
309 break;
310 default:
311 log_debug("%s: unexpected imsg %d",
312 __func__, imsg.hdr.type);
313 break;
315 imsg_free(&imsg);
318 if (!shut)
319 imsg_event_add(iev);
320 else {
321 /* This pipe is dead. Remove its event handler. */
322 event_del(&iev->ev);
323 log_debug("pipe closed, shutting down...");
324 event_loopexit(NULL);
328 static void
329 client_privdrop(const char *username, const char *dir)
331 struct passwd *pw;
333 setproctitle("client %s", username);
335 if ((pw = getpwnam(username)) == NULL)
336 fatalx("getpwnam(%s) failed", username);
338 if (chroot(dir) == -1)
339 fatal("chroot");
340 if (chdir("/") == -1)
341 fatal("chdir(\"/\")");
343 if (setgroups(1, &pw->pw_gid) ||
344 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
345 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
346 fatal("can't drop privileges");
348 sandbox_client();
349 log_debug("client ready; user=%s dir=%s", username, dir);
351 if ((evb = evbuffer_new()) == NULL)
352 fatal("evbuffer_new");
355 static int
356 client_send_listener(int type, const void *data, uint16_t len)
358 int ret;
360 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
361 data, len)) != -1)
362 imsg_event_add(iev_listener);
364 return ret;
367 /* set qid fields from sb */
368 static void
369 qid_update_from_sb(struct qid *qid, struct stat *sb)
371 qid->path = sb->st_ino;
373 /*
374 * Theoretically (and hopefully!) this should be a 64 bit
375 * number. Unfortunately, 9P uses 32 bit timestamps.
376 */
377 qid->vers = sb->st_mtim.tv_sec;
379 if (S_ISREG(sb->st_mode))
380 qid->type = QTFILE;
381 else if (S_ISDIR(sb->st_mode))
382 qid->type = QTDIR;
383 else if (S_ISLNK(sb->st_mode))
384 qid->type = QTSYMLINK;
387 /* creates a qid given a fd */
388 static struct qid *
389 qid_from_fd(int fd, const char *path, struct stat *s)
391 struct qid *qid;
392 struct stat sb;
393 int r;
395 if ((qid = calloc(1, sizeof(*qid))) == NULL)
396 return NULL;
398 if (path != NULL)
399 strlcpy(qid->fpath, path, sizeof(qid->fpath));
401 qid->fd = fd;
403 if (s == NULL) {
404 s = &sb;
405 if (path == NULL)
406 r = fstat(fd, s);
407 else
408 r = fstatat(fd, path, s, 0);
409 if (r == -1) {
410 free(qid);
411 return NULL;
415 qid_update_from_sb(qid, s);
417 STAILQ_INSERT_HEAD(&qids, qid, entries);
419 return qid;
422 static struct qid *
423 qid_incref(struct qid *qid)
425 qid->refcount++;
426 return qid;
429 static void
430 qid_decref(struct qid *qid)
432 if (--qid->refcount > 0)
433 return;
435 STAILQ_REMOVE(&qids, qid, qid, entries);
437 close(qid->fd);
438 free(qid);
441 static struct fid *
442 new_fid(struct qid *qid, uint32_t fid)
444 struct fid *f;
446 if ((f = calloc(1, sizeof(*f))) == NULL)
447 return NULL;
449 f->qid = qid_incref(qid);
450 f->fid = fid;
451 f->fd = -1;
453 STAILQ_INSERT_HEAD(&fids, f, entries);
455 return f;
458 static struct fid *
459 fid_by_id(uint32_t fid)
461 struct fid *f;
463 STAILQ_FOREACH(f, &fids, entries) {
464 if (f->fid == fid)
465 return f;
468 return NULL;
471 static void
472 free_fid(struct fid *f)
474 int r;
476 if (f->fd != -1) {
477 if (f->dir != NULL)
478 r = closedir(f->dir);
479 else
480 r = close(f->fd);
482 if (r == -1)
483 fatal("can't close fid %d", f->fid);
485 if (f->evb != NULL)
486 evbuffer_free(f->evb);
488 /* try to honour ORCLOSE if requested */
489 if (f->iomode & O_CLOEXEC)
490 unlinkat(f->qid->fd, f->qid->fpath, 0);
493 qid_decref(f->qid);
495 STAILQ_REMOVE(&fids, f, fid, entries);
496 free(f);
499 static void
500 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
501 uint8_t **cnt)
503 size_t olen = len;
505 if (!NPREAD32("len", &hdr->len, &data, &len) ||
506 !NPREAD8("type", &hdr->type, &data, &len) ||
507 !NPREAD16("tag", &hdr->tag, &data, &len))
508 goto err;
510 if (olen != hdr->len)
511 goto err;
513 if (hdr->type < Tversion ||
514 hdr->type >= Tmax ||
515 hdr->type == Terror ||
516 (hdr->type & 0x1) != 0) /* cannot recv a R* */
517 goto err;
519 hdr->tag = le32toh(hdr->tag);
521 *cnt = (uint8_t *)data;
522 return;
524 err:
525 /* TODO: send a proper message to terminate the connection. */
526 fatalx("got invalid message");
529 static void
530 np_write16(struct evbuffer *e, uint16_t x)
532 x = htole16(x);
533 evbuffer_add(e, &x, sizeof(x));
536 static void
537 np_write32(struct evbuffer *e, uint32_t x)
539 x = htole32(x);
540 evbuffer_add(e, &x, sizeof(x));
543 static void
544 np_write64(struct evbuffer *e, uint64_t x)
546 x = htole64(x);
547 evbuffer_add(e, &x, sizeof(x));
550 static void
551 np_writebuf(struct evbuffer *e, size_t len, void *data)
553 evbuffer_add(e, data, len);
556 static void
557 np_header(uint32_t len, uint8_t type, uint16_t tag)
559 len += HEADERSIZE;
561 len = htole32(len);
562 tag = htole16(tag);
564 evbuffer_add(evb, &len, sizeof(len));
565 evbuffer_add(evb, &type, sizeof(type));
566 evbuffer_add(evb, &tag, sizeof(tag));
569 static void
570 np_string(struct evbuffer *e, uint16_t len, const char *str)
572 uint16_t l = len;
574 len = htole16(len);
575 evbuffer_add(e, &len, sizeof(len));
576 evbuffer_add(e, str, l);
579 static void
580 np_qid(struct evbuffer *e, struct qid *qid)
582 uint64_t path;
583 uint32_t vers;
585 path = htole64(qid->path);
586 vers = htole32(qid->vers);
588 evbuffer_add(e, &qid->type, sizeof(qid->type));
589 evbuffer_add(e, &vers, sizeof(vers));
590 evbuffer_add(e, &path, sizeof(path));
593 static void
594 do_send(void)
596 size_t len;
597 void *data;
599 len = EVBUFFER_LENGTH(evb);
600 data = EVBUFFER_DATA(evb);
602 #if DEBUG_PACKETS
603 hexdump("outgoing packet", data, len);
604 #endif
605 client_send_listener(IMSG_BUF, data, len);
606 evbuffer_drain(evb, len);
609 static void
610 np_version(uint16_t tag, uint32_t msize, const char *version)
612 uint16_t l;
614 l = strlen(version);
616 msize = htole32(msize);
618 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
619 evbuffer_add(evb, &msize, sizeof(msize));
620 np_string(evb, l, version);
621 do_send();
624 static void
625 np_attach(uint16_t tag, struct qid *qid)
627 np_header(QIDSIZE, Rattach, tag);
628 np_qid(evb, qid);
629 do_send();
632 static void
633 np_clunk(uint16_t tag)
635 np_header(0, Rclunk, tag);
636 do_send();
639 static void
640 np_flush(uint16_t tag)
642 np_header(0, Rflush, tag);
643 do_send();
646 static void
647 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
649 int i;
651 /* two bytes for the counter */
652 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
653 np_write16(evb, nwqid);
654 for (i = 0; i < nwqid; ++i)
655 np_qid(evb, wqid + i);
657 do_send();
660 static void
661 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
663 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
664 np_qid(evb, qid);
665 np_write32(evb, iounit);
666 do_send();
669 static void
670 np_read(uint16_t tag, uint32_t count, void *data)
672 np_header(sizeof(count) + count, Rread, tag);
673 np_write32(evb, count);
674 np_writebuf(evb, count, data);
675 do_send();
678 static void
679 np_write(uint16_t tag, uint32_t count)
681 np_header(sizeof(count), Rwrite, tag);
682 np_write32(evb, count);
683 do_send();
686 static void
687 np_stat(uint16_t tag, uint32_t count, void *data)
689 np_header(count, Rstat, tag);
690 np_writebuf(evb, count, data);
691 do_send();
694 static void
695 np_error(uint16_t tag, const char *errstr)
697 uint16_t l;
699 l = strlen(errstr);
701 np_header(sizeof(l) + l, Rerror, tag);
702 np_string(evb, l, errstr);
703 do_send();
706 static void
707 np_errno(uint16_t tag)
709 int saved_errno;
710 char buf[64];
712 saved_errno = errno;
714 strerror_r(errno, buf, sizeof(buf));
715 np_error(tag, buf);
717 errno = saved_errno;
720 static int
721 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
722 size_t *len)
724 if (*len < sizeof(*dst)) {
725 log_warnx("%s: wanted %zu bytes for the %s field but only "
726 "%zu are available.", t, sizeof(*dst), f, *len);
727 return -1;
730 memcpy(dst, *src, sizeof(*dst));
731 *src += sizeof(*dst);
732 *len -= sizeof(*dst);
734 return 1;
737 static int
738 np_read16(const char *t, const char *f, uint16_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);
750 *dst = le16toh(*dst);
752 return 1;
755 static int
756 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
757 size_t *len)
759 if (*len < sizeof(*dst)) {
760 log_warnx("%s: wanted %zu bytes for the %s field but only "
761 "%zu are available.", t, sizeof(*dst), f, *len);
762 return -1;
765 memcpy(dst, *src, sizeof(*dst));
766 *src += sizeof(*dst);
767 *len -= sizeof(*dst);
768 *dst = le32toh(*dst);
770 return 1;
773 static int
774 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
775 size_t *len)
777 if (*len < sizeof(*dst)) {
778 log_warnx("%s: wanted %zu bytes for the %s field but only "
779 "%zu are available.", t, sizeof(*dst), f, *len);
780 return -1;
783 memcpy(dst, *src, sizeof(*dst));
784 *src += sizeof(*dst);
785 *len -= sizeof(*dst);
786 *dst = le64toh(*dst);
788 return 1;
791 static int
792 np_readstr(const char *t, const char *f, char *res, size_t reslen,
793 const uint8_t **src, size_t *len)
795 uint16_t sl;
796 char buf[32];
798 strlcpy(buf, f, sizeof(buf));
799 strlcat(buf, "-len", sizeof(buf));
801 if (!np_read16(t, buf, &sl, src, len))
802 return READSTRERR;
804 if (*len < sl) {
805 log_warnx("%s: wanted %d bytes for the %s field but only "
806 "%zu are available.", t, sl, f, *len);
807 return READSTRERR;
810 if (*len > reslen-1)
811 return READSTRTRUNC;
813 memcpy(res, *src, sl);
814 res[sl] = '\0';
815 *src += sl;
816 *len -= sl;
818 return 0;
821 static void
822 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
824 char *dot, version[32];
826 if (handshaked)
827 goto err;
829 /* msize[4] version[s] */
830 if (!NPREAD32("msize", &msize, &data, &len))
831 goto err;
833 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
834 case READSTRERR:
835 goto err;
836 case READSTRTRUNC:
837 log_warnx("9P version string too long, truncated");
838 goto mismatch;
841 if ((dot = strchr(version, '.')) != NULL)
842 *dot = '\0';
844 if (strcmp(version, VERSION9P) != 0 ||
845 msize == 0)
846 goto mismatch;
848 /* version matched */
849 handshaked = 1;
850 msize = MIN(msize, MSIZE9P);
851 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
852 np_version(hdr->tag, msize, VERSION9P);
853 return;
855 mismatch:
856 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
857 version);
858 np_version(hdr->tag, MSIZE9P, "unknown");
859 return;
861 err:
862 client_send_listener(IMSG_CLOSE, NULL, 0);
863 client_shutdown();
866 static void
867 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
869 struct qid *qid;
870 struct fid *f;
871 uint32_t fid, afid;
872 int fd;
873 char aname[PATH_MAX];
875 /* fid[4] afid[4] uname[s] aname[s] */
877 if (!NPREAD32("fid", &fid, &data, &len) ||
878 !NPREAD32("afid", &afid, &data, &len))
879 goto err;
881 /* read the uname but don't actually use it */
882 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
883 case READSTRERR:
884 goto err;
885 case READSTRTRUNC:
886 np_error(hdr->tag, "name too long");
887 return;
890 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
891 case READSTRERR:
892 goto err;
893 case READSTRTRUNC:
894 np_error(hdr->tag, "name too long");
895 return;
898 if (fid_by_id(fid) != NULL || afid != NOFID) {
899 np_error(hdr->tag, "invalid fid or afid");
900 return;
903 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
904 goto fail;
906 if ((qid = qid_from_fd(fd, NULL, NULL)) == NULL)
907 goto fail;
909 log_debug("attached %s to %d", aname, fid);
911 if ((f = new_fid(qid, fid)) == NULL) {
912 qid_decref(qid);
913 goto fail;
916 np_attach(hdr->tag, qid);
917 return;
919 fail:
920 np_errno(hdr->tag);
921 log_warn("failed to attach %s", aname);
922 return;
923 return;
925 err:
926 client_send_listener(IMSG_CLOSE, NULL, 0);
927 client_shutdown();
930 static void
931 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
933 struct fid *f;
934 uint32_t fid;
936 /* fid[4] */
937 if (!NPREAD32("fid", &fid, &data, &len)) {
938 client_send_listener(IMSG_CLOSE, NULL, 0);
939 client_shutdown();
940 return;
943 if ((f = fid_by_id(fid)) == NULL) {
944 np_error(hdr->tag, "invalid fid");
945 return;
948 free_fid(f);
949 np_clunk(hdr->tag);
952 static void
953 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
955 uint16_t oldtag;
957 /*
958 * We're doing only synchronous I/O. Tflush is implemented
959 * only because it's illegal to reply with a Rerror.
960 */
962 /* oldtag[2] */
963 if (len != sizeof(oldtag)) {
964 log_warnx("Tclunk with the wrong size: got %zu want %zu",
965 len, sizeof(oldtag));
966 client_send_listener(IMSG_CLOSE, NULL, 0);
967 client_shutdown();
968 return;
971 np_flush(hdr->tag);
974 static void
975 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
977 struct stat sb;
978 struct qid *qid, wqid[MAXWELEM] = {0};
979 struct fid *f, *nf;
980 uint32_t fid, newfid;
981 uint16_t nwname;
982 int fd, oldfd, no, nwqid = 0;
983 char wnam[PATH_MAX];
985 if (!NPREAD32("fid", &fid, &data, &len) ||
986 !NPREAD32("newfid", &newfid, &data, &len) ||
987 !NPREAD16("nwname", &nwname, &data, &len))
988 goto err;
990 if (nwname > MAXWELEM) {
991 log_warnx("Twalk: more than %d path elements: %d",
992 MAXWELEM, nwname);
993 goto err;
996 if ((f = fid_by_id(fid)) == NULL) {
997 np_error(hdr->tag, "invalid fid");
998 return;
1001 if (f->fd != -1) {
1002 np_error(hdr->tag, "fid already opened for I/O");
1003 return;
1006 if (fid == newfid)
1007 nf = f;
1008 else if ((nf = fid_by_id(newfid)) != NULL) {
1009 np_error(hdr->tag, "newfid already in use");
1010 return;
1011 } else
1012 nf = NULL;
1014 /* special case: fid duplication */
1015 if (nwname == 0) {
1017 * TODO: should we forbid fids duplication when fid ==
1018 * newfid?
1020 if (nf == NULL && (nf = new_fid(f->qid, newfid)) == NULL)
1021 fatal("new_fid duplication");
1023 np_walk(hdr->tag, 1, f->qid);
1024 return;
1027 if (f->qid->type != QTDIR) {
1028 np_error(hdr->tag, "fid doesn't represent a directory");
1029 return;
1032 oldfd = f->qid->fd;
1034 for (nwqid = 0; nwqid < nwname; nwqid++) {
1035 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1036 case READSTRERR:
1037 goto err;
1038 case READSTRTRUNC:
1039 np_error(hdr->tag, "wname too long");
1040 return;
1043 if (*wnam == '\0' ||
1044 strchr(wnam, '/') != NULL ||
1045 !strcmp(wnam, ".")) {
1046 errno = EINVAL;
1047 goto cantopen;
1050 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1051 errno != ENOTDIR)
1052 goto cantopen;
1054 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1055 (fd != -1 && fstat(fd, &sb) == -1))
1056 goto cantopen;
1058 qid_update_from_sb(&wqid[nwqid], &sb);
1060 /* reached a file but we still have other components */
1061 if (fd == -1 && nwqid+1 < nwname)
1062 goto cantopen;
1064 /* reached the end and found a file */
1065 if (fd == -1 && nwqid+1 == nwname)
1066 continue;
1068 if (oldfd != f->qid->fd)
1069 close(oldfd);
1070 oldfd = fd;
1074 * There can be two possibilities: fd == -1 means that we've
1075 * reached a file and we should save BOTH the dirfd (oldfd)
1076 * and the path (wnam); or we just reached another directory,
1077 * in which case we can just create a new qid using fd.
1079 if (fd == -1)
1080 qid = qid_from_fd(oldfd, wnam, &sb);
1081 else
1082 qid = qid_from_fd(oldfd, NULL, &sb);
1083 if (qid == NULL)
1084 fatal("qid_from_fd");
1086 if (nf == NULL) {
1087 if ((nf = new_fid(qid, newfid)) == NULL)
1088 fatal("new_fid");
1089 } else {
1090 /* swap qid */
1091 qid_decref(nf->qid);
1092 nf->qid = qid_incref(qid);
1095 np_walk(hdr->tag, nwqid, wqid);
1096 return;
1098 cantopen:
1099 if (oldfd != f->qid->fd)
1100 close(oldfd);
1101 no = errno;
1102 if (nwqid == 0)
1103 np_error(hdr->tag, strerror(no));
1104 else
1105 np_walk(hdr->tag, nwqid, wqid);
1106 return;
1108 err:
1109 client_send_listener(IMSG_CLOSE, NULL, 0);
1110 client_shutdown();
1113 static inline int
1114 npmode_to_unix(uint8_t mode, int *flags)
1116 switch (mode & 0x0F) {
1117 case KOREAD:
1118 *flags = O_RDONLY;
1119 break;
1120 case KOWRITE:
1121 *flags = O_WRONLY;
1122 break;
1123 case KORDWR:
1124 *flags = O_RDWR;
1125 break;
1126 case KOEXEC:
1127 log_warnx("tried to open something with KOEXEC");
1128 /* fallthrough */
1129 default:
1130 return -1;
1133 if (mode & KOTRUNC)
1134 *flags |= O_TRUNC;
1135 if (mode & KORCLOSE)
1136 *flags |= O_CLOEXEC;
1138 return 0;
1141 static void
1142 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1144 struct stat sb;
1145 struct qid qid;
1146 struct fid *f;
1147 uint32_t fid;
1148 uint8_t mode;
1149 const char *path;
1151 /* fid[4] mode[1] */
1152 if (!NPREAD32("fid", &fid, &data, &len) ||
1153 !NPREAD8("mode", &mode, &data, &len)) {
1154 client_send_listener(IMSG_CLOSE, NULL, 0);
1155 client_shutdown();
1156 return;
1159 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1160 np_error(hdr->tag, "invalid fid");
1161 return;
1164 if (npmode_to_unix(mode, &f->iomode) == -1) {
1165 np_error(hdr->tag, "invalid mode");
1166 return;
1169 if (f->qid->type & QTDIR &&
1170 (f->iomode & O_WRONLY || f->iomode & O_RDWR)) {
1171 np_error(hdr->tag, "can't open directory for writing");
1172 return;
1175 path = f->qid->fpath;
1176 if (*path == '\0')
1177 path = ".";
1179 if ((f->fd = openat(f->qid->fd, path, f->iomode)) == -1) {
1180 np_error(hdr->tag, strerror(errno));
1181 return;
1184 if (fstat(f->fd, &sb) == -1)
1185 fatal("fstat");
1187 if (S_ISDIR(sb.st_mode)) {
1188 assert(f->qid->type & QTDIR);
1189 if ((f->dir = fdopendir(f->fd)) == NULL) {
1190 np_errno(hdr->tag);
1191 close(f->fd);
1192 f->fd = -1;
1193 return;
1196 if ((f->evb = evbuffer_new()) == NULL) {
1197 np_errno(hdr->tag);
1198 closedir(f->dir);
1199 f->dir = NULL;
1200 f->fd = -1;
1204 f->offset = 0;
1206 qid_update_from_sb(&qid, &sb);
1207 np_open(hdr->tag, &qid, sb.st_blksize);
1210 static inline void
1211 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1213 struct qid qid;
1214 const char *uid, *gid, *muid;
1215 size_t tot;
1216 uint16_t namlen, uidlen, gidlen, ulen;
1218 qid_update_from_sb(&qid, sb);
1220 /* TODO: fill these fields */
1221 uid = "";
1222 gid = "";
1223 muid = "";
1225 namlen = strlen(fname);
1226 uidlen = strlen(uid);
1227 gidlen = strlen(gid);
1228 ulen = strlen(muid);
1230 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1231 if (tot > UINT32_MAX) {
1232 log_warnx("stat info for dir entry %s would overflow",
1233 fname);
1234 return;
1237 np_write16(evb, tot); /* size[2] */
1238 np_write16(evb, sb->st_rdev); /* type[2] */
1239 np_write32(evb, sb->st_dev); /* dev[4] */
1240 np_qid(evb, &qid); /* qid[13] */
1242 /* XXX: translate? */
1243 np_write32(evb, sb->st_mode); /* mode[4] */
1245 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1246 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1247 np_write64(evb, sb->st_size); /* length[8] */
1248 np_string(evb, namlen, fname); /* name[s] */
1249 np_string(evb, uidlen, uid); /* uid[s] */
1250 np_string(evb, gidlen, gid); /* gid[s] */
1251 np_string(evb, ulen, muid); /* muid[s] */
1254 static void
1255 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1257 struct fid *f;
1258 ssize_t r;
1259 uint64_t off;
1260 uint32_t fid, count;
1261 char buf[2048];
1263 /* fid[4] offset[8] count[4] */
1264 if (!NPREAD32("fid", &fid, &data, &len) ||
1265 !NPREAD64("offset", &off, &data, &len) ||
1266 !NPREAD32("count", &count, &data, &len)) {
1267 client_send_listener(IMSG_CLOSE, NULL, 0);
1268 client_shutdown();
1269 return;
1272 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1273 np_error(hdr->tag, "invalid fid");
1274 return;
1277 if (TYPE_OVERFLOW(off_t, off)) {
1278 log_warnx("unexpected size_t size");
1279 np_error(hdr->tag, "invalid offset");
1280 return;
1283 if (f->dir == NULL) {
1284 /* read a file */
1285 r = pread(f->fd, buf, sizeof(buf), (off_t)off);
1286 if (r == -1)
1287 np_errno(hdr->tag);
1288 else
1289 np_read(hdr->tag, r, buf);
1290 } else {
1291 if (off == 0 && f->offset != 0) {
1292 rewinddir(f->dir);
1293 f->offset = 0;
1296 if (off != f->offset) {
1297 np_error(hdr->tag, "can't seek in directories");
1298 return;
1301 while (EVBUFFER_LENGTH(f->evb) < count) {
1302 struct dirent *d;
1303 struct stat sb;
1305 if ((d = readdir(f->dir)) == NULL)
1306 break;
1307 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1308 warn("fstatat");
1309 continue;
1311 serialize_stat(d->d_name, &sb, f->evb);
1314 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1315 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1316 evbuffer_drain(f->evb, count);
1318 f->offset += count;
1322 static void
1323 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1325 struct fid *f;
1326 ssize_t r;
1327 uint64_t off;
1328 uint32_t fid, count;
1330 /* fid[4] offset[8] count[4] data[count] */
1331 if (!NPREAD32("fid", &fid, &data, &len) ||
1332 !NPREAD64("off", &off, &data, &len) ||
1333 !NPREAD32("count", &count, &data, &len) ||
1334 len != count) {
1335 client_send_listener(IMSG_CLOSE, NULL, 0);
1336 client_shutdown();
1337 return;
1340 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1341 np_error(hdr->tag, "invalid fid");
1342 return;
1345 if (!(f->iomode & O_WRONLY) &&
1346 !(f->iomode & O_RDWR)) {
1347 np_error(hdr->tag, "fid not opened for writing");
1348 return;
1351 if (TYPE_OVERFLOW(off_t, off)) {
1352 log_warnx("unexpected off_t size");
1353 np_error(hdr->tag, "invalid offset");
1354 return;
1357 if ((r = pwrite(f->fd, data, len, off)) == -1)
1358 np_errno(hdr->tag);
1359 else
1360 np_write(hdr->tag, r);
1363 static void
1364 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1366 struct evbuffer *evb;
1367 struct stat sb;
1368 struct fid *f;
1369 const char *fname;
1370 int r;
1371 uint32_t fid;
1373 /* fid[4] */
1374 if (!NPREAD32("fid", &fid, &data, &len)) {
1375 client_send_listener(IMSG_CLOSE, NULL, 0);
1376 client_shutdown();
1377 return;
1381 * plan9' stat(9P) is not clear on whether the stat is allowed
1382 * on opened fids or not.
1384 if ((f = fid_by_id(fid)) == NULL) {
1385 np_error(hdr->tag, "invalid fid");
1386 return;
1389 if ((evb = evbuffer_new()) == NULL)
1390 fatal("evbuffer_new");
1392 if (f->qid->type & QTDIR) {
1393 fname = ".";
1394 r = fstat(f->qid->fd, &sb);
1395 } else {
1396 fname = f->qid->fpath;
1397 r = fstatat(f->qid->fd, f->qid->fpath, &sb, 0);
1400 if (r == -1) {
1401 np_errno(hdr->tag);
1402 evbuffer_free(evb);
1403 return;
1406 serialize_stat(fname, &sb, evb);
1407 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1408 evbuffer_free(evb);
1411 static void
1412 handle_message(struct imsg *imsg, size_t len)
1414 struct msg {
1415 uint8_t type;
1416 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1417 } msgs[] = {
1418 {Tversion, tversion},
1419 {Tattach, tattach},
1420 {Tclunk, tclunk},
1421 {Tflush, tflush},
1422 {Twalk, twalk},
1423 {Topen, topen},
1424 {Tread, tread},
1425 {Twrite, twrite},
1426 {Tstat, tstat},
1428 struct np_msg_header hdr;
1429 size_t i;
1430 uint8_t *data;
1432 #if DEBUG_PACKETS
1433 hexdump("incoming packet", imsg->data, len);
1434 #endif
1436 parse_message(imsg->data, len, &hdr, &data);
1437 len -= HEADERSIZE;
1439 log_debug("got request: len=%d type=%d[%s] tag=%d",
1440 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1442 if (!handshaked && hdr.type != Tversion) {
1443 client_send_listener(IMSG_CLOSE, NULL, 0);
1444 client_shutdown();
1445 return;
1448 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1449 if (msgs[i].type != hdr.type)
1450 continue;
1452 msgs[i].fn(&hdr, data, len);
1453 return;
1456 np_error(hdr.tag, "Not supported.");