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, uint32_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, uint32_t count, void *data)
737 if (sizeof(count) + count + HEADERSIZE >= msize) {
738 np_error(tag, "Rstat would overflow");
739 return;
742 np_header(count, Rstat, tag);
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 if (!np_read16(t, "stat.size", &st->size, src, len) ||
895 !np_read16(t, "stat.type", &st->type, src, len) ||
896 !np_read32(t, "stat.dev", &st->dev, src, len) ||
897 !np_read64(t, "stat.qid.path", &st->qid.path, src, len) ||
898 !np_read32(t, "stat.qid.vers", &st->qid.vers, src, len) ||
899 !np_read8(t, "stat.qid.type", &st->qid.type, src, len) ||
900 !np_read32(t, "stat.mode", &st->mode, src, len) ||
901 !np_read32(t, "stat.atime", &st->atime, src, len) ||
902 !np_read32(t, "stat.mtime", &st->mtime, src, len) ||
903 !np_read64(t, "stat.length", &st->length, src, len))
904 return READSTRERR;
906 /*
907 * ignore everything but the name, we don't support
908 * changing those fields anyway
909 */
910 st->name = name;
911 return np_readstr(t, "stat.name", name, namelen, src, len);
914 static void
915 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
917 char *dot, version[32];
919 if (handshaked)
920 goto err;
922 /* msize[4] version[s] */
923 if (!NPREAD32("msize", &msize, &data, &len))
924 goto err;
926 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
927 case READSTRERR:
928 goto err;
929 case READSTRTRUNC:
930 log_warnx("9P version string too long, truncated");
931 goto mismatch;
934 if (len != 0)
935 goto err;
937 if ((dot = strchr(version, '.')) != NULL)
938 *dot = '\0';
940 if (strcmp(version, VERSION9P) != 0 ||
941 msize == 0)
942 goto mismatch;
944 /* version matched */
945 handshaked = 1;
946 msize = MIN(msize, CLIENT_MSIZE);
947 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
948 np_version(hdr->tag, msize, VERSION9P);
949 return;
951 mismatch:
952 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
953 version);
954 np_version(hdr->tag, MSIZE9P, "unknown");
955 return;
957 err:
958 client_send_listener(IMSG_CLOSE, NULL, 0);
959 client_shutdown();
962 static void
963 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
965 struct dir *dir;
966 struct fid *f;
967 uint32_t fid, afid;
968 int fd;
969 char aname[PATH_MAX];
971 /* fid[4] afid[4] uname[s] aname[s] */
973 if (!NPREAD32("fid", &fid, &data, &len) ||
974 !NPREAD32("afid", &afid, &data, &len))
975 goto err;
977 /* read the uname but don't actually use it */
978 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
979 case READSTRERR:
980 goto err;
981 case READSTRTRUNC:
982 np_error(hdr->tag, "name too long");
983 return;
986 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
987 case READSTRERR:
988 goto err;
989 case READSTRTRUNC:
990 np_error(hdr->tag, "name too long");
991 return;
994 if (len != 0)
995 goto err;
997 if (fid_by_id(fid) != NULL || afid != NOFID) {
998 np_error(hdr->tag, "invalid fid or afid");
999 return;
1002 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
1003 goto fail;
1005 if ((dir = new_dir(fd)) == NULL)
1006 goto fail;
1008 log_debug("attached %s to %d", aname, fid);
1010 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
1011 dir_decref(dir);
1012 goto fail;
1015 np_attach(hdr->tag, &f->qid);
1016 return;
1018 fail:
1019 np_errno(hdr->tag);
1020 log_warn("failed to attach %s", aname);
1021 return;
1023 err:
1024 client_send_listener(IMSG_CLOSE, NULL, 0);
1025 client_shutdown();
1028 static void
1029 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1031 struct fid *f;
1032 uint32_t fid;
1034 /* fid[4] */
1035 if (!NPREAD32("fid", &fid, &data, &len) ||
1036 len != 0) {
1037 client_send_listener(IMSG_CLOSE, NULL, 0);
1038 client_shutdown();
1039 return;
1042 if ((f = fid_by_id(fid)) == NULL) {
1043 np_error(hdr->tag, "invalid fid");
1044 return;
1047 free_fid(f);
1048 np_clunk(hdr->tag);
1051 static void
1052 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1054 uint16_t oldtag;
1057 * We're doing only synchronous I/O. Tflush is implemented
1058 * only because it's illegal to reply with a Rerror.
1061 /* oldtag[2] */
1062 if (len != sizeof(oldtag)) {
1063 log_warnx("Tflush with the wrong size: got %zu want %zu",
1064 len, sizeof(oldtag));
1065 client_send_listener(IMSG_CLOSE, NULL, 0);
1066 client_shutdown();
1067 return;
1070 np_flush(hdr->tag);
1073 static void
1074 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1076 struct stat sb;
1077 struct dir *dir;
1078 struct qid wqid[MAXWELEM] = {0};
1079 struct fid *f, *nf;
1080 uint32_t fid, newfid;
1081 uint16_t nwname;
1082 int fd, oldfd, no, nwqid = 0;
1083 char wnam[PATH_MAX];
1085 if (!NPREAD32("fid", &fid, &data, &len) ||
1086 !NPREAD32("newfid", &newfid, &data, &len) ||
1087 !NPREAD16("nwname", &nwname, &data, &len))
1088 goto err;
1090 if (nwname > MAXWELEM) {
1091 log_warnx("Twalk: more than %d path elements: %d",
1092 MAXWELEM, nwname);
1093 goto err;
1096 if ((f = fid_by_id(fid)) == NULL) {
1097 np_error(hdr->tag, "invalid fid");
1098 return;
1101 if (f->fd != -1) {
1102 np_error(hdr->tag, "fid already opened for I/O");
1103 return;
1106 if (fid == newfid)
1107 nf = f;
1108 else if ((nf = fid_by_id(newfid)) != NULL) {
1109 np_error(hdr->tag, "newfid already in use");
1110 return;
1111 } else
1112 nf = NULL;
1114 /* special case: fid duplication */
1115 if (nwname == 0) {
1117 * TODO: should we forbid fids duplication when fid ==
1118 * newfid?
1120 if (nf == NULL &&
1121 (nf = new_fid(f->dir, newfid, f->fname, &f->qid)) == NULL)
1122 fatal("new_fid duplication");
1124 np_walk(hdr->tag, 0, NULL);
1125 return;
1128 if (!(f->qid.type & QTDIR)) {
1129 np_error(hdr->tag, "fid doesn't represent a directory");
1130 return;
1133 oldfd = f->dir->fd;
1135 for (nwqid = 0; nwqid < nwname; nwqid++) {
1136 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1137 case READSTRERR:
1138 goto err;
1139 case READSTRTRUNC:
1140 np_error(hdr->tag, "wname too long");
1141 return;
1144 if (*wnam == '\0' ||
1145 strchr(wnam, '/') != NULL ||
1146 !strcmp(wnam, ".")) {
1147 errno = EINVAL;
1148 goto cantopen;
1151 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1152 errno != ENOTDIR)
1153 goto cantopen;
1155 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1156 (fd != -1 && fstat(fd, &sb) == -1))
1157 goto cantopen;
1159 qid_update_from_sb(&wqid[nwqid], &sb);
1161 /* reached a file but we still have other components */
1162 if (fd == -1 && nwqid+1 < nwname)
1163 goto cantopen;
1165 /* reached the end and found a file */
1166 if (fd == -1 && nwqid+1 == nwname)
1167 continue;
1169 if (oldfd != f->dir->fd)
1170 close(oldfd);
1171 oldfd = fd;
1174 if (len != 0)
1175 goto err;
1178 * If fd is -1 we've reached a file, otherwise we've just
1179 * reached another directory. We must pay attention to what
1180 * file descriptor we use to create the dir, because if we've
1181 * reached a file and oldfd is f->dir->fd then we *must* share
1182 * the same dir (it was a walk of one path from a directory to a
1183 * file, otherwise fun is bound to happen as soon as the client
1184 * closes the fid for the directory but keeps the one for the
1185 * file.
1187 if (fd == -1 && oldfd == f->dir->fd)
1188 dir = f->dir;
1189 else if (fd == -1)
1190 dir = new_dir(oldfd);
1191 else
1192 dir = new_dir(fd);
1194 if (dir == NULL)
1195 fatal("new_dir");
1197 if (nf == NULL) {
1198 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1199 fatal("new fid");
1200 } else {
1201 /* update the dir */
1202 dir_decref(nf->dir);
1203 nf->dir = dir_incref(dir);
1206 np_walk(hdr->tag, nwqid, wqid);
1207 return;
1209 cantopen:
1210 if (oldfd != f->dir->fd)
1211 close(oldfd);
1212 no = errno;
1213 if (nwqid == 0)
1214 np_error(hdr->tag, strerror(no));
1215 else
1216 np_walk(hdr->tag, nwqid, wqid);
1217 return;
1219 err:
1220 client_send_listener(IMSG_CLOSE, NULL, 0);
1221 client_shutdown();
1224 static inline int
1225 npmode_to_unix(uint8_t mode, int *flags)
1227 switch (mode & 0x0F) {
1228 case KOREAD:
1229 *flags = O_RDONLY;
1230 break;
1231 case KOWRITE:
1232 *flags = O_WRONLY;
1233 break;
1234 case KORDWR:
1235 *flags = O_RDWR;
1236 break;
1237 case KOEXEC:
1238 log_warnx("tried to open something with KOEXEC");
1239 /* fallthrough */
1240 default:
1241 return -1;
1244 if (mode & KOTRUNC)
1245 *flags |= O_TRUNC;
1246 if (mode & KORCLOSE)
1247 *flags |= O_CLOEXEC;
1249 return 0;
1252 static void
1253 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1255 struct stat sb;
1256 struct qid qid;
1257 struct fid *f;
1258 uint32_t fid;
1259 uint8_t mode;
1260 const char *path;
1262 /* fid[4] mode[1] */
1263 if (!NPREAD32("fid", &fid, &data, &len) ||
1264 !NPREAD8("mode", &mode, &data, &len) ||
1265 len != 0) {
1266 client_send_listener(IMSG_CLOSE, NULL, 0);
1267 client_shutdown();
1268 return;
1271 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1272 np_error(hdr->tag, "invalid fid");
1273 return;
1276 if (npmode_to_unix(mode, &f->iomode) == -1) {
1277 np_error(hdr->tag, "invalid mode");
1278 return;
1281 path = f->fname;
1282 if (f->qid.type & QTDIR)
1283 path = ".";
1285 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1286 np_error(hdr->tag, strerror(errno));
1287 return;
1290 if (fstat(f->fd, &sb) == -1)
1291 fatal("fstat");
1293 if (S_ISDIR(sb.st_mode)) {
1294 if ((f->d = fdopendir(f->fd)) == NULL) {
1295 np_errno(hdr->tag);
1296 close(f->fd);
1297 f->fd = -1;
1298 return;
1301 if ((f->evb = evbuffer_new()) == NULL) {
1302 np_errno(hdr->tag);
1303 closedir(f->d);
1304 f->d = NULL;
1305 f->fd = -1;
1309 f->offset = 0;
1311 qid_update_from_sb(&qid, &sb);
1312 np_open(hdr->tag, &qid, sb.st_blksize);
1315 static void
1316 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1318 struct stat sb;
1319 struct qid qid;
1320 struct fid *f;
1321 uint32_t fid, perm;
1322 uint8_t mode;
1323 char name[PATH_MAX];
1325 /* fid[4] name[s] perm[4] mode[1] */
1326 if (!NPREAD32("fid", &fid, &data, &len))
1327 goto err;
1328 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1329 case READSTRERR:
1330 goto err;
1331 case READSTRTRUNC:
1332 np_error(hdr->tag, "name too long");
1333 return;
1335 if (!NPREAD32("perm", &perm, &data, &len) ||
1336 !NPREAD8("mode", &mode, &data, &len) ||
1337 len != 0)
1338 goto err;
1340 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1341 strchr(name, '/') != NULL) {
1342 np_error(hdr->tag, "invalid name");
1343 return;
1346 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1347 np_error(hdr->tag, "invalid fid");
1348 return;
1351 if (!(f->qid.type & QTDIR)) {
1352 np_error(hdr->tag, "fid doesn't identify a directory");
1353 return;
1356 if (npmode_to_unix(mode, &f->iomode) == -1) {
1357 np_error(hdr->tag, "invalid mode");
1358 return;
1361 if (f->iomode & O_RDONLY) {
1362 np_error(hdr->tag, "can't create a read-only file");
1363 return;
1366 /* TODO: parse the mode */
1368 if (perm & 0x80000000) {
1369 /* create a directory */
1370 f->fd = mkdirat(f->dir->fd, name, 0755);
1371 } else {
1372 /* create a file */
1373 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1374 0644);
1377 if (f->fd == -1) {
1378 np_errno(hdr->tag);
1379 return;
1382 if (fstat(f->fd, &sb) == -1)
1383 fatal("fstat");
1385 if (S_ISDIR(sb.st_mode)) {
1386 if ((f->d = fdopendir(f->fd)) == NULL) {
1387 np_errno(hdr->tag);
1388 close(f->fd);
1389 f->fd = -1;
1390 return;
1393 if ((f->evb = evbuffer_new()) == NULL) {
1394 np_errno(hdr->tag);
1395 closedir(f->d);
1396 f->d = NULL;
1397 f->fd = -1;
1401 f->offset = 0;
1403 qid_update_from_sb(&qid, &sb);
1404 np_create(hdr->tag, &qid, sb.st_blksize);
1406 return;
1408 err:
1409 client_send_listener(IMSG_CLOSE, NULL, 0);
1410 client_shutdown();
1413 static inline void
1414 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1416 struct qid qid;
1417 const char *uid, *gid, *muid;
1418 size_t tot;
1419 uint16_t namlen, uidlen, gidlen, ulen;
1421 qid_update_from_sb(&qid, sb);
1423 /* TODO: fill these fields */
1424 uid = "";
1425 gid = "";
1426 muid = "";
1428 namlen = strlen(fname);
1429 uidlen = strlen(uid);
1430 gidlen = strlen(gid);
1431 ulen = strlen(muid);
1433 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1434 if (tot > UINT32_MAX) {
1435 log_warnx("stat info for dir entry %s would overflow",
1436 fname);
1437 return;
1440 np_write16(evb, tot); /* size[2] */
1441 np_write16(evb, sb->st_rdev); /* type[2] */
1442 np_write32(evb, sb->st_dev); /* dev[4] */
1443 np_qid(evb, &qid); /* qid[13] */
1445 /* XXX: translate? */
1446 np_write32(evb, sb->st_mode); /* mode[4] */
1448 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1449 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1451 /* special case: directories have size 0 */
1452 if (qid.type & QTDIR)
1453 np_write64(evb, 0);
1454 else
1455 np_write64(evb, sb->st_size); /* length[8] */
1457 np_string(evb, namlen, fname); /* name[s] */
1458 np_string(evb, uidlen, uid); /* uid[s] */
1459 np_string(evb, gidlen, gid); /* gid[s] */
1460 np_string(evb, ulen, muid); /* muid[s] */
1463 static void
1464 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1466 struct fid *f;
1467 ssize_t r;
1468 size_t howmuch;
1469 uint64_t off;
1470 uint32_t fid, count;
1471 char buf[2048];
1473 /* fid[4] offset[8] count[4] */
1474 if (!NPREAD32("fid", &fid, &data, &len) ||
1475 !NPREAD64("offset", &off, &data, &len) ||
1476 !NPREAD32("count", &count, &data, &len) ||
1477 len != 0) {
1478 client_send_listener(IMSG_CLOSE, NULL, 0);
1479 client_shutdown();
1480 return;
1483 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1484 np_error(hdr->tag, "invalid fid");
1485 return;
1488 if (TYPE_OVERFLOW(off_t, off)) {
1489 log_warnx("unexpected off_t size");
1490 np_error(hdr->tag, "invalid offset");
1491 return;
1494 if (f->d == NULL) {
1495 /* read a file */
1496 howmuch = MIN(sizeof(buf), count);
1497 r = pread(f->fd, buf, howmuch, (off_t)off);
1498 if (r == -1)
1499 np_errno(hdr->tag);
1500 else
1501 np_read(hdr->tag, r, buf);
1502 } else {
1503 if (off == 0 && f->offset != 0) {
1504 rewinddir(f->d);
1505 f->offset = 0;
1506 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1509 if (off != f->offset) {
1510 np_error(hdr->tag, "can't seek in directories");
1511 return;
1514 while (EVBUFFER_LENGTH(f->evb) < count) {
1515 struct dirent *d;
1516 struct stat sb;
1518 if ((d = readdir(f->d)) == NULL)
1519 break;
1520 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1521 warn("fstatat");
1522 continue;
1524 serialize_stat(d->d_name, &sb, f->evb);
1527 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1528 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1529 evbuffer_drain(f->evb, count);
1531 f->offset += count;
1535 static void
1536 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1538 struct fid *f;
1539 ssize_t r;
1540 uint64_t off;
1541 uint32_t fid, count;
1543 /* fid[4] offset[8] count[4] data[count] */
1544 if (!NPREAD32("fid", &fid, &data, &len) ||
1545 !NPREAD64("off", &off, &data, &len) ||
1546 !NPREAD32("count", &count, &data, &len) ||
1547 len != count) {
1548 client_send_listener(IMSG_CLOSE, NULL, 0);
1549 client_shutdown();
1550 return;
1553 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1554 np_error(hdr->tag, "invalid fid");
1555 return;
1558 if (!(f->iomode & O_WRONLY) &&
1559 !(f->iomode & O_RDWR)) {
1560 np_error(hdr->tag, "fid not opened for writing");
1561 return;
1564 if (TYPE_OVERFLOW(off_t, off)) {
1565 log_warnx("unexpected off_t size");
1566 np_error(hdr->tag, "invalid offset");
1567 return;
1570 if ((r = pwrite(f->fd, data, len, off)) == -1)
1571 np_errno(hdr->tag);
1572 else
1573 np_write(hdr->tag, r);
1576 static void
1577 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1579 struct evbuffer *evb;
1580 struct stat sb;
1581 struct fid *f;
1582 int r;
1583 uint32_t fid;
1585 /* fid[4] */
1586 if (!NPREAD32("fid", &fid, &data, &len) ||
1587 len != 0) {
1588 client_send_listener(IMSG_CLOSE, NULL, 0);
1589 client_shutdown();
1590 return;
1594 * plan9' stat(9P) is not clear on whether the stat is allowed
1595 * on opened fids or not. We're allowing stat regardless of the
1596 * status of the fid.
1599 if ((f = fid_by_id(fid)) == NULL) {
1600 np_error(hdr->tag, "invalid fid");
1601 return;
1604 if ((evb = evbuffer_new()) == NULL)
1605 fatal("evbuffer_new");
1607 if (f->fd != -1)
1608 r = fstat(f->fd, &sb);
1609 else if (f->qid.type & QTDIR)
1610 r = fstat(f->dir->fd, &sb);
1611 else
1612 r = fstatat(f->dir->fd, f->fname, &sb, 0);
1614 if (r == -1) {
1615 np_errno(hdr->tag);
1616 evbuffer_free(evb);
1617 return;
1620 serialize_stat(f->fname, &sb, evb);
1621 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1622 evbuffer_free(evb);
1625 static void
1626 twstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1628 struct timespec times[2];
1629 struct np_stat st;
1630 struct fid *f;
1631 int r;
1632 uint32_t fid;
1633 char name[PATH_MAX];
1635 /* fid[4] stat[n] */
1636 if (!NPREAD32("fid", &fid, &data, &len))
1637 goto err;
1639 switch (NPREADST("stat", &st, name, sizeof(name), &data, &len)) {
1640 case READSTRERR:
1641 goto err;
1642 case READSTRTRUNC:
1643 log_warnx("wstat new name would overflow");
1644 np_error(hdr->tag, "new name too long");
1645 return;
1649 * We skip the reading of some fields voluntarily because we
1650 * don't support chown, so len will always be > 0!
1652 #ifdef notyet
1653 if (len != 0)
1654 goto err;
1655 #endif
1657 if ((f = fid_by_id(fid)) == NULL) {
1658 np_error(hdr->tag, "invalid fid");
1659 return;
1663 * 9P wants these edits to be done in an atomic fashion,
1664 * something that I don't think it's possible on UNIX without
1665 * some special kernel help. Changing atime or mtime,
1666 * permissions, or rename the file are different syscalls.
1668 * Also, silently ignore stuff we can't/don't want to modify.
1671 /* change the permissions */
1672 if (st.mode != (uint32_t)-1) {
1673 mode_t m = st.mode & 0x7F; /* silently truncate higer bits */
1674 if (f->fd != -1)
1675 r = fchmod(f->fd, m);
1676 else
1677 r = fchmodat(f->dir->fd, f->fname, m, 0);
1679 if (r == -1) {
1680 np_errno(hdr->tag);
1681 return;
1685 /* change the atime/mtime of the fid, opened or not */
1686 if (st.atime != (uint32_t)-1 || st.mtime != (uint32_t)-1) {
1687 times[0].tv_nsec = UTIME_OMIT;
1688 times[1].tv_nsec = UTIME_OMIT;
1690 if (st.atime != (uint32_t)-1) {
1691 times[0].tv_sec = st.atime;
1692 times[0].tv_nsec = 0;
1694 if (st.mtime != (uint32_t)-1) {
1695 times[1].tv_sec = st.mtime;
1696 times[1].tv_nsec = 0;
1699 if (f->fd != -1)
1700 r = futimens(f->fd, times);
1701 else
1702 r = utimensat(f->dir->fd, f->fname, times, 0);
1704 if (r == -1) {
1705 np_errno(hdr->tag);
1706 return;
1710 /* truncate */
1711 if (st.length != (uint64_t)-1) {
1712 if (f->fd == -1) {
1713 np_error(hdr->tag, "can't truncate a non-opened fid");
1714 return;
1717 if (f->qid.type & QTDIR && st.length != 0) {
1718 np_error(hdr->tag, "can't truncate directories");
1719 return;
1722 if (TYPE_OVERFLOW(off_t, st.length)) {
1723 log_warnx("truncate request overflows off_t: %"PRIu64,
1724 st.length);
1725 np_error(hdr->tag, "length overflows");
1726 return;
1729 if (f->qid.type == 0 &&
1730 ftruncate(f->fd, st.length) == -1) {
1731 np_errno(hdr->tag);
1732 return;
1736 /* rename (change the name entry) */
1737 if (*st.name != '\0') {
1738 struct stat sb;
1739 const char *newname;
1742 * XXX: 9P requires that we disallow changing the name
1743 * to that of an existing file. We can't do that
1744 * atomically (rename is happy about stealing names)
1745 * so this is just a best effort.
1747 if (fstatat(f->dir->fd, st.name, &sb, 0) == -1 &&
1748 errno != ENOENT) {
1749 np_error(hdr->tag, "target file exists");
1750 return;
1753 r = renameat(f->dir->fd, f->fname, f->dir->fd, st.name);
1754 if (r == -1) {
1755 np_errno(hdr->tag);
1756 return;
1759 /* fix the fid so it points to the new file */
1761 if ((newname = strchr(st.name, '/')) != NULL)
1762 newname++; /* skip / */
1763 else
1764 newname = st.name;
1765 strlcpy(f->fname, newname, sizeof(f->fname));
1767 if (strchr(st.name, '/') != NULL) {
1768 struct dir *dir;
1769 char *dname;
1770 int fd;
1772 dname = dirname(st.name);
1773 fd = openat(f->dir->fd, dname, O_RDONLY|O_DIRECTORY);
1774 if (fd == -1) {
1775 np_errno(hdr->tag);
1776 free_fid(f);
1777 return;
1780 if ((dir = new_dir(fd)) == NULL) {
1781 np_errno(hdr->tag);
1782 free_fid(f);
1783 return;
1786 dir_decref(f->dir);
1787 f->dir = dir_incref(dir);
1791 np_wstat(hdr->tag);
1792 return;
1794 err:
1795 client_send_listener(IMSG_CLOSE, NULL, 0);
1796 client_shutdown();
1799 static void
1800 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1802 struct fid *f;
1803 uint32_t fid;
1804 int r;
1805 char dirpath[PATH_MAX + 3];
1807 /* fid[4] */
1808 if (!NPREAD32("fid", &fid, &data, &len) ||
1809 len != 0) {
1810 client_send_listener(IMSG_CLOSE, NULL, 0);
1811 client_shutdown();
1812 return;
1815 if ((f = fid_by_id(fid)) == NULL) {
1816 np_error(hdr->tag, "invalid fid");
1817 return;
1820 if (f->qid.type & QTDIR) { /* directory */
1821 strlcpy(dirpath, "../", sizeof(dirpath));
1822 strlcat(dirpath, f->fname, sizeof(dirpath));
1823 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1824 } else /* file */
1825 r = unlinkat(f->dir->fd, f->fname, 0);
1827 if (r == -1)
1828 np_errno(hdr->tag);
1829 else
1830 np_remove(hdr->tag);
1832 free_fid(f);
1835 static void
1836 handle_message(struct imsg *imsg, size_t len)
1838 struct msg {
1839 uint8_t type;
1840 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1841 } msgs[] = {
1842 {Tversion, tversion},
1843 {Tattach, tattach},
1844 {Tclunk, tclunk},
1845 {Tflush, tflush},
1846 {Twalk, twalk},
1847 {Topen, topen},
1848 {Tcreate, tcreate},
1849 {Tread, tread},
1850 {Twrite, twrite},
1851 {Tstat, tstat},
1852 {Twstat, twstat},
1853 {Tremove, tremove},
1855 struct np_msg_header hdr;
1856 size_t i;
1857 uint8_t *data;
1859 #if DEBUG_PACKETS
1860 hexdump("incoming packet", imsg->data, len);
1861 #endif
1863 parse_message(imsg->data, len, &hdr, &data);
1864 len -= HEADERSIZE;
1866 log_debug("got request: len=%d type=%d[%s] tag=%d",
1867 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1869 if (!handshaked && hdr.type != Tversion) {
1870 client_send_listener(IMSG_CLOSE, NULL, 0);
1871 client_shutdown();
1872 return;
1875 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1876 if (msgs[i].type != hdr.type)
1877 continue;
1879 msgs[i].fn(&hdr, data, len);
1880 return;
1883 np_error(hdr.tag, "Not supported.");