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 <endian.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <pwd.h>
25 #include <signal.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <syslog.h>
29 #include <unistd.h>
31 #include "client.h"
32 #include "kamid.h"
33 #include "log.h"
34 #include "sandbox.h"
35 #include "utils.h"
37 #define DEBUG_PACKETS 0
39 STAILQ_HEAD(qidhead, qid) qids;
40 struct qid {
41 /* definition of a qid */
42 uint64_t path;
43 uint32_t vers;
44 uint8_t type;
46 int refcount;
48 int fd;
49 char fpath[PATH_MAX+1];
51 STAILQ_ENTRY(qid) entries;
52 };
54 STAILQ_HEAD(fidhead, fid) fids;
55 struct fid {
56 uint32_t fid;
58 /*
59 * 0 when the fid was not yet opened for I/O otherwise set to
60 * the flags passed to open(2). O_CLOEXEC means ORCLOSE, that
61 * is to unlink the file upon Tclunk.
62 */
63 int iomode;
65 /*
66 * if iomode is set, this fid was opened and fd represents its
67 * file descriptor.
68 */
69 int fd;
71 struct qid *qid;
72 STAILQ_ENTRY(fid) entries;
73 };
75 static struct imsgev *iev_listener;
76 static struct evbuffer *evb;
77 static uint32_t peerid;
79 static int handshaked, attached;
80 uint32_t msize;
82 static ATTR_DEAD void client_shutdown(void);
83 static void client_sig_handler(int, short, void *);
84 static void client_dispatch_listener(int, short, void *);
85 static void client_privdrop(const char *, const char *);
87 static int client_send_listener(int, const void *, uint16_t);
89 static void qid_update_from_sb(struct qid *, struct stat *);
90 static struct qid *qid_from_fd(int, const char *, struct stat *);
91 static struct qid *qid_incref(struct qid *);
92 static void qid_decref(struct qid *);
94 static struct fid *new_fid(struct qid *, uint32_t);
95 static struct fid *fid_by_id(uint32_t);
96 static void free_fid(struct fid *);
98 static void parse_message(const uint8_t *, size_t,
99 struct np_msg_header *, uint8_t **);
101 static void np_write16(uint16_t);
102 static void np_write32(uint32_t);
103 static void np_header(uint32_t, uint8_t, uint16_t);
104 static void np_string(uint16_t, const char *);
105 static void np_qid(struct qid *);
106 static void do_send(void);
108 static void np_version(uint16_t, uint32_t, const char *);
109 static void np_attach(uint16_t, struct qid *);
110 static void np_clunk(uint16_t);
111 static void np_flush(uint16_t);
112 static void np_walk(uint16_t, int, struct qid *);
113 static void np_open(uint16_t, struct qid *, uint32_t);
114 static void np_error(uint16_t, const char *);
115 static void np_errno(uint16_t);
117 static int np_read8(const char *, const char *, uint8_t *,
118 const uint8_t **, size_t *);
119 static int np_read16(const char *, const char *, uint16_t *,
120 const uint8_t **, size_t *);
121 static int np_read32(const char *, const char *, uint32_t *,
122 const uint8_t **, size_t *);
124 #define READSTRERR -1
125 #define READSTRTRUNC -2
126 static int np_readstr(const char *, const char *, char *, size_t,
127 const uint8_t **, size_t *);
129 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
130 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
131 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
133 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
135 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
136 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
137 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
138 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
139 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
140 static void topen(struct np_msg_header *, const uint8_t *, size_t);
141 static void handle_message(struct imsg *, size_t);
143 ATTR_DEAD void
144 client(int debug, int verbose)
146 struct event ev_sigint, ev_sigterm;
148 log_init(debug, LOG_DAEMON);
149 log_setverbose(verbose);
151 setproctitle("client");
152 log_procinit("client");
154 log_debug("warming up");
156 event_init();
158 /* Setup signal handlers */
159 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
160 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
162 signal_add(&ev_sigint, NULL);
163 signal_add(&ev_sigterm, NULL);
165 signal(SIGPIPE, SIG_IGN);
166 signal(SIGHUP, SIG_IGN);
168 /* Setup pipe and event handler to the listener process */
169 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
170 fatal(NULL);
172 imsg_init(&iev_listener->ibuf, 3);
173 iev_listener->handler = client_dispatch_listener;
175 /* Setup event handlers. */
176 iev_listener->events = EV_READ;
177 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
178 iev_listener->events, iev_listener->handler, iev_listener);
179 event_add(&iev_listener->ev, NULL);
181 event_dispatch();
182 client_shutdown();
185 static ATTR_DEAD void
186 client_shutdown(void)
188 if (evb != NULL)
189 evbuffer_free(evb);
191 msgbuf_clear(&iev_listener->ibuf.w);
192 close(iev_listener->ibuf.fd);
194 free(iev_listener);
196 log_debug("client exiting");
197 exit(0);
200 static void
201 client_sig_handler(int sig, short event, void *d)
203 /*
204 * Normal signal handler rules don't apply because libevent
205 * decouples for us.
206 */
208 switch (sig) {
209 case SIGINT:
210 case SIGTERM:
211 client_shutdown();
212 default:
213 fatalx("unexpected signal %d", sig);
217 #define AUTH_NONE 0
218 #define AUTH_USER 1
219 #define AUTH_DONE 2
221 static void
222 client_dispatch_listener(int fd, short event, void *d)
224 static int auth = AUTH_NONE;
225 static char username[64] = {0};
226 static char dir[PATH_MAX] = {0};
227 struct imsg imsg;
228 struct imsgev *iev = d;
229 struct imsgbuf *ibuf;
230 ssize_t n;
231 int shut = 0;
233 ibuf = &iev->ibuf;
235 if (event & EV_READ) {
236 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
237 fatal("imsg_read error");
238 if (n == 0) /* Connection closed */
239 shut = 1;
241 if (event & EV_WRITE) {
242 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
243 fatal("msgbuf_write");
244 if (n == 0) /* Connection closed */
245 shut = 1;
248 for (;;) {
249 if ((n = imsg_get(ibuf, &imsg)) == -1)
250 fatal("%s: imsg_get error", __func__);
251 if (n == 0) /* No more messages. */
252 break;
254 switch (imsg.hdr.type) {
255 case IMSG_AUTH:
256 peerid = imsg.hdr.peerid;
257 if (auth)
258 fatalx("%s: IMSG_AUTH already done", __func__);
259 auth = AUTH_USER;
260 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
261 strlcpy(username, imsg.data, sizeof(username));
262 break;
263 case IMSG_AUTH_DIR:
264 if (auth != AUTH_USER)
265 fatalx("%s: IMSG_AUTH_DIR not after IMSG_AUTH",
266 __func__);
267 auth = AUTH_DONE;
268 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
269 strlcpy(dir, imsg.data, sizeof(dir));
270 client_privdrop(username, dir);
271 memset(username, 0, sizeof(username));
272 memset(dir, 0, sizeof(username));
273 break;
274 case IMSG_BUF:
275 /* echo! */
276 if (!auth)
277 fatalx("%s: can't handle messages before"
278 " doing the auth", __func__);
279 handle_message(&imsg, IMSG_DATA_SIZE(imsg));
280 break;
281 case IMSG_CONN_GONE:
282 log_debug("closing");
283 shut = 1;
284 break;
285 default:
286 log_debug("%s: unexpected imsg %d",
287 __func__, imsg.hdr.type);
288 break;
290 imsg_free(&imsg);
293 if (!shut)
294 imsg_event_add(iev);
295 else {
296 /* This pipe is dead. Remove its event handler. */
297 event_del(&iev->ev);
298 log_debug("pipe closed, shutting down...");
299 event_loopexit(NULL);
303 static void
304 client_privdrop(const char *username, const char *dir)
306 struct passwd *pw;
308 setproctitle("client %s", username);
310 if ((pw = getpwnam(username)) == NULL)
311 fatalx("getpwnam(%s) failed", username);
313 if (chroot(dir) == -1)
314 fatal("chroot");
315 if (chdir("/") == -1)
316 fatal("chdir(\"/\")");
318 if (setgroups(1, &pw->pw_gid) ||
319 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
320 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
321 fatal("can't drop privileges");
323 sandbox_client();
324 log_debug("client ready; user=%s dir=%s", username, dir);
326 if ((evb = evbuffer_new()) == NULL)
327 fatal("evbuffer_new");
330 static int
331 client_send_listener(int type, const void *data, uint16_t len)
333 int ret;
335 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
336 data, len)) != -1)
337 imsg_event_add(iev_listener);
339 return ret;
342 /* set qid fields from sb */
343 static void
344 qid_update_from_sb(struct qid *qid, struct stat *sb)
346 qid->path = sb->st_ino;
348 /*
349 * Theoretically (and hopefully!) this should be a 64 bit
350 * number. Unfortunately, 9P uses 32 bit timestamps.
351 */
352 qid->vers = sb->st_mtim.tv_sec;
354 if (S_ISREG(sb->st_mode))
355 qid->type = QTFILE;
356 else if (S_ISDIR(sb->st_mode))
357 qid->type = QTDIR;
358 else if (S_ISLNK(sb->st_mode))
359 qid->type = QTSYMLINK;
362 /* creates a qid given a fd */
363 static struct qid *
364 qid_from_fd(int fd, const char *path, struct stat *s)
366 struct qid *qid;
367 struct stat sb;
368 int r;
370 if ((qid = calloc(1, sizeof(*qid))) == NULL)
371 return NULL;
373 if (path != NULL)
374 strlcpy(qid->fpath, path, sizeof(qid->fpath));
376 qid->fd = fd;
378 if (s == NULL) {
379 s = &sb;
380 if (path == NULL)
381 r = fstat(fd, s);
382 else
383 r = fstatat(fd, path, s, 0);
384 if (r == -1) {
385 free(qid);
386 return NULL;
390 qid_update_from_sb(qid, s);
392 STAILQ_INSERT_HEAD(&qids, qid, entries);
394 return qid;
397 static struct qid *
398 qid_incref(struct qid *qid)
400 qid->refcount++;
401 return qid;
404 static void
405 qid_decref(struct qid *qid)
407 if (--qid->refcount > 0)
408 return;
410 STAILQ_REMOVE(&qids, qid, qid, entries);
412 close(qid->fd);
413 free(qid);
415 if (STAILQ_EMPTY(&qids))
416 attached = 0;
419 static struct fid *
420 new_fid(struct qid *qid, uint32_t fid)
422 struct fid *f;
424 if ((f = calloc(1, sizeof(*f))) == NULL)
425 return NULL;
427 f->qid = qid_incref(qid);
428 f->fid = fid;
429 f->fd = -1;
431 STAILQ_INSERT_HEAD(&fids, f, entries);
433 return f;
436 static struct fid *
437 fid_by_id(uint32_t fid)
439 struct fid *f;
441 STAILQ_FOREACH(f, &fids, entries) {
442 if (f->fid == fid)
443 return f;
446 return NULL;
449 static void
450 free_fid(struct fid *f)
452 if (f->fd != -1) {
453 close(f->fd);
454 /* try to honour ORCLOSE if requested */
455 if (f->iomode & O_CLOEXEC)
456 unlinkat(f->qid->fd, f->qid->fpath, 0);
459 qid_decref(f->qid);
461 STAILQ_REMOVE(&fids, f, fid, entries);
462 free(f);
465 static void
466 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
467 uint8_t **cnt)
469 size_t olen = len;
471 if (!NPREAD32("len", &hdr->len, &data, &len) ||
472 !NPREAD8("type", &hdr->type, &data, &len) ||
473 !NPREAD16("tag", &hdr->tag, &data, &len))
474 goto err;
476 if (olen != hdr->len)
477 goto err;
479 if (hdr->type < Tversion ||
480 hdr->type >= Tmax ||
481 hdr->type == Terror ||
482 (hdr->type & 0x1) != 0) /* cannot recv a R* */
483 goto err;
485 hdr->tag = le32toh(hdr->tag);
487 *cnt = (uint8_t *)data;
488 return;
490 err:
491 /* TODO: send a proper message to terminate the connection. */
492 fatalx("got invalid message");
495 static void
496 np_write16(uint16_t x)
498 x = htole16(x);
499 evbuffer_add(evb, &x, sizeof(x));
502 static void
503 np_write32(uint32_t x)
505 x = htole32(x);
506 evbuffer_add(evb, &x, sizeof(x));
509 static void
510 np_header(uint32_t len, uint8_t type, uint16_t tag)
512 len += HEADERSIZE;
514 len = htole32(len);
515 tag = htole16(tag);
517 evbuffer_add(evb, &len, sizeof(len));
518 evbuffer_add(evb, &type, sizeof(type));
519 evbuffer_add(evb, &tag, sizeof(tag));
522 static void
523 np_string(uint16_t len, const char *str)
525 uint16_t l = len;
527 len = htole16(len);
528 evbuffer_add(evb, &len, sizeof(len));
529 evbuffer_add(evb, str, l);
532 static void
533 np_qid(struct qid *qid)
535 uint64_t path;
536 uint32_t vers;
538 path = htole64(qid->path);
539 vers = htole32(qid->vers);
541 evbuffer_add(evb, &qid->type, sizeof(qid->type));
542 evbuffer_add(evb, &vers, sizeof(vers));
543 evbuffer_add(evb, &path, sizeof(path));
546 static void
547 do_send(void)
549 size_t len;
550 void *data;
552 len = EVBUFFER_LENGTH(evb);
553 data = EVBUFFER_DATA(evb);
555 #if DEBUG_PACKETS
556 hexdump("outgoing packet", data, len);
557 #endif
558 client_send_listener(IMSG_BUF, data, len);
559 evbuffer_drain(evb, len);
562 static void
563 np_version(uint16_t tag, uint32_t msize, const char *version)
565 uint16_t l;
567 l = strlen(version);
569 msize = htole32(msize);
571 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
572 evbuffer_add(evb, &msize, sizeof(msize));
573 np_string(l, version);
574 do_send();
577 static void
578 np_attach(uint16_t tag, struct qid *qid)
580 np_header(QIDSIZE, Rattach, tag);
581 np_qid(qid);
582 do_send();
585 static void
586 np_clunk(uint16_t tag)
588 np_header(0, Rclunk, tag);
589 do_send();
592 static void
593 np_flush(uint16_t tag)
595 np_header(0, Rflush, tag);
596 do_send();
599 static void
600 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
602 int i;
604 /* two bytes for the counter */
605 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
606 np_write16(nwqid);
607 for (i = 0; i < nwqid; ++i)
608 np_qid(wqid + i);
610 do_send();
613 static void
614 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
616 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
617 np_qid(qid);
618 np_write32(iounit);
619 do_send();
622 static void
623 np_error(uint16_t tag, const char *errstr)
625 uint16_t l;
627 l = strlen(errstr);
629 np_header(sizeof(l) + l, Rerror, tag);
630 np_string(l, errstr);
631 do_send();
634 static void
635 np_errno(uint16_t tag)
637 int saved_errno;
638 char buf[64];
640 saved_errno = errno;
642 strerror_r(errno, buf, sizeof(buf));
643 np_error(tag, buf);
645 errno = saved_errno;
648 static int
649 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
650 size_t *len)
652 if (*len < sizeof(*dst)) {
653 log_warnx("%s: wanted %zu bytes for the %s field but only "
654 "%zu are available.", t, sizeof(*dst), f, *len);
655 return -1;
658 memcpy(dst, *src, sizeof(*dst));
659 *src += sizeof(*dst);
660 *len -= sizeof(*dst);
662 return 1;
665 static int
666 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
667 size_t *len)
669 if (*len < sizeof(*dst)) {
670 log_warnx("%s: wanted %zu bytes for the %s field but only "
671 "%zu are available.", t, sizeof(*dst), f, *len);
672 return -1;
675 memcpy(dst, *src, sizeof(*dst));
676 *src += sizeof(*dst);
677 *len -= sizeof(*dst);
678 *dst = le16toh(*dst);
680 return 1;
683 static int
684 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
685 size_t *len)
687 if (*len < sizeof(*dst)) {
688 log_warnx("%s: wanted %zu bytes for the %s field but only "
689 "%zu are available.", t, sizeof(*dst), f, *len);
690 return -1;
693 memcpy(dst, *src, sizeof(*dst));
694 *src += sizeof(*dst);
695 *len -= sizeof(*dst);
696 *dst = le32toh(*dst);
698 return 1;
701 static int
702 np_readstr(const char *t, const char *f, char *res, size_t reslen,
703 const uint8_t **src, size_t *len)
705 uint16_t sl;
706 char buf[32];
708 strlcpy(buf, f, sizeof(buf));
709 strlcat(buf, "-len", sizeof(buf));
711 if (!np_read16(t, buf, &sl, src, len))
712 return READSTRERR;
714 if (*len < sl) {
715 log_warnx("%s: wanted %d bytes for the %s field but only "
716 "%zu are available.", t, sl, f, *len);
717 return READSTRERR;
720 if (*len > reslen-1)
721 return READSTRTRUNC;
723 memcpy(res, *src, sl);
724 res[sl] = '\0';
725 *src += sl;
726 *len -= sl;
728 return 0;
731 static void
732 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
734 char *dot, version[32];
736 if (handshaked)
737 goto err;
739 /* msize[4] version[s] */
740 if (!NPREAD32("msize", &msize, &data, &len))
741 goto err;
743 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
744 case READSTRERR:
745 goto err;
746 case READSTRTRUNC:
747 log_warnx("9P version string too long, truncated");
748 goto mismatch;
751 if ((dot = strchr(version, '.')) != NULL)
752 *dot = '\0';
754 if (strcmp(version, VERSION9P) != 0 ||
755 msize == 0)
756 goto mismatch;
758 /* version matched */
759 handshaked = 1;
760 msize = MIN(msize, MSIZE9P);
761 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
762 np_version(hdr->tag, msize, VERSION9P);
763 return;
765 mismatch:
766 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
767 version);
768 np_version(hdr->tag, MSIZE9P, "unknown");
769 return;
771 err:
772 client_send_listener(IMSG_CLOSE, NULL, 0);
773 client_shutdown();
776 static void
777 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
779 struct qid *qid;
780 struct fid *f;
781 uint32_t fid, afid;
782 int fd;
783 char aname[PATH_MAX];
785 if (attached) {
786 np_error(hdr->tag, "already attached");
787 return;
790 /* fid[4] afid[4] uname[s] aname[s] */
792 if (!NPREAD32("fid", &fid, &data, &len) ||
793 !NPREAD32("afid", &afid, &data, &len))
794 goto err;
796 /* read the uname but don't actually use it */
797 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
798 case READSTRERR:
799 goto err;
800 case READSTRTRUNC:
801 np_error(hdr->tag, "name too long");
802 return;
805 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
806 case READSTRERR:
807 goto err;
808 case READSTRTRUNC:
809 np_error(hdr->tag, "name too long");
810 return;
813 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
814 goto fail;
816 if ((qid = qid_from_fd(fd, NULL, NULL)) == NULL)
817 goto fail;
819 log_debug("attached %s", aname);
821 if ((f = new_fid(qid, fid)) == NULL) {
822 qid_decref(qid);
823 goto fail;
826 np_attach(hdr->tag, qid);
827 attached = 1;
828 return;
830 fail:
831 np_errno(hdr->tag);
832 log_warn("failed to attach %s", aname);
833 return;
834 return;
836 err:
837 client_send_listener(IMSG_CLOSE, NULL, 0);
838 client_shutdown();
841 static void
842 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
844 struct fid *f;
845 uint32_t fid;
847 /* fid[4] */
848 if (!NPREAD32("fid", &fid, &data, &len)) {
849 client_send_listener(IMSG_CLOSE, NULL, 0);
850 client_shutdown();
851 return;
854 if ((f = fid_by_id(fid)) == NULL) {
855 np_error(hdr->tag, "invalid fid");
856 return;
859 free_fid(f);
860 np_clunk(hdr->tag);
863 static void
864 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
866 uint16_t oldtag;
868 /*
869 * We're doing only synchronous I/O. Tflush is implemented
870 * only because it's illegal to reply with a Rerror.
871 */
873 /* oldtag[2] */
874 if (len != sizeof(oldtag)) {
875 log_warnx("Tclunk with the wrong size: got %zu want %zu",
876 len, sizeof(oldtag));
877 client_send_listener(IMSG_CLOSE, NULL, 0);
878 client_shutdown();
879 return;
882 np_flush(hdr->tag);
885 static void
886 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
888 struct stat sb;
889 struct qid *qid, wqid[MAXWELEM] = {0};
890 struct fid *f, *nf;
891 uint32_t fid, newfid;
892 uint16_t nwname;
893 int fd, oldfd, no, nwqid = 0;
894 char wnam[PATH_MAX+1];
896 if (!NPREAD32("fid", &fid, &data, &len) ||
897 !NPREAD32("newfid", &newfid, &data, &len) ||
898 !NPREAD16("nwname", &nwname, &data, &len))
899 goto err;
901 if (nwname > MAXWELEM) {
902 log_warnx("Twalk: more than %d path elements: %d",
903 MAXWELEM, nwname);
904 goto err;
907 if ((f = fid_by_id(fid)) == NULL) {
908 np_error(hdr->tag, "invalid fid");
909 return;
912 if (f->iomode != 0) {
913 np_error(hdr->tag, "fid already opened for I/O");
914 return;
917 if (fid == newfid)
918 nf = f;
919 else if ((nf = fid_by_id(newfid)) != NULL) {
920 np_error(hdr->tag, "newfid already in use");
921 return;
922 } else
923 nf = NULL;
925 /* special case: fid duplication */
926 if (nwname == 0) {
927 /*
928 * TODO: should we forbid fids duplication when fid ==
929 * newfid?
930 */
931 if (nf == NULL && (nf = new_fid(f->qid, newfid)) == NULL)
932 fatal("new_fid duplication");
934 np_walk(hdr->tag, 1, f->qid);
935 return;
938 if (f->qid->type != QTDIR) {
939 np_error(hdr->tag, "fid doesn't represent a directory");
940 return;
943 oldfd = f->qid->fd;
945 for (nwqid = 0; nwqid < nwname; nwqid++) {
946 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
947 case READSTRERR:
948 goto err;
949 case READSTRTRUNC:
950 np_error(hdr->tag, "wname too long");
951 return;
954 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
955 errno != ENOTDIR) {
956 nwqid--;
957 goto cantopen;
960 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
961 (fd != -1 && fstat(fd, &sb) == -1)) {
962 nwqid--;
963 goto cantopen;
966 qid_update_from_sb(&wqid[nwqid], &sb);
968 /* reached a file but we still have other components */
969 if (fd == -1 && nwqid+1 < nwname)
970 goto cantopen;
972 /* reached the end and found a file */
973 if (fd == -1 && nwqid+1 == nwname)
974 continue;
976 if (oldfd != f->qid->fd)
977 close(oldfd);
978 oldfd = fd;
981 /*
982 * There can be two possibilities: fd == -1 means that we've
983 * reached a file and we should save BOTH the dirfd (oldfd)
984 * and the path (wnam); or we just reached another directory,
985 * in which case we can just create a new qid using fd.
986 */
987 if (fd == -1)
988 qid = qid_from_fd(oldfd, wnam, &sb);
989 else
990 qid = qid_from_fd(oldfd, NULL, &sb);
991 if (qid == NULL)
992 fatal("qid_from_fd");
994 if (nf == NULL) {
995 if ((nf = new_fid(qid, newfid)) == NULL)
996 fatal("new_fid");
997 } else {
998 /* swap qid */
999 qid_decref(nf->qid);
1000 nf->qid = qid_incref(qid);
1003 np_walk(hdr->tag, nwqid, wqid);
1004 return;
1006 cantopen:
1007 if (oldfd != f->qid->fd)
1008 close(oldfd);
1009 no = errno;
1010 if (nwqid == 0)
1011 np_error(hdr->tag, strerror(no));
1012 else
1013 np_walk(hdr->tag, nwqid, wqid);
1014 return;
1016 err:
1017 client_send_listener(IMSG_CLOSE, NULL, 0);
1018 client_shutdown();
1021 static inline int
1022 npmode_to_unix(uint8_t mode, int *flags)
1024 switch (mode & 0x0F) {
1025 case KOREAD:
1026 *flags = O_RDONLY;
1027 break;
1028 case KOWRITE:
1029 *flags = O_WRONLY;
1030 break;
1031 case KORDWR:
1032 *flags = O_RDWR;
1033 break;
1034 case KOEXEC:
1035 log_warnx("tried to open something with KOEXEC");
1036 /* fallthrough */
1037 default:
1038 return -1;
1041 if (mode & KOTRUNC)
1042 *flags |= O_TRUNC;
1043 if (mode & KORCLOSE)
1044 *flags |= O_CLOEXEC;
1046 return 0;
1049 static void
1050 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1052 struct stat sb;
1053 struct qid qid;
1054 struct fid *f;
1055 uint32_t fid;
1056 uint8_t mode;
1058 /* fid[4] mode[1] */
1059 if (!NPREAD32("fid", &fid, &data, &len) ||
1060 !NPREAD8("mode", &mode, &data, &len)) {
1061 client_send_listener(IMSG_CLOSE, NULL, 0);
1062 client_shutdown();
1063 return;
1066 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1067 np_error(hdr->tag, "invalid fid");
1068 return;
1071 if (f->qid->type & QTDIR) {
1073 * XXX: real 9P2000 uses reads on directories to list the
1074 * files, but 9P2000.L (and possibly .U too) uses
1075 * Treaddir. It's my intention to support the 9p-style
1076 * read-on-dir, just not yet.
1078 np_error(hdr->tag, "can't do I/O on directories yet");
1079 return;
1082 if (npmode_to_unix(mode, &f->iomode) == -1) {
1083 np_error(hdr->tag, "invalid mode");
1084 return;
1087 if ((f->fd = openat(f->qid->fd, f->qid->fpath, f->iomode)) == -1) {
1088 np_error(hdr->tag, strerror(errno));
1089 return;
1092 if (fstat(f->fd, &sb) == -1)
1093 fatal("fstat");
1095 qid_update_from_sb(&qid, &sb);
1096 np_open(hdr->tag, &qid, sb.st_blksize);
1099 static void
1100 handle_message(struct imsg *imsg, size_t len)
1102 struct msg {
1103 uint8_t type;
1104 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1105 } msgs[] = {
1106 {Tversion, tversion},
1107 {Tattach, tattach},
1108 {Tclunk, tclunk},
1109 {Tflush, tflush},
1110 {Twalk, twalk},
1111 {Topen, topen},
1113 struct np_msg_header hdr;
1114 size_t i;
1115 uint8_t *data;
1117 #if DEBUG_PACKETS
1118 hexdump("incoming packet", imsg->data, len);
1119 #endif
1121 parse_message(imsg->data, len, &hdr, &data);
1122 len -= HEADERSIZE;
1124 log_debug("got request: len=%d type=%d[%s] tag=%d",
1125 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1127 if (!handshaked && hdr.type != Tversion) {
1128 client_send_listener(IMSG_CLOSE, NULL, 0);
1129 client_shutdown();
1130 return;
1133 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1134 if (msgs[i].type != hdr.type)
1135 continue;
1137 msgs[i].fn(&hdr, data, len);
1138 return;
1141 np_error(hdr.tag, "Not supported.");