Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "compat.h"
19 #include <sys/stat.h>
21 #include <dirent.h>
22 #include <endian.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <pwd.h>
26 #include <signal.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <syslog.h>
30 #include <unistd.h>
32 #include "client.h"
33 #include "kamid.h"
34 #include "log.h"
35 #include "sandbox.h"
36 #include "utils.h"
38 /*
39 * XXX: atm is difficult to accept messages bigger than MAX_IMSGSIZE
40 * minus IMSG_HEADER_SIZE, we need something to split messages into
41 * chunks and receive them one by the other.
42 *
43 * CLIENT_MSIZE is thus the maximum message size we can handle now.
44 */
45 #define CLIENT_MSIZE (MAX_IMSGSIZE - IMSG_HEADER_SIZE)
47 #define DEBUG_PACKETS 0
49 /* straight outta /src/usr.bin/ssh/scp.c */
50 #define TYPE_OVERFLOW(type, val) \
51 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
52 (sizeof(type) == 8 && (val) > INT64_MAX) || \
53 (sizeof(type) != 4 && sizeof(type) != 8))
55 struct qid {
56 uint64_t path;
57 uint32_t vers;
58 uint8_t type;
59 };
61 STAILQ_HEAD(dirhead, dir) dirs;
62 struct dir {
63 int refcount;
64 int fd;
65 STAILQ_ENTRY(dir) entries;
66 };
68 STAILQ_HEAD(fidhead, fid) fids;
69 struct fid {
70 uint32_t fid;
72 char fpath[PATH_MAX];
74 /*
75 * the flags passed to open(2). O_CLOEXEC means ORCLOSE, that
76 * is to unlink the file upon Tclunk.
77 */
78 int iomode;
80 /*
81 * if fd is not -1 this fid was opened, fd represents its
82 * file descriptor and iomode the flags passed to open(2).
83 */
84 int fd;
85 DIR *d;
86 struct evbuffer *evb;
88 /*
89 * expected offset for Tread against a directory.
90 */
91 uint64_t offset;
93 struct qid qid;
94 struct dir *dir;
95 STAILQ_ENTRY(fid) entries;
96 };
98 static struct imsgev *iev_listener;
99 static struct evbuffer *evb;
100 static uint32_t peerid;
102 static int handshaked;
103 uint32_t msize;
105 static __dead void client_shutdown(void);
106 static void client_sig_handler(int, short, void *);
107 static void client_dispatch_listener(int, short, void *);
108 static void client_privdrop(const char *, const char *);
110 static int client_send_listener(int, const void *, uint16_t);
112 static void qid_update_from_sb(struct qid *, struct stat *);
114 static struct dir *new_dir(int);
115 static struct dir *dir_incref(struct dir *);
116 static void dir_decref(struct dir *);
118 static struct fid *new_fid(struct dir *, uint32_t, const char *, struct qid *);
119 static struct fid *fid_by_id(uint32_t);
120 static void free_fid(struct fid *);
122 static void parse_message(const uint8_t *, size_t,
123 struct np_msg_header *, uint8_t **);
125 static void np_write16(struct evbuffer *, uint16_t);
126 static void np_write32(struct evbuffer *, uint32_t);
127 static void np_write64(struct evbuffer *, uint64_t);
128 static void np_header(uint32_t, uint8_t, uint16_t);
129 static void np_string(struct evbuffer *, uint16_t, const char *);
130 static void np_qid(struct evbuffer *, struct qid *);
131 static void do_send(void);
133 static void np_version(uint16_t, uint32_t, const char *);
134 static void np_attach(uint16_t, struct qid *);
135 static void np_clunk(uint16_t);
136 static void np_flush(uint16_t);
137 static void np_walk(uint16_t, int, struct qid *);
138 static void np_open(uint16_t, struct qid *, uint32_t);
139 static void np_create(uint16_t, struct qid *, uint32_t);
140 static void np_read(uint16_t, uint32_t, void *);
141 static void np_write(uint16_t, uint32_t);
142 static void np_stat(uint16_t, uint32_t, void *);
143 static void np_remove(uint16_t);
144 static void np_error(uint16_t, const char *);
145 static void np_errno(uint16_t);
147 static int np_read8(const char *, const char *, uint8_t *,
148 const uint8_t **, size_t *);
149 static int np_read16(const char *, const char *, uint16_t *,
150 const uint8_t **, size_t *);
151 static int np_read32(const char *, const char *, uint32_t *,
152 const uint8_t **, size_t *);
153 static int np_read64(const char *, const char *, uint64_t *,
154 const uint8_t **, size_t *);
156 #define READSTRERR -1
157 #define READSTRTRUNC -2
158 static int np_readstr(const char *, const char *, char *, size_t,
159 const uint8_t **, size_t *);
161 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
162 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
163 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
164 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
166 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
168 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
169 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
170 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
171 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
172 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
173 static void topen(struct np_msg_header *, const uint8_t *, size_t);
174 static void tcreate(struct np_msg_header *, const uint8_t *, size_t);
175 static void tread(struct np_msg_header *, const uint8_t *, size_t);
176 static void twrite(struct np_msg_header *, const uint8_t *, size_t);
177 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
178 static void tremove(struct np_msg_header *, const uint8_t *, size_t);
179 static void handle_message(struct imsg *, size_t);
181 __dead void
182 client(int debug, int verbose)
184 struct event ev_sigint, ev_sigterm;
186 log_init(debug, LOG_DAEMON);
187 log_setverbose(verbose);
189 setproctitle("client");
190 log_procinit("client");
192 log_debug("warming up");
194 event_init();
196 /* Setup signal handlers */
197 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
198 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
200 signal_add(&ev_sigint, NULL);
201 signal_add(&ev_sigterm, NULL);
203 signal(SIGPIPE, SIG_IGN);
204 signal(SIGHUP, SIG_IGN);
206 /* Setup pipe and event handler to the listener process */
207 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
208 fatal(NULL);
210 imsg_init(&iev_listener->ibuf, 3);
211 iev_listener->handler = client_dispatch_listener;
213 /* Setup event handlers. */
214 iev_listener->events = EV_READ;
215 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
216 iev_listener->events, iev_listener->handler, iev_listener);
217 event_add(&iev_listener->ev, NULL);
219 event_dispatch();
220 client_shutdown();
223 static __dead void
224 client_shutdown(void)
226 if (evb != NULL)
227 evbuffer_free(evb);
229 msgbuf_clear(&iev_listener->ibuf.w);
230 close(iev_listener->ibuf.fd);
232 free(iev_listener);
234 log_debug("client exiting");
235 exit(0);
238 static void
239 client_sig_handler(int sig, short event, void *d)
241 /*
242 * Normal signal handler rules don't apply because libevent
243 * decouples for us.
244 */
246 switch (sig) {
247 case SIGINT:
248 case SIGTERM:
249 client_shutdown();
250 default:
251 fatalx("unexpected signal %d", sig);
255 #define AUTH_NONE 0
256 #define AUTH_USER 1
257 #define AUTH_DONE 2
259 static void
260 client_dispatch_listener(int fd, short event, void *d)
262 static int auth = AUTH_NONE;
263 static char username[64] = {0};
264 static char dir[PATH_MAX] = {0};
265 struct imsg imsg;
266 struct imsgev *iev = d;
267 struct imsgbuf *ibuf;
268 ssize_t n;
269 int shut = 0;
271 ibuf = &iev->ibuf;
273 if (event & EV_READ) {
274 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
275 fatal("imsg_read error");
276 if (n == 0) /* Connection closed */
277 shut = 1;
279 if (event & EV_WRITE) {
280 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
281 fatal("msgbuf_write");
282 if (n == 0) /* Connection closed */
283 shut = 1;
286 for (;;) {
287 if ((n = imsg_get(ibuf, &imsg)) == -1)
288 fatal("%s: imsg_get error", __func__);
289 if (n == 0) /* No more messages. */
290 break;
292 switch (imsg.hdr.type) {
293 case IMSG_AUTH:
294 peerid = imsg.hdr.peerid;
295 if (auth)
296 fatalx("%s: IMSG_AUTH already done", __func__);
297 auth = AUTH_USER;
298 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
299 strlcpy(username, imsg.data, sizeof(username));
300 break;
301 case IMSG_AUTH_DIR:
302 if (auth != AUTH_USER)
303 fatalx("%s: IMSG_AUTH_DIR not after IMSG_AUTH",
304 __func__);
305 auth = AUTH_DONE;
306 ((char *)imsg.data)[IMSG_DATA_SIZE(imsg)-1] = '\0';
307 strlcpy(dir, imsg.data, sizeof(dir));
308 client_privdrop(username, dir);
309 memset(username, 0, sizeof(username));
310 memset(dir, 0, sizeof(username));
311 break;
312 case IMSG_BUF:
313 /* echo! */
314 if (!auth)
315 fatalx("%s: can't handle messages before"
316 " doing the auth", __func__);
317 handle_message(&imsg, IMSG_DATA_SIZE(imsg));
318 break;
319 case IMSG_CONN_GONE:
320 log_debug("closing");
321 shut = 1;
322 break;
323 default:
324 log_debug("%s: unexpected imsg %d",
325 __func__, imsg.hdr.type);
326 break;
328 imsg_free(&imsg);
331 if (!shut)
332 imsg_event_add(iev);
333 else {
334 /* This pipe is dead. Remove its event handler. */
335 event_del(&iev->ev);
336 log_debug("pipe closed, shutting down...");
337 event_loopexit(NULL);
341 static void
342 client_privdrop(const char *username, const char *dir)
344 struct passwd *pw;
346 setproctitle("client %s", username);
348 if ((pw = getpwnam(username)) == NULL)
349 fatalx("getpwnam(%s) failed", username);
351 if (chroot(dir) == -1)
352 fatal("chroot");
353 if (chdir("/") == -1)
354 fatal("chdir(\"/\")");
356 if (setgroups(1, &pw->pw_gid) ||
357 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
358 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
359 fatal("can't drop privileges");
361 sandbox_client();
362 log_debug("client ready; user=%s dir=%s", username, dir);
364 if ((evb = evbuffer_new()) == NULL)
365 fatal("evbuffer_new");
368 static int
369 client_send_listener(int type, const void *data, uint16_t len)
371 int ret;
373 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
374 data, len)) != -1)
375 imsg_event_add(iev_listener);
377 return ret;
380 /* set qid fields from sb */
381 static void
382 qid_update_from_sb(struct qid *qid, struct stat *sb)
384 qid->path = sb->st_ino;
386 /*
387 * Theoretically (and hopefully!) this should be a 64 bit
388 * number. Unfortunately, 9P uses 32 bit timestamps.
389 */
390 qid->vers = sb->st_mtim.tv_sec;
392 if (S_ISREG(sb->st_mode))
393 qid->type = QTFILE;
394 else if (S_ISDIR(sb->st_mode))
395 qid->type = QTDIR;
396 else if (S_ISLNK(sb->st_mode))
397 qid->type = QTSYMLINK;
400 /* creates a qid given a fd */
401 static struct dir *
402 new_dir(int fd)
404 struct dir *dir;
406 if ((dir = calloc(1, sizeof(*dir))) == NULL)
407 return NULL;
409 dir->fd = fd;
410 STAILQ_INSERT_HEAD(&dirs, dir, entries);
411 return dir;
414 static struct dir *
415 dir_incref(struct dir *dir)
417 dir->refcount++;
418 return dir;
421 static void
422 dir_decref(struct dir *dir)
424 if (--dir->refcount > 0)
425 return;
427 STAILQ_REMOVE(&dirs, dir, dir, entries);
429 close(dir->fd);
430 free(dir);
433 static struct fid *
434 new_fid(struct dir *dir, uint32_t fid, const char *path, struct qid *qid)
436 struct fid *f;
437 struct qid q;
438 struct stat sb;
440 if (qid == NULL) {
441 if (fstatat(dir->fd, path, &sb, 0)) {
442 log_warn("fstatat(%s)", path);
443 return NULL;
445 qid_update_from_sb(&q, &sb);
446 qid = &q;
449 if ((f = calloc(1, sizeof(*f))) == NULL)
450 return NULL;
452 f->dir = dir_incref(dir);
453 f->fid = fid;
454 f->fd = -1;
456 strlcpy(f->fpath, path, sizeof(f->fpath));
458 memcpy(&f->qid, qid, sizeof(f->qid));
460 STAILQ_INSERT_HEAD(&fids, f, entries);
462 return f;
465 static struct fid *
466 fid_by_id(uint32_t fid)
468 struct fid *f;
470 STAILQ_FOREACH(f, &fids, entries) {
471 if (f->fid == fid)
472 return f;
475 return NULL;
478 static void
479 free_fid(struct fid *f)
481 int r;
483 if (f->fd != -1) {
484 if (f->d != NULL)
485 r = closedir(f->d);
486 else
487 r = close(f->fd);
489 if (r == -1)
490 fatal("can't close fid %d", f->fid);
492 if (f->evb != NULL)
493 evbuffer_free(f->evb);
495 /* try to honour ORCLOSE if requested */
496 if (f->iomode & O_CLOEXEC)
497 unlinkat(f->dir->fd, f->fpath, 0);
500 dir_decref(f->dir);
502 STAILQ_REMOVE(&fids, f, fid, entries);
503 free(f);
506 static void
507 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
508 uint8_t **cnt)
510 size_t olen = len;
512 if (!NPREAD32("len", &hdr->len, &data, &len) ||
513 !NPREAD8("type", &hdr->type, &data, &len) ||
514 !NPREAD16("tag", &hdr->tag, &data, &len))
515 goto err;
517 if (olen != hdr->len)
518 goto err;
520 if (hdr->type < Tversion ||
521 hdr->type >= Tmax ||
522 hdr->type == Terror ||
523 (hdr->type & 0x1) != 0) /* cannot recv a R* */
524 goto err;
526 hdr->tag = le32toh(hdr->tag);
528 *cnt = (uint8_t *)data;
529 return;
531 err:
532 /* TODO: send a proper message to terminate the connection. */
533 fatalx("got invalid message");
536 static void
537 np_write16(struct evbuffer *e, uint16_t x)
539 x = htole16(x);
540 evbuffer_add(e, &x, sizeof(x));
543 static void
544 np_write32(struct evbuffer *e, uint32_t x)
546 x = htole32(x);
547 evbuffer_add(e, &x, sizeof(x));
550 static void
551 np_write64(struct evbuffer *e, uint64_t x)
553 x = htole64(x);
554 evbuffer_add(e, &x, sizeof(x));
557 static void
558 np_writebuf(struct evbuffer *e, size_t len, void *data)
560 evbuffer_add(e, data, len);
563 static void
564 np_header(uint32_t len, uint8_t type, uint16_t tag)
566 len += HEADERSIZE;
568 len = htole32(len);
569 tag = htole16(tag);
571 evbuffer_add(evb, &len, sizeof(len));
572 evbuffer_add(evb, &type, sizeof(type));
573 evbuffer_add(evb, &tag, sizeof(tag));
576 static void
577 np_string(struct evbuffer *e, uint16_t len, const char *str)
579 uint16_t l = len;
581 len = htole16(len);
582 evbuffer_add(e, &len, sizeof(len));
583 evbuffer_add(e, str, l);
586 static void
587 np_qid(struct evbuffer *e, struct qid *qid)
589 uint64_t path;
590 uint32_t vers;
592 path = htole64(qid->path);
593 vers = htole32(qid->vers);
595 evbuffer_add(e, &qid->type, sizeof(qid->type));
596 evbuffer_add(e, &vers, sizeof(vers));
597 evbuffer_add(e, &path, sizeof(path));
600 static void
601 do_send(void)
603 size_t len;
604 void *data;
606 len = EVBUFFER_LENGTH(evb);
607 data = EVBUFFER_DATA(evb);
609 #if DEBUG_PACKETS
610 hexdump("outgoing packet", data, len);
611 #endif
612 client_send_listener(IMSG_BUF, data, len);
613 evbuffer_drain(evb, len);
616 static void
617 np_version(uint16_t tag, uint32_t msize, const char *version)
619 uint16_t l;
621 l = strlen(version);
623 msize = htole32(msize);
625 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
626 evbuffer_add(evb, &msize, sizeof(msize));
627 np_string(evb, l, version);
628 do_send();
631 static void
632 np_attach(uint16_t tag, struct qid *qid)
634 np_header(QIDSIZE, Rattach, tag);
635 np_qid(evb, qid);
636 do_send();
639 static void
640 np_clunk(uint16_t tag)
642 np_header(0, Rclunk, tag);
643 do_send();
646 static void
647 np_flush(uint16_t tag)
649 np_header(0, Rflush, tag);
650 do_send();
653 static void
654 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
656 int i;
658 /* two bytes for the counter */
659 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
660 np_write16(evb, nwqid);
661 for (i = 0; i < nwqid; ++i)
662 np_qid(evb, wqid + i);
664 do_send();
667 static void
668 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
670 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
671 np_qid(evb, qid);
672 np_write32(evb, iounit);
673 do_send();
676 static void
677 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
679 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
680 np_qid(evb, qid);
681 np_write32(evb, iounit);
682 do_send();
685 static void
686 np_read(uint16_t tag, uint32_t count, void *data)
688 np_header(sizeof(count) + count, Rread, tag);
689 np_write32(evb, count);
690 np_writebuf(evb, count, data);
691 do_send();
694 static void
695 np_write(uint16_t tag, uint32_t count)
697 np_header(sizeof(count), Rwrite, tag);
698 np_write32(evb, count);
699 do_send();
702 static void
703 np_stat(uint16_t tag, uint32_t count, void *data)
705 np_header(count, Rstat, tag);
706 np_writebuf(evb, count, data);
707 do_send();
710 static void
711 np_remove(uint16_t tag)
713 np_header(0, Rremove, tag);
714 do_send();
717 static void
718 np_error(uint16_t tag, const char *errstr)
720 uint16_t l;
722 l = strlen(errstr);
724 np_header(sizeof(l) + l, Rerror, tag);
725 np_string(evb, l, errstr);
726 do_send();
729 static void
730 np_errno(uint16_t tag)
732 int saved_errno;
733 char buf[64];
735 saved_errno = errno;
737 strerror_r(errno, buf, sizeof(buf));
738 np_error(tag, buf);
740 errno = saved_errno;
743 static int
744 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
745 size_t *len)
747 if (*len < sizeof(*dst)) {
748 log_warnx("%s: wanted %zu bytes for the %s field but only "
749 "%zu are available.", t, sizeof(*dst), f, *len);
750 return -1;
753 memcpy(dst, *src, sizeof(*dst));
754 *src += sizeof(*dst);
755 *len -= sizeof(*dst);
757 return 1;
760 static int
761 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
762 size_t *len)
764 if (*len < sizeof(*dst)) {
765 log_warnx("%s: wanted %zu bytes for the %s field but only "
766 "%zu are available.", t, sizeof(*dst), f, *len);
767 return -1;
770 memcpy(dst, *src, sizeof(*dst));
771 *src += sizeof(*dst);
772 *len -= sizeof(*dst);
773 *dst = le16toh(*dst);
775 return 1;
778 static int
779 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
780 size_t *len)
782 if (*len < sizeof(*dst)) {
783 log_warnx("%s: wanted %zu bytes for the %s field but only "
784 "%zu are available.", t, sizeof(*dst), f, *len);
785 return -1;
788 memcpy(dst, *src, sizeof(*dst));
789 *src += sizeof(*dst);
790 *len -= sizeof(*dst);
791 *dst = le32toh(*dst);
793 return 1;
796 static int
797 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
798 size_t *len)
800 if (*len < sizeof(*dst)) {
801 log_warnx("%s: wanted %zu bytes for the %s field but only "
802 "%zu are available.", t, sizeof(*dst), f, *len);
803 return -1;
806 memcpy(dst, *src, sizeof(*dst));
807 *src += sizeof(*dst);
808 *len -= sizeof(*dst);
809 *dst = le64toh(*dst);
811 return 1;
814 static int
815 np_readstr(const char *t, const char *f, char *res, size_t reslen,
816 const uint8_t **src, size_t *len)
818 uint16_t sl;
819 char buf[32];
821 strlcpy(buf, f, sizeof(buf));
822 strlcat(buf, "-len", sizeof(buf));
824 if (!np_read16(t, buf, &sl, src, len))
825 return READSTRERR;
827 if (*len < sl) {
828 log_warnx("%s: wanted %d bytes for the %s field but only "
829 "%zu are available.", t, sl, f, *len);
830 return READSTRERR;
833 if (*len > reslen-1)
834 return READSTRTRUNC;
836 memcpy(res, *src, sl);
837 res[sl] = '\0';
838 *src += sl;
839 *len -= sl;
841 return 0;
844 static void
845 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
847 char *dot, version[32];
849 if (handshaked)
850 goto err;
852 /* msize[4] version[s] */
853 if (!NPREAD32("msize", &msize, &data, &len))
854 goto err;
856 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
857 case READSTRERR:
858 goto err;
859 case READSTRTRUNC:
860 log_warnx("9P version string too long, truncated");
861 goto mismatch;
864 if ((dot = strchr(version, '.')) != NULL)
865 *dot = '\0';
867 if (strcmp(version, VERSION9P) != 0 ||
868 msize == 0)
869 goto mismatch;
871 /* version matched */
872 handshaked = 1;
873 msize = MIN(msize, CLIENT_MSIZE);
874 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
875 np_version(hdr->tag, msize, VERSION9P);
876 return;
878 mismatch:
879 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
880 version);
881 np_version(hdr->tag, MSIZE9P, "unknown");
882 return;
884 err:
885 client_send_listener(IMSG_CLOSE, NULL, 0);
886 client_shutdown();
889 static void
890 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
892 struct dir *dir;
893 struct fid *f;
894 uint32_t fid, afid;
895 int fd;
896 char aname[PATH_MAX];
898 /* fid[4] afid[4] uname[s] aname[s] */
900 if (!NPREAD32("fid", &fid, &data, &len) ||
901 !NPREAD32("afid", &afid, &data, &len))
902 goto err;
904 /* read the uname but don't actually use it */
905 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
906 case READSTRERR:
907 goto err;
908 case READSTRTRUNC:
909 np_error(hdr->tag, "name too long");
910 return;
913 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
914 case READSTRERR:
915 goto err;
916 case READSTRTRUNC:
917 np_error(hdr->tag, "name too long");
918 return;
921 if (fid_by_id(fid) != NULL || afid != NOFID) {
922 np_error(hdr->tag, "invalid fid or afid");
923 return;
926 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
927 goto fail;
929 if ((dir = new_dir(fd)) == NULL)
930 goto fail;
932 log_debug("attached %s to %d", aname, fid);
934 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
935 dir_decref(dir);
936 goto fail;
939 np_attach(hdr->tag, &f->qid);
940 return;
942 fail:
943 np_errno(hdr->tag);
944 log_warn("failed to attach %s", aname);
945 return;
947 err:
948 client_send_listener(IMSG_CLOSE, NULL, 0);
949 client_shutdown();
952 static void
953 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
955 struct fid *f;
956 uint32_t fid;
958 /* fid[4] */
959 if (!NPREAD32("fid", &fid, &data, &len)) {
960 client_send_listener(IMSG_CLOSE, NULL, 0);
961 client_shutdown();
962 return;
965 if ((f = fid_by_id(fid)) == NULL) {
966 np_error(hdr->tag, "invalid fid");
967 return;
970 free_fid(f);
971 np_clunk(hdr->tag);
974 static void
975 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
977 uint16_t oldtag;
979 /*
980 * We're doing only synchronous I/O. Tflush is implemented
981 * only because it's illegal to reply with a Rerror.
982 */
984 /* oldtag[2] */
985 if (len != sizeof(oldtag)) {
986 log_warnx("Tflush with the wrong size: got %zu want %zu",
987 len, sizeof(oldtag));
988 client_send_listener(IMSG_CLOSE, NULL, 0);
989 client_shutdown();
990 return;
993 np_flush(hdr->tag);
996 static void
997 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
999 struct stat sb;
1000 struct dir *dir;
1001 struct qid wqid[MAXWELEM] = {0};
1002 struct fid *f, *nf;
1003 uint32_t fid, newfid;
1004 uint16_t nwname;
1005 int fd, oldfd, no, nwqid = 0;
1006 char wnam[PATH_MAX];
1008 if (!NPREAD32("fid", &fid, &data, &len) ||
1009 !NPREAD32("newfid", &newfid, &data, &len) ||
1010 !NPREAD16("nwname", &nwname, &data, &len))
1011 goto err;
1013 if (nwname > MAXWELEM) {
1014 log_warnx("Twalk: more than %d path elements: %d",
1015 MAXWELEM, nwname);
1016 goto err;
1019 if ((f = fid_by_id(fid)) == NULL) {
1020 np_error(hdr->tag, "invalid fid");
1021 return;
1024 if (f->fd != -1) {
1025 np_error(hdr->tag, "fid already opened for I/O");
1026 return;
1029 if (fid == newfid)
1030 nf = f;
1031 else if ((nf = fid_by_id(newfid)) != NULL) {
1032 np_error(hdr->tag, "newfid already in use");
1033 return;
1034 } else
1035 nf = NULL;
1037 /* special case: fid duplication */
1038 if (nwname == 0) {
1040 * TODO: should we forbid fids duplication when fid ==
1041 * newfid?
1043 if (nf == NULL &&
1044 (nf = new_fid(f->dir, newfid, f->fpath, &f->qid)) == NULL)
1045 fatal("new_fid duplication");
1047 np_walk(hdr->tag, 0, NULL);
1048 return;
1051 if (!(f->qid.type & QTDIR)) {
1052 np_error(hdr->tag, "fid doesn't represent a directory");
1053 return;
1056 oldfd = f->dir->fd;
1058 for (nwqid = 0; nwqid < nwname; nwqid++) {
1059 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1060 case READSTRERR:
1061 goto err;
1062 case READSTRTRUNC:
1063 np_error(hdr->tag, "wname too long");
1064 return;
1067 if (*wnam == '\0' ||
1068 strchr(wnam, '/') != NULL ||
1069 !strcmp(wnam, ".")) {
1070 errno = EINVAL;
1071 goto cantopen;
1074 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1075 errno != ENOTDIR)
1076 goto cantopen;
1078 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1079 (fd != -1 && fstat(fd, &sb) == -1))
1080 goto cantopen;
1082 qid_update_from_sb(&wqid[nwqid], &sb);
1084 /* reached a file but we still have other components */
1085 if (fd == -1 && nwqid+1 < nwname)
1086 goto cantopen;
1088 /* reached the end and found a file */
1089 if (fd == -1 && nwqid+1 == nwname)
1090 continue;
1092 if (oldfd != f->dir->fd)
1093 close(oldfd);
1094 oldfd = fd;
1098 * If fd is -1 we've reached a file, otherwise we've just
1099 * reached another directory. We must pay attention to what
1100 * file descriptor we use to create the dir, because if we've
1101 * reached a file and oldfd is f->dir->fd then we *must* share
1102 * the same dir (it was a walk of one path from a directory to a
1103 * file, otherwise fun is bound to happen as soon as the client
1104 * closes the fid for the directory but keeps the one for the
1105 * file.
1107 if (fd == -1 && oldfd == f->dir->fd)
1108 dir = f->dir;
1109 else if (fd == -1)
1110 dir = new_dir(oldfd);
1111 else
1112 dir = new_dir(fd);
1114 if (dir == NULL)
1115 fatal("new_dir");
1117 if (nf == NULL) {
1118 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1119 fatal("new fid");
1120 } else {
1121 /* update the dir */
1122 dir_decref(nf->dir);
1123 nf->dir = dir_incref(dir);
1126 np_walk(hdr->tag, nwqid, wqid);
1127 return;
1129 cantopen:
1130 if (oldfd != f->dir->fd)
1131 close(oldfd);
1132 no = errno;
1133 if (nwqid == 0)
1134 np_error(hdr->tag, strerror(no));
1135 else
1136 np_walk(hdr->tag, nwqid, wqid);
1137 return;
1139 err:
1140 client_send_listener(IMSG_CLOSE, NULL, 0);
1141 client_shutdown();
1144 static inline int
1145 npmode_to_unix(uint8_t mode, int *flags)
1147 switch (mode & 0x0F) {
1148 case KOREAD:
1149 *flags = O_RDONLY;
1150 break;
1151 case KOWRITE:
1152 *flags = O_WRONLY;
1153 break;
1154 case KORDWR:
1155 *flags = O_RDWR;
1156 break;
1157 case KOEXEC:
1158 log_warnx("tried to open something with KOEXEC");
1159 /* fallthrough */
1160 default:
1161 return -1;
1164 if (mode & KOTRUNC)
1165 *flags |= O_TRUNC;
1166 if (mode & KORCLOSE)
1167 *flags |= O_CLOEXEC;
1169 return 0;
1172 static void
1173 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1175 struct stat sb;
1176 struct qid qid;
1177 struct fid *f;
1178 uint32_t fid;
1179 uint8_t mode;
1180 const char *path;
1182 /* fid[4] mode[1] */
1183 if (!NPREAD32("fid", &fid, &data, &len) ||
1184 !NPREAD8("mode", &mode, &data, &len)) {
1185 client_send_listener(IMSG_CLOSE, NULL, 0);
1186 client_shutdown();
1187 return;
1190 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1191 np_error(hdr->tag, "invalid fid");
1192 return;
1195 if (npmode_to_unix(mode, &f->iomode) == -1) {
1196 np_error(hdr->tag, "invalid mode");
1197 return;
1200 path = f->fpath;
1201 if (f->qid.type & QTDIR)
1202 path = ".";
1204 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1205 np_error(hdr->tag, strerror(errno));
1206 return;
1209 if (fstat(f->fd, &sb) == -1)
1210 fatal("fstat");
1212 if (S_ISDIR(sb.st_mode)) {
1213 if ((f->d = fdopendir(f->fd)) == NULL) {
1214 np_errno(hdr->tag);
1215 close(f->fd);
1216 f->fd = -1;
1217 return;
1220 if ((f->evb = evbuffer_new()) == NULL) {
1221 np_errno(hdr->tag);
1222 closedir(f->d);
1223 f->d = NULL;
1224 f->fd = -1;
1228 f->offset = 0;
1230 qid_update_from_sb(&qid, &sb);
1231 np_open(hdr->tag, &qid, sb.st_blksize);
1234 static void
1235 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1237 struct stat sb;
1238 struct qid qid;
1239 struct fid *f;
1240 uint32_t fid, perm;
1241 uint8_t mode;
1242 char name[PATH_MAX];
1244 /* fid[4] name[s] perm[4] mode[1] */
1245 if (!NPREAD32("fid", &fid, &data, &len))
1246 goto err;
1247 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1248 case READSTRERR:
1249 goto err;
1250 case READSTRTRUNC:
1251 np_error(hdr->tag, "name too long");
1252 return;
1254 if (!NPREAD32("perm", &perm, &data, &len) ||
1255 !NPREAD8("mode", &mode, &data, &len))
1256 goto err;
1258 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1259 strchr(name, '/') != NULL) {
1260 np_error(hdr->tag, "invalid name");
1261 return;
1264 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1265 np_error(hdr->tag, "invalid fid");
1266 return;
1269 if (!(f->qid.type & QTDIR)) {
1270 np_error(hdr->tag, "fid doesn't identify a directory");
1271 return;
1274 if (npmode_to_unix(mode, &f->iomode) == -1) {
1275 np_error(hdr->tag, "invalid mode");
1276 return;
1279 if (f->iomode & O_RDONLY) {
1280 np_error(hdr->tag, "can't create a read-only file");
1281 return;
1284 /* TODO: parse the mode */
1286 if (perm & 0x80000000) {
1287 /* create a directory */
1288 f->fd = mkdirat(f->dir->fd, name, 0755);
1289 } else {
1290 /* create a file */
1291 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1292 0644);
1295 if (f->fd == -1) {
1296 np_errno(hdr->tag);
1297 return;
1300 if (fstat(f->fd, &sb) == -1)
1301 fatal("fstat");
1303 if (S_ISDIR(sb.st_mode)) {
1304 if ((f->d = fdopendir(f->fd)) == NULL) {
1305 np_errno(hdr->tag);
1306 close(f->fd);
1307 f->fd = -1;
1308 return;
1311 if ((f->evb = evbuffer_new()) == NULL) {
1312 np_errno(hdr->tag);
1313 closedir(f->d);
1314 f->d = NULL;
1315 f->fd = -1;
1319 f->offset = 0;
1321 qid_update_from_sb(&qid, &sb);
1322 np_create(hdr->tag, &qid, sb.st_blksize);
1324 return;
1326 err:
1327 client_send_listener(IMSG_CLOSE, NULL, 0);
1328 client_shutdown();
1331 static inline void
1332 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1334 struct qid qid;
1335 const char *uid, *gid, *muid;
1336 size_t tot;
1337 uint16_t namlen, uidlen, gidlen, ulen;
1339 qid_update_from_sb(&qid, sb);
1341 /* TODO: fill these fields */
1342 uid = "";
1343 gid = "";
1344 muid = "";
1346 namlen = strlen(fname);
1347 uidlen = strlen(uid);
1348 gidlen = strlen(gid);
1349 ulen = strlen(muid);
1351 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1352 if (tot > UINT32_MAX) {
1353 log_warnx("stat info for dir entry %s would overflow",
1354 fname);
1355 return;
1358 np_write16(evb, tot); /* size[2] */
1359 np_write16(evb, sb->st_rdev); /* type[2] */
1360 np_write32(evb, sb->st_dev); /* dev[4] */
1361 np_qid(evb, &qid); /* qid[13] */
1363 /* XXX: translate? */
1364 np_write32(evb, sb->st_mode); /* mode[4] */
1366 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1367 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1368 np_write64(evb, sb->st_size); /* length[8] */
1369 np_string(evb, namlen, fname); /* name[s] */
1370 np_string(evb, uidlen, uid); /* uid[s] */
1371 np_string(evb, gidlen, gid); /* gid[s] */
1372 np_string(evb, ulen, muid); /* muid[s] */
1375 static void
1376 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1378 struct fid *f;
1379 ssize_t r;
1380 uint64_t off;
1381 uint32_t fid, count;
1382 char buf[2048];
1384 /* fid[4] offset[8] count[4] */
1385 if (!NPREAD32("fid", &fid, &data, &len) ||
1386 !NPREAD64("offset", &off, &data, &len) ||
1387 !NPREAD32("count", &count, &data, &len)) {
1388 client_send_listener(IMSG_CLOSE, NULL, 0);
1389 client_shutdown();
1390 return;
1393 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1394 np_error(hdr->tag, "invalid fid");
1395 return;
1398 if (TYPE_OVERFLOW(off_t, off)) {
1399 log_warnx("unexpected off_t size");
1400 np_error(hdr->tag, "invalid offset");
1401 return;
1404 if (f->d == NULL) {
1405 /* read a file */
1406 r = pread(f->fd, buf, sizeof(buf), (off_t)off);
1407 if (r == -1)
1408 np_errno(hdr->tag);
1409 else
1410 np_read(hdr->tag, r, buf);
1411 } else {
1412 if (off == 0 && f->offset != 0) {
1413 rewinddir(f->d);
1414 f->offset = 0;
1417 if (off != f->offset) {
1418 np_error(hdr->tag, "can't seek in directories");
1419 return;
1422 while (EVBUFFER_LENGTH(f->evb) < count) {
1423 struct dirent *d;
1424 struct stat sb;
1426 if ((d = readdir(f->d)) == NULL)
1427 break;
1428 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1429 warn("fstatat");
1430 continue;
1432 serialize_stat(d->d_name, &sb, f->evb);
1435 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1436 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1437 evbuffer_drain(f->evb, count);
1439 f->offset += count;
1443 static void
1444 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1446 struct fid *f;
1447 ssize_t r;
1448 uint64_t off;
1449 uint32_t fid, count;
1451 /* fid[4] offset[8] count[4] data[count] */
1452 if (!NPREAD32("fid", &fid, &data, &len) ||
1453 !NPREAD64("off", &off, &data, &len) ||
1454 !NPREAD32("count", &count, &data, &len) ||
1455 len != count) {
1456 client_send_listener(IMSG_CLOSE, NULL, 0);
1457 client_shutdown();
1458 return;
1461 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1462 np_error(hdr->tag, "invalid fid");
1463 return;
1466 if (!(f->iomode & O_WRONLY) &&
1467 !(f->iomode & O_RDWR)) {
1468 np_error(hdr->tag, "fid not opened for writing");
1469 return;
1472 if (TYPE_OVERFLOW(off_t, off)) {
1473 log_warnx("unexpected off_t size");
1474 np_error(hdr->tag, "invalid offset");
1475 return;
1478 if ((r = pwrite(f->fd, data, len, off)) == -1)
1479 np_errno(hdr->tag);
1480 else
1481 np_write(hdr->tag, r);
1484 static void
1485 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1487 struct evbuffer *evb;
1488 struct stat sb;
1489 struct fid *f;
1490 int r;
1491 uint32_t fid;
1493 /* fid[4] */
1494 if (!NPREAD32("fid", &fid, &data, &len)) {
1495 client_send_listener(IMSG_CLOSE, NULL, 0);
1496 client_shutdown();
1497 return;
1501 * plan9' stat(9P) is not clear on whether the stat is allowed
1502 * on opened fids or not.
1504 if ((f = fid_by_id(fid)) == NULL) {
1505 np_error(hdr->tag, "invalid fid");
1506 return;
1509 if ((evb = evbuffer_new()) == NULL)
1510 fatal("evbuffer_new");
1512 if (f->fd != -1)
1513 r = fstat(f->fd, &sb);
1514 else
1515 r = fstatat(f->dir->fd, f->fpath, &sb, 0);
1517 if (r == -1) {
1518 np_errno(hdr->tag);
1519 evbuffer_free(evb);
1520 return;
1523 serialize_stat(f->fpath, &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;
1534 char dirpath[PATH_MAX + 3];
1536 /* fid[4] */
1537 if (!NPREAD32("fid", &fid, &data, &len)) {
1538 client_send_listener(IMSG_CLOSE, NULL, 0);
1539 client_shutdown();
1540 return;
1543 if ((f = fid_by_id(fid)) == NULL) {
1544 np_error(hdr->tag, "invalid fid");
1545 return;
1548 if (f->qid.type & QTDIR) { /* directory */
1549 strlcpy(dirpath, "../", sizeof(dirpath));
1550 strlcat(dirpath, f->fpath, sizeof(dirpath));
1551 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1552 } else /* file */
1553 r = unlinkat(f->dir->fd, f->fpath, 0);
1555 if (r == -1)
1556 np_errno(hdr->tag);
1557 else
1558 np_remove(hdr->tag);
1560 free_fid(f);
1563 static void
1564 handle_message(struct imsg *imsg, size_t len)
1566 struct msg {
1567 uint8_t type;
1568 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1569 } msgs[] = {
1570 {Tversion, tversion},
1571 {Tattach, tattach},
1572 {Tclunk, tclunk},
1573 {Tflush, tflush},
1574 {Twalk, twalk},
1575 {Topen, topen},
1576 {Tcreate, tcreate},
1577 {Tread, tread},
1578 {Twrite, twrite},
1579 {Tstat, tstat},
1580 {Tremove, tremove},
1582 struct np_msg_header hdr;
1583 size_t i;
1584 uint8_t *data;
1586 #if DEBUG_PACKETS
1587 hexdump("incoming packet", imsg->data, len);
1588 #endif
1590 parse_message(imsg->data, len, &hdr, &data);
1591 len -= HEADERSIZE;
1593 log_debug("got request: len=%d type=%d[%s] tag=%d",
1594 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1596 if (!handshaked && hdr.type != Tversion) {
1597 client_send_listener(IMSG_CLOSE, NULL, 0);
1598 client_shutdown();
1599 return;
1602 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1603 if (msgs[i].type != hdr.type)
1604 continue;
1606 msgs[i].fn(&hdr, data, len);
1607 return;
1610 np_error(hdr.tag, "Not supported.");