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