Merge branch 'master' of ssh://gnunet.org/gnunet
[oweals/gnunet.git] / src / util / client.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001-2016 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file util/client.c
23  * @brief code for access to services
24  * @author Christian Grothoff
25  *
26  * Generic TCP code for reliable, record-oriented TCP
27  * connections between clients and service providers.
28  */
29 #include "platform.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_resolver_service.h"
33 #include "gnunet_socks.h"
34
35
36 #define LOG(kind,...) GNUNET_log_from (kind, "util-client",__VA_ARGS__)
37
38 /**
39  * Timeout we use on TCP connect before trying another
40  * result from the DNS resolver.  Actual value used
41  * is this value divided by the number of address families.
42  * Default is 5s.
43  */
44 #define CONNECT_RETRY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
45
46
47
48 /**
49  * Internal state for a client connected to a GNUnet service.
50  */
51 struct ClientState;
52
53
54 /**
55  * During connect, we try multiple possible IP addresses
56  * to find out which one might work.
57  */
58 struct AddressProbe
59 {
60
61   /**
62    * This is a linked list.
63    */
64   struct AddressProbe *next;
65
66   /**
67    * This is a doubly-linked list.
68    */
69   struct AddressProbe *prev;
70
71   /**
72    * The address; do not free (allocated at the end of this struct).
73    */
74   const struct sockaddr *addr;
75
76   /**
77    * Underlying OS's socket.
78    */
79   struct GNUNET_NETWORK_Handle *sock;
80
81   /**
82    * Connection for which we are probing.
83    */
84   struct ClientState *cstate;
85
86   /**
87    * Lenth of addr.
88    */
89   socklen_t addrlen;
90
91   /**
92    * Task waiting for the connection to finish connecting.
93    */
94   struct GNUNET_SCHEDULER_Task *task;
95 };
96
97
98 /**
99  * Internal state for a client connected to a GNUnet service.
100  */
101 struct ClientState
102 {
103
104   /**
105    * The connection handle, NULL if not live
106    */
107   struct GNUNET_NETWORK_Handle *sock;
108
109   /**
110    * Handle to a pending DNS lookup request, NULL if DNS is finished.
111    */
112   struct GNUNET_RESOLVER_RequestHandle *dns_active;
113
114   /**
115    * Our configuration.
116    */
117   const struct GNUNET_CONFIGURATION_Handle *cfg;
118
119   /**
120    * Linked list of sockets we are currently trying out
121    * (during connect).
122    */
123   struct AddressProbe *ap_head;
124
125   /**
126    * Linked list of sockets we are currently trying out
127    * (during connect).
128    */
129   struct AddressProbe *ap_tail;
130
131   /**
132    * Name of the service we interact with.
133    */
134   char *service_name;
135
136   /**
137    * Hostname, if any.
138    */
139   char *hostname;
140
141   /**
142    * Next message to transmit to the service. NULL for none.
143    */
144   const struct GNUNET_MessageHeader *msg;
145
146   /**
147    * Task for trying to connect to the service.
148    */
149   struct GNUNET_SCHEDULER_Task *retry_task;
150
151   /**
152    * Task for sending messages to the service.
153    */
154   struct GNUNET_SCHEDULER_Task *send_task;
155
156   /**
157    * Task for sending messages to the service.
158    */
159   struct GNUNET_SCHEDULER_Task *recv_task;
160
161   /**
162    * Tokenizer for inbound messages.
163    */
164   struct GNUNET_MessageStreamTokenizer *mst;
165
166   /**
167    * Message queue under our control.
168    */
169   struct GNUNET_MQ_Handle *mq;
170
171   /**
172    * Timeout for receiving a response (absolute time).
173    */
174   struct GNUNET_TIME_Absolute receive_timeout;
175
176   /**
177    * Current value for our incremental back-off (for
178    * connect re-tries).
179    */
180   struct GNUNET_TIME_Relative back_off;
181
182   /**
183    * TCP port (0 for disabled).
184    */
185   unsigned long long port;
186
187   /**
188    * Offset in the message where we are for transmission.
189    */
190   size_t msg_off;
191
192   /**
193    * How often have we tried to connect?
194    */
195   unsigned int attempts;
196
197   /**
198    * Are we supposed to die?  #GNUNET_SYSERR if destruction must be
199    * deferred, #GNUNET_NO by default, #GNUNET_YES if destruction was
200    * deferred.
201    */
202   int in_destroy;
203
204 };
205
206
207 /**
208  * Try to connect to the service.
209  *
210  * @param cls the `struct ClientState` to try to connect to the service
211  */
212 static void
213 start_connect (void *cls);
214
215
216 /**
217  * We've failed for good to establish a connection (timeout or
218  * no more addresses to try).
219  *
220  * @param cstate the connection we tried to establish
221  */
222 static void
223 connect_fail_continuation (struct ClientState *cstate)
224 {
225   GNUNET_break (NULL == cstate->ap_head);
226   GNUNET_break (NULL == cstate->ap_tail);
227   GNUNET_break (NULL == cstate->dns_active);
228   GNUNET_break (NULL == cstate->sock);
229   GNUNET_assert (NULL == cstate->send_task);
230   GNUNET_assert (NULL == cstate->recv_task);
231   // GNUNET_assert (NULL == cstate->proxy_handshake);
232
233   cstate->back_off = GNUNET_TIME_STD_BACKOFF (cstate->back_off);
234   LOG (GNUNET_ERROR_TYPE_DEBUG,
235        "Failed to establish connection to `%s', no further addresses to try, will try again in %s.\n",
236        cstate->service_name,
237        GNUNET_STRINGS_relative_time_to_string (cstate->back_off,
238                                                GNUNET_YES));
239   cstate->retry_task
240     = GNUNET_SCHEDULER_add_delayed (cstate->back_off,
241                                     &start_connect,
242                                     cstate);
243 }
244
245
246 /**
247  * We are ready to send a message to the service.
248  *
249  * @param cls the `struct ClientState` with the `msg` to transmit
250  */
251 static void
252 transmit_ready (void *cls)
253 {
254   struct ClientState *cstate = cls;
255   ssize_t ret;
256   size_t len;
257   const char *pos;
258   int notify_in_flight;
259
260   cstate->send_task = NULL;
261   pos = (const char *) cstate->msg;
262   len = ntohs (cstate->msg->size);
263   GNUNET_assert (cstate->msg_off < len);
264  RETRY:
265   ret = GNUNET_NETWORK_socket_send (cstate->sock,
266                                     &pos[cstate->msg_off],
267                                     len - cstate->msg_off);
268   if (-1 == ret)
269   {
270     if (EINTR == errno)
271       goto RETRY;
272     GNUNET_MQ_inject_error (cstate->mq,
273                             GNUNET_MQ_ERROR_WRITE);
274     return;
275   }
276   notify_in_flight = (0 == cstate->msg_off);
277   cstate->msg_off += ret;
278   if (cstate->msg_off < len)
279   {
280     cstate->send_task
281       = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
282                                         cstate->sock,
283                                         &transmit_ready,
284                                         cstate);
285     if (notify_in_flight)
286       GNUNET_MQ_impl_send_in_flight (cstate->mq);
287     return;
288   }
289   cstate->msg = NULL;
290   GNUNET_MQ_impl_send_continue (cstate->mq);
291 }
292
293
294 /**
295  * We have received a full message, pass to the MQ dispatcher.
296  * Called by the tokenizer via #receive_ready().
297  *
298  * @param cls the `struct ClientState`
299  * @param msg message we received.
300  * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
301  */
302 static int
303 recv_message (void *cls,
304               const struct GNUNET_MessageHeader *msg)
305 {
306   struct ClientState *cstate = cls;
307
308   if (GNUNET_YES == cstate->in_destroy)
309     return GNUNET_SYSERR;
310   LOG (GNUNET_ERROR_TYPE_DEBUG,
311        "Received message of type %u and size %u from %s\n",
312        ntohs (msg->type),
313        ntohs (msg->size),
314        cstate->service_name);
315   GNUNET_MQ_inject_message (cstate->mq,
316                             msg);
317   if (GNUNET_YES == cstate->in_destroy)
318     return GNUNET_SYSERR;
319   return GNUNET_OK;
320 }
321
322
323 /**
324  * Cancel all remaining connect attempts
325  *
326  * @param cstate handle of the client state to process
327  */
328 static void
329 cancel_aps (struct ClientState *cstate)
330 {
331   struct AddressProbe *pos;
332
333   while (NULL != (pos = cstate->ap_head))
334   {
335     GNUNET_break (GNUNET_OK ==
336                   GNUNET_NETWORK_socket_close (pos->sock));
337     GNUNET_SCHEDULER_cancel (pos->task);
338     GNUNET_CONTAINER_DLL_remove (cstate->ap_head,
339                                  cstate->ap_tail,
340                                  pos);
341     GNUNET_free (pos);
342   }
343 }
344
345
346 /**
347  * Implement the destruction of a message queue.  Implementations must
348  * not free @a mq, but should take care of @a impl_state.
349  *
350  * @param mq the message queue to destroy
351  * @param impl_state our `struct ClientState`
352  */
353 static void
354 connection_client_destroy_impl (struct GNUNET_MQ_Handle *mq,
355                                 void *impl_state)
356 {
357   struct ClientState *cstate = impl_state;
358
359   if (GNUNET_SYSERR == cstate->in_destroy)
360   {
361     /* defer destruction */
362     cstate->in_destroy = GNUNET_YES;
363     cstate->mq = NULL;
364     return;
365   }
366   if (NULL != cstate->dns_active)
367     GNUNET_RESOLVER_request_cancel (cstate->dns_active);
368   if (NULL != cstate->send_task)
369     GNUNET_SCHEDULER_cancel (cstate->send_task);
370   if (NULL != cstate->recv_task)
371     GNUNET_SCHEDULER_cancel (cstate->recv_task);
372   if (NULL != cstate->retry_task)
373     GNUNET_SCHEDULER_cancel (cstate->retry_task);
374   if (NULL != cstate->sock)
375     GNUNET_NETWORK_socket_close (cstate->sock);
376   cancel_aps (cstate);
377   GNUNET_free (cstate->service_name);
378   GNUNET_free_non_null (cstate->hostname);
379   GNUNET_MST_destroy (cstate->mst);
380   GNUNET_free (cstate);
381 }
382
383
384 /**
385  * This function is called once we have data ready to read.
386  *
387  * @param cls `struct ClientState` with connection to read from
388  */
389 static void
390 receive_ready (void *cls)
391 {
392   struct ClientState *cstate = cls;
393   int ret;
394
395   cstate->recv_task = NULL;
396   cstate->in_destroy = GNUNET_SYSERR;
397   ret = GNUNET_MST_read (cstate->mst,
398                          cstate->sock,
399                          GNUNET_NO,
400                          GNUNET_NO);
401   if (GNUNET_SYSERR == ret)
402   {
403     if (NULL != cstate->mq)
404       GNUNET_MQ_inject_error (cstate->mq,
405                               GNUNET_MQ_ERROR_READ);
406     if (GNUNET_YES == cstate->in_destroy)
407       connection_client_destroy_impl (cstate->mq,
408                                       cstate);
409     return;
410   }
411   if (GNUNET_YES == cstate->in_destroy)
412   {
413     connection_client_destroy_impl (cstate->mq,
414                                     cstate);
415     return;
416   }
417   cstate->in_destroy = GNUNET_NO;
418   cstate->recv_task
419     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
420                                      cstate->sock,
421                                      &receive_ready,
422                                      cstate);
423 }
424
425
426 /**
427  * We've succeeded in establishing a connection.
428  *
429  * @param cstate the connection we tried to establish
430  */
431 static void
432 connect_success_continuation (struct ClientState *cstate)
433 {
434   GNUNET_assert (NULL == cstate->recv_task);
435   cstate->recv_task
436     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
437                                      cstate->sock,
438                                      &receive_ready,
439                                      cstate);
440   if (NULL != cstate->msg)
441   {
442     GNUNET_assert (NULL == cstate->send_task);
443     cstate->send_task
444       = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
445                                         cstate->sock,
446                                         &transmit_ready,
447                                         cstate);
448   }
449 }
450
451
452 /**
453  * Try connecting to the server using UNIX domain sockets.
454  *
455  * @param service_name name of service to connect to
456  * @param cfg configuration to use
457  * @return NULL on error, socket connected to UNIX otherwise
458  */
459 static struct GNUNET_NETWORK_Handle *
460 try_unixpath (const char *service_name,
461               const struct GNUNET_CONFIGURATION_Handle *cfg)
462 {
463 #if AF_UNIX
464   struct GNUNET_NETWORK_Handle *sock;
465   char *unixpath;
466   struct sockaddr_un s_un;
467
468   unixpath = NULL;
469   if ((GNUNET_OK ==
470        GNUNET_CONFIGURATION_get_value_filename (cfg,
471                                                 service_name,
472                                                 "UNIXPATH",
473                                                 &unixpath)) &&
474       (0 < strlen (unixpath)))
475   {
476     /* We have a non-NULL unixpath, need to validate it */
477     if (strlen (unixpath) >= sizeof (s_un.sun_path))
478     {
479       LOG (GNUNET_ERROR_TYPE_WARNING,
480            _("UNIXPATH `%s' too long, maximum length is %llu\n"),
481            unixpath,
482            (unsigned long long) sizeof (s_un.sun_path));
483       unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
484       LOG (GNUNET_ERROR_TYPE_INFO,
485            _("Using `%s' instead\n"),
486            unixpath);
487       if (NULL == unixpath)
488         return NULL;
489     }
490     memset (&s_un,
491             0,
492             sizeof (s_un));
493     s_un.sun_family = AF_UNIX;
494     strncpy (s_un.sun_path,
495              unixpath,
496              sizeof (s_un.sun_path) - 1);
497 #ifdef LINUX
498     {
499       int abstract;
500
501       abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
502                                                        "TESTING",
503                                                        "USE_ABSTRACT_SOCKETS");
504       if (GNUNET_YES == abstract)
505         s_un.sun_path[0] = '\0';
506     }
507 #endif
508 #if HAVE_SOCKADDR_UN_SUN_LEN
509     s_un.sun_len = (u_char) sizeof (struct sockaddr_un);
510 #endif
511     sock = GNUNET_NETWORK_socket_create (AF_UNIX,
512                                          SOCK_STREAM,
513                                          0);
514     if ( (NULL != sock) &&
515          ( (GNUNET_OK ==
516             GNUNET_NETWORK_socket_connect (sock,
517                                            (struct sockaddr *) &s_un,
518                                            sizeof (s_un))) ||
519            (EINPROGRESS == errno) ) )
520     {
521       LOG (GNUNET_ERROR_TYPE_DEBUG,
522            "Successfully connected to unixpath `%s'!\n",
523            unixpath);
524       GNUNET_free (unixpath);
525       return sock;
526     }
527     if (NULL != sock)
528       GNUNET_NETWORK_socket_close (sock);
529   }
530   GNUNET_free_non_null (unixpath);
531 #endif
532   return NULL;
533 }
534
535
536 /**
537  * Scheduler let us know that we're either ready to write on the
538  * socket OR connect timed out.  Do the right thing.
539  *
540  * @param cls the `struct AddressProbe *` with the address that we are probing
541  */
542 static void
543 connect_probe_continuation (void *cls)
544 {
545   struct AddressProbe *ap = cls;
546   struct ClientState *cstate = ap->cstate;
547   const struct GNUNET_SCHEDULER_TaskContext *tc;
548   int error;
549   socklen_t len;
550
551   ap->task = NULL;
552   GNUNET_assert (NULL != ap->sock);
553   GNUNET_CONTAINER_DLL_remove (cstate->ap_head,
554                                cstate->ap_tail,
555                                ap);
556   len = sizeof (error);
557   error = 0;
558   tc = GNUNET_SCHEDULER_get_task_context ();
559   if ( (0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
560        (GNUNET_OK !=
561         GNUNET_NETWORK_socket_getsockopt (ap->sock,
562                                           SOL_SOCKET,
563                                           SO_ERROR,
564                                           &error,
565                                           &len)) ||
566        (0 != error) )
567   {
568     GNUNET_break (GNUNET_OK ==
569                   GNUNET_NETWORK_socket_close (ap->sock));
570     GNUNET_free (ap);
571     if ( (NULL == cstate->ap_head) &&
572          //      (NULL == cstate->proxy_handshake) &&
573          (NULL == cstate->dns_active) )
574       connect_fail_continuation (cstate);
575     return;
576   }
577   LOG (GNUNET_ERROR_TYPE_DEBUG,
578        "Connection to `%s' succeeded!\n",
579        cstate->service_name);
580   /* trigger jobs that waited for the connection */
581   GNUNET_assert (NULL == cstate->sock);
582   cstate->sock = ap->sock;
583   GNUNET_free (ap);
584   cancel_aps (cstate);
585   connect_success_continuation (cstate);
586 }
587
588
589 /**
590  * Try to establish a connection given the specified address.
591  * This function is called by the resolver once we have a DNS reply.
592  *
593  * @param cls our `struct ClientState *`
594  * @param addr address to try, NULL for "last call"
595  * @param addrlen length of @a addr
596  */
597 static void
598 try_connect_using_address (void *cls,
599                            const struct sockaddr *addr,
600                            socklen_t addrlen)
601 {
602   struct ClientState *cstate = cls;
603   struct AddressProbe *ap;
604
605   if (NULL == addr)
606   {
607     cstate->dns_active = NULL;
608     if ( (NULL == cstate->ap_head) &&
609          //  (NULL == cstate->proxy_handshake) &&
610          (NULL == cstate->sock) )
611       connect_fail_continuation (cstate);
612     return;
613   }
614   if (NULL != cstate->sock)
615     return;                     /* already connected */
616   /* try to connect */
617   LOG (GNUNET_ERROR_TYPE_DEBUG,
618        "Trying to connect using address `%s:%u'\n",
619        GNUNET_a2s (addr,
620                    addrlen),
621        cstate->port);
622   ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
623   ap->addr = (const struct sockaddr *) &ap[1];
624   GNUNET_memcpy (&ap[1],
625                  addr,
626                  addrlen);
627   ap->addrlen = addrlen;
628   ap->cstate = cstate;
629
630   switch (ap->addr->sa_family)
631   {
632   case AF_INET:
633     ((struct sockaddr_in *) ap->addr)->sin_port = htons (cstate->port);
634     break;
635   case AF_INET6:
636     ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (cstate->port);
637     break;
638   default:
639     GNUNET_break (0);
640     GNUNET_free (ap);
641     return;                     /* not supported by us */
642   }
643   ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family,
644                                            SOCK_STREAM,
645                                            0);
646   if (NULL == ap->sock)
647   {
648     GNUNET_free (ap);
649     return;                     /* not supported by OS */
650   }
651   if ( (GNUNET_OK !=
652         GNUNET_NETWORK_socket_connect (ap->sock,
653                                        ap->addr,
654                                        ap->addrlen)) &&
655        (EINPROGRESS != errno) )
656   {
657     /* maybe refused / unsupported address, try next */
658     GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO,
659                          "connect");
660     GNUNET_break (GNUNET_OK ==
661                   GNUNET_NETWORK_socket_close (ap->sock));
662     GNUNET_free (ap);
663     return;
664   }
665   GNUNET_CONTAINER_DLL_insert (cstate->ap_head,
666                                cstate->ap_tail,
667                                ap);
668   ap->task = GNUNET_SCHEDULER_add_write_net (CONNECT_RETRY_TIMEOUT,
669                                              ap->sock,
670                                              &connect_probe_continuation,
671                                              ap);
672 }
673
674
675 /**
676  * Test whether the configuration has proper values for connection
677  * (UNIXPATH || (PORT && HOSTNAME)).
678  *
679  * @param service_name name of service to connect to
680  * @param cfg configuration to use
681  * @return #GNUNET_OK if the configuration is valid, #GNUNET_SYSERR if not
682  */
683 static int
684 test_service_configuration (const char *service_name,
685                             const struct GNUNET_CONFIGURATION_Handle *cfg)
686 {
687   int ret = GNUNET_SYSERR;
688   char *hostname = NULL;
689   unsigned long long port;
690 #if AF_UNIX
691   char *unixpath = NULL;
692
693   if ((GNUNET_OK ==
694        GNUNET_CONFIGURATION_get_value_filename (cfg,
695                                                 service_name,
696                                                 "UNIXPATH",
697                                                 &unixpath)) &&
698       (0 < strlen (unixpath)))
699     ret = GNUNET_OK;
700   GNUNET_free_non_null (unixpath);
701 #endif
702
703   if ( (GNUNET_YES ==
704         GNUNET_CONFIGURATION_have_value (cfg,
705                                          service_name,
706                                          "PORT")) &&
707        (GNUNET_OK ==
708         GNUNET_CONFIGURATION_get_value_number (cfg,
709                                                service_name,
710                                                "PORT",
711                                                &port)) &&
712        (port <= 65535) &&
713        (0 != port) &&
714        (GNUNET_OK ==
715         GNUNET_CONFIGURATION_get_value_string (cfg,
716                                                service_name,
717                                                "HOSTNAME",
718                                                &hostname)) &&
719        (0 != strlen (hostname)) )
720     ret = GNUNET_OK;
721   GNUNET_free_non_null (hostname);
722   return ret;
723 }
724
725
726 /**
727  * Try to connect to the service.
728  *
729  * @param cls the `struct ClientState` to try to connect to the service
730  */
731 static void
732 start_connect (void *cls)
733 {
734   struct ClientState *cstate = cls;
735
736   cstate->retry_task = NULL;
737 #if 0
738   /* Never use a local source if a proxy is configured */
739   if (GNUNET_YES ==
740       GNUNET_SOCKS_check_service (cstate->service_name,
741                                   cstate->cfg))
742   {
743     socks_connect (cstate);
744     return;
745   }
746 #endif
747
748   if ( (0 == (cstate->attempts++ % 2)) ||
749        (0 == cstate->port) ||
750        (NULL == cstate->hostname) )
751   {
752     /* on even rounds, try UNIX first, or always
753        if we do not have a DNS name and TCP port. */
754     cstate->sock = try_unixpath (cstate->service_name,
755                                  cstate->cfg);
756     if (NULL != cstate->sock)
757     {
758       connect_success_continuation (cstate);
759       return;
760     }
761   }
762   if ( (NULL == cstate->hostname) ||
763        (0 == cstate->port) )
764   {
765     /* All options failed. Boo! */
766     connect_fail_continuation (cstate);
767     return;
768   }
769   cstate->dns_active
770     = GNUNET_RESOLVER_ip_get (cstate->hostname,
771                               AF_UNSPEC,
772                               CONNECT_RETRY_TIMEOUT,
773                               &try_connect_using_address,
774                               cstate);
775 }
776
777
778 /**
779  * Implements the transmission functionality of a message queue.
780  *
781  * @param mq the message queue
782  * @param msg the message to send
783  * @param impl_state our `struct ClientState`
784  */
785 static void
786 connection_client_send_impl (struct GNUNET_MQ_Handle *mq,
787                              const struct GNUNET_MessageHeader *msg,
788                              void *impl_state)
789 {
790   struct ClientState *cstate = impl_state;
791
792   /* only one message at a time allowed */
793   GNUNET_assert (NULL == cstate->msg);
794   GNUNET_assert (NULL == cstate->send_task);
795   cstate->msg = msg;
796   cstate->msg_off = 0;
797   if (NULL == cstate->sock)
798     return; /* still waiting for connection */
799   cstate->send_task
800     = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
801                                       cstate->sock,
802                                       &transmit_ready,
803                                       cstate);
804 }
805
806
807 /**
808  * Cancel the currently sent message.
809  *
810  * @param mq message queue
811  * @param impl_state our `struct ClientState`
812  */
813 static void
814 connection_client_cancel_impl (struct GNUNET_MQ_Handle *mq,
815                                void *impl_state)
816 {
817   struct ClientState *cstate = impl_state;
818
819   GNUNET_assert (NULL != cstate->msg);
820   GNUNET_assert (0 == cstate->msg_off);
821   cstate->msg = NULL;
822   if (NULL != cstate->send_task)
823   {
824     GNUNET_SCHEDULER_cancel (cstate->send_task);
825     cstate->send_task = NULL;
826   }
827 }
828
829
830 /**
831  * Create a message queue to connect to a GNUnet service.
832  * If handlers are specfied, receive messages from the connection.
833  *
834  * @param cfg our configuration
835  * @param service_name name of the service to connect to
836  * @param handlers handlers for receiving messages, can be NULL
837  * @param error_handler error handler
838  * @param error_handler_cls closure for the @a error_handler
839  * @return the message queue, NULL on error
840  */
841 struct GNUNET_MQ_Handle *
842 GNUNET_CLIENT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
843                        const char *service_name,
844                        const struct GNUNET_MQ_MessageHandler *handlers,
845                        GNUNET_MQ_ErrorHandler error_handler,
846                        void *error_handler_cls)
847 {
848   struct ClientState *cstate;
849
850   if (GNUNET_OK !=
851       test_service_configuration (service_name,
852                                   cfg))
853     return NULL;
854   cstate = GNUNET_new (struct ClientState);
855   cstate->service_name = GNUNET_strdup (service_name);
856   cstate->cfg = cfg;
857   cstate->retry_task = GNUNET_SCHEDULER_add_now (&start_connect,
858                                                  cstate);
859   cstate->mst = GNUNET_MST_create (&recv_message,
860                                    cstate);
861   if (GNUNET_YES ==
862       GNUNET_CONFIGURATION_have_value (cfg,
863                                        service_name,
864                                        "PORT"))
865   {
866     if (! ( (GNUNET_OK !=
867              GNUNET_CONFIGURATION_get_value_number (cfg,
868                                                     service_name,
869                                                     "PORT",
870                                                     &cstate->port)) ||
871             (cstate->port > 65535) ||
872             (GNUNET_OK !=
873              GNUNET_CONFIGURATION_get_value_string (cfg,
874                                                     service_name,
875                                                     "HOSTNAME",
876                                                     &cstate->hostname)) ) &&
877         (0 == strlen (cstate->hostname)) )
878     {
879       GNUNET_free (cstate->hostname);
880       cstate->hostname = NULL;
881       LOG (GNUNET_ERROR_TYPE_WARNING,
882            _("Need a non-empty hostname for service `%s'.\n"),
883            service_name);
884     }
885   }
886   cstate->mq = GNUNET_MQ_queue_for_callbacks (&connection_client_send_impl,
887                                               &connection_client_destroy_impl,
888                                               &connection_client_cancel_impl,
889                                               cstate,
890                                               handlers,
891                                               error_handler,
892                                               error_handler_cls);
893   return cstate->mq;
894 }
895
896 /* end of client.c */