Execute install scripts with cwd==/ (bnc#886764)
[platform/upstream/libzypp.git] / zypp / ExternalProgram.h
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/ExternalProgram.h
10 */
11
12
13 #ifndef ZYPP_EXTERNALPROGRAM_H
14 #define ZYPP_EXTERNALPROGRAM_H
15
16 #include <unistd.h>
17
18 #include <map>
19 #include <string>
20 #include <vector>
21
22 #include "zypp/base/ExternalDataSource.h"
23 #include "zypp/Pathname.h"
24
25 namespace zypp {
26
27     /**
28      * @short Execute a program and give access to its io
29      * An object of this class encapsulates the execution of
30      * an external program. It starts the program using fork
31      * and some exec.. call, gives you access to the program's
32      * stdio and closes the program after use.
33      *
34      * \code
35      *
36      * const char* argv[] =
37      * {
38      *     "/usr/bin/foo,
39      *     "--option1",
40      *     "--option2",
41      *     NULL
42      * };
43      *
44      * ExternalProgram prog( argv,
45      *                        ExternalProgram::Discard_Stderr,
46      *                        false, -1, true);
47      * string line;
48      * for(line = prog.receiveLine();
49      *     ! line.empty();
50      *     line = prog.receiveLine() )
51      * {
52      *     stream << line;
53      * }
54      * prog.close();
55      *
56      * \endcode
57      */
58     class ExternalProgram : public zypp::externalprogram::ExternalDataSource
59     {
60
61     public:
62
63       typedef std::vector<std::string> Arguments;
64
65       /**
66        * Define symbols for different policies on the handling
67        * of stderr
68        */
69       enum Stderr_Disposition {
70         Normal_Stderr,
71         Discard_Stderr,
72         Stderr_To_Stdout,
73         Stderr_To_FileDesc
74       };
75
76
77       /**
78        * For passing additional environment variables to set
79        */
80       typedef std::map<std::string,std::string> Environment;
81
82       /**
83        * Start the external program by using the shell <tt>/bin/sh<tt>
84        * with the option <tt>-c</tt>. You can use io direction symbols < and >.
85        * @param commandline a shell commandline that is appended to
86        * <tt>/bin/sh -c</tt>.
87        * @param default_locale whether to set LC_ALL=C before starting
88        * @param root directory to chroot into; or just 'cd' if '/'l;  nothing if empty
89        */
90       ExternalProgram (std::string commandline,
91                      Stderr_Disposition stderr_disp = Normal_Stderr,
92                      bool use_pty = false, int stderr_fd = -1, bool default_locale = false,
93                      const Pathname& root = "");
94
95       /**
96        * Start an external program by giving the arguments as an arry of char *pointers.
97        * If environment is provided, varaiables will be added to the childs environment,
98        * overwriting existing ones.
99        *
100        * Initial args starting with \c # are discarded but some are treated specially:
101        *        #/[path] - chdir to /[path] before executing
102        *
103        * Stdin redirection: If the \b 1st argument starts with a \b '<', the remaining
104        * part is treated as file opened for reading on standard input (or \c /dev/null
105        * if empty).
106        * \code
107        *   // cat file /tmp/x
108        *   const char* argv[] = { "</tmp/x", "cat", NULL };
109        *   ExternalProgram prog( argv );
110        * \endcode
111        */
112
113       ExternalProgram();
114
115       ExternalProgram (const Arguments &argv,
116                      Stderr_Disposition stderr_disp = Normal_Stderr,
117                      bool use_pty = false, int stderr_fd = -1, bool default_locale = false,
118                      const Pathname& root = "");
119
120       ExternalProgram (const Arguments &argv, const Environment & environment,
121                      Stderr_Disposition stderr_disp = Normal_Stderr,
122                      bool use_pty = false, int stderr_fd = -1, bool default_locale = false,
123                      const Pathname& root = "");
124
125       ExternalProgram (const char *const *argv,
126                      Stderr_Disposition stderr_disp = Normal_Stderr,
127                      bool use_pty = false, int stderr_fd = -1, bool default_locale = false,
128                      const Pathname& root = "");
129
130       ExternalProgram (const char *const *argv, const Environment & environment,
131                      Stderr_Disposition stderr_disp = Normal_Stderr,
132                      bool use_pty = false, int stderr_fd = -1, bool default_locale = false,
133                      const Pathname& root = "");
134
135       ExternalProgram (const char *binpath, const char *const *argv_1,
136                      bool use_pty = false);
137
138
139       ExternalProgram (const char *binpath, const char *const *argv_1, const Environment & environment,
140                      bool use_pty = false);
141
142
143       ~ExternalProgram();
144
145       /** Wait for the progamm to complete. */
146       int close();
147
148       /**
149        * Kill the program
150        */
151       bool kill();
152
153       /**
154        * Return whether program is running
155        */
156       bool running();
157
158       /**
159        * return pid
160        * */
161       pid_t getpid() { return pid; }
162
163       /** The command we're executing. */
164       const std::string & command() const
165       { return _command; }
166
167       /** Some detail telling why the execution failed, if it failed.
168        * Empty if the command is still running or successfully completed.
169        *
170        * \li <tt>Can't open pty (%s).</tt>
171        * \li <tt>Can't open pipe (%s).</tt>
172        * \li <tt>Can't fork (%s).</tt>
173        * \li <tt>Command exited with status %d.</tt>
174        * \li <tt>Command was killed by signal %d (%s).</tt>
175       */
176       const std::string & execError() const
177       { return _execError; }
178
179       /**
180        * origfd will be accessible as newfd and closed (unless they were equal)
181        */
182       static void renumber_fd (int origfd, int newfd);
183
184     public:
185
186       /**
187        * Redirect all command output to an \c ostream.
188        * Returns when the command has completed.
189        * \code
190        *   std::ostringstream s;
191        *   ExternalProgram("pwd") >> s;
192        *   SEC << s.str() << endl;
193        * \endcode
194        * \code
195        *   std::ostringstream s;
196        *   ExternalProgram prog("ls -l wrzl");
197        *   prog >> s;
198        *   if ( prog.close() == 0 )
199        *     MIL << s.str() << endl;
200        *   else
201        *     ERR << prog.execError() << endl;
202        * \endcode
203        */
204       std::ostream & operator>>( std::ostream & out_r );
205
206     protected:
207       int checkStatus( int );
208
209     private:
210
211       /**
212        * Set to true, if a pair of ttys is used for communication
213        * instead of a pair of pipes.
214        */
215       bool use_pty;
216
217       pid_t pid;
218       int _exitStatus;
219       /** Store the command we're executing. */
220       std::string _command;
221       /** Remember execution errors like failed fork/exec. */
222       std::string _execError;
223
224       void start_program (const char *const *argv, const Environment & environment,
225                         Stderr_Disposition stderr_disp = Normal_Stderr,
226                         int stderr_fd = -1, bool default_locale = false,
227                         const char* root = NULL);
228
229     };
230
231
232   namespace _ExternalProgram
233   {
234     /** Helper providing pipe FDs for \ref ExternalProgramWithStderr.
235      * Moved to a basse class because the pipe needs to be initialized
236      * before the \ref ExternalProgram base class is initialized.
237      * \see \ref ExternalProgramWithStderr
238      */
239     struct EarlyPipe
240     {
241       enum { R=0, W=1 };
242       EarlyPipe();
243       ~EarlyPipe();
244       void closeW()             { if ( _fds[W] != -1 ) { ::close( _fds[W] ); _fds[W] = -1; } }
245       FILE * stderr()           { return _stderr; }
246       protected:
247         FILE * _stderr;
248         int _fds[2];
249     };
250   }
251
252   /** ExternalProgram extended to offer reading programs stderr.
253    * \see \ref ExternalProgram
254    */
255   class ExternalProgramWithStderr : private _ExternalProgram::EarlyPipe, public ExternalProgram
256   {
257     public:
258       ExternalProgramWithStderr( const Arguments & argv_r )
259         : ExternalProgram( argv_r, Stderr_To_FileDesc, /*use_pty*/false, _fds[W] )
260       { _initStdErr(); }
261
262       ExternalProgramWithStderr( const Arguments & argv_r, const Environment & environment_r )
263         : ExternalProgram( argv_r, environment_r, Stderr_To_FileDesc, /*use_pty*/false, _fds[W] )
264       { _initStdErr(); }
265
266     public:
267       /** Return \c FILE* to read programms stderr (O_NONBLOCK set). */
268       using _ExternalProgram::EarlyPipe::stderr;
269
270       /** Read data up to \c delim_r from stderr (nonblocking).
271        * \note If \c delim_r is '\0', we read as much data as possible.
272        * \return \c false if data are not yet available (\c retval_r remains untouched then).
273        */
274       bool stderrGetUpTo( std::string & retval_r, const char delim_r, bool returnDelim_r = false );
275
276       /** Read next complete line from stderr (nonblocking).
277        * \return \c false if data are not yet available (\c retval_r remains untouched then).
278        */
279       bool stderrGetline( std::string & retval_r, bool returnDelim_r = false  )
280       { return stderrGetUpTo( retval_r, '\n', returnDelim_r ); }
281
282     private:
283       /** Close write end of the pipe (childs end). */
284       void _initStdErr()
285       { closeW(); }
286
287     private:
288       std::string _buffer;
289   };
290
291 } // namespace zypp
292
293 #endif // ZYPP_EXTERNALPROGRAM_H