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 *, int *);
186 static void twrite_cont(struct fid *, off_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 if (olen != hdr->len)
549 goto err;
551 if (hdr->type < Tversion ||
552 hdr->type >= Tmax ||
553 hdr->type == Terror ||
554 (hdr->type & 0x1) != 0) /* cannot recv a R* */
555 goto err;
557 hdr->tag = le32toh(hdr->tag);
559 *cnt = (uint8_t *)data;
560 return;
562 err:
563 log_warnx("got invalid message: (%d, %d, %d)",
564 hdr->len, hdr->type, hdr->tag);
565 client_send_listener(IMSG_CLOSE, NULL, 0);
566 client_shutdown();
569 static void
570 np_write16(struct evbuffer *e, uint16_t x)
572 x = htole16(x);
573 evbuffer_add(e, &x, sizeof(x));
576 static void
577 np_write32(struct evbuffer *e, uint32_t x)
579 x = htole32(x);
580 evbuffer_add(e, &x, sizeof(x));
583 static void
584 np_write64(struct evbuffer *e, uint64_t x)
586 x = htole64(x);
587 evbuffer_add(e, &x, sizeof(x));
590 static void
591 np_writebuf(struct evbuffer *e, size_t len, void *data)
593 evbuffer_add(e, data, len);
596 static void
597 np_header(uint32_t len, uint8_t type, uint16_t tag)
599 len += HEADERSIZE;
601 len = htole32(len);
602 tag = htole16(tag);
604 evbuffer_add(evb, &len, sizeof(len));
605 evbuffer_add(evb, &type, sizeof(type));
606 evbuffer_add(evb, &tag, sizeof(tag));
609 static void
610 np_string(struct evbuffer *e, uint16_t len, const char *str)
612 uint16_t l = len;
614 len = htole16(len);
615 evbuffer_add(e, &len, sizeof(len));
616 evbuffer_add(e, str, l);
619 static void
620 np_qid(struct evbuffer *e, struct qid *qid)
622 uint64_t path;
623 uint32_t vers;
625 path = htole64(qid->path);
626 vers = htole32(qid->vers);
628 evbuffer_add(e, &qid->type, sizeof(qid->type));
629 evbuffer_add(e, &vers, sizeof(vers));
630 evbuffer_add(e, &path, sizeof(path));
633 static void
634 do_send(void)
636 size_t len;
637 void *data;
639 len = EVBUFFER_LENGTH(evb);
640 data = EVBUFFER_DATA(evb);
642 #if DEBUG_PACKETS
643 hexdump("outgoing packet", data, len);
644 #endif
645 client_send_listener(IMSG_BUF, data, len);
646 evbuffer_drain(evb, len);
649 static void
650 np_version(uint16_t tag, uint32_t msize, const char *version)
652 uint16_t l;
654 l = strlen(version);
656 msize = htole32(msize);
658 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
659 evbuffer_add(evb, &msize, sizeof(msize));
660 np_string(evb, l, version);
661 do_send();
664 static void
665 np_attach(uint16_t tag, struct qid *qid)
667 np_header(QIDSIZE, Rattach, tag);
668 np_qid(evb, qid);
669 do_send();
672 static void
673 np_clunk(uint16_t tag)
675 np_header(0, Rclunk, tag);
676 do_send();
679 static void
680 np_flush(uint16_t tag)
682 np_header(0, Rflush, tag);
683 do_send();
686 static void
687 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
689 int i;
691 /* two bytes for the counter */
692 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
693 np_write16(evb, nwqid);
694 for (i = 0; i < nwqid; ++i)
695 np_qid(evb, wqid + i);
697 do_send();
700 static void
701 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
703 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
704 np_qid(evb, qid);
705 np_write32(evb, iounit);
706 do_send();
709 static void
710 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
712 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
713 np_qid(evb, qid);
714 np_write32(evb, iounit);
715 do_send();
718 static void
719 np_read(uint16_t tag, uint32_t count, void *data)
721 if (sizeof(count) + count + HEADERSIZE >= msize) {
722 np_error(tag, "Rread would overflow");
723 return;
726 np_header(sizeof(count) + count, Rread, tag);
727 np_write32(evb, count);
728 np_writebuf(evb, count, data);
729 do_send();
732 static void
733 np_write(uint16_t tag, uint32_t count)
735 np_header(sizeof(count), Rwrite, tag);
736 np_write32(evb, count);
737 do_send();
740 static void
741 np_stat(uint16_t tag, uint16_t count, void *data)
743 if (sizeof(count) + count + HEADERSIZE >= msize) {
744 np_error(tag, "Rstat would overflow");
745 return;
748 np_header(sizeof(count) + count, Rstat, tag);
749 np_write16(evb, count);
750 np_writebuf(evb, count, data);
751 do_send();
754 static void
755 np_wstat(uint16_t tag)
757 np_header(0, Rwstat, tag);
758 do_send();
761 static void
762 np_remove(uint16_t tag)
764 np_header(0, Rremove, tag);
765 do_send();
768 static void
769 np_error(uint16_t tag, const char *errstr)
771 uint16_t l;
773 l = strlen(errstr);
775 np_header(sizeof(l) + l, Rerror, tag);
776 np_string(evb, l, errstr);
777 do_send();
780 static void
781 np_errno(uint16_t tag)
783 int saved_errno;
784 char buf[NL_TEXTMAX] = {0};
786 saved_errno = errno;
788 strerror_r(errno, buf, sizeof(buf));
789 np_error(tag, buf);
791 errno = saved_errno;
794 static int
795 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
796 size_t *len)
798 if (*len < sizeof(*dst)) {
799 log_warnx("%s: wanted %zu bytes for the %s field but only "
800 "%zu are available.", t, sizeof(*dst), f, *len);
801 return 0;
804 memcpy(dst, *src, sizeof(*dst));
805 *src += sizeof(*dst);
806 *len -= sizeof(*dst);
808 return 1;
811 static int
812 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
813 size_t *len)
815 if (*len < sizeof(*dst)) {
816 log_warnx("%s: wanted %zu bytes for the %s field but only "
817 "%zu are available.", t, sizeof(*dst), f, *len);
818 return 0;
821 memcpy(dst, *src, sizeof(*dst));
822 *src += sizeof(*dst);
823 *len -= sizeof(*dst);
824 *dst = le16toh(*dst);
826 return 1;
829 static int
830 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
831 size_t *len)
833 if (*len < sizeof(*dst)) {
834 log_warnx("%s: wanted %zu bytes for the %s field but only "
835 "%zu are available.", t, sizeof(*dst), f, *len);
836 return 0;
839 memcpy(dst, *src, sizeof(*dst));
840 *src += sizeof(*dst);
841 *len -= sizeof(*dst);
842 *dst = le32toh(*dst);
844 return 1;
847 static int
848 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
849 size_t *len)
851 if (*len < sizeof(*dst)) {
852 log_warnx("%s: wanted %zu bytes for the %s field but only "
853 "%zu are available.", t, sizeof(*dst), f, *len);
854 return 0;
857 memcpy(dst, *src, sizeof(*dst));
858 *src += sizeof(*dst);
859 *len -= sizeof(*dst);
860 *dst = le64toh(*dst);
862 return 1;
865 static int
866 np_readstr(const char *t, const char *f, char *res, size_t reslen,
867 const uint8_t **src, size_t *len)
869 uint16_t sl;
870 char buf[32];
872 strlcpy(buf, f, sizeof(buf));
873 strlcat(buf, "-len", sizeof(buf));
875 if (!np_read16(t, buf, &sl, src, len))
876 return READSTRERR;
878 if (*len < sl) {
879 log_warnx("%s: wanted %d bytes for the %s field but only "
880 "%zu are available.", t, sl, f, *len);
881 return READSTRERR;
884 if (*len > reslen-1)
885 return READSTRTRUNC;
887 memcpy(res, *src, sl);
888 res[sl] = '\0';
889 *src += sl;
890 *len -= sl;
892 return 0;
895 static int
896 np_readst(const char *t, const char *f, struct np_stat *st,
897 char *name, size_t namelen, const uint8_t **src, size_t *len)
899 memset(st, 0, sizeof(*st));
901 /* len is sent twice! */
902 if (!np_read16(t, "stat len", &st->size, src, len) ||
903 !np_read16(t, "stat.size", &st->size, src, len) ||
904 !np_read16(t, "stat.type", &st->type, src, len) ||
905 !np_read32(t, "stat.dev", &st->dev, src, len) ||
906 !np_read64(t, "stat.qid.path", &st->qid.path, src, len) ||
907 !np_read32(t, "stat.qid.vers", &st->qid.vers, src, len) ||
908 !np_read8(t, "stat.qid.type", &st->qid.type, src, len) ||
909 !np_read32(t, "stat.mode", &st->mode, src, len) ||
910 !np_read32(t, "stat.atime", &st->atime, src, len) ||
911 !np_read32(t, "stat.mtime", &st->mtime, src, len) ||
912 !np_read64(t, "stat.length", &st->length, src, len))
913 return READSTRERR;
915 /*
916 * ignore everything but the name, we don't support
917 * changing those fields anyway
918 */
919 st->name = name;
920 return np_readstr(t, "stat.name", name, namelen, src, len);
923 static void
924 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
926 char *dot, version[32];
928 if (handshaked)
929 goto err;
931 /* msize[4] version[s] */
932 if (!NPREAD32("msize", &msize, &data, &len))
933 goto err;
935 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
936 case READSTRERR:
937 goto err;
938 case READSTRTRUNC:
939 log_warnx("9P version string too long, truncated");
940 np_version(hdr->tag, MSIZE9P, "unknown");
941 return;
944 if (len != 0)
945 goto err;
947 if ((dot = strchr(version, '.')) != NULL)
948 *dot = '\0';
950 if (strcmp(version, VERSION9P) != 0) {
951 log_warnx("unknown 9P version \"%s\"; want "VERSION9P,
952 version);
953 np_version(hdr->tag, MSIZE9P, "unknown");
954 return;
957 if (msize < MIN_MSIZE) {
958 log_warnx("msize too small: %"PRIu32"; want %d at least",
959 msize, MIN_MSIZE);
960 np_version(hdr->tag, MSIZE9P, "unknown");
961 return;
964 /* version matched */
965 handshaked = 1;
966 msize = MIN(msize, MSIZE9P);
967 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
968 np_version(hdr->tag, msize, VERSION9P);
969 return;
971 err:
972 client_send_listener(IMSG_CLOSE, NULL, 0);
973 client_shutdown();
976 static void
977 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
979 struct dir *dir;
980 struct fid *f;
981 uint32_t fid, afid;
982 int fd;
983 char aname[PATH_MAX];
985 /* fid[4] afid[4] uname[s] aname[s] */
987 if (!NPREAD32("fid", &fid, &data, &len) ||
988 !NPREAD32("afid", &afid, &data, &len))
989 goto err;
991 /* read the uname but don't actually use it */
992 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
993 case READSTRERR:
994 goto err;
995 case READSTRTRUNC:
996 np_error(hdr->tag, "name too long");
997 return;
1000 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
1001 case READSTRERR:
1002 goto err;
1003 case READSTRTRUNC:
1004 np_error(hdr->tag, "name too long");
1005 return;
1008 if (*aname == '\0')
1009 strlcpy(aname, "/", sizeof(aname));
1011 if (len != 0)
1012 goto err;
1014 if (fid_by_id(fid) != NULL || afid != NOFID) {
1015 np_error(hdr->tag, "invalid fid or afid");
1016 return;
1019 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
1020 goto fail;
1022 if ((dir = new_dir(fd)) == NULL)
1023 goto fail;
1025 log_debug("attached %s to %d", aname, fid);
1027 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
1028 dir_decref(dir);
1029 goto fail;
1032 np_attach(hdr->tag, &f->qid);
1033 return;
1035 fail:
1036 np_errno(hdr->tag);
1037 log_warn("failed to attach %s", aname);
1038 return;
1040 err:
1041 client_send_listener(IMSG_CLOSE, NULL, 0);
1042 client_shutdown();
1045 static void
1046 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1048 struct fid *f;
1049 uint32_t fid;
1051 /* fid[4] */
1052 if (!NPREAD32("fid", &fid, &data, &len) ||
1053 len != 0) {
1054 client_send_listener(IMSG_CLOSE, NULL, 0);
1055 client_shutdown();
1056 return;
1059 if ((f = fid_by_id(fid)) == NULL) {
1060 np_error(hdr->tag, "invalid fid");
1061 return;
1064 free_fid(f);
1065 np_clunk(hdr->tag);
1068 static void
1069 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1071 uint16_t oldtag;
1074 * We're doing only synchronous I/O. Tflush is implemented
1075 * only because it's illegal to reply with a Rerror.
1078 /* oldtag[2] */
1079 if (len != sizeof(oldtag)) {
1080 log_warnx("Tflush with the wrong size: got %zu want %zu",
1081 len, sizeof(oldtag));
1082 client_send_listener(IMSG_CLOSE, NULL, 0);
1083 client_shutdown();
1084 return;
1087 np_flush(hdr->tag);
1090 static void
1091 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1093 struct stat sb;
1094 struct dir *dir;
1095 struct qid wqid[MAXWELEM] = {0};
1096 struct fid *f, *nf;
1097 uint32_t fid, newfid;
1098 uint16_t nwname;
1099 int fd, oldfd, no, nwqid = 0;
1100 char wnam[PATH_MAX];
1102 if (!NPREAD32("fid", &fid, &data, &len) ||
1103 !NPREAD32("newfid", &newfid, &data, &len) ||
1104 !NPREAD16("nwname", &nwname, &data, &len))
1105 goto err;
1107 if (nwname > MAXWELEM) {
1108 log_warnx("Twalk: more than %d path elements: %d",
1109 MAXWELEM, nwname);
1110 goto err;
1113 if ((f = fid_by_id(fid)) == NULL) {
1114 np_error(hdr->tag, "invalid fid");
1115 return;
1118 if (f->fd != -1) {
1119 np_error(hdr->tag, "fid already opened for I/O");
1120 return;
1123 if (fid == newfid)
1124 nf = f;
1125 else if ((nf = fid_by_id(newfid)) != NULL) {
1126 np_error(hdr->tag, "newfid already in use");
1127 return;
1128 } else
1129 nf = NULL;
1131 /* special case: fid duplication */
1132 if (nwname == 0) {
1134 * TODO: should we forbid fids duplication when fid ==
1135 * newfid?
1137 if (nf == NULL &&
1138 (nf = new_fid(f->dir, newfid, f->fname, &f->qid)) == NULL)
1139 fatal("new_fid duplication");
1141 np_walk(hdr->tag, 0, NULL);
1142 return;
1145 if (!(f->qid.type & QTDIR)) {
1146 np_error(hdr->tag, "fid doesn't represent a directory");
1147 return;
1150 oldfd = f->dir->fd;
1152 for (nwqid = 0; nwqid < nwname; nwqid++) {
1153 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1154 case READSTRERR:
1155 goto err;
1156 case READSTRTRUNC:
1157 np_error(hdr->tag, "wname too long");
1158 return;
1161 if (*wnam == '\0' ||
1162 strchr(wnam, '/') != NULL ||
1163 !strcmp(wnam, ".")) {
1164 errno = EINVAL;
1165 goto cantopen;
1168 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1169 errno != ENOTDIR)
1170 goto cantopen;
1172 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1173 (fd != -1 && fstat(fd, &sb) == -1))
1174 goto cantopen;
1176 qid_update_from_sb(&wqid[nwqid], &sb);
1178 /* reached a file but we still have other components */
1179 if (fd == -1 && nwqid+1 < nwname)
1180 goto cantopen;
1182 /* reached the end and found a file */
1183 if (fd == -1 && nwqid+1 == nwname)
1184 continue;
1186 if (oldfd != f->dir->fd)
1187 close(oldfd);
1188 oldfd = fd;
1191 if (len != 0)
1192 goto err;
1195 * If fd is -1 we've reached a file, otherwise we've just
1196 * reached another directory. We must pay attention to what
1197 * file descriptor we use to create the dir, because if we've
1198 * reached a file and oldfd is f->dir->fd then we *must* share
1199 * the same dir (it was a walk of one path from a directory to a
1200 * file, otherwise fun is bound to happen as soon as the client
1201 * closes the fid for the directory but keeps the one for the
1202 * file.
1204 if (fd == -1 && oldfd == f->dir->fd)
1205 dir = f->dir;
1206 else if (fd == -1)
1207 dir = new_dir(oldfd);
1208 else
1209 dir = new_dir(fd);
1211 if (dir == NULL)
1212 fatal("new_dir");
1214 if (nf == NULL) {
1215 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1216 fatal("new fid");
1217 } else {
1218 /* update the dir */
1219 dir_decref(nf->dir);
1220 nf->dir = dir_incref(dir);
1223 np_walk(hdr->tag, nwqid, wqid);
1224 return;
1226 cantopen:
1227 if (oldfd != f->dir->fd)
1228 close(oldfd);
1229 no = errno;
1230 if (nwqid == 0)
1231 np_error(hdr->tag, strerror(no));
1232 else
1233 np_walk(hdr->tag, nwqid, wqid);
1234 return;
1236 err:
1237 client_send_listener(IMSG_CLOSE, NULL, 0);
1238 client_shutdown();
1241 static inline int
1242 npmode_to_unix(uint8_t mode, int *flags)
1244 switch (mode & 0x0F) {
1245 case KOREAD:
1246 *flags = O_RDONLY;
1247 break;
1248 case KOWRITE:
1249 *flags = O_WRONLY;
1250 break;
1251 case KORDWR:
1252 *flags = O_RDWR;
1253 break;
1254 case KOEXEC:
1255 log_warnx("tried to open something with KOEXEC");
1256 /* fallthrough */
1257 default:
1258 return -1;
1261 if (mode & KOTRUNC)
1262 *flags |= O_TRUNC;
1263 if (mode & KORCLOSE)
1264 *flags |= O_CLOEXEC;
1266 return 0;
1269 static void
1270 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1272 struct stat sb;
1273 struct qid qid;
1274 struct fid *f;
1275 uint32_t fid;
1276 uint8_t mode;
1277 const char *path;
1279 /* fid[4] mode[1] */
1280 if (!NPREAD32("fid", &fid, &data, &len) ||
1281 !NPREAD8("mode", &mode, &data, &len) ||
1282 len != 0) {
1283 client_send_listener(IMSG_CLOSE, NULL, 0);
1284 client_shutdown();
1285 return;
1288 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1289 np_error(hdr->tag, "invalid fid");
1290 return;
1293 if (npmode_to_unix(mode, &f->iomode) == -1) {
1294 np_error(hdr->tag, "invalid mode");
1295 return;
1298 path = f->fname;
1299 if (f->qid.type & QTDIR)
1300 path = ".";
1302 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1303 np_error(hdr->tag, strerror(errno));
1304 return;
1307 if (fstat(f->fd, &sb) == -1)
1308 fatal("fstat");
1310 if (S_ISDIR(sb.st_mode)) {
1311 if ((f->d = fdopendir(f->fd)) == NULL) {
1312 np_errno(hdr->tag);
1313 close(f->fd);
1314 f->fd = -1;
1315 return;
1318 if ((f->evb = evbuffer_new()) == NULL) {
1319 np_errno(hdr->tag);
1320 closedir(f->d);
1321 f->d = NULL;
1322 f->fd = -1;
1326 f->offset = 0;
1328 qid_update_from_sb(&qid, &sb);
1329 np_open(hdr->tag, &qid, sb.st_blksize);
1332 static void
1333 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1335 struct stat sb;
1336 struct qid qid;
1337 struct fid *f;
1338 uint32_t fid, perm;
1339 uint8_t mode;
1340 char name[PATH_MAX];
1342 /* fid[4] name[s] perm[4] mode[1] */
1343 if (!NPREAD32("fid", &fid, &data, &len))
1344 goto err;
1345 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1346 case READSTRERR:
1347 goto err;
1348 case READSTRTRUNC:
1349 np_error(hdr->tag, "name too long");
1350 return;
1352 if (!NPREAD32("perm", &perm, &data, &len) ||
1353 !NPREAD8("mode", &mode, &data, &len) ||
1354 len != 0)
1355 goto err;
1357 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1358 strchr(name, '/') != NULL) {
1359 np_error(hdr->tag, "invalid name");
1360 return;
1363 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1364 np_error(hdr->tag, "invalid fid");
1365 return;
1368 if (!(f->qid.type & QTDIR)) {
1369 np_error(hdr->tag, "fid doesn't identify a directory");
1370 return;
1373 if (npmode_to_unix(mode, &f->iomode) == -1) {
1374 np_error(hdr->tag, "invalid mode");
1375 return;
1378 if (f->iomode & O_RDONLY) {
1379 np_error(hdr->tag, "can't create a read-only file");
1380 return;
1383 /* TODO: parse the mode */
1385 if (perm & 0x80000000) {
1386 /* create a directory */
1387 f->fd = mkdirat(f->dir->fd, name, 0755);
1388 } else {
1389 /* create a file */
1390 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1391 0644);
1394 if (f->fd == -1) {
1395 np_errno(hdr->tag);
1396 return;
1399 if (fstat(f->fd, &sb) == -1)
1400 fatal("fstat");
1402 if (S_ISDIR(sb.st_mode)) {
1403 if ((f->d = fdopendir(f->fd)) == NULL) {
1404 np_errno(hdr->tag);
1405 close(f->fd);
1406 f->fd = -1;
1407 return;
1410 if ((f->evb = evbuffer_new()) == NULL) {
1411 np_errno(hdr->tag);
1412 closedir(f->d);
1413 f->d = NULL;
1414 f->fd = -1;
1418 f->offset = 0;
1420 qid_update_from_sb(&qid, &sb);
1421 np_create(hdr->tag, &qid, sb.st_blksize);
1423 return;
1425 err:
1426 client_send_listener(IMSG_CLOSE, NULL, 0);
1427 client_shutdown();
1430 static inline int
1431 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1433 struct qid qid;
1434 const char *uid, *gid, *muid;
1435 size_t tot;
1436 uint32_t mode;
1437 uint16_t namlen, uidlen, gidlen, ulen;
1439 qid_update_from_sb(&qid, sb);
1441 /* TODO: fill these fields */
1442 uid = "";
1443 gid = "";
1444 muid = "";
1446 namlen = strlen(fname);
1447 uidlen = strlen(uid);
1448 gidlen = strlen(gid);
1449 ulen = strlen(muid);
1451 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1452 if (tot > UINT16_MAX) {
1453 log_warnx("stat info for dir entry %s would overflow",
1454 fname);
1455 return -1;
1458 mode = sb->st_mode & 0xFFFF;
1459 if (qid.type & QTDIR)
1460 mode |= 0x80000000;
1462 np_write16(evb, tot); /* size[2] */
1463 np_write16(evb, sb->st_rdev); /* type[2] */
1464 np_write32(evb, sb->st_dev); /* dev[4] */
1465 np_qid(evb, &qid); /* qid[13] */
1466 np_write32(evb, mode); /* mode[4] */
1467 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1468 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1470 /* special case: directories have size 0 */
1471 if (qid.type & QTDIR)
1472 np_write64(evb, 0);
1473 else
1474 np_write64(evb, sb->st_size); /* length[8] */
1476 np_string(evb, namlen, fname); /* name[s] */
1477 np_string(evb, uidlen, uid); /* uid[s] */
1478 np_string(evb, gidlen, gid); /* gid[s] */
1479 np_string(evb, ulen, muid); /* muid[s] */
1481 return 0;
1484 static void
1485 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1487 struct fid *f;
1488 ssize_t r;
1489 size_t howmuch;
1490 uint64_t off;
1491 uint32_t fid, count;
1492 char buf[2048];
1494 /* fid[4] offset[8] count[4] */
1495 if (!NPREAD32("fid", &fid, &data, &len) ||
1496 !NPREAD64("offset", &off, &data, &len) ||
1497 !NPREAD32("count", &count, &data, &len) ||
1498 len != 0) {
1499 client_send_listener(IMSG_CLOSE, NULL, 0);
1500 client_shutdown();
1501 return;
1504 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1505 np_error(hdr->tag, "invalid fid");
1506 return;
1509 if (TYPE_OVERFLOW(off_t, off)) {
1510 log_warnx("unexpected off_t size");
1511 np_error(hdr->tag, "invalid offset");
1512 return;
1515 if (f->d == NULL) {
1516 /* read a file */
1517 howmuch = MIN(sizeof(buf), count);
1518 r = pread(f->fd, buf, howmuch, (off_t)off);
1519 if (r == -1)
1520 np_errno(hdr->tag);
1521 else
1522 np_read(hdr->tag, r, buf);
1523 } else {
1524 if (off == 0 && f->offset != 0) {
1525 rewinddir(f->d);
1526 f->offset = 0;
1527 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1530 if (off != f->offset) {
1531 np_error(hdr->tag, "can't seek in directories");
1532 return;
1535 while (EVBUFFER_LENGTH(f->evb) < count) {
1536 struct dirent *d;
1537 struct stat sb;
1539 if ((d = readdir(f->d)) == NULL)
1540 break;
1541 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1542 continue;
1543 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1544 warn("fstatat");
1545 continue;
1547 serialize_stat(d->d_name, &sb, f->evb);
1550 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1551 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1552 evbuffer_drain(f->evb, count);
1554 f->offset += count;
1558 static void
1559 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len,
1560 struct fid **writefid, off_t *writepos, size_t *writeleft, int *writeskip)
1562 struct fid *f;
1563 ssize_t r;
1564 uint64_t off;
1565 uint32_t fid, count;
1567 /* fid[4] offset[8] count[4] data[count] */
1568 if (!NPREAD32("fid", &fid, &data, &len) ||
1569 !NPREAD64("off", &off, &data, &len) ||
1570 !NPREAD32("count", &count, &data, &len) ||
1571 count < len) {
1572 client_send_listener(IMSG_CLOSE, NULL, 0);
1573 client_shutdown();
1574 return;
1577 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1578 *writeskip = 1;
1579 np_error(hdr->tag, "invalid fid");
1580 return;
1583 if (!(f->iomode & O_WRONLY) &&
1584 !(f->iomode & O_RDWR)) {
1585 *writeskip = 1;
1586 np_error(hdr->tag, "fid not opened for writing");
1587 return;
1590 if (TYPE_OVERFLOW(off_t, off)) {
1591 *writeskip = 1;
1592 log_warnx("unexpected off_t size");
1593 np_error(hdr->tag, "invalid offset");
1594 return;
1597 if ((r = pwrite(f->fd, data, len, off)) == -1) {
1598 *writeskip = 1;
1599 np_errno(hdr->tag);
1600 } else if (count == len)
1601 np_write(hdr->tag, r);
1603 /* account for a continuated write */
1604 if (count > len) {
1605 *writefid = f;
1606 *writepos = off + len;
1607 *writeleft = count - len;
1608 *writeskip = 0;
1612 static void
1613 twrite_cont(struct fid *f, off_t *writepos, size_t *writeleft, int *writeskip,
1614 uint16_t tag, const uint8_t *data, size_t len)
1616 ssize_t r;
1618 if (len > *writeleft) {
1619 client_send_listener(IMSG_CLOSE, NULL, 0);
1620 client_shutdown();
1621 return;
1624 if ((r = pwrite(f->fd, data, len, *writepos)) == -1) {
1625 *writeskip = 1;
1626 np_errno(tag);
1627 return;
1630 *writeleft -= len;
1631 *writepos += len;
1633 if (*writeleft == 0)
1634 np_write(tag, r);
1637 static void
1638 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1640 struct evbuffer *evb;
1641 struct stat sb;
1642 struct fid *f;
1643 int r;
1644 uint32_t fid;
1646 /* fid[4] */
1647 if (!NPREAD32("fid", &fid, &data, &len) ||
1648 len != 0) {
1649 client_send_listener(IMSG_CLOSE, NULL, 0);
1650 client_shutdown();
1651 return;
1655 * plan9' stat(9P) is not clear on whether the stat is allowed
1656 * on opened fids or not. We're allowing stat regardless of the
1657 * status of the fid.
1660 if ((f = fid_by_id(fid)) == NULL) {
1661 np_error(hdr->tag, "invalid fid");
1662 return;
1665 if ((evb = evbuffer_new()) == NULL)
1666 fatal("evbuffer_new");
1668 if (f->fd != -1)
1669 r = fstat(f->fd, &sb);
1670 else if (f->qid.type & QTDIR)
1671 r = fstat(f->dir->fd, &sb);
1672 else
1673 r = fstatat(f->dir->fd, f->fname, &sb, 0);
1675 if (r == -1) {
1676 np_errno(hdr->tag);
1677 evbuffer_free(evb);
1678 return;
1681 if (serialize_stat(f->fname, &sb, evb) == -1)
1682 np_error(hdr->tag, "stat would overflow");
1683 else
1684 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1685 evbuffer_free(evb);
1688 static void
1689 twstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1691 struct timespec times[2];
1692 struct np_stat st;
1693 struct fid *f;
1694 int r;
1695 uint32_t fid;
1696 char name[PATH_MAX];
1698 /* fid[4] stat[n] */
1699 if (!NPREAD32("fid", &fid, &data, &len))
1700 goto err;
1702 switch (NPREADST("stat", &st, name, sizeof(name), &data, &len)) {
1703 case READSTRERR:
1704 goto err;
1705 case READSTRTRUNC:
1706 log_warnx("wstat new name would overflow");
1707 np_error(hdr->tag, "new name too long");
1708 return;
1712 * We skip the reading of some fields voluntarily because we
1713 * don't support chown, so len will always be > 0!
1715 #ifdef notyet
1716 if (len != 0)
1717 goto err;
1718 #endif
1720 if ((f = fid_by_id(fid)) == NULL) {
1721 np_error(hdr->tag, "invalid fid");
1722 return;
1726 * 9P wants these edits to be done in an atomic fashion,
1727 * something that I don't think it's possible on UNIX without
1728 * some special kernel help. Changing atime or mtime,
1729 * permissions, or rename the file are different syscalls.
1731 * Also, silently ignore stuff we can't/don't want to modify.
1734 /* change the permissions */
1735 if (st.mode != (uint32_t)-1) {
1736 mode_t m = st.mode & 0x7FF; /* silently truncate higer bits */
1737 if (f->fd != -1)
1738 r = fchmod(f->fd, m);
1739 else
1740 r = fchmodat(f->dir->fd, f->fname, m, 0);
1742 if (r == -1) {
1743 np_errno(hdr->tag);
1744 return;
1748 /* change the atime/mtime of the fid, opened or not */
1749 if (st.atime != (uint32_t)-1 || st.mtime != (uint32_t)-1) {
1750 times[0].tv_nsec = UTIME_OMIT;
1751 times[1].tv_nsec = UTIME_OMIT;
1753 if (st.atime != (uint32_t)-1) {
1754 times[0].tv_sec = st.atime;
1755 times[0].tv_nsec = 0;
1757 if (st.mtime != (uint32_t)-1) {
1758 times[1].tv_sec = st.mtime;
1759 times[1].tv_nsec = 0;
1762 if (f->fd != -1)
1763 r = futimens(f->fd, times);
1764 else
1765 r = utimensat(f->dir->fd, f->fname, times, 0);
1767 if (r == -1) {
1768 np_errno(hdr->tag);
1769 return;
1773 /* truncate */
1774 if (st.length != (uint64_t)-1) {
1775 if (f->fd == -1) {
1776 np_error(hdr->tag, "can't truncate a non-opened fid");
1777 return;
1780 if (f->qid.type & QTDIR && st.length != 0) {
1781 np_error(hdr->tag, "can't truncate directories");
1782 return;
1785 if (TYPE_OVERFLOW(off_t, st.length)) {
1786 log_warnx("truncate request overflows off_t: %"PRIu64,
1787 st.length);
1788 np_error(hdr->tag, "length overflows");
1789 return;
1792 if (f->qid.type == 0 &&
1793 ftruncate(f->fd, st.length) == -1) {
1794 np_errno(hdr->tag);
1795 return;
1799 /* rename (change the name entry) */
1800 if (*st.name != '\0') {
1801 struct stat sb;
1802 const char *newname;
1805 * XXX: 9P requires that we disallow changing the name
1806 * to that of an existing file. We can't do that
1807 * atomically (rename is happy about stealing names)
1808 * so this is just a best effort.
1810 if (fstatat(f->dir->fd, st.name, &sb, 0) == -1 &&
1811 errno != ENOENT) {
1812 np_error(hdr->tag, "target file exists");
1813 return;
1816 r = renameat(f->dir->fd, f->fname, f->dir->fd, st.name);
1817 if (r == -1) {
1818 np_errno(hdr->tag);
1819 return;
1822 /* fix the fid so it points to the new file */
1824 if ((newname = strchr(st.name, '/')) != NULL)
1825 newname++; /* skip / */
1826 else
1827 newname = st.name;
1828 strlcpy(f->fname, newname, sizeof(f->fname));
1830 if (strchr(st.name, '/') != NULL) {
1831 struct dir *dir;
1832 char *dname;
1833 int fd;
1835 dname = dirname(st.name);
1836 fd = openat(f->dir->fd, dname, O_RDONLY|O_DIRECTORY);
1837 if (fd == -1) {
1838 np_errno(hdr->tag);
1839 free_fid(f);
1840 return;
1843 if ((dir = new_dir(fd)) == NULL) {
1844 np_errno(hdr->tag);
1845 free_fid(f);
1846 return;
1849 dir_decref(f->dir);
1850 f->dir = dir_incref(dir);
1854 np_wstat(hdr->tag);
1855 return;
1857 err:
1858 client_send_listener(IMSG_CLOSE, NULL, 0);
1859 client_shutdown();
1862 static void
1863 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1865 struct fid *f;
1866 uint32_t fid;
1867 int r;
1868 char dirpath[PATH_MAX + 3];
1870 /* fid[4] */
1871 if (!NPREAD32("fid", &fid, &data, &len) ||
1872 len != 0) {
1873 client_send_listener(IMSG_CLOSE, NULL, 0);
1874 client_shutdown();
1875 return;
1878 if ((f = fid_by_id(fid)) == NULL) {
1879 np_error(hdr->tag, "invalid fid");
1880 return;
1883 if (f->qid.type & QTDIR) { /* directory */
1884 strlcpy(dirpath, "../", sizeof(dirpath));
1885 strlcat(dirpath, f->fname, sizeof(dirpath));
1886 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1887 } else /* file */
1888 r = unlinkat(f->dir->fd, f->fname, 0);
1890 if (r == -1)
1891 np_errno(hdr->tag);
1892 else
1893 np_remove(hdr->tag);
1895 free_fid(f);
1898 static void
1899 handle_message(struct imsg *imsg, size_t len, int cont)
1901 static struct fid *writefid;
1902 static off_t writepos;
1903 static size_t writeleft;
1904 static int writeskip;
1905 static uint16_t writetag;
1906 struct msg {
1907 uint8_t type;
1908 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1909 } msgs[] = {
1910 {Tversion, tversion},
1911 {Tattach, tattach},
1912 {Tclunk, tclunk},
1913 {Tflush, tflush},
1914 {Twalk, twalk},
1915 {Topen, topen},
1916 {Tcreate, tcreate},
1917 {Tread, tread},
1918 /* {Twrite, twrite}, */
1919 {Tstat, tstat},
1920 {Twstat, twstat},
1921 {Tremove, tremove},
1923 struct np_msg_header hdr;
1924 size_t i;
1925 uint8_t *data;
1927 #if DEBUG_PACKETS
1928 hexdump("incoming packet", imsg->data, len);
1929 #endif
1932 * Twrite is special and can be "continued" to allow writing
1933 * more than what the imsg framework would allow us to.
1935 if (writeleft > 0 && !cont) {
1936 log_warnx("received a non continuation message when still "
1937 "missed %zu bytes to write", writeleft);
1938 client_send_listener(IMSG_CLOSE, NULL, 0);
1939 client_shutdown();
1940 return;
1943 if (cont) {
1944 if (writeskip)
1945 return;
1947 if (writefid == NULL) {
1948 log_warnx("received a continuation message without "
1949 "seeing a Twrite");
1950 client_send_listener(IMSG_CLOSE, NULL, 0);
1951 client_shutdown();
1952 return;
1955 log_warnx("continuing...");
1956 twrite_cont(writefid, &writepos, &writeleft, &writeskip,
1957 writetag, imsg->data, len);
1958 return;
1961 writefid = NULL;
1962 writepos = -1;
1963 writeleft = 0;
1964 writeskip = 0;
1966 parse_message(imsg->data, len, &hdr, &data);
1967 len -= HEADERSIZE;
1969 log_debug("got request: len=%d type=%d[%s] tag=%d",
1970 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1972 if (!handshaked && hdr.type != Tversion) {
1973 client_send_listener(IMSG_CLOSE, NULL, 0);
1974 client_shutdown();
1975 return;
1978 if (hdr.type == Twrite) {
1979 writetag = hdr.tag;
1980 twrite(&hdr, data, len, &writefid, &writepos, &writeleft,
1981 &writeskip);
1982 return;
1985 if (len > IMSG_MAXSIZE) {
1986 log_warnx("can't handle message: too long for its type");
1987 client_send_listener(IMSG_CLOSE, NULL, 0);
1988 client_shutdown();
1989 return;
1992 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1993 if (msgs[i].type != hdr.type)
1994 continue;
1996 msgs[i].fn(&hdr, data, len);
1997 return;
2000 np_error(hdr.tag, "Not supported.");