Blob


1 /*
2 * Copyright (c) 2021, 2022 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>
20 #include <sys/types.h>
21 #include <sys/uio.h>
23 #include <dirent.h>
24 #include <endian.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <inttypes.h>
28 #include <libgen.h>
29 #include <pwd.h>
30 #include <signal.h>
31 #include <stdint.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <syslog.h>
36 #include <unistd.h>
38 #include "client.h"
39 #include "kami.h"
40 #include "kamid.h"
41 #include "log.h"
42 #include "sandbox.h"
43 #include "utils.h"
45 /*
46 * Max message size aviable via a single imsg.
47 */
48 #define IMSG_MAXSIZE (MAX_IMSGSIZE - IMSG_HEADER_SIZE)
50 /*
51 * The minimum value allowed for the msize.
52 */
53 #define MIN_MSIZE 256
55 #define DEBUG_PACKETS 0
57 /* straight outta /src/usr.bin/ssh/scp.c */
58 #define TYPE_OVERFLOW(type, val) \
59 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
60 (sizeof(type) == 8 && (val) > INT64_MAX) || \
61 (sizeof(type) != 4 && sizeof(type) != 8))
63 STAILQ_HEAD(dirhead, dir) dirs;
64 struct dir {
65 int refcount;
66 int fd;
67 STAILQ_ENTRY(dir) entries;
68 };
70 STAILQ_HEAD(fidhead, fid) fids;
71 struct fid {
72 uint32_t fid;
74 char fname[NAME_MAX];
76 /*
77 * the flags passed to open(2). O_CLOEXEC means ORCLOSE, that
78 * is to unlink the file upon Tclunk.
79 */
80 int iomode;
82 /*
83 * if fd is not -1 this fid was opened, fd represents its
84 * file descriptor and iomode the flags passed to open(2).
85 */
86 int fd;
87 DIR *d;
88 struct evbuffer *evb;
90 /*
91 * expected offset for Tread against a directory.
92 */
93 uint64_t offset;
95 struct qid qid;
96 struct dir *dir;
97 STAILQ_ENTRY(fid) entries;
98 };
100 static struct imsgev *iev_listener;
101 static struct evbuffer *evb;
102 static uint32_t peerid;
104 static int handshaked;
105 uint32_t msize;
107 static __dead void client_shutdown(void);
108 static void client_sig_handler(int, short, void *);
109 static void client_dispatch_listener(int, short, void *);
110 static void client_privdrop(const char *, const char *);
112 static int client_send_listenerp(int, uint32_t, const void *, uint16_t);
113 static int client_send_listener(int, const void *, uint16_t);
115 static void qid_update_from_sb(struct qid *, struct stat *);
117 static struct dir *new_dir(int);
118 static struct dir *dir_incref(struct dir *);
119 static void dir_decref(struct dir *);
121 static struct fid *new_fid(struct dir *, uint32_t, const char *, struct qid *);
122 static struct fid *fid_by_id(uint32_t);
123 static void free_fid(struct fid *);
125 static void parse_message(const uint8_t *, size_t,
126 struct np_msg_header *, uint8_t **);
128 static void np_write16(struct evbuffer *, uint16_t);
129 static void np_write32(struct evbuffer *, uint32_t);
130 static void np_write64(struct evbuffer *, uint64_t);
131 static void np_header(uint32_t, uint8_t, uint16_t);
132 static void np_string(struct evbuffer *, uint16_t, const char *);
133 static void np_qid(struct evbuffer *, struct qid *);
134 static void do_send(void);
136 static void np_version(uint16_t, uint32_t, const char *);
137 static void np_attach(uint16_t, struct qid *);
138 static void np_clunk(uint16_t);
139 static void np_flush(uint16_t);
140 static void np_walk(uint16_t, int, struct qid *);
141 static void np_open(uint16_t, struct qid *, uint32_t);
142 static void np_create(uint16_t, struct qid *, uint32_t);
143 static void np_read(uint16_t, uint32_t, void *);
144 static void np_write(uint16_t, uint32_t);
145 static void np_stat(uint16_t, uint16_t, void *);
146 static void np_wstat(uint16_t);
147 static void np_remove(uint16_t);
148 static void np_error(uint16_t, const char *);
149 static void np_errno(uint16_t);
151 static int np_read8(const char *, const char *, uint8_t *,
152 const uint8_t **, size_t *);
153 static int np_read16(const char *, const char *, uint16_t *,
154 const uint8_t **, size_t *);
155 static int np_read32(const char *, const char *, uint32_t *,
156 const uint8_t **, size_t *);
157 static int np_read64(const char *, const char *, uint64_t *,
158 const uint8_t **, size_t *);
160 #define READSTRERR -1
161 #define READSTRTRUNC -2
162 static int np_readstr(const char *, const char *, char *, size_t,
163 const uint8_t **, size_t *);
165 static int np_readst(const char *, const char *, struct np_stat *,
166 char *, size_t, const uint8_t **, size_t *);
168 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
169 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
170 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
171 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
173 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
175 #define NPREADST(f, dst, n, nl, src, len) np_readst(__func__, f, dst, n, nl, src, len)
177 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
178 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
179 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
180 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
181 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
182 static void topen(struct np_msg_header *, const uint8_t *, size_t);
183 static void tcreate(struct np_msg_header *, const uint8_t *, size_t);
184 static void tread(struct np_msg_header *, const uint8_t *, size_t);
185 static void twrite(struct np_msg_header *, const uint8_t *, size_t, struct fid **, off_t *, size_t *, size_t *, int *);
186 static void twrite_cont(struct fid *, off_t *, size_t *, size_t *, int *, uint16_t, const uint8_t *, size_t);
187 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
188 static void twstat(struct np_msg_header *, const uint8_t *, size_t);
189 static void tremove(struct np_msg_header *, const uint8_t *, size_t);
190 static void handle_message(struct imsg *, size_t, int);
192 __dead void
193 client(int debug, int verbose)
195 struct event ev_sigint, ev_sigterm;
197 log_init(debug, LOG_DAEMON);
198 log_setverbose(verbose);
200 setproctitle("client");
201 log_procinit("client");
203 log_debug("warming up");
205 event_init();
207 /* Setup signal handlers */
208 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
209 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
211 signal_add(&ev_sigint, NULL);
212 signal_add(&ev_sigterm, NULL);
214 signal(SIGPIPE, SIG_IGN);
215 signal(SIGHUP, SIG_IGN);
217 /* Setup pipe and event handler to the listener process */
218 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
219 fatal(NULL);
221 imsg_init(&iev_listener->ibuf, 3);
222 iev_listener->handler = client_dispatch_listener;
224 /* Setup event handlers. */
225 iev_listener->events = EV_READ;
226 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
227 iev_listener->events, iev_listener->handler, iev_listener);
228 event_add(&iev_listener->ev, NULL);
230 event_dispatch();
231 client_shutdown();
234 static __dead void
235 client_shutdown(void)
237 if (evb != NULL)
238 evbuffer_free(evb);
240 msgbuf_clear(&iev_listener->ibuf.w);
241 close(iev_listener->ibuf.fd);
243 free(iev_listener);
245 log_debug("client exiting");
246 exit(0);
249 static void
250 client_sig_handler(int sig, short event, void *d)
252 /*
253 * Normal signal handler rules don't apply because libevent
254 * decouples for us.
255 */
257 switch (sig) {
258 case SIGINT:
259 case SIGTERM:
260 client_shutdown();
261 default:
262 fatalx("unexpected signal %d", sig);
266 static void
267 client_dispatch_listener(int fd, short event, void *d)
269 static int auth = 0;
270 struct kd_auth_proc rauth;
271 struct kd_debug_info debug;
272 struct fid *f;
273 struct imsg imsg;
274 struct imsgev *iev = d;
275 struct imsgbuf *ibuf;
276 ssize_t n;
277 int shut = 0;
279 ibuf = &iev->ibuf;
281 if (event & EV_READ) {
282 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
283 fatal("imsg_read error");
284 if (n == 0) /* Connection closed */
285 shut = 1;
287 if (event & EV_WRITE) {
288 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
289 fatal("msgbuf_write");
290 if (n == 0) /* Connection closed */
291 shut = 1;
294 for (;;) {
295 if ((n = imsg_get(ibuf, &imsg)) == -1)
296 fatal("%s: imsg_get error", __func__);
297 if (n == 0) /* No more messages. */
298 break;
300 switch (imsg.hdr.type) {
301 case IMSG_CTL_LOG_VERBOSE:
302 if (IMSG_DATA_SIZE(imsg) != sizeof(verbose))
303 fatalx("%s: IMSG_CTL_LOG_VERBOSE wrong size",
304 __func__);
305 memcpy(&verbose, imsg.data, sizeof(verbose));
306 log_setverbose(verbose);
307 break;
308 case IMSG_CTL_DEBUG:
309 STAILQ_FOREACH(f, &fids, entries) {
310 memset(&debug, 0, sizeof(debug));
311 debug.fid = f->fid;
312 strlcpy(debug.path, f->fname,
313 sizeof(debug.path));
314 client_send_listenerp(IMSG_CTL_DEBUG_BACK,
315 imsg.hdr.peerid, &debug, sizeof(debug));
317 client_send_listenerp(IMSG_CTL_DEBUG_END,
318 imsg.hdr.peerid, NULL, 0);
319 break;
320 case IMSG_AUTH:
321 peerid = imsg.hdr.peerid;
322 if (auth)
323 fatalx("%s: IMSG_AUTH already done", __func__);
324 auth = 1;
326 if (IMSG_DATA_SIZE(imsg) != sizeof(rauth))
327 fatalx("mismatching size for IMSG_AUTH");
328 memcpy(&rauth, imsg.data, sizeof(rauth));
329 if (rauth.uname[sizeof(rauth.uname)-1] != '\0' ||
330 rauth.dir[sizeof(rauth.dir)-1] != '\0')
331 fatalx("IMSG_AUTH strings not NUL-terminated");
333 client_privdrop(rauth.uname, rauth.dir);
334 explicit_bzero(&rauth, sizeof(rauth));
335 break;
336 case IMSG_BUF:
337 case IMSG_BUF_CONT:
338 if (!auth)
339 fatalx("%s: can't handle messages before"
340 " doing the auth", __func__);
341 handle_message(&imsg, IMSG_DATA_SIZE(imsg),
342 imsg.hdr.type == IMSG_BUF_CONT);
343 break;
344 case IMSG_CONN_GONE:
345 log_debug("closing");
346 shut = 1;
347 break;
348 default:
349 log_debug("%s: unexpected imsg %d",
350 __func__, imsg.hdr.type);
351 break;
353 imsg_free(&imsg);
356 if (!shut)
357 imsg_event_add(iev);
358 else {
359 /* This pipe is dead. Remove its event handler. */
360 event_del(&iev->ev);
361 log_debug("pipe closed, shutting down...");
362 event_loopexit(NULL);
366 static void
367 client_privdrop(const char *username, const char *dir)
369 struct passwd *pw;
371 setproctitle("client %s", username);
373 if ((pw = getpwnam(username)) == NULL)
374 fatalx("getpwnam(%s) failed", username);
376 if (chroot(dir) == -1)
377 fatal("chroot");
378 if (chdir("/") == -1)
379 fatal("chdir(\"/\")");
381 if (setgroups(1, &pw->pw_gid) ||
382 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
383 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
384 fatal("can't drop privileges");
386 sandbox_client();
387 log_debug("client ready; user=%s dir=%s", username, dir);
389 if ((evb = evbuffer_new()) == NULL)
390 fatal("evbuffer_new");
393 static int
394 client_send_listenerp(int type, uint32_t peerid, const void *data, uint16_t len)
396 int ret;
398 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
399 data, len)) != -1)
400 imsg_event_add(iev_listener);
402 return ret;
405 static int
406 client_send_listener(int type, const void *data, uint16_t len)
408 return client_send_listenerp(type, peerid, data, len);
411 /* set qid fields from sb */
412 static void
413 qid_update_from_sb(struct qid *qid, struct stat *sb)
415 qid->path = sb->st_ino;
417 /*
418 * Theoretically (and hopefully!) this should be a 64 bit
419 * number. Unfortunately, 9P uses 32 bit timestamps.
420 */
421 qid->vers = sb->st_mtim.tv_sec;
423 if (S_ISREG(sb->st_mode))
424 qid->type = QTFILE;
425 else if (S_ISDIR(sb->st_mode))
426 qid->type = QTDIR;
427 else if (S_ISLNK(sb->st_mode))
428 qid->type = QTSYMLINK;
431 /* creates a qid given a fd */
432 static struct dir *
433 new_dir(int fd)
435 struct dir *dir;
437 if ((dir = calloc(1, sizeof(*dir))) == NULL)
438 return NULL;
440 dir->fd = fd;
441 STAILQ_INSERT_HEAD(&dirs, dir, entries);
442 return dir;
445 static struct dir *
446 dir_incref(struct dir *dir)
448 dir->refcount++;
449 return dir;
452 static void
453 dir_decref(struct dir *dir)
455 if (--dir->refcount > 0)
456 return;
458 STAILQ_REMOVE(&dirs, dir, dir, entries);
460 close(dir->fd);
461 free(dir);
464 static struct fid *
465 new_fid(struct dir *dir, uint32_t fid, const char *path, struct qid *qid)
467 struct fid *f;
468 struct qid q;
469 struct stat sb;
471 if (qid == NULL) {
472 if (fstatat(dir->fd, path, &sb, 0)) {
473 log_warn("fstatat(%s)", path);
474 return NULL;
476 qid_update_from_sb(&q, &sb);
477 qid = &q;
480 if ((f = calloc(1, sizeof(*f))) == NULL)
481 return NULL;
483 f->dir = dir_incref(dir);
484 f->fid = fid;
485 f->fd = -1;
487 strlcpy(f->fname, path, sizeof(f->fname));
489 memcpy(&f->qid, qid, sizeof(f->qid));
491 STAILQ_INSERT_HEAD(&fids, f, entries);
493 return f;
496 static struct fid *
497 fid_by_id(uint32_t fid)
499 struct fid *f;
501 STAILQ_FOREACH(f, &fids, entries) {
502 if (f->fid == fid)
503 return f;
506 return NULL;
509 static void
510 free_fid(struct fid *f)
512 int r;
514 if (f->fd != -1) {
515 if (f->d != NULL)
516 r = closedir(f->d);
517 else
518 r = close(f->fd);
520 if (r == -1)
521 fatal("can't close fid %d", f->fid);
523 if (f->evb != NULL)
524 evbuffer_free(f->evb);
526 /* try to honour ORCLOSE if requested */
527 if (f->iomode & O_CLOEXEC)
528 unlinkat(f->dir->fd, f->fname, 0);
531 dir_decref(f->dir);
533 STAILQ_REMOVE(&fids, f, fid, entries);
534 free(f);
537 static void
538 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
539 uint8_t **cnt)
541 size_t olen = len;
543 if (!NPREAD32("len", &hdr->len, &data, &len) ||
544 !NPREAD8("type", &hdr->type, &data, &len) ||
545 !NPREAD16("tag", &hdr->tag, &data, &len))
546 goto err;
548 /*
549 * Allow only "jumbo" Twrites.
550 */
551 if (hdr->type != Twrite && olen != hdr->len)
552 goto err;
554 if (hdr->type < Tversion ||
555 hdr->type >= Tmax ||
556 hdr->type == Terror ||
557 (hdr->type & 0x1) != 0) /* cannot recv a R* */
558 goto err;
560 hdr->tag = le32toh(hdr->tag);
562 *cnt = (uint8_t *)data;
563 return;
565 err:
566 log_warnx("got invalid message: (%d, %d, %d)",
567 hdr->len, hdr->type, hdr->tag);
568 client_send_listener(IMSG_CLOSE, NULL, 0);
569 client_shutdown();
572 static void
573 np_write16(struct evbuffer *e, uint16_t x)
575 x = htole16(x);
576 evbuffer_add(e, &x, sizeof(x));
579 static void
580 np_write32(struct evbuffer *e, uint32_t x)
582 x = htole32(x);
583 evbuffer_add(e, &x, sizeof(x));
586 static void
587 np_write64(struct evbuffer *e, uint64_t x)
589 x = htole64(x);
590 evbuffer_add(e, &x, sizeof(x));
593 static void
594 np_writebuf(struct evbuffer *e, size_t len, void *data)
596 evbuffer_add(e, data, len);
599 static void
600 np_header(uint32_t len, uint8_t type, uint16_t tag)
602 len += HEADERSIZE;
604 len = htole32(len);
605 tag = htole16(tag);
607 evbuffer_add(evb, &len, sizeof(len));
608 evbuffer_add(evb, &type, sizeof(type));
609 evbuffer_add(evb, &tag, sizeof(tag));
612 static void
613 np_string(struct evbuffer *e, uint16_t len, const char *str)
615 uint16_t l = len;
617 len = htole16(len);
618 evbuffer_add(e, &len, sizeof(len));
619 evbuffer_add(e, str, l);
622 static void
623 np_qid(struct evbuffer *e, struct qid *qid)
625 uint64_t path;
626 uint32_t vers;
628 path = htole64(qid->path);
629 vers = htole32(qid->vers);
631 evbuffer_add(e, &qid->type, sizeof(qid->type));
632 evbuffer_add(e, &vers, sizeof(vers));
633 evbuffer_add(e, &path, sizeof(path));
636 static void
637 do_send(void)
639 size_t len;
640 uint8_t *data;
642 len = EVBUFFER_LENGTH(evb);
643 data = EVBUFFER_DATA(evb);
645 #if DEBUG_PACKETS
646 hexdump("outgoing packet", data, len);
647 #endif
649 while (len > IMSG_MAXSIZE) {
650 client_send_listener(IMSG_BUF, data, IMSG_MAXSIZE);
651 evbuffer_drain(evb, IMSG_MAXSIZE);
652 len -= IMSG_MAXSIZE;
653 data += IMSG_MAXSIZE;
656 if (len != 0) {
657 client_send_listener(IMSG_BUF, data, len);
658 evbuffer_drain(evb, len);
662 static void
663 np_version(uint16_t tag, uint32_t msize, const char *version)
665 uint16_t l;
667 l = strlen(version);
669 msize = htole32(msize);
671 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
672 evbuffer_add(evb, &msize, sizeof(msize));
673 np_string(evb, l, version);
674 do_send();
677 static void
678 np_attach(uint16_t tag, struct qid *qid)
680 np_header(QIDSIZE, Rattach, tag);
681 np_qid(evb, qid);
682 do_send();
685 static void
686 np_clunk(uint16_t tag)
688 np_header(0, Rclunk, tag);
689 do_send();
692 static void
693 np_flush(uint16_t tag)
695 np_header(0, Rflush, tag);
696 do_send();
699 static void
700 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
702 int i;
704 /* two bytes for the counter */
705 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
706 np_write16(evb, nwqid);
707 for (i = 0; i < nwqid; ++i)
708 np_qid(evb, wqid + i);
710 do_send();
713 static void
714 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
716 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
717 np_qid(evb, qid);
718 np_write32(evb, iounit);
719 do_send();
722 static void
723 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
725 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
726 np_qid(evb, qid);
727 np_write32(evb, iounit);
728 do_send();
731 static void
732 np_read(uint16_t tag, uint32_t count, void *data)
734 if (sizeof(count) + count + HEADERSIZE > msize) {
735 np_error(tag, "Rread would overflow");
736 return;
739 np_header(sizeof(count) + count, Rread, tag);
740 np_write32(evb, count);
741 np_writebuf(evb, count, data);
742 do_send();
745 static void
746 np_write(uint16_t tag, uint32_t count)
748 np_header(sizeof(count), Rwrite, tag);
749 np_write32(evb, count);
750 do_send();
753 static void
754 np_stat(uint16_t tag, uint16_t count, void *data)
756 if (sizeof(count) + count + HEADERSIZE >= msize) {
757 np_error(tag, "Rstat would overflow");
758 return;
761 np_header(sizeof(count) + count, Rstat, tag);
762 np_write16(evb, count);
763 np_writebuf(evb, count, data);
764 do_send();
767 static void
768 np_wstat(uint16_t tag)
770 np_header(0, Rwstat, tag);
771 do_send();
774 static void
775 np_remove(uint16_t tag)
777 np_header(0, Rremove, tag);
778 do_send();
781 static void
782 np_error(uint16_t tag, const char *errstr)
784 uint16_t l;
786 l = strlen(errstr);
788 np_header(sizeof(l) + l, Rerror, tag);
789 np_string(evb, l, errstr);
790 do_send();
793 static void
794 np_errno(uint16_t tag)
796 int saved_errno;
797 char buf[NL_TEXTMAX] = {0};
799 saved_errno = errno;
801 strerror_r(errno, buf, sizeof(buf));
802 np_error(tag, buf);
804 errno = saved_errno;
807 static int
808 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
809 size_t *len)
811 if (*len < sizeof(*dst)) {
812 log_warnx("%s: wanted %zu bytes for the %s field but only "
813 "%zu are available.", t, sizeof(*dst), f, *len);
814 return 0;
817 memcpy(dst, *src, sizeof(*dst));
818 *src += sizeof(*dst);
819 *len -= sizeof(*dst);
821 return 1;
824 static int
825 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
826 size_t *len)
828 if (*len < sizeof(*dst)) {
829 log_warnx("%s: wanted %zu bytes for the %s field but only "
830 "%zu are available.", t, sizeof(*dst), f, *len);
831 return 0;
834 memcpy(dst, *src, sizeof(*dst));
835 *src += sizeof(*dst);
836 *len -= sizeof(*dst);
837 *dst = le16toh(*dst);
839 return 1;
842 static int
843 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
844 size_t *len)
846 if (*len < sizeof(*dst)) {
847 log_warnx("%s: wanted %zu bytes for the %s field but only "
848 "%zu are available.", t, sizeof(*dst), f, *len);
849 return 0;
852 memcpy(dst, *src, sizeof(*dst));
853 *src += sizeof(*dst);
854 *len -= sizeof(*dst);
855 *dst = le32toh(*dst);
857 return 1;
860 static int
861 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
862 size_t *len)
864 if (*len < sizeof(*dst)) {
865 log_warnx("%s: wanted %zu bytes for the %s field but only "
866 "%zu are available.", t, sizeof(*dst), f, *len);
867 return 0;
870 memcpy(dst, *src, sizeof(*dst));
871 *src += sizeof(*dst);
872 *len -= sizeof(*dst);
873 *dst = le64toh(*dst);
875 return 1;
878 static int
879 np_readstr(const char *t, const char *f, char *res, size_t reslen,
880 const uint8_t **src, size_t *len)
882 uint16_t sl;
883 char buf[32];
885 strlcpy(buf, f, sizeof(buf));
886 strlcat(buf, "-len", sizeof(buf));
888 if (!np_read16(t, buf, &sl, src, len))
889 return READSTRERR;
891 if (*len < sl) {
892 log_warnx("%s: wanted %d bytes for the %s field but only "
893 "%zu are available.", t, sl, f, *len);
894 return READSTRERR;
897 if (*len > reslen-1)
898 return READSTRTRUNC;
900 memcpy(res, *src, sl);
901 res[sl] = '\0';
902 *src += sl;
903 *len -= sl;
905 return 0;
908 static int
909 np_readst(const char *t, const char *f, struct np_stat *st,
910 char *name, size_t namelen, const uint8_t **src, size_t *len)
912 memset(st, 0, sizeof(*st));
914 /* len is sent twice! */
915 if (!np_read16(t, "stat len", &st->size, src, len) ||
916 !np_read16(t, "stat.size", &st->size, src, len) ||
917 !np_read16(t, "stat.type", &st->type, src, len) ||
918 !np_read32(t, "stat.dev", &st->dev, src, len) ||
919 !np_read64(t, "stat.qid.path", &st->qid.path, src, len) ||
920 !np_read32(t, "stat.qid.vers", &st->qid.vers, src, len) ||
921 !np_read8(t, "stat.qid.type", &st->qid.type, src, len) ||
922 !np_read32(t, "stat.mode", &st->mode, src, len) ||
923 !np_read32(t, "stat.atime", &st->atime, src, len) ||
924 !np_read32(t, "stat.mtime", &st->mtime, src, len) ||
925 !np_read64(t, "stat.length", &st->length, src, len))
926 return READSTRERR;
928 /*
929 * ignore everything but the name, we don't support
930 * changing those fields anyway
931 */
932 st->name = name;
933 return np_readstr(t, "stat.name", name, namelen, src, len);
936 static void
937 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
939 char *dot, version[32];
941 if (handshaked)
942 goto err;
944 /* msize[4] version[s] */
945 if (!NPREAD32("msize", &msize, &data, &len))
946 goto err;
948 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
949 case READSTRERR:
950 goto err;
951 case READSTRTRUNC:
952 log_warnx("9P version string too long, truncated");
953 np_version(hdr->tag, MSIZE9P, "unknown");
954 return;
957 if (len != 0)
958 goto err;
960 if ((dot = strchr(version, '.')) != NULL)
961 *dot = '\0';
963 if (strcmp(version, VERSION9P) != 0) {
964 log_warnx("unknown 9P version \"%s\"; want "VERSION9P,
965 version);
966 np_version(hdr->tag, MSIZE9P, "unknown");
967 return;
970 if (msize < MIN_MSIZE) {
971 log_warnx("msize too small: %"PRIu32"; want %d at least",
972 msize, MIN_MSIZE);
973 np_version(hdr->tag, MSIZE9P, "unknown");
974 return;
977 /* version matched */
978 handshaked = 1;
979 msize = MIN(msize, MSIZE9P);
980 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
981 np_version(hdr->tag, msize, VERSION9P);
982 return;
984 err:
985 client_send_listener(IMSG_CLOSE, NULL, 0);
986 client_shutdown();
989 static void
990 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
992 struct dir *dir;
993 struct fid *f;
994 uint32_t fid, afid;
995 int fd;
996 char aname[PATH_MAX];
998 /* fid[4] afid[4] uname[s] aname[s] */
1000 if (!NPREAD32("fid", &fid, &data, &len) ||
1001 !NPREAD32("afid", &afid, &data, &len))
1002 goto err;
1004 /* read the uname but don't actually use it */
1005 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
1006 case READSTRERR:
1007 goto err;
1008 case READSTRTRUNC:
1009 np_error(hdr->tag, "name too long");
1010 return;
1013 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
1014 case READSTRERR:
1015 goto err;
1016 case READSTRTRUNC:
1017 np_error(hdr->tag, "name too long");
1018 return;
1021 if (*aname == '\0')
1022 strlcpy(aname, "/", sizeof(aname));
1024 if (len != 0)
1025 goto err;
1027 if (fid_by_id(fid) != NULL || afid != NOFID) {
1028 np_error(hdr->tag, "invalid fid or afid");
1029 return;
1032 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
1033 goto fail;
1035 if ((dir = new_dir(fd)) == NULL)
1036 goto fail;
1038 log_debug("attached %s to %d", aname, fid);
1040 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
1041 dir_decref(dir);
1042 goto fail;
1045 np_attach(hdr->tag, &f->qid);
1046 return;
1048 fail:
1049 np_errno(hdr->tag);
1050 log_warn("failed to attach %s", aname);
1051 return;
1053 err:
1054 client_send_listener(IMSG_CLOSE, NULL, 0);
1055 client_shutdown();
1058 static void
1059 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1061 struct fid *f;
1062 uint32_t fid;
1064 /* fid[4] */
1065 if (!NPREAD32("fid", &fid, &data, &len) ||
1066 len != 0) {
1067 client_send_listener(IMSG_CLOSE, NULL, 0);
1068 client_shutdown();
1069 return;
1072 if ((f = fid_by_id(fid)) == NULL) {
1073 np_error(hdr->tag, "invalid fid");
1074 return;
1077 free_fid(f);
1078 np_clunk(hdr->tag);
1081 static void
1082 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1084 uint16_t oldtag;
1087 * We're doing only synchronous I/O. Tflush is implemented
1088 * only because it's illegal to reply with a Rerror.
1091 /* oldtag[2] */
1092 if (len != sizeof(oldtag)) {
1093 log_warnx("Tflush with the wrong size: got %zu want %zu",
1094 len, sizeof(oldtag));
1095 client_send_listener(IMSG_CLOSE, NULL, 0);
1096 client_shutdown();
1097 return;
1100 np_flush(hdr->tag);
1103 static void
1104 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1106 struct stat sb;
1107 struct dir *dir;
1108 struct qid wqid[MAXWELEM] = {0};
1109 struct fid *f, *nf;
1110 uint32_t fid, newfid;
1111 uint16_t nwname;
1112 int fd, oldfd, no, nwqid = 0;
1113 char wnam[PATH_MAX];
1115 if (!NPREAD32("fid", &fid, &data, &len) ||
1116 !NPREAD32("newfid", &newfid, &data, &len) ||
1117 !NPREAD16("nwname", &nwname, &data, &len))
1118 goto err;
1120 if (nwname > MAXWELEM) {
1121 log_warnx("Twalk: more than %d path elements: %d",
1122 MAXWELEM, nwname);
1123 goto err;
1126 if ((f = fid_by_id(fid)) == NULL) {
1127 np_error(hdr->tag, "invalid fid");
1128 return;
1131 if (f->fd != -1) {
1132 np_error(hdr->tag, "fid already opened for I/O");
1133 return;
1136 if (fid == newfid)
1137 nf = f;
1138 else if ((nf = fid_by_id(newfid)) != NULL) {
1139 np_error(hdr->tag, "newfid already in use");
1140 return;
1141 } else
1142 nf = NULL;
1144 /* special case: fid duplication */
1145 if (nwname == 0) {
1147 * TODO: should we forbid fids duplication when fid ==
1148 * newfid?
1150 if (nf == NULL &&
1151 (nf = new_fid(f->dir, newfid, f->fname, &f->qid)) == NULL)
1152 fatal("new_fid duplication");
1154 np_walk(hdr->tag, 0, NULL);
1155 return;
1158 if (!(f->qid.type & QTDIR)) {
1159 np_error(hdr->tag, "fid doesn't represent a directory");
1160 return;
1163 oldfd = f->dir->fd;
1165 for (nwqid = 0; nwqid < nwname; nwqid++) {
1166 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1167 case READSTRERR:
1168 goto err;
1169 case READSTRTRUNC:
1170 np_error(hdr->tag, "wname too long");
1171 return;
1174 if (*wnam == '\0' ||
1175 strchr(wnam, '/') != NULL ||
1176 !strcmp(wnam, ".")) {
1177 errno = EINVAL;
1178 goto cantopen;
1181 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1182 errno != ENOTDIR)
1183 goto cantopen;
1185 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1186 (fd != -1 && fstat(fd, &sb) == -1))
1187 goto cantopen;
1189 qid_update_from_sb(&wqid[nwqid], &sb);
1191 /* reached a file but we still have other components */
1192 if (fd == -1 && nwqid+1 < nwname)
1193 goto cantopen;
1195 /* reached the end and found a file */
1196 if (fd == -1 && nwqid+1 == nwname)
1197 continue;
1199 if (oldfd != f->dir->fd)
1200 close(oldfd);
1201 oldfd = fd;
1204 if (len != 0)
1205 goto err;
1208 * If fd is -1 we've reached a file, otherwise we've just
1209 * reached another directory. We must pay attention to what
1210 * file descriptor we use to create the dir, because if we've
1211 * reached a file and oldfd is f->dir->fd then we *must* share
1212 * the same dir (it was a walk of one path from a directory to a
1213 * file, otherwise fun is bound to happen as soon as the client
1214 * closes the fid for the directory but keeps the one for the
1215 * file.
1217 if (fd == -1 && oldfd == f->dir->fd)
1218 dir = f->dir;
1219 else if (fd == -1)
1220 dir = new_dir(oldfd);
1221 else
1222 dir = new_dir(fd);
1224 if (dir == NULL)
1225 fatal("new_dir");
1227 if (nf == NULL) {
1228 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1229 fatal("new fid");
1230 } else {
1231 /* update the dir */
1232 dir_decref(nf->dir);
1233 nf->dir = dir_incref(dir);
1236 np_walk(hdr->tag, nwqid, wqid);
1237 return;
1239 cantopen:
1240 if (oldfd != f->dir->fd)
1241 close(oldfd);
1242 no = errno;
1243 if (nwqid == 0)
1244 np_error(hdr->tag, strerror(no));
1245 else
1246 np_walk(hdr->tag, nwqid, wqid);
1247 return;
1249 err:
1250 client_send_listener(IMSG_CLOSE, NULL, 0);
1251 client_shutdown();
1254 static inline int
1255 npmode_to_unix(uint8_t mode, int *flags)
1257 switch (mode & 0x0F) {
1258 case KOREAD:
1259 *flags = O_RDONLY;
1260 break;
1261 case KOWRITE:
1262 *flags = O_WRONLY;
1263 break;
1264 case KORDWR:
1265 *flags = O_RDWR;
1266 break;
1267 case KOEXEC:
1268 log_warnx("tried to open something with KOEXEC");
1269 /* fallthrough */
1270 default:
1271 return -1;
1274 if (mode & KOTRUNC)
1275 *flags |= O_TRUNC;
1276 if (mode & KORCLOSE)
1277 *flags |= O_CLOEXEC;
1279 return 0;
1282 static void
1283 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1285 struct stat sb;
1286 struct qid qid;
1287 struct fid *f;
1288 uint32_t fid;
1289 uint8_t mode;
1290 const char *path;
1292 /* fid[4] mode[1] */
1293 if (!NPREAD32("fid", &fid, &data, &len) ||
1294 !NPREAD8("mode", &mode, &data, &len) ||
1295 len != 0) {
1296 client_send_listener(IMSG_CLOSE, NULL, 0);
1297 client_shutdown();
1298 return;
1301 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1302 np_error(hdr->tag, "invalid fid");
1303 return;
1306 if (npmode_to_unix(mode, &f->iomode) == -1) {
1307 np_error(hdr->tag, "invalid mode");
1308 return;
1311 path = f->fname;
1312 if (f->qid.type & QTDIR)
1313 path = ".";
1315 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1316 np_error(hdr->tag, strerror(errno));
1317 return;
1320 if (fstat(f->fd, &sb) == -1)
1321 fatal("fstat");
1323 if (S_ISDIR(sb.st_mode)) {
1324 if ((f->d = fdopendir(f->fd)) == NULL) {
1325 np_errno(hdr->tag);
1326 close(f->fd);
1327 f->fd = -1;
1328 return;
1331 if ((f->evb = evbuffer_new()) == NULL) {
1332 np_errno(hdr->tag);
1333 closedir(f->d);
1334 f->d = NULL;
1335 f->fd = -1;
1339 f->offset = 0;
1341 qid_update_from_sb(&qid, &sb);
1342 np_open(hdr->tag, &qid, sb.st_blksize);
1345 static void
1346 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1348 struct stat sb;
1349 struct qid qid;
1350 struct fid *f;
1351 uint32_t fid, perm;
1352 uint8_t mode;
1353 char name[PATH_MAX];
1355 /* fid[4] name[s] perm[4] mode[1] */
1356 if (!NPREAD32("fid", &fid, &data, &len))
1357 goto err;
1358 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1359 case READSTRERR:
1360 goto err;
1361 case READSTRTRUNC:
1362 np_error(hdr->tag, "name too long");
1363 return;
1365 if (!NPREAD32("perm", &perm, &data, &len) ||
1366 !NPREAD8("mode", &mode, &data, &len) ||
1367 len != 0)
1368 goto err;
1370 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1371 strchr(name, '/') != NULL) {
1372 np_error(hdr->tag, "invalid name");
1373 return;
1376 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1377 np_error(hdr->tag, "invalid fid");
1378 return;
1381 if (!(f->qid.type & QTDIR)) {
1382 np_error(hdr->tag, "fid doesn't identify a directory");
1383 return;
1386 if (npmode_to_unix(mode, &f->iomode) == -1) {
1387 np_error(hdr->tag, "invalid mode");
1388 return;
1391 if (f->iomode & O_RDONLY) {
1392 np_error(hdr->tag, "can't create a read-only file");
1393 return;
1396 /* TODO: parse the mode */
1398 if (perm & 0x80000000) {
1399 /* create a directory */
1400 f->fd = mkdirat(f->dir->fd, name, 0755);
1401 } else {
1402 /* create a file */
1403 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1404 0644);
1407 if (f->fd == -1) {
1408 np_errno(hdr->tag);
1409 return;
1412 if (fstat(f->fd, &sb) == -1)
1413 fatal("fstat");
1415 if (S_ISDIR(sb.st_mode)) {
1416 if ((f->d = fdopendir(f->fd)) == NULL) {
1417 np_errno(hdr->tag);
1418 close(f->fd);
1419 f->fd = -1;
1420 return;
1423 if ((f->evb = evbuffer_new()) == NULL) {
1424 np_errno(hdr->tag);
1425 closedir(f->d);
1426 f->d = NULL;
1427 f->fd = -1;
1431 f->offset = 0;
1433 qid_update_from_sb(&qid, &sb);
1434 np_create(hdr->tag, &qid, sb.st_blksize);
1436 return;
1438 err:
1439 client_send_listener(IMSG_CLOSE, NULL, 0);
1440 client_shutdown();
1443 static inline int
1444 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1446 struct qid qid;
1447 const char *uid, *gid, *muid;
1448 size_t tot;
1449 uint32_t mode;
1450 uint16_t namlen, uidlen, gidlen, ulen;
1452 qid_update_from_sb(&qid, sb);
1454 /* TODO: fill these fields */
1455 uid = "";
1456 gid = "";
1457 muid = "";
1459 namlen = strlen(fname);
1460 uidlen = strlen(uid);
1461 gidlen = strlen(gid);
1462 ulen = strlen(muid);
1464 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1465 if (tot > UINT16_MAX) {
1466 log_warnx("stat info for dir entry %s would overflow",
1467 fname);
1468 return -1;
1471 mode = sb->st_mode & 0xFFFF;
1472 if (qid.type & QTDIR)
1473 mode |= 0x80000000;
1475 np_write16(evb, tot); /* size[2] */
1476 np_write16(evb, sb->st_rdev); /* type[2] */
1477 np_write32(evb, sb->st_dev); /* dev[4] */
1478 np_qid(evb, &qid); /* qid[13] */
1479 np_write32(evb, mode); /* mode[4] */
1480 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1481 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1483 /* special case: directories have size 0 */
1484 if (qid.type & QTDIR)
1485 np_write64(evb, 0);
1486 else
1487 np_write64(evb, sb->st_size); /* length[8] */
1489 np_string(evb, namlen, fname); /* name[s] */
1490 np_string(evb, uidlen, uid); /* uid[s] */
1491 np_string(evb, gidlen, gid); /* gid[s] */
1492 np_string(evb, ulen, muid); /* muid[s] */
1494 return 0;
1497 static void
1498 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1500 static char buf[MSIZE9P - HEADERSIZE - 4];
1501 struct fid *f;
1502 ssize_t r;
1503 size_t howmuch;
1504 uint64_t off;
1505 uint32_t fid, count;
1507 /* fid[4] offset[8] count[4] */
1508 if (!NPREAD32("fid", &fid, &data, &len) ||
1509 !NPREAD64("offset", &off, &data, &len) ||
1510 !NPREAD32("count", &count, &data, &len) ||
1511 len != 0) {
1512 client_send_listener(IMSG_CLOSE, NULL, 0);
1513 client_shutdown();
1514 return;
1517 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1518 np_error(hdr->tag, "invalid fid");
1519 return;
1522 if (TYPE_OVERFLOW(off_t, off)) {
1523 log_warnx("unexpected off_t size");
1524 np_error(hdr->tag, "invalid offset");
1525 return;
1528 if (f->d == NULL) {
1529 /* read a file */
1530 howmuch = MIN(sizeof(buf), count);
1531 r = pread(f->fd, buf, howmuch, (off_t)off);
1532 if (r == -1)
1533 np_errno(hdr->tag);
1534 else
1535 np_read(hdr->tag, r, buf);
1536 } else {
1537 if (off == 0 && f->offset != 0) {
1538 rewinddir(f->d);
1539 f->offset = 0;
1540 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1543 if (off != f->offset) {
1544 np_error(hdr->tag, "can't seek in directories");
1545 return;
1548 while (EVBUFFER_LENGTH(f->evb) < count) {
1549 struct dirent *d;
1550 struct stat sb;
1552 if ((d = readdir(f->d)) == NULL)
1553 break;
1554 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1555 continue;
1556 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1557 warn("fstatat");
1558 continue;
1560 serialize_stat(d->d_name, &sb, f->evb);
1563 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1564 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1565 evbuffer_drain(f->evb, count);
1567 f->offset += count;
1571 static void
1572 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len,
1573 struct fid **writefid, off_t *writepos, size_t *writetot,
1574 size_t *writeleft, int *writeskip)
1576 struct fid *f;
1577 ssize_t r;
1578 uint64_t off;
1579 uint32_t fid, count;
1581 /* fid[4] offset[8] count[4] data[count] */
1582 if (!NPREAD32("fid", &fid, &data, &len) ||
1583 !NPREAD64("off", &off, &data, &len) ||
1584 !NPREAD32("count", &count, &data, &len) ||
1585 count < len) {
1586 client_send_listener(IMSG_CLOSE, NULL, 0);
1587 client_shutdown();
1588 return;
1591 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1592 *writeskip = 1;
1593 np_error(hdr->tag, "invalid fid");
1594 return;
1597 if (!(f->iomode & O_WRONLY) &&
1598 !(f->iomode & O_RDWR)) {
1599 *writeskip = 1;
1600 np_error(hdr->tag, "fid not opened for writing");
1601 return;
1604 if (TYPE_OVERFLOW(off_t, off)) {
1605 *writeskip = 1;
1606 log_warnx("unexpected off_t size");
1607 np_error(hdr->tag, "invalid offset");
1608 return;
1611 if ((r = pwrite(f->fd, data, len, off)) == -1) {
1612 *writeskip = 1;
1613 np_errno(hdr->tag);
1614 } else if (count == len)
1615 np_write(hdr->tag, r);
1617 /* account for a continuated write */
1618 if (count > len) {
1619 *writefid = f;
1620 *writepos = off + len;
1621 *writetot = len;
1622 *writeleft = count - len;
1623 *writeskip = 0;
1627 static void
1628 twrite_cont(struct fid *f, off_t *writepos, size_t *writetot,
1629 size_t *writeleft, int *writeskip, uint16_t tag, const uint8_t *data,
1630 size_t len)
1632 ssize_t r;
1634 if (len > *writeleft) {
1635 client_send_listener(IMSG_CLOSE, NULL, 0);
1636 client_shutdown();
1637 return;
1640 if ((r = pwrite(f->fd, data, len, *writepos)) == -1) {
1641 *writeskip = 1;
1642 np_errno(tag);
1643 return;
1646 *writetot += len;
1647 *writeleft -= len;
1648 *writepos += len;
1650 if (*writeleft == 0)
1651 np_write(tag, *writetot);
1654 static void
1655 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1657 struct evbuffer *evb;
1658 struct stat sb;
1659 struct fid *f;
1660 int r;
1661 uint32_t fid;
1663 /* fid[4] */
1664 if (!NPREAD32("fid", &fid, &data, &len) ||
1665 len != 0) {
1666 client_send_listener(IMSG_CLOSE, NULL, 0);
1667 client_shutdown();
1668 return;
1672 * plan9' stat(9P) is not clear on whether the stat is allowed
1673 * on opened fids or not. We're allowing stat regardless of the
1674 * status of the fid.
1677 if ((f = fid_by_id(fid)) == NULL) {
1678 np_error(hdr->tag, "invalid fid");
1679 return;
1682 if ((evb = evbuffer_new()) == NULL)
1683 fatal("evbuffer_new");
1685 if (f->fd != -1)
1686 r = fstat(f->fd, &sb);
1687 else if (f->qid.type & QTDIR)
1688 r = fstat(f->dir->fd, &sb);
1689 else
1690 r = fstatat(f->dir->fd, f->fname, &sb, 0);
1692 if (r == -1) {
1693 np_errno(hdr->tag);
1694 evbuffer_free(evb);
1695 return;
1698 if (serialize_stat(f->fname, &sb, evb) == -1)
1699 np_error(hdr->tag, "stat would overflow");
1700 else
1701 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1702 evbuffer_free(evb);
1705 static void
1706 twstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1708 struct timespec times[2];
1709 struct np_stat st;
1710 struct fid *f;
1711 int r;
1712 uint32_t fid;
1713 char name[PATH_MAX];
1715 /* fid[4] stat[n] */
1716 if (!NPREAD32("fid", &fid, &data, &len))
1717 goto err;
1719 switch (NPREADST("stat", &st, name, sizeof(name), &data, &len)) {
1720 case READSTRERR:
1721 goto err;
1722 case READSTRTRUNC:
1723 log_warnx("wstat new name would overflow");
1724 np_error(hdr->tag, "new name too long");
1725 return;
1729 * We skip the reading of some fields voluntarily because we
1730 * don't support chown, so len will always be > 0!
1732 #ifdef notyet
1733 if (len != 0)
1734 goto err;
1735 #endif
1737 if ((f = fid_by_id(fid)) == NULL) {
1738 np_error(hdr->tag, "invalid fid");
1739 return;
1743 * 9P wants these edits to be done in an atomic fashion,
1744 * something that I don't think it's possible on UNIX without
1745 * some special kernel help. Changing atime or mtime,
1746 * permissions, or rename the file are different syscalls.
1748 * Also, silently ignore stuff we can't/don't want to modify.
1751 /* change the permissions */
1752 if (st.mode != (uint32_t)-1) {
1753 mode_t m = st.mode & 0x7FF; /* silently truncate higer bits */
1754 if (f->fd != -1)
1755 r = fchmod(f->fd, m);
1756 else
1757 r = fchmodat(f->dir->fd, f->fname, m, 0);
1759 if (r == -1) {
1760 np_errno(hdr->tag);
1761 return;
1765 /* change the atime/mtime of the fid, opened or not */
1766 if (st.atime != (uint32_t)-1 || st.mtime != (uint32_t)-1) {
1767 times[0].tv_nsec = UTIME_OMIT;
1768 times[1].tv_nsec = UTIME_OMIT;
1770 if (st.atime != (uint32_t)-1) {
1771 times[0].tv_sec = st.atime;
1772 times[0].tv_nsec = 0;
1774 if (st.mtime != (uint32_t)-1) {
1775 times[1].tv_sec = st.mtime;
1776 times[1].tv_nsec = 0;
1779 if (f->fd != -1)
1780 r = futimens(f->fd, times);
1781 else
1782 r = utimensat(f->dir->fd, f->fname, times, 0);
1784 if (r == -1) {
1785 np_errno(hdr->tag);
1786 return;
1790 /* truncate */
1791 if (st.length != (uint64_t)-1) {
1792 if (f->fd == -1) {
1793 np_error(hdr->tag, "can't truncate a non-opened fid");
1794 return;
1797 if (f->qid.type & QTDIR && st.length != 0) {
1798 np_error(hdr->tag, "can't truncate directories");
1799 return;
1802 if (TYPE_OVERFLOW(off_t, st.length)) {
1803 log_warnx("truncate request overflows off_t: %"PRIu64,
1804 st.length);
1805 np_error(hdr->tag, "length overflows");
1806 return;
1809 if (f->qid.type == 0 &&
1810 ftruncate(f->fd, st.length) == -1) {
1811 np_errno(hdr->tag);
1812 return;
1816 /* rename (change the name entry) */
1817 if (*st.name != '\0') {
1818 struct stat sb;
1819 const char *newname;
1822 * XXX: 9P requires that we disallow changing the name
1823 * to that of an existing file. We can't do that
1824 * atomically (rename is happy about stealing names)
1825 * so this is just a best effort.
1827 if (fstatat(f->dir->fd, st.name, &sb, 0) == -1 &&
1828 errno != ENOENT) {
1829 np_error(hdr->tag, "target file exists");
1830 return;
1833 r = renameat(f->dir->fd, f->fname, f->dir->fd, st.name);
1834 if (r == -1) {
1835 np_errno(hdr->tag);
1836 return;
1839 /* fix the fid so it points to the new file */
1841 if ((newname = strchr(st.name, '/')) != NULL)
1842 newname++; /* skip / */
1843 else
1844 newname = st.name;
1845 strlcpy(f->fname, newname, sizeof(f->fname));
1847 if (strchr(st.name, '/') != NULL) {
1848 struct dir *dir;
1849 char *dname;
1850 int fd;
1852 dname = dirname(st.name);
1853 fd = openat(f->dir->fd, dname, O_RDONLY|O_DIRECTORY);
1854 if (fd == -1) {
1855 np_errno(hdr->tag);
1856 free_fid(f);
1857 return;
1860 if ((dir = new_dir(fd)) == NULL) {
1861 np_errno(hdr->tag);
1862 free_fid(f);
1863 return;
1866 dir_decref(f->dir);
1867 f->dir = dir_incref(dir);
1871 np_wstat(hdr->tag);
1872 return;
1874 err:
1875 client_send_listener(IMSG_CLOSE, NULL, 0);
1876 client_shutdown();
1879 static void
1880 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1882 struct fid *f;
1883 uint32_t fid;
1884 int r;
1885 char dirpath[PATH_MAX + 3];
1887 /* fid[4] */
1888 if (!NPREAD32("fid", &fid, &data, &len) ||
1889 len != 0) {
1890 client_send_listener(IMSG_CLOSE, NULL, 0);
1891 client_shutdown();
1892 return;
1895 if ((f = fid_by_id(fid)) == NULL) {
1896 np_error(hdr->tag, "invalid fid");
1897 return;
1900 if (f->qid.type & QTDIR) { /* directory */
1901 strlcpy(dirpath, "../", sizeof(dirpath));
1902 strlcat(dirpath, f->fname, sizeof(dirpath));
1903 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1904 } else /* file */
1905 r = unlinkat(f->dir->fd, f->fname, 0);
1907 if (r == -1)
1908 np_errno(hdr->tag);
1909 else
1910 np_remove(hdr->tag);
1912 free_fid(f);
1915 static void
1916 handle_message(struct imsg *imsg, size_t len, int cont)
1918 static struct fid *writefid;
1919 static off_t writepos;
1920 static size_t writetot;
1921 static size_t writeleft;
1922 static int writeskip;
1923 static uint16_t writetag;
1924 struct msg {
1925 uint8_t type;
1926 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1927 } msgs[] = {
1928 {Tversion, tversion},
1929 {Tattach, tattach},
1930 {Tclunk, tclunk},
1931 {Tflush, tflush},
1932 {Twalk, twalk},
1933 {Topen, topen},
1934 {Tcreate, tcreate},
1935 {Tread, tread},
1936 /* {Twrite, twrite}, */
1937 {Tstat, tstat},
1938 {Twstat, twstat},
1939 {Tremove, tremove},
1941 struct np_msg_header hdr;
1942 size_t i;
1943 uint8_t *data;
1945 #if DEBUG_PACKETS
1946 hexdump("incoming packet", imsg->data, len);
1947 #endif
1950 * Twrite is special and can be "continued" to allow writing
1951 * more than what the imsg framework would allow us to.
1953 if (cont) {
1954 if (writeskip)
1955 return;
1957 if (writefid == NULL) {
1958 log_warnx("received a continuation message without "
1959 "seeing a Twrite");
1960 client_send_listener(IMSG_CLOSE, NULL, 0);
1961 client_shutdown();
1962 return;
1965 twrite_cont(writefid, &writepos, &writetot, &writeleft,
1966 &writeskip, writetag, imsg->data, len);
1967 return;
1970 if (writeleft > 0) {
1971 log_warnx("received a non continuation message when still "
1972 "missed %zu bytes to write", writeleft);
1973 client_send_listener(IMSG_CLOSE, NULL, 0);
1974 client_shutdown();
1975 return;
1978 writefid = NULL;
1979 writepos = -1;
1980 writetot = 0;
1981 writeleft = 0;
1982 writeskip = 0;
1984 parse_message(imsg->data, len, &hdr, &data);
1985 len -= HEADERSIZE;
1987 log_debug("got request: len=%d type=%d[%s] tag=%d",
1988 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1990 if (!handshaked && hdr.type != Tversion) {
1991 client_send_listener(IMSG_CLOSE, NULL, 0);
1992 client_shutdown();
1993 return;
1996 if (hdr.type == Twrite) {
1997 writetag = hdr.tag;
1998 twrite(&hdr, data, len, &writefid, &writepos, &writetot,
1999 &writeleft, &writeskip);
2000 return;
2003 if (len > IMSG_MAXSIZE) {
2004 log_warnx("can't handle message: too long for its type");
2005 client_send_listener(IMSG_CLOSE, NULL, 0);
2006 client_shutdown();
2007 return;
2010 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
2011 if (msgs[i].type != hdr.type)
2012 continue;
2014 msgs[i].fn(&hdr, data, len);
2015 return;
2018 np_error(hdr.tag, "Not supported.");