1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 5                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2014 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: Rasmus Lerdorf <rasmus@php.net>                              |
16   |         Ilia Alshanetsky <iliaa@php.net>                             |
17   +----------------------------------------------------------------------+
18 */
19/* $Id$ */
20
21#include <stdio.h>
22#include "php.h"
23#include <ctype.h>
24#include "php_string.h"
25#include "ext/standard/head.h"
26#include "ext/standard/file.h"
27#include "basic_functions.h"
28#include "exec.h"
29#include "php_globals.h"
30#include "SAPI.h"
31
32#if HAVE_SYS_WAIT_H
33#include <sys/wait.h>
34#endif
35#if HAVE_SIGNAL_H
36#include <signal.h>
37#endif
38
39#if HAVE_SYS_TYPES_H
40#include <sys/types.h>
41#endif
42#if HAVE_SYS_STAT_H
43#include <sys/stat.h>
44#endif
45#if HAVE_FCNTL_H
46#include <fcntl.h>
47#endif
48
49#if HAVE_NICE && HAVE_UNISTD_H
50#include <unistd.h>
51#endif
52
53/* {{{ php_exec
54 * If type==0, only last line of output is returned (exec)
55 * If type==1, all lines will be printed and last lined returned (system)
56 * If type==2, all lines will be saved to given array (exec with &$array)
57 * If type==3, output will be printed binary, no lines will be saved or returned (passthru)
58 *
59 */
60PHPAPI int php_exec(int type, char *cmd, zval *array, zval *return_value TSRMLS_DC)
61{
62    FILE *fp;
63    char *buf;
64    int l = 0, pclose_return;
65    char *b, *d=NULL;
66    php_stream *stream;
67    size_t buflen, bufl = 0;
68#if PHP_SIGCHILD
69    void (*sig_handler)() = NULL;
70#endif
71
72#if PHP_SIGCHILD
73    sig_handler = signal (SIGCHLD, SIG_DFL);
74#endif
75
76#ifdef PHP_WIN32
77    fp = VCWD_POPEN(cmd, "rb");
78#else
79    fp = VCWD_POPEN(cmd, "r");
80#endif
81    if (!fp) {
82        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to fork [%s]", cmd);
83        goto err;
84    }
85
86    stream = php_stream_fopen_from_pipe(fp, "rb");
87
88    buf = (char *) emalloc(EXEC_INPUT_BUF);
89    buflen = EXEC_INPUT_BUF;
90
91    if (type != 3) {
92        b = buf;
93
94        while (php_stream_get_line(stream, b, EXEC_INPUT_BUF, &bufl)) {
95            /* no new line found, let's read some more */
96            if (b[bufl - 1] != '\n' && !php_stream_eof(stream)) {
97                if (buflen < (bufl + (b - buf) + EXEC_INPUT_BUF)) {
98                    bufl += b - buf;
99                    buflen = bufl + EXEC_INPUT_BUF;
100                    buf = erealloc(buf, buflen);
101                    b = buf + bufl;
102                } else {
103                    b += bufl;
104                }
105                continue;
106            } else if (b != buf) {
107                bufl += b - buf;
108            }
109
110            if (type == 1) {
111                PHPWRITE(buf, bufl);
112                if (php_output_get_level(TSRMLS_C) < 1) {
113                    sapi_flush(TSRMLS_C);
114                }
115            } else if (type == 2) {
116                /* strip trailing whitespaces */
117                l = bufl;
118                while (l-- && isspace(((unsigned char *)buf)[l]));
119                if (l != (int)(bufl - 1)) {
120                    bufl = l + 1;
121                    buf[bufl] = '\0';
122                }
123                add_next_index_stringl(array, buf, bufl, 1);
124            }
125            b = buf;
126        }
127        if (bufl) {
128            /* strip trailing whitespaces if we have not done so already */
129            if ((type == 2 && buf != b) || type != 2) {
130                l = bufl;
131                while (l-- && isspace(((unsigned char *)buf)[l]));
132                if (l != (int)(bufl - 1)) {
133                    bufl = l + 1;
134                    buf[bufl] = '\0';
135                }
136                if (type == 2) {
137                    add_next_index_stringl(array, buf, bufl, 1);
138                }
139            }
140
141            /* Return last line from the shell command */
142            RETVAL_STRINGL(buf, bufl, 1);
143        } else { /* should return NULL, but for BC we return "" */
144            RETVAL_EMPTY_STRING();
145        }
146    } else {
147        while((bufl = php_stream_read(stream, buf, EXEC_INPUT_BUF)) > 0) {
148            PHPWRITE(buf, bufl);
149        }
150    }
151
152    pclose_return = php_stream_close(stream);
153    efree(buf);
154
155done:
156#if PHP_SIGCHILD
157    if (sig_handler) {
158        signal(SIGCHLD, sig_handler);
159    }
160#endif
161    if (d) {
162        efree(d);
163    }
164    return pclose_return;
165err:
166    pclose_return = -1;
167    goto done;
168}
169/* }}} */
170
171static void php_exec_ex(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */
172{
173    char *cmd;
174    int cmd_len;
175    zval *ret_code=NULL, *ret_array=NULL;
176    int ret;
177
178    if (mode) {
179        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z/", &cmd, &cmd_len, &ret_code) == FAILURE) {
180            RETURN_FALSE;
181        }
182    } else {
183        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z/z/", &cmd, &cmd_len, &ret_array, &ret_code) == FAILURE) {
184            RETURN_FALSE;
185        }
186    }
187    if (!cmd_len) {
188        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot execute a blank command");
189        RETURN_FALSE;
190    }
191    if (strlen(cmd) != cmd_len) {
192        php_error_docref(NULL TSRMLS_CC, E_WARNING, "NULL byte detected. Possible attack");
193        RETURN_FALSE;
194    }
195
196    if (!ret_array) {
197        ret = php_exec(mode, cmd, NULL, return_value TSRMLS_CC);
198    } else {
199        if (Z_TYPE_P(ret_array) != IS_ARRAY) {
200            zval_dtor(ret_array);
201            array_init(ret_array);
202        }
203        ret = php_exec(2, cmd, ret_array, return_value TSRMLS_CC);
204    }
205    if (ret_code) {
206        zval_dtor(ret_code);
207        ZVAL_LONG(ret_code, ret);
208    }
209}
210/* }}} */
211
212/* {{{ proto string exec(string command [, array &output [, int &return_value]])
213   Execute an external program */
214PHP_FUNCTION(exec)
215{
216    php_exec_ex(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
217}
218/* }}} */
219
220/* {{{ proto int system(string command [, int &return_value])
221   Execute an external program and display output */
222PHP_FUNCTION(system)
223{
224    php_exec_ex(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
225}
226/* }}} */
227
228/* {{{ proto void passthru(string command [, int &return_value])
229   Execute an external program and display raw output */
230PHP_FUNCTION(passthru)
231{
232    php_exec_ex(INTERNAL_FUNCTION_PARAM_PASSTHRU, 3);
233}
234/* }}} */
235
236/* {{{ php_escape_shell_cmd
237   Escape all chars that could possibly be used to
238   break out of a shell command
239
240   This function emalloc's a string and returns the pointer.
241   Remember to efree it when done with it.
242
243   *NOT* safe for binary strings
244*/
245PHPAPI char *php_escape_shell_cmd(char *str)
246{
247    register int x, y, l = strlen(str);
248    char *cmd;
249    char *p = NULL;
250    size_t estimate = (2 * l) + 1;
251
252    TSRMLS_FETCH();
253
254    cmd = safe_emalloc(2, l, 1);
255
256    for (x = 0, y = 0; x < l; x++) {
257        int mb_len = php_mblen(str + x, (l - x));
258
259        /* skip non-valid multibyte characters */
260        if (mb_len < 0) {
261            continue;
262        } else if (mb_len > 1) {
263            memcpy(cmd + y, str + x, mb_len);
264            y += mb_len;
265            x += mb_len - 1;
266            continue;
267        }
268
269        switch (str[x]) {
270#ifndef PHP_WIN32
271            case '"':
272            case '\'':
273                if (!p && (p = memchr(str + x + 1, str[x], l - x - 1))) {
274                    /* noop */
275                } else if (p && *p == str[x]) {
276                    p = NULL;
277                } else {
278                    cmd[y++] = '\\';
279                }
280                cmd[y++] = str[x];
281                break;
282#else
283            /* % is Windows specific for enviromental variables, ^%PATH% will
284                output PATH whil ^%PATH^% not. escapeshellcmd will escape all %.
285            */
286            case '%':
287            case '"':
288            case '\'':
289#endif
290            case '#': /* This is character-set independent */
291            case '&':
292            case ';':
293            case '`':
294            case '|':
295            case '*':
296            case '?':
297            case '~':
298            case '<':
299            case '>':
300            case '^':
301            case '(':
302            case ')':
303            case '[':
304            case ']':
305            case '{':
306            case '}':
307            case '$':
308            case '\\':
309            case '\x0A': /* excluding these two */
310            case '\xFF':
311#ifdef PHP_WIN32
312                cmd[y++] = '^';
313#else
314                cmd[y++] = '\\';
315#endif
316                /* fall-through */
317            default:
318                cmd[y++] = str[x];
319
320        }
321    }
322    cmd[y] = '\0';
323
324    if ((estimate - y) > 4096) {
325        /* realloc if the estimate was way overill
326         * Arbitrary cutoff point of 4096 */
327        cmd = erealloc(cmd, y + 1);
328    }
329
330    return cmd;
331}
332/* }}} */
333
334/* {{{ php_escape_shell_arg
335 */
336PHPAPI char *php_escape_shell_arg(char *str)
337{
338    int x, y = 0, l = strlen(str);
339    char *cmd;
340    size_t estimate = (4 * l) + 3;
341
342    TSRMLS_FETCH();
343
344    cmd = safe_emalloc(4, l, 3); /* worst case */
345
346#ifdef PHP_WIN32
347    cmd[y++] = '"';
348#else
349    cmd[y++] = '\'';
350#endif
351
352    for (x = 0; x < l; x++) {
353        int mb_len = php_mblen(str + x, (l - x));
354
355        /* skip non-valid multibyte characters */
356        if (mb_len < 0) {
357            continue;
358        } else if (mb_len > 1) {
359            memcpy(cmd + y, str + x, mb_len);
360            y += mb_len;
361            x += mb_len - 1;
362            continue;
363        }
364
365        switch (str[x]) {
366#ifdef PHP_WIN32
367        case '"':
368        case '%':
369            cmd[y++] = ' ';
370            break;
371#else
372        case '\'':
373            cmd[y++] = '\'';
374            cmd[y++] = '\\';
375            cmd[y++] = '\'';
376#endif
377            /* fall-through */
378        default:
379            cmd[y++] = str[x];
380        }
381    }
382#ifdef PHP_WIN32
383    cmd[y++] = '"';
384#else
385    cmd[y++] = '\'';
386#endif
387    cmd[y] = '\0';
388
389    if ((estimate - y) > 4096) {
390        /* realloc if the estimate was way overill
391         * Arbitrary cutoff point of 4096 */
392        cmd = erealloc(cmd, y + 1);
393    }
394    return cmd;
395}
396/* }}} */
397
398/* {{{ proto string escapeshellcmd(string command)
399   Escape shell metacharacters */
400PHP_FUNCTION(escapeshellcmd)
401{
402    char *command;
403    int command_len;
404    char *cmd = NULL;
405
406    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &command, &command_len) == FAILURE) {
407        return;
408    }
409
410    if (command_len) {
411        cmd = php_escape_shell_cmd(command);
412        RETVAL_STRING(cmd, 0);
413    } else {
414        RETVAL_EMPTY_STRING();
415    }
416}
417/* }}} */
418
419/* {{{ proto string escapeshellarg(string arg)
420   Quote and escape an argument for use in a shell command */
421PHP_FUNCTION(escapeshellarg)
422{
423    char *argument;
424    int argument_len;
425    char *cmd = NULL;
426
427    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &argument, &argument_len) == FAILURE) {
428        return;
429    }
430
431    if (argument) {
432        cmd = php_escape_shell_arg(argument);
433        RETVAL_STRING(cmd, 0);
434    }
435}
436/* }}} */
437
438/* {{{ proto string shell_exec(string cmd)
439   Execute command via shell and return complete output as string */
440PHP_FUNCTION(shell_exec)
441{
442    FILE *in;
443    size_t total_readbytes;
444    char *command;
445    int command_len;
446    char *ret;
447    php_stream *stream;
448
449    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &command, &command_len) == FAILURE) {
450        return;
451    }
452
453#ifdef PHP_WIN32
454    if ((in=VCWD_POPEN(command, "rt"))==NULL) {
455#else
456    if ((in=VCWD_POPEN(command, "r"))==NULL) {
457#endif
458        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to execute '%s'", command);
459        RETURN_FALSE;
460    }
461
462    stream = php_stream_fopen_from_pipe(in, "rb");
463    total_readbytes = php_stream_copy_to_mem(stream, &ret, PHP_STREAM_COPY_ALL, 0);
464    php_stream_close(stream);
465
466    if (total_readbytes > 0) {
467        RETVAL_STRINGL(ret, total_readbytes, 0);
468    }
469}
470/* }}} */
471
472#ifdef HAVE_NICE
473/* {{{ proto bool proc_nice(int priority)
474   Change the priority of the current process */
475PHP_FUNCTION(proc_nice)
476{
477    long pri;
478
479    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &pri) == FAILURE) {
480        RETURN_FALSE;
481    }
482
483    errno = 0;
484    php_ignore_value(nice(pri));
485    if (errno) {
486        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Only a super user may attempt to increase the priority of a process");
487        RETURN_FALSE;
488    }
489
490    RETURN_TRUE;
491}
492/* }}} */
493#endif
494
495/*
496 * Local variables:
497 * tab-width: 4
498 * c-basic-offset: 4
499 * End:
500 * vim600: sw=4 ts=4 fdm=marker
501 * vim<600: sw=4 ts=4
502 */
503