2 * Copyright (c) 2021, 2022 Omar Polo <op@omarpolo.com>
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.
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.
20 #include <sys/types.h>
46 * The minimum value allowed for the msize.
50 #define DEBUG_PACKETS 0
52 /* straight outta /src/usr.bin/ssh/scp.c */
53 #define TYPE_OVERFLOW(type, val) \
54 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
55 (sizeof(type) == 8 && (val) > INT64_MAX) || \
56 (sizeof(type) != 4 && sizeof(type) != 8))
58 STAILQ_HEAD(dirhead, dir) dirs;
62 STAILQ_ENTRY(dir) entries;
65 STAILQ_HEAD(fidhead, fid) fids;
72 * the flags passed to open(2). O_CLOEXEC means ORCLOSE, that
73 * is to unlink the file upon Tclunk.
78 * if fd is not -1 this fid was opened, fd represents its
79 * file descriptor and iomode the flags passed to open(2).
86 * expected offset for Tread against a directory.
92 STAILQ_ENTRY(fid) entries;
95 static struct imsgev *iev_listener;
96 static struct evbuffer *evb;
97 static uint32_t peerid;
99 static int handshaked;
102 static __dead void client_shutdown(void);
103 static void client_sig_handler(int, short, void *);
104 static void client_dispatch_listener(int, short, void *);
105 static void client_privdrop(const char *, const char *);
107 static int client_send_listenerp(int, uint32_t, const void *, uint16_t);
108 static int client_send_listener(int, const void *, uint16_t);
110 static void qid_update_from_sb(struct qid *, struct stat *);
112 static struct dir *new_dir(int);
113 static struct dir *dir_incref(struct dir *);
114 static void dir_decref(struct dir *);
116 static struct fid *new_fid(struct dir *, uint32_t, const char *, struct qid *);
117 static struct fid *fid_by_id(uint32_t);
118 static void free_fid(struct fid *);
120 static void parse_message(const uint8_t *, size_t,
121 struct np_msg_header *, uint8_t **);
123 static void np_write16(struct evbuffer *, uint16_t);
124 static void np_write32(struct evbuffer *, uint32_t);
125 static void np_write64(struct evbuffer *, uint64_t);
126 static void np_header(uint32_t, uint8_t, uint16_t);
127 static void np_string(struct evbuffer *, uint16_t, const char *);
128 static void np_qid(struct evbuffer *, struct qid *);
129 static void do_send(void);
131 static void np_version(uint16_t, uint32_t, const char *);
132 static void np_attach(uint16_t, struct qid *);
133 static void np_clunk(uint16_t);
134 static void np_flush(uint16_t);
135 static void np_walk(uint16_t, int, struct qid *);
136 static void np_open(uint16_t, struct qid *, uint32_t);
137 static void np_create(uint16_t, struct qid *, uint32_t);
138 static void np_read(uint16_t, uint32_t, void *);
139 static void np_write(uint16_t, uint32_t);
140 static void np_stat(uint16_t, uint16_t, void *);
141 static void np_wstat(uint16_t);
142 static void np_remove(uint16_t);
143 static void np_error(uint16_t, const char *);
144 static void np_errno(uint16_t);
146 static int np_read8(const char *, const char *, uint8_t *,
147 const uint8_t **, size_t *);
148 static int np_read16(const char *, const char *, uint16_t *,
149 const uint8_t **, size_t *);
150 static int np_read32(const char *, const char *, uint32_t *,
151 const uint8_t **, size_t *);
152 static int np_read64(const char *, const char *, uint64_t *,
153 const uint8_t **, size_t *);
155 #define READSTRERR -1
156 #define READSTRTRUNC -2
157 static int np_readstr(const char *, const char *, char *, size_t,
158 const uint8_t **, size_t *);
160 static int np_readst(const char *, const char *, struct np_stat *,
161 char *, size_t, const uint8_t **, size_t *);
163 #define NPREAD8(f, dst, src, len) np_read8(__func__, f, dst, src, len)
164 #define NPREAD16(f, dst, src, len) np_read16(__func__, f, dst, src, len)
165 #define NPREAD32(f, dst, src, len) np_read32(__func__, f, dst, src, len)
166 #define NPREAD64(f, dst, src, len) np_read64(__func__, f, dst, src, len)
168 #define NPREADSTR(f, b, bl, src, len) np_readstr(__func__, f, b, bl, src, len)
170 #define NPREADST(f, dst, n, nl, src, len) np_readst(__func__, f, dst, n, nl, src, len)
172 static void tversion(struct np_msg_header *, const uint8_t *, size_t);
173 static void tattach(struct np_msg_header *, const uint8_t *, size_t);
174 static void tclunk(struct np_msg_header *, const uint8_t *, size_t);
175 static void tflush(struct np_msg_header *, const uint8_t *, size_t);
176 static void twalk(struct np_msg_header *, const uint8_t *, size_t);
177 static void topen(struct np_msg_header *, const uint8_t *, size_t);
178 static void tcreate(struct np_msg_header *, const uint8_t *, size_t);
179 static void tread(struct np_msg_header *, const uint8_t *, size_t);
180 static void twrite(struct np_msg_header *, const uint8_t *, size_t, struct fid **, off_t *, size_t *, int *);
181 static void twrite_cont(struct fid *, off_t *, size_t *, int *, uint16_t, const uint8_t *, size_t);
182 static void tstat(struct np_msg_header *, const uint8_t *, size_t);
183 static void twstat(struct np_msg_header *, const uint8_t *, size_t);
184 static void tremove(struct np_msg_header *, const uint8_t *, size_t);
185 static void handle_message(struct imsg *, size_t, int);
188 client(int debug, int verbose)
190 struct event ev_sigint, ev_sigterm;
192 log_init(debug, LOG_DAEMON);
193 log_setverbose(verbose);
195 setproctitle("client");
196 log_procinit("client");
198 log_debug("warming up");
202 /* Setup signal handlers */
203 signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
204 signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
206 signal_add(&ev_sigint, NULL);
207 signal_add(&ev_sigterm, NULL);
209 signal(SIGPIPE, SIG_IGN);
210 signal(SIGHUP, SIG_IGN);
212 /* Setup pipe and event handler to the listener process */
213 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
216 imsg_init(&iev_listener->ibuf, 3);
217 iev_listener->handler = client_dispatch_listener;
219 /* Setup event handlers. */
220 iev_listener->events = EV_READ;
221 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
222 iev_listener->events, iev_listener->handler, iev_listener);
223 event_add(&iev_listener->ev, NULL);
230 client_shutdown(void)
235 msgbuf_clear(&iev_listener->ibuf.w);
236 close(iev_listener->ibuf.fd);
240 log_debug("client exiting");
245 client_sig_handler(int sig, short event, void *d)
248 * Normal signal handler rules don't apply because libevent
257 fatalx("unexpected signal %d", sig);
262 client_dispatch_listener(int fd, short event, void *d)
265 struct kd_auth_proc rauth;
266 struct kd_debug_info debug;
269 struct imsgev *iev = d;
270 struct imsgbuf *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 */
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 */
290 if ((n = imsg_get(ibuf, &imsg)) == -1)
291 fatal("%s: imsg_get error", __func__);
292 if (n == 0) /* No more messages. */
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",
300 memcpy(&verbose, imsg.data, sizeof(verbose));
301 log_setverbose(verbose);
304 STAILQ_FOREACH(f, &fids, entries) {
305 memset(&debug, 0, sizeof(debug));
307 strlcpy(debug.path, f->fname,
309 client_send_listenerp(IMSG_CTL_DEBUG_BACK,
310 imsg.hdr.peerid, &debug, sizeof(debug));
312 client_send_listenerp(IMSG_CTL_DEBUG_END,
313 imsg.hdr.peerid, NULL, 0);
316 peerid = imsg.hdr.peerid;
318 fatalx("%s: IMSG_AUTH already done", __func__);
321 if (IMSG_DATA_SIZE(imsg) != sizeof(rauth))
322 fatalx("mismatching size for IMSG_AUTH");
323 memcpy(&rauth, imsg.data, sizeof(rauth));
324 if (rauth.uname[sizeof(rauth.uname)-1] != '\0' ||
325 rauth.dir[sizeof(rauth.dir)-1] != '\0')
326 fatalx("IMSG_AUTH strings not NUL-terminated");
328 client_privdrop(rauth.uname, rauth.dir);
329 explicit_bzero(&rauth, sizeof(rauth));
334 fatalx("%s: can't handle messages before"
335 " doing the auth", __func__);
336 handle_message(&imsg, IMSG_DATA_SIZE(imsg),
337 imsg.hdr.type == IMSG_BUF_CONT);
340 log_debug("closing");
344 log_debug("%s: unexpected imsg %d",
345 __func__, imsg.hdr.type);
354 /* This pipe is dead. Remove its event handler. */
356 log_debug("pipe closed, shutting down...");
357 event_loopexit(NULL);
362 client_privdrop(const char *username, const char *dir)
366 setproctitle("client %s", username);
368 if ((pw = getpwnam(username)) == NULL)
369 fatalx("getpwnam(%s) failed", username);
371 if (chroot(dir) == -1)
373 if (chdir("/") == -1)
374 fatal("chdir(\"/\")");
376 if (setgroups(1, &pw->pw_gid) ||
377 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
378 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
379 fatal("can't drop privileges");
382 log_debug("client ready; user=%s dir=%s", username, dir);
384 if ((evb = evbuffer_new()) == NULL)
385 fatal("evbuffer_new");
389 client_send_listenerp(int type, uint32_t peerid, const void *data, uint16_t len)
393 if ((ret = imsg_compose(&iev_listener->ibuf, type, peerid, 0, -1,
395 imsg_event_add(iev_listener);
401 client_send_listener(int type, const void *data, uint16_t len)
403 return client_send_listenerp(type, peerid, data, len);
406 /* set qid fields from sb */
408 qid_update_from_sb(struct qid *qid, struct stat *sb)
410 qid->path = sb->st_ino;
413 * Theoretically (and hopefully!) this should be a 64 bit
414 * number. Unfortunately, 9P uses 32 bit timestamps.
416 qid->vers = sb->st_mtim.tv_sec;
418 if (S_ISREG(sb->st_mode))
420 else if (S_ISDIR(sb->st_mode))
422 else if (S_ISLNK(sb->st_mode))
423 qid->type = QTSYMLINK;
426 /* creates a qid given a fd */
432 if ((dir = calloc(1, sizeof(*dir))) == NULL)
436 STAILQ_INSERT_HEAD(&dirs, dir, entries);
441 dir_incref(struct dir *dir)
448 dir_decref(struct dir *dir)
450 if (--dir->refcount > 0)
453 STAILQ_REMOVE(&dirs, dir, dir, entries);
460 new_fid(struct dir *dir, uint32_t fid, const char *path, struct qid *qid)
467 if (fstatat(dir->fd, path, &sb, 0)) {
468 log_warn("fstatat(%s)", path);
471 qid_update_from_sb(&q, &sb);
475 if ((f = calloc(1, sizeof(*f))) == NULL)
478 f->dir = dir_incref(dir);
482 strlcpy(f->fname, path, sizeof(f->fname));
484 memcpy(&f->qid, qid, sizeof(f->qid));
486 STAILQ_INSERT_HEAD(&fids, f, entries);
492 fid_by_id(uint32_t fid)
496 STAILQ_FOREACH(f, &fids, entries) {
505 free_fid(struct fid *f)
516 fatal("can't close fid %d", f->fid);
519 evbuffer_free(f->evb);
521 /* try to honour ORCLOSE if requested */
522 if (f->iomode & O_CLOEXEC)
523 unlinkat(f->dir->fd, f->fname, 0);
528 STAILQ_REMOVE(&fids, f, fid, entries);
533 parse_message(const uint8_t *data, size_t len, struct np_msg_header *hdr,
538 if (!NPREAD32("len", &hdr->len, &data, &len) ||
539 !NPREAD8("type", &hdr->type, &data, &len) ||
540 !NPREAD16("tag", &hdr->tag, &data, &len))
543 if (olen != hdr->len)
546 if (hdr->type < Tversion ||
548 hdr->type == Terror ||
549 (hdr->type & 0x1) != 0) /* cannot recv a R* */
552 hdr->tag = le32toh(hdr->tag);
554 *cnt = (uint8_t *)data;
558 /* TODO: send a proper message to terminate the connection. */
559 fatalx("got invalid message");
563 np_write16(struct evbuffer *e, uint16_t x)
566 evbuffer_add(e, &x, sizeof(x));
570 np_write32(struct evbuffer *e, uint32_t x)
573 evbuffer_add(e, &x, sizeof(x));
577 np_write64(struct evbuffer *e, uint64_t x)
580 evbuffer_add(e, &x, sizeof(x));
584 np_writebuf(struct evbuffer *e, size_t len, void *data)
586 evbuffer_add(e, data, len);
590 np_header(uint32_t len, uint8_t type, uint16_t tag)
597 evbuffer_add(evb, &len, sizeof(len));
598 evbuffer_add(evb, &type, sizeof(type));
599 evbuffer_add(evb, &tag, sizeof(tag));
603 np_string(struct evbuffer *e, uint16_t len, const char *str)
608 evbuffer_add(e, &len, sizeof(len));
609 evbuffer_add(e, str, l);
613 np_qid(struct evbuffer *e, struct qid *qid)
618 path = htole64(qid->path);
619 vers = htole32(qid->vers);
621 evbuffer_add(e, &qid->type, sizeof(qid->type));
622 evbuffer_add(e, &vers, sizeof(vers));
623 evbuffer_add(e, &path, sizeof(path));
632 len = EVBUFFER_LENGTH(evb);
633 data = EVBUFFER_DATA(evb);
636 hexdump("outgoing packet", data, len);
638 client_send_listener(IMSG_BUF, data, len);
639 evbuffer_drain(evb, len);
643 np_version(uint16_t tag, uint32_t msize, const char *version)
649 msize = htole32(msize);
651 np_header(sizeof(msize) + sizeof(l) + l, Rversion, tag);
652 evbuffer_add(evb, &msize, sizeof(msize));
653 np_string(evb, l, version);
658 np_attach(uint16_t tag, struct qid *qid)
660 np_header(QIDSIZE, Rattach, tag);
666 np_clunk(uint16_t tag)
668 np_header(0, Rclunk, tag);
673 np_flush(uint16_t tag)
675 np_header(0, Rflush, tag);
680 np_walk(uint16_t tag, int nwqid, struct qid *wqid)
684 /* two bytes for the counter */
685 np_header(2 + QIDSIZE * nwqid, Rwalk, tag);
686 np_write16(evb, nwqid);
687 for (i = 0; i < nwqid; ++i)
688 np_qid(evb, wqid + i);
694 np_open(uint16_t tag, struct qid *qid, uint32_t iounit)
696 np_header(QIDSIZE + sizeof(iounit), Ropen, tag);
698 np_write32(evb, iounit);
703 np_create(uint16_t tag, struct qid *qid, uint32_t iounit)
705 np_header(QIDSIZE + sizeof(iounit), Rcreate, tag);
707 np_write32(evb, iounit);
712 np_read(uint16_t tag, uint32_t count, void *data)
714 if (sizeof(count) + count + HEADERSIZE >= msize) {
715 np_error(tag, "Rread would overflow");
719 np_header(sizeof(count) + count, Rread, tag);
720 np_write32(evb, count);
721 np_writebuf(evb, count, data);
726 np_write(uint16_t tag, uint32_t count)
728 np_header(sizeof(count), Rwrite, tag);
729 np_write32(evb, count);
734 np_stat(uint16_t tag, uint16_t count, void *data)
736 if (sizeof(count) + count + HEADERSIZE >= msize) {
737 np_error(tag, "Rstat would overflow");
741 np_header(sizeof(count) + count, Rstat, tag);
742 np_write16(evb, count);
743 np_writebuf(evb, count, data);
748 np_wstat(uint16_t tag)
750 np_header(0, Rwstat, tag);
755 np_remove(uint16_t tag)
757 np_header(0, Rremove, tag);
762 np_error(uint16_t tag, const char *errstr)
768 np_header(sizeof(l) + l, Rerror, tag);
769 np_string(evb, l, errstr);
774 np_errno(uint16_t tag)
777 char buf[NL_TEXTMAX] = {0};
781 strerror_r(errno, buf, sizeof(buf));
788 np_read8(const char *t, const char *f, uint8_t *dst, const uint8_t **src,
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);
797 memcpy(dst, *src, sizeof(*dst));
798 *src += sizeof(*dst);
799 *len -= sizeof(*dst);
805 np_read16(const char *t, const char *f, uint16_t *dst, const uint8_t **src,
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);
814 memcpy(dst, *src, sizeof(*dst));
815 *src += sizeof(*dst);
816 *len -= sizeof(*dst);
817 *dst = le16toh(*dst);
823 np_read32(const char *t, const char *f, uint32_t *dst, const uint8_t **src,
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);
832 memcpy(dst, *src, sizeof(*dst));
833 *src += sizeof(*dst);
834 *len -= sizeof(*dst);
835 *dst = le32toh(*dst);
841 np_read64(const char *t, const char *f, uint64_t *dst, const uint8_t **src,
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);
850 memcpy(dst, *src, sizeof(*dst));
851 *src += sizeof(*dst);
852 *len -= sizeof(*dst);
853 *dst = le64toh(*dst);
859 np_readstr(const char *t, const char *f, char *res, size_t reslen,
860 const uint8_t **src, size_t *len)
865 strlcpy(buf, f, sizeof(buf));
866 strlcat(buf, "-len", sizeof(buf));
868 if (!np_read16(t, buf, &sl, src, len))
872 log_warnx("%s: wanted %d bytes for the %s field but only "
873 "%zu are available.", t, sl, f, *len);
880 memcpy(res, *src, sl);
889 np_readst(const char *t, const char *f, struct np_stat *st,
890 char *name, size_t namelen, const uint8_t **src, size_t *len)
892 memset(st, 0, sizeof(*st));
894 /* len is sent twice! */
895 if (!np_read16(t, "stat len", &st->size, src, len) ||
896 !np_read16(t, "stat.size", &st->size, src, len) ||
897 !np_read16(t, "stat.type", &st->type, src, len) ||
898 !np_read32(t, "stat.dev", &st->dev, src, len) ||
899 !np_read64(t, "stat.qid.path", &st->qid.path, src, len) ||
900 !np_read32(t, "stat.qid.vers", &st->qid.vers, src, len) ||
901 !np_read8(t, "stat.qid.type", &st->qid.type, src, len) ||
902 !np_read32(t, "stat.mode", &st->mode, src, len) ||
903 !np_read32(t, "stat.atime", &st->atime, src, len) ||
904 !np_read32(t, "stat.mtime", &st->mtime, src, len) ||
905 !np_read64(t, "stat.length", &st->length, src, len))
909 * ignore everything but the name, we don't support
910 * changing those fields anyway
913 return np_readstr(t, "stat.name", name, namelen, src, len);
917 tversion(struct np_msg_header *hdr, const uint8_t *data, size_t len)
919 char *dot, version[32];
924 /* msize[4] version[s] */
925 if (!NPREAD32("msize", &msize, &data, &len))
928 switch (NPREADSTR("version", version, sizeof(version), &data, &len)) {
932 log_warnx("9P version string too long, truncated");
933 np_version(hdr->tag, MSIZE9P, "unknown");
940 if ((dot = strchr(version, '.')) != NULL)
943 if (strcmp(version, VERSION9P) != 0) {
944 log_warnx("unknown 9P version \"%s\"; want "VERSION9P,
946 np_version(hdr->tag, MSIZE9P, "unknown");
950 if (msize < MIN_MSIZE) {
951 log_warnx("msize too small: %"PRIu32"; want %d at least",
953 np_version(hdr->tag, MSIZE9P, "unknown");
957 /* version matched */
959 msize = MIN(msize, MSIZE9P);
960 client_send_listener(IMSG_MSIZE, &msize, sizeof(msize));
961 np_version(hdr->tag, msize, VERSION9P);
965 client_send_listener(IMSG_CLOSE, NULL, 0);
970 tattach(struct np_msg_header *hdr, const uint8_t *data, size_t len)
976 char aname[PATH_MAX];
978 /* fid[4] afid[4] uname[s] aname[s] */
980 if (!NPREAD32("fid", &fid, &data, &len) ||
981 !NPREAD32("afid", &afid, &data, &len))
984 /* read the uname but don't actually use it */
985 switch (NPREADSTR("uname", aname, sizeof(aname), &data, &len)) {
989 np_error(hdr->tag, "name too long");
993 switch (NPREADSTR("aname", aname, sizeof(aname), &data, &len)) {
997 np_error(hdr->tag, "name too long");
1002 strlcpy(aname, "/", sizeof(aname));
1007 if (fid_by_id(fid) != NULL || afid != NOFID) {
1008 np_error(hdr->tag, "invalid fid or afid");
1012 if ((fd = open(aname, O_RDONLY|O_DIRECTORY)) == -1)
1015 if ((dir = new_dir(fd)) == NULL)
1018 log_debug("attached %s to %d", aname, fid);
1020 if ((f = new_fid(dir, fid, aname, NULL)) == NULL) {
1025 np_attach(hdr->tag, &f->qid);
1030 log_warn("failed to attach %s", aname);
1034 client_send_listener(IMSG_CLOSE, NULL, 0);
1039 tclunk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1045 if (!NPREAD32("fid", &fid, &data, &len) ||
1047 client_send_listener(IMSG_CLOSE, NULL, 0);
1052 if ((f = fid_by_id(fid)) == NULL) {
1053 np_error(hdr->tag, "invalid fid");
1062 tflush(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1067 * We're doing only synchronous I/O. Tflush is implemented
1068 * only because it's illegal to reply with a Rerror.
1072 if (len != sizeof(oldtag)) {
1073 log_warnx("Tflush with the wrong size: got %zu want %zu",
1074 len, sizeof(oldtag));
1075 client_send_listener(IMSG_CLOSE, NULL, 0);
1084 twalk(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1088 struct qid wqid[MAXWELEM] = {0};
1090 uint32_t fid, newfid;
1092 int fd, oldfd, no, nwqid = 0;
1093 char wnam[PATH_MAX];
1095 if (!NPREAD32("fid", &fid, &data, &len) ||
1096 !NPREAD32("newfid", &newfid, &data, &len) ||
1097 !NPREAD16("nwname", &nwname, &data, &len))
1100 if (nwname > MAXWELEM) {
1101 log_warnx("Twalk: more than %d path elements: %d",
1106 if ((f = fid_by_id(fid)) == NULL) {
1107 np_error(hdr->tag, "invalid fid");
1112 np_error(hdr->tag, "fid already opened for I/O");
1118 else if ((nf = fid_by_id(newfid)) != NULL) {
1119 np_error(hdr->tag, "newfid already in use");
1124 /* special case: fid duplication */
1127 * TODO: should we forbid fids duplication when fid ==
1131 (nf = new_fid(f->dir, newfid, f->fname, &f->qid)) == NULL)
1132 fatal("new_fid duplication");
1134 np_walk(hdr->tag, 0, NULL);
1138 if (!(f->qid.type & QTDIR)) {
1139 np_error(hdr->tag, "fid doesn't represent a directory");
1145 for (nwqid = 0; nwqid < nwname; nwqid++) {
1146 switch (NPREADSTR("wname", wnam, sizeof(wnam), &data, &len)) {
1150 np_error(hdr->tag, "wname too long");
1154 if (*wnam == '\0' ||
1155 strchr(wnam, '/') != NULL ||
1156 !strcmp(wnam, ".")) {
1161 if ((fd = openat(oldfd, wnam, O_RDONLY|O_DIRECTORY)) == -1 &&
1165 if ((fd == -1 && fstatat(oldfd, wnam, &sb, 0) == -1) ||
1166 (fd != -1 && fstat(fd, &sb) == -1))
1169 qid_update_from_sb(&wqid[nwqid], &sb);
1171 /* reached a file but we still have other components */
1172 if (fd == -1 && nwqid+1 < nwname)
1175 /* reached the end and found a file */
1176 if (fd == -1 && nwqid+1 == nwname)
1179 if (oldfd != f->dir->fd)
1188 * If fd is -1 we've reached a file, otherwise we've just
1189 * reached another directory. We must pay attention to what
1190 * file descriptor we use to create the dir, because if we've
1191 * reached a file and oldfd is f->dir->fd then we *must* share
1192 * the same dir (it was a walk of one path from a directory to a
1193 * file, otherwise fun is bound to happen as soon as the client
1194 * closes the fid for the directory but keeps the one for the
1197 if (fd == -1 && oldfd == f->dir->fd)
1200 dir = new_dir(oldfd);
1208 if ((nf = new_fid(dir, newfid, wnam, &wqid[nwqid-1])) == NULL)
1211 /* update the dir */
1212 dir_decref(nf->dir);
1213 nf->dir = dir_incref(dir);
1216 np_walk(hdr->tag, nwqid, wqid);
1220 if (oldfd != f->dir->fd)
1224 np_error(hdr->tag, strerror(no));
1226 np_walk(hdr->tag, nwqid, wqid);
1230 client_send_listener(IMSG_CLOSE, NULL, 0);
1235 npmode_to_unix(uint8_t mode, int *flags)
1237 switch (mode & 0x0F) {
1248 log_warnx("tried to open something with KOEXEC");
1256 if (mode & KORCLOSE)
1257 *flags |= O_CLOEXEC;
1263 topen(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1272 /* fid[4] mode[1] */
1273 if (!NPREAD32("fid", &fid, &data, &len) ||
1274 !NPREAD8("mode", &mode, &data, &len) ||
1276 client_send_listener(IMSG_CLOSE, NULL, 0);
1281 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1282 np_error(hdr->tag, "invalid fid");
1286 if (npmode_to_unix(mode, &f->iomode) == -1) {
1287 np_error(hdr->tag, "invalid mode");
1292 if (f->qid.type & QTDIR)
1295 if ((f->fd = openat(f->dir->fd, path, f->iomode)) == -1) {
1296 np_error(hdr->tag, strerror(errno));
1300 if (fstat(f->fd, &sb) == -1)
1303 if (S_ISDIR(sb.st_mode)) {
1304 if ((f->d = fdopendir(f->fd)) == NULL) {
1311 if ((f->evb = evbuffer_new()) == NULL) {
1321 qid_update_from_sb(&qid, &sb);
1322 np_open(hdr->tag, &qid, sb.st_blksize);
1326 tcreate(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1333 char name[PATH_MAX];
1335 /* fid[4] name[s] perm[4] mode[1] */
1336 if (!NPREAD32("fid", &fid, &data, &len))
1338 switch (NPREADSTR("name", name, sizeof(name), &data, &len)) {
1342 np_error(hdr->tag, "name too long");
1345 if (!NPREAD32("perm", &perm, &data, &len) ||
1346 !NPREAD8("mode", &mode, &data, &len) ||
1350 if (!strcmp(name, ".") || !strcmp(name, "..") ||
1351 strchr(name, '/') != NULL) {
1352 np_error(hdr->tag, "invalid name");
1356 if ((f = fid_by_id(fid)) == NULL || f->fd != -1) {
1357 np_error(hdr->tag, "invalid fid");
1361 if (!(f->qid.type & QTDIR)) {
1362 np_error(hdr->tag, "fid doesn't identify a directory");
1366 if (npmode_to_unix(mode, &f->iomode) == -1) {
1367 np_error(hdr->tag, "invalid mode");
1371 if (f->iomode & O_RDONLY) {
1372 np_error(hdr->tag, "can't create a read-only file");
1376 /* TODO: parse the mode */
1378 if (perm & 0x80000000) {
1379 /* create a directory */
1380 f->fd = mkdirat(f->dir->fd, name, 0755);
1383 f->fd = openat(f->dir->fd, name, f->iomode | O_CREAT | O_TRUNC,
1392 if (fstat(f->fd, &sb) == -1)
1395 if (S_ISDIR(sb.st_mode)) {
1396 if ((f->d = fdopendir(f->fd)) == NULL) {
1403 if ((f->evb = evbuffer_new()) == NULL) {
1413 qid_update_from_sb(&qid, &sb);
1414 np_create(hdr->tag, &qid, sb.st_blksize);
1419 client_send_listener(IMSG_CLOSE, NULL, 0);
1424 serialize_stat(const char *fname, struct stat *sb, struct evbuffer *evb)
1427 const char *uid, *gid, *muid;
1430 uint16_t namlen, uidlen, gidlen, ulen;
1432 qid_update_from_sb(&qid, sb);
1434 /* TODO: fill these fields */
1439 namlen = strlen(fname);
1440 uidlen = strlen(uid);
1441 gidlen = strlen(gid);
1442 ulen = strlen(muid);
1444 tot = NPSTATSIZ(namlen, uidlen, gidlen, ulen);
1445 if (tot > UINT16_MAX) {
1446 log_warnx("stat info for dir entry %s would overflow",
1451 mode = sb->st_mode & 0xFFFF;
1452 if (qid.type & QTDIR)
1455 np_write16(evb, tot); /* size[2] */
1456 np_write16(evb, sb->st_rdev); /* type[2] */
1457 np_write32(evb, sb->st_dev); /* dev[4] */
1458 np_qid(evb, &qid); /* qid[13] */
1459 np_write32(evb, mode); /* mode[4] */
1460 np_write32(evb, sb->st_atim.tv_sec); /* atime[4] */
1461 np_write32(evb, sb->st_mtim.tv_sec); /* mtime[4] */
1463 /* special case: directories have size 0 */
1464 if (qid.type & QTDIR)
1467 np_write64(evb, sb->st_size); /* length[8] */
1469 np_string(evb, namlen, fname); /* name[s] */
1470 np_string(evb, uidlen, uid); /* uid[s] */
1471 np_string(evb, gidlen, gid); /* gid[s] */
1472 np_string(evb, ulen, muid); /* muid[s] */
1478 tread(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1484 uint32_t fid, count;
1487 /* fid[4] offset[8] count[4] */
1488 if (!NPREAD32("fid", &fid, &data, &len) ||
1489 !NPREAD64("offset", &off, &data, &len) ||
1490 !NPREAD32("count", &count, &data, &len) ||
1492 client_send_listener(IMSG_CLOSE, NULL, 0);
1497 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1498 np_error(hdr->tag, "invalid fid");
1502 if (TYPE_OVERFLOW(off_t, off)) {
1503 log_warnx("unexpected off_t size");
1504 np_error(hdr->tag, "invalid offset");
1510 howmuch = MIN(sizeof(buf), count);
1511 r = pread(f->fd, buf, howmuch, (off_t)off);
1515 np_read(hdr->tag, r, buf);
1517 if (off == 0 && f->offset != 0) {
1520 evbuffer_drain(f->evb, EVBUFFER_LENGTH(f->evb));
1523 if (off != f->offset) {
1524 np_error(hdr->tag, "can't seek in directories");
1528 while (EVBUFFER_LENGTH(f->evb) < count) {
1532 if ((d = readdir(f->d)) == NULL)
1534 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
1536 if (fstatat(f->fd, d->d_name, &sb, 0) == -1) {
1540 serialize_stat(d->d_name, &sb, f->evb);
1543 count = MIN(count, EVBUFFER_LENGTH(f->evb));
1544 np_read(hdr->tag, count, EVBUFFER_DATA(f->evb));
1545 evbuffer_drain(f->evb, count);
1552 twrite(struct np_msg_header *hdr, const uint8_t *data, size_t len,
1553 struct fid **writefid, off_t *writepos, size_t *writeleft, int *writeskip)
1558 uint32_t fid, count;
1560 /* fid[4] offset[8] count[4] data[count] */
1561 if (!NPREAD32("fid", &fid, &data, &len) ||
1562 !NPREAD64("off", &off, &data, &len) ||
1563 !NPREAD32("count", &count, &data, &len) ||
1565 client_send_listener(IMSG_CLOSE, NULL, 0);
1570 if ((f = fid_by_id(fid)) == NULL || f->fd == -1) {
1572 np_error(hdr->tag, "invalid fid");
1576 if (!(f->iomode & O_WRONLY) &&
1577 !(f->iomode & O_RDWR)) {
1579 np_error(hdr->tag, "fid not opened for writing");
1583 if (TYPE_OVERFLOW(off_t, off)) {
1585 log_warnx("unexpected off_t size");
1586 np_error(hdr->tag, "invalid offset");
1590 if ((r = pwrite(f->fd, data, len, off)) == -1) {
1593 } else if (count == len)
1594 np_write(hdr->tag, r);
1596 /* account for a continuated write */
1599 *writepos = off + len;
1600 *writeleft = count - len;
1606 twrite_cont(struct fid *f, off_t *writepos, size_t *writeleft, int *writeskip,
1607 uint16_t tag, const uint8_t *data, size_t len)
1611 if (len > *writeleft) {
1612 client_send_listener(IMSG_CLOSE, NULL, 0);
1617 if ((r = pwrite(f->fd, data, len, *writepos)) == -1) {
1626 if (*writeleft == 0)
1631 tstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1633 struct evbuffer *evb;
1640 if (!NPREAD32("fid", &fid, &data, &len) ||
1642 client_send_listener(IMSG_CLOSE, NULL, 0);
1648 * plan9' stat(9P) is not clear on whether the stat is allowed
1649 * on opened fids or not. We're allowing stat regardless of the
1650 * status of the fid.
1653 if ((f = fid_by_id(fid)) == NULL) {
1654 np_error(hdr->tag, "invalid fid");
1658 if ((evb = evbuffer_new()) == NULL)
1659 fatal("evbuffer_new");
1662 r = fstat(f->fd, &sb);
1663 else if (f->qid.type & QTDIR)
1664 r = fstat(f->dir->fd, &sb);
1666 r = fstatat(f->dir->fd, f->fname, &sb, 0);
1674 if (serialize_stat(f->fname, &sb, evb) == -1)
1675 np_error(hdr->tag, "stat would overflow");
1677 np_stat(hdr->tag, EVBUFFER_LENGTH(evb), EVBUFFER_DATA(evb));
1682 twstat(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1684 struct timespec times[2];
1689 char name[PATH_MAX];
1691 /* fid[4] stat[n] */
1692 if (!NPREAD32("fid", &fid, &data, &len))
1695 switch (NPREADST("stat", &st, name, sizeof(name), &data, &len)) {
1699 log_warnx("wstat new name would overflow");
1700 np_error(hdr->tag, "new name too long");
1705 * We skip the reading of some fields voluntarily because we
1706 * don't support chown, so len will always be > 0!
1713 if ((f = fid_by_id(fid)) == NULL) {
1714 np_error(hdr->tag, "invalid fid");
1719 * 9P wants these edits to be done in an atomic fashion,
1720 * something that I don't think it's possible on UNIX without
1721 * some special kernel help. Changing atime or mtime,
1722 * permissions, or rename the file are different syscalls.
1724 * Also, silently ignore stuff we can't/don't want to modify.
1727 /* change the permissions */
1728 if (st.mode != (uint32_t)-1) {
1729 mode_t m = st.mode & 0x7FF; /* silently truncate higer bits */
1731 r = fchmod(f->fd, m);
1733 r = fchmodat(f->dir->fd, f->fname, m, 0);
1741 /* change the atime/mtime of the fid, opened or not */
1742 if (st.atime != (uint32_t)-1 || st.mtime != (uint32_t)-1) {
1743 times[0].tv_nsec = UTIME_OMIT;
1744 times[1].tv_nsec = UTIME_OMIT;
1746 if (st.atime != (uint32_t)-1) {
1747 times[0].tv_sec = st.atime;
1748 times[0].tv_nsec = 0;
1750 if (st.mtime != (uint32_t)-1) {
1751 times[1].tv_sec = st.mtime;
1752 times[1].tv_nsec = 0;
1756 r = futimens(f->fd, times);
1758 r = utimensat(f->dir->fd, f->fname, times, 0);
1767 if (st.length != (uint64_t)-1) {
1769 np_error(hdr->tag, "can't truncate a non-opened fid");
1773 if (f->qid.type & QTDIR && st.length != 0) {
1774 np_error(hdr->tag, "can't truncate directories");
1778 if (TYPE_OVERFLOW(off_t, st.length)) {
1779 log_warnx("truncate request overflows off_t: %"PRIu64,
1781 np_error(hdr->tag, "length overflows");
1785 if (f->qid.type == 0 &&
1786 ftruncate(f->fd, st.length) == -1) {
1792 /* rename (change the name entry) */
1793 if (*st.name != '\0') {
1795 const char *newname;
1798 * XXX: 9P requires that we disallow changing the name
1799 * to that of an existing file. We can't do that
1800 * atomically (rename is happy about stealing names)
1801 * so this is just a best effort.
1803 if (fstatat(f->dir->fd, st.name, &sb, 0) == -1 &&
1805 np_error(hdr->tag, "target file exists");
1809 r = renameat(f->dir->fd, f->fname, f->dir->fd, st.name);
1815 /* fix the fid so it points to the new file */
1817 if ((newname = strchr(st.name, '/')) != NULL)
1818 newname++; /* skip / */
1821 strlcpy(f->fname, newname, sizeof(f->fname));
1823 if (strchr(st.name, '/') != NULL) {
1828 dname = dirname(st.name);
1829 fd = openat(f->dir->fd, dname, O_RDONLY|O_DIRECTORY);
1836 if ((dir = new_dir(fd)) == NULL) {
1843 f->dir = dir_incref(dir);
1851 client_send_listener(IMSG_CLOSE, NULL, 0);
1856 tremove(struct np_msg_header *hdr, const uint8_t *data, size_t len)
1861 char dirpath[PATH_MAX + 3];
1864 if (!NPREAD32("fid", &fid, &data, &len) ||
1866 client_send_listener(IMSG_CLOSE, NULL, 0);
1871 if ((f = fid_by_id(fid)) == NULL) {
1872 np_error(hdr->tag, "invalid fid");
1876 if (f->qid.type & QTDIR) { /* directory */
1877 strlcpy(dirpath, "../", sizeof(dirpath));
1878 strlcat(dirpath, f->fname, sizeof(dirpath));
1879 r = unlinkat(f->dir->fd, dirpath, AT_REMOVEDIR);
1881 r = unlinkat(f->dir->fd, f->fname, 0);
1886 np_remove(hdr->tag);
1892 handle_message(struct imsg *imsg, size_t len, int cont)
1894 static struct fid *writefid;
1895 static off_t writepos;
1896 static size_t writeleft;
1897 static int writeskip;
1898 static uint16_t writetag;
1901 void (*fn)(struct np_msg_header *, const uint8_t *, size_t);
1903 {Tversion, tversion},
1911 /* {Twrite, twrite}, */
1916 struct np_msg_header hdr;
1921 hexdump("incoming packet", imsg->data, len);
1925 * Twrite is special and can be "continued" to allow writing
1926 * more than what the imsg framework would allow us to.
1928 if (writeleft > 0 && !cont) {
1929 log_warnx("received a non continuation message when still "
1930 "missed %zu bytes to write", writeleft);
1931 client_send_listener(IMSG_CLOSE, NULL, 0);
1940 if (writefid == NULL) {
1941 log_warnx("received a continuation message without "
1943 client_send_listener(IMSG_CLOSE, NULL, 0);
1948 log_warnx("continuing...");
1949 twrite_cont(writefid, &writepos, &writeleft, &writeskip,
1950 writetag, imsg->data, len);
1959 parse_message(imsg->data, len, &hdr, &data);
1962 log_debug("got request: len=%d type=%d[%s] tag=%d",
1963 hdr.len, hdr.type, pp_msg_type(hdr.type), hdr.tag);
1965 if (!handshaked && hdr.type != Tversion) {
1966 client_send_listener(IMSG_CLOSE, NULL, 0);
1971 if (hdr.type == Twrite) {
1973 twrite(&hdr, data, len, &writefid, &writepos, &writeleft,
1978 for (i = 0; i < sizeof(msgs)/sizeof(msgs[0]); ++i) {
1979 if (msgs[i].type != hdr.type)
1982 msgs[i].fn(&hdr, data, len);
1986 np_error(hdr.tag, "Not supported.");