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