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