Support linux namespace clone flags
[folly.git] / folly / Subprocess.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * Subprocess library, modeled after Python's subprocess module
19  * (http://docs.python.org/2/library/subprocess.html)
20  *
21  * This library defines one class (Subprocess) which represents a child
22  * process.  Subprocess has two constructors: one that takes a vector<string>
23  * and executes the given executable without using the shell, and one
24  * that takes a string and executes the given command using the shell.
25  * Subprocess allows you to redirect the child's standard input, standard
26  * output, and standard error to/from child descriptors in the parent,
27  * or to create communication pipes between the child and the parent.
28  *
29  * The simplest example is a thread-safe [1] version of the system() library
30  * function:
31  *    Subprocess(cmd).wait();
32  * which executes the command using the default shell and waits for it
33  * to complete, returning the exit status.
34  *
35  * A thread-safe [1] version of popen() (type="r", to read from the child):
36  *    Subprocess proc(cmd, Subprocess::pipeStdout());
37  *    // read from proc.stdoutFd()
38  *    proc.wait();
39  *
40  * A thread-safe [1] version of popen() (type="w", to write to the child):
41  *    Subprocess proc(cmd, Subprocess::pipeStdin());
42  *    // write to proc.stdinFd()
43  *    proc.wait();
44  *
45  * If you want to redirect both stdin and stdout to pipes, you can, but note
46  * that you're subject to a variety of deadlocks.  You'll want to use
47  * nonblocking I/O, like the callback version of communicate().
48  *
49  * The string or IOBuf-based variants of communicate() are the simplest way
50  * to communicate with a child via its standard input, standard output, and
51  * standard error.  They buffer everything in memory, so they are not great
52  * for large amounts of data (or long-running processes), but they are much
53  * simpler than the callback version.
54  *
55  * == A note on thread-safety ==
56  *
57  * [1] "thread-safe" refers ONLY to the fact that Subprocess is very careful
58  * to fork in a way that does not cause grief in multithreaded programs.
59  *
60  * Caveat: If your system does not have the atomic pipe2 system call, it is
61  * not safe to concurrently call Subprocess from different threads.
62  * Therefore, it is best to have a single thread be responsible for spawning
63  * subprocesses.
64  *
65  * A particular instances of Subprocess is emphatically **not** thread-safe.
66  * If you need to simultaneously communicate via the pipes, and interact
67  * with the Subprocess state, your best bet is to:
68  *  - takeOwnershipOfPipes() to separate the pipe I/O from the subprocess.
69  *  - Only interact with the Subprocess from one thread at a time.
70  *
71  * The current implementation of communicate() cannot be safely interrupted.
72  * To do so correctly, one would need to use EventFD, or open a dedicated
73  * pipe to be messaged from a different thread -- in particular, kill() will
74  * not do, since a descendant may keep the pipes open indefinitely.
75  *
76  * So, once you call communicate(), you must wait for it to return, and not
77  * touch the pipes from other threads.  closeParentFd() is emphatically
78  * unsafe to call concurrently, and even sendSignal() is not a good idea.
79  * You can perhaps give the Subprocess's PID to a different thread before
80  * starting communicate(), and use that PID to send a signal without
81  * accessing the Subprocess object.  In that case, you will need a mutex
82  * that ensures you don't wait() before you sent said signal.  In a
83  * nutshell, don't do this.
84  *
85  * In fact, signals are inherently concurrency-unsafe on Unix: if you signal
86  * a PID, while another thread is in waitpid(), the signal may fire either
87  * before or after the process is reaped.  This means that your signal can,
88  * in pathological circumstances, be delivered to the wrong process (ouch!).
89  * To avoid this, you should only use non-blocking waits (i.e. poll()), and
90  * make sure to serialize your signals (i.e. kill()) with the waits --
91  * either wait & signal from the same thread, or use a mutex.
92  */
93
94 #pragma once
95
96 #include <sys/types.h>
97 #include <signal.h>
98 #if __APPLE__
99 #include <sys/wait.h>
100 #else
101 #include <wait.h>
102 #endif
103
104 #include <exception>
105 #include <vector>
106 #include <string>
107
108 #include <boost/container/flat_map.hpp>
109 #include <boost/operators.hpp>
110
111 #include <folly/Exception.h>
112 #include <folly/File.h>
113 #include <folly/FileUtil.h>
114 #include <folly/Function.h>
115 #include <folly/MapUtil.h>
116 #include <folly/Optional.h>
117 #include <folly/Portability.h>
118 #include <folly/Range.h>
119 #include <folly/gen/String.h>
120 #include <folly/io/IOBufQueue.h>
121
122 namespace folly {
123
124 /**
125  * Class to wrap a process return code.
126  */
127 class Subprocess;
128 class ProcessReturnCode {
129   friend class Subprocess;
130  public:
131   enum State {
132     // Subprocess starts in the constructor, so this state designates only
133     // default-initialized or moved-out ProcessReturnCodes.
134     NOT_STARTED,
135     RUNNING,
136     EXITED,
137     KILLED
138   };
139
140   // Default-initialized for convenience. Subprocess::returnCode() will
141   // never produce this value.
142   ProcessReturnCode() : ProcessReturnCode(RV_NOT_STARTED) {}
143
144   // Trivially copyable
145   ProcessReturnCode(const ProcessReturnCode& p) = default;
146   ProcessReturnCode& operator=(const ProcessReturnCode& p) = default;
147   // Non-default move: In order for Subprocess to be movable, the "moved
148   // out" state must not be "running", or ~Subprocess() will abort.
149   ProcessReturnCode(ProcessReturnCode&& p) noexcept;
150   ProcessReturnCode& operator=(ProcessReturnCode&& p) noexcept;
151
152   /**
153    * Process state.  One of:
154    * NOT_STARTED: process hasn't been started successfully
155    * RUNNING: process is currently running
156    * EXITED: process exited (successfully or not)
157    * KILLED: process was killed by a signal.
158    */
159   State state() const;
160
161   /**
162    * Helper wrappers around state().
163    */
164   bool notStarted() const { return state() == NOT_STARTED; }
165   bool running() const { return state() == RUNNING; }
166   bool exited() const { return state() == EXITED; }
167   bool killed() const { return state() == KILLED; }
168
169   /**
170    * Exit status.  Only valid if state() == EXITED; throws otherwise.
171    */
172   int exitStatus() const;
173
174   /**
175    * Signal that caused the process's termination.  Only valid if
176    * state() == KILLED; throws otherwise.
177    */
178   int killSignal() const;
179
180   /**
181    * Was a core file generated?  Only valid if state() == KILLED; throws
182    * otherwise.
183    */
184   bool coreDumped() const;
185
186   /**
187    * String representation; one of
188    * "not started"
189    * "running"
190    * "exited with status <status>"
191    * "killed by signal <signal>"
192    * "killed by signal <signal> (core dumped)"
193    */
194   std::string str() const;
195
196   /**
197    * Helper function to enforce a precondition based on this.
198    * Throws std::logic_error if in an unexpected state.
199    */
200   void enforce(State state) const;
201  private:
202   explicit ProcessReturnCode(int rv) : rawStatus_(rv) { }
203   static constexpr int RV_NOT_STARTED = -2;
204   static constexpr int RV_RUNNING = -1;
205
206   int rawStatus_;
207 };
208
209 /**
210  * Base exception thrown by the Subprocess methods.
211  */
212 class SubprocessError : public std::exception {};
213
214 /**
215  * Exception thrown by *Checked methods of Subprocess.
216  */
217 class CalledProcessError : public SubprocessError {
218  public:
219   explicit CalledProcessError(ProcessReturnCode rc);
220   ~CalledProcessError() throw() = default;
221   const char* what() const throw() override { return what_.c_str(); }
222   ProcessReturnCode returnCode() const { return returnCode_; }
223  private:
224   ProcessReturnCode returnCode_;
225   std::string what_;
226 };
227
228 /**
229  * Exception thrown if the subprocess cannot be started.
230  */
231 class SubprocessSpawnError : public SubprocessError {
232  public:
233   SubprocessSpawnError(const char* executable, int errCode, int errnoValue);
234   ~SubprocessSpawnError() throw() = default;
235   const char* what() const throw() override { return what_.c_str(); }
236   int errnoValue() const { return errnoValue_; }
237
238  private:
239   int errnoValue_;
240   std::string what_;
241 };
242
243 /**
244  * Subprocess.
245  */
246 class Subprocess {
247  public:
248   static const int CLOSE = -1;
249   static const int PIPE = -2;
250   static const int PIPE_IN = -3;
251   static const int PIPE_OUT = -4;
252
253   /**
254    * See Subprocess::Options::dangerousPostForkPreExecCallback() for usage.
255    * Every derived class should include the following warning:
256    *
257    * DANGER: This class runs after fork in a child processes. Be fast, the
258    * parent thread is waiting, but remember that other parent threads are
259    * running and may mutate your state.  Avoid mutating any data belonging to
260    * the parent.  Avoid interacting with non-POD data that originated in the
261    * parent.  Avoid any libraries that may internally reference non-POD data.
262    * Especially beware parent mutexes -- for example, glog's LOG() uses one.
263    */
264   struct DangerousPostForkPreExecCallback {
265     virtual ~DangerousPostForkPreExecCallback() {}
266     // This must return 0 on success, or an `errno` error code.
267     virtual int operator()() = 0;
268   };
269
270   /**
271    * Class representing various options: file descriptor behavior, and
272    * whether to use $PATH for searching for the executable,
273    *
274    * By default, we don't use $PATH, file descriptors are closed if
275    * the close-on-exec flag is set (fcntl FD_CLOEXEC) and inherited
276    * otherwise.
277    */
278   class Options : private boost::orable<Options> {
279     friend class Subprocess;
280    public:
281     Options() {}  // E.g. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58328
282
283     /**
284      * Change action for file descriptor fd.
285      *
286      * "action" may be another file descriptor number (dup2()ed before the
287      * child execs), or one of CLOSE, PIPE_IN, and PIPE_OUT.
288      *
289      * CLOSE: close the file descriptor in the child
290      * PIPE_IN: open a pipe *from* the child
291      * PIPE_OUT: open a pipe *to* the child
292      *
293      * PIPE is a shortcut; same as PIPE_IN for stdin (fd 0), same as
294      * PIPE_OUT for stdout (fd 1) or stderr (fd 2), and an error for
295      * other file descriptors.
296      */
297     Options& fd(int fd, int action);
298
299     /**
300      * Shortcut to change the action for standard input.
301      */
302     Options& stdinFd(int action) { return fd(STDIN_FILENO, action); }
303
304     /**
305      * Shortcut to change the action for standard output.
306      */
307     Options& stdoutFd(int action) { return fd(STDOUT_FILENO, action); }
308
309     /**
310      * Shortcut to change the action for standard error.
311      * Note that stderr(1) will redirect the standard error to the same
312      * file descriptor as standard output; the equivalent of bash's "2>&1"
313      */
314     Options& stderrFd(int action) { return fd(STDERR_FILENO, action); }
315
316     Options& pipeStdin() { return fd(STDIN_FILENO, PIPE_IN); }
317     Options& pipeStdout() { return fd(STDOUT_FILENO, PIPE_OUT); }
318     Options& pipeStderr() { return fd(STDERR_FILENO, PIPE_OUT); }
319
320     /**
321      * Close all other fds (other than standard input, output, error,
322      * and file descriptors explicitly specified with fd()).
323      *
324      * This is potentially slow; it's generally a better idea to
325      * set the close-on-exec flag on all file descriptors that shouldn't
326      * be inherited by the child.
327      *
328      * Even with this option set, standard input, output, and error are
329      * not closed; use stdin(CLOSE), stdout(CLOSE), stderr(CLOSE) if you
330      * desire this.
331      */
332     Options& closeOtherFds() { closeOtherFds_ = true; return *this; }
333
334     /**
335      * Use the search path ($PATH) when searching for the executable.
336      */
337     Options& usePath() { usePath_ = true; return *this; }
338
339     /**
340      * Change the child's working directory, after the vfork.
341      */
342     Options& chdir(const std::string& dir) { childDir_ = dir; return *this; }
343
344 #if __linux__
345     /**
346      * Child will receive a signal when the parent exits.
347      */
348     Options& parentDeathSignal(int sig) {
349       parentDeathSignal_ = sig;
350       return *this;
351     }
352 #endif
353
354     /**
355      * Child will be made a process group leader when it starts. Upside: one
356      * can reliably all its kill non-daemonizing descendants.  Downside: the
357      * child will not receive Ctrl-C etc during interactive use.
358      */
359     Options& processGroupLeader() {
360       processGroupLeader_ = true;
361       return *this;
362     }
363
364     /**
365      * *** READ THIS WHOLE DOCBLOCK BEFORE USING ***
366      *
367      * Run this callback in the child after the fork, just before the
368      * exec(), and after the child's state has been completely set up:
369      *  - signal handlers have been reset to default handling and unblocked
370      *  - the working directory was set
371      *  - closed any file descriptors specified via Options()
372      *  - set child process flags (see code)
373      *
374      * This is EXTREMELY DANGEROUS. For example, this innocuous-looking code
375      * can cause a fraction of your Subprocess launches to hang forever:
376      *
377      *   LOG(INFO) << "Hello from the child";
378      *
379      * The reason is that glog has an internal mutex. If your fork() happens
380      * when the parent has the mutex locked, the child will wait forever.
381      *
382      * == GUIDELINES ==
383      *
384      * - Be quick -- the parent thread is blocked until you exit.
385      * - Remember that other parent threads are running, and may mutate your
386      *   state.
387      * - Avoid mutating any data belonging to the parent.
388      * - Avoid interacting with non-POD data that came from the parent.
389      * - Avoid any libraries that may internally reference non-POD state.
390      * - Especially beware parent mutexes, e.g. LOG() uses a global mutex.
391      * - Avoid invoking the parent's destructors (you can accidentally
392      *   delete files, terminate network connections, etc).
393      * - Read http://ewontfix.com/7/
394      */
395     Options& dangerousPostForkPreExecCallback(
396         DangerousPostForkPreExecCallback* cob) {
397       dangerousPostForkPreExecCallback_ = cob;
398       return *this;
399     }
400
401 #if __linux__
402     /**
403      * This is an experimental feature, it is best you don't use it at this
404      * point of time.
405      * Although folly would support cloning with custom flags in some form, this
406      * API might change in the near future. So use the following assuming it is
407      * experimental. (Apr 11, 2017)
408      *
409      * This unlocks Subprocess to support clone flags, many of them need
410      * CAP_SYS_ADMIN permissions. It might also require you to go through the
411      * implementation to understand what happens before, between and after the
412      * fork-and-exec.
413      *
414      * `man 2 clone` would be a starting point for knowing about the available
415      * flags.
416      */
417     using clone_flags_t = uint64_t;
418     Options& useCloneWithFlags(clone_flags_t cloneFlags) noexcept {
419       cloneFlags_ = cloneFlags;
420       return *this;
421     }
422 #endif
423
424     /**
425      * Helpful way to combine Options.
426      */
427     Options& operator|=(const Options& other);
428
429    private:
430     typedef boost::container::flat_map<int, int> FdMap;
431     FdMap fdActions_;
432     bool closeOtherFds_{false};
433     bool usePath_{false};
434     std::string childDir_;  // "" keeps the parent's working directory
435 #if __linux__
436     int parentDeathSignal_{0};
437 #endif
438     bool processGroupLeader_{false};
439     DangerousPostForkPreExecCallback*
440       dangerousPostForkPreExecCallback_{nullptr};
441 #if __linux__
442     // none means `vfork()` instead of a custom `clone()`
443     // Optional<> is used because value of '0' means do clone without any flags.
444     Optional<clone_flags_t> cloneFlags_;
445 #endif
446   };
447
448   static Options pipeStdin() { return Options().stdinFd(PIPE); }
449   static Options pipeStdout() { return Options().stdoutFd(PIPE); }
450   static Options pipeStderr() { return Options().stderrFd(PIPE); }
451
452   // Non-copiable, but movable
453   Subprocess(const Subprocess&) = delete;
454   Subprocess& operator=(const Subprocess&) = delete;
455   Subprocess(Subprocess&&) = default;
456   Subprocess& operator=(Subprocess&&) = default;
457
458   /**
459    * Create an uninitialized subprocess.
460    *
461    * In this state it can only be destroyed, or assigned to using the move
462    * assignment operator.
463    */
464   Subprocess();
465
466   /**
467    * Create a subprocess from the given arguments.  argv[0] must be listed.
468    * If not-null, executable must be the actual executable
469    * being used (otherwise it's the same as argv[0]).
470    *
471    * If env is not-null, it must contain name=value strings to be used
472    * as the child's environment; otherwise, we inherit the environment
473    * from the parent.  env must be null if options.usePath is set.
474    */
475   explicit Subprocess(
476       const std::vector<std::string>& argv,
477       const Options& options = Options(),
478       const char* executable = nullptr,
479       const std::vector<std::string>* env = nullptr);
480   ~Subprocess();
481
482   /**
483    * Create a subprocess run as a shell command (as shell -c 'command')
484    *
485    * The shell to use is taken from the environment variable $SHELL,
486    * or /bin/sh if $SHELL is unset.
487    */
488   FOLLY_DEPRECATED("Prefer not running in a shell or use `shellify`.")
489   explicit Subprocess(
490       const std::string& cmd,
491       const Options& options = Options(),
492       const std::vector<std::string>* env = nullptr);
493
494   ////
495   //// The methods below only manipulate the process state, and do not
496   //// affect its communication pipes.
497   ////
498
499   /**
500    * Return the child's pid, or -1 if the child wasn't successfully spawned
501    * or has already been wait()ed upon.
502    */
503   pid_t pid() const;
504
505   /**
506    * Return the child's status (as per wait()) if the process has already
507    * been waited on, -1 if the process is still running, or -2 if the
508    * process hasn't been successfully started.  NOTE that this does not call
509    * waitpid() or Subprocess::poll(), but simply returns the status stored
510    * in the Subprocess object.
511    */
512   ProcessReturnCode returnCode() const { return returnCode_; }
513
514   /**
515    * Poll the child's status and return it. Return the exit status if the
516    * subprocess had quit, or RUNNING otherwise.  Throws an std::logic_error
517    * if called on a Subprocess whose status is no longer RUNNING.  No other
518    * exceptions are possible.  Aborts on egregious violations of contract,
519    * e.g. if you wait for the underlying process without going through this
520    * Subprocess instance.
521    */
522   ProcessReturnCode poll();
523
524   /**
525    * Poll the child's status.  If the process is still running, return false.
526    * Otherwise, return true if the process exited with status 0 (success),
527    * or throw CalledProcessError if the process exited with a non-zero status.
528    */
529   bool pollChecked();
530
531   /**
532    * Wait for the process to terminate and return its status.  Like poll(),
533    * the only exception this can throw is std::logic_error if you call this
534    * on a Subprocess whose status is RUNNING.  Aborts on egregious
535    * violations of contract, like an out-of-band waitpid(p.pid(), 0, 0).
536    */
537   ProcessReturnCode wait();
538
539   /**
540    * Wait for the process to terminate, throw if unsuccessful.
541    */
542   void waitChecked();
543
544   /**
545    * Send a signal to the child.  Shortcuts for the commonly used Unix
546    * signals are below.
547    */
548   void sendSignal(int signal);
549   void terminate() { sendSignal(SIGTERM); }
550   void kill() { sendSignal(SIGKILL); }
551
552   ////
553   //// The methods below only affect the process's communication pipes, but
554   //// not its return code or state (they do not poll() or wait()).
555   ////
556
557   /**
558    * Communicate with the child until all pipes to/from the child are closed.
559    *
560    * The input buffer is written to the process' stdin pipe, and data is read
561    * from the stdout and stderr pipes.  Non-blocking I/O is performed on all
562    * pipes simultaneously to avoid deadlocks.
563    *
564    * The stdin pipe will be closed after the full input buffer has been written.
565    * An error will be thrown if a non-empty input buffer is supplied but stdin
566    * was not configured as a pipe.
567    *
568    * Returns a pair of buffers containing the data read from stdout and stderr.
569    * If stdout or stderr is not a pipe, an empty IOBuf queue will be returned
570    * for the respective buffer.
571    *
572    * Note that communicate() and communicateIOBuf() both return when all
573    * pipes to/from the child are closed; the child might stay alive after
574    * that, so you must still wait().
575    *
576    * communicateIOBuf() uses IOBufQueue for buffering (which has the
577    * advantage that it won't try to allocate all data at once), but it does
578    * store the subprocess's entire output in memory before returning.
579    *
580    * communicate() uses strings for simplicity.
581    */
582   std::pair<IOBufQueue, IOBufQueue> communicateIOBuf(
583       IOBufQueue input = IOBufQueue());
584
585   std::pair<std::string, std::string> communicate(
586       StringPiece input = StringPiece());
587
588   /**
589    * Communicate with the child until all pipes to/from the child are closed.
590    *
591    * == Semantics ==
592    *
593    * readCallback(pfd, cfd) will be called whenever there's data available
594    * on any pipe *from* the child (PIPE_OUT).  pfd is the file descriptor
595    * in the parent (that you use to read from); cfd is the file descriptor
596    * in the child (used for identifying the stream; 1 = child's standard
597    * output, 2 = child's standard error, etc)
598    *
599    * writeCallback(pfd, cfd) will be called whenever a pipe *to* the child is
600    * writable (PIPE_IN).  pfd is the file descriptor in the parent (that you
601    * use to write to); cfd is the file descriptor in the child (used for
602    * identifying the stream; 0 = child's standard input, etc)
603    *
604    * The read and write callbacks must read from / write to pfd and return
605    * false during normal operation.  Return true to tell communicate() to
606    * close the pipe.  For readCallback, this might send SIGPIPE to the
607    * child, or make its writes fail with EPIPE, so you should generally
608    * avoid returning true unless you've reached end-of-file.
609    *
610    * communicate() returns when all pipes to/from the child are closed; the
611    * child might stay alive after that, so you must still wait().
612    * Conversely, the child may quit long before its pipes are closed, since
613    * its descendants can keep them alive forever.
614    *
615    * Most users won't need to use this callback version; the simpler version
616    * of communicate (which buffers data in memory) will probably work fine.
617    *
618    * == Things you must get correct ==
619    *
620    * 1) You MUST consume all data passed to readCallback (or return true to
621    * close the pipe).  Similarly, you MUST write to a writable pipe (or
622    * return true to close the pipe).  To do otherwise is an error that can
623    * result in a deadlock.  You must do this even for pipes you are not
624    * interested in.
625    *
626    * 2) pfd is nonblocking, so be prepared for read() / write() to return -1
627    * and set errno to EAGAIN (in which case you should return false).  Use
628    * readNoInt() from FileUtil.h to handle interrupted reads for you.
629    *
630    * 3) Your callbacks MUST NOT call any of the Subprocess methods that
631    * manipulate the pipe FDs.  Check the docblocks, but, for example,
632    * neither closeParentFd (return true instead) nor takeOwnershipOfPipes
633    * are safe.  Stick to reading/writing from pfd, as appropriate.
634    *
635    * == Good to know ==
636    *
637    * 1) See ReadLinesCallback for an easy way to consume the child's output
638    * streams line-by-line (or tokenized by another delimiter).
639    *
640    * 2) "Wait until the descendants close the pipes" is usually the behavior
641    * you want, since the descendants may have something to say even if the
642    * immediate child is dead.  If you need to be able to force-close all
643    * parent FDs, communicate() will NOT work for you.  Do it your own way by
644    * using takeOwnershipOfPipes().
645    *
646    * Why not? You can return "true" from your callbacks to sever active
647    * pipes, but inactive ones can remain open indefinitely.  It is
648    * impossible to safely close inactive pipes while another thread is
649    * blocked in communicate().  This is BY DESIGN.  Racing communicate()'s
650    * read/write callbacks can result in wrong I/O and data corruption.  This
651    * class would need internal synchronization and timeouts, a poor and
652    * expensive implementation choice, in order to make closeParentFd()
653    * thread-safe.
654    */
655   using FdCallback = folly::Function<bool(int, int)>;
656   void communicate(FdCallback readCallback, FdCallback writeCallback);
657
658   /**
659    * A readCallback for Subprocess::communicate() that helps you consume
660    * lines (or other delimited pieces) from your subprocess's file
661    * descriptors.  Use the readLinesCallback() helper to get template
662    * deduction.  For example:
663    *
664    *   subprocess.communicate(
665    *     Subprocess::readLinesCallback(
666    *       [](int fd, folly::StringPiece s) {
667    *         std::cout << fd << " said: " << s;
668    *         return false;  // Keep reading from the child
669    *       }
670    *     ),
671    *     [](int pdf, int cfd){ return true; }  // Don't write to the child
672    *   );
673    *
674    * If a file line exceeds maxLineLength, your callback will get some
675    * initial chunks of maxLineLength with no trailing delimiters.  The final
676    * chunk of a line is delimiter-terminated iff the delimiter was present
677    * in the input.  In particular, the last line in a file always lacks a
678    * delimiter -- so if a file ends on a delimiter, the final line is empty.
679    *
680    * Like a regular communicate() callback, your fdLineCb() normally returns
681    * false.  It may return true to tell Subprocess to close the underlying
682    * file descriptor.  The child process may then receive SIGPIPE or get
683    * EPIPE errors on writes.
684    */
685   template <class Callback>
686   class ReadLinesCallback {
687    private:
688     // Binds an FD to the client-provided FD+line callback
689     struct StreamSplitterCallback {
690       StreamSplitterCallback(Callback& cb, int fd) : cb_(cb), fd_(fd) { }
691       // The return value semantics are inverted vs StreamSplitter
692       bool operator()(StringPiece s) { return !cb_(fd_, s); }
693       Callback& cb_;
694       int fd_;
695     };
696     typedef gen::StreamSplitter<StreamSplitterCallback> LineSplitter;
697    public:
698     explicit ReadLinesCallback(
699       Callback&& fdLineCb,
700       uint64_t maxLineLength = 0,  // No line length limit by default
701       char delimiter = '\n',
702       uint64_t bufSize = 1024
703     ) : fdLineCb_(std::forward<Callback>(fdLineCb)),
704         maxLineLength_(maxLineLength),
705         delimiter_(delimiter),
706         bufSize_(bufSize) {}
707
708     bool operator()(int pfd, int cfd) {
709       // Make a splitter for this cfd if it doesn't already exist
710       auto it = fdToSplitter_.find(cfd);
711       auto& splitter = (it != fdToSplitter_.end()) ? it->second
712         : fdToSplitter_.emplace(cfd, LineSplitter(
713             delimiter_, StreamSplitterCallback(fdLineCb_, cfd), maxLineLength_
714           )).first->second;
715       // Read as much as we can from this FD
716       char buf[bufSize_];
717       while (true) {
718         ssize_t ret = readNoInt(pfd, buf, bufSize_);
719         if (ret == -1 && errno == EAGAIN) {  // No more data for now
720           return false;
721         }
722         checkUnixError(ret, "read");
723         if (ret == 0) {  // Reached end-of-file
724           splitter.flush();  // Ignore return since the file is over anyway
725           return true;
726         }
727         if (!splitter(StringPiece(buf, ret))) {
728           return true;  // The callback told us to stop
729         }
730       }
731     }
732
733    private:
734     Callback fdLineCb_;
735     const uint64_t maxLineLength_;
736     const char delimiter_;
737     const uint64_t bufSize_;
738     // We lazily make splitters for all cfds that get used.
739     std::unordered_map<int, LineSplitter> fdToSplitter_;
740   };
741
742   // Helper to enable template deduction
743   template <class Callback>
744   static auto readLinesCallback(
745       Callback&& fdLineCb,
746       uint64_t maxLineLength = 0, // No line length limit by default
747       char delimiter = '\n',
748       uint64_t bufSize = 1024)
749       -> ReadLinesCallback<typename std::decay<Callback>::type> {
750     return ReadLinesCallback<typename std::decay<Callback>::type>(
751         std::forward<Callback>(fdLineCb), maxLineLength, delimiter, bufSize);
752   }
753
754   /**
755    * communicate() callbacks can use this to temporarily enable/disable
756    * notifications (callbacks) for a pipe to/from the child.  By default,
757    * all are enabled.  Useful for "chatty" communication -- you want to
758    * disable write callbacks until you receive the expected message.
759    *
760    * Disabling a pipe does not free you from the requirement to consume all
761    * incoming data.  Failing to do so will easily create deadlock bugs.
762    *
763    * Throws if the childFd is not known.
764    */
765   void enableNotifications(int childFd, bool enabled);
766
767   /**
768    * Are notifications for one pipe to/from child enabled?  Throws if the
769    * childFd is not known.
770    */
771   bool notificationsEnabled(int childFd) const;
772
773   ////
774   //// The following methods are meant for the cases when communicate() is
775   //// not suitable.  You should not need them when you call communicate(),
776   //// and, in fact, it is INHERENTLY UNSAFE to use closeParentFd() or
777   //// takeOwnershipOfPipes() from a communicate() callback.
778   ////
779
780   /**
781    * Close the parent file descriptor given a file descriptor in the child.
782    * DO NOT USE from communicate() callbacks; make them return true instead.
783    */
784   void closeParentFd(int childFd);
785
786   /**
787    * Set all pipes from / to child to be non-blocking.  communicate() does
788    * this for you.
789    */
790   void setAllNonBlocking();
791
792   /**
793    * Get parent file descriptor corresponding to the given file descriptor
794    * in the child.  Throws if childFd isn't a pipe (PIPE_IN / PIPE_OUT).
795    * Do not close() the returned file descriptor; use closeParentFd, above.
796    */
797   int parentFd(int childFd) const {
798     return pipes_[findByChildFd(childFd)].pipe.fd();
799   }
800   int stdinFd() const { return parentFd(0); }
801   int stdoutFd() const { return parentFd(1); }
802   int stderrFd() const { return parentFd(2); }
803
804   /**
805    * The child's pipes are logically separate from the process metadata
806    * (they may even be kept alive by the child's descendants).  This call
807    * lets you manage the pipes' lifetime separetely from the lifetime of the
808    * child process.
809    *
810    * After this call, the Subprocess instance will have no knowledge of
811    * these pipes, and the caller assumes responsibility for managing their
812    * lifetimes.  Pro-tip: prefer to explicitly close() the pipes, since
813    * folly::File would otherwise silently suppress I/O errors.
814    *
815    * No, you may NOT call this from a communicate() callback.
816    */
817   struct ChildPipe {
818     ChildPipe(int fd, folly::File&& ppe) : childFd(fd), pipe(std::move(ppe)) {}
819     int childFd;
820     folly::File pipe;  // Owns the parent FD
821   };
822   std::vector<ChildPipe> takeOwnershipOfPipes();
823
824  private:
825   static const int RV_RUNNING = ProcessReturnCode::RV_RUNNING;
826   static const int RV_NOT_STARTED = ProcessReturnCode::RV_NOT_STARTED;
827
828   // spawn() sets up a pipe to read errors from the child,
829   // then calls spawnInternal() to do the bulk of the work.  Once
830   // spawnInternal() returns it reads the error pipe to see if the child
831   // encountered any errors.
832   void spawn(
833       std::unique_ptr<const char*[]> argv,
834       const char* executable,
835       const Options& options,
836       const std::vector<std::string>* env);
837   void spawnInternal(
838       std::unique_ptr<const char*[]> argv,
839       const char* executable,
840       Options& options,
841       const std::vector<std::string>* env,
842       int errFd);
843
844   // Actions to run in child.
845   // Note that this runs after vfork(), so tread lightly.
846   // Returns 0 on success, or an errno value on failure.
847   int prepareChild(const Options& options,
848                    const sigset_t* sigmask,
849                    const char* childDir) const;
850   int runChild(const char* executable, char** argv, char** env,
851                const Options& options) const;
852
853   /**
854    * Read from the error pipe, and throw SubprocessSpawnError if the child
855    * failed before calling exec().
856    */
857   void readChildErrorPipe(int pfd, const char* executable);
858
859   // Returns an index into pipes_. Throws std::invalid_argument if not found.
860   size_t findByChildFd(const int childFd) const;
861
862   pid_t pid_{-1};
863   ProcessReturnCode returnCode_{RV_NOT_STARTED};
864
865   /**
866    * Represents a pipe between this process, and the child process (or its
867    * descendant).  To interact with these pipes, you can use communicate(),
868    * or use parentFd() and related methods, or separate them from the
869    * Subprocess instance entirely via takeOwnershipOfPipes().
870    */
871   struct Pipe : private boost::totally_ordered<Pipe> {
872     folly::File pipe; // Our end of the pipe, wrapped in a File to auto-close.
873     int childFd = -1; // Identifies the pipe: what FD is this in the child?
874     int direction = PIPE_IN; // one of PIPE_IN / PIPE_OUT
875     bool enabled = true; // Are notifications enabled in communicate()?
876
877     bool operator<(const Pipe& other) const {
878       return childFd < other.childFd;
879     }
880     bool operator==(const Pipe& other) const {
881       return childFd == other.childFd;
882     }
883   };
884
885   // Populated at process start according to fdActions, empty after
886   // takeOwnershipOfPipes().  Sorted by childFd.  Can only have elements
887   // erased, but not inserted, after being populated.
888   //
889   // The number of pipes between parent and child is assumed to be small,
890   // so we're happy with a vector here, even if it means linear erase.
891   std::vector<Pipe> pipes_;
892 };
893
894 inline Subprocess::Options& Subprocess::Options::operator|=(
895     const Subprocess::Options& other) {
896   if (this == &other) return *this;
897   // Replace
898   for (auto& p : other.fdActions_) {
899     fdActions_[p.first] = p.second;
900   }
901   closeOtherFds_ |= other.closeOtherFds_;
902   usePath_ |= other.usePath_;
903   processGroupLeader_ |= other.processGroupLeader_;
904   return *this;
905 }
906
907 }  // namespace folly