xref: /php-src/main/streams/xp_socket.c (revision ae5220ae)
1 /*
2   +----------------------------------------------------------------------+
3   | Copyright (c) The PHP Group                                          |
4   +----------------------------------------------------------------------+
5   | This source file is subject to version 3.01 of the PHP license,      |
6   | that is bundled with this package in the file LICENSE, and is        |
7   | available through the world-wide-web at the following url:           |
8   | https://www.php.net/license/3_01.txt                                 |
9   | If you did not receive a copy of the PHP license and are unable to   |
10   | obtain it through the world-wide-web, please send a note to          |
11   | license@php.net so we can mail you a copy immediately.               |
12   +----------------------------------------------------------------------+
13   | Author: Wez Furlong <wez@thebrainroom.com>                           |
14   +----------------------------------------------------------------------+
15 */
16 
17 #include "php.h"
18 #include "ext/standard/file.h"
19 #include "streams/php_streams_int.h"
20 #include "php_network.h"
21 
22 #if defined(PHP_WIN32) || defined(__riscos__)
23 # undef AF_UNIX
24 #endif
25 
26 #ifdef AF_UNIX
27 #include <sys/un.h>
28 #endif
29 
30 #ifndef MSG_DONTWAIT
31 # define MSG_DONTWAIT 0
32 #endif
33 
34 #ifndef MSG_PEEK
35 # define MSG_PEEK 0
36 #endif
37 
38 #ifdef PHP_WIN32
39 /* send/recv family on windows expects int */
40 # define XP_SOCK_BUF_SIZE(sz) (((sz) > INT_MAX) ? INT_MAX : (int)(sz))
41 #else
42 # define XP_SOCK_BUF_SIZE(sz) (sz)
43 #endif
44 
45 const php_stream_ops php_stream_generic_socket_ops;
46 PHPAPI const php_stream_ops php_stream_socket_ops;
47 const php_stream_ops php_stream_udp_socket_ops;
48 #ifdef AF_UNIX
49 const php_stream_ops php_stream_unix_socket_ops;
50 const php_stream_ops php_stream_unixdg_socket_ops;
51 #endif
52 
53 
54 static int php_tcp_sockop_set_option(php_stream *stream, int option, int value, void *ptrparam);
55 
56 /* {{{ Generic socket stream operations */
php_sockop_write(php_stream * stream,const char * buf,size_t count)57 static ssize_t php_sockop_write(php_stream *stream, const char *buf, size_t count)
58 {
59 	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
60 	ssize_t didwrite;
61 	struct timeval *ptimeout;
62 
63 	if (!sock || sock->socket == -1) {
64 		return 0;
65 	}
66 
67 	if (sock->timeout.tv_sec == -1)
68 		ptimeout = NULL;
69 	else
70 		ptimeout = &sock->timeout;
71 
72 retry:
73 	didwrite = send(sock->socket, buf, XP_SOCK_BUF_SIZE(count), (sock->is_blocked && ptimeout) ? MSG_DONTWAIT : 0);
74 
75 	if (didwrite <= 0) {
76 		char *estr;
77 		int err = php_socket_errno();
78 
79 		if (PHP_IS_TRANSIENT_ERROR(err)) {
80 			if (sock->is_blocked) {
81 				int retval;
82 
83 				sock->timeout_event = 0;
84 
85 				do {
86 					retval = php_pollfd_for(sock->socket, POLLOUT, ptimeout);
87 
88 					if (retval == 0) {
89 						sock->timeout_event = 1;
90 						break;
91 					}
92 
93 					if (retval > 0) {
94 						/* writable now; retry */
95 						goto retry;
96 					}
97 
98 					err = php_socket_errno();
99 				} while (err == EINTR);
100 			} else {
101 				/* EWOULDBLOCK/EAGAIN is not an error for a non-blocking stream.
102 				 * Report zero byte write instead. */
103 				return 0;
104 			}
105 		}
106 
107 		if (!(stream->flags & PHP_STREAM_FLAG_SUPPRESS_ERRORS)) {
108 			estr = php_socket_strerror(err, NULL, 0);
109 			php_error_docref(NULL, E_NOTICE,
110 				"Send of " ZEND_LONG_FMT " bytes failed with errno=%d %s",
111 				(zend_long)count, err, estr);
112 			efree(estr);
113 		}
114 	}
115 
116 	if (didwrite > 0) {
117 		php_stream_notify_progress_increment(PHP_STREAM_CONTEXT(stream), didwrite, 0);
118 	}
119 
120 	return didwrite;
121 }
122 
php_sock_stream_wait_for_data(php_stream * stream,php_netstream_data_t * sock,bool has_buffered_data)123 static void php_sock_stream_wait_for_data(php_stream *stream, php_netstream_data_t *sock, bool has_buffered_data)
124 {
125 	int retval;
126 	struct timeval *ptimeout, zero_timeout;
127 
128 	if (!sock || sock->socket == -1) {
129 		return;
130 	}
131 
132 	sock->timeout_event = 0;
133 
134 	if (has_buffered_data) {
135 		/* If there is already buffered data, use no timeout. */
136 		zero_timeout.tv_sec = 0;
137 		zero_timeout.tv_usec = 0;
138 		ptimeout = &zero_timeout;
139 	} else if (sock->timeout.tv_sec == -1) {
140 		ptimeout = NULL;
141 	} else {
142 		ptimeout = &sock->timeout;
143 	}
144 
145 	while(1) {
146 		retval = php_pollfd_for(sock->socket, PHP_POLLREADABLE, ptimeout);
147 
148 		if (retval == 0)
149 			sock->timeout_event = 1;
150 
151 		if (retval >= 0)
152 			break;
153 
154 		if (php_socket_errno() != EINTR)
155 			break;
156 	}
157 }
158 
php_sockop_read(php_stream * stream,char * buf,size_t count)159 static ssize_t php_sockop_read(php_stream *stream, char *buf, size_t count)
160 {
161 	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
162 
163 	if (!sock || sock->socket == -1) {
164 		return -1;
165 	}
166 
167 	int recv_flags = 0;
168 	/* Special handling for blocking read. */
169 	if (sock->is_blocked) {
170 		/* Find out if there is any data buffered from the previous read. */
171 		bool has_buffered_data = stream->has_buffered_data;
172 		/* No need to wait if there is any data buffered or no timeout. */
173 		bool dont_wait = has_buffered_data ||
174 				(sock->timeout.tv_sec == 0 && sock->timeout.tv_usec == 0);
175 		/* Set MSG_DONTWAIT if no wait is needed or there is unlimited timeout which was
176 		 * added by fix for #41984 committed in 9343c5404. */
177 		if (dont_wait || sock->timeout.tv_sec != -1) {
178 			recv_flags = MSG_DONTWAIT;
179 		}
180 		/* If the wait is needed or it is a platform without MSG_DONTWAIT support (e.g. Windows),
181 		 * then poll for data. */
182 		if (!dont_wait || MSG_DONTWAIT == 0) {
183 			php_sock_stream_wait_for_data(stream, sock, has_buffered_data);
184 			if (sock->timeout_event) {
185 				/* It is ok to timeout if there is any data buffered so return 0, otherwise -1. */
186 				return has_buffered_data ? 0 : -1;
187 			}
188 		}
189 	}
190 
191 	ssize_t nr_bytes = recv(sock->socket, buf, XP_SOCK_BUF_SIZE(count), recv_flags);
192 	int err = php_socket_errno();
193 
194 	if (nr_bytes < 0) {
195 		if (PHP_IS_TRANSIENT_ERROR(err)) {
196 			nr_bytes = 0;
197 		} else {
198 			stream->eof = 1;
199 		}
200 	} else if (nr_bytes == 0) {
201 		stream->eof = 1;
202 	}
203 
204 	if (nr_bytes > 0) {
205 		php_stream_notify_progress_increment(PHP_STREAM_CONTEXT(stream), nr_bytes, 0);
206 	}
207 
208 	return nr_bytes;
209 }
210 
211 
php_sockop_close(php_stream * stream,int close_handle)212 static int php_sockop_close(php_stream *stream, int close_handle)
213 {
214 	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
215 #ifdef PHP_WIN32
216 	int n;
217 #endif
218 
219 	if (!sock) {
220 		return 0;
221 	}
222 
223 	if (close_handle) {
224 
225 #ifdef PHP_WIN32
226 		if (sock->socket == -1)
227 			sock->socket = SOCK_ERR;
228 #endif
229 		if (sock->socket != SOCK_ERR) {
230 #ifdef PHP_WIN32
231 			/* prevent more data from coming in */
232 			shutdown(sock->socket, SHUT_RD);
233 
234 			/* try to make sure that the OS sends all data before we close the connection.
235 			 * Essentially, we are waiting for the socket to become writeable, which means
236 			 * that all pending data has been sent.
237 			 * We use a small timeout which should encourage the OS to send the data,
238 			 * but at the same time avoid hanging indefinitely.
239 			 * */
240 			do {
241 				n = php_pollfd_for_ms(sock->socket, POLLOUT, 500);
242 			} while (n == -1 && php_socket_errno() == EINTR);
243 #endif
244 			closesocket(sock->socket);
245 			sock->socket = SOCK_ERR;
246 		}
247 
248 	}
249 
250 	pefree(sock, php_stream_is_persistent(stream));
251 
252 	return 0;
253 }
254 
php_sockop_flush(php_stream * stream)255 static int php_sockop_flush(php_stream *stream)
256 {
257 #if 0
258 	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
259 	return fsync(sock->socket);
260 #endif
261 	return 0;
262 }
263 
php_sockop_stat(php_stream * stream,php_stream_statbuf * ssb)264 static int php_sockop_stat(php_stream *stream, php_stream_statbuf *ssb)
265 {
266 #ifdef ZEND_WIN32
267 	return 0;
268 #else
269 	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
270 
271 	return zend_fstat(sock->socket, &ssb->sb);
272 #endif
273 }
274 
sock_sendto(php_netstream_data_t * sock,const char * buf,size_t buflen,int flags,struct sockaddr * addr,socklen_t addrlen)275 static inline int sock_sendto(php_netstream_data_t *sock, const char *buf, size_t buflen, int flags,
276 		struct sockaddr *addr, socklen_t addrlen
277 		)
278 {
279 	int ret;
280 	if (addr) {
281 		ret = sendto(sock->socket, buf, XP_SOCK_BUF_SIZE(buflen), flags, addr, XP_SOCK_BUF_SIZE(addrlen));
282 
283 		return (ret == SOCK_CONN_ERR) ? -1 : ret;
284 	}
285 #ifdef PHP_WIN32
286 	return ((ret = send(sock->socket, buf, buflen > INT_MAX ? INT_MAX : (int)buflen, flags)) == SOCK_CONN_ERR) ? -1 : ret;
287 #else
288 	return ((ret = send(sock->socket, buf, buflen, flags)) == SOCK_CONN_ERR) ? -1 : ret;
289 #endif
290 }
291 
sock_recvfrom(php_netstream_data_t * sock,char * buf,size_t buflen,int flags,zend_string ** textaddr,struct sockaddr ** addr,socklen_t * addrlen)292 static inline int sock_recvfrom(php_netstream_data_t *sock, char *buf, size_t buflen, int flags,
293 		zend_string **textaddr,
294 		struct sockaddr **addr, socklen_t *addrlen
295 		)
296 {
297 	int ret;
298 	int want_addr = textaddr || addr;
299 
300 	if (want_addr) {
301 		php_sockaddr_storage sa;
302 		socklen_t sl = sizeof(sa);
303 		ret = recvfrom(sock->socket, buf, XP_SOCK_BUF_SIZE(buflen), flags, (struct sockaddr*)&sa, &sl);
304 		ret = (ret == SOCK_CONN_ERR) ? -1 : ret;
305 #ifdef PHP_WIN32
306 		/* POSIX discards excess bytes without signalling failure; emulate this on Windows */
307 		if (ret == -1 && WSAGetLastError() == WSAEMSGSIZE) {
308 			ret = buflen;
309 		}
310 #endif
311 		if (sl) {
312 			php_network_populate_name_from_sockaddr((struct sockaddr*)&sa, sl,
313 					textaddr, addr, addrlen);
314 		} else {
315 			if (textaddr) {
316 				*textaddr = ZSTR_EMPTY_ALLOC();
317 			}
318 			if (addr) {
319 				*addr = NULL;
320 				*addrlen = 0;
321 			}
322 		}
323 	} else {
324 		ret = recv(sock->socket, buf, XP_SOCK_BUF_SIZE(buflen), flags);
325 		ret = (ret == SOCK_CONN_ERR) ? -1 : ret;
326 	}
327 
328 	return ret;
329 }
330 
php_sockop_set_option(php_stream * stream,int option,int value,void * ptrparam)331 static int php_sockop_set_option(php_stream *stream, int option, int value, void *ptrparam)
332 {
333 	int oldmode, flags;
334 	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
335 	php_stream_xport_param *xparam;
336 
337 	if (!sock) {
338 		return PHP_STREAM_OPTION_RETURN_NOTIMPL;
339 	}
340 
341 	switch(option) {
342 		case PHP_STREAM_OPTION_CHECK_LIVENESS:
343 			{
344 				struct timeval tv;
345 				char buf;
346 				int alive = 1;
347 
348 				if (value == -1) {
349 					if (sock->timeout.tv_sec == -1) {
350 						tv.tv_sec = FG(default_socket_timeout);
351 						tv.tv_usec = 0;
352 					} else {
353 						tv = sock->timeout;
354 					}
355 				} else {
356 					tv.tv_sec = value;
357 					tv.tv_usec = 0;
358 				}
359 
360 				if (sock->socket == -1) {
361 					alive = 0;
362 				} else if (
363 					(
364 						value == 0 &&
365 						!(stream->flags & PHP_STREAM_FLAG_NO_IO) &&
366 						((MSG_DONTWAIT != 0) || !sock->is_blocked)
367 					) ||
368 					php_pollfd_for(sock->socket, PHP_POLLREADABLE|POLLPRI, &tv) > 0
369 				) {
370 					/* the poll() call was skipped if the socket is non-blocking (or MSG_DONTWAIT is available) and if the timeout is zero */
371 #ifdef PHP_WIN32
372 					int ret;
373 #else
374 					ssize_t ret;
375 #endif
376 
377 					ret = recv(sock->socket, &buf, sizeof(buf), MSG_PEEK|MSG_DONTWAIT);
378 					if (0 == ret) {
379 						/* the counterpart did properly shutdown */
380 						alive = 0;
381 					} else if (0 > ret) {
382 						int err = php_socket_errno();
383 						if (err != EWOULDBLOCK && err != EMSGSIZE && err != EAGAIN) {
384 							/* there was an unrecoverable error */
385 							alive = 0;
386 						}
387 					}
388 				}
389 				return alive ? PHP_STREAM_OPTION_RETURN_OK : PHP_STREAM_OPTION_RETURN_ERR;
390 			}
391 
392 		case PHP_STREAM_OPTION_BLOCKING:
393 			oldmode = sock->is_blocked;
394 			if (SUCCESS == php_set_sock_blocking(sock->socket, value)) {
395 				sock->is_blocked = value;
396 				return oldmode;
397 			}
398 			return PHP_STREAM_OPTION_RETURN_ERR;
399 
400 		case PHP_STREAM_OPTION_READ_TIMEOUT:
401 			sock->timeout = *(struct timeval*)ptrparam;
402 			sock->timeout_event = 0;
403 			return PHP_STREAM_OPTION_RETURN_OK;
404 
405 		case PHP_STREAM_OPTION_META_DATA_API:
406 			add_assoc_bool((zval *)ptrparam, "timed_out", sock->timeout_event);
407 			add_assoc_bool((zval *)ptrparam, "blocked", sock->is_blocked);
408 			add_assoc_bool((zval *)ptrparam, "eof", stream->eof);
409 			return PHP_STREAM_OPTION_RETURN_OK;
410 
411 		case PHP_STREAM_OPTION_XPORT_API:
412 			xparam = (php_stream_xport_param *)ptrparam;
413 
414 			switch (xparam->op) {
415 				case STREAM_XPORT_OP_LISTEN:
416 					xparam->outputs.returncode = (listen(sock->socket, xparam->inputs.backlog) == 0) ?  0: -1;
417 					return PHP_STREAM_OPTION_RETURN_OK;
418 
419 				case STREAM_XPORT_OP_GET_NAME:
420 					xparam->outputs.returncode = php_network_get_sock_name(sock->socket,
421 							xparam->want_textaddr ? &xparam->outputs.textaddr : NULL,
422 							xparam->want_addr ? &xparam->outputs.addr : NULL,
423 							xparam->want_addr ? &xparam->outputs.addrlen : NULL
424 							);
425 					return PHP_STREAM_OPTION_RETURN_OK;
426 
427 				case STREAM_XPORT_OP_GET_PEER_NAME:
428 					xparam->outputs.returncode = php_network_get_peer_name(sock->socket,
429 							xparam->want_textaddr ? &xparam->outputs.textaddr : NULL,
430 							xparam->want_addr ? &xparam->outputs.addr : NULL,
431 							xparam->want_addr ? &xparam->outputs.addrlen : NULL
432 							);
433 					return PHP_STREAM_OPTION_RETURN_OK;
434 
435 				case STREAM_XPORT_OP_SEND:
436 					flags = 0;
437 					if ((xparam->inputs.flags & STREAM_OOB) == STREAM_OOB) {
438 						flags |= MSG_OOB;
439 					}
440 					xparam->outputs.returncode = sock_sendto(sock,
441 							xparam->inputs.buf, xparam->inputs.buflen,
442 							flags,
443 							xparam->inputs.addr,
444 							xparam->inputs.addrlen);
445 					if (xparam->outputs.returncode == -1) {
446 						char *err = php_socket_strerror(php_socket_errno(), NULL, 0);
447 						php_error_docref(NULL, E_WARNING,
448 						   	"%s\n", err);
449 						efree(err);
450 					}
451 					return PHP_STREAM_OPTION_RETURN_OK;
452 
453 				case STREAM_XPORT_OP_RECV:
454 					flags = 0;
455 					if ((xparam->inputs.flags & STREAM_OOB) == STREAM_OOB) {
456 						flags |= MSG_OOB;
457 					}
458 					if ((xparam->inputs.flags & STREAM_PEEK) == STREAM_PEEK) {
459 						flags |= MSG_PEEK;
460 					}
461 					xparam->outputs.returncode = sock_recvfrom(sock,
462 							xparam->inputs.buf, xparam->inputs.buflen,
463 							flags,
464 							xparam->want_textaddr ? &xparam->outputs.textaddr : NULL,
465 							xparam->want_addr ? &xparam->outputs.addr : NULL,
466 							xparam->want_addr ? &xparam->outputs.addrlen : NULL
467 							);
468 					return PHP_STREAM_OPTION_RETURN_OK;
469 
470 
471 #ifdef HAVE_SHUTDOWN
472 # ifndef SHUT_RD
473 #  define SHUT_RD 0
474 # endif
475 # ifndef SHUT_WR
476 #  define SHUT_WR 1
477 # endif
478 # ifndef SHUT_RDWR
479 #  define SHUT_RDWR 2
480 # endif
481 				case STREAM_XPORT_OP_SHUTDOWN: {
482 					static const int shutdown_how[] = {SHUT_RD, SHUT_WR, SHUT_RDWR};
483 
484 					xparam->outputs.returncode = shutdown(sock->socket, shutdown_how[xparam->how]);
485 					return PHP_STREAM_OPTION_RETURN_OK;
486 				}
487 #endif
488 
489 				default:
490 					break;
491 			}
492 	}
493 
494 	return PHP_STREAM_OPTION_RETURN_NOTIMPL;
495 }
496 
php_sockop_cast(php_stream * stream,int castas,void ** ret)497 static int php_sockop_cast(php_stream *stream, int castas, void **ret)
498 {
499 	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
500 
501 	if (!sock) {
502 		return FAILURE;
503 	}
504 
505 	switch(castas)	{
506 		case PHP_STREAM_AS_STDIO:
507 			if (ret)	{
508 				*(FILE**)ret = fdopen(sock->socket, stream->mode);
509 				if (*ret)
510 					return SUCCESS;
511 				return FAILURE;
512 			}
513 			return SUCCESS;
514 		case PHP_STREAM_AS_FD_FOR_SELECT:
515 		case PHP_STREAM_AS_FD:
516 		case PHP_STREAM_AS_SOCKETD:
517 			if (ret)
518 				*(php_socket_t *)ret = sock->socket;
519 			return SUCCESS;
520 		default:
521 			return FAILURE;
522 	}
523 }
524 /* }}} */
525 
526 /* These may look identical, but we need them this way so that
527  * we can determine which type of socket we are dealing with
528  * by inspecting stream->ops.
529  * A "useful" side-effect is that the user's scripts can then
530  * make similar decisions using stream_get_meta_data.
531  * */
532 const php_stream_ops php_stream_generic_socket_ops = {
533 	php_sockop_write, php_sockop_read,
534 	php_sockop_close, php_sockop_flush,
535 	"generic_socket",
536 	NULL, /* seek */
537 	php_sockop_cast,
538 	php_sockop_stat,
539 	php_sockop_set_option,
540 };
541 
542 
543 const php_stream_ops php_stream_socket_ops = {
544 	php_sockop_write, php_sockop_read,
545 	php_sockop_close, php_sockop_flush,
546 	"tcp_socket",
547 	NULL, /* seek */
548 	php_sockop_cast,
549 	php_sockop_stat,
550 	php_tcp_sockop_set_option,
551 };
552 
553 const php_stream_ops php_stream_udp_socket_ops = {
554 	php_sockop_write, php_sockop_read,
555 	php_sockop_close, php_sockop_flush,
556 	"udp_socket",
557 	NULL, /* seek */
558 	php_sockop_cast,
559 	php_sockop_stat,
560 	php_tcp_sockop_set_option,
561 };
562 
563 #ifdef AF_UNIX
564 const php_stream_ops php_stream_unix_socket_ops = {
565 	php_sockop_write, php_sockop_read,
566 	php_sockop_close, php_sockop_flush,
567 	"unix_socket",
568 	NULL, /* seek */
569 	php_sockop_cast,
570 	php_sockop_stat,
571 	php_tcp_sockop_set_option,
572 };
573 const php_stream_ops php_stream_unixdg_socket_ops = {
574 	php_sockop_write, php_sockop_read,
575 	php_sockop_close, php_sockop_flush,
576 	"udg_socket",
577 	NULL, /* seek */
578 	php_sockop_cast,
579 	php_sockop_stat,
580 	php_tcp_sockop_set_option,
581 };
582 #endif
583 
584 
585 /* network socket operations */
586 
587 #ifdef AF_UNIX
parse_unix_address(php_stream_xport_param * xparam,struct sockaddr_un * unix_addr)588 static inline int parse_unix_address(php_stream_xport_param *xparam, struct sockaddr_un *unix_addr)
589 {
590 	memset(unix_addr, 0, sizeof(*unix_addr));
591 	unix_addr->sun_family = AF_UNIX;
592 
593 	/* we need to be binary safe on systems that support an abstract
594 	 * namespace */
595 	if (xparam->inputs.namelen >= sizeof(unix_addr->sun_path)) {
596 		/* On linux, when the path begins with a NUL byte we are
597 		 * referring to an abstract namespace.  In theory we should
598 		 * allow an extra byte below, since we don't need the NULL.
599 		 * BUT, to get into this branch of code, the name is too long,
600 		 * so we don't care. */
601 		xparam->inputs.namelen = sizeof(unix_addr->sun_path) - 1;
602 		php_error_docref(NULL, E_NOTICE,
603 			"socket path exceeded the maximum allowed length of %lu bytes "
604 			"and was truncated", (unsigned long)sizeof(unix_addr->sun_path));
605 	}
606 
607 	memcpy(unix_addr->sun_path, xparam->inputs.name, xparam->inputs.namelen);
608 
609 	return 1;
610 }
611 #endif
612 
parse_ip_address_ex(const char * str,size_t str_len,int * portno,int get_err,zend_string ** err)613 static inline char *parse_ip_address_ex(const char *str, size_t str_len, int *portno, int get_err, zend_string **err)
614 {
615 	char *colon;
616 	char *host = NULL;
617 
618 #ifdef HAVE_IPV6
619 	char *p;
620 
621 	if (*(str) == '[' && str_len > 1) {
622 		/* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */
623 		p = memchr(str + 1, ']', str_len - 2);
624 		if (!p || *(p + 1) != ':') {
625 			if (get_err) {
626 				*err = strpprintf(0, "Failed to parse IPv6 address \"%s\"", str);
627 			}
628 			return NULL;
629 		}
630 		*portno = atoi(p + 2);
631 		return estrndup(str + 1, p - str - 1);
632 	}
633 #endif
634 	if (str_len) {
635 		colon = memchr(str, ':', str_len - 1);
636 	} else {
637 		colon = NULL;
638 	}
639 	if (colon) {
640 		*portno = atoi(colon + 1);
641 		host = estrndup(str, colon - str);
642 	} else {
643 		if (get_err) {
644 			*err = strpprintf(0, "Failed to parse address \"%s\"", str);
645 		}
646 		return NULL;
647 	}
648 
649 	return host;
650 }
651 
parse_ip_address(php_stream_xport_param * xparam,int * portno)652 static inline char *parse_ip_address(php_stream_xport_param *xparam, int *portno)
653 {
654 	return parse_ip_address_ex(xparam->inputs.name, xparam->inputs.namelen, portno, xparam->want_errortext, &xparam->outputs.error_text);
655 }
656 
php_tcp_sockop_bind(php_stream * stream,php_netstream_data_t * sock,php_stream_xport_param * xparam)657 static inline int php_tcp_sockop_bind(php_stream *stream, php_netstream_data_t *sock,
658 		php_stream_xport_param *xparam)
659 {
660 	char *host = NULL;
661 	int portno, err;
662 	long sockopts = STREAM_SOCKOP_NONE;
663 	zval *tmpzval = NULL;
664 
665 #ifdef AF_UNIX
666 	if (stream->ops == &php_stream_unix_socket_ops || stream->ops == &php_stream_unixdg_socket_ops) {
667 		struct sockaddr_un unix_addr;
668 
669 		sock->socket = socket(PF_UNIX, stream->ops == &php_stream_unix_socket_ops ? SOCK_STREAM : SOCK_DGRAM, 0);
670 
671 		if (sock->socket == SOCK_ERR) {
672 			if (xparam->want_errortext) {
673 				xparam->outputs.error_text = strpprintf(0, "Failed to create unix%s socket %s",
674 						stream->ops == &php_stream_unix_socket_ops ? "" : "datagram",
675 						strerror(errno));
676 			}
677 			return -1;
678 		}
679 
680 		parse_unix_address(xparam, &unix_addr);
681 
682 		return bind(sock->socket, (const struct sockaddr *)&unix_addr,
683 			(socklen_t) XtOffsetOf(struct sockaddr_un, sun_path) + xparam->inputs.namelen);
684 	}
685 #endif
686 
687 	host = parse_ip_address(xparam, &portno);
688 
689 	if (host == NULL) {
690 		return -1;
691 	}
692 
693 #ifdef IPV6_V6ONLY
694 	if (PHP_STREAM_CONTEXT(stream)
695 		&& (tmpzval = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "socket", "ipv6_v6only")) != NULL
696 		&& Z_TYPE_P(tmpzval) != IS_NULL
697 	) {
698 		sockopts |= STREAM_SOCKOP_IPV6_V6ONLY;
699 		sockopts |= STREAM_SOCKOP_IPV6_V6ONLY_ENABLED * zend_is_true(tmpzval);
700 	}
701 #endif
702 
703 #ifdef SO_REUSEPORT
704 	if (PHP_STREAM_CONTEXT(stream)
705 		&& (tmpzval = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "socket", "so_reuseport")) != NULL
706 		&& zend_is_true(tmpzval)
707 	) {
708 		sockopts |= STREAM_SOCKOP_SO_REUSEPORT;
709 	}
710 #endif
711 
712 #ifdef SO_BROADCAST
713 	if (stream->ops == &php_stream_udp_socket_ops /* SO_BROADCAST is only applicable for UDP */
714 		&& PHP_STREAM_CONTEXT(stream)
715 		&& (tmpzval = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "socket", "so_broadcast")) != NULL
716 		&& zend_is_true(tmpzval)
717 	) {
718 		sockopts |= STREAM_SOCKOP_SO_BROADCAST;
719 	}
720 #endif
721 
722 	sock->socket = php_network_bind_socket_to_local_addr(host, portno,
723 			stream->ops == &php_stream_udp_socket_ops ? SOCK_DGRAM : SOCK_STREAM,
724 			sockopts,
725 			xparam->want_errortext ? &xparam->outputs.error_text : NULL,
726 			&err
727 			);
728 
729 	if (host) {
730 		efree(host);
731 	}
732 
733 	return sock->socket == -1 ? -1 : 0;
734 }
735 
php_tcp_sockop_connect(php_stream * stream,php_netstream_data_t * sock,php_stream_xport_param * xparam)736 static inline int php_tcp_sockop_connect(php_stream *stream, php_netstream_data_t *sock,
737 		php_stream_xport_param *xparam)
738 {
739 	char *host = NULL, *bindto = NULL;
740 	int portno, bindport = 0;
741 	int err = 0;
742 	int ret;
743 	zval *tmpzval = NULL;
744 	long sockopts = STREAM_SOCKOP_NONE;
745 
746 #ifdef AF_UNIX
747 	if (stream->ops == &php_stream_unix_socket_ops || stream->ops == &php_stream_unixdg_socket_ops) {
748 		struct sockaddr_un unix_addr;
749 
750 		sock->socket = socket(PF_UNIX, stream->ops == &php_stream_unix_socket_ops ? SOCK_STREAM : SOCK_DGRAM, 0);
751 
752 		if (sock->socket == SOCK_ERR) {
753 			if (xparam->want_errortext) {
754 				xparam->outputs.error_text = strpprintf(0, "Failed to create unix socket");
755 			}
756 			return -1;
757 		}
758 
759 		parse_unix_address(xparam, &unix_addr);
760 
761 		ret = php_network_connect_socket(sock->socket,
762 				(const struct sockaddr *)&unix_addr, (socklen_t) XtOffsetOf(struct sockaddr_un, sun_path) + xparam->inputs.namelen,
763 				xparam->op == STREAM_XPORT_OP_CONNECT_ASYNC, xparam->inputs.timeout,
764 				xparam->want_errortext ? &xparam->outputs.error_text : NULL,
765 				&err);
766 
767 		xparam->outputs.error_code = err;
768 
769 		goto out;
770 	}
771 #endif
772 
773 	host = parse_ip_address(xparam, &portno);
774 
775 	if (host == NULL) {
776 		return -1;
777 	}
778 
779 	if (PHP_STREAM_CONTEXT(stream) && (tmpzval = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "socket", "bindto")) != NULL) {
780 		if (Z_TYPE_P(tmpzval) != IS_STRING) {
781 			if (xparam->want_errortext) {
782 				xparam->outputs.error_text = strpprintf(0, "local_addr context option is not a string.");
783 			}
784 			efree(host);
785 			return -1;
786 		}
787 		bindto = parse_ip_address_ex(Z_STRVAL_P(tmpzval), Z_STRLEN_P(tmpzval), &bindport, xparam->want_errortext, &xparam->outputs.error_text);
788 	}
789 
790 #ifdef SO_BROADCAST
791 	if (stream->ops == &php_stream_udp_socket_ops /* SO_BROADCAST is only applicable for UDP */
792 		&& PHP_STREAM_CONTEXT(stream)
793 		&& (tmpzval = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "socket", "so_broadcast")) != NULL
794 		&& zend_is_true(tmpzval)
795 	) {
796 		sockopts |= STREAM_SOCKOP_SO_BROADCAST;
797 	}
798 #endif
799 
800 	if (stream->ops != &php_stream_udp_socket_ops /* TCP_NODELAY is only applicable for TCP */
801 #ifdef AF_UNIX
802 		&& stream->ops != &php_stream_unix_socket_ops
803 		&& stream->ops != &php_stream_unixdg_socket_ops
804 #endif
805 		&& PHP_STREAM_CONTEXT(stream)
806 		&& (tmpzval = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "socket", "tcp_nodelay")) != NULL
807 		&& zend_is_true(tmpzval)
808 	) {
809 		sockopts |= STREAM_SOCKOP_TCP_NODELAY;
810 	}
811 
812 	/* Note: the test here for php_stream_udp_socket_ops is important, because we
813 	 * want the default to be TCP sockets so that the openssl extension can
814 	 * re-use this code. */
815 
816 	sock->socket = php_network_connect_socket_to_host(host, portno,
817 			stream->ops == &php_stream_udp_socket_ops ? SOCK_DGRAM : SOCK_STREAM,
818 			xparam->op == STREAM_XPORT_OP_CONNECT_ASYNC,
819 			xparam->inputs.timeout,
820 			xparam->want_errortext ? &xparam->outputs.error_text : NULL,
821 			&err,
822 			bindto,
823 			bindport,
824 			sockopts
825 			);
826 
827 	ret = sock->socket == -1 ? -1 : 0;
828 	xparam->outputs.error_code = err;
829 
830 	if (host) {
831 		efree(host);
832 	}
833 	if (bindto) {
834 		efree(bindto);
835 	}
836 
837 #ifdef AF_UNIX
838 out:
839 #endif
840 
841 	if (ret >= 0 && xparam->op == STREAM_XPORT_OP_CONNECT_ASYNC && err == EINPROGRESS) {
842 		/* indicates pending connection */
843 		return 1;
844 	}
845 
846 	return ret;
847 }
848 
php_tcp_sockop_accept(php_stream * stream,php_netstream_data_t * sock,php_stream_xport_param * xparam STREAMS_DC)849 static inline int php_tcp_sockop_accept(php_stream *stream, php_netstream_data_t *sock,
850 		php_stream_xport_param *xparam STREAMS_DC)
851 {
852 	int clisock;
853 	bool nodelay = 0;
854 	zval *tmpzval = NULL;
855 
856 	xparam->outputs.client = NULL;
857 
858 	if ((NULL != PHP_STREAM_CONTEXT(stream)) &&
859 		(tmpzval = php_stream_context_get_option(PHP_STREAM_CONTEXT(stream), "socket", "tcp_nodelay")) != NULL &&
860 		zend_is_true(tmpzval)) {
861 		nodelay = 1;
862 	}
863 
864 	clisock = php_network_accept_incoming(sock->socket,
865 		xparam->want_textaddr ? &xparam->outputs.textaddr : NULL,
866 		xparam->want_addr ? &xparam->outputs.addr : NULL,
867 		xparam->want_addr ? &xparam->outputs.addrlen : NULL,
868 		xparam->inputs.timeout,
869 		xparam->want_errortext ? &xparam->outputs.error_text : NULL,
870 		&xparam->outputs.error_code,
871 		nodelay);
872 
873 	if (clisock >= 0) {
874 		php_netstream_data_t *clisockdata = (php_netstream_data_t*) emalloc(sizeof(*clisockdata));
875 
876 		memcpy(clisockdata, sock, sizeof(*clisockdata));
877 		clisockdata->socket = clisock;
878 #ifdef __linux__
879 		/* O_NONBLOCK is not inherited on Linux */
880 		clisockdata->is_blocked = 1;
881 #endif
882 
883 		xparam->outputs.client = php_stream_alloc_rel(stream->ops, clisockdata, NULL, "r+");
884 		if (xparam->outputs.client) {
885 			xparam->outputs.client->ctx = stream->ctx;
886 			if (stream->ctx) {
887 				GC_ADDREF(stream->ctx);
888 			}
889 		}
890 	}
891 
892 	return xparam->outputs.client == NULL ? -1 : 0;
893 }
894 
php_tcp_sockop_set_option(php_stream * stream,int option,int value,void * ptrparam)895 static int php_tcp_sockop_set_option(php_stream *stream, int option, int value, void *ptrparam)
896 {
897 	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
898 	php_stream_xport_param *xparam;
899 
900 	switch(option) {
901 		case PHP_STREAM_OPTION_XPORT_API:
902 			xparam = (php_stream_xport_param *)ptrparam;
903 
904 			switch(xparam->op) {
905 				case STREAM_XPORT_OP_CONNECT:
906 				case STREAM_XPORT_OP_CONNECT_ASYNC:
907 					xparam->outputs.returncode = php_tcp_sockop_connect(stream, sock, xparam);
908 					return PHP_STREAM_OPTION_RETURN_OK;
909 
910 				case STREAM_XPORT_OP_BIND:
911 					xparam->outputs.returncode = php_tcp_sockop_bind(stream, sock, xparam);
912 					return PHP_STREAM_OPTION_RETURN_OK;
913 
914 
915 				case STREAM_XPORT_OP_ACCEPT:
916 					xparam->outputs.returncode = php_tcp_sockop_accept(stream, sock, xparam STREAMS_CC);
917 					return PHP_STREAM_OPTION_RETURN_OK;
918 				default:
919 					/* fall through */
920 					;
921 			}
922 	}
923 	return php_sockop_set_option(stream, option, value, ptrparam);
924 }
925 
926 
php_stream_generic_socket_factory(const char * proto,size_t protolen,const char * resourcename,size_t resourcenamelen,const char * persistent_id,int options,int flags,struct timeval * timeout,php_stream_context * context STREAMS_DC)927 PHPAPI php_stream *php_stream_generic_socket_factory(const char *proto, size_t protolen,
928 		const char *resourcename, size_t resourcenamelen,
929 		const char *persistent_id, int options, int flags,
930 		struct timeval *timeout,
931 		php_stream_context *context STREAMS_DC)
932 {
933 	php_stream *stream = NULL;
934 	php_netstream_data_t *sock;
935 	const php_stream_ops *ops;
936 
937 	/* which type of socket ? */
938 	if (strncmp(proto, "tcp", protolen) == 0) {
939 		ops = &php_stream_socket_ops;
940 	} else if (strncmp(proto, "udp", protolen) == 0) {
941 		ops = &php_stream_udp_socket_ops;
942 	}
943 #ifdef AF_UNIX
944 	else if (strncmp(proto, "unix", protolen) == 0) {
945 		ops = &php_stream_unix_socket_ops;
946 	} else if (strncmp(proto, "udg", protolen) == 0) {
947 		ops = &php_stream_unixdg_socket_ops;
948 	}
949 #endif
950 	else {
951 		/* should never happen */
952 		return NULL;
953 	}
954 
955 	sock = pemalloc(sizeof(php_netstream_data_t), persistent_id ? 1 : 0);
956 	memset(sock, 0, sizeof(php_netstream_data_t));
957 
958 	sock->is_blocked = 1;
959 	sock->timeout.tv_sec = FG(default_socket_timeout);
960 	sock->timeout.tv_usec = 0;
961 
962 	/* we don't know the socket until we have determined if we are binding or
963 	 * connecting */
964 	sock->socket = -1;
965 
966 	stream = php_stream_alloc_rel(ops, sock, persistent_id, "r+");
967 
968 	if (stream == NULL)	{
969 		pefree(sock, persistent_id ? 1 : 0);
970 		return NULL;
971 	}
972 
973 	return stream;
974 }
975