added logging
[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   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
265               "client: message of type %u trying to send with socket %p (MQ: %p\n",
266               ntohs(cstate->msg->type),
267               cstate->sock,
268               cstate->mq);
269
270  RETRY:
271   ret = GNUNET_NETWORK_socket_send (cstate->sock,
272                                     &pos[cstate->msg_off],
273                                     len - cstate->msg_off);
274   if (-1 == ret)
275   {
276     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
277                 "client: error during sending message of type %u\n",
278                 ntohs(cstate->msg->type));
279     if (EINTR == errno){
280       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
281                   "client: retrying message of type %u\n",
282                   ntohs(cstate->msg->type));
283       goto RETRY;
284     }
285     GNUNET_MQ_inject_error (cstate->mq,
286                             GNUNET_MQ_ERROR_WRITE);
287     return;
288   }
289   notify_in_flight = (0 == cstate->msg_off);
290   cstate->msg_off += ret;
291   if (cstate->msg_off < len)
292   {
293     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
294                 "client: rescheduling message of type %u\n",
295                 ntohs(cstate->msg->type));
296     cstate->send_task
297       = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
298                                         cstate->sock,
299                                         &transmit_ready,
300                                         cstate);
301     if (notify_in_flight)
302       GNUNET_MQ_impl_send_in_flight (cstate->mq);
303     return;
304   }
305   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
306               "client: sending message of type %u successful\n",
307               ntohs(cstate->msg->type));
308   cstate->msg = NULL;
309   GNUNET_MQ_impl_send_continue (cstate->mq);
310 }
311
312
313 /**
314  * We have received a full message, pass to the MQ dispatcher.
315  * Called by the tokenizer via #receive_ready().
316  *
317  * @param cls the `struct ClientState`
318  * @param msg message we received.
319  * @return #GNUNET_OK on success,
320  *     #GNUNET_NO to stop further processing due to disconnect (no error)
321  *     #GNUNET_SYSERR to stop further processing due to error
322  */
323 static int
324 recv_message (void *cls,
325               const struct GNUNET_MessageHeader *msg)
326 {
327   struct ClientState *cstate = cls;
328
329   if (GNUNET_YES == cstate->in_destroy)
330     return GNUNET_NO;
331   LOG (GNUNET_ERROR_TYPE_DEBUG,
332        "Received message of type %u and size %u from %s\n",
333        ntohs (msg->type),
334        ntohs (msg->size),
335        cstate->service_name);
336   GNUNET_MQ_inject_message (cstate->mq,
337                             msg);
338   if (GNUNET_YES == cstate->in_destroy)
339     return GNUNET_NO;
340   return GNUNET_OK;
341 }
342
343
344 /**
345  * Cancel all remaining connect attempts
346  *
347  * @param cstate handle of the client state to process
348  */
349 static void
350 cancel_aps (struct ClientState *cstate)
351 {
352   struct AddressProbe *pos;
353
354   while (NULL != (pos = cstate->ap_head))
355   {
356     GNUNET_break (GNUNET_OK ==
357                   GNUNET_NETWORK_socket_close (pos->sock));
358     GNUNET_SCHEDULER_cancel (pos->task);
359     GNUNET_CONTAINER_DLL_remove (cstate->ap_head,
360                                  cstate->ap_tail,
361                                  pos);
362     GNUNET_free (pos);
363   }
364 }
365
366
367 /**
368  * Implement the destruction of a message queue.  Implementations must
369  * not free @a mq, but should take care of @a impl_state.
370  *
371  * @param mq the message queue to destroy
372  * @param impl_state our `struct ClientState`
373  */
374 static void
375 connection_client_destroy_impl (struct GNUNET_MQ_Handle *mq,
376                                 void *impl_state)
377 {
378   struct ClientState *cstate = impl_state;
379
380   if (GNUNET_SYSERR == cstate->in_destroy)
381   {
382     /* defer destruction */
383     cstate->in_destroy = GNUNET_YES;
384     cstate->mq = NULL;
385     return;
386   }
387   if (NULL != cstate->dns_active)
388     GNUNET_RESOLVER_request_cancel (cstate->dns_active);
389   if (NULL != cstate->send_task)
390     GNUNET_SCHEDULER_cancel (cstate->send_task);
391   if (NULL != cstate->recv_task)
392     GNUNET_SCHEDULER_cancel (cstate->recv_task);
393   if (NULL != cstate->retry_task)
394     GNUNET_SCHEDULER_cancel (cstate->retry_task);
395   if (NULL != cstate->sock){
396     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
397                 "client: destroying socket: %p\n",
398                 cstate->sock);
399     GNUNET_NETWORK_socket_close (cstate->sock);
400   }
401   cancel_aps (cstate);
402   GNUNET_free (cstate->service_name);
403   GNUNET_free_non_null (cstate->hostname);
404   GNUNET_MST_destroy (cstate->mst);
405   GNUNET_free (cstate);
406 }
407
408
409 /**
410  * This function is called once we have data ready to read.
411  *
412  * @param cls `struct ClientState` with connection to read from
413  */
414 static void
415 receive_ready (void *cls)
416 {
417   struct ClientState *cstate = cls;
418   int ret;
419
420   cstate->recv_task = NULL;
421   cstate->in_destroy = GNUNET_SYSERR;
422   ret = GNUNET_MST_read (cstate->mst,
423                          cstate->sock,
424                          GNUNET_NO,
425                          GNUNET_NO);
426   if (GNUNET_SYSERR == ret)
427   {
428     if (NULL != cstate->mq)
429       GNUNET_MQ_inject_error (cstate->mq,
430                               GNUNET_MQ_ERROR_READ);
431     if (GNUNET_YES == cstate->in_destroy)
432       connection_client_destroy_impl (cstate->mq,
433                                       cstate);
434     return;
435   }
436   if (GNUNET_YES == cstate->in_destroy)
437   {
438     connection_client_destroy_impl (cstate->mq,
439                                     cstate);
440     return;
441   }
442   cstate->in_destroy = GNUNET_NO;
443   cstate->recv_task
444     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
445                                      cstate->sock,
446                                      &receive_ready,
447                                      cstate);
448 }
449
450
451 /**
452  * We've succeeded in establishing a connection.
453  *
454  * @param cstate the connection we tried to establish
455  */
456 static void
457 connect_success_continuation (struct ClientState *cstate)
458 {
459   GNUNET_assert (NULL == cstate->recv_task);
460   cstate->recv_task
461     = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
462                                      cstate->sock,
463                                      &receive_ready,
464                                      cstate);
465   if (NULL != cstate->msg)
466   {
467     GNUNET_assert (NULL == cstate->send_task);
468     cstate->send_task
469       = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
470                                         cstate->sock,
471                                         &transmit_ready,
472                                         cstate);
473   }
474 }
475
476
477 /**
478  * Try connecting to the server using UNIX domain sockets.
479  *
480  * @param service_name name of service to connect to
481  * @param cfg configuration to use
482  * @return NULL on error, socket connected to UNIX otherwise
483  */
484 static struct GNUNET_NETWORK_Handle *
485 try_unixpath (const char *service_name,
486               const struct GNUNET_CONFIGURATION_Handle *cfg)
487 {
488 #if AF_UNIX
489   struct GNUNET_NETWORK_Handle *sock;
490   char *unixpath;
491   struct sockaddr_un s_un;
492
493   unixpath = NULL;
494   if ((GNUNET_OK ==
495        GNUNET_CONFIGURATION_get_value_filename (cfg,
496                                                 service_name,
497                                                 "UNIXPATH",
498                                                 &unixpath)) &&
499       (0 < strlen (unixpath)))
500   {
501     /* We have a non-NULL unixpath, need to validate it */
502     if (strlen (unixpath) >= sizeof (s_un.sun_path))
503     {
504       LOG (GNUNET_ERROR_TYPE_WARNING,
505            _("UNIXPATH `%s' too long, maximum length is %llu\n"),
506            unixpath,
507            (unsigned long long) sizeof (s_un.sun_path));
508       unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
509       LOG (GNUNET_ERROR_TYPE_INFO,
510            _("Using `%s' instead\n"),
511            unixpath);
512       if (NULL == unixpath)
513         return NULL;
514     }
515     memset (&s_un,
516             0,
517             sizeof (s_un));
518     s_un.sun_family = AF_UNIX;
519     strncpy (s_un.sun_path,
520              unixpath,
521              sizeof (s_un.sun_path) - 1);
522 #ifdef LINUX
523     {
524       int abstract;
525
526       abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
527                                                        "TESTING",
528                                                        "USE_ABSTRACT_SOCKETS");
529       if (GNUNET_YES == abstract)
530         s_un.sun_path[0] = '\0';
531     }
532 #endif
533 #if HAVE_SOCKADDR_UN_SUN_LEN
534     s_un.sun_len = (u_char) sizeof (struct sockaddr_un);
535 #endif
536     sock = GNUNET_NETWORK_socket_create (AF_UNIX,
537                                          SOCK_STREAM,
538                                          0);
539     if ( (NULL != sock) &&
540          ( (GNUNET_OK ==
541             GNUNET_NETWORK_socket_connect (sock,
542                                            (struct sockaddr *) &s_un,
543                                            sizeof (s_un))) ||
544            (EINPROGRESS == errno) ) )
545     {
546       LOG (GNUNET_ERROR_TYPE_DEBUG,
547            "Successfully connected to unixpath `%s'!\n",
548            unixpath);
549       GNUNET_free (unixpath);
550       return sock;
551     }
552     if (NULL != sock)
553       GNUNET_NETWORK_socket_close (sock);
554   }
555   GNUNET_free_non_null (unixpath);
556 #endif
557   return NULL;
558 }
559
560
561 /**
562  * Scheduler let us know that we're either ready to write on the
563  * socket OR connect timed out.  Do the right thing.
564  *
565  * @param cls the `struct AddressProbe *` with the address that we are probing
566  */
567 static void
568 connect_probe_continuation (void *cls)
569 {
570   struct AddressProbe *ap = cls;
571   struct ClientState *cstate = ap->cstate;
572   const struct GNUNET_SCHEDULER_TaskContext *tc;
573   int error;
574   socklen_t len;
575
576   ap->task = NULL;
577   GNUNET_assert (NULL != ap->sock);
578   GNUNET_CONTAINER_DLL_remove (cstate->ap_head,
579                                cstate->ap_tail,
580                                ap);
581   len = sizeof (error);
582   error = 0;
583   tc = GNUNET_SCHEDULER_get_task_context ();
584   if ( (0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
585        (GNUNET_OK !=
586         GNUNET_NETWORK_socket_getsockopt (ap->sock,
587                                           SOL_SOCKET,
588                                           SO_ERROR,
589                                           &error,
590                                           &len)) ||
591        (0 != error) )
592   {
593     GNUNET_break (GNUNET_OK ==
594                   GNUNET_NETWORK_socket_close (ap->sock));
595     GNUNET_free (ap);
596     if ( (NULL == cstate->ap_head) &&
597          //      (NULL == cstate->proxy_handshake) &&
598          (NULL == cstate->dns_active) )
599       connect_fail_continuation (cstate);
600     return;
601   }
602   LOG (GNUNET_ERROR_TYPE_DEBUG,
603        "Connection to `%s' succeeded!\n",
604        cstate->service_name);
605   /* trigger jobs that waited for the connection */
606   GNUNET_assert (NULL == cstate->sock);
607   cstate->sock = ap->sock;
608   GNUNET_free (ap);
609   cancel_aps (cstate);
610   connect_success_continuation (cstate);
611 }
612
613
614 /**
615  * Try to establish a connection given the specified address.
616  * This function is called by the resolver once we have a DNS reply.
617  *
618  * @param cls our `struct ClientState *`
619  * @param addr address to try, NULL for "last call"
620  * @param addrlen length of @a addr
621  */
622 static void
623 try_connect_using_address (void *cls,
624                            const struct sockaddr *addr,
625                            socklen_t addrlen)
626 {
627   struct ClientState *cstate = cls;
628   struct AddressProbe *ap;
629
630   if (NULL == addr)
631   {
632     cstate->dns_active = NULL;
633     if ( (NULL == cstate->ap_head) &&
634          //  (NULL == cstate->proxy_handshake) &&
635          (NULL == cstate->sock) )
636       connect_fail_continuation (cstate);
637     return;
638   }
639   if (NULL != cstate->sock)
640     return;                     /* already connected */
641   /* try to connect */
642   LOG (GNUNET_ERROR_TYPE_DEBUG,
643        "Trying to connect using address `%s:%u'\n",
644        GNUNET_a2s (addr,
645                    addrlen),
646        cstate->port);
647   ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
648   ap->addr = (const struct sockaddr *) &ap[1];
649   GNUNET_memcpy (&ap[1],
650                  addr,
651                  addrlen);
652   ap->addrlen = addrlen;
653   ap->cstate = cstate;
654
655   switch (ap->addr->sa_family)
656   {
657   case AF_INET:
658     ((struct sockaddr_in *) ap->addr)->sin_port = htons (cstate->port);
659     break;
660   case AF_INET6:
661     ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (cstate->port);
662     break;
663   default:
664     GNUNET_break (0);
665     GNUNET_free (ap);
666     return;                     /* not supported by us */
667   }
668   ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family,
669                                            SOCK_STREAM,
670                                            0);
671   if (NULL == ap->sock)
672   {
673     GNUNET_free (ap);
674     return;                     /* not supported by OS */
675   }
676   if ( (GNUNET_OK !=
677         GNUNET_NETWORK_socket_connect (ap->sock,
678                                        ap->addr,
679                                        ap->addrlen)) &&
680        (EINPROGRESS != errno) )
681   {
682     /* maybe refused / unsupported address, try next */
683     GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO,
684                          "connect");
685     GNUNET_break (GNUNET_OK ==
686                   GNUNET_NETWORK_socket_close (ap->sock));
687     GNUNET_free (ap);
688     return;
689   }
690   GNUNET_CONTAINER_DLL_insert (cstate->ap_head,
691                                cstate->ap_tail,
692                                ap);
693   ap->task = GNUNET_SCHEDULER_add_write_net (CONNECT_RETRY_TIMEOUT,
694                                              ap->sock,
695                                              &connect_probe_continuation,
696                                              ap);
697 }
698
699
700 /**
701  * Test whether the configuration has proper values for connection
702  * (UNIXPATH || (PORT && HOSTNAME)).
703  *
704  * @param service_name name of service to connect to
705  * @param cfg configuration to use
706  * @return #GNUNET_OK if the configuration is valid, #GNUNET_SYSERR if not
707  */
708 static int
709 test_service_configuration (const char *service_name,
710                             const struct GNUNET_CONFIGURATION_Handle *cfg)
711 {
712   int ret = GNUNET_SYSERR;
713   char *hostname = NULL;
714   unsigned long long port;
715 #if AF_UNIX
716   char *unixpath = NULL;
717
718   if ((GNUNET_OK ==
719        GNUNET_CONFIGURATION_get_value_filename (cfg,
720                                                 service_name,
721                                                 "UNIXPATH",
722                                                 &unixpath)) &&
723       (0 < strlen (unixpath)))
724     ret = GNUNET_OK;
725   GNUNET_free_non_null (unixpath);
726 #endif
727
728   if ( (GNUNET_YES ==
729         GNUNET_CONFIGURATION_have_value (cfg,
730                                          service_name,
731                                          "PORT")) &&
732        (GNUNET_OK ==
733         GNUNET_CONFIGURATION_get_value_number (cfg,
734                                                service_name,
735                                                "PORT",
736                                                &port)) &&
737        (port <= 65535) &&
738        (0 != port) &&
739        (GNUNET_OK ==
740         GNUNET_CONFIGURATION_get_value_string (cfg,
741                                                service_name,
742                                                "HOSTNAME",
743                                                &hostname)) &&
744        (0 != strlen (hostname)) )
745     ret = GNUNET_OK;
746   GNUNET_free_non_null (hostname);
747   return ret;
748 }
749
750
751 /**
752  * Try to connect to the service.
753  *
754  * @param cls the `struct ClientState` to try to connect to the service
755  */
756 static void
757 start_connect (void *cls)
758 {
759   struct ClientState *cstate = cls;
760
761   cstate->retry_task = NULL;
762 #if 0
763   /* Never use a local source if a proxy is configured */
764   if (GNUNET_YES ==
765       GNUNET_SOCKS_check_service (cstate->service_name,
766                                   cstate->cfg))
767   {
768     socks_connect (cstate);
769     return;
770   }
771 #endif
772
773   if ( (0 == (cstate->attempts++ % 2)) ||
774        (0 == cstate->port) ||
775        (NULL == cstate->hostname) )
776   {
777     /* on even rounds, try UNIX first, or always
778        if we do not have a DNS name and TCP port. */
779     cstate->sock = try_unixpath (cstate->service_name,
780                                  cstate->cfg);
781     if (NULL != cstate->sock)
782     {
783       connect_success_continuation (cstate);
784       return;
785     }
786   }
787   if ( (NULL == cstate->hostname) ||
788        (0 == cstate->port) )
789   {
790     /* All options failed. Boo! */
791     connect_fail_continuation (cstate);
792     return;
793   }
794   cstate->dns_active
795     = GNUNET_RESOLVER_ip_get (cstate->hostname,
796                               AF_UNSPEC,
797                               CONNECT_RETRY_TIMEOUT,
798                               &try_connect_using_address,
799                               cstate);
800 }
801
802
803 /**
804  * Implements the transmission functionality of a message queue.
805  *
806  * @param mq the message queue
807  * @param msg the message to send
808  * @param impl_state our `struct ClientState`
809  */
810 static void
811 connection_client_send_impl (struct GNUNET_MQ_Handle *mq,
812                              const struct GNUNET_MessageHeader *msg,
813                              void *impl_state)
814 {
815   struct ClientState *cstate = impl_state;
816
817   /* only one message at a time allowed */
818   GNUNET_assert (NULL == cstate->msg);
819   GNUNET_assert (NULL == cstate->send_task);
820   cstate->msg = msg;
821   cstate->msg_off = 0;
822   if (NULL == cstate->sock){
823     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
824                 "client: message of type %u waiting for socket\n",
825                 ntohs(msg->type));
826     return; /* still waiting for connection */
827    }
828   cstate->send_task
829     = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
830                                       cstate->sock,
831                                       &transmit_ready,
832                                       cstate);
833 }
834
835
836 /**
837  * Cancel the currently sent message.
838  *
839  * @param mq message queue
840  * @param impl_state our `struct ClientState`
841  */
842 static void
843 connection_client_cancel_impl (struct GNUNET_MQ_Handle *mq,
844                                void *impl_state)
845 {
846   struct ClientState *cstate = impl_state;
847
848   GNUNET_assert (NULL != cstate->msg);
849   GNUNET_assert (0 == cstate->msg_off);
850   cstate->msg = NULL;
851   if (NULL != cstate->send_task)
852   {
853     GNUNET_SCHEDULER_cancel (cstate->send_task);
854     cstate->send_task = NULL;
855   }
856 }
857
858
859 /**
860  * Create a message queue to connect to a GNUnet service.
861  * If handlers are specfied, receive messages from the connection.
862  *
863  * @param cfg our configuration
864  * @param service_name name of the service to connect to
865  * @param handlers handlers for receiving messages, can be NULL
866  * @param error_handler error handler
867  * @param error_handler_cls closure for the @a error_handler
868  * @return the message queue, NULL on error
869  */
870 struct GNUNET_MQ_Handle *
871 GNUNET_CLIENT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
872                        const char *service_name,
873                        const struct GNUNET_MQ_MessageHandler *handlers,
874                        GNUNET_MQ_ErrorHandler error_handler,
875                        void *error_handler_cls)
876 {
877   struct ClientState *cstate;
878
879   if (GNUNET_OK !=
880       test_service_configuration (service_name,
881                                   cfg))
882     return NULL;
883   cstate = GNUNET_new (struct ClientState);
884   cstate->service_name = GNUNET_strdup (service_name);
885   cstate->cfg = cfg;
886   cstate->retry_task = GNUNET_SCHEDULER_add_now (&start_connect,
887                                                  cstate);
888   cstate->mst = GNUNET_MST_create (&recv_message,
889                                    cstate);
890   if (GNUNET_YES ==
891       GNUNET_CONFIGURATION_have_value (cfg,
892                                        service_name,
893                                        "PORT"))
894   {
895     if (! ( (GNUNET_OK !=
896              GNUNET_CONFIGURATION_get_value_number (cfg,
897                                                     service_name,
898                                                     "PORT",
899                                                     &cstate->port)) ||
900             (cstate->port > 65535) ||
901             (GNUNET_OK !=
902              GNUNET_CONFIGURATION_get_value_string (cfg,
903                                                     service_name,
904                                                     "HOSTNAME",
905                                                     &cstate->hostname)) ) &&
906         (0 == strlen (cstate->hostname)) )
907     {
908       GNUNET_free (cstate->hostname);
909       cstate->hostname = NULL;
910       LOG (GNUNET_ERROR_TYPE_WARNING,
911            _("Need a non-empty hostname for service `%s'.\n"),
912            service_name);
913     }
914   }
915   cstate->mq = GNUNET_MQ_queue_for_callbacks (&connection_client_send_impl,
916                                               &connection_client_destroy_impl,
917                                               &connection_client_cancel_impl,
918                                               cstate,
919                                               handlers,
920                                               error_handler,
921                                               error_handler_cls);
922   return cstate->mq;
923 }
924
925 /* end of client.c */