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+1];
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;
80 uint64_t offset;
82 struct qid *qid;
83 STAILQ_ENTRY(fid) entries;
84 };
86 static struct imsgev *iev_listener;
87 static struct evbuffer *evb;
88 static uint32_t peerid;
90 static int handshaked;
91 uint32_t msize;
93 static ATTR_DEAD void client_shutdown(void);
94 static void client_sig_handler(int, short, void *);
95 static void client_dispatch_listener(int, short, void *);
96 static void client_privdrop(const char *, const char *);
98 static int client_send_listener(int, const void *, uint16_t);
100 static void qid_update_from_sb(struct qid *, struct stat *);
101 static struct qid *qid_from_fd(int, const char *, struct stat *);
102 static struct qid *qid_incref(struct qid *);
103 static void qid_decref(struct qid *);
105 static struct fid *new_fid(struct qid *, uint32_t);
106 static struct fid *fid_by_id(uint32_t);
107 static void free_fid(struct fid *);
109 static void parse_message(const uint8_t *, size_t,
110 struct np_msg_header *, uint8_t **);
112 static void np_write16(uint16_t);
113 static void np_write32(uint32_t);
114 static void np_header(uint32_t, uint8_t, uint16_t);
115 static void np_string(uint16_t, const char *);
116 static void np_qid(struct qid *);
117 static void do_send(void);
119 static void np_version(uint16_t, uint32_t, const char *);
120 static void np_attach(uint16_t, struct qid *);
121 static void np_clunk(uint16_t);
122 static void np_flush(uint16_t);
123 static void np_walk(uint16_t, int, struct qid *);
124 static void np_open(uint16_t, struct qid *, uint32_t);
125 static void np_read(uint16_t, uint32_t, void *);
126 static void np_error(uint16_t, const char *);
127 static void np_errno(uint16_t);
129 static int np_read8(const char *, const char *, uint8_t *,
130 const uint8_t **, size_t *);
131 static int np_read16(const char *, const char *, uint16_t *,
132 const uint8_t **, size_t *);
133 static int np_read32(const char *, const char *, uint32_t *,
134 const uint8_t **, size_t *);
135 static int np_read64(const char *, const char *, uint64_t *,
136 const uint8_t **, size_t *);
138 #define READSTRERR -1
139 #define READSTRTRUNC -2
140 static int np_readstr(const char *, const char *, char *, size_t,
141 const uint8_t **, size_t *);
143 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
144 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
145 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
146 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
148 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
150 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
151 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
152 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
153 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
154 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
155 static void topen(struct np_msg_header *, const uint8_t *, size_t);
156 static void tread(struct np_msg_header *, const uint8_t *, size_t);
157 static void handle_message(struct imsg *, size_t);
159 ATTR_DEAD void
160 client(int debug, int verbose)
162 struct event ev_sigint, ev_sigterm;
164 log_init(debug, LOG_DAEMON);
165 log_setverbose(verbose);
167 setproctitle("client");
168 log_procinit("client");
170 log_debug("warming up");
172 event_init();
174 /* Setup signal handlers */
175 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
176 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
178 signal_add(&ev_sigint, NULL);
179 signal_add(&ev_sigterm, NULL);
181 signal(SIGPIPE, SIG_IGN);
182 signal(SIGHUP, SIG_IGN);
184 /* Setup pipe and event handler to the listener process */
185 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
186 fatal(NULL);
188 imsg_init(&iev_listener->ibuf, 3);
189 iev_listener->handler = client_dispatch_listener;
191 /* Setup event handlers. */
192 iev_listener->events = EV_READ;
193 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
194 iev_listener->events, iev_listener->handler, iev_listener);
195 event_add(&iev_listener->ev, NULL);
197 event_dispatch();
198 client_shutdown();
201 static ATTR_DEAD void
202 client_shutdown(void)
204 if (evb != NULL)
205 evbuffer_free(evb);
207 msgbuf_clear(&iev_listener->ibuf.w);
208 close(iev_listener->ibuf.fd);
210 free(iev_listener);
212 log_debug("client exiting");
213 exit(0);
216 static void
217 client_sig_handler(int sig, short event, void *d)
219 /*
220 * Normal signal handler rules don't apply because libevent
221 * decouples for us.
222 */
224 switch (sig) {
225 case SIGINT:
226 case SIGTERM:
227 client_shutdown();
228 default:
229 fatalx("unexpected signal %d", sig);
233 #define AUTH_NONE 0
234 #define AUTH_USER 1
235 #define AUTH_DONE 2
237 static void
238 client_dispatch_listener(int fd, short event, void *d)
240 static int auth = AUTH_NONE;
241 static char username[64] = {0};
242 static char dir[PATH_MAX] = {0};
243 struct imsg imsg;
244 struct imsgev *iev = d;
245 struct imsgbuf *ibuf;
246 ssize_t n;
247 int shut = 0;
249 ibuf = &iev->ibuf;
251 if (event & EV_READ) {
252 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
253 fatal("imsg_read error");
254 if (n == 0) /* Connection closed */
255 shut = 1;
257 if (event & EV_WRITE) {
258 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
259 fatal("msgbuf_write");
260 if (n == 0) /* Connection closed */
261 shut = 1;
264 for (;;) {
265 if ((n = imsg_get(ibuf, &imsg)) == -1)
266 fatal("%s: imsg_get error", __func__);
267 if (n == 0) /* No more messages. */
268 break;
270 switch (imsg.hdr.type) {
271 case IMSG_AUTH:
272 peerid = imsg.hdr.peerid;
273 if (auth)
274 fatalx("%s: IMSG_AUTH already done", __func__);
275 auth = AUTH_USER;
276 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
277 strlcpy(username, imsg.data, sizeof(username));
278 break;
279 case IMSG_AUTH_DIR:
280 if (auth != AUTH_USER)
281 fatalx("%s: IMSG_AUTH_DIR not after IMSG_AUTH",
282 __func__);
283 auth = AUTH_DONE;
284 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
285 strlcpy(dir, imsg.data, sizeof(dir));
286 client_privdrop(username, dir);
287 memset(username, 0, sizeof(username));
288 memset(dir, 0, sizeof(username));
289 break;
290 case IMSG_BUF:
291 /* echo! */
292 if (!auth)
293 fatalx("%s: can't handle messages before"
294 " doing the auth", __func__);
295 handle_message(&imsg, IMSG_DATA_SIZE(imsg));
296 break;
297 case IMSG_CONN_GONE:
298 log_debug("closing");
299 shut = 1;
300 break;
301 default:
302 log_debug("%s: unexpected imsg %d",
303 __func__, imsg.hdr.type);
304 break;
306 imsg_free(&imsg);
309 if (!shut)
310 imsg_event_add(iev);
311 else {
312 /* This pipe is dead. Remove its event handler. */
313 event_del(&iev->ev);
314 log_debug("pipe closed, shutting down...");
315 event_loopexit(NULL);
319 static void
320 client_privdrop(const char *username, const char *dir)
322 struct passwd *pw;
324 setproctitle("client %s", username);
326 if ((pw = getpwnam(username)) == NULL)
327 fatalx("getpwnam(%s) failed", username);
329 if (chroot(dir) == -1)
330 fatal("chroot");
331 if (chdir("/") == -1)
332 fatal("chdir(\"/\")");
334 if (setgroups(1, &pw->pw_gid) ||
335 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
336 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
337 fatal("can't drop privileges");
339 sandbox_client();
340 log_debug("client ready; user=%s dir=%s", username, dir);
342 if ((evb = evbuffer_new()) == NULL)
343 fatal("evbuffer_new");
346 static int
347 client_send_listener(int type, const void *data, uint16_t len)
349 int ret;
351 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
352 data, len)) != -1)
353 imsg_event_add(iev_listener);
355 return ret;
358 /* set qid fields from sb */
359 static void
360 qid_update_from_sb(struct qid *qid, struct stat *sb)
362 qid->path = sb->st_ino;
364 /*
365 * Theoretically (and hopefully!) this should be a 64 bit
366 * number. Unfortunately, 9P uses 32 bit timestamps.
367 */
368 qid->vers = sb->st_mtim.tv_sec;
370 if (S_ISREG(sb->st_mode))
371 qid->type = QTFILE;
372 else if (S_ISDIR(sb->st_mode))
373 qid->type = QTDIR;
374 else if (S_ISLNK(sb->st_mode))
375 qid->type = QTSYMLINK;
378 /* creates a qid given a fd */
379 static struct qid *
380 qid_from_fd(int fd, const char *path, struct stat *s)
382 struct qid *qid;
383 struct stat sb;
384 int r;
386 if ((qid = calloc(1, sizeof(*qid))) == NULL)
387 return NULL;
389 if (path != NULL)
390 strlcpy(qid->fpath, path, sizeof(qid->fpath));
392 qid->fd = fd;
394 if (s == NULL) {
395 s = &sb;
396 if (path == NULL)
397 r = fstat(fd, s);
398 else
399 r = fstatat(fd, path, s, 0);
400 if (r == -1) {
401 free(qid);
402 return NULL;
406 qid_update_from_sb(qid, s);
408 STAILQ_INSERT_HEAD(&qids, qid, entries);
410 return qid;
413 static struct qid *
414 qid_incref(struct qid *qid)
416 qid->refcount++;
417 return qid;
420 static void
421 qid_decref(struct qid *qid)
423 if (--qid->refcount > 0)
424 return;
426 STAILQ_REMOVE(&qids, qid, qid, entries);
428 close(qid->fd);
429 free(qid);
432 static struct fid *
433 new_fid(struct qid *qid, uint32_t fid)
435 struct fid *f;
437 if ((f = calloc(1, sizeof(*f))) == NULL)
438 return NULL;
440 f->qid = qid_incref(qid);
441 f->fid = fid;
442 f->fd = -1;
444 STAILQ_INSERT_HEAD(&fids, f, entries);
446 return f;
449 static struct fid *
450 fid_by_id(uint32_t fid)
452 struct fid *f;
454 STAILQ_FOREACH(f, &fids, entries) {
455 if (f->fid == fid)
456 return f;
459 return NULL;
462 static void
463 free_fid(struct fid *f)
465 int r;
467 if (f->fd != -1) {
468 if (f->dir != NULL)
469 r = closedir(f->dir);
470 else
471 r = close(f->fd);
473 if (r == -1)
474 fatal("can't close fid %d", f->fid);
476 evbuffer_free(f->evb);
478 /* try to honour ORCLOSE if requested */
479 if (f->iomode & O_CLOEXEC)
480 unlinkat(f->qid->fd, f->qid->fpath, 0);
483 qid_decref(f->qid);
485 STAILQ_REMOVE(&fids, f, fid, entries);
486 free(f);
489 static void
490 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
491 uint8_t **cnt)
493 size_t olen = len;
495 if (!NPREAD32("len", &hdr->len, &data, &len) ||
496 !NPREAD8("type", &hdr->type, &data, &len) ||
497 !NPREAD16("tag", &hdr->tag, &data, &len))
498 goto err;
500 if (olen != hdr->len)
501 goto err;
503 if (hdr->type < Tversion ||
504 hdr->type >= Tmax ||
505 hdr->type == Terror ||
506 (hdr->type & 0x1) != 0) /* cannot recv a R* */
507 goto err;
509 hdr->tag = le32toh(hdr->tag);
511 *cnt = (uint8_t *)data;
512 return;
514 err:
515 /* TODO: send a proper message to terminate the connection. */
516 fatalx("got invalid message");
519 static void
520 np_write16(uint16_t x)
522 x = htole16(x);
523 evbuffer_add(evb, &x, sizeof(x));
526 static void
527 np_write32(uint32_t x)
529 x = htole32(x);
530 evbuffer_add(evb, &x, sizeof(x));
533 static void
534 np_writebuf(size_t len, void *data)
536 evbuffer_add(evb, data, len);
539 static void
540 np_header(uint32_t len, uint8_t type, uint16_t tag)
542 len += HEADERSIZE;
544 len = htole32(len);
545 tag = htole16(tag);
547 evbuffer_add(evb, &len, sizeof(len));
548 evbuffer_add(evb, &type, sizeof(type));
549 evbuffer_add(evb, &tag, sizeof(tag));
552 static void
553 np_string(uint16_t len, const char *str)
555 uint16_t l = len;
557 len = htole16(len);
558 evbuffer_add(evb, &len, sizeof(len));
559 evbuffer_add(evb, str, l);
562 static void
563 np_qid(struct qid *qid)
565 uint64_t path;
566 uint32_t vers;
568 path = htole64(qid->path);
569 vers = htole32(qid->vers);
571 evbuffer_add(evb, &qid->type, sizeof(qid->type));
572 evbuffer_add(evb, &vers, sizeof(vers));
573 evbuffer_add(evb, &path, sizeof(path));
576 static void
577 do_send(void)
579 size_t len;
580 void *data;
582 len = EVBUFFER_LENGTH(evb);
583 data = EVBUFFER_DATA(evb);
585 #if DEBUG_PACKETS
586 hexdump("outgoing packet", data, len);
587 #endif
588 client_send_listener(IMSG_BUF, data, len);
589 evbuffer_drain(evb, len);
592 static void
593 np_version(uint16_t tag, uint32_t msize, const char *version)
595 uint16_t l;
597 l = strlen(version);
599 msize = htole32(msize);
601 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
602 evbuffer_add(evb, &msize, sizeof(msize));
603 np_string(l, version);
604 do_send();
607 static void
608 np_attach(uint16_t tag, struct qid *qid)
610 np_header(QIDSIZE, Rattach, tag);
611 np_qid(qid);
612 do_send();
615 static void
616 np_clunk(uint16_t tag)
618 np_header(0, Rclunk, tag);
619 do_send();
622 static void
623 np_flush(uint16_t tag)
625 np_header(0, Rflush, tag);
626 do_send();
629 static void
630 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
632 int i;
634 /* two bytes for the counter */
635 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
636 np_write16(nwqid);
637 for (i = 0; i < nwqid; ++i)
638 np_qid(wqid + i);
640 do_send();
643 static void
644 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
646 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
647 np_qid(qid);
648 np_write32(iounit);
649 do_send();
652 static void
653 np_read(uint16_t tag, uint32_t count, void *data)
655 np_header(sizeof(count) + count, Rread, tag);
656 np_write32(count);
657 np_writebuf(count, data);
658 do_send();
661 static void
662 np_error(uint16_t tag, const char *errstr)
664 uint16_t l;
666 l = strlen(errstr);
668 np_header(sizeof(l) + l, Rerror, tag);
669 np_string(l, errstr);
670 do_send();
673 static void
674 np_errno(uint16_t tag)
676 int saved_errno;
677 char buf[64];
679 saved_errno = errno;
681 strerror_r(errno, buf, sizeof(buf));
682 np_error(tag, buf);
684 errno = saved_errno;
687 static int
688 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
689 size_t *len)
691 if (*len < sizeof(*dst)) {
692 log_warnx("%s: wanted %zu bytes for the %s field but only "
693 "%zu are available.", t, sizeof(*dst), f, *len);
694 return -1;
697 memcpy(dst, *src, sizeof(*dst));
698 *src += sizeof(*dst);
699 *len -= sizeof(*dst);
701 return 1;
704 static int
705 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
706 size_t *len)
708 if (*len < sizeof(*dst)) {
709 log_warnx("%s: wanted %zu bytes for the %s field but only "
710 "%zu are available.", t, sizeof(*dst), f, *len);
711 return -1;
714 memcpy(dst, *src, sizeof(*dst));
715 *src += sizeof(*dst);
716 *len -= sizeof(*dst);
717 *dst = le16toh(*dst);
719 return 1;
722 static int
723 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
724 size_t *len)
726 if (*len < sizeof(*dst)) {
727 log_warnx("%s: wanted %zu bytes for the %s field but only "
728 "%zu are available.", t, sizeof(*dst), f, *len);
729 return -1;
732 memcpy(dst, *src, sizeof(*dst));
733 *src += sizeof(*dst);
734 *len -= sizeof(*dst);
735 *dst = le32toh(*dst);
737 return 1;
740 static int
741 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
742 size_t *len)
744 if (*len < sizeof(*dst)) {
745 log_warnx("%s: wanted %zu bytes for the %s field but only "
746 "%zu are available.", t, sizeof(*dst), f, *len);
747 return -1;
750 memcpy(dst, *src, sizeof(*dst));
751 *src += sizeof(*dst);
752 *len -= sizeof(*dst);
753 *dst = le64toh(*dst);
755 return 1;
758 static int
759 np_readstr(const char *t, const char *f, char *res, size_t reslen,
760 const uint8_t **src, size_t *len)
762 uint16_t sl;
763 char buf[32];
765 strlcpy(buf, f, sizeof(buf));
766 strlcat(buf, "-len", sizeof(buf));
768 if (!np_read16(t, buf, &sl, src, len))
769 return READSTRERR;
771 if (*len < sl) {
772 log_warnx("%s: wanted %d bytes for the %s field but only "
773 "%zu are available.", t, sl, f, *len);
774 return READSTRERR;
777 if (*len > reslen-1)
778 return READSTRTRUNC;
780 memcpy(res, *src, sl);
781 res[sl] = '\0';
782 *src += sl;
783 *len -= sl;
785 return 0;
788 static void
789 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
791 char *dot, version[32];
793 if (handshaked)
794 goto err;
796 /* msize[4] version[s] */
797 if (!NPREAD32("msize", &msize, &data, &len))
798 goto err;
800 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
801 case READSTRERR:
802 goto err;
803 case READSTRTRUNC:
804 log_warnx("9P version string too long, truncated");
805 goto mismatch;
808 if ((dot = strchr(version, '.')) != NULL)
809 *dot = '\0';
811 if (strcmp(version, VERSION9P) != 0 ||
812 msize == 0)
813 goto mismatch;
815 /* version matched */
816 handshaked = 1;
817 msize = MIN(msize, MSIZE9P);
818 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
819 np_version(hdr->tag, msize, VERSION9P);
820 return;
822 mismatch:
823 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
824 version);
825 np_version(hdr->tag, MSIZE9P, "unknown");
826 return;
828 err:
829 client_send_listener(IMSG_CLOSE, NULL, 0);
830 client_shutdown();
833 static void
834 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
836 struct qid *qid;
837 struct fid *f;
838 uint32_t fid, afid;
839 int fd;
840 char aname[PATH_MAX];
842 /* fid[4] afid[4] uname[s] aname[s] */
844 if (!NPREAD32("fid", &fid, &data, &len) ||
845 !NPREAD32("afid", &afid, &data, &len))
846 goto err;
848 /* read the uname but don't actually use it */
849 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
850 case READSTRERR:
851 goto err;
852 case READSTRTRUNC:
853 np_error(hdr->tag, "name too long");
854 return;
857 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
858 case READSTRERR:
859 goto err;
860 case READSTRTRUNC:
861 np_error(hdr->tag, "name too long");
862 return;
865 if (fid_by_id(fid) != NULL || afid != NOFID) {
866 np_error(hdr->tag, "invalid fid or afid");
867 return;
870 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
871 goto fail;
873 if ((qid = qid_from_fd(fd, NULL, NULL)) == NULL)
874 goto fail;
876 log_debug("attached %s to %d", aname, fid);
878 if ((f = new_fid(qid, fid)) == NULL) {
879 qid_decref(qid);
880 goto fail;
883 np_attach(hdr->tag, qid);
884 return;
886 fail:
887 np_errno(hdr->tag);
888 log_warn("failed to attach %s", aname);
889 return;
890 return;
892 err:
893 client_send_listener(IMSG_CLOSE, NULL, 0);
894 client_shutdown();
897 static void
898 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
900 struct fid *f;
901 uint32_t fid;
903 /* fid[4] */
904 if (!NPREAD32("fid", &fid, &data, &len)) {
905 client_send_listener(IMSG_CLOSE, NULL, 0);
906 client_shutdown();
907 return;
910 if ((f = fid_by_id(fid)) == NULL) {
911 np_error(hdr->tag, "invalid fid");
912 return;
915 free_fid(f);
916 np_clunk(hdr->tag);
919 static void
920 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
922 uint16_t oldtag;
924 /*
925 * We're doing only synchronous I/O. Tflush is implemented
926 * only because it's illegal to reply with a Rerror.
927 */
929 /* oldtag[2] */
930 if (len != sizeof(oldtag)) {
931 log_warnx("Tclunk with the wrong size: got %zu want %zu",
932 len, sizeof(oldtag));
933 client_send_listener(IMSG_CLOSE, NULL, 0);
934 client_shutdown();
935 return;
938 np_flush(hdr->tag);
941 static void
942 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
944 struct stat sb;
945 struct qid *qid, wqid[MAXWELEM] = {0};
946 struct fid *f, *nf;
947 uint32_t fid, newfid;
948 uint16_t nwname;
949 int fd, oldfd, no, nwqid = 0;
950 char wnam[PATH_MAX+1];
952 if (!NPREAD32("fid", &fid, &data, &len) ||
953 !NPREAD32("newfid", &newfid, &data, &len) ||
954 !NPREAD16("nwname", &nwname, &data, &len))
955 goto err;
957 if (nwname > MAXWELEM) {
958 log_warnx("Twalk: more than %d path elements: %d",
959 MAXWELEM, nwname);
960 goto err;
963 if ((f = fid_by_id(fid)) == NULL) {
964 np_error(hdr->tag, "invalid fid");
965 return;
968 if (f->fd != -1) {
969 np_error(hdr->tag, "fid already opened for I/O");
970 return;
973 if (fid == newfid)
974 nf = f;
975 else if ((nf = fid_by_id(newfid)) != NULL) {
976 np_error(hdr->tag, "newfid already in use");
977 return;
978 } else
979 nf = NULL;
981 /* special case: fid duplication */
982 if (nwname == 0) {
983 /*
984 * TODO: should we forbid fids duplication when fid ==
985 * newfid?
986 */
987 if (nf == NULL && (nf = new_fid(f->qid, newfid)) == NULL)
988 fatal("new_fid duplication");
990 np_walk(hdr->tag, 1, f->qid);
991 return;
994 if (f->qid->type != QTDIR) {
995 np_error(hdr->tag, "fid doesn't represent a directory");
996 return;
999 oldfd = f->qid->fd;
1001 for (nwqid = 0; nwqid < nwname; nwqid++) {
1002 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1003 case READSTRERR:
1004 goto err;
1005 case READSTRTRUNC:
1006 np_error(hdr->tag, "wname too long");
1007 return;
1010 if (*wnam == '\0' ||
1011 strchr(wnam, '/') != NULL ||
1012 !strcmp(wnam, ".")) {
1013 errno = EINVAL;
1014 goto cantopen;
1017 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1018 errno != ENOTDIR)
1019 goto cantopen;
1021 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1022 (fd != -1 && fstat(fd, &sb) == -1))
1023 goto cantopen;
1025 qid_update_from_sb(&wqid[nwqid], &sb);
1027 /* reached a file but we still have other components */
1028 if (fd == -1 && nwqid+1 < nwname)
1029 goto cantopen;
1031 /* reached the end and found a file */
1032 if (fd == -1 && nwqid+1 == nwname)
1033 continue;
1035 if (oldfd != f->qid->fd)
1036 close(oldfd);
1037 oldfd = fd;
1041 * There can be two possibilities: fd == -1 means that we've
1042 * reached a file and we should save BOTH the dirfd (oldfd)
1043 * and the path (wnam); or we just reached another directory,
1044 * in which case we can just create a new qid using fd.
1046 if (fd == -1)
1047 qid = qid_from_fd(oldfd, wnam, &sb);
1048 else
1049 qid = qid_from_fd(oldfd, NULL, &sb);
1050 if (qid == NULL)
1051 fatal("qid_from_fd");
1053 if (nf == NULL) {
1054 if ((nf = new_fid(qid, newfid)) == NULL)
1055 fatal("new_fid");
1056 } else {
1057 /* swap qid */
1058 qid_decref(nf->qid);
1059 nf->qid = qid_incref(qid);
1062 np_walk(hdr->tag, nwqid, wqid);
1063 return;
1065 cantopen:
1066 if (oldfd != f->qid->fd)
1067 close(oldfd);
1068 no = errno;
1069 if (nwqid == 0)
1070 np_error(hdr->tag, strerror(no));
1071 else
1072 np_walk(hdr->tag, nwqid, wqid);
1073 return;
1075 err:
1076 client_send_listener(IMSG_CLOSE, NULL, 0);
1077 client_shutdown();
1080 static inline int
1081 npmode_to_unix(uint8_t mode, int *flags)
1083 switch (mode & 0x0F) {
1084 case KOREAD:
1085 *flags = O_RDONLY;
1086 break;
1087 case KOWRITE:
1088 *flags = O_WRONLY;
1089 break;
1090 case KORDWR:
1091 *flags = O_RDWR;
1092 break;
1093 case KOEXEC:
1094 log_warnx("tried to open something with KOEXEC");
1095 /* fallthrough */
1096 default:
1097 return -1;
1100 if (mode & KOTRUNC)
1101 *flags |= O_TRUNC;
1102 if (mode & KORCLOSE)
1103 *flags |= O_CLOEXEC;
1105 return 0;
1108 static void
1109 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1111 struct stat sb;
1112 struct qid qid;
1113 struct fid *f;
1114 uint32_t fid;
1115 uint8_t mode;
1116 const char *path;
1118 /* fid[4] mode[1] */
1119 if (!NPREAD32("fid", &fid, &data, &len) ||
1120 !NPREAD8("mode", &mode, &data, &len)) {
1121 client_send_listener(IMSG_CLOSE, NULL, 0);
1122 client_shutdown();
1123 return;
1126 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1127 np_error(hdr->tag, "invalid fid");
1128 return;
1131 if (npmode_to_unix(mode, &f->iomode) == -1) {
1132 np_error(hdr->tag, "invalid mode");
1133 return;
1136 if (f->qid->type & QTDIR &&
1137 (f->iomode & O_WRONLY || f->iomode & O_RDWR)) {
1138 np_error(hdr->tag, "can't open directory for writing");
1139 return;
1142 path = f->qid->fpath;
1143 if (*path == '\0')
1144 path = ".";
1146 if ((f->fd = openat(f->qid->fd, path, f->iomode)) == -1) {
1147 np_error(hdr->tag, strerror(errno));
1148 return;
1151 if (fstat(f->fd, &sb) == -1)
1152 fatal("fstat");
1154 if (S_ISDIR(sb.st_mode)) {
1155 assert(f->qid->type & QTDIR);
1156 if ((f->dir = fdopendir(f->fd)) == NULL) {
1157 np_errno(hdr->tag);
1158 close(f->fd);
1159 f->fd = -1;
1160 return;
1163 if ((f->evb = evbuffer_new()) == NULL) {
1164 np_errno(hdr->tag);
1165 closedir(f->dir);
1166 f->dir = NULL;
1167 f->fd = -1;
1171 f->offset = 0;
1173 qid_update_from_sb(&qid, &sb);
1174 np_open(hdr->tag, &qid, sb.st_blksize);
1177 static void
1178 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1180 struct fid *f;
1181 ssize_t r;
1182 uint64_t off;
1183 uint32_t fid, count;
1184 char buf[2048];
1186 /* fid[4] offset[8] count[4] */
1187 if (!NPREAD32("fid", &fid, &data, &len) ||
1188 !NPREAD64("offset", &off, &data, &len) ||
1189 !NPREAD32("count", &count, &data, &len)) {
1190 client_send_listener(IMSG_CLOSE, NULL, 0);
1191 client_shutdown();
1192 return;
1195 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1196 np_error(hdr->tag, "invalid fid");
1197 return;
1200 if (TYPE_OVERFLOW(off_t, off)) {
1201 log_warnx("unexpected size_t size");
1202 np_error(hdr->tag, "invalid offset");
1203 return;
1206 if (f->dir == NULL) {
1207 /* read a file */
1208 r = pread(f->fd, buf, sizeof(buf), (off_t)off);
1209 if (r == -1)
1210 np_errno(hdr->tag);
1211 else
1212 np_read(hdr->tag, r, buf);
1213 } else {
1214 /* read dirents */
1215 np_error(hdr->tag, "not implemented yet");
1219 static void
1220 handle_message(struct imsg *imsg, size_t len)
1222 struct msg {
1223 uint8_t type;
1224 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1225 } msgs[] = {
1226 {Tversion, tversion},
1227 {Tattach, tattach},
1228 {Tclunk, tclunk},
1229 {Tflush, tflush},
1230 {Twalk, twalk},
1231 {Topen, topen},
1232 {Tread, tread},
1234 struct np_msg_header hdr;
1235 size_t i;
1236 uint8_t *data;
1238 #if DEBUG_PACKETS
1239 hexdump("incoming packet", imsg->data, len);
1240 #endif
1242 parse_message(imsg->data, len, &hdr, &data);
1243 len -= HEADERSIZE;
1245 log_debug("got request: len=%d type=%d[%s] tag=%d",
1246 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1248 if (!handshaked && hdr.type != Tversion) {
1249 client_send_listener(IMSG_CLOSE, NULL, 0);
1250 client_shutdown();
1251 return;
1254 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1255 if (msgs[i].type != hdr.type)
1256 continue;
1258 msgs[i].fn(&hdr, data, len);
1259 return;
1262 np_error(hdr.tag, "Not supported.");