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 * The minimum value allowed for the msize.
47 */
48 #define MIN_MSIZE 256
50 #define DEBUG_PACKETS 0
52 /* straight outta /src/usr.bin/ssh/scp.c */
53 #define TYPE_OVERFLOW(type, val) \
54 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
55 (sizeof(type) == 8 && (val) > INT64_MAX) || \
56 (sizeof(type) != 4 && sizeof(type) != 8))
58 STAILQ_HEAD(dirhead, dir) dirs;
59 struct dir {
60 int refcount;
61 int fd;
62 STAILQ_ENTRY(dir) entries;
63 };
65 STAILQ_HEAD(fidhead, fid) fids;
66 struct fid {
67 uint32_t fid;
69 char fname[NAME_MAX];
71 /*
72 * the flags passed to open(2). O_CLOEXEC means ORCLOSE, that
73 * is to unlink the file upon Tclunk.
74 */
75 int iomode;
77 /*
78 * if fd is not -1 this fid was opened, fd represents its
79 * file descriptor and iomode the flags passed to open(2).
80 */
81 int fd;
82 DIR *d;
83 struct evbuffer *evb;
85 /*
86 * expected offset for Tread against a directory.
87 */
88 uint64_t offset;
90 struct qid qid;
91 struct dir *dir;
92 STAILQ_ENTRY(fid) entries;
93 };
95 static struct imsgev *iev_listener;
96 static struct evbuffer *evb;
97 static uint32_t peerid;
99 static int handshaked;
100 uint32_t msize;
102 static __dead void client_shutdown(void);
103 static void client_sig_handler(int, short, void *);
104 static void client_dispatch_listener(int, short, void *);
105 static void client_privdrop(const char *, const char *);
107 static int client_send_listenerp(int, uint32_t, const void *, uint16_t);
108 static int client_send_listener(int, const void *, uint16_t);
110 static void qid_update_from_sb(struct qid *, struct stat *);
112 static struct dir *new_dir(int);
113 static struct dir *dir_incref(struct dir *);
114 static void dir_decref(struct dir *);
116 static struct fid *new_fid(struct dir *, uint32_t, const char *, struct qid *);
117 static struct fid *fid_by_id(uint32_t);
118 static void free_fid(struct fid *);
120 static void parse_message(const uint8_t *, size_t,
121 struct np_msg_header *, uint8_t **);
123 static void np_write16(struct evbuffer *, uint16_t);
124 static void np_write32(struct evbuffer *, uint32_t);
125 static void np_write64(struct evbuffer *, uint64_t);
126 static void np_header(uint32_t, uint8_t, uint16_t);
127 static void np_string(struct evbuffer *, uint16_t, const char *);
128 static void np_qid(struct evbuffer *, struct qid *);
129 static void do_send(void);
131 static void np_version(uint16_t, uint32_t, const char *);
132 static void np_attach(uint16_t, struct qid *);
133 static void np_clunk(uint16_t);
134 static void np_flush(uint16_t);
135 static void np_walk(uint16_t, int, struct qid *);
136 static void np_open(uint16_t, struct qid *, uint32_t);
137 static void np_create(uint16_t, struct qid *, uint32_t);
138 static void np_read(uint16_t, uint32_t, void *);
139 static void np_write(uint16_t, uint32_t);
140 static void np_stat(uint16_t, uint16_t, void *);
141 static void np_wstat(uint16_t);
142 static void np_remove(uint16_t);
143 static void np_error(uint16_t, const char *);
144 static void np_errno(uint16_t);
146 static int np_read8(const char *, const char *, uint8_t *,
147 const uint8_t **, size_t *);
148 static int np_read16(const char *, const char *, uint16_t *,
149 const uint8_t **, size_t *);
150 static int np_read32(const char *, const char *, uint32_t *,
151 const uint8_t **, size_t *);
152 static int np_read64(const char *, const char *, uint64_t *,
153 const uint8_t **, size_t *);
155 #define READSTRERR -1
156 #define READSTRTRUNC -2
157 static int np_readstr(const char *, const char *, char *, size_t,
158 const uint8_t **, size_t *);
160 static int np_readst(const char *, const char *, struct np_stat *,
161 char *, size_t, const uint8_t **, size_t *);
163 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
164 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
165 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
166 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
168 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
170 #define NPREADST(f, dst, n, nl, src, len) np_readst(__func__, f, dst, n, nl, src, len)
172 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
173 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
174 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
175 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
176 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
177 static void topen(struct np_msg_header *, const uint8_t *, size_t);
178 static void tcreate(struct np_msg_header *, const uint8_t *, size_t);
179 static void tread(struct np_msg_header *, const uint8_t *, size_t);
180 static void twrite(struct np_msg_header *, const uint8_t *, size_t, struct fid **, off_t *, size_t *, int *);
181 static void twrite_cont(struct fid *, off_t *, size_t *, int *, uint16_t, const uint8_t *, size_t);
182 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
183 static void twstat(struct np_msg_header *, const uint8_t *, size_t);
184 static void tremove(struct np_msg_header *, const uint8_t *, size_t);
185 static void handle_message(struct imsg *, size_t, int);
187 __dead void
188 client(int debug, int verbose)
190 struct event ev_sigint, ev_sigterm;
192 log_init(debug, LOG_DAEMON);
193 log_setverbose(verbose);
195 setproctitle("client");
196 log_procinit("client");
198 log_debug("warming up");
200 event_init();
202 /* Setup signal handlers */
203 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
204 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
206 signal_add(&ev_sigint, NULL);
207 signal_add(&ev_sigterm, NULL);
209 signal(SIGPIPE, SIG_IGN);
210 signal(SIGHUP, SIG_IGN);
212 /* Setup pipe and event handler to the listener process */
213 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
214 fatal(NULL);
216 imsg_init(&iev_listener->ibuf, 3);
217 iev_listener->handler = client_dispatch_listener;
219 /* Setup event handlers. */
220 iev_listener->events = EV_READ;
221 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
222 iev_listener->events, iev_listener->handler, iev_listener);
223 event_add(&iev_listener->ev, NULL);
225 event_dispatch();
226 client_shutdown();
229 static __dead void
230 client_shutdown(void)
232 if (evb != NULL)
233 evbuffer_free(evb);
235 msgbuf_clear(&iev_listener->ibuf.w);
236 close(iev_listener->ibuf.fd);
238 free(iev_listener);
240 log_debug("client exiting");
241 exit(0);
244 static void
245 client_sig_handler(int sig, short event, void *d)
247 /*
248 * Normal signal handler rules don't apply because libevent
249 * decouples for us.
250 */
252 switch (sig) {
253 case SIGINT:
254 case SIGTERM:
255 client_shutdown();
256 default:
257 fatalx("unexpected signal %d", sig);
261 static void
262 client_dispatch_listener(int fd, short event, void *d)
264 static int auth = 0;
265 struct kd_auth_proc rauth;
266 struct kd_debug_info debug;
267 struct fid *f;
268 struct imsg imsg;
269 struct imsgev *iev = d;
270 struct imsgbuf *ibuf;
271 ssize_t n;
272 int shut = 0;
274 ibuf = &iev->ibuf;
276 if (event & EV_READ) {
277 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
278 fatal("imsg_read error");
279 if (n == 0) /* Connection closed */
280 shut = 1;
282 if (event & EV_WRITE) {
283 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
284 fatal("msgbuf_write");
285 if (n == 0) /* Connection closed */
286 shut = 1;
289 for (;;) {
290 if ((n = imsg_get(ibuf, &imsg)) == -1)
291 fatal("%s: imsg_get error", __func__);
292 if (n == 0) /* No more messages. */
293 break;
295 switch (imsg.hdr.type) {
296 case IMSG_CTL_LOG_VERBOSE:
297 if (IMSG_DATA_SIZE(imsg) != sizeof(verbose))
298 fatalx("%s: IMSG_CTL_LOG_VERBOSE wrong size",
299 __func__);
300 memcpy(&verbose, imsg.data, sizeof(verbose));
301 log_setverbose(verbose);
302 break;
303 case IMSG_CTL_DEBUG:
304 STAILQ_FOREACH(f, &fids, entries) {
305 memset(&debug, 0, sizeof(debug));
306 debug.fid = f->fid;
307 strlcpy(debug.path, f->fname,
308 sizeof(debug.path));
309 client_send_listenerp(IMSG_CTL_DEBUG_BACK,
310 imsg.hdr.peerid, &debug, sizeof(debug));
312 client_send_listenerp(IMSG_CTL_DEBUG_END,
313 imsg.hdr.peerid, NULL, 0);
314 break;
315 case IMSG_AUTH:
316 peerid = imsg.hdr.peerid;
317 if (auth)
318 fatalx("%s: IMSG_AUTH already done", __func__);
319 auth = 1;
321 if (IMSG_DATA_SIZE(imsg) != sizeof(rauth))
322 fatalx("mismatching size for IMSG_AUTH");
323 memcpy(&rauth, imsg.data, sizeof(rauth));
324 if (rauth.uname[sizeof(rauth.uname)-1] != '\0' ||
325 rauth.dir[sizeof(rauth.dir)-1] != '\0')
326 fatalx("IMSG_AUTH strings not NUL-terminated");
328 client_privdrop(rauth.uname, rauth.dir);
329 explicit_bzero(&rauth, sizeof(rauth));
330 break;
331 case IMSG_BUF:
332 case IMSG_BUF_CONT:
333 if (!auth)
334 fatalx("%s: can't handle messages before"
335 " doing the auth", __func__);
336 handle_message(&imsg, IMSG_DATA_SIZE(imsg),
337 imsg.hdr.type == IMSG_BUF_CONT);
338 break;
339 case IMSG_CONN_GONE:
340 log_debug("closing");
341 shut = 1;
342 break;
343 default:
344 log_debug("%s: unexpected imsg %d",
345 __func__, imsg.hdr.type);
346 break;
348 imsg_free(&imsg);
351 if (!shut)
352 imsg_event_add(iev);
353 else {
354 /* This pipe is dead. Remove its event handler. */
355 event_del(&iev->ev);
356 log_debug("pipe closed, shutting down...");
357 event_loopexit(NULL);
361 static void
362 client_privdrop(const char *username, const char *dir)
364 struct passwd *pw;
366 setproctitle("client %s", username);
368 if ((pw = getpwnam(username)) == NULL)
369 fatalx("getpwnam(%s) failed", username);
371 if (chroot(dir) == -1)
372 fatal("chroot");
373 if (chdir("/") == -1)
374 fatal("chdir(\"/\")");
376 if (setgroups(1, &pw->pw_gid) ||
377 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
378 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
379 fatal("can't drop privileges");
381 sandbox_client();
382 log_debug("client ready; user=%s dir=%s", username, dir);
384 if ((evb = evbuffer_new()) == NULL)
385 fatal("evbuffer_new");
388 static int
389 client_send_listenerp(int type, uint32_t peerid, const void *data, uint16_t len)
391 int ret;
393 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
394 data, len)) != -1)
395 imsg_event_add(iev_listener);
397 return ret;
400 static int
401 client_send_listener(int type, const void *data, uint16_t len)
403 return client_send_listenerp(type, peerid, data, len);
406 /* set qid fields from sb */
407 static void
408 qid_update_from_sb(struct qid *qid, struct stat *sb)
410 qid->path = sb->st_ino;
412 /*
413 * Theoretically (and hopefully!) this should be a 64 bit
414 * number. Unfortunately, 9P uses 32 bit timestamps.
415 */
416 qid->vers = sb->st_mtim.tv_sec;
418 if (S_ISREG(sb->st_mode))
419 qid->type = QTFILE;
420 else if (S_ISDIR(sb->st_mode))
421 qid->type = QTDIR;
422 else if (S_ISLNK(sb->st_mode))
423 qid->type = QTSYMLINK;
426 /* creates a qid given a fd */
427 static struct dir *
428 new_dir(int fd)
430 struct dir *dir;
432 if ((dir = calloc(1, sizeof(*dir))) == NULL)
433 return NULL;
435 dir->fd = fd;
436 STAILQ_INSERT_HEAD(&dirs, dir, entries);
437 return dir;
440 static struct dir *
441 dir_incref(struct dir *dir)
443 dir->refcount++;
444 return dir;
447 static void
448 dir_decref(struct dir *dir)
450 if (--dir->refcount > 0)
451 return;
453 STAILQ_REMOVE(&dirs, dir, dir, entries);
455 close(dir->fd);
456 free(dir);
459 static struct fid *
460 new_fid(struct dir *dir, uint32_t fid, const char *path, struct qid *qid)
462 struct fid *f;
463 struct qid q;
464 struct stat sb;
466 if (qid == NULL) {
467 if (fstatat(dir->fd, path, &sb, 0)) {
468 log_warn("fstatat(%s)", path);
469 return NULL;
471 qid_update_from_sb(&q, &sb);
472 qid = &q;
475 if ((f = calloc(1, sizeof(*f))) == NULL)
476 return NULL;
478 f->dir = dir_incref(dir);
479 f->fid = fid;
480 f->fd = -1;
482 strlcpy(f->fname, path, sizeof(f->fname));
484 memcpy(&f->qid, qid, sizeof(f->qid));
486 STAILQ_INSERT_HEAD(&fids, f, entries);
488 return f;
491 static struct fid *
492 fid_by_id(uint32_t fid)
494 struct fid *f;
496 STAILQ_FOREACH(f, &fids, entries) {
497 if (f->fid == fid)
498 return f;
501 return NULL;
504 static void
505 free_fid(struct fid *f)
507 int r;
509 if (f->fd != -1) {
510 if (f->d != NULL)
511 r = closedir(f->d);
512 else
513 r = close(f->fd);
515 if (r == -1)
516 fatal("can't close fid %d", f->fid);
518 if (f->evb != NULL)
519 evbuffer_free(f->evb);
521 /* try to honour ORCLOSE if requested */
522 if (f->iomode & O_CLOEXEC)
523 unlinkat(f->dir->fd, f->fname, 0);
526 dir_decref(f->dir);
528 STAILQ_REMOVE(&fids, f, fid, entries);
529 free(f);
532 static void
533 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
534 uint8_t **cnt)
536 size_t olen = len;
538 if (!NPREAD32("len", &hdr->len, &data, &len) ||
539 !NPREAD8("type", &hdr->type, &data, &len) ||
540 !NPREAD16("tag", &hdr->tag, &data, &len))
541 goto err;
543 if (olen != hdr->len)
544 goto err;
546 if (hdr->type < Tversion ||
547 hdr->type >= Tmax ||
548 hdr->type == Terror ||
549 (hdr->type & 0x1) != 0) /* cannot recv a R* */
550 goto err;
552 hdr->tag = le32toh(hdr->tag);
554 *cnt = (uint8_t *)data;
555 return;
557 err:
558 /* TODO: send a proper message to terminate the connection. */
559 fatalx("got invalid message");
562 static void
563 np_write16(struct evbuffer *e, uint16_t x)
565 x = htole16(x);
566 evbuffer_add(e, &x, sizeof(x));
569 static void
570 np_write32(struct evbuffer *e, uint32_t x)
572 x = htole32(x);
573 evbuffer_add(e, &x, sizeof(x));
576 static void
577 np_write64(struct evbuffer *e, uint64_t x)
579 x = htole64(x);
580 evbuffer_add(e, &x, sizeof(x));
583 static void
584 np_writebuf(struct evbuffer *e, size_t len, void *data)
586 evbuffer_add(e, data, len);
589 static void
590 np_header(uint32_t len, uint8_t type, uint16_t tag)
592 len += HEADERSIZE;
594 len = htole32(len);
595 tag = htole16(tag);
597 evbuffer_add(evb, &len, sizeof(len));
598 evbuffer_add(evb, &type, sizeof(type));
599 evbuffer_add(evb, &tag, sizeof(tag));
602 static void
603 np_string(struct evbuffer *e, uint16_t len, const char *str)
605 uint16_t l = len;
607 len = htole16(len);
608 evbuffer_add(e, &len, sizeof(len));
609 evbuffer_add(e, str, l);
612 static void
613 np_qid(struct evbuffer *e, struct qid *qid)
615 uint64_t path;
616 uint32_t vers;
618 path = htole64(qid->path);
619 vers = htole32(qid->vers);
621 evbuffer_add(e, &qid->type, sizeof(qid->type));
622 evbuffer_add(e, &vers, sizeof(vers));
623 evbuffer_add(e, &path, sizeof(path));
626 static void
627 do_send(void)
629 size_t len;
630 void *data;
632 len = EVBUFFER_LENGTH(evb);
633 data = EVBUFFER_DATA(evb);
635 #if DEBUG_PACKETS
636 hexdump("outgoing packet", data, len);
637 #endif
638 client_send_listener(IMSG_BUF, data, len);
639 evbuffer_drain(evb, len);
642 static void
643 np_version(uint16_t tag, uint32_t msize, const char *version)
645 uint16_t l;
647 l = strlen(version);
649 msize = htole32(msize);
651 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
652 evbuffer_add(evb, &msize, sizeof(msize));
653 np_string(evb, l, version);
654 do_send();
657 static void
658 np_attach(uint16_t tag, struct qid *qid)
660 np_header(QIDSIZE, Rattach, tag);
661 np_qid(evb, qid);
662 do_send();
665 static void
666 np_clunk(uint16_t tag)
668 np_header(0, Rclunk, tag);
669 do_send();
672 static void
673 np_flush(uint16_t tag)
675 np_header(0, Rflush, tag);
676 do_send();
679 static void
680 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
682 int i;
684 /* two bytes for the counter */
685 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
686 np_write16(evb, nwqid);
687 for (i = 0; i < nwqid; ++i)
688 np_qid(evb, wqid + i);
690 do_send();
693 static void
694 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
696 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
697 np_qid(evb, qid);
698 np_write32(evb, iounit);
699 do_send();
702 static void
703 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
705 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
706 np_qid(evb, qid);
707 np_write32(evb, iounit);
708 do_send();
711 static void
712 np_read(uint16_t tag, uint32_t count, void *data)
714 if (sizeof(count) + count + HEADERSIZE >= msize) {
715 np_error(tag, "Rread would overflow");
716 return;
719 np_header(sizeof(count) + count, Rread, tag);
720 np_write32(evb, count);
721 np_writebuf(evb, count, data);
722 do_send();
725 static void
726 np_write(uint16_t tag, uint32_t count)
728 np_header(sizeof(count), Rwrite, tag);
729 np_write32(evb, count);
730 do_send();
733 static void
734 np_stat(uint16_t tag, uint16_t count, void *data)
736 if (sizeof(count) + count + HEADERSIZE >= msize) {
737 np_error(tag, "Rstat would overflow");
738 return;
741 np_header(sizeof(count) + count, Rstat, tag);
742 np_write16(evb, count);
743 np_writebuf(evb, count, data);
744 do_send();
747 static void
748 np_wstat(uint16_t tag)
750 np_header(0, Rwstat, tag);
751 do_send();
754 static void
755 np_remove(uint16_t tag)
757 np_header(0, Rremove, tag);
758 do_send();
761 static void
762 np_error(uint16_t tag, const char *errstr)
764 uint16_t l;
766 l = strlen(errstr);
768 np_header(sizeof(l) + l, Rerror, tag);
769 np_string(evb, l, errstr);
770 do_send();
773 static void
774 np_errno(uint16_t tag)
776 int saved_errno;
777 char buf[NL_TEXTMAX] = {0};
779 saved_errno = errno;
781 strerror_r(errno, buf, sizeof(buf));
782 np_error(tag, buf);
784 errno = saved_errno;
787 static int
788 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
789 size_t *len)
791 if (*len < sizeof(*dst)) {
792 log_warnx("%s: wanted %zu bytes for the %s field but only "
793 "%zu are available.", t, sizeof(*dst), f, *len);
794 return 0;
797 memcpy(dst, *src, sizeof(*dst));
798 *src += sizeof(*dst);
799 *len -= sizeof(*dst);
801 return 1;
804 static int
805 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
806 size_t *len)
808 if (*len < sizeof(*dst)) {
809 log_warnx("%s: wanted %zu bytes for the %s field but only "
810 "%zu are available.", t, sizeof(*dst), f, *len);
811 return 0;
814 memcpy(dst, *src, sizeof(*dst));
815 *src += sizeof(*dst);
816 *len -= sizeof(*dst);
817 *dst = le16toh(*dst);
819 return 1;
822 static int
823 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
824 size_t *len)
826 if (*len < sizeof(*dst)) {
827 log_warnx("%s: wanted %zu bytes for the %s field but only "
828 "%zu are available.", t, sizeof(*dst), f, *len);
829 return 0;
832 memcpy(dst, *src, sizeof(*dst));
833 *src += sizeof(*dst);
834 *len -= sizeof(*dst);
835 *dst = le32toh(*dst);
837 return 1;
840 static int
841 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
842 size_t *len)
844 if (*len < sizeof(*dst)) {
845 log_warnx("%s: wanted %zu bytes for the %s field but only "
846 "%zu are available.", t, sizeof(*dst), f, *len);
847 return 0;
850 memcpy(dst, *src, sizeof(*dst));
851 *src += sizeof(*dst);
852 *len -= sizeof(*dst);
853 *dst = le64toh(*dst);
855 return 1;
858 static int
859 np_readstr(const char *t, const char *f, char *res, size_t reslen,
860 const uint8_t **src, size_t *len)
862 uint16_t sl;
863 char buf[32];
865 strlcpy(buf, f, sizeof(buf));
866 strlcat(buf, "-len", sizeof(buf));
868 if (!np_read16(t, buf, &sl, src, len))
869 return READSTRERR;
871 if (*len < sl) {
872 log_warnx("%s: wanted %d bytes for the %s field but only "
873 "%zu are available.", t, sl, f, *len);
874 return READSTRERR;
877 if (*len > reslen-1)
878 return READSTRTRUNC;
880 memcpy(res, *src, sl);
881 res[sl] = '\0';
882 *src += sl;
883 *len -= sl;
885 return 0;
888 static int
889 np_readst(const char *t, const char *f, struct np_stat *st,
890 char *name, size_t namelen, const uint8_t **src, size_t *len)
892 memset(st, 0, sizeof(*st));
894 /* len is sent twice! */
895 if (!np_read16(t, "stat len", &st->size, src, len) ||
896 !np_read16(t, "stat.size", &st->size, src, len) ||
897 !np_read16(t, "stat.type", &st->type, src, len) ||
898 !np_read32(t, "stat.dev", &st->dev, src, len) ||
899 !np_read64(t, "stat.qid.path", &st->qid.path, src, len) ||
900 !np_read32(t, "stat.qid.vers", &st->qid.vers, src, len) ||
901 !np_read8(t, "stat.qid.type", &st->qid.type, src, len) ||
902 !np_read32(t, "stat.mode", &st->mode, src, len) ||
903 !np_read32(t, "stat.atime", &st->atime, src, len) ||
904 !np_read32(t, "stat.mtime", &st->mtime, src, len) ||
905 !np_read64(t, "stat.length", &st->length, src, len))
906 return READSTRERR;
908 /*
909 * ignore everything but the name, we don't support
910 * changing those fields anyway
911 */
912 st->name = name;
913 return np_readstr(t, "stat.name", name, namelen, src, len);
916 static void
917 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
919 char *dot, version[32];
921 if (handshaked)
922 goto err;
924 /* msize[4] version[s] */
925 if (!NPREAD32("msize", &msize, &data, &len))
926 goto err;
928 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
929 case READSTRERR:
930 goto err;
931 case READSTRTRUNC:
932 log_warnx("9P version string too long, truncated");
933 np_version(hdr->tag, MSIZE9P, "unknown");
934 return;
937 if (len != 0)
938 goto err;
940 if ((dot = strchr(version, '.')) != NULL)
941 *dot = '\0';
943 if (strcmp(version, VERSION9P) != 0) {
944 log_warnx("unknown 9P version \"%s\"; want "VERSION9P,
945 version);
946 np_version(hdr->tag, MSIZE9P, "unknown");
947 return;
950 if (msize < MIN_MSIZE) {
951 log_warnx("msize too small: %"PRIu32"; want %d at least",
952 msize, MIN_MSIZE);
953 np_version(hdr->tag, MSIZE9P, "unknown");
954 return;
957 /* version matched */
958 handshaked = 1;
959 msize = MIN(msize, MSIZE9P);
960 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
961 np_version(hdr->tag, msize, VERSION9P);
962 return;
964 err:
965 client_send_listener(IMSG_CLOSE, NULL, 0);
966 client_shutdown();
969 static void
970 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
972 struct dir *dir;
973 struct fid *f;
974 uint32_t fid, afid;
975 int fd;
976 char aname[PATH_MAX];
978 /* fid[4] afid[4] uname[s] aname[s] */
980 if (!NPREAD32("fid", &fid, &data, &len) ||
981 !NPREAD32("afid", &afid, &data, &len))
982 goto err;
984 /* read the uname but don't actually use it */
985 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
986 case READSTRERR:
987 goto err;
988 case READSTRTRUNC:
989 np_error(hdr->tag, "name too long");
990 return;
993 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
994 case READSTRERR:
995 goto err;
996 case READSTRTRUNC:
997 np_error(hdr->tag, "name too long");
998 return;
1001 if (*aname == '\0')
1002 strlcpy(aname, "/", sizeof(aname));
1004 if (len != 0)
1005 goto err;
1007 if (fid_by_id(fid) != NULL || afid != NOFID) {
1008 np_error(hdr->tag, "invalid fid or afid");
1009 return;
1012 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
1013 goto fail;
1015 if ((dir = new_dir(fd)) == NULL)
1016 goto fail;
1018 log_debug("attached %s to %d", aname, fid);
1020 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
1021 dir_decref(dir);
1022 goto fail;
1025 np_attach(hdr->tag, &f->qid);
1026 return;
1028 fail:
1029 np_errno(hdr->tag);
1030 log_warn("failed to attach %s", aname);
1031 return;
1033 err:
1034 client_send_listener(IMSG_CLOSE, NULL, 0);
1035 client_shutdown();
1038 static void
1039 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1041 struct fid *f;
1042 uint32_t fid;
1044 /* fid[4] */
1045 if (!NPREAD32("fid", &fid, &data, &len) ||
1046 len != 0) {
1047 client_send_listener(IMSG_CLOSE, NULL, 0);
1048 client_shutdown();
1049 return;
1052 if ((f = fid_by_id(fid)) == NULL) {
1053 np_error(hdr->tag, "invalid fid");
1054 return;
1057 free_fid(f);
1058 np_clunk(hdr->tag);
1061 static void
1062 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1064 uint16_t oldtag;
1067 * We're doing only synchronous I/O. Tflush is implemented
1068 * only because it's illegal to reply with a Rerror.
1071 /* oldtag[2] */
1072 if (len != sizeof(oldtag)) {
1073 log_warnx("Tflush with the wrong size: got %zu want %zu",
1074 len, sizeof(oldtag));
1075 client_send_listener(IMSG_CLOSE, NULL, 0);
1076 client_shutdown();
1077 return;
1080 np_flush(hdr->tag);
1083 static void
1084 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1086 struct stat sb;
1087 struct dir *dir;
1088 struct qid wqid[MAXWELEM] = {0};
1089 struct fid *f, *nf;
1090 uint32_t fid, newfid;
1091 uint16_t nwname;
1092 int fd, oldfd, no, nwqid = 0;
1093 char wnam[PATH_MAX];
1095 if (!NPREAD32("fid", &fid, &data, &len) ||
1096 !NPREAD32("newfid", &newfid, &data, &len) ||
1097 !NPREAD16("nwname", &nwname, &data, &len))
1098 goto err;
1100 if (nwname > MAXWELEM) {
1101 log_warnx("Twalk: more than %d path elements: %d",
1102 MAXWELEM, nwname);
1103 goto err;
1106 if ((f = fid_by_id(fid)) == NULL) {
1107 np_error(hdr->tag, "invalid fid");
1108 return;
1111 if (f->fd != -1) {
1112 np_error(hdr->tag, "fid already opened for I/O");
1113 return;
1116 if (fid == newfid)
1117 nf = f;
1118 else if ((nf = fid_by_id(newfid)) != NULL) {
1119 np_error(hdr->tag, "newfid already in use");
1120 return;
1121 } else
1122 nf = NULL;
1124 /* special case: fid duplication */
1125 if (nwname == 0) {
1127 * TODO: should we forbid fids duplication when fid ==
1128 * newfid?
1130 if (nf == NULL &&
1131 (nf = new_fid(f->dir, newfid, f->fname, &f->qid)) == NULL)
1132 fatal("new_fid duplication");
1134 np_walk(hdr->tag, 0, NULL);
1135 return;
1138 if (!(f->qid.type & QTDIR)) {
1139 np_error(hdr->tag, "fid doesn't represent a directory");
1140 return;
1143 oldfd = f->dir->fd;
1145 for (nwqid = 0; nwqid < nwname; nwqid++) {
1146 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1147 case READSTRERR:
1148 goto err;
1149 case READSTRTRUNC:
1150 np_error(hdr->tag, "wname too long");
1151 return;
1154 if (*wnam == '\0' ||
1155 strchr(wnam, '/') != NULL ||
1156 !strcmp(wnam, ".")) {
1157 errno = EINVAL;
1158 goto cantopen;
1161 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1162 errno != ENOTDIR)
1163 goto cantopen;
1165 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1166 (fd != -1 && fstat(fd, &sb) == -1))
1167 goto cantopen;
1169 qid_update_from_sb(&wqid[nwqid], &sb);
1171 /* reached a file but we still have other components */
1172 if (fd == -1 && nwqid+1 < nwname)
1173 goto cantopen;
1175 /* reached the end and found a file */
1176 if (fd == -1 && nwqid+1 == nwname)
1177 continue;
1179 if (oldfd != f->dir->fd)
1180 close(oldfd);
1181 oldfd = fd;
1184 if (len != 0)
1185 goto err;
1188 * If fd is -1 we've reached a file, otherwise we've just
1189 * reached another directory. We must pay attention to what
1190 * file descriptor we use to create the dir, because if we've
1191 * reached a file and oldfd is f->dir->fd then we *must* share
1192 * the same dir (it was a walk of one path from a directory to a
1193 * file, otherwise fun is bound to happen as soon as the client
1194 * closes the fid for the directory but keeps the one for the
1195 * file.
1197 if (fd == -1 && oldfd == f->dir->fd)
1198 dir = f->dir;
1199 else if (fd == -1)
1200 dir = new_dir(oldfd);
1201 else
1202 dir = new_dir(fd);
1204 if (dir == NULL)
1205 fatal("new_dir");
1207 if (nf == NULL) {
1208 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1209 fatal("new fid");
1210 } else {
1211 /* update the dir */
1212 dir_decref(nf->dir);
1213 nf->dir = dir_incref(dir);
1216 np_walk(hdr->tag, nwqid, wqid);
1217 return;
1219 cantopen:
1220 if (oldfd != f->dir->fd)
1221 close(oldfd);
1222 no = errno;
1223 if (nwqid == 0)
1224 np_error(hdr->tag, strerror(no));
1225 else
1226 np_walk(hdr->tag, nwqid, wqid);
1227 return;
1229 err:
1230 client_send_listener(IMSG_CLOSE, NULL, 0);
1231 client_shutdown();
1234 static inline int
1235 npmode_to_unix(uint8_t mode, int *flags)
1237 switch (mode & 0x0F) {
1238 case KOREAD:
1239 *flags = O_RDONLY;
1240 break;
1241 case KOWRITE:
1242 *flags = O_WRONLY;
1243 break;
1244 case KORDWR:
1245 *flags = O_RDWR;
1246 break;
1247 case KOEXEC:
1248 log_warnx("tried to open something with KOEXEC");
1249 /* fallthrough */
1250 default:
1251 return -1;
1254 if (mode & KOTRUNC)
1255 *flags |= O_TRUNC;
1256 if (mode & KORCLOSE)
1257 *flags |= O_CLOEXEC;
1259 return 0;
1262 static void
1263 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1265 struct stat sb;
1266 struct qid qid;
1267 struct fid *f;
1268 uint32_t fid;
1269 uint8_t mode;
1270 const char *path;
1272 /* fid[4] mode[1] */
1273 if (!NPREAD32("fid", &fid, &data, &len) ||
1274 !NPREAD8("mode", &mode, &data, &len) ||
1275 len != 0) {
1276 client_send_listener(IMSG_CLOSE, NULL, 0);
1277 client_shutdown();
1278 return;
1281 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1282 np_error(hdr->tag, "invalid fid");
1283 return;
1286 if (npmode_to_unix(mode, &f->iomode) == -1) {
1287 np_error(hdr->tag, "invalid mode");
1288 return;
1291 path = f->fname;
1292 if (f->qid.type & QTDIR)
1293 path = ".";
1295 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1296 np_error(hdr->tag, strerror(errno));
1297 return;
1300 if (fstat(f->fd, &sb) == -1)
1301 fatal("fstat");
1303 if (S_ISDIR(sb.st_mode)) {
1304 if ((f->d = fdopendir(f->fd)) == NULL) {
1305 np_errno(hdr->tag);
1306 close(f->fd);
1307 f->fd = -1;
1308 return;
1311 if ((f->evb = evbuffer_new()) == NULL) {
1312 np_errno(hdr->tag);
1313 closedir(f->d);
1314 f->d = NULL;
1315 f->fd = -1;
1319 f->offset = 0;
1321 qid_update_from_sb(&qid, &sb);
1322 np_open(hdr->tag, &qid, sb.st_blksize);
1325 static void
1326 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1328 struct stat sb;
1329 struct qid qid;
1330 struct fid *f;
1331 uint32_t fid, perm;
1332 uint8_t mode;
1333 char name[PATH_MAX];
1335 /* fid[4] name[s] perm[4] mode[1] */
1336 if (!NPREAD32("fid", &fid, &data, &len))
1337 goto err;
1338 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1339 case READSTRERR:
1340 goto err;
1341 case READSTRTRUNC:
1342 np_error(hdr->tag, "name too long");
1343 return;
1345 if (!NPREAD32("perm", &perm, &data, &len) ||
1346 !NPREAD8("mode", &mode, &data, &len) ||
1347 len != 0)
1348 goto err;
1350 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1351 strchr(name, '/') != NULL) {
1352 np_error(hdr->tag, "invalid name");
1353 return;
1356 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1357 np_error(hdr->tag, "invalid fid");
1358 return;
1361 if (!(f->qid.type & QTDIR)) {
1362 np_error(hdr->tag, "fid doesn't identify a directory");
1363 return;
1366 if (npmode_to_unix(mode, &f->iomode) == -1) {
1367 np_error(hdr->tag, "invalid mode");
1368 return;
1371 if (f->iomode & O_RDONLY) {
1372 np_error(hdr->tag, "can't create a read-only file");
1373 return;
1376 /* TODO: parse the mode */
1378 if (perm & 0x80000000) {
1379 /* create a directory */
1380 f->fd = mkdirat(f->dir->fd, name, 0755);
1381 } else {
1382 /* create a file */
1383 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1384 0644);
1387 if (f->fd == -1) {
1388 np_errno(hdr->tag);
1389 return;
1392 if (fstat(f->fd, &sb) == -1)
1393 fatal("fstat");
1395 if (S_ISDIR(sb.st_mode)) {
1396 if ((f->d = fdopendir(f->fd)) == NULL) {
1397 np_errno(hdr->tag);
1398 close(f->fd);
1399 f->fd = -1;
1400 return;
1403 if ((f->evb = evbuffer_new()) == NULL) {
1404 np_errno(hdr->tag);
1405 closedir(f->d);
1406 f->d = NULL;
1407 f->fd = -1;
1411 f->offset = 0;
1413 qid_update_from_sb(&qid, &sb);
1414 np_create(hdr->tag, &qid, sb.st_blksize);
1416 return;
1418 err:
1419 client_send_listener(IMSG_CLOSE, NULL, 0);
1420 client_shutdown();
1423 static inline int
1424 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1426 struct qid qid;
1427 const char *uid, *gid, *muid;
1428 size_t tot;
1429 uint32_t mode;
1430 uint16_t namlen, uidlen, gidlen, ulen;
1432 qid_update_from_sb(&qid, sb);
1434 /* TODO: fill these fields */
1435 uid = "";
1436 gid = "";
1437 muid = "";
1439 namlen = strlen(fname);
1440 uidlen = strlen(uid);
1441 gidlen = strlen(gid);
1442 ulen = strlen(muid);
1444 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1445 if (tot > UINT16_MAX) {
1446 log_warnx("stat info for dir entry %s would overflow",
1447 fname);
1448 return -1;
1451 mode = sb->st_mode & 0xFFFF;
1452 if (qid.type & QTDIR)
1453 mode |= 0x80000000;
1455 np_write16(evb, tot); /* size[2] */
1456 np_write16(evb, sb->st_rdev); /* type[2] */
1457 np_write32(evb, sb->st_dev); /* dev[4] */
1458 np_qid(evb, &qid); /* qid[13] */
1459 np_write32(evb, mode); /* mode[4] */
1460 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1461 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1463 /* special case: directories have size 0 */
1464 if (qid.type & QTDIR)
1465 np_write64(evb, 0);
1466 else
1467 np_write64(evb, sb->st_size); /* length[8] */
1469 np_string(evb, namlen, fname); /* name[s] */
1470 np_string(evb, uidlen, uid); /* uid[s] */
1471 np_string(evb, gidlen, gid); /* gid[s] */
1472 np_string(evb, ulen, muid); /* muid[s] */
1474 return 0;
1477 static void
1478 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1480 struct fid *f;
1481 ssize_t r;
1482 size_t howmuch;
1483 uint64_t off;
1484 uint32_t fid, count;
1485 char buf[2048];
1487 /* fid[4] offset[8] count[4] */
1488 if (!NPREAD32("fid", &fid, &data, &len) ||
1489 !NPREAD64("offset", &off, &data, &len) ||
1490 !NPREAD32("count", &count, &data, &len) ||
1491 len != 0) {
1492 client_send_listener(IMSG_CLOSE, NULL, 0);
1493 client_shutdown();
1494 return;
1497 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1498 np_error(hdr->tag, "invalid fid");
1499 return;
1502 if (TYPE_OVERFLOW(off_t, off)) {
1503 log_warnx("unexpected off_t size");
1504 np_error(hdr->tag, "invalid offset");
1505 return;
1508 if (f->d == NULL) {
1509 /* read a file */
1510 howmuch = MIN(sizeof(buf), count);
1511 r = pread(f->fd, buf, howmuch, (off_t)off);
1512 if (r == -1)
1513 np_errno(hdr->tag);
1514 else
1515 np_read(hdr->tag, r, buf);
1516 } else {
1517 if (off == 0 && f->offset != 0) {
1518 rewinddir(f->d);
1519 f->offset = 0;
1520 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1523 if (off != f->offset) {
1524 np_error(hdr->tag, "can't seek in directories");
1525 return;
1528 while (EVBUFFER_LENGTH(f->evb) < count) {
1529 struct dirent *d;
1530 struct stat sb;
1532 if ((d = readdir(f->d)) == NULL)
1533 break;
1534 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1535 continue;
1536 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1537 warn("fstatat");
1538 continue;
1540 serialize_stat(d->d_name, &sb, f->evb);
1543 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1544 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1545 evbuffer_drain(f->evb, count);
1547 f->offset += count;
1551 static void
1552 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len,
1553 struct fid **writefid, off_t *writepos, size_t *writeleft, int *writeskip)
1555 struct fid *f;
1556 ssize_t r;
1557 uint64_t off;
1558 uint32_t fid, count;
1560 /* fid[4] offset[8] count[4] data[count] */
1561 if (!NPREAD32("fid", &fid, &data, &len) ||
1562 !NPREAD64("off", &off, &data, &len) ||
1563 !NPREAD32("count", &count, &data, &len) ||
1564 count < len) {
1565 client_send_listener(IMSG_CLOSE, NULL, 0);
1566 client_shutdown();
1567 return;
1570 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1571 *writeskip = 1;
1572 np_error(hdr->tag, "invalid fid");
1573 return;
1576 if (!(f->iomode & O_WRONLY) &&
1577 !(f->iomode & O_RDWR)) {
1578 *writeskip = 1;
1579 np_error(hdr->tag, "fid not opened for writing");
1580 return;
1583 if (TYPE_OVERFLOW(off_t, off)) {
1584 *writeskip = 1;
1585 log_warnx("unexpected off_t size");
1586 np_error(hdr->tag, "invalid offset");
1587 return;
1590 if ((r = pwrite(f->fd, data, len, off)) == -1) {
1591 *writeskip = 1;
1592 np_errno(hdr->tag);
1593 } else if (count == len)
1594 np_write(hdr->tag, r);
1596 /* account for a continuated write */
1597 if (count > len) {
1598 *writefid = f;
1599 *writepos = off + len;
1600 *writeleft = count - len;
1601 *writeskip = 0;
1605 static void
1606 twrite_cont(struct fid *f, off_t *writepos, size_t *writeleft, int *writeskip,
1607 uint16_t tag, const uint8_t *data, size_t len)
1609 ssize_t r;
1611 if (len > *writeleft) {
1612 client_send_listener(IMSG_CLOSE, NULL, 0);
1613 client_shutdown();
1614 return;
1617 if ((r = pwrite(f->fd, data, len, *writepos)) == -1) {
1618 *writeskip = 1;
1619 np_errno(tag);
1620 return;
1623 *writeleft -= len;
1624 *writepos += len;
1626 if (*writeleft == 0)
1627 np_write(tag, r);
1630 static void
1631 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1633 struct evbuffer *evb;
1634 struct stat sb;
1635 struct fid *f;
1636 int r;
1637 uint32_t fid;
1639 /* fid[4] */
1640 if (!NPREAD32("fid", &fid, &data, &len) ||
1641 len != 0) {
1642 client_send_listener(IMSG_CLOSE, NULL, 0);
1643 client_shutdown();
1644 return;
1648 * plan9' stat(9P) is not clear on whether the stat is allowed
1649 * on opened fids or not. We're allowing stat regardless of the
1650 * status of the fid.
1653 if ((f = fid_by_id(fid)) == NULL) {
1654 np_error(hdr->tag, "invalid fid");
1655 return;
1658 if ((evb = evbuffer_new()) == NULL)
1659 fatal("evbuffer_new");
1661 if (f->fd != -1)
1662 r = fstat(f->fd, &sb);
1663 else if (f->qid.type & QTDIR)
1664 r = fstat(f->dir->fd, &sb);
1665 else
1666 r = fstatat(f->dir->fd, f->fname, &sb, 0);
1668 if (r == -1) {
1669 np_errno(hdr->tag);
1670 evbuffer_free(evb);
1671 return;
1674 if (serialize_stat(f->fname, &sb, evb) == -1)
1675 np_error(hdr->tag, "stat would overflow");
1676 else
1677 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1678 evbuffer_free(evb);
1681 static void
1682 twstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1684 struct timespec times[2];
1685 struct np_stat st;
1686 struct fid *f;
1687 int r;
1688 uint32_t fid;
1689 char name[PATH_MAX];
1691 /* fid[4] stat[n] */
1692 if (!NPREAD32("fid", &fid, &data, &len))
1693 goto err;
1695 switch (NPREADST("stat", &st, name, sizeof(name), &data, &len)) {
1696 case READSTRERR:
1697 goto err;
1698 case READSTRTRUNC:
1699 log_warnx("wstat new name would overflow");
1700 np_error(hdr->tag, "new name too long");
1701 return;
1705 * We skip the reading of some fields voluntarily because we
1706 * don't support chown, so len will always be > 0!
1708 #ifdef notyet
1709 if (len != 0)
1710 goto err;
1711 #endif
1713 if ((f = fid_by_id(fid)) == NULL) {
1714 np_error(hdr->tag, "invalid fid");
1715 return;
1719 * 9P wants these edits to be done in an atomic fashion,
1720 * something that I don't think it's possible on UNIX without
1721 * some special kernel help. Changing atime or mtime,
1722 * permissions, or rename the file are different syscalls.
1724 * Also, silently ignore stuff we can't/don't want to modify.
1727 /* change the permissions */
1728 if (st.mode != (uint32_t)-1) {
1729 mode_t m = st.mode & 0x7FF; /* silently truncate higer bits */
1730 if (f->fd != -1)
1731 r = fchmod(f->fd, m);
1732 else
1733 r = fchmodat(f->dir->fd, f->fname, m, 0);
1735 if (r == -1) {
1736 np_errno(hdr->tag);
1737 return;
1741 /* change the atime/mtime of the fid, opened or not */
1742 if (st.atime != (uint32_t)-1 || st.mtime != (uint32_t)-1) {
1743 times[0].tv_nsec = UTIME_OMIT;
1744 times[1].tv_nsec = UTIME_OMIT;
1746 if (st.atime != (uint32_t)-1) {
1747 times[0].tv_sec = st.atime;
1748 times[0].tv_nsec = 0;
1750 if (st.mtime != (uint32_t)-1) {
1751 times[1].tv_sec = st.mtime;
1752 times[1].tv_nsec = 0;
1755 if (f->fd != -1)
1756 r = futimens(f->fd, times);
1757 else
1758 r = utimensat(f->dir->fd, f->fname, times, 0);
1760 if (r == -1) {
1761 np_errno(hdr->tag);
1762 return;
1766 /* truncate */
1767 if (st.length != (uint64_t)-1) {
1768 if (f->fd == -1) {
1769 np_error(hdr->tag, "can't truncate a non-opened fid");
1770 return;
1773 if (f->qid.type & QTDIR && st.length != 0) {
1774 np_error(hdr->tag, "can't truncate directories");
1775 return;
1778 if (TYPE_OVERFLOW(off_t, st.length)) {
1779 log_warnx("truncate request overflows off_t: %"PRIu64,
1780 st.length);
1781 np_error(hdr->tag, "length overflows");
1782 return;
1785 if (f->qid.type == 0 &&
1786 ftruncate(f->fd, st.length) == -1) {
1787 np_errno(hdr->tag);
1788 return;
1792 /* rename (change the name entry) */
1793 if (*st.name != '\0') {
1794 struct stat sb;
1795 const char *newname;
1798 * XXX: 9P requires that we disallow changing the name
1799 * to that of an existing file. We can't do that
1800 * atomically (rename is happy about stealing names)
1801 * so this is just a best effort.
1803 if (fstatat(f->dir->fd, st.name, &sb, 0) == -1 &&
1804 errno != ENOENT) {
1805 np_error(hdr->tag, "target file exists");
1806 return;
1809 r = renameat(f->dir->fd, f->fname, f->dir->fd, st.name);
1810 if (r == -1) {
1811 np_errno(hdr->tag);
1812 return;
1815 /* fix the fid so it points to the new file */
1817 if ((newname = strchr(st.name, '/')) != NULL)
1818 newname++; /* skip / */
1819 else
1820 newname = st.name;
1821 strlcpy(f->fname, newname, sizeof(f->fname));
1823 if (strchr(st.name, '/') != NULL) {
1824 struct dir *dir;
1825 char *dname;
1826 int fd;
1828 dname = dirname(st.name);
1829 fd = openat(f->dir->fd, dname, O_RDONLY|O_DIRECTORY);
1830 if (fd == -1) {
1831 np_errno(hdr->tag);
1832 free_fid(f);
1833 return;
1836 if ((dir = new_dir(fd)) == NULL) {
1837 np_errno(hdr->tag);
1838 free_fid(f);
1839 return;
1842 dir_decref(f->dir);
1843 f->dir = dir_incref(dir);
1847 np_wstat(hdr->tag);
1848 return;
1850 err:
1851 client_send_listener(IMSG_CLOSE, NULL, 0);
1852 client_shutdown();
1855 static void
1856 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1858 struct fid *f;
1859 uint32_t fid;
1860 int r;
1861 char dirpath[PATH_MAX + 3];
1863 /* fid[4] */
1864 if (!NPREAD32("fid", &fid, &data, &len) ||
1865 len != 0) {
1866 client_send_listener(IMSG_CLOSE, NULL, 0);
1867 client_shutdown();
1868 return;
1871 if ((f = fid_by_id(fid)) == NULL) {
1872 np_error(hdr->tag, "invalid fid");
1873 return;
1876 if (f->qid.type & QTDIR) { /* directory */
1877 strlcpy(dirpath, "../", sizeof(dirpath));
1878 strlcat(dirpath, f->fname, sizeof(dirpath));
1879 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1880 } else /* file */
1881 r = unlinkat(f->dir->fd, f->fname, 0);
1883 if (r == -1)
1884 np_errno(hdr->tag);
1885 else
1886 np_remove(hdr->tag);
1888 free_fid(f);
1891 static void
1892 handle_message(struct imsg *imsg, size_t len, int cont)
1894 static struct fid *writefid;
1895 static off_t writepos;
1896 static size_t writeleft;
1897 static int writeskip;
1898 static uint16_t writetag;
1899 struct msg {
1900 uint8_t type;
1901 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1902 } msgs[] = {
1903 {Tversion, tversion},
1904 {Tattach, tattach},
1905 {Tclunk, tclunk},
1906 {Tflush, tflush},
1907 {Twalk, twalk},
1908 {Topen, topen},
1909 {Tcreate, tcreate},
1910 {Tread, tread},
1911 /* {Twrite, twrite}, */
1912 {Tstat, tstat},
1913 {Twstat, twstat},
1914 {Tremove, tremove},
1916 struct np_msg_header hdr;
1917 size_t i;
1918 uint8_t *data;
1920 #if DEBUG_PACKETS
1921 hexdump("incoming packet", imsg->data, len);
1922 #endif
1925 * Twrite is special and can be "continued" to allow writing
1926 * more than what the imsg framework would allow us to.
1928 if (writeleft > 0 && !cont) {
1929 log_warnx("received a non continuation message when still "
1930 "missed %zu bytes to write", writeleft);
1931 client_send_listener(IMSG_CLOSE, NULL, 0);
1932 client_shutdown();
1933 return;
1936 if (cont) {
1937 if (writeskip)
1938 return;
1940 if (writefid == NULL) {
1941 log_warnx("received a continuation message without "
1942 "seeing a Twrite");
1943 client_send_listener(IMSG_CLOSE, NULL, 0);
1944 client_shutdown();
1945 return;
1948 log_warnx("continuing...");
1949 twrite_cont(writefid, &writepos, &writeleft, &writeskip,
1950 writetag, imsg->data, len);
1951 return;
1954 writefid = NULL;
1955 writepos = -1;
1956 writeleft = 0;
1957 writeskip = 0;
1959 parse_message(imsg->data, len, &hdr, &data);
1960 len -= HEADERSIZE;
1962 log_debug("got request: len=%d type=%d[%s] tag=%d",
1963 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1965 if (!handshaked && hdr.type != Tversion) {
1966 client_send_listener(IMSG_CLOSE, NULL, 0);
1967 client_shutdown();
1968 return;
1971 if (hdr.type == Twrite) {
1972 writetag = hdr.tag;
1973 twrite(&hdr, data, len, &writefid, &writepos, &writeleft,
1974 &writeskip);
1975 return;
1978 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1979 if (msgs[i].type != hdr.type)
1980 continue;
1982 msgs[i].fn(&hdr, data, len);
1983 return;
1986 np_error(hdr.tag, "Not supported.");