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

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.86    ! moko       16: volatile const char * IDENT_PA_EXEC_C="$Id: pa_exec.C,v 1.85 2015/10/26 01:21:58 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.65      paf        24:                                                                                LPCTSTR szScriptFileSpec,
1.51      paf        25:                                                                                char *szEnv,
1.73      misha      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.51      paf       120: static void read_pipe(String& result, HANDLE hOutRead, String::Language lang){
                    121:        while(true) {
1.77      misha     122:                char *buf=new(PointerFreeGC) char[MAX_STRING+1];
1.78      misha     123:                DWORD size=0;
1.77      misha     124:                if(!ReadFile(hOutRead, buf, MAX_STRING, &size, NULL) || !size) 
1.51      paf       125:                        break;
                    126:                buf[size]=0;
                    127:                result.append_know_length(buf, size, lang);
                    128:        }
1.1       paf       129: }
                    130: 
1.70      misha     131: static void read_pipe(File_read_result& result, HANDLE hOutRead){
1.71      misha     132: 
1.77      misha     133:        char *buf=(char*)pa_malloc(MAX_STRING+1);
                    134:        DWORD bufsize = MAX_STRING;
1.70      misha     135: 
                    136:        result.headers = 0;
                    137:        result.length = 0;
                    138:        result.str = 0;
                    139:        result.success = false;
                    140: 
                    141:        while(true) {
1.77      misha     142:                DWORD size=0;
                    143:                if(!ReadFile(hOutRead, buf + result.length, bufsize - result.length, &size, NULL) || !size)
1.70      misha     144:                        break;
1.77      misha     145:                result.length += size;
                    146:                if(result.length >= bufsize){
                    147:                        bufsize *= 2;
                    148:                        buf=(char*)pa_realloc(buf, bufsize+1);
1.70      misha     149:                }
1.77      misha     150:                result.str=buf;
1.70      misha     151:        }
                    152: }
                    153: 
1.51      paf       154: static const char* buildCommand(const char* file_spec_cstr, const ArrayString& argv) {
                    155:        const char* result=file_spec_cstr;
1.4       paf       156:        if(FILE *f=fopen(file_spec_cstr, "r")) {
1.51      paf       157:                try {
1.1       paf       158:                char buf[MAX_STRING];
                    159:                size_t size=fread(buf, 1, MAX_STRING-1, f);
                    160:                if(size>2) {
                    161:                        buf[size]=0;
                    162:                        if(strncmp(buf, "#!", 2)==0) {
1.51      paf       163:                                const char* begin=buf+2;
1.65      paf       164:                                while(*begin==' ') // alx: were an old magic for some linux-es
1.4       paf       165:                                        begin++;
1.68      paf       166:                                if(const char *end=strchr(begin, '\n')) {
1.51      paf       167:                                        String string(pa_strdup(begin, end-begin));
1.1       paf       168:                                        string << " " << file_spec_cstr;
1.8       parser    169:                                        result=string.cstr();
1.1       paf       170:                                }
                    171:                        }
                    172:                }
1.51      paf       173:                } catch(...) {
                    174:                        fclose(f);
                    175:                        rethrow;
                    176:                }
1.1       paf       177:                fclose(f);
                    178:        }
1.51      paf       179:        { // appending argv
                    180:                String string(result);
                    181:                for(size_t i=0; i<argv.count(); i++) {
                    182:                        string << " ";
                    183:                        string << *argv[i];
1.8       parser    184:                }
                    185: 
1.51      paf       186:                result=string.cstr();
1.8       parser    187:        }
                    188: 
                    189:        return result;
1.1       paf       190: }
                    191: 
1.51      paf       192: #else
1.1       paf       193: 
1.51      paf       194: static pid_t execve_piped(const char* file_spec_cstr, 
1.27      paf       195:                        char * const argv[], char * const env[],
                    196:                        int *pipe_in, int *pipe_out, int *pipe_err) {
1.46      paf       197:        pid_t pid;
1.1       paf       198:        int in_fds[2];
                    199:        int out_fds[2];
                    200:        int err_fds[2];
                    201:        int save_errno;
                    202:        
                    203:        if(pipe_in && pipe(in_fds)<0) {
                    204:                save_errno=errno;
                    205:                errno=save_errno;
                    206:                return 0;
                    207:        }
                    208:        
                    209:        if(pipe_out && pipe(out_fds)<0) {
                    210:                save_errno=errno;
                    211:                if(pipe_in) {
                    212:                        close(in_fds[0]); close(in_fds[1]);
                    213:                }
                    214:                errno=save_errno;
                    215:                return 0;
                    216:        }
                    217:        
                    218:        if(pipe_err && pipe(err_fds)<0) {
                    219:                save_errno=errno;
                    220:                if(pipe_in) {
                    221:                        close(in_fds[0]); close(in_fds[1]);
                    222:                }
                    223:                if(pipe_out) {
                    224:                        close(out_fds[0]); close(out_fds[1]);
                    225:                }
                    226:                errno=save_errno;
                    227:                return 0;
                    228:        }
                    229:        
                    230:        if((pid=fork())<0) {
                    231:                save_errno=errno;
                    232:                if(pipe_in) {
                    233:                        close(in_fds[0]); close(in_fds[1]);
                    234:                }
                    235:                if(pipe_out) {
                    236:                        close(out_fds[0]); close(out_fds[1]);
                    237:                }
                    238:                if(pipe_err) {
                    239:                        close(err_fds[0]); close(err_fds[1]);
                    240:                }
                    241:                errno=save_errno;
1.46      paf       242:                return -1;
1.1       paf       243:        }
                    244:        
                    245:        if(!pid) {
                    246:                /* Child process */
                    247:                
                    248:                if(pipe_out) {
                    249:                        close(out_fds[0]);
                    250:                        dup2(out_fds[1], STDOUT_FILENO);
                    251:                        close(out_fds[1]);
                    252:                }
                    253:                
                    254:                if(pipe_in) {
                    255:                        close(in_fds[1]);
                    256:                        dup2(in_fds[0], STDIN_FILENO);
                    257:                        close(in_fds[0]);
                    258:                }
                    259:                
                    260:                if(pipe_err) {
                    261:                        close(err_fds[0]);
                    262:                        dup2(err_fds[1], STDERR_FILENO);
                    263:                        close(err_fds[1]);
                    264:                }
                    265:                
1.42      paf       266:                /* grabbed this from Apache source: */
                    267:                /*  HP-UX SIGCHLD fix goes here, if someone will remind me what it is... */
1.1       paf       268:                signal(SIGCHLD, SIG_DFL);       /* Was that it? */
                    269:        
1.31      paf       270:                // chdir to script's directory
                    271:                char dir[MAX_STRING];
                    272:                strncpy(dir, file_spec_cstr, MAX_STRING-1); dir[MAX_STRING-1]=0;
                    273:                rsplit(dir,'/'); // trim filename
                    274:                chdir(dir);
                    275: 
                    276:                //  execute
                    277:                execve(file_spec_cstr, argv, env);
1.1       paf       278:                exit(-errno);
                    279:        }
                    280:        
                    281:        /* Parent process */
                    282:        
                    283:        if(pipe_out) {
                    284:                close(out_fds[1]);
                    285:                *pipe_out=out_fds[0];
                    286:        }
                    287:        
                    288:        if(pipe_in) {
                    289:                close(in_fds[0]);
                    290:                *pipe_in=in_fds[1];
                    291:        }
                    292:        
                    293:        if(pipe_err) {
                    294:                close(err_fds[1]);
                    295:                *pipe_err=err_fds[0];
                    296:        }
                    297: 
                    298:        return pid;
                    299: }
                    300: 
                    301: static int get_exit_status(int pid) {
                    302:        int status;
1.58      paf       303:        pid_t cid;
                    304:        while ((cid=waitpid(pid, &status, WUNTRACED)) == -1 && errno == EINTR); 
                    305:        if(!cid)
1.1       paf       306:                return -1;
                    307:        return WIFEXITED(status) ? 
                    308:                WEXITSTATUS(status) : -2;
                    309: }
                    310: 
1.51      paf       311: static void read_pipe(String& result, int file, String::Language lang){
1.1       paf       312:        while(true) {
1.77      misha     313:                char *buf=new(PointerFreeGC) char[MAX_STRING+1];
                    314:                ssize_t length=read(file, buf, MAX_STRING);
1.51      paf       315:                if(length<=0)
1.49      paf       316:                        break;
1.51      paf       317:                buf[length]=0;
                    318:                result.append_know_length(buf, length, lang);
                    319:        }
1.1       paf       320: }
                    321: 
1.70      misha     322: static void read_pipe(File_read_result& result, int file){
1.77      misha     323:        char *buf=(char*)pa_malloc(MAX_STRING+1);
                    324:        ssize_t bufsize = MAX_STRING;
1.70      misha     325: 
                    326:        result.headers = 0;
                    327:        result.length = 0;
                    328:        result.str = 0;
                    329:        result.success = false;
                    330: 
                    331:        while(true) {
1.77      misha     332:                ssize_t size=read(file, buf + result.length, bufsize - result.length);
1.70      misha     333:                if(size <= 0)
                    334:                        break;
1.77      misha     335:                result.length += size;
                    336:                if(result.length >= bufsize){
                    337:                        bufsize *= 2;
                    338:                        buf=(char*)pa_realloc(buf, bufsize+1);
1.70      misha     339:                }
1.77      misha     340:                result.str=buf;
1.70      misha     341:        }
                    342: }
                    343: 
1.51      paf       344: #endif
1.1       paf       345: 
1.51      paf       346: #ifndef DOXYGEN
                    347: struct Append_env_pair_info {
1.84      moko      348: #ifdef _MSC_VER
1.62      paf       349:        String::Body& body;
                    350:        Append_env_pair_info(String::Body& abody): body(abody) {}
1.51      paf       351: #else
                    352:        char **env_ref;
                    353: #endif
                    354: };
                    355: #endif
1.83      moko      356: 
1.75      misha     357: ///@test maybe here and at argv construction --- untaint_cstr(String::L_AS_IS
1.51      paf       358: static void append_env_pair(HashStringString::key_type key, HashStringString::value_type value,
                    359:                Append_env_pair_info *info) {
1.84      moko      360: #ifdef _MSC_VER
1.62      paf       361:        info->body << key << "=" << value;
                    362:        info->body.append_know_length("\1", 1); // placeholder for of zero byte
1.1       paf       363: #else
1.52      paf       364:        String::Body body;
1.63      paf       365:        body << key << "=" << value.cstr();
1.1       paf       366: 
1.61      paf       367:        *(info->env_ref++)=body.cstrm();
1.1       paf       368: #endif
                    369: }
1.31      paf       370: 
1.51      paf       371: PA_exec_result pa_exec(
1.81      misha     372:                        bool forced_allow,
1.32      paf       373:                        const String& file_spec, 
1.51      paf       374:                        const HashStringString* env, 
                    375:                        const ArrayString& argv, 
                    376:                        String& in) {
                    377:        PA_exec_result result;
1.1       paf       378: 
1.28      paf       379: #ifdef NO_PA_EXECS
1.32      paf       380:        if(!forced_allow)
1.69      misha     381:                throw Exception(PARSER_RUNTIME,
1.32      paf       382:                        &file_spec,
                    383:                        "parser execs are disabled [recompile parser without --disable-execs configure option]");
                    384: #endif
1.28      paf       385: 
1.84      moko      386: #ifdef _MSC_VER
1.1       paf       387: 
                    388:        PROCESS_INFORMATION pi; 
                    389:        HANDLE hInWrite, hOutRead, hErrRead;
1.75      misha     390:        const char* script_spec_cstr=file_spec.taint_cstr(String::L_FILE_SPEC);
1.65      paf       391:        const char* cmd=buildCommand(script_spec_cstr, argv);
1.53      paf       392:        char* env_cstr=0;
1.1       paf       393:        if(env) {
1.62      paf       394:                String::Body body;
                    395:                Append_env_pair_info info(body);
1.68      paf       396:                env->for_each<Append_env_pair_info*>(append_env_pair, &info);
1.62      paf       397:                env_cstr=info.body.cstrm();
1.51      paf       398:                for(char* replacer=env_cstr; *replacer; replacer++)
                    399:                        if(*replacer=='\1')
                    400:                                *replacer=0;
1.1       paf       401:        }
1.65      paf       402:        if(DWORD error=CreateHiddenConsoleProcess(cmd, script_spec_cstr, env_cstr, &pi, &hInWrite, &hOutRead, &hErrRead)) {
1.36      paf       403:                char szErrorDesc[MAX_STRING];
1.51      paf       404:                const char* param="the file you tried to run";
1.36      paf       405:                size_t error_size=FormatMessage(
                    406:                        FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ARGUMENT_ARRAY , NULL, error,
                    407:                        MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
1.51      paf       408:                        szErrorDesc, sizeof(szErrorDesc), (va_list *)&param);
1.36      paf       409:                if(error_size>3) // ".\r\n"
                    410:                        szErrorDesc[error_size-3]=0;
1.73      misha     411: 
1.72      misha     412:                throw Exception("file.execute",
1.36      paf       413:                        &file_spec,
1.56      paf       414:                        "exec failed - %s (%u). Consider adding shbang line (#!x:\\interpreter\\command line)", 
                    415:                                error_size?szErrorDesc:"<unknown>", error);
1.36      paf       416:        } else {
1.51      paf       417:                const char* in_cstr=in.cstr();
1.5       paf       418:                DWORD written_size;
1.51      paf       419:                WriteFile(hInWrite, in_cstr, in.length(), &written_size, NULL);
1.9       parser    420:                CloseHandle(hInWrite);
1.70      misha     421:                read_pipe(result.out, hOutRead);
1.9       parser    422:                CloseHandle(hOutRead);
1.83      moko      423:                read_pipe(result.err, hErrRead, String::L_TAINTED);
1.9       parser    424:                CloseHandle(hErrRead);
1.83      moko      425:                // We must close the handles to the new process and its main thread
                    426:                // to prevent handle and memory leaks.
1.1       paf       427:                CloseHandle(pi.hProcess);
1.73      misha     428:                CloseHandle(pi.hThread);
1.1       paf       429:        }
                    430: 
                    431: #else
1.53      paf       432: 
                    433:        // execve needs non const
1.75      misha     434:        char* file_spec_cstr=file_spec.taint_cstrm(String::L_FILE_SPEC); 
1.1       paf       435: 
                    436:        int pipe_write, pipe_read, pipe_err;
1.31      paf       437: 
1.32      paf       438:        if(!forced_allow) {
                    439:                struct stat finfo;
                    440:                if(stat(file_spec_cstr, &finfo)!=0)
1.34      paf       441:                        throw Exception("file.missing", 
1.51      paf       442:                                &file_spec, 
                    443:                                "stat failed: %s (%d), actual filename '%s'", 
                    444:                                        strerror(errno), errno, file_spec_cstr);
1.31      paf       445: 
1.50      paf       446:                check_safe_mode(finfo, file_spec, file_spec_cstr);
1.32      paf       447:        }
1.31      paf       448: 
1.76      misha     449:        char* argv_cstrs[1+100+1]={file_spec_cstr, 0};
1.51      paf       450:        const int argv_size=argv.count();
                    451:        const int argv_max=sizeof(argv_cstrs)/sizeof(argv_cstrs[0])-1-1;
                    452:        if(argv_size>argv_max)
1.69      misha     453:                throw Exception(PARSER_RUNTIME,
1.51      paf       454:                        &file_spec,
                    455:                        "too many arguments (%d > max %d)", argv_size, argv_max);
                    456:        for(int i=0; i<argv_size; i++)
                    457:                argv_cstrs[1+i]=argv[i]->cstrm();
                    458:        argv_cstrs[1+argv_size]=0;
                    459: 
                    460:        char **env_cstrs;
1.1       paf       461:        if(env) {
1.51      paf       462:                env_cstrs=new(PointerFreeGC) char *[env->count()+1/*0*/];
                    463:                Append_env_pair_info info={env_cstrs}; 
                    464:                env->for_each(append_env_pair, &info);
                    465:                *info.env_ref=0;
                    466:        } else
                    467:                env_cstrs=0;
1.31      paf       468: 
1.46      paf       469:        pid_t pid=execve_piped(
1.1       paf       470:                file_spec_cstr,
1.27      paf       471:                argv_cstrs, env_cstrs,
1.22      paf       472:                &pipe_write, &pipe_read, &pipe_err);
1.46      paf       473:        if(pid>0) {
1.21      paf       474:                // in child
1.73      misha     475:                if(!in.is_empty()) {// there is some in data
1.51      paf       476:                        const char* in_cstr=in.cstr();
                    477:                        write(pipe_write, in_cstr, in.length());
                    478:                }
1.1       paf       479:                close(pipe_write);
1.70      misha     480:                read_pipe(result.out, pipe_read);
1.5       paf       481:                close(pipe_read);
1.51      paf       482:                read_pipe(result.err, pipe_err, String::L_TAINTED);
1.1       paf       483:                close(pipe_err);
                    484: 
1.51      paf       485:                result.status=get_exit_status(pid); // negative may mean "-errno[execl()]"
1.59      paf       486:        } else { 
                    487:                const char* str=strerror(errno);
1.72      misha     488:                throw Exception("file.execute",
1.2       paf       489:                        &file_spec,
1.59      paf       490:                        "%s error: %s (%d)", pid<0?"fork":"pipe", str?str:"<unknown>", errno); 
                    491:        }
1.1       paf       492: #endif
                    493: 
1.51      paf       494:        return result;
1.1       paf       495: }

E-mail: