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 <errno.h>
25 #include <fcntl.h>
26 #include <inttypes.h>
27 #include <libgen.h>
28 #include <pwd.h>
29 #include <signal.h>
30 #include <stdint.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <syslog.h>
35 #include <unistd.h>
37 #include "client.h"
38 #include "kami.h"
39 #include "kamid.h"
40 #include "log.h"
41 #include "sandbox.h"
42 #include "utils.h"
44 /*
45 * Max message size aviable via a single imsg.
46 */
47 #define IMSG_MAXSIZE (MAX_IMSGSIZE - IMSG_HEADER_SIZE)
49 /*
50 * The minimum value allowed for the msize.
51 */
52 #define MIN_MSIZE 256
54 #define DEBUG_PACKETS 0
56 /* straight outta /src/usr.bin/ssh/scp.c */
57 #define TYPE_OVERFLOW(type, val) \
58 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
59 (sizeof(type) == 8 && (val) > INT64_MAX) || \
60 (sizeof(type) != 4 && sizeof(type) != 8))
62 STAILQ_HEAD(dirhead, dir) dirs;
63 struct dir {
64 int refcount;
65 int fd;
66 STAILQ_ENTRY(dir) entries;
67 };
69 STAILQ_HEAD(fidhead, fid) fids;
70 struct fid {
71 uint32_t fid;
73 char fname[NAME_MAX];
75 /*
76 * the flags passed to open(2). O_CLOEXEC means ORCLOSE, that
77 * is to unlink the file upon Tclunk.
78 */
79 int iomode;
81 /*
82 * if fd is not -1 this fid was opened, fd represents its
83 * file descriptor and iomode the flags passed to open(2).
84 */
85 int fd;
86 DIR *d;
87 struct evbuffer *evb;
89 /*
90 * expected offset for Tread against a directory.
91 */
92 uint64_t offset;
94 struct qid qid;
95 struct dir *dir;
96 STAILQ_ENTRY(fid) entries;
97 };
99 static struct imsgev *iev_listener;
100 static struct evbuffer *evb;
101 static uint32_t peerid;
103 static int handshaked;
104 uint32_t msize;
106 static __dead void client_shutdown(void);
107 static void client_sig_handler(int, short, void *);
108 static void client_dispatch_listener(int, short, void *);
109 static void client_privdrop(const char *, const char *);
111 static int client_send_listenerp(int, uint32_t, const void *, uint16_t);
112 static int client_send_listener(int, const void *, uint16_t);
114 static void qid_update_from_sb(struct qid *, struct stat *);
116 static struct dir *new_dir(int);
117 static struct dir *dir_incref(struct dir *);
118 static void dir_decref(struct dir *);
120 static struct fid *new_fid(struct dir *, uint32_t, const char *, struct qid *);
121 static struct fid *fid_by_id(uint32_t);
122 static void free_fid(struct fid *);
124 static void parse_message(const uint8_t *, size_t,
125 struct np_msg_header *, uint8_t **);
127 static void np_write16(struct evbuffer *, uint16_t);
128 static void np_write32(struct evbuffer *, uint32_t);
129 static void np_write64(struct evbuffer *, uint64_t);
130 static void np_header(uint32_t, uint8_t, uint16_t);
131 static void np_string(struct evbuffer *, uint16_t, const char *);
132 static void np_qid(struct evbuffer *, struct qid *);
133 static void do_send(void);
135 static void np_version(uint16_t, uint32_t, const char *);
136 static void np_attach(uint16_t, struct qid *);
137 static void np_clunk(uint16_t);
138 static void np_flush(uint16_t);
139 static void np_walk(uint16_t, int, struct qid *);
140 static void np_open(uint16_t, struct qid *, uint32_t);
141 static void np_create(uint16_t, struct qid *, uint32_t);
142 static void np_read(uint16_t, uint32_t, void *);
143 static void np_write(uint16_t, uint32_t);
144 static void np_stat(uint16_t, uint16_t, void *);
145 static void np_wstat(uint16_t);
146 static void np_remove(uint16_t);
147 static void np_error(uint16_t, const char *);
148 static void np_errno(uint16_t);
150 static int np_read8(const char *, const char *, uint8_t *,
151 const uint8_t **, size_t *);
152 static int np_read16(const char *, const char *, uint16_t *,
153 const uint8_t **, size_t *);
154 static int np_read32(const char *, const char *, uint32_t *,
155 const uint8_t **, size_t *);
156 static int np_read64(const char *, const char *, uint64_t *,
157 const uint8_t **, size_t *);
159 #define READSTRERR -1
160 #define READSTRTRUNC -2
161 static int np_readstr(const char *, const char *, char *, size_t,
162 const uint8_t **, size_t *);
164 static int np_readst(const char *, const char *, struct np_stat *,
165 char *, size_t, const uint8_t **, size_t *);
167 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
168 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
169 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
170 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
172 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
174 #define NPREADST(f, dst, n, nl, src, len) np_readst(__func__, f, dst, n, nl, src, len)
176 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
177 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
178 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
179 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
180 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
181 static void topen(struct np_msg_header *, const uint8_t *, size_t);
182 static void tcreate(struct np_msg_header *, const uint8_t *, size_t);
183 static void tread(struct np_msg_header *, const uint8_t *, size_t);
184 static void twrite(struct np_msg_header *, const uint8_t *, size_t, struct fid **, off_t *, size_t *, size_t *, int *);
185 static void twrite_cont(struct fid *, off_t *, size_t *, size_t *, int *, uint16_t, const uint8_t *, size_t);
186 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
187 static void twstat(struct np_msg_header *, const uint8_t *, size_t);
188 static void tremove(struct np_msg_header *, const uint8_t *, size_t);
189 static void handle_message(struct imsg *, size_t, int);
191 __dead void
192 client(int debug, int verbose)
194 struct event ev_sigint, ev_sigterm;
196 log_init(debug, LOG_DAEMON);
197 log_setverbose(verbose);
199 setproctitle("client");
200 log_procinit("client");
202 log_debug("warming up");
204 event_init();
206 /* Setup signal handlers */
207 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
208 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
210 signal_add(&ev_sigint, NULL);
211 signal_add(&ev_sigterm, NULL);
213 signal(SIGPIPE, SIG_IGN);
214 signal(SIGHUP, SIG_IGN);
216 /* Setup pipe and event handler to the listener process */
217 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
218 fatal(NULL);
220 imsg_init(&iev_listener->ibuf, 3);
221 iev_listener->handler = client_dispatch_listener;
223 /* Setup event handlers. */
224 iev_listener->events = EV_READ;
225 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
226 iev_listener->events, iev_listener->handler, iev_listener);
227 event_add(&iev_listener->ev, NULL);
229 event_dispatch();
230 client_shutdown();
233 static __dead void
234 client_shutdown(void)
236 if (evb != NULL)
237 evbuffer_free(evb);
239 msgbuf_clear(&iev_listener->ibuf.w);
240 close(iev_listener->ibuf.fd);
242 free(iev_listener);
244 log_debug("client exiting");
245 exit(0);
248 static void
249 client_sig_handler(int sig, short event, void *d)
251 /*
252 * Normal signal handler rules don't apply because libevent
253 * decouples for us.
254 */
256 switch (sig) {
257 case SIGINT:
258 case SIGTERM:
259 client_shutdown();
260 default:
261 fatalx("unexpected signal %d", sig);
265 static void
266 client_dispatch_listener(int fd, short event, void *d)
268 static int auth = 0;
269 struct kd_auth_proc rauth;
270 struct kd_debug_info debug;
271 struct fid *f;
272 struct imsg imsg;
273 struct imsgev *iev = d;
274 struct imsgbuf *ibuf;
275 ssize_t n;
276 int shut = 0;
278 ibuf = &iev->ibuf;
280 if (event & EV_READ) {
281 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
282 fatal("imsg_read error");
283 if (n == 0) /* Connection closed */
284 shut = 1;
286 if (event & EV_WRITE) {
287 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
288 fatal("msgbuf_write");
289 if (n == 0) /* Connection closed */
290 shut = 1;
293 for (;;) {
294 if ((n = imsg_get(ibuf, &imsg)) == -1)
295 fatal("%s: imsg_get error", __func__);
296 if (n == 0) /* No more messages. */
297 break;
299 switch (imsg.hdr.type) {
300 case IMSG_CTL_LOG_VERBOSE:
301 if (IMSG_DATA_SIZE(imsg) != sizeof(verbose))
302 fatalx("%s: IMSG_CTL_LOG_VERBOSE wrong size",
303 __func__);
304 memcpy(&verbose, imsg.data, sizeof(verbose));
305 log_setverbose(verbose);
306 break;
307 case IMSG_CTL_DEBUG:
308 STAILQ_FOREACH(f, &fids, entries) {
309 memset(&debug, 0, sizeof(debug));
310 debug.fid = f->fid;
311 strlcpy(debug.path, f->fname,
312 sizeof(debug.path));
313 client_send_listenerp(IMSG_CTL_DEBUG_BACK,
314 imsg.hdr.peerid, &debug, sizeof(debug));
316 client_send_listenerp(IMSG_CTL_DEBUG_END,
317 imsg.hdr.peerid, NULL, 0);
318 break;
319 case IMSG_AUTH:
320 peerid = imsg.hdr.peerid;
321 if (auth)
322 fatalx("%s: IMSG_AUTH already done", __func__);
323 auth = 1;
325 if (IMSG_DATA_SIZE(imsg) != sizeof(rauth))
326 fatalx("mismatching size for IMSG_AUTH");
327 memcpy(&rauth, imsg.data, sizeof(rauth));
328 if (rauth.uname[sizeof(rauth.uname)-1] != '\0' ||
329 rauth.dir[sizeof(rauth.dir)-1] != '\0')
330 fatalx("IMSG_AUTH strings not NUL-terminated");
332 client_privdrop(rauth.uname, rauth.dir);
333 explicit_bzero(&rauth, sizeof(rauth));
334 break;
335 case IMSG_BUF:
336 case IMSG_BUF_CONT:
337 if (!auth)
338 fatalx("%s: can't handle messages before"
339 " doing the auth", __func__);
340 handle_message(&imsg, IMSG_DATA_SIZE(imsg),
341 imsg.hdr.type == IMSG_BUF_CONT);
342 break;
343 case IMSG_CONN_GONE:
344 log_debug("closing");
345 shut = 1;
346 break;
347 default:
348 log_debug("%s: unexpected imsg %d",
349 __func__, imsg.hdr.type);
350 break;
352 imsg_free(&imsg);
355 if (!shut)
356 imsg_event_add(iev);
357 else {
358 /* This pipe is dead. Remove its event handler. */
359 event_del(&iev->ev);
360 log_debug("pipe closed, shutting down...");
361 event_loopexit(NULL);
365 static void
366 client_privdrop(const char *username, const char *dir)
368 struct passwd *pw;
370 setproctitle("client %s", username);
372 if ((pw = getpwnam(username)) == NULL)
373 fatalx("getpwnam(%s) failed", username);
375 if (chroot(dir) == -1)
376 fatal("chroot");
377 if (chdir("/") == -1)
378 fatal("chdir(\"/\")");
380 if (setgroups(1, &pw->pw_gid) ||
381 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
382 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
383 fatal("can't drop privileges");
385 sandbox_client();
386 log_debug("client ready; user=%s dir=%s", username, dir);
388 if ((evb = evbuffer_new()) == NULL)
389 fatal("evbuffer_new");
392 static int
393 client_send_listenerp(int type, uint32_t peerid, const void *data, uint16_t len)
395 int ret;
397 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
398 data, len)) != -1)
399 imsg_event_add(iev_listener);
401 return ret;
404 static int
405 client_send_listener(int type, const void *data, uint16_t len)
407 return client_send_listenerp(type, peerid, data, len);
410 /* set qid fields from sb */
411 static void
412 qid_update_from_sb(struct qid *qid, struct stat *sb)
414 qid->path = sb->st_ino;
416 /*
417 * Theoretically (and hopefully!) this should be a 64 bit
418 * number. Unfortunately, 9P uses 32 bit timestamps.
419 */
420 qid->vers = sb->st_mtim.tv_sec;
422 if (S_ISREG(sb->st_mode))
423 qid->type = QTFILE;
424 else if (S_ISDIR(sb->st_mode))
425 qid->type = QTDIR;
426 else if (S_ISLNK(sb->st_mode))
427 qid->type = QTSYMLINK;
430 /* creates a qid given a fd */
431 static struct dir *
432 new_dir(int fd)
434 struct dir *dir;
436 if ((dir = calloc(1, sizeof(*dir))) == NULL)
437 return NULL;
439 dir->fd = fd;
440 STAILQ_INSERT_HEAD(&dirs, dir, entries);
441 return dir;
444 static struct dir *
445 dir_incref(struct dir *dir)
447 dir->refcount++;
448 return dir;
451 static void
452 dir_decref(struct dir *dir)
454 if (--dir->refcount > 0)
455 return;
457 STAILQ_REMOVE(&dirs, dir, dir, entries);
459 close(dir->fd);
460 free(dir);
463 static struct fid *
464 new_fid(struct dir *dir, uint32_t fid, const char *path, struct qid *qid)
466 struct fid *f;
467 struct qid q;
468 struct stat sb;
470 if (qid == NULL) {
471 if (fstatat(dir->fd, path, &sb, 0)) {
472 log_warn("fstatat(%s)", path);
473 return NULL;
475 qid_update_from_sb(&q, &sb);
476 qid = &q;
479 if ((f = calloc(1, sizeof(*f))) == NULL)
480 return NULL;
482 f->dir = dir_incref(dir);
483 f->fid = fid;
484 f->fd = -1;
486 strlcpy(f->fname, path, sizeof(f->fname));
488 memcpy(&f->qid, qid, sizeof(f->qid));
490 STAILQ_INSERT_HEAD(&fids, f, entries);
492 return f;
495 static struct fid *
496 fid_by_id(uint32_t fid)
498 struct fid *f;
500 STAILQ_FOREACH(f, &fids, entries) {
501 if (f->fid == fid)
502 return f;
505 return NULL;
508 static void
509 free_fid(struct fid *f)
511 int r;
513 if (f->fd != -1) {
514 if (f->d != NULL)
515 r = closedir(f->d);
516 else
517 r = close(f->fd);
519 if (r == -1)
520 fatal("can't close fid %d", f->fid);
522 if (f->evb != NULL)
523 evbuffer_free(f->evb);
525 /* try to honour ORCLOSE if requested */
526 if (f->iomode & O_CLOEXEC)
527 unlinkat(f->dir->fd, f->fname, 0);
530 dir_decref(f->dir);
532 STAILQ_REMOVE(&fids, f, fid, entries);
533 free(f);
536 static void
537 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
538 uint8_t **cnt)
540 size_t olen = len;
542 if (!NPREAD32("len", &hdr->len, &data, &len) ||
543 !NPREAD8("type", &hdr->type, &data, &len) ||
544 !NPREAD16("tag", &hdr->tag, &data, &len))
545 goto err;
547 /*
548 * Allow only "jumbo" Twrites.
549 */
550 if (hdr->type != Twrite && olen != hdr->len)
551 goto err;
553 if (hdr->type < Tversion ||
554 hdr->type >= Tmax ||
555 hdr->type == Terror ||
556 (hdr->type & 0x1) != 0) /* cannot recv a R* */
557 goto err;
559 hdr->tag = le32toh(hdr->tag);
561 *cnt = (uint8_t *)data;
562 return;
564 err:
565 log_warnx("got invalid message: (%d, %d, %d)",
566 hdr->len, hdr->type, hdr->tag);
567 client_send_listener(IMSG_CLOSE, NULL, 0);
568 client_shutdown();
571 static void
572 np_write16(struct evbuffer *e, uint16_t x)
574 x = htole16(x);
575 evbuffer_add(e, &x, sizeof(x));
578 static void
579 np_write32(struct evbuffer *e, uint32_t x)
581 x = htole32(x);
582 evbuffer_add(e, &x, sizeof(x));
585 static void
586 np_write64(struct evbuffer *e, uint64_t x)
588 x = htole64(x);
589 evbuffer_add(e, &x, sizeof(x));
592 static void
593 np_writebuf(struct evbuffer *e, size_t len, void *data)
595 evbuffer_add(e, data, len);
598 static void
599 np_header(uint32_t len, uint8_t type, uint16_t tag)
601 len += HEADERSIZE;
603 len = htole32(len);
604 tag = htole16(tag);
606 evbuffer_add(evb, &len, sizeof(len));
607 evbuffer_add(evb, &type, sizeof(type));
608 evbuffer_add(evb, &tag, sizeof(tag));
611 static void
612 np_string(struct evbuffer *e, uint16_t len, const char *str)
614 uint16_t l = len;
616 len = htole16(len);
617 evbuffer_add(e, &len, sizeof(len));
618 evbuffer_add(e, str, l);
621 static void
622 np_qid(struct evbuffer *e, struct qid *qid)
624 uint64_t path;
625 uint32_t vers;
627 path = htole64(qid->path);
628 vers = htole32(qid->vers);
630 evbuffer_add(e, &qid->type, sizeof(qid->type));
631 evbuffer_add(e, &vers, sizeof(vers));
632 evbuffer_add(e, &path, sizeof(path));
635 static void
636 do_send(void)
638 size_t len;
639 uint8_t *data;
641 len = EVBUFFER_LENGTH(evb);
642 data = EVBUFFER_DATA(evb);
644 #if DEBUG_PACKETS
645 hexdump("outgoing packet", data, len);
646 #endif
648 while (len > IMSG_MAXSIZE) {
649 client_send_listener(IMSG_BUF, data, IMSG_MAXSIZE);
650 evbuffer_drain(evb, IMSG_MAXSIZE);
651 len -= IMSG_MAXSIZE;
652 data += IMSG_MAXSIZE;
655 if (len != 0) {
656 client_send_listener(IMSG_BUF, data, len);
657 evbuffer_drain(evb, len);
661 static void
662 np_version(uint16_t tag, uint32_t msize, const char *version)
664 uint16_t l;
666 l = strlen(version);
668 msize = htole32(msize);
670 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
671 evbuffer_add(evb, &msize, sizeof(msize));
672 np_string(evb, l, version);
673 do_send();
676 static void
677 np_attach(uint16_t tag, struct qid *qid)
679 np_header(QIDSIZE, Rattach, tag);
680 np_qid(evb, qid);
681 do_send();
684 static void
685 np_clunk(uint16_t tag)
687 np_header(0, Rclunk, tag);
688 do_send();
691 static void
692 np_flush(uint16_t tag)
694 np_header(0, Rflush, tag);
695 do_send();
698 static void
699 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
701 int i;
703 /* two bytes for the counter */
704 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
705 np_write16(evb, nwqid);
706 for (i = 0; i < nwqid; ++i)
707 np_qid(evb, wqid + i);
709 do_send();
712 static void
713 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
715 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
716 np_qid(evb, qid);
717 np_write32(evb, iounit);
718 do_send();
721 static void
722 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
724 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
725 np_qid(evb, qid);
726 np_write32(evb, iounit);
727 do_send();
730 static void
731 np_read(uint16_t tag, uint32_t count, void *data)
733 if (sizeof(count) + count + HEADERSIZE > msize) {
734 np_error(tag, "Rread would overflow");
735 return;
738 np_header(sizeof(count) + count, Rread, tag);
739 np_write32(evb, count);
740 np_writebuf(evb, count, data);
741 do_send();
744 static void
745 np_write(uint16_t tag, uint32_t count)
747 np_header(sizeof(count), Rwrite, tag);
748 np_write32(evb, count);
749 do_send();
752 static void
753 np_stat(uint16_t tag, uint16_t count, void *data)
755 if (sizeof(count) + count + HEADERSIZE >= msize) {
756 np_error(tag, "Rstat would overflow");
757 return;
760 np_header(sizeof(count) + count, Rstat, tag);
761 np_write16(evb, count);
762 np_writebuf(evb, count, data);
763 do_send();
766 static void
767 np_wstat(uint16_t tag)
769 np_header(0, Rwstat, tag);
770 do_send();
773 static void
774 np_remove(uint16_t tag)
776 np_header(0, Rremove, tag);
777 do_send();
780 static void
781 np_error(uint16_t tag, const char *errstr)
783 uint16_t l;
785 l = strlen(errstr);
787 np_header(sizeof(l) + l, Rerror, tag);
788 np_string(evb, l, errstr);
789 do_send();
792 static void
793 np_errno(uint16_t tag)
795 int saved_errno;
796 char buf[NL_TEXTMAX] = {0};
798 saved_errno = errno;
800 strerror_r(errno, buf, sizeof(buf));
801 np_error(tag, buf);
803 errno = saved_errno;
806 static int
807 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
808 size_t *len)
810 if (*len < sizeof(*dst)) {
811 log_warnx("%s: wanted %zu bytes for the %s field but only "
812 "%zu are available.", t, sizeof(*dst), f, *len);
813 return 0;
816 memcpy(dst, *src, sizeof(*dst));
817 *src += sizeof(*dst);
818 *len -= sizeof(*dst);
820 return 1;
823 static int
824 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
825 size_t *len)
827 if (*len < sizeof(*dst)) {
828 log_warnx("%s: wanted %zu bytes for the %s field but only "
829 "%zu are available.", t, sizeof(*dst), f, *len);
830 return 0;
833 memcpy(dst, *src, sizeof(*dst));
834 *src += sizeof(*dst);
835 *len -= sizeof(*dst);
836 *dst = le16toh(*dst);
838 return 1;
841 static int
842 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
843 size_t *len)
845 if (*len < sizeof(*dst)) {
846 log_warnx("%s: wanted %zu bytes for the %s field but only "
847 "%zu are available.", t, sizeof(*dst), f, *len);
848 return 0;
851 memcpy(dst, *src, sizeof(*dst));
852 *src += sizeof(*dst);
853 *len -= sizeof(*dst);
854 *dst = le32toh(*dst);
856 return 1;
859 static int
860 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
861 size_t *len)
863 if (*len < sizeof(*dst)) {
864 log_warnx("%s: wanted %zu bytes for the %s field but only "
865 "%zu are available.", t, sizeof(*dst), f, *len);
866 return 0;
869 memcpy(dst, *src, sizeof(*dst));
870 *src += sizeof(*dst);
871 *len -= sizeof(*dst);
872 *dst = le64toh(*dst);
874 return 1;
877 static int
878 np_readstr(const char *t, const char *f, char *res, size_t reslen,
879 const uint8_t **src, size_t *len)
881 uint16_t sl;
882 char buf[32];
884 strlcpy(buf, f, sizeof(buf));
885 strlcat(buf, "-len", sizeof(buf));
887 if (!np_read16(t, buf, &sl, src, len))
888 return READSTRERR;
890 if (*len < sl) {
891 log_warnx("%s: wanted %d bytes for the %s field but only "
892 "%zu are available.", t, sl, f, *len);
893 return READSTRERR;
896 if (*len > reslen-1)
897 return READSTRTRUNC;
899 memcpy(res, *src, sl);
900 res[sl] = '\0';
901 *src += sl;
902 *len -= sl;
904 return 0;
907 static int
908 np_readst(const char *t, const char *f, struct np_stat *st,
909 char *name, size_t namelen, const uint8_t **src, size_t *len)
911 memset(st, 0, sizeof(*st));
913 /* len is sent twice! */
914 if (!np_read16(t, "stat len", &st->size, src, len) ||
915 !np_read16(t, "stat.size", &st->size, src, len) ||
916 !np_read16(t, "stat.type", &st->type, src, len) ||
917 !np_read32(t, "stat.dev", &st->dev, src, len) ||
918 !np_read64(t, "stat.qid.path", &st->qid.path, src, len) ||
919 !np_read32(t, "stat.qid.vers", &st->qid.vers, src, len) ||
920 !np_read8(t, "stat.qid.type", &st->qid.type, src, len) ||
921 !np_read32(t, "stat.mode", &st->mode, src, len) ||
922 !np_read32(t, "stat.atime", &st->atime, src, len) ||
923 !np_read32(t, "stat.mtime", &st->mtime, src, len) ||
924 !np_read64(t, "stat.length", &st->length, src, len))
925 return READSTRERR;
927 /*
928 * ignore everything but the name, we don't support
929 * changing those fields anyway
930 */
931 st->name = name;
932 return np_readstr(t, "stat.name", name, namelen, src, len);
935 static void
936 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
938 char *dot, version[32];
940 if (handshaked)
941 goto err;
943 /* msize[4] version[s] */
944 if (!NPREAD32("msize", &msize, &data, &len))
945 goto err;
947 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
948 case READSTRERR:
949 goto err;
950 case READSTRTRUNC:
951 log_warnx("9P version string too long, truncated");
952 np_version(hdr->tag, MSIZE9P, "unknown");
953 return;
956 if (len != 0)
957 goto err;
959 if ((dot = strchr(version, '.')) != NULL)
960 *dot = '\0';
962 if (strcmp(version, VERSION9P) != 0) {
963 log_warnx("unknown 9P version \"%s\"; want "VERSION9P,
964 version);
965 np_version(hdr->tag, MSIZE9P, "unknown");
966 return;
969 if (msize < MIN_MSIZE) {
970 log_warnx("msize too small: %"PRIu32"; want %d at least",
971 msize, MIN_MSIZE);
972 np_version(hdr->tag, MSIZE9P, "unknown");
973 return;
976 /* version matched */
977 handshaked = 1;
978 msize = MIN(msize, MSIZE9P);
979 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
980 np_version(hdr->tag, msize, VERSION9P);
981 return;
983 err:
984 client_send_listener(IMSG_CLOSE, NULL, 0);
985 client_shutdown();
988 static void
989 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
991 struct dir *dir;
992 struct fid *f;
993 uint32_t fid, afid;
994 int fd;
995 char aname[PATH_MAX];
997 /* fid[4] afid[4] uname[s] aname[s] */
999 if (!NPREAD32("fid", &fid, &data, &len) ||
1000 !NPREAD32("afid", &afid, &data, &len))
1001 goto err;
1003 /* read the uname but don't actually use it */
1004 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
1005 case READSTRERR:
1006 goto err;
1007 case READSTRTRUNC:
1008 np_error(hdr->tag, "name too long");
1009 return;
1012 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
1013 case READSTRERR:
1014 goto err;
1015 case READSTRTRUNC:
1016 np_error(hdr->tag, "name too long");
1017 return;
1020 if (*aname == '\0')
1021 strlcpy(aname, "/", sizeof(aname));
1023 if (len != 0)
1024 goto err;
1026 if (fid_by_id(fid) != NULL || afid != NOFID) {
1027 np_error(hdr->tag, "invalid fid or afid");
1028 return;
1031 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
1032 goto fail;
1034 if ((dir = new_dir(fd)) == NULL)
1035 goto fail;
1037 log_debug("attached %s to %d", aname, fid);
1039 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
1040 dir_decref(dir);
1041 goto fail;
1044 np_attach(hdr->tag, &f->qid);
1045 return;
1047 fail:
1048 np_errno(hdr->tag);
1049 log_warn("failed to attach %s", aname);
1050 return;
1052 err:
1053 client_send_listener(IMSG_CLOSE, NULL, 0);
1054 client_shutdown();
1057 static void
1058 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1060 struct fid *f;
1061 uint32_t fid;
1063 /* fid[4] */
1064 if (!NPREAD32("fid", &fid, &data, &len) ||
1065 len != 0) {
1066 client_send_listener(IMSG_CLOSE, NULL, 0);
1067 client_shutdown();
1068 return;
1071 if ((f = fid_by_id(fid)) == NULL) {
1072 np_error(hdr->tag, "invalid fid");
1073 return;
1076 free_fid(f);
1077 np_clunk(hdr->tag);
1080 static void
1081 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1083 uint16_t oldtag;
1086 * We're doing only synchronous I/O. Tflush is implemented
1087 * only because it's illegal to reply with a Rerror.
1090 /* oldtag[2] */
1091 if (len != sizeof(oldtag)) {
1092 log_warnx("Tflush with the wrong size: got %zu want %zu",
1093 len, sizeof(oldtag));
1094 client_send_listener(IMSG_CLOSE, NULL, 0);
1095 client_shutdown();
1096 return;
1099 np_flush(hdr->tag);
1102 static void
1103 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1105 struct stat sb;
1106 struct dir *dir;
1107 struct qid wqid[MAXWELEM] = {0};
1108 struct fid *f, *nf;
1109 uint32_t fid, newfid;
1110 uint16_t nwname;
1111 int fd, oldfd, no, nwqid = 0;
1112 char wnam[PATH_MAX];
1114 if (!NPREAD32("fid", &fid, &data, &len) ||
1115 !NPREAD32("newfid", &newfid, &data, &len) ||
1116 !NPREAD16("nwname", &nwname, &data, &len))
1117 goto err;
1119 if (nwname > MAXWELEM) {
1120 log_warnx("Twalk: more than %d path elements: %d",
1121 MAXWELEM, nwname);
1122 goto err;
1125 if ((f = fid_by_id(fid)) == NULL) {
1126 np_error(hdr->tag, "invalid fid");
1127 return;
1130 if (f->fd != -1) {
1131 np_error(hdr->tag, "fid already opened for I/O");
1132 return;
1135 if (fid == newfid)
1136 nf = f;
1137 else if ((nf = fid_by_id(newfid)) != NULL) {
1138 np_error(hdr->tag, "newfid already in use");
1139 return;
1140 } else
1141 nf = NULL;
1143 /* special case: fid duplication */
1144 if (nwname == 0) {
1146 * TODO: should we forbid fids duplication when fid ==
1147 * newfid?
1149 if (nf == NULL &&
1150 (nf = new_fid(f->dir, newfid, f->fname, &f->qid)) == NULL)
1151 fatal("new_fid duplication");
1153 np_walk(hdr->tag, 0, NULL);
1154 return;
1157 if (!(f->qid.type & QTDIR)) {
1158 np_error(hdr->tag, "fid doesn't represent a directory");
1159 return;
1162 oldfd = f->dir->fd;
1164 for (nwqid = 0; nwqid < nwname; nwqid++) {
1165 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1166 case READSTRERR:
1167 goto err;
1168 case READSTRTRUNC:
1169 np_error(hdr->tag, "wname too long");
1170 return;
1173 if (*wnam == '\0' ||
1174 strchr(wnam, '/') != NULL ||
1175 !strcmp(wnam, ".")) {
1176 errno = EINVAL;
1177 goto cantopen;
1180 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1181 errno != ENOTDIR)
1182 goto cantopen;
1184 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1185 (fd != -1 && fstat(fd, &sb) == -1))
1186 goto cantopen;
1188 qid_update_from_sb(&wqid[nwqid], &sb);
1190 /* reached a file but we still have other components */
1191 if (fd == -1 && nwqid+1 < nwname)
1192 goto cantopen;
1194 /* reached the end and found a file */
1195 if (fd == -1 && nwqid+1 == nwname)
1196 continue;
1198 if (oldfd != f->dir->fd)
1199 close(oldfd);
1200 oldfd = fd;
1203 if (len != 0)
1204 goto err;
1207 * If fd is -1 we've reached a file, otherwise we've just
1208 * reached another directory. We must pay attention to what
1209 * file descriptor we use to create the dir, because if we've
1210 * reached a file and oldfd is f->dir->fd then we *must* share
1211 * the same dir (it was a walk of one path from a directory to a
1212 * file, otherwise fun is bound to happen as soon as the client
1213 * closes the fid for the directory but keeps the one for the
1214 * file.
1216 if (fd == -1 && oldfd == f->dir->fd)
1217 dir = f->dir;
1218 else if (fd == -1)
1219 dir = new_dir(oldfd);
1220 else
1221 dir = new_dir(fd);
1223 if (dir == NULL)
1224 fatal("new_dir");
1226 if (nf == NULL) {
1227 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1228 fatal("new fid");
1229 } else {
1230 /* update the dir */
1231 dir_decref(nf->dir);
1232 nf->dir = dir_incref(dir);
1235 np_walk(hdr->tag, nwqid, wqid);
1236 return;
1238 cantopen:
1239 if (oldfd != f->dir->fd)
1240 close(oldfd);
1241 no = errno;
1242 if (nwqid == 0)
1243 np_error(hdr->tag, strerror(no));
1244 else
1245 np_walk(hdr->tag, nwqid, wqid);
1246 return;
1248 err:
1249 client_send_listener(IMSG_CLOSE, NULL, 0);
1250 client_shutdown();
1253 static inline int
1254 npmode_to_unix(uint8_t mode, int *flags)
1256 switch (mode & 0x0F) {
1257 case KOREAD:
1258 *flags = O_RDONLY;
1259 break;
1260 case KOWRITE:
1261 *flags = O_WRONLY;
1262 break;
1263 case KORDWR:
1264 *flags = O_RDWR;
1265 break;
1266 case KOEXEC:
1267 log_warnx("tried to open something with KOEXEC");
1268 /* fallthrough */
1269 default:
1270 return -1;
1273 if (mode & KOTRUNC)
1274 *flags |= O_TRUNC;
1275 if (mode & KORCLOSE)
1276 *flags |= O_CLOEXEC;
1278 return 0;
1281 static void
1282 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1284 struct stat sb;
1285 struct qid qid;
1286 struct fid *f;
1287 uint32_t fid;
1288 uint8_t mode;
1289 const char *path;
1291 /* fid[4] mode[1] */
1292 if (!NPREAD32("fid", &fid, &data, &len) ||
1293 !NPREAD8("mode", &mode, &data, &len) ||
1294 len != 0) {
1295 client_send_listener(IMSG_CLOSE, NULL, 0);
1296 client_shutdown();
1297 return;
1300 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1301 np_error(hdr->tag, "invalid fid");
1302 return;
1305 if (npmode_to_unix(mode, &f->iomode) == -1) {
1306 np_error(hdr->tag, "invalid mode");
1307 return;
1310 path = f->fname;
1311 if (f->qid.type & QTDIR)
1312 path = ".";
1314 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1315 np_error(hdr->tag, strerror(errno));
1316 return;
1319 if (fstat(f->fd, &sb) == -1)
1320 fatal("fstat");
1322 if (S_ISDIR(sb.st_mode)) {
1323 if ((f->d = fdopendir(f->fd)) == NULL) {
1324 np_errno(hdr->tag);
1325 close(f->fd);
1326 f->fd = -1;
1327 return;
1330 if ((f->evb = evbuffer_new()) == NULL) {
1331 np_errno(hdr->tag);
1332 closedir(f->d);
1333 f->d = NULL;
1334 f->fd = -1;
1338 f->offset = 0;
1340 qid_update_from_sb(&qid, &sb);
1341 np_open(hdr->tag, &qid, sb.st_blksize);
1344 static void
1345 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1347 struct stat sb;
1348 struct qid qid;
1349 struct fid *f;
1350 uint32_t fid, perm;
1351 uint8_t mode;
1352 char name[PATH_MAX];
1354 /* fid[4] name[s] perm[4] mode[1] */
1355 if (!NPREAD32("fid", &fid, &data, &len))
1356 goto err;
1357 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1358 case READSTRERR:
1359 goto err;
1360 case READSTRTRUNC:
1361 np_error(hdr->tag, "name too long");
1362 return;
1364 if (!NPREAD32("perm", &perm, &data, &len) ||
1365 !NPREAD8("mode", &mode, &data, &len) ||
1366 len != 0)
1367 goto err;
1369 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1370 strchr(name, '/') != NULL) {
1371 np_error(hdr->tag, "invalid name");
1372 return;
1375 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1376 np_error(hdr->tag, "invalid fid");
1377 return;
1380 if (!(f->qid.type & QTDIR)) {
1381 np_error(hdr->tag, "fid doesn't identify a directory");
1382 return;
1385 if (npmode_to_unix(mode, &f->iomode) == -1) {
1386 np_error(hdr->tag, "invalid mode");
1387 return;
1390 if (f->iomode & O_RDONLY) {
1391 np_error(hdr->tag, "can't create a read-only file");
1392 return;
1395 /* TODO: parse the mode */
1397 if (perm & 0x80000000) {
1398 /* create a directory */
1399 f->fd = mkdirat(f->dir->fd, name, 0755);
1400 } else {
1401 /* create a file */
1402 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1403 0644);
1406 if (f->fd == -1) {
1407 np_errno(hdr->tag);
1408 return;
1411 if (fstat(f->fd, &sb) == -1)
1412 fatal("fstat");
1414 if (S_ISDIR(sb.st_mode)) {
1415 if ((f->d = fdopendir(f->fd)) == NULL) {
1416 np_errno(hdr->tag);
1417 close(f->fd);
1418 f->fd = -1;
1419 return;
1422 if ((f->evb = evbuffer_new()) == NULL) {
1423 np_errno(hdr->tag);
1424 closedir(f->d);
1425 f->d = NULL;
1426 f->fd = -1;
1430 f->offset = 0;
1432 qid_update_from_sb(&qid, &sb);
1433 np_create(hdr->tag, &qid, sb.st_blksize);
1435 return;
1437 err:
1438 client_send_listener(IMSG_CLOSE, NULL, 0);
1439 client_shutdown();
1442 static inline int
1443 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1445 struct qid qid;
1446 const char *uid, *gid, *muid;
1447 size_t tot;
1448 uint32_t mode;
1449 uint16_t namlen, uidlen, gidlen, ulen;
1451 qid_update_from_sb(&qid, sb);
1453 /* TODO: fill these fields */
1454 uid = "";
1455 gid = "";
1456 muid = "";
1458 namlen = strlen(fname);
1459 uidlen = strlen(uid);
1460 gidlen = strlen(gid);
1461 ulen = strlen(muid);
1463 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1464 if (tot > UINT16_MAX) {
1465 log_warnx("stat info for dir entry %s would overflow",
1466 fname);
1467 return -1;
1470 mode = sb->st_mode & 0xFFFF;
1471 if (qid.type & QTDIR)
1472 mode |= 0x80000000;
1474 np_write16(evb, tot); /* size[2] */
1475 np_write16(evb, sb->st_rdev); /* type[2] */
1476 np_write32(evb, sb->st_dev); /* dev[4] */
1477 np_qid(evb, &qid); /* qid[13] */
1478 np_write32(evb, mode); /* mode[4] */
1479 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1480 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1482 /* special case: directories have size 0 */
1483 if (qid.type & QTDIR)
1484 np_write64(evb, 0);
1485 else
1486 np_write64(evb, sb->st_size); /* length[8] */
1488 np_string(evb, namlen, fname); /* name[s] */
1489 np_string(evb, uidlen, uid); /* uid[s] */
1490 np_string(evb, gidlen, gid); /* gid[s] */
1491 np_string(evb, ulen, muid); /* muid[s] */
1493 return 0;
1496 static void
1497 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1499 static char buf[MSIZE9P - HEADERSIZE - 4];
1500 struct fid *f;
1501 ssize_t r;
1502 size_t howmuch;
1503 uint64_t off;
1504 uint32_t fid, count;
1506 /* fid[4] offset[8] count[4] */
1507 if (!NPREAD32("fid", &fid, &data, &len) ||
1508 !NPREAD64("offset", &off, &data, &len) ||
1509 !NPREAD32("count", &count, &data, &len) ||
1510 len != 0) {
1511 client_send_listener(IMSG_CLOSE, NULL, 0);
1512 client_shutdown();
1513 return;
1516 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1517 np_error(hdr->tag, "invalid fid");
1518 return;
1521 if (TYPE_OVERFLOW(off_t, off)) {
1522 log_warnx("unexpected off_t size");
1523 np_error(hdr->tag, "invalid offset");
1524 return;
1527 if (f->d == NULL) {
1528 /* read a file */
1529 howmuch = MIN(sizeof(buf), count);
1530 r = pread(f->fd, buf, howmuch, (off_t)off);
1531 if (r == -1)
1532 np_errno(hdr->tag);
1533 else
1534 np_read(hdr->tag, r, buf);
1535 } else {
1536 if (off == 0 && f->offset != 0) {
1537 rewinddir(f->d);
1538 f->offset = 0;
1539 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1542 if (off != f->offset) {
1543 np_error(hdr->tag, "can't seek in directories");
1544 return;
1547 while (EVBUFFER_LENGTH(f->evb) < count) {
1548 struct dirent *d;
1549 struct stat sb;
1551 if ((d = readdir(f->d)) == NULL)
1552 break;
1553 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1554 continue;
1555 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1556 warn("fstatat");
1557 continue;
1559 serialize_stat(d->d_name, &sb, f->evb);
1562 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1563 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1564 evbuffer_drain(f->evb, count);
1566 f->offset += count;
1570 static void
1571 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len,
1572 struct fid **writefid, off_t *writepos, size_t *writetot,
1573 size_t *writeleft, int *writeskip)
1575 struct fid *f;
1576 ssize_t r;
1577 uint64_t off;
1578 uint32_t fid, count;
1580 /* fid[4] offset[8] count[4] data[count] */
1581 if (!NPREAD32("fid", &fid, &data, &len) ||
1582 !NPREAD64("off", &off, &data, &len) ||
1583 !NPREAD32("count", &count, &data, &len) ||
1584 count < len) {
1585 client_send_listener(IMSG_CLOSE, NULL, 0);
1586 client_shutdown();
1587 return;
1590 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1591 *writeskip = 1;
1592 np_error(hdr->tag, "invalid fid");
1593 return;
1596 if (!(f->iomode & O_WRONLY) &&
1597 !(f->iomode & O_RDWR)) {
1598 *writeskip = 1;
1599 np_error(hdr->tag, "fid not opened for writing");
1600 return;
1603 if (TYPE_OVERFLOW(off_t, off)) {
1604 *writeskip = 1;
1605 log_warnx("unexpected off_t size");
1606 np_error(hdr->tag, "invalid offset");
1607 return;
1610 if ((r = pwrite(f->fd, data, len, off)) == -1) {
1611 *writeskip = 1;
1612 np_errno(hdr->tag);
1613 } else if (count == len)
1614 np_write(hdr->tag, r);
1616 /* account for a continuated write */
1617 if (count > len) {
1618 *writefid = f;
1619 *writepos = off + len;
1620 *writetot = len;
1621 *writeleft = count - len;
1622 *writeskip = 0;
1626 static void
1627 twrite_cont(struct fid *f, off_t *writepos, size_t *writetot,
1628 size_t *writeleft, int *writeskip, uint16_t tag, const uint8_t *data,
1629 size_t len)
1631 ssize_t r;
1633 if (len > *writeleft) {
1634 client_send_listener(IMSG_CLOSE, NULL, 0);
1635 client_shutdown();
1636 return;
1639 if ((r = pwrite(f->fd, data, len, *writepos)) == -1) {
1640 *writeskip = 1;
1641 np_errno(tag);
1642 return;
1645 *writetot += len;
1646 *writeleft -= len;
1647 *writepos += len;
1649 if (*writeleft == 0)
1650 np_write(tag, *writetot);
1653 static void
1654 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1656 struct evbuffer *evb;
1657 struct stat sb;
1658 struct fid *f;
1659 int r;
1660 uint32_t fid;
1662 /* fid[4] */
1663 if (!NPREAD32("fid", &fid, &data, &len) ||
1664 len != 0) {
1665 client_send_listener(IMSG_CLOSE, NULL, 0);
1666 client_shutdown();
1667 return;
1671 * plan9' stat(9P) is not clear on whether the stat is allowed
1672 * on opened fids or not. We're allowing stat regardless of the
1673 * status of the fid.
1676 if ((f = fid_by_id(fid)) == NULL) {
1677 np_error(hdr->tag, "invalid fid");
1678 return;
1681 if ((evb = evbuffer_new()) == NULL)
1682 fatal("evbuffer_new");
1684 if (f->fd != -1)
1685 r = fstat(f->fd, &sb);
1686 else if (f->qid.type & QTDIR)
1687 r = fstat(f->dir->fd, &sb);
1688 else
1689 r = fstatat(f->dir->fd, f->fname, &sb, 0);
1691 if (r == -1) {
1692 np_errno(hdr->tag);
1693 evbuffer_free(evb);
1694 return;
1697 if (serialize_stat(f->fname, &sb, evb) == -1)
1698 np_error(hdr->tag, "stat would overflow");
1699 else
1700 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1701 evbuffer_free(evb);
1704 static void
1705 twstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1707 struct timespec times[2];
1708 struct np_stat st;
1709 struct fid *f;
1710 int r;
1711 uint32_t fid;
1712 char name[PATH_MAX];
1714 /* fid[4] stat[n] */
1715 if (!NPREAD32("fid", &fid, &data, &len))
1716 goto err;
1718 switch (NPREADST("stat", &st, name, sizeof(name), &data, &len)) {
1719 case READSTRERR:
1720 goto err;
1721 case READSTRTRUNC:
1722 log_warnx("wstat new name would overflow");
1723 np_error(hdr->tag, "new name too long");
1724 return;
1728 * We skip the reading of some fields voluntarily because we
1729 * don't support chown, so len will always be > 0!
1731 #ifdef notyet
1732 if (len != 0)
1733 goto err;
1734 #endif
1736 if ((f = fid_by_id(fid)) == NULL) {
1737 np_error(hdr->tag, "invalid fid");
1738 return;
1742 * 9P wants these edits to be done in an atomic fashion,
1743 * something that I don't think it's possible on UNIX without
1744 * some special kernel help. Changing atime or mtime,
1745 * permissions, or rename the file are different syscalls.
1747 * Also, silently ignore stuff we can't/don't want to modify.
1750 /* change the permissions */
1751 if (st.mode != (uint32_t)-1) {
1752 mode_t m = st.mode & 0x7FF; /* silently truncate higer bits */
1753 if (f->fd != -1)
1754 r = fchmod(f->fd, m);
1755 else
1756 r = fchmodat(f->dir->fd, f->fname, m, 0);
1758 if (r == -1) {
1759 np_errno(hdr->tag);
1760 return;
1764 /* change the atime/mtime of the fid, opened or not */
1765 if (st.atime != (uint32_t)-1 || st.mtime != (uint32_t)-1) {
1766 times[0].tv_nsec = UTIME_OMIT;
1767 times[1].tv_nsec = UTIME_OMIT;
1769 if (st.atime != (uint32_t)-1) {
1770 times[0].tv_sec = st.atime;
1771 times[0].tv_nsec = 0;
1773 if (st.mtime != (uint32_t)-1) {
1774 times[1].tv_sec = st.mtime;
1775 times[1].tv_nsec = 0;
1778 if (f->fd != -1)
1779 r = futimens(f->fd, times);
1780 else
1781 r = utimensat(f->dir->fd, f->fname, times, 0);
1783 if (r == -1) {
1784 np_errno(hdr->tag);
1785 return;
1789 /* truncate */
1790 if (st.length != (uint64_t)-1) {
1791 if (f->fd == -1) {
1792 np_error(hdr->tag, "can't truncate a non-opened fid");
1793 return;
1796 if (f->qid.type & QTDIR && st.length != 0) {
1797 np_error(hdr->tag, "can't truncate directories");
1798 return;
1801 if (TYPE_OVERFLOW(off_t, st.length)) {
1802 log_warnx("truncate request overflows off_t: %"PRIu64,
1803 st.length);
1804 np_error(hdr->tag, "length overflows");
1805 return;
1808 if (f->qid.type == 0 &&
1809 ftruncate(f->fd, st.length) == -1) {
1810 np_errno(hdr->tag);
1811 return;
1815 /* rename (change the name entry) */
1816 if (*st.name != '\0') {
1817 struct stat sb;
1818 const char *newname;
1821 * XXX: 9P requires that we disallow changing the name
1822 * to that of an existing file. We can't do that
1823 * atomically (rename is happy about stealing names)
1824 * so this is just a best effort.
1826 if (fstatat(f->dir->fd, st.name, &sb, 0) == -1 &&
1827 errno != ENOENT) {
1828 np_error(hdr->tag, "target file exists");
1829 return;
1832 r = renameat(f->dir->fd, f->fname, f->dir->fd, st.name);
1833 if (r == -1) {
1834 np_errno(hdr->tag);
1835 return;
1838 /* fix the fid so it points to the new file */
1840 if ((newname = strchr(st.name, '/')) != NULL)
1841 newname++; /* skip / */
1842 else
1843 newname = st.name;
1844 strlcpy(f->fname, newname, sizeof(f->fname));
1846 if (strchr(st.name, '/') != NULL) {
1847 struct dir *dir;
1848 char *dname;
1849 int fd;
1851 dname = dirname(st.name);
1852 fd = openat(f->dir->fd, dname, O_RDONLY|O_DIRECTORY);
1853 if (fd == -1) {
1854 np_errno(hdr->tag);
1855 free_fid(f);
1856 return;
1859 if ((dir = new_dir(fd)) == NULL) {
1860 np_errno(hdr->tag);
1861 free_fid(f);
1862 return;
1865 dir_decref(f->dir);
1866 f->dir = dir_incref(dir);
1870 np_wstat(hdr->tag);
1871 return;
1873 err:
1874 client_send_listener(IMSG_CLOSE, NULL, 0);
1875 client_shutdown();
1878 static void
1879 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1881 struct fid *f;
1882 uint32_t fid;
1883 int r;
1884 char dirpath[PATH_MAX + 3];
1886 /* fid[4] */
1887 if (!NPREAD32("fid", &fid, &data, &len) ||
1888 len != 0) {
1889 client_send_listener(IMSG_CLOSE, NULL, 0);
1890 client_shutdown();
1891 return;
1894 if ((f = fid_by_id(fid)) == NULL) {
1895 np_error(hdr->tag, "invalid fid");
1896 return;
1899 if (f->qid.type & QTDIR) { /* directory */
1900 strlcpy(dirpath, "../", sizeof(dirpath));
1901 strlcat(dirpath, f->fname, sizeof(dirpath));
1902 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1903 } else /* file */
1904 r = unlinkat(f->dir->fd, f->fname, 0);
1906 if (r == -1)
1907 np_errno(hdr->tag);
1908 else
1909 np_remove(hdr->tag);
1911 free_fid(f);
1914 static void
1915 handle_message(struct imsg *imsg, size_t len, int cont)
1917 static struct fid *writefid;
1918 static off_t writepos;
1919 static size_t writetot;
1920 static size_t writeleft;
1921 static int writeskip;
1922 static uint16_t writetag;
1923 struct msg {
1924 uint8_t type;
1925 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1926 } msgs[] = {
1927 {Tversion, tversion},
1928 {Tattach, tattach},
1929 {Tclunk, tclunk},
1930 {Tflush, tflush},
1931 {Twalk, twalk},
1932 {Topen, topen},
1933 {Tcreate, tcreate},
1934 {Tread, tread},
1935 /* {Twrite, twrite}, */
1936 {Tstat, tstat},
1937 {Twstat, twstat},
1938 {Tremove, tremove},
1940 struct np_msg_header hdr;
1941 size_t i;
1942 uint8_t *data;
1944 #if DEBUG_PACKETS
1945 hexdump("incoming packet", imsg->data, len);
1946 #endif
1949 * Twrite is special and can be "continued" to allow writing
1950 * more than what the imsg framework would allow us to.
1952 if (cont) {
1953 if (writeskip)
1954 return;
1956 if (writefid == NULL) {
1957 log_warnx("received a continuation message without "
1958 "seeing a Twrite");
1959 client_send_listener(IMSG_CLOSE, NULL, 0);
1960 client_shutdown();
1961 return;
1964 twrite_cont(writefid, &writepos, &writetot, &writeleft,
1965 &writeskip, writetag, imsg->data, len);
1966 return;
1969 if (writeleft > 0) {
1970 log_warnx("received a non continuation message when still "
1971 "missed %zu bytes to write", writeleft);
1972 client_send_listener(IMSG_CLOSE, NULL, 0);
1973 client_shutdown();
1974 return;
1977 writefid = NULL;
1978 writepos = -1;
1979 writetot = 0;
1980 writeleft = 0;
1981 writeskip = 0;
1983 parse_message(imsg->data, len, &hdr, &data);
1984 len -= HEADERSIZE;
1986 log_debug("got request: len=%d type=%d[%s] tag=%d",
1987 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1989 if (!handshaked && hdr.type != Tversion) {
1990 client_send_listener(IMSG_CLOSE, NULL, 0);
1991 client_shutdown();
1992 return;
1995 if (hdr.type == Twrite) {
1996 writetag = hdr.tag;
1997 twrite(&hdr, data, len, &writefid, &writepos, &writetot,
1998 &writeleft, &writeskip);
1999 return;
2002 if (len > IMSG_MAXSIZE) {
2003 log_warnx("can't handle message: too long for its type");
2004 client_send_listener(IMSG_CLOSE, NULL, 0);
2005 client_shutdown();
2006 return;
2009 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
2010 if (msgs[i].type != hdr.type)
2011 continue;
2013 msgs[i].fn(&hdr, data, len);
2014 return;
2017 np_error(hdr.tag, "Not supported.");