Bring in the "Port PUFFS from NetBSD/FreeBSD" GSoC 2011 project results.
[dragonfly.git] / usr.sbin / puffs / mount_psshfs / psshfs.c
1 /*      $NetBSD: psshfs.c,v 1.63 2011/05/19 15:07:16 riastradh Exp $    */
2
3 /*
4  * Copyright (c) 2006-2009  Antti Kantee.  All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
16  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 /*
29  * psshfs: puffs sshfs
30  *
31  * psshfs implements sshfs functionality on top of puffs making it
32  * possible to mount a filesystme through the sftp service.
33  *
34  * psshfs can execute multiple operations in "parallel" by using the
35  * puffs_cc framework for continuations.
36  *
37  * Concurrency control is handled currently by vnode locking (this
38  * will change in the future).  Context switch locations are easy to
39  * find by grepping for puffs_framebuf_enqueue_cc().
40  */
41
42 #include <sys/types.h>
43 #include <sys/wait.h>
44 #include <sys/ioctl.h>
45 #include <sys/socket.h>
46 #include <sys/uio.h>
47
48 #include <assert.h>
49 #include <err.h>
50 #include <errno.h>
51 #include <paths.h>
52 #include <poll.h>
53 #include <puffs.h>
54 #include <signal.h>
55 #include <stdlib.h>
56 #include <stdio.h>
57 #include <unistd.h>
58
59 #include "psshfs.h"
60 #include "util_compat.h"
61
62 static int      pssh_connect(struct puffs_usermount *, int);
63 static void     psshfs_loopfn(struct puffs_usermount *);
64 static void     usage(void);
65 static void     add_ssharg(char ***, int *, const char *);
66 static void     psshfs_notify(struct puffs_usermount *, int, int);
67
68 #define SSH_PATH "/usr/bin/ssh"
69
70 unsigned int max_reads;
71 static int sighup;
72
73 static void
74 add_ssharg(char ***sshargs, int *nargs, const char *arg)
75 {
76
77         *sshargs = realloc(*sshargs, (*nargs + 2) * sizeof(char*));
78         if (!*sshargs)
79                 err(1, "realloc");
80         (*sshargs)[(*nargs)++] = estrdup(arg);
81         (*sshargs)[*nargs] = NULL;
82 }
83
84 static void
85 usage()
86 {
87
88         fprintf(stderr, "usage: %s "
89             "[-ceprst] [-F configfile] [-O sshopt=value] [-o opts] "
90             "user@host:path mountpath\n",
91             getprogname());
92         exit(1);
93 }
94
95 static void
96 takehup(int sig)
97 {
98
99         sighup = 1;
100 }
101
102 int
103 main(int argc, char *argv[])
104 {
105         struct psshfs_ctx pctx;
106         struct puffs_usermount *pu;
107         struct puffs_ops *pops;
108         struct psshfs_node *root = &pctx.psn_root;
109         struct puffs_node *pn_root;
110         puffs_framev_fdnotify_fn notfn;
111         struct vattr *rva;
112         char **sshargs;
113         char *userhost;
114         char *hostpath;
115         int mntflags, pflags, ch;
116         int detach;
117         int exportfs, refreshival, numconnections;
118         int nargs;
119
120         setprogname(argv[0]);
121         puffs_unmountonsignal(SIGINT, true);
122         puffs_unmountonsignal(SIGTERM, true);
123
124         if (argc < 3)
125                 usage();
126
127         memset(&pctx, 0, sizeof(pctx));
128         mntflags = pflags = exportfs = nargs = 0;
129         numconnections = 1;
130         detach = 1;
131         refreshival = DEFAULTREFRESH;
132         notfn = puffs_framev_unmountonclose;
133         sshargs = NULL;
134         add_ssharg(&sshargs, &nargs, SSH_PATH);
135         add_ssharg(&sshargs, &nargs, "-axs");
136         add_ssharg(&sshargs, &nargs, "-oClearAllForwardings=yes");
137
138         while ((ch = getopt(argc, argv, "c:eF:g:o:O:pr:st:u:")) != -1) {
139                 switch (ch) {
140                 case 'c':
141                         numconnections = atoi(optarg);
142                         if (numconnections < 1 || numconnections > 2) {
143                                 fprintf(stderr, "%s: only 1 or 2 connections "
144                                     "permitted currently\n", getprogname());
145                                 usage();
146                                 /*NOTREACHED*/
147                         }
148                         break;
149                 case 'e':
150                         exportfs = 1;
151                         break;
152                 case 'F':
153                         add_ssharg(&sshargs, &nargs, "-F");
154                         add_ssharg(&sshargs, &nargs, optarg);
155                         break;
156                 case 'g':
157                         pctx.domanglegid = 1;
158                         pctx.manglegid = atoi(optarg);
159                         if (pctx.manglegid == (gid_t)-1)
160                                 errx(1, "-1 not allowed for -g");
161                         pctx.mygid = getegid();
162                         break;
163                 case 'O':
164                         add_ssharg(&sshargs, &nargs, "-o");
165                         add_ssharg(&sshargs, &nargs, optarg);
166                         break;
167                 case 'o':
168                         getmntopts(optarg, puffsmopts, &mntflags, &pflags);
169                         break;
170                 case 'p':
171                         notfn = psshfs_notify;
172                         break;
173                 case 'r':
174                         max_reads = atoi(optarg);
175                         break;
176                 case 's':
177                         detach = 0;
178                         break;
179                 case 't':
180                         refreshival = atoi(optarg);
181                         if (refreshival < 0 && refreshival != -1)
182                                 errx(1, "invalid timeout %d", refreshival);
183                         break;
184                 case 'u':
185                         pctx.domangleuid = 1;
186                         pctx.mangleuid = atoi(optarg);
187                         if (pctx.mangleuid == (uid_t)-1)
188                                 errx(1, "-1 not allowed for -u");
189                         pctx.myuid = geteuid();
190                         break;
191                 default:
192                         usage();
193                         /*NOTREACHED*/
194                 }
195         }
196         argc -= optind;
197         argv += optind;
198
199         if (pflags & PUFFS_FLAG_OPDUMP)
200                 detach = 0;
201         pflags |= PUFFS_FLAG_BUILDPATH;
202         pflags |= PUFFS_KFLAG_WTCACHE | PUFFS_KFLAG_IAONDEMAND;
203
204         if (argc != 2)
205                 usage();
206
207         PUFFSOP_INIT(pops);
208
209         PUFFSOP_SET(pops, psshfs, fs, unmount);
210         PUFFSOP_SETFSNOP(pops, sync); /* XXX */
211         PUFFSOP_SET(pops, psshfs, fs, statvfs);
212         PUFFSOP_SET(pops, psshfs, fs, nodetofh);
213         PUFFSOP_SET(pops, psshfs, fs, fhtonode);
214
215         PUFFSOP_SET(pops, psshfs, node, lookup);
216         PUFFSOP_SET(pops, psshfs, node, create);
217         PUFFSOP_SET(pops, psshfs, node, open);
218         PUFFSOP_SET(pops, psshfs, node, inactive);
219         PUFFSOP_SET(pops, psshfs, node, readdir);
220         PUFFSOP_SET(pops, psshfs, node, getattr);
221         PUFFSOP_SET(pops, psshfs, node, setattr);
222         PUFFSOP_SET(pops, psshfs, node, mkdir);
223         PUFFSOP_SET(pops, psshfs, node, remove);
224         PUFFSOP_SET(pops, psshfs, node, readlink);
225         PUFFSOP_SET(pops, psshfs, node, rmdir);
226         PUFFSOP_SET(pops, psshfs, node, symlink);
227         PUFFSOP_SET(pops, psshfs, node, rename);
228         PUFFSOP_SET(pops, psshfs, node, read);
229         PUFFSOP_SET(pops, psshfs, node, write);
230         PUFFSOP_SET(pops, psshfs, node, reclaim);
231
232         pu = puffs_init(pops, argv[0], "psshfs", &pctx, pflags);
233         if (pu == NULL)
234                 err(1, "puffs_init");
235
236         pctx.mounttime = time(NULL);
237         pctx.refreshival = refreshival;
238         pctx.numconnections = numconnections;
239
240         userhost = argv[0];
241         hostpath = strchr(userhost, ':');
242         if (hostpath) {
243                 *hostpath++ = '\0';
244                 pctx.mountpath = hostpath;
245         } else
246                 pctx.mountpath = ".";
247
248         add_ssharg(&sshargs, &nargs, argv[0]);
249         add_ssharg(&sshargs, &nargs, "sftp");
250         pctx.sshargs = sshargs;
251
252         pctx.nextino = 2;
253         memset(root, 0, sizeof(struct psshfs_node));
254         TAILQ_INIT(&root->pw);
255         pn_root = puffs_pn_new(pu, root);
256         if (pn_root == NULL)
257                 return errno;
258         puffs_setroot(pu, pn_root);
259
260         puffs_framev_init(pu, psbuf_read, psbuf_write, psbuf_cmp, NULL, notfn);
261
262         signal(SIGHUP, takehup);
263         puffs_ml_setloopfn(pu, psshfs_loopfn);
264         if (pssh_connect(pu, PSSHFD_META) == -1)
265                 err(1, "can't connect meta");
266         if (puffs_framev_addfd(pu, pctx.sshfd,
267             PUFFS_FBIO_READ | PUFFS_FBIO_WRITE) == -1)
268                 err(1, "framebuf addfd meta");
269         if (numconnections == 2) {
270                 if (pssh_connect(pu, PSSHFD_DATA) == -1)
271                         err(1, "can't connect data");
272                 if (puffs_framev_addfd(pu, pctx.sshfd_data,
273                     PUFFS_FBIO_READ | PUFFS_FBIO_WRITE) == -1)
274                         err(1, "framebuf addfd data");
275         } else {
276                 pctx.sshfd_data = pctx.sshfd;
277         }
278
279         if (exportfs)
280                 puffs_setfhsize(pu, sizeof(struct psshfs_fid),
281                     PUFFS_FHFLAG_NFSV2 | PUFFS_FHFLAG_NFSV3);
282
283         rva = &pn_root->pn_va;
284         rva->va_fileid = pctx.nextino++;
285
286         /*
287          * For root link count, just guess something ridiculously high.
288          * Guessing too high has no known adverse effects, but fts(3)
289          * doesn't like too low values.  This guess will be replaced
290          * with the real value when readdir is first called for
291          * the root directory.
292          */
293         rva->va_nlink = 8811;
294
295         if (detach)
296                 if (puffs_daemon(pu, 1, 1) == -1)
297                         err(1, "puffs_daemon");
298
299         if (puffs_mount(pu, argv[1], mntflags, puffs_getroot(pu)) == -1)
300                 err(1, "puffs_mount");
301         if (puffs_setblockingmode(pu, PUFFSDEV_NONBLOCK) == -1)
302                 err(1, "setblockingmode");
303
304         if (puffs_mainloop(pu) == -1)
305                 err(1, "mainloop");
306         puffs_exit(pu, 1);
307
308         return 0;
309 }
310
311 #define RETRY_MAX 100
312
313 void
314 psshfs_notify(struct puffs_usermount *pu, int fd, int what)
315 {
316         struct psshfs_ctx *pctx = puffs_getspecific(pu);
317         int nretry, which, newfd, dummy;
318
319         if (fd == pctx->sshfd) {
320                 which = PSSHFD_META;
321         } else {
322                 assert(fd == pctx->sshfd_data);
323                 which = PSSHFD_DATA;
324         }
325
326         if (puffs_getstate(pu) != PUFFS_STATE_RUNNING)
327                 return;
328
329         if (what != (PUFFS_FBIO_READ | PUFFS_FBIO_WRITE)) {
330                 puffs_framev_removefd(pu, fd, ECONNRESET);
331                 return;
332         }
333         close(fd);
334
335         /* deal with zmobies, beware of half-eaten brain */
336         while (waitpid(-1, &dummy, WNOHANG) > 0)
337                 continue;
338
339         for (nretry = 0;;nretry++) {
340                 if ((newfd = pssh_connect(pu, which)) == -1)
341                         goto retry2;
342
343                 if (puffs_framev_addfd(pu, newfd,
344                     PUFFS_FBIO_READ | PUFFS_FBIO_WRITE) == -1)
345                         goto retry1;
346
347                 break;
348  retry1:
349                 fprintf(stderr, "reconnect failed... ");
350                 close(newfd);
351  retry2:
352                 if (nretry < RETRY_MAX) {
353                         fprintf(stderr, "retry (%d left)\n", RETRY_MAX-nretry);
354                         sleep(nretry);
355                 } else {
356                         fprintf(stderr, "retry count exceeded, going south\n");
357                         exit(1); /* XXXXXXX */
358                 }
359         }
360 }
361
362 static int
363 pssh_connect(struct puffs_usermount *pu, int which)
364 {
365         struct psshfs_ctx *pctx = puffs_getspecific(pu);
366         char * const *sshargs = pctx->sshargs;
367         int fds[2];
368         pid_t pid;
369         int dnfd, x;
370         int *sshfd;
371         pid_t *sshpid;
372
373         if (which == PSSHFD_META) {
374                 sshfd = &pctx->sshfd;
375                 sshpid = &pctx->sshpid;
376         } else {
377                 assert(which == PSSHFD_DATA);
378                 sshfd = &pctx->sshfd_data;
379                 sshpid = &pctx->sshpid_data;
380         }
381
382         if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == -1)
383                 return -1;
384
385         pid = fork();
386         switch (pid) {
387         case -1:
388                 return -1;
389                 /*NOTREACHED*/
390         case 0: /* child */
391                 if (dup2(fds[0], STDIN_FILENO) == -1)
392                         err(1, "child dup2");
393                 if (dup2(fds[0], STDOUT_FILENO) == -1)
394                         err(1, "child dup2");
395                 close(fds[0]);
396                 close(fds[1]);
397
398                 dnfd = open(_PATH_DEVNULL, O_RDWR);
399                 if (dnfd != -1)
400                         dup2(dnfd, STDERR_FILENO);
401
402                 execvp(sshargs[0], sshargs);
403                 /*NOTREACHED*/
404                 break;
405         default:
406                 *sshpid = pid;
407                 *sshfd = fds[1];
408                 close(fds[0]);
409                 break;
410         }
411
412         if (psshfs_handshake(pu, *sshfd) != 0)
413                 errx(1, "handshake failed, server does not support sftp?");
414         x = 1;
415         if (ioctl(*sshfd, FIONBIO, &x) == -1)
416                 err(1, "nonblocking descriptor %d", which);
417
418         return *sshfd;
419 }
420
421 static void *
422 invalone(struct puffs_usermount *pu, struct puffs_node *pn, void *arg)
423 {
424         struct psshfs_node *psn = pn->pn_data;
425
426         psn->attrread = 0;
427         psn->dentread = 0;
428         psn->slread = 0;
429
430         return NULL;
431 }
432
433 static void
434 psshfs_loopfn(struct puffs_usermount *pu)
435 {
436
437         if (sighup) {
438                 puffs_pn_nodewalk(pu, invalone, NULL);
439                 sighup = 0;
440         }
441 }