-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
nt.c
2180 lines (1821 loc) · 45.9 KB
/
nt.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) 1993, Intergraph Corporation
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the perl README file.
*
* Various Unix compatibility functions and NT specific functions.
*
* Some of this code was derived from the MSDOS port(s) and the OS/2 port.
*
*/
#include "ruby.h"
#include <fcntl.h>
#include <process.h>
#include <sys/stat.h>
/* #include <sys/wait.h> */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <windows.h>
#include <winbase.h>
#include <wincon.h>
#include "nt.h"
#include "dir.h"
#ifndef index
#define index(x, y) strchr((x), (y))
#endif
#ifndef bool
#define bool int
#endif
bool NtSyncProcess = TRUE;
#if 0 // declared in header file
extern char **environ;
#define environ _environ
#endif
static bool NtHasRedirection (char *);
static int valid_filename(char *s);
static void StartSockets ();
static char *str_grow(struct RString *str, size_t new_size);
char *NTLoginName;
DWORD Win32System = (DWORD)-1;
static DWORD
IdOS(void)
{
static OSVERSIONINFO osver;
if (osver.dwPlatformId != Win32System) {
memset(&osver, 0, sizeof(OSVERSIONINFO));
osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osver);
Win32System = osver.dwPlatformId;
}
return (Win32System);
}
static int
IsWin95(void) {
return (IdOS() == VER_PLATFORM_WIN32_WINDOWS);
}
static int
IsWinNT(void) {
return (IdOS() == VER_PLATFORM_WIN32_NT);
}
/* simulate flock by locking a range on the file */
#define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
#define LK_LEN 0xffff0000
int
flock(int fd, int oper)
{
OVERLAPPED o;
int i = -1;
HANDLE fh;
fh = (HANDLE)_get_osfhandle(fd);
memset(&o, 0, sizeof(o));
if(IsWinNT()) {
switch(oper) {
case LOCK_SH: /* shared lock */
LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
break;
case LOCK_EX: /* exclusive lock */
LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
break;
case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
break;
case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
LK_ERR(LockFileEx(fh,
LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
0, LK_LEN, 0, &o),i);
if(errno == EDOM) errno = EWOULDBLOCK;
break;
case LOCK_UN: /* unlock lock */
if (UnlockFileEx(fh, 0, LK_LEN, 0, &o)) {
i = 0;
}
else {
/* GetLastError() must returns `ERROR_NOT_LOCKED' */
errno = EWOULDBLOCK;
}
if(errno == EDOM) errno = EWOULDBLOCK;
break;
default: /* unknown */
errno = EINVAL;
break;
}
}
else if(IsWin95()) {
switch(oper) {
case LOCK_EX:
while(i == -1) {
LK_ERR(LockFile(fh, 0, 0, LK_LEN, 0), i);
if(errno != EDOM && i == -1) break;
}
break;
case LOCK_EX | LOCK_NB:
LK_ERR(LockFile(fh, 0, 0, LK_LEN, 0), i);
if(errno == EDOM) errno = EWOULDBLOCK;
break;
case LOCK_UN:
LK_ERR(UnlockFile(fh, 0, 0, LK_LEN, 0), i);
if(errno == EDOM) errno = EWOULDBLOCK;
break;
default:
errno = EINVAL;
break;
}
}
return i;
}
#undef LK_ERR
#undef LK_LEN
#undef const
FILE *fdopen(int, const char *);
#if 0
void
sleep(unsigned int len)
{
time_t end;
end = time((time_t *)0) + len;
while (time((time_t *)0) < end)
;
}
#endif
//
// Initialization stuff
//
#if (_MSC_VER >= 1000)
__declspec(dllexport) void __stdcall
#else
void
#endif
NtInitialize(int *argc, char ***argv) {
WORD version;
int ret;
//
// subvert cmd.exe\'s feeble attempt at command line parsing
//
*argc = NtMakeCmdVector((char *)GetCommandLine(), argv, TRUE);
//
// Now set up the correct time stuff
//
tzset();
// Initialize Winsock
// StartSockets();
}
char *getlogin()
{
char buffer[200];
int len = 200;
extern char *NTLoginName;
if (NTLoginName == NULL) {
if (GetUserName(buffer, &len)) {
NTLoginName = ALLOC_N(char, len+1);
strncpy(NTLoginName, buffer, len);
NTLoginName[len] = '\0';
}
else {
NTLoginName = "<Unknown>";
}
}
return NTLoginName;
}
#if 1
// popen stuff
//
// use these so I can remember which index is which
//
#define NtPipeRead 0 // index of pipe read descriptor
#define NtPipeWrite 1 // index of pipe write descriptor
#define NtPipeSize 1024 // size of pipe buffer
#define MYPOPENSIZE 256 // size of book keeping structure
struct {
int inuse;
int pid;
HANDLE oshandle;
FILE *pipe;
} MyPopenRecord[MYPOPENSIZE];
int SafeFree(char **vec, int vecc)
{
// vec
// |
// V ^---------------------V
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
// | | | .... | NULL | | ..... |\0 | | ..... |\0 |...
// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
// |- elements+1 -| ^ 1st element ^ 2nd element
char *p;
p = (char *)(vec - (vecc * sizeof (char *) + 1));
free(p);
return 0;
}
static char *szInternalCmds[] = {
"cd",
"chdir",
"cls",
"copy",
"date",
"del",
"dir",
"echo",
"erase",
"label",
"md",
"mkdir",
"path",
"rd",
"rem",
"ren",
"rename",
"rmdir",
"set",
"start",
"time",
"type",
"ver",
"vol",
};
int
isInternalCmd(char *cmd)
{
int fRet;
char **vec;
int vecc = NtMakeCmdVector(cmd, &vec, FALSE);
SafeFree (vec, vecc);
return 0;
}
FILE *
mypopen (char *cmd, char *mode)
{
FILE *fp;
int saved, reading;
int pipemode;
int pipes[2];
int pid;
int slot;
static initialized = 0;
//
// if first time through, intialize our book keeping structure
//
if (!initialized++) {
for (slot = 0; slot < MYPOPENSIZE; slot++)
MyPopenRecord[slot].inuse = FALSE;
}
//printf("mypopen %s\n", cmd);
//
// find a free popen slot
//
for (slot = 0; slot < MYPOPENSIZE && MyPopenRecord[slot].inuse; slot++)
;
if (slot > MYPOPENSIZE) {
return NULL;
}
//
// Figure out what we\'re doing...
//
reading = (*mode == 'r') ? TRUE : FALSE;
pipemode = (*(mode+1) == 'b') ? O_BINARY : O_TEXT;
//
// Now get a pipe
//
#if 0
if (_pipe(pipes, NtPipeSize, pipemode) == -1) {
return NULL;
}
if (reading) {
//
// we\'re reading from the pipe, so we must hook up the
// write end of the pipe to the new processes stdout.
// To do this we must save our file handle from stdout
// by _dup\'ing it, then setting our stdout to be the pipe\'s
// write descriptor. We must also make the write handle
// inheritable so the new process can use it.
if ((saved = _dup(fileno(stdout))) == -1) {
_close(pipes[NtPipeRead]);
_close(pipes[NtPipeWrite]);
return NULL;
}
if (_dup2 (pipes[NtPipeWrite], fileno(stdout)) == -1) {
_close(pipes[NtPipeRead]);
_close(pipes[NtPipeWrite]);
return NULL;
}
}
else {
//
// must be writing to the new process. Do the opposite of
// the above, i.e. hook up the processes stdin to the read
// end of the pipe.
//
if ((saved = _dup(fileno(stdin))) == -1) {
_close(pipes[NtPipeRead]);
_close(pipes[NtPipeWrite]);
return NULL;
}
if (_dup2(pipes[NtPipeRead], fileno(stdin)) == -1) {
_close(pipes[NtPipeRead]);
_close(pipes[NtPipeWrite]);
return NULL;
}
}
//
// Start the new process. Must set _fileinfo to non-zero value
// for file descriptors to be inherited. Reset after the process
// is started.
//
if (NtHasRedirection(cmd)) {
docmd:
pid = spawnlpe(_P_NOWAIT, "cmd.exe", "/c", cmd, 0, environ);
if (pid == -1) {
_close(pipes[NtPipeRead]);
_close(pipes[NtPipeWrite]);
return NULL;
}
}
else {
char **vec;
int vecc = NtMakeCmdVector(cmd, &vec, FALSE);
//pid = spawnvpe (_P_NOWAIT, vec[0], vec, environ);
pid = spawnvpe (_P_WAIT, vec[0], vec, environ);
if (pid == -1) {
goto docmd;
}
Safefree (vec, vecc);
}
if (reading) {
//
// We need to close our instance of the inherited pipe write
// handle now that it's been inherited so that it will actually close
// when the child process ends.
//
if (_close(pipes[NtPipeWrite]) == -1) {
_close(pipes[NtPipeRead]);
return NULL;
}
if (_dup2 (saved, fileno(stdout)) == -1) {
_close(pipes[NtPipeRead]);
return NULL;
}
_close(saved);
//
// Now get a stream pointer to return to the calling program.
//
if ((fp = (FILE *) fdopen(pipes[NtPipeRead], mode)) == NULL) {
return NULL;
}
}
else {
//
// need to close our read end of the pipe so that it will go
// away when the write end is closed.
//
if (_close(pipes[NtPipeRead]) == -1) {
_close(pipes[NtPipeWrite]);
return NULL;
}
if (_dup2 (saved, fileno(stdin)) == -1) {
_close(pipes[NtPipeWrite]);
return NULL;
}
_close(saved);
//
// Now get a stream pointer to return to the calling program.
//
if ((fp = (FILE *) fdopen(pipes[NtPipeWrite], mode)) == NULL) {
_close(pipes[NtPipeWrite]);
return NULL;
}
}
//
// do the book keeping
//
MyPopenRecord[slot].inuse = TRUE;
MyPopenRecord[slot].pipe = fp;
MyPopenRecord[slot].pid = pid;
return fp;
#else
{
int p[2];
BOOL fRet;
HANDLE hInFile, hOutFile, hStdin, hStdout;
LPCSTR lpApplicationName = NULL;
LPTSTR lpCommandLine;
LPTSTR lpCmd2 = NULL;
DWORD dwCreationFlags;
STARTUPINFO aStartupInfo;
PROCESS_INFORMATION aProcessInformation;
SECURITY_ATTRIBUTES sa;
int fd;
sa.nLength = sizeof (SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
fRet = CreatePipe(&hInFile, &hOutFile, &sa, 2048L);
if (!fRet)
Fatal("cannot open pipe \"%s\" (%s)", cmd, strerror(errno));
memset(&aStartupInfo, 0, sizeof (STARTUPINFO));
memset(&aProcessInformation, 0, sizeof (PROCESS_INFORMATION));
aStartupInfo.cb = sizeof (STARTUPINFO);
aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
if (reading) {
aStartupInfo.hStdInput = GetStdHandle(STD_OUTPUT_HANDLE);//hStdin;
aStartupInfo.hStdError = INVALID_HANDLE_VALUE;
//for save
DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_OUTPUT_HANDLE),
GetCurrentProcess(), &hStdout,
0, FALSE, DUPLICATE_SAME_ACCESS
);
//for redirect
DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_INPUT_HANDLE),
GetCurrentProcess(), &hStdin,
0, TRUE, DUPLICATE_SAME_ACCESS
);
aStartupInfo.hStdOutput = hOutFile;
}
else {
aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); //hStdout;
aStartupInfo.hStdError = INVALID_HANDLE_VALUE;
// for save
DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_INPUT_HANDLE),
GetCurrentProcess(), &hStdin,
0, FALSE, DUPLICATE_SAME_ACCESS
);
//for redirect
DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_OUTPUT_HANDLE),
GetCurrentProcess(), &hStdout,
0, TRUE, DUPLICATE_SAME_ACCESS
);
aStartupInfo.hStdInput = hInFile;
}
dwCreationFlags = (NORMAL_PRIORITY_CLASS);
lpCommandLine = cmd;
if (NtHasRedirection(cmd) || isInternalCmd(cmd)) {
lpApplicationName = getenv("COMSPEC");
lpCmd2 = malloc(strlen(lpApplicationName) + 1 + strlen(cmd) + sizeof (" /c "));
if (lpCmd2 == NULL)
Fatal("Mypopen: malloc failed");
sprintf(lpCmd2, "%s %s%s", lpApplicationName, " /c ", cmd);
lpCommandLine = lpCmd2;
}
fRet = CreateProcess(lpApplicationName, lpCommandLine, &sa, &sa,
sa.bInheritHandle, dwCreationFlags, NULL, NULL, &aStartupInfo, &aProcessInformation);
if (!fRet) {
CloseHandle(hInFile);
CloseHandle(hOutFile);
Fatal("cannot fork for \"%s\" (%s)", cmd, strerror(errno));
}
CloseHandle(aProcessInformation.hThread);
if (reading) {
HANDLE hDummy;
fd = _open_osfhandle((long)hInFile, (_O_RDONLY | pipemode));
CloseHandle(hOutFile);
DuplicateHandle(GetCurrentProcess(), hStdout,
GetCurrentProcess(), &hDummy,
0, TRUE, (DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE)
);
}
else {
HANDLE hDummy;
fd = _open_osfhandle((long)hOutFile, (_O_WRONLY | pipemode));
CloseHandle(hInFile);
DuplicateHandle(GetCurrentProcess(), hStdin,
GetCurrentProcess(), &hDummy,
0, TRUE, (DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE)
);
}
if (fd == -1)
Fatal("cannot open pipe \"%s\" (%s)", cmd, strerror(errno));
if ((fp = (FILE *) fdopen(fd, mode)) == NULL)
return NULL;
if (lpCmd2)
free(lpCmd2);
MyPopenRecord[slot].inuse = TRUE;
MyPopenRecord[slot].pipe = fp;
MyPopenRecord[slot].oshandle = (reading ? hInFile : hOutFile);
MyPopenRecord[slot].pid = (int)aProcessInformation.hProcess;
return fp;
}
#endif
}
int
mypclose(FILE *fp)
{
int i;
int exitcode;
Sleep(100);
for (i = 0; i < MYPOPENSIZE; i++) {
if (MyPopenRecord[i].inuse && MyPopenRecord[i].pipe == fp)
break;
}
if (i >= MYPOPENSIZE) {
Fatal("Invalid file pointer passed to mypclose!\n");
}
//
// get the return status of the process
//
#if 0
if (_cwait(&exitcode, MyPopenRecord[i].pid, WAIT_CHILD) == -1) {
if (errno == ECHILD) {
fprintf(stderr, "mypclose: nosuch child as pid %x\n",
MyPopenRecord[i].pid);
}
}
#else
for (;;) {
if (GetExitCodeProcess((HANDLE)MyPopenRecord[i].pid, &exitcode)) {
if (exitcode == STILL_ACTIVE) {
//printf("Process is Active.\n");
Sleep(100);
TerminateProcess((HANDLE)MyPopenRecord[i].pid, 0); // ugly...
continue;
}
else if (exitcode == 0) {
//printf("done.\n");
break;
}
else {
//printf("never.\n");
break;
}
}
}
#endif
//
// close the pipe
//
CloseHandle(MyPopenRecord[i].oshandle);
fflush(fp);
fclose(fp);
//
// free this slot
//
MyPopenRecord[i].inuse = FALSE;
MyPopenRecord[i].pipe = NULL;
MyPopenRecord[i].pid = 0;
return exitcode;
}
#endif
#if 1
typedef char* CHARP;
/*
* The following code is based on the do_exec and do_aexec functions
* in file doio.c
*/
int
do_spawn(cmd)
char *cmd;
{
register char **a;
register char *s;
char **argv;
int status;
char *shell, *cmd2;
int mode = NtSyncProcess ? P_WAIT : P_NOWAIT;
/* save an extra exec if possible */
if ((shell = getenv("RUBYSHELL")) != 0) {
if (NtHasRedirection(cmd)) {
int i;
char *p;
char *argv[4];
char *cmdline = ALLOC_N(char, (strlen(cmd) * 2 + 1));
p=cmdline;
*p++ = '"';
for (s=cmd; *s;) {
if (*s == '"')
*p++ = '\\'; /* Escape d-quote */
*p++ = *s++;
}
*p++ = '"';
*p = '\0';
/* fprintf(stderr, "do_spawn: %s %s\n", shell, cmdline); */
argv[0] = shell;
argv[1] = "-c";
argv[2] = cmdline;
argv[4] = NULL;
status = spawnvpe(mode, argv[0], argv, environ);
/* return spawnle(mode, shell, shell, "-c", cmd, (char*)0, environ); */
free(cmdline);
return status;
}
}
else if ((shell = getenv("COMSPEC")) != 0) {
if (NtHasRedirection(cmd) /* || isInternalCmd(cmd) */) {
do_comspec_shell:
return spawnle(mode, shell, shell, "/c", cmd, (char*)0, environ);
}
}
argv = ALLOC_N(CHARP, (strlen(cmd) / 2 + 2));
cmd2 = ALLOC_N(char, (strlen(cmd) + 1));
strcpy(cmd2, cmd);
a = argv;
for (s = cmd2; *s;) {
while (*s && isspace(*s)) s++;
if (*s)
*(a++) = s;
while (*s && !isspace(*s)) s++;
if (*s)
*s++ = '\0';
}
*a = NULL;
if (argv[0]) {
if ((status = spawnvpe(mode, argv[0], argv, environ)) == -1) {
free(argv);
free(cmd2);
return -1;
}
}
free(cmd2);
free(argv);
return status;
}
#endif
typedef struct _NtCmdLineElement {
struct _NtCmdLineElement *next, *prev;
char *str;
int len;
int flags;
} NtCmdLineElement;
//
// Possible values for flags
//
#define NTGLOB 0x1 // element contains a wildcard
#define NTMALLOC 0x2 // string in element was malloc'ed
#define NTSTRING 0x4 // element contains a quoted string
NtCmdLineElement *NtCmdHead = NULL, *NtCmdTail = NULL;
void
NtFreeCmdLine(void)
{
NtCmdLineElement *ptr;
while(NtCmdHead) {
ptr = NtCmdHead;
NtCmdHead = NtCmdHead->next;
free(ptr);
}
NtCmdHead = NtCmdTail = NULL;
}
//
// This function expands wild card characters that were spotted
// during the parse phase. The idea here is to call FindFirstFile and
// FindNextFile with the wildcard pattern specified, and splice in the
// resulting list of new names. If the wildcard pattern doesn\'t match
// any existing files, just leave it in the list.
//
void
NtCmdGlob (NtCmdLineElement *patt)
{
WIN32_FIND_DATA fd;
HANDLE fh;
char buffer[512];
NtCmdLineElement *tmphead, *tmptail, *tmpcurr;
strncpy(buffer, patt->str, patt->len);
buffer[patt->len] = '\0';
if ((fh = FindFirstFile (buffer, &fd)) == INVALID_HANDLE_VALUE) {
return;
}
tmphead = tmptail = NULL;
do {
tmpcurr = ALLOC(NtCmdLineElement);
if (tmpcurr == NULL) {
fprintf(stderr, "Out of Memory in globbing!\n");
while (tmphead) {
tmpcurr = tmphead;
tmphead = tmphead->next;
free(tmpcurr->str);
free(tmpcurr);
}
return;
}
memset (tmpcurr, 0, sizeof(*tmpcurr));
tmpcurr->len = strlen(fd.cFileName);
tmpcurr->str = ALLOC_N(char, tmpcurr->len+1);
if (tmpcurr->str == NULL) {
fprintf(stderr, "Out of Memory in globbing!\n");
while (tmphead) {
tmpcurr = tmphead;
tmphead = tmphead->next;
free(tmpcurr->str);
free(tmpcurr);
}
return;
}
strcpy(tmpcurr->str, fd.cFileName);
tmpcurr->flags |= NTMALLOC;
if (tmptail) {
tmptail->next = tmpcurr;
tmpcurr->prev = tmptail;
tmptail = tmpcurr;
}
else {
tmptail = tmphead = tmpcurr;
}
} while(FindNextFile(fh, &fd));
//
// ok, now we\'ve got a list of files that matched the wildcard
// specification. Put it in place of the pattern structure.
//
tmphead->prev = patt->prev;
tmptail->next = patt->next;
if (tmphead->prev)
tmphead->prev->next = tmphead;
if (tmptail->next)
tmptail->next->prev = tmptail;
//
// Now get rid of the pattern structure
//
if (patt->flags & NTMALLOC)
free(patt->str);
free(patt);
}
//
// Check a command string to determine if it has I/O redirection
// characters that require it to be executed by a command interpreter
//
static bool
NtHasRedirection (char *cmd)
{
int inquote = 0;
char quote = '\0';
char *ptr ;
//
// Scan the string, looking for redirection (< or >) or pipe
// characters (|) that are not in a quoted string
//
for (ptr = cmd; *ptr; ptr++) {
switch (*ptr) {
case '\'':
case '\"':
if (inquote) {
if (quote == *ptr) {
inquote = 0;
quote = '\0';
}
}
else {
quote = *ptr;
inquote++;
}
break;
case '>':
case '<':
if (!inquote)
return TRUE;
}
}
return FALSE;
}
int
NtMakeCmdVector (char *cmdline, char ***vec, int InputCmd)
{
int cmdlen = strlen(cmdline);
int done, instring, globbing, quoted, len;
int newline, need_free = 0, i;
int elements, strsz;
int slashes = 0;
char *ptr, *base, *buffer;
char **vptr;
char quote;
NtCmdLineElement *curr;
//
// just return if we don\'t have a command line
//
if (cmdlen == 0) {
*vec = NULL;
return 0;
}
//
// strip trailing white space
//
ptr = cmdline+(cmdlen - 1);
while(ptr >= cmdline && isspace(*ptr))
--ptr;
*++ptr = '\0';
//
// check for newlines and formfeeds. If we find any, make a new
// command string that replaces them with escaped sequences (\n or \f)
//
for (ptr = cmdline, newline = 0; *ptr; ptr++) {
if (*ptr == '\n' || *ptr == '\f')
newline++;
}
if (newline) {
base = ALLOC_N(char, strlen(cmdline) + 1 + newline + slashes);
if (base == NULL) {
fprintf(stderr, "malloc failed!\n");
return 0;
}
for (i = 0, ptr = base; (unsigned) i < strlen(cmdline); i++) {
switch (cmdline[i]) {
case '\n':
*ptr++ = '\\';
*ptr++ = 'n';
break;
default:
*ptr++ = cmdline[i];
}
}
*ptr = '\0';
cmdline = base;
need_free++;
}
//
// Ok, parse the command line, building a list of CmdLineElements.
// When we\'ve finished, and it\'s an input command (meaning that it\'s
// the processes argv), we\'ll do globing and then build the argument
// vector.
// The outer loop does one interation for each element seen.
// The inner loop does one interation for each character in the element.
//
for (done = 0, ptr = cmdline; *ptr;) {
//
// zap any leading whitespace
//
while(isspace(*ptr))
ptr++;
base = ptr;
for (done = newline = globbing = instring = quoted = 0;
*ptr && !done; ptr++) {
//
// Switch on the current character. We only care about the
// white-space characters, the wild-card characters, and the
// quote characters.
//
switch (*ptr) {
case ' ':
case '\t':
#if 0
case '/': // have to do this for NT/DOS option strings