network.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2016 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | This source file is subject to version 3.01 of the PHP license, |
  8. | that is bundled with this package in the file LICENSE, and is |
  9. | available through the world-wide-web at the following url: |
  10. | http://www.php.net/license/3_01.txt |
  11. | If you did not receive a copy of the PHP license and are unable to |
  12. | obtain it through the world-wide-web, please send a note to |
  13. | license@php.net so we can mail you a copy immediately. |
  14. +----------------------------------------------------------------------+
  15. | Author: Stig Venaas <venaas@uninett.no> |
  16. | Streams work by Wez Furlong <wez@thebrainroom.com> |
  17. +----------------------------------------------------------------------+
  18. */
  19. /* $Id$ */
  20. /*#define DEBUG_MAIN_NETWORK 1*/
  21. #include "php.h"
  22. #include <stddef.h>
  23. #include <errno.h>
  24. #ifdef PHP_WIN32
  25. # include <Ws2tcpip.h>
  26. # include "win32/inet.h"
  27. # define O_RDONLY _O_RDONLY
  28. # include "win32/param.h"
  29. #elif defined(NETWARE)
  30. #include <sys/timeval.h>
  31. #include <sys/param.h>
  32. #else
  33. #include <sys/param.h>
  34. #endif
  35. #include <sys/types.h>
  36. #if HAVE_SYS_SOCKET_H
  37. #include <sys/socket.h>
  38. #endif
  39. #ifndef _FCNTL_H
  40. #include <fcntl.h>
  41. #endif
  42. #ifdef HAVE_SYS_SELECT_H
  43. #include <sys/select.h>
  44. #endif
  45. #if HAVE_SYS_POLL_H
  46. #include <sys/poll.h>
  47. #endif
  48. #if defined(NETWARE)
  49. #ifdef USE_WINSOCK
  50. #include <novsock2.h>
  51. #else
  52. #include <arpa/inet.h>
  53. #include <netinet/in.h>
  54. #include <netdb.h>
  55. #include <sys/select.h>
  56. #include <sys/socket.h>
  57. #endif
  58. #elif !defined(PHP_WIN32)
  59. #include <netinet/in.h>
  60. #include <netdb.h>
  61. #if HAVE_ARPA_INET_H
  62. #include <arpa/inet.h>
  63. #endif
  64. #endif
  65. #ifndef HAVE_INET_ATON
  66. int inet_aton(const char *, struct in_addr *);
  67. #endif
  68. #include "php_network.h"
  69. #if defined(PHP_WIN32) || defined(__riscos__) || defined(NETWARE)
  70. #undef AF_UNIX
  71. #endif
  72. #if defined(AF_UNIX)
  73. #include <sys/un.h>
  74. #endif
  75. #include "ext/standard/file.h"
  76. #ifdef PHP_WIN32
  77. # include "win32/time.h"
  78. # define SOCK_ERR INVALID_SOCKET
  79. # define SOCK_CONN_ERR SOCKET_ERROR
  80. # define PHP_TIMEOUT_ERROR_VALUE WSAETIMEDOUT
  81. #if HAVE_IPV6
  82. const struct in6_addr in6addr_any = {0}; /* IN6ADDR_ANY_INIT; */
  83. #endif
  84. #else
  85. # define SOCK_ERR -1
  86. # define SOCK_CONN_ERR -1
  87. # define PHP_TIMEOUT_ERROR_VALUE ETIMEDOUT
  88. #endif
  89. #if HAVE_GETADDRINFO
  90. #ifdef HAVE_GAI_STRERROR
  91. # define PHP_GAI_STRERROR(x) (gai_strerror(x))
  92. #else
  93. # define PHP_GAI_STRERROR(x) (php_gai_strerror(x))
  94. /* {{{ php_gai_strerror
  95. */
  96. static const char *php_gai_strerror(int code)
  97. {
  98. static struct {
  99. int code;
  100. const char *msg;
  101. } values[] = {
  102. # ifdef EAI_ADDRFAMILY
  103. {EAI_ADDRFAMILY, "Address family for hostname not supported"},
  104. # endif
  105. {EAI_AGAIN, "Temporary failure in name resolution"},
  106. {EAI_BADFLAGS, "Bad value for ai_flags"},
  107. {EAI_FAIL, "Non-recoverable failure in name resolution"},
  108. {EAI_FAMILY, "ai_family not supported"},
  109. {EAI_MEMORY, "Memory allocation failure"},
  110. # ifdef EAI_NODATA
  111. {EAI_NODATA, "No address associated with hostname"},
  112. # endif
  113. {EAI_NONAME, "Name or service not known"},
  114. {EAI_SERVICE, "Servname not supported for ai_socktype"},
  115. {EAI_SOCKTYPE, "ai_socktype not supported"},
  116. {EAI_SYSTEM, "System error"},
  117. {0, NULL}
  118. };
  119. int i;
  120. for (i = 0; values[i].msg != NULL; i++) {
  121. if (values[i].code == code) {
  122. return (char *)values[i].msg;
  123. }
  124. }
  125. return "Unknown error";
  126. }
  127. /* }}} */
  128. #endif
  129. #endif
  130. /* {{{ php_network_freeaddresses
  131. */
  132. PHPAPI void php_network_freeaddresses(struct sockaddr **sal)
  133. {
  134. struct sockaddr **sap;
  135. if (sal == NULL)
  136. return;
  137. for (sap = sal; *sap != NULL; sap++)
  138. efree(*sap);
  139. efree(sal);
  140. }
  141. /* }}} */
  142. /* {{{ php_network_getaddresses
  143. * Returns number of addresses, 0 for none/error
  144. */
  145. PHPAPI int php_network_getaddresses(const char *host, int socktype, struct sockaddr ***sal, char **error_string TSRMLS_DC)
  146. {
  147. struct sockaddr **sap;
  148. int n;
  149. #if HAVE_GETADDRINFO
  150. # if HAVE_IPV6
  151. static int ipv6_borked = -1; /* the way this is used *is* thread safe */
  152. # endif
  153. struct addrinfo hints, *res, *sai;
  154. #else
  155. struct hostent *host_info;
  156. struct in_addr in;
  157. #endif
  158. if (host == NULL) {
  159. return 0;
  160. }
  161. #if HAVE_GETADDRINFO
  162. memset(&hints, '\0', sizeof(hints));
  163. hints.ai_family = AF_INET; /* default to regular inet (see below) */
  164. hints.ai_socktype = socktype;
  165. # if HAVE_IPV6
  166. /* probe for a working IPv6 stack; even if detected as having v6 at compile
  167. * time, at runtime some stacks are slow to resolve or have other issues
  168. * if they are not correctly configured.
  169. * static variable use is safe here since simple store or fetch operations
  170. * are atomic and because the actual probe process is not in danger of
  171. * collisions or race conditions. */
  172. if (ipv6_borked == -1) {
  173. int s;
  174. s = socket(PF_INET6, SOCK_DGRAM, 0);
  175. if (s == SOCK_ERR) {
  176. ipv6_borked = 1;
  177. } else {
  178. ipv6_borked = 0;
  179. closesocket(s);
  180. }
  181. }
  182. hints.ai_family = ipv6_borked ? AF_INET : AF_UNSPEC;
  183. # endif
  184. if ((n = getaddrinfo(host, NULL, &hints, &res))) {
  185. if (error_string) {
  186. spprintf(error_string, 0, "php_network_getaddresses: getaddrinfo failed: %s", PHP_GAI_STRERROR(n));
  187. php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", *error_string);
  188. } else {
  189. php_error_docref(NULL TSRMLS_CC, E_WARNING, "php_network_getaddresses: getaddrinfo failed: %s", PHP_GAI_STRERROR(n));
  190. }
  191. return 0;
  192. } else if (res == NULL) {
  193. if (error_string) {
  194. spprintf(error_string, 0, "php_network_getaddresses: getaddrinfo failed (null result pointer) errno=%d", errno);
  195. php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", *error_string);
  196. } else {
  197. php_error_docref(NULL TSRMLS_CC, E_WARNING, "php_network_getaddresses: getaddrinfo failed (null result pointer)");
  198. }
  199. return 0;
  200. }
  201. sai = res;
  202. for (n = 1; (sai = sai->ai_next) != NULL; n++)
  203. ;
  204. *sal = safe_emalloc((n + 1), sizeof(*sal), 0);
  205. sai = res;
  206. sap = *sal;
  207. do {
  208. *sap = emalloc(sai->ai_addrlen);
  209. memcpy(*sap, sai->ai_addr, sai->ai_addrlen);
  210. sap++;
  211. } while ((sai = sai->ai_next) != NULL);
  212. freeaddrinfo(res);
  213. #else
  214. if (!inet_aton(host, &in)) {
  215. /* XXX NOT THREAD SAFE (is safe under win32) */
  216. if(strlen(host) > MAXFQDNLEN) {
  217. host_info = NULL;
  218. errno = E2BIG;
  219. } else {
  220. host_info = gethostbyname(host);
  221. }
  222. if (host_info == NULL) {
  223. if (error_string) {
  224. spprintf(error_string, 0, "php_network_getaddresses: gethostbyname failed. errno=%d", errno);
  225. php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", *error_string);
  226. } else {
  227. php_error_docref(NULL TSRMLS_CC, E_WARNING, "php_network_getaddresses: gethostbyname failed");
  228. }
  229. return 0;
  230. }
  231. in = *((struct in_addr *) host_info->h_addr);
  232. }
  233. *sal = safe_emalloc(2, sizeof(*sal), 0);
  234. sap = *sal;
  235. *sap = emalloc(sizeof(struct sockaddr_in));
  236. (*sap)->sa_family = AF_INET;
  237. ((struct sockaddr_in *)*sap)->sin_addr = in;
  238. sap++;
  239. n = 1;
  240. #endif
  241. *sap = NULL;
  242. return n;
  243. }
  244. /* }}} */
  245. #ifndef O_NONBLOCK
  246. #define O_NONBLOCK O_NDELAY
  247. #endif
  248. #if !defined(__BEOS__)
  249. # define HAVE_NON_BLOCKING_CONNECT 1
  250. # ifdef PHP_WIN32
  251. typedef u_long php_non_blocking_flags_t;
  252. # define SET_SOCKET_BLOCKING_MODE(sock, save) \
  253. save = TRUE; ioctlsocket(sock, FIONBIO, &save)
  254. # define RESTORE_SOCKET_BLOCKING_MODE(sock, save) \
  255. ioctlsocket(sock, FIONBIO, &save)
  256. # else
  257. typedef int php_non_blocking_flags_t;
  258. # define SET_SOCKET_BLOCKING_MODE(sock, save) \
  259. save = fcntl(sock, F_GETFL, 0); \
  260. fcntl(sock, F_SETFL, save | O_NONBLOCK)
  261. # define RESTORE_SOCKET_BLOCKING_MODE(sock, save) \
  262. fcntl(sock, F_SETFL, save)
  263. # endif
  264. #endif
  265. /* Connect to a socket using an interruptible connect with optional timeout.
  266. * Optionally, the connect can be made asynchronously, which will implicitly
  267. * enable non-blocking mode on the socket.
  268. * */
  269. /* {{{ php_network_connect_socket */
  270. PHPAPI int php_network_connect_socket(php_socket_t sockfd,
  271. const struct sockaddr *addr,
  272. socklen_t addrlen,
  273. int asynchronous,
  274. struct timeval *timeout,
  275. char **error_string,
  276. int *error_code)
  277. {
  278. #if HAVE_NON_BLOCKING_CONNECT
  279. php_non_blocking_flags_t orig_flags;
  280. int n;
  281. int error = 0;
  282. socklen_t len;
  283. int ret = 0;
  284. SET_SOCKET_BLOCKING_MODE(sockfd, orig_flags);
  285. if ((n = connect(sockfd, addr, addrlen)) != 0) {
  286. error = php_socket_errno();
  287. if (error_code) {
  288. *error_code = error;
  289. }
  290. if (error != EINPROGRESS) {
  291. if (error_string) {
  292. *error_string = php_socket_strerror(error, NULL, 0);
  293. }
  294. return -1;
  295. }
  296. if (asynchronous && error == EINPROGRESS) {
  297. /* this is fine by us */
  298. return 0;
  299. }
  300. }
  301. if (n == 0) {
  302. goto ok;
  303. }
  304. # ifdef PHP_WIN32
  305. /* The documentation for connect() says in case of non-blocking connections
  306. * the select function reports success in the writefds set and failure in
  307. * the exceptfds set. Indeed, using PHP_POLLREADABLE results in select
  308. * failing only due to the timeout and not immediately as would be
  309. * expected when a connection is actively refused. This way,
  310. * php_pollfd_for will return a mask with POLLOUT if the connection
  311. * is successful and with POLLPRI otherwise. */
  312. if ((n = php_pollfd_for(sockfd, POLLOUT|POLLPRI, timeout)) == 0) {
  313. #else
  314. if ((n = php_pollfd_for(sockfd, PHP_POLLREADABLE|POLLOUT, timeout)) == 0) {
  315. #endif
  316. error = PHP_TIMEOUT_ERROR_VALUE;
  317. }
  318. if (n > 0) {
  319. len = sizeof(error);
  320. /*
  321. BSD-derived systems set errno correctly
  322. Solaris returns -1 from getsockopt in case of error
  323. */
  324. if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (char*)&error, &len) != 0) {
  325. ret = -1;
  326. }
  327. } else {
  328. /* whoops: sockfd has disappeared */
  329. ret = -1;
  330. }
  331. ok:
  332. if (!asynchronous) {
  333. /* back to blocking mode */
  334. RESTORE_SOCKET_BLOCKING_MODE(sockfd, orig_flags);
  335. }
  336. if (error_code) {
  337. *error_code = error;
  338. }
  339. if (error) {
  340. ret = -1;
  341. if (error_string) {
  342. *error_string = php_socket_strerror(error, NULL, 0);
  343. }
  344. }
  345. return ret;
  346. #else
  347. if (asynchronous) {
  348. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Asynchronous connect() not supported on this platform");
  349. }
  350. return (connect(sockfd, addr, addrlen) == 0) ? 0 : -1;
  351. #endif
  352. }
  353. /* }}} */
  354. /* {{{ sub_times */
  355. static inline void sub_times(struct timeval a, struct timeval b, struct timeval *result)
  356. {
  357. result->tv_usec = a.tv_usec - b.tv_usec;
  358. if (result->tv_usec < 0L) {
  359. a.tv_sec--;
  360. result->tv_usec += 1000000L;
  361. }
  362. result->tv_sec = a.tv_sec - b.tv_sec;
  363. if (result->tv_sec < 0L) {
  364. result->tv_sec++;
  365. result->tv_usec -= 1000000L;
  366. }
  367. }
  368. /* }}} */
  369. /* Bind to a local IP address.
  370. * Returns the bound socket, or -1 on failure.
  371. * */
  372. /* {{{ php_network_bind_socket_to_local_addr */
  373. php_socket_t php_network_bind_socket_to_local_addr(const char *host, unsigned port,
  374. int socktype, char **error_string, int *error_code
  375. TSRMLS_DC)
  376. {
  377. int num_addrs, n, err = 0;
  378. php_socket_t sock;
  379. struct sockaddr **sal, **psal, *sa;
  380. socklen_t socklen;
  381. num_addrs = php_network_getaddresses(host, socktype, &psal, error_string TSRMLS_CC);
  382. if (num_addrs == 0) {
  383. /* could not resolve address(es) */
  384. return -1;
  385. }
  386. for (sal = psal; *sal != NULL; sal++) {
  387. sa = *sal;
  388. /* create a socket for this address */
  389. sock = socket(sa->sa_family, socktype, 0);
  390. if (sock == SOCK_ERR) {
  391. continue;
  392. }
  393. switch (sa->sa_family) {
  394. #if HAVE_GETADDRINFO && HAVE_IPV6
  395. case AF_INET6:
  396. ((struct sockaddr_in6 *)sa)->sin6_family = sa->sa_family;
  397. ((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
  398. socklen = sizeof(struct sockaddr_in6);
  399. break;
  400. #endif
  401. case AF_INET:
  402. ((struct sockaddr_in *)sa)->sin_family = sa->sa_family;
  403. ((struct sockaddr_in *)sa)->sin_port = htons(port);
  404. socklen = sizeof(struct sockaddr_in);
  405. break;
  406. default:
  407. /* Unknown family */
  408. socklen = 0;
  409. sa = NULL;
  410. }
  411. if (sa) {
  412. /* attempt to bind */
  413. #ifdef SO_REUSEADDR
  414. {
  415. int val = 1;
  416. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&val, sizeof(val));
  417. }
  418. #endif
  419. n = bind(sock, sa, socklen);
  420. if (n != SOCK_CONN_ERR) {
  421. goto bound;
  422. }
  423. err = php_socket_errno();
  424. }
  425. closesocket(sock);
  426. }
  427. sock = -1;
  428. if (error_code) {
  429. *error_code = err;
  430. }
  431. if (error_string) {
  432. *error_string = php_socket_strerror(err, NULL, 0);
  433. }
  434. bound:
  435. php_network_freeaddresses(psal);
  436. return sock;
  437. }
  438. /* }}} */
  439. PHPAPI int php_network_parse_network_address_with_port(const char *addr, long addrlen, struct sockaddr *sa, socklen_t *sl TSRMLS_DC)
  440. {
  441. char *colon;
  442. char *tmp;
  443. int ret = FAILURE;
  444. short port;
  445. struct sockaddr_in *in4 = (struct sockaddr_in*)sa;
  446. struct sockaddr **psal;
  447. int n;
  448. char *errstr = NULL;
  449. #if HAVE_IPV6
  450. struct sockaddr_in6 *in6 = (struct sockaddr_in6*)sa;
  451. #endif
  452. if (*addr == '[') {
  453. colon = memchr(addr + 1, ']', addrlen-1);
  454. if (!colon || colon[1] != ':') {
  455. return FAILURE;
  456. }
  457. port = atoi(colon + 2);
  458. addr++;
  459. } else {
  460. colon = memchr(addr, ':', addrlen);
  461. if (!colon) {
  462. return FAILURE;
  463. }
  464. port = atoi(colon + 1);
  465. }
  466. tmp = estrndup(addr, colon - addr);
  467. /* first, try interpreting the address as a numeric address */
  468. #if HAVE_IPV6 && HAVE_INET_PTON
  469. if (inet_pton(AF_INET6, tmp, &in6->sin6_addr) > 0) {
  470. in6->sin6_port = htons(port);
  471. in6->sin6_family = AF_INET6;
  472. *sl = sizeof(struct sockaddr_in6);
  473. ret = SUCCESS;
  474. goto out;
  475. }
  476. #endif
  477. if (inet_aton(tmp, &in4->sin_addr) > 0) {
  478. in4->sin_port = htons(port);
  479. in4->sin_family = AF_INET;
  480. *sl = sizeof(struct sockaddr_in);
  481. ret = SUCCESS;
  482. goto out;
  483. }
  484. /* looks like we'll need to resolve it */
  485. n = php_network_getaddresses(tmp, SOCK_DGRAM, &psal, &errstr TSRMLS_CC);
  486. if (n == 0) {
  487. if (errstr) {
  488. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to resolve `%s': %s", tmp, errstr);
  489. STR_FREE(errstr);
  490. }
  491. goto out;
  492. }
  493. /* copy the details from the first item */
  494. switch ((*psal)->sa_family) {
  495. #if HAVE_GETADDRINFO && HAVE_IPV6
  496. case AF_INET6:
  497. *in6 = **(struct sockaddr_in6**)psal;
  498. in6->sin6_port = htons(port);
  499. *sl = sizeof(struct sockaddr_in6);
  500. ret = SUCCESS;
  501. break;
  502. #endif
  503. case AF_INET:
  504. *in4 = **(struct sockaddr_in**)psal;
  505. in4->sin_port = htons(port);
  506. *sl = sizeof(struct sockaddr_in);
  507. ret = SUCCESS;
  508. break;
  509. }
  510. php_network_freeaddresses(psal);
  511. out:
  512. STR_FREE(tmp);
  513. return ret;
  514. }
  515. PHPAPI void php_network_populate_name_from_sockaddr(
  516. /* input address */
  517. struct sockaddr *sa, socklen_t sl,
  518. /* output readable address */
  519. char **textaddr, long *textaddrlen,
  520. /* output address */
  521. struct sockaddr **addr,
  522. socklen_t *addrlen
  523. TSRMLS_DC)
  524. {
  525. if (addr) {
  526. *addr = emalloc(sl);
  527. memcpy(*addr, sa, sl);
  528. *addrlen = sl;
  529. }
  530. if (textaddr) {
  531. #if HAVE_IPV6 && HAVE_INET_NTOP
  532. char abuf[256];
  533. #endif
  534. char *buf = NULL;
  535. switch (sa->sa_family) {
  536. case AF_INET:
  537. /* generally not thread safe, but it *is* thread safe under win32 */
  538. buf = inet_ntoa(((struct sockaddr_in*)sa)->sin_addr);
  539. if (buf) {
  540. *textaddrlen = spprintf(textaddr, 0, "%s:%d",
  541. buf, ntohs(((struct sockaddr_in*)sa)->sin_port));
  542. }
  543. break;
  544. #if HAVE_IPV6 && HAVE_INET_NTOP
  545. case AF_INET6:
  546. buf = (char*)inet_ntop(sa->sa_family, &((struct sockaddr_in6*)sa)->sin6_addr, (char *)&abuf, sizeof(abuf));
  547. if (buf) {
  548. *textaddrlen = spprintf(textaddr, 0, "%s:%d",
  549. buf, ntohs(((struct sockaddr_in6*)sa)->sin6_port));
  550. }
  551. break;
  552. #endif
  553. #ifdef AF_UNIX
  554. case AF_UNIX:
  555. {
  556. struct sockaddr_un *ua = (struct sockaddr_un*)sa;
  557. if (ua->sun_path[0] == '\0') {
  558. /* abstract name */
  559. int len = strlen(ua->sun_path + 1) + 1;
  560. *textaddrlen = len;
  561. *textaddr = emalloc(len + 1);
  562. memcpy(*textaddr, ua->sun_path, len);
  563. (*textaddr)[len] = '\0';
  564. } else {
  565. *textaddrlen = strlen(ua->sun_path);
  566. *textaddr = estrndup(ua->sun_path, *textaddrlen);
  567. }
  568. }
  569. break;
  570. #endif
  571. }
  572. }
  573. }
  574. PHPAPI int php_network_get_peer_name(php_socket_t sock,
  575. char **textaddr, long *textaddrlen,
  576. struct sockaddr **addr,
  577. socklen_t *addrlen
  578. TSRMLS_DC)
  579. {
  580. php_sockaddr_storage sa;
  581. socklen_t sl = sizeof(sa);
  582. memset(&sa, 0, sizeof(sa));
  583. if (getpeername(sock, (struct sockaddr*)&sa, &sl) == 0) {
  584. php_network_populate_name_from_sockaddr((struct sockaddr*)&sa, sl,
  585. textaddr, textaddrlen,
  586. addr, addrlen
  587. TSRMLS_CC);
  588. return 0;
  589. }
  590. return -1;
  591. }
  592. PHPAPI int php_network_get_sock_name(php_socket_t sock,
  593. char **textaddr, long *textaddrlen,
  594. struct sockaddr **addr,
  595. socklen_t *addrlen
  596. TSRMLS_DC)
  597. {
  598. php_sockaddr_storage sa;
  599. socklen_t sl = sizeof(sa);
  600. memset(&sa, 0, sizeof(sa));
  601. if (getsockname(sock, (struct sockaddr*)&sa, &sl) == 0) {
  602. php_network_populate_name_from_sockaddr((struct sockaddr*)&sa, sl,
  603. textaddr, textaddrlen,
  604. addr, addrlen
  605. TSRMLS_CC);
  606. return 0;
  607. }
  608. return -1;
  609. }
  610. /* Accept a client connection from a server socket,
  611. * using an optional timeout.
  612. * Returns the peer address in addr/addrlen (it will emalloc
  613. * these, so be sure to efree the result).
  614. * If you specify textaddr/textaddrlen, a text-printable
  615. * version of the address will be emalloc'd and returned.
  616. * */
  617. /* {{{ php_network_accept_incoming */
  618. PHPAPI php_socket_t php_network_accept_incoming(php_socket_t srvsock,
  619. char **textaddr, long *textaddrlen,
  620. struct sockaddr **addr,
  621. socklen_t *addrlen,
  622. struct timeval *timeout,
  623. char **error_string,
  624. int *error_code
  625. TSRMLS_DC)
  626. {
  627. php_socket_t clisock = -1;
  628. int error = 0, n;
  629. php_sockaddr_storage sa;
  630. socklen_t sl;
  631. n = php_pollfd_for(srvsock, PHP_POLLREADABLE, timeout);
  632. if (n == 0) {
  633. error = PHP_TIMEOUT_ERROR_VALUE;
  634. } else if (n == -1) {
  635. error = php_socket_errno();
  636. } else {
  637. sl = sizeof(sa);
  638. clisock = accept(srvsock, (struct sockaddr*)&sa, &sl);
  639. if (clisock != SOCK_ERR) {
  640. php_network_populate_name_from_sockaddr((struct sockaddr*)&sa, sl,
  641. textaddr, textaddrlen,
  642. addr, addrlen
  643. TSRMLS_CC);
  644. } else {
  645. error = php_socket_errno();
  646. }
  647. }
  648. if (error_code) {
  649. *error_code = error;
  650. }
  651. if (error_string) {
  652. *error_string = php_socket_strerror(error, NULL, 0);
  653. }
  654. return clisock;
  655. }
  656. /* }}} */
  657. /* Connect to a remote host using an interruptible connect with optional timeout.
  658. * Optionally, the connect can be made asynchronously, which will implicitly
  659. * enable non-blocking mode on the socket.
  660. * Returns the connected (or connecting) socket, or -1 on failure.
  661. * */
  662. /* {{{ php_network_connect_socket_to_host */
  663. php_socket_t php_network_connect_socket_to_host(const char *host, unsigned short port,
  664. int socktype, int asynchronous, struct timeval *timeout, char **error_string,
  665. int *error_code, char *bindto, unsigned short bindport
  666. TSRMLS_DC)
  667. {
  668. int num_addrs, n, fatal = 0;
  669. php_socket_t sock;
  670. struct sockaddr **sal, **psal, *sa;
  671. struct timeval working_timeout;
  672. socklen_t socklen;
  673. #if HAVE_GETTIMEOFDAY
  674. struct timeval limit_time, time_now;
  675. #endif
  676. num_addrs = php_network_getaddresses(host, socktype, &psal, error_string TSRMLS_CC);
  677. if (num_addrs == 0) {
  678. /* could not resolve address(es) */
  679. return -1;
  680. }
  681. if (timeout) {
  682. memcpy(&working_timeout, timeout, sizeof(working_timeout));
  683. #if HAVE_GETTIMEOFDAY
  684. gettimeofday(&limit_time, NULL);
  685. limit_time.tv_sec += working_timeout.tv_sec;
  686. limit_time.tv_usec += working_timeout.tv_usec;
  687. if (limit_time.tv_usec >= 1000000) {
  688. limit_time.tv_usec -= 1000000;
  689. limit_time.tv_sec++;
  690. }
  691. #endif
  692. }
  693. for (sal = psal; !fatal && *sal != NULL; sal++) {
  694. sa = *sal;
  695. /* create a socket for this address */
  696. sock = socket(sa->sa_family, socktype, 0);
  697. if (sock == SOCK_ERR) {
  698. continue;
  699. }
  700. switch (sa->sa_family) {
  701. #if HAVE_GETADDRINFO && HAVE_IPV6
  702. case AF_INET6:
  703. if (!bindto || strchr(bindto, ':')) {
  704. ((struct sockaddr_in6 *)sa)->sin6_family = sa->sa_family;
  705. ((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
  706. socklen = sizeof(struct sockaddr_in6);
  707. } else {
  708. socklen = 0;
  709. sa = NULL;
  710. }
  711. break;
  712. #endif
  713. case AF_INET:
  714. ((struct sockaddr_in *)sa)->sin_family = sa->sa_family;
  715. ((struct sockaddr_in *)sa)->sin_port = htons(port);
  716. socklen = sizeof(struct sockaddr_in);
  717. break;
  718. default:
  719. /* Unknown family */
  720. socklen = 0;
  721. sa = NULL;
  722. }
  723. if (sa) {
  724. /* make a connection attempt */
  725. if (bindto) {
  726. struct sockaddr *local_address = NULL;
  727. int local_address_len = 0;
  728. if (sa->sa_family == AF_INET) {
  729. struct sockaddr_in *in4 = emalloc(sizeof(struct sockaddr_in));
  730. local_address = (struct sockaddr*)in4;
  731. local_address_len = sizeof(struct sockaddr_in);
  732. in4->sin_family = sa->sa_family;
  733. in4->sin_port = htons(bindport);
  734. if (!inet_aton(bindto, &in4->sin_addr)) {
  735. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid IP Address: %s", bindto);
  736. goto skip_bind;
  737. }
  738. memset(&(in4->sin_zero), 0, sizeof(in4->sin_zero));
  739. }
  740. #if HAVE_IPV6 && HAVE_INET_PTON
  741. else { /* IPV6 */
  742. struct sockaddr_in6 *in6 = emalloc(sizeof(struct sockaddr_in6));
  743. local_address = (struct sockaddr*)in6;
  744. local_address_len = sizeof(struct sockaddr_in6);
  745. in6->sin6_family = sa->sa_family;
  746. in6->sin6_port = htons(bindport);
  747. if (inet_pton(AF_INET6, bindto, &in6->sin6_addr) < 1) {
  748. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid IP Address: %s", bindto);
  749. goto skip_bind;
  750. }
  751. }
  752. #endif
  753. if (!local_address || bind(sock, local_address, local_address_len)) {
  754. php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed to bind to '%s:%d', system said: %s", bindto, bindport, strerror(errno));
  755. }
  756. skip_bind:
  757. if (local_address) {
  758. efree(local_address);
  759. }
  760. }
  761. /* free error string received during previous iteration (if any) */
  762. if (error_string && *error_string) {
  763. efree(*error_string);
  764. *error_string = NULL;
  765. }
  766. n = php_network_connect_socket(sock, sa, socklen, asynchronous,
  767. timeout ? &working_timeout : NULL,
  768. error_string, error_code);
  769. if (n != -1) {
  770. goto connected;
  771. }
  772. /* adjust timeout for next attempt */
  773. #if HAVE_GETTIMEOFDAY
  774. if (timeout) {
  775. gettimeofday(&time_now, NULL);
  776. if (timercmp(&time_now, &limit_time, >=)) {
  777. /* time limit expired; don't attempt any further connections */
  778. fatal = 1;
  779. } else {
  780. /* work out remaining time */
  781. sub_times(limit_time, time_now, &working_timeout);
  782. }
  783. }
  784. #else
  785. if (error_code && *error_code == PHP_TIMEOUT_ERROR_VALUE) {
  786. /* Don't even bother trying to connect to the next alternative;
  787. * we have no way to determine how long we have already taken
  788. * and it is quite likely that the next attempt will fail too. */
  789. fatal = 1;
  790. } else {
  791. /* re-use the same initial timeout.
  792. * Not the best thing, but in practice it should be good-enough */
  793. if (timeout) {
  794. memcpy(&working_timeout, timeout, sizeof(working_timeout));
  795. }
  796. }
  797. #endif
  798. }
  799. closesocket(sock);
  800. }
  801. sock = -1;
  802. connected:
  803. php_network_freeaddresses(psal);
  804. return sock;
  805. }
  806. /* }}} */
  807. /* {{{ php_any_addr
  808. * Fills the any (wildcard) address into php_sockaddr_storage
  809. */
  810. PHPAPI void php_any_addr(int family, php_sockaddr_storage *addr, unsigned short port)
  811. {
  812. memset(addr, 0, sizeof(php_sockaddr_storage));
  813. switch (family) {
  814. #if HAVE_IPV6
  815. case AF_INET6: {
  816. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) addr;
  817. sin6->sin6_family = AF_INET6;
  818. sin6->sin6_port = htons(port);
  819. sin6->sin6_addr = in6addr_any;
  820. break;
  821. }
  822. #endif
  823. case AF_INET: {
  824. struct sockaddr_in *sin = (struct sockaddr_in *) addr;
  825. sin->sin_family = AF_INET;
  826. sin->sin_port = htons(port);
  827. sin->sin_addr.s_addr = htonl(INADDR_ANY);
  828. break;
  829. }
  830. }
  831. }
  832. /* }}} */
  833. /* {{{ php_sockaddr_size
  834. * Returns the size of struct sockaddr_xx for the family
  835. */
  836. PHPAPI int php_sockaddr_size(php_sockaddr_storage *addr)
  837. {
  838. switch (((struct sockaddr *)addr)->sa_family) {
  839. case AF_INET:
  840. return sizeof(struct sockaddr_in);
  841. #if HAVE_IPV6
  842. case AF_INET6:
  843. return sizeof(struct sockaddr_in6);
  844. #endif
  845. #ifdef AF_UNIX
  846. case AF_UNIX:
  847. return sizeof(struct sockaddr_un);
  848. #endif
  849. default:
  850. return 0;
  851. }
  852. }
  853. /* }}} */
  854. /* Given a socket error code, if buf == NULL:
  855. * emallocs storage for the error message and returns
  856. * else
  857. * sprintf message into provided buffer and returns buf
  858. */
  859. /* {{{ php_socket_strerror */
  860. PHPAPI char *php_socket_strerror(long err, char *buf, size_t bufsize)
  861. {
  862. #ifndef PHP_WIN32
  863. char *errstr;
  864. errstr = strerror(err);
  865. if (buf == NULL) {
  866. buf = estrdup(errstr);
  867. } else {
  868. strncpy(buf, errstr, bufsize);
  869. buf[bufsize?(bufsize-1):0] = 0;
  870. }
  871. return buf;
  872. #else
  873. char *sysbuf;
  874. int free_it = 1;
  875. if (!FormatMessage(
  876. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  877. FORMAT_MESSAGE_FROM_SYSTEM |
  878. FORMAT_MESSAGE_IGNORE_INSERTS,
  879. NULL,
  880. err,
  881. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  882. (LPTSTR)&sysbuf,
  883. 0,
  884. NULL)) {
  885. free_it = 0;
  886. sysbuf = "Unknown Error";
  887. }
  888. if (buf == NULL) {
  889. buf = estrdup(sysbuf);
  890. } else {
  891. strncpy(buf, sysbuf, bufsize);
  892. buf[bufsize?(bufsize-1):0] = 0;
  893. }
  894. if (free_it) {
  895. LocalFree(sysbuf);
  896. }
  897. return buf;
  898. #endif
  899. }
  900. /* }}} */
  901. /* deprecated */
  902. PHPAPI php_stream *_php_stream_sock_open_from_socket(php_socket_t socket, const char *persistent_id STREAMS_DC TSRMLS_DC)
  903. {
  904. php_stream *stream;
  905. php_netstream_data_t *sock;
  906. sock = pemalloc(sizeof(php_netstream_data_t), persistent_id ? 1 : 0);
  907. memset(sock, 0, sizeof(php_netstream_data_t));
  908. sock->is_blocked = 1;
  909. sock->timeout.tv_sec = FG(default_socket_timeout);
  910. sock->timeout.tv_usec = 0;
  911. sock->socket = socket;
  912. stream = php_stream_alloc_rel(&php_stream_generic_socket_ops, sock, persistent_id, "r+");
  913. if (stream == NULL) {
  914. pefree(sock, persistent_id ? 1 : 0);
  915. } else {
  916. stream->flags |= PHP_STREAM_FLAG_AVOID_BLOCKING;
  917. }
  918. return stream;
  919. }
  920. PHPAPI php_stream *_php_stream_sock_open_host(const char *host, unsigned short port,
  921. int socktype, struct timeval *timeout, const char *persistent_id STREAMS_DC TSRMLS_DC)
  922. {
  923. char *res;
  924. long reslen;
  925. php_stream *stream;
  926. reslen = spprintf(&res, 0, "tcp://%s:%d", host, port);
  927. stream = php_stream_xport_create(res, reslen, REPORT_ERRORS,
  928. STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT, persistent_id, timeout, NULL, NULL, NULL);
  929. efree(res);
  930. return stream;
  931. }
  932. PHPAPI int php_set_sock_blocking(int socketd, int block TSRMLS_DC)
  933. {
  934. int ret = SUCCESS;
  935. int flags;
  936. int myflag = 0;
  937. #ifdef PHP_WIN32
  938. /* with ioctlsocket, a non-zero sets nonblocking, a zero sets blocking */
  939. flags = !block;
  940. if (ioctlsocket(socketd, FIONBIO, &flags) == SOCKET_ERROR) {
  941. ret = FAILURE;
  942. }
  943. #else
  944. flags = fcntl(socketd, F_GETFL);
  945. #ifdef O_NONBLOCK
  946. myflag = O_NONBLOCK; /* POSIX version */
  947. #elif defined(O_NDELAY)
  948. myflag = O_NDELAY; /* old non-POSIX version */
  949. #endif
  950. if (!block) {
  951. flags |= myflag;
  952. } else {
  953. flags &= ~myflag;
  954. }
  955. if (fcntl(socketd, F_SETFL, flags) == -1) {
  956. ret = FAILURE;
  957. }
  958. #endif
  959. return ret;
  960. }
  961. PHPAPI void _php_emit_fd_setsize_warning(int max_fd)
  962. {
  963. TSRMLS_FETCH();
  964. #ifdef PHP_WIN32
  965. php_error_docref(NULL TSRMLS_CC, E_WARNING,
  966. "PHP needs to be recompiled with a larger value of FD_SETSIZE.\n"
  967. "If this binary is from an official www.php.net package, file a bug report\n"
  968. "at http://bugs.php.net, including the following information:\n"
  969. "FD_SETSIZE=%d, but you are using %d.\n"
  970. " --enable-fd-setsize=%d is recommended, but you may want to set it\n"
  971. "to match to maximum number of sockets each script will work with at\n"
  972. "one time, in order to avoid seeing this error again at a later date.",
  973. FD_SETSIZE, max_fd, (max_fd + 128) & ~127);
  974. #else
  975. php_error_docref(NULL TSRMLS_CC, E_WARNING,
  976. "You MUST recompile PHP with a larger value of FD_SETSIZE.\n"
  977. "It is set to %d, but you have descriptors numbered at least as high as %d.\n"
  978. " --enable-fd-setsize=%d is recommended, but you may want to set it\n"
  979. "to equal the maximum number of open files supported by your system,\n"
  980. "in order to avoid seeing this error again at a later date.",
  981. FD_SETSIZE, max_fd, (max_fd + 1024) & ~1023);
  982. #endif
  983. }
  984. #if defined(PHP_USE_POLL_2_EMULATION)
  985. /* emulate poll(2) using select(2), safely. */
  986. PHPAPI int php_poll2(php_pollfd *ufds, unsigned int nfds, int timeout)
  987. {
  988. fd_set rset, wset, eset;
  989. php_socket_t max_fd = SOCK_ERR;
  990. unsigned int i;
  991. int n;
  992. struct timeval tv;
  993. /* check the highest numbered descriptor */
  994. for (i = 0; i < nfds; i++) {
  995. if (ufds[i].fd > max_fd)
  996. max_fd = ufds[i].fd;
  997. }
  998. PHP_SAFE_MAX_FD(max_fd, nfds + 1);
  999. FD_ZERO(&rset);
  1000. FD_ZERO(&wset);
  1001. FD_ZERO(&eset);
  1002. for (i = 0; i < nfds; i++) {
  1003. if (ufds[i].events & PHP_POLLREADABLE) {
  1004. PHP_SAFE_FD_SET(ufds[i].fd, &rset);
  1005. }
  1006. if (ufds[i].events & POLLOUT) {
  1007. PHP_SAFE_FD_SET(ufds[i].fd, &wset);
  1008. }
  1009. if (ufds[i].events & POLLPRI) {
  1010. PHP_SAFE_FD_SET(ufds[i].fd, &eset);
  1011. }
  1012. }
  1013. if (timeout >= 0) {
  1014. tv.tv_sec = timeout / 1000;
  1015. tv.tv_usec = (timeout - (tv.tv_sec * 1000)) * 1000;
  1016. }
  1017. /* Reseting/initializing */
  1018. #ifdef PHP_WIN32
  1019. WSASetLastError(0);
  1020. #else
  1021. errno = 0;
  1022. #endif
  1023. n = select(max_fd + 1, &rset, &wset, &eset, timeout >= 0 ? &tv : NULL);
  1024. if (n >= 0) {
  1025. for (i = 0; i < nfds; i++) {
  1026. ufds[i].revents = 0;
  1027. if (PHP_SAFE_FD_ISSET(ufds[i].fd, &rset)) {
  1028. /* could be POLLERR or POLLHUP but can't tell without probing */
  1029. ufds[i].revents |= POLLIN;
  1030. }
  1031. if (PHP_SAFE_FD_ISSET(ufds[i].fd, &wset)) {
  1032. ufds[i].revents |= POLLOUT;
  1033. }
  1034. if (PHP_SAFE_FD_ISSET(ufds[i].fd, &eset)) {
  1035. ufds[i].revents |= POLLPRI;
  1036. }
  1037. }
  1038. }
  1039. return n;
  1040. }
  1041. #endif
  1042. /*
  1043. * Local variables:
  1044. * tab-width: 8
  1045. * c-basic-offset: 8
  1046. * End:
  1047. * vim600: sw=4 ts=4 fdm=marker
  1048. * vim<600: sw=4 ts=4
  1049. */