xref: /netbsd/lib/librumpuser/sp_common.c (revision f1116d95)
1 /*      $NetBSD: sp_common.c,v 1.43 2021/12/07 10:39:33 gson 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  * Common client/server sysproxy routines.  #included.
30  */
31 
32 #include "rumpuser_port.h"
33 
34 #include <sys/types.h>
35 #include <sys/mman.h>
36 #include <sys/queue.h>
37 #include <sys/socket.h>
38 #include <sys/un.h>
39 #include <sys/uio.h>
40 
41 #include <arpa/inet.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 
45 #include <assert.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <inttypes.h>
49 #include <limits.h>
50 #include <poll.h>
51 #include <pthread.h>
52 #include <stdarg.h>
53 #include <stddef.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 
59 /*
60  * XXX: NetBSD's __unused collides with Linux headers, so we cannot
61  * define it before we've included everything.
62  */
63 #if !defined(__unused) && (defined(__clang__) || defined(__GNUC__))
64 #define __unused __attribute__((__unused__))
65 #endif
66 #if !defined(__printflike) && (defined(__clang__) || defined(__GNUC__))
67 #define __printflike(a,b) __attribute__((__format__(__printf__, a, b))))
68 #endif
69 
70 //#define DEBUG
71 #ifdef DEBUG
72 #define DPRINTF(x) mydprintf x
73 static __printflike(1, 2) void
mydprintf(const char * fmt,...)74 mydprintf(const char *fmt, ...)
75 {
76 	va_list ap;
77 
78 	va_start(ap, fmt);
79 	vfprintf(stderr, fmt, ap);
80 	va_end(ap);
81 }
82 #else
83 #define DPRINTF(x)
84 #endif
85 
86 #ifndef HOSTOPS
87 #define host_poll poll
88 #define host_read read
89 #define host_sendmsg sendmsg
90 #define host_setsockopt setsockopt
91 #endif
92 
93 #define IOVPUT(_io_, _b_) _io_.iov_base = 			\
94     (void *)&_b_; _io_.iov_len = sizeof(_b_);
95 #define IOVPUT_WITHSIZE(_io_, _b_, _l_) _io_.iov_base =		\
96     (void *)(_b_); _io_.iov_len = _l_;
97 #define SENDIOV(_spc_, _iov_) dosend(_spc_, _iov_, __arraycount(_iov_))
98 
99 /*
100  * Bah, I hate writing on-off-wire conversions in C
101  */
102 
103 enum { RUMPSP_REQ, RUMPSP_RESP, RUMPSP_ERROR };
104 enum {	RUMPSP_HANDSHAKE,
105 	RUMPSP_SYSCALL,
106 	RUMPSP_COPYIN, RUMPSP_COPYINSTR,
107 	RUMPSP_COPYOUT, RUMPSP_COPYOUTSTR,
108 	RUMPSP_ANONMMAP,
109 	RUMPSP_PREFORK,
110 	RUMPSP_RAISE };
111 
112 enum { HANDSHAKE_GUEST, HANDSHAKE_AUTH, HANDSHAKE_FORK, HANDSHAKE_EXEC };
113 
114 /*
115  * error types used for RUMPSP_ERROR
116  */
117 enum rumpsp_err { RUMPSP_ERR_NONE = 0, RUMPSP_ERR_TRYAGAIN, RUMPSP_ERR_AUTH,
118 	RUMPSP_ERR_INVALID_PREFORK, RUMPSP_ERR_RFORK_FAILED,
119 	RUMPSP_ERR_INEXEC, RUMPSP_ERR_NOMEM, RUMPSP_ERR_MALFORMED_REQUEST };
120 
121 /*
122  * The mapping of the above types to errno.  They are almost never exposed
123  * to the client after handshake (except for a server resource shortage
124  * and the client trying to be funny).  This is a function instead of
125  * an array to catch missing values.  Theoretically, the compiled code
126  * should be the same.
127  */
128 static int
errmap(enum rumpsp_err error)129 errmap(enum rumpsp_err error)
130 {
131 
132 	switch (error) {
133 	/* XXX: no EAUTH on Linux */
134 	case RUMPSP_ERR_NONE:			return 0;
135 	case RUMPSP_ERR_AUTH:			return EPERM;
136 	case RUMPSP_ERR_TRYAGAIN:		return EAGAIN;
137 	case RUMPSP_ERR_INVALID_PREFORK:	return ESRCH;
138 	case RUMPSP_ERR_RFORK_FAILED:		return EIO; /* got a light? */
139 	case RUMPSP_ERR_INEXEC:			return EBUSY;
140 	case RUMPSP_ERR_NOMEM:			return ENOMEM;
141 	case RUMPSP_ERR_MALFORMED_REQUEST:	return EINVAL;
142 	}
143 
144 	return -1;
145 }
146 
147 #define AUTHLEN 4 /* 128bit fork auth */
148 
149 struct rsp_hdr {
150 	uint64_t rsp_len;
151 	uint64_t rsp_reqno;
152 	uint16_t rsp_class;
153 	uint16_t rsp_type;
154 	/*
155 	 * We want this structure 64bit-aligned for typecast fun,
156 	 * so might as well use the following for something.
157 	 */
158 	union {
159 		uint32_t sysnum;
160 		uint32_t error;
161 		uint32_t handshake;
162 		uint32_t signo;
163 	} u;
164 };
165 #define HDRSZ sizeof(struct rsp_hdr)
166 #define rsp_sysnum u.sysnum
167 #define rsp_error u.error
168 #define rsp_handshake u.handshake
169 #define rsp_signo u.signo
170 
171 #define MAXBANNER 96
172 
173 /*
174  * Data follows the header.  We have two types of structured data.
175  */
176 
177 /* copyin/copyout */
178 struct rsp_copydata {
179 	size_t rcp_len;
180 	void *rcp_addr;
181 	uint8_t rcp_data[0];
182 };
183 
184 /* syscall response */
185 struct rsp_sysresp {
186 	int rsys_error;
187 	register_t rsys_retval[2];
188 };
189 
190 struct handshake_fork {
191 	uint32_t rf_auth[4];
192 	int rf_cancel;
193 };
194 
195 struct respwait {
196 	uint64_t rw_reqno;
197 	void *rw_data;
198 	size_t rw_dlen;
199 	int rw_done;
200 	int rw_error;
201 
202 	pthread_cond_t rw_cv;
203 
204 	TAILQ_ENTRY(respwait) rw_entries;
205 };
206 
207 struct prefork;
208 struct spclient {
209 	int spc_fd;
210 	int spc_refcnt;
211 	int spc_state;
212 
213 	pthread_mutex_t spc_mtx;
214 	pthread_cond_t spc_cv;
215 
216 	struct lwp *spc_mainlwp;
217 	pid_t spc_pid;
218 
219 	TAILQ_HEAD(, respwait) spc_respwait;
220 
221 	/* rest of the fields are zeroed upon disconnect */
222 #define SPC_ZEROFF offsetof(struct spclient, spc_pfd)
223 	struct pollfd *spc_pfd;
224 
225 	struct rsp_hdr spc_hdr;
226 	uint8_t *spc_buf;
227 	size_t spc_off;
228 
229 	uint64_t spc_nextreq;
230 	uint64_t spc_syscallreq;
231 	uint64_t spc_generation;
232 	int spc_ostatus, spc_istatus;
233 	int spc_reconnecting;
234 	int spc_inexec;
235 
236 	LIST_HEAD(, prefork) spc_pflist;
237 };
238 #define SPCSTATUS_FREE 0
239 #define SPCSTATUS_BUSY 1
240 #define SPCSTATUS_WANTED 2
241 
242 #define SPCSTATE_NEW     0
243 #define SPCSTATE_RUNNING 1
244 #define SPCSTATE_DYING   2
245 
246 typedef int (*addrparse_fn)(const char *, struct sockaddr **, int);
247 typedef int (*connecthook_fn)(int);
248 typedef void (*cleanup_fn)(struct sockaddr *);
249 
250 static int readframe(struct spclient *);
251 static void handlereq(struct spclient *);
252 
253 static __inline void
spcresetbuf(struct spclient * spc)254 spcresetbuf(struct spclient *spc)
255 {
256 
257 	spc->spc_buf = NULL;
258 	spc->spc_off = 0;
259 }
260 
261 static __inline void
spcfreebuf(struct spclient * spc)262 spcfreebuf(struct spclient *spc)
263 {
264 
265 	free(spc->spc_buf);
266 	spcresetbuf(spc);
267 }
268 
269 static void
sendlockl(struct spclient * spc)270 sendlockl(struct spclient *spc)
271 {
272 
273 	while (spc->spc_ostatus != SPCSTATUS_FREE) {
274 		spc->spc_ostatus = SPCSTATUS_WANTED;
275 		pthread_cond_wait(&spc->spc_cv, &spc->spc_mtx);
276 	}
277 	spc->spc_ostatus = SPCSTATUS_BUSY;
278 }
279 
280 static void __unused
sendlock(struct spclient * spc)281 sendlock(struct spclient *spc)
282 {
283 
284 	pthread_mutex_lock(&spc->spc_mtx);
285 	sendlockl(spc);
286 	pthread_mutex_unlock(&spc->spc_mtx);
287 }
288 
289 static void
sendunlockl(struct spclient * spc)290 sendunlockl(struct spclient *spc)
291 {
292 
293 	if (spc->spc_ostatus == SPCSTATUS_WANTED)
294 		pthread_cond_broadcast(&spc->spc_cv);
295 	spc->spc_ostatus = SPCSTATUS_FREE;
296 }
297 
298 static void
sendunlock(struct spclient * spc)299 sendunlock(struct spclient *spc)
300 {
301 
302 	pthread_mutex_lock(&spc->spc_mtx);
303 	sendunlockl(spc);
304 	pthread_mutex_unlock(&spc->spc_mtx);
305 }
306 
307 static int
dosend(struct spclient * spc,struct iovec * iov,size_t iovlen)308 dosend(struct spclient *spc, struct iovec *iov, size_t iovlen)
309 {
310 	struct msghdr msg;
311 	struct pollfd pfd;
312 	ssize_t n = 0;
313 	int fd = spc->spc_fd;
314 
315 	pfd.fd = fd;
316 	pfd.events = POLLOUT;
317 
318 	memset(&msg, 0, sizeof(msg));
319 
320 	for (;;) {
321 		/* not first round?  poll */
322 		if (n) {
323 			if (host_poll(&pfd, 1, INFTIM) == -1) {
324 				if (errno == EINTR)
325 					continue;
326 				return errno;
327 			}
328 		}
329 
330 		msg.msg_iov = iov;
331 		msg.msg_iovlen = iovlen;
332 		n = host_sendmsg(fd, &msg, MSG_NOSIGNAL);
333 		if (n == -1)  {
334 			if (errno == EPIPE)
335 				return ENOTCONN;
336 			if (errno != EAGAIN)
337 				return errno;
338 			continue;
339 		}
340 		if (n == 0) {
341 			return ENOTCONN;
342 		}
343 
344 		/* ok, need to adjust iovec for potential next round */
345 		while (iovlen && n >= (ssize_t)iov[0].iov_len) {
346 			n -= iov[0].iov_len;
347 			iov++;
348 			iovlen--;
349 		}
350 
351 		if (iovlen == 0) {
352 			_DIAGASSERT(n == 0);
353 			break;
354 		} else {
355 			iov[0].iov_base =
356 			    (void *)((uint8_t *)iov[0].iov_base + n);
357 			iov[0].iov_len -= n;
358 		}
359 	}
360 
361 	return 0;
362 }
363 
364 static void
doputwait(struct spclient * spc,struct respwait * rw,struct rsp_hdr * rhdr)365 doputwait(struct spclient *spc, struct respwait *rw, struct rsp_hdr *rhdr)
366 {
367 
368 	rw->rw_data = NULL;
369 	rw->rw_dlen = rw->rw_done = rw->rw_error = 0;
370 	pthread_cond_init(&rw->rw_cv, NULL);
371 
372 	pthread_mutex_lock(&spc->spc_mtx);
373 	rw->rw_reqno = rhdr->rsp_reqno = spc->spc_nextreq++;
374 	TAILQ_INSERT_TAIL(&spc->spc_respwait, rw, rw_entries);
375 }
376 
377 static void __unused
putwait_locked(struct spclient * spc,struct respwait * rw,struct rsp_hdr * rhdr)378 putwait_locked(struct spclient *spc, struct respwait *rw, struct rsp_hdr *rhdr)
379 {
380 
381 	doputwait(spc, rw, rhdr);
382 	pthread_mutex_unlock(&spc->spc_mtx);
383 }
384 
385 static void
putwait(struct spclient * spc,struct respwait * rw,struct rsp_hdr * rhdr)386 putwait(struct spclient *spc, struct respwait *rw, struct rsp_hdr *rhdr)
387 {
388 
389 	doputwait(spc, rw, rhdr);
390 	sendlockl(spc);
391 	pthread_mutex_unlock(&spc->spc_mtx);
392 }
393 
394 static void
dounputwait(struct spclient * spc,struct respwait * rw)395 dounputwait(struct spclient *spc, struct respwait *rw)
396 {
397 
398 	TAILQ_REMOVE(&spc->spc_respwait, rw, rw_entries);
399 	pthread_mutex_unlock(&spc->spc_mtx);
400 	pthread_cond_destroy(&rw->rw_cv);
401 
402 }
403 
404 static void __unused
unputwait_locked(struct spclient * spc,struct respwait * rw)405 unputwait_locked(struct spclient *spc, struct respwait *rw)
406 {
407 
408 	pthread_mutex_lock(&spc->spc_mtx);
409 	dounputwait(spc, rw);
410 }
411 
412 static void
unputwait(struct spclient * spc,struct respwait * rw)413 unputwait(struct spclient *spc, struct respwait *rw)
414 {
415 
416 	pthread_mutex_lock(&spc->spc_mtx);
417 	sendunlockl(spc);
418 
419 	dounputwait(spc, rw);
420 }
421 
422 static void
kickwaiter(struct spclient * spc)423 kickwaiter(struct spclient *spc)
424 {
425 	struct respwait *rw;
426 	int error = 0;
427 
428 	pthread_mutex_lock(&spc->spc_mtx);
429 	TAILQ_FOREACH(rw, &spc->spc_respwait, rw_entries) {
430 		if (rw->rw_reqno == spc->spc_hdr.rsp_reqno)
431 			break;
432 	}
433 	if (rw == NULL) {
434 		DPRINTF(("no waiter found, invalid reqno %" PRIu64 "?\n",
435 		    spc->spc_hdr.rsp_reqno));
436 		pthread_mutex_unlock(&spc->spc_mtx);
437 		spcfreebuf(spc);
438 		return;
439 	}
440 	DPRINTF(("rump_sp: client %p woke up waiter at %p\n", spc, rw));
441 	rw->rw_data = spc->spc_buf;
442 	rw->rw_done = 1;
443 	rw->rw_dlen = (size_t)(spc->spc_off - HDRSZ);
444 	if (spc->spc_hdr.rsp_class == RUMPSP_ERROR) {
445 		error = rw->rw_error = errmap(spc->spc_hdr.rsp_error);
446 	}
447 	pthread_cond_signal(&rw->rw_cv);
448 	pthread_mutex_unlock(&spc->spc_mtx);
449 
450 	if (error)
451 		spcfreebuf(spc);
452 	else
453 		spcresetbuf(spc);
454 }
455 
456 static void
kickall(struct spclient * spc)457 kickall(struct spclient *spc)
458 {
459 	struct respwait *rw;
460 
461 	/* DIAGASSERT(mutex_owned(spc_lock)) */
462 	TAILQ_FOREACH(rw, &spc->spc_respwait, rw_entries)
463 		pthread_cond_broadcast(&rw->rw_cv);
464 }
465 
466 static int
readframe(struct spclient * spc)467 readframe(struct spclient *spc)
468 {
469 	int fd = spc->spc_fd;
470 	size_t left;
471 	size_t framelen;
472 	ssize_t n;
473 
474 	/* still reading header? */
475 	if (spc->spc_off < HDRSZ) {
476 		DPRINTF(("rump_sp: readframe getting header at offset %zu\n",
477 		    spc->spc_off));
478 
479 		left = HDRSZ - spc->spc_off;
480 		/*LINTED: cast ok */
481 		n = host_read(fd, (uint8_t*)&spc->spc_hdr + spc->spc_off, left);
482 		if (n == 0) {
483 			return -1;
484 		}
485 		if (n == -1) {
486 			if (errno == EAGAIN)
487 				return 0;
488 			return -1;
489 		}
490 
491 		spc->spc_off += n;
492 		if (spc->spc_off < HDRSZ) {
493 			return 0;
494 		}
495 
496 		/*LINTED*/
497 		framelen = spc->spc_hdr.rsp_len;
498 
499 		if (framelen < HDRSZ) {
500 			return -1;
501 		} else if (framelen == HDRSZ) {
502 			return 1;
503 		}
504 
505 		/* Add an extra byte so that we are always NUL-terminated */
506 		spc->spc_buf = malloc(framelen - HDRSZ + 1);
507 		if (spc->spc_buf == NULL) {
508 			return -1;
509 		}
510 		memset(spc->spc_buf, 0, framelen - HDRSZ + 1);
511 
512 		/* "fallthrough" */
513 	} else {
514 		/*LINTED*/
515 		framelen = spc->spc_hdr.rsp_len;
516 	}
517 
518 	left = framelen - spc->spc_off;
519 
520 	DPRINTF(("rump_sp: readframe getting body at offset %zu, left %zu\n",
521 	    spc->spc_off, left));
522 
523 	if (left == 0)
524 		return 1;
525 	n = host_read(fd, spc->spc_buf + (spc->spc_off - HDRSZ), left);
526 	if (n == 0) {
527 		return -1;
528 	}
529 	if (n == -1) {
530 		if (errno == EAGAIN)
531 			return 0;
532 		return -1;
533 	}
534 	spc->spc_off += n;
535 	left -= n;
536 
537 	/* got everything? */
538 	if (left == 0)
539 		return 1;
540 	else
541 		return 0;
542 }
543 
544 static int
tcp_parse(const char * addr,struct sockaddr ** sa,int allow_wildcard)545 tcp_parse(const char *addr, struct sockaddr **sa, int allow_wildcard)
546 {
547 	struct sockaddr_in sin;
548 	char buf[64];
549 	const char *p;
550 	size_t l;
551 	int port;
552 
553 	memset(&sin, 0, sizeof(sin));
554 	SIN_SETLEN(sin, sizeof(sin));
555 	sin.sin_family = AF_INET;
556 
557 	p = strchr(addr, ':');
558 	if (!p) {
559 		fprintf(stderr, "rump_sp_tcp: missing port specifier\n");
560 		return EINVAL;
561 	}
562 
563 	l = p - addr;
564 	if (l > sizeof(buf)-1) {
565 		fprintf(stderr, "rump_sp_tcp: address too long\n");
566 		return EINVAL;
567 	}
568 	strncpy(buf, addr, l);
569 	buf[l] = '\0';
570 
571 	/* special INADDR_ANY treatment */
572 	if (strcmp(buf, "*") == 0 || strcmp(buf, "0") == 0) {
573 		sin.sin_addr.s_addr = INADDR_ANY;
574 	} else {
575 		switch (inet_pton(AF_INET, buf, &sin.sin_addr)) {
576 		case 1:
577 			break;
578 		case 0:
579 			fprintf(stderr, "rump_sp_tcp: cannot parse %s\n", buf);
580 			return EINVAL;
581 		case -1:
582 			fprintf(stderr, "rump_sp_tcp: inet_pton failed\n");
583 			return errno;
584 		default:
585 			assert(/*CONSTCOND*/0);
586 			return EINVAL;
587 		}
588 	}
589 
590 	if (!allow_wildcard && sin.sin_addr.s_addr == INADDR_ANY) {
591 		fprintf(stderr, "rump_sp_tcp: client needs !INADDR_ANY\n");
592 		return EINVAL;
593 	}
594 
595 	/* advance to port number & parse */
596 	p++;
597 	l = strspn(p, "0123456789");
598 	if (l == 0) {
599 		fprintf(stderr, "rump_sp_tcp: port now found: %s\n", p);
600 		return EINVAL;
601 	}
602 	strncpy(buf, p, l);
603 	buf[l] = '\0';
604 
605 	if (*(p+l) != '/' && *(p+l) != '\0') {
606 		fprintf(stderr, "rump_sp_tcp: junk at end of port: %s\n", addr);
607 		return EINVAL;
608 	}
609 
610 	port = atoi(buf);
611 	if (port < 0 || port >= (1<<(8*sizeof(in_port_t)))) {
612 		fprintf(stderr, "rump_sp_tcp: port %d out of range\n", port);
613 		return ERANGE;
614 	}
615 	sin.sin_port = htons(port);
616 
617 	*sa = malloc(sizeof(sin));
618 	if (*sa == NULL)
619 		return errno;
620 	memcpy(*sa, &sin, sizeof(sin));
621 	return 0;
622 }
623 
624 static int
tcp_connecthook(int s)625 tcp_connecthook(int s)
626 {
627 	int x;
628 
629 	x = 1;
630 	host_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &x, sizeof(x));
631 
632 	return 0;
633 }
634 
635 static char parsedurl[256];
636 
637 /*ARGSUSED*/
638 static int
unix_parse(const char * addr,struct sockaddr ** sa,int allow_wildcard)639 unix_parse(const char *addr, struct sockaddr **sa, int allow_wildcard)
640 {
641 	struct sockaddr_un s_un;
642 	size_t slen;
643 	int savepath = 0;
644 
645 	if (strlen(addr) >= sizeof(s_un.sun_path))
646 		return ENAMETOOLONG;
647 
648 	/*
649 	 * The pathname can be all kinds of spaghetti elementals,
650 	 * so meek and obidient we accept everything.  However, use
651 	 * full path for easy cleanup in case someone gives a relative
652 	 * one and the server does a chdir() between now than the
653 	 * cleanup.
654 	 */
655 	memset(&s_un, 0, sizeof(s_un));
656 	s_un.sun_family = AF_LOCAL;
657 	if (*addr != '/') {
658 		char mywd[PATH_MAX];
659 
660 		if (getcwd(mywd, sizeof(mywd)) == NULL) {
661 			fprintf(stderr, "warning: cannot determine cwd, "
662 			    "omitting socket cleanup\n");
663 		} else {
664 			if (strlen(addr)+strlen(mywd)+1
665 			    >= sizeof(s_un.sun_path))
666 				return ENAMETOOLONG;
667 			strcpy(s_un.sun_path, mywd);
668 			strcat(s_un.sun_path, "/");
669 			savepath = 1;
670 		}
671 	}
672 	strcat(s_un.sun_path, addr);
673 #if !(defined(__linux__) || defined(__sun__) || defined(__CYGWIN__))
674 	s_un.sun_len = SUN_LEN(&s_un);
675 #endif
676 	slen = sizeof(s_un);
677 
678 	if (savepath && *parsedurl == '\0') {
679 		snprintf(parsedurl, sizeof(parsedurl),
680 		    "unix://%s", s_un.sun_path);
681 	}
682 
683 	*sa = malloc(slen);
684 	if (*sa == NULL)
685 		return errno;
686 	memcpy(*sa, &s_un, slen);
687 
688 	return 0;
689 }
690 
691 static void
unix_cleanup(struct sockaddr * sa)692 unix_cleanup(struct sockaddr *sa)
693 {
694 	struct sockaddr_un *s_sun = (void *)sa;
695 
696 	/*
697 	 * cleanup only absolute paths.  see unix_parse() above
698 	 */
699 	if (*s_sun->sun_path == '/') {
700 		unlink(s_sun->sun_path);
701 	}
702 }
703 
704 /*ARGSUSED*/
705 static int
addrparse_notsupp(const char * addr __unused,struct sockaddr ** sa __unused,int allow_wildcard __unused)706 addrparse_notsupp(const char *addr __unused, struct sockaddr **sa __unused,
707 		  int allow_wildcard __unused)
708 {
709 
710 	fprintf(stderr, "rump_sp: support not yet implemented\n");
711 	return EOPNOTSUPP;
712 }
713 
714 static void
cleanup_success(struct sockaddr * sa __unused)715 cleanup_success(struct sockaddr *sa __unused)
716 {
717 }
718 
719 static int
connecthook_success(int s __unused)720 connecthook_success(int s __unused)
721 {
722 
723 	return 0;
724 }
725 
726 static struct {
727 	const char *id;
728 	int domain;
729 	socklen_t slen;
730 	addrparse_fn ap;
731 	connecthook_fn connhook;
732 	cleanup_fn cleanup;
733 } parsetab[] = {
734 	{ "tcp", PF_INET, sizeof(struct sockaddr_in),
735 	    tcp_parse, tcp_connecthook, cleanup_success },
736 	{ "unix", PF_LOCAL, sizeof(struct sockaddr_un),
737 	    unix_parse, connecthook_success, unix_cleanup },
738 	{ "tcp6", PF_INET6, sizeof(struct sockaddr_in6),
739 	    addrparse_notsupp, connecthook_success,
740 	    cleanup_success },
741 };
742 #define NPARSE (sizeof(parsetab)/sizeof(parsetab[0]))
743 
744 static int
parseurl(const char * url,struct sockaddr ** sap,unsigned * idxp,int allow_wildcard)745 parseurl(const char *url, struct sockaddr **sap, unsigned *idxp,
746 	int allow_wildcard)
747 {
748 	char id[16];
749 	const char *p, *p2;
750 	size_t l;
751 	unsigned i;
752 	int error;
753 
754 	/*
755 	 * Parse the url
756 	 */
757 
758 	p = url;
759 	p2 = strstr(p, "://");
760 	if (!p2) {
761 		fprintf(stderr, "rump_sp: invalid locator ``%s''\n", p);
762 		return EINVAL;
763 	}
764 	l = p2-p;
765 	if (l > sizeof(id)-1) {
766 		fprintf(stderr, "rump_sp: identifier too long in ``%s''\n", p);
767 		return EINVAL;
768 	}
769 
770 	strncpy(id, p, l);
771 	id[l] = '\0';
772 	p2 += 3; /* beginning of address */
773 
774 	for (i = 0; i < NPARSE; i++) {
775 		if (strcmp(id, parsetab[i].id) == 0) {
776 			error = parsetab[i].ap(p2, sap, allow_wildcard);
777 			if (error)
778 				return error;
779 			break;
780 		}
781 	}
782 	if (i == NPARSE) {
783 		fprintf(stderr, "rump_sp: invalid identifier ``%s''\n", p);
784 		return EINVAL;
785 	}
786 
787 	*idxp = i;
788 	return 0;
789 }
790