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_create(uint16_t, struct qid *, uint32_t);
131 static void np_read(uint16_t, uint32_t, void *);
132 static void np_write(uint16_t, uint32_t);
133 static void np_stat(uint16_t, uint32_t, void *);
134 static void np_remove(uint16_t);
135 static void np_error(uint16_t, const char *);
136 static void np_errno(uint16_t);
138 static int np_read8(const char *, const char *, uint8_t *,
139 const uint8_t **, size_t *);
140 static int np_read16(const char *, const char *, uint16_t *,
141 const uint8_t **, size_t *);
142 static int np_read32(const char *, const char *, uint32_t *,
143 const uint8_t **, size_t *);
144 static int np_read64(const char *, const char *, uint64_t *,
145 const uint8_t **, size_t *);
147 #define READSTRERR -1
148 #define READSTRTRUNC -2
149 static int np_readstr(const char *, const char *, char *, size_t,
150 const uint8_t **, size_t *);
152 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
153 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
154 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
155 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
157 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
159 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
160 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
161 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
162 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
163 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
164 static void topen(struct np_msg_header *, const uint8_t *, size_t);
165 static void tcreate(struct np_msg_header *, const uint8_t *, size_t);
166 static void tread(struct np_msg_header *, const uint8_t *, size_t);
167 static void twrite(struct np_msg_header *, const uint8_t *, size_t);
168 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
169 static void tremove(struct np_msg_header *, const uint8_t *, size_t);
170 static void handle_message(struct imsg *, size_t);
172 ATTR_DEAD void
173 client(int debug, int verbose)
175 struct event ev_sigint, ev_sigterm;
177 log_init(debug, LOG_DAEMON);
178 log_setverbose(verbose);
180 setproctitle("client");
181 log_procinit("client");
183 log_debug("warming up");
185 event_init();
187 /* Setup signal handlers */
188 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
189 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
191 signal_add(&ev_sigint, NULL);
192 signal_add(&ev_sigterm, NULL);
194 signal(SIGPIPE, SIG_IGN);
195 signal(SIGHUP, SIG_IGN);
197 /* Setup pipe and event handler to the listener process */
198 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
199 fatal(NULL);
201 imsg_init(&iev_listener->ibuf, 3);
202 iev_listener->handler = client_dispatch_listener;
204 /* Setup event handlers. */
205 iev_listener->events = EV_READ;
206 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
207 iev_listener->events, iev_listener->handler, iev_listener);
208 event_add(&iev_listener->ev, NULL);
210 event_dispatch();
211 client_shutdown();
214 static ATTR_DEAD void
215 client_shutdown(void)
217 if (evb != NULL)
218 evbuffer_free(evb);
220 msgbuf_clear(&iev_listener->ibuf.w);
221 close(iev_listener->ibuf.fd);
223 free(iev_listener);
225 log_debug("client exiting");
226 exit(0);
229 static void
230 client_sig_handler(int sig, short event, void *d)
232 /*
233 * Normal signal handler rules don't apply because libevent
234 * decouples for us.
235 */
237 switch (sig) {
238 case SIGINT:
239 case SIGTERM:
240 client_shutdown();
241 default:
242 fatalx("unexpected signal %d", sig);
246 #define AUTH_NONE 0
247 #define AUTH_USER 1
248 #define AUTH_DONE 2
250 static void
251 client_dispatch_listener(int fd, short event, void *d)
253 static int auth = AUTH_NONE;
254 static char username[64] = {0};
255 static char dir[PATH_MAX] = {0};
256 struct imsg imsg;
257 struct imsgev *iev = d;
258 struct imsgbuf *ibuf;
259 ssize_t n;
260 int shut = 0;
262 ibuf = &iev->ibuf;
264 if (event & EV_READ) {
265 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
266 fatal("imsg_read error");
267 if (n == 0) /* Connection closed */
268 shut = 1;
270 if (event & EV_WRITE) {
271 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
272 fatal("msgbuf_write");
273 if (n == 0) /* Connection closed */
274 shut = 1;
277 for (;;) {
278 if ((n = imsg_get(ibuf, &imsg)) == -1)
279 fatal("%s: imsg_get error", __func__);
280 if (n == 0) /* No more messages. */
281 break;
283 switch (imsg.hdr.type) {
284 case IMSG_AUTH:
285 peerid = imsg.hdr.peerid;
286 if (auth)
287 fatalx("%s: IMSG_AUTH already done", __func__);
288 auth = AUTH_USER;
289 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
290 strlcpy(username, imsg.data, sizeof(username));
291 break;
292 case IMSG_AUTH_DIR:
293 if (auth != AUTH_USER)
294 fatalx("%s: IMSG_AUTH_DIR not after IMSG_AUTH",
295 __func__);
296 auth = AUTH_DONE;
297 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
298 strlcpy(dir, imsg.data, sizeof(dir));
299 client_privdrop(username, dir);
300 memset(username, 0, sizeof(username));
301 memset(dir, 0, sizeof(username));
302 break;
303 case IMSG_BUF:
304 /* echo! */
305 if (!auth)
306 fatalx("%s: can't handle messages before"
307 " doing the auth", __func__);
308 handle_message(&imsg, IMSG_DATA_SIZE(imsg));
309 break;
310 case IMSG_CONN_GONE:
311 log_debug("closing");
312 shut = 1;
313 break;
314 default:
315 log_debug("%s: unexpected imsg %d",
316 __func__, imsg.hdr.type);
317 break;
319 imsg_free(&imsg);
322 if (!shut)
323 imsg_event_add(iev);
324 else {
325 /* This pipe is dead. Remove its event handler. */
326 event_del(&iev->ev);
327 log_debug("pipe closed, shutting down...");
328 event_loopexit(NULL);
332 static void
333 client_privdrop(const char *username, const char *dir)
335 struct passwd *pw;
337 setproctitle("client %s", username);
339 if ((pw = getpwnam(username)) == NULL)
340 fatalx("getpwnam(%s) failed", username);
342 if (chroot(dir) == -1)
343 fatal("chroot");
344 if (chdir("/") == -1)
345 fatal("chdir(\"/\")");
347 if (setgroups(1, &pw->pw_gid) ||
348 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
349 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
350 fatal("can't drop privileges");
352 sandbox_client();
353 log_debug("client ready; user=%s dir=%s", username, dir);
355 if ((evb = evbuffer_new()) == NULL)
356 fatal("evbuffer_new");
359 static int
360 client_send_listener(int type, const void *data, uint16_t len)
362 int ret;
364 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
365 data, len)) != -1)
366 imsg_event_add(iev_listener);
368 return ret;
371 /* set qid fields from sb */
372 static void
373 qid_update_from_sb(struct qid *qid, struct stat *sb)
375 qid->path = sb->st_ino;
377 /*
378 * Theoretically (and hopefully!) this should be a 64 bit
379 * number. Unfortunately, 9P uses 32 bit timestamps.
380 */
381 qid->vers = sb->st_mtim.tv_sec;
383 if (S_ISREG(sb->st_mode))
384 qid->type = QTFILE;
385 else if (S_ISDIR(sb->st_mode))
386 qid->type = QTDIR;
387 else if (S_ISLNK(sb->st_mode))
388 qid->type = QTSYMLINK;
391 /* creates a qid given a fd */
392 static struct qid *
393 qid_from_fd(int fd, const char *path, struct stat *s)
395 struct qid *qid;
396 struct stat sb;
397 int r;
399 if ((qid = calloc(1, sizeof(*qid))) == NULL)
400 return NULL;
402 if (path != NULL)
403 strlcpy(qid->fpath, path, sizeof(qid->fpath));
405 qid->fd = fd;
407 if (s == NULL) {
408 s = &sb;
409 if (path == NULL)
410 r = fstat(fd, s);
411 else
412 r = fstatat(fd, path, s, 0);
413 if (r == -1) {
414 free(qid);
415 return NULL;
419 qid_update_from_sb(qid, s);
421 STAILQ_INSERT_HEAD(&qids, qid, entries);
423 return qid;
426 static struct qid *
427 qid_incref(struct qid *qid)
429 qid->refcount++;
430 return qid;
433 static void
434 qid_decref(struct qid *qid)
436 if (--qid->refcount > 0)
437 return;
439 STAILQ_REMOVE(&qids, qid, qid, entries);
441 close(qid->fd);
442 free(qid);
445 static struct fid *
446 new_fid(struct qid *qid, uint32_t fid)
448 struct fid *f;
450 if ((f = calloc(1, sizeof(*f))) == NULL)
451 return NULL;
453 f->qid = qid_incref(qid);
454 f->fid = fid;
455 f->fd = -1;
457 STAILQ_INSERT_HEAD(&fids, f, entries);
459 return f;
462 static struct fid *
463 fid_by_id(uint32_t fid)
465 struct fid *f;
467 STAILQ_FOREACH(f, &fids, entries) {
468 if (f->fid == fid)
469 return f;
472 return NULL;
475 static void
476 free_fid(struct fid *f)
478 int r;
480 if (f->fd != -1) {
481 if (f->dir != NULL)
482 r = closedir(f->dir);
483 else
484 r = close(f->fd);
486 if (r == -1)
487 fatal("can't close fid %d", f->fid);
489 if (f->evb != NULL)
490 evbuffer_free(f->evb);
492 /* try to honour ORCLOSE if requested */
493 if (f->iomode & O_CLOEXEC)
494 unlinkat(f->qid->fd, f->qid->fpath, 0);
497 qid_decref(f->qid);
499 STAILQ_REMOVE(&fids, f, fid, entries);
500 free(f);
503 static void
504 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
505 uint8_t **cnt)
507 size_t olen = len;
509 if (!NPREAD32("len", &hdr->len, &data, &len) ||
510 !NPREAD8("type", &hdr->type, &data, &len) ||
511 !NPREAD16("tag", &hdr->tag, &data, &len))
512 goto err;
514 if (olen != hdr->len)
515 goto err;
517 if (hdr->type < Tversion ||
518 hdr->type >= Tmax ||
519 hdr->type == Terror ||
520 (hdr->type & 0x1) != 0) /* cannot recv a R* */
521 goto err;
523 hdr->tag = le32toh(hdr->tag);
525 *cnt = (uint8_t *)data;
526 return;
528 err:
529 /* TODO: send a proper message to terminate the connection. */
530 fatalx("got invalid message");
533 static void
534 np_write16(struct evbuffer *e, uint16_t x)
536 x = htole16(x);
537 evbuffer_add(e, &x, sizeof(x));
540 static void
541 np_write32(struct evbuffer *e, uint32_t x)
543 x = htole32(x);
544 evbuffer_add(e, &x, sizeof(x));
547 static void
548 np_write64(struct evbuffer *e, uint64_t x)
550 x = htole64(x);
551 evbuffer_add(e, &x, sizeof(x));
554 static void
555 np_writebuf(struct evbuffer *e, size_t len, void *data)
557 evbuffer_add(e, data, len);
560 static void
561 np_header(uint32_t len, uint8_t type, uint16_t tag)
563 len += HEADERSIZE;
565 len = htole32(len);
566 tag = htole16(tag);
568 evbuffer_add(evb, &len, sizeof(len));
569 evbuffer_add(evb, &type, sizeof(type));
570 evbuffer_add(evb, &tag, sizeof(tag));
573 static void
574 np_string(struct evbuffer *e, uint16_t len, const char *str)
576 uint16_t l = len;
578 len = htole16(len);
579 evbuffer_add(e, &len, sizeof(len));
580 evbuffer_add(e, str, l);
583 static void
584 np_qid(struct evbuffer *e, struct qid *qid)
586 uint64_t path;
587 uint32_t vers;
589 path = htole64(qid->path);
590 vers = htole32(qid->vers);
592 evbuffer_add(e, &qid->type, sizeof(qid->type));
593 evbuffer_add(e, &vers, sizeof(vers));
594 evbuffer_add(e, &path, sizeof(path));
597 static void
598 do_send(void)
600 size_t len;
601 void *data;
603 len = EVBUFFER_LENGTH(evb);
604 data = EVBUFFER_DATA(evb);
606 #if DEBUG_PACKETS
607 hexdump("outgoing packet", data, len);
608 #endif
609 client_send_listener(IMSG_BUF, data, len);
610 evbuffer_drain(evb, len);
613 static void
614 np_version(uint16_t tag, uint32_t msize, const char *version)
616 uint16_t l;
618 l = strlen(version);
620 msize = htole32(msize);
622 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
623 evbuffer_add(evb, &msize, sizeof(msize));
624 np_string(evb, l, version);
625 do_send();
628 static void
629 np_attach(uint16_t tag, struct qid *qid)
631 np_header(QIDSIZE, Rattach, tag);
632 np_qid(evb, qid);
633 do_send();
636 static void
637 np_clunk(uint16_t tag)
639 np_header(0, Rclunk, tag);
640 do_send();
643 static void
644 np_flush(uint16_t tag)
646 np_header(0, Rflush, tag);
647 do_send();
650 static void
651 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
653 int i;
655 /* two bytes for the counter */
656 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
657 np_write16(evb, nwqid);
658 for (i = 0; i < nwqid; ++i)
659 np_qid(evb, wqid + i);
661 do_send();
664 static void
665 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
667 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
668 np_qid(evb, qid);
669 np_write32(evb, iounit);
670 do_send();
673 static void
674 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
676 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
677 np_qid(evb, qid);
678 np_write32(evb, iounit);
679 do_send();
682 static void
683 np_read(uint16_t tag, uint32_t count, void *data)
685 np_header(sizeof(count) + count, Rread, tag);
686 np_write32(evb, count);
687 np_writebuf(evb, count, data);
688 do_send();
691 static void
692 np_write(uint16_t tag, uint32_t count)
694 np_header(sizeof(count), Rwrite, tag);
695 np_write32(evb, count);
696 do_send();
699 static void
700 np_stat(uint16_t tag, uint32_t count, void *data)
702 np_header(count, Rstat, tag);
703 np_writebuf(evb, count, data);
704 do_send();
707 static void
708 np_remove(uint16_t tag)
710 np_header(0, Rremove, tag);
711 do_send();
714 static void
715 np_error(uint16_t tag, const char *errstr)
717 uint16_t l;
719 l = strlen(errstr);
721 np_header(sizeof(l) + l, Rerror, tag);
722 np_string(evb, l, errstr);
723 do_send();
726 static void
727 np_errno(uint16_t tag)
729 int saved_errno;
730 char buf[64];
732 saved_errno = errno;
734 strerror_r(errno, buf, sizeof(buf));
735 np_error(tag, buf);
737 errno = saved_errno;
740 static int
741 np_read8(const char *t, const char *f, uint8_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);
754 return 1;
757 static int
758 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
759 size_t *len)
761 if (*len < sizeof(*dst)) {
762 log_warnx("%s: wanted %zu bytes for the %s field but only "
763 "%zu are available.", t, sizeof(*dst), f, *len);
764 return -1;
767 memcpy(dst, *src, sizeof(*dst));
768 *src += sizeof(*dst);
769 *len -= sizeof(*dst);
770 *dst = le16toh(*dst);
772 return 1;
775 static int
776 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
777 size_t *len)
779 if (*len < sizeof(*dst)) {
780 log_warnx("%s: wanted %zu bytes for the %s field but only "
781 "%zu are available.", t, sizeof(*dst), f, *len);
782 return -1;
785 memcpy(dst, *src, sizeof(*dst));
786 *src += sizeof(*dst);
787 *len -= sizeof(*dst);
788 *dst = le32toh(*dst);
790 return 1;
793 static int
794 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
795 size_t *len)
797 if (*len < sizeof(*dst)) {
798 log_warnx("%s: wanted %zu bytes for the %s field but only "
799 "%zu are available.", t, sizeof(*dst), f, *len);
800 return -1;
803 memcpy(dst, *src, sizeof(*dst));
804 *src += sizeof(*dst);
805 *len -= sizeof(*dst);
806 *dst = le64toh(*dst);
808 return 1;
811 static int
812 np_readstr(const char *t, const char *f, char *res, size_t reslen,
813 const uint8_t **src, size_t *len)
815 uint16_t sl;
816 char buf[32];
818 strlcpy(buf, f, sizeof(buf));
819 strlcat(buf, "-len", sizeof(buf));
821 if (!np_read16(t, buf, &sl, src, len))
822 return READSTRERR;
824 if (*len < sl) {
825 log_warnx("%s: wanted %d bytes for the %s field but only "
826 "%zu are available.", t, sl, f, *len);
827 return READSTRERR;
830 if (*len > reslen-1)
831 return READSTRTRUNC;
833 memcpy(res, *src, sl);
834 res[sl] = '\0';
835 *src += sl;
836 *len -= sl;
838 return 0;
841 static void
842 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
844 char *dot, version[32];
846 if (handshaked)
847 goto err;
849 /* msize[4] version[s] */
850 if (!NPREAD32("msize", &msize, &data, &len))
851 goto err;
853 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
854 case READSTRERR:
855 goto err;
856 case READSTRTRUNC:
857 log_warnx("9P version string too long, truncated");
858 goto mismatch;
861 if ((dot = strchr(version, '.')) != NULL)
862 *dot = '\0';
864 if (strcmp(version, VERSION9P) != 0 ||
865 msize == 0)
866 goto mismatch;
868 /* version matched */
869 handshaked = 1;
870 msize = MIN(msize, MSIZE9P);
871 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
872 np_version(hdr->tag, msize, VERSION9P);
873 return;
875 mismatch:
876 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
877 version);
878 np_version(hdr->tag, MSIZE9P, "unknown");
879 return;
881 err:
882 client_send_listener(IMSG_CLOSE, NULL, 0);
883 client_shutdown();
886 static void
887 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
889 struct qid *qid;
890 struct fid *f;
891 uint32_t fid, afid;
892 int fd;
893 char aname[PATH_MAX];
895 /* fid[4] afid[4] uname[s] aname[s] */
897 if (!NPREAD32("fid", &fid, &data, &len) ||
898 !NPREAD32("afid", &afid, &data, &len))
899 goto err;
901 /* read the uname but don't actually use it */
902 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
903 case READSTRERR:
904 goto err;
905 case READSTRTRUNC:
906 np_error(hdr->tag, "name too long");
907 return;
910 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
911 case READSTRERR:
912 goto err;
913 case READSTRTRUNC:
914 np_error(hdr->tag, "name too long");
915 return;
918 if (fid_by_id(fid) != NULL || afid != NOFID) {
919 np_error(hdr->tag, "invalid fid or afid");
920 return;
923 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
924 goto fail;
926 if ((qid = qid_from_fd(fd, NULL, NULL)) == NULL)
927 goto fail;
929 log_debug("attached %s to %d", aname, fid);
931 if ((f = new_fid(qid, fid)) == NULL) {
932 qid_decref(qid);
933 goto fail;
936 np_attach(hdr->tag, qid);
937 return;
939 fail:
940 np_errno(hdr->tag);
941 log_warn("failed to attach %s", aname);
942 return;
943 return;
945 err:
946 client_send_listener(IMSG_CLOSE, NULL, 0);
947 client_shutdown();
950 static void
951 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
953 struct fid *f;
954 uint32_t fid;
956 /* fid[4] */
957 if (!NPREAD32("fid", &fid, &data, &len)) {
958 client_send_listener(IMSG_CLOSE, NULL, 0);
959 client_shutdown();
960 return;
963 if ((f = fid_by_id(fid)) == NULL) {
964 np_error(hdr->tag, "invalid fid");
965 return;
968 free_fid(f);
969 np_clunk(hdr->tag);
972 static void
973 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
975 uint16_t oldtag;
977 /*
978 * We're doing only synchronous I/O. Tflush is implemented
979 * only because it's illegal to reply with a Rerror.
980 */
982 /* oldtag[2] */
983 if (len != sizeof(oldtag)) {
984 log_warnx("Tflush with the wrong size: got %zu want %zu",
985 len, sizeof(oldtag));
986 client_send_listener(IMSG_CLOSE, NULL, 0);
987 client_shutdown();
988 return;
991 np_flush(hdr->tag);
994 static void
995 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
997 struct stat sb;
998 struct qid *qid, wqid[MAXWELEM] = {0};
999 struct fid *f, *nf;
1000 uint32_t fid, newfid;
1001 uint16_t nwname;
1002 int fd, oldfd, no, nwqid = 0;
1003 char wnam[PATH_MAX];
1005 if (!NPREAD32("fid", &fid, &data, &len) ||
1006 !NPREAD32("newfid", &newfid, &data, &len) ||
1007 !NPREAD16("nwname", &nwname, &data, &len))
1008 goto err;
1010 if (nwname > MAXWELEM) {
1011 log_warnx("Twalk: more than %d path elements: %d",
1012 MAXWELEM, nwname);
1013 goto err;
1016 if ((f = fid_by_id(fid)) == NULL) {
1017 np_error(hdr->tag, "invalid fid");
1018 return;
1021 if (f->fd != -1) {
1022 np_error(hdr->tag, "fid already opened for I/O");
1023 return;
1026 if (fid == newfid)
1027 nf = f;
1028 else if ((nf = fid_by_id(newfid)) != NULL) {
1029 np_error(hdr->tag, "newfid already in use");
1030 return;
1031 } else
1032 nf = NULL;
1034 /* special case: fid duplication */
1035 if (nwname == 0) {
1037 * TODO: should we forbid fids duplication when fid ==
1038 * newfid?
1040 if (nf == NULL && (nf = new_fid(f->qid, newfid)) == NULL)
1041 fatal("new_fid duplication");
1043 np_walk(hdr->tag, 1, f->qid);
1044 return;
1047 if (f->qid->type != QTDIR) {
1048 np_error(hdr->tag, "fid doesn't represent a directory");
1049 return;
1052 oldfd = f->qid->fd;
1054 for (nwqid = 0; nwqid < nwname; nwqid++) {
1055 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1056 case READSTRERR:
1057 goto err;
1058 case READSTRTRUNC:
1059 np_error(hdr->tag, "wname too long");
1060 return;
1063 if (*wnam == '\0' ||
1064 strchr(wnam, '/') != NULL ||
1065 !strcmp(wnam, ".")) {
1066 errno = EINVAL;
1067 goto cantopen;
1070 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1071 errno != ENOTDIR)
1072 goto cantopen;
1074 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1075 (fd != -1 && fstat(fd, &sb) == -1))
1076 goto cantopen;
1078 qid_update_from_sb(&wqid[nwqid], &sb);
1080 /* reached a file but we still have other components */
1081 if (fd == -1 && nwqid+1 < nwname)
1082 goto cantopen;
1084 /* reached the end and found a file */
1085 if (fd == -1 && nwqid+1 == nwname)
1086 continue;
1088 if (oldfd != f->qid->fd)
1089 close(oldfd);
1090 oldfd = fd;
1094 * There can be two possibilities: fd == -1 means that we've
1095 * reached a file and we should save BOTH the dirfd (oldfd)
1096 * and the path (wnam); or we just reached another directory,
1097 * in which case we can just create a new qid using fd.
1099 if (fd == -1)
1100 qid = qid_from_fd(oldfd, wnam, &sb);
1101 else
1102 qid = qid_from_fd(oldfd, NULL, &sb);
1103 if (qid == NULL)
1104 fatal("qid_from_fd");
1106 if (nf == NULL) {
1107 if ((nf = new_fid(qid, newfid)) == NULL)
1108 fatal("new_fid");
1109 } else {
1110 /* swap qid */
1111 qid_decref(nf->qid);
1112 nf->qid = qid_incref(qid);
1115 np_walk(hdr->tag, nwqid, wqid);
1116 return;
1118 cantopen:
1119 if (oldfd != f->qid->fd)
1120 close(oldfd);
1121 no = errno;
1122 if (nwqid == 0)
1123 np_error(hdr->tag, strerror(no));
1124 else
1125 np_walk(hdr->tag, nwqid, wqid);
1126 return;
1128 err:
1129 client_send_listener(IMSG_CLOSE, NULL, 0);
1130 client_shutdown();
1133 static inline int
1134 npmode_to_unix(uint8_t mode, int *flags)
1136 switch (mode & 0x0F) {
1137 case KOREAD:
1138 *flags = O_RDONLY;
1139 break;
1140 case KOWRITE:
1141 *flags = O_WRONLY;
1142 break;
1143 case KORDWR:
1144 *flags = O_RDWR;
1145 break;
1146 case KOEXEC:
1147 log_warnx("tried to open something with KOEXEC");
1148 /* fallthrough */
1149 default:
1150 return -1;
1153 if (mode & KOTRUNC)
1154 *flags |= O_TRUNC;
1155 if (mode & KORCLOSE)
1156 *flags |= O_CLOEXEC;
1158 return 0;
1161 static void
1162 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1164 struct stat sb;
1165 struct qid qid;
1166 struct fid *f;
1167 uint32_t fid;
1168 uint8_t mode;
1169 const char *path;
1171 /* fid[4] mode[1] */
1172 if (!NPREAD32("fid", &fid, &data, &len) ||
1173 !NPREAD8("mode", &mode, &data, &len)) {
1174 client_send_listener(IMSG_CLOSE, NULL, 0);
1175 client_shutdown();
1176 return;
1179 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1180 np_error(hdr->tag, "invalid fid");
1181 return;
1184 if (npmode_to_unix(mode, &f->iomode) == -1) {
1185 np_error(hdr->tag, "invalid mode");
1186 return;
1189 if (f->qid->type & QTDIR &&
1190 (f->iomode & O_WRONLY || f->iomode & O_RDWR)) {
1191 np_error(hdr->tag, "can't open directory for writing");
1192 return;
1195 path = f->qid->fpath;
1196 if (*path == '\0')
1197 path = ".";
1199 if ((f->fd = openat(f->qid->fd, path, f->iomode)) == -1) {
1200 np_error(hdr->tag, strerror(errno));
1201 return;
1204 if (fstat(f->fd, &sb) == -1)
1205 fatal("fstat");
1207 if (S_ISDIR(sb.st_mode)) {
1208 assert(f->qid->type & QTDIR);
1209 if ((f->dir = fdopendir(f->fd)) == NULL) {
1210 np_errno(hdr->tag);
1211 close(f->fd);
1212 f->fd = -1;
1213 return;
1216 if ((f->evb = evbuffer_new()) == NULL) {
1217 np_errno(hdr->tag);
1218 closedir(f->dir);
1219 f->dir = NULL;
1220 f->fd = -1;
1224 f->offset = 0;
1226 qid_update_from_sb(&qid, &sb);
1227 np_open(hdr->tag, &qid, sb.st_blksize);
1230 static void
1231 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1233 struct stat sb;
1234 struct qid qid;
1235 struct fid *f;
1236 uint32_t fid, perm;
1237 uint8_t mode;
1238 char name[PATH_MAX];
1240 /* fid[4] name[s] perm[4] mode[1] */
1241 if (!NPREAD32("fid", &fid, &data, &len))
1242 goto err;
1243 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1244 case READSTRERR:
1245 goto err;
1246 case READSTRTRUNC:
1247 np_error(hdr->tag, "name too long");
1248 return;
1250 if (!NPREAD32("perm", &perm, &data, &len) ||
1251 !NPREAD8("mode", &mode, &data, &len))
1252 goto err;
1254 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1255 strchr(name, '/') != NULL) {
1256 np_error(hdr->tag, "invalid name");
1257 return;
1260 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1261 np_error(hdr->tag, "invalid fid");
1262 return;
1265 if (!(f->qid->type & QTDIR)) {
1266 np_error(hdr->tag, "fid doesn't identify a directory");
1267 return;
1270 if (npmode_to_unix(mode, &f->iomode) == -1) {
1271 np_error(hdr->tag, "invalid mode");
1272 return;
1275 if (f->iomode & O_RDONLY) {
1276 np_error(hdr->tag, "can't create a read-only file");
1277 return;
1280 /* TODO: parse the mode */
1282 if (perm & 0x80000000) {
1283 /* create a directory */
1284 f->fd = mkdirat(f->qid->fd, name, 0755);
1285 } else {
1286 /* create a file */
1287 f->fd = openat(f->qid->fd, name, f->iomode | O_CREAT | O_TRUNC,
1288 0644);
1291 if (f->fd == -1) {
1292 np_errno(hdr->tag);
1293 return;
1296 if (fstat(f->fd, &sb) == -1)
1297 fatal("fstat");
1299 if (S_ISDIR(sb.st_mode)) {
1300 if ((f->dir = fdopendir(f->fd)) == NULL) {
1301 np_errno(hdr->tag);
1302 close(f->fd);
1303 f->fd = -1;
1304 return;
1307 if ((f->evb = evbuffer_new()) == NULL) {
1308 np_errno(hdr->tag);
1309 closedir(f->dir);
1310 f->dir = NULL;
1311 f->fd = -1;
1315 f->offset = 0;
1317 qid_update_from_sb(&qid, &sb);
1318 np_create(hdr->tag, &qid, sb.st_blksize);
1320 return;
1322 err:
1323 client_send_listener(IMSG_CLOSE, NULL, 0);
1324 client_shutdown();
1327 static inline void
1328 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1330 struct qid qid;
1331 const char *uid, *gid, *muid;
1332 size_t tot;
1333 uint16_t namlen, uidlen, gidlen, ulen;
1335 qid_update_from_sb(&qid, sb);
1337 /* TODO: fill these fields */
1338 uid = "";
1339 gid = "";
1340 muid = "";
1342 namlen = strlen(fname);
1343 uidlen = strlen(uid);
1344 gidlen = strlen(gid);
1345 ulen = strlen(muid);
1347 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1348 if (tot > UINT32_MAX) {
1349 log_warnx("stat info for dir entry %s would overflow",
1350 fname);
1351 return;
1354 np_write16(evb, tot); /* size[2] */
1355 np_write16(evb, sb->st_rdev); /* type[2] */
1356 np_write32(evb, sb->st_dev); /* dev[4] */
1357 np_qid(evb, &qid); /* qid[13] */
1359 /* XXX: translate? */
1360 np_write32(evb, sb->st_mode); /* mode[4] */
1362 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1363 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1364 np_write64(evb, sb->st_size); /* length[8] */
1365 np_string(evb, namlen, fname); /* name[s] */
1366 np_string(evb, uidlen, uid); /* uid[s] */
1367 np_string(evb, gidlen, gid); /* gid[s] */
1368 np_string(evb, ulen, muid); /* muid[s] */
1371 static void
1372 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1374 struct fid *f;
1375 ssize_t r;
1376 uint64_t off;
1377 uint32_t fid, count;
1378 char buf[2048];
1380 /* fid[4] offset[8] count[4] */
1381 if (!NPREAD32("fid", &fid, &data, &len) ||
1382 !NPREAD64("offset", &off, &data, &len) ||
1383 !NPREAD32("count", &count, &data, &len)) {
1384 client_send_listener(IMSG_CLOSE, NULL, 0);
1385 client_shutdown();
1386 return;
1389 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1390 np_error(hdr->tag, "invalid fid");
1391 return;
1394 if (TYPE_OVERFLOW(off_t, off)) {
1395 log_warnx("unexpected size_t size");
1396 np_error(hdr->tag, "invalid offset");
1397 return;
1400 if (f->dir == NULL) {
1401 /* read a file */
1402 r = pread(f->fd, buf, sizeof(buf), (off_t)off);
1403 if (r == -1)
1404 np_errno(hdr->tag);
1405 else
1406 np_read(hdr->tag, r, buf);
1407 } else {
1408 if (off == 0 && f->offset != 0) {
1409 rewinddir(f->dir);
1410 f->offset = 0;
1413 if (off != f->offset) {
1414 np_error(hdr->tag, "can't seek in directories");
1415 return;
1418 while (EVBUFFER_LENGTH(f->evb) < count) {
1419 struct dirent *d;
1420 struct stat sb;
1422 if ((d = readdir(f->dir)) == NULL)
1423 break;
1424 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1425 warn("fstatat");
1426 continue;
1428 serialize_stat(d->d_name, &sb, f->evb);
1431 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1432 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1433 evbuffer_drain(f->evb, count);
1435 f->offset += count;
1439 static void
1440 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1442 struct fid *f;
1443 ssize_t r;
1444 uint64_t off;
1445 uint32_t fid, count;
1447 /* fid[4] offset[8] count[4] data[count] */
1448 if (!NPREAD32("fid", &fid, &data, &len) ||
1449 !NPREAD64("off", &off, &data, &len) ||
1450 !NPREAD32("count", &count, &data, &len) ||
1451 len != count) {
1452 client_send_listener(IMSG_CLOSE, NULL, 0);
1453 client_shutdown();
1454 return;
1457 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1458 np_error(hdr->tag, "invalid fid");
1459 return;
1462 if (!(f->iomode & O_WRONLY) &&
1463 !(f->iomode & O_RDWR)) {
1464 np_error(hdr->tag, "fid not opened for writing");
1465 return;
1468 if (TYPE_OVERFLOW(off_t, off)) {
1469 log_warnx("unexpected off_t size");
1470 np_error(hdr->tag, "invalid offset");
1471 return;
1474 if ((r = pwrite(f->fd, data, len, off)) == -1)
1475 np_errno(hdr->tag);
1476 else
1477 np_write(hdr->tag, r);
1480 static void
1481 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1483 struct evbuffer *evb;
1484 struct stat sb;
1485 struct fid *f;
1486 const char *fname;
1487 int r;
1488 uint32_t fid;
1490 /* fid[4] */
1491 if (!NPREAD32("fid", &fid, &data, &len)) {
1492 client_send_listener(IMSG_CLOSE, NULL, 0);
1493 client_shutdown();
1494 return;
1498 * plan9' stat(9P) is not clear on whether the stat is allowed
1499 * on opened fids or not.
1501 if ((f = fid_by_id(fid)) == NULL) {
1502 np_error(hdr->tag, "invalid fid");
1503 return;
1506 if ((evb = evbuffer_new()) == NULL)
1507 fatal("evbuffer_new");
1509 if (f->qid->type & QTDIR) {
1510 fname = ".";
1511 r = fstat(f->qid->fd, &sb);
1512 } else {
1513 fname = f->qid->fpath;
1514 r = fstatat(f->qid->fd, f->qid->fpath, &sb, 0);
1517 if (r == -1) {
1518 np_errno(hdr->tag);
1519 evbuffer_free(evb);
1520 return;
1523 serialize_stat(fname, &sb, evb);
1524 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1525 evbuffer_free(evb);
1528 static void
1529 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1531 struct fid *f;
1532 uint32_t fid;
1533 int r;
1535 /* fid[4] */
1536 if (!NPREAD32("fid", &fid, &data, &len)) {
1537 client_send_listener(IMSG_CLOSE, NULL, 0);
1538 client_shutdown();
1539 return;
1542 if ((f = fid_by_id(fid)) == NULL) {
1543 np_error(hdr->tag, "invalid fid");
1544 return;
1547 if (f->fd == -1 || f->dir == NULL) /* unlink file */
1548 r = unlinkat(f->qid->fd, f->qid->fpath, 0);
1549 else /* directory */
1550 r = unlinkat(f->qid->fd, f->qid->fpath, AT_REMOVEDIR);
1552 if (r == -1)
1553 np_errno(hdr->tag);
1554 else
1555 np_remove(hdr->tag);
1557 free_fid(f);
1560 static void
1561 handle_message(struct imsg *imsg, size_t len)
1563 struct msg {
1564 uint8_t type;
1565 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1566 } msgs[] = {
1567 {Tversion, tversion},
1568 {Tattach, tattach},
1569 {Tclunk, tclunk},
1570 {Tflush, tflush},
1571 {Twalk, twalk},
1572 {Topen, topen},
1573 {Tcreate, tcreate},
1574 {Tread, tread},
1575 {Twrite, twrite},
1576 {Tstat, tstat},
1577 {Tremove, tremove},
1579 struct np_msg_header hdr;
1580 size_t i;
1581 uint8_t *data;
1583 #if DEBUG_PACKETS
1584 hexdump("incoming packet", imsg->data, len);
1585 #endif
1587 parse_message(imsg->data, len, &hdr, &data);
1588 len -= HEADERSIZE;
1590 log_debug("got request: len=%d type=%d[%s] tag=%d",
1591 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1593 if (!handshaked && hdr.type != Tversion) {
1594 client_send_listener(IMSG_CLOSE, NULL, 0);
1595 client_shutdown();
1596 return;
1599 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1600 if (msgs[i].type != hdr.type)
1601 continue;
1603 msgs[i].fn(&hdr, data, len);
1604 return;
1607 np_error(hdr.tag, "Not supported.");