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 * XXX: atm is difficult to accept messages bigger than MAX_IMSGSIZE
47 * minus IMSG_HEADER_SIZE, we need something to split messages into
48 * chunks and receive them one by the other.
49 *
50 * CLIENT_MSIZE is thus the maximum message size we can handle now.
51 */
52 #define CLIENT_MSIZE (MAX_IMSGSIZE - IMSG_HEADER_SIZE)
54 #define DEBUG_PACKETS 0
56 /* straight outta /src/usr.bin/ssh/scp.c */
57 #define TYPE_OVERFLOW(type, val) \
58 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
59 (sizeof(type) == 8 && (val) > INT64_MAX) || \
60 (sizeof(type) != 4 && sizeof(type) != 8))
62 STAILQ_HEAD(dirhead, dir) dirs;
63 struct dir {
64 int refcount;
65 int fd;
66 STAILQ_ENTRY(dir) entries;
67 };
69 STAILQ_HEAD(fidhead, fid) fids;
70 struct fid {
71 uint32_t fid;
73 char fname[NAME_MAX];
75 /*
76 * the flags passed to open(2). O_CLOEXEC means ORCLOSE, that
77 * is to unlink the file upon Tclunk.
78 */
79 int iomode;
81 /*
82 * if fd is not -1 this fid was opened, fd represents its
83 * file descriptor and iomode the flags passed to open(2).
84 */
85 int fd;
86 DIR *d;
87 struct evbuffer *evb;
89 /*
90 * expected offset for Tread against a directory.
91 */
92 uint64_t offset;
94 struct qid qid;
95 struct dir *dir;
96 STAILQ_ENTRY(fid) entries;
97 };
99 static struct imsgev *iev_listener;
100 static struct evbuffer *evb;
101 static uint32_t peerid;
103 static int handshaked;
104 uint32_t msize;
106 static __dead void client_shutdown(void);
107 static void client_sig_handler(int, short, void *);
108 static void client_dispatch_listener(int, short, void *);
109 static void client_privdrop(const char *, const char *);
111 static int client_send_listenerp(int, uint32_t, const void *, uint16_t);
112 static int client_send_listener(int, const void *, uint16_t);
114 static void qid_update_from_sb(struct qid *, struct stat *);
116 static struct dir *new_dir(int);
117 static struct dir *dir_incref(struct dir *);
118 static void dir_decref(struct dir *);
120 static struct fid *new_fid(struct dir *, uint32_t, const char *, struct qid *);
121 static struct fid *fid_by_id(uint32_t);
122 static void free_fid(struct fid *);
124 static void parse_message(const uint8_t *, size_t,
125 struct np_msg_header *, uint8_t **);
127 static void np_write16(struct evbuffer *, uint16_t);
128 static void np_write32(struct evbuffer *, uint32_t);
129 static void np_write64(struct evbuffer *, uint64_t);
130 static void np_header(uint32_t, uint8_t, uint16_t);
131 static void np_string(struct evbuffer *, uint16_t, const char *);
132 static void np_qid(struct evbuffer *, struct qid *);
133 static void do_send(void);
135 static void np_version(uint16_t, uint32_t, const char *);
136 static void np_attach(uint16_t, struct qid *);
137 static void np_clunk(uint16_t);
138 static void np_flush(uint16_t);
139 static void np_walk(uint16_t, int, struct qid *);
140 static void np_open(uint16_t, struct qid *, uint32_t);
141 static void np_create(uint16_t, struct qid *, uint32_t);
142 static void np_read(uint16_t, uint32_t, void *);
143 static void np_write(uint16_t, uint32_t);
144 static void np_stat(uint16_t, uint16_t, void *);
145 static void np_wstat(uint16_t);
146 static void np_remove(uint16_t);
147 static void np_error(uint16_t, const char *);
148 static void np_errno(uint16_t);
150 static int np_read8(const char *, const char *, uint8_t *,
151 const uint8_t **, size_t *);
152 static int np_read16(const char *, const char *, uint16_t *,
153 const uint8_t **, size_t *);
154 static int np_read32(const char *, const char *, uint32_t *,
155 const uint8_t **, size_t *);
156 static int np_read64(const char *, const char *, uint64_t *,
157 const uint8_t **, size_t *);
159 #define READSTRERR -1
160 #define READSTRTRUNC -2
161 static int np_readstr(const char *, const char *, char *, size_t,
162 const uint8_t **, size_t *);
164 static int np_readst(const char *, const char *, struct np_stat *,
165 char *, size_t, const uint8_t **, size_t *);
167 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
168 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
169 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
170 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
172 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
174 #define NPREADST(f, dst, n, nl, src, len) np_readst(__func__, f, dst, n, nl, src, len)
176 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
177 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
178 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
179 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
180 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
181 static void topen(struct np_msg_header *, const uint8_t *, size_t);
182 static void tcreate(struct np_msg_header *, const uint8_t *, size_t);
183 static void tread(struct np_msg_header *, const uint8_t *, size_t);
184 static void twrite(struct np_msg_header *, const uint8_t *, size_t);
185 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
186 static void twstat(struct np_msg_header *, const uint8_t *, size_t);
187 static void tremove(struct np_msg_header *, const uint8_t *, size_t);
188 static void handle_message(struct imsg *, size_t);
190 __dead void
191 client(int debug, int verbose)
193 struct event ev_sigint, ev_sigterm;
195 log_init(debug, LOG_DAEMON);
196 log_setverbose(verbose);
198 setproctitle("client");
199 log_procinit("client");
201 log_debug("warming up");
203 event_init();
205 /* Setup signal handlers */
206 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
207 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
209 signal_add(&ev_sigint, NULL);
210 signal_add(&ev_sigterm, NULL);
212 signal(SIGPIPE, SIG_IGN);
213 signal(SIGHUP, SIG_IGN);
215 /* Setup pipe and event handler to the listener process */
216 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
217 fatal(NULL);
219 imsg_init(&iev_listener->ibuf, 3);
220 iev_listener->handler = client_dispatch_listener;
222 /* Setup event handlers. */
223 iev_listener->events = EV_READ;
224 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
225 iev_listener->events, iev_listener->handler, iev_listener);
226 event_add(&iev_listener->ev, NULL);
228 event_dispatch();
229 client_shutdown();
232 static __dead void
233 client_shutdown(void)
235 if (evb != NULL)
236 evbuffer_free(evb);
238 msgbuf_clear(&iev_listener->ibuf.w);
239 close(iev_listener->ibuf.fd);
241 free(iev_listener);
243 log_debug("client exiting");
244 exit(0);
247 static void
248 client_sig_handler(int sig, short event, void *d)
250 /*
251 * Normal signal handler rules don't apply because libevent
252 * decouples for us.
253 */
255 switch (sig) {
256 case SIGINT:
257 case SIGTERM:
258 client_shutdown();
259 default:
260 fatalx("unexpected signal %d", sig);
264 static void
265 client_dispatch_listener(int fd, short event, void *d)
267 static int auth = 0;
268 struct kd_auth_proc rauth;
269 struct kd_debug_info debug;
270 struct fid *f;
271 struct imsg imsg;
272 struct imsgev *iev = d;
273 struct imsgbuf *ibuf;
274 ssize_t n;
275 int shut = 0;
277 ibuf = &iev->ibuf;
279 if (event & EV_READ) {
280 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
281 fatal("imsg_read error");
282 if (n == 0) /* Connection closed */
283 shut = 1;
285 if (event & EV_WRITE) {
286 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
287 fatal("msgbuf_write");
288 if (n == 0) /* Connection closed */
289 shut = 1;
292 for (;;) {
293 if ((n = imsg_get(ibuf, &imsg)) == -1)
294 fatal("%s: imsg_get error", __func__);
295 if (n == 0) /* No more messages. */
296 break;
298 switch (imsg.hdr.type) {
299 case IMSG_CTL_LOG_VERBOSE:
300 if (IMSG_DATA_SIZE(imsg) != sizeof(verbose))
301 fatalx("%s: IMSG_CTL_LOG_VERBOSE wrong size",
302 __func__);
303 memcpy(&verbose, imsg.data, sizeof(verbose));
304 log_setverbose(verbose);
305 break;
306 case IMSG_CTL_DEBUG:
307 STAILQ_FOREACH(f, &fids, entries) {
308 memset(&debug, 0, sizeof(debug));
309 debug.fid = f->fid;
310 strlcpy(debug.path, f->fname,
311 sizeof(debug.path));
312 client_send_listenerp(IMSG_CTL_DEBUG_BACK,
313 imsg.hdr.peerid, &debug, sizeof(debug));
315 client_send_listenerp(IMSG_CTL_DEBUG_END,
316 imsg.hdr.peerid, NULL, 0);
317 break;
318 case IMSG_AUTH:
319 peerid = imsg.hdr.peerid;
320 if (auth)
321 fatalx("%s: IMSG_AUTH already done", __func__);
322 auth = 1;
324 if (IMSG_DATA_SIZE(imsg) != sizeof(rauth))
325 fatalx("mismatching size for IMSG_AUTH");
326 memcpy(&rauth, imsg.data, sizeof(rauth));
327 if (rauth.uname[sizeof(rauth.uname)-1] != '\0' ||
328 rauth.dir[sizeof(rauth.dir)-1] != '\0')
329 fatalx("IMSG_AUTH strings not NUL-terminated");
331 client_privdrop(rauth.uname, rauth.dir);
332 explicit_bzero(&rauth, sizeof(rauth));
333 break;
334 case IMSG_BUF:
335 if (!auth)
336 fatalx("%s: can't handle messages before"
337 " doing the auth", __func__);
338 handle_message(&imsg, IMSG_DATA_SIZE(imsg));
339 break;
340 case IMSG_CONN_GONE:
341 log_debug("closing");
342 shut = 1;
343 break;
344 default:
345 log_debug("%s: unexpected imsg %d",
346 __func__, imsg.hdr.type);
347 break;
349 imsg_free(&imsg);
352 if (!shut)
353 imsg_event_add(iev);
354 else {
355 /* This pipe is dead. Remove its event handler. */
356 event_del(&iev->ev);
357 log_debug("pipe closed, shutting down...");
358 event_loopexit(NULL);
362 static void
363 client_privdrop(const char *username, const char *dir)
365 struct passwd *pw;
367 setproctitle("client %s", username);
369 if ((pw = getpwnam(username)) == NULL)
370 fatalx("getpwnam(%s) failed", username);
372 if (chroot(dir) == -1)
373 fatal("chroot");
374 if (chdir("/") == -1)
375 fatal("chdir(\"/\")");
377 if (setgroups(1, &pw->pw_gid) ||
378 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
379 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
380 fatal("can't drop privileges");
382 sandbox_client();
383 log_debug("client ready; user=%s dir=%s", username, dir);
385 if ((evb = evbuffer_new()) == NULL)
386 fatal("evbuffer_new");
389 static int
390 client_send_listenerp(int type, uint32_t peerid, const void *data, uint16_t len)
392 int ret;
394 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
395 data, len)) != -1)
396 imsg_event_add(iev_listener);
398 return ret;
401 static int
402 client_send_listener(int type, const void *data, uint16_t len)
404 return client_send_listenerp(type, peerid, data, len);
407 /* set qid fields from sb */
408 static void
409 qid_update_from_sb(struct qid *qid, struct stat *sb)
411 qid->path = sb->st_ino;
413 /*
414 * Theoretically (and hopefully!) this should be a 64 bit
415 * number. Unfortunately, 9P uses 32 bit timestamps.
416 */
417 qid->vers = sb->st_mtim.tv_sec;
419 if (S_ISREG(sb->st_mode))
420 qid->type = QTFILE;
421 else if (S_ISDIR(sb->st_mode))
422 qid->type = QTDIR;
423 else if (S_ISLNK(sb->st_mode))
424 qid->type = QTSYMLINK;
427 /* creates a qid given a fd */
428 static struct dir *
429 new_dir(int fd)
431 struct dir *dir;
433 if ((dir = calloc(1, sizeof(*dir))) == NULL)
434 return NULL;
436 dir->fd = fd;
437 STAILQ_INSERT_HEAD(&dirs, dir, entries);
438 return dir;
441 static struct dir *
442 dir_incref(struct dir *dir)
444 dir->refcount++;
445 return dir;
448 static void
449 dir_decref(struct dir *dir)
451 if (--dir->refcount > 0)
452 return;
454 STAILQ_REMOVE(&dirs, dir, dir, entries);
456 close(dir->fd);
457 free(dir);
460 static struct fid *
461 new_fid(struct dir *dir, uint32_t fid, const char *path, struct qid *qid)
463 struct fid *f;
464 struct qid q;
465 struct stat sb;
467 if (qid == NULL) {
468 if (fstatat(dir->fd, path, &sb, 0)) {
469 log_warn("fstatat(%s)", path);
470 return NULL;
472 qid_update_from_sb(&q, &sb);
473 qid = &q;
476 if ((f = calloc(1, sizeof(*f))) == NULL)
477 return NULL;
479 f->dir = dir_incref(dir);
480 f->fid = fid;
481 f->fd = -1;
483 strlcpy(f->fname, path, sizeof(f->fname));
485 memcpy(&f->qid, qid, sizeof(f->qid));
487 STAILQ_INSERT_HEAD(&fids, f, entries);
489 return f;
492 static struct fid *
493 fid_by_id(uint32_t fid)
495 struct fid *f;
497 STAILQ_FOREACH(f, &fids, entries) {
498 if (f->fid == fid)
499 return f;
502 return NULL;
505 static void
506 free_fid(struct fid *f)
508 int r;
510 if (f->fd != -1) {
511 if (f->d != NULL)
512 r = closedir(f->d);
513 else
514 r = close(f->fd);
516 if (r == -1)
517 fatal("can't close fid %d", f->fid);
519 if (f->evb != NULL)
520 evbuffer_free(f->evb);
522 /* try to honour ORCLOSE if requested */
523 if (f->iomode & O_CLOEXEC)
524 unlinkat(f->dir->fd, f->fname, 0);
527 dir_decref(f->dir);
529 STAILQ_REMOVE(&fids, f, fid, entries);
530 free(f);
533 static void
534 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
535 uint8_t **cnt)
537 size_t olen = len;
539 if (!NPREAD32("len", &hdr->len, &data, &len) ||
540 !NPREAD8("type", &hdr->type, &data, &len) ||
541 !NPREAD16("tag", &hdr->tag, &data, &len))
542 goto err;
544 if (olen != hdr->len)
545 goto err;
547 if (hdr->type < Tversion ||
548 hdr->type >= Tmax ||
549 hdr->type == Terror ||
550 (hdr->type & 0x1) != 0) /* cannot recv a R* */
551 goto err;
553 hdr->tag = le32toh(hdr->tag);
555 *cnt = (uint8_t *)data;
556 return;
558 err:
559 /* TODO: send a proper message to terminate the connection. */
560 fatalx("got invalid message");
563 static void
564 np_write16(struct evbuffer *e, uint16_t x)
566 x = htole16(x);
567 evbuffer_add(e, &x, sizeof(x));
570 static void
571 np_write32(struct evbuffer *e, uint32_t x)
573 x = htole32(x);
574 evbuffer_add(e, &x, sizeof(x));
577 static void
578 np_write64(struct evbuffer *e, uint64_t x)
580 x = htole64(x);
581 evbuffer_add(e, &x, sizeof(x));
584 static void
585 np_writebuf(struct evbuffer *e, size_t len, void *data)
587 evbuffer_add(e, data, len);
590 static void
591 np_header(uint32_t len, uint8_t type, uint16_t tag)
593 len += HEADERSIZE;
595 len = htole32(len);
596 tag = htole16(tag);
598 evbuffer_add(evb, &len, sizeof(len));
599 evbuffer_add(evb, &type, sizeof(type));
600 evbuffer_add(evb, &tag, sizeof(tag));
603 static void
604 np_string(struct evbuffer *e, uint16_t len, const char *str)
606 uint16_t l = len;
608 len = htole16(len);
609 evbuffer_add(e, &len, sizeof(len));
610 evbuffer_add(e, str, l);
613 static void
614 np_qid(struct evbuffer *e, struct qid *qid)
616 uint64_t path;
617 uint32_t vers;
619 path = htole64(qid->path);
620 vers = htole32(qid->vers);
622 evbuffer_add(e, &qid->type, sizeof(qid->type));
623 evbuffer_add(e, &vers, sizeof(vers));
624 evbuffer_add(e, &path, sizeof(path));
627 static void
628 do_send(void)
630 size_t len;
631 void *data;
633 len = EVBUFFER_LENGTH(evb);
634 data = EVBUFFER_DATA(evb);
636 #if DEBUG_PACKETS
637 hexdump("outgoing packet", data, len);
638 #endif
639 client_send_listener(IMSG_BUF, data, len);
640 evbuffer_drain(evb, len);
643 static void
644 np_version(uint16_t tag, uint32_t msize, const char *version)
646 uint16_t l;
648 l = strlen(version);
650 msize = htole32(msize);
652 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
653 evbuffer_add(evb, &msize, sizeof(msize));
654 np_string(evb, l, version);
655 do_send();
658 static void
659 np_attach(uint16_t tag, struct qid *qid)
661 np_header(QIDSIZE, Rattach, tag);
662 np_qid(evb, qid);
663 do_send();
666 static void
667 np_clunk(uint16_t tag)
669 np_header(0, Rclunk, tag);
670 do_send();
673 static void
674 np_flush(uint16_t tag)
676 np_header(0, Rflush, tag);
677 do_send();
680 static void
681 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
683 int i;
685 /* two bytes for the counter */
686 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
687 np_write16(evb, nwqid);
688 for (i = 0; i < nwqid; ++i)
689 np_qid(evb, wqid + i);
691 do_send();
694 static void
695 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
697 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
698 np_qid(evb, qid);
699 np_write32(evb, iounit);
700 do_send();
703 static void
704 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
706 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
707 np_qid(evb, qid);
708 np_write32(evb, iounit);
709 do_send();
712 static void
713 np_read(uint16_t tag, uint32_t count, void *data)
715 if (sizeof(count) + count + HEADERSIZE >= msize) {
716 np_error(tag, "Rread would overflow");
717 return;
720 np_header(sizeof(count) + count, Rread, tag);
721 np_write32(evb, count);
722 np_writebuf(evb, count, data);
723 do_send();
726 static void
727 np_write(uint16_t tag, uint32_t count)
729 np_header(sizeof(count), Rwrite, tag);
730 np_write32(evb, count);
731 do_send();
734 static void
735 np_stat(uint16_t tag, uint16_t count, void *data)
737 if (sizeof(count) + count + HEADERSIZE >= msize) {
738 np_error(tag, "Rstat would overflow");
739 return;
742 np_header(sizeof(count) + count, Rstat, tag);
743 np_write16(evb, count);
744 np_writebuf(evb, count, data);
745 do_send();
748 static void
749 np_wstat(uint16_t tag)
751 np_header(0, Rwstat, tag);
752 do_send();
755 static void
756 np_remove(uint16_t tag)
758 np_header(0, Rremove, tag);
759 do_send();
762 static void
763 np_error(uint16_t tag, const char *errstr)
765 uint16_t l;
767 l = strlen(errstr);
769 np_header(sizeof(l) + l, Rerror, tag);
770 np_string(evb, l, errstr);
771 do_send();
774 static void
775 np_errno(uint16_t tag)
777 int saved_errno;
778 char buf[NL_TEXTMAX] = {0};
780 saved_errno = errno;
782 strerror_r(errno, buf, sizeof(buf));
783 np_error(tag, buf);
785 errno = saved_errno;
788 static int
789 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
790 size_t *len)
792 if (*len < sizeof(*dst)) {
793 log_warnx("%s: wanted %zu bytes for the %s field but only "
794 "%zu are available.", t, sizeof(*dst), f, *len);
795 return 0;
798 memcpy(dst, *src, sizeof(*dst));
799 *src += sizeof(*dst);
800 *len -= sizeof(*dst);
802 return 1;
805 static int
806 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
807 size_t *len)
809 if (*len < sizeof(*dst)) {
810 log_warnx("%s: wanted %zu bytes for the %s field but only "
811 "%zu are available.", t, sizeof(*dst), f, *len);
812 return 0;
815 memcpy(dst, *src, sizeof(*dst));
816 *src += sizeof(*dst);
817 *len -= sizeof(*dst);
818 *dst = le16toh(*dst);
820 return 1;
823 static int
824 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
825 size_t *len)
827 if (*len < sizeof(*dst)) {
828 log_warnx("%s: wanted %zu bytes for the %s field but only "
829 "%zu are available.", t, sizeof(*dst), f, *len);
830 return 0;
833 memcpy(dst, *src, sizeof(*dst));
834 *src += sizeof(*dst);
835 *len -= sizeof(*dst);
836 *dst = le32toh(*dst);
838 return 1;
841 static int
842 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
843 size_t *len)
845 if (*len < sizeof(*dst)) {
846 log_warnx("%s: wanted %zu bytes for the %s field but only "
847 "%zu are available.", t, sizeof(*dst), f, *len);
848 return 0;
851 memcpy(dst, *src, sizeof(*dst));
852 *src += sizeof(*dst);
853 *len -= sizeof(*dst);
854 *dst = le64toh(*dst);
856 return 1;
859 static int
860 np_readstr(const char *t, const char *f, char *res, size_t reslen,
861 const uint8_t **src, size_t *len)
863 uint16_t sl;
864 char buf[32];
866 strlcpy(buf, f, sizeof(buf));
867 strlcat(buf, "-len", sizeof(buf));
869 if (!np_read16(t, buf, &sl, src, len))
870 return READSTRERR;
872 if (*len < sl) {
873 log_warnx("%s: wanted %d bytes for the %s field but only "
874 "%zu are available.", t, sl, f, *len);
875 return READSTRERR;
878 if (*len > reslen-1)
879 return READSTRTRUNC;
881 memcpy(res, *src, sl);
882 res[sl] = '\0';
883 *src += sl;
884 *len -= sl;
886 return 0;
889 static int
890 np_readst(const char *t, const char *f, struct np_stat *st,
891 char *name, size_t namelen, const uint8_t **src, size_t *len)
893 memset(st, 0, sizeof(*st));
895 /* len is sent twice! */
896 if (!np_read16(t, "stat len", &st->size, src, len) ||
897 !np_read16(t, "stat.size", &st->size, src, len) ||
898 !np_read16(t, "stat.type", &st->type, src, len) ||
899 !np_read32(t, "stat.dev", &st->dev, src, len) ||
900 !np_read64(t, "stat.qid.path", &st->qid.path, src, len) ||
901 !np_read32(t, "stat.qid.vers", &st->qid.vers, src, len) ||
902 !np_read8(t, "stat.qid.type", &st->qid.type, src, len) ||
903 !np_read32(t, "stat.mode", &st->mode, src, len) ||
904 !np_read32(t, "stat.atime", &st->atime, src, len) ||
905 !np_read32(t, "stat.mtime", &st->mtime, src, len) ||
906 !np_read64(t, "stat.length", &st->length, src, len))
907 return READSTRERR;
909 /*
910 * ignore everything but the name, we don't support
911 * changing those fields anyway
912 */
913 st->name = name;
914 return np_readstr(t, "stat.name", name, namelen, src, len);
917 static void
918 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
920 char *dot, version[32];
922 if (handshaked)
923 goto err;
925 /* msize[4] version[s] */
926 if (!NPREAD32("msize", &msize, &data, &len))
927 goto err;
929 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
930 case READSTRERR:
931 goto err;
932 case READSTRTRUNC:
933 log_warnx("9P version string too long, truncated");
934 goto mismatch;
937 if (len != 0)
938 goto err;
940 if ((dot = strchr(version, '.')) != NULL)
941 *dot = '\0';
943 if (strcmp(version, VERSION9P) != 0 ||
944 msize == 0)
945 goto mismatch;
947 /* version matched */
948 handshaked = 1;
949 msize = MIN(msize, CLIENT_MSIZE);
950 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
951 np_version(hdr->tag, msize, VERSION9P);
952 return;
954 mismatch:
955 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
956 version);
957 np_version(hdr->tag, MSIZE9P, "unknown");
958 return;
960 err:
961 client_send_listener(IMSG_CLOSE, NULL, 0);
962 client_shutdown();
965 static void
966 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
968 struct dir *dir;
969 struct fid *f;
970 uint32_t fid, afid;
971 int fd;
972 char aname[PATH_MAX];
974 /* fid[4] afid[4] uname[s] aname[s] */
976 if (!NPREAD32("fid", &fid, &data, &len) ||
977 !NPREAD32("afid", &afid, &data, &len))
978 goto err;
980 /* read the uname but don't actually use it */
981 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
982 case READSTRERR:
983 goto err;
984 case READSTRTRUNC:
985 np_error(hdr->tag, "name too long");
986 return;
989 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
990 case READSTRERR:
991 goto err;
992 case READSTRTRUNC:
993 np_error(hdr->tag, "name too long");
994 return;
997 if (*aname == '\0')
998 strlcpy(aname, "/", sizeof(aname));
1000 if (len != 0)
1001 goto err;
1003 if (fid_by_id(fid) != NULL || afid != NOFID) {
1004 np_error(hdr->tag, "invalid fid or afid");
1005 return;
1008 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
1009 goto fail;
1011 if ((dir = new_dir(fd)) == NULL)
1012 goto fail;
1014 log_debug("attached %s to %d", aname, fid);
1016 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
1017 dir_decref(dir);
1018 goto fail;
1021 np_attach(hdr->tag, &f->qid);
1022 return;
1024 fail:
1025 np_errno(hdr->tag);
1026 log_warn("failed to attach %s", aname);
1027 return;
1029 err:
1030 client_send_listener(IMSG_CLOSE, NULL, 0);
1031 client_shutdown();
1034 static void
1035 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1037 struct fid *f;
1038 uint32_t fid;
1040 /* fid[4] */
1041 if (!NPREAD32("fid", &fid, &data, &len) ||
1042 len != 0) {
1043 client_send_listener(IMSG_CLOSE, NULL, 0);
1044 client_shutdown();
1045 return;
1048 if ((f = fid_by_id(fid)) == NULL) {
1049 np_error(hdr->tag, "invalid fid");
1050 return;
1053 free_fid(f);
1054 np_clunk(hdr->tag);
1057 static void
1058 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1060 uint16_t oldtag;
1063 * We're doing only synchronous I/O. Tflush is implemented
1064 * only because it's illegal to reply with a Rerror.
1067 /* oldtag[2] */
1068 if (len != sizeof(oldtag)) {
1069 log_warnx("Tflush with the wrong size: got %zu want %zu",
1070 len, sizeof(oldtag));
1071 client_send_listener(IMSG_CLOSE, NULL, 0);
1072 client_shutdown();
1073 return;
1076 np_flush(hdr->tag);
1079 static void
1080 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1082 struct stat sb;
1083 struct dir *dir;
1084 struct qid wqid[MAXWELEM] = {0};
1085 struct fid *f, *nf;
1086 uint32_t fid, newfid;
1087 uint16_t nwname;
1088 int fd, oldfd, no, nwqid = 0;
1089 char wnam[PATH_MAX];
1091 if (!NPREAD32("fid", &fid, &data, &len) ||
1092 !NPREAD32("newfid", &newfid, &data, &len) ||
1093 !NPREAD16("nwname", &nwname, &data, &len))
1094 goto err;
1096 if (nwname > MAXWELEM) {
1097 log_warnx("Twalk: more than %d path elements: %d",
1098 MAXWELEM, nwname);
1099 goto err;
1102 if ((f = fid_by_id(fid)) == NULL) {
1103 np_error(hdr->tag, "invalid fid");
1104 return;
1107 if (f->fd != -1) {
1108 np_error(hdr->tag, "fid already opened for I/O");
1109 return;
1112 if (fid == newfid)
1113 nf = f;
1114 else if ((nf = fid_by_id(newfid)) != NULL) {
1115 np_error(hdr->tag, "newfid already in use");
1116 return;
1117 } else
1118 nf = NULL;
1120 /* special case: fid duplication */
1121 if (nwname == 0) {
1123 * TODO: should we forbid fids duplication when fid ==
1124 * newfid?
1126 if (nf == NULL &&
1127 (nf = new_fid(f->dir, newfid, f->fname, &f->qid)) == NULL)
1128 fatal("new_fid duplication");
1130 np_walk(hdr->tag, 0, NULL);
1131 return;
1134 if (!(f->qid.type & QTDIR)) {
1135 np_error(hdr->tag, "fid doesn't represent a directory");
1136 return;
1139 oldfd = f->dir->fd;
1141 for (nwqid = 0; nwqid < nwname; nwqid++) {
1142 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1143 case READSTRERR:
1144 goto err;
1145 case READSTRTRUNC:
1146 np_error(hdr->tag, "wname too long");
1147 return;
1150 if (*wnam == '\0' ||
1151 strchr(wnam, '/') != NULL ||
1152 !strcmp(wnam, ".")) {
1153 errno = EINVAL;
1154 goto cantopen;
1157 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1158 errno != ENOTDIR)
1159 goto cantopen;
1161 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1162 (fd != -1 && fstat(fd, &sb) == -1))
1163 goto cantopen;
1165 qid_update_from_sb(&wqid[nwqid], &sb);
1167 /* reached a file but we still have other components */
1168 if (fd == -1 && nwqid+1 < nwname)
1169 goto cantopen;
1171 /* reached the end and found a file */
1172 if (fd == -1 && nwqid+1 == nwname)
1173 continue;
1175 if (oldfd != f->dir->fd)
1176 close(oldfd);
1177 oldfd = fd;
1180 if (len != 0)
1181 goto err;
1184 * If fd is -1 we've reached a file, otherwise we've just
1185 * reached another directory. We must pay attention to what
1186 * file descriptor we use to create the dir, because if we've
1187 * reached a file and oldfd is f->dir->fd then we *must* share
1188 * the same dir (it was a walk of one path from a directory to a
1189 * file, otherwise fun is bound to happen as soon as the client
1190 * closes the fid for the directory but keeps the one for the
1191 * file.
1193 if (fd == -1 && oldfd == f->dir->fd)
1194 dir = f->dir;
1195 else if (fd == -1)
1196 dir = new_dir(oldfd);
1197 else
1198 dir = new_dir(fd);
1200 if (dir == NULL)
1201 fatal("new_dir");
1203 if (nf == NULL) {
1204 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1205 fatal("new fid");
1206 } else {
1207 /* update the dir */
1208 dir_decref(nf->dir);
1209 nf->dir = dir_incref(dir);
1212 np_walk(hdr->tag, nwqid, wqid);
1213 return;
1215 cantopen:
1216 if (oldfd != f->dir->fd)
1217 close(oldfd);
1218 no = errno;
1219 if (nwqid == 0)
1220 np_error(hdr->tag, strerror(no));
1221 else
1222 np_walk(hdr->tag, nwqid, wqid);
1223 return;
1225 err:
1226 client_send_listener(IMSG_CLOSE, NULL, 0);
1227 client_shutdown();
1230 static inline int
1231 npmode_to_unix(uint8_t mode, int *flags)
1233 switch (mode & 0x0F) {
1234 case KOREAD:
1235 *flags = O_RDONLY;
1236 break;
1237 case KOWRITE:
1238 *flags = O_WRONLY;
1239 break;
1240 case KORDWR:
1241 *flags = O_RDWR;
1242 break;
1243 case KOEXEC:
1244 log_warnx("tried to open something with KOEXEC");
1245 /* fallthrough */
1246 default:
1247 return -1;
1250 if (mode & KOTRUNC)
1251 *flags |= O_TRUNC;
1252 if (mode & KORCLOSE)
1253 *flags |= O_CLOEXEC;
1255 return 0;
1258 static void
1259 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1261 struct stat sb;
1262 struct qid qid;
1263 struct fid *f;
1264 uint32_t fid;
1265 uint8_t mode;
1266 const char *path;
1268 /* fid[4] mode[1] */
1269 if (!NPREAD32("fid", &fid, &data, &len) ||
1270 !NPREAD8("mode", &mode, &data, &len) ||
1271 len != 0) {
1272 client_send_listener(IMSG_CLOSE, NULL, 0);
1273 client_shutdown();
1274 return;
1277 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1278 np_error(hdr->tag, "invalid fid");
1279 return;
1282 if (npmode_to_unix(mode, &f->iomode) == -1) {
1283 np_error(hdr->tag, "invalid mode");
1284 return;
1287 path = f->fname;
1288 if (f->qid.type & QTDIR)
1289 path = ".";
1291 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1292 np_error(hdr->tag, strerror(errno));
1293 return;
1296 if (fstat(f->fd, &sb) == -1)
1297 fatal("fstat");
1299 if (S_ISDIR(sb.st_mode)) {
1300 if ((f->d = fdopendir(f->fd)) == NULL) {
1301 np_errno(hdr->tag);
1302 close(f->fd);
1303 f->fd = -1;
1304 return;
1307 if ((f->evb = evbuffer_new()) == NULL) {
1308 np_errno(hdr->tag);
1309 closedir(f->d);
1310 f->d = NULL;
1311 f->fd = -1;
1315 f->offset = 0;
1317 qid_update_from_sb(&qid, &sb);
1318 np_open(hdr->tag, &qid, sb.st_blksize);
1321 static void
1322 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1324 struct stat sb;
1325 struct qid qid;
1326 struct fid *f;
1327 uint32_t fid, perm;
1328 uint8_t mode;
1329 char name[PATH_MAX];
1331 /* fid[4] name[s] perm[4] mode[1] */
1332 if (!NPREAD32("fid", &fid, &data, &len))
1333 goto err;
1334 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1335 case READSTRERR:
1336 goto err;
1337 case READSTRTRUNC:
1338 np_error(hdr->tag, "name too long");
1339 return;
1341 if (!NPREAD32("perm", &perm, &data, &len) ||
1342 !NPREAD8("mode", &mode, &data, &len) ||
1343 len != 0)
1344 goto err;
1346 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1347 strchr(name, '/') != NULL) {
1348 np_error(hdr->tag, "invalid name");
1349 return;
1352 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1353 np_error(hdr->tag, "invalid fid");
1354 return;
1357 if (!(f->qid.type & QTDIR)) {
1358 np_error(hdr->tag, "fid doesn't identify a directory");
1359 return;
1362 if (npmode_to_unix(mode, &f->iomode) == -1) {
1363 np_error(hdr->tag, "invalid mode");
1364 return;
1367 if (f->iomode & O_RDONLY) {
1368 np_error(hdr->tag, "can't create a read-only file");
1369 return;
1372 /* TODO: parse the mode */
1374 if (perm & 0x80000000) {
1375 /* create a directory */
1376 f->fd = mkdirat(f->dir->fd, name, 0755);
1377 } else {
1378 /* create a file */
1379 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1380 0644);
1383 if (f->fd == -1) {
1384 np_errno(hdr->tag);
1385 return;
1388 if (fstat(f->fd, &sb) == -1)
1389 fatal("fstat");
1391 if (S_ISDIR(sb.st_mode)) {
1392 if ((f->d = fdopendir(f->fd)) == NULL) {
1393 np_errno(hdr->tag);
1394 close(f->fd);
1395 f->fd = -1;
1396 return;
1399 if ((f->evb = evbuffer_new()) == NULL) {
1400 np_errno(hdr->tag);
1401 closedir(f->d);
1402 f->d = NULL;
1403 f->fd = -1;
1407 f->offset = 0;
1409 qid_update_from_sb(&qid, &sb);
1410 np_create(hdr->tag, &qid, sb.st_blksize);
1412 return;
1414 err:
1415 client_send_listener(IMSG_CLOSE, NULL, 0);
1416 client_shutdown();
1419 static inline int
1420 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1422 struct qid qid;
1423 const char *uid, *gid, *muid;
1424 size_t tot;
1425 uint32_t mode;
1426 uint16_t namlen, uidlen, gidlen, ulen;
1428 qid_update_from_sb(&qid, sb);
1430 /* TODO: fill these fields */
1431 uid = "";
1432 gid = "";
1433 muid = "";
1435 namlen = strlen(fname);
1436 uidlen = strlen(uid);
1437 gidlen = strlen(gid);
1438 ulen = strlen(muid);
1440 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1441 if (tot > UINT16_MAX) {
1442 log_warnx("stat info for dir entry %s would overflow",
1443 fname);
1444 return -1;
1447 mode = sb->st_mode & 0xFFFF;
1448 if (qid.type & QTDIR)
1449 mode |= 0x80000000;
1451 np_write16(evb, tot); /* size[2] */
1452 np_write16(evb, sb->st_rdev); /* type[2] */
1453 np_write32(evb, sb->st_dev); /* dev[4] */
1454 np_qid(evb, &qid); /* qid[13] */
1455 np_write32(evb, mode); /* mode[4] */
1456 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1457 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1459 /* special case: directories have size 0 */
1460 if (qid.type & QTDIR)
1461 np_write64(evb, 0);
1462 else
1463 np_write64(evb, sb->st_size); /* length[8] */
1465 np_string(evb, namlen, fname); /* name[s] */
1466 np_string(evb, uidlen, uid); /* uid[s] */
1467 np_string(evb, gidlen, gid); /* gid[s] */
1468 np_string(evb, ulen, muid); /* muid[s] */
1470 return 0;
1473 static void
1474 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1476 struct fid *f;
1477 ssize_t r;
1478 size_t howmuch;
1479 uint64_t off;
1480 uint32_t fid, count;
1481 char buf[2048];
1483 /* fid[4] offset[8] count[4] */
1484 if (!NPREAD32("fid", &fid, &data, &len) ||
1485 !NPREAD64("offset", &off, &data, &len) ||
1486 !NPREAD32("count", &count, &data, &len) ||
1487 len != 0) {
1488 client_send_listener(IMSG_CLOSE, NULL, 0);
1489 client_shutdown();
1490 return;
1493 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1494 np_error(hdr->tag, "invalid fid");
1495 return;
1498 if (TYPE_OVERFLOW(off_t, off)) {
1499 log_warnx("unexpected off_t size");
1500 np_error(hdr->tag, "invalid offset");
1501 return;
1504 if (f->d == NULL) {
1505 /* read a file */
1506 howmuch = MIN(sizeof(buf), count);
1507 r = pread(f->fd, buf, howmuch, (off_t)off);
1508 if (r == -1)
1509 np_errno(hdr->tag);
1510 else
1511 np_read(hdr->tag, r, buf);
1512 } else {
1513 if (off == 0 && f->offset != 0) {
1514 rewinddir(f->d);
1515 f->offset = 0;
1516 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1519 if (off != f->offset) {
1520 np_error(hdr->tag, "can't seek in directories");
1521 return;
1524 while (EVBUFFER_LENGTH(f->evb) < count) {
1525 struct dirent *d;
1526 struct stat sb;
1528 if ((d = readdir(f->d)) == NULL)
1529 break;
1530 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1531 continue;
1532 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1533 warn("fstatat");
1534 continue;
1536 serialize_stat(d->d_name, &sb, f->evb);
1539 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1540 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1541 evbuffer_drain(f->evb, count);
1543 f->offset += count;
1547 static void
1548 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1550 struct fid *f;
1551 ssize_t r;
1552 uint64_t off;
1553 uint32_t fid, count;
1555 /* fid[4] offset[8] count[4] data[count] */
1556 if (!NPREAD32("fid", &fid, &data, &len) ||
1557 !NPREAD64("off", &off, &data, &len) ||
1558 !NPREAD32("count", &count, &data, &len) ||
1559 len != count) {
1560 client_send_listener(IMSG_CLOSE, NULL, 0);
1561 client_shutdown();
1562 return;
1565 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1566 np_error(hdr->tag, "invalid fid");
1567 return;
1570 if (!(f->iomode & O_WRONLY) &&
1571 !(f->iomode & O_RDWR)) {
1572 np_error(hdr->tag, "fid not opened for writing");
1573 return;
1576 if (TYPE_OVERFLOW(off_t, off)) {
1577 log_warnx("unexpected off_t size");
1578 np_error(hdr->tag, "invalid offset");
1579 return;
1582 if ((r = pwrite(f->fd, data, len, off)) == -1)
1583 np_errno(hdr->tag);
1584 else
1585 np_write(hdr->tag, r);
1588 static void
1589 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1591 struct evbuffer *evb;
1592 struct stat sb;
1593 struct fid *f;
1594 int r;
1595 uint32_t fid;
1597 /* fid[4] */
1598 if (!NPREAD32("fid", &fid, &data, &len) ||
1599 len != 0) {
1600 client_send_listener(IMSG_CLOSE, NULL, 0);
1601 client_shutdown();
1602 return;
1606 * plan9' stat(9P) is not clear on whether the stat is allowed
1607 * on opened fids or not. We're allowing stat regardless of the
1608 * status of the fid.
1611 if ((f = fid_by_id(fid)) == NULL) {
1612 np_error(hdr->tag, "invalid fid");
1613 return;
1616 if ((evb = evbuffer_new()) == NULL)
1617 fatal("evbuffer_new");
1619 if (f->fd != -1)
1620 r = fstat(f->fd, &sb);
1621 else if (f->qid.type & QTDIR)
1622 r = fstat(f->dir->fd, &sb);
1623 else
1624 r = fstatat(f->dir->fd, f->fname, &sb, 0);
1626 if (r == -1) {
1627 np_errno(hdr->tag);
1628 evbuffer_free(evb);
1629 return;
1632 if (serialize_stat(f->fname, &sb, evb) == -1)
1633 np_error(hdr->tag, "stat would overflow");
1634 else
1635 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1636 evbuffer_free(evb);
1639 static void
1640 twstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1642 struct timespec times[2];
1643 struct np_stat st;
1644 struct fid *f;
1645 int r;
1646 uint32_t fid;
1647 char name[PATH_MAX];
1649 /* fid[4] stat[n] */
1650 if (!NPREAD32("fid", &fid, &data, &len))
1651 goto err;
1653 switch (NPREADST("stat", &st, name, sizeof(name), &data, &len)) {
1654 case READSTRERR:
1655 goto err;
1656 case READSTRTRUNC:
1657 log_warnx("wstat new name would overflow");
1658 np_error(hdr->tag, "new name too long");
1659 return;
1663 * We skip the reading of some fields voluntarily because we
1664 * don't support chown, so len will always be > 0!
1666 #ifdef notyet
1667 if (len != 0)
1668 goto err;
1669 #endif
1671 if ((f = fid_by_id(fid)) == NULL) {
1672 np_error(hdr->tag, "invalid fid");
1673 return;
1677 * 9P wants these edits to be done in an atomic fashion,
1678 * something that I don't think it's possible on UNIX without
1679 * some special kernel help. Changing atime or mtime,
1680 * permissions, or rename the file are different syscalls.
1682 * Also, silently ignore stuff we can't/don't want to modify.
1685 /* change the permissions */
1686 if (st.mode != (uint32_t)-1) {
1687 mode_t m = st.mode & 0x7F; /* silently truncate higer bits */
1688 if (f->fd != -1)
1689 r = fchmod(f->fd, m);
1690 else
1691 r = fchmodat(f->dir->fd, f->fname, m, 0);
1693 if (r == -1) {
1694 np_errno(hdr->tag);
1695 return;
1699 /* change the atime/mtime of the fid, opened or not */
1700 if (st.atime != (uint32_t)-1 || st.mtime != (uint32_t)-1) {
1701 times[0].tv_nsec = UTIME_OMIT;
1702 times[1].tv_nsec = UTIME_OMIT;
1704 if (st.atime != (uint32_t)-1) {
1705 times[0].tv_sec = st.atime;
1706 times[0].tv_nsec = 0;
1708 if (st.mtime != (uint32_t)-1) {
1709 times[1].tv_sec = st.mtime;
1710 times[1].tv_nsec = 0;
1713 if (f->fd != -1)
1714 r = futimens(f->fd, times);
1715 else
1716 r = utimensat(f->dir->fd, f->fname, times, 0);
1718 if (r == -1) {
1719 np_errno(hdr->tag);
1720 return;
1724 /* truncate */
1725 if (st.length != (uint64_t)-1) {
1726 if (f->fd == -1) {
1727 np_error(hdr->tag, "can't truncate a non-opened fid");
1728 return;
1731 if (f->qid.type & QTDIR && st.length != 0) {
1732 np_error(hdr->tag, "can't truncate directories");
1733 return;
1736 if (TYPE_OVERFLOW(off_t, st.length)) {
1737 log_warnx("truncate request overflows off_t: %"PRIu64,
1738 st.length);
1739 np_error(hdr->tag, "length overflows");
1740 return;
1743 if (f->qid.type == 0 &&
1744 ftruncate(f->fd, st.length) == -1) {
1745 np_errno(hdr->tag);
1746 return;
1750 /* rename (change the name entry) */
1751 if (*st.name != '\0') {
1752 struct stat sb;
1753 const char *newname;
1756 * XXX: 9P requires that we disallow changing the name
1757 * to that of an existing file. We can't do that
1758 * atomically (rename is happy about stealing names)
1759 * so this is just a best effort.
1761 if (fstatat(f->dir->fd, st.name, &sb, 0) == -1 &&
1762 errno != ENOENT) {
1763 np_error(hdr->tag, "target file exists");
1764 return;
1767 r = renameat(f->dir->fd, f->fname, f->dir->fd, st.name);
1768 if (r == -1) {
1769 np_errno(hdr->tag);
1770 return;
1773 /* fix the fid so it points to the new file */
1775 if ((newname = strchr(st.name, '/')) != NULL)
1776 newname++; /* skip / */
1777 else
1778 newname = st.name;
1779 strlcpy(f->fname, newname, sizeof(f->fname));
1781 if (strchr(st.name, '/') != NULL) {
1782 struct dir *dir;
1783 char *dname;
1784 int fd;
1786 dname = dirname(st.name);
1787 fd = openat(f->dir->fd, dname, O_RDONLY|O_DIRECTORY);
1788 if (fd == -1) {
1789 np_errno(hdr->tag);
1790 free_fid(f);
1791 return;
1794 if ((dir = new_dir(fd)) == NULL) {
1795 np_errno(hdr->tag);
1796 free_fid(f);
1797 return;
1800 dir_decref(f->dir);
1801 f->dir = dir_incref(dir);
1805 np_wstat(hdr->tag);
1806 return;
1808 err:
1809 client_send_listener(IMSG_CLOSE, NULL, 0);
1810 client_shutdown();
1813 static void
1814 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1816 struct fid *f;
1817 uint32_t fid;
1818 int r;
1819 char dirpath[PATH_MAX + 3];
1821 /* fid[4] */
1822 if (!NPREAD32("fid", &fid, &data, &len) ||
1823 len != 0) {
1824 client_send_listener(IMSG_CLOSE, NULL, 0);
1825 client_shutdown();
1826 return;
1829 if ((f = fid_by_id(fid)) == NULL) {
1830 np_error(hdr->tag, "invalid fid");
1831 return;
1834 if (f->qid.type & QTDIR) { /* directory */
1835 strlcpy(dirpath, "../", sizeof(dirpath));
1836 strlcat(dirpath, f->fname, sizeof(dirpath));
1837 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1838 } else /* file */
1839 r = unlinkat(f->dir->fd, f->fname, 0);
1841 if (r == -1)
1842 np_errno(hdr->tag);
1843 else
1844 np_remove(hdr->tag);
1846 free_fid(f);
1849 static void
1850 handle_message(struct imsg *imsg, size_t len)
1852 struct msg {
1853 uint8_t type;
1854 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1855 } msgs[] = {
1856 {Tversion, tversion},
1857 {Tattach, tattach},
1858 {Tclunk, tclunk},
1859 {Tflush, tflush},
1860 {Twalk, twalk},
1861 {Topen, topen},
1862 {Tcreate, tcreate},
1863 {Tread, tread},
1864 {Twrite, twrite},
1865 {Tstat, tstat},
1866 {Twstat, twstat},
1867 {Tremove, tremove},
1869 struct np_msg_header hdr;
1870 size_t i;
1871 uint8_t *data;
1873 #if DEBUG_PACKETS
1874 hexdump("incoming packet", imsg->data, len);
1875 #endif
1877 parse_message(imsg->data, len, &hdr, &data);
1878 len -= HEADERSIZE;
1880 log_debug("got request: len=%d type=%d[%s] tag=%d",
1881 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1883 if (!handshaked && hdr.type != Tversion) {
1884 client_send_listener(IMSG_CLOSE, NULL, 0);
1885 client_shutdown();
1886 return;
1889 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1890 if (msgs[i].type != hdr.type)
1891 continue;
1893 msgs[i].fn(&hdr, data, len);
1894 return;
1897 np_error(hdr.tag, "Not supported.");