rumpclient.c revision 1.58 1 /* $NetBSD: rumpclient.c,v 1.58 2014/04/02 14:48:03 pooka Exp $ */
2
3 /*
4 * Copyright (c) 2010, 2011 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 * Client side routines for rump syscall proxy.
30 */
31
32 #include <rump/rumpuser_port.h>
33
34 /*
35 * We use kqueue on NetBSD, poll elsewhere. Theoretically we could
36 * use kqueue on other BSD's too, but I haven't tested those. We
37 * want to use kqueue because it will give us the ability to get signal
38 * notifications but defer their handling to a stage where we do not
39 * hold the communication lock. Taking a signal while holding on to
40 * that lock may cause a deadlock. Therefore, block signals throughout
41 * the RPC when using poll. On Linux, we use signalfd in the same role
42 * as kqueue on NetBSD to be able to take signals while waiting for a
43 * response from the server.
44 */
45
46 #ifdef __NetBSD__
47 #define USE_KQUEUE
48 #endif
49 #ifdef __linux__
50 #define USE_SIGNALFD
51 #endif
52
53 __RCSID("$NetBSD: rumpclient.c,v 1.58 2014/04/02 14:48:03 pooka Exp $");
54
55 #include <sys/param.h>
56 #include <sys/mman.h>
57 #include <sys/socket.h>
58 #include <sys/time.h>
59
60 #ifdef USE_KQUEUE
61 #include <sys/event.h>
62 #endif
63
64 #include <arpa/inet.h>
65 #include <netinet/in.h>
66 #include <netinet/tcp.h>
67
68 #include <assert.h>
69 #include <dlfcn.h>
70 #include <errno.h>
71 #include <fcntl.h>
72 #include <poll.h>
73 #include <pthread.h>
74 #include <signal.h>
75 #include <stdarg.h>
76 #include <stdbool.h>
77 #include <stdio.h>
78 #include <stdlib.h>
79 #include <string.h>
80 #include <unistd.h>
81
82 #include <rump/rumpclient.h>
83
84 #define HOSTOPS
85 int (*host_socket)(int, int, int);
86 int (*host_close)(int);
87 int (*host_connect)(int, const struct sockaddr *, socklen_t);
88 int (*host_fcntl)(int, int, ...);
89 int (*host_poll)(struct pollfd *, nfds_t, int);
90 ssize_t (*host_read)(int, void *, size_t);
91 ssize_t (*host_sendmsg)(int, const struct msghdr *, int);
92 int (*host_setsockopt)(int, int, int, const void *, socklen_t);
93 int (*host_dup)(int);
94
95 #ifdef USE_KQUEUE
96 int (*host_kqueue)(void);
97 int (*host_kevent)(int, const struct kevent *, size_t,
98 struct kevent *, size_t, const struct timespec *);
99 #endif
100
101 #ifdef USE_SIGNALFD
102 #include <sys/signalfd.h>
103
104 int (*host_signalfd)(int, const sigset_t *, int);
105 #endif
106
107 int (*host_execve)(const char *, char *const[], char *const[]);
108
109 #include "sp_common.c"
110 #include "rumpuser_sigtrans.c"
111
112 static struct spclient clispc = {
113 .spc_fd = -1,
114 };
115
116 static int holyfd;
117 static sigset_t fullset;
118
119 static int doconnect(void);
120 static int handshake_req(struct spclient *, int, void *, int, bool);
121
122 /*
123 * Default: don't retry. Most clients can't handle it
124 * (consider e.g. fds suddenly going missing).
125 */
126 static time_t retrytimo = 0;
127
128 /* always defined to nothingness for now */
129 #define ERRLOG(a)
130
131 static int
132 send_with_recon(struct spclient *spc, struct iovec *iov, size_t iovlen)
133 {
134 struct timeval starttime, curtime;
135 time_t prevreconmsg;
136 unsigned reconretries;
137 int rv;
138
139 for (prevreconmsg = 0, reconretries = 0;;) {
140 rv = dosend(spc, iov, iovlen);
141 if (__predict_false(rv == ENOTCONN || rv == EBADF)) {
142 /* no persistent connections */
143 if (retrytimo == 0) {
144 rv = ENOTCONN;
145 break;
146 }
147 if (retrytimo == RUMPCLIENT_RETRYCONN_DIE)
148 _exit(1);
149
150 if (!prevreconmsg) {
151 prevreconmsg = time(NULL);
152 gettimeofday(&starttime, NULL);
153 }
154 if (reconretries == 1) {
155 if (retrytimo == RUMPCLIENT_RETRYCONN_ONCE) {
156 rv = ENOTCONN;
157 break;
158 }
159 fprintf(stderr, "rump_sp: connection to "
160 "kernel lost, trying to reconnect ...\n");
161 } else if (time(NULL) - prevreconmsg > 120) {
162 fprintf(stderr, "rump_sp: still trying to "
163 "reconnect ...\n");
164 prevreconmsg = time(NULL);
165 }
166
167 /* check that we aren't over the limit */
168 if (retrytimo > 0) {
169 time_t tdiff;
170
171 gettimeofday(&curtime, NULL);
172 tdiff = curtime.tv_sec - starttime.tv_sec;
173 if (starttime.tv_usec > curtime.tv_usec)
174 tdiff--;
175 if (tdiff >= retrytimo) {
176 fprintf(stderr, "rump_sp: reconnect "
177 "failed, %lld second timeout\n",
178 (long long)retrytimo);
179 return ENOTCONN;
180 }
181 }
182
183 /* adhoc backoff timer */
184 if (reconretries < 10) {
185 usleep(100000 * reconretries);
186 } else {
187 sleep(MIN(10, reconretries-9));
188 }
189 reconretries++;
190
191 if ((rv = doconnect()) != 0)
192 continue;
193 if ((rv = handshake_req(&clispc, HANDSHAKE_GUEST,
194 NULL, 0, true)) != 0)
195 continue;
196
197 /*
198 * ok, reconnect succesful. we need to return to
199 * the upper layer to get the entire PDU resent.
200 */
201 if (reconretries != 1)
202 fprintf(stderr, "rump_sp: reconnected!\n");
203 rv = EAGAIN;
204 break;
205 } else {
206 _DIAGASSERT(errno != EAGAIN);
207 break;
208 }
209 }
210
211 return rv;
212 }
213
214 static int
215 cliwaitresp(struct spclient *spc, struct respwait *rw, sigset_t *mask,
216 bool keeplock)
217 {
218 uint64_t mygen;
219 bool imalive = true;
220
221 pthread_mutex_lock(&spc->spc_mtx);
222 if (!keeplock)
223 sendunlockl(spc);
224 mygen = spc->spc_generation;
225
226 rw->rw_error = 0;
227 while (!rw->rw_done && rw->rw_error == 0) {
228 if (__predict_false(spc->spc_generation != mygen || !imalive))
229 break;
230
231 /* are we free to receive? */
232 if (spc->spc_istatus == SPCSTATUS_FREE) {
233 int gotresp, dosig, rv;
234
235 spc->spc_istatus = SPCSTATUS_BUSY;
236 pthread_mutex_unlock(&spc->spc_mtx);
237
238 dosig = 0;
239 for (gotresp = 0; !gotresp; ) {
240 #ifdef USE_KQUEUE
241 struct kevent kev[8];
242 int i;
243
244 /*
245 * typically we don't have a frame waiting
246 * when we come in here, so call kevent now
247 */
248 rv = host_kevent(holyfd, NULL, 0,
249 kev, __arraycount(kev), NULL);
250
251 if (__predict_false(rv == -1)) {
252 goto activity;
253 }
254
255 /*
256 * XXX: don't know how this can happen
257 * (timeout cannot expire since there
258 * isn't one), but it does happen.
259 * treat it as an expectional condition
260 * and go through tryread to determine
261 * alive status.
262 */
263 if (__predict_false(rv == 0))
264 goto activity;
265
266 for (i = 0; i < rv; i++) {
267 if (kev[i].filter == EVFILT_SIGNAL)
268 dosig++;
269 }
270 if (dosig)
271 goto cleanup;
272
273 /*
274 * ok, activity. try to read a frame to
275 * determine what happens next.
276 */
277 activity:
278 #else /* !USE_KQUEUE */
279 struct pollfd pfd[2];
280
281 pfd[0].fd = clispc.spc_fd;
282 pfd[0].events = POLLIN;
283 pfd[1].fd = holyfd;
284 pfd[1].events = POLLIN;
285
286 rv = host_poll(pfd, 2, -1);
287 if (pfd[1].revents & POLLIN) {
288 dosig = 1;
289 goto cleanup;
290 }
291 #endif /* !USE_KQUEUE */
292
293 switch (readframe(spc)) {
294 case 0:
295 continue;
296 case -1:
297 imalive = false;
298 goto cleanup;
299 default:
300 /* case 1 */
301 break;
302 }
303
304 switch (spc->spc_hdr.rsp_class) {
305 case RUMPSP_RESP:
306 case RUMPSP_ERROR:
307 kickwaiter(spc);
308 gotresp = spc->spc_hdr.rsp_reqno ==
309 rw->rw_reqno;
310 break;
311 case RUMPSP_REQ:
312 handlereq(spc);
313 break;
314 default:
315 /* panic */
316 break;
317 }
318 }
319
320 cleanup:
321 pthread_mutex_lock(&spc->spc_mtx);
322 if (spc->spc_istatus == SPCSTATUS_WANTED)
323 kickall(spc);
324 spc->spc_istatus = SPCSTATUS_FREE;
325
326 /* take one for the team */
327 if (dosig) {
328 pthread_mutex_unlock(&spc->spc_mtx);
329 pthread_sigmask(SIG_SETMASK, mask, NULL);
330 pthread_sigmask(SIG_SETMASK, &fullset, NULL);
331 pthread_mutex_lock(&spc->spc_mtx);
332 }
333 } else {
334 spc->spc_istatus = SPCSTATUS_WANTED;
335 pthread_cond_wait(&rw->rw_cv, &spc->spc_mtx);
336 }
337 }
338 TAILQ_REMOVE(&spc->spc_respwait, rw, rw_entries);
339 pthread_mutex_unlock(&spc->spc_mtx);
340 pthread_cond_destroy(&rw->rw_cv);
341
342 if (spc->spc_generation != mygen || !imalive) {
343 return ENOTCONN;
344 }
345 return rw->rw_error;
346 }
347
348 static int
349 syscall_req(struct spclient *spc, sigset_t *omask, int sysnum,
350 const void *data, size_t dlen, void **resp)
351 {
352 struct rsp_hdr rhdr;
353 struct respwait rw;
354 struct iovec iov[2];
355 int rv;
356
357 rhdr.rsp_len = sizeof(rhdr) + dlen;
358 rhdr.rsp_class = RUMPSP_REQ;
359 rhdr.rsp_type = RUMPSP_SYSCALL;
360 rhdr.rsp_sysnum = sysnum;
361
362 IOVPUT(iov[0], rhdr);
363 IOVPUT_WITHSIZE(iov[1], __UNCONST(data), dlen);
364
365 do {
366 putwait(spc, &rw, &rhdr);
367 if ((rv = send_with_recon(spc, iov, __arraycount(iov))) != 0) {
368 unputwait(spc, &rw);
369 continue;
370 }
371
372 rv = cliwaitresp(spc, &rw, omask, false);
373 if (rv == ENOTCONN)
374 rv = EAGAIN;
375 } while (rv == EAGAIN);
376
377 *resp = rw.rw_data;
378 return rv;
379 }
380
381 static int
382 handshake_req(struct spclient *spc, int type, void *data,
383 int cancel, bool haslock)
384 {
385 struct handshake_fork rf;
386 const char *myprogname = NULL; /* XXXgcc */
387 struct rsp_hdr rhdr;
388 struct respwait rw;
389 sigset_t omask;
390 size_t bonus;
391 struct iovec iov[2];
392 int rv;
393
394 if (type == HANDSHAKE_FORK) {
395 bonus = sizeof(rf);
396 } else {
397 #ifdef __NetBSD__
398 /* would procfs work on NetBSD too? */
399 myprogname = getprogname();
400 #else
401 int fd = open("/proc/self/comm", O_RDONLY);
402 if (fd == -1) {
403 myprogname = "???";
404 } else {
405 static char commname[128];
406
407 memset(commname, 0, sizeof(commname));
408 if (read(fd, commname, sizeof(commname)) > 0) {
409 char *n;
410
411 n = strrchr(commname, '\n');
412 if (n)
413 *n = '\0';
414 myprogname = commname;
415 } else {
416 myprogname = "???";
417 }
418 close(fd);
419 }
420 #endif
421 bonus = strlen(myprogname)+1;
422 }
423
424 /* performs server handshake */
425 rhdr.rsp_len = sizeof(rhdr) + bonus;
426 rhdr.rsp_class = RUMPSP_REQ;
427 rhdr.rsp_type = RUMPSP_HANDSHAKE;
428 rhdr.rsp_handshake = type;
429
430 IOVPUT(iov[0], rhdr);
431
432 pthread_sigmask(SIG_SETMASK, &fullset, &omask);
433 if (haslock)
434 putwait_locked(spc, &rw, &rhdr);
435 else
436 putwait(spc, &rw, &rhdr);
437 if (type == HANDSHAKE_FORK) {
438 memcpy(rf.rf_auth, data, sizeof(rf.rf_auth)); /* uh, why? */
439 rf.rf_cancel = cancel;
440 IOVPUT(iov[1], rf);
441 } else {
442 IOVPUT_WITHSIZE(iov[1], __UNCONST(myprogname), bonus);
443 }
444 rv = send_with_recon(spc, iov, __arraycount(iov));
445 if (rv || cancel) {
446 if (haslock)
447 unputwait_locked(spc, &rw);
448 else
449 unputwait(spc, &rw);
450 if (cancel) {
451 goto out;
452 }
453 } else {
454 rv = cliwaitresp(spc, &rw, &omask, haslock);
455 }
456 if (rv)
457 goto out;
458
459 rv = *(int *)rw.rw_data;
460 free(rw.rw_data);
461
462 out:
463 pthread_sigmask(SIG_SETMASK, &omask, NULL);
464 return rv;
465 }
466
467 static int
468 prefork_req(struct spclient *spc, sigset_t *omask, void **resp)
469 {
470 struct rsp_hdr rhdr;
471 struct respwait rw;
472 struct iovec iov[1];
473 int rv;
474
475 rhdr.rsp_len = sizeof(rhdr);
476 rhdr.rsp_class = RUMPSP_REQ;
477 rhdr.rsp_type = RUMPSP_PREFORK;
478 rhdr.rsp_error = 0;
479
480 IOVPUT(iov[0], rhdr);
481
482 do {
483 putwait(spc, &rw, &rhdr);
484 rv = send_with_recon(spc, iov, __arraycount(iov));
485 if (rv != 0) {
486 unputwait(spc, &rw);
487 continue;
488 }
489
490 rv = cliwaitresp(spc, &rw, omask, false);
491 if (rv == ENOTCONN)
492 rv = EAGAIN;
493 } while (rv == EAGAIN);
494
495 *resp = rw.rw_data;
496 return rv;
497 }
498
499 /*
500 * prevent response code from deadlocking with reconnect code
501 */
502 static int
503 resp_sendlock(struct spclient *spc)
504 {
505 int rv = 0;
506
507 pthread_mutex_lock(&spc->spc_mtx);
508 while (spc->spc_ostatus != SPCSTATUS_FREE) {
509 if (__predict_false(spc->spc_reconnecting)) {
510 rv = EBUSY;
511 goto out;
512 }
513 spc->spc_ostatus = SPCSTATUS_WANTED;
514 pthread_cond_wait(&spc->spc_cv, &spc->spc_mtx);
515 }
516 spc->spc_ostatus = SPCSTATUS_BUSY;
517
518 out:
519 pthread_mutex_unlock(&spc->spc_mtx);
520 return rv;
521 }
522
523 static void
524 send_copyin_resp(struct spclient *spc, uint64_t reqno, void *data, size_t dlen,
525 int wantstr)
526 {
527 struct rsp_hdr rhdr;
528 struct iovec iov[2];
529
530 if (wantstr)
531 dlen = MIN(dlen, strlen(data)+1);
532
533 rhdr.rsp_len = sizeof(rhdr) + dlen;
534 rhdr.rsp_reqno = reqno;
535 rhdr.rsp_class = RUMPSP_RESP;
536 rhdr.rsp_type = RUMPSP_COPYIN;
537 rhdr.rsp_sysnum = 0;
538
539 IOVPUT(iov[0], rhdr);
540 IOVPUT_WITHSIZE(iov[1], data, dlen);
541
542 if (resp_sendlock(spc) != 0)
543 return;
544 (void)SENDIOV(spc, iov);
545 sendunlock(spc);
546 }
547
548 static void
549 send_anonmmap_resp(struct spclient *spc, uint64_t reqno, void *addr)
550 {
551 struct rsp_hdr rhdr;
552 struct iovec iov[2];
553
554 rhdr.rsp_len = sizeof(rhdr) + sizeof(addr);
555 rhdr.rsp_reqno = reqno;
556 rhdr.rsp_class = RUMPSP_RESP;
557 rhdr.rsp_type = RUMPSP_ANONMMAP;
558 rhdr.rsp_sysnum = 0;
559
560 IOVPUT(iov[0], rhdr);
561 IOVPUT(iov[1], addr);
562
563 if (resp_sendlock(spc) != 0)
564 return;
565 (void)SENDIOV(spc, iov);
566 sendunlock(spc);
567 }
568
569 int
570 rumpclient_syscall(int sysnum, const void *data, size_t dlen,
571 register_t *retval)
572 {
573 struct rsp_sysresp *resp;
574 sigset_t omask;
575 void *rdata;
576 int rv;
577
578 pthread_sigmask(SIG_SETMASK, &fullset, &omask);
579
580 DPRINTF(("rumpsp syscall_req: syscall %d with %p/%zu\n",
581 sysnum, data, dlen));
582
583 rv = syscall_req(&clispc, &omask, sysnum, data, dlen, &rdata);
584 if (rv)
585 goto out;
586
587 resp = rdata;
588 DPRINTF(("rumpsp syscall_resp: syscall %d error %d, rv: %d/%d\n",
589 sysnum, rv, resp->rsys_retval[0], resp->rsys_retval[1]));
590
591 memcpy(retval, &resp->rsys_retval, sizeof(resp->rsys_retval));
592 rv = resp->rsys_error;
593 free(rdata);
594
595 out:
596 pthread_sigmask(SIG_SETMASK, &omask, NULL);
597 return rv;
598 }
599
600 static void
601 handlereq(struct spclient *spc)
602 {
603 struct rsp_copydata *copydata;
604 struct rsp_hdr *rhdr = &spc->spc_hdr;
605 void *mapaddr;
606 size_t maplen;
607 int reqtype = spc->spc_hdr.rsp_type;
608 int sig;
609
610 switch (reqtype) {
611 case RUMPSP_COPYIN:
612 case RUMPSP_COPYINSTR:
613 /*LINTED*/
614 copydata = (struct rsp_copydata *)spc->spc_buf;
615 DPRINTF(("rump_sp handlereq: copyin request: %p/%zu\n",
616 copydata->rcp_addr, copydata->rcp_len));
617 send_copyin_resp(spc, spc->spc_hdr.rsp_reqno,
618 copydata->rcp_addr, copydata->rcp_len,
619 reqtype == RUMPSP_COPYINSTR);
620 break;
621 case RUMPSP_COPYOUT:
622 case RUMPSP_COPYOUTSTR:
623 /*LINTED*/
624 copydata = (struct rsp_copydata *)spc->spc_buf;
625 DPRINTF(("rump_sp handlereq: copyout request: %p/%zu\n",
626 copydata->rcp_addr, copydata->rcp_len));
627 /*LINTED*/
628 memcpy(copydata->rcp_addr, copydata->rcp_data,
629 copydata->rcp_len);
630 break;
631 case RUMPSP_ANONMMAP:
632 /*LINTED*/
633 maplen = *(size_t *)spc->spc_buf;
634 mapaddr = mmap(NULL, maplen, PROT_READ|PROT_WRITE,
635 MAP_ANON|MAP_PRIVATE, -1, 0);
636 if (mapaddr == MAP_FAILED)
637 mapaddr = NULL;
638 DPRINTF(("rump_sp handlereq: anonmmap: %p\n", mapaddr));
639 send_anonmmap_resp(spc, spc->spc_hdr.rsp_reqno, mapaddr);
640 break;
641 case RUMPSP_RAISE:
642 sig = rumpuser__sig_rump2host(rhdr->rsp_signo);
643 DPRINTF(("rump_sp handlereq: raise sig %d\n", sig));
644 raise(sig);
645 /*
646 * We most likely have signals blocked, but the signal
647 * will be handled soon enough when we return.
648 */
649 break;
650 default:
651 printf("PANIC: INVALID TYPE %d\n", reqtype);
652 abort();
653 break;
654 }
655
656 spcfreebuf(spc);
657 }
658
659 static unsigned ptab_idx;
660 static struct sockaddr *serv_sa;
661
662 /* dup until we get a "good" fd which does not collide with stdio */
663 static int
664 dupgood(int myfd, int mustchange)
665 {
666 int ofds[4];
667 int sverrno;
668 unsigned int i;
669
670 for (i = 0; (myfd <= 2 || mustchange) && myfd != -1; i++) {
671 assert(i < __arraycount(ofds));
672 ofds[i] = myfd;
673 myfd = host_dup(myfd);
674 if (mustchange) {
675 i--; /* prevent closing old fd */
676 mustchange = 0;
677 }
678 }
679
680 sverrno = 0;
681 if (myfd == -1 && i > 0)
682 sverrno = errno;
683
684 while (i-- > 0) {
685 host_close(ofds[i]);
686 }
687
688 if (sverrno)
689 errno = sverrno;
690
691 return myfd;
692 }
693
694 #if defined(USE_KQUEUE)
695
696 static int
697 makeholyfd(void)
698 {
699 struct kevent kev[NSIG+1];
700 int i, fd;
701
702 /* setup kqueue, we want all signals and the fd */
703 if ((fd = dupgood(host_kqueue(), 0)) == -1) {
704 ERRLOG(("rump_sp: cannot setup kqueue"));
705 return -1;
706 }
707
708 for (i = 0; i < NSIG; i++) {
709 EV_SET(&kev[i], i+1, EVFILT_SIGNAL, EV_ADD|EV_ENABLE, 0, 0, 0);
710 }
711 EV_SET(&kev[NSIG], clispc.spc_fd,
712 EVFILT_READ, EV_ADD|EV_ENABLE, 0, 0, 0);
713 if (host_kevent(fd, kev, NSIG+1, NULL, 0, NULL) == -1) {
714 ERRLOG(("rump_sp: kevent() failed"));
715 return -1;
716
717 return fd;
718 }
719
720 #elif defined(USE_SIGNALFD) /* !USE_KQUEUE */
721
722 static int
723 makeholyfd(void)
724 {
725
726 return host_signalfd(-1, &fullset, 0);
727 }
728
729 #else /* !USE_KQUEUE && !USE_SIGNALFD */
730
731 static int
732 makeholyfd(void)
733 {
734
735 return -1;
736 }
737
738 #endif
739
740 static int
741 doconnect(void)
742 {
743 struct respwait rw;
744 struct rsp_hdr rhdr;
745 char banner[MAXBANNER];
746 int s, error, flags;
747 ssize_t n;
748
749 if (holyfd != -1)
750 host_close(holyfd);
751 holyfd = -1;
752 s = -1;
753
754 if (clispc.spc_fd != -1)
755 host_close(clispc.spc_fd);
756 clispc.spc_fd = -1;
757
758 /*
759 * for reconnect, gate everyone out of the receiver code
760 */
761 putwait_locked(&clispc, &rw, &rhdr);
762
763 pthread_mutex_lock(&clispc.spc_mtx);
764 clispc.spc_reconnecting = 1;
765 pthread_cond_broadcast(&clispc.spc_cv);
766 clispc.spc_generation++;
767 while (clispc.spc_istatus != SPCSTATUS_FREE) {
768 clispc.spc_istatus = SPCSTATUS_WANTED;
769 pthread_cond_wait(&rw.rw_cv, &clispc.spc_mtx);
770 }
771 kickall(&clispc);
772
773 /*
774 * we can release it already since we hold the
775 * send lock during reconnect
776 * XXX: assert it
777 */
778 clispc.spc_istatus = SPCSTATUS_FREE;
779 pthread_mutex_unlock(&clispc.spc_mtx);
780 unputwait_locked(&clispc, &rw);
781
782 free(clispc.spc_buf);
783 clispc.spc_off = 0;
784
785 s = dupgood(host_socket(parsetab[ptab_idx].domain, SOCK_STREAM, 0), 0);
786 if (s == -1)
787 return -1;
788
789 while (host_connect(s, serv_sa, parsetab[ptab_idx].slen) == -1) {
790 if (errno == EINTR)
791 continue;
792 ERRLOG(("rump_sp: client connect failed: %s\n",
793 strerror(errno)));
794 return -1;
795 }
796
797 if ((error = parsetab[ptab_idx].connhook(s)) != 0) {
798 ERRLOG(("rump_sp: connect hook failed\n"));
799 return -1;
800 }
801
802 if ((n = host_read(s, banner, sizeof(banner)-1)) <= 0) {
803 ERRLOG(("rump_sp: failed to read banner\n"));
804 return -1;
805 }
806
807 if (banner[n-1] != '\n') {
808 ERRLOG(("rump_sp: invalid banner\n"));
809 return -1;
810 }
811 banner[n] = '\0';
812 /* XXX parse the banner some day */
813
814 flags = host_fcntl(s, F_GETFL, 0);
815 if (host_fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1) {
816 ERRLOG(("rump_sp: socket fd NONBLOCK: %s\n", strerror(errno)));
817 return -1;
818 }
819 clispc.spc_fd = s;
820 clispc.spc_state = SPCSTATE_RUNNING;
821 clispc.spc_reconnecting = 0;
822 holyfd = makeholyfd();
823
824 return 0;
825 }
826
827 static int
828 doinit(void)
829 {
830
831 TAILQ_INIT(&clispc.spc_respwait);
832 pthread_mutex_init(&clispc.spc_mtx, NULL);
833 pthread_cond_init(&clispc.spc_cv, NULL);
834
835 return 0;
836 }
837
838 #ifdef RTLD_NEXT
839 void *rumpclient__dlsym(void *, const char *);
840 void *
841 rumpclient__dlsym(void *handle, const char *symbol)
842 {
843
844 return dlsym(handle, symbol);
845 }
846 void *rumphijack_dlsym(void *, const char *)
847 __attribute__((__weak__, alias("rumpclient__dlsym")));
848 #endif
849
850 static pid_t init_done = 0;
851
852 int
853 rumpclient_init(void)
854 {
855 char *p;
856 int error;
857 int rv = -1;
858 int hstype;
859 pid_t mypid;
860
861 /*
862 * Make sure we're not riding the context of a previous
863 * host fork. Note: it's *possible* that after n>1 forks
864 * we have the same pid as one of our exited parents, but
865 * I'm pretty sure there are 0 practical implications, since
866 * it means generations would have to skip rumpclient init.
867 */
868 if (init_done == (mypid = getpid()))
869 return 0;
870
871 /* kq does not traverse fork() */
872 #ifdef USE_KQUEUE
873 if (init_done != 0)
874 holyfd = -1;
875 #endif
876 init_done = mypid;
877
878 sigfillset(&fullset);
879
880 /*
881 * sag mir, wo die symbols sind. zogen fort, der krieg beginnt.
882 * wann wird man je verstehen? wann wird man je verstehen?
883 */
884 #ifdef RTLD_NEXT
885 #define FINDSYM2(_name_,_syscall_) \
886 if ((host_##_name_ = rumphijack_dlsym(RTLD_NEXT, \
887 #_syscall_)) == NULL) { \
888 if (rumphijack_dlsym == rumpclient__dlsym) \
889 host_##_name_ = _name_; /* static fallback */ \
890 if (host_##_name_ == NULL) { \
891 fprintf(stderr,"cannot find %s: %s", #_syscall_,\
892 dlerror()); \
893 exit(1); \
894 } \
895 }
896 #else
897 #define FINDSYM2(_name_,_syscall) \
898 host_##_name_ = _name_;
899 #endif
900 #define FINDSYM(_name_) FINDSYM2(_name_,_name_)
901 #ifdef __NetBSD__
902 FINDSYM2(socket,__socket30)
903 #else
904 FINDSYM(socket)
905 #endif
906
907 FINDSYM(close)
908 FINDSYM(connect)
909 FINDSYM(fcntl)
910 FINDSYM(poll)
911 FINDSYM(read)
912 FINDSYM(sendmsg)
913 FINDSYM(setsockopt)
914 FINDSYM(dup)
915 FINDSYM(execve)
916
917 #ifdef USE_KQUEUE
918 FINDSYM(kqueue)
919 #if !__NetBSD_Prereq__(5,99,7)
920 FINDSYM(kevent)
921 #else
922 FINDSYM2(kevent,_sys___kevent50)
923 #endif
924 #endif /* USE_KQUEUE */
925
926 #ifdef USE_SIGNALFD
927 FINDSYM(signalfd)
928 #endif
929
930 #undef FINDSYM
931 #undef FINDSY2
932
933 if ((p = getenv("RUMP__PARSEDSERVER")) == NULL) {
934 if ((p = getenv("RUMP_SERVER")) == NULL) {
935 fprintf(stderr, "error: RUMP_SERVER not set\n");
936 errno = ENOENT;
937 goto out;
938 }
939 }
940
941 if ((error = parseurl(p, &serv_sa, &ptab_idx, 0)) != 0) {
942 errno = error;
943 goto out;
944 }
945
946 if (doinit() == -1)
947 goto out;
948
949 if ((p = getenv("RUMPCLIENT__EXECFD")) != NULL) {
950 sscanf(p, "%d,%d", &clispc.spc_fd, &holyfd);
951 unsetenv("RUMPCLIENT__EXECFD");
952 hstype = HANDSHAKE_EXEC;
953 } else {
954 if (doconnect() == -1)
955 goto out;
956 hstype = HANDSHAKE_GUEST;
957 }
958
959 error = handshake_req(&clispc, hstype, NULL, 0, false);
960 if (error) {
961 pthread_mutex_destroy(&clispc.spc_mtx);
962 pthread_cond_destroy(&clispc.spc_cv);
963 if (clispc.spc_fd != -1)
964 host_close(clispc.spc_fd);
965 errno = error;
966 goto out;
967 }
968 rv = 0;
969
970 out:
971 if (rv == -1)
972 init_done = 0;
973 return rv;
974 }
975
976 struct rumpclient_fork {
977 uint32_t fork_auth[AUTHLEN];
978 struct spclient fork_spc;
979 int fork_holyfd;
980 };
981
982 struct rumpclient_fork *
983 rumpclient_prefork(void)
984 {
985 struct rumpclient_fork *rpf;
986 sigset_t omask;
987 void *resp;
988 int rv;
989
990 pthread_sigmask(SIG_SETMASK, &fullset, &omask);
991 rpf = malloc(sizeof(*rpf));
992 if (rpf == NULL)
993 goto out;
994
995 if ((rv = prefork_req(&clispc, &omask, &resp)) != 0) {
996 free(rpf);
997 errno = rv;
998 rpf = NULL;
999 goto out;
1000 }
1001
1002 memcpy(rpf->fork_auth, resp, sizeof(rpf->fork_auth));
1003 free(resp);
1004
1005 rpf->fork_spc = clispc;
1006 rpf->fork_holyfd = holyfd;
1007
1008 out:
1009 pthread_sigmask(SIG_SETMASK, &omask, NULL);
1010 return rpf;
1011 }
1012
1013 int
1014 rumpclient_fork_init(struct rumpclient_fork *rpf)
1015 {
1016 int error;
1017 int osock;
1018
1019 osock = clispc.spc_fd;
1020 memset(&clispc, 0, sizeof(clispc));
1021 clispc.spc_fd = osock;
1022
1023 #ifdef USE_KQUEUE
1024 holyfd = -1; /* kqueue descriptor is not copied over fork() */
1025 #else
1026 if (holyfd != -1) {
1027 host_close(holyfd);
1028 holyfd = -1;
1029 }
1030 #endif
1031
1032 if (doinit() == -1)
1033 return -1;
1034 if (doconnect() == -1)
1035 return -1;
1036
1037 error = handshake_req(&clispc, HANDSHAKE_FORK, rpf->fork_auth,
1038 0, false);
1039 if (error) {
1040 pthread_mutex_destroy(&clispc.spc_mtx);
1041 pthread_cond_destroy(&clispc.spc_cv);
1042 errno = error;
1043 return -1;
1044 }
1045
1046 return 0;
1047 }
1048
1049 /*ARGSUSED*/
1050 void
1051 rumpclient_fork_cancel(struct rumpclient_fork *rpf)
1052 {
1053
1054 /* EUNIMPL */
1055 }
1056
1057 void
1058 rumpclient_fork_vparent(struct rumpclient_fork *rpf)
1059 {
1060
1061 clispc = rpf->fork_spc;
1062 holyfd = rpf->fork_holyfd;
1063 }
1064
1065 void
1066 rumpclient_setconnretry(time_t timeout)
1067 {
1068
1069 if (timeout < RUMPCLIENT_RETRYCONN_DIE)
1070 return; /* gigo */
1071
1072 retrytimo = timeout;
1073 }
1074
1075 int
1076 rumpclient__closenotify(int *fdp, enum rumpclient_closevariant variant)
1077 {
1078 int fd = *fdp;
1079 int untilfd, rv;
1080 int newfd;
1081
1082 switch (variant) {
1083 case RUMPCLIENT_CLOSE_FCLOSEM:
1084 untilfd = MAX(clispc.spc_fd, holyfd);
1085 for (; fd <= untilfd; fd++) {
1086 if (fd == clispc.spc_fd || fd == holyfd)
1087 continue;
1088 rv = host_close(fd);
1089 if (rv == -1)
1090 return -1;
1091 }
1092 *fdp = fd;
1093 break;
1094
1095 case RUMPCLIENT_CLOSE_CLOSE:
1096 case RUMPCLIENT_CLOSE_DUP2:
1097 if (fd == clispc.spc_fd) {
1098 newfd = dupgood(clispc.spc_fd, 1);
1099 if (newfd == -1)
1100 return -1;
1101
1102 #ifdef USE_KQUEUE
1103 {
1104 struct kevent kev[2];
1105
1106 /*
1107 * now, we have a new socket number, so change
1108 * the file descriptor that kqueue is
1109 * monitoring. remove old and add new.
1110 */
1111 EV_SET(&kev[0], clispc.spc_fd,
1112 EVFILT_READ, EV_DELETE, 0, 0, 0);
1113 EV_SET(&kev[1], newfd,
1114 EVFILT_READ, EV_ADD|EV_ENABLE, 0, 0, 0);
1115 if (host_kevent(holyfd, kev, 2, NULL, 0, NULL) == -1) {
1116 int sverrno = errno;
1117 host_close(newfd);
1118 errno = sverrno;
1119 return -1;
1120 }}
1121 #endif /* !USE_KQUEUE */
1122 clispc.spc_fd = newfd;
1123 }
1124 if (holyfd != -1 && fd == holyfd) {
1125 newfd = dupgood(holyfd, 1);
1126 if (newfd == -1)
1127 return -1;
1128 holyfd = newfd;
1129 }
1130 break;
1131 }
1132
1133 return 0;
1134 }
1135
1136 pid_t
1137 rumpclient_fork(void)
1138 {
1139
1140 return rumpclient__dofork(fork);
1141 }
1142
1143 /*
1144 * Process is about to exec. Save info about our existing connection
1145 * in the env. rumpclient will check for this info in init().
1146 * This is mostly for the benefit of rumphijack, but regular applications
1147 * may use it as well.
1148 */
1149 int
1150 rumpclient_exec(const char *path, char *const argv[], char *const envp[])
1151 {
1152 char buf[4096];
1153 char **newenv;
1154 char *envstr, *envstr2;
1155 size_t nelem;
1156 int rv, sverrno;
1157
1158 snprintf(buf, sizeof(buf), "RUMPCLIENT__EXECFD=%d,%d",
1159 clispc.spc_fd, holyfd);
1160 envstr = malloc(strlen(buf)+1);
1161 if (envstr == NULL) {
1162 return ENOMEM;
1163 }
1164 strcpy(envstr, buf);
1165
1166 /* do we have a fully parsed url we want to forward in the env? */
1167 if (*parsedurl != '\0') {
1168 snprintf(buf, sizeof(buf),
1169 "RUMP__PARSEDSERVER=%s", parsedurl);
1170 envstr2 = malloc(strlen(buf)+1);
1171 if (envstr2 == NULL) {
1172 free(envstr);
1173 return ENOMEM;
1174 }
1175 strcpy(envstr2, buf);
1176 } else {
1177 envstr2 = NULL;
1178 }
1179
1180 for (nelem = 0; envp && envp[nelem]; nelem++)
1181 continue;
1182
1183 newenv = malloc(sizeof(*newenv) * (nelem+3));
1184 if (newenv == NULL) {
1185 free(envstr2);
1186 free(envstr);
1187 return ENOMEM;
1188 }
1189 memcpy(&newenv[0], envp, nelem*sizeof(*envp));
1190
1191 newenv[nelem] = envstr;
1192 newenv[nelem+1] = envstr2;
1193 newenv[nelem+2] = NULL;
1194
1195 rv = host_execve(path, argv, newenv);
1196
1197 _DIAGASSERT(rv != 0);
1198 sverrno = errno;
1199 free(envstr2);
1200 free(envstr);
1201 free(newenv);
1202 errno = sverrno;
1203 return rv;
1204 }
1205
1206 /*
1207 * daemon() is handwritten for the benefit of platforms which
1208 * do not support daemon().
1209 */
1210 int
1211 rumpclient_daemon(int nochdir, int noclose)
1212 {
1213 struct rumpclient_fork *rf;
1214 int sverrno;
1215
1216 if ((rf = rumpclient_prefork()) == NULL)
1217 return -1;
1218
1219 switch (fork()) {
1220 case 0:
1221 break;
1222 case -1:
1223 goto daemonerr;
1224 default:
1225 _exit(0);
1226 }
1227
1228 if (setsid() == -1)
1229 goto daemonerr;
1230 if (!nochdir && chdir("/") == -1)
1231 goto daemonerr;
1232 if (!noclose) {
1233 int fd = open("/dev/null", O_RDWR);
1234 dup2(fd, 0);
1235 dup2(fd, 1);
1236 dup2(fd, 2);
1237 if (fd > 2)
1238 close(fd);
1239 }
1240
1241 /* note: fork is either completed or cancelled by the call */
1242 if (rumpclient_fork_init(rf) == -1)
1243 return -1;
1244
1245 return 0;
1246
1247 daemonerr:
1248 sverrno = errno;
1249 rumpclient_fork_cancel(rf);
1250 errno = sverrno;
1251 return -1;
1252 }
1253