xref: /PHP-8.0/ext/ftp/ftp.c (revision 42c72ef4)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | http://www.php.net/license/3_01.txt                                  |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Authors: Andrew Skalski <askalski@chek.com>                          |
14    |          Stefan Esser <sesser@php.net> (resume functions)            |
15    +----------------------------------------------------------------------+
16  */
17 
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21 
22 #include "php.h"
23 
24 #include <stdio.h>
25 #include <ctype.h>
26 #include <stdlib.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #include <fcntl.h>
31 #include <string.h>
32 #include <time.h>
33 #ifdef PHP_WIN32
34 #include <winsock2.h>
35 #else
36 #ifdef HAVE_SYS_TYPES_H
37 #include <sys/types.h>
38 #endif
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42 #include <netdb.h>
43 #endif
44 #include <errno.h>
45 
46 #ifdef HAVE_SYS_TIME_H
47 #include <sys/time.h>
48 #endif
49 
50 #ifdef HAVE_SYS_SELECT_H
51 #include <sys/select.h>
52 #endif
53 
54 #ifdef HAVE_FTP_SSL
55 #include <openssl/ssl.h>
56 #include <openssl/err.h>
57 #endif
58 
59 #include "ftp.h"
60 #include "ext/standard/fsock.h"
61 
62 #ifdef PHP_WIN32
63 # undef ETIMEDOUT
64 # define ETIMEDOUT WSAETIMEDOUT
65 #endif
66 
67 /* sends an ftp command, returns true on success, false on error.
68  * it sends the string "cmd args\r\n" if args is non-null, or
69  * "cmd\r\n" if args is null
70  */
71 static int		ftp_putcmd(	ftpbuf_t *ftp,
72 					const char *cmd,
73 					const size_t cmd_len,
74 					const char *args,
75 					const size_t args_len);
76 
77 /* wrapper around send/recv to handle timeouts */
78 static int		my_send(ftpbuf_t *ftp, php_socket_t s, void *buf, size_t len);
79 static int		my_recv(ftpbuf_t *ftp, php_socket_t s, void *buf, size_t len);
80 static int		my_accept(ftpbuf_t *ftp, php_socket_t s, struct sockaddr *addr, socklen_t *addrlen);
81 
82 /* reads a line the socket , returns true on success, false on error */
83 static int		ftp_readline(ftpbuf_t *ftp);
84 
85 /* reads an ftp response, returns true on success, false on error */
86 static int		ftp_getresp(ftpbuf_t *ftp);
87 
88 /* sets the ftp transfer type */
89 static int		ftp_type(ftpbuf_t *ftp, ftptype_t type);
90 
91 /* opens up a data stream */
92 static databuf_t*	ftp_getdata(ftpbuf_t *ftp);
93 
94 /* accepts the data connection, returns updated data buffer */
95 static databuf_t*	data_accept(databuf_t *data, ftpbuf_t *ftp);
96 
97 /* closes the data connection, returns NULL */
98 static databuf_t*	data_close(ftpbuf_t *ftp, databuf_t *data);
99 
100 /* generic file lister */
101 static char**		ftp_genlist(ftpbuf_t *ftp, const char *cmd, const size_t cmd_len, const char *path, const size_t path_len);
102 
103 #ifdef HAVE_FTP_SSL
104 /* shuts down a TLS/SSL connection */
105 static void		ftp_ssl_shutdown(ftpbuf_t *ftp, php_socket_t fd, SSL *ssl_handle);
106 #endif
107 
108 /* IP and port conversion box */
109 union ipbox {
110 	struct in_addr	ia[2];
111 	unsigned short	s[4];
112 	unsigned char	c[8];
113 };
114 
115 /* {{{ ftp_open */
116 ftpbuf_t*
ftp_open(const char * host,short port,zend_long timeout_sec)117 ftp_open(const char *host, short port, zend_long timeout_sec)
118 {
119 	ftpbuf_t		*ftp;
120 	socklen_t		 size;
121 	struct timeval tv;
122 
123 
124 	/* alloc the ftp structure */
125 	ftp = ecalloc(1, sizeof(*ftp));
126 
127 	tv.tv_sec = timeout_sec;
128 	tv.tv_usec = 0;
129 
130 	ftp->fd = php_network_connect_socket_to_host(host,
131 			(unsigned short) (port ? port : 21), SOCK_STREAM,
132 			0, &tv, NULL, NULL, NULL, 0, STREAM_SOCKOP_NONE);
133 	if (ftp->fd == -1) {
134 		goto bail;
135 	}
136 
137 	/* Default Settings */
138 	ftp->timeout_sec = timeout_sec;
139 	ftp->nb = 0;
140 
141 	size = sizeof(ftp->localaddr);
142 	memset(&ftp->localaddr, 0, size);
143 	if (getsockname(ftp->fd, (struct sockaddr*) &ftp->localaddr, &size) != 0) {
144 		php_error_docref(NULL, E_WARNING, "getsockname failed: %s (%d)", strerror(errno), errno);
145 		goto bail;
146 	}
147 
148 	if (!ftp_getresp(ftp) || ftp->resp != 220) {
149 		goto bail;
150 	}
151 
152 	return ftp;
153 
154 bail:
155 	if (ftp->fd != -1) {
156 		closesocket(ftp->fd);
157 	}
158 	efree(ftp);
159 	return NULL;
160 }
161 /* }}} */
162 
163 /* {{{ ftp_close */
164 ftpbuf_t*
ftp_close(ftpbuf_t * ftp)165 ftp_close(ftpbuf_t *ftp)
166 {
167 	if (ftp == NULL) {
168 		return NULL;
169 	}
170 	if (ftp->data) {
171 		data_close(ftp, ftp->data);
172 	}
173 	if (ftp->stream && ftp->closestream) {
174 			php_stream_close(ftp->stream);
175 	}
176 	if (ftp->fd != -1) {
177 #ifdef HAVE_FTP_SSL
178 		if (ftp->ssl_active) {
179 			ftp_ssl_shutdown(ftp, ftp->fd, ftp->ssl_handle);
180 		}
181 #endif
182 		closesocket(ftp->fd);
183 	}
184 	ftp_gc(ftp);
185 	efree(ftp);
186 	return NULL;
187 }
188 /* }}} */
189 
190 /* {{{ ftp_gc */
191 void
ftp_gc(ftpbuf_t * ftp)192 ftp_gc(ftpbuf_t *ftp)
193 {
194 	if (ftp == NULL) {
195 		return;
196 	}
197 	if (ftp->pwd) {
198 		efree(ftp->pwd);
199 		ftp->pwd = NULL;
200 	}
201 	if (ftp->syst) {
202 		efree(ftp->syst);
203 		ftp->syst = NULL;
204 	}
205 }
206 /* }}} */
207 
208 /* {{{ ftp_quit */
209 int
ftp_quit(ftpbuf_t * ftp)210 ftp_quit(ftpbuf_t *ftp)
211 {
212 	if (ftp == NULL) {
213 		return 0;
214 	}
215 
216 	if (!ftp_putcmd(ftp, "QUIT", sizeof("QUIT")-1, NULL, (size_t) 0)) {
217 		return 0;
218 	}
219 	if (!ftp_getresp(ftp) || ftp->resp != 221) {
220 		return 0;
221 	}
222 
223 	if (ftp->pwd) {
224 		efree(ftp->pwd);
225 		ftp->pwd = NULL;
226 	}
227 
228 	return 1;
229 }
230 /* }}} */
231 
232 /* {{{ ftp_login */
233 int
ftp_login(ftpbuf_t * ftp,const char * user,const size_t user_len,const char * pass,const size_t pass_len)234 ftp_login(ftpbuf_t *ftp, const char *user, const size_t user_len, const char *pass, const size_t pass_len)
235 {
236 #ifdef HAVE_FTP_SSL
237 	SSL_CTX	*ctx = NULL;
238 	long ssl_ctx_options = SSL_OP_ALL;
239 	int err, res;
240 	zend_bool retry;
241 #endif
242 	if (ftp == NULL) {
243 		return 0;
244 	}
245 
246 #ifdef HAVE_FTP_SSL
247 	if (ftp->use_ssl && !ftp->ssl_active) {
248 		if (!ftp_putcmd(ftp, "AUTH", sizeof("AUTH")-1, "TLS", sizeof("TLS")-1)) {
249 			return 0;
250 		}
251 		if (!ftp_getresp(ftp)) {
252 			return 0;
253 		}
254 
255 		if (ftp->resp != 234) {
256 			if (!ftp_putcmd(ftp, "AUTH", sizeof("AUTH")-1, "SSL", sizeof("SSL")-1)) {
257 				return 0;
258 			}
259 			if (!ftp_getresp(ftp)) {
260 				return 0;
261 			}
262 
263 			if (ftp->resp != 334) {
264 				return 0;
265 			} else {
266 				ftp->old_ssl = 1;
267 				ftp->use_ssl_for_data = 1;
268 			}
269 		}
270 
271 		ctx = SSL_CTX_new(SSLv23_client_method());
272 		if (ctx == NULL) {
273 			php_error_docref(NULL, E_WARNING, "Failed to create the SSL context");
274 			return 0;
275 		}
276 
277 #if OPENSSL_VERSION_NUMBER >= 0x0090605fL
278 		ssl_ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
279 #endif
280 		SSL_CTX_set_options(ctx, ssl_ctx_options);
281 
282 		/* allow SSL to re-use sessions */
283 		SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_BOTH);
284 
285 		ftp->ssl_handle = SSL_new(ctx);
286 		SSL_CTX_free(ctx);
287 
288 		if (ftp->ssl_handle == NULL) {
289 			php_error_docref(NULL, E_WARNING, "Failed to create the SSL handle");
290 			return 0;
291 		}
292 
293 		SSL_set_fd(ftp->ssl_handle, ftp->fd);
294 
295 		do {
296 			res = SSL_connect(ftp->ssl_handle);
297 			err = SSL_get_error(ftp->ssl_handle, res);
298 
299 			/* TODO check if handling other error codes would make sense */
300 			switch (err) {
301 				case SSL_ERROR_NONE:
302 					retry = 0;
303 					break;
304 
305 				case SSL_ERROR_ZERO_RETURN:
306 					retry = 0;
307 					SSL_shutdown(ftp->ssl_handle);
308 					break;
309 
310 				case SSL_ERROR_WANT_READ:
311 				case SSL_ERROR_WANT_WRITE: {
312 						php_pollfd p;
313 						int i;
314 
315 						p.fd = ftp->fd;
316 						p.events = (err == SSL_ERROR_WANT_READ) ? (POLLIN|POLLPRI) : POLLOUT;
317 						p.revents = 0;
318 
319 						i = php_poll2(&p, 1, 300);
320 
321 						retry = i > 0;
322 					}
323 					break;
324 
325 				default:
326 					php_error_docref(NULL, E_WARNING, "SSL/TLS handshake failed");
327 					SSL_shutdown(ftp->ssl_handle);
328 					SSL_free(ftp->ssl_handle);
329 					return 0;
330 			}
331 		} while (retry);
332 
333 		ftp->ssl_active = 1;
334 
335 		if (!ftp->old_ssl) {
336 
337 			/* set protection buffersize to zero */
338 			if (!ftp_putcmd(ftp, "PBSZ", sizeof("PBSZ")-1, "0", sizeof("0")-1)) {
339 				return 0;
340 			}
341 			if (!ftp_getresp(ftp)) {
342 				return 0;
343 			}
344 
345 			/* enable data conn encryption */
346 			if (!ftp_putcmd(ftp, "PROT", sizeof("PROT")-1, "P", sizeof("P")-1)) {
347 				return 0;
348 			}
349 			if (!ftp_getresp(ftp)) {
350 				return 0;
351 			}
352 
353 			ftp->use_ssl_for_data = (ftp->resp >= 200 && ftp->resp <=299);
354 		}
355 	}
356 #endif
357 
358 	if (!ftp_putcmd(ftp, "USER", sizeof("USER")-1, user, user_len)) {
359 		return 0;
360 	}
361 	if (!ftp_getresp(ftp)) {
362 		return 0;
363 	}
364 	if (ftp->resp == 230) {
365 		return 1;
366 	}
367 	if (ftp->resp != 331) {
368 		return 0;
369 	}
370 	if (!ftp_putcmd(ftp, "PASS", sizeof("PASS")-1, pass, pass_len)) {
371 		return 0;
372 	}
373 	if (!ftp_getresp(ftp)) {
374 		return 0;
375 	}
376 	return (ftp->resp == 230);
377 }
378 /* }}} */
379 
380 /* {{{ ftp_reinit */
381 int
ftp_reinit(ftpbuf_t * ftp)382 ftp_reinit(ftpbuf_t *ftp)
383 {
384 	if (ftp == NULL) {
385 		return 0;
386 	}
387 
388 	ftp_gc(ftp);
389 
390 	ftp->nb = 0;
391 
392 	if (!ftp_putcmd(ftp, "REIN", sizeof("REIN")-1, NULL, (size_t) 0)) {
393 		return 0;
394 	}
395 	if (!ftp_getresp(ftp) || ftp->resp != 220) {
396 		return 0;
397 	}
398 
399 	return 1;
400 }
401 /* }}} */
402 
403 /* {{{ ftp_syst */
404 const char*
ftp_syst(ftpbuf_t * ftp)405 ftp_syst(ftpbuf_t *ftp)
406 {
407 	char *syst, *end;
408 
409 	if (ftp == NULL) {
410 		return NULL;
411 	}
412 
413 	/* default to cached value */
414 	if (ftp->syst) {
415 		return ftp->syst;
416 	}
417 	if (!ftp_putcmd(ftp, "SYST", sizeof("SYST")-1, NULL, (size_t) 0)) {
418 		return NULL;
419 	}
420 	if (!ftp_getresp(ftp) || ftp->resp != 215) {
421 		return NULL;
422 	}
423 	syst = ftp->inbuf;
424 	while (*syst == ' ') {
425 		syst++;
426 	}
427 	if ((end = strchr(syst, ' '))) {
428 		*end = 0;
429 	}
430 	ftp->syst = estrdup(syst);
431 	if (end) {
432 		*end = ' ';
433 	}
434 	return ftp->syst;
435 }
436 /* }}} */
437 
438 /* {{{ ftp_pwd */
439 const char*
ftp_pwd(ftpbuf_t * ftp)440 ftp_pwd(ftpbuf_t *ftp)
441 {
442 	char *pwd, *end;
443 
444 	if (ftp == NULL) {
445 		return NULL;
446 	}
447 
448 	/* default to cached value */
449 	if (ftp->pwd) {
450 		return ftp->pwd;
451 	}
452 	if (!ftp_putcmd(ftp, "PWD", sizeof("PWD")-1, NULL, (size_t) 0)) {
453 		return NULL;
454 	}
455 	if (!ftp_getresp(ftp) || ftp->resp != 257) {
456 		return NULL;
457 	}
458 	/* copy out the pwd from response */
459 	if ((pwd = strchr(ftp->inbuf, '"')) == NULL) {
460 		return NULL;
461 	}
462 	if ((end = strrchr(++pwd, '"')) == NULL) {
463 		return NULL;
464 	}
465 	ftp->pwd = estrndup(pwd, end - pwd);
466 
467 	return ftp->pwd;
468 }
469 /* }}} */
470 
471 /* {{{ ftp_exec */
472 int
ftp_exec(ftpbuf_t * ftp,const char * cmd,const size_t cmd_len)473 ftp_exec(ftpbuf_t *ftp, const char *cmd, const size_t cmd_len)
474 {
475 	if (ftp == NULL) {
476 		return 0;
477 	}
478 	if (!ftp_putcmd(ftp, "SITE EXEC", sizeof("SITE EXEC")-1, cmd, cmd_len)) {
479 		return 0;
480 	}
481 	if (!ftp_getresp(ftp) || ftp->resp != 200) {
482 		return 0;
483 	}
484 
485 	return 1;
486 }
487 /* }}} */
488 
489 /* {{{ ftp_raw */
490 void
ftp_raw(ftpbuf_t * ftp,const char * cmd,const size_t cmd_len,zval * return_value)491 ftp_raw(ftpbuf_t *ftp, const char *cmd, const size_t cmd_len, zval *return_value)
492 {
493 	if (ftp == NULL || cmd == NULL) {
494 		RETURN_NULL();
495 	}
496 	if (!ftp_putcmd(ftp, cmd, cmd_len, NULL, (size_t) 0)) {
497 		RETURN_NULL();
498 	}
499 	array_init(return_value);
500 	while (ftp_readline(ftp)) {
501 		add_next_index_string(return_value, ftp->inbuf);
502 		if (isdigit(ftp->inbuf[0]) && isdigit(ftp->inbuf[1]) && isdigit(ftp->inbuf[2]) && ftp->inbuf[3] == ' ') {
503 			return;
504 		}
505 	}
506 }
507 /* }}} */
508 
509 /* {{{ ftp_chdir */
510 int
ftp_chdir(ftpbuf_t * ftp,const char * dir,const size_t dir_len)511 ftp_chdir(ftpbuf_t *ftp, const char *dir, const size_t dir_len)
512 {
513 	if (ftp == NULL) {
514 		return 0;
515 	}
516 
517 	if (ftp->pwd) {
518 		efree(ftp->pwd);
519 		ftp->pwd = NULL;
520 	}
521 
522 	if (!ftp_putcmd(ftp, "CWD", sizeof("CWD")-1, dir, dir_len)) {
523 		return 0;
524 	}
525 	if (!ftp_getresp(ftp) || ftp->resp != 250) {
526 		return 0;
527 	}
528 	return 1;
529 }
530 /* }}} */
531 
532 /* {{{ ftp_cdup */
533 int
ftp_cdup(ftpbuf_t * ftp)534 ftp_cdup(ftpbuf_t *ftp)
535 {
536 	if (ftp == NULL) {
537 		return 0;
538 	}
539 
540 	if (ftp->pwd) {
541 		efree(ftp->pwd);
542 		ftp->pwd = NULL;
543 	}
544 
545 	if (!ftp_putcmd(ftp, "CDUP", sizeof("CDUP")-1, NULL, (size_t) 0)) {
546 		return 0;
547 	}
548 	if (!ftp_getresp(ftp) || ftp->resp != 250) {
549 		return 0;
550 	}
551 	return 1;
552 }
553 /* }}} */
554 
555 /* {{{ ftp_mkdir */
556 zend_string*
ftp_mkdir(ftpbuf_t * ftp,const char * dir,const size_t dir_len)557 ftp_mkdir(ftpbuf_t *ftp, const char *dir, const size_t dir_len)
558 {
559 	char *mkd, *end;
560 	zend_string *ret;
561 
562 	if (ftp == NULL) {
563 		return NULL;
564 	}
565 	if (!ftp_putcmd(ftp, "MKD", sizeof("MKD")-1, dir, dir_len)) {
566 		return NULL;
567 	}
568 	if (!ftp_getresp(ftp) || ftp->resp != 257) {
569 		return NULL;
570 	}
571 	/* copy out the dir from response */
572 	if ((mkd = strchr(ftp->inbuf, '"')) == NULL) {
573 		return zend_string_init(dir, dir_len, 0);
574 	}
575 	if ((end = strrchr(++mkd, '"')) == NULL) {
576 		return NULL;
577 	}
578 	*end = 0;
579 	ret = zend_string_init(mkd, end - mkd, 0);
580 	*end = '"';
581 
582 	return ret;
583 }
584 /* }}} */
585 
586 /* {{{ ftp_rmdir */
587 int
ftp_rmdir(ftpbuf_t * ftp,const char * dir,const size_t dir_len)588 ftp_rmdir(ftpbuf_t *ftp, const char *dir, const size_t dir_len)
589 {
590 	if (ftp == NULL) {
591 		return 0;
592 	}
593 	if (!ftp_putcmd(ftp, "RMD", sizeof("RMD")-1, dir, dir_len)) {
594 		return 0;
595 	}
596 	if (!ftp_getresp(ftp) || ftp->resp != 250) {
597 		return 0;
598 	}
599 	return 1;
600 }
601 /* }}} */
602 
603 /* {{{ ftp_chmod */
604 int
ftp_chmod(ftpbuf_t * ftp,const int mode,const char * filename,const int filename_len)605 ftp_chmod(ftpbuf_t *ftp, const int mode, const char *filename, const int filename_len)
606 {
607 	char *buffer;
608 	size_t buffer_len;
609 
610 	if (ftp == NULL || filename_len <= 0) {
611 		return 0;
612 	}
613 
614 	buffer_len = spprintf(&buffer, 0, "CHMOD %o %s", mode, filename);
615 
616 	if (!buffer) {
617 		return 0;
618 	}
619 
620 	if (!ftp_putcmd(ftp, "SITE", sizeof("SITE")-1, buffer, buffer_len)) {
621 		efree(buffer);
622 		return 0;
623 	}
624 
625 	efree(buffer);
626 
627 	if (!ftp_getresp(ftp) || ftp->resp != 200) {
628 		return 0;
629 	}
630 
631 	return 1;
632 }
633 /* }}} */
634 
635 /* {{{ ftp_alloc */
636 int
ftp_alloc(ftpbuf_t * ftp,const zend_long size,zend_string ** response)637 ftp_alloc(ftpbuf_t *ftp, const zend_long size, zend_string **response)
638 {
639 	char buffer[64];
640 	int buffer_len;
641 
642 	if (ftp == NULL || size <= 0) {
643 		return 0;
644 	}
645 
646 	buffer_len = snprintf(buffer, sizeof(buffer) - 1, ZEND_LONG_FMT, size);
647 
648 	if (buffer_len < 0) {
649 		return 0;
650 	}
651 
652 	if (!ftp_putcmd(ftp, "ALLO", sizeof("ALLO")-1, buffer, buffer_len)) {
653 		return 0;
654 	}
655 
656 	if (!ftp_getresp(ftp)) {
657 		return 0;
658 	}
659 
660 	if (response) {
661 		*response = zend_string_init(ftp->inbuf, strlen(ftp->inbuf), 0);
662 	}
663 
664 	if (ftp->resp < 200 || ftp->resp >= 300) {
665 		return 0;
666 	}
667 
668 	return 1;
669 }
670 /* }}} */
671 
672 /* {{{ ftp_nlist */
673 char**
ftp_nlist(ftpbuf_t * ftp,const char * path,const size_t path_len)674 ftp_nlist(ftpbuf_t *ftp, const char *path, const size_t path_len)
675 {
676 	return ftp_genlist(ftp, "NLST", sizeof("NLST")-1, path, path_len);
677 }
678 /* }}} */
679 
680 /* {{{ ftp_list */
681 char**
ftp_list(ftpbuf_t * ftp,const char * path,const size_t path_len,int recursive)682 ftp_list(ftpbuf_t *ftp, const char *path, const size_t path_len, int recursive)
683 {
684 	return ftp_genlist(ftp, ((recursive) ? "LIST -R" : "LIST"), ((recursive) ? sizeof("LIST -R")-1 : sizeof("LIST")-1), path, path_len);
685 }
686 /* }}} */
687 
688 /* {{{ ftp_mlsd */
689 char**
ftp_mlsd(ftpbuf_t * ftp,const char * path,const size_t path_len)690 ftp_mlsd(ftpbuf_t *ftp, const char *path, const size_t path_len)
691 {
692 	return ftp_genlist(ftp, "MLSD", sizeof("MLSD")-1, path, path_len);
693 }
694 /* }}} */
695 
696 /* {{{ ftp_mlsd_parse_line */
697 int
ftp_mlsd_parse_line(HashTable * ht,const char * input)698 ftp_mlsd_parse_line(HashTable *ht, const char *input) {
699 
700 	zval zstr;
701 	const char *end = input + strlen(input);
702 
703 	const char *sp = memchr(input, ' ', end - input);
704 	if (!sp) {
705 		php_error_docref(NULL, E_WARNING, "Missing pathname in MLSD response");
706 		return FAILURE;
707 	}
708 
709 	/* Extract pathname */
710 	ZVAL_STRINGL(&zstr, sp + 1, end - sp - 1);
711 	zend_hash_str_update(ht, "name", sizeof("name")-1, &zstr);
712 	end = sp;
713 
714 	while (input < end) {
715 		const char *semi, *eq;
716 
717 		/* Find end of fact */
718 		semi = memchr(input, ';', end - input);
719 		if (!semi) {
720 			php_error_docref(NULL, E_WARNING, "Malformed fact in MLSD response");
721 			return FAILURE;
722 		}
723 
724 		/* Separate fact key and value */
725 		eq = memchr(input, '=', semi - input);
726 		if (!eq) {
727 			php_error_docref(NULL, E_WARNING, "Malformed fact in MLSD response");
728 			return FAILURE;
729 		}
730 
731 		ZVAL_STRINGL(&zstr, eq + 1, semi - eq - 1);
732 		zend_hash_str_update(ht, input, eq - input, &zstr);
733 		input = semi + 1;
734 	}
735 
736 	return SUCCESS;
737 }
738 /* }}} */
739 
740 /* {{{ ftp_type */
741 int
ftp_type(ftpbuf_t * ftp,ftptype_t type)742 ftp_type(ftpbuf_t *ftp, ftptype_t type)
743 {
744 	const char *typechar;
745 
746 	if (ftp == NULL) {
747 		return 0;
748 	}
749 	if (type == ftp->type) {
750 		return 1;
751 	}
752 	if (type == FTPTYPE_ASCII) {
753 		typechar = "A";
754 	} else if (type == FTPTYPE_IMAGE) {
755 		typechar = "I";
756 	} else {
757 		return 0;
758 	}
759 	if (!ftp_putcmd(ftp, "TYPE", sizeof("TYPE")-1, typechar, 1)) {
760 		return 0;
761 	}
762 	if (!ftp_getresp(ftp) || ftp->resp != 200) {
763 		return 0;
764 	}
765 	ftp->type = type;
766 
767 	return 1;
768 }
769 /* }}} */
770 
771 /* {{{ ftp_pasv */
772 int
ftp_pasv(ftpbuf_t * ftp,int pasv)773 ftp_pasv(ftpbuf_t *ftp, int pasv)
774 {
775 	char			*ptr;
776 	union ipbox		ipbox;
777 	unsigned long		b[6];
778 	socklen_t			n;
779 	struct sockaddr *sa;
780 	struct sockaddr_in *sin;
781 
782 	if (ftp == NULL) {
783 		return 0;
784 	}
785 	if (pasv && ftp->pasv == 2) {
786 		return 1;
787 	}
788 	ftp->pasv = 0;
789 	if (!pasv) {
790 		return 1;
791 	}
792 	n = sizeof(ftp->pasvaddr);
793 	memset(&ftp->pasvaddr, 0, n);
794 	sa = (struct sockaddr *) &ftp->pasvaddr;
795 
796 	if (getpeername(ftp->fd, sa, &n) < 0) {
797 		return 0;
798 	}
799 
800 #ifdef HAVE_IPV6
801 	if (sa->sa_family == AF_INET6) {
802 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
803 		char *endptr, delimiter;
804 
805 		/* try EPSV first */
806 		if (!ftp_putcmd(ftp, "EPSV", sizeof("EPSV")-1, NULL, (size_t) 0)) {
807 			return 0;
808 		}
809 		if (!ftp_getresp(ftp)) {
810 			return 0;
811 		}
812 		if (ftp->resp == 229) {
813 			/* parse out the port */
814 			for (ptr = ftp->inbuf; *ptr && *ptr != '('; ptr++);
815 			if (!*ptr) {
816 				return 0;
817 			}
818 			delimiter = *++ptr;
819 			for (n = 0; *ptr && n < 3; ptr++) {
820 				if (*ptr == delimiter) {
821 					n++;
822 				}
823 			}
824 
825 			sin6->sin6_port = htons((unsigned short) strtoul(ptr, &endptr, 10));
826 			if (ptr == endptr || *endptr != delimiter) {
827 				return 0;
828 			}
829 			ftp->pasv = 2;
830 			return 1;
831 		}
832 	}
833 
834 	/* fall back to PASV */
835 #endif
836 
837 	if (!ftp_putcmd(ftp, "PASV",  sizeof("PASV")-1, NULL, (size_t) 0)) {
838 		return 0;
839 	}
840 	if (!ftp_getresp(ftp) || ftp->resp != 227) {
841 		return 0;
842 	}
843 	/* parse out the IP and port */
844 	for (ptr = ftp->inbuf; *ptr && !isdigit(*ptr); ptr++);
845 	n = sscanf(ptr, "%lu,%lu,%lu,%lu,%lu,%lu", &b[0], &b[1], &b[2], &b[3], &b[4], &b[5]);
846 	if (n != 6) {
847 		return 0;
848 	}
849 	for (n = 0; n < 6; n++) {
850 		ipbox.c[n] = (unsigned char) b[n];
851 	}
852 	sin = (struct sockaddr_in *) sa;
853 	if (ftp->usepasvaddress) {
854 		sin->sin_addr = ipbox.ia[0];
855 	}
856 	sin->sin_port = ipbox.s[2];
857 
858 	ftp->pasv = 2;
859 
860 	return 1;
861 }
862 /* }}} */
863 
864 /* {{{ ftp_get */
865 int
ftp_get(ftpbuf_t * ftp,php_stream * outstream,const char * path,const size_t path_len,ftptype_t type,zend_long resumepos)866 ftp_get(ftpbuf_t *ftp, php_stream *outstream, const char *path, const size_t path_len, ftptype_t type, zend_long resumepos)
867 {
868 	databuf_t		*data = NULL;
869 	size_t			rcvd;
870 	char			arg[11];
871 
872 	if (ftp == NULL) {
873 		return 0;
874 	}
875 	if (!ftp_type(ftp, type)) {
876 		goto bail;
877 	}
878 
879 	if ((data = ftp_getdata(ftp)) == NULL) {
880 		goto bail;
881 	}
882 
883 	ftp->data = data;
884 
885 	if (resumepos > 0) {
886 		int arg_len = snprintf(arg, sizeof(arg), ZEND_LONG_FMT, resumepos);
887 
888 		if (arg_len < 0) {
889 			goto bail;
890 		}
891 		if (!ftp_putcmd(ftp, "REST", sizeof("REST")-1, arg, arg_len)) {
892 			goto bail;
893 		}
894 		if (!ftp_getresp(ftp) || (ftp->resp != 350)) {
895 			goto bail;
896 		}
897 	}
898 
899 	if (!ftp_putcmd(ftp, "RETR", sizeof("RETR")-1, path, path_len)) {
900 		goto bail;
901 	}
902 	if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125)) {
903 		goto bail;
904 	}
905 
906 	if ((data = data_accept(data, ftp)) == NULL) {
907 		goto bail;
908 	}
909 
910 	while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) {
911 		if (rcvd == (size_t)-1) {
912 			goto bail;
913 		}
914 
915 		if (type == FTPTYPE_ASCII) {
916 #ifndef PHP_WIN32
917 			char *s;
918 #endif
919 			char *ptr = data->buf;
920 			char *e = ptr + rcvd;
921 			/* logic depends on the OS EOL
922 			 * Win32 -> \r\n
923 			 * Everything Else \n
924 			 */
925 #ifdef PHP_WIN32
926 			php_stream_write(outstream, ptr, (e - ptr));
927 			ptr = e;
928 #else
929 			while (e > ptr && (s = memchr(ptr, '\r', (e - ptr)))) {
930 				php_stream_write(outstream, ptr, (s - ptr));
931 				if (*(s + 1) == '\n') {
932 					s++;
933 					php_stream_putc(outstream, '\n');
934 				}
935 				ptr = s + 1;
936 			}
937 #endif
938 			if (ptr < e) {
939 				php_stream_write(outstream, ptr, (e - ptr));
940 			}
941 		} else if (rcvd != php_stream_write(outstream, data->buf, rcvd)) {
942 			goto bail;
943 		}
944 	}
945 
946 	ftp->data = data = data_close(ftp, data);
947 
948 	if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) {
949 		goto bail;
950 	}
951 
952 	return 1;
953 bail:
954 	ftp->data = data_close(ftp, data);
955 	return 0;
956 }
957 /* }}} */
958 
959 /* {{{ ftp_put */
960 int
ftp_put(ftpbuf_t * ftp,const char * path,const size_t path_len,php_stream * instream,ftptype_t type,zend_long startpos)961 ftp_put(ftpbuf_t *ftp, const char *path, const size_t path_len, php_stream *instream, ftptype_t type, zend_long startpos)
962 {
963 	databuf_t		*data = NULL;
964 	zend_long			size;
965 	char			*ptr;
966 	int			ch;
967 	char			arg[11];
968 
969 	if (ftp == NULL) {
970 		return 0;
971 	}
972 	if (!ftp_type(ftp, type)) {
973 		goto bail;
974 	}
975 	if ((data = ftp_getdata(ftp)) == NULL) {
976 		goto bail;
977 	}
978 	ftp->data = data;
979 
980 	if (startpos > 0) {
981 		int arg_len = snprintf(arg, sizeof(arg), ZEND_LONG_FMT, startpos);
982 
983 		if (arg_len < 0) {
984 			goto bail;
985 		}
986 		if (!ftp_putcmd(ftp, "REST", sizeof("REST")-1, arg, arg_len)) {
987 			goto bail;
988 		}
989 		if (!ftp_getresp(ftp) || (ftp->resp != 350)) {
990 			goto bail;
991 		}
992 	}
993 
994 	if (!ftp_putcmd(ftp, "STOR", sizeof("STOR")-1, path, path_len)) {
995 		goto bail;
996 	}
997 	if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125)) {
998 		goto bail;
999 	}
1000 	if ((data = data_accept(data, ftp)) == NULL) {
1001 		goto bail;
1002 	}
1003 
1004 	size = 0;
1005 	ptr = data->buf;
1006 	while (!php_stream_eof(instream) && (ch = php_stream_getc(instream))!=EOF) {
1007 		/* flush if necessary */
1008 		if (FTP_BUFSIZE - size < 2) {
1009 			if (my_send(ftp, data->fd, data->buf, size) != size) {
1010 				goto bail;
1011 			}
1012 			ptr = data->buf;
1013 			size = 0;
1014 		}
1015 
1016 		if (ch == '\n' && type == FTPTYPE_ASCII) {
1017 			*ptr++ = '\r';
1018 			size++;
1019 		}
1020 
1021 		*ptr++ = ch;
1022 		size++;
1023 	}
1024 
1025 	if (size && my_send(ftp, data->fd, data->buf, size) != size) {
1026 		goto bail;
1027 	}
1028 	ftp->data = data = data_close(ftp, data);
1029 
1030 	if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250 && ftp->resp != 200)) {
1031 		goto bail;
1032 	}
1033 	return 1;
1034 bail:
1035 	ftp->data = data_close(ftp, data);
1036 	return 0;
1037 }
1038 /* }}} */
1039 
1040 
1041 /* {{{ ftp_append */
1042 int
ftp_append(ftpbuf_t * ftp,const char * path,const size_t path_len,php_stream * instream,ftptype_t type)1043 ftp_append(ftpbuf_t *ftp, const char *path, const size_t path_len, php_stream *instream, ftptype_t type)
1044 {
1045 	databuf_t		*data = NULL;
1046 	zend_long			size;
1047 	char			*ptr;
1048 	int			ch;
1049 
1050 	if (ftp == NULL) {
1051 		return 0;
1052 	}
1053 	if (!ftp_type(ftp, type)) {
1054 		goto bail;
1055 	}
1056 	if ((data = ftp_getdata(ftp)) == NULL) {
1057 		goto bail;
1058 	}
1059 	ftp->data = data;
1060 
1061 	if (!ftp_putcmd(ftp, "APPE", sizeof("APPE")-1, path, path_len)) {
1062 		goto bail;
1063 	}
1064 	if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125)) {
1065 		goto bail;
1066 	}
1067 	if ((data = data_accept(data, ftp)) == NULL) {
1068 		goto bail;
1069 	}
1070 
1071 	size = 0;
1072 	ptr = data->buf;
1073 	while (!php_stream_eof(instream) && (ch = php_stream_getc(instream))!=EOF) {
1074 		/* flush if necessary */
1075 		if (FTP_BUFSIZE - size < 2) {
1076 			if (my_send(ftp, data->fd, data->buf, size) != size) {
1077 				goto bail;
1078 			}
1079 			ptr = data->buf;
1080 			size = 0;
1081 		}
1082 
1083 		if (ch == '\n' && type == FTPTYPE_ASCII) {
1084 			*ptr++ = '\r';
1085 			size++;
1086 		}
1087 
1088 		*ptr++ = ch;
1089 		size++;
1090 	}
1091 
1092 	if (size && my_send(ftp, data->fd, data->buf, size) != size) {
1093 		goto bail;
1094 	}
1095 	ftp->data = data = data_close(ftp, data);
1096 
1097 	if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250 && ftp->resp != 200)) {
1098 		goto bail;
1099 	}
1100 	return 1;
1101 bail:
1102 	ftp->data = data_close(ftp, data);
1103 	return 0;
1104 }
1105 /* }}} */
1106 
1107 /* {{{ ftp_size */
1108 zend_long
ftp_size(ftpbuf_t * ftp,const char * path,const size_t path_len)1109 ftp_size(ftpbuf_t *ftp, const char *path, const size_t path_len)
1110 {
1111 	zend_long res;
1112 
1113 	if (ftp == NULL) {
1114 		return -1;
1115 	}
1116 	if (!ftp_type(ftp, FTPTYPE_IMAGE)) {
1117 		return -1;
1118 	}
1119 	if (!ftp_putcmd(ftp, "SIZE", sizeof("SIZE")-1, path, path_len)) {
1120 		return -1;
1121 	}
1122 	if (!ftp_getresp(ftp) || ftp->resp != 213) {
1123 		return -1;
1124 	}
1125 	ZEND_ATOL(res, ftp->inbuf);
1126 	return res;
1127 }
1128 /* }}} */
1129 
1130 /* {{{ ftp_mdtm */
1131 time_t
ftp_mdtm(ftpbuf_t * ftp,const char * path,const size_t path_len)1132 ftp_mdtm(ftpbuf_t *ftp, const char *path, const size_t path_len)
1133 {
1134 	time_t		stamp;
1135 	struct tm	*gmt, tmbuf;
1136 	struct tm	tm;
1137 	char		*ptr;
1138 	int		n;
1139 
1140 	if (ftp == NULL) {
1141 		return -1;
1142 	}
1143 	if (!ftp_putcmd(ftp, "MDTM", sizeof("MDTM")-1, path, path_len)) {
1144 		return -1;
1145 	}
1146 	if (!ftp_getresp(ftp) || ftp->resp != 213) {
1147 		return -1;
1148 	}
1149 	/* parse out the timestamp */
1150 	for (ptr = ftp->inbuf; *ptr && !isdigit(*ptr); ptr++);
1151 	n = sscanf(ptr, "%4u%2u%2u%2u%2u%2u", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec);
1152 	if (n != 6) {
1153 		return -1;
1154 	}
1155 	tm.tm_year -= 1900;
1156 	tm.tm_mon--;
1157 	tm.tm_isdst = -1;
1158 
1159 	/* figure out the GMT offset */
1160 	stamp = time(NULL);
1161 	gmt = php_gmtime_r(&stamp, &tmbuf);
1162 	if (!gmt) {
1163 		return -1;
1164 	}
1165 	gmt->tm_isdst = -1;
1166 
1167 	/* apply the GMT offset */
1168 	tm.tm_sec += stamp - mktime(gmt);
1169 	tm.tm_isdst = gmt->tm_isdst;
1170 
1171 	stamp = mktime(&tm);
1172 
1173 	return stamp;
1174 }
1175 /* }}} */
1176 
1177 /* {{{ ftp_delete */
1178 int
ftp_delete(ftpbuf_t * ftp,const char * path,const size_t path_len)1179 ftp_delete(ftpbuf_t *ftp, const char *path, const size_t path_len)
1180 {
1181 	if (ftp == NULL) {
1182 		return 0;
1183 	}
1184 	if (!ftp_putcmd(ftp, "DELE", sizeof("DELE")-1, path, path_len)) {
1185 		return 0;
1186 	}
1187 	if (!ftp_getresp(ftp) || ftp->resp != 250) {
1188 		return 0;
1189 	}
1190 
1191 	return 1;
1192 }
1193 /* }}} */
1194 
1195 /* {{{ ftp_rename */
1196 int
ftp_rename(ftpbuf_t * ftp,const char * src,const size_t src_len,const char * dest,const size_t dest_len)1197 ftp_rename(ftpbuf_t *ftp, const char *src, const size_t src_len, const char *dest, const size_t dest_len)
1198 {
1199 	if (ftp == NULL) {
1200 		return 0;
1201 	}
1202 	if (!ftp_putcmd(ftp, "RNFR", sizeof("RNFR")-1, src, src_len)) {
1203 		return 0;
1204 	}
1205 	if (!ftp_getresp(ftp) || ftp->resp != 350) {
1206 		return 0;
1207 	}
1208 	if (!ftp_putcmd(ftp, "RNTO", sizeof("RNTO")-1, dest, dest_len)) {
1209 		return 0;
1210 	}
1211 	if (!ftp_getresp(ftp) || ftp->resp != 250) {
1212 		return 0;
1213 	}
1214 	return 1;
1215 }
1216 /* }}} */
1217 
1218 /* {{{ ftp_site */
1219 int
ftp_site(ftpbuf_t * ftp,const char * cmd,const size_t cmd_len)1220 ftp_site(ftpbuf_t *ftp, const char *cmd, const size_t cmd_len)
1221 {
1222 	if (ftp == NULL) {
1223 		return 0;
1224 	}
1225 	if (!ftp_putcmd(ftp, "SITE", sizeof("SITE")-1, cmd, cmd_len)) {
1226 		return 0;
1227 	}
1228 	if (!ftp_getresp(ftp) || ftp->resp < 200 || ftp->resp >= 300) {
1229 		return 0;
1230 	}
1231 
1232 	return 1;
1233 }
1234 /* }}} */
1235 
1236 /* static functions */
1237 
1238 /* {{{ ftp_putcmd */
1239 int
ftp_putcmd(ftpbuf_t * ftp,const char * cmd,const size_t cmd_len,const char * args,const size_t args_len)1240 ftp_putcmd(ftpbuf_t *ftp, const char *cmd, const size_t cmd_len, const char *args, const size_t args_len)
1241 {
1242 	int		size;
1243 	char		*data;
1244 
1245 	if (strpbrk(cmd, "\r\n")) {
1246 		return 0;
1247 	}
1248 	/* build the output buffer */
1249 	if (args && args[0]) {
1250 		/* "cmd args\r\n\0" */
1251 		if (cmd_len + args_len + 4 > FTP_BUFSIZE) {
1252 			return 0;
1253 		}
1254 		if (strpbrk(args, "\r\n")) {
1255 			return 0;
1256 		}
1257 		size = slprintf(ftp->outbuf, sizeof(ftp->outbuf), "%s %s\r\n", cmd, args);
1258 	} else {
1259 		/* "cmd\r\n\0" */
1260 		if (cmd_len + 3 > FTP_BUFSIZE) {
1261 			return 0;
1262 		}
1263 		size = slprintf(ftp->outbuf, sizeof(ftp->outbuf), "%s\r\n", cmd);
1264 	}
1265 
1266 	data = ftp->outbuf;
1267 
1268 	/* Clear the inbuf and extra-lines buffer */
1269 	ftp->inbuf[0] = '\0';
1270 	ftp->extra = NULL;
1271 
1272 	if (my_send(ftp, ftp->fd, data, size) != size) {
1273 		return 0;
1274 	}
1275 	return 1;
1276 }
1277 /* }}} */
1278 
1279 /* {{{ ftp_readline */
1280 int
ftp_readline(ftpbuf_t * ftp)1281 ftp_readline(ftpbuf_t *ftp)
1282 {
1283 	long		size, rcvd;
1284 	char		*data, *eol;
1285 
1286 	/* shift the extra to the front */
1287 	size = FTP_BUFSIZE;
1288 	rcvd = 0;
1289 	if (ftp->extra) {
1290 		memmove(ftp->inbuf, ftp->extra, ftp->extralen);
1291 		rcvd = ftp->extralen;
1292 	}
1293 
1294 	data = ftp->inbuf;
1295 
1296 	do {
1297 		size -= rcvd;
1298 		for (eol = data; rcvd; rcvd--, eol++) {
1299 			if (*eol == '\r') {
1300 				*eol = 0;
1301 				ftp->extra = eol + 1;
1302 				if (rcvd > 1 && *(eol + 1) == '\n') {
1303 					ftp->extra++;
1304 					rcvd--;
1305 				}
1306 				if ((ftp->extralen = --rcvd) == 0) {
1307 					ftp->extra = NULL;
1308 				}
1309 				return 1;
1310 			} else if (*eol == '\n') {
1311 				*eol = 0;
1312 				ftp->extra = eol + 1;
1313 				if ((ftp->extralen = --rcvd) == 0) {
1314 					ftp->extra = NULL;
1315 				}
1316 				return 1;
1317 			}
1318 		}
1319 
1320 		data = eol;
1321 		if ((rcvd = my_recv(ftp, ftp->fd, data, size)) < 1) {
1322 			*data = 0;
1323 			return 0;
1324 		}
1325 	} while (size);
1326 
1327 	*data = 0;
1328 	return 0;
1329 }
1330 /* }}} */
1331 
1332 /* {{{ ftp_getresp */
1333 int
ftp_getresp(ftpbuf_t * ftp)1334 ftp_getresp(ftpbuf_t *ftp)
1335 {
1336 	if (ftp == NULL) {
1337 		return 0;
1338 	}
1339 	ftp->resp = 0;
1340 
1341 	while (1) {
1342 
1343 		if (!ftp_readline(ftp)) {
1344 			return 0;
1345 		}
1346 
1347 		/* Break out when the end-tag is found */
1348 		if (isdigit(ftp->inbuf[0]) && isdigit(ftp->inbuf[1]) && isdigit(ftp->inbuf[2]) && ftp->inbuf[3] == ' ') {
1349 			break;
1350 		}
1351 	}
1352 
1353 	/* translate the tag */
1354 	if (!isdigit(ftp->inbuf[0]) || !isdigit(ftp->inbuf[1]) || !isdigit(ftp->inbuf[2])) {
1355 		return 0;
1356 	}
1357 
1358 	ftp->resp = 100 * (ftp->inbuf[0] - '0') + 10 * (ftp->inbuf[1] - '0') + (ftp->inbuf[2] - '0');
1359 
1360 	memmove(ftp->inbuf, ftp->inbuf + 4, FTP_BUFSIZE - 4);
1361 
1362 	if (ftp->extra) {
1363 		ftp->extra -= 4;
1364 	}
1365 	return 1;
1366 }
1367 /* }}} */
1368 
single_send(ftpbuf_t * ftp,php_socket_t s,void * buf,size_t size)1369 int single_send(ftpbuf_t *ftp, php_socket_t s, void *buf, size_t size) {
1370 #ifdef HAVE_FTP_SSL
1371 	int err;
1372 	zend_bool retry = 0;
1373 	SSL *handle = NULL;
1374 	php_socket_t fd;
1375 	size_t sent;
1376 
1377 	if (ftp->use_ssl && ftp->fd == s && ftp->ssl_active) {
1378 		handle = ftp->ssl_handle;
1379 		fd = ftp->fd;
1380 	} else if (ftp->use_ssl && ftp->fd != s && ftp->use_ssl_for_data && ftp->data->ssl_active) {
1381 		handle = ftp->data->ssl_handle;
1382 		fd = ftp->data->fd;
1383 	} else {
1384 		return send(s, buf, size, 0);
1385 	}
1386 
1387 	do {
1388 		sent = SSL_write(handle, buf, size);
1389 		err = SSL_get_error(handle, sent);
1390 
1391 		switch (err) {
1392 			case SSL_ERROR_NONE:
1393 				retry = 0;
1394 				break;
1395 
1396 			case SSL_ERROR_ZERO_RETURN:
1397 				retry = 0;
1398 				SSL_shutdown(handle);
1399 				break;
1400 
1401 			case SSL_ERROR_WANT_READ:
1402 			case SSL_ERROR_WANT_CONNECT: {
1403 					php_pollfd p;
1404 					int i;
1405 
1406 					p.fd = fd;
1407 					p.events = POLLOUT;
1408 					p.revents = 0;
1409 
1410 					i = php_poll2(&p, 1, 300);
1411 
1412 					retry = i > 0;
1413 				}
1414 				break;
1415 
1416 			default:
1417 				php_error_docref(NULL, E_WARNING, "SSL write failed");
1418 				return -1;
1419 		}
1420 	} while (retry);
1421 	return sent;
1422 #else
1423 	return send(s, buf, size, 0);
1424 #endif
1425 }
1426 
1427 /* {{{ my_send */
1428 int
my_send(ftpbuf_t * ftp,php_socket_t s,void * buf,size_t len)1429 my_send(ftpbuf_t *ftp, php_socket_t s, void *buf, size_t len)
1430 {
1431 	zend_long		size, sent;
1432     int         n;
1433 
1434 	size = len;
1435 	while (size) {
1436 		n = php_pollfd_for_ms(s, POLLOUT, ftp->timeout_sec * 1000);
1437 
1438 		if (n < 1) {
1439 			char buf[256];
1440 			if (n == 0) {
1441 #ifdef PHP_WIN32
1442 				_set_errno(ETIMEDOUT);
1443 #else
1444 				errno = ETIMEDOUT;
1445 #endif
1446 			}
1447 			php_error_docref(NULL, E_WARNING, "%s", php_socket_strerror(errno, buf, sizeof buf));
1448 			return -1;
1449 		}
1450 
1451 		sent = single_send(ftp, s, buf, size);
1452 		if (sent == -1) {
1453 			return -1;
1454 		}
1455 
1456 		buf = (char*) buf + sent;
1457 		size -= sent;
1458 	}
1459 
1460 	return len;
1461 }
1462 /* }}} */
1463 
1464 /* {{{ my_recv */
1465 int
my_recv(ftpbuf_t * ftp,php_socket_t s,void * buf,size_t len)1466 my_recv(ftpbuf_t *ftp, php_socket_t s, void *buf, size_t len)
1467 {
1468 	int		n, nr_bytes;
1469 #ifdef HAVE_FTP_SSL
1470 	int err;
1471 	zend_bool retry = 0;
1472 	SSL *handle = NULL;
1473 	php_socket_t fd;
1474 #endif
1475 	n = php_pollfd_for_ms(s, PHP_POLLREADABLE, ftp->timeout_sec * 1000);
1476 	if (n < 1) {
1477 		char buf[256];
1478 		if (n == 0) {
1479 #ifdef PHP_WIN32
1480 			_set_errno(ETIMEDOUT);
1481 #else
1482 			errno = ETIMEDOUT;
1483 #endif
1484 		}
1485 		php_error_docref(NULL, E_WARNING, "%s", php_socket_strerror(errno, buf, sizeof buf));
1486 		return -1;
1487 	}
1488 
1489 #ifdef HAVE_FTP_SSL
1490 	if (ftp->use_ssl && ftp->fd == s && ftp->ssl_active) {
1491 		handle = ftp->ssl_handle;
1492 		fd = ftp->fd;
1493 	} else if (ftp->use_ssl && ftp->fd != s && ftp->use_ssl_for_data && ftp->data->ssl_active) {
1494 		handle = ftp->data->ssl_handle;
1495 		fd = ftp->data->fd;
1496 	}
1497 
1498 	if (handle) {
1499 		do {
1500 			nr_bytes = SSL_read(handle, buf, len);
1501 			err = SSL_get_error(handle, nr_bytes);
1502 
1503 			switch (err) {
1504 				case SSL_ERROR_NONE:
1505 					retry = 0;
1506 					break;
1507 
1508 				case SSL_ERROR_ZERO_RETURN:
1509 					retry = 0;
1510 					SSL_shutdown(handle);
1511 					break;
1512 
1513 				case SSL_ERROR_WANT_READ:
1514 				case SSL_ERROR_WANT_CONNECT: {
1515 						php_pollfd p;
1516 						int i;
1517 
1518 						p.fd = fd;
1519 						p.events = POLLIN|POLLPRI;
1520 						p.revents = 0;
1521 
1522 						i = php_poll2(&p, 1, 300);
1523 
1524 						retry = i > 0;
1525 					}
1526 					break;
1527 
1528 				default:
1529 					php_error_docref(NULL, E_WARNING, "SSL read failed");
1530 					return -1;
1531 			}
1532 		} while (retry);
1533 	} else {
1534 #endif
1535 		nr_bytes = recv(s, buf, len, 0);
1536 #ifdef HAVE_FTP_SSL
1537 	}
1538 #endif
1539 	return (nr_bytes);
1540 }
1541 /* }}} */
1542 
1543 /* {{{ data_available */
1544 int
data_available(ftpbuf_t * ftp,php_socket_t s)1545 data_available(ftpbuf_t *ftp, php_socket_t s)
1546 {
1547 	int		n;
1548 
1549 	n = php_pollfd_for_ms(s, PHP_POLLREADABLE, 1000);
1550 	if (n < 1) {
1551 		char buf[256];
1552 		if (n == 0) {
1553 #ifdef PHP_WIN32
1554 			_set_errno(ETIMEDOUT);
1555 #else
1556 			errno = ETIMEDOUT;
1557 #endif
1558 		}
1559 		php_error_docref(NULL, E_WARNING, "%s", php_socket_strerror(errno, buf, sizeof buf));
1560 		return 0;
1561 	}
1562 
1563 	return 1;
1564 }
1565 /* }}} */
1566 /* {{{ data_writeable */
1567 int
data_writeable(ftpbuf_t * ftp,php_socket_t s)1568 data_writeable(ftpbuf_t *ftp, php_socket_t s)
1569 {
1570 	int		n;
1571 
1572 	n = php_pollfd_for_ms(s, POLLOUT, 1000);
1573 	if (n < 1) {
1574 		char buf[256];
1575 		if (n == 0) {
1576 #ifdef PHP_WIN32
1577 			_set_errno(ETIMEDOUT);
1578 #else
1579 			errno = ETIMEDOUT;
1580 #endif
1581 		}
1582 		php_error_docref(NULL, E_WARNING, "%s", php_socket_strerror(errno, buf, sizeof buf));
1583 		return 0;
1584 	}
1585 
1586 	return 1;
1587 }
1588 /* }}} */
1589 
1590 /* {{{ my_accept */
1591 int
my_accept(ftpbuf_t * ftp,php_socket_t s,struct sockaddr * addr,socklen_t * addrlen)1592 my_accept(ftpbuf_t *ftp, php_socket_t s, struct sockaddr *addr, socklen_t *addrlen)
1593 {
1594 	int		n;
1595 
1596 	n = php_pollfd_for_ms(s, PHP_POLLREADABLE, ftp->timeout_sec * 1000);
1597 	if (n < 1) {
1598 		char buf[256];
1599 		if (n == 0) {
1600 #ifdef PHP_WIN32
1601 			_set_errno(ETIMEDOUT);
1602 #else
1603 			errno = ETIMEDOUT;
1604 #endif
1605 		}
1606 		php_error_docref(NULL, E_WARNING, "%s", php_socket_strerror(errno, buf, sizeof buf));
1607 		return -1;
1608 	}
1609 
1610 	return accept(s, addr, addrlen);
1611 }
1612 /* }}} */
1613 
1614 /* {{{ ftp_getdata */
1615 databuf_t*
ftp_getdata(ftpbuf_t * ftp)1616 ftp_getdata(ftpbuf_t *ftp)
1617 {
1618 	int				fd = -1;
1619 	databuf_t		*data;
1620 	php_sockaddr_storage addr;
1621 	struct sockaddr *sa;
1622 	socklen_t		size;
1623 	union ipbox		ipbox;
1624 	char			arg[sizeof("255, 255, 255, 255, 255, 255")];
1625 	struct timeval	tv;
1626 	int				arg_len;
1627 
1628 
1629 	/* ask for a passive connection if we need one */
1630 	if (ftp->pasv && !ftp_pasv(ftp, 1)) {
1631 		return NULL;
1632 	}
1633 	/* alloc the data structure */
1634 	data = ecalloc(1, sizeof(*data));
1635 	data->listener = -1;
1636 	data->fd = -1;
1637 	data->type = ftp->type;
1638 
1639 	sa = (struct sockaddr *) &ftp->localaddr;
1640 	/* bind/listen */
1641 	if ((fd = socket(sa->sa_family, SOCK_STREAM, 0)) == SOCK_ERR) {
1642 		php_error_docref(NULL, E_WARNING, "socket() failed: %s (%d)", strerror(errno), errno);
1643 		goto bail;
1644 	}
1645 
1646 	/* passive connection handler */
1647 	if (ftp->pasv) {
1648 		/* clear the ready status */
1649 		ftp->pasv = 1;
1650 
1651 		/* connect */
1652 		/* Win 95/98 seems not to like size > sizeof(sockaddr_in) */
1653 		size = php_sockaddr_size(&ftp->pasvaddr);
1654 		tv.tv_sec = ftp->timeout_sec;
1655 		tv.tv_usec = 0;
1656 		if (php_connect_nonb(fd, (struct sockaddr*) &ftp->pasvaddr, size, &tv) == -1) {
1657 			php_error_docref(NULL, E_WARNING, "php_connect_nonb() failed: %s (%d)", strerror(errno), errno);
1658 			goto bail;
1659 		}
1660 
1661 		data->fd = fd;
1662 
1663 		ftp->data = data;
1664 		return data;
1665 	}
1666 
1667 
1668 	/* active (normal) connection */
1669 
1670 	/* bind to a local address */
1671 	php_any_addr(sa->sa_family, &addr, 0);
1672 	size = php_sockaddr_size(&addr);
1673 
1674 	if (bind(fd, (struct sockaddr*) &addr, size) != 0) {
1675 		php_error_docref(NULL, E_WARNING, "bind() failed: %s (%d)", strerror(errno), errno);
1676 		goto bail;
1677 	}
1678 
1679 	if (getsockname(fd, (struct sockaddr*) &addr, &size) != 0) {
1680 		php_error_docref(NULL, E_WARNING, "getsockname() failed: %s (%d)", strerror(errno), errno);
1681 		goto bail;
1682 	}
1683 
1684 	if (listen(fd, 5) != 0) {
1685 		php_error_docref(NULL, E_WARNING, "listen() failed: %s (%d)", strerror(errno), errno);
1686 		goto bail;
1687 	}
1688 
1689 	data->listener = fd;
1690 
1691 #if defined(HAVE_IPV6) && defined(HAVE_INET_NTOP)
1692 	if (sa->sa_family == AF_INET6) {
1693 		/* need to use EPRT */
1694 		char eprtarg[INET6_ADDRSTRLEN + sizeof("|x||xxxxx|")];
1695 		char out[INET6_ADDRSTRLEN];
1696 		int eprtarg_len;
1697 		inet_ntop(AF_INET6, &((struct sockaddr_in6*) sa)->sin6_addr, out, sizeof(out));
1698 		eprtarg_len = snprintf(eprtarg, sizeof(eprtarg), "|2|%s|%hu|", out, ntohs(((struct sockaddr_in6 *) &addr)->sin6_port));
1699 
1700 		if (eprtarg_len < 0) {
1701 			goto bail;
1702 		}
1703 
1704 		if (!ftp_putcmd(ftp, "EPRT", sizeof("EPRT")-1, eprtarg, eprtarg_len)) {
1705 			goto bail;
1706 		}
1707 
1708 		if (!ftp_getresp(ftp) || ftp->resp != 200) {
1709 			goto bail;
1710 		}
1711 
1712 		ftp->data = data;
1713 		return data;
1714 	}
1715 #endif
1716 
1717 	/* send the PORT */
1718 	ipbox.ia[0] = ((struct sockaddr_in*) sa)->sin_addr;
1719 	ipbox.s[2] = ((struct sockaddr_in*) &addr)->sin_port;
1720 	arg_len = snprintf(arg, sizeof(arg), "%u,%u,%u,%u,%u,%u", ipbox.c[0], ipbox.c[1], ipbox.c[2], ipbox.c[3], ipbox.c[4], ipbox.c[5]);
1721 
1722 	if (arg_len < 0) {
1723 		goto bail;
1724 	}
1725 	if (!ftp_putcmd(ftp, "PORT", sizeof("PORT")-1, arg, arg_len)) {
1726 		goto bail;
1727 	}
1728 	if (!ftp_getresp(ftp) || ftp->resp != 200) {
1729 		goto bail;
1730 	}
1731 
1732 	ftp->data = data;
1733 	return data;
1734 
1735 bail:
1736 	if (fd != -1) {
1737 		closesocket(fd);
1738 	}
1739 	efree(data);
1740 	return NULL;
1741 }
1742 /* }}} */
1743 
1744 /* {{{ data_accept */
1745 databuf_t*
data_accept(databuf_t * data,ftpbuf_t * ftp)1746 data_accept(databuf_t *data, ftpbuf_t *ftp)
1747 {
1748 	php_sockaddr_storage addr;
1749 	socklen_t			size;
1750 
1751 #ifdef HAVE_FTP_SSL
1752 	SSL_CTX		*ctx;
1753 	SSL_SESSION *session;
1754 	int err, res;
1755 	zend_bool retry;
1756 #endif
1757 
1758 	if (data->fd != -1) {
1759 		goto data_accepted;
1760 	}
1761 	size = sizeof(addr);
1762 	data->fd = my_accept(ftp, data->listener, (struct sockaddr*) &addr, &size);
1763 	closesocket(data->listener);
1764 	data->listener = -1;
1765 
1766 	if (data->fd == -1) {
1767 		efree(data);
1768 		return NULL;
1769 	}
1770 
1771 data_accepted:
1772 #ifdef HAVE_FTP_SSL
1773 
1774 	/* now enable ssl if we need to */
1775 	if (ftp->use_ssl && ftp->use_ssl_for_data) {
1776 		ctx = SSL_get_SSL_CTX(ftp->ssl_handle);
1777 		if (ctx == NULL) {
1778 			php_error_docref(NULL, E_WARNING, "data_accept: failed to retrieve the existing SSL context");
1779 			return 0;
1780 		}
1781 
1782 		data->ssl_handle = SSL_new(ctx);
1783 		if (data->ssl_handle == NULL) {
1784 			php_error_docref(NULL, E_WARNING, "data_accept: failed to create the SSL handle");
1785 			return 0;
1786 		}
1787 
1788 		SSL_set_fd(data->ssl_handle, data->fd);
1789 
1790 		if (ftp->old_ssl) {
1791 			SSL_copy_session_id(data->ssl_handle, ftp->ssl_handle);
1792 		}
1793 
1794 		/* get the session from the control connection so we can re-use it */
1795 		session = SSL_get_session(ftp->ssl_handle);
1796 		if (session == NULL) {
1797 			php_error_docref(NULL, E_WARNING, "data_accept: failed to retrieve the existing SSL session");
1798 			SSL_free(data->ssl_handle);
1799 			return 0;
1800 		}
1801 
1802 		/* and set it on the data connection */
1803 		res = SSL_set_session(data->ssl_handle, session);
1804 		if (res == 0) {
1805 			php_error_docref(NULL, E_WARNING, "data_accept: failed to set the existing SSL session");
1806 			SSL_free(data->ssl_handle);
1807 			return 0;
1808 		}
1809 
1810 		do {
1811 			res = SSL_connect(data->ssl_handle);
1812 			err = SSL_get_error(data->ssl_handle, res);
1813 
1814 			switch (err) {
1815 				case SSL_ERROR_NONE:
1816 					retry = 0;
1817 					break;
1818 
1819 				case SSL_ERROR_ZERO_RETURN:
1820 					retry = 0;
1821 					SSL_shutdown(data->ssl_handle);
1822 					break;
1823 
1824 				case SSL_ERROR_WANT_READ:
1825 				case SSL_ERROR_WANT_WRITE: {
1826 						php_pollfd p;
1827 						int i;
1828 
1829 						p.fd = data->fd;
1830 						p.events = (err == SSL_ERROR_WANT_READ) ? (POLLIN|POLLPRI) : POLLOUT;
1831 						p.revents = 0;
1832 
1833 						i = php_poll2(&p, 1, 300);
1834 
1835 						retry = i > 0;
1836 					}
1837 					break;
1838 
1839 				default:
1840 					php_error_docref(NULL, E_WARNING, "data_accept: SSL/TLS handshake failed");
1841 					SSL_shutdown(data->ssl_handle);
1842 					SSL_free(data->ssl_handle);
1843 					return 0;
1844 			}
1845 		} while (retry);
1846 
1847 		data->ssl_active = 1;
1848 	}
1849 
1850 #endif
1851 
1852 	return data;
1853 }
1854 /* }}} */
1855 
1856 /* {{{ ftp_ssl_shutdown */
1857 #ifdef HAVE_FTP_SSL
ftp_ssl_shutdown(ftpbuf_t * ftp,php_socket_t fd,SSL * ssl_handle)1858 static void ftp_ssl_shutdown(ftpbuf_t *ftp, php_socket_t fd, SSL *ssl_handle) {
1859 	/* In TLS 1.3 it's common to receive session tickets after the handshake has completed. We need to train
1860 	   the socket (read the tickets until EOF/close_notify alert) before closing the socket. Otherwise the
1861 	   server might get an ECONNRESET which might lead to data truncation on server side.
1862 	*/
1863 	char buf[256]; /* We will use this for the OpenSSL error buffer, so it has
1864 			  to be at least 256 bytes long.*/
1865 	int done = 1, err, nread;
1866 	unsigned long sslerror;
1867 
1868 	err = SSL_shutdown(ssl_handle);
1869 	if (err < 0) {
1870 		php_error_docref(NULL, E_WARNING, "SSL_shutdown failed");
1871 	}
1872 	else if (err == 0) {
1873 		/* The shutdown is not yet finished. Call SSL_read() to do a bidirectional shutdown. */
1874 		done = 0;
1875 	}
1876 
1877 	while (!done && data_available(ftp, fd)) {
1878 		ERR_clear_error();
1879 		nread = SSL_read(ssl_handle, buf, sizeof(buf));
1880 		if (nread <= 0) {
1881 			err = SSL_get_error(ssl_handle, nread);
1882 			switch (err) {
1883 				case SSL_ERROR_NONE: /* this is not an error */
1884 				case SSL_ERROR_ZERO_RETURN: /* no more data */
1885 					/* This is the expected response. There was no data but only
1886 					   the close notify alert */
1887 					done = 1;
1888 					break;
1889 				case SSL_ERROR_WANT_READ:
1890 					/* there's data pending, re-invoke SSL_read() */
1891 					break;
1892 				case SSL_ERROR_WANT_WRITE:
1893 					/* SSL wants a write. Really odd. Let's bail out. */
1894 					done = 1;
1895 					break;
1896 				case SSL_ERROR_SYSCALL:
1897 					/* most likely the peer closed the connection without
1898 					   sending a close_notify shutdown alert;
1899 					   bail out to avoid raising a spurious warning */
1900 					done = 1;
1901 					break;
1902 				default:
1903 					if ((sslerror = ERR_get_error())) {
1904 						ERR_error_string_n(sslerror, buf, sizeof(buf));
1905 						php_error_docref(NULL, E_WARNING, "SSL_read on shutdown: %s", buf);
1906 					} else if (errno) {
1907 						php_error_docref(NULL, E_WARNING, "SSL_read on shutdown: %s (%d)", strerror(errno), errno);
1908 					}
1909 					done = 1;
1910 					break;
1911 			}
1912 		}
1913 	}
1914 	(void)SSL_free(ssl_handle);
1915 }
1916 #endif
1917 /* }}} */
1918 
1919 /* {{{ data_close */
1920 databuf_t*
data_close(ftpbuf_t * ftp,databuf_t * data)1921 data_close(ftpbuf_t *ftp, databuf_t *data)
1922 {
1923 	if (data == NULL) {
1924 		return NULL;
1925 	}
1926 	if (data->listener != -1) {
1927 #ifdef HAVE_FTP_SSL
1928 		if (data->ssl_active) {
1929 			/* don't free the data context, it's the same as the control */
1930 			ftp_ssl_shutdown(ftp, data->listener, data->ssl_handle);
1931 			data->ssl_active = 0;
1932 		}
1933 #endif
1934 		closesocket(data->listener);
1935 	}
1936 	if (data->fd != -1) {
1937 #ifdef HAVE_FTP_SSL
1938 		if (data->ssl_active) {
1939 			/* don't free the data context, it's the same as the control */
1940 			ftp_ssl_shutdown(ftp, data->fd, data->ssl_handle);
1941 			data->ssl_active = 0;
1942 		}
1943 #endif
1944 		closesocket(data->fd);
1945 	}
1946 	if (ftp) {
1947 		ftp->data = NULL;
1948 	}
1949 	efree(data);
1950 	return NULL;
1951 }
1952 /* }}} */
1953 
1954 /* {{{ ftp_genlist */
1955 char**
ftp_genlist(ftpbuf_t * ftp,const char * cmd,const size_t cmd_len,const char * path,const size_t path_len)1956 ftp_genlist(ftpbuf_t *ftp, const char *cmd, const size_t cmd_len, const char *path, const size_t path_len)
1957 {
1958 	php_stream	*tmpstream = NULL;
1959 	databuf_t	*data = NULL;
1960 	char		*ptr;
1961 	int		ch, lastch;
1962 	size_t		size, rcvd;
1963 	size_t		lines;
1964 	char		**ret = NULL;
1965 	char		**entry;
1966 	char		*text;
1967 
1968 
1969 	if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) {
1970 		php_error_docref(NULL, E_WARNING, "Unable to create temporary file.  Check permissions in temporary files directory.");
1971 		return NULL;
1972 	}
1973 
1974 	if (!ftp_type(ftp, FTPTYPE_ASCII)) {
1975 		goto bail;
1976 	}
1977 
1978 	if ((data = ftp_getdata(ftp)) == NULL) {
1979 		goto bail;
1980 	}
1981 	ftp->data = data;
1982 
1983 	if (!ftp_putcmd(ftp, cmd, cmd_len, path, path_len)) {
1984 		goto bail;
1985 	}
1986 	if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) {
1987 		goto bail;
1988 	}
1989 
1990 	/* some servers don't open a ftp-data connection if the directory is empty */
1991 	if (ftp->resp == 226) {
1992 		ftp->data = data_close(ftp, data);
1993 		php_stream_close(tmpstream);
1994 		return ecalloc(1, sizeof(char*));
1995 	}
1996 
1997 	/* pull data buffer into tmpfile */
1998 	if ((data = data_accept(data, ftp)) == NULL) {
1999 		goto bail;
2000 	}
2001 	size = 0;
2002 	lines = 0;
2003 	lastch = 0;
2004 	while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) {
2005 		if (rcvd == (size_t)-1 || rcvd > ((size_t)(-1))-size) {
2006 			goto bail;
2007 		}
2008 
2009 		php_stream_write(tmpstream, data->buf, rcvd);
2010 
2011 		size += rcvd;
2012 		for (ptr = data->buf; rcvd; rcvd--, ptr++) {
2013 			if (*ptr == '\n' && lastch == '\r') {
2014 				lines++;
2015 			}
2016 			lastch = *ptr;
2017 		}
2018 	}
2019 
2020 	ftp->data = data_close(ftp, data);
2021 
2022 	php_stream_rewind(tmpstream);
2023 
2024 	ret = safe_emalloc((lines + 1), sizeof(char*), size);
2025 
2026 	entry = ret;
2027 	text = (char*) (ret + lines + 1);
2028 	*entry = text;
2029 	lastch = 0;
2030 	while ((ch = php_stream_getc(tmpstream)) != EOF) {
2031 		if (ch == '\n' && lastch == '\r') {
2032 			*(text - 1) = 0;
2033 			*++entry = text;
2034 		} else {
2035 			*text++ = ch;
2036 		}
2037 		lastch = ch;
2038 	}
2039 	*entry = NULL;
2040 
2041 	php_stream_close(tmpstream);
2042 
2043 	if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) {
2044 		efree(ret);
2045 		return NULL;
2046 	}
2047 
2048 	return ret;
2049 bail:
2050 	ftp->data = data_close(ftp, data);
2051 	php_stream_close(tmpstream);
2052 	if (ret)
2053 		efree(ret);
2054 	return NULL;
2055 }
2056 /* }}} */
2057 
2058 /* {{{ ftp_nb_get */
2059 int
ftp_nb_get(ftpbuf_t * ftp,php_stream * outstream,const char * path,const size_t path_len,ftptype_t type,zend_long resumepos)2060 ftp_nb_get(ftpbuf_t *ftp, php_stream *outstream, const char *path, const size_t path_len, ftptype_t type, zend_long resumepos)
2061 {
2062 	databuf_t		*data = NULL;
2063 	char			arg[11];
2064 
2065 	if (ftp == NULL) {
2066 		return PHP_FTP_FAILED;
2067 	}
2068 
2069 	if (!ftp_type(ftp, type)) {
2070 		goto bail;
2071 	}
2072 
2073 	if ((data = ftp_getdata(ftp)) == NULL) {
2074 		goto bail;
2075 	}
2076 
2077 	if (resumepos>0) {
2078 		int arg_len = snprintf(arg, sizeof(arg), ZEND_LONG_FMT, resumepos);
2079 
2080 		if (arg_len < 0) {
2081 			goto bail;
2082 		}
2083 		if (!ftp_putcmd(ftp, "REST", sizeof("REST")-1, arg, arg_len)) {
2084 			goto bail;
2085 		}
2086 		if (!ftp_getresp(ftp) || (ftp->resp != 350)) {
2087 			goto bail;
2088 		}
2089 	}
2090 
2091 	if (!ftp_putcmd(ftp, "RETR", sizeof("RETR")-1, path, path_len)) {
2092 		goto bail;
2093 	}
2094 	if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125)) {
2095 		goto bail;
2096 	}
2097 
2098 	if ((data = data_accept(data, ftp)) == NULL) {
2099 		goto bail;
2100 	}
2101 
2102 	ftp->data = data;
2103 	ftp->stream = outstream;
2104 	ftp->lastch = 0;
2105 	ftp->nb = 1;
2106 
2107 	return (ftp_nb_continue_read(ftp));
2108 
2109 bail:
2110 	ftp->data = data_close(ftp, data);
2111 	return PHP_FTP_FAILED;
2112 }
2113 /* }}} */
2114 
2115 /* {{{ ftp_nb_continue_read */
2116 int
ftp_nb_continue_read(ftpbuf_t * ftp)2117 ftp_nb_continue_read(ftpbuf_t *ftp)
2118 {
2119 	databuf_t	*data = NULL;
2120 	char		*ptr;
2121 	int		lastch;
2122 	size_t		rcvd;
2123 	ftptype_t	type;
2124 
2125 	data = ftp->data;
2126 
2127 	/* check if there is already more data */
2128 	if (!data_available(ftp, data->fd)) {
2129 		return PHP_FTP_MOREDATA;
2130 	}
2131 
2132 	type = ftp->type;
2133 
2134 	lastch = ftp->lastch;
2135 	if ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) {
2136 		if (rcvd == (size_t)-1) {
2137 			goto bail;
2138 		}
2139 
2140 		if (type == FTPTYPE_ASCII) {
2141 			for (ptr = data->buf; rcvd; rcvd--, ptr++) {
2142 				if (lastch == '\r' && *ptr != '\n') {
2143 					php_stream_putc(ftp->stream, '\r');
2144 				}
2145 				if (*ptr != '\r') {
2146 					php_stream_putc(ftp->stream, *ptr);
2147 				}
2148 				lastch = *ptr;
2149 			}
2150 		} else if (rcvd != php_stream_write(ftp->stream, data->buf, rcvd)) {
2151 			goto bail;
2152 		}
2153 
2154 		ftp->lastch = lastch;
2155 		return PHP_FTP_MOREDATA;
2156 	}
2157 
2158 	if (type == FTPTYPE_ASCII && lastch == '\r') {
2159 		php_stream_putc(ftp->stream, '\r');
2160 	}
2161 
2162 	ftp->data = data = data_close(ftp, data);
2163 
2164 	if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) {
2165 		goto bail;
2166 	}
2167 
2168 	ftp->nb = 0;
2169 	return PHP_FTP_FINISHED;
2170 bail:
2171 	ftp->nb = 0;
2172 	ftp->data = data_close(ftp, data);
2173 	return PHP_FTP_FAILED;
2174 }
2175 /* }}} */
2176 
2177 /* {{{ ftp_nb_put */
2178 int
ftp_nb_put(ftpbuf_t * ftp,const char * path,const size_t path_len,php_stream * instream,ftptype_t type,zend_long startpos)2179 ftp_nb_put(ftpbuf_t *ftp, const char *path, const size_t path_len, php_stream *instream, ftptype_t type, zend_long startpos)
2180 {
2181 	databuf_t		*data = NULL;
2182 	char			arg[11];
2183 
2184 	if (ftp == NULL) {
2185 		return 0;
2186 	}
2187 	if (!ftp_type(ftp, type)) {
2188 		goto bail;
2189 	}
2190 	if ((data = ftp_getdata(ftp)) == NULL) {
2191 		goto bail;
2192 	}
2193 	if (startpos > 0) {
2194 		int arg_len = snprintf(arg, sizeof(arg), ZEND_LONG_FMT, startpos);
2195 
2196 		if (arg_len < 0) {
2197 			goto bail;
2198 		}
2199 		if (!ftp_putcmd(ftp, "REST", sizeof("REST")-1, arg, arg_len)) {
2200 			goto bail;
2201 		}
2202 		if (!ftp_getresp(ftp) || (ftp->resp != 350)) {
2203 			goto bail;
2204 		}
2205 	}
2206 
2207 	if (!ftp_putcmd(ftp, "STOR", sizeof("STOR")-1, path, path_len)) {
2208 		goto bail;
2209 	}
2210 	if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125)) {
2211 		goto bail;
2212 	}
2213 	if ((data = data_accept(data, ftp)) == NULL) {
2214 		goto bail;
2215 	}
2216 	ftp->data = data;
2217 	ftp->stream = instream;
2218 	ftp->lastch = 0;
2219 	ftp->nb = 1;
2220 
2221 	return (ftp_nb_continue_write(ftp));
2222 
2223 bail:
2224 	ftp->data = data_close(ftp, data);
2225 	return PHP_FTP_FAILED;
2226 }
2227 /* }}} */
2228 
2229 
2230 /* {{{ ftp_nb_continue_write */
2231 int
ftp_nb_continue_write(ftpbuf_t * ftp)2232 ftp_nb_continue_write(ftpbuf_t *ftp)
2233 {
2234 	long			size;
2235 	char			*ptr;
2236 	int 			ch;
2237 
2238 	/* check if we can write more data */
2239 	if (!data_writeable(ftp, ftp->data->fd)) {
2240 		return PHP_FTP_MOREDATA;
2241 	}
2242 
2243 	size = 0;
2244 	ptr = ftp->data->buf;
2245 	while (!php_stream_eof(ftp->stream) && (ch = php_stream_getc(ftp->stream)) != EOF) {
2246 
2247 		if (ch == '\n' && ftp->type == FTPTYPE_ASCII) {
2248 			*ptr++ = '\r';
2249 			size++;
2250 		}
2251 
2252 		*ptr++ = ch;
2253 		size++;
2254 
2255 		/* flush if necessary */
2256 		if (FTP_BUFSIZE - size < 2) {
2257 			if (my_send(ftp, ftp->data->fd, ftp->data->buf, size) != size) {
2258 				goto bail;
2259 			}
2260 			return PHP_FTP_MOREDATA;
2261 		}
2262 	}
2263 
2264 	if (size && my_send(ftp, ftp->data->fd, ftp->data->buf, size) != size) {
2265 		goto bail;
2266 	}
2267 	ftp->data = data_close(ftp, ftp->data);
2268 
2269 	if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) {
2270 		goto bail;
2271 	}
2272 	ftp->nb = 0;
2273 	return PHP_FTP_FINISHED;
2274 bail:
2275 	ftp->data = data_close(ftp, ftp->data);
2276 	ftp->nb = 0;
2277 	return PHP_FTP_FAILED;
2278 }
2279 /* }}} */
2280