Annotation of parser3/src/main/pa_exec.C, revision 1.88

1.1       paf         1: /** @file
                      2:        Parser: program executing for different OS-es.
                      3: 
1.85      moko        4:        Copyright (c) 2001-2015 Art. Lebedev Studio (http://www.artlebedev.com)
1.25      paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.1       paf         6: 
1.18      paf         7:        @todo setrlimit
1.1       paf         8: */
1.38      paf         9: 
1.1       paf        10: #include "pa_config_includes.h"
                     11: 
1.19      paf        12: #include "pa_exec.h"
                     13: #include "pa_exception.h"
                     14: #include "pa_common.h"
                     15: 
1.88    ! moko       16: volatile const char * IDENT_PA_EXEC_C="$Id: pa_exec.C,v 1.87 2015/10/28 22:50:00 moko Exp $" IDENT_PA_EXEC_H;
1.82      moko       17: 
1.84      moko       18: #ifdef _MSC_VER
1.1       paf        19: 
1.83      moko       20: #include <windows.h>
1.1       paf        21: 
                     22: /// this func from http://www.ccas.ru/~posp/popov/spawn.htm
1.36      paf        23: static DWORD CreateHiddenConsoleProcess(LPCTSTR szCmdLine,
1.88    ! moko       24:                                        LPCTSTR szScriptFileSpec,
        !            25:                                        char *szEnv,
        !            26:                                        PROCESS_INFORMATION* ppi, 
        !            27:                                        LPHANDLE phInWrite,
        !            28:                                        LPHANDLE phOutRead,
        !            29:                                        LPHANDLE phErrRead)
1.1       paf        30: {
1.51      paf        31:        DWORD result=0;
1.36      paf        32:        BOOL fCreated;
1.51      paf        33:        STARTUPINFO si;
                     34:        SECURITY_ATTRIBUTES sa={0};
                     35:        HANDLE hInRead;
                     36:        HANDLE hOutWrite;
                     37:        HANDLE hErrWrite;
                     38:        
                     39:        // Create pipes
                     40:        // initialize security attributes for handle inheritance (for WinNT)
                     41:        sa.nLength=sizeof(sa);
                     42:        sa.bInheritHandle=TRUE;
                     43:        sa.lpSecurityDescriptor=NULL;
                     44:        
                     45:        // create STDIN pipe
                     46:        if(!CreatePipe(&hInRead, phInWrite, &sa, 0))
                     47:                goto error;
1.86      moko       48: 
                     49:        // Ensure the write handle to the pipe for STDIN is not inherited. 
                     50:        if (!SetHandleInformation(*phInWrite, HANDLE_FLAG_INHERIT, 0))
                     51:                goto error;
                     52: 
1.51      paf        53:        // create STDOUT pipe
                     54:        if(!CreatePipe(phOutRead, &hOutWrite, &sa, 0))
                     55:                goto error;
                     56:        
1.86      moko       57:        // Ensure the read handle to the pipe for STDOUT is not inherited.
                     58:        if (!SetHandleInformation(*phOutRead, HANDLE_FLAG_INHERIT, 0))
                     59:                goto error;
                     60: 
1.51      paf        61:        // create STDERR pipe
                     62:        if(!CreatePipe(phErrRead, &hErrWrite, &sa, 0))
                     63:                goto error;
                     64:        
1.86      moko       65:        // Ensure the read handle to the pipe for STDERR is not inherited.
                     66:        if (!SetHandleInformation(*phErrRead, HANDLE_FLAG_INHERIT, 0))
                     67:                goto error;
                     68: 
1.51      paf        69:        // process startup information
                     70:        memset(&si, 0, sizeof(si));
                     71:        si.cb=sizeof(si); 
                     72:        si.dwFlags=STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
                     73:        // child process' console must be hidden for Win95 compatibility
                     74:        si.wShowWindow=SW_HIDE;
                     75:        // assign "other" sides of pipes
                     76:        si.hStdInput=hInRead;
                     77:        si.hStdOutput=hOutWrite;
                     78:        si.hStdError=hErrWrite;
                     79:        
1.31      paf        80:        // calculating script's directory
                     81:        char dir[MAX_STRING];
1.65      paf        82:        strncpy(dir, szScriptFileSpec, MAX_STRING-1); dir[MAX_STRING-1]=0;
1.33      paf        83:        lsplit(dir,' '); // trim arguments
1.31      paf        84:        rsplit(dir,'/'); rsplit(dir,'\\'); // trim filename
1.51      paf        85:        
                     86:        // Create a child process (suspended)
                     87:        fCreated=CreateProcess(NULL,
                     88:                (LPTSTR)szCmdLine,
                     89:                NULL,
                     90:                NULL,
                     91:                TRUE,
                     92:                CREATE_NO_WINDOW,
                     93:                szEnv,
                     94:                dir,
                     95:                &si,
                     96:                ppi);
1.36      paf        97:        if(!fCreated)
                     98:                result=GetLastError();
1.51      paf        99:        
                    100:        CloseHandle(hInRead);
                    101:        CloseHandle(hOutWrite);
                    102:        CloseHandle(hErrWrite);
                    103:        
                    104:        if(!fCreated)
                    105:                goto error;
                    106:        
                    107:        return result;
                    108:        
1.1       paf       109: error:
1.36      paf       110:        if(!result/*yet*/)
                    111:                result=GetLastError(); // get it
1.51      paf       112:        
                    113:        CloseHandle(*phInWrite);
                    114:        CloseHandle(*phOutRead);
                    115:        CloseHandle(*phErrRead);
                    116:        
                    117:        return result;
                    118: }
1.36      paf       119: 
1.87      moko      120: static int get_exit_status(HANDLE hProcess) {
                    121:        DWORD dwExitCode = 0;
                    122:        if(!GetExitCodeProcess(hProcess, &dwExitCode))
                    123:                return -1;
                    124:        if(dwExitCode != STILL_ACTIVE)
                    125:                return dwExitCode;
                    126:        // wait for 1 second for process to exit
                    127:        if(WaitForSingleObject(hProcess, 1000) != WAIT_OBJECT_0)
                    128:                return -2;
                    129:        if(!GetExitCodeProcess(hProcess, &dwExitCode))
                    130:                return -1;
                    131:        return dwExitCode;
                    132: }
                    133: 
1.51      paf       134: static void read_pipe(String& result, HANDLE hOutRead, String::Language lang){
                    135:        while(true) {
1.77      misha     136:                char *buf=new(PointerFreeGC) char[MAX_STRING+1];
1.78      misha     137:                DWORD size=0;
1.77      misha     138:                if(!ReadFile(hOutRead, buf, MAX_STRING, &size, NULL) || !size) 
1.51      paf       139:                        break;
                    140:                buf[size]=0;
                    141:                result.append_know_length(buf, size, lang);
                    142:        }
1.1       paf       143: }
                    144: 
1.70      misha     145: static void read_pipe(File_read_result& result, HANDLE hOutRead){
1.71      misha     146: 
1.77      misha     147:        char *buf=(char*)pa_malloc(MAX_STRING+1);
                    148:        DWORD bufsize = MAX_STRING;
1.70      misha     149: 
                    150:        result.headers = 0;
                    151:        result.length = 0;
                    152:        result.str = 0;
                    153:        result.success = false;
                    154: 
                    155:        while(true) {
1.77      misha     156:                DWORD size=0;
                    157:                if(!ReadFile(hOutRead, buf + result.length, bufsize - result.length, &size, NULL) || !size)
1.70      misha     158:                        break;
1.77      misha     159:                result.length += size;
                    160:                if(result.length >= bufsize){
                    161:                        bufsize *= 2;
                    162:                        buf=(char*)pa_realloc(buf, bufsize+1);
1.70      misha     163:                }
1.77      misha     164:                result.str=buf;
1.70      misha     165:        }
                    166: }
                    167: 
1.51      paf       168: static const char* buildCommand(const char* file_spec_cstr, const ArrayString& argv) {
                    169:        const char* result=file_spec_cstr;
1.4       paf       170:        if(FILE *f=fopen(file_spec_cstr, "r")) {
1.51      paf       171:                try {
1.1       paf       172:                char buf[MAX_STRING];
                    173:                size_t size=fread(buf, 1, MAX_STRING-1, f);
                    174:                if(size>2) {
                    175:                        buf[size]=0;
                    176:                        if(strncmp(buf, "#!", 2)==0) {
1.51      paf       177:                                const char* begin=buf+2;
1.65      paf       178:                                while(*begin==' ') // alx: were an old magic for some linux-es
1.4       paf       179:                                        begin++;
1.68      paf       180:                                if(const char *end=strchr(begin, '\n')) {
1.51      paf       181:                                        String string(pa_strdup(begin, end-begin));
1.1       paf       182:                                        string << " " << file_spec_cstr;
1.8       parser    183:                                        result=string.cstr();
1.1       paf       184:                                }
                    185:                        }
                    186:                }
1.51      paf       187:                } catch(...) {
                    188:                        fclose(f);
                    189:                        rethrow;
                    190:                }
1.1       paf       191:                fclose(f);
                    192:        }
1.51      paf       193:        { // appending argv
                    194:                String string(result);
                    195:                for(size_t i=0; i<argv.count(); i++) {
                    196:                        string << " ";
                    197:                        string << *argv[i];
1.8       parser    198:                }
                    199: 
1.51      paf       200:                result=string.cstr();
1.8       parser    201:        }
                    202: 
                    203:        return result;
1.1       paf       204: }
                    205: 
1.51      paf       206: #else
1.1       paf       207: 
1.51      paf       208: static pid_t execve_piped(const char* file_spec_cstr, 
1.27      paf       209:                        char * const argv[], char * const env[],
                    210:                        int *pipe_in, int *pipe_out, int *pipe_err) {
1.46      paf       211:        pid_t pid;
1.1       paf       212:        int in_fds[2];
                    213:        int out_fds[2];
                    214:        int err_fds[2];
                    215:        int save_errno;
                    216:        
                    217:        if(pipe_in && pipe(in_fds)<0) {
                    218:                save_errno=errno;
                    219:                errno=save_errno;
                    220:                return 0;
                    221:        }
                    222:        
                    223:        if(pipe_out && pipe(out_fds)<0) {
                    224:                save_errno=errno;
                    225:                if(pipe_in) {
                    226:                        close(in_fds[0]); close(in_fds[1]);
                    227:                }
                    228:                errno=save_errno;
                    229:                return 0;
                    230:        }
                    231:        
                    232:        if(pipe_err && pipe(err_fds)<0) {
                    233:                save_errno=errno;
                    234:                if(pipe_in) {
                    235:                        close(in_fds[0]); close(in_fds[1]);
                    236:                }
                    237:                if(pipe_out) {
                    238:                        close(out_fds[0]); close(out_fds[1]);
                    239:                }
                    240:                errno=save_errno;
                    241:                return 0;
                    242:        }
                    243:        
                    244:        if((pid=fork())<0) {
                    245:                save_errno=errno;
                    246:                if(pipe_in) {
                    247:                        close(in_fds[0]); close(in_fds[1]);
                    248:                }
                    249:                if(pipe_out) {
                    250:                        close(out_fds[0]); close(out_fds[1]);
                    251:                }
                    252:                if(pipe_err) {
                    253:                        close(err_fds[0]); close(err_fds[1]);
                    254:                }
                    255:                errno=save_errno;
1.46      paf       256:                return -1;
1.1       paf       257:        }
                    258:        
                    259:        if(!pid) {
                    260:                /* Child process */
                    261:                
                    262:                if(pipe_out) {
                    263:                        close(out_fds[0]);
                    264:                        dup2(out_fds[1], STDOUT_FILENO);
                    265:                        close(out_fds[1]);
                    266:                }
                    267:                
                    268:                if(pipe_in) {
                    269:                        close(in_fds[1]);
                    270:                        dup2(in_fds[0], STDIN_FILENO);
                    271:                        close(in_fds[0]);
                    272:                }
                    273:                
                    274:                if(pipe_err) {
                    275:                        close(err_fds[0]);
                    276:                        dup2(err_fds[1], STDERR_FILENO);
                    277:                        close(err_fds[1]);
                    278:                }
                    279:                
1.42      paf       280:                /* grabbed this from Apache source: */
                    281:                /*  HP-UX SIGCHLD fix goes here, if someone will remind me what it is... */
1.1       paf       282:                signal(SIGCHLD, SIG_DFL);       /* Was that it? */
                    283:        
1.31      paf       284:                // chdir to script's directory
                    285:                char dir[MAX_STRING];
                    286:                strncpy(dir, file_spec_cstr, MAX_STRING-1); dir[MAX_STRING-1]=0;
                    287:                rsplit(dir,'/'); // trim filename
                    288:                chdir(dir);
                    289: 
                    290:                //  execute
                    291:                execve(file_spec_cstr, argv, env);
1.1       paf       292:                exit(-errno);
                    293:        }
                    294:        
                    295:        /* Parent process */
                    296:        
                    297:        if(pipe_out) {
                    298:                close(out_fds[1]);
                    299:                *pipe_out=out_fds[0];
                    300:        }
                    301:        
                    302:        if(pipe_in) {
                    303:                close(in_fds[0]);
                    304:                *pipe_in=in_fds[1];
                    305:        }
                    306:        
                    307:        if(pipe_err) {
                    308:                close(err_fds[1]);
                    309:                *pipe_err=err_fds[0];
                    310:        }
                    311: 
                    312:        return pid;
                    313: }
                    314: 
                    315: static int get_exit_status(int pid) {
                    316:        int status;
1.58      paf       317:        pid_t cid;
                    318:        while ((cid=waitpid(pid, &status, WUNTRACED)) == -1 && errno == EINTR); 
                    319:        if(!cid)
1.1       paf       320:                return -1;
                    321:        return WIFEXITED(status) ? 
                    322:                WEXITSTATUS(status) : -2;
                    323: }
                    324: 
1.51      paf       325: static void read_pipe(String& result, int file, String::Language lang){
1.1       paf       326:        while(true) {
1.77      misha     327:                char *buf=new(PointerFreeGC) char[MAX_STRING+1];
                    328:                ssize_t length=read(file, buf, MAX_STRING);
1.51      paf       329:                if(length<=0)
1.49      paf       330:                        break;
1.51      paf       331:                buf[length]=0;
                    332:                result.append_know_length(buf, length, lang);
                    333:        }
1.1       paf       334: }
                    335: 
1.70      misha     336: static void read_pipe(File_read_result& result, int file){
1.77      misha     337:        char *buf=(char*)pa_malloc(MAX_STRING+1);
                    338:        ssize_t bufsize = MAX_STRING;
1.70      misha     339: 
                    340:        result.headers = 0;
                    341:        result.length = 0;
                    342:        result.str = 0;
                    343:        result.success = false;
                    344: 
                    345:        while(true) {
1.77      misha     346:                ssize_t size=read(file, buf + result.length, bufsize - result.length);
1.70      misha     347:                if(size <= 0)
                    348:                        break;
1.77      misha     349:                result.length += size;
                    350:                if(result.length >= bufsize){
                    351:                        bufsize *= 2;
                    352:                        buf=(char*)pa_realloc(buf, bufsize+1);
1.70      misha     353:                }
1.77      misha     354:                result.str=buf;
1.70      misha     355:        }
                    356: }
                    357: 
1.51      paf       358: #endif
1.1       paf       359: 
1.51      paf       360: #ifndef DOXYGEN
                    361: struct Append_env_pair_info {
1.84      moko      362: #ifdef _MSC_VER
1.62      paf       363:        String::Body& body;
                    364:        Append_env_pair_info(String::Body& abody): body(abody) {}
1.51      paf       365: #else
                    366:        char **env_ref;
                    367: #endif
                    368: };
                    369: #endif
1.83      moko      370: 
1.75      misha     371: ///@test maybe here and at argv construction --- untaint_cstr(String::L_AS_IS
1.51      paf       372: static void append_env_pair(HashStringString::key_type key, HashStringString::value_type value,
                    373:                Append_env_pair_info *info) {
1.84      moko      374: #ifdef _MSC_VER
1.62      paf       375:        info->body << key << "=" << value;
                    376:        info->body.append_know_length("\1", 1); // placeholder for of zero byte
1.1       paf       377: #else
1.52      paf       378:        String::Body body;
1.63      paf       379:        body << key << "=" << value.cstr();
1.1       paf       380: 
1.61      paf       381:        *(info->env_ref++)=body.cstrm();
1.1       paf       382: #endif
                    383: }
1.31      paf       384: 
1.51      paf       385: PA_exec_result pa_exec(
1.81      misha     386:                        bool forced_allow,
1.32      paf       387:                        const String& file_spec, 
1.51      paf       388:                        const HashStringString* env, 
                    389:                        const ArrayString& argv, 
                    390:                        String& in) {
                    391:        PA_exec_result result;
1.1       paf       392: 
1.28      paf       393: #ifdef NO_PA_EXECS
1.32      paf       394:        if(!forced_allow)
1.88    ! moko      395:                throw Exception(PARSER_RUNTIME, &file_spec, "parser execs are disabled [recompile parser without --disable-execs configure option]");
1.32      paf       396: #endif
1.28      paf       397: 
1.84      moko      398: #ifdef _MSC_VER
1.1       paf       399: 
                    400:        PROCESS_INFORMATION pi; 
                    401:        HANDLE hInWrite, hOutRead, hErrRead;
1.75      misha     402:        const char* script_spec_cstr=file_spec.taint_cstr(String::L_FILE_SPEC);
1.65      paf       403:        const char* cmd=buildCommand(script_spec_cstr, argv);
1.53      paf       404:        char* env_cstr=0;
1.1       paf       405:        if(env) {
1.62      paf       406:                String::Body body;
                    407:                Append_env_pair_info info(body);
1.68      paf       408:                env->for_each<Append_env_pair_info*>(append_env_pair, &info);
1.62      paf       409:                env_cstr=info.body.cstrm();
1.51      paf       410:                for(char* replacer=env_cstr; *replacer; replacer++)
                    411:                        if(*replacer=='\1')
                    412:                                *replacer=0;
1.1       paf       413:        }
1.65      paf       414:        if(DWORD error=CreateHiddenConsoleProcess(cmd, script_spec_cstr, env_cstr, &pi, &hInWrite, &hOutRead, &hErrRead)) {
1.36      paf       415:                char szErrorDesc[MAX_STRING];
1.51      paf       416:                const char* param="the file you tried to run";
1.36      paf       417:                size_t error_size=FormatMessage(
                    418:                        FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ARGUMENT_ARRAY , NULL, error,
                    419:                        MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
1.51      paf       420:                        szErrorDesc, sizeof(szErrorDesc), (va_list *)&param);
1.36      paf       421:                if(error_size>3) // ".\r\n"
                    422:                        szErrorDesc[error_size-3]=0;
1.73      misha     423: 
1.88    ! moko      424:                throw Exception("file.execute", &file_spec, "exec failed - %s (%u). Consider adding shbang line (#!x:\\interpreter\\command line)", error_size ? szErrorDesc : "<unknown>", error);
1.36      paf       425:        } else {
1.51      paf       426:                const char* in_cstr=in.cstr();
1.5       paf       427:                DWORD written_size;
1.51      paf       428:                WriteFile(hInWrite, in_cstr, in.length(), &written_size, NULL);
1.9       parser    429:                CloseHandle(hInWrite);
1.70      misha     430:                read_pipe(result.out, hOutRead);
1.9       parser    431:                CloseHandle(hOutRead);
1.83      moko      432:                read_pipe(result.err, hErrRead, String::L_TAINTED);
1.9       parser    433:                CloseHandle(hErrRead);
1.87      moko      434:                result.status=get_exit_status(pi.hProcess);
1.83      moko      435:                // We must close the handles to the new process and its main thread
                    436:                // to prevent handle and memory leaks.
1.1       paf       437:                CloseHandle(pi.hProcess);
1.73      misha     438:                CloseHandle(pi.hThread);
1.1       paf       439:        }
                    440: 
                    441: #else
1.53      paf       442: 
                    443:        // execve needs non const
1.75      misha     444:        char* file_spec_cstr=file_spec.taint_cstrm(String::L_FILE_SPEC); 
1.1       paf       445: 
                    446:        int pipe_write, pipe_read, pipe_err;
1.31      paf       447: 
1.32      paf       448:        if(!forced_allow) {
                    449:                struct stat finfo;
                    450:                if(stat(file_spec_cstr, &finfo)!=0)
1.88    ! moko      451:                        throw Exception("file.missing", &file_spec, "stat failed: %s (%d), actual filename '%s'", strerror(errno), errno, file_spec_cstr);
1.31      paf       452: 
1.50      paf       453:                check_safe_mode(finfo, file_spec, file_spec_cstr);
1.32      paf       454:        }
1.31      paf       455: 
1.76      misha     456:        char* argv_cstrs[1+100+1]={file_spec_cstr, 0};
1.51      paf       457:        const int argv_size=argv.count();
                    458:        const int argv_max=sizeof(argv_cstrs)/sizeof(argv_cstrs[0])-1-1;
                    459:        if(argv_size>argv_max)
1.88    ! moko      460:                throw Exception(PARSER_RUNTIME, &file_spec, "too many arguments (%d > max %d)", argv_size, argv_max);
1.51      paf       461:        for(int i=0; i<argv_size; i++)
                    462:                argv_cstrs[1+i]=argv[i]->cstrm();
                    463:        argv_cstrs[1+argv_size]=0;
                    464: 
                    465:        char **env_cstrs;
1.1       paf       466:        if(env) {
1.51      paf       467:                env_cstrs=new(PointerFreeGC) char *[env->count()+1/*0*/];
                    468:                Append_env_pair_info info={env_cstrs}; 
                    469:                env->for_each(append_env_pair, &info);
                    470:                *info.env_ref=0;
                    471:        } else
                    472:                env_cstrs=0;
1.31      paf       473: 
1.46      paf       474:        pid_t pid=execve_piped(
1.1       paf       475:                file_spec_cstr,
1.27      paf       476:                argv_cstrs, env_cstrs,
1.22      paf       477:                &pipe_write, &pipe_read, &pipe_err);
1.46      paf       478:        if(pid>0) {
1.21      paf       479:                // in child
1.73      misha     480:                if(!in.is_empty()) {// there is some in data
1.51      paf       481:                        const char* in_cstr=in.cstr();
                    482:                        write(pipe_write, in_cstr, in.length());
                    483:                }
1.1       paf       484:                close(pipe_write);
1.70      misha     485:                read_pipe(result.out, pipe_read);
1.5       paf       486:                close(pipe_read);
1.51      paf       487:                read_pipe(result.err, pipe_err, String::L_TAINTED);
1.1       paf       488:                close(pipe_err);
                    489: 
1.51      paf       490:                result.status=get_exit_status(pid); // negative may mean "-errno[execl()]"
1.59      paf       491:        } else { 
                    492:                const char* str=strerror(errno);
1.88    ! moko      493:                throw Exception("file.execute", &file_spec, "%s error: %s (%d)", pid<0?"fork":"pipe", str?str:"<unknown>", errno); 
1.59      paf       494:        }
1.1       paf       495: #endif
                    496: 
1.51      paf       497:        return result;
1.1       paf       498: }

E-mail: