summaryrefslogtreecommitdiff
path: root/main/network.c
blob: 2c504952b2dd1064dbcee47d8379b52138521f9f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
/*
   +----------------------------------------------------------------------+
   | Copyright (c) The PHP Group                                          |
   +----------------------------------------------------------------------+
   | This source file is subject to version 3.01 of the PHP license,      |
   | that is bundled with this package in the file LICENSE, and is        |
   | available through the world-wide-web at the following url:           |
   | http://www.php.net/license/3_01.txt                                  |
   | If you did not receive a copy of the PHP license and are unable to   |
   | obtain it through the world-wide-web, please send a note to          |
   | license@php.net so we can mail you a copy immediately.               |
   +----------------------------------------------------------------------+
   | Author: Stig Venaas <venaas@uninett.no>                              |
   | Streams work by Wez Furlong <wez@thebrainroom.com>                   |
   +----------------------------------------------------------------------+
 */

/*#define DEBUG_MAIN_NETWORK 1*/

#include "php.h"

#include <stddef.h>
#include <errno.h>


#ifdef PHP_WIN32
# include <Ws2tcpip.h>
# include "win32/inet.h"
# include "win32/winutil.h"
# define O_RDONLY _O_RDONLY
# include "win32/param.h"
#else
#include <sys/param.h>
#endif

#include <sys/types.h>
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif

#ifndef _FCNTL_H
#include <fcntl.h>
#endif

#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#if HAVE_POLL_H
#include <poll.h>
#elif HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif


#ifndef PHP_WIN32
#include <netinet/in.h>
#include <netdb.h>
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#endif

#ifndef HAVE_INET_ATON
int inet_aton(const char *, struct in_addr *);
#endif

#include "php_network.h"

#if defined(PHP_WIN32) || defined(__riscos__)
#undef AF_UNIX
#endif

#if defined(AF_UNIX)
#include <sys/un.h>
#endif

#include "ext/standard/file.h"

#ifdef PHP_WIN32
# include "win32/time.h"
# define SOCK_ERR INVALID_SOCKET
# define SOCK_CONN_ERR SOCKET_ERROR
# define PHP_TIMEOUT_ERROR_VALUE		WSAETIMEDOUT

#if HAVE_IPV6
const struct in6_addr in6addr_any = {0}; /* IN6ADDR_ANY_INIT; */
#endif

#else
# define SOCK_ERR -1
# define SOCK_CONN_ERR -1
# define PHP_TIMEOUT_ERROR_VALUE		ETIMEDOUT
#endif

#if HAVE_GETADDRINFO
#ifdef HAVE_GAI_STRERROR
#  define PHP_GAI_STRERROR(x) (gai_strerror(x))
#else
#  define PHP_GAI_STRERROR(x) (php_gai_strerror(x))
/* {{{ php_gai_strerror */
static const char *php_gai_strerror(int code)
{
        static struct {
                int code;
                const char *msg;
        } values[] = {
#  ifdef EAI_ADDRFAMILY
                {EAI_ADDRFAMILY, "Address family for hostname not supported"},
#  endif
                {EAI_AGAIN, "Temporary failure in name resolution"},
                {EAI_BADFLAGS, "Bad value for ai_flags"},
                {EAI_FAIL, "Non-recoverable failure in name resolution"},
                {EAI_FAMILY, "ai_family not supported"},
                {EAI_MEMORY, "Memory allocation failure"},
#  ifdef EAI_NODATA
                {EAI_NODATA, "No address associated with hostname"},
#  endif
                {EAI_NONAME, "Name or service not known"},
                {EAI_SERVICE, "Servname not supported for ai_socktype"},
                {EAI_SOCKTYPE, "ai_socktype not supported"},
                {EAI_SYSTEM, "System error"},
                {0, NULL}
        };
        int i;

        for (i = 0; values[i].msg != NULL; i++) {
                if (values[i].code == code) {
                        return (char *)values[i].msg;
                }
        }

        return "Unknown error";
}
/* }}} */
#endif
#endif

/* {{{ php_network_freeaddresses */
PHPAPI void php_network_freeaddresses(struct sockaddr **sal)
{
	struct sockaddr **sap;

	if (sal == NULL)
		return;
	for (sap = sal; *sap != NULL; sap++)
		efree(*sap);
	efree(sal);
}
/* }}} */

/* {{{ php_network_getaddresses
 * Returns number of addresses, 0 for none/error
 */
PHPAPI int php_network_getaddresses(const char *host, int socktype, struct sockaddr ***sal, zend_string **error_string)
{
	struct sockaddr **sap;
	int n;
#if HAVE_GETADDRINFO
# if HAVE_IPV6
	static int ipv6_borked = -1; /* the way this is used *is* thread safe */
# endif
	struct addrinfo hints, *res, *sai;
#else
	struct hostent *host_info;
	struct in_addr in;
#endif

	if (host == NULL) {
		return 0;
	}
#if HAVE_GETADDRINFO
	memset(&hints, '\0', sizeof(hints));

	hints.ai_family = AF_INET; /* default to regular inet (see below) */
	hints.ai_socktype = socktype;

# if HAVE_IPV6
	/* probe for a working IPv6 stack; even if detected as having v6 at compile
	 * time, at runtime some stacks are slow to resolve or have other issues
	 * if they are not correctly configured.
	 * static variable use is safe here since simple store or fetch operations
	 * are atomic and because the actual probe process is not in danger of
	 * collisions or race conditions. */
	if (ipv6_borked == -1) {
		int s;

		s = socket(PF_INET6, SOCK_DGRAM, 0);
		if (s == SOCK_ERR) {
			ipv6_borked = 1;
		} else {
			ipv6_borked = 0;
			closesocket(s);
		}
	}
	hints.ai_family = ipv6_borked ? AF_INET : AF_UNSPEC;
# endif

	if ((n = getaddrinfo(host, NULL, &hints, &res))) {
		if (error_string) {
			/* free error string received during previous iteration (if any) */
			if (*error_string) {
				zend_string_release_ex(*error_string, 0);
			}
			*error_string = strpprintf(0, "php_network_getaddresses: getaddrinfo failed: %s", PHP_GAI_STRERROR(n));
			php_error_docref(NULL, E_WARNING, "%s", ZSTR_VAL(*error_string));
		} else {
			php_error_docref(NULL, E_WARNING, "php_network_getaddresses: getaddrinfo failed: %s", PHP_GAI_STRERROR(n));
		}
		return 0;
	} else if (res == NULL) {
		if (error_string) {
			/* free error string received during previous iteration (if any) */
			if (*error_string) {
				zend_string_release_ex(*error_string, 0);
			}
			*error_string = strpprintf(0, "php_network_getaddresses: getaddrinfo failed (null result pointer) errno=%d", errno);
			php_error_docref(NULL, E_WARNING, "%s", ZSTR_VAL(*error_string));
		} else {
			php_error_docref(NULL, E_WARNING, "php_network_getaddresses: getaddrinfo failed (null result pointer)");
		}
		return 0;
	}

	sai = res;
	for (n = 1; (sai = sai->ai_next) != NULL; n++)
		;

	*sal = safe_emalloc((n + 1), sizeof(*sal), 0);
	sai = res;
	sap = *sal;

	do {
		*sap = emalloc(sai->ai_addrlen);
		memcpy(*sap, sai->ai_addr, sai->ai_addrlen);
		sap++;
	} while ((sai = sai->ai_next) != NULL);

	freeaddrinfo(res);
#else
	if (!inet_aton(host, &in)) {
		if(strlen(host) > MAXFQDNLEN) {
			host_info = NULL;
			errno = E2BIG;
		} else {
			host_info = php_network_gethostbyname(host);
		}
		if (host_info == NULL) {
			if (error_string) {
				/* free error string received during previous iteration (if any) */
				if (*error_string) {
					zend_string_release_ex(*error_string, 0);
				}
				*error_string = strpprintf(0, "php_network_getaddresses: gethostbyname failed. errno=%d", errno);
				php_error_docref(NULL, E_WARNING, "%s", ZSTR_VAL(*error_string));
			} else {
				php_error_docref(NULL, E_WARNING, "php_network_getaddresses: gethostbyname failed");
			}
			return 0;
		}
		in = *((struct in_addr *) host_info->h_addr);
	}

	*sal = safe_emalloc(2, sizeof(*sal), 0);
	sap = *sal;
	*sap = emalloc(sizeof(struct sockaddr_in));
	(*sap)->sa_family = AF_INET;
	((struct sockaddr_in *)*sap)->sin_addr = in;
	sap++;
	n = 1;
#endif

	*sap = NULL;
	return n;
}
/* }}} */

#ifndef O_NONBLOCK
#define O_NONBLOCK O_NDELAY
#endif

#ifdef PHP_WIN32
typedef u_long php_non_blocking_flags_t;
#  define SET_SOCKET_BLOCKING_MODE(sock, save) \
     save = TRUE; ioctlsocket(sock, FIONBIO, &save)
#  define RESTORE_SOCKET_BLOCKING_MODE(sock, save) \
	 ioctlsocket(sock, FIONBIO, &save)
#else
typedef int php_non_blocking_flags_t;
#  define SET_SOCKET_BLOCKING_MODE(sock, save) \
	 save = fcntl(sock, F_GETFL, 0); \
	 fcntl(sock, F_SETFL, save | O_NONBLOCK)
#  define RESTORE_SOCKET_BLOCKING_MODE(sock, save) \
	 fcntl(sock, F_SETFL, save)
#endif

/* Connect to a socket using an interruptible connect with optional timeout.
 * Optionally, the connect can be made asynchronously, which will implicitly
 * enable non-blocking mode on the socket.
 * */
/* {{{ php_network_connect_socket */
PHPAPI int php_network_connect_socket(php_socket_t sockfd,
		const struct sockaddr *addr,
		socklen_t addrlen,
		int asynchronous,
		struct timeval *timeout,
		zend_string **error_string,
		int *error_code)
{
	php_non_blocking_flags_t orig_flags;
	int n;
	int error = 0;
	socklen_t len;
	int ret = 0;

	SET_SOCKET_BLOCKING_MODE(sockfd, orig_flags);

	if ((n = connect(sockfd, addr, addrlen)) != 0) {
		error = php_socket_errno();

		if (error_code) {
			*error_code = error;
		}

		if (error != EINPROGRESS) {
			if (error_string) {
				*error_string = php_socket_error_str(error);
			}

			return -1;
		}
		if (asynchronous && error == EINPROGRESS) {
			/* this is fine by us */
			return 0;
		}
	}

	if (n == 0) {
		goto ok;
	}
# ifdef PHP_WIN32
	/* The documentation for connect() says in case of non-blocking connections
	 * the select function reports success in the writefds set and failure in
	 * the exceptfds set. Indeed, using PHP_POLLREADABLE results in select
	 * failing only due to the timeout and not immediately as would be
	 * expected when a connection is actively refused. This way,
	 * php_pollfd_for will return a mask with POLLOUT if the connection
	 * is successful and with POLLPRI otherwise. */
	if ((n = php_pollfd_for(sockfd, POLLOUT|POLLPRI, timeout)) == 0) {
#else
	if ((n = php_pollfd_for(sockfd, PHP_POLLREADABLE|POLLOUT, timeout)) == 0) {
#endif
		error = PHP_TIMEOUT_ERROR_VALUE;
	}

	if (n > 0) {
		len = sizeof(error);
		/*
		   BSD-derived systems set errno correctly
		   Solaris returns -1 from getsockopt in case of error
		   */
		if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (char*)&error, &len) != 0) {
			ret = -1;
		}
	} else {
		/* whoops: sockfd has disappeared */
		ret = -1;
	}

ok:
	if (!asynchronous) {
		/* back to blocking mode */
		RESTORE_SOCKET_BLOCKING_MODE(sockfd, orig_flags);
	}

	if (error_code) {
		*error_code = error;
	}

	if (error) {
		ret = -1;
		if (error_string) {
			*error_string = php_socket_error_str(error);
		}
	}
	return ret;
}
/* }}} */

/* {{{ sub_times */
static inline void sub_times(struct timeval a, struct timeval b, struct timeval *result)
{
	result->tv_usec = a.tv_usec - b.tv_usec;
	if (result->tv_usec < 0L) {
		a.tv_sec--;
		result->tv_usec += 1000000L;
	}
	result->tv_sec = a.tv_sec - b.tv_sec;
	if (result->tv_sec < 0L) {
		result->tv_sec++;
		result->tv_usec -= 1000000L;
	}
}
/* }}} */

/* Bind to a local IP address.
 * Returns the bound socket, or -1 on failure.
 * */
/* {{{ php_network_bind_socket_to_local_addr */
php_socket_t php_network_bind_socket_to_local_addr(const char *host, unsigned port,
		int socktype, long sockopts, zend_string **error_string, int *error_code
		)
{
	int num_addrs, n, err = 0;
	php_socket_t sock;
	struct sockaddr **sal, **psal, *sa;
	socklen_t socklen;
	int sockoptval = 1;

	num_addrs = php_network_getaddresses(host, socktype, &psal, error_string);

	if (num_addrs == 0) {
		/* could not resolve address(es) */
		return -1;
	}

	for (sal = psal; *sal != NULL; sal++) {
		sa = *sal;

		/* create a socket for this address */
		sock = socket(sa->sa_family, socktype, 0);

		if (sock == SOCK_ERR) {
			continue;
		}

		switch (sa->sa_family) {
#if HAVE_GETADDRINFO && HAVE_IPV6
			case AF_INET6:
				((struct sockaddr_in6 *)sa)->sin6_family = sa->sa_family;
				((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
				socklen = sizeof(struct sockaddr_in6);
				break;
#endif
			case AF_INET:
				((struct sockaddr_in *)sa)->sin_family = sa->sa_family;
				((struct sockaddr_in *)sa)->sin_port = htons(port);
				socklen = sizeof(struct sockaddr_in);
				break;
			default:
				/* Unknown family */
				socklen = 0;
				sa = NULL;
		}

		if (sa) {
			/* attempt to bind */

#ifdef SO_REUSEADDR
			setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&sockoptval, sizeof(sockoptval));
#endif
#ifdef IPV6_V6ONLY
			if (sockopts & STREAM_SOCKOP_IPV6_V6ONLY) {
				int ipv6_val = !!(sockopts & STREAM_SOCKOP_IPV6_V6ONLY_ENABLED);
				setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6_val, sizeof(sockoptval));
			}
#endif
#ifdef SO_REUSEPORT
			if (sockopts & STREAM_SOCKOP_SO_REUSEPORT) {
				setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (char*)&sockoptval, sizeof(sockoptval));
			}
#endif
#ifdef SO_BROADCAST
			if (sockopts & STREAM_SOCKOP_SO_BROADCAST) {
				setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char*)&sockoptval, sizeof(sockoptval));
			}
#endif
#ifdef TCP_NODELAY
			if (sockopts & STREAM_SOCKOP_TCP_NODELAY) {
				setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&sockoptval, sizeof(sockoptval));
			}
#endif

			n = bind(sock, sa, socklen);

			if (n != SOCK_CONN_ERR) {
				goto bound;
			}

			err = php_socket_errno();
		}

		closesocket(sock);
	}
	sock = -1;

	if (error_code) {
		*error_code = err;
	}
	if (error_string) {
		*error_string = php_socket_error_str(err);
	}

bound:

	php_network_freeaddresses(psal);

	return sock;

}
/* }}} */

PHPAPI int php_network_parse_network_address_with_port(const char *addr, zend_long addrlen, struct sockaddr *sa, socklen_t *sl)
{
	char *colon;
	char *tmp;
	int ret = FAILURE;
	short port;
	struct sockaddr_in *in4 = (struct sockaddr_in*)sa;
	struct sockaddr **psal;
	int n;
	zend_string *errstr = NULL;
#if HAVE_IPV6
	struct sockaddr_in6 *in6 = (struct sockaddr_in6*)sa;

	memset(in6, 0, sizeof(struct sockaddr_in6));
#else
	memset(in4, 0, sizeof(struct sockaddr_in));
#endif

	if (*addr == '[') {
		colon = memchr(addr + 1, ']', addrlen-1);
		if (!colon || colon[1] != ':') {
			return FAILURE;
		}
		port = atoi(colon + 2);
		addr++;
	} else {
		colon = memchr(addr, ':', addrlen);
		if (!colon) {
			return FAILURE;
		}
		port = atoi(colon + 1);
	}

	tmp = estrndup(addr, colon - addr);

	/* first, try interpreting the address as a numeric address */

#if HAVE_IPV6 && HAVE_INET_PTON
	if (inet_pton(AF_INET6, tmp, &in6->sin6_addr) > 0) {
		in6->sin6_port = htons(port);
		in6->sin6_family = AF_INET6;
		*sl = sizeof(struct sockaddr_in6);
		ret = SUCCESS;
		goto out;
	}
#endif
	if (inet_aton(tmp, &in4->sin_addr) > 0) {
		in4->sin_port = htons(port);
		in4->sin_family = AF_INET;
		*sl = sizeof(struct sockaddr_in);
		ret = SUCCESS;
		goto out;
	}

	/* looks like we'll need to resolve it */
	n = php_network_getaddresses(tmp, SOCK_DGRAM, &psal, &errstr);

	if (n == 0) {
		if (errstr) {
			php_error_docref(NULL, E_WARNING, "Failed to resolve `%s': %s", tmp, ZSTR_VAL(errstr));
			zend_string_release_ex(errstr, 0);
		}
		goto out;
	}

	/* copy the details from the first item */
	switch ((*psal)->sa_family) {
#if HAVE_GETADDRINFO && HAVE_IPV6
		case AF_INET6:
			*in6 = **(struct sockaddr_in6**)psal;
			in6->sin6_port = htons(port);
			*sl = sizeof(struct sockaddr_in6);
			ret = SUCCESS;
			break;
#endif
		case AF_INET:
			*in4 = **(struct sockaddr_in**)psal;
			in4->sin_port = htons(port);
			*sl = sizeof(struct sockaddr_in);
			ret = SUCCESS;
			break;
	}

	php_network_freeaddresses(psal);

out:
	efree(tmp);
	return ret;
}


PHPAPI void php_network_populate_name_from_sockaddr(
		/* input address */
		struct sockaddr *sa, socklen_t sl,
		/* output readable address */
		zend_string **textaddr,
		/* output address */
		struct sockaddr **addr,
		socklen_t *addrlen
		)
{
	if (addr) {
		*addr = emalloc(sl);
		memcpy(*addr, sa, sl);
		*addrlen = sl;
	}

	if (textaddr) {
#if HAVE_IPV6 && HAVE_INET_NTOP
		char abuf[256];
#endif
		char *buf = NULL;

		switch (sa->sa_family) {
			case AF_INET:
				/* generally not thread safe, but it *is* thread safe under win32 */
				buf = inet_ntoa(((struct sockaddr_in*)sa)->sin_addr);
				if (buf) {
					*textaddr = strpprintf(0, "%s:%d",
						buf, ntohs(((struct sockaddr_in*)sa)->sin_port));
				}

				break;

#if HAVE_IPV6 && HAVE_INET_NTOP
			case AF_INET6:
				buf = (char*)inet_ntop(sa->sa_family, &((struct sockaddr_in6*)sa)->sin6_addr, (char *)&abuf, sizeof(abuf));
				if (buf) {
					*textaddr = strpprintf(0, "[%s]:%d",
						buf, ntohs(((struct sockaddr_in6*)sa)->sin6_port));
				}

				break;
#endif
#ifdef AF_UNIX
			case AF_UNIX:
				{
					struct sockaddr_un *ua = (struct sockaddr_un*)sa;

					if (ua->sun_path[0] == '\0') {
						/* abstract name */
						int len = sl - sizeof(sa_family_t);
						*textaddr = zend_string_init((char*)ua->sun_path, len, 0);
					} else {
						int len = strlen(ua->sun_path);
						*textaddr = zend_string_init((char*)ua->sun_path, len, 0);
					}
				}
				break;
#endif

		}

	}
}

PHPAPI int php_network_get_peer_name(php_socket_t sock,
		zend_string **textaddr,
		struct sockaddr **addr,
		socklen_t *addrlen
		)
{
	php_sockaddr_storage sa;
	socklen_t sl = sizeof(sa);
	memset(&sa, 0, sizeof(sa));

	if (getpeername(sock, (struct sockaddr*)&sa, &sl) == 0) {
		php_network_populate_name_from_sockaddr((struct sockaddr*)&sa, sl,
				textaddr,
				addr, addrlen
				);
		return 0;
	}
	return -1;
}

PHPAPI int php_network_get_sock_name(php_socket_t sock,
		zend_string **textaddr,
		struct sockaddr **addr,
		socklen_t *addrlen
		)
{
	php_sockaddr_storage sa;
	socklen_t sl = sizeof(sa);
	memset(&sa, 0, sizeof(sa));

	if (getsockname(sock, (struct sockaddr*)&sa, &sl) == 0) {
		php_network_populate_name_from_sockaddr((struct sockaddr*)&sa, sl,
				textaddr,
				addr, addrlen
				);
		return 0;
	}
	return -1;

}


/* Accept a client connection from a server socket,
 * using an optional timeout.
 * Returns the peer address in addr/addrlen (it will emalloc
 * these, so be sure to efree the result).
 * If you specify textaddr, a text-printable
 * version of the address will be emalloc'd and returned.
 * */

/* {{{ php_network_accept_incoming */
PHPAPI php_socket_t php_network_accept_incoming(php_socket_t srvsock,
		zend_string **textaddr,
		struct sockaddr **addr,
		socklen_t *addrlen,
		struct timeval *timeout,
		zend_string **error_string,
		int *error_code,
		int tcp_nodelay
		)
{
	php_socket_t clisock = -1;
	int error = 0, n;
	php_sockaddr_storage sa;
	socklen_t sl;

	n = php_pollfd_for(srvsock, PHP_POLLREADABLE, timeout);

	if (n == 0) {
		error = PHP_TIMEOUT_ERROR_VALUE;
	} else if (n == -1) {
		error = php_socket_errno();
	} else {
		sl = sizeof(sa);

		clisock = accept(srvsock, (struct sockaddr*)&sa, &sl);

		if (clisock != SOCK_ERR) {
			php_network_populate_name_from_sockaddr((struct sockaddr*)&sa, sl,
					textaddr,
					addr, addrlen
					);
			if (tcp_nodelay) {
#ifdef TCP_NODELAY
				setsockopt(clisock, IPPROTO_TCP, TCP_NODELAY, (char*)&tcp_nodelay, sizeof(tcp_nodelay));
#endif
			}
		} else {
			error = php_socket_errno();
		}
	}

	if (error_code) {
		*error_code = error;
	}
	if (error_string) {
		*error_string = php_socket_error_str(error);
	}

	return clisock;
}
/* }}} */


/* Connect to a remote host using an interruptible connect with optional timeout.
 * Optionally, the connect can be made asynchronously, which will implicitly
 * enable non-blocking mode on the socket.
 * Returns the connected (or connecting) socket, or -1 on failure.
 * */

/* {{{ php_network_connect_socket_to_host */
php_socket_t php_network_connect_socket_to_host(const char *host, unsigned short port,
		int socktype, int asynchronous, struct timeval *timeout, zend_string **error_string,
		int *error_code, const char *bindto, unsigned short bindport, long sockopts
		)
{
	int num_addrs, n, fatal = 0;
	php_socket_t sock;
	struct sockaddr **sal, **psal, *sa;
	struct timeval working_timeout;
	socklen_t socklen;
#if HAVE_GETTIMEOFDAY
	struct timeval limit_time, time_now;
#endif

	num_addrs = php_network_getaddresses(host, socktype, &psal, error_string);

	if (num_addrs == 0) {
		/* could not resolve address(es) */
		return -1;
	}

	if (timeout) {
		memcpy(&working_timeout, timeout, sizeof(working_timeout));
#if HAVE_GETTIMEOFDAY
		gettimeofday(&limit_time, NULL);
		limit_time.tv_sec += working_timeout.tv_sec;
		limit_time.tv_usec += working_timeout.tv_usec;
		if (limit_time.tv_usec >= 1000000) {
			limit_time.tv_usec -= 1000000;
			limit_time.tv_sec++;
		}
#endif
	}

	for (sal = psal; !fatal && *sal != NULL; sal++) {
		sa = *sal;

		/* create a socket for this address */
		sock = socket(sa->sa_family, socktype, 0);

		if (sock == SOCK_ERR) {
			continue;
		}

		switch (sa->sa_family) {
#if HAVE_GETADDRINFO && HAVE_IPV6
			case AF_INET6:
				if (!bindto || strchr(bindto, ':')) {
					((struct sockaddr_in6 *)sa)->sin6_family = sa->sa_family;
					((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
					socklen = sizeof(struct sockaddr_in6);
				} else {
					socklen = 0;
					sa = NULL;
				}
				break;
#endif
			case AF_INET:
				((struct sockaddr_in *)sa)->sin_family = sa->sa_family;
				((struct sockaddr_in *)sa)->sin_port = htons(port);
				socklen = sizeof(struct sockaddr_in);
				break;
			default:
				/* Unknown family */
				socklen = 0;
				sa = NULL;
		}

		if (sa) {
			/* make a connection attempt */

			if (bindto) {
				struct sockaddr *local_address = NULL;
				int local_address_len = 0;

				if (sa->sa_family == AF_INET) {
					if (strchr(bindto,':')) {
						goto skip_bind;
					}
					struct sockaddr_in *in4 = emalloc(sizeof(struct sockaddr_in));

					local_address = (struct sockaddr*)in4;
					local_address_len = sizeof(struct sockaddr_in);

					in4->sin_family = sa->sa_family;
					in4->sin_port = htons(bindport);
					if (!inet_aton(bindto, &in4->sin_addr)) {
						php_error_docref(NULL, E_WARNING, "Invalid IP Address: %s", bindto);
						goto skip_bind;
					}
					memset(&(in4->sin_zero), 0, sizeof(in4->sin_zero));
				}
#if HAVE_IPV6 && HAVE_INET_PTON
				 else { /* IPV6 */
					struct sockaddr_in6 *in6 = emalloc(sizeof(struct sockaddr_in6));

					local_address = (struct sockaddr*)in6;
					local_address_len = sizeof(struct sockaddr_in6);

					in6->sin6_family = sa->sa_family;
					in6->sin6_port = htons(bindport);
					if (inet_pton(AF_INET6, bindto, &in6->sin6_addr) < 1) {
						php_error_docref(NULL, E_WARNING, "Invalid IP Address: %s", bindto);
						goto skip_bind;
					}
				}
#endif

				if (!local_address || bind(sock, local_address, local_address_len)) {
					php_error_docref(NULL, E_WARNING, "Failed to bind to '%s:%d', system said: %s", bindto, bindport, strerror(errno));
				}
skip_bind:
				if (local_address) {
					efree(local_address);
				}
			}
			/* free error string received during previous iteration (if any) */
			if (error_string && *error_string) {
				zend_string_release_ex(*error_string, 0);
				*error_string = NULL;
			}

#ifdef SO_BROADCAST
			{
				int val = 1;
				if (sockopts & STREAM_SOCKOP_SO_BROADCAST) {
					setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char*)&val, sizeof(val));
				}
			}
#endif

#ifdef TCP_NODELAY
			{
				int val = 1;
				if (sockopts & STREAM_SOCKOP_TCP_NODELAY) {
					setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&val, sizeof(val));
				}
			}
#endif
			n = php_network_connect_socket(sock, sa, socklen, asynchronous,
					timeout ? &working_timeout : NULL,
					error_string, error_code);

			if (n != -1) {
				goto connected;
			}

			/* adjust timeout for next attempt */
#if HAVE_GETTIMEOFDAY
			if (timeout) {
				gettimeofday(&time_now, NULL);

				if (!timercmp(&time_now, &limit_time, <)) {
					/* time limit expired; don't attempt any further connections */
					fatal = 1;
				} else {
					/* work out remaining time */
					sub_times(limit_time, time_now, &working_timeout);
				}
			}
#else
			if (error_code && *error_code == PHP_TIMEOUT_ERROR_VALUE) {
				/* Don't even bother trying to connect to the next alternative;
				 * we have no way to determine how long we have already taken
				 * and it is quite likely that the next attempt will fail too. */
				fatal = 1;
			} else {
				/* re-use the same initial timeout.
				 * Not the best thing, but in practice it should be good-enough */
				if (timeout) {
					memcpy(&working_timeout, timeout, sizeof(working_timeout));
				}
			}
#endif
		}

		closesocket(sock);
	}
	sock = -1;

connected:

	php_network_freeaddresses(psal);

	return sock;
}
/* }}} */

/* {{{ php_any_addr
 * Fills the any (wildcard) address into php_sockaddr_storage
 */
PHPAPI void php_any_addr(int family, php_sockaddr_storage *addr, unsigned short port)
{
	memset(addr, 0, sizeof(php_sockaddr_storage));
	switch (family) {
#if HAVE_IPV6
	case AF_INET6: {
		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) addr;
		sin6->sin6_family = AF_INET6;
		sin6->sin6_port = htons(port);
		sin6->sin6_addr = in6addr_any;
		break;
	}
#endif
	case AF_INET: {
		struct sockaddr_in *sin = (struct sockaddr_in *) addr;
		sin->sin_family = AF_INET;
		sin->sin_port = htons(port);
		sin->sin_addr.s_addr = htonl(INADDR_ANY);
		break;
	}
	}
}
/* }}} */

/* {{{ php_sockaddr_size
 * Returns the size of struct sockaddr_xx for the family
 */
PHPAPI int php_sockaddr_size(php_sockaddr_storage *addr)
{
	switch (((struct sockaddr *)addr)->sa_family) {
	case AF_INET:
		return sizeof(struct sockaddr_in);
#if HAVE_IPV6
	case AF_INET6:
		return sizeof(struct sockaddr_in6);
#endif
#ifdef AF_UNIX
	case AF_UNIX:
		return sizeof(struct sockaddr_un);
#endif
	default:
		return 0;
	}
}
/* }}} */

/* Given a socket error code, if buf == NULL:
 *   emallocs storage for the error message and returns
 * else
 *   sprintf message into provided buffer and returns buf
 */
/* {{{ php_socket_strerror */
PHPAPI char *php_socket_strerror(long err, char *buf, size_t bufsize)
{
#ifndef PHP_WIN32
	char *errstr;

	errstr = strerror(err);
	if (buf == NULL) {
		buf = estrdup(errstr);
	} else {
		strncpy(buf, errstr, bufsize);
		buf[bufsize?(bufsize-1):0] = 0;
	}
	return buf;
#else
	char *sysbuf = php_win32_error_to_msg(err);
	if (!sysbuf[0]) {
		sysbuf = "Unknown Error";
	}

	if (buf == NULL) {
		buf = estrdup(sysbuf);
	} else {
		strncpy(buf, sysbuf, bufsize);
		buf[bufsize?(bufsize-1):0] = 0;
	}

	php_win32_error_msg_free(sysbuf);

	return buf;
#endif
}
/* }}} */

/* {{{ php_socket_error_str */
PHPAPI zend_string *php_socket_error_str(long err)
{
#ifndef PHP_WIN32
	char *errstr;

	errstr = strerror(err);
	return zend_string_init(errstr, strlen(errstr), 0);
#else
	zend_string *ret;

	char *sysbuf = php_win32_error_to_msg(err);
	if (!sysbuf[0]) {
		sysbuf = "Unknown Error";
	}

	ret = zend_string_init(sysbuf, strlen(sysbuf), 0);

	php_win32_error_msg_free(sysbuf);

	return ret;
#endif
}
/* }}} */

/* deprecated */
PHPAPI php_stream *_php_stream_sock_open_from_socket(php_socket_t socket, const char *persistent_id STREAMS_DC)
{
	php_stream *stream;
	php_netstream_data_t *sock;

	sock = pemalloc(sizeof(php_netstream_data_t), persistent_id ? 1 : 0);
	memset(sock, 0, sizeof(php_netstream_data_t));

	sock->is_blocked = 1;
	sock->timeout.tv_sec = FG(default_socket_timeout);
	sock->timeout.tv_usec = 0;
	sock->socket = socket;

	stream = php_stream_alloc_rel(&php_stream_generic_socket_ops, sock, persistent_id, "r+");

	if (stream == NULL) {
		pefree(sock, persistent_id ? 1 : 0);
	} else {
		stream->flags |= PHP_STREAM_FLAG_AVOID_BLOCKING;
	}

	return stream;
}

PHPAPI php_stream *_php_stream_sock_open_host(const char *host, unsigned short port,
		int socktype, struct timeval *timeout, const char *persistent_id STREAMS_DC)
{
	char *res;
	zend_long reslen;
	php_stream *stream;

	reslen = spprintf(&res, 0, "tcp://%s:%d", host, port);

	stream = php_stream_xport_create(res, reslen, REPORT_ERRORS,
			STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT, persistent_id, timeout, NULL, NULL, NULL);

	efree(res);

	return stream;
}

PHPAPI int php_set_sock_blocking(php_socket_t socketd, int block)
{
	int ret = SUCCESS;

#ifdef PHP_WIN32
	u_long flags;

	/* with ioctlsocket, a non-zero sets nonblocking, a zero sets blocking */
	flags = !block;
	if (ioctlsocket(socketd, FIONBIO, &flags) == SOCKET_ERROR) {
		ret = FAILURE;
	}
#else
	int myflag = 0;
	int flags = fcntl(socketd, F_GETFL);

#ifdef O_NONBLOCK
	myflag = O_NONBLOCK; /* POSIX version */
#elif defined(O_NDELAY)
	myflag = O_NDELAY;   /* old non-POSIX version */
#endif
	if (!block) {
		flags |= myflag;
	} else {
		flags &= ~myflag;
	}
	if (fcntl(socketd, F_SETFL, flags) == -1) {
		ret = FAILURE;
	}
#endif
	return ret;
}

PHPAPI void _php_emit_fd_setsize_warning(int max_fd)
{

#ifdef PHP_WIN32
	php_error_docref(NULL, E_WARNING,
		"PHP needs to be recompiled with a larger value of FD_SETSIZE.\n"
		"If this binary is from an official www.php.net package, file a bug report\n"
		"at http://bugs.php.net, including the following information:\n"
		"FD_SETSIZE=%d, but you are using %d.\n"
		" --enable-fd-setsize=%d is recommended, but you may want to set it\n"
		"to match to maximum number of sockets each script will work with at\n"
		"one time, in order to avoid seeing this error again at a later date.",
		FD_SETSIZE, max_fd, (max_fd + 128) & ~127);
#else
	php_error_docref(NULL, E_WARNING,
		"You MUST recompile PHP with a larger value of FD_SETSIZE.\n"
		"It is set to %d, but you have descriptors numbered at least as high as %d.\n"
		" --enable-fd-setsize=%d is recommended, but you may want to set it\n"
		"to equal the maximum number of open files supported by your system,\n"
		"in order to avoid seeing this error again at a later date.",
		FD_SETSIZE, max_fd, (max_fd + 1024) & ~1023);
#endif
}

#if defined(PHP_USE_POLL_2_EMULATION)

/* emulate poll(2) using select(2), safely. */

PHPAPI int php_poll2(php_pollfd *ufds, unsigned int nfds, int timeout)
{
	fd_set rset, wset, eset;
	php_socket_t max_fd = SOCK_ERR; /* effectively unused on Windows */
	unsigned int i;
	int n;
	struct timeval tv;

#ifndef PHP_WIN32
	/* check the highest numbered descriptor */
	for (i = 0; i < nfds; i++) {
		if (ufds[i].fd > max_fd)
			max_fd = ufds[i].fd;
	}
#endif

	PHP_SAFE_MAX_FD(max_fd, nfds + 1);

	FD_ZERO(&rset);
	FD_ZERO(&wset);
	FD_ZERO(&eset);

	for (i = 0; i < nfds; i++) {
		if (ufds[i].events & PHP_POLLREADABLE) {
			PHP_SAFE_FD_SET(ufds[i].fd, &rset);
		}
		if (ufds[i].events & POLLOUT) {
			PHP_SAFE_FD_SET(ufds[i].fd, &wset);
		}
		if (ufds[i].events & POLLPRI) {
			PHP_SAFE_FD_SET(ufds[i].fd, &eset);
		}
	}

	if (timeout >= 0) {
		tv.tv_sec = timeout / 1000;
		tv.tv_usec = (timeout - (tv.tv_sec * 1000)) * 1000;
	}
/* Resetting/initializing */
#ifdef PHP_WIN32
	WSASetLastError(0);
#else
	errno = 0;
#endif
	n = select(max_fd + 1, &rset, &wset, &eset, timeout >= 0 ? &tv : NULL);

	if (n >= 0) {
		for (i = 0; i < nfds; i++) {
			ufds[i].revents = 0;

			if (PHP_SAFE_FD_ISSET(ufds[i].fd, &rset)) {
				/* could be POLLERR or POLLHUP but can't tell without probing */
				ufds[i].revents |= POLLIN;
			}
			if (PHP_SAFE_FD_ISSET(ufds[i].fd, &wset)) {
				ufds[i].revents |= POLLOUT;
			}
			if (PHP_SAFE_FD_ISSET(ufds[i].fd, &eset)) {
				ufds[i].revents |= POLLPRI;
			}
		}
	}
	return n;
}
#endif

#if defined(HAVE_GETHOSTBYNAME_R)
#ifdef HAVE_FUNC_GETHOSTBYNAME_R_6
struct hostent * gethostname_re (const char *host,struct hostent *hostbuf,char **tmphstbuf,size_t *hstbuflen)
{
	struct hostent *hp;
	int herr,res;

	if (*hstbuflen == 0) {
		*hstbuflen = 1024;
		*tmphstbuf = (char *)malloc (*hstbuflen);
	}

	while (( res =
		gethostbyname_r(host,hostbuf,*tmphstbuf,*hstbuflen,&hp,&herr))
		&& (errno == ERANGE)) {
		/* Enlarge the buffer. */
		*hstbuflen *= 2;
		*tmphstbuf = (char *)realloc (*tmphstbuf,*hstbuflen);
	}

	if (res != SUCCESS) {
		return NULL;
	}

	return hp;
}
#endif
#ifdef HAVE_FUNC_GETHOSTBYNAME_R_5
struct hostent * gethostname_re (const char *host,struct hostent *hostbuf,char **tmphstbuf,size_t *hstbuflen)
{
	struct hostent *hp;
	int herr;

	if (*hstbuflen == 0) {
		*hstbuflen = 1024;
		*tmphstbuf = (char *)malloc (*hstbuflen);
	}

	while ((NULL == ( hp =
		gethostbyname_r(host,hostbuf,*tmphstbuf,*hstbuflen,&herr)))
		&& (errno == ERANGE)) {
		/* Enlarge the buffer. */
		*hstbuflen *= 2;
		*tmphstbuf = (char *)realloc (*tmphstbuf,*hstbuflen);
	}
	return hp;
}
#endif
#ifdef HAVE_FUNC_GETHOSTBYNAME_R_3
struct hostent * gethostname_re (const char *host,struct hostent *hostbuf,char **tmphstbuf,size_t *hstbuflen)
{
	if (*hstbuflen == 0) {
		*hstbuflen = sizeof(struct hostent_data);
		*tmphstbuf = (char *)malloc (*hstbuflen);
	} else {
		if (*hstbuflen < sizeof(struct hostent_data)) {
			*hstbuflen = sizeof(struct hostent_data);
			*tmphstbuf = (char *)realloc(*tmphstbuf, *hstbuflen);
		}
	}
	memset((void *)(*tmphstbuf),0,*hstbuflen);

	if (SUCCESS != gethostbyname_r(host,hostbuf,(struct hostent_data *)*tmphstbuf)) {
		return NULL;
	}

	return hostbuf;
}
#endif
#endif

PHPAPI struct hostent*	php_network_gethostbyname(const char *name) {
#if !defined(HAVE_GETHOSTBYNAME_R)
	return gethostbyname(name);
#else
	if (FG(tmp_host_buf)) {
		free(FG(tmp_host_buf));
	}

	FG(tmp_host_buf) = NULL;
	FG(tmp_host_buf_len) = 0;

	memset(&FG(tmp_host_info), 0, sizeof(struct hostent));

	return gethostname_re(name, &FG(tmp_host_info), &FG(tmp_host_buf), &FG(tmp_host_buf_len));
#endif
}