Revert "Merge remote-tracking branch 'remotes/origin/upstream'"
[framework/uifw/ecore.git] / src / lib / ecore / ecore_exe.c
1 #ifdef HAVE_CONFIG_H
2 # include <config.h>
3 #endif
4
5 #if defined (__FreeBSD__) || defined (__OpenBSD__) || defined (__NetBSD__)
6 # include <sys/time.h>
7 # include <sys/resource.h>
8 #endif
9
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <errno.h>
14 #include <sys/types.h>
15 #include <unistd.h>
16 #include <fcntl.h>
17
18 #ifdef HAVE_SYS_PRCTL_H
19 # include <sys/prctl.h>
20 #endif
21
22 #ifdef HAVE_SYS_WAIT_H
23 # include <sys/wait.h>
24 #endif
25
26 #include "Ecore.h"
27 #include "ecore_private.h"
28
29 /* FIXME: Getting respawn to work
30  *
31  * There is no way that we can do anything about the internal state info of
32  * an external exe.  The same can be said about the state of user code.  User
33  * code in this context means the code that is using ecore_exe to manage exe's
34  * for it.
35  *
36  * Document that the exe must be respawnable, in other words, there is no
37  * state that it cannot regenerate by just killing it and starting it again.
38  * This includes state that the user code knows about, as the respawn is
39  * transparent to that code.  On the other hand, maybe a respawn event might
40  * be useful, or maybe resend the currently non existent add event.  For
41  * consistancy with ecore_con, an add event is good anyway.
42  *
43  * The Ecore_exe structure is reused for respawning, so that the (opaque)
44  * pointer held by the user remains valid.  This means that the Ecore_Exe
45  * init and del functions may need to be split into two parts each to avoid
46  * duplicating code - common code part, and the rest.  This implies that
47  * the unchanging members mentioned next should NEVER change.
48  *
49  * These structure members don't need to change -
50  *   __list_data       - we stay on the list
51  *   ECORE_MAGIC       - this is a constant
52  *   data              - passed in originally
53  *   cmd               - passed in originally
54  *   flags             - passed in originally
55  *
56  * These structure members need to change -
57  *   tag               - state that must be regenerated, zap it
58  *   pid               - it will be different
59  *   child_fd_write    - it will be different
60  *   child_fd_read     - it will be different
61  *   child_fd_error    - it will be different
62  *   write_fd_handler  - we cannot change the fd used by a handler, this changes coz the fd changes.
63  *   read_fd_handler   - we cannot change the fd used by a handler, this changes coz the fd changes.
64  *   error_fd_handler  - we cannot change the fd used by a handler, this changes coz the fd changes.
65  *
66  * Hmm, the read, write, and error buffers could be tricky.
67  * They are not atomic, and could be in a semi complete state.
68  * They fall into the "state must be regenerated" mentioned above.
69  * A respawn/add event should take care of it.
70  *
71  * These structure members need to change -
72  *   write_data_buf    - state that must be regenerated, zap it
73  *   write_data_size   - state that must be regenerated, zap it
74  *   write_data_offset - state that must be regenerated, zap it
75  *   read_data_buf     - state that must be regenerated, zap it
76  *   read_data_size    - state that must be regenerated, zap it
77  *   error_data_buf    - state that must be regenerated, zap it
78  *   error_data_size   - state that must be regenerated, zap it
79  *   close_write       - state that must be regenerated, zap it
80  *
81  * There is the problem that an exe that fell over and needs respawning
82  * might keep falling over, keep needing to be respawned, and tie up system
83  * resources with the constant respawning.  An exponentially increasing
84  * timeout (with maximum timeout) between respawns should take care of that.
85  * Although this is not a "contention for a resource" problem, the exe falling
86  * over may be, so a random element added to the timeout may help, and won't
87  * hurt.  The user code may need to be informed that a timeout is in progress.
88  */
89
90 struct _Ecore_Exe
91 {
92    EINA_INLIST;
93                      ECORE_MAGIC;
94    pid_t             pid;
95    void             *data;
96    char             *tag, *cmd;
97    Ecore_Exe_Flags   flags;
98    Ecore_Fd_Handler *write_fd_handler; /* the fd_handler to handle write to child - if this was used, or NULL if not */
99    Ecore_Fd_Handler *read_fd_handler; /* the fd_handler to handle read from child - if this was used, or NULL if not */
100    Ecore_Fd_Handler *error_fd_handler; /* the fd_handler to handle errors from child - if this was used, or NULL if not */
101    void             *write_data_buf; /* a data buffer for data to write to the child -
102                                       * realloced as needed for more data and flushed when the fd handler says writes are possible
103                                       */
104    int               write_data_size; /* the size in bytes of the data buffer */
105    int               write_data_offset; /* the offset in bytes in the data buffer */
106    void             *read_data_buf; /* data read from the child awating delivery to an event */
107    int               read_data_size; /* data read from child in bytes */
108    void             *error_data_buf; /* errors read from the child awating delivery to an event */
109    int               error_data_size; /* errors read from child in bytes */
110    int               child_fd_write; /* fd to write TO to send data to the child */
111    int               child_fd_read; /* fd to read FROM when child has sent us (the parent) data */
112    int               child_fd_error; /* fd to read FROM when child has sent us (the parent) errors */
113    int               child_fd_write_x; /* fd to write TO to send data to the child */
114    int               child_fd_read_x; /* fd to read FROM when child has sent us (the parent) data */
115    int               child_fd_error_x; /* fd to read FROM when child has sent us (the parent) errors */
116    Eina_Bool         close_stdin : 1;
117
118    int               start_bytes, end_bytes, start_lines, end_lines; /* Number of bytes/lines to auto pipe at start/end of stdout/stderr. */
119
120    Ecore_Timer      *doomsday_clock; /* The Timer of Death.  Muahahahaha. */
121    void             *doomsday_clock_dead; /* data for the doomsday clock */
122
123    Ecore_Exe_Cb      pre_free_cb;
124 };
125
126 /* TODO: Something to let people build a command line and does auto escaping -
127  *
128  * ecore_exe_snprintf()
129  *
130  *   OR
131  *
132  * cmd = ecore_exe_comand_parameter_append(cmd, "firefox");
133  * cmd = ecore_exe_comand_parameter_append(cmd, "http://www.foo.com/bar.html?baz=yes");
134  * each parameter appended is one argument, and it gets escaped, quoted, and
135  * appended with a preceding space.  The first is the command off course.
136  */
137
138 struct _ecore_exe_dead_exe
139 {
140    pid_t pid;
141    char *cmd;
142 };
143
144 static inline void _ecore_exe_exec_it(const char     *exe_cmd,
145                                       Ecore_Exe_Flags flags);
146 static Eina_Bool   _ecore_exe_data_generic_handler(void             *data,
147                                                    Ecore_Fd_Handler *fd_handler,
148                                                    Ecore_Exe_Flags   flags);
149 static Eina_Bool            _ecore_exe_data_error_handler(void             *data,
150                                                           Ecore_Fd_Handler *fd_handler);
151 static Eina_Bool            _ecore_exe_data_read_handler(void             *data,
152                                                          Ecore_Fd_Handler *fd_handler);
153 static Eina_Bool            _ecore_exe_data_write_handler(void             *data,
154                                                           Ecore_Fd_Handler *fd_handler);
155 static void                 _ecore_exe_flush(Ecore_Exe *exe);
156 static void                 _ecore_exe_event_exe_data_free(void *data __UNUSED__,
157                                                            void *ev);
158 static Ecore_Exe           *_ecore_exe_is_it_alive(pid_t pid);
159 static Eina_Bool            _ecore_exe_make_sure_its_dead(void *data);
160 static Eina_Bool            _ecore_exe_make_sure_its_really_dead(void *data);
161 static Ecore_Exe_Event_Add *_ecore_exe_event_add_new(void);
162 static void                 _ecore_exe_event_add_free(void *data,
163                                                       void *ev);
164 static void                 _ecore_exe_dead_attach(Ecore_Exe *exe);
165
166 EAPI int ECORE_EXE_EVENT_ADD = 0;
167 EAPI int ECORE_EXE_EVENT_DEL = 0;
168 EAPI int ECORE_EXE_EVENT_DATA = 0;
169 EAPI int ECORE_EXE_EVENT_ERROR = 0;
170
171 static Ecore_Exe *exes = NULL;
172 static const char *shell = NULL;
173
174 /* FIXME: This errno checking stuff should be put elsewhere for everybody to use.
175  * For now it lives here though, just to make testing easier.
176  */
177 static int _ecore_exe_check_errno(int         result,
178                                   const char *file,
179                                   int         line);
180
181 #define E_IF_NO_ERRNO(result, foo, ok)                                                           \
182   while (((ok) = _ecore_exe_check_errno((result) = (foo), __FILE__, __LINE__)) == -1) sleep(1);  \
183           if (ok)
184
185 #define E_NO_ERRNO(result, foo, ok) \
186   while (((ok) = _ecore_exe_check_errno((result) = (foo), __FILE__, __LINE__)) == -1) sleep(1)
187
188 #define E_IF_NO_ERRNO_NOLOOP(result, foo, ok) \
189   if (((ok) = _ecore_exe_check_errno((result) = (foo), __FILE__, __LINE__)))
190
191 static int
192 _ecore_exe_check_errno(int         result,
193                        const char *file,
194                        int         line)
195 {
196    int saved_errno = errno;
197
198    if (result == -1)
199    {
200       perror("*** errno reports ");
201 /* What is currently supported -
202  *
203  *   pipe
204  *     EFAULT  Argument is not valid.
205  *     EMFILE  Too many file descriptors used by process.
206  *     ENFILE  Too many open files by system.
207  *   read
208  *     EAGAIN  No data now, try again.
209  *     EBADF   This is not an fd that can be read.
210  *     EFAULT  This is not a valid buffer.
211  *     EINTR   Interupted by signal, try again.
212  *     EINVAL  This is not an fd that can be read.
213  *     EIO     I/O error.
214  *     EISDIR  This is a directory, and cannot be read.
215  *     others  Depending on what sort of thing we are reading from.
216  *   close
217  *     EBADF   This is not an fd that can be closed.
218  *     EINTR   Interupted by signal, try again.
219  *     EIO     I/O error.
220  *   dup2
221  *     EBADF   This is not an fd that can be dup2'ed.
222  *     EBUSY   Race condition between open() and dup()
223  *     EINTR   Interupted by signal, try again.
224  *     EMFILE  Too many file descriptors used by process.
225  *   fcntl
226  *     EACCES, EAGAIN  Locked or mapped by something else, try again later.
227  *     EBADF   This is not an fd that can be fcntl'ed.
228  *     EDEADLK This will cause a deadlock.
229  *     EFAULT  This is not a valid lock.
230  *     EINTR   Interupted by signal, try again.
231  *     EINVAL  This is not a valid arg.
232  *     EMFILE  Too many file descriptors used by process.
233  *     ENOLCK  Problem getting a lock.
234  *     EPERM   Not allowed to do that.
235  *   fsync
236  *     EBADF   This is not an fd that is open for writing.
237  *     EINVAL, EROFS  This is not an fd that can be fsynced.
238  *     EIO     I/O error.
239  *
240  * How to use it -
241  *    int ok = 0;
242  *    int result;
243  *
244  *    E_IF_NO_ERRNO(result, foo(bar), ok)
245  *      {
246  *         E_IF_NO_ERRNO_NOLOOP(result, foo(bar), ok)
247  *            {
248  *            }
249  *      }
250  *
251  *   if (!ok)
252  *     {
253  *        // Something failed, cleanup.
254  *     }
255  */
256       switch (saved_errno)
257       {
258        case EACCES:
259        case EAGAIN:
260        case EINTR:
261          { /* Not now, try later. */
262             ERR("*** Must try again in %s @%u.", file, line);
263             result = -1;
264             break;
265          }
266
267        case EMFILE:
268        case ENFILE:
269        case ENOLCK:
270          { /* Low on resources. */
271             ERR("*** Low on resources in %s @%u.", file,
272                 line);
273             result = 0;
274             break;
275          }
276
277        case EIO:
278          { /* I/O error. */
279             ERR("*** I/O error in %s @%u.", file, line);
280             result = 0;
281             break;
282          }
283
284        case EFAULT:
285        case EBADF:
286        case EINVAL:
287        case EROFS:
288        case EISDIR:
289        case EDEADLK:
290        case EPERM:
291        case EBUSY:
292          { /* Programmer fucked up. */
293             ERR("*** NAUGHTY PROGRAMMER!!!\n"
294                 "*** SPANK SPANK SPANK!!!\n"
295                 "*** Now go fix your code in %s @%u. Tut tut tut!",
296                 file, line);
297             result = 0;
298             break;
299          }
300
301        default:
302          { /* Unsupported errno code, please add this one. */
303             ERR("*** NAUGHTY PROGRAMMER!!!\n"
304                 "*** SPANK SPANK SPANK!!!\n"
305                 "*** Unsupported errno code %d, please add this one.\n"
306                 "*** Now go fix your code in %s @%u, from %s @%u. Tut tut tut!",
307                 saved_errno, __FILE__, __LINE__, file, line);
308             result = 0;
309             break;
310          }
311       }
312    }
313    else /* Everything is fine. */
314      result = 1;
315
316    errno = saved_errno;
317    return result;
318 }
319
320 /**
321  * @addtogroup Ecore_Exe_Group
322  *
323  * @{
324  */
325
326 static int run_pri = ECORE_EXE_PRIORITY_INHERIT;
327
328 /**
329  * Sets the priority at which to launch processes
330  *
331  * This sets the priority of processes run by ecore_exe_run() and
332  * ecore_exe_pipe_run().
333  * @li On Windows, the child process is created by default with the
334  * @ref ECORE_EXE_WIN32_PRIORITY_NORMAL priority, unless the calling
335  * process is in @ref ECORE_EXE_WIN32_PRIORITY_IDLE or
336  * @ref ECORE_EXE_WIN32_PRIORITY_BELOW_NORMAL priority. In that case, the
337  * child process inherits this priority.
338  * @li On other platforms, if set to @ref ECORE_EXE_PRIORITY_INHERIT child
339  * processes inherits the priority of their parent. This is the default.
340  *
341  * @param   pri value a Ecore_Exe_Win32_Priority value on Windows, -20
342  * to 19 or @ref ECORE_EXE_PRIORITY_INHERIT on other OS.
343  */
344 EAPI void
345 ecore_exe_run_priority_set(int pri)
346 {
347    EINA_MAIN_LOOP_CHECK_RETURN;
348    run_pri = pri;
349 }
350
351 /**
352  * Gets the priority at which to launch processes
353  *
354  * This gets ths priority of launched processes. See
355  * ecore_exe_run_priority_set() for details. This just returns the value set
356  * by this call.
357  *
358  * @return the value set by ecore_exe_run_priority_set()
359  */
360 EAPI int
361 ecore_exe_run_priority_get(void)
362 {
363    EINA_MAIN_LOOP_CHECK_RETURN_VAL(0);
364    return run_pri;
365 }
366
367 /**
368  * Spawns a child process.
369  *
370  * This is now just a thin wrapper around ecore_exe_pipe_run()
371  * @note When you use this function you will have no permissions
372  * to write or read on the pipe that connects you with the spwaned process.
373  * If you need to do that use ecore_exe_pipe_run() with the
374  * appropriated flags.
375  *
376  * @param   exe_cmd The command to run with @c /bin/sh.
377  * @param   data    Data to attach to the returned process handle.
378  * @return  A process handle to the spawned process.
379  */
380 EAPI Ecore_Exe *
381 ecore_exe_run(const char *exe_cmd,
382               const void *data)
383 {
384    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
385    return ecore_exe_pipe_run(exe_cmd, 0, data);
386 }
387
388 /**
389  * Spawns a child process with its stdin/out available for communication.
390  *
391  * This function forks and runs the given command using @c /bin/sh.
392  *
393  * Note that the process handle is only valid until a child process
394  * terminated event is received.  After all handlers for the child process
395  * terminated event have been called, the handle will be freed by Ecore.
396  *
397  * This function does the same thing as ecore_exe_run(), but also makes the
398  * standard in and/or out as well as stderr from the child process available
399  * for reading or writing.  To write use ecore_exe_send().  To read listen to
400  * ECORE_EXE_EVENT_DATA or ECORE_EXE_EVENT_ERROR events (set up handlers).
401  * Ecore may buffer read and error data until a newline character if asked
402  * for with the @p flags.  All data will be included in the events (newlines
403  * will be replaced with NULLS if line buffered).  ECORE_EXE_EVENT_DATA events
404  * will only happen if the process is run with ECORE_EXE_PIPE_READ enabled
405  * in the flags.  The same with the error version.  Writing will only be
406  * allowed with ECORE_EXE_PIPE_WRITE enabled in the flags.
407  *
408  * @param   exe_cmd The command to run with @c /bin/sh.
409  * @param   flags   The flag parameters for how to deal with inter-process I/O
410  * @param   data    Data to attach to the returned process handle.
411  * @return  A process handle to the spawned process.
412  */
413 EAPI Ecore_Exe *
414 ecore_exe_pipe_run(const char     *exe_cmd,
415                    Ecore_Exe_Flags flags,
416                    const void     *data)
417 {
418    Ecore_Exe *exe = NULL;
419    int statusPipe[2] = { -1, -1 };
420    int errorPipe[2] = { -1, -1 };
421    int readPipe[2] = { -1, -1 };
422    int writePipe[2] = { -1, -1 };
423    int n = 0;
424    int ok = 1;
425    int result;
426
427    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
428    if (!exe_cmd) return NULL;
429    exe = calloc(1, sizeof(Ecore_Exe));
430    if (!exe) return NULL;
431
432    if ((flags & ECORE_EXE_PIPE_AUTO) && (!(flags & ECORE_EXE_PIPE_ERROR))
433        && (!(flags & ECORE_EXE_PIPE_READ)))
434      /* We need something to auto pipe. */
435      flags |= ECORE_EXE_PIPE_READ | ECORE_EXE_PIPE_ERROR;
436
437    exe->child_fd_error = -1;
438    exe->child_fd_read = -1;
439    exe->child_fd_write = -1;
440    exe->child_fd_error_x = -1;
441    exe->child_fd_read_x = -1;
442    exe->child_fd_write_x = -1;
443
444    /*  Create some pipes. */
445    if (ok)
446    {
447       E_IF_NO_ERRNO_NOLOOP(result, pipe(statusPipe), ok)
448       {
449       }
450    }
451    if (ok && (flags & ECORE_EXE_PIPE_ERROR))
452    {
453       E_IF_NO_ERRNO_NOLOOP(result, pipe(errorPipe), ok)
454       {
455          exe->child_fd_error = errorPipe[0];
456          exe->child_fd_error_x = errorPipe[1];
457       }
458    }
459    if (ok && (flags & ECORE_EXE_PIPE_READ))
460    {
461       E_IF_NO_ERRNO_NOLOOP(result, pipe(readPipe), ok)
462       {
463          exe->child_fd_read = readPipe[0];
464          exe->child_fd_read_x = readPipe[1];
465       }
466    }
467    if (ok && (flags & ECORE_EXE_PIPE_WRITE))
468    {
469       E_IF_NO_ERRNO_NOLOOP(result, pipe(writePipe), ok)
470       {
471          exe->child_fd_write = writePipe[1];
472          exe->child_fd_write_x = writePipe[0];
473       }
474    }
475    if (ok)
476    {
477       pid_t pid = 0;
478       volatile int vfork_exec_errno = 0;
479
480       /* FIXME: I should double check this.  After a quick look around, this is already done, but via a more modern method. */
481       /* signal(SIGPIPE, SIG_IGN);    We only want EPIPE on errors */
482       pid = fork();
483
484       if (pid == -1)
485       {
486          ERR("Failed to fork process");
487          pid = 0;
488       }
489       else if (pid == 0) /* child */
490       {
491          if (run_pri != ECORE_EXE_PRIORITY_INHERIT)
492          {
493             if ((run_pri >= -20) && (run_pri <= 19))
494               setpriority(PRIO_PROCESS, 0, run_pri);
495          }
496          /* dup2 STDERR, STDIN, and STDOUT.  dup2() allegedly closes the
497           * second pipe if it's open. On the other hand, there was the
498           * Great FD Leak Scare of '06, so let's be paranoid. */
499          if (ok && (flags & ECORE_EXE_PIPE_ERROR))
500          {
501             E_NO_ERRNO(result, close(STDERR_FILENO), ok);
502             E_NO_ERRNO(result, dup2(errorPipe[1], STDERR_FILENO), ok);
503          }
504          if (ok && (flags & ECORE_EXE_PIPE_READ))
505          {
506             E_NO_ERRNO(result, close(STDOUT_FILENO), ok);
507             E_NO_ERRNO(result, dup2(readPipe[1], STDOUT_FILENO), ok);
508          }
509          if (ok && (flags & ECORE_EXE_PIPE_WRITE))
510          {
511             E_NO_ERRNO(result, close(STDIN_FILENO), ok);
512             E_NO_ERRNO(result, dup2(writePipe[0], STDIN_FILENO), ok);
513          }
514
515          if (ok)
516          {
517             /* Setup the status pipe. */
518              E_NO_ERRNO(result, close(statusPipe[0]), ok);
519              E_IF_NO_ERRNO(result, fcntl(statusPipe[1], F_SETFD, FD_CLOEXEC), ok) /* close on exec shows success */
520              {
521                 /* Run the actual command. */
522                  _ecore_exe_exec_it(exe_cmd, flags); /* no return */
523              }
524          }
525
526          /* Something went 'orribly wrong. */
527          vfork_exec_errno = errno;
528
529          /* Close the pipes. */
530          if (flags & ECORE_EXE_PIPE_ERROR)
531            E_NO_ERRNO(result, close(errorPipe[1]), ok);
532          if (flags & ECORE_EXE_PIPE_READ)
533            E_NO_ERRNO(result, close(readPipe[1]), ok);
534          if (flags & ECORE_EXE_PIPE_WRITE)
535            E_NO_ERRNO(result, close(writePipe[0]), ok);
536          E_NO_ERRNO(result, close(statusPipe[1]), ok);
537
538          _exit(-1);
539       }
540       else   /* parent */
541       {
542          /* Close the unused pipes. */
543           E_NO_ERRNO(result, close(statusPipe[1]), ok);
544
545           /* FIXME: after having a good look at the current e fd
546            * handling, investigate fcntl(dataPipe[x], F_SETSIG, ...) */
547           /* FIXME: above F_SETSIG etc. - this is async SIGIO based IO
548            * which is also linux specific so we probably don't want to
549            * do this as long as select() is working fine. the only time
550            * we really want to think of SIGIO async IO is when it all
551            * actually works basically everywhere and we can turn all
552            * IO into DMA async activities (i.e. you do a read() then
553            * the read is complete not on return but when you get a
554            * SIGIO - the read() just starts the transfer and it is
555            * completed in the background by DMA (or whatever mechanism
556            * the kernel choses)) */
557
558           /* Wait for it to start executing. */
559           /* FIXME: this doesn't seem very nice - we sit and block
560            * waiting on a child process... even though it's just
561            * the segment between the fork() and the exec) it just feels
562            * wrong */
563           for (;; )
564           {
565              char buf;
566
567              E_NO_ERRNO(result, read(statusPipe[0], &buf, 1), ok);
568              if (result == 0)
569              {
570                 if (vfork_exec_errno != 0)
571                 {
572                    n = vfork_exec_errno;
573                    ERR("Could not start \"%s\"", exe_cmd);
574                    pid = 0;
575                 }
576                 break;
577              }
578           }
579
580           /* Close the status pipe. */
581           E_NO_ERRNO(result, close(statusPipe[0]), ok);
582       }
583
584       if (pid)
585       {
586          /* Setup the exe structure. */
587           ECORE_MAGIC_SET(exe, ECORE_MAGIC_EXE);
588           exe->start_bytes = -1;
589           exe->end_bytes = -1;
590           exe->start_lines = -1;
591           exe->end_lines = -1;
592           exe->pid = pid;
593           exe->flags = flags;
594           exe->data = (void *)data;
595           if ((exe->cmd = strdup(exe_cmd)))
596           {
597              if (flags & ECORE_EXE_PIPE_ERROR) /* Setup the error stuff. */
598              {
599                 E_IF_NO_ERRNO(result,
600                               fcntl(exe->child_fd_error, F_SETFL,
601                                     O_NONBLOCK), ok) {
602                 }
603                 E_IF_NO_ERRNO(result,
604                               fcntl(exe->child_fd_error, F_SETFD,
605                                     FD_CLOEXEC), ok) {
606                 }
607                 E_IF_NO_ERRNO(result,
608                               fcntl(exe->child_fd_error_x, F_SETFD,
609                                     FD_CLOEXEC), ok) {
610                 }
611                 {
612                    exe->error_fd_handler =
613                      ecore_main_fd_handler_add(exe->child_fd_error,
614                                                ECORE_FD_READ,
615                                                _ecore_exe_data_error_handler,
616                                                exe, NULL, NULL);
617                    if (!exe->error_fd_handler)
618                      ok = 0;
619                 }
620              }
621              if (ok && (flags & ECORE_EXE_PIPE_READ)) /* Setup the read stuff. */
622              {
623                 E_IF_NO_ERRNO(result,
624                               fcntl(exe->child_fd_read, F_SETFL,
625                                     O_NONBLOCK), ok) {
626                 }
627                 E_IF_NO_ERRNO(result,
628                               fcntl(exe->child_fd_read, F_SETFD,
629                                     FD_CLOEXEC), ok) {
630                 }
631                 E_IF_NO_ERRNO(result,
632                               fcntl(exe->child_fd_read_x, F_SETFD,
633                                     FD_CLOEXEC), ok) {
634                 }
635                 {
636                    exe->read_fd_handler =
637                      ecore_main_fd_handler_add(exe->child_fd_read,
638                                                ECORE_FD_READ,
639                                                _ecore_exe_data_read_handler,
640                                                exe, NULL, NULL);
641                    if (!exe->read_fd_handler)
642                      ok = 0;
643                 }
644              }
645              if (ok && (flags & ECORE_EXE_PIPE_WRITE)) /* Setup the write stuff. */
646              {
647                 E_IF_NO_ERRNO(result,
648                               fcntl(exe->child_fd_write, F_SETFL,
649                                     O_NONBLOCK), ok) {
650                 }
651                 E_IF_NO_ERRNO(result,
652                               fcntl(exe->child_fd_write, F_SETFD,
653                                     FD_CLOEXEC), ok) {
654                 }
655                 E_IF_NO_ERRNO(result,
656                               fcntl(exe->child_fd_write_x, F_SETFD,
657                                     FD_CLOEXEC), ok) {
658                 }
659                 {
660                    exe->write_fd_handler =
661                      ecore_main_fd_handler_add(exe->child_fd_write,
662                                                ECORE_FD_WRITE,
663                                                _ecore_exe_data_write_handler,
664                                                exe, NULL, NULL);
665                    if (exe->write_fd_handler)
666                      ecore_main_fd_handler_active_set(exe->write_fd_handler, 0);  /* Nothing to write to start with. */
667                    else
668                      ok = 0;
669                 }
670              }
671
672              exes = (Ecore_Exe *)eina_inlist_append(EINA_INLIST_GET(exes), EINA_INLIST_GET(exe));
673              n = 0;
674           }
675           else
676             ok = 0;
677       }
678       else
679         ok = 0;
680    }
681
682    if (!ok) /* Something went wrong, so pull down everything. */
683    {
684       if (exe->pid) ecore_exe_terminate(exe);
685       IF_FN_DEL(ecore_exe_free, exe);
686    }
687    else
688    {
689       Ecore_Exe_Event_Add *e;
690
691       e = _ecore_exe_event_add_new();
692       e->exe = exe;
693       if (e) /* Send the event. */
694         ecore_event_add(ECORE_EXE_EVENT_ADD, e,
695                         _ecore_exe_event_add_free, NULL);
696       /* INF("Running as %d for %s.\n", exe->pid, exe->cmd); */
697    }
698
699    errno = n;
700    return exe;
701 }
702
703 /**
704  * Defines a function to be called before really freeing the handle data.
705  *
706  * This might be useful for language bindings such as Python and Perl
707  * that need to deallocate wrappers associated with this handle.
708  *
709  * This handle should never be modified by this call. It should be
710  * considered informative only. All getters are valid when the given
711  * function is called back.
712  *
713  * @param exe The child process to attach the pre_free function.
714  * @param func The function to call before @a exe is freed.
715  */
716 EAPI void
717 ecore_exe_callback_pre_free_set(Ecore_Exe   *exe,
718                                 Ecore_Exe_Cb func)
719 {
720    EINA_MAIN_LOOP_CHECK_RETURN;
721    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
722    {
723       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE,
724                        "ecore_exe_callback_pre_free_set");
725       return;
726    }
727    exe->pre_free_cb = func;
728 }
729
730 /**
731  * Sends data to the given child process which it receives on stdin.
732  *
733  * This function writes to a child processes standard in, with unlimited
734  * buffering. This call will never block. It may fail if the system runs out
735  * of memory.
736  *
737  * @param exe  The child process to send to
738  * @param data The data to send
739  * @param size The size of the data to send, in bytes
740  * @return @c EINA_TRUE if successful, @c EINA_FALSE on failure.
741  */
742 EAPI Eina_Bool
743 ecore_exe_send(Ecore_Exe  *exe,
744                const void *data,
745                int         size)
746 {
747    void *buf;
748
749    EINA_MAIN_LOOP_CHECK_RETURN_VAL(EINA_FALSE);
750    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
751    {
752       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_send");
753       return EINA_FALSE;
754    }
755
756    if (exe->close_stdin)
757    {
758       ERR("Ecore_Exe %p stdin is closed! Cannot send %d bytes from %p",
759           exe, size, data);
760       return EINA_FALSE;
761    }
762
763    if (exe->child_fd_write == -1)
764    {
765       ERR("Ecore_Exe %p created without ECORE_EXE_PIPE_WRITE! "
766           "Cannot send %d bytes from %p", exe, size, data);
767       return EINA_FALSE;
768    }
769
770    buf = realloc(exe->write_data_buf, exe->write_data_size + size);
771    if (!buf) return EINA_FALSE;
772
773    exe->write_data_buf = buf;
774    memcpy((char *)exe->write_data_buf + exe->write_data_size, data, size);
775    exe->write_data_size += size;
776
777    if (exe->write_fd_handler)
778      ecore_main_fd_handler_active_set(exe->write_fd_handler, ECORE_FD_WRITE);
779
780    return EINA_TRUE;
781 }
782
783 /**
784  * The stdin of the given child process will close when the write buffer is empty.
785  *
786  * @param exe  The child process
787  */
788 EAPI void
789 ecore_exe_close_stdin(Ecore_Exe *exe)
790 {
791    EINA_MAIN_LOOP_CHECK_RETURN;
792    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
793    {
794       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_close_stdin");
795       return;
796    }
797    exe->close_stdin = 1;
798 }
799
800 /**
801  * Sets the auto pipe limits for the given process handle. On Windows
802  * this function does nothing.
803  *
804  * @param   exe The given process handle.
805  * @param   start_bytes limit of bytes at start of output to buffer.
806  * @param   end_bytes limit of bytes at end of output to buffer.
807  * @param   start_lines limit of lines at start of output to buffer.
808  * @param   end_lines limit of lines at end of output to buffer.
809  */
810 EAPI void
811 ecore_exe_auto_limits_set(Ecore_Exe *exe,
812                           int        start_bytes,
813                           int        end_bytes,
814                           int        start_lines,
815                           int        end_lines)
816 {
817    EINA_MAIN_LOOP_CHECK_RETURN;
818    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
819    {
820       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_auto_limits_set");
821       return;
822    }
823    /* FIXME: sanitize the input. */
824    exe->start_bytes = start_bytes;
825    exe->end_bytes = end_bytes;
826    exe->start_lines = start_lines;
827    exe->end_lines = end_lines;
828
829    /* FIXME: get this can of worms working.
830     *
831     * capture stderr & stdout internally
832     *
833     * raster and onefang keep moving the goal posts on this one.  It started out as
834     * "show users the error output if an exe fails" and is rapidly approaching
835     * "alternative method of getting the data, poll vs event driven".  Some serious
836     * thinking needs to be applied to this.  Do we really want to go that far?  If
837     * so, we should change the names.  The basic design will probably remain the
838     * same which ever way we go.  The constant goal post moving is probably due to
839     * generic design methods leading to feature creep as we inspired each other to
840     * more generic designs.  It does seem like the closer we get to poll driven,
841     * the more issues and corner cases there are.
842     *
843     * Instead of doing the usual register an event handler thing, we are ecore_exe,
844     * we can take some short cuts.  Don't send the events, just leave the exe buffers
845     * as is until the user asks for them, then return the event.
846     *
847     * start = 0,  end = 0;   clogged arteries get flushed, everything is ignored.
848     * start = -1, end = -1;  clogged arteries get transferred to internal buffers.  Actually, either == -1 means buffer everything.
849     * start = X,  end = 0;   buffer first X out of clogged arteries, flush and ignore rest.
850     * start = 0,  end = X;   circular buffer X
851     * start = X,  end = Y;   buffer first X out of clogged arteries, circular buffer Y from beginning.
852     *
853     * bytes vs lines, which ever one reaches the limit first.
854     * Before we go beyond the start+end limit, leave the end buffer empty, and store both in the start buffer, coz they overlap.
855     * After we pass the the start+end limit, insert "\n...\n" at the end of the start buffer, copy the rest to the end buffer, then store in the end buffer.
856     *
857     * Other issues -
858     * Spank programmer for polling data if polling is not turned on.
859     * Spank programmer for setting up event callbacks if polling is turned on.
860     * Spank programmer for freeing the event data if it came from the event system, as that autofrees.
861     * Spank the programmer if they try to set the limits bigger than what has been gathered & ignored already, coz they just lost data.
862     * Spank onefang and raster for opening this can of worms.
863     * Should we have separate out/err limits?
864     * Should we remove from the internal buffer the data that was delivered already?
865     * If so, what to do about limits, start, and end?  They could loose their meaning.
866     */
867 }
868
869 /**
870  * Gets the auto pipe data for the given process handle
871  *
872  * @param   exe The given process handle.
873  * @param   flags   Is this a ECORE_EXE_PIPE_READ or ECORE_EXE_PIPE_ERROR?
874  * @return The event data.
875  */
876 EAPI Ecore_Exe_Event_Data *
877 ecore_exe_event_data_get(Ecore_Exe      *exe,
878                          Ecore_Exe_Flags flags)
879 {
880    Ecore_Exe_Event_Data *e = NULL;
881    int is_buffered = 0;
882    unsigned char *inbuf;
883    int inbuf_num;
884
885    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
886    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
887    {
888       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_event_data_get");
889       return NULL;
890    }
891
892    /* Sort out what sort of event we are. */
893    if (flags & ECORE_EXE_PIPE_READ)
894    {
895       flags = ECORE_EXE_PIPE_READ;
896       if (exe->flags & ECORE_EXE_PIPE_READ_LINE_BUFFERED)
897         is_buffered = 1;
898    }
899    else
900    {
901       flags = ECORE_EXE_PIPE_ERROR;
902       if (exe->flags & ECORE_EXE_PIPE_ERROR_LINE_BUFFERED)
903         is_buffered = 1;
904    }
905
906    /* Get the data. */
907    if (flags & ECORE_EXE_PIPE_READ)
908    {
909       inbuf = exe->read_data_buf;
910       inbuf_num = exe->read_data_size;
911       exe->read_data_buf = NULL;
912       exe->read_data_size = 0;
913    }
914    else
915    {
916       inbuf = exe->error_data_buf;
917       inbuf_num = exe->error_data_size;
918       exe->error_data_buf = NULL;
919       exe->error_data_size = 0;
920    }
921
922    e = calloc(1, sizeof(Ecore_Exe_Event_Data));
923    if (e)
924    {
925       e->exe = exe;
926       e->data = inbuf;
927       e->size = inbuf_num;
928
929       if (is_buffered) /* Deal with line buffering. */
930       {
931          int max = 0;
932          int count = 0;
933          int i;
934          int last = 0;
935          char *c;
936
937          c = (char *)inbuf;
938          for (i = 0; i < inbuf_num; i++) /* Find the lines. */
939          {
940             if (inbuf[i] == '\n')
941             {
942                if (count >= max)
943                {
944                   /* In testing, the lines seem to arrive in batches of 500 to 1000 lines at most, roughly speaking. */
945                    max += 10; /* FIXME: Maybe keep track of the largest number of lines ever sent, and add half that many instead of 10. */
946                    e->lines = realloc(e->lines, sizeof(Ecore_Exe_Event_Data_Line) * (max + 1)); /* Allow room for the NULL termination. */
947                }
948                /* raster said to leave the line endings as line endings, however -
949                 * This is line buffered mode, we are not dealing with binary here, but lines.
950                 * If we are not dealing with binary, we must be dealing with ASCII, unicode, or some other text format.
951                 * Thus the user is most likely gonna deal with this text as strings.
952                 * Thus the user is most likely gonna pass this data to str functions.
953                 * rasters way - the endings are always gonna be '\n';  onefangs way - they will always be '\0'
954                 * We are handing them the string length as a convenience.
955                 * Thus if they really want it in raw format, they can e->lines[i].line[e->lines[i].size - 1] = '\n'; easily enough.
956                 * In the default case, we can do this conversion quicker than the user can, as we already have the index and pointer.
957                 * Let's make it easy on them to use these as standard C strings.
958                 *
959                 * onefang is proud to announce that he has just set a new personal record for the
960                 * most over documentation of a simple assignment statement.  B-)
961                 */
962                inbuf[i] = '\0';
963                e->lines[count].line = c;
964                e->lines[count].size = i - last;
965                last = i + 1;
966                c = (char *)&inbuf[last];
967                count++;
968             }
969          }
970          if (i > last) /* Partial line left over, save it for next time. */
971          {
972             if (count != 0) e->size = last;
973             if (flags & ECORE_EXE_PIPE_READ)
974             {
975                exe->read_data_size = i - last;
976                exe->read_data_buf = malloc(exe->read_data_size);
977                memcpy(exe->read_data_buf, c, exe->read_data_size);
978             }
979             else
980             {
981                exe->error_data_size = i - last;
982                exe->error_data_buf = malloc(exe->error_data_size);
983                memcpy(exe->error_data_buf, c, exe->error_data_size);
984             }
985          }
986          if (count == 0) /* No lines to send, cancel the event. */
987          {
988             _ecore_exe_event_exe_data_free(NULL, e);
989             e = NULL;
990          }
991          else /* NULL terminate the array, so that people know where the end is. */
992          {
993             e->lines[count].line = NULL;
994             e->lines[count].size = 0;
995          }
996       }
997    }
998
999    return e;
1000 }
1001
1002 /**
1003  * Sets the string tag for the given process handle
1004  *
1005  * @param   exe The given process handle.
1006  * @param   tag The string tag to set on the process handle.
1007  */
1008 EAPI void
1009 ecore_exe_tag_set(Ecore_Exe  *exe,
1010                   const char *tag)
1011 {
1012    EINA_MAIN_LOOP_CHECK_RETURN;
1013    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1014    {
1015       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_tag_set");
1016       return;
1017    }
1018    IF_FREE(exe->tag);
1019    if (tag)
1020      exe->tag = strdup(tag);
1021    else
1022      exe->tag = NULL;
1023 }
1024
1025 /**
1026  * Retrieves the tag attached to the given process handle. There is no need to
1027  * free it as it just returns the internal pointer value. This value is only
1028  * valid as long as the @p exe is valid or until the tag is set to something
1029  * else on this @p exe.
1030  *
1031  * @param   exe The given process handle.
1032  * @return The string attached to @p exe. It is a handle to existing
1033  *         internal string and should not be modified, use
1034  *         ecore_exe_tag_set() to change it. It might be @c NULL.
1035  */
1036 EAPI const char *
1037 ecore_exe_tag_get(const Ecore_Exe *exe)
1038 {
1039    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
1040    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1041    {
1042       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_tag_get");
1043       return NULL;
1044    }
1045    return exe->tag;
1046 }
1047
1048 /**
1049  * Frees the given process handle.
1050  *
1051  * Note that the process that the handle represents is unaffected by this
1052  * function.
1053  *
1054  * @param   exe The given process handle.
1055  * @return  The data attached to the handle when @ref ecore_exe_run was
1056  *          called.
1057  */
1058 EAPI void *
1059 ecore_exe_free(Ecore_Exe *exe)
1060 {
1061    void *data;
1062    int ok = 0;
1063    int result;
1064
1065    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
1066    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1067    {
1068       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_free");
1069       return NULL;
1070    }
1071
1072    data = exe->data;
1073
1074    if (exe->pre_free_cb)
1075      exe->pre_free_cb(data, exe);
1076
1077    if (exe->doomsday_clock)
1078    {
1079       struct _ecore_exe_dead_exe *dead;
1080
1081       ecore_timer_del(exe->doomsday_clock);
1082       exe->doomsday_clock = NULL;
1083       dead = exe->doomsday_clock_dead;
1084       if (dead)
1085       {
1086          IF_FREE(dead->cmd);
1087          free(dead);
1088          exe->doomsday_clock_dead = NULL;
1089       }
1090    }
1091    IF_FN_DEL(ecore_main_fd_handler_del, exe->write_fd_handler);
1092    IF_FN_DEL(ecore_main_fd_handler_del, exe->read_fd_handler);
1093    IF_FN_DEL(ecore_main_fd_handler_del, exe->error_fd_handler);
1094    if (exe->child_fd_write_x != -1)
1095      E_NO_ERRNO(result, close(exe->child_fd_write_x), ok);
1096    if (exe->child_fd_read_x != -1)
1097      E_NO_ERRNO(result, close(exe->child_fd_read_x), ok);
1098    if (exe->child_fd_error_x != -1)
1099      E_NO_ERRNO(result, close(exe->child_fd_error_x), ok);
1100    if (exe->child_fd_write != -1)
1101      E_NO_ERRNO(result, close(exe->child_fd_write), ok);
1102    if (exe->child_fd_read != -1)
1103      E_NO_ERRNO(result, close(exe->child_fd_read), ok);
1104    if (exe->child_fd_error != -1)
1105      E_NO_ERRNO(result, close(exe->child_fd_error), ok);
1106    IF_FREE(exe->write_data_buf);
1107    IF_FREE(exe->read_data_buf);
1108    IF_FREE(exe->error_data_buf);
1109    IF_FREE(exe->cmd);
1110
1111    exes = (Ecore_Exe *)eina_inlist_remove(EINA_INLIST_GET(exes), EINA_INLIST_GET(exe));
1112    ECORE_MAGIC_SET(exe, ECORE_MAGIC_NONE);
1113    IF_FREE(exe->tag);
1114    free(exe);
1115    return data;
1116 }
1117
1118 /**
1119  * Frees the given event data.
1120  *
1121  * @param   e The given event data.
1122  */
1123 EAPI void
1124 ecore_exe_event_data_free(Ecore_Exe_Event_Data *e)
1125 {
1126    if (!e) return;
1127    IF_FREE(e->lines);
1128    IF_FREE(e->data);
1129    free(e);
1130 }
1131
1132 /**
1133  * Retrieves the process ID of the given spawned process.
1134  * @param   exe Handle to the given spawned process.
1135  * @return  The process ID on success.  @c -1 otherwise.
1136  */
1137 EAPI pid_t
1138 ecore_exe_pid_get(const Ecore_Exe *exe)
1139 {
1140    EINA_MAIN_LOOP_CHECK_RETURN_VAL(0);
1141    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1142    {
1143       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_pid_get");
1144       return -1;
1145    }
1146    return exe->pid;
1147 }
1148
1149 /**
1150  * Retrieves the command of the given spawned process.
1151  * @param   exe Handle to the given spawned process.
1152  * @return The command on success, @c NULL otherwise. This string is the
1153  *         pointer to the internal value and must not be modified in
1154  *         any way.
1155  */
1156 EAPI const char *
1157 ecore_exe_cmd_get(const Ecore_Exe *exe)
1158 {
1159    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
1160    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1161    {
1162       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_cmd_get");
1163       return NULL;
1164    }
1165    return exe->cmd;
1166 }
1167
1168 /**
1169  * Retrieves the data attached to the given process handle.
1170  * @param   exe The given process handle.
1171  * @return The data pointer attached to @p exe Given to
1172  *         ecore_exe_run() or ecore_exe_pipe_run()
1173  */
1174 EAPI void *
1175 ecore_exe_data_get(const Ecore_Exe *exe)
1176 {
1177    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
1178    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1179    {
1180       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_data_get");
1181       return NULL;
1182    }
1183    return exe->data;
1184 }
1185
1186 /**
1187  * Sets the data attached to the given process handle.
1188  * @param   exe The given process handle.
1189  * @param   data The pointer to attach
1190  * @return The data pointer previously attached to @p exe with
1191  *         ecore_exe_run(), ecore_exe_pipe_run(), or ecore_exe_data_set()
1192  * @since 1.1
1193  */
1194 EAPI void *
1195 ecore_exe_data_set(Ecore_Exe *exe,
1196                    void      *data)
1197 {
1198    void *ret;
1199    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
1200    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1201    {
1202       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, __func__);
1203       return NULL;
1204    }
1205    ret = exe->data;
1206    exe->data = data;
1207    return ret;
1208 }
1209
1210 /**
1211  * Retrieves the flags attached to the given process handle.
1212  * @param   exe The given process handle.
1213  * @return  The flags attached to @p exe.
1214  */
1215 EAPI Ecore_Exe_Flags
1216 ecore_exe_flags_get(const Ecore_Exe *exe)
1217 {
1218    EINA_MAIN_LOOP_CHECK_RETURN_VAL(0);
1219    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1220    {
1221       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_data_get");
1222       return 0;
1223    }
1224    return exe->flags;
1225 }
1226
1227 /**
1228  * Pauses the given process by sending it a @c SIGSTOP signal.
1229  * @param   exe Process handle to the given process.
1230  */
1231 EAPI void
1232 ecore_exe_pause(Ecore_Exe *exe)
1233 {
1234    EINA_MAIN_LOOP_CHECK_RETURN;
1235    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1236    {
1237       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_pause");
1238       return;
1239    }
1240    kill(exe->pid, SIGSTOP);
1241 }
1242
1243 /**
1244  * Continues the given paused process by sending it a @c SIGCONT signal.
1245  * @param   exe Process handle to the given process.
1246  */
1247 EAPI void
1248 ecore_exe_continue(Ecore_Exe *exe)
1249 {
1250    EINA_MAIN_LOOP_CHECK_RETURN;
1251    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1252    {
1253       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_continue");
1254       return;
1255    }
1256    kill(exe->pid, SIGCONT);
1257 }
1258
1259 /**
1260  * Sends the given spawned process a interrupt (@c SIGINT) signal.
1261  * @param   exe Process handle to the given process.
1262  */
1263 EAPI void
1264 ecore_exe_interrupt(Ecore_Exe *exe)
1265 {
1266    EINA_MAIN_LOOP_CHECK_RETURN;
1267    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1268    {
1269       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_interrupt");
1270       return;
1271    }
1272    _ecore_exe_dead_attach(exe);
1273    kill(exe->pid, SIGINT);
1274 }
1275
1276 /**
1277  * Sends the given spawned process a quit (@c SIGQUIT) signal.
1278  * @param   exe Process handle to the given process.
1279  */
1280 EAPI void
1281 ecore_exe_quit(Ecore_Exe *exe)
1282 {
1283    EINA_MAIN_LOOP_CHECK_RETURN;
1284    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1285    {
1286       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_quit");
1287       return;
1288    }
1289    _ecore_exe_dead_attach(exe);
1290    kill(exe->pid, SIGQUIT);
1291 }
1292
1293 /**
1294  * Sends the given spawned process a terminate (@c SIGTERM) signal.
1295  * @param   exe Process handle to the given process.
1296  */
1297 EAPI void
1298 ecore_exe_terminate(Ecore_Exe *exe)
1299 {
1300    EINA_MAIN_LOOP_CHECK_RETURN;
1301    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1302    {
1303       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_terminate");
1304       return;
1305    }
1306    _ecore_exe_dead_attach(exe);
1307    INF("Sending TERM signal to %s (%d).", exe->cmd, exe->pid);
1308    kill(exe->pid, SIGTERM);
1309 }
1310
1311 /**
1312  * Kills the given spawned process by sending it a @c SIGKILL signal.
1313  * @param   exe Process handle to the given process.
1314  */
1315 EAPI void
1316 ecore_exe_kill(Ecore_Exe *exe)
1317 {
1318    struct _ecore_exe_dead_exe *dead;
1319
1320    EINA_MAIN_LOOP_CHECK_RETURN;
1321    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1322    {
1323       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_kill");
1324       return;
1325    }
1326
1327    dead = calloc(1, sizeof(struct _ecore_exe_dead_exe));
1328    if (dead)
1329    {
1330       dead->pid = exe->pid;
1331       dead->cmd = strdup(exe->cmd);
1332       IF_FN_DEL(ecore_timer_del, exe->doomsday_clock);
1333       exe->doomsday_clock =
1334         ecore_timer_add(10.0, _ecore_exe_make_sure_its_really_dead, dead);
1335    }
1336
1337    INF("Sending KILL signal to %s (%d).", exe->cmd, exe->pid);
1338    kill(exe->pid, SIGKILL);
1339 }
1340
1341 /**
1342  * Sends a @c SIGUSR signal to the given spawned process.
1343  * @param   exe Process handle to the given process.
1344  * @param   num The number user signal to send.  Must be either 1 or 2, or
1345  *              the signal will be ignored.
1346  */
1347 EAPI void
1348 ecore_exe_signal(Ecore_Exe *exe,
1349                  int        num)
1350 {
1351    EINA_MAIN_LOOP_CHECK_RETURN;
1352    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1353    {
1354       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_signal");
1355       return;
1356    }
1357    if (num == 1)
1358      kill(exe->pid, SIGUSR1);
1359    else if (num == 2)
1360      kill(exe->pid, SIGUSR2);
1361 }
1362
1363 /**
1364  * Sends a @c SIGHUP signal to the given spawned process.
1365  * @param   exe Process handle to the given process.
1366  */
1367 EAPI void
1368 ecore_exe_hup(Ecore_Exe *exe)
1369 {
1370    EINA_MAIN_LOOP_CHECK_RETURN;
1371    if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1372    {
1373       ECORE_MAGIC_FAIL(exe, ECORE_MAGIC_EXE, "ecore_exe_hup");
1374       return;
1375    }
1376    kill(exe->pid, SIGHUP);
1377 }
1378
1379 /**
1380  * @}
1381  */
1382
1383 static Ecore_Exe *
1384 _ecore_exe_is_it_alive(pid_t pid)
1385 {
1386    Ecore_Exe *exe = NULL;
1387
1388    /* FIXME: There is no nice, safe, OS independent way to tell if a
1389     * particular PID is still alive.  I have written code to do so
1390     * for my urunlevel busybox applet (http://urunlevel.sourceforge.net/),
1391     * but it's for linux only, and still not guaranteed.
1392     *
1393     * So for now, we just check that a valid Ecore_Exe structure
1394     * exists for it.  Even that is not a guarantee, as the structure
1395     * can be freed without killing the process.
1396     *
1397     * I think we can safely put exe's into two categories, those users
1398     * that care about the life of the exe, and the run and forget type.
1399     * The run and forget type starts up the exe, then free's the
1400     * Ecore_Exe structure straight away.  They can never call any of
1401     * the functions that can call this, so we don't worry about them.
1402     *
1403     * Those user's that care about the life of exe's will keep the
1404     * Ecore_Exe structure around, terminate them eventually, or
1405     * register for exit events.  For these ones the assumption
1406     * that valid Ecore_Exe struct == live exe is almost valid.
1407     *
1408     * I will probably copy my urunlevel code into here someday.
1409     */
1410    exe = _ecore_exe_find(pid);
1411    if (exe)
1412    {
1413       if (!ECORE_MAGIC_CHECK(exe, ECORE_MAGIC_EXE))
1414         exe = NULL;
1415    }
1416
1417    return exe;
1418 }
1419
1420 static Eina_Bool
1421 _ecore_exe_make_sure_its_dead(void *data)
1422 {
1423    struct _ecore_exe_dead_exe *dead;
1424
1425    dead = data;
1426    if (dead)
1427    {
1428       Ecore_Exe *exe = NULL;
1429
1430       if ((exe = _ecore_exe_is_it_alive(dead->pid)))
1431       {
1432          if (dead->cmd)
1433            INF("Sending KILL signal to allegedly dead %s (%d).",
1434                dead->cmd, dead->pid);
1435          else
1436            INF("Sending KILL signal to allegedly dead PID %d.",
1437                dead->pid);
1438          exe->doomsday_clock =
1439            ecore_timer_add(10.0, _ecore_exe_make_sure_its_really_dead,
1440                            dead);
1441          kill(dead->pid, SIGKILL);
1442       }
1443       else
1444       {
1445          IF_FREE(dead->cmd);
1446          free(dead);
1447       }
1448    }
1449    return ECORE_CALLBACK_CANCEL;
1450 }
1451
1452 static Eina_Bool
1453 _ecore_exe_make_sure_its_really_dead(void *data)
1454 {
1455    struct _ecore_exe_dead_exe *dead;
1456
1457    dead = data;
1458    if (dead)
1459    {
1460       Ecore_Exe *exe = NULL;
1461
1462       if ((exe = _ecore_exe_is_it_alive(dead->pid)))
1463       {
1464          ERR("RUN!  The zombie wants to eat your brains!  And your CPU!");
1465          if (dead->cmd)
1466            INF("%s (%d) is not really dead.", dead->cmd, dead->pid);
1467          else
1468            INF("PID %d is not really dead.", dead->pid);
1469          exe->doomsday_clock = NULL;
1470       }
1471       IF_FREE(dead->cmd);
1472       free(dead);
1473    }
1474    return ECORE_CALLBACK_CANCEL;
1475 }
1476
1477 void
1478 _ecore_exe_init(void)
1479 {
1480    ECORE_EXE_EVENT_ADD = ecore_event_type_new();
1481    ECORE_EXE_EVENT_DEL = ecore_event_type_new();
1482    ECORE_EXE_EVENT_DATA = ecore_event_type_new();
1483    ECORE_EXE_EVENT_ERROR = ecore_event_type_new();
1484 }
1485
1486 void
1487 _ecore_exe_shutdown(void)
1488 {
1489    while (exes)
1490      ecore_exe_free(exes);
1491 }
1492
1493 Ecore_Exe *
1494 _ecore_exe_find(pid_t pid)
1495 {
1496    Ecore_Exe *exe;
1497
1498    EINA_INLIST_FOREACH(exes, exe)
1499    {
1500       if (exe->pid == pid)
1501         return exe;
1502    }
1503    return NULL;
1504 }
1505
1506 Ecore_Timer *
1507 _ecore_exe_doomsday_clock_get(Ecore_Exe *exe)
1508 {
1509    return exe->doomsday_clock;
1510 }
1511
1512 void
1513 _ecore_exe_doomsday_clock_set(Ecore_Exe   *exe,
1514                               Ecore_Timer *dc)
1515 {
1516    exe->doomsday_clock = dc;
1517 }
1518
1519 static inline void
1520 _ecore_exe_exec_it(const char     *exe_cmd,
1521                    Ecore_Exe_Flags flags)
1522 {
1523    char use_sh = 1;
1524    char *buf = NULL;
1525    char **args = NULL;
1526    int save_errno = 0;
1527
1528    /* So what is this doing?
1529     *
1530     * We are trying to avoid wrapping the exe call with /bin/sh -c.
1531     * We conservatively search for certain shell meta characters,
1532     * If we don't find them, we can call the exe directly.
1533     */
1534    if (!strpbrk(exe_cmd, "|&;<>()$`\\\"'*?#"))
1535    {
1536       char *token;
1537       char pre_command = 1;
1538       int num_tokens = 0;
1539
1540       if (!(buf = strdup(exe_cmd)))
1541         return;
1542
1543       token = strtok(buf, " \t\n\v");
1544       while (token)
1545       {
1546          if (token[0] == '~')
1547            break;
1548          if (pre_command)
1549          {
1550             if (token[0] == '[')
1551               break;
1552             if (strchr(token, '='))
1553               break;
1554             else
1555               pre_command = 0;
1556          }
1557          num_tokens++;
1558          token = strtok(NULL, " \t\n\v");
1559       }
1560       IF_FREE(buf);
1561       if ((!token) && (num_tokens))
1562       {
1563          int i = 0;
1564
1565          if (!(buf = strdup(exe_cmd)))
1566            return;
1567
1568          token = strtok(buf, " \t\n\v");
1569          use_sh = 0;
1570          if (!(args = (char **)calloc(num_tokens + 1, sizeof(char *))))
1571          {
1572             IF_FREE(buf);
1573             return;
1574          }
1575          for (i = 0; i < num_tokens; i++)
1576          {
1577             if (token)
1578               args[i] = token;
1579             token = strtok(NULL, " \t\n\v");
1580          }
1581          args[num_tokens] = NULL;
1582       }
1583    }
1584
1585 #ifdef HAVE_SYS_PRCTL_H
1586    if ((flags & ECORE_EXE_TERM_WITH_PARENT))
1587    {
1588       prctl(PR_SET_PDEATHSIG, SIGTERM);
1589    }
1590 #endif
1591
1592    if (!(flags & ECORE_EXE_NOT_LEADER)) setsid();
1593    if ((flags & ECORE_EXE_USE_SH))
1594    {
1595       errno = 0;
1596       execl("/bin/sh", "/bin/sh", "-c", exe_cmd, (char *)NULL);
1597    }
1598    else if (use_sh) /* We have to use a shell to run this. */
1599    {
1600       if (!shell) /* Find users preferred shell. */
1601       {
1602          shell = getenv("SHELL");
1603          if (!shell)
1604            shell = "/bin/sh";
1605       }
1606       errno = 0;
1607       execl(shell, shell, "-c", exe_cmd, (char *)NULL);
1608    }
1609    else
1610    { /* We can run this directly. */
1611       if (!args)
1612       {
1613          IF_FREE(buf);
1614          IF_FREE(args);
1615          ERR("arg[0] is NULL!");
1616          return;
1617       }
1618       errno = 0;
1619       execvp(args[0], args);
1620    }
1621
1622    save_errno = errno;
1623    IF_FREE(buf);
1624    IF_FREE(args);
1625    errno = save_errno;
1626    return;
1627 }
1628
1629 static Eina_Bool
1630 _ecore_exe_data_generic_handler(void             *data,
1631                                 Ecore_Fd_Handler *fd_handler,
1632                                 Ecore_Exe_Flags   flags)
1633 {
1634    Ecore_Exe *exe;
1635    int child_fd;
1636    int event_type;
1637
1638    exe = data;
1639
1640    /* Sort out what sort of handler we are. */
1641    if (flags & ECORE_EXE_PIPE_READ)
1642    {
1643       flags = ECORE_EXE_PIPE_READ;
1644       event_type = ECORE_EXE_EVENT_DATA;
1645       child_fd = exe->child_fd_read;
1646    }
1647    else
1648    {
1649       flags = ECORE_EXE_PIPE_ERROR;
1650       event_type = ECORE_EXE_EVENT_ERROR;
1651       child_fd = exe->child_fd_error;
1652    }
1653
1654    if ((fd_handler)
1655        && (ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_READ)))
1656    {
1657       unsigned char *inbuf;
1658       int inbuf_num;
1659
1660       /* Get any left over data from last time. */
1661       if (flags & ECORE_EXE_PIPE_READ)
1662       {
1663          inbuf = exe->read_data_buf;
1664          inbuf_num = exe->read_data_size;
1665          exe->read_data_buf = NULL;
1666          exe->read_data_size = 0;
1667       }
1668       else
1669       {
1670          inbuf = exe->error_data_buf;
1671          inbuf_num = exe->error_data_size;
1672          exe->error_data_buf = NULL;
1673          exe->error_data_size = 0;
1674       }
1675
1676       for (;; )
1677       {
1678          int num, lost_exe;
1679          char buf[READBUFSIZ];
1680
1681          lost_exe = 0;
1682          errno = 0;
1683          if ((num = read(child_fd, buf, READBUFSIZ)) < 1)
1684          {
1685             /* FIXME: SPEED/SIZE TRADE OFF - add a smaller READBUFSIZE
1686              * (currently 64k) to inbuf, use that instead of buf, and
1687              * save ourselves a memcpy(). */
1688               lost_exe = ((errno == EIO) ||
1689                           (errno == EBADF) ||
1690                           (errno == EPIPE) ||
1691                           (errno == EINVAL) || (errno == ENOSPC));
1692               if ((errno != EAGAIN) && (errno != EINTR))
1693                 perror("_ecore_exe_generic_handler() read problem ");
1694          }
1695          if (num > 0) /* data got read. */
1696          {
1697             inbuf = realloc(inbuf, inbuf_num + num);
1698             memcpy(inbuf + inbuf_num, buf, num);
1699             inbuf_num += num;
1700          }
1701          else
1702          { /* No more data to read. */
1703             if (inbuf)
1704             {
1705                Ecore_Exe_Event_Data *e;
1706
1707                /* Stash the data away for later. */
1708                if (flags & ECORE_EXE_PIPE_READ)
1709                {
1710                   exe->read_data_buf = inbuf;
1711                   exe->read_data_size = inbuf_num;
1712                }
1713                else
1714                {
1715                   exe->error_data_buf = inbuf;
1716                   exe->error_data_size = inbuf_num;
1717                }
1718
1719                if (!(exe->flags & ECORE_EXE_PIPE_AUTO))
1720                {
1721                   e = ecore_exe_event_data_get(exe, flags);
1722                   if (e) /* Send the event. */
1723                     ecore_event_add(event_type, e,
1724                                     _ecore_exe_event_exe_data_free,
1725                                     NULL);
1726                }
1727             }
1728             if (lost_exe)
1729             {
1730                if (flags & ECORE_EXE_PIPE_READ)
1731                {
1732                   if (exe->read_data_size)
1733                     INF("There are %d bytes left unsent from the dead exe %s.",
1734                         exe->read_data_size, exe->cmd);
1735                }
1736                else
1737                {
1738                   if (exe->error_data_size)
1739                     INF("There are %d bytes left unsent from the dead exe %s.",
1740                         exe->error_data_size, exe->cmd);
1741                }
1742                /* Thought about this a bit.  If the exe has actually
1743                 * died, this won't do any harm as it must have died
1744                 * recently and the pid has not had a chance to recycle.
1745                 * It is also a paranoid catchall, coz the usual ecore_signal
1746                 * mechenism should kick in.  But let's give it a good
1747                 * kick in the head anyway.
1748                 */
1749                ecore_exe_terminate(exe);
1750             }
1751             break;
1752          }
1753       }
1754    }
1755
1756    return ECORE_CALLBACK_RENEW;
1757 }
1758
1759 static Eina_Bool
1760 _ecore_exe_data_error_handler(void             *data,
1761                               Ecore_Fd_Handler *fd_handler)
1762 {
1763    return _ecore_exe_data_generic_handler(data, fd_handler,
1764                                           ECORE_EXE_PIPE_ERROR);
1765 }
1766
1767 static Eina_Bool
1768 _ecore_exe_data_read_handler(void             *data,
1769                              Ecore_Fd_Handler *fd_handler)
1770 {
1771    return _ecore_exe_data_generic_handler(data, fd_handler,
1772                                           ECORE_EXE_PIPE_READ);
1773 }
1774
1775 static Eina_Bool
1776 _ecore_exe_data_write_handler(void             *data,
1777                               Ecore_Fd_Handler *fd_handler __UNUSED__)
1778 {
1779    Ecore_Exe *exe;
1780
1781    exe = data;
1782    if ((exe->write_fd_handler) &&
1783        (ecore_main_fd_handler_active_get
1784           (exe->write_fd_handler, ECORE_FD_WRITE)))
1785      _ecore_exe_flush(exe);
1786
1787    /* If we have sent all there is to send, and we need to close the pipe, then close it. */
1788    if ((exe->close_stdin == 1)
1789        && (exe->write_data_size == exe->write_data_offset))
1790    {
1791       int ok = 0;
1792       int result;
1793
1794       INF("Closing stdin for %s", exe->cmd);
1795       /* if (exe->child_fd_write != -1)  E_NO_ERRNO(result, fsync(exe->child_fd_write), ok);   This a) doesn't work, and b) isn't needed. */
1796       IF_FN_DEL(ecore_main_fd_handler_del, exe->write_fd_handler);
1797       if (exe->child_fd_write != -1)
1798         E_NO_ERRNO(result, close(exe->child_fd_write), ok);
1799       exe->child_fd_write = -1;
1800       IF_FREE(exe->write_data_buf);
1801    }
1802
1803    return ECORE_CALLBACK_RENEW;
1804 }
1805
1806 static void
1807 _ecore_exe_flush(Ecore_Exe *exe)
1808 {
1809    int count;
1810
1811    /* check whether we need to write anything at all. */
1812    if ((exe->child_fd_write == -1) || (!exe->write_data_buf))
1813      return;
1814    if (exe->write_data_size == exe->write_data_offset)
1815      return;
1816
1817    count = write(exe->child_fd_write,
1818                  (char *)exe->write_data_buf + exe->write_data_offset,
1819                  exe->write_data_size - exe->write_data_offset);
1820    if (count < 1)
1821    {
1822       if (errno == EIO || errno == EBADF || errno == EPIPE || errno == EINVAL || errno == ENOSPC) /* we lost our exe! */
1823       {
1824          ecore_exe_terminate(exe);
1825          if (exe->write_fd_handler)
1826            ecore_main_fd_handler_active_set(exe->write_fd_handler, 0);
1827       }
1828    }
1829    else
1830    {
1831       exe->write_data_offset += count;
1832       if (exe->write_data_offset >= exe->write_data_size) /* Nothing left to write, clean up. */
1833       {
1834          exe->write_data_size = 0;
1835          exe->write_data_offset = 0;
1836          IF_FREE(exe->write_data_buf);
1837          if (exe->write_fd_handler)
1838            ecore_main_fd_handler_active_set(exe->write_fd_handler, 0);
1839       }
1840    }
1841 }
1842
1843 static void
1844 _ecore_exe_event_exe_data_free(void *data __UNUSED__,
1845                                void *ev)
1846 {
1847    Ecore_Exe_Event_Data *e;
1848
1849    e = ev;
1850    ecore_exe_event_data_free(e);
1851 }
1852
1853 static Ecore_Exe_Event_Add *
1854 _ecore_exe_event_add_new(void)
1855 {
1856    Ecore_Exe_Event_Add *e;
1857
1858    e = calloc(1, sizeof(Ecore_Exe_Event_Add));
1859    return e;
1860 }
1861
1862 static void
1863 _ecore_exe_event_add_free(void *data __UNUSED__,
1864                           void *ev)
1865 {
1866    Ecore_Exe_Event_Add *e;
1867
1868    e = ev;
1869    free(e);
1870 }
1871
1872 void *
1873 _ecore_exe_event_del_new(void)
1874 {
1875    Ecore_Exe_Event_Del *e;
1876
1877    e = calloc(1, sizeof(Ecore_Exe_Event_Del));
1878    return e;
1879 }
1880
1881 void
1882 _ecore_exe_event_del_free(void *data __UNUSED__,
1883                           void *ev)
1884 {
1885    Ecore_Exe_Event_Del *e;
1886
1887    e = ev;
1888    if (e->exe)
1889      ecore_exe_free(e->exe);
1890    free(e);
1891 }
1892
1893 static void
1894 _ecore_exe_dead_attach(Ecore_Exe *exe)
1895 {
1896    struct _ecore_exe_dead_exe *dead;
1897
1898    if (exe->doomsday_clock_dead) return;
1899    dead = calloc(1, sizeof(struct _ecore_exe_dead_exe));
1900    if (dead)
1901    {
1902       dead->pid = exe->pid;
1903       dead->cmd = strdup(exe->cmd);
1904       IF_FN_DEL(ecore_timer_del, exe->doomsday_clock);
1905       exe->doomsday_clock =
1906         ecore_timer_add(10.0, _ecore_exe_make_sure_its_dead, dead);
1907       exe->doomsday_clock_dead = dead;
1908    }
1909 }
1910