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