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_listener(int, const void *, uint16_t);
113 static void qid_update_from_sb(struct qid *, struct stat *);
115 static struct dir *new_dir(int);
116 static struct dir *dir_incref(struct dir *);
117 static void dir_decref(struct dir *);
119 static struct fid *new_fid(struct dir *, uint32_t, const char *, struct qid *);
120 static struct fid *fid_by_id(uint32_t);
121 static void free_fid(struct fid *);
123 static void parse_message(const uint8_t *, size_t,
124 struct np_msg_header *, uint8_t **);
126 static void np_write16(struct evbuffer *, uint16_t);
127 static void np_write32(struct evbuffer *, uint32_t);
128 static void np_write64(struct evbuffer *, uint64_t);
129 static void np_header(uint32_t, uint8_t, uint16_t);
130 static void np_string(struct evbuffer *, uint16_t, const char *);
131 static void np_qid(struct evbuffer *, struct qid *);
132 static void do_send(void);
134 static void np_version(uint16_t, uint32_t, const char *);
135 static void np_attach(uint16_t, struct qid *);
136 static void np_clunk(uint16_t);
137 static void np_flush(uint16_t);
138 static void np_walk(uint16_t, int, struct qid *);
139 static void np_open(uint16_t, struct qid *, uint32_t);
140 static void np_create(uint16_t, struct qid *, uint32_t);
141 static void np_read(uint16_t, uint32_t, void *);
142 static void np_write(uint16_t, uint32_t);
143 static void np_stat(uint16_t, uint32_t, void *);
144 static void np_wstat(uint16_t);
145 static void np_remove(uint16_t);
146 static void np_error(uint16_t, const char *);
147 static void np_errno(uint16_t);
149 static int np_read8(const char *, const char *, uint8_t *,
150 const uint8_t **, size_t *);
151 static int np_read16(const char *, const char *, uint16_t *,
152 const uint8_t **, size_t *);
153 static int np_read32(const char *, const char *, uint32_t *,
154 const uint8_t **, size_t *);
155 static int np_read64(const char *, const char *, uint64_t *,
156 const uint8_t **, size_t *);
158 #define READSTRERR -1
159 #define READSTRTRUNC -2
160 static int np_readstr(const char *, const char *, char *, size_t,
161 const uint8_t **, size_t *);
163 static int np_readst(const char *, const char *, struct np_stat *,
164 char *, size_t, const uint8_t **, size_t *);
166 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
167 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
168 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
169 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
171 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
173 #define NPREADST(f, dst, n, nl, src, len) np_readst(__func__, f, dst, n, nl, src, len)
175 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
176 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
177 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
178 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
179 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
180 static void topen(struct np_msg_header *, const uint8_t *, size_t);
181 static void tcreate(struct np_msg_header *, const uint8_t *, size_t);
182 static void tread(struct np_msg_header *, const uint8_t *, size_t);
183 static void twrite(struct np_msg_header *, const uint8_t *, size_t);
184 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
185 static void twstat(struct np_msg_header *, const uint8_t *, size_t);
186 static void tremove(struct np_msg_header *, const uint8_t *, size_t);
187 static void handle_message(struct imsg *, size_t);
189 __dead void
190 client(int debug, int verbose)
192 struct event ev_sigint, ev_sigterm;
194 log_init(debug, LOG_DAEMON);
195 log_setverbose(verbose);
197 setproctitle("client");
198 log_procinit("client");
200 log_debug("warming up");
202 event_init();
204 /* Setup signal handlers */
205 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
206 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
208 signal_add(&ev_sigint, NULL);
209 signal_add(&ev_sigterm, NULL);
211 signal(SIGPIPE, SIG_IGN);
212 signal(SIGHUP, SIG_IGN);
214 /* Setup pipe and event handler to the listener process */
215 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
216 fatal(NULL);
218 imsg_init(&iev_listener->ibuf, 3);
219 iev_listener->handler = client_dispatch_listener;
221 /* Setup event handlers. */
222 iev_listener->events = EV_READ;
223 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
224 iev_listener->events, iev_listener->handler, iev_listener);
225 event_add(&iev_listener->ev, NULL);
227 event_dispatch();
228 client_shutdown();
231 static __dead void
232 client_shutdown(void)
234 if (evb != NULL)
235 evbuffer_free(evb);
237 msgbuf_clear(&iev_listener->ibuf.w);
238 close(iev_listener->ibuf.fd);
240 free(iev_listener);
242 log_debug("client exiting");
243 exit(0);
246 static void
247 client_sig_handler(int sig, short event, void *d)
249 /*
250 * Normal signal handler rules don't apply because libevent
251 * decouples for us.
252 */
254 switch (sig) {
255 case SIGINT:
256 case SIGTERM:
257 client_shutdown();
258 default:
259 fatalx("unexpected signal %d", sig);
263 static void
264 client_dispatch_listener(int fd, short event, void *d)
266 static int auth = 0;
267 struct kd_auth_proc rauth;
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_AUTH:
304 peerid = imsg.hdr.peerid;
305 if (auth)
306 fatalx("%s: IMSG_AUTH already done", __func__);
307 auth = 1;
309 if (IMSG_DATA_SIZE(imsg) != sizeof(rauth))
310 fatalx("mismatching size for IMSG_AUTH");
311 memcpy(&rauth, imsg.data, sizeof(rauth));
312 if (rauth.uname[sizeof(rauth.uname)-1] != '\0' ||
313 rauth.dir[sizeof(rauth.dir)-1] != '\0')
314 fatalx("IMSG_AUTH strings not NUL-terminated");
316 client_privdrop(rauth.uname, rauth.dir);
317 explicit_bzero(&rauth, sizeof(rauth));
318 break;
319 case IMSG_BUF:
320 if (!auth)
321 fatalx("%s: can't handle messages before"
322 " doing the auth", __func__);
323 handle_message(&imsg, IMSG_DATA_SIZE(imsg));
324 break;
325 case IMSG_CONN_GONE:
326 log_debug("closing");
327 shut = 1;
328 break;
329 default:
330 log_debug("%s: unexpected imsg %d",
331 __func__, imsg.hdr.type);
332 break;
334 imsg_free(&imsg);
337 if (!shut)
338 imsg_event_add(iev);
339 else {
340 /* This pipe is dead. Remove its event handler. */
341 event_del(&iev->ev);
342 log_debug("pipe closed, shutting down...");
343 event_loopexit(NULL);
347 static void
348 client_privdrop(const char *username, const char *dir)
350 struct passwd *pw;
352 setproctitle("client %s", username);
354 if ((pw = getpwnam(username)) == NULL)
355 fatalx("getpwnam(%s) failed", username);
357 if (chroot(dir) == -1)
358 fatal("chroot");
359 if (chdir("/") == -1)
360 fatal("chdir(\"/\")");
362 if (setgroups(1, &pw->pw_gid) ||
363 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
364 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
365 fatal("can't drop privileges");
367 sandbox_client();
368 log_debug("client ready; user=%s dir=%s", username, dir);
370 if ((evb = evbuffer_new()) == NULL)
371 fatal("evbuffer_new");
374 static int
375 client_send_listener(int type, const void *data, uint16_t len)
377 int ret;
379 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
380 data, len)) != -1)
381 imsg_event_add(iev_listener);
383 return ret;
386 /* set qid fields from sb */
387 static void
388 qid_update_from_sb(struct qid *qid, struct stat *sb)
390 qid->path = sb->st_ino;
392 /*
393 * Theoretically (and hopefully!) this should be a 64 bit
394 * number. Unfortunately, 9P uses 32 bit timestamps.
395 */
396 qid->vers = sb->st_mtim.tv_sec;
398 if (S_ISREG(sb->st_mode))
399 qid->type = QTFILE;
400 else if (S_ISDIR(sb->st_mode))
401 qid->type = QTDIR;
402 else if (S_ISLNK(sb->st_mode))
403 qid->type = QTSYMLINK;
406 /* creates a qid given a fd */
407 static struct dir *
408 new_dir(int fd)
410 struct dir *dir;
412 if ((dir = calloc(1, sizeof(*dir))) == NULL)
413 return NULL;
415 dir->fd = fd;
416 STAILQ_INSERT_HEAD(&dirs, dir, entries);
417 return dir;
420 static struct dir *
421 dir_incref(struct dir *dir)
423 dir->refcount++;
424 return dir;
427 static void
428 dir_decref(struct dir *dir)
430 if (--dir->refcount > 0)
431 return;
433 STAILQ_REMOVE(&dirs, dir, dir, entries);
435 close(dir->fd);
436 free(dir);
439 static struct fid *
440 new_fid(struct dir *dir, uint32_t fid, const char *path, struct qid *qid)
442 struct fid *f;
443 struct qid q;
444 struct stat sb;
446 if (qid == NULL) {
447 if (fstatat(dir->fd, path, &sb, 0)) {
448 log_warn("fstatat(%s)", path);
449 return NULL;
451 qid_update_from_sb(&q, &sb);
452 qid = &q;
455 if ((f = calloc(1, sizeof(*f))) == NULL)
456 return NULL;
458 f->dir = dir_incref(dir);
459 f->fid = fid;
460 f->fd = -1;
462 strlcpy(f->fname, path, sizeof(f->fname));
464 memcpy(&f->qid, qid, sizeof(f->qid));
466 STAILQ_INSERT_HEAD(&fids, f, entries);
468 return f;
471 static struct fid *
472 fid_by_id(uint32_t fid)
474 struct fid *f;
476 STAILQ_FOREACH(f, &fids, entries) {
477 if (f->fid == fid)
478 return f;
481 return NULL;
484 static void
485 free_fid(struct fid *f)
487 int r;
489 if (f->fd != -1) {
490 if (f->d != NULL)
491 r = closedir(f->d);
492 else
493 r = close(f->fd);
495 if (r == -1)
496 fatal("can't close fid %d", f->fid);
498 if (f->evb != NULL)
499 evbuffer_free(f->evb);
501 /* try to honour ORCLOSE if requested */
502 if (f->iomode & O_CLOEXEC)
503 unlinkat(f->dir->fd, f->fname, 0);
506 dir_decref(f->dir);
508 STAILQ_REMOVE(&fids, f, fid, entries);
509 free(f);
512 static void
513 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
514 uint8_t **cnt)
516 size_t olen = len;
518 if (!NPREAD32("len", &hdr->len, &data, &len) ||
519 !NPREAD8("type", &hdr->type, &data, &len) ||
520 !NPREAD16("tag", &hdr->tag, &data, &len))
521 goto err;
523 if (olen != hdr->len)
524 goto err;
526 if (hdr->type < Tversion ||
527 hdr->type >= Tmax ||
528 hdr->type == Terror ||
529 (hdr->type & 0x1) != 0) /* cannot recv a R* */
530 goto err;
532 hdr->tag = le32toh(hdr->tag);
534 *cnt = (uint8_t *)data;
535 return;
537 err:
538 /* TODO: send a proper message to terminate the connection. */
539 fatalx("got invalid message");
542 static void
543 np_write16(struct evbuffer *e, uint16_t x)
545 x = htole16(x);
546 evbuffer_add(e, &x, sizeof(x));
549 static void
550 np_write32(struct evbuffer *e, uint32_t x)
552 x = htole32(x);
553 evbuffer_add(e, &x, sizeof(x));
556 static void
557 np_write64(struct evbuffer *e, uint64_t x)
559 x = htole64(x);
560 evbuffer_add(e, &x, sizeof(x));
563 static void
564 np_writebuf(struct evbuffer *e, size_t len, void *data)
566 evbuffer_add(e, data, len);
569 static void
570 np_header(uint32_t len, uint8_t type, uint16_t tag)
572 len += HEADERSIZE;
574 len = htole32(len);
575 tag = htole16(tag);
577 evbuffer_add(evb, &len, sizeof(len));
578 evbuffer_add(evb, &type, sizeof(type));
579 evbuffer_add(evb, &tag, sizeof(tag));
582 static void
583 np_string(struct evbuffer *e, uint16_t len, const char *str)
585 uint16_t l = len;
587 len = htole16(len);
588 evbuffer_add(e, &len, sizeof(len));
589 evbuffer_add(e, str, l);
592 static void
593 np_qid(struct evbuffer *e, struct qid *qid)
595 uint64_t path;
596 uint32_t vers;
598 path = htole64(qid->path);
599 vers = htole32(qid->vers);
601 evbuffer_add(e, &qid->type, sizeof(qid->type));
602 evbuffer_add(e, &vers, sizeof(vers));
603 evbuffer_add(e, &path, sizeof(path));
606 static void
607 do_send(void)
609 size_t len;
610 void *data;
612 len = EVBUFFER_LENGTH(evb);
613 data = EVBUFFER_DATA(evb);
615 #if DEBUG_PACKETS
616 hexdump("outgoing packet", data, len);
617 #endif
618 client_send_listener(IMSG_BUF, data, len);
619 evbuffer_drain(evb, len);
622 static void
623 np_version(uint16_t tag, uint32_t msize, const char *version)
625 uint16_t l;
627 l = strlen(version);
629 msize = htole32(msize);
631 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
632 evbuffer_add(evb, &msize, sizeof(msize));
633 np_string(evb, l, version);
634 do_send();
637 static void
638 np_attach(uint16_t tag, struct qid *qid)
640 np_header(QIDSIZE, Rattach, tag);
641 np_qid(evb, qid);
642 do_send();
645 static void
646 np_clunk(uint16_t tag)
648 np_header(0, Rclunk, tag);
649 do_send();
652 static void
653 np_flush(uint16_t tag)
655 np_header(0, Rflush, tag);
656 do_send();
659 static void
660 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
662 int i;
664 /* two bytes for the counter */
665 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
666 np_write16(evb, nwqid);
667 for (i = 0; i < nwqid; ++i)
668 np_qid(evb, wqid + i);
670 do_send();
673 static void
674 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
676 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
677 np_qid(evb, qid);
678 np_write32(evb, iounit);
679 do_send();
682 static void
683 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
685 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
686 np_qid(evb, qid);
687 np_write32(evb, iounit);
688 do_send();
691 static void
692 np_read(uint16_t tag, uint32_t count, void *data)
694 if (sizeof(count) + count + HEADERSIZE >= msize) {
695 np_error(tag, "Rread would overflow");
696 return;
699 np_header(sizeof(count) + count, Rread, tag);
700 np_write32(evb, count);
701 np_writebuf(evb, count, data);
702 do_send();
705 static void
706 np_write(uint16_t tag, uint32_t count)
708 np_header(sizeof(count), Rwrite, tag);
709 np_write32(evb, count);
710 do_send();
713 static void
714 np_stat(uint16_t tag, uint32_t count, void *data)
716 if (sizeof(count) + count + HEADERSIZE >= msize) {
717 np_error(tag, "Rstat would overflow");
718 return;
721 np_header(count, Rstat, tag);
722 np_writebuf(evb, count, data);
723 do_send();
726 static void
727 np_wstat(uint16_t tag)
729 np_header(0, Rwstat, tag);
730 do_send();
733 static void
734 np_remove(uint16_t tag)
736 np_header(0, Rremove, tag);
737 do_send();
740 static void
741 np_error(uint16_t tag, const char *errstr)
743 uint16_t l;
745 l = strlen(errstr);
747 np_header(sizeof(l) + l, Rerror, tag);
748 np_string(evb, l, errstr);
749 do_send();
752 static void
753 np_errno(uint16_t tag)
755 int saved_errno;
756 char buf[NL_TEXTMAX] = {0};
758 saved_errno = errno;
760 strerror_r(errno, buf, sizeof(buf));
761 np_error(tag, buf);
763 errno = saved_errno;
766 static int
767 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
768 size_t *len)
770 if (*len < sizeof(*dst)) {
771 log_warnx("%s: wanted %zu bytes for the %s field but only "
772 "%zu are available.", t, sizeof(*dst), f, *len);
773 return 0;
776 memcpy(dst, *src, sizeof(*dst));
777 *src += sizeof(*dst);
778 *len -= sizeof(*dst);
780 return 1;
783 static int
784 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
785 size_t *len)
787 if (*len < sizeof(*dst)) {
788 log_warnx("%s: wanted %zu bytes for the %s field but only "
789 "%zu are available.", t, sizeof(*dst), f, *len);
790 return 0;
793 memcpy(dst, *src, sizeof(*dst));
794 *src += sizeof(*dst);
795 *len -= sizeof(*dst);
796 *dst = le16toh(*dst);
798 return 1;
801 static int
802 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
803 size_t *len)
805 if (*len < sizeof(*dst)) {
806 log_warnx("%s: wanted %zu bytes for the %s field but only "
807 "%zu are available.", t, sizeof(*dst), f, *len);
808 return 0;
811 memcpy(dst, *src, sizeof(*dst));
812 *src += sizeof(*dst);
813 *len -= sizeof(*dst);
814 *dst = le32toh(*dst);
816 return 1;
819 static int
820 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
821 size_t *len)
823 if (*len < sizeof(*dst)) {
824 log_warnx("%s: wanted %zu bytes for the %s field but only "
825 "%zu are available.", t, sizeof(*dst), f, *len);
826 return 0;
829 memcpy(dst, *src, sizeof(*dst));
830 *src += sizeof(*dst);
831 *len -= sizeof(*dst);
832 *dst = le64toh(*dst);
834 return 1;
837 static int
838 np_readstr(const char *t, const char *f, char *res, size_t reslen,
839 const uint8_t **src, size_t *len)
841 uint16_t sl;
842 char buf[32];
844 strlcpy(buf, f, sizeof(buf));
845 strlcat(buf, "-len", sizeof(buf));
847 if (!np_read16(t, buf, &sl, src, len))
848 return READSTRERR;
850 if (*len < sl) {
851 log_warnx("%s: wanted %d bytes for the %s field but only "
852 "%zu are available.", t, sl, f, *len);
853 return READSTRERR;
856 if (*len > reslen-1)
857 return READSTRTRUNC;
859 memcpy(res, *src, sl);
860 res[sl] = '\0';
861 *src += sl;
862 *len -= sl;
864 return 0;
867 static int
868 np_readst(const char *t, const char *f, struct np_stat *st,
869 char *name, size_t namelen, const uint8_t **src, size_t *len)
871 memset(st, 0, sizeof(*st));
873 if (!np_read16(t, "stat.size", &st->size, src, len) ||
874 !np_read16(t, "stat.type", &st->type, src, len) ||
875 !np_read32(t, "stat.dev", &st->dev, src, len) ||
876 !np_read64(t, "stat.qid.path", &st->qid.path, src, len) ||
877 !np_read32(t, "stat.qid.vers", &st->qid.vers, src, len) ||
878 !np_read8(t, "stat.qid.type", &st->qid.type, src, len) ||
879 !np_read32(t, "stat.mode", &st->mode, src, len) ||
880 !np_read32(t, "stat.atime", &st->atime, src, len) ||
881 !np_read32(t, "stat.mtime", &st->mtime, src, len) ||
882 !np_read64(t, "stat.length", &st->length, src, len))
883 return READSTRERR;
885 /*
886 * ignore everything but the name, we don't support
887 * changing those fields anyway
888 */
889 st->name = name;
890 return np_readstr(t, "stat.name", name, namelen, src, len);
893 static void
894 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
896 char *dot, version[32];
898 if (handshaked)
899 goto err;
901 /* msize[4] version[s] */
902 if (!NPREAD32("msize", &msize, &data, &len))
903 goto err;
905 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
906 case READSTRERR:
907 goto err;
908 case READSTRTRUNC:
909 log_warnx("9P version string too long, truncated");
910 goto mismatch;
913 if (len != 0)
914 goto err;
916 if ((dot = strchr(version, '.')) != NULL)
917 *dot = '\0';
919 if (strcmp(version, VERSION9P) != 0 ||
920 msize == 0)
921 goto mismatch;
923 /* version matched */
924 handshaked = 1;
925 msize = MIN(msize, CLIENT_MSIZE);
926 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
927 np_version(hdr->tag, msize, VERSION9P);
928 return;
930 mismatch:
931 log_warnx("unknown 9P version string: \"%s\", want "VERSION9P,
932 version);
933 np_version(hdr->tag, MSIZE9P, "unknown");
934 return;
936 err:
937 client_send_listener(IMSG_CLOSE, NULL, 0);
938 client_shutdown();
941 static void
942 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
944 struct dir *dir;
945 struct fid *f;
946 uint32_t fid, afid;
947 int fd;
948 char aname[PATH_MAX];
950 /* fid[4] afid[4] uname[s] aname[s] */
952 if (!NPREAD32("fid", &fid, &data, &len) ||
953 !NPREAD32("afid", &afid, &data, &len))
954 goto err;
956 /* read the uname but don't actually use it */
957 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
958 case READSTRERR:
959 goto err;
960 case READSTRTRUNC:
961 np_error(hdr->tag, "name too long");
962 return;
965 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
966 case READSTRERR:
967 goto err;
968 case READSTRTRUNC:
969 np_error(hdr->tag, "name too long");
970 return;
973 if (len != 0)
974 goto err;
976 if (fid_by_id(fid) != NULL || afid != NOFID) {
977 np_error(hdr->tag, "invalid fid or afid");
978 return;
981 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
982 goto fail;
984 if ((dir = new_dir(fd)) == NULL)
985 goto fail;
987 log_debug("attached %s to %d", aname, fid);
989 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
990 dir_decref(dir);
991 goto fail;
994 np_attach(hdr->tag, &f->qid);
995 return;
997 fail:
998 np_errno(hdr->tag);
999 log_warn("failed to attach %s", aname);
1000 return;
1002 err:
1003 client_send_listener(IMSG_CLOSE, NULL, 0);
1004 client_shutdown();
1007 static void
1008 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1010 struct fid *f;
1011 uint32_t fid;
1013 /* fid[4] */
1014 if (!NPREAD32("fid", &fid, &data, &len) ||
1015 len != 0) {
1016 client_send_listener(IMSG_CLOSE, NULL, 0);
1017 client_shutdown();
1018 return;
1021 if ((f = fid_by_id(fid)) == NULL) {
1022 np_error(hdr->tag, "invalid fid");
1023 return;
1026 free_fid(f);
1027 np_clunk(hdr->tag);
1030 static void
1031 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1033 uint16_t oldtag;
1036 * We're doing only synchronous I/O. Tflush is implemented
1037 * only because it's illegal to reply with a Rerror.
1040 /* oldtag[2] */
1041 if (len != sizeof(oldtag)) {
1042 log_warnx("Tflush with the wrong size: got %zu want %zu",
1043 len, sizeof(oldtag));
1044 client_send_listener(IMSG_CLOSE, NULL, 0);
1045 client_shutdown();
1046 return;
1049 np_flush(hdr->tag);
1052 static void
1053 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1055 struct stat sb;
1056 struct dir *dir;
1057 struct qid wqid[MAXWELEM] = {0};
1058 struct fid *f, *nf;
1059 uint32_t fid, newfid;
1060 uint16_t nwname;
1061 int fd, oldfd, no, nwqid = 0;
1062 char wnam[PATH_MAX];
1064 if (!NPREAD32("fid", &fid, &data, &len) ||
1065 !NPREAD32("newfid", &newfid, &data, &len) ||
1066 !NPREAD16("nwname", &nwname, &data, &len))
1067 goto err;
1069 if (nwname > MAXWELEM) {
1070 log_warnx("Twalk: more than %d path elements: %d",
1071 MAXWELEM, nwname);
1072 goto err;
1075 if ((f = fid_by_id(fid)) == NULL) {
1076 np_error(hdr->tag, "invalid fid");
1077 return;
1080 if (f->fd != -1) {
1081 np_error(hdr->tag, "fid already opened for I/O");
1082 return;
1085 if (fid == newfid)
1086 nf = f;
1087 else if ((nf = fid_by_id(newfid)) != NULL) {
1088 np_error(hdr->tag, "newfid already in use");
1089 return;
1090 } else
1091 nf = NULL;
1093 /* special case: fid duplication */
1094 if (nwname == 0) {
1096 * TODO: should we forbid fids duplication when fid ==
1097 * newfid?
1099 if (nf == NULL &&
1100 (nf = new_fid(f->dir, newfid, f->fname, &f->qid)) == NULL)
1101 fatal("new_fid duplication");
1103 np_walk(hdr->tag, 0, NULL);
1104 return;
1107 if (!(f->qid.type & QTDIR)) {
1108 np_error(hdr->tag, "fid doesn't represent a directory");
1109 return;
1112 oldfd = f->dir->fd;
1114 for (nwqid = 0; nwqid < nwname; nwqid++) {
1115 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1116 case READSTRERR:
1117 goto err;
1118 case READSTRTRUNC:
1119 np_error(hdr->tag, "wname too long");
1120 return;
1123 if (*wnam == '\0' ||
1124 strchr(wnam, '/') != NULL ||
1125 !strcmp(wnam, ".")) {
1126 errno = EINVAL;
1127 goto cantopen;
1130 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1131 errno != ENOTDIR)
1132 goto cantopen;
1134 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1135 (fd != -1 && fstat(fd, &sb) == -1))
1136 goto cantopen;
1138 qid_update_from_sb(&wqid[nwqid], &sb);
1140 /* reached a file but we still have other components */
1141 if (fd == -1 && nwqid+1 < nwname)
1142 goto cantopen;
1144 /* reached the end and found a file */
1145 if (fd == -1 && nwqid+1 == nwname)
1146 continue;
1148 if (oldfd != f->dir->fd)
1149 close(oldfd);
1150 oldfd = fd;
1153 if (len != 0)
1154 goto err;
1157 * If fd is -1 we've reached a file, otherwise we've just
1158 * reached another directory. We must pay attention to what
1159 * file descriptor we use to create the dir, because if we've
1160 * reached a file and oldfd is f->dir->fd then we *must* share
1161 * the same dir (it was a walk of one path from a directory to a
1162 * file, otherwise fun is bound to happen as soon as the client
1163 * closes the fid for the directory but keeps the one for the
1164 * file.
1166 if (fd == -1 && oldfd == f->dir->fd)
1167 dir = f->dir;
1168 else if (fd == -1)
1169 dir = new_dir(oldfd);
1170 else
1171 dir = new_dir(fd);
1173 if (dir == NULL)
1174 fatal("new_dir");
1176 if (nf == NULL) {
1177 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1178 fatal("new fid");
1179 } else {
1180 /* update the dir */
1181 dir_decref(nf->dir);
1182 nf->dir = dir_incref(dir);
1185 np_walk(hdr->tag, nwqid, wqid);
1186 return;
1188 cantopen:
1189 if (oldfd != f->dir->fd)
1190 close(oldfd);
1191 no = errno;
1192 if (nwqid == 0)
1193 np_error(hdr->tag, strerror(no));
1194 else
1195 np_walk(hdr->tag, nwqid, wqid);
1196 return;
1198 err:
1199 client_send_listener(IMSG_CLOSE, NULL, 0);
1200 client_shutdown();
1203 static inline int
1204 npmode_to_unix(uint8_t mode, int *flags)
1206 switch (mode & 0x0F) {
1207 case KOREAD:
1208 *flags = O_RDONLY;
1209 break;
1210 case KOWRITE:
1211 *flags = O_WRONLY;
1212 break;
1213 case KORDWR:
1214 *flags = O_RDWR;
1215 break;
1216 case KOEXEC:
1217 log_warnx("tried to open something with KOEXEC");
1218 /* fallthrough */
1219 default:
1220 return -1;
1223 if (mode & KOTRUNC)
1224 *flags |= O_TRUNC;
1225 if (mode & KORCLOSE)
1226 *flags |= O_CLOEXEC;
1228 return 0;
1231 static void
1232 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1234 struct stat sb;
1235 struct qid qid;
1236 struct fid *f;
1237 uint32_t fid;
1238 uint8_t mode;
1239 const char *path;
1241 /* fid[4] mode[1] */
1242 if (!NPREAD32("fid", &fid, &data, &len) ||
1243 !NPREAD8("mode", &mode, &data, &len) ||
1244 len != 0) {
1245 client_send_listener(IMSG_CLOSE, NULL, 0);
1246 client_shutdown();
1247 return;
1250 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1251 np_error(hdr->tag, "invalid fid");
1252 return;
1255 if (npmode_to_unix(mode, &f->iomode) == -1) {
1256 np_error(hdr->tag, "invalid mode");
1257 return;
1260 path = f->fname;
1261 if (f->qid.type & QTDIR)
1262 path = ".";
1264 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1265 np_error(hdr->tag, strerror(errno));
1266 return;
1269 if (fstat(f->fd, &sb) == -1)
1270 fatal("fstat");
1272 if (S_ISDIR(sb.st_mode)) {
1273 if ((f->d = fdopendir(f->fd)) == NULL) {
1274 np_errno(hdr->tag);
1275 close(f->fd);
1276 f->fd = -1;
1277 return;
1280 if ((f->evb = evbuffer_new()) == NULL) {
1281 np_errno(hdr->tag);
1282 closedir(f->d);
1283 f->d = NULL;
1284 f->fd = -1;
1288 f->offset = 0;
1290 qid_update_from_sb(&qid, &sb);
1291 np_open(hdr->tag, &qid, sb.st_blksize);
1294 static void
1295 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1297 struct stat sb;
1298 struct qid qid;
1299 struct fid *f;
1300 uint32_t fid, perm;
1301 uint8_t mode;
1302 char name[PATH_MAX];
1304 /* fid[4] name[s] perm[4] mode[1] */
1305 if (!NPREAD32("fid", &fid, &data, &len))
1306 goto err;
1307 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1308 case READSTRERR:
1309 goto err;
1310 case READSTRTRUNC:
1311 np_error(hdr->tag, "name too long");
1312 return;
1314 if (!NPREAD32("perm", &perm, &data, &len) ||
1315 !NPREAD8("mode", &mode, &data, &len) ||
1316 len != 0)
1317 goto err;
1319 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1320 strchr(name, '/') != NULL) {
1321 np_error(hdr->tag, "invalid name");
1322 return;
1325 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1326 np_error(hdr->tag, "invalid fid");
1327 return;
1330 if (!(f->qid.type & QTDIR)) {
1331 np_error(hdr->tag, "fid doesn't identify a directory");
1332 return;
1335 if (npmode_to_unix(mode, &f->iomode) == -1) {
1336 np_error(hdr->tag, "invalid mode");
1337 return;
1340 if (f->iomode & O_RDONLY) {
1341 np_error(hdr->tag, "can't create a read-only file");
1342 return;
1345 /* TODO: parse the mode */
1347 if (perm & 0x80000000) {
1348 /* create a directory */
1349 f->fd = mkdirat(f->dir->fd, name, 0755);
1350 } else {
1351 /* create a file */
1352 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1353 0644);
1356 if (f->fd == -1) {
1357 np_errno(hdr->tag);
1358 return;
1361 if (fstat(f->fd, &sb) == -1)
1362 fatal("fstat");
1364 if (S_ISDIR(sb.st_mode)) {
1365 if ((f->d = fdopendir(f->fd)) == NULL) {
1366 np_errno(hdr->tag);
1367 close(f->fd);
1368 f->fd = -1;
1369 return;
1372 if ((f->evb = evbuffer_new()) == NULL) {
1373 np_errno(hdr->tag);
1374 closedir(f->d);
1375 f->d = NULL;
1376 f->fd = -1;
1380 f->offset = 0;
1382 qid_update_from_sb(&qid, &sb);
1383 np_create(hdr->tag, &qid, sb.st_blksize);
1385 return;
1387 err:
1388 client_send_listener(IMSG_CLOSE, NULL, 0);
1389 client_shutdown();
1392 static inline void
1393 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1395 struct qid qid;
1396 const char *uid, *gid, *muid;
1397 size_t tot;
1398 uint16_t namlen, uidlen, gidlen, ulen;
1400 qid_update_from_sb(&qid, sb);
1402 /* TODO: fill these fields */
1403 uid = "";
1404 gid = "";
1405 muid = "";
1407 namlen = strlen(fname);
1408 uidlen = strlen(uid);
1409 gidlen = strlen(gid);
1410 ulen = strlen(muid);
1412 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1413 if (tot > UINT32_MAX) {
1414 log_warnx("stat info for dir entry %s would overflow",
1415 fname);
1416 return;
1419 np_write16(evb, tot); /* size[2] */
1420 np_write16(evb, sb->st_rdev); /* type[2] */
1421 np_write32(evb, sb->st_dev); /* dev[4] */
1422 np_qid(evb, &qid); /* qid[13] */
1424 /* XXX: translate? */
1425 np_write32(evb, sb->st_mode); /* mode[4] */
1427 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1428 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1430 /* special case: directories have size 0 */
1431 if (qid.type & QTDIR)
1432 np_write64(evb, 0);
1433 else
1434 np_write64(evb, sb->st_size); /* length[8] */
1436 np_string(evb, namlen, fname); /* name[s] */
1437 np_string(evb, uidlen, uid); /* uid[s] */
1438 np_string(evb, gidlen, gid); /* gid[s] */
1439 np_string(evb, ulen, muid); /* muid[s] */
1442 static void
1443 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1445 struct fid *f;
1446 ssize_t r;
1447 size_t howmuch;
1448 uint64_t off;
1449 uint32_t fid, count;
1450 char buf[2048];
1452 /* fid[4] offset[8] count[4] */
1453 if (!NPREAD32("fid", &fid, &data, &len) ||
1454 !NPREAD64("offset", &off, &data, &len) ||
1455 !NPREAD32("count", &count, &data, &len) ||
1456 len != 0) {
1457 client_send_listener(IMSG_CLOSE, NULL, 0);
1458 client_shutdown();
1459 return;
1462 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1463 np_error(hdr->tag, "invalid fid");
1464 return;
1467 if (TYPE_OVERFLOW(off_t, off)) {
1468 log_warnx("unexpected off_t size");
1469 np_error(hdr->tag, "invalid offset");
1470 return;
1473 if (f->d == NULL) {
1474 /* read a file */
1475 howmuch = MIN(sizeof(buf), count);
1476 r = pread(f->fd, buf, howmuch, (off_t)off);
1477 if (r == -1)
1478 np_errno(hdr->tag);
1479 else
1480 np_read(hdr->tag, r, buf);
1481 } else {
1482 if (off == 0 && f->offset != 0) {
1483 rewinddir(f->d);
1484 f->offset = 0;
1485 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1488 if (off != f->offset) {
1489 np_error(hdr->tag, "can't seek in directories");
1490 return;
1493 while (EVBUFFER_LENGTH(f->evb) < count) {
1494 struct dirent *d;
1495 struct stat sb;
1497 if ((d = readdir(f->d)) == NULL)
1498 break;
1499 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1500 warn("fstatat");
1501 continue;
1503 serialize_stat(d->d_name, &sb, f->evb);
1506 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1507 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1508 evbuffer_drain(f->evb, count);
1510 f->offset += count;
1514 static void
1515 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1517 struct fid *f;
1518 ssize_t r;
1519 uint64_t off;
1520 uint32_t fid, count;
1522 /* fid[4] offset[8] count[4] data[count] */
1523 if (!NPREAD32("fid", &fid, &data, &len) ||
1524 !NPREAD64("off", &off, &data, &len) ||
1525 !NPREAD32("count", &count, &data, &len) ||
1526 len != count) {
1527 client_send_listener(IMSG_CLOSE, NULL, 0);
1528 client_shutdown();
1529 return;
1532 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1533 np_error(hdr->tag, "invalid fid");
1534 return;
1537 if (!(f->iomode & O_WRONLY) &&
1538 !(f->iomode & O_RDWR)) {
1539 np_error(hdr->tag, "fid not opened for writing");
1540 return;
1543 if (TYPE_OVERFLOW(off_t, off)) {
1544 log_warnx("unexpected off_t size");
1545 np_error(hdr->tag, "invalid offset");
1546 return;
1549 if ((r = pwrite(f->fd, data, len, off)) == -1)
1550 np_errno(hdr->tag);
1551 else
1552 np_write(hdr->tag, r);
1555 static void
1556 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1558 struct evbuffer *evb;
1559 struct stat sb;
1560 struct fid *f;
1561 int r;
1562 uint32_t fid;
1564 /* fid[4] */
1565 if (!NPREAD32("fid", &fid, &data, &len) ||
1566 len != 0) {
1567 client_send_listener(IMSG_CLOSE, NULL, 0);
1568 client_shutdown();
1569 return;
1573 * plan9' stat(9P) is not clear on whether the stat is allowed
1574 * on opened fids or not. We're allowing stat regardless of the
1575 * status of the fid.
1578 if ((f = fid_by_id(fid)) == NULL) {
1579 np_error(hdr->tag, "invalid fid");
1580 return;
1583 if ((evb = evbuffer_new()) == NULL)
1584 fatal("evbuffer_new");
1586 if (f->fd != -1)
1587 r = fstat(f->fd, &sb);
1588 else if (f->qid.type & QTDIR)
1589 r = fstat(f->dir->fd, &sb);
1590 else
1591 r = fstatat(f->dir->fd, f->fname, &sb, 0);
1593 if (r == -1) {
1594 np_errno(hdr->tag);
1595 evbuffer_free(evb);
1596 return;
1599 serialize_stat(f->fname, &sb, evb);
1600 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1601 evbuffer_free(evb);
1604 static void
1605 twstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1607 struct timespec times[2];
1608 struct np_stat st;
1609 struct fid *f;
1610 int r;
1611 uint32_t fid;
1612 char name[PATH_MAX];
1614 /* fid[4] stat[n] */
1615 if (!NPREAD32("fid", &fid, &data, &len))
1616 goto err;
1618 switch (NPREADST("stat", &st, name, sizeof(name), &data, &len)) {
1619 case READSTRERR:
1620 goto err;
1621 case READSTRTRUNC:
1622 log_warnx("wstat new name would overflow");
1623 np_error(hdr->tag, "new name too long");
1624 return;
1628 * We skip the reading of some fields voluntarily because we
1629 * don't support chown, so len will always be > 0!
1631 #ifdef notyet
1632 if (len != 0)
1633 goto err;
1634 #endif
1636 if ((f = fid_by_id(fid)) == NULL) {
1637 np_error(hdr->tag, "invalid fid");
1638 return;
1642 * 9P wants these edits to be done in an atomic fashion,
1643 * something that I don't think it's possible on UNIX without
1644 * some special kernel help. Changing atime or mtime,
1645 * permissions, or rename the file are different syscalls.
1647 * Also, silently ignore stuff we can't/don't want to modify.
1650 /* change the permissions */
1651 if (st.mode != (uint32_t)-1) {
1652 mode_t m = st.mode & 0x7F; /* silently truncate higer bits */
1653 if (f->fd != -1)
1654 r = fchmod(f->fd, m);
1655 else
1656 r = fchmodat(f->dir->fd, f->fname, m, 0);
1658 if (r == -1) {
1659 np_errno(hdr->tag);
1660 return;
1664 /* change the atime/mtime of the fid, opened or not */
1665 if (st.atime != (uint32_t)-1 || st.mtime != (uint32_t)-1) {
1666 times[0].tv_nsec = UTIME_OMIT;
1667 times[1].tv_nsec = UTIME_OMIT;
1669 if (st.atime != (uint32_t)-1) {
1670 times[0].tv_sec = st.atime;
1671 times[0].tv_nsec = 0;
1673 if (st.mtime != (uint32_t)-1) {
1674 times[1].tv_sec = st.mtime;
1675 times[1].tv_nsec = 0;
1678 if (f->fd != -1)
1679 r = futimens(f->fd, times);
1680 else
1681 r = utimensat(f->dir->fd, f->fname, times, 0);
1683 if (r == -1) {
1684 np_errno(hdr->tag);
1685 return;
1689 /* truncate */
1690 if (st.length != (uint64_t)-1) {
1691 if (f->fd == -1) {
1692 np_error(hdr->tag, "can't truncate a non-opened fid");
1693 return;
1696 if (f->qid.type & QTDIR && st.length != 0) {
1697 np_error(hdr->tag, "can't truncate directories");
1698 return;
1701 if (TYPE_OVERFLOW(off_t, st.length)) {
1702 log_warnx("truncate request overflows off_t: %"PRIu64,
1703 st.length);
1704 np_error(hdr->tag, "length overflows");
1705 return;
1708 if (f->qid.type == 0 &&
1709 ftruncate(f->fd, st.length) == -1) {
1710 np_errno(hdr->tag);
1711 return;
1715 /* rename (change the name entry) */
1716 if (*st.name != '\0') {
1717 struct stat sb;
1718 const char *newname;
1721 * XXX: 9P requires that we disallow changing the name
1722 * to that of an existing file. We can't do that
1723 * atomically (rename is happy about stealing names)
1724 * so this is just a best effort.
1726 if (fstatat(f->dir->fd, st.name, &sb, 0) == -1 &&
1727 errno != ENOENT) {
1728 np_error(hdr->tag, "target file exists");
1729 return;
1732 r = renameat(f->dir->fd, f->fname, f->dir->fd, st.name);
1733 if (r == -1) {
1734 np_errno(hdr->tag);
1735 return;
1738 /* fix the fid so it points to the new file */
1740 if ((newname = strchr(st.name, '/')) != NULL)
1741 newname++; /* skip / */
1742 else
1743 newname = st.name;
1744 strlcpy(f->fname, newname, sizeof(f->fname));
1746 if (strchr(st.name, '/') != NULL) {
1747 struct dir *dir;
1748 char *dname;
1749 int fd;
1751 dname = dirname(st.name);
1752 fd = openat(f->dir->fd, dname, O_RDONLY|O_DIRECTORY);
1753 if (fd == -1) {
1754 np_errno(hdr->tag);
1755 free_fid(f);
1756 return;
1759 if ((dir = new_dir(fd)) == NULL) {
1760 np_errno(hdr->tag);
1761 free_fid(f);
1762 return;
1765 dir_decref(f->dir);
1766 f->dir = dir_incref(dir);
1770 np_wstat(hdr->tag);
1771 return;
1773 err:
1774 client_send_listener(IMSG_CLOSE, NULL, 0);
1775 client_shutdown();
1778 static void
1779 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1781 struct fid *f;
1782 uint32_t fid;
1783 int r;
1784 char dirpath[PATH_MAX + 3];
1786 /* fid[4] */
1787 if (!NPREAD32("fid", &fid, &data, &len) ||
1788 len != 0) {
1789 client_send_listener(IMSG_CLOSE, NULL, 0);
1790 client_shutdown();
1791 return;
1794 if ((f = fid_by_id(fid)) == NULL) {
1795 np_error(hdr->tag, "invalid fid");
1796 return;
1799 if (f->qid.type & QTDIR) { /* directory */
1800 strlcpy(dirpath, "../", sizeof(dirpath));
1801 strlcat(dirpath, f->fname, sizeof(dirpath));
1802 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1803 } else /* file */
1804 r = unlinkat(f->dir->fd, f->fname, 0);
1806 if (r == -1)
1807 np_errno(hdr->tag);
1808 else
1809 np_remove(hdr->tag);
1811 free_fid(f);
1814 static void
1815 handle_message(struct imsg *imsg, size_t len)
1817 struct msg {
1818 uint8_t type;
1819 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1820 } msgs[] = {
1821 {Tversion, tversion},
1822 {Tattach, tattach},
1823 {Tclunk, tclunk},
1824 {Tflush, tflush},
1825 {Twalk, twalk},
1826 {Topen, topen},
1827 {Tcreate, tcreate},
1828 {Tread, tread},
1829 {Twrite, twrite},
1830 {Tstat, tstat},
1831 {Twstat, twstat},
1832 {Tremove, tremove},
1834 struct np_msg_header hdr;
1835 size_t i;
1836 uint8_t *data;
1838 #if DEBUG_PACKETS
1839 hexdump("incoming packet", imsg->data, len);
1840 #endif
1842 parse_message(imsg->data, len, &hdr, &data);
1843 len -= HEADERSIZE;
1845 log_debug("got request: len=%d type=%d[%s] tag=%d",
1846 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1848 if (!handshaked && hdr.type != Tversion) {
1849 client_send_listener(IMSG_CLOSE, NULL, 0);
1850 client_shutdown();
1851 return;
1854 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1855 if (msgs[i].type != hdr.type)
1856 continue;
1858 msgs[i].fn(&hdr, data, len);
1859 return;
1862 np_error(hdr.tag, "Not supported.");