Debian Codegraph @

texk/web2c/luatexdir/lua/loslibext.c

raw
1 /* loslibext.c
2
3 Copyright 2006-2012 Taco Hoekwater <[email protected]>
4
5 This file is part of LuaTeX.
6
7 LuaTeX is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2 of the License, or (at your
10 option) any later version.
11
12 LuaTeX is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 License for more details.
16
17 You should have received a copy of the GNU General Public License along
18 with LuaTeX; if not, see <http://www.gnu.org/licenses/>. */
19
20 #include "ptexlib.h"
21 #include "lua/luatex-api.h"
22
23 #include <kpathsea/c-stat.h>
24 #include <kpathsea/c-dir.h>
25 #include <time.h>
26
27
28 #if defined(_WIN32) || defined(__NT__)
29 # define MKDIR(a,b) mkdir(a)
30 #else
31 # define MKDIR(a,b) mkdir(a,b)
32 #endif
33
34 /* An attempt to figure out the basic platform, does not
35 care about niceties like version numbers yet,
36 and ignores platforms where luatex is unlikely to
37 successfully compile without major prorting effort
38 (amiga|mac|os2|vms) */
39
40 #if defined(_WIN32) || defined(__NT__)
41 # define OS_PLATTYPE "windows"
42 # define OS_PLATNAME "windows"
43 #elif defined(__GO32__) || defined(__DJGPP__) || defined(__DOS__)
44 # define OS_PLATTYPE "msdos"
45 # define OS_PLATNAME "msdos"
46 #else /* assume everything else is unix-y */
47 # include <sys/utsname.h>
48 # define OS_PLATTYPE "unix"
49 /* this is just a first guess */
50 # if defined(__BSD__)
51 # define OS_PLATNAME "bsd"
52 # elif defined(__CYGWIN__)
53 # define OS_PLATNAME "cygwin"
54 # elif defined(__SYSV__)
55 # define OS_PLATNAME "sysv"
56 # else
57 # define OS_PLATNAME "generic"
58 # endif
59 /* attempt to be more precise */
60 # if defined(__LINUX__) || defined (__linux)
61 # undef OS_PLATNAME
62 # define OS_PLATNAME "linux"
63 # elif defined(__FREEBSD__) || defined(__FreeBSD__) || defined(__FreeBSD)
64 # undef OS_PLATNAME
65 # define OS_PLATNAME "freebsd"
66 # elif defined(__FreeBSD_kernel__)
67 # undef OS_PLATNAME
68 # define OS_PLATNAME "kfreebsd"
69 # elif defined(__OPENBSD__) || defined(__OpenBSD)
70 # undef OS_PLATNAME
71 # define OS_PLATNAME "openbsd"
72 # elif defined(__SOLARIS__)
73 # undef OS_PLATNAME
74 # define OS_PLATNAME "solaris"
75 # elif defined(__SUNOS__) || defined(__SUN__) || defined(sun)
76 # undef OS_PLATNAME
77 # define OS_PLATNAME "sunos"
78 # elif defined(HPUX) || defined(__hpux)
79 # undef OS_PLATNAME
80 # define OS_PLATNAME "hpux"
81 # elif defined(__sgi)
82 # undef OS_PLATNAME
83 # define OS_PLATNAME "irix"
84 # elif defined(__MACH__) && defined(__APPLE__)
85 # undef OS_PLATNAME
86 # define OS_PLATNAME "macosx"
87 # elif defined(__GNU__)
88 # undef OS_PLATNAME
89 # define OS_PLATNAME "gnu"
90 # endif
91 #endif
92
93
94
95
96
97 /* there could be more platforms that don't have these two,
98 * but win32 and sunos are for sure.
99 * gettimeofday() for win32 is using an alternative definition
100 */
101
102 #if (! defined(_WIN32)) && (! defined(__SUNOS__))
103 # include <sys/time.h> /* gettimeofday() */
104 # include <sys/times.h> /* times() */
105 # include <sys/wait.h>
106 #endif
107
108 /* set this to one for spawn instead of exec on windows */
109
110 #define DONT_REALLY_EXIT 1
111
112 /* Note: under WIN32, |environ| is nothing but a copy of the actual
113 environment as it was during program startup. That variable
114 can then be changed (which is a little odd), but such changes
115 do not survive in the actual environment *unless* they are
116 passed on down in e.g. |_execvpe|, when they would be inherited
117 by the child process.
118
119 This gives trouble because some parts of the texk code actually
120 change the contents of the |environ| variable as a side-effect
121 of other processing, and that explains why the current code does
122 not use |environ| at all for the moment.
123
124 The API is kept in place for now, just in case. Thanks to Tomek
125 for the patch and the persistence in tracking this down.
126 */
127
128 #ifdef _WIN32
129 # include <process.h>
130 # define spawn_command(a,b,c) c ? \
131 _spawnvpe(_P_WAIT,(const char *)a,(const char* const*)b,(const char* const*)c) : \
132 _spawnvp(_P_WAIT,(const char *)a,(const char* const*)b)
133 # if DONT_REALLY_EXIT
134 # define exec_command(a,b,c) exit(spawn_command((a),(b),(c)))
135 # else
136 # define exec_command(a,b,c) c ? \
137 _execvpe((const char *)a,(const char* const*)b,(const char* const*)c) : \
138 _execvp((const char *)a,(const char* const*)b)
139 # endif
140 #else
141 # include <unistd.h>
142 # define DEFAULT_PATH "/bin:/usr/bin:."
143
144 static int exec_command(const char *file, char *const *av, char *const *envp)
145 {
146 char *path;
147 const char *searchpath, *esp;
148 size_t prefixlen, filelen, totallen;
149
150 if (strchr(file, '/')) /* Specific path */
151 return envp ? execve(file, av, envp) : execv(file, av);
152
153 filelen = strlen(file);
154 path = NULL;
155
156 searchpath = getenv("PATH");
157 if (!searchpath)
158 searchpath = DEFAULT_PATH;
159
160 errno = ENOENT; /* Default errno, if execve() doesn't change it */
161
162 do {
163 esp = strchr(searchpath, ':');
164 if (esp)
165 prefixlen = (size_t) (esp - searchpath);
166 else
167 prefixlen = strlen(searchpath);
168
169 if (prefixlen == 0 || searchpath[prefixlen - 1] == '/') {
170 totallen = prefixlen + filelen;
171 # ifdef PATH_MAX
172 if (totallen >= PATH_MAX)
173 continue;
174 # endif
175 path = malloc(totallen + 1);
176 memcpy(path, searchpath, prefixlen);
177 memcpy(path + prefixlen, file, filelen);
178 } else {
179 totallen = prefixlen + filelen + 1;
180 # ifdef PATH_MAX
181 if (totallen >= PATH_MAX)
182 continue;
183 # endif
184 path = malloc(totallen + 1);
185 memcpy(path, searchpath, prefixlen);
186 path[prefixlen] = '/';
187 memcpy(path + prefixlen + 1, file, filelen);
188 }
189 path[totallen] = '\0';
190
191 if (envp) {
192 execve(path, av, envp);
193 } else {
194 execv(path, av);
195 }
196 free(path);
197 path = NULL;
198 if (errno == E2BIG || errno == ENOEXEC ||
199 errno == ENOMEM || errno == ETXTBSY)
200 break; /* Report this as an error, no more search */
201
202 searchpath = esp + 1;
203 } while (esp);
204
205 return -1;
206 }
207
208 /*
209 It is not possible to mimic |spawnve()| completely. The main problem is
210 that the |fork|--|waitpid| combination cannot really do identical error
211 reporting to the parent process, because it has to pass all the possible
212 error conditions as well as the actual process return status through a
213 single 8-bit value.
214
215 The current implementation tries to give back meaningful results for |execve()|
216 errors in the child, for the cases that could also be returned by |spawnve()|,
217 and for |ETXTBSY|, because that can be triggered by our path searching routine.
218
219 This implementation does not differentiate abnormal status conditions reported
220 by |waitpid()|, but will simply return a single error indication value.
221
222 For all this, hyjacking a bunch of numbers in the range 1...255 is needed.
223 The chance of collisions is hopefully diminished by using a rather random
224 range in the 8-bit section.
225 */
226
227 # define INVALID_RET_E2BIG 143
228 # define INVALID_RET_ENOENT 144
229 # define INVALID_RET_ENOEXEC 145
230 # define INVALID_RET_ENOMEM 146
231 # define INVALID_RET_ETXTBSY 147
232 # define INVALID_RET_UNKNOWN 148
233 # define INVALID_RET_INTR 149
234
235 static int spawn_command(const char *file, char *const *av, char *const *envp)
236 {
237 pid_t pid, wait_pid;
238 int status;
239 pid = fork();
240 if (pid < 0) {
241 return -1; /* fork failed */
242 }
243 if (pid > 0) { /* parent */
244 status = 0;
245 wait_pid = waitpid(pid, &status, 0);
246 if (wait_pid == pid) {
247 if (WIFEXITED(status))
248 return WEXITSTATUS(status);
249 else
250 return INVALID_RET_INTR;
251 } else {
252 return -1; /* some waitpid error */
253 }
254 } else {
255 int f;
256 /* somewhat random upper limit. ignore errors on purpose */
257 for (f = 0; f < 256; f++)
258 (void) fsync(f);
259
260 if (exec_command(file, av, envp)) {
261 /* let's hope no-one uses these values */
262 switch (errno) {
263 case E2BIG:
264 exit(INVALID_RET_E2BIG);
265 case ETXTBSY:
266 exit(INVALID_RET_ETXTBSY);
267 case ENOENT:
268 exit(INVALID_RET_ENOENT);
269 case ENOEXEC:
270 exit(INVALID_RET_ENOEXEC);
271 case ENOMEM:
272 exit(INVALID_RET_ENOMEM);
273 default:
274 exit(INVALID_RET_UNKNOWN);
275 }
276 return -1;
277 }
278 }
279 return 0;
280 }
281
282 #endif
283
284 #ifdef _WIN32
285 static char *get_command_name(char *maincmd)
286 {
287 /* retrieve argv[0] part from the command string,
288 it will be truncated to MAX_PATH if it's too long */
289 char *cmdname = (char *) malloc(sizeof(char) * MAX_PATH);
290 int i, k, quoted;
291 quoted = k = 0;
292 for (i = 0; (i < MAX_PATH) && maincmd[i] &&
293 ((maincmd[i] != ' ' && maincmd[i] != '\t') || quoted); i++) {
294 if (maincmd[i] == '"') {
295 quoted = !quoted;
296 } else {
297 cmdname[k] = maincmd[i];
298 k++;
299 }
300 }
301 cmdname[k] = '\0';
302 return cmdname;
303 }
304 #endif
305
306 static char **do_split_command(const char *maincmd, char **runcmd)
307 {
308 char **cmdline = NULL;
309 #ifdef _WIN32
310 /* On WIN32 don't split anything, because
311 _spawnvpe can't put it back together properly
312 if there are quoted arguments with spaces.
313 Instead, dump everything into one argument
314 and it will be passed through as is */
315 cmdline = malloc(sizeof(char *) * 2);
316 cmdline[0] = xstrdup(maincmd);
317 cmdline[1] = NULL;
318 *runcmd = get_command_name(cmdline[0]);
319 #else
320 char *piece, *start_piece;
321 const char *cmd;
322 unsigned int i, j;
323 int ret = 0;
324 int in_string = 0;
325 int quoted = 0;
326 if (strlen(maincmd) == 0)
327 return NULL;
328 /* allocate the array of options first. it will probably be
329 be a little bit too big, but better too much than to little */
330 j = 2;
331 for (i = 0; i < strlen(maincmd); i++) {
332 if (maincmd[i] == ' ')
333 j++;
334 }
335 cmdline = malloc(sizeof(char *) * j);
336 for (i = 0; i < j; i++) {
337 cmdline[i] = NULL;
338 }
339 cmd = maincmd;
340 i = 0;
341 while (cmd[i] == ' ')
342 i++; /* skip leading spaces */
343 start_piece = malloc(strlen(cmd) + 1); /* a buffer */
344 piece = start_piece;
345 for (; i <= strlen(maincmd); i++) {
346 if (cmd[i] == '\\' &&
347 (cmd[i + 1] == '\\' || cmd[i + 1] == '\'' || cmd[i + 1] == '"')) {
348 quoted = 1;
349 continue;
350 }
351 if (in_string && cmd[i] == in_string && !quoted) {
352 in_string = 0;
353 continue;
354 }
355 if ((cmd[i] == '"' || cmd[i] == '\'') && !quoted) {
356 in_string = cmd[i];
357 continue;
358 }
359 if ((in_string == 0 && cmd[i] == ' ') || cmd[i] == 0) {
360 *piece = 0;
361 cmdline[ret++] = xstrdup(start_piece);
362 piece = start_piece;
363 while (i < strlen(maincmd) && cmd[(i + 1)] == ' ')
364 i++;
365 continue;
366 }
367 *piece++ = cmd[i];
368 quoted = 0;
369 }
370 xfree(start_piece);
371 *runcmd = cmdline[0];
372 #endif
373 return cmdline;
374 }
375
376 static char **do_flatten_command(lua_State * L, char **runcmd)
377 {
378 unsigned int i;
379 int j;
380 const char *s;
381 char **cmdline = NULL;
382 *runcmd = NULL;
383
384 for (j = 1;; j++) {
385 lua_rawgeti(L, 1, j);
386 if (lua_isnil(L, -1)) {
387 lua_pop(L, 1);
388 break;
389 }
390 lua_pop(L, 1);
391 }
392 if (j == 1)
393 return NULL;
394 cmdline = malloc(sizeof(char *) * (unsigned) (j + 1));
395 for (i = 1; i <= (unsigned) j; i++) {
396 cmdline[i] = NULL;
397 lua_rawgeti(L, 1, (int) i);
398 if (lua_isnil(L, -1) || (s = lua_tostring(L, -1)) == NULL) {
399 lua_pop(L, 1);
400 if (i == 1) {
401 xfree(cmdline);
402 return NULL;
403 } else {
404 break;
405 }
406 } else {
407 lua_pop(L, 1);
408 cmdline[(i - 1)] = xstrdup(s);
409 }
410 }
411 cmdline[i] = NULL;
412
413 lua_rawgeti(L, 1, 0);
414 if (lua_isnil(L, -1) || (s = lua_tostring(L, -1)) == NULL) {
415 #ifdef _WIN32
416 *runcmd = get_command_name(cmdline[0]);
417 #else
418 *runcmd = cmdline[0];
419 #endif
420 } else {
421 *runcmd = xstrdup(s);
422 }
423 lua_pop(L, 1);
424
425 return cmdline;
426 }
427
428
429 static int os_exec(lua_State * L)
430 {
431 int allow = 0;
432 const char *maincmd = NULL;
433 char *runcmd = NULL;
434 char *safecmd = NULL, *cmdname = NULL;
435 char **cmdline = NULL;
436 char **envblock = NULL;
437
438 if (lua_gettop(L) != 1) {
439 lua_pushnil(L);
440 lua_pushliteral(L, "invalid arguments passed");
441 return 2;
442 }
443 if (shellenabledp <= 0) {
444 lua_pushnil(L);
445 lua_pushliteral(L, "All command execution disabled.");
446 return 2;
447 }
448 if (lua_type(L, 1) == LUA_TSTRING) {
449 maincmd = lua_tostring(L, 1);
450 cmdline = do_split_command(maincmd, &runcmd);
451 } else if (lua_type(L, 1) == LUA_TTABLE) {
452 cmdline = do_flatten_command(L, &runcmd);
453 }
454 /* If restrictedshell == 0, any command is allowed. */
455 /* this is a little different from \write18/ os.execute processing
456 * because it does not test for commands with fixed arguments,
457 * but I am not so eager to attempt to fix that. Just document
458 * that os.exec() checks only the command name.
459 */
460 if (restrictedshell == 0) {
461 allow = 1;
462 } else {
463 const char *theruncmd = runcmd;
464 allow = shell_cmd_is_allowed(theruncmd, &safecmd, &cmdname);
465 }
466
467 if (allow > 0 && cmdline != NULL && runcmd != NULL) {
468 #if defined(_WIN32) && DONT_REALLY_EXIT
469 if (allow == 2)
470 exec_command(safecmd, cmdline, envblock);
471 else
472 exec_command(runcmd, cmdline, envblock);
473 #else
474 {
475 int r;
476 if (allow == 2)
477 r = exec_command(safecmd, cmdline, envblock);
478 else
479 r = exec_command(runcmd, cmdline, envblock);
480 if (r == -1) {
481 lua_pushnil(L);
482 lua_pushfstring(L, "%s: %s", runcmd, strerror(errno));
483 lua_pushinteger(L, errno);
484 return 3;
485 }
486 }
487 #endif
488 }
489 if (safecmd)
490 free(safecmd);
491 if (cmdname)
492 free(cmdname);
493 if (allow == 0) {
494 lua_pushnil(L);
495 lua_pushliteral(L, "Command execution disabled via shell_escape='p'");
496 return 2;
497 }
498 lua_pushnil(L);
499 lua_pushliteral(L, "invalid command line passed");
500 return 2;
501 }
502
503 #define do_error_return(A,B) do { \
504 lua_pushnil(L); \
505 lua_pushfstring(L,"%s: %s",runcmd,(A)); \
506 lua_pushinteger(L, B); \
507 return 3; \
508 } while (0)
509
510 static int os_spawn(lua_State * L)
511 {
512 int allow = 0;
513 const char *maincmd = NULL;
514 char *runcmd = NULL;
515 char *safecmd = NULL, *cmdname = NULL;
516 char **cmdline = NULL;
517 char **envblock = NULL;
518 int i;
519 int top = lua_gettop(L);
520 if (top != 1 && top != 2) {
521 lua_pushnil(L);
522 lua_pushliteral(L, "invalid arguments passed");
523 return 2;
524 }
525 if (shellenabledp <= 0) {
526 lua_pushnil(L);
527 lua_pushliteral(L, "All command execution disabled.");
528 return 2;
529 }
530 if (lua_type(L, 1) == LUA_TSTRING) {
531 maincmd = lua_tostring(L, 1);
532 cmdline = do_split_command(maincmd, &runcmd);
533 } else if (lua_type(L, 1) == LUA_TTABLE) {
534 cmdline = do_flatten_command(L, &runcmd);
535 }
536 /* Allow setting the environment */
537 if (restrictedshell == 0 && top == 2 && lua_istable(L, 2)) {
538 const char *key, *val;
539 char *value;
540 int size = 0;
541 lua_pushnil(L);
542 while (lua_next(L, 2) != 0) {
543 if (lua_type(L, -2) == LUA_TSTRING &&
544 lua_type(L, -1) == LUA_TSTRING) {
545 key = lua_tostring(L, -2);
546 val = lua_tostring(L, -1);
547 value = xmalloc((unsigned) (strlen(key) + strlen(val) + 2));
548 sprintf(value, "%s=%s", key, val);
549 envblock = xreallocarray(envblock, char*, size + 1);
550 envblock[size] = value;
551 size++;
552 }
553 lua_pop(L, 1);
554 }
555 if (envblock) {
556 envblock[size++] = NULL;
557 } else {
558 envblock = xmalloc(sizeof(char *));
559 envblock[0] = NULL;
560 }
561 }
562 /* If restrictedshell == 0, any command is allowed. */
563 /* this is a little different from \write18/ os.execute processing
564 * because it does not test for commands with fixed arguments,
565 * but I am not so eager to attempt to fix that. Just document
566 * that os.exec() checks only the command name.
567 */
568 if (restrictedshell == 0) {
569 allow = 1;
570 } else {
571 const char *theruncmd = runcmd;
572 allow = shell_cmd_is_allowed(theruncmd, &safecmd, &cmdname);
573 }
574 if (allow > 0 && cmdline != NULL && runcmd != NULL) {
575 if (allow == 2)
576 i = spawn_command(safecmd, cmdline, envblock);
577 else
578 i = spawn_command(runcmd, cmdline, envblock);
579 if (safecmd)
580 free(safecmd);
581 if (cmdname)
582 free(cmdname);
583 if (i == 0) {
584 lua_pushinteger(L, i);
585 return 1;
586 } else if (i == -1) {
587 /* this branch covers WIN32 as well as fork() and waitpid() errors */
588 do_error_return(strerror(errno), errno);
589 #ifndef _WIN32
590 } else if (i == INVALID_RET_E2BIG) {
591 do_error_return(strerror(E2BIG), i);
592 } else if (i == INVALID_RET_ENOENT) {
593 do_error_return(strerror(ENOENT), i);
594 } else if (i == INVALID_RET_ENOEXEC) {
595 do_error_return(strerror(ENOEXEC), i);
596 } else if (i == INVALID_RET_ENOMEM) {
597 do_error_return(strerror(ENOMEM), i);
598 } else if (i == INVALID_RET_ETXTBSY) {
599 do_error_return(strerror(ETXTBSY), i);
600 } else if (i == INVALID_RET_UNKNOWN) {
601 do_error_return("execution failed", i);
602 } else if (i == INVALID_RET_INTR) {
603 do_error_return("execution interrupted", i);
604 #endif
605 } else {
606 lua_pushinteger(L, i);
607 return 1;
608 }
609 }
610 if (safecmd)
611 free(safecmd);
612 if (cmdname)
613 free(cmdname);
614 if (allow == 0) {
615 lua_pushnil(L);
616 lua_pushliteral(L, "Command execution disabled via shell_escape='p'");
617 return 2;
618 }
619 lua_pushnil(L);
620 lua_pushliteral(L, "invalid command line passed");
621 return 2;
622 }
623
624 /* Hans wants to set env values */
625
626 static int os_setenv(lua_State * L)
627 {
628 const char *key, *val;
629 char *value;
630 key = luaL_optstring(L, 1, NULL);
631 val = luaL_optstring(L, 2, NULL);
632 if (key) {
633 if (val) {
634 value = xmalloc((unsigned) (strlen(key) + strlen(val) + 2));
635 sprintf(value, "%s=%s", key, val);
636 if (putenv(value)) {
637 return luaL_error(L, "unable to change environment");
638 }
639 } else {
640 #if defined(_WIN32) || defined(__sun__) || defined(__sun) || defined(_AIX)
641 value = xmalloc(strlen(key) + 2);
642 sprintf(value, "%s=", key);
643 if (putenv(value)) {
644 return luaL_error(L, "unable to change environment");
645 }
646 #else
647 (void) unsetenv(key);
648 #endif
649 }
650 }
651 lua_pushboolean(L, 1);
652 return 1;
653 }
654
655
656 static void find_env(lua_State * L)
657 {
658 char *envitem, *envitem_orig;
659 char *envkey;
660 char **envpointer;
661 envpointer = environ;
662 lua_getglobal(L, "os");
663 if (envpointer != NULL && lua_istable(L, -1)) {
664 luaL_checkstack(L, 2, "out of stack space");
665 lua_pushstring(L, "env");
666 lua_newtable(L);
667 while (*envpointer) {
668 /* TODO: perhaps a memory leak here */
669 luaL_checkstack(L, 2, "out of stack space");
670 envitem = xstrdup(*envpointer);
671 envitem_orig = envitem;
672 envkey = envitem;
673 while (*envitem != '=') {
674 envitem++;
675 }
676 *envitem = 0;
677 envitem++;
678 lua_pushstring(L, envkey);
679 lua_pushstring(L, envitem);
680 lua_rawset(L, -3);
681 envpointer++;
682 free(envitem_orig);
683 }
684 lua_rawset(L, -3);
685 }
686 lua_pop(L, 1);
687 }
688
689 static int ex_sleep(lua_State * L)
690 {
691 lua_Number interval = luaL_checknumber(L, 1);
692 lua_Number units = luaL_optnumber(L, 2, 1);
693 #ifdef _WIN32
694 Sleep((DWORD) (1e3 * interval / units));
695 #else /* assumes posix or bsd */
696 usleep((unsigned) (1e6 * interval / units));
697 #endif
698 return 0;
699 }
700
701
702
703 #ifdef _WIN32
704 # define _UTSNAME_LENGTH 65
705
706 /* Structure describing the system and machine. */
707 struct utsname {
708 char sysname[_UTSNAME_LENGTH];
709 char nodename[_UTSNAME_LENGTH];
710 char release[_UTSNAME_LENGTH];
711 char version[_UTSNAME_LENGTH];
712 char machine[_UTSNAME_LENGTH];
713 };
714
715 /*
716 * Get name and information about current kernel.
717 */
718 static int uname(struct utsname *uts)
719 {
720 enum { WinNT, Win95, Win98, WinUnknown };
721 OSVERSIONINFO osver;
722 SYSTEM_INFO sysinfo;
723 DWORD sLength;
724 DWORD os = WinUnknown;
725
726 memset(uts, 0, sizeof(*uts));
727
728 osver.dwOSVersionInfoSize = sizeof(osver);
729 GetVersionEx(&osver);
730 GetSystemInfo(&sysinfo);
731
732
733 /*
734 Windows 10 10.0*
735 Windows Server 2016 10.0*
736 Windows 8.1 6.3*
737 Windows Server 2012 R2 6.3*
738 Windows 8 6.2
739 Windows Server 2012 6.2
740 Windows 7 6.1
741 Windows Server 2008 R2 6.1
742 Windows Server 2008 6.0
743 Windows Vista 6.0
744 Windows Server 2003 R2 5.2
745 Windows Server 2003 5.2
746 Windows XP 64-Bit Edition 5.2
747 Windows XP 5.1
748 Windows 2000 5.0
749 */
750
751 switch (osver.dwPlatformId) {
752 case VER_PLATFORM_WIN32_NT:
753 if (osver.dwMajorVersion == 4)
754 strcpy(uts->sysname, "Windows NT 4");
755 else if (osver.dwMajorVersion <= 3)
756 strcpy(uts->sysname, "Windows NT 3");
757 else if (osver.dwMajorVersion == 5) {
758 if (osver.dwMinorVersion == 0)
759 strcpy(uts->sysname, "Windows 2000");
760 else if (osver.dwMinorVersion == 1)
761 strcpy(uts->sysname, "Windows XP");
762 else if (osver.dwMinorVersion == 2)
763 strcpy(uts->sysname, "Windows XP 64-Bit");
764 } else if (osver.dwMajorVersion == 6) {
765 if (osver.dwMinorVersion == 0)
766 strcpy(uts->sysname, "Windows Vista");
767 else if (osver.dwMinorVersion == 1)
768 strcpy(uts->sysname, "Windows 7");
769 else if (osver.dwMinorVersion == 2)
770 strcpy(uts->sysname, "Windows 8");
771 else if (osver.dwMinorVersion == 3)
772 strcpy(uts->sysname, "Windows 8.1");
773 } else if (osver.dwMajorVersion == 10) {
774 strcpy(uts->sysname, "Windows 10");
775 }
776 os = WinNT;
777 break;
778
779 case VER_PLATFORM_WIN32_WINDOWS: /* Win95, Win98 or WinME */
780 if ((osver.dwMajorVersion > 4) ||
781 ((osver.dwMajorVersion == 4) && (osver.dwMinorVersion > 0))) {
782 if (osver.dwMinorVersion >= 90)
783 strcpy(uts->sysname, "Windows ME"); /* ME */
784 else
785 strcpy(uts->sysname, "Windows 98"); /* 98 */
786 os = Win98;
787 } else {
788 strcpy(uts->sysname, "Windows 95"); /* 95 */
789 os = Win95;
790 }
791 break;
792
793 case VER_PLATFORM_WIN32s: /* Windows 3.x */
794 strcpy(uts->sysname, "Windows");
795 break;
796
797 default: /* anything else */
798 strcpy(uts->sysname, "Windows");
799 break;
800 }
801
802 sprintf(uts->version, "%ld.%02ld",
803 osver.dwMajorVersion, osver.dwMinorVersion);
804
805 if (osver.szCSDVersion[0] != '\0' &&
806 (strlen(osver.szCSDVersion) + strlen(uts->version) + 1) <
807 sizeof(uts->version)) {
808 strcat(uts->version, " ");
809 strcat(uts->version, osver.szCSDVersion);
810 }
811
812 sprintf(uts->release, "build %ld", osver.dwBuildNumber & 0xFFFF);
813
814 switch (sysinfo.wProcessorArchitecture) {
815 case PROCESSOR_ARCHITECTURE_AMD64:
816 strcpy(uts->machine, "amd64");
817 break;
818 case PROCESSOR_ARCHITECTURE_ARM:
819 strcpy(uts->machine, "arm");
820 break;
821 case PROCESSOR_ARCHITECTURE_ARM64:
822 strcpy(uts->machine, "arm64");
823 break;
824 case PROCESSOR_ARCHITECTURE_IA64:
825 strcpy(uts->machine, "ia64");
826 break;
827 case PROCESSOR_ARCHITECTURE_PPC:
828 strcpy(uts->machine, "ppc");
829 break;
830 case PROCESSOR_ARCHITECTURE_ALPHA:
831 strcpy(uts->machine, "alpha");
832 break;
833 case PROCESSOR_ARCHITECTURE_MIPS:
834 strcpy(uts->machine, "mips");
835 break;
836 case PROCESSOR_ARCHITECTURE_INTEL:
837 /*
838 * dwProcessorType is only valid in Win95 and Win98 and WinME
839 * wProcessorLevel is only valid in WinNT
840 */
841 switch (os) {
842 case Win95:
843 case Win98:
844 switch (sysinfo.dwProcessorType) {
845 case PROCESSOR_INTEL_386:
846 case PROCESSOR_INTEL_486:
847 case PROCESSOR_INTEL_PENTIUM:
848 sprintf(uts->machine, "i%ld", sysinfo.dwProcessorType);
849 break;
850 default:
851 strcpy(uts->machine, "i386");
852 break;
853 }
854 break;
855 case WinNT:
856 sprintf(uts->machine, "i%d86", sysinfo.wProcessorLevel);
857 break;
858 default:
859 strcpy(uts->machine, "unknown");
860 break;
861 }
862 break;
863 default:
864 strcpy(uts->machine, "unknown");
865 break;
866 }
867
868 sLength = sizeof(uts->nodename) - 1;
869 GetComputerName(uts->nodename, &sLength);
870 return 0;
871 }
872 #endif
873
874
875 static int ex_uname(lua_State * L)
876 {
877 struct utsname uts;
878 if (uname(&uts) >= 0) {
879 lua_newtable(L);
880 lua_pushstring(L, uts.sysname);
881 lua_setfield(L, -2, "sysname");
882 lua_pushstring(L, uts.machine);
883 lua_setfield(L, -2, "machine");
884 lua_pushstring(L, uts.release);
885 lua_setfield(L, -2, "release");
886 lua_pushstring(L, uts.version);
887 lua_setfield(L, -2, "version");
888 lua_pushstring(L, uts.nodename);
889 lua_setfield(L, -2, "nodename");
890 } else {
891 lua_pushnil(L);
892 }
893 return 1;
894 }
895
896
897 #if (! defined (_WIN32)) && (! defined (__SUNOS__))
898 static int os_times(lua_State * L)
899 {
900 struct tms r;
901 (void) times(&r);
902 lua_newtable(L);
903 lua_pushnumber(L, /* float */
904 ((lua_Number) (r.tms_utime)) /
905 (lua_Number) sysconf(_SC_CLK_TCK));
906 lua_setfield(L, -2, "utime");
907 lua_pushnumber(L, /* float */
908 ((lua_Number) (r.tms_stime)) /
909 (lua_Number) sysconf(_SC_CLK_TCK));
910 lua_setfield(L, -2, "stime");
911 lua_pushnumber(L, /* float */
912 ((lua_Number) (r.tms_cutime)) /
913 (lua_Number) sysconf(_SC_CLK_TCK));
914 lua_setfield(L, -2, "cutime");
915 lua_pushnumber(L, /* float */
916 ((lua_Number) (r.tms_cstime)) /
917 (lua_Number) sysconf(_SC_CLK_TCK));
918 lua_setfield(L, -2, "cstime");
919 return 1;
920 }
921 #endif
922
923 #if ! defined (__SUNOS__)
924
925 # if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
926 # define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
927 # else
928 # define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
929 # endif
930
931 static int os_gettimeofday(lua_State * L)
932 {
933 double v;
934 # ifndef _WIN32
935 struct timeval tv;
936 gettimeofday(&tv, NULL);
937 v = (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
938 # else
939 FILETIME ft;
940 int64_t tmpres = 0;
941
942 GetSystemTimeAsFileTime(&ft);
943
944 tmpres |= ft.dwHighDateTime;
945 tmpres <<= 32;
946 tmpres |= ft.dwLowDateTime;
947 tmpres /= 10;
948 tmpres -= DELTA_EPOCH_IN_MICROSECS; /*converting file time to unix epoch */
949 v = (double) tmpres / 1000000.0;
950 # endif
951 lua_pushnumber(L, v); /* float */
952 return 1;
953 }
954 #endif
955
956
957 #define MAXTRIES 36*36*36
958
959 #ifndef HAVE_MKDTEMP
960 static const char repl[] = "0123456789abcdefghijklmnopqrstuvwxyz";
961 static int dirs_made = 0;
962
963 static char *do_mkdtemp(char *tmpl)
964 {
965 int count;
966 int value;
967 char *xes = &tmpl[strlen(tmpl) - 6];
968 /* this is not really all that random, but it will do */
969 if (dirs_made == 0) {
970 srand((unsigned) time(NULL));
971 }
972 value = rand();
973 for (count = 0; count < MAXTRIES; value += 8413, ++count) {
974 int v = value;
975 xes[0] = repl[v % 36];
976 v /= 36;
977 xes[1] = repl[v % 36];
978 v /= 36;
979 xes[2] = repl[v % 36];
980 v /= 36;
981 xes[3] = repl[v % 36];
982 v /= 36;
983 xes[4] = repl[v % 36];
984 v /= 36;
985 xes[5] = repl[v % 36];
986 if (MKDIR(tmpl, S_IRUSR | S_IWUSR | S_IXUSR) >= 0) {
987 dirs_made++;
988 return tmpl;
989 } else if (errno != EEXIST) {
990 return NULL;
991 }
992 }
993 return NULL;
994 }
995 #endif
996
997 static int os_tmpdir(lua_State * L)
998 {
999 char *s, *tempdir;
1000 const char *tmp = luaL_optstring(L, 1, "luatex.XXXXXX");
1001 if (tmp == NULL ||
1002 strlen(tmp) < 6 || (strcmp(tmp + strlen(tmp) - 6, "XXXXXX") != 0)) {
1003 lua_pushnil(L);
1004 lua_pushstring(L, "Invalid argument to os.tmpdir()");
1005 return 2;
1006 } else {
1007 tempdir = xstrdup(tmp);
1008 }
1009 #ifdef HAVE_MKDTEMP
1010 s = mkdtemp(tempdir);
1011 #else
1012 s = do_mkdtemp(tempdir);
1013 #endif
1014 if (s == NULL) {
1015 int en = errno; /* calls to Lua API may change this value */
1016 lua_pushnil(L);
1017 lua_pushfstring(L, "%s", strerror(en));
1018 return 2;
1019 } else {
1020 lua_pushstring(L, s);
1021 return 1;
1022 }
1023 }
1024
1025
1026 static int os_execute(lua_State * L)
1027 {
1028 int allow = 0;
1029 int ret = 1;
1030 char *safecmd = NULL;
1031 char *cmdname = NULL;
1032 const char *cmd = luaL_optstring(L, 1, NULL);
1033
1034 if (cmd == NULL) { /* pretend we are \.{\\pdfshellescape} */
1035 if (shellenabledp <= 0) {
1036 lua_pushinteger(L, 0);
1037 } else if (restrictedshell == 0) {
1038 lua_pushinteger(L, 1);
1039 } else {
1040 lua_pushinteger(L, 2);
1041 }
1042 return 1;
1043 }
1044 if (shellenabledp <= 0) {
1045 lua_pushnil(L);
1046 lua_pushstring(L, "All command execution disabled.");
1047 return 2;
1048 }
1049 /* If restrictedshell == 0, any command is allowed. */
1050 if (restrictedshell == 0)
1051 allow = 1;
1052 else
1053 allow = shell_cmd_is_allowed(cmd, &safecmd, &cmdname);
1054
1055 if (allow == 1) {
1056 lua_pushinteger(L, system(cmd));
1057 } else if (allow == 2) {
1058 lua_pushinteger(L, system(safecmd));
1059 } else {
1060 lua_pushnil(L);
1061 ret = 2;
1062 if (allow == 0)
1063 lua_pushstring(L,
1064 "Command execution disabled via shell_escape='p'");
1065 else /* allow == -1 */
1066 lua_pushstring(L, "Quoting error in system command line.");
1067 }
1068 if (safecmd)
1069 free(safecmd);
1070 if (cmdname)
1071 free(cmdname);
1072 return ret;
1073 }
1074
1075
1076 /*
1077 ** ======================================================
1078 ** l_kpse_popen spawns a new process connected to the current
1079 ** one through the file streams with some checks by kpse.
1080 ** Almost verbatim from Lua liolib.c .
1081 ** =======================================================
1082 */
1083 #if !defined(l_kpse_popen) /* { */
1084
1085 #if defined(LUA_USE_POSIX) /* { */
1086
1087 #define l_kpse_popen(L,c,m) (fflush(NULL), popen(c,m))
1088 #define l_kpse_pclose(L,file) (pclose(file))
1089
1090 #elif defined(LUA_USE_WINDOWS) /* }{ */
1091
1092 #define l_kpse_popen(L,c,m) (_popen(c,m))
1093 #define l_kpse_pclose(L,file) (_pclose(file))
1094
1095 #else /* }{ */
1096
1097 /* ISO C definitions */
1098 #define l_kpse_popen(L,c,m) \
1099 ((void)((void)c, m), \
1100 luaL_error(L, "'popen' not supported"), \
1101 (FILE*)0)
1102 #define l_kpse_pclose(L,file) ((void)L, (void)file, -1)
1103
1104 #endif /* } */
1105
1106 #endif /* } */
1107 typedef luaL_Stream LStream;
1108 #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
1109 static LStream *newprefile (lua_State *L) {
1110 LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
1111 p->closef = NULL; /* mark file handle as 'closed' */
1112 luaL_setmetatable(L, LUA_FILEHANDLE);
1113 return p;
1114 }
1115 static int io_kpse_pclose (lua_State *L) {
1116 LStream *p = tolstream(L);
1117 return luaL_execresult(L, l_kpse_pclose(L, p->f));
1118 }
1119 static int io_kpse_check_permissions(lua_State *L) {
1120 const char *filename = luaL_checkstring(L, 1);
1121 if (filename == NULL) {
1122 lua_pushboolean(L,0);
1123 lua_pushliteral(L,"no command name given");
1124 } else if (shellenabledp <= 0) {
1125 lua_pushboolean(L,0);
1126 lua_pushliteral(L,"all command execution is disabled");
1127 } else if (restrictedshell == 0) {
1128 lua_pushboolean(L,1);
1129 lua_pushstring(L,filename);
1130 } else {
1131 char *safecmd = NULL;
1132 char *cmdname = NULL;
1133 switch (shell_cmd_is_allowed(filename, &safecmd, &cmdname)) {
1134 case 0:
1135 lua_pushboolean(L,0);
1136 lua_pushliteral(L, "specific command execution disabled");
1137 break;
1138 case 1:
1139 /* doesn't happen */
1140 lua_pushboolean(L,1);
1141 lua_pushstring(L,filename);
1142 break;
1143 case 2:
1144 lua_pushboolean(L,1);
1145 lua_pushstring(L,safecmd);
1146 break;
1147 default:
1148 /* -1 */
1149 lua_pushboolean(L,0);
1150 lua_pushliteral(L, "bad command line quoting");
1151 break;
1152 }
1153 }
1154 return 2;
1155 }
1156 static int io_kpse_popen (lua_State *L) {
1157 const char *filename = NULL;
1158 const char *mode = NULL;
1159 LStream *p = NULL;
1160 int okay;
1161 filename = luaL_checkstring(L, 1);
1162 mode = luaL_optstring(L, 2, "r");
1163 lua_pushstring(L,filename);
1164 io_kpse_check_permissions(L);
1165 filename = luaL_checkstring(L, -1);
1166 okay = lua_toboolean(L,-2);
1167 if (okay && filename) {
1168 p = newprefile(L);
1169 luaL_argcheck(L, ((mode[0] == 'r' || mode[0] == 'w') && mode[1] == '\0'),
1170 2, "invalid mode");
1171 p->f = l_kpse_popen(L, filename, mode);
1172 p->closef = &io_kpse_pclose;
1173 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
1174 } else {
1175 lua_pushnil(L);
1176 lua_pushvalue(L,-2);
1177 return 2;
1178 }
1179 }
1180
1181
1182
1183 /* socket.sleep and socket.gettime */
1184 /* are duplicated here, and they are */
1185 /* always available (the socket library */
1186 /* can be nil in some setups) */
1187 #ifdef _WIN32
1188 static int socket_timeout_lua_sleep(lua_State *L)
1189 {
1190 double n = luaL_checknumber(L, 1);
1191 if (n < 0.0) n = 0.0;
1192 if (n < DBL_MAX/1000.0) n *= 1000.0;
1193 if (n > INT_MAX) n = INT_MAX;
1194 Sleep((int)n);
1195 return 0;
1196 }
1197 static double socket_timeout_gettime(void) {
1198 FILETIME ft;
1199 double t;
1200 GetSystemTimeAsFileTime(&ft);
1201 /* Windows file time (time since January 1, 1601 (UTC)) */
1202 t = ft.dwLowDateTime/1.0e7 + ft.dwHighDateTime*(4294967296.0/1.0e7);
1203 /* convert to Unix Epoch time (time since January 1, 1970 (UTC)) */
1204 return (t - 11644473600.0);
1205 }
1206 #else
1207 static int socket_timeout_lua_sleep(lua_State *L)
1208 {
1209 double n = luaL_checknumber(L, 1);
1210 struct timespec t, r;
1211 if (n < 0.0) n = 0.0;
1212 if (n > INT_MAX) n = INT_MAX;
1213 t.tv_sec = (int) n;
1214 n -= t.tv_sec;
1215 t.tv_nsec = (int) (n * 1000000000);
1216 if (t.tv_nsec >= 1000000000) t.tv_nsec = 999999999;
1217 while (nanosleep(&t, &r) != 0) {
1218 t.tv_sec = r.tv_sec;
1219 t.tv_nsec = r.tv_nsec;
1220 }
1221 return 0;
1222 }
1223 static double socket_timeout_gettime(void) {
1224 struct timeval v;
1225 gettimeofday(&v, (struct timezone *) NULL);
1226 /* Unix Epoch time (time since January 1, 1970 (UTC)) */
1227 return v.tv_sec + v.tv_usec/1.0e6;
1228 }
1229 #endif
1230 static int socket_timeout_lua_gettime(lua_State *L)
1231 {
1232 lua_pushnumber(L, socket_timeout_gettime());
1233 return 1;
1234 }
1235
1236
1237 void open_oslibext(lua_State * L)
1238 {
1239
1240 find_env(L);
1241
1242 lua_getglobal(L, "os");
1243 lua_pushcfunction(L, ex_sleep);
1244 lua_setfield(L, -2, "sleep");
1245 lua_pushliteral(L, OS_PLATTYPE);
1246 lua_setfield(L, -2, "type");
1247 lua_pushliteral(L, OS_PLATNAME);
1248 lua_setfield(L, -2, "name");
1249 lua_pushcfunction(L, ex_uname);
1250 lua_setfield(L, -2, "uname");
1251 #if (! defined (_WIN32)) && (! defined (__SUNOS__))
1252 lua_pushcfunction(L, os_times);
1253 lua_setfield(L, -2, "times");
1254 #endif
1255 #if ! defined (__SUNOS__)
1256 lua_pushcfunction(L, os_gettimeofday);
1257 lua_setfield(L, -2, "gettimeofday");
1258 #endif
1259
1260 lua_pushcfunction(L, os_setenv);
1261 lua_setfield(L, -2, "setenv");
1262 lua_pushcfunction(L, os_exec);
1263 lua_setfield(L, -2, "exec");
1264 lua_pushcfunction(L, os_spawn);
1265 lua_setfield(L, -2, "spawn");
1266 lua_pushcfunction(L, os_execute);
1267 lua_setfield(L, -2, "execute");
1268 lua_pushcfunction(L, os_tmpdir);
1269 lua_setfield(L, -2, "tmpdir");
1270
1271 lua_pushcfunction(L, io_kpse_popen);
1272 lua_setfield(L, -2, "kpsepopen");
1273
1274 lua_pushcfunction(L, socket_timeout_lua_sleep);
1275 lua_setfield(L, -2, "socketsleep");
1276
1277 lua_pushcfunction(L, socket_timeout_lua_gettime);
1278 lua_setfield(L, -2, "socketgettime");
1279
1280
1281 lua_pop(L, 1); /* pop the table */
1282 }