Tizen 2.1 base
[framework/uifw/ecore.git] / src / lib / ecore / ecore_pipe.c
1 #ifdef HAVE_CONFIG_H
2 # include <config.h>
3 #endif
4
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <errno.h>
8 #include <math.h>
9
10 #ifdef HAVE_ISFINITE
11 # define ECORE_FINITE(t)  isfinite(t)
12 #else
13 # ifdef _MSC_VER
14 #  define ECORE_FINITE(t) _finite(t)
15 # else
16 #  define ECORE_FINITE(t) finite(t)
17 # endif
18 #endif
19
20 #define FIX_HZ 1
21
22 #ifdef FIX_HZ
23 # ifndef _MSC_VER
24 #  include <sys/param.h>
25 # endif
26 # ifndef HZ
27 #  define HZ 100
28 # endif
29 #endif
30
31 #ifdef HAVE_EVIL
32 # include <Evil.h>
33 #endif
34
35 #ifdef HAVE_ESCAPE
36 # include <Escape.h>
37 #endif
38
39 #ifdef HAVE_EXOTIC
40 # include <Exotic.h>
41 #endif
42
43 #include "Ecore.h"
44 #include "ecore_private.h"
45
46 /* How of then we should retry to write to the pipe */
47 #define ECORE_PIPE_WRITE_RETRY 6
48
49 /*
50  * On Windows, pipe() is implemented with sockets.
51  * Contrary to Linux, Windows uses different functions
52  * for sockets and fd's: write() is for fd's and send
53  * is for sockets. So I need to put some win32 code
54  * here. I can't think of a solution where the win32
55  * code is in Evil and not here.
56  */
57
58 #ifdef _WIN32
59
60 # include <winsock2.h>
61
62 # define pipe_write(fd, buffer, size) send((fd), (char *)(buffer), size, 0)
63 # define pipe_read(fd, buffer, size)  recv((fd), (char *)(buffer), size, 0)
64 # define pipe_close(fd)               closesocket(fd)
65 # define PIPE_FD_INVALID INVALID_SOCKET
66 # define PIPE_FD_ERROR   SOCKET_ERROR
67
68 #else
69
70 # include <unistd.h>
71 # include <fcntl.h>
72
73 # define pipe_write(fd, buffer, size) write((fd), buffer, size)
74 # define pipe_read(fd, buffer, size)  read((fd), buffer, size)
75 # define pipe_close(fd)               close(fd)
76 # define PIPE_FD_INVALID -1
77 # define PIPE_FD_ERROR   -1
78
79 #endif /* ! _WIN32 */
80
81 #include <Ecore.h>
82 #include "ecore_private.h"
83
84 struct _Ecore_Pipe
85 {
86                      ECORE_MAGIC;
87    int               fd_read;
88    int               fd_write;
89    Ecore_Fd_Handler *fd_handler;
90    const void       *data;
91    Ecore_Pipe_Cb     handler;
92    unsigned int      len;
93    int               handling;
94    size_t            already_read;
95    void             *passed_data;
96    int               message;
97    Eina_Bool         delete_me : 1;
98 };
99 GENERIC_ALLOC_SIZE_DECLARE(Ecore_Pipe);
100
101 static Eina_Bool _ecore_pipe_read(void             *data,
102                                   Ecore_Fd_Handler *fd_handler);
103
104 /**
105  * @addtogroup Ecore_Pipe_Group
106  *
107  * @{
108  */
109
110 /**
111  * Create two file descriptors (sockets on Windows). Add
112  * a callback that will be called when the file descriptor that
113  * is listened receives data. An event is also put in the event
114  * queue when data is received.
115  *
116  * @param handler The handler called when data is received.
117  * @param data    Data to pass to @p handler when it is called.
118  * @return        A newly created Ecore_Pipe object if successful.
119  *                @c NULL otherwise.
120  */
121 EAPI Ecore_Pipe *
122 ecore_pipe_add(Ecore_Pipe_Cb handler,
123                const void   *data)
124 {
125    Ecore_Pipe *p;
126    int fds[2];
127
128    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
129    if (!handler) return NULL;
130
131    p = ecore_pipe_calloc(1);
132    if (!p) return NULL;
133
134    if (pipe(fds))
135      {
136         ecore_pipe_mp_free(p);
137         return NULL;
138      }
139
140    ECORE_MAGIC_SET(p, ECORE_MAGIC_PIPE);
141    p->fd_read = fds[0];
142    p->fd_write = fds[1];
143    p->handler = handler;
144    p->data = data;
145
146    _ecore_fd_close_on_exec(fds[0]);
147    _ecore_fd_close_on_exec(fds[1]);
148
149    fcntl(p->fd_read, F_SETFL, O_NONBLOCK);
150    p->fd_handler = ecore_main_fd_handler_add(p->fd_read,
151                                              ECORE_FD_READ,
152                                              _ecore_pipe_read,
153                                              p,
154                                              NULL, NULL);
155    return p;
156 }
157
158 /**
159  * Free an Ecore_Pipe object created with ecore_pipe_add().
160  *
161  * @param p The Ecore_Pipe object to be freed.
162  * @return The pointer to the private data
163  */
164 EAPI void *
165 ecore_pipe_del(Ecore_Pipe *p)
166 {
167    void *data;
168
169    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
170    if (!ECORE_MAGIC_CHECK(p, ECORE_MAGIC_PIPE))
171      {
172         ECORE_MAGIC_FAIL(p, ECORE_MAGIC_PIPE, "ecore_pipe_del");
173         return NULL;
174      }
175    p->delete_me = EINA_TRUE;
176    if (p->handling > 0) return (void *)p->data;
177    if (p->fd_handler) _ecore_main_fd_handler_del(p->fd_handler);
178    if (p->fd_read != PIPE_FD_INVALID) pipe_close(p->fd_read);
179    if (p->fd_write != PIPE_FD_INVALID) pipe_close(p->fd_write);
180    data = (void *)p->data;
181    ecore_pipe_mp_free(p);
182    return data;
183 }
184
185 /**
186  * Close the read end of an Ecore_Pipe object created with ecore_pipe_add().
187  *
188  * @param p The Ecore_Pipe object.
189  */
190 EAPI void
191 ecore_pipe_read_close(Ecore_Pipe *p)
192 {
193    EINA_MAIN_LOOP_CHECK_RETURN;
194    if (!ECORE_MAGIC_CHECK(p, ECORE_MAGIC_PIPE))
195      {
196         ECORE_MAGIC_FAIL(p, ECORE_MAGIC_PIPE, "ecore_pipe_read_close");
197         return;
198      }
199    if (p->fd_handler)
200      {
201         _ecore_main_fd_handler_del(p->fd_handler);
202         p->fd_handler = NULL;
203      }
204    if (p->fd_read != PIPE_FD_INVALID)
205      {
206         pipe_close(p->fd_read);
207         p->fd_read = PIPE_FD_INVALID;
208      }
209 }
210
211 /**
212  * Stop monitoring if necessary the pipe for reading. See ecore_pipe_thaw()
213  * for monitoring it again.
214  *
215  * @param p The Ecore_Pipe object.
216  * @since 1.1
217  */
218 EAPI void
219 ecore_pipe_freeze(Ecore_Pipe *p)
220 {
221    EINA_MAIN_LOOP_CHECK_RETURN;
222    if (!ECORE_MAGIC_CHECK(p, ECORE_MAGIC_PIPE))
223      {
224         ECORE_MAGIC_FAIL(p, ECORE_MAGIC_PIPE, "ecore_pipe_read_freeze");
225         return;
226      }
227    if (p->fd_handler)
228      {
229         _ecore_main_fd_handler_del(p->fd_handler);
230         p->fd_handler = NULL;
231      }
232 }
233
234 /**
235  * Start monitoring again the pipe for reading. See ecore_pipe_freeze() for
236  * stopping the monitoring activity. This will not work if
237  * ecore_pipe_read_close() was previously called on the same pipe.
238  *
239  * @param p The Ecore_Pipe object.
240  * @since 1.1
241  */
242 EAPI void
243 ecore_pipe_thaw(Ecore_Pipe *p)
244 {
245    EINA_MAIN_LOOP_CHECK_RETURN;
246    if (!ECORE_MAGIC_CHECK(p, ECORE_MAGIC_PIPE))
247      {
248         ECORE_MAGIC_FAIL(p, ECORE_MAGIC_PIPE, "ecore_pipe_read_thaw");
249         return;
250      }
251    if (!p->fd_handler && p->fd_read != PIPE_FD_INVALID)
252      {
253         p->fd_handler = ecore_main_fd_handler_add(p->fd_read,
254                                                   ECORE_FD_READ,
255                                                   _ecore_pipe_read,
256                                                   p,
257                                                   NULL, NULL);
258      }
259 }
260
261 /**
262  * @brief Wait from another thread on the read side of a pipe.
263  *
264  * @param p The pipe to watch on.
265  * @param message_count The minimal number of message to wait before exiting.
266  * @param wait The amount of time in second to wait before exiting.
267  * @return the number of message catched during that wait call.
268  * @since 1.1
269  *
270  * Negative value for @p wait means infite wait.
271  */
272 EAPI int
273 ecore_pipe_wait(Ecore_Pipe *p,
274                 int         message_count,
275                 double      wait)
276 {
277    struct timeval tv, *t;
278    fd_set rset;
279    double end = 0.0;
280    double timeout;
281    int ret;
282    int total = 0;
283
284    EINA_MAIN_LOOP_CHECK_RETURN_VAL(-1);
285    if (p->fd_read == PIPE_FD_INVALID)
286      return -1;
287
288    FD_ZERO(&rset);
289    FD_SET(p->fd_read, &rset);
290
291    if (wait >= 0.0)
292      end = ecore_loop_time_get() + wait;
293    timeout = wait;
294
295    while (message_count > 0 && (timeout > 0.0 || wait <= 0.0))
296      {
297         if (wait >= 0.0)
298           {
299              /* finite() tests for NaN, too big, too small, and infinity.  */
300               if ((!ECORE_FINITE(timeout)) || (timeout == 0.0))
301                 {
302                    tv.tv_sec = 0;
303                    tv.tv_usec = 0;
304                 }
305               else if (timeout > 0.0)
306                 {
307                    int sec, usec;
308 #ifdef FIX_HZ
309                    timeout += (0.5 / HZ);
310                    sec = (int)timeout;
311                    usec = (int)((timeout - (double)sec) * 1000000);
312 #else
313                    sec = (int)timeout;
314                    usec = (int)((timeout - (double)sec) * 1000000);
315 #endif
316                    tv.tv_sec = sec;
317                    tv.tv_usec = usec;
318                 }
319               t = &tv;
320           }
321         else
322           {
323              t = NULL;
324           }
325
326         ret = main_loop_select(p->fd_read + 1, &rset, NULL, NULL, t);
327
328         if (ret > 0)
329           {
330              _ecore_pipe_read(p, NULL);
331              message_count -= p->message;
332              total += p->message;
333              p->message = 0;
334           }
335         else if (ret == 0)
336           {
337              break;
338           }
339         else if (errno != EINTR)
340           {
341              close(p->fd_read);
342              p->fd_read = PIPE_FD_INVALID;
343              break;
344           }
345
346         if (wait >= 0.0)
347           timeout = end - ecore_loop_time_get();
348      }
349
350    return total;
351 }
352
353 /**
354  * Close the write end of an Ecore_Pipe object created with ecore_pipe_add().
355  *
356  * @param p The Ecore_Pipe object.
357  */
358 EAPI void
359 ecore_pipe_write_close(Ecore_Pipe *p)
360 {
361    if (!ECORE_MAGIC_CHECK(p, ECORE_MAGIC_PIPE))
362      {
363         ECORE_MAGIC_FAIL(p, ECORE_MAGIC_PIPE, "ecore_pipe_write_close");
364         return;
365      }
366    if (p->fd_write != PIPE_FD_INVALID)
367      {
368         pipe_close(p->fd_write);
369         p->fd_write = PIPE_FD_INVALID;
370      }
371 }
372
373 /**
374  * Write on the file descriptor the data passed as parameter.
375  *
376  * @param p      The Ecore_Pipe object.
377  * @param buffer The data to write into the pipe.
378  * @param nbytes The size of the @p buffer in bytes
379  * @return       @c EINA_TRUE on a successful write, @c EINA_FALSE on error.
380  */
381 EAPI Eina_Bool
382 ecore_pipe_write(Ecore_Pipe  *p,
383                  const void  *buffer,
384                  unsigned int nbytes)
385 {
386    ssize_t ret;
387    size_t already_written = 0;
388    int retry = ECORE_PIPE_WRITE_RETRY;
389
390    if (!ECORE_MAGIC_CHECK(p, ECORE_MAGIC_PIPE))
391      {
392         ECORE_MAGIC_FAIL(p, ECORE_MAGIC_PIPE, "ecore_pipe_write");
393         return EINA_FALSE;
394      }
395
396    if (p->delete_me) return EINA_FALSE;
397
398    if (p->fd_write == PIPE_FD_INVALID) return EINA_FALSE;
399
400    /* First write the len into the pipe */
401    do
402      {
403         ret = pipe_write(p->fd_write, &nbytes, sizeof(nbytes));
404         if (ret == sizeof(nbytes))
405           {
406              retry = ECORE_PIPE_WRITE_RETRY;
407              break;
408           }
409         else if (ret > 0)
410           {
411              /* XXX What should we do here? */
412               ERR("The length of the data was not written complete"
413                   " to the pipe");
414               return EINA_FALSE;
415           }
416         else if (ret == PIPE_FD_ERROR && errno == EPIPE)
417           {
418              pipe_close(p->fd_write);
419              p->fd_write = PIPE_FD_INVALID;
420              return EINA_FALSE;
421           }
422         else if (ret == PIPE_FD_ERROR && errno == EINTR)
423           /* try it again */
424           ;
425         else
426           {
427              ERR("An unhandled error (ret: %zd errno: %d)"
428                  "occurred while writing to the pipe the length",
429                  ret, errno);
430           }
431      }
432    while (retry--);
433
434    if (retry != ECORE_PIPE_WRITE_RETRY) return EINA_FALSE;
435
436    /* and now pass the data to the pipe */
437    do
438      {
439         ret = pipe_write(p->fd_write,
440                          ((unsigned char *)buffer) + already_written,
441                          nbytes - already_written);
442
443         if (ret == (ssize_t)(nbytes - already_written))
444           return EINA_TRUE;
445         else if (ret >= 0)
446           {
447              already_written -= ret;
448              continue;
449           }
450         else if (ret == PIPE_FD_ERROR && errno == EPIPE)
451           {
452              pipe_close(p->fd_write);
453              p->fd_write = PIPE_FD_INVALID;
454              return EINA_FALSE;
455           }
456         else if (ret == PIPE_FD_ERROR && errno == EINTR)
457           /* try it again */
458           ;
459         else
460           {
461              ERR("An unhandled error (ret: %zd errno: %d)"
462                  "occurred while writing to the pipe the length",
463                  ret, errno);
464           }
465      }
466    while (retry--);
467
468    return EINA_FALSE;
469 }
470
471 /**
472  * @}
473  */
474
475 /* Private function */
476 static void
477 _ecore_pipe_unhandle(Ecore_Pipe *p)
478 {
479    p->handling--;
480    if (p->delete_me)
481      {
482         ecore_pipe_del(p);
483      }
484 }
485
486 static Eina_Bool
487 _ecore_pipe_read(void             *data,
488                  Ecore_Fd_Handler *fd_handler __UNUSED__)
489 {
490    Ecore_Pipe *p = (Ecore_Pipe *)data;
491    int i;
492
493    p->handling++;
494    for (i = 0; i < 16; i++)
495      {
496         ssize_t ret;
497
498         /* if we already have read some data we don't need to read the len
499          * but to finish the already started job
500          */
501         if (p->len == 0)
502           {
503              /* read the len of the passed data */
504               ret = pipe_read(p->fd_read, &p->len, sizeof(p->len));
505
506      /* catch the non error case first */
507               /* read amount ok - nothing more to do */
508               if (ret == sizeof(p->len))
509                 ;
510               else if (ret > 0)
511                 {
512      /* we got more data than we asked for - definite error */
513                     ERR("Only read %i bytes from the pipe, although"
514                         " we need to read %i bytes.",
515                         (int)ret, (int)sizeof(p->len));
516                     _ecore_pipe_unhandle(p);
517                     return ECORE_CALLBACK_CANCEL;
518                 }
519               else if (ret == 0)
520                 {
521      /* we got no data */
522                     if (i == 0)
523                       {
524      /* no data on first try through means an error */
525                           if (!p->delete_me)
526                             p->handler((void *)p->data, NULL, 0);
527                           if (p->passed_data) free(p->passed_data);
528                           p->passed_data = NULL;
529                           p->already_read = 0;
530                           p->len = 0;
531                           p->message++;
532                           pipe_close(p->fd_read);
533                           p->fd_read = PIPE_FD_INVALID;
534                           p->fd_handler = NULL;
535                           _ecore_pipe_unhandle(p);
536                           return ECORE_CALLBACK_CANCEL;
537                       }
538                     else
539                       {
540      /* no data after first loop try is ok */
541                           _ecore_pipe_unhandle(p);
542                           return ECORE_CALLBACK_RENEW;
543                       }
544                 }
545 #ifndef _WIN32
546               else if ((ret == PIPE_FD_ERROR) &&
547                        ((errno == EINTR) || (errno == EAGAIN)))
548                 {
549                    return ECORE_CALLBACK_RENEW;
550                 }
551               else
552                 {
553                    ERR("An unhandled error (ret: %i errno: %i [%s])"
554                        "occurred while reading from the pipe the length",
555                        (int)ret, errno, strerror(errno));
556                    return ECORE_CALLBACK_RENEW;
557                 }
558 #else
559               else /* ret == PIPE_FD_ERROR is the only other case on Windows */
560                 {
561                    if (WSAGetLastError() != WSAEWOULDBLOCK)
562                      {
563                         if (!p->delete_me)
564                           p->handler((void *)p->data, NULL, 0);
565                         if (p->passed_data) free(p->passed_data);
566                         p->passed_data = NULL;
567                         p->already_read = 0;
568                         p->len = 0;
569                         p->message++;
570                         pipe_close(p->fd_read);
571                         p->fd_read = PIPE_FD_INVALID;
572                         p->fd_handler = NULL;
573                         _ecore_pipe_unhandle(p);
574                         return ECORE_CALLBACK_CANCEL;
575                      }
576                 }
577 #endif
578           }
579
580         /* if somehow we got less than or equal to 0 we got an errnoneous
581          * messages so call callback with null and len we got. this case should
582          * never happen */
583         if (p->len == 0)
584           {
585              if (!p->delete_me)
586                p->handler((void *)p->data, NULL, 0);
587              /* reset all values to 0 */
588              if (p->passed_data) free(p->passed_data);
589              p->passed_data = NULL;
590              p->already_read = 0;
591              p->len = 0;
592              p->message++;
593              _ecore_pipe_unhandle(p);
594              return ECORE_CALLBACK_RENEW;
595           }
596
597         /* we dont have a buffer to hold the data, so alloc it */
598         if (!p->passed_data)
599           {
600              p->passed_data = malloc(p->len);
601              /* alloc failed - error case */
602              if (!p->passed_data)
603                {
604                   if (!p->delete_me)
605                     p->handler((void *)p->data, NULL, 0);
606      /* close the pipe */
607                   p->already_read = 0;
608                   p->len = 0;
609                   p->message++;
610                   pipe_close(p->fd_read);
611                   p->fd_read = PIPE_FD_INVALID;
612                   p->fd_handler = NULL;
613                   _ecore_pipe_unhandle(p);
614                   return ECORE_CALLBACK_CANCEL;
615                }
616           }
617
618         /* and read the passed data */
619         ret = pipe_read(p->fd_read,
620                         ((unsigned char *)p->passed_data) + p->already_read,
621                         p->len - p->already_read);
622
623         /* catch the non error case first */
624         /* if we read enough data to finish the message/buffer */
625         if (ret == (ssize_t)(p->len - p->already_read))
626           {
627              if (!p->delete_me)
628                p->handler((void *)p->data, p->passed_data, p->len);
629              free(p->passed_data);
630              /* reset all values to 0 */
631              p->passed_data = NULL;
632              p->already_read = 0;
633              p->len = 0;
634              p->message++;
635           }
636         else if (ret > 0)
637           {
638              /* more data left to read */
639               p->already_read += ret;
640               _ecore_pipe_unhandle(p);
641               return ECORE_CALLBACK_RENEW;
642           }
643         else if (ret == 0)
644           {
645              /* 0 bytes to read - could be more to read next select wake up */
646               _ecore_pipe_unhandle(p);
647               return ECORE_CALLBACK_RENEW;
648           }
649 #ifndef _WIN32
650         else if ((ret == PIPE_FD_ERROR) &&
651                  ((errno == EINTR) || (errno == EAGAIN)))
652           {
653              _ecore_pipe_unhandle(p);
654              return ECORE_CALLBACK_RENEW;
655           }
656         else
657           {
658              ERR("An unhandled error (ret: %zd errno: %d)"
659                  "occurred while reading from the pipe the data",
660                  ret, errno);
661              _ecore_pipe_unhandle(p);
662              return ECORE_CALLBACK_RENEW;
663           }
664 #else
665         else /* ret == PIPE_FD_ERROR is the only other case on Windows */
666           {
667              if (WSAGetLastError() != WSAEWOULDBLOCK)
668                {
669                   if (!p->delete_me)
670                     p->handler((void *)p->data, NULL, 0);
671                   if (p->passed_data) free(p->passed_data);
672                   p->passed_data = NULL;
673                   p->already_read = 0;
674                   p->len = 0;
675                   p->message++;
676                   pipe_close(p->fd_read);
677                   p->fd_read = PIPE_FD_INVALID;
678                   p->fd_handler = NULL;
679                   _ecore_pipe_unhandle(p);
680                   return ECORE_CALLBACK_CANCEL;
681                }
682              else
683                break;
684           }
685 #endif
686      }
687
688    _ecore_pipe_unhandle(p);
689    return ECORE_CALLBACK_RENEW;
690 }
691