summaryrefslogtreecommitdiff
path: root/main/network.c
blob: 54b3cb089234811a09b274b7b9a86195db32b276 (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
/*
   +----------------------------------------------------------------------+
   | PHP Version 4                                                        |
   +----------------------------------------------------------------------+
   | Copyright (c) 1997-2002 The PHP Group                                |
   +----------------------------------------------------------------------+
   | This source file is subject to version 2.02 of the PHP license,      |
   | that is bundled with this package in the file LICENSE, and is        |
   | available at through the world-wide-web at                           |
   | http://www.php.net/license/2_02.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>                              |
   +----------------------------------------------------------------------+
 */
/* $Id$ */

/*#define DEBUG_MAIN_NETWORK 1*/
#define MAX_CHUNKS_PER_READ 10

#include "php.h"

#include <stddef.h>

#ifdef PHP_WIN32
#include <windows.h>
#include <winsock.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_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
# define SOCK_ERR INVALID_SOCKET
# define SOCK_CONN_ERR SOCKET_ERROR
#else
# define SOCK_ERR -1
# define SOCK_CONN_ERR -1
#endif

#ifdef 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 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
 */
static 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
 */
static int php_network_getaddresses(const char *host, struct sockaddr ***sal)
{
	struct sockaddr **sap;
	int n;

	if (host == NULL) {
		return 0;
	}

	{
#ifdef HAVE_GETADDRINFO
		struct addrinfo hints, *res, *sai;

		memset(&hints, '\0', sizeof(hints));
		hints.ai_family = AF_UNSPEC;
		if ((n = getaddrinfo(host, NULL, &hints, &res))) {
			php_error(E_WARNING, "php_network_getaddresses: getaddrinfo failed: %s", PHP_GAI_STRERROR(n));
			return 0;
		} else if (res == NULL) {
			php_error(E_WARNING, "php_network_getaddresses: getaddrinfo failed (null result pointer)");
			return 0;
		}

		sai = res;
		for (n = 1; (sai = sai->ai_next) != NULL; n++);
		*sal = emalloc((n + 1) * sizeof(*sal));
		sai = res;
		sap = *sal;
		do {
			switch (sai->ai_family) {
#  ifdef HAVE_IPV6
			case AF_INET6:
				*sap = emalloc(sizeof(struct sockaddr_in6));
				*(struct sockaddr_in6 *)*sap =
					*((struct sockaddr_in6 *)sai->ai_addr);
				sap++;
				break;
#  endif
			case AF_INET:
				*sap = emalloc(sizeof(struct sockaddr_in));
				*(struct sockaddr_in *)*sap =
					*((struct sockaddr_in *)sai->ai_addr);
				sap++;
				break;
			}
		} while ((sai = sai->ai_next) != NULL);
		freeaddrinfo(res);
#else
		struct hostent *host_info;
		struct in_addr in;

		if (!inet_aton(host, &in)) {
			/* XXX NOT THREAD SAFE */
			host_info = gethostbyname(host);
			if (host_info == NULL) {
				php_error(E_WARNING, "php_network_getaddresses: gethostbyname failed");
				return 0;
			}
			in = *((struct in_addr *) host_info->h_addr);
		}

		*sal = emalloc(2 * sizeof(*sal));
		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;
}
/* }}} */

/* {{{ php_connect_nonb */
PHPAPI int php_connect_nonb(int sockfd,
						const struct sockaddr *addr,
						socklen_t addrlen,
						struct timeval *timeout)
{
	/* probably won't work on Win32, someone else might try it (read: fix it ;) */

#if (!defined(__BEOS__) && !defined(PHP_WIN32)) && (defined(O_NONBLOCK) || defined(O_NDELAY))

#ifndef O_NONBLOCK
#define O_NONBLOCK O_NDELAY
#endif

	int flags;
	int n;
	int error = 0;
	socklen_t len;
	int ret = 0;
	fd_set rset;
	fd_set wset;

	if (timeout == NULL)	{
		/* blocking mode */
		return connect(sockfd, addr, addrlen);
	}
	
	flags = fcntl(sockfd, F_GETFL, 0);
	fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);

	if ((n = connect(sockfd, addr, addrlen)) < 0) {
		if (errno != EINPROGRESS) {
			return -1;
		}
	}

	if (n == 0) {
		goto ok;
	}

	FD_ZERO(&rset);
	FD_SET(sockfd, &rset);

	wset = rset;

	if ((n = select(sockfd + 1, &rset, &wset, NULL, timeout)) == 0) {
		error = ETIMEDOUT;
	}

	if(FD_ISSET(sockfd, &rset) || FD_ISSET(sockfd, &wset)) {
		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, &error, &len) < 0) {
			ret = -1;
		}
	} else {
		/* whoops: sockfd has disappeared */
		ret = -1;
	}

ok:
	fcntl(sockfd, F_SETFL, flags);

	if(error) {
		errno = error;
		ret = -1;
	}
	return ret;
#else /* !defined(PHP_WIN32) && ... */
	return connect(sockfd, addr, addrlen);
#endif
}
/* }}} */

/* {{{ php_hostconnect
 * Creates a socket of type socktype and connects to the given host and
 * port, returns the created socket on success, else returns -1.
 * timeout gives timeout in seconds, 0 means blocking mode.
 */
int php_hostconnect(const char *host, unsigned short port, int socktype, int timeout)
{	
	int n, repeatto, s;
	struct sockaddr **sal, **psal;
	struct timeval timeoutval;
	
	n = php_network_getaddresses(host, &sal);

	if (n == 0)
		return -1;
	
	/* is this a good idea? 5s? */
	repeatto = timeout / n > 5;
	if (repeatto) {
		timeout /= n;
	}
	timeoutval.tv_sec = timeout;
	timeoutval.tv_usec = 0;

	psal = sal;
	while (*sal != NULL) {
		s = socket((*sal)->sa_family, socktype, 0);
		if (s != SOCK_ERR) {
			switch ((*sal)->sa_family) {
#if defined( HAVE_GETADDRINFO ) && defined( HAVE_IPV6 )
				case AF_INET6:
					{
						struct sockaddr_in6 *sa =
							(struct sockaddr_in6 *)*sal;

						sa->sin6_family = (*sal)->sa_family;
						sa->sin6_port = htons(port);
						if (php_connect_nonb(s, (struct sockaddr *) sa,
									sizeof(*sa), timeout ? &timeoutval : NULL) != SOCK_CONN_ERR)
							goto ok;
					} 
					break;
#endif
				case AF_INET:
					{
						struct sockaddr_in *sa =
							(struct sockaddr_in *)*sal;

						sa->sin_family = (*sal)->sa_family;
						sa->sin_port = htons(port);
						if (php_connect_nonb(s, (struct sockaddr *) sa,
									sizeof(*sa), timeout ? &timeoutval : NULL) != SOCK_CONN_ERR)
							goto ok;

					} 
					break;
			}
			close (s);
		}
		sal++;
		if (repeatto) {
			timeoutval.tv_sec = timeout;
			timeoutval.tv_usec = 0;
		}
	}
	php_network_freeaddresses(psal);
	php_error(E_WARNING, "php_hostconnect: connect failed");
	return -1;

 ok:
	php_network_freeaddresses(psal);
	return s;
}
/* }}} */

/* {{{ php_any_addr
 * Fills the any (wildcard) address into php_sockaddr_storage
 */
void php_any_addr(int family, php_sockaddr_storage *addr, unsigned short port)
{
	memset(addr, 0, sizeof(php_sockaddr_storage));
	switch (family) {
#ifdef 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 = INADDR_ANY;
		break;
	}
	}
}
/* }}} */

/* {{{ php_sockaddr_size
 * Returns the size of struct sockaddr_xx for the family
 */
int php_sockaddr_size(php_sockaddr_storage *addr)
{
	switch (((struct sockaddr *)addr)->sa_family) {
	case AF_INET:
		return sizeof(struct sockaddr_in);
#ifdef 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;
	}
}
/* }}} */

PHPAPI php_stream *_php_stream_sock_open_from_socket(int socket, int persistent STREAMS_DC TSRMLS_DC)
{
	php_stream *stream;
	php_netstream_data_t *sock;

	sock = pemalloc(sizeof(php_netstream_data_t), persistent);
	memset(sock, 0, sizeof(php_netstream_data_t));

	sock->is_blocked = 1;
	sock->chunk_size = FG(def_chunk_size);
	sock->timeout.tv_sec = -1;
	sock->socket = socket;

	stream = php_stream_alloc_rel(&php_stream_socket_ops, sock, persistent, "r+");

	if (stream == NULL)	
		pefree(sock, persistent);

	return stream;
}

PHPAPI php_stream *_php_stream_sock_open_host(const char *host, unsigned short port,
		int socktype, int timeout, int persistent STREAMS_DC TSRMLS_DC)
{
	int socket;

	socket = php_hostconnect(host, port, socktype, timeout);

	if (socket == -1)
		return NULL;

	return php_stream_sock_open_from_socket_rel(socket, persistent);
}

PHPAPI php_stream *_php_stream_sock_open_unix(const char *path, int pathlen, int persistent,
		struct timeval *timeout STREAMS_DC TSRMLS_DC)
{
#if defined(AF_UNIX)
	int socketd;
	struct  sockaddr_un unix_addr;

	socketd = socket(PF_UNIX, SOCK_STREAM, 0);
	if (socketd == SOCK_ERR)
		return NULL;

	memset(&unix_addr, 0, sizeof(unix_addr));
	unix_addr.sun_family = AF_UNIX;

	/* we need to be binary safe on systems that support an abstract
	 * namespace */
	if (pathlen >= sizeof(unix_addr.sun_path)) {
		/* On linux, when the path begins with a NUL byte we are
		 * referring to an abstract namespace.  In theory we should
		 * allow an extra byte below, since we don't need the NULL.
		 * BUT, to get into this branch of code, the name is too long,
		 * so we don't care. */
		pathlen = sizeof(unix_addr.sun_path) - 1;
	}
	
	memcpy(unix_addr.sun_path, path, pathlen);

	if (php_connect_nonb(socketd, (struct sockaddr *) &unix_addr, sizeof(unix_addr), timeout) == SOCK_CONN_ERR) 
		return NULL;

	return php_stream_sock_open_from_socket_rel(socketd, persistent);
#else
	return NULL;
#endif
}

#if HAVE_OPENSSL_EXT
PHPAPI int php_stream_sock_ssl_activate_with_method(php_stream *stream, int activate, SSL_METHOD *method TSRMLS_DC)
{
	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
	SSL_CTX *ctx = NULL;

	if (!php_stream_is(stream, PHP_STREAM_IS_SOCKET))
		return FAILURE;
	
	if (activate == sock->ssl_active)
		return SUCCESS;	/* already in desired mode */
	
	if (activate && sock->ssl_handle == NULL)	{
		ctx = SSL_CTX_new(method);
		if (ctx == NULL)
			return FAILURE;

		sock->ssl_handle = SSL_new(ctx);
		if (sock->ssl_handle == NULL)	{
			SSL_CTX_free(ctx);
			return FAILURE;
		}
		
		SSL_set_fd(sock->ssl_handle, sock->socket);
	}

	if (activate)	{
		if (SSL_connect(sock->ssl_handle) <= 0)	{
			SSL_shutdown(sock->ssl_handle);
			return FAILURE;
		}
		sock->ssl_active = activate;
	}
	else	{
		SSL_shutdown(sock->ssl_handle);
		sock->ssl_active = 0;
	}
	return SUCCESS;
}
#endif

PHPAPI void php_stream_sock_set_timeout(php_stream *stream, struct timeval *timeout TSRMLS_DC)
{
	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;

	if (!php_stream_is(stream, PHP_STREAM_IS_SOCKET))
		return;
	
	sock->timeout = *timeout;
	sock->timeout_event = 0;
}

PHPAPI int php_stream_sock_set_blocking(php_stream *stream, int mode TSRMLS_DC)
{
	int oldmode;
	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;

	if (!php_stream_is(stream, PHP_STREAM_IS_SOCKET))
		return 0;
	
	oldmode = sock->is_blocked;
	sock->is_blocked = mode;

	return oldmode;
}

PHPAPI size_t php_stream_sock_set_chunk_size(php_stream *stream, size_t size TSRMLS_DC)
{
	size_t oldsize;
	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;

	if (!php_stream_is(stream, PHP_STREAM_IS_SOCKET))
		return 0;
	
	oldsize = sock->chunk_size;
	sock->chunk_size = size;

	return oldsize;
}

#define TOREAD(sock) ((sock)->writepos - (sock)->readpos)
#define READPTR(sock) ((sock)->readbuf + (sock)->readpos)
#define WRITEPTR(sock) ((sock)->readbuf + (sock)->writepos)

static size_t php_sockop_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC)
{
	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
	size_t didwrite;
	
#if HAVE_OPENSSL_EXT
	if (sock->ssl_active)
		didwrite = SSL_write(sock->ssl_handle, buf, count);
	else
#endif
	didwrite = send(sock->socket, buf, count, 0);
	
	php_stream_notify_progress_increment(stream->context, didwrite, 0);

	return didwrite;
}

#if ZEND_DEBUG && DEBUG_MAIN_NETWORK
static inline void dump_sock_state(char *msg, php_netstream_data_t *sock TSRMLS_DC)
{
	printf("%s: blocked=%d timeout_event=%d eof=%d inbuf=%d timeout=%d\n", msg, sock->is_blocked, sock->timeout_event, sock->eof, TOREAD(sock), sock->timeout);
}
# define DUMP_SOCK_STATE(msg, sock)	dump_sock_state(msg, sock TSRMLS_CC)
#else
# define DUMP_SOCK_STATE(msg, sock)	/* nothing */
#endif

static void php_sock_stream_wait_for_data(php_stream *stream, php_netstream_data_t *sock TSRMLS_DC)
{
	fd_set fdr, tfdr;
	int retval;
	struct timeval timeout, *ptimeout;

	FD_ZERO(&fdr);
	FD_SET(sock->socket, &fdr);
	sock->timeout_event = 0;

	if (sock->timeout.tv_sec == -1)
		ptimeout = NULL;
	else
		ptimeout = &timeout;

	
	while(1) {
		tfdr = fdr;
		timeout = sock->timeout;

DUMP_SOCK_STATE("wait_for_data", sock);

		retval = select(sock->socket + 1, &tfdr, NULL, NULL, ptimeout);

		if (retval == 0)
			sock->timeout_event = 1;

		if (retval >= 0)
			break;
	}
DUMP_SOCK_STATE("wait_for_data: done", sock);
}


static size_t php_sock_stream_read_internal(php_stream *stream, php_netstream_data_t *sock TSRMLS_DC)
{
	char buf[PHP_SOCK_CHUNK_SIZE];
	int nr_bytes;
	size_t nr_read = 0;
	
	/* For blocking sockets, we wait until there is some
	   data to read (real data or EOF)

	   Otherwise, recv() may time out and return 0 and
	   therefore sock->eof would be set errornously.
	 */

DUMP_SOCK_STATE("read_internal entry", sock);

	if(sock->is_blocked) {
		php_sock_stream_wait_for_data(stream, sock TSRMLS_CC);
		if (sock->timeout_event)
			return 0;
	}

DUMP_SOCK_STATE("read_internal about to recv/SSL_read", sock);

	/* read at a maximum sock->chunk_size */
#if HAVE_OPENSSL_EXT
	if (sock->ssl_active)
		nr_bytes = SSL_read(sock->ssl_handle, buf, sock->chunk_size);
	else
#endif
	nr_bytes = recv(sock->socket, buf, sock->chunk_size, 0);
DUMP_SOCK_STATE("read_internal after recv/SSL_read", sock);

#if DEBUG_MAIN_NETWORK
printf("read_internal read %d/%d bytes\n", nr_bytes, sock->chunk_size);
#endif

	if(nr_bytes > 0) {

		php_stream_notify_progress_increment(stream->context, nr_bytes, 0);
		
		/* try to avoid an ever-expanding buffer */
		if (sock->readpos > 0) {
			memmove(sock->readbuf, READPTR(sock), sock->readbuflen - sock->readpos);
			sock->writepos -= sock->readpos;
			sock->readpos = 0;
		}
		
		if(sock->writepos + nr_bytes > sock->readbuflen) {
			sock->readbuflen += sock->chunk_size;
			sock->readbuf = perealloc(sock->readbuf, sock->readbuflen,
					php_stream_is_persistent(stream));
		}
		memcpy(WRITEPTR(sock), buf, nr_bytes);
		sock->writepos += nr_bytes;
		nr_read = nr_bytes;
	} else if(nr_bytes == 0 || (nr_bytes < 0 && errno != EWOULDBLOCK)) {
		sock->eof = 1;
	}

	return nr_read;

}

static size_t php_sock_stream_read(php_stream *stream, php_netstream_data_t *sock TSRMLS_DC)
{
	size_t nr_bytes;
	size_t nr_read = 0;
	int i;

	for(i = 0; !sock->eof && i < MAX_CHUNKS_PER_READ; i++) {
DUMP_SOCK_STATE("read about to read_internal", sock);
		nr_bytes = php_sock_stream_read_internal(stream, sock TSRMLS_CC);
		if(nr_bytes == 0)
			break;
		
		
		nr_read += nr_bytes;
	}

	return nr_read;
}

static size_t php_sockop_read(php_stream *stream, char *buf, size_t count TSRMLS_DC)
{
	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
	size_t ret = 0;

	if (buf == NULL && count == 0) {
		/* check for EOF condition */
DUMP_SOCK_STATE("check for EOF", sock);
		
		if (sock->eof)
			return EOF;
		
		if (TOREAD(sock))
			return 0;

		/* no data in the buffer - lets examine the socket */
#if HAVE_SYS_POLL_H
		{
			struct pollfd topoll;
			
			topoll.fd = sock->socket;
			topoll.events = POLLIN;
			topoll.revents = 0;
			
			if (poll(&topoll, 1, 0) == 1) {
				return topoll.revents & POLLHUP ? EOF : 0;
			}
		}
#endif

		/* in the absence of other methods of checking if the
		 * socket is still active, try to read a chunk of data */
		sock->timeout_event = 0;
		php_sock_stream_read_internal(stream, sock TSRMLS_CC);
		
		if (sock->timeout_event || sock->eof)
			return EOF;
		
		return 0;
	}
	
	if (sock->is_blocked) {
		sock->timeout_event = 0;
		while(!sock->eof && TOREAD(sock) < count && !sock->timeout_event)
			if (php_sock_stream_read_internal(stream, sock TSRMLS_CC) == 0)
				break;
	} else {
		php_sock_stream_read(stream, sock TSRMLS_CC);
	}

	if(count < 0)
		return ret;

	ret = MIN(TOREAD(sock), count);
	if (ret) {
		memcpy(buf, READPTR(sock), ret);
		sock->readpos += ret;
	}
#if DEBUG_MAIN_NETWORK
	DUMP_SOCK_STATE("sockop_read", sock);
	printf("sockop_read returning with %d bytes read\n", ret);
#endif
	return ret;
}

static int php_sockop_close(php_stream *stream, int close_handle TSRMLS_DC)
{
	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;

	if (close_handle) {
#if HAVE_OPENSSL_EXT
		if (sock->ssl_active) {
			SSL_shutdown(sock->ssl_handle);
			sock->ssl_active = 0;
		}
		if (sock->ssl_handle) {
			SSL_free(sock->ssl_handle);
			sock->ssl_handle = NULL;
		}
#endif

		shutdown(sock->socket, 0);
		closesocket(sock->socket);

	}
	if (sock->readbuf)
		pefree(sock->readbuf, php_stream_is_persistent(stream));

	pefree(sock, php_stream_is_persistent(stream));
	
	return 0;
}

static int php_sockop_flush(php_stream *stream TSRMLS_DC)
{
	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
	return fsync(sock->socket);
}

static int php_sockop_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC)
{
	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
	return fstat(sock->socket, &ssb->sb);
}

static int php_sockop_cast(php_stream *stream, int castas, void **ret TSRMLS_DC)
{
	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;

	switch(castas)	{
		case PHP_STREAM_AS_STDIO:
#if HAVE_OPENSSL_EXT
			if (sock->ssl_active)
				return FAILURE;
#endif
			if (ret)	{
				/* DANGER!: data buffered in stream->readbuf will be forgotten! */
				if (TOREAD(sock) > 0)
					zend_error(E_WARNING, "%s(): %d bytes of buffered data lost during conversion to FILE*!", get_active_function_name(TSRMLS_C), TOREAD(sock));
				*ret = fdopen(sock->socket, stream->mode);
				if (*ret)
					return SUCCESS;
				return FAILURE;
			}
			return SUCCESS;
		case PHP_STREAM_AS_FD:
		case PHP_STREAM_AS_SOCKETD:
#if HAVE_OPENSSL_EXT
			if (sock->ssl_active)
				return FAILURE;
#endif
			if (ret)
				*ret = (void*)sock->socket;
			return SUCCESS;
		default:
			return FAILURE;
	}
}

#define SEARCHCR() do {												\
	if (TOREAD(sock)) {												\
		for (p = READPTR(sock), pe = p + MIN(TOREAD(sock), maxlen);	\
				*p != '\n'; ) 										\
			if (++p >= pe) { 										\
				p = NULL; 											\
				break; 												\
			}														\
	} else															\
		p = NULL;													\
} while (0)


static char *php_sockop_gets(php_stream *stream, char *buf, size_t maxlen TSRMLS_DC)
{
	php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract;
	char *p = NULL, *pe;
	char *ret = NULL;
	size_t amount = 0;

	if (maxlen==0) {
		buf[0] = 0;
		return buf;
	}

	SEARCHCR();

	if(!p) {
		if(sock->is_blocked) {
			sock->timeout_event = 0;
			
			while(!p && !sock->eof && !sock->timeout_event && TOREAD(sock) < maxlen) {
				php_sock_stream_read_internal(stream, sock TSRMLS_CC);
				SEARCHCR();
			}
		} else {
			php_sock_stream_read(stream, sock TSRMLS_CC);
			SEARCHCR();
		}
	}

	if(p) {
 		amount = (ptrdiff_t) p - (ptrdiff_t) READPTR(sock) + 1;
	} else {
		amount = TOREAD(sock);
	}

	amount = MIN(amount, maxlen);

	if(amount > 0) {
		memcpy(buf, READPTR(sock), amount);
		sock->readpos += amount;
	}
	buf[amount] = '\0';

	/* signal error only, if we don't return data from this call and
	   if there is no data to read and if the eof flag is set */
	if(amount || TOREAD(sock) || !sock->eof) {
		ret = buf;
	}

	return ret;
}

php_stream_ops php_stream_socket_ops = {
	php_sockop_write, php_sockop_read,
	php_sockop_close, php_sockop_flush,
	"socket",
	NULL, php_sockop_gets,
	php_sockop_cast,
	php_sockop_stat
};




/*
 * Local variables:
 * tab-width: 8
 * c-basic-offset: 8
 * End:
 * vim600: sw=4 ts=4 fdm=marker
 * vim<600: sw=4 ts=4
 */