-
Notifications
You must be signed in to change notification settings - Fork 7.8k
/
Copy pathproc_open.c
1568 lines (1369 loc) · 43 KB
/
proc_open.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Wez Furlong <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include <ctype.h>
#include <signal.h>
#include "ext/standard/basic_functions.h"
#include "ext/standard/file.h"
#include "exec.h"
#include "SAPI.h"
#include "main/php_network.h"
#include "zend_smart_str.h"
#ifdef PHP_WIN32
# include "win32/sockets.h"
#endif
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_POSIX_SPAWN_FILE_ACTIONS_ADDCHDIR_NP
/* Only defined on glibc >= 2.29, FreeBSD CURRENT, musl >= 1.1.24,
* MacOS Catalina or later..
* It should be posible to modify this so it is also
* used in older systems when $cwd == NULL but care must be taken
* as at least glibc < 2.24 has a legacy implementation known
* to be really buggy.
*/
#include <spawn.h>
#define USE_POSIX_SPAWN
#endif
/* This symbol is defined in ext/standard/config.m4.
* Essentially, it is set if you HAVE_FORK || PHP_WIN32
* Other platforms may modify that configure check and add suitable #ifdefs
* around the alternate code. */
#ifdef PHP_CAN_SUPPORT_PROC_OPEN
#ifdef HAVE_OPENPTY
# ifdef HAVE_PTY_H
# include <pty.h>
# elif defined(__FreeBSD__)
/* FreeBSD defines `openpty` in <libutil.h> */
# include <libutil.h>
# elif defined(__NetBSD__) || defined(__DragonFly__)
/* On recent NetBSD/DragonFlyBSD releases the emalloc, estrdup ... calls had been introduced in libutil */
# if defined(__NetBSD__)
# include <sys/termios.h>
# else
# include <termios.h>
# endif
extern int openpty(int *, int *, char *, struct termios *, struct winsize *);
# elif defined(__sun)
# include <termios.h>
# else
/* Mac OS X (and some BSDs) define `openpty` in <util.h> */
# include <util.h>
# endif
#elif defined(__sun)
# include <fcntl.h>
# include <stropts.h>
# include <termios.h>
# define HAVE_OPENPTY 1
/* Solaris before version 11.4 and Illumos do not have any openpty implementation */
int openpty(int *master, int *slave, char *name, struct termios *termp, struct winsize *winp)
{
int fd, sd;
const char *slaveid;
assert(master);
assert(slave);
sd = *master = *slave = -1;
fd = open("/dev/ptmx", O_NOCTTY|O_RDWR);
if (fd == -1) {
return -1;
}
/* Checking if we can have to the pseudo terminal */
if (grantpt(fd) != 0 || unlockpt(fd) != 0) {
goto fail;
}
slaveid = ptsname(fd);
if (!slaveid) {
goto fail;
}
/* Getting the slave path and pushing pseudo terminal */
sd = open(slaveid, O_NOCTTY|O_RDONLY);
if (sd == -1 || ioctl(sd, I_PUSH, "ptem") == -1) {
goto fail;
}
if (termp) {
if (tcgetattr(sd, termp) < 0) {
goto fail;
}
}
if (winp) {
if (ioctl(sd, TIOCSWINSZ, winp) == -1) {
goto fail;
}
}
*slave = sd;
*master = fd;
return 0;
fail:
if (sd != -1) {
close(sd);
}
if (fd != -1) {
close(fd);
}
return -1;
}
#endif
#include "proc_open.h"
static int le_proc_open; /* Resource number for `proc` resources */
/* {{{ _php_array_to_envp
* Process the `environment` argument to `proc_open`
* Convert into data structures which can be passed to underlying OS APIs like `exec` on POSIX or
* `CreateProcessW` on Win32 */
static php_process_env _php_array_to_envp(zval *environment)
{
zval *element;
php_process_env env;
zend_string *key, *str;
#ifndef PHP_WIN32
char **ep;
#endif
char *p;
size_t sizeenv = 0;
HashTable *env_hash; /* temporary PHP array used as helper */
memset(&env, 0, sizeof(env));
if (!environment) {
return env;
}
uint32_t cnt = zend_hash_num_elements(Z_ARRVAL_P(environment));
if (cnt < 1) {
#ifndef PHP_WIN32
env.envarray = (char **) ecalloc(1, sizeof(char *));
#endif
env.envp = (char *) ecalloc(4, 1);
return env;
}
ALLOC_HASHTABLE(env_hash);
zend_hash_init(env_hash, cnt, NULL, NULL, 0);
/* first, we have to get the size of all the elements in the hash */
ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(environment), key, element) {
str = zval_get_string(element);
if (ZSTR_LEN(str) == 0) {
zend_string_release_ex(str, 0);
continue;
}
sizeenv += ZSTR_LEN(str) + 1;
if (key && ZSTR_LEN(key)) {
sizeenv += ZSTR_LEN(key) + 1;
zend_hash_add_ptr(env_hash, key, str);
} else {
zend_hash_next_index_insert_ptr(env_hash, str);
}
} ZEND_HASH_FOREACH_END();
#ifndef PHP_WIN32
ep = env.envarray = (char **) ecalloc(cnt + 1, sizeof(char *));
#endif
p = env.envp = (char *) ecalloc(sizeenv + 4, 1);
ZEND_HASH_FOREACH_STR_KEY_PTR(env_hash, key, str) {
#ifndef PHP_WIN32
*ep = p;
++ep;
#endif
if (key) {
p = zend_mempcpy(p, ZSTR_VAL(key), ZSTR_LEN(key));
*p++ = '=';
}
p = zend_mempcpy(p, ZSTR_VAL(str), ZSTR_LEN(str));
*p++ = '\0';
zend_string_release_ex(str, 0);
} ZEND_HASH_FOREACH_END();
assert((uint32_t)(p - env.envp) <= sizeenv);
zend_hash_destroy(env_hash);
FREE_HASHTABLE(env_hash);
return env;
}
/* }}} */
/* {{{ _php_free_envp
* Free the structures allocated by `_php_array_to_envp` */
static void _php_free_envp(php_process_env env)
{
#ifndef PHP_WIN32
if (env.envarray) {
efree(env.envarray);
}
#endif
if (env.envp) {
efree(env.envp);
}
}
/* }}} */
#ifdef HAVE_SYS_WAIT_H
static pid_t waitpid_cached(php_process_handle *proc, int *wait_status, int options)
{
if (proc->has_cached_exit_wait_status) {
*wait_status = proc->cached_exit_wait_status_value;
return proc->child;
}
pid_t wait_pid = waitpid(proc->child, wait_status, options);
/* The "exit" status is the final status of the process.
* If we were to cache the status unconditionally,
* we would return stale statuses in the future after the process continues. */
if (wait_pid > 0 && WIFEXITED(*wait_status)) {
proc->has_cached_exit_wait_status = true;
proc->cached_exit_wait_status_value = *wait_status;
}
return wait_pid;
}
#endif
/* {{{ proc_open_rsrc_dtor
* Free `proc` resource, either because all references to it were dropped or because `pclose` or
* `proc_close` were called */
static void proc_open_rsrc_dtor(zend_resource *rsrc)
{
php_process_handle *proc = (php_process_handle*)rsrc->ptr;
#ifdef PHP_WIN32
DWORD wstatus;
#elif HAVE_SYS_WAIT_H
int wstatus;
int waitpid_options = 0;
pid_t wait_pid;
#endif
/* Close all handles to avoid a deadlock */
for (int i = 0; i < proc->npipes; i++) {
if (proc->pipes[i] != NULL) {
GC_DELREF(proc->pipes[i]);
zend_list_close(proc->pipes[i]);
proc->pipes[i] = NULL;
}
}
/* `pclose_wait` tells us: Are we freeing this resource because `pclose` or `proc_close` were
* called? If so, we need to wait until the child process exits, because its exit code is
* needed as the return value of those functions.
* But if we're freeing the resource because of GC, don't wait. */
#ifdef PHP_WIN32
if (FG(pclose_wait)) {
WaitForSingleObject(proc->childHandle, INFINITE);
}
GetExitCodeProcess(proc->childHandle, &wstatus);
if (wstatus == STILL_ACTIVE) {
FG(pclose_ret) = -1;
} else {
FG(pclose_ret) = wstatus;
}
CloseHandle(proc->childHandle);
#elif HAVE_SYS_WAIT_H
if (!FG(pclose_wait)) {
waitpid_options = WNOHANG;
}
do {
wait_pid = waitpid_cached(proc, &wstatus, waitpid_options);
} while (wait_pid == -1 && errno == EINTR);
if (wait_pid <= 0) {
FG(pclose_ret) = -1;
} else {
if (WIFEXITED(wstatus)) {
wstatus = WEXITSTATUS(wstatus);
}
FG(pclose_ret) = wstatus;
}
#else
FG(pclose_ret) = -1;
#endif
_php_free_envp(proc->env);
efree(proc->pipes);
zend_string_release_ex(proc->command, false);
efree(proc);
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION(proc_open) */
PHP_MINIT_FUNCTION(proc_open)
{
le_proc_open = zend_register_list_destructors_ex(proc_open_rsrc_dtor, NULL, "process",
module_number);
return SUCCESS;
}
/* }}} */
/* {{{ Kill a process opened by `proc_open` */
PHP_FUNCTION(proc_terminate)
{
zval *zproc;
php_process_handle *proc;
zend_long sig_no = SIGTERM;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_RESOURCE(zproc)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(sig_no)
ZEND_PARSE_PARAMETERS_END();
proc = (php_process_handle*)zend_fetch_resource(Z_RES_P(zproc), "process", le_proc_open);
if (proc == NULL) {
RETURN_THROWS();
}
#ifdef PHP_WIN32
RETURN_BOOL(TerminateProcess(proc->childHandle, 255));
#else
RETURN_BOOL(kill(proc->child, sig_no) == 0);
#endif
}
/* }}} */
/* {{{ Close a process opened by `proc_open` */
PHP_FUNCTION(proc_close)
{
zval *zproc;
php_process_handle *proc;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_RESOURCE(zproc)
ZEND_PARSE_PARAMETERS_END();
proc = (php_process_handle*)zend_fetch_resource(Z_RES_P(zproc), "process", le_proc_open);
if (proc == NULL) {
RETURN_THROWS();
}
FG(pclose_wait) = 1; /* See comment in `proc_open_rsrc_dtor` */
zend_list_close(Z_RES_P(zproc));
FG(pclose_wait) = 0;
RETURN_LONG(FG(pclose_ret));
}
/* }}} */
/* {{{ Get information about a process opened by `proc_open` */
PHP_FUNCTION(proc_get_status)
{
zval *zproc;
php_process_handle *proc;
#ifdef PHP_WIN32
DWORD wstatus;
#elif HAVE_SYS_WAIT_H
int wstatus;
pid_t wait_pid;
#endif
bool running = 1, signaled = 0, stopped = 0;
int exitcode = -1, termsig = 0, stopsig = 0;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_RESOURCE(zproc)
ZEND_PARSE_PARAMETERS_END();
proc = (php_process_handle*)zend_fetch_resource(Z_RES_P(zproc), "process", le_proc_open);
if (proc == NULL) {
RETURN_THROWS();
}
array_init(return_value);
add_assoc_str(return_value, "command", zend_string_copy(proc->command));
add_assoc_long(return_value, "pid", (zend_long)proc->child);
#ifdef PHP_WIN32
GetExitCodeProcess(proc->childHandle, &wstatus);
running = wstatus == STILL_ACTIVE;
exitcode = running ? -1 : wstatus;
/* The status is always available on Windows and will always read the same,
* even if the child has already exited. This is because the result stays available
* until the child handle is closed. Hence no caching is used on Windows. */
add_assoc_bool(return_value, "cached", false);
#elif HAVE_SYS_WAIT_H
wait_pid = waitpid_cached(proc, &wstatus, WNOHANG|WUNTRACED);
if (wait_pid == proc->child) {
if (WIFEXITED(wstatus)) {
running = 0;
exitcode = WEXITSTATUS(wstatus);
}
if (WIFSIGNALED(wstatus)) {
running = 0;
signaled = 1;
termsig = WTERMSIG(wstatus);
}
if (WIFSTOPPED(wstatus)) {
stopped = 1;
stopsig = WSTOPSIG(wstatus);
}
} else if (wait_pid == -1) {
/* The only error which could occur here is ECHILD, which means that the PID we were
* looking for either does not exist or is not a child of this process */
running = 0;
}
add_assoc_bool(return_value, "cached", proc->has_cached_exit_wait_status);
#endif
add_assoc_bool(return_value, "running", running);
add_assoc_bool(return_value, "signaled", signaled);
add_assoc_bool(return_value, "stopped", stopped);
add_assoc_long(return_value, "exitcode", exitcode);
add_assoc_long(return_value, "termsig", termsig);
add_assoc_long(return_value, "stopsig", stopsig);
}
/* }}} */
#ifdef PHP_WIN32
/* We use this to allow child processes to inherit handles
* One static instance can be shared and used for all calls to `proc_open`, since the values are
* never changed */
SECURITY_ATTRIBUTES php_proc_open_security = {
.nLength = sizeof(SECURITY_ATTRIBUTES),
.lpSecurityDescriptor = NULL,
.bInheritHandle = TRUE
};
# define pipe(pair) (CreatePipe(&pair[0], &pair[1], &php_proc_open_security, 0) ? 0 : -1)
# define COMSPEC_NT "cmd.exe"
static inline HANDLE dup_handle(HANDLE src, BOOL inherit, BOOL closeorig)
{
HANDLE copy, self = GetCurrentProcess();
if (!DuplicateHandle(self, src, self, ©, 0, inherit, DUPLICATE_SAME_ACCESS |
(closeorig ? DUPLICATE_CLOSE_SOURCE : 0)))
return NULL;
return copy;
}
static inline HANDLE dup_fd_as_handle(int fd)
{
return dup_handle((HANDLE)_get_osfhandle(fd), TRUE, FALSE);
}
# define close_descriptor(fd) CloseHandle(fd)
#else /* !PHP_WIN32 */
# define close_descriptor(fd) close(fd)
#endif
/* Determines the type of a descriptor item. */
typedef enum _descriptor_type {
DESCRIPTOR_TYPE_STD,
DESCRIPTOR_TYPE_PIPE,
DESCRIPTOR_TYPE_SOCKET
} descriptor_type;
/* One instance of this struct is created for each item in `$descriptorspec` argument to `proc_open`
* They are used within `proc_open` and freed before it returns */
typedef struct _descriptorspec_item {
int index; /* desired FD # in child process */
descriptor_type type;
php_file_descriptor_t childend; /* FD # opened for use in child
* (will be copied to `index` in child) */
php_file_descriptor_t parentend; /* FD # opened for use in parent
* (for pipes only; will be 0 otherwise) */
int mode_flags; /* mode for opening FDs: r/o, r/w, binary (on Win32), etc */
} descriptorspec_item;
static zend_string *get_valid_arg_string(zval *zv, int elem_num) {
zend_string *str = zval_get_string(zv);
if (!str) {
return NULL;
}
if (elem_num == 1 && ZSTR_LEN(str) == 0) {
zend_value_error("First element must contain a non-empty program name");
zend_string_release(str);
return NULL;
}
if (strlen(ZSTR_VAL(str)) != ZSTR_LEN(str)) {
zend_value_error("Command array element %d contains a null byte", elem_num);
zend_string_release(str);
return NULL;
}
return str;
}
#ifdef PHP_WIN32
static void append_backslashes(smart_str *str, size_t num_bs)
{
for (size_t i = 0; i < num_bs; i++) {
smart_str_appendc(str, '\\');
}
}
const char *special_chars = "()!^\"<>&|%";
static bool is_special_character_present(const zend_string *arg)
{
for (size_t i = 0; i < ZSTR_LEN(arg); ++i) {
if (strchr(special_chars, ZSTR_VAL(arg)[i]) != NULL) {
return true;
}
}
return false;
}
/* See https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments and
* https://learn.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way */
static void append_win_escaped_arg(smart_str *str, zend_string *arg, bool is_cmd_argument)
{
size_t num_bs = 0;
bool has_special_character = false;
if (is_cmd_argument) {
has_special_character = is_special_character_present(arg);
if (has_special_character) {
/* Escape double quote with ^ if executed by cmd.exe. */
smart_str_appendc(str, '^');
}
}
smart_str_appendc(str, '"');
for (size_t i = 0; i < ZSTR_LEN(arg); ++i) {
char c = ZSTR_VAL(arg)[i];
if (c == '\\') {
num_bs++;
continue;
}
if (c == '"') {
/* Backslashes before " need to be doubled. */
num_bs = num_bs * 2 + 1;
}
append_backslashes(str, num_bs);
if (has_special_character && strchr(special_chars, c) != NULL) {
/* Escape special chars with ^ if executed by cmd.exe. */
smart_str_appendc(str, '^');
}
smart_str_appendc(str, c);
num_bs = 0;
}
append_backslashes(str, num_bs * 2);
if (has_special_character) {
/* Escape double quote with ^ if executed by cmd.exe. */
smart_str_appendc(str, '^');
}
smart_str_appendc(str, '"');
}
static bool is_executed_by_cmd(const char *prog_name, size_t prog_name_length)
{
size_t out_len;
WCHAR long_name[MAX_PATH];
WCHAR full_name[MAX_PATH];
LPWSTR file_part = NULL;
wchar_t *prog_name_wide = php_win32_cp_conv_any_to_w(prog_name, prog_name_length, &out_len);
if (GetLongPathNameW(prog_name_wide, long_name, MAX_PATH) == 0) {
/* This can fail for example with ERROR_FILE_NOT_FOUND (short path resolution only works for existing files)
* in which case we'll pass the path verbatim to the FullPath transformation. */
lstrcpynW(long_name, prog_name_wide, MAX_PATH);
}
free(prog_name_wide);
prog_name_wide = NULL;
if (GetFullPathNameW(long_name, MAX_PATH, full_name, &file_part) == 0 || file_part == NULL) {
return false;
}
bool uses_cmd = false;
if (_wcsicmp(file_part, L"cmd.exe") == 0 || _wcsicmp(file_part, L"cmd") == 0) {
uses_cmd = true;
} else {
const WCHAR *extension_dot = wcsrchr(file_part, L'.');
if (extension_dot && (_wcsicmp(extension_dot, L".bat") == 0 || _wcsicmp(extension_dot, L".cmd") == 0)) {
uses_cmd = true;
}
}
return uses_cmd;
}
static zend_string *create_win_command_from_args(HashTable *args)
{
smart_str str = {0};
zval *arg_zv;
bool is_prog_name = true;
bool is_cmd_execution = false;
int elem_num = 0;
ZEND_HASH_FOREACH_VAL(args, arg_zv) {
zend_string *arg_str = get_valid_arg_string(arg_zv, ++elem_num);
if (!arg_str) {
smart_str_free(&str);
return NULL;
}
if (is_prog_name) {
is_cmd_execution = is_executed_by_cmd(ZSTR_VAL(arg_str), ZSTR_LEN(arg_str));
} else {
smart_str_appendc(&str, ' ');
}
append_win_escaped_arg(&str, arg_str, !is_prog_name && is_cmd_execution);
is_prog_name = 0;
zend_string_release(arg_str);
} ZEND_HASH_FOREACH_END();
smart_str_0(&str);
return str.s;
}
/* Get a boolean option from the `other_options` array which can be passed to `proc_open`.
* (Currently, all options apply on Windows only.) */
static bool get_option(zval *other_options, char *opt_name, size_t opt_name_len)
{
HashTable *opt_ary = Z_ARRVAL_P(other_options);
zval *item = zend_hash_str_find_deref(opt_ary, opt_name, opt_name_len);
return item != NULL &&
(Z_TYPE_P(item) == IS_TRUE ||
((Z_TYPE_P(item) == IS_LONG) && Z_LVAL_P(item)));
}
/* Initialize STARTUPINFOW struct, used on Windows when spawning a process.
* Ref: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfow */
static void init_startup_info(STARTUPINFOW *si, descriptorspec_item *descriptors, int ndesc)
{
memset(si, 0, sizeof(STARTUPINFOW));
si->cb = sizeof(STARTUPINFOW);
si->dwFlags = STARTF_USESTDHANDLES;
si->hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si->hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si->hStdError = GetStdHandle(STD_ERROR_HANDLE);
/* redirect stdin/stdout/stderr if requested */
for (int i = 0; i < ndesc; i++) {
switch (descriptors[i].index) {
case 0:
si->hStdInput = descriptors[i].childend;
break;
case 1:
si->hStdOutput = descriptors[i].childend;
break;
case 2:
si->hStdError = descriptors[i].childend;
break;
}
}
}
static void init_process_info(PROCESS_INFORMATION *pi)
{
memset(&pi, 0, sizeof(pi));
}
/* on success, returns length of *comspec, which then needs to be efree'd by caller */
static size_t find_comspec_nt(wchar_t **comspec)
{
zend_string *path = NULL;
wchar_t *pathw = NULL;
wchar_t *bufp = NULL;
DWORD buflen = MAX_PATH, len = 0;
path = php_getenv("PATH", 4);
if (path == NULL) {
goto out;
}
pathw = php_win32_cp_any_to_w(ZSTR_VAL(path));
if (pathw == NULL) {
goto out;
}
bufp = emalloc(buflen * sizeof(wchar_t));
do {
/* the first call to SearchPathW() fails if the buffer is too small,
* what is unlikely but possible; to avoid an explicit second call to
* SeachPathW() and the error handling, we're looping */
len = SearchPathW(pathw, L"cmd.exe", NULL, buflen, bufp, NULL);
if (len == 0) {
goto out;
}
if (len < buflen) {
break;
}
buflen = len;
bufp = erealloc(bufp, buflen * sizeof(wchar_t));
} while (1);
*comspec = bufp;
out:
if (path != NULL) {
zend_string_release(path);
}
if (pathw != NULL) {
free(pathw);
}
if (bufp != NULL && bufp != *comspec) {
efree(bufp);
}
return len;
}
static zend_result convert_command_to_use_shell(wchar_t **cmdw, size_t cmdw_len)
{
wchar_t *comspec;
size_t len = find_comspec_nt(&comspec);
if (len == 0) {
php_error_docref(NULL, E_WARNING, "Command conversion failed");
return FAILURE;
}
len += sizeof(" /s /c ") + cmdw_len + 3;
wchar_t *cmdw_shell = (wchar_t *)malloc(len * sizeof(wchar_t));
if (cmdw_shell == NULL) {
efree(comspec);
php_error_docref(NULL, E_WARNING, "Command conversion failed");
return FAILURE;
}
if (_snwprintf(cmdw_shell, len, L"%s /s /c \"%s\"", comspec, *cmdw) == -1) {
efree(comspec);
free(cmdw_shell);
php_error_docref(NULL, E_WARNING, "Command conversion failed");
return FAILURE;
}
efree(comspec);
free(*cmdw);
*cmdw = cmdw_shell;
return SUCCESS;
}
#endif
/* Convert command parameter array passed as first argument to `proc_open` into command string */
static zend_string* get_command_from_array(HashTable *array, char ***argv, int num_elems)
{
zval *arg_zv;
zend_string *command = NULL;
int i = 0;
*argv = safe_emalloc(sizeof(char *), num_elems + 1, 0);
ZEND_HASH_FOREACH_VAL(array, arg_zv) {
zend_string *arg_str = get_valid_arg_string(arg_zv, i + 1);
if (!arg_str) {
/* Terminate with NULL so exit_fail code knows how many entries to free */
(*argv)[i] = NULL;
if (command != NULL) {
zend_string_release_ex(command, false);
}
return NULL;
}
if (i == 0) {
command = zend_string_copy(arg_str);
}
(*argv)[i++] = estrdup(ZSTR_VAL(arg_str));
zend_string_release(arg_str);
} ZEND_HASH_FOREACH_END();
(*argv)[i] = NULL;
return command;
}
static descriptorspec_item* alloc_descriptor_array(HashTable *descriptorspec)
{
uint32_t ndescriptors = zend_hash_num_elements(descriptorspec);
return ecalloc(ndescriptors, sizeof(descriptorspec_item));
}
static zend_string* get_string_parameter(zval *array, int index, char *param_name)
{
zval *array_item;
if ((array_item = zend_hash_index_find(Z_ARRVAL_P(array), index)) == NULL) {
zend_value_error("Missing %s", param_name);
return NULL;
}
return zval_try_get_string(array_item);
}
static zend_result set_proc_descriptor_to_blackhole(descriptorspec_item *desc)
{
#ifdef PHP_WIN32
desc->childend = CreateFileA("nul", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (desc->childend == NULL) {
php_error_docref(NULL, E_WARNING, "Failed to open nul");
return FAILURE;
}
#else
desc->childend = open("/dev/null", O_RDWR);
if (desc->childend < 0) {
php_error_docref(NULL, E_WARNING, "Failed to open /dev/null: %s", strerror(errno));
return FAILURE;
}
#endif
return SUCCESS;
}
static zend_result set_proc_descriptor_to_pty(descriptorspec_item *desc, int *master_fd, int *slave_fd)
{
#ifdef HAVE_OPENPTY
/* All FDs set to PTY in the child process will go to the slave end of the same PTY.
* Likewise, all the corresponding entries in `$pipes` in the parent will all go to the master
* end of the same PTY.
* If this is the first descriptorspec set to 'pty', find an available PTY and get master and
* slave FDs. */
if (*master_fd == -1) {
if (openpty(master_fd, slave_fd, NULL, NULL, NULL)) {
php_error_docref(NULL, E_WARNING, "Could not open PTY (pseudoterminal): %s", strerror(errno));
return FAILURE;
}
}
desc->type = DESCRIPTOR_TYPE_PIPE;
desc->childend = dup(*slave_fd);
desc->parentend = dup(*master_fd);
desc->mode_flags = O_RDWR;
return SUCCESS;
#else
php_error_docref(NULL, E_WARNING, "PTY (pseudoterminal) not supported on this system");
return FAILURE;
#endif
}
/* Mark the descriptor close-on-exec, so it won't be inherited by children */
static php_file_descriptor_t make_descriptor_cloexec(php_file_descriptor_t fd)
{
#ifdef PHP_WIN32
return dup_handle(fd, FALSE, TRUE);
#else
#if defined(F_SETFD) && defined(FD_CLOEXEC)
fcntl(fd, F_SETFD, FD_CLOEXEC);
#endif
return fd;
#endif
}
static zend_result set_proc_descriptor_to_pipe(descriptorspec_item *desc, zend_string *zmode)
{
php_file_descriptor_t newpipe[2];
if (pipe(newpipe)) {
php_error_docref(NULL, E_WARNING, "Unable to create pipe %s", strerror(errno));
return FAILURE;
}
desc->type = DESCRIPTOR_TYPE_PIPE;
if (!zend_string_starts_with_literal(zmode, "w")) {
desc->parentend = newpipe[1];
desc->childend = newpipe[0];
desc->mode_flags = O_WRONLY;
} else {
desc->parentend = newpipe[0];
desc->childend = newpipe[1];
desc->mode_flags = O_RDONLY;
}
desc->parentend = make_descriptor_cloexec(desc->parentend);
#ifdef PHP_WIN32
if (ZSTR_LEN(zmode) >= 2 && ZSTR_VAL(zmode)[1] == 'b')
desc->mode_flags |= O_BINARY;
#endif
return SUCCESS;
}
#ifdef PHP_WIN32
#define create_socketpair(socks) socketpair_win32(AF_INET, SOCK_STREAM, 0, (socks), 0)
#else
#define create_socketpair(socks) socketpair(AF_UNIX, SOCK_STREAM, 0, (socks))
#endif
static zend_result set_proc_descriptor_to_socket(descriptorspec_item *desc)
{
php_socket_t sock[2];
if (create_socketpair(sock)) {
zend_string *err = php_socket_error_str(php_socket_errno());
php_error_docref(NULL, E_WARNING, "Unable to create socket pair: %s", ZSTR_VAL(err));
zend_string_release(err);
return FAILURE;
}
desc->type = DESCRIPTOR_TYPE_SOCKET;
desc->parentend = make_descriptor_cloexec((php_file_descriptor_t) sock[0]);
/* Pass sock[1] to child because it will never use overlapped IO on Windows. */
desc->childend = (php_file_descriptor_t) sock[1];
return SUCCESS;
}
static zend_result set_proc_descriptor_to_file(descriptorspec_item *desc, zend_string *file_path,
zend_string *file_mode)
{
php_socket_t fd;
/* try a wrapper */
php_stream *stream = php_stream_open_wrapper(ZSTR_VAL(file_path), ZSTR_VAL(file_mode),
REPORT_ERRORS|STREAM_WILL_CAST, NULL);
if (stream == NULL) {
return FAILURE;
}
/* force into an fd */
if (php_stream_cast(stream, PHP_STREAM_CAST_RELEASE|PHP_STREAM_AS_FD, (void **)&fd,
REPORT_ERRORS) == FAILURE) {
return FAILURE;
}
#ifdef PHP_WIN32
desc->childend = dup_fd_as_handle((int)fd);
_close((int)fd);
/* Simulate the append mode by fseeking to the end of the file
* This introduces a potential race condition, but it is the best we can do */
if (strchr(ZSTR_VAL(file_mode), 'a')) {
SetFilePointer(desc->childend, 0, NULL, FILE_END);
}
#else
desc->childend = fd;
#endif
return SUCCESS;
}
static zend_result dup_proc_descriptor(php_file_descriptor_t from, php_file_descriptor_t *to,
zend_ulong nindex)
{
#ifdef PHP_WIN32
*to = dup_handle(from, TRUE, FALSE);
if (*to == NULL) {
php_error_docref(NULL, E_WARNING, "Failed to dup() for descriptor " ZEND_LONG_FMT, nindex);
return FAILURE;
}
#else
*to = dup(from);
if (*to < 0) {
php_error_docref(NULL, E_WARNING, "Failed to dup() for descriptor " ZEND_LONG_FMT ": %s",
nindex, strerror(errno));
return FAILURE;
}
#endif
return SUCCESS;
}
static zend_result redirect_proc_descriptor(descriptorspec_item *desc, int target,
descriptorspec_item *descriptors, int ndesc, int nindex)
{
php_file_descriptor_t redirect_to = PHP_INVALID_FD;
for (int i = 0; i < ndesc; i++) {