1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/ExternalProgram.cc
12 #define _GNU_SOURCE 1 // for ::getline
19 #include <pty.h> // openpty
20 #include <stdlib.h> // setenv
22 #include <cstring> // strsignal
26 #include "zypp/base/Logger.h"
27 #include "zypp/base/String.h"
28 #include "zypp/base/Gettext.h"
29 #include "zypp/ExternalProgram.h"
35 ExternalProgram::ExternalProgram()
41 ExternalProgram::ExternalProgram( std::string commandline,
42 Stderr_Disposition stderr_disp,
46 const Pathname & root )
53 argv[2] = commandline.c_str();
56 start_program( argv, Environment(), stderr_disp, stderr_fd, default_locale, root.c_str() );
60 ExternalProgram::ExternalProgram( const Arguments & argv,
61 Stderr_Disposition stderr_disp,
65 const Pathname & root )
69 const char * argvp[argv.size() + 1];
71 for_( i, argv.begin(), argv.end() )
73 argvp[c] = i->c_str();
78 start_program( argvp, Environment(), stderr_disp, stderr_fd, default_locale, root.c_str() );
82 ExternalProgram::ExternalProgram( const Arguments & argv,
83 const Environment & environment,
84 Stderr_Disposition stderr_disp,
88 const Pathname & root )
92 const char * argvp[argv.size() + 1];
94 for_( i, argv.begin(), argv.end() )
96 argvp[c] = i->c_str();
101 start_program( argvp, environment, stderr_disp, stderr_fd, default_locale, root.c_str() );
106 ExternalProgram::ExternalProgram( const char *const *argv,
107 Stderr_Disposition stderr_disp,
111 const Pathname & root )
115 start_program( argv, Environment(), stderr_disp, stderr_fd, default_locale, root.c_str() );
119 ExternalProgram::ExternalProgram( const char *const * argv,
120 const Environment & environment,
121 Stderr_Disposition stderr_disp,
125 const Pathname & root )
129 start_program( argv, environment, stderr_disp, stderr_fd, default_locale, root.c_str() );
133 ExternalProgram::ExternalProgram( const char *binpath,
134 const char *const *argv_1,
142 const char *argv[i + 1];
144 memcpy( &argv[1], argv_1, (i - 1) * sizeof (char *) );
145 start_program( argv, Environment() );
149 ExternalProgram::ExternalProgram( const char *binpath,
150 const char *const *argv_1,
151 const Environment & environment,
159 const char *argv[i + 1];
161 memcpy( &argv[1], argv_1, (i - 1) * sizeof (char *) );
162 start_program( argv, environment );
166 ExternalProgram::~ExternalProgram()
171 void ExternalProgram::start_program( const char *const *argv,
172 const Environment & environment,
173 Stderr_Disposition stderr_disp,
180 int to_external[2], from_external[2]; // fds for pair of pipes
181 int master_tty, slave_tty; // fds for pair of ttys
183 // retrieve options at beginning of arglist
184 const char * redirectStdin = nullptr; // <[file]
185 const char * redirectStdout = nullptr; // >[file]
186 const char * chdirTo = nullptr; // #/[path]
190 if ( root[0] == '\0' )
192 root = nullptr; // ignore empty root
194 else if ( root[0] == '/' && root[1] == '\0' )
196 // If root is '/' do not chroot, but chdir to '/'
197 // unless arglist defines another dir.
203 for ( bool strip = false; argv[0]; ++argv )
206 switch ( argv[0][0] )
210 redirectStdin = argv[0]+1;
211 if ( *redirectStdin == '\0' )
212 redirectStdin = "/dev/null";
217 redirectStdout = argv[0]+1;
218 if ( *redirectStdout == '\0' )
219 redirectStdout = "/dev/null";
224 if ( argv[0][1] == '/' ) // #/[path]
232 // do not remove the single quotes around every argument, copy&paste of
233 // command to shell will not work otherwise!
236 for (int i = 0; argv[i]; i++)
238 if (i>0) cmdstr << ' ';
244 cmdstr << " < '" << redirectStdin << "'";
245 if ( redirectStdout )
246 cmdstr << " > '" << redirectStdout << "'";
247 _command = cmdstr.str();
249 DBG << "Executing " << _command << endl;
254 // Create pair of ttys
255 DBG << "Using ttys for communication with " << argv[0] << endl;
256 if (openpty (&master_tty, &slave_tty, 0, 0, 0) != 0)
258 _execError = str::form( _("Can't open pty (%s)."), strerror(errno) );
260 ERR << _execError << endl;
266 // Create pair of pipes
267 if (pipe (to_external) != 0 || pipe (from_external) != 0)
269 _execError = str::form( _("Can't open pipe (%s)."), strerror(errno) );
271 ERR << _execError << endl;
276 // Create module process
277 if ((pid = fork()) == 0)
279 //////////////////////////////////////////////////////////////////////
280 // Don't write to the logfile after fork!
281 //////////////////////////////////////////////////////////////////////
286 dup2 (slave_tty, 1); // set new stdout
287 renumber_fd (slave_tty, 0); // set new stdin
288 ::close(master_tty); // Belongs to father process
290 // We currently have no controlling terminal (due to setsid).
291 // The first open call will also set the new ctty (due to historical
292 // unix guru knowledge ;-) )
295 ttyname_r(slave_tty, name, sizeof(name));
296 ::close(open(name, O_RDONLY));
300 renumber_fd (to_external[0], 0); // set new stdin
301 ::close(from_external[0]); // Belongs to father process
303 renumber_fd (from_external[1], 1); // set new stdout
304 ::close(to_external [1]); // Belongs to father process
310 int inp_fd = open( redirectStdin, O_RDONLY );
314 if ( redirectStdout )
317 int inp_fd = open( redirectStdout, O_WRONLY|O_CREAT|O_APPEND, 0600 );
322 if (stderr_disp == Discard_Stderr)
324 int null_fd = open("/dev/null", O_WRONLY);
328 else if (stderr_disp == Stderr_To_Stdout)
332 else if (stderr_disp == Stderr_To_FileDesc)
334 // Note: We don't have to close anything regarding stderr_fd.
335 // Our caller is responsible for that.
339 for ( Environment::const_iterator it = environment.begin(); it != environment.end(); ++it ) {
340 setenv( it->first.c_str(), it->second.c_str(), 1 );
344 setenv("LC_ALL","C",1);
348 if(chroot(root) == -1)
350 _execError = str::form( _("Can't chroot to '%s' (%s)."), root, strerror(errno) );
351 std::cerr << _execError << endl;// After fork log on stderr too
352 _exit (128); // No sense in returning! I am forked away!!
358 if ( chdirTo && chdir( chdirTo ) == -1 )
360 _execError = root ? str::form( _("Can't chdir to '%s' inside chroot '%s' (%s)."), chdirTo, root, strerror(errno) )
361 : str::form( _("Can't chdir to '%s' (%s)."), chdirTo, strerror(errno) );
362 std::cerr << _execError << endl;// After fork log on stderr too
363 _exit (128); // No sense in returning! I am forked away!!
366 // close all filedesctiptors above stderr
367 for ( int i = ::getdtablesize() - 1; i > 2; --i ) {
371 execvp(argv[0], const_cast<char *const *>(argv));
372 // don't want to get here
373 _execError = str::form( _("Can't exec '%s' (%s)."), argv[0], strerror(errno) );
374 std::cerr << _execError << endl;// After fork log on stderr too
375 _exit (129); // No sense in returning! I am forked away!!
376 //////////////////////////////////////////////////////////////////////
379 else if (pid == -1) // Fork failed, close everything.
381 _execError = str::form( _("Can't fork (%s)."), strerror(errno) );
383 ERR << _execError << endl;
390 ::close(to_external[0]);
391 ::close(to_external[1]);
392 ::close(from_external[0]);
393 ::close(from_external[1]);
400 ::close(slave_tty); // belongs to child process
401 inputfile = fdopen(master_tty, "r");
402 outputfile = fdopen(master_tty, "w");
406 ::close(to_external[0]); // belongs to child process
407 ::close(from_external[1]); // belongs to child process
408 inputfile = fdopen(from_external[0], "r");
409 outputfile = fdopen(to_external[1], "w");
412 DBG << "pid " << pid << " launched" << endl;
414 if (!inputfile || !outputfile)
416 ERR << "Cannot create streams to external program " << argv[0] << endl;
424 ExternalProgram::close()
430 // Discard any output instead of closing the pipe,
431 // but watch out for the command exiting while some
432 // subprocess keeps the filedescriptor open.
433 setBlocking( false );
434 FILE * inputfile = inputFile();
435 int inputfileFd = ::fileno( inputfile );
439 /* Watch inputFile to see when it has input. */
442 FD_SET( inputfileFd, &rfds );
444 /* Wait up to 1 seconds. */
446 tv.tv_sec = (delay < 0 ? 1 : 0);
447 tv.tv_usec = (delay < 0 ? 0 : delay*100000);
448 if ( delay >= 0 && ++delay > 9 )
450 int retval = select( inputfileFd+1, &rfds, NULL, NULL, &tv );
454 ERR << "select error: " << strerror(errno) << endl;
455 if ( errno != EINTR )
460 // Data is available now.
461 static size_t linebuffer_size = 0; // static because getline allocs
462 static char * linebuffer = 0; // and reallocs if buffer is too small
463 getline( &linebuffer, &linebuffer_size, inputfile );
464 // ::feof check is important as select returns
465 // positive if the file was closed.
466 if ( ::feof( inputfile ) )
468 clearerr( inputfile );
472 // No data within time.
479 if ( pid > 0 ) // bsc#1109877: must re-check! running() in the loop above may have already waited.
481 // Wait for child to exit
486 ret = waitpid(pid, &status, 0);
488 while (ret == -1 && errno == EINTR);
492 _exitStatus = checkStatus( status );
502 int ExternalProgram::checkStatus( int status )
504 if (WIFEXITED (status))
506 status = WEXITSTATUS (status);
509 DBG << "Pid " << pid << " exited with status " << status << endl;
510 _execError = str::form( _("Command exited with status %d."), status );
514 // if 'launch' is logged, completion should be logged,
515 // even if successfull.
516 DBG << "Pid " << pid << " successfully completed" << endl;
517 _execError.clear(); // empty if running or successfully completed
520 else if (WIFSIGNALED (status))
522 status = WTERMSIG (status);
523 WAR << "Pid " << pid << " was killed by signal " << status
524 << " (" << strsignal(status);
525 if (WCOREDUMP (status))
527 WAR << ", core dumped";
530 _execError = str::form( _("Command was killed by signal %d (%s)."), status, strsignal(status) );
534 ERR << "Pid " << pid << " exited with unknown error" << endl;
535 _execError = _("Command exited with unknown error.");
542 ExternalProgram::kill()
546 ::kill(pid, SIGKILL);
554 ExternalProgram::running()
556 if ( pid < 0 ) return false;
559 int p = waitpid( pid, &status, WNOHANG );
563 ERR << "waitpid( " << pid << ") returned error '" << strerror(errno) << "'" << endl;
567 return true; // still running
571 // Here: completed...
572 _exitStatus = checkStatus( status );
577 // origfd will be accessible as newfd and closed (unless they were equal)
578 void ExternalProgram::renumber_fd (int origfd, int newfd)
580 // It may happen that origfd is already the one we want
581 // (Although in our circumstances, that would mean somebody has closed
582 // our stdin or stdout... weird but has appened to Cray, #49797)
585 dup2 (origfd, newfd);
590 std::ostream & ExternalProgram::operator>>( std::ostream & out_r )
593 for ( std::string line = receiveLine(); line.length(); line = receiveLine() )
598 //////////////////////////////////////////////////////////////////////
600 // class ExternalProgramWithStderr
602 //////////////////////////////////////////////////////////////////////
604 namespace _ExternalProgram
606 EarlyPipe::EarlyPipe()
608 _fds[R] = _fds[W] = -1;
610 ::pipe2( _fds, O_NONBLOCK );
613 ::fcntl(_fds[R], F_SETFD, O_NONBLOCK );
614 ::fcntl(_fds[W], F_SETFD, O_NONBLOCK );
616 _stderr = ::fdopen( _fds[R], "r" );
619 EarlyPipe::~EarlyPipe()
627 bool ExternalProgramWithStderr::stderrGetUpTo( std::string & retval_r, const char delim_r, bool returnDelim_r )
631 if ( delim_r && ! _buffer.empty() )
633 // check for delim already in buffer
634 std::string::size_type pos( _buffer.find( delim_r ) );
635 if ( pos != std::string::npos )
637 retval_r = _buffer.substr( 0, returnDelim_r ? pos+1 : pos );
638 _buffer.erase( 0, pos+1 );
642 ::clearerr( _stderr );
644 int ch = fgetc( _stderr );
647 if ( ch != delim_r || ! delim_r )
648 _buffer.push_back( ch );
652 _buffer.push_back( delim_r );
656 else if ( ::feof( _stderr ) )
658 if ( _buffer.empty() )
662 else if ( errno != EINTR )
665 // HERE: we left after readig at least one char (\n)
666 retval_r.swap( _buffer );