137a3b751a1cb6e21562f1448b8e8606fd4460ba
[profile/ivi/ecore.git] / src / lib / ecore_con / ecore_con.c
1 #ifdef HAVE_CONFIG_H
2 # include <config.h>
3 #endif
4
5 #include <stdio.h>
6 #include <string.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <errno.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12
13 #ifdef HAVE_ARPA_INET_H
14 # include <arpa/inet.h>
15 #endif
16
17 #ifdef HAVE_NETINET_TCP_H
18 # include <netinet/tcp.h>
19 #endif
20
21 #ifdef HAVE_NETINET_IN_H
22 # include <netinet/in.h>
23 #endif
24
25 #ifdef HAVE_SYS_SOCKET_H
26 # include <sys/socket.h>
27 #endif
28
29 #ifdef HAVE_SYS_UN_H
30 # include <sys/un.h>
31 #endif
32
33 #ifdef HAVE_WS2TCPIP_H
34 # include <ws2tcpip.h>
35 #endif
36
37 #ifdef HAVE_EVIL
38 # include <Evil.h>
39 #endif
40
41 #include "Ecore.h"
42 #include "ecore_private.h"
43 #include "Ecore_Con.h"
44 #include "ecore_con_private.h"
45
46 static Eina_Bool _ecore_con_client_timer(Ecore_Con_Client *cl);
47 static void      _ecore_con_cl_timer_update(Ecore_Con_Client *cl);
48
49 static void      _ecore_con_cb_tcp_connect(void           *data,
50                                            Ecore_Con_Info *info);
51 static void      _ecore_con_cb_udp_connect(void           *data,
52                                            Ecore_Con_Info *info);
53 static void      _ecore_con_cb_tcp_listen(void           *data,
54                                           Ecore_Con_Info *info);
55 static void      _ecore_con_cb_udp_listen(void           *data,
56                                           Ecore_Con_Info *info);
57
58 static void      _ecore_con_server_free(Ecore_Con_Server *svr);
59 static void      _ecore_con_client_free(Ecore_Con_Client *cl);
60
61 static Eina_Bool _ecore_con_svr_tcp_handler(void             *data,
62                                             Ecore_Fd_Handler *fd_handler);
63 static Eina_Bool _ecore_con_cl_handler(void             *data,
64                                        Ecore_Fd_Handler *fd_handler);
65 static Eina_Bool _ecore_con_cl_udp_handler(void             *data,
66                                            Ecore_Fd_Handler *fd_handler);
67 static Eina_Bool _ecore_con_svr_udp_handler(void             *data,
68                                             Ecore_Fd_Handler *fd_handler);
69
70 static void      _ecore_con_svr_cl_read(Ecore_Con_Client *cl);
71 static Eina_Bool _ecore_con_svr_cl_handler(void             *data,
72                                            Ecore_Fd_Handler *fd_handler);
73
74 static void _ecore_con_server_flush(Ecore_Con_Server *svr);
75 static void _ecore_con_client_flush(Ecore_Con_Client *cl);
76
77 static void _ecore_con_event_client_add_free(void *data,
78                                              void *ev);
79 static void _ecore_con_event_client_del_free(void *data,
80                                              void *ev);
81 static void _ecore_con_event_client_data_free(void *data,
82                                               void *ev);
83 static void _ecore_con_event_server_add_free(void *data,
84                                              void *ev);
85 static void _ecore_con_event_server_del_free(void *data,
86                                              void *ev);
87 static void _ecore_con_event_server_data_free(void *data,
88                                               void *ev);
89
90 static void _ecore_con_lookup_done(void           *data,
91                                    Ecore_Con_Info *infos);
92
93 static const char *
94 _ecore_con_pretty_ip(struct sockaddr *client_addr,
95                      socklen_t        size);
96
97 EAPI int ECORE_CON_EVENT_CLIENT_ADD = 0;
98 EAPI int ECORE_CON_EVENT_CLIENT_DEL = 0;
99 EAPI int ECORE_CON_EVENT_SERVER_ADD = 0;
100 EAPI int ECORE_CON_EVENT_SERVER_DEL = 0;
101 EAPI int ECORE_CON_EVENT_CLIENT_DATA = 0;
102 EAPI int ECORE_CON_EVENT_SERVER_DATA = 0;
103
104 static Eina_List *servers = NULL;
105 static int _ecore_con_init_count = 0;
106 int _ecore_con_log_dom = -1;
107
108 /**
109  * @addtogroup Ecore_Con_Lib_Group Ecore Connection Library Functions
110  *
111  * Utility functions that set up and shut down the Ecore Connection
112  * library.
113  * @{
114  */
115
116 /**
117  * Initialises the Ecore_Con library.
118  * @return  Number of times the library has been initialised without being
119  *          shut down.
120  */
121 EAPI int
122 ecore_con_init(void)
123 {
124    if (++_ecore_con_init_count != 1)
125      return _ecore_con_init_count;
126
127 #ifdef HAVE_EVIL
128    if (!evil_init())
129      return --_ecore_con_init_count;
130
131 #endif
132
133    if (!ecore_init())
134      return --_ecore_con_init_count;
135
136    _ecore_con_log_dom = eina_log_domain_register
137        ("ecore_con", ECORE_CON_DEFAULT_LOG_COLOR);
138    if (_ecore_con_log_dom < 0)
139      {
140         EINA_LOG_ERR("Impossible to create a log domain for Ecore Con.");
141         ecore_shutdown();
142         return --_ecore_con_init_count;
143      }
144
145    ECORE_CON_EVENT_CLIENT_ADD = ecore_event_type_new();
146    ECORE_CON_EVENT_CLIENT_DEL = ecore_event_type_new();
147    ECORE_CON_EVENT_SERVER_ADD = ecore_event_type_new();
148    ECORE_CON_EVENT_SERVER_DEL = ecore_event_type_new();
149    ECORE_CON_EVENT_CLIENT_DATA = ecore_event_type_new();
150    ECORE_CON_EVENT_SERVER_DATA = ecore_event_type_new();
151
152
153    eina_magic_string_set(ECORE_MAGIC_CON_SERVER, "Ecore_Con_Server");
154    eina_magic_string_set(ECORE_MAGIC_CON_CLIENT, "Ecore_Con_Server");
155    eina_magic_string_set(ECORE_MAGIC_CON_URL, "Ecore_Con_Url");
156
157    /* TODO Remember return value, if it fails, use gethostbyname() */
158    ecore_con_ssl_init();
159    ecore_con_info_init();
160
161    return _ecore_con_init_count;
162 }
163
164 /**
165  * Shuts down the Ecore_Con library.
166  * @return  Number of times the library has been initialised without being
167  *          shut down.
168  */
169 EAPI int
170 ecore_con_shutdown(void)
171 {
172    Eina_List *l, *l2;
173    Ecore_Con_Server *svr;
174    
175    if (--_ecore_con_init_count != 0)
176      return _ecore_con_init_count;
177
178    EINA_LIST_FOREACH_SAFE(servers, l, l2, svr)
179      _ecore_con_server_free(svr);
180
181    ecore_con_info_shutdown();
182    ecore_con_ssl_shutdown();
183    eina_log_domain_unregister(_ecore_con_log_dom);
184    _ecore_con_log_dom = -1;
185    ecore_shutdown();
186 #ifdef HAVE_EVIL
187    evil_shutdown();
188 #endif
189
190    return _ecore_con_init_count;
191 }
192
193 /**
194  * Do an asynchronous DNS lookup.
195  *
196  * This function performs a DNS lookup on the hostname specified by @p name, then
197  * calls @p done_cb with
198  *
199  * @param name IP address or server name to translate.
200  * @param done_cb Callback to notify when done.
201  * @param data User data to be given to done_cb.
202  * @return EINA_TRUE if the request did not fail to be set up, EINA_FALSE if it failed.
203  */
204 EAPI Eina_Bool
205 ecore_con_lookup(const char      *name,
206                  Ecore_Con_Dns_Cb done_cb,
207                  const void      *data)
208 {
209    Ecore_Con_Server *svr;
210    Ecore_Con_Lookup *lk;
211    struct addrinfo hints;
212
213    if (!name || !done_cb)
214      return EINA_FALSE;
215
216    svr = calloc(1, sizeof(Ecore_Con_Server));
217    if (!svr)
218      return EINA_FALSE;
219
220    lk = malloc(sizeof (Ecore_Con_Lookup));
221    if (!lk)
222      {
223         free(svr);
224         return EINA_FALSE;
225      }
226
227    lk->done_cb = done_cb;
228    lk->data = data;
229
230    svr->name = strdup(name);
231    if (!svr->name)
232      goto on_error;
233
234    svr->type = ECORE_CON_REMOTE_TCP;
235    svr->port = 1025;
236    svr->data = lk;
237    svr->created = EINA_TRUE;
238    svr->reject_excess_clients = EINA_FALSE;
239    svr->client_limit = -1;
240    svr->clients = NULL;
241    svr->ppid = getpid();
242
243    memset(&hints, 0, sizeof(struct addrinfo));
244    hints.ai_family = AF_INET6;
245    hints.ai_socktype = SOCK_STREAM;
246    hints.ai_flags = AI_CANONNAME;
247    hints.ai_protocol = IPPROTO_TCP;
248    hints.ai_canonname = NULL;
249    hints.ai_next = NULL;
250    hints.ai_addr = NULL;
251
252    if (ecore_con_info_get(svr, _ecore_con_lookup_done, svr,
253                           &hints))
254      return EINA_TRUE;
255
256    free(svr->name);
257 on_error:
258    free(lk);
259    free(svr);
260    return EINA_FALSE;
261 }
262
263 /**
264  * @}
265  */
266
267 /**
268  * @addtogroup Ecore_Con_Server_Group Ecore Connection Server Functions
269  *
270  * Functions that operate on Ecore server objects.
271  *
272  * @{
273  */
274
275 /**
276  * @example ecore_con_server_example.c
277  * Shows how to write a simple server using the Ecore_Con library.
278  */
279
280 /**
281  * Creates a server to listen for connections.
282  *
283  * The socket on which the server listens depends on the connection
284  * type:
285  * @li If @a compl_type is @c ECORE_CON_LOCAL_USER, the server will listen on
286  *     the Unix socket "~/.ecore/[name]/[port]".
287  * @li If @a compl_type is @c ECORE_CON_LOCAL_SYSTEM, the server will listen
288  *     on Unix socket "/tmp/.ecore_service|[name]|[port]".
289  * @li If @a compl_type is @c ECORE_CON_REMOTE_TCP, the server will listen
290  *     on TCP port @c port.
291  *
292  * @param  compl_type The connection type.
293  * @param  name       Name to associate with the socket.  It is used when
294  *                    generating the socket name of a Unix socket, or for
295  *                    determining what host to listen on for TCP sockets.
296  *                    @c NULL will not be accepted.
297  * @param  port       Number to identify socket.  When a Unix socket is used,
298  *                    it becomes part of the socket name.  When a TCP socket
299  *                    is used, it is used as the TCP port.
300  * @param  data       Data to associate with the created Ecore_Con_Server
301  *                    object.
302  * @return A new Ecore_Con_Server.
303  */
304 EAPI Ecore_Con_Server *
305 ecore_con_server_add(Ecore_Con_Type compl_type,
306                      const char    *name,
307                      int            port,
308                      const void    *data)
309 {
310    Ecore_Con_Server *svr;
311    Ecore_Con_Type type;
312
313    if (port < 0 || !name)
314      return NULL;  /* local  user   socket: FILE:   ~/.ecore/[name]/[port] */
315
316    /* local  system socket: FILE:   /tmp/.ecore_service|[name]|[port] */
317    /* remote system socket: TCP/IP: [name]:[port] */
318    svr = calloc(1, sizeof(Ecore_Con_Server));
319    if (!svr)
320      return NULL;
321
322    svr->name = strdup(name);
323    if (!svr->name)
324      goto error;
325
326    svr->type = compl_type;
327    svr->port = port;
328    svr->data = (void *)data;
329    svr->created = EINA_TRUE;
330    if (compl_type & ECORE_CON_LOAD_CERT)
331      svr->use_cert = EINA_TRUE;
332    svr->reject_excess_clients = EINA_FALSE;
333    svr->client_limit = -1;
334    svr->clients = NULL;
335    svr->ppid = getpid();
336    if (ecore_con_ssl_server_prepare(svr, compl_type & ECORE_CON_SSL))
337      goto error;
338
339    type = compl_type & ECORE_CON_TYPE;
340
341    if ((type == ECORE_CON_LOCAL_USER) ||
342        (type == ECORE_CON_LOCAL_SYSTEM) ||
343        (type == ECORE_CON_LOCAL_ABSTRACT))
344      /* Local */
345      if (!ecore_con_local_listen(svr, _ecore_con_svr_tcp_handler, svr))
346        goto error;
347
348    if ((type == ECORE_CON_REMOTE_TCP) ||
349        (type == ECORE_CON_REMOTE_NODELAY))
350      {
351         /* TCP */
352          if (!ecore_con_info_tcp_listen(svr, _ecore_con_cb_tcp_listen,
353                                         svr))
354            goto error;
355      }
356    else if ((type == ECORE_CON_REMOTE_MCAST) ||
357             (type == ECORE_CON_REMOTE_UDP))
358      /* UDP and MCAST */
359      if (!ecore_con_info_udp_listen(svr, _ecore_con_cb_udp_listen,
360                                     svr))
361        goto error;
362
363    servers = eina_list_append(servers, svr);
364    ECORE_MAGIC_SET(svr, ECORE_MAGIC_CON_SERVER);
365
366    return svr;
367
368 error:
369    if (svr->name)
370      free(svr->name);
371
372    if (svr->path)
373      free(svr->path);
374
375 #ifndef _WIN32
376    if (svr->fd >= 0)
377      close(svr->fd);
378
379    if (svr->fd_handler)
380      ecore_main_fd_handler_del(svr->fd_handler);
381
382    if (svr->write_buf)
383      free(svr->write_buf);
384
385    if (svr->ip)
386      eina_stringshare_del(svr->ip);
387
388 #endif
389    ecore_con_ssl_server_shutdown(svr);
390    free(svr);
391    return NULL;
392 }
393
394 /**
395  * Creates a connection to the specified server and returns an associated object.
396  *
397  * The socket to which the connection is made depends on the connection type:
398  * @li If @a compl_type is @c ECORE_CON_LOCAL_USER, the function will
399  *     connect to the server at the Unix socket
400  *     "~/.ecore/[name]/[port]".
401  * @li If @a compl_type is @c ECORE_CON_LOCAL_SYSTEM, the function will
402  *     connect to the server at the Unix socket
403  *     "/tmp/.ecore_service|[name]|[port]".
404  * @li If @a compl_type is @c ECORE_CON_REMOTE_TCP, the function will
405  *     connect to the server at the TCP port "[name]:[port]".
406  *
407  * @param  compl_type The connection type.
408  * @param  name       Name used when determining what socket to connect to.
409  *                    It is used to generate the socket name when the socket
410  *                    is a Unix socket.  It is used as the hostname when
411  *                    connecting with a TCP socket.
412  * @param  port       Number to identify the socket to connect to.  Used when
413  *                    generating the socket name for a Unix socket, or as the
414  *                    TCP port when connecting to a TCP socket.
415  * @param  data       Data to associate with the created Ecore_Con_Server
416  *                    object.
417  * @return A new Ecore_Con_Server.
418  */
419 EAPI Ecore_Con_Server *
420 ecore_con_server_connect(Ecore_Con_Type compl_type,
421                          const char    *name,
422                          int            port,
423                          const void    *data)
424 {
425    Ecore_Con_Server *svr;
426    Ecore_Con_Type type;
427
428    if (!name)
429      return NULL;
430    /* local  user   socket: FILE:   ~/.ecore/[name]/[port] */
431    /* local  system socket: FILE:   /tmp/.ecore_service|[name]|[port] */
432    /* remote system socket: TCP/IP: [name]:[port] */
433    svr = calloc(1, sizeof(Ecore_Con_Server));
434    if (!svr)
435      return NULL;
436
437    svr->name = strdup(name);
438    if (!svr->name)
439      goto error;
440
441    svr->type = compl_type;
442    svr->port = port;
443    svr->data = (void *)data;
444    svr->created = EINA_FALSE;
445    svr->use_cert = (compl_type & ECORE_CON_LOAD_CERT);
446    svr->reject_excess_clients = EINA_FALSE;
447    svr->clients = NULL;
448    svr->client_limit = -1;
449    if (ecore_con_ssl_server_prepare(svr, compl_type & ECORE_CON_SSL))
450      goto error;
451
452    type = compl_type & ECORE_CON_TYPE;
453
454    if (((type == ECORE_CON_REMOTE_TCP) ||
455         (type == ECORE_CON_REMOTE_NODELAY) ||
456         (type == ECORE_CON_REMOTE_UDP) ||
457         (type == ECORE_CON_REMOTE_BROADCAST)) &&
458        (port < 0))
459      goto error;
460
461    if ((type == ECORE_CON_LOCAL_USER) ||
462        (type == ECORE_CON_LOCAL_SYSTEM) ||
463        (type == ECORE_CON_LOCAL_ABSTRACT))
464      /* Local */
465      if (!ecore_con_local_connect(svr, _ecore_con_cl_handler, svr,
466                                   _ecore_con_event_server_add_free))
467        goto
468        error;
469
470    if ((type == ECORE_CON_REMOTE_TCP) ||
471        (type == ECORE_CON_REMOTE_NODELAY))
472      {
473         /* TCP */
474          if (!ecore_con_info_tcp_connect(svr, _ecore_con_cb_tcp_connect,
475                                          svr))
476            goto error;
477      }
478    else if ((type == ECORE_CON_REMOTE_UDP) ||
479             (type == ECORE_CON_REMOTE_BROADCAST))
480      /* UDP and MCAST */
481      if (!ecore_con_info_udp_connect(svr, _ecore_con_cb_udp_connect,
482                                      svr))
483        goto error;
484
485    servers = eina_list_append(servers, svr);
486    ECORE_MAGIC_SET(svr, ECORE_MAGIC_CON_SERVER);
487
488    return svr;
489
490 error:
491    if (svr->name)
492      free(svr->name);
493
494    if (svr->path)
495      free(svr->path);
496
497    if (svr->fd >= 0)
498      close(svr->fd);
499
500    if (svr->fd_handler)
501      ecore_main_fd_handler_del(svr->fd_handler);
502
503    ecore_con_ssl_server_shutdown(svr);
504    free(svr);
505    return NULL;
506 }
507
508 /**
509  * Set the default time after which an inactive client will be disconnected
510  * @param svr The server object
511  * @param timeout The timeout, in seconds, to disconnect after
512  * This function is used to set the idle timeout on clients.  A value of < 1
513  * disables the idle timeout.
514  */
515 EAPI void
516 ecore_con_server_timeout_set(Ecore_Con_Server *svr,
517                              double            timeout)
518 {
519    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
520      {
521         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER, "ecore_con_server_timeout_set");
522         return;
523      }
524
525    svr->client_disconnect_time = timeout;
526 }
527
528 /**
529  * Get the default time after which an inactive client will be disconnected
530  * @param svr The server object
531  * @return The timeout, in seconds, to disconnect after
532  * This function is used to get the idle timeout for clients.  A value of < 1
533  * means the idle timeout is disabled.
534  */
535 EAPI double
536 ecore_con_server_timeout_get(Ecore_Con_Server *svr)
537 {
538    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
539      {
540         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER, "ecore_con_server_timeout_get");
541         return 0;
542      }
543
544    return svr->client_disconnect_time;
545 }
546
547 /**
548  * Closes the connection and frees the given server.
549  * @param   svr The given server.
550  * @return  Data associated with the server when it was created.
551  * @see ecore_con_server_add, ecore_con_server_connect
552  */
553 EAPI void *
554 ecore_con_server_del(Ecore_Con_Server *svr)
555 {
556    void *data;
557
558    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
559      {
560         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER, "ecore_con_server_del");
561         return NULL;
562      }
563
564    if (svr->delete_me)
565      return NULL;
566
567    data = svr->data;
568    svr->delete_me = EINA_TRUE;
569    if (svr->event_count > 0)
570      {
571         if (svr->fd_handler)
572           {
573              ecore_main_fd_handler_del(svr->fd_handler);
574              svr->fd_handler = NULL;
575           }
576      }
577    else
578      _ecore_con_server_free(svr);
579
580    return data;
581 }
582
583 /**
584  * Retrieves the data associated with the given server.
585  * @param   svr The given server.
586  * @return  The associated data.
587  */
588 EAPI void *
589 ecore_con_server_data_get(Ecore_Con_Server *svr)
590 {
591    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
592      {
593         ECORE_MAGIC_FAIL(svr,
594                          ECORE_MAGIC_CON_SERVER,
595                          "ecore_con_server_data_get");
596         return NULL;
597      }
598
599    return svr->data;
600 }
601
602 /**
603  * Sets the data associated with the given server.
604  * @param svr The given server.
605  * @param data The data to associate with @p svr
606  * @return  The previously associated data, if any.
607  */
608 EAPI void *
609 ecore_con_server_data_set(Ecore_Con_Server *svr,
610                           void             *data)
611 {
612    void *ret = NULL;
613
614    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
615      {
616         ECORE_MAGIC_FAIL(svr,
617                          ECORE_MAGIC_CON_SERVER,
618                          "ecore_con_server_data_get");
619         return NULL;
620      }
621
622    ret = svr->data;
623    svr->data = data;
624    return ret;
625 }
626
627 /**
628  * Retrieves whether the given server is currently connected.
629  * @param   svr The given server.
630  * @return  #EINA_TRUE if the server is connected.  #EINA_FALSE otherwise.
631  */
632 EAPI Eina_Bool
633 ecore_con_server_connected_get(Ecore_Con_Server *svr)
634 {
635    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
636      {
637         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER,
638                          "ecore_con_server_connected_get");
639         return EINA_FALSE;
640      }
641
642    if (svr->connecting)
643      return EINA_FALSE;
644
645    return EINA_TRUE;
646 }
647
648 /**
649  * Retrieves the current list of clients.
650  * @param   svr The given server.
651  * @return  The list of clients on this server.
652  */
653 EAPI Eina_List *
654 ecore_con_server_clients_get(Ecore_Con_Server *svr)
655 {
656    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
657      {
658         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER,
659                          "ecore_con_server_clients_get");
660         return NULL;
661      }
662
663    return svr->clients;
664 }
665
666 /**
667  * Retrieves the name of server.
668  * @param   svr The given server.
669  * @return  The name of the server.
670  */
671 EAPI const char *
672 ecore_con_server_name_get(Ecore_Con_Server *svr)
673 {
674    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
675      {
676         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER,
677                          "ecore_con_server_name_get");
678         return NULL;
679      }
680
681    return svr->name;
682 }
683
684 /**
685  * Retrieves the server port in use.
686  * @param   svr The given server.
687  * @return  The server port in use.
688  */
689 EAPI int
690 ecore_con_server_port_get(Ecore_Con_Server *svr)
691 {
692    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
693      {
694         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER,
695                          "ecore_con_server_port_get");
696         return -1;
697      }
698    return svr->port;
699 }
700
701 /**
702  * Sends the given data to the given server.
703  * @param   svr  The given server.
704  * @param   data The given data.
705  * @param   size Length of the data, in bytes, to send.
706  * @return  The number of bytes sent.  @c 0 will be returned if there is an
707  *          error.
708  */
709 EAPI int
710 ecore_con_server_send(Ecore_Con_Server *svr,
711                       const void       *data,
712                       int               size)
713 {
714    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
715      {
716         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER, "ecore_con_server_send");
717         return 0;
718      }
719
720    EINA_SAFETY_ON_TRUE_RETURN_VAL(svr->dead, 0);
721
722    EINA_SAFETY_ON_NULL_RETURN_VAL(data, 0);
723
724    EINA_SAFETY_ON_TRUE_RETURN_VAL(size < 1, 0);
725
726    if (svr->fd_handler)
727      ecore_main_fd_handler_active_set(svr->fd_handler, ECORE_FD_READ | ECORE_FD_WRITE);
728
729    if (svr->write_buf)
730      {
731         unsigned char *newbuf;
732
733         newbuf = realloc(svr->write_buf, svr->write_buf_size + size);
734         EINA_SAFETY_ON_NULL_RETURN_VAL(newbuf, 0);
735
736         svr->write_buf = newbuf;
737         memcpy(svr->write_buf + svr->write_buf_size, data, size);
738         svr->write_buf_size += size;
739      }
740    else
741      {
742         svr->write_buf = malloc(size);
743         EINA_SAFETY_ON_NULL_RETURN_VAL(svr->write_buf, 0);
744
745         svr->write_buf_size = size;
746         memcpy(svr->write_buf, data, size);
747      }
748
749    return size;
750 }
751
752 /**
753  * Sets a limit on the number of clients that can be handled concurrently
754  * by the given server, and a policy on what to do if excess clients try to
755  * connect.
756  * Beware that if you set this once ecore is already running, you may
757  * already have pending CLIENT_ADD events in your event queue.  Those
758  * clients have already connected and will not be affected by this call.
759  * Only clients subsequently trying to connect will be affected.
760  * @param   svr           The given server.
761  * @param   client_limit  The maximum number of clients to handle
762  *                        concurrently.  -1 means unlimited (default).  0
763  *                        effectively disables the server.
764  * @param   reject_excess_clients  Set to 1 to automatically disconnect
765  *                        excess clients as soon as they connect if you are
766  *                        already handling client_limit clients.  Set to 0
767  *                        (default) to just hold off on the "accept()"
768  *                        system call until the number of active clients
769  *                        drops. This causes the kernel to queue up to 4096
770  *                        connections (or your kernel's limit, whichever is
771  *                        lower).
772  */
773 EAPI void
774 ecore_con_server_client_limit_set(Ecore_Con_Server *svr,
775                                   int               client_limit,
776                                   char              reject_excess_clients)
777 {
778    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
779      {
780         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER,
781                          "ecore_con_server_client_limit_set");
782         return;
783      }
784
785    svr->client_limit = client_limit;
786    svr->reject_excess_clients = reject_excess_clients;
787 }
788
789 /**
790  * Gets the IP address of a server that has been connected to.
791  *
792  * @param   svr           The given server.
793  * @return  A pointer to an internal string that contains the IP address of
794  *          the connected server in the form "XXX.YYY.ZZZ.AAA" IP notation.
795  *          This string should not be modified or trusted to stay valid after
796  *          deletion for the @p svr object. If no IP is known NULL is returned.
797  */
798 EAPI const char *
799 ecore_con_server_ip_get(Ecore_Con_Server *svr)
800 {
801    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
802      {
803         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER, "ecore_con_server_ip_get");
804         return NULL;
805      }
806
807    return svr->ip;
808 }
809
810 /**
811  * @brief Check how long a server has been connected
812  * @param svr The server to check
813  * @return The total time, in seconds, that the server has been connected/running
814  * This function is used to find out how long a server has been connected/running for.
815  */
816 EAPI double
817 ecore_con_server_uptime_get(Ecore_Con_Server *svr)
818 {
819    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
820      {
821         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER, "ecore_con_server_uptime_get");
822         return -1;
823      }
824
825    return ecore_time_get() - svr->start_time;
826 }
827
828 /**
829  * Flushes all pending data to the given server. Will return when done.
830  *
831  * @param   svr           The given server.
832  */
833 EAPI void
834 ecore_con_server_flush(Ecore_Con_Server *svr)
835 {
836    if (!ECORE_MAGIC_CHECK(svr, ECORE_MAGIC_CON_SERVER))
837      {
838         ECORE_MAGIC_FAIL(svr, ECORE_MAGIC_CON_SERVER, "ecore_con_server_flush");
839         return;
840      }
841
842    _ecore_con_server_flush(svr);
843 }
844
845 /**
846  * @}
847  */
848
849 /**
850  * @addtogroup Ecore_Con_Client_Group Ecore Connection Client Functions
851  *
852  * Functions that operate on Ecore connection client objects.
853  *
854  * @{
855  */
856
857 /**
858  * @example ecore_con_client_example.c
859  * Shows how to write a simple client that connects to the example server.
860  */
861
862 /**
863  * Sends the given data to the given client.
864  * @param   cl   The given client.
865  * @param   data The given data.
866  * @param   size Length of the data, in bytes, to send.
867  * @return  The number of bytes sent.  @c 0 will be returned if there is an
868  *          error.
869  */
870 EAPI int
871 ecore_con_client_send(Ecore_Con_Client *cl,
872                       const void       *data,
873                       int               size)
874 {
875    if (!ECORE_MAGIC_CHECK(cl, ECORE_MAGIC_CON_CLIENT))
876      {
877         ECORE_MAGIC_FAIL(cl, ECORE_MAGIC_CON_CLIENT, "ecore_con_client_send");
878         return 0;
879      }
880
881    EINA_SAFETY_ON_TRUE_RETURN_VAL(cl->dead, 0);
882
883    EINA_SAFETY_ON_NULL_RETURN_VAL(data, 0);
884
885    EINA_SAFETY_ON_TRUE_RETURN_VAL(size < 1, 0);
886
887    if (cl->fd_handler)
888      ecore_main_fd_handler_active_set(cl->fd_handler, ECORE_FD_READ | ECORE_FD_WRITE);
889
890    if (cl->host_server && ((cl->host_server->type & ECORE_CON_TYPE) == ECORE_CON_REMOTE_UDP))
891      sendto(cl->host_server->fd, data, size, 0, (struct sockaddr *)cl->client_addr,
892             cl->client_addr_len);
893    else if (cl->buf)
894      {
895         unsigned char *newbuf;
896
897         newbuf = realloc(cl->buf, cl->buf_size + size);
898         EINA_SAFETY_ON_NULL_RETURN_VAL(newbuf, 0);
899
900         cl->buf = newbuf;
901
902         memcpy(cl->buf + cl->buf_size, data, size);
903         cl->buf_size += size;
904      }
905    else
906      {
907         cl->buf = malloc(size);
908         EINA_SAFETY_ON_NULL_RETURN_VAL(cl->buf, 0);
909
910         cl->buf_size = size;
911         memcpy(cl->buf, data, size);
912      }
913
914    return size;
915 }
916
917 /**
918  * Retrieves the server representing the socket the client has
919  * connected to.
920  * @param   cl The given client.
921  * @return  The server that the client connected to.
922  */
923 EAPI Ecore_Con_Server *
924 ecore_con_client_server_get(Ecore_Con_Client *cl)
925 {
926    if (!ECORE_MAGIC_CHECK(cl, ECORE_MAGIC_CON_CLIENT))
927      {
928         ECORE_MAGIC_FAIL(cl, ECORE_MAGIC_CON_CLIENT,
929                          "ecore_con_client_server_get");
930         return NULL;
931      }
932
933    return cl->host_server;
934 }
935
936 /**
937  * Returns whether the client is still connected
938  * @param   cl The given client.
939  * @return  #EINA_TRUE if connected, else EINA_FALSE
940  */
941 EAPI Eina_Bool
942 ecore_con_client_connected_get(Ecore_Con_Client *cl)
943 {
944    if (!ECORE_MAGIC_CHECK(cl, ECORE_MAGIC_CON_CLIENT))
945      {
946         ECORE_MAGIC_FAIL(cl, ECORE_MAGIC_CON_CLIENT,
947                          "ecore_con_client_connected_get");
948         return EINA_FALSE;
949      }
950
951    return !cl->dead;
952 }
953
954 /**
955  * Set the time after which the client will be disconnected when inactive
956  * @param cl The client object
957  * @param timeout The timeout, in seconds, to disconnect after
958  * This function is used to set the idle timeout on a client.  A value of < 1
959  * disables the idle timeout.
960  */
961 EAPI void
962 ecore_con_client_timeout_set(Ecore_Con_Client *cl,
963                              double            timeout)
964 {
965    if (!ECORE_MAGIC_CHECK(cl, ECORE_MAGIC_CON_CLIENT))
966      {
967         ECORE_MAGIC_FAIL(cl, ECORE_MAGIC_CON_CLIENT,
968                          "ecore_con_client_timeout_set");
969         return;
970      }
971
972    cl->disconnect_time = timeout;
973
974    _ecore_con_cl_timer_update(cl);
975 }
976
977 /**
978  * Get the default time after which the client will be disconnected when inactive
979  * @param cl The client object
980  * @return The timeout, in seconds, to disconnect after
981  * This function is used to get the idle timeout for a client.  A value of < 1
982  * means the idle timeout is disabled.
983  */
984 EAPI double
985 ecore_con_client_timeout_get(Ecore_Con_Client *cl)
986 {
987    if (!ECORE_MAGIC_CHECK(cl, ECORE_MAGIC_CON_CLIENT))
988      {
989         ECORE_MAGIC_FAIL(cl, ECORE_MAGIC_CON_CLIENT, "ecore_con_client_timeout_get");
990         return 0;
991      }
992
993    return cl->disconnect_time;
994 }
995
996 /**
997  * Closes the connection and frees memory allocated to the given client.
998  * @param   cl The given client.
999  * @return  Data associated with the client.
1000  */
1001 EAPI void *
1002 ecore_con_client_del(Ecore_Con_Client *cl)
1003 {
1004    void *data = NULL;
1005
1006    if (!ECORE_MAGIC_CHECK(cl, ECORE_MAGIC_CON_CLIENT))
1007      {
1008         ECORE_MAGIC_FAIL(cl, ECORE_MAGIC_CON_CLIENT, "ecore_con_client_del");
1009         return NULL;
1010      }
1011
1012    if (cl->client_addr)
1013      free(cl->client_addr);
1014    cl->client_addr = NULL;
1015
1016    data = cl->data;
1017    cl->delete_me = EINA_TRUE;
1018    if (cl->event_count > 0)
1019      {
1020         if (cl->fd_handler)
1021           {
1022              ecore_main_fd_handler_del(cl->fd_handler);
1023              cl->fd_handler = NULL;
1024           }
1025      }
1026    else
1027      {
1028         if (cl->host_server)
1029           {
1030              cl->host_server->clients = eina_list_remove(cl->host_server->clients, cl);
1031              --cl->host_server->client_count;
1032           }
1033
1034         _ecore_con_client_free(cl);
1035      }
1036
1037    return data;
1038 }
1039
1040 /**
1041  * Sets the data associated with the given client to @p data.
1042  * @param   cl   The given client.
1043  * @param   data What to set the data to.
1044  */
1045 EAPI void
1046 ecore_con_client_data_set(Ecore_Con_Client *cl,
1047                           const void       *data)
1048 {
1049    if (!ECORE_MAGIC_CHECK(cl, ECORE_MAGIC_CON_CLIENT))
1050      {
1051         ECORE_MAGIC_FAIL(cl,
1052                          ECORE_MAGIC_CON_CLIENT,
1053                          "ecore_con_client_data_set");
1054         return;
1055      }
1056
1057    cl->data = (void *)data;
1058 }
1059
1060 /**
1061  * Retrieves the data associated with the given client.
1062  * @param   cl The given client.
1063  * @return  The data associated with @p cl.
1064  */
1065 EAPI void *
1066 ecore_con_client_data_get(Ecore_Con_Client *cl)
1067 {
1068    if (!ECORE_MAGIC_CHECK(cl, ECORE_MAGIC_CON_CLIENT))
1069      {
1070         ECORE_MAGIC_FAIL(cl,
1071                          ECORE_MAGIC_CON_CLIENT,
1072                          "ecore_con_client_data_get");
1073         return NULL;
1074      }
1075
1076    return cl->data;
1077 }
1078
1079 /**
1080  * Gets the IP address of a cleint that has connected.
1081  *
1082  * @param   cl            The given client.
1083  * @return  A pointer to an internal string that contains the IP address of
1084  *          the connected client in the form "XXX.YYY.ZZZ.AAA" IP notation.
1085  *          This string should not be modified or trusted to stay valid after
1086  *          deletion for the @p cl object. If no IP is known NULL is returned.
1087  */
1088 EAPI const char *
1089 ecore_con_client_ip_get(Ecore_Con_Client *cl)
1090 {
1091    if (!ECORE_MAGIC_CHECK(cl, ECORE_MAGIC_CON_CLIENT))
1092      {
1093         ECORE_MAGIC_FAIL(cl, ECORE_MAGIC_CON_CLIENT, "ecore_con_client_ip_get");
1094         return NULL;
1095      }
1096    if (!cl->ip)
1097      cl->ip = _ecore_con_pretty_ip(cl->client_addr, cl->client_addr_len);
1098
1099    return cl->ip;
1100 }
1101
1102 /**
1103  * @brief Check how long a client has been connected
1104  * @param cl The client to check
1105  * @return The total time, in seconds, that the client has been connected to the server
1106  * This function is used to find out how long a client has been connected for.
1107  */
1108 EAPI double
1109 ecore_con_client_uptime_get(Ecore_Con_Client *cl)
1110 {
1111    if (!ECORE_MAGIC_CHECK(cl, ECORE_MAGIC_CON_CLIENT))
1112      {
1113         ECORE_MAGIC_FAIL(cl, ECORE_MAGIC_CON_CLIENT, "ecore_con_client_uptime_get");
1114         return -1;
1115      }
1116
1117    return ecore_time_get() - cl->start_time;
1118 }
1119
1120 /**
1121  * Flushes all pending data to the given client. Will return when done.
1122  *
1123  * @param   cl            The given client.
1124  */
1125 EAPI void
1126 ecore_con_client_flush(Ecore_Con_Client *cl)
1127 {
1128    if (!ECORE_MAGIC_CHECK(cl, ECORE_MAGIC_CON_CLIENT))
1129      {
1130         ECORE_MAGIC_FAIL(cl, ECORE_MAGIC_CON_CLIENT, "ecore_con_client_flush");
1131         return;
1132      }
1133
1134    _ecore_con_client_flush(cl);
1135 }
1136
1137 /**
1138  * @}
1139  */
1140
1141 static void
1142 _ecore_con_server_free(Ecore_Con_Server *svr)
1143 {
1144    Ecore_Con_Client *cl;
1145    double t_start, t;
1146
1147    if ((!svr->write_buf) && svr->delete_me && (!svr->dead) && (svr->event_count < 1))
1148      {
1149         /* this is a catch-all for cases when a server is not properly killed. */
1150
1151         Ecore_Con_Event_Server_Del *e;
1152
1153         svr->dead = EINA_TRUE;
1154         e = calloc(1, sizeof(Ecore_Con_Event_Server_Del));
1155         EINA_SAFETY_ON_NULL_RETURN(e);
1156
1157         svr->event_count++;
1158         e->server = svr;
1159         ecore_event_add(ECORE_CON_EVENT_SERVER_DEL, e,
1160                         _ecore_con_event_server_del_free, NULL);
1161         return;
1162      }
1163
1164    if (svr->event_count > 0)
1165      return;
1166    ECORE_MAGIC_SET(svr, ECORE_MAGIC_NONE);
1167    t_start = ecore_time_get();
1168    while ((svr->write_buf) && (!svr->dead))
1169      {
1170         _ecore_con_server_flush(svr);
1171         t = ecore_time_get();
1172         if ((t - t_start) > 0.5)
1173           {
1174              WRN("ECORE_CON: EEK - stuck in _ecore_con_server_free() trying\n"
1175                  "  to flush data out from the server, and have been for\n"
1176                  "  %1.1f seconds. This is taking too long. Aborting flush.",
1177                  (t - t_start));
1178              break;
1179           }
1180      }
1181
1182    if (svr->write_buf)
1183      free(svr->write_buf);
1184
1185    EINA_LIST_FREE(svr->clients, cl)
1186      _ecore_con_client_free(cl);
1187    if ((svr->created) && (svr->path) && (svr->ppid == getpid()))
1188      unlink(svr->path);
1189
1190    ecore_con_ssl_server_shutdown(svr);
1191    if (svr->fd >= 0)
1192      close(svr->fd);
1193
1194    if (svr->name)
1195      free(svr->name);
1196
1197    if (svr->path)
1198      free(svr->path);
1199
1200    if (svr->ip)
1201      eina_stringshare_del(svr->ip);
1202
1203    if (svr->fd_handler)
1204      ecore_main_fd_handler_del(svr->fd_handler);
1205
1206    servers = eina_list_remove(servers, svr);
1207    svr->data = NULL;
1208    free(svr);
1209 }
1210
1211 static void
1212 _ecore_con_client_free(Ecore_Con_Client *cl)
1213 {
1214    double t_start, t;
1215
1216    if ((!cl->buf) && cl->delete_me && (!cl->dead) && (cl->event_count < 1))
1217      {
1218         /* this is a catch-all for cases when a client is not properly killed. */
1219
1220           /* we lost our client! */
1221            Ecore_Con_Event_Client_Del *e;
1222
1223            cl->dead = EINA_TRUE;
1224            e = calloc(1, sizeof(Ecore_Con_Event_Client_Del));
1225            EINA_SAFETY_ON_NULL_RETURN(e);
1226
1227            cl->event_count++;
1228            _ecore_con_cl_timer_update(cl);
1229            e->client = cl;
1230            ecore_event_add(ECORE_CON_EVENT_CLIENT_DEL, e,
1231                            _ecore_con_event_client_del_free, NULL);
1232            return;
1233      }
1234
1235    if (cl->event_count > 0)
1236      return;
1237    ECORE_MAGIC_SET(cl, ECORE_MAGIC_NONE);
1238    t_start = ecore_time_get();
1239    while ((cl->buf) && (!cl->dead))
1240      {
1241         _ecore_con_client_flush(cl);
1242         t = ecore_time_get();
1243         if ((t - t_start) > 0.5)
1244           {
1245              WRN("EEK - stuck in _ecore_con_client_free() trying\n"
1246                  "  to flush data out from the client, and have been for\n"
1247                  "  %1.1f seconds. This is taking too long. Aborting flush.",
1248                  (t - t_start));
1249              break;
1250           }
1251      }
1252    if (cl->buf)
1253      free(cl->buf);
1254
1255    if (cl->host_server->type & ECORE_CON_SSL)
1256      ecore_con_ssl_client_shutdown(cl);
1257
1258    if (cl->fd >= 0)
1259      close(cl->fd);
1260
1261    if (cl->fd_handler)
1262      ecore_main_fd_handler_del(cl->fd_handler);
1263
1264    if (cl->ip)
1265      eina_stringshare_del(cl->ip);
1266    cl->data = NULL;
1267    free(cl);
1268    return;
1269 }
1270
1271 static void
1272 _ecore_con_server_kill(Ecore_Con_Server *svr)
1273 {
1274    if (!svr->delete_me)
1275      {
1276         Ecore_Con_Event_Server_Del *e;
1277
1278         e = calloc(1, sizeof(Ecore_Con_Event_Server_Del));
1279         EINA_SAFETY_ON_NULL_RETURN(e);
1280
1281         svr->event_count++;
1282         e->server = svr;
1283         ecore_event_add(ECORE_CON_EVENT_SERVER_DEL, e,
1284                         _ecore_con_event_server_del_free, NULL);
1285      }
1286
1287    svr->dead = EINA_TRUE;
1288    if (svr->fd_handler)
1289      ecore_main_fd_handler_del(svr->fd_handler);
1290
1291    svr->fd_handler = NULL;
1292 }
1293
1294 static Eina_Bool
1295 _ecore_con_client_timer(Ecore_Con_Client *cl)
1296 {
1297    ecore_con_client_del(cl);
1298
1299    return ECORE_CALLBACK_CANCEL;
1300 }
1301
1302 static void
1303 _ecore_con_cl_timer_update(Ecore_Con_Client *cl)
1304 {
1305    if (cl->disconnect_time)
1306      {
1307         if (cl->disconnect_time > 0)
1308           {
1309              if (cl->until_deletion)
1310                ecore_timer_interval_set(cl->until_deletion, cl->disconnect_time);
1311              else
1312                cl->until_deletion = ecore_timer_add(cl->disconnect_time, (Ecore_Task_Cb)_ecore_con_client_timer, cl);
1313           }
1314         else if (cl->until_deletion)
1315           {
1316              ecore_timer_del(cl->until_deletion);
1317              cl->until_deletion = NULL;
1318           }
1319      }
1320    else
1321      {
1322         if (cl->host_server->client_disconnect_time > 0)
1323           {
1324              if (cl->until_deletion)
1325                ecore_timer_interval_set(cl->until_deletion, cl->host_server->client_disconnect_time);
1326              else
1327                cl->until_deletion = ecore_timer_add(cl->host_server->client_disconnect_time, (Ecore_Task_Cb)_ecore_con_client_timer, cl);
1328           }
1329         else if (cl->until_deletion)
1330           {
1331              ecore_timer_del(cl->until_deletion);
1332              cl->until_deletion = NULL;
1333           }
1334      }
1335 }
1336
1337 static void
1338 _ecore_con_cb_tcp_listen(void           *data,
1339                          Ecore_Con_Info *net_info)
1340 {
1341    Ecore_Con_Server *svr;
1342    struct linger lin;
1343
1344    svr = data;
1345
1346    if (!net_info)
1347      goto error;
1348
1349    svr->fd = socket(net_info->info.ai_family, net_info->info.ai_socktype,
1350                     net_info->info.ai_protocol);
1351    if (svr->fd < 0)
1352      goto error;
1353
1354    if (fcntl(svr->fd, F_SETFL, O_NONBLOCK) < 0)
1355      goto error;
1356
1357    if (fcntl(svr->fd, F_SETFD, FD_CLOEXEC) < 0)
1358      goto error;
1359
1360    lin.l_onoff = 1;
1361    lin.l_linger = 0;
1362    if (setsockopt(svr->fd, SOL_SOCKET, SO_LINGER, (const void *)&lin,
1363                   sizeof(struct linger)) < 0)
1364      goto error;
1365
1366    if ((svr->type & ECORE_CON_TYPE) == ECORE_CON_REMOTE_NODELAY)
1367      {
1368         int flag = 1;
1369
1370         if (setsockopt(svr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag,
1371                        sizeof(int)) < 0)
1372           goto error;
1373      }
1374
1375    if (bind(svr->fd, net_info->info.ai_addr,
1376             net_info->info.ai_addrlen) < 0)
1377      goto error;
1378
1379    if (listen(svr->fd, 4096) < 0)
1380      goto error;
1381
1382    svr->fd_handler = ecore_main_fd_handler_add(svr->fd, ECORE_FD_READ,
1383                                                _ecore_con_svr_tcp_handler, svr, NULL, NULL);
1384    if (!svr->fd_handler)
1385      goto error;
1386
1387    return;
1388
1389 error:
1390    ecore_con_ssl_server_shutdown(svr);
1391    _ecore_con_server_kill(svr);
1392 }
1393
1394 static void
1395 _ecore_con_cb_udp_listen(void           *data,
1396                          Ecore_Con_Info *net_info)
1397 {
1398    Ecore_Con_Server *svr;
1399    Ecore_Con_Type type;
1400    struct ip_mreq mreq;
1401    struct ipv6_mreq mreq6;
1402    const int on = 1;
1403
1404    svr = data;
1405    type = svr->type;
1406    type &= ECORE_CON_TYPE;
1407
1408    if (!net_info)
1409      goto error;
1410
1411    svr->fd = socket(net_info->info.ai_family, net_info->info.ai_socktype,
1412                     net_info->info.ai_protocol);
1413    if (svr->fd < 0)
1414      goto error;
1415
1416    if (type == ECORE_CON_REMOTE_MCAST)
1417      {
1418         if (net_info->info.ai_family == AF_INET)
1419           {
1420              if (!inet_pton(net_info->info.ai_family, net_info->ip,
1421                             &mreq.imr_multiaddr))
1422                goto error;
1423
1424              mreq.imr_interface.s_addr = htonl(INADDR_ANY);
1425              if (setsockopt(svr->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1426                             (const void *)&mreq, sizeof(mreq)) != 0)
1427                goto error;
1428           }
1429         else if (net_info->info.ai_family == AF_INET6)
1430           {
1431              if (!inet_pton(net_info->info.ai_family, net_info->ip,
1432                             &mreq6.ipv6mr_multiaddr))
1433                goto error;
1434
1435              mreq6.ipv6mr_interface = htonl(INADDR_ANY);
1436              if (setsockopt(svr->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1437                             (const void *)&mreq6, sizeof(mreq6)) != 0)
1438                goto error;
1439           }
1440
1441         if (setsockopt(svr->fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&on,
1442                        sizeof(on)) != 0)
1443           goto error;
1444      }
1445
1446    if (fcntl(svr->fd, F_SETFL, O_NONBLOCK) < 0)
1447      goto error;
1448
1449    if (fcntl(svr->fd, F_SETFD, FD_CLOEXEC) < 0)
1450      goto error;
1451
1452    if (bind(svr->fd, net_info->info.ai_addr,
1453             net_info->info.ai_addrlen) < 0)
1454      goto error;
1455
1456    svr->fd_handler =
1457      ecore_main_fd_handler_add(svr->fd, ECORE_FD_READ,
1458                                _ecore_con_svr_udp_handler, svr, NULL, NULL);
1459    if (!svr->fd_handler)
1460      goto error;
1461
1462    svr->ip = eina_stringshare_add(net_info->ip);
1463
1464    return;
1465
1466 error:
1467    ecore_con_ssl_server_shutdown(svr);
1468    _ecore_con_server_kill(svr);
1469 }
1470
1471 static void
1472 _ecore_con_cb_tcp_connect(void           *data,
1473                           Ecore_Con_Info *net_info)
1474 {
1475    Ecore_Con_Server *svr;
1476    int res;
1477    int curstate = 0;
1478
1479    svr = data;
1480
1481    if (!net_info)
1482      goto error;
1483
1484    svr->fd = socket(net_info->info.ai_family, net_info->info.ai_socktype,
1485                     net_info->info.ai_protocol);
1486    if (svr->fd < 0)
1487      goto error;
1488
1489    if (fcntl(svr->fd, F_SETFL, O_NONBLOCK) < 0)
1490      goto error;
1491
1492    if (fcntl(svr->fd, F_SETFD, FD_CLOEXEC) < 0)
1493      goto error;
1494
1495    if (setsockopt(svr->fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&curstate,
1496                   sizeof(curstate)) < 0)
1497      goto error;
1498
1499    if ((svr->type & ECORE_CON_TYPE) == ECORE_CON_REMOTE_NODELAY)
1500      {
1501         int flag = 1;
1502
1503         if (setsockopt(svr->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag,
1504                        sizeof(int)) < 0)
1505           goto error;
1506      }
1507
1508    res = connect(svr->fd, net_info->info.ai_addr, net_info->info.ai_addrlen);
1509 #ifdef _WIN32
1510    if (res == SOCKET_ERROR)
1511      {
1512         if (WSAGetLastError() != WSAEINPROGRESS)
1513           goto error;
1514
1515 #else
1516    if (res < 0)
1517      {
1518         if (errno != EINPROGRESS)
1519           goto error;
1520
1521 #endif
1522         svr->connecting = EINA_TRUE;
1523         svr->fd_handler =
1524           ecore_main_fd_handler_add(svr->fd, ECORE_FD_READ | ECORE_FD_WRITE,
1525                                     _ecore_con_cl_handler, svr, NULL, NULL);
1526      }
1527    else
1528      svr->fd_handler = ecore_main_fd_handler_add(svr->fd, ECORE_FD_READ,
1529                                                  _ecore_con_cl_handler, svr, NULL, NULL);
1530
1531    if (svr->type & ECORE_CON_SSL)
1532      {
1533         svr->handshaking = EINA_TRUE;
1534         svr->ssl_state = ECORE_CON_SSL_STATE_INIT;
1535         DBG("beginning ssl handshake");
1536         if (ecore_con_ssl_server_init(svr))
1537           goto error;
1538      }
1539
1540    if (!svr->fd_handler)
1541      goto error;
1542
1543    svr->ip = eina_stringshare_add(net_info->ip);
1544
1545    return;
1546
1547 error:
1548    ecore_con_ssl_server_shutdown(svr);
1549    _ecore_con_server_kill(svr);
1550 }
1551
1552 static void
1553 _ecore_con_cb_udp_connect(void           *data,
1554                           Ecore_Con_Info *net_info)
1555 {
1556    Ecore_Con_Server *svr;
1557    int curstate = 0;
1558    int broadcast = 1;
1559    svr = data;
1560
1561    if (!net_info)
1562      goto error;
1563
1564    svr->fd = socket(net_info->info.ai_family, net_info->info.ai_socktype,
1565                     net_info->info.ai_protocol);
1566    if (svr->fd < 0)
1567      goto error;
1568
1569    if (fcntl(svr->fd, F_SETFL, O_NONBLOCK) < 0)
1570      goto error;
1571
1572    if (fcntl(svr->fd, F_SETFD, FD_CLOEXEC) < 0)
1573      goto error;
1574
1575    if ((svr->type & ECORE_CON_TYPE) == ECORE_CON_REMOTE_BROADCAST)
1576      {
1577         if (setsockopt(svr->fd, SOL_SOCKET, SO_BROADCAST,
1578                        (const void *)&broadcast,
1579                        sizeof(broadcast)) < 0)
1580           goto error;
1581      }
1582    else if (setsockopt(svr->fd, SOL_SOCKET, SO_REUSEADDR,
1583                        (const void *)&curstate, sizeof(curstate)) < 0)
1584      goto error;
1585
1586    if (connect(svr->fd, net_info->info.ai_addr, net_info->info.ai_addrlen) < 0)
1587      goto error;
1588
1589    svr->fd_handler = ecore_main_fd_handler_add(svr->fd, ECORE_FD_READ | ECORE_FD_WRITE,
1590                                                _ecore_con_cl_udp_handler, svr, NULL, NULL);
1591
1592    if (!svr->fd_handler)
1593      goto error;
1594
1595    svr->ip = eina_stringshare_add(net_info->ip);
1596
1597    return;
1598
1599 error:
1600    ecore_con_ssl_server_shutdown(svr);
1601    _ecore_con_server_kill(svr);
1602 }
1603
1604 static Ecore_Con_State
1605 svr_try_connect_plain(Ecore_Con_Server *svr)
1606 {
1607    int res;
1608    int so_err = 0;
1609    unsigned int size = sizeof(int);
1610
1611    errno = 0;
1612    res = getsockopt(svr->fd, SOL_SOCKET, SO_ERROR, (void *)&so_err, &size);
1613 #ifdef _WIN32
1614    if (res == SOCKET_ERROR)
1615      so_err = WSAGetLastError();
1616
1617    if ((so_err == WSAEINPROGRESS) && !svr->dead)
1618      return ECORE_CON_INPROGRESS;
1619
1620 #else
1621    if (res < 0)
1622      so_err = errno;
1623
1624    if ((so_err == EINPROGRESS) && !svr->dead)
1625      return ECORE_CON_INPROGRESS;
1626
1627 #endif
1628
1629    if (so_err)
1630      {
1631         /* we lost our server! */
1632         ERR("Connection lost: %s", strerror(so_err));
1633         _ecore_con_server_kill(svr);
1634         return ECORE_CON_DISCONNECTED;
1635      }
1636
1637    if ((!svr->delete_me) && (!svr->handshaking) && svr->connecting)
1638      {
1639         /* we got our server! */
1640          Ecore_Con_Event_Server_Add *e;
1641
1642          svr->connecting = EINA_FALSE;
1643          e = calloc(1, sizeof(Ecore_Con_Event_Server_Add));
1644          EINA_SAFETY_ON_NULL_RETURN_VAL(e, ECORE_CON_CONNECTED);
1645
1646          svr->event_count++;
1647          svr->start_time = ecore_time_get();
1648          e->server = svr;
1649          ecore_event_add(ECORE_CON_EVENT_SERVER_ADD, e,
1650                          _ecore_con_event_server_add_free, NULL);
1651      }
1652
1653    if (svr->fd_handler && (!svr->write_buf))
1654      ecore_main_fd_handler_active_set(svr->fd_handler, ECORE_FD_READ);
1655
1656    if (!svr->dead)
1657      return ECORE_CON_CONNECTED;
1658    else
1659      return ECORE_CON_DISCONNECTED;
1660 }
1661
1662 static const char *
1663 _ecore_con_pretty_ip(struct sockaddr *client_addr,
1664                      socklen_t        size)
1665 {
1666    char ipbuf[INET6_ADDRSTRLEN + 1];
1667
1668    /* show v4mapped address in pretty form */
1669    if (client_addr->sa_family == AF_INET6)
1670      {
1671         struct sockaddr_in6 *sa6;
1672
1673         sa6 = (struct sockaddr_in6 *)client_addr;
1674         if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
1675           {
1676              snprintf(ipbuf, sizeof (ipbuf), "%u.%u.%u.%u",
1677                       sa6->sin6_addr.s6_addr[12],
1678                       sa6->sin6_addr.s6_addr[13],
1679                       sa6->sin6_addr.s6_addr[14],
1680                       sa6->sin6_addr.s6_addr[15]);
1681              return eina_stringshare_add(ipbuf);
1682           }
1683      }
1684
1685    if (getnameinfo(client_addr, size, ipbuf, sizeof (ipbuf), NULL, 0, NI_NUMERICHOST))
1686      return eina_stringshare_add("0.0.0.0");
1687
1688    ipbuf[sizeof (ipbuf) - 1] = 0;
1689    return eina_stringshare_add(ipbuf);
1690 }
1691
1692 static Eina_Bool
1693 _ecore_con_svr_tcp_handler(void                        *data,
1694                            Ecore_Fd_Handler *fd_handler __UNUSED__)
1695 {
1696    Ecore_Con_Server *svr;
1697    Ecore_Con_Client *cl = NULL;
1698    unsigned char client_addr[256];
1699    unsigned int client_addr_len = sizeof(client_addr);
1700    int new_fd;
1701
1702    svr = data;
1703    if (svr->dead)
1704      return ECORE_CALLBACK_RENEW;
1705
1706    if (svr->delete_me)
1707      return ECORE_CALLBACK_RENEW;
1708
1709    if ((svr->client_limit >= 0) && (!svr->reject_excess_clients) &&
1710        (svr->client_count >= (unsigned int)svr->client_limit))
1711      return ECORE_CALLBACK_RENEW;
1712
1713    /* a new client */
1714    memset(&client_addr, 0, client_addr_len);
1715    new_fd = accept(svr->fd, (struct sockaddr *)&client_addr, (socklen_t *)&client_addr_len);
1716    if (new_fd < 0)
1717      /* error! */
1718      return ECORE_CALLBACK_RENEW;
1719
1720    if ((svr->client_limit >= 0) && (svr->reject_excess_clients) &&
1721        (svr->client_count >= (unsigned int)svr->client_limit))
1722      goto error;
1723
1724    cl = calloc(1, sizeof(Ecore_Con_Client));
1725    if (!cl)
1726      goto error;
1727
1728    fcntl(new_fd, F_SETFL, O_NONBLOCK);
1729    fcntl(new_fd, F_SETFD, FD_CLOEXEC);
1730    cl->fd = new_fd;
1731    cl->host_server = svr;
1732
1733    cl->fd_handler = ecore_main_fd_handler_add(cl->fd, ECORE_FD_READ,
1734                                               _ecore_con_svr_cl_handler, cl, NULL, NULL);
1735    ECORE_MAGIC_SET(cl, ECORE_MAGIC_CON_CLIENT);
1736
1737    if (svr->type & ECORE_CON_SSL)
1738      {
1739         cl->handshaking = EINA_TRUE;
1740         cl->ssl_state = ECORE_CON_SSL_STATE_INIT;
1741         if (ecore_con_ssl_client_init(cl))
1742           goto error;
1743      }
1744
1745    cl->client_addr = malloc(client_addr_len);
1746    if (!cl->client_addr)
1747      goto error;
1748    cl->client_addr_len = client_addr_len;
1749    memcpy(cl->client_addr, &client_addr, client_addr_len);
1750    
1751    svr->clients = eina_list_append(svr->clients, cl);
1752    svr->client_count++;
1753    
1754    if ((!cl->delete_me) && (!cl->handshaking))
1755      {
1756         Ecore_Con_Event_Client_Add *e;
1757
1758         e = calloc(1, sizeof(Ecore_Con_Event_Client_Add));
1759         EINA_SAFETY_ON_NULL_RETURN_VAL(e, ECORE_CALLBACK_RENEW);
1760
1761         cl->event_count++;
1762         _ecore_con_cl_timer_update(cl);
1763         e->client = cl;
1764         ecore_event_add(ECORE_CON_EVENT_CLIENT_ADD, e,
1765                         _ecore_con_event_client_add_free, NULL);
1766
1767      }
1768
1769    return ECORE_CALLBACK_RENEW;
1770
1771 error:
1772    close(new_fd);
1773    if (cl->fd_handler)
1774      ecore_main_fd_handler_del(cl->fd_handler);
1775    return ECORE_CALLBACK_RENEW;
1776 }
1777
1778 static void
1779 _ecore_con_cl_read(Ecore_Con_Server *svr)
1780 {
1781    DBG("svr=%p", svr);
1782    int num = 0;
1783    Eina_Bool lost_server = EINA_TRUE;
1784    unsigned char buf[READBUFSIZ];
1785
1786    /* only possible with non-ssl connections */
1787    if (svr->connecting && (svr_try_connect_plain(svr) != ECORE_CON_CONNECTED))
1788      return;
1789
1790    if (svr->handshaking)
1791      {
1792         DBG("Continuing ssl handshake");
1793         if (!ecore_con_ssl_server_init(svr))
1794           lost_server = EINA_FALSE;
1795      }
1796
1797    if (!(svr->type & ECORE_CON_SSL))
1798      {
1799         errno = 0;
1800         num = read(svr->fd, buf, sizeof(buf));
1801         if ((num > 0) || (errno == EAGAIN))
1802           lost_server = EINA_FALSE;
1803      }
1804    else
1805      {
1806        num = ecore_con_ssl_server_read(svr, buf, sizeof(buf));
1807          if (num > 0)
1808            lost_server = EINA_FALSE;
1809      }
1810
1811    if (lost_server)
1812      _ecore_con_server_kill(svr);
1813
1814    if ((num > 0) && (!svr->delete_me))
1815    {
1816       Ecore_Con_Event_Server_Data *e;
1817
1818       e = malloc(sizeof(Ecore_Con_Event_Server_Data));
1819       EINA_SAFETY_ON_NULL_RETURN(e);
1820
1821       svr->event_count++;
1822       e->server = svr;
1823       e->data = malloc(num);
1824       if (!e->data)
1825         {
1826            ERR("alloc!");
1827            free(e);
1828            return;
1829         }
1830       memcpy(e->data, buf, num);
1831       e->size = num;
1832       ecore_event_add(ECORE_CON_EVENT_SERVER_DATA, e,
1833                       _ecore_con_event_server_data_free, NULL);
1834    }
1835
1836
1837 }
1838
1839 static Eina_Bool
1840 _ecore_con_cl_handler(void             *data,
1841                       Ecore_Fd_Handler *fd_handler)
1842 {
1843    Ecore_Con_Server *svr;
1844    Eina_Bool want_read, want_write;
1845
1846    svr = data;
1847    if (svr->dead)
1848      return ECORE_CALLBACK_RENEW;
1849
1850    if (svr->delete_me)
1851      return ECORE_CALLBACK_RENEW;
1852
1853    want_read = ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_READ);
1854    want_write = ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_WRITE);
1855
1856    if (svr->handshaking && (want_read || want_write))
1857      {
1858         DBG("Continuing ssl handshake: preparing to %s...", want_read ? "read" : "write");
1859 #ifdef ISCOMFITOR
1860         if (want_read)
1861           {
1862              char buf[READBUFSIZ];
1863              ssize_t len;
1864              len = recv(svr->fd, buf, sizeof(buf), MSG_DONTWAIT | MSG_PEEK);
1865              DBG("%zu bytes in buffer", len);
1866           }
1867 #endif
1868         if (ecore_con_ssl_server_init(svr))
1869           {
1870              ERR("ssl handshaking failed!");
1871              svr->handshaking = EINA_FALSE;
1872              Ecore_Con_Event_Server_Del *e;
1873
1874              e = calloc(1, sizeof(Ecore_Con_Event_Server_Del));
1875              EINA_SAFETY_ON_NULL_RETURN_VAL(e, ECORE_CALLBACK_RENEW);
1876
1877              svr->event_count++;
1878              e->server = svr;
1879              ecore_event_add(ECORE_CON_EVENT_SERVER_DEL, e,
1880                              _ecore_con_event_server_del_free, NULL);
1881           }
1882         else if (!svr->ssl_state)
1883           {
1884              /* we got our server! */
1885               Ecore_Con_Event_Server_Add *e;
1886
1887               svr->connecting = EINA_FALSE;
1888               e = calloc(1, sizeof(Ecore_Con_Event_Server_Add));
1889               EINA_SAFETY_ON_NULL_RETURN_VAL(e, ECORE_CALLBACK_RENEW);
1890
1891               svr->event_count++;
1892               svr->start_time = ecore_time_get();
1893               e->server = svr;
1894               ecore_event_add(ECORE_CON_EVENT_SERVER_ADD, e,
1895                               _ecore_con_event_server_add_free, NULL);
1896           }
1897      }
1898    else if (want_read)
1899      _ecore_con_cl_read(svr);
1900    else if (want_write) /* only possible with non-ssl connections */
1901      {
1902         if (svr->connecting && (!svr_try_connect_plain(svr)))
1903           return ECORE_CALLBACK_RENEW;
1904
1905         _ecore_con_server_flush(svr);
1906      }
1907
1908    return ECORE_CALLBACK_RENEW;
1909 }
1910
1911 static Eina_Bool
1912 _ecore_con_cl_udp_handler(void             *data,
1913                           Ecore_Fd_Handler *fd_handler)
1914 {
1915    Ecore_Con_Event_Server_Data *e;
1916    unsigned char *inbuf;
1917    unsigned char buf[READBUFSIZ];
1918    int num;
1919    Ecore_Con_Server *svr;
1920    Eina_Bool want_read, want_write;
1921
1922    want_read = ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_READ);
1923    want_write = ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_WRITE);
1924
1925    svr = data;
1926    if (svr->dead || svr->delete_me || ((!want_read) && (!want_write)))
1927      return ECORE_CALLBACK_RENEW;
1928
1929    if (want_write)
1930      {
1931         _ecore_con_server_flush(svr);
1932         return ECORE_CALLBACK_RENEW;
1933      }
1934
1935    errno = 0;
1936    num = read(svr->fd, buf, READBUFSIZ);
1937
1938    if ((errno == EIO) || (errno == EBADF) || (errno == EPIPE) || (errno == EINVAL) ||
1939        (errno == ENOSPC) || (errno == ECONNREFUSED))
1940      _ecore_con_server_kill(svr);
1941
1942    if ((num < 1) || (svr->delete_me))
1943      return ECORE_CALLBACK_RENEW;
1944
1945    inbuf = malloc(num);
1946    if (!inbuf)
1947      return ECORE_CALLBACK_RENEW;
1948
1949    memcpy(inbuf, buf, num);
1950
1951    e = calloc(1, sizeof(Ecore_Con_Event_Server_Data));
1952    EINA_SAFETY_ON_NULL_RETURN_VAL(e, ECORE_CALLBACK_RENEW);
1953
1954    svr->event_count++;
1955    e->server = svr;
1956    e->data = inbuf;
1957    e->size = num;
1958    ecore_event_add(ECORE_CON_EVENT_SERVER_DATA, e,
1959                    _ecore_con_event_server_data_free, NULL);
1960
1961    return ECORE_CALLBACK_RENEW;
1962 }
1963
1964 static Eina_Bool
1965 _ecore_con_svr_udp_handler(void             *data,
1966                            Ecore_Fd_Handler *fd_handler)
1967 {
1968    unsigned char buf[READBUFSIZ];
1969    unsigned char client_addr[256];
1970    unsigned int client_addr_len = sizeof(client_addr);
1971    int num;
1972    Ecore_Con_Server *svr;
1973    Ecore_Con_Client *cl = NULL;
1974
1975    svr = data;
1976
1977    if (svr->delete_me || svr->dead) 
1978      return ECORE_CALLBACK_RENEW;
1979
1980    if (ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_WRITE))
1981      {
1982         _ecore_con_client_flush(cl);
1983         return ECORE_CALLBACK_RENEW;
1984      }
1985
1986    if (!ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_READ))
1987      return ECORE_CALLBACK_RENEW;
1988
1989    errno = 0;
1990 #ifdef _WIN32
1991    num = fcntl(svr->fd, F_SETFL, O_NONBLOCK);
1992    if (num >= 0)
1993      num = recvfrom(svr->fd, buf, sizeof(buf), 0,
1994                 (struct sockaddr *)&client_addr,
1995                 &client_addr_len);
1996
1997 #else
1998    num = recvfrom(svr->fd, buf, sizeof(buf), MSG_DONTWAIT,
1999               (struct sockaddr *)&client_addr,
2000               &client_addr_len);
2001 #endif
2002
2003    if ((errno == EIO) || (errno == EBADF) || (errno == EPIPE) ||
2004        (errno == EINVAL) || (errno == ENOSPC) || (errno == ECONNREFUSED))
2005      {
2006         if (!svr->delete_me)
2007           {
2008 /* we lost our client! */
2009               Ecore_Con_Event_Client_Del *e;
2010
2011               e = calloc(1, sizeof(Ecore_Con_Event_Client_Del));
2012               EINA_SAFETY_ON_NULL_RETURN_VAL(e, ECORE_CALLBACK_RENEW);
2013
2014               svr->event_count++;
2015               /* be explicit here */
2016               e->client = NULL;
2017               ecore_event_add(ECORE_CON_EVENT_CLIENT_DEL, e,
2018                               _ecore_con_event_client_del_free, NULL);
2019           }
2020
2021         svr->dead = EINA_TRUE;
2022         svr->fd_handler = NULL;
2023         return ECORE_CALLBACK_CANCEL;
2024      }
2025
2026
2027 /* Create a new client for use in the client data event */
2028    cl = calloc(1, sizeof(Ecore_Con_Client));
2029    EINA_SAFETY_ON_NULL_RETURN_VAL(cl, ECORE_CALLBACK_RENEW);
2030
2031    cl->host_server = svr;
2032    cl->client_addr = malloc(client_addr_len);
2033    if (!cl->client_addr)
2034      {
2035         free(cl);
2036         return ECORE_CALLBACK_RENEW;
2037      }
2038    cl->client_addr_len = client_addr_len;
2039
2040    memcpy(cl->client_addr, &client_addr, client_addr_len);
2041    ECORE_MAGIC_SET(cl, ECORE_MAGIC_CON_CLIENT);
2042    svr->clients = eina_list_append(svr->clients, cl);
2043    svr->client_count++;
2044
2045    { /* indent to keep it all nicely separated */
2046       Ecore_Con_Event_Client_Add *add;
2047
2048       add = calloc(1, sizeof(Ecore_Con_Event_Client_Add));
2049       EINA_SAFETY_ON_NULL_RETURN_VAL(add, ECORE_CALLBACK_RENEW);
2050
2051       /*cl->event_count++;*/
2052       add->client = cl;
2053       _ecore_con_cl_timer_update(cl);
2054       ecore_event_add(ECORE_CON_EVENT_CLIENT_ADD, add,
2055                       _ecore_con_event_client_add_free, NULL);
2056    }
2057
2058
2059    {
2060       Ecore_Con_Event_Client_Data *e;
2061       e = calloc(1, sizeof(Ecore_Con_Event_Client_Data));
2062       EINA_SAFETY_ON_NULL_RETURN_VAL(e, ECORE_CALLBACK_RENEW);
2063
2064       svr->event_count++;
2065       _ecore_con_cl_timer_update(cl);
2066       e->client = cl;
2067       e->data = malloc(num);
2068       if (!e->data)
2069         {
2070            free(cl->client_addr);
2071            free(cl);
2072            return ECORE_CALLBACK_RENEW;
2073         }
2074
2075       memcpy(e->data, buf, num);
2076       e->size = num;
2077       ecore_event_add(ECORE_CON_EVENT_CLIENT_DATA, e,
2078                       _ecore_con_event_client_data_free, NULL);
2079    }
2080
2081    return ECORE_CALLBACK_RENEW;
2082 }
2083
2084 static void
2085 _ecore_con_svr_cl_read(Ecore_Con_Client *cl)
2086 {
2087    DBG("cl=%p", cl);
2088    int num = 0;
2089    Eina_Bool lost_client = EINA_TRUE;
2090    unsigned char buf[READBUFSIZ];
2091
2092    if (cl->handshaking)
2093      {
2094         /* add an extra handshake attempt just before read, even though
2095          * read also attempts to handshake, to try to finish sooner
2096          */
2097         if (ecore_con_ssl_client_init(cl))
2098           lost_client = EINA_FALSE;
2099
2100         _ecore_con_cl_timer_update(cl);
2101      }
2102
2103    if (!(cl->host_server->type & ECORE_CON_SSL))
2104      {
2105         errno = 0;
2106         num = read(cl->fd, buf, sizeof(buf));
2107         if ((num > 0) || (errno == EAGAIN))
2108           lost_client = EINA_FALSE;
2109      }
2110    else
2111      {
2112         num = ecore_con_ssl_client_read(cl, buf, sizeof(buf));
2113         if (num > 0)
2114           lost_client = EINA_FALSE;
2115      }
2116
2117    if (lost_client)
2118      {
2119         if (!cl->delete_me)
2120           {
2121              /* we lost our client! */
2122               Ecore_Con_Event_Client_Del *e;
2123
2124               e = calloc(1, sizeof(Ecore_Con_Event_Client_Del));
2125               EINA_SAFETY_ON_NULL_RETURN(e);
2126
2127               cl->event_count++;
2128               _ecore_con_cl_timer_update(cl);
2129               e->client = cl;
2130               ecore_event_add(ECORE_CON_EVENT_CLIENT_DEL, e,
2131                               _ecore_con_event_client_del_free, NULL);
2132           }
2133         INF("Lost client %s", (cl->ip) ? cl->ip : "");
2134         cl->dead = EINA_TRUE;
2135         if (cl->fd_handler)
2136           ecore_main_fd_handler_del(cl->fd_handler);
2137
2138         cl->fd_handler = NULL;
2139         return;
2140      }
2141
2142    if ((num > 0) && (!cl->delete_me))
2143      {
2144         Ecore_Con_Event_Client_Data *e;
2145
2146         e = malloc(sizeof(Ecore_Con_Event_Client_Data));
2147         EINA_SAFETY_ON_NULL_RETURN(e);
2148
2149         cl->event_count++;
2150         _ecore_con_cl_timer_update(cl);
2151         e->client = cl;
2152         e->data = malloc(num);
2153         if (!e->data)
2154           {
2155              ERR("alloc!");
2156              free(e);
2157              return;
2158           }
2159         memcpy(e->data, buf, num);
2160         e->size = num;
2161         ecore_event_add(ECORE_CON_EVENT_CLIENT_DATA, e,
2162                         _ecore_con_event_client_data_free, NULL);
2163      }
2164
2165
2166 }
2167
2168 static Eina_Bool
2169 _ecore_con_svr_cl_handler(void             *data,
2170                           Ecore_Fd_Handler *fd_handler)
2171 {
2172    Ecore_Con_Client *cl;
2173
2174    cl = data;
2175    if (cl->dead)
2176      return ECORE_CALLBACK_RENEW;
2177
2178    if (cl->delete_me)
2179      return ECORE_CALLBACK_RENEW;
2180
2181    if (cl->handshaking && ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_READ | ECORE_FD_WRITE))
2182      {
2183         if (ecore_con_ssl_client_init(cl))
2184           {
2185              ERR("ssl handshaking failed!");
2186              cl->handshaking = EINA_FALSE;
2187              /* we lost our client! */
2188              Ecore_Con_Event_Client_Del *e;
2189
2190              cl->dead = EINA_TRUE;
2191              INF("Lost client %s", (cl->ip) ? cl->ip : "");
2192              e = calloc(1, sizeof(Ecore_Con_Event_Client_Del));
2193              EINA_SAFETY_ON_NULL_RETURN_VAL(e, ECORE_CALLBACK_RENEW);
2194
2195              cl->event_count++;
2196              _ecore_con_cl_timer_update(cl);
2197              e->client = cl;
2198              ecore_event_add(ECORE_CON_EVENT_CLIENT_DEL, e,
2199                              _ecore_con_event_client_del_free, NULL);
2200           }
2201         else if (!cl->ssl_state)
2202           {
2203              Ecore_Con_Event_Client_Add *e;
2204
2205              e = calloc(1, sizeof(Ecore_Con_Event_Client_Add));
2206              EINA_SAFETY_ON_NULL_RETURN_VAL(e, ECORE_CALLBACK_RENEW);
2207
2208              e->client = cl;
2209              cl->event_count++;
2210              _ecore_con_cl_timer_update(cl);
2211              ecore_event_add(ECORE_CON_EVENT_CLIENT_ADD, e,
2212                              _ecore_con_event_client_add_free, NULL);
2213           }
2214      }
2215    else if (ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_READ))
2216      _ecore_con_svr_cl_read(cl);
2217
2218    else if (ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_WRITE))
2219      _ecore_con_client_flush(cl);
2220
2221    return ECORE_CALLBACK_RENEW;
2222 }
2223
2224 static void
2225 _ecore_con_server_flush(Ecore_Con_Server *svr)
2226 {
2227    int count, num;
2228
2229    if (!svr->write_buf)
2230      return;
2231
2232    /* check whether we need to write anything at all.
2233     * we must not write zero bytes with SSL_write() since it
2234     * causes undefined behaviour
2235     */
2236    if (svr->write_buf_size == svr->write_buf_offset)
2237      return;
2238
2239    num = svr->write_buf_size - svr->write_buf_offset;
2240
2241    if (svr->handshaking)
2242      {
2243         DBG("Continuing ssl handshake");
2244         if (ecore_con_ssl_server_init(svr))
2245           _ecore_con_server_kill(svr);
2246         return;
2247      }
2248
2249    if (!(svr->type & ECORE_CON_SSL))
2250      count = write(svr->fd, svr->write_buf + svr->write_buf_offset, num);
2251    else
2252      count = ecore_con_ssl_server_write(svr, svr->write_buf + svr->write_buf_offset, num);
2253
2254    if (count < 0)
2255      {
2256         /* we lost our server! */
2257          _ecore_con_server_kill(svr);
2258          return;
2259      }
2260
2261    svr->write_buf_offset += count;
2262    if (svr->write_buf_offset >= svr->write_buf_size)
2263      {
2264         svr->write_buf_size = 0;
2265         svr->write_buf_offset = 0;
2266         free(svr->write_buf);
2267         svr->write_buf = NULL;
2268         if (svr->fd_handler)
2269           ecore_main_fd_handler_active_set(svr->fd_handler, ECORE_FD_READ);
2270      }
2271    else if (count < num)
2272      ecore_main_fd_handler_active_set(svr->fd_handler, ECORE_FD_WRITE);
2273 }
2274
2275 static void
2276 _ecore_con_client_flush(Ecore_Con_Client *cl)
2277 {
2278    int num, count = 0;
2279
2280    if (!cl->buf)
2281      return;
2282
2283    if (cl->handshaking)
2284      {
2285         if (ecore_con_ssl_client_init(cl))
2286           count = -1;
2287
2288         _ecore_con_cl_timer_update(cl);
2289      }
2290
2291    if (!count)
2292      {
2293         num = cl->buf_size - cl->buf_offset;
2294         if (!(cl->host_server->type & ECORE_CON_SSL))
2295           count = write(cl->fd, cl->buf + cl->buf_offset, num);
2296         else
2297           count = ecore_con_ssl_client_write(cl, cl->buf + cl->buf_offset, num);
2298      }
2299
2300    if (count < 0)
2301      {
2302         if ((errno == EIO) || (errno == EBADF) || (errno == EPIPE) ||
2303             (errno == EINVAL) || (errno == ENOSPC) || (errno == ECONNREFUSED))
2304           if (!cl->delete_me)
2305             {
2306                /* we lost our client! */
2307                 Ecore_Con_Event_Client_Del *e;
2308
2309                 e = calloc(1, sizeof(Ecore_Con_Event_Client_Del));
2310                 EINA_SAFETY_ON_NULL_RETURN(e);
2311
2312                 cl->event_count++;
2313                 _ecore_con_cl_timer_update(cl);
2314                 e->client = cl;
2315                 ecore_event_add(ECORE_CON_EVENT_CLIENT_DEL, e,
2316                                 _ecore_con_event_client_del_free, NULL);
2317
2318                 cl->dead = EINA_TRUE;
2319                 INF("Lost client %s", (cl->ip) ? cl->ip : "");
2320                 if (cl->fd_handler)
2321                   ecore_main_fd_handler_del(cl->fd_handler);
2322
2323                 cl->fd_handler = NULL;
2324             }
2325
2326         return;
2327      }
2328
2329    cl->buf_offset += count;
2330    if (cl->buf_offset >= cl->buf_size)
2331      {
2332         cl->buf_size = 0;
2333         cl->buf_offset = 0;
2334         free(cl->buf);
2335         cl->buf = NULL;
2336         if (cl->fd_handler)
2337           ecore_main_fd_handler_active_set(cl->fd_handler, ECORE_FD_READ);
2338      }
2339    else if (count < num)
2340      ecore_main_fd_handler_active_set(cl->fd_handler, ECORE_FD_WRITE);
2341 }
2342
2343 static void
2344 _ecore_con_event_client_add_free(void *data __UNUSED__,
2345                                  void      *ev)
2346 {
2347    Ecore_Con_Event_Client_Add *e;
2348
2349    e = ev;
2350    e->client->event_count--;
2351    if ((e->client->event_count <= 0) &&
2352        (e->client->delete_me))
2353      ecore_con_client_del(e->client);
2354
2355    free(e);
2356 }
2357
2358 static void
2359 _ecore_con_event_client_del_free(void *data __UNUSED__,
2360                                  void      *ev)
2361 {
2362    Ecore_Con_Event_Client_Del *e;
2363
2364    e = ev;
2365    e->client->event_count--;
2366    if ((e->client->event_count <= 0) && (e->client->delete_me))
2367      ecore_con_client_del(e->client);
2368
2369    free(e);
2370 }
2371
2372 static void
2373 _ecore_con_event_client_data_free(void *data __UNUSED__,
2374                                   void      *ev)
2375 {
2376    Ecore_Con_Event_Client_Data *e;
2377
2378    e = ev;
2379    e->client->event_count--;
2380    if (e->data)
2381      free(e->data);
2382
2383    if (((e->client->event_count <= 0) && (e->client->delete_me)) ||
2384        ((e->client->host_server &&
2385          ((e->client->host_server->type & ECORE_CON_TYPE) == ECORE_CON_REMOTE_UDP ||
2386           (e->client->host_server->type & ECORE_CON_TYPE) == ECORE_CON_REMOTE_MCAST))))
2387      ecore_con_client_del(e->client);
2388
2389    free(e);
2390 }
2391
2392 static void
2393 _ecore_con_event_server_add_free(void *data __UNUSED__,
2394                                  void      *ev)
2395 {
2396    Ecore_Con_Event_Server_Add *e;
2397
2398    e = ev;
2399    e->server->event_count--;
2400    if ((e->server->event_count <= 0) &&
2401        (e->server->delete_me))
2402      _ecore_con_server_free(e->server);
2403
2404    free(e);
2405 }
2406
2407 static void
2408 _ecore_con_event_server_del_free(void *data __UNUSED__,
2409                                  void      *ev)
2410 {
2411    Ecore_Con_Event_Server_Del *e;
2412
2413    e = ev;
2414    e->server->event_count--;
2415    if ((e->server->event_count <= 0) &&
2416        (e->server->delete_me))
2417      _ecore_con_server_free(e->server);
2418
2419    free(e);
2420 }
2421
2422 static void
2423 _ecore_con_event_server_data_free(void *data __UNUSED__,
2424                                   void      *ev)
2425 {
2426    Ecore_Con_Event_Server_Data *e;
2427
2428    e = ev;
2429    e->server->event_count--;
2430    if (e->data)
2431      free(e->data);
2432
2433    if ((e->server->event_count <= 0) &&
2434        (e->server->delete_me))
2435      _ecore_con_server_free(e->server);
2436
2437    free(e);
2438 }
2439
2440 static void
2441 _ecore_con_lookup_done(void           *data,
2442                        Ecore_Con_Info *infos)
2443 {
2444    Ecore_Con_Server *svr;
2445    Ecore_Con_Lookup *lk;
2446
2447    svr = data;
2448    lk = svr->data;
2449
2450    if (infos)
2451      lk->done_cb(infos->info.ai_canonname, infos->ip,
2452                  infos->info.ai_addr, infos->info.ai_addrlen,
2453                  (void *)lk->data);
2454    else
2455      lk->done_cb(NULL, NULL, NULL, 0, (void *)lk->data);
2456
2457    free(svr->name);
2458    free(lk);
2459    free(svr);
2460 }
2461