LRN's patch argument order
[oweals/gnunet.git] / src / util / client.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2006, 2008, 2009 Christian Grothoff (and other contributing authors)
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 2, 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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, 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
30 #include "platform.h"
31 #include "gnunet_common.h"
32 #include "gnunet_client_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_scheduler_lib.h"
36
37 #define DEBUG_CLIENT GNUNET_EXTRA_LOGGING
38
39 /**
40  * How often do we re-try tranmsitting requests before giving up?
41  * Note that if we succeeded transmitting a request but failed to read
42  * a response, we do NOT re-try.
43  */
44 #define MAX_ATTEMPTS 50
45
46 #define LOG(kind,...) GNUNET_log_from (kind, "util",__VA_ARGS__)
47
48 /**
49  * Handle for a transmission request.
50  */
51 struct GNUNET_CLIENT_TransmitHandle
52 {
53   /**
54    * Connection state.
55    */
56   struct GNUNET_CLIENT_Connection *sock;
57
58   /**
59    * Function to call to get the data for transmission.
60    */
61   GNUNET_CONNECTION_TransmitReadyNotify notify;
62
63   /**
64    * Closure for notify.
65    */
66   void *notify_cls;
67
68   /**
69    * Handle to the transmission with the underlying
70    * connection.
71    */
72   struct GNUNET_CONNECTION_TransmitHandle *th;
73
74   /**
75    * If we are re-trying and are delaying to do so,
76    * handle to the scheduled task managing the delay.
77    */
78   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
79
80   /**
81    * Timeout for the operation overall.
82    */
83   struct GNUNET_TIME_Absolute timeout;
84
85   /**
86    * Number of bytes requested.
87    */
88   size_t size;
89
90   /**
91    * Are we allowed to re-try to connect without telling
92    * the user (of this API) about the connection troubles?
93    */
94   int auto_retry;
95
96   /**
97    * Number of attempts left for transmitting the request.  We may
98    * fail the first time (say because the service is not yet up), in
99    * which case (if auto_retry is set) we wait a bit and re-try
100    * (timeout permitting).
101    */
102   unsigned int attempts_left;
103
104 };
105
106
107 /**
108  * Context for processing
109  * "GNUNET_CLIENT_transmit_and_get_response" requests.
110  */
111 struct TransmitGetResponseContext
112 {
113   /**
114    * Client handle.
115    */
116   struct GNUNET_CLIENT_Connection *sock;
117
118   /**
119    * Message to transmit; do not free, allocated
120    * right after this struct.
121    */
122   const struct GNUNET_MessageHeader *hdr;
123
124   /**
125    * Timeout to use.
126    */
127   struct GNUNET_TIME_Absolute timeout;
128
129   /**
130    * Function to call when done.
131    */
132   GNUNET_CLIENT_MessageHandler rn;
133
134   /**
135    * Closure for "rn".
136    */
137   void *rn_cls;
138 };
139
140 /**
141  * Struct to refer to a GNUnet TCP connection.
142  * This is more than just a socket because if the server
143  * drops the connection, the client automatically tries
144  * to reconnect (and for that needs connection information).
145  */
146 struct GNUNET_CLIENT_Connection
147 {
148
149   /**
150    * the socket handle, NULL if not live
151    */
152   struct GNUNET_CONNECTION_Handle *sock;
153
154   /**
155    * Our configuration.
156    */
157   const struct GNUNET_CONFIGURATION_Handle *cfg;
158
159   /**
160    * Name of the service we interact with.
161    */
162   char *service_name;
163
164   /**
165    * Context of a transmit_and_get_response operation, NULL
166    * if no such operation is pending.
167    */
168   struct TransmitGetResponseContext *tag;
169
170   /**
171    * Handler for current receiver task.
172    */
173   GNUNET_CLIENT_MessageHandler receiver_handler;
174
175   /**
176    * Closure for receiver_handler.
177    */
178   void *receiver_handler_cls;
179
180   /**
181    * Handle for a pending transmission request, NULL if there is
182    * none pending.
183    */
184   struct GNUNET_CLIENT_TransmitHandle *th;
185
186   /**
187    * Handler for service test completion (NULL unless in service_test)
188    */
189   GNUNET_SCHEDULER_Task test_cb;
190
191   /**
192    * Deadline for calling 'test_cb'.
193    */
194   struct GNUNET_TIME_Absolute test_deadline;
195
196   /**
197    * If we are re-trying and are delaying to do so,
198    * handle to the scheduled task managing the delay.
199    */
200   GNUNET_SCHEDULER_TaskIdentifier receive_task;
201
202   /**
203    * Closure for test_cb (NULL unless in service_test)
204    */
205   void *test_cb_cls;
206
207   /**
208    * Buffer for received message.
209    */
210   char *received_buf;
211
212   /**
213    * Timeout for receiving a response (absolute time).
214    */
215   struct GNUNET_TIME_Absolute receive_timeout;
216
217   /**
218    * Current value for our incremental back-off (for
219    * connect re-tries).
220    */
221   struct GNUNET_TIME_Relative back_off;
222
223   /**
224    * Number of bytes in received_buf that are valid.
225    */
226   size_t received_pos;
227
228   /**
229    * Size of received_buf.
230    */
231   unsigned int received_size;
232
233   /**
234    * Do we have a complete response in received_buf?
235    */
236   int msg_complete;
237
238   /**
239    * Are we currently busy doing receive-processing?
240    * GNUNET_YES if so, GNUNET_NO if not.
241    */
242   int in_receive;
243
244   /**
245    * How often have we tried to connect?
246    */
247   unsigned int attempts;
248
249 };
250
251
252 /**
253  * Try to connect to the service.
254  *
255  * @param service_name name of service to connect to
256  * @param cfg configuration to use
257  * @param attempt counter used to alternate between IP and UNIX domain sockets
258  * @return NULL on error
259  */
260 static struct GNUNET_CONNECTION_Handle *
261 do_connect (const char *service_name,
262             const struct GNUNET_CONFIGURATION_Handle *cfg, unsigned int attempt)
263 {
264   struct GNUNET_CONNECTION_Handle *sock;
265   char *hostname;
266   char *unixpath;
267   unsigned long long port;
268
269   sock = NULL;
270 #if AF_UNIX
271   if (0 == (attempt % 2))
272   {
273     /* on even rounds, try UNIX */
274     unixpath = NULL;
275     if ((GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "UNIXPATH", &unixpath)) && (0 < strlen (unixpath)))     /* We have a non-NULL unixpath, does that mean it's valid? */
276     {
277       sock = GNUNET_CONNECTION_create_from_connect_to_unixpath (cfg, unixpath);
278       if (sock != NULL)
279       {
280 #if DEBUG_CLIENT
281         LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to unixpath `%s'!\n",
282              unixpath);
283 #endif
284         GNUNET_free (unixpath);
285         return sock;
286       }
287     }
288     GNUNET_free_non_null (unixpath);
289   }
290 #endif
291
292   if ((GNUNET_OK !=
293        GNUNET_CONFIGURATION_get_value_number (cfg, service_name, "PORT", &port))
294       || (port > 65535) ||
295       (GNUNET_OK !=
296        GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "HOSTNAME",
297                                               &hostname)))
298   {
299     LOG (GNUNET_ERROR_TYPE_WARNING,
300          _
301          ("Could not determine valid hostname and port for service `%s' from configuration.\n"),
302          service_name);
303     return NULL;
304   }
305   if (0 == strlen (hostname))
306   {
307     GNUNET_free (hostname);
308     LOG (GNUNET_ERROR_TYPE_WARNING,
309          _("Need a non-empty hostname for service `%s'.\n"), service_name);
310     return NULL;
311   }
312   if (port == 0)
313   {
314 #if AF_UNIX
315     if (0 != (attempt % 2))
316     {
317       /* try UNIX */
318       unixpath = NULL;
319       if ((GNUNET_OK ==
320            GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "UNIXPATH",
321                                                   &unixpath)) &&
322           (0 < strlen (unixpath)))
323       {
324         sock =
325             GNUNET_CONNECTION_create_from_connect_to_unixpath (cfg, unixpath);
326         if (sock != NULL)
327         {
328           GNUNET_free (unixpath);
329           GNUNET_free (hostname);
330           return sock;
331         }
332       }
333       GNUNET_free_non_null (unixpath);
334     }
335 #endif
336 #if DEBUG_CLIENT
337     LOG (GNUNET_ERROR_TYPE_DEBUG,
338          "Port is 0 for service `%s', UNIXPATH did not work, returning NULL!\n",
339          service_name);
340 #endif
341     GNUNET_free (hostname);
342     return NULL;
343   }
344
345   sock = GNUNET_CONNECTION_create_from_connect (cfg, hostname, port);
346   GNUNET_free (hostname);
347   return sock;
348 }
349
350
351 /**
352  * Get a connection with a service.
353  *
354  * @param service_name name of the service
355  * @param cfg configuration to use
356  * @return NULL on error (service unknown to configuration)
357  */
358 struct GNUNET_CLIENT_Connection *
359 GNUNET_CLIENT_connect (const char *service_name,
360                        const struct GNUNET_CONFIGURATION_Handle *cfg)
361 {
362   struct GNUNET_CLIENT_Connection *ret;
363   struct GNUNET_CONNECTION_Handle *sock;
364
365   sock = do_connect (service_name, cfg, 0);
366   ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
367   ret->attempts = 1;
368   ret->sock = sock;
369   ret->service_name = GNUNET_strdup (service_name);
370   ret->cfg = cfg;
371   ret->back_off = GNUNET_TIME_UNIT_MILLISECONDS;
372   return ret;
373 }
374
375
376 /**
377  * Destroy connection with the service.  This will automatically
378  * cancel any pending "receive" request (however, the handler will
379  * *NOT* be called, not even with a NULL message).  Any pending
380  * transmission request will also be cancelled UNLESS the callback for
381  * the transmission request has already been called, in which case the
382  * transmission 'finish_pending_write' argument determines whether or
383  * not the write is guaranteed to complete before the socket is fully
384  * destroyed (unless, of course, there is an error with the server in
385  * which case the message may still be lost).
386  *
387  * @param finish_pending_write should a transmission already passed to the
388  *          handle be completed?
389  * @param sock handle to the service connection
390  */
391 void
392 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock,
393                           int finish_pending_write)
394 {
395   if (sock->in_receive == GNUNET_YES)
396   {
397     GNUNET_CONNECTION_receive_cancel (sock->sock);
398     sock->in_receive = GNUNET_NO;
399   }
400   if (sock->th != NULL)
401   {
402     GNUNET_CLIENT_notify_transmit_ready_cancel (sock->th);
403     sock->th = NULL;
404   }
405   if (NULL != sock->sock)
406   {
407     GNUNET_CONNECTION_destroy (sock->sock, finish_pending_write);
408     sock->sock = NULL;
409   }
410   if (sock->receive_task != GNUNET_SCHEDULER_NO_TASK)
411   {
412     GNUNET_SCHEDULER_cancel (sock->receive_task);
413     sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
414   }
415   if (sock->tag != NULL)
416   {
417     GNUNET_free (sock->tag);
418     sock->tag = NULL;
419   }
420   sock->receiver_handler = NULL;
421   GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
422   GNUNET_free (sock->service_name);
423   GNUNET_free (sock);
424 }
425
426
427 /**
428  * Check if message is complete
429  */
430 static void
431 check_complete (struct GNUNET_CLIENT_Connection *conn)
432 {
433   if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
434       (conn->received_pos >=
435        ntohs (((const struct GNUNET_MessageHeader *) conn->received_buf)->
436               size)))
437     conn->msg_complete = GNUNET_YES;
438 }
439
440
441 /**
442  * Callback function for data received from the network.  Note that
443  * both "available" and "errCode" would be 0 if the read simply timed out.
444  *
445  * @param cls closure
446  * @param buf pointer to received data
447  * @param available number of bytes availabe in "buf",
448  *        possibly 0 (on errors)
449  * @param addr address of the sender
450  * @param addrlen size of addr
451  * @param errCode value of errno (on errors receiving)
452  */
453 static void
454 receive_helper (void *cls, const void *buf, size_t available,
455                 const struct sockaddr *addr, socklen_t addrlen, int errCode)
456 {
457   struct GNUNET_CLIENT_Connection *conn = cls;
458   struct GNUNET_TIME_Relative remaining;
459   GNUNET_CLIENT_MessageHandler receive_handler;
460   void *receive_handler_cls;
461
462   GNUNET_assert (conn->msg_complete == GNUNET_NO);
463   conn->in_receive = GNUNET_NO;
464   if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
465   {
466     /* signal timeout! */
467 #if DEBUG_CLIENT
468     LOG (GNUNET_ERROR_TYPE_DEBUG,
469          "Timeout in receive_helper, available %u, conn->sock %s, errCode `%s'\n",
470          (unsigned int) available, conn->sock == NULL ? "NULL" : "non-NULL",
471          STRERROR (errCode));
472 #endif
473     if (NULL != (receive_handler = conn->receiver_handler))
474     {
475       receive_handler_cls = conn->receiver_handler_cls;
476       conn->receiver_handler = NULL;
477       receive_handler (receive_handler_cls, NULL);
478     }
479     return;
480   }
481
482   /* FIXME: optimize for common fast case where buf contains the
483    * entire message and we need no copying... */
484
485
486   /* slow path: append to array */
487   if (conn->received_size < conn->received_pos + available)
488     GNUNET_array_grow (conn->received_buf, conn->received_size,
489                        conn->received_pos + available);
490   memcpy (&conn->received_buf[conn->received_pos], buf, available);
491   conn->received_pos += available;
492   check_complete (conn);
493   /* check for timeout */
494   remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
495   if (remaining.rel_value == 0)
496   {
497     /* signal timeout! */
498     if (NULL != conn->receiver_handler)
499       conn->receiver_handler (conn->receiver_handler_cls, NULL);
500     return;
501   }
502   /* back to receive -- either for more data or to call callback! */
503   GNUNET_CLIENT_receive (conn, conn->receiver_handler,
504                          conn->receiver_handler_cls, remaining);
505 }
506
507
508 /**
509  * Continuation to call the receive callback.
510  *
511  * @param cls  our handle to the client connection
512  * @param tc scheduler context
513  */
514 static void
515 receive_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
516 {
517   struct GNUNET_CLIENT_Connection *sock = cls;
518   GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
519   const struct GNUNET_MessageHeader *cmsg =
520       (const struct GNUNET_MessageHeader *) sock->received_buf;
521   void *handler_cls = sock->receiver_handler_cls;
522   uint16_t msize = ntohs (cmsg->size);
523   char mbuf[msize];
524   struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) mbuf;
525
526 #if DEBUG_CLIENT
527   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received message of type %u and size %u\n",
528        ntohs (cmsg->type), msize);
529 #endif
530   sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
531   GNUNET_assert (GNUNET_YES == sock->msg_complete);
532   GNUNET_assert (sock->received_pos >= msize);
533   memcpy (msg, cmsg, msize);
534   memmove (sock->received_buf, &sock->received_buf[msize],
535            sock->received_pos - msize);
536   sock->received_pos -= msize;
537   sock->msg_complete = GNUNET_NO;
538   sock->receiver_handler = NULL;
539   check_complete (sock);
540   if (handler != NULL)
541     handler (handler_cls, msg);
542 }
543
544
545 /**
546  * Read from the service.
547  *
548  * @param sock the service
549  * @param handler function to call with the message
550  * @param handler_cls closure for handler
551  * @param timeout how long to wait until timing out
552  */
553 void
554 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
555                        GNUNET_CLIENT_MessageHandler handler, void *handler_cls,
556                        struct GNUNET_TIME_Relative timeout)
557 {
558   if (sock->sock == NULL)
559   {
560     /* already disconnected, fail instantly! */
561     GNUNET_break (0);           /* this should not happen in well-written code! */
562     if (NULL != handler)
563       handler (handler_cls, NULL);
564     return;
565   }
566   sock->receiver_handler = handler;
567   sock->receiver_handler_cls = handler_cls;
568   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
569   if (GNUNET_YES == sock->msg_complete)
570   {
571     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->receive_task);
572     sock->receive_task = GNUNET_SCHEDULER_add_now (&receive_task, sock);
573   }
574   else
575   {
576     GNUNET_assert (sock->in_receive == GNUNET_NO);
577     sock->in_receive = GNUNET_YES;
578 #if DEBUG_CLIENT
579     LOG (GNUNET_ERROR_TYPE_DEBUG, "calling GNUNET_CONNECTION_receive\n");
580 #endif
581     GNUNET_CONNECTION_receive (sock->sock, GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
582                                timeout, &receive_helper, sock);
583   }
584 }
585
586
587 /**
588  * Report service unavailable.
589  */
590 static void
591 service_test_error (GNUNET_SCHEDULER_Task task, void *task_cls)
592 {
593   GNUNET_SCHEDULER_add_continuation (task, task_cls,
594                                      GNUNET_SCHEDULER_REASON_TIMEOUT);
595 }
596
597
598 /**
599  * Receive confirmation from test, service is up.
600  *
601  * @param cls closure
602  * @param msg message received, NULL on timeout or fatal error
603  */
604 static void
605 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
606 {
607   struct GNUNET_CLIENT_Connection *conn = cls;
608
609   /* We may want to consider looking at the reply in more
610    * detail in the future, for example, is this the
611    * correct service? FIXME! */
612   if (msg != NULL)
613   {
614 #if DEBUG_CLIENT
615     LOG (GNUNET_ERROR_TYPE_DEBUG,
616          "Received confirmation that service is running.\n");
617 #endif
618     GNUNET_SCHEDULER_add_continuation (conn->test_cb, conn->test_cb_cls,
619                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
620   }
621   else
622   {
623     service_test_error (conn->test_cb, conn->test_cb_cls);
624   }
625   GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
626 }
627
628
629 /**
630  * Send the 'TEST' message to the service.  If successful, prepare to
631  * receive the reply.
632  *
633  * @param cls the 'struct GNUNET_CLIENT_Connection' of the connection to test
634  * @param size number of bytes available in buf
635  * @param buf where to write the message
636  * @return number of bytes written to buf
637  */
638 static size_t
639 write_test (void *cls, size_t size, void *buf)
640 {
641   struct GNUNET_CLIENT_Connection *conn = cls;
642   struct GNUNET_MessageHeader *msg;
643
644   if (size < sizeof (struct GNUNET_MessageHeader))
645   {
646 #if DEBUG_CLIENT
647     LOG (GNUNET_ERROR_TYPE_DEBUG, _("Failure to transmit TEST request.\n"));
648 #endif
649     service_test_error (conn->test_cb, conn->test_cb_cls);
650     GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
651     return 0;                   /* client disconnected */
652   }
653 #if DEBUG_CLIENT
654   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' request.\n", "TEST");
655 #endif
656   msg = (struct GNUNET_MessageHeader *) buf;
657   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
658   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
659   GNUNET_CLIENT_receive (conn, &confirm_handler, conn,
660                          GNUNET_TIME_absolute_get_remaining
661                          (conn->test_deadline));
662   return sizeof (struct GNUNET_MessageHeader);
663 }
664
665
666 /**
667  * Test if the service is running.  If we are given a UNIXPATH or a local address,
668  * we do this NOT by trying to connect to the service, but by trying to BIND to
669  * the same port.  If the BIND fails, we know the service is running.
670  *
671  * @param service name of the service to wait for
672  * @param cfg configuration to use
673  * @param timeout how long to wait at most
674  * @param task task to run if service is running
675  *        (reason will be "PREREQ_DONE" (service running)
676  *         or "TIMEOUT" (service not known to be running))
677  * @param task_cls closure for task
678  */
679 void
680 GNUNET_CLIENT_service_test (const char *service,
681                             const struct GNUNET_CONFIGURATION_Handle *cfg,
682                             struct GNUNET_TIME_Relative timeout,
683                             GNUNET_SCHEDULER_Task task, void *task_cls)
684 {
685   char *hostname;
686   unsigned long long port;
687   struct GNUNET_NETWORK_Handle *sock;
688   struct GNUNET_CLIENT_Connection *conn;
689
690 #if DEBUG_CLIENT
691   LOG (GNUNET_ERROR_TYPE_DEBUG, "Testing if service `%s' is running.\n",
692        service);
693 #endif
694 #ifdef AF_UNIX
695   {
696     /* probe UNIX support */
697     struct sockaddr_un s_un;
698     size_t slen;
699     char *unixpath;
700
701     unixpath = NULL;
702     if ((GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, service, "UNIXPATH", &unixpath)) && (0 < strlen (unixpath)))  /* We have a non-NULL unixpath, does that mean it's valid? */
703     {
704       if (strlen (unixpath) >= sizeof (s_un.sun_path))
705       {
706         LOG (GNUNET_ERROR_TYPE_WARNING,
707              _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
708              sizeof (s_un.sun_path));
709       }
710       else
711       {
712         sock = GNUNET_NETWORK_socket_create (PF_UNIX, SOCK_STREAM, 0);
713         if (sock != NULL)
714         {
715           memset (&s_un, 0, sizeof (s_un));
716           s_un.sun_family = AF_UNIX;
717           slen = strlen (unixpath) + 1;
718           if (slen >= sizeof (s_un.sun_path))
719             slen = sizeof (s_un.sun_path) - 1;
720           memcpy (s_un.sun_path, unixpath, slen);
721           s_un.sun_path[slen] = '\0';
722           slen = sizeof (struct sockaddr_un);
723 #if LINUX
724           s_un.sun_path[0] = '\0';
725 #endif
726 #if HAVE_SOCKADDR_IN_SIN_LEN
727           s_un.sun_len = (u_char) slen;
728 #endif
729           if (GNUNET_OK !=
730               GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_un,
731                                           slen))
732           {
733             /* failed to bind => service must be running */
734             GNUNET_free (unixpath);
735             (void) GNUNET_NETWORK_socket_close (sock);
736             GNUNET_SCHEDULER_add_continuation (task, task_cls,
737                                                GNUNET_SCHEDULER_REASON_PREREQ_DONE);
738             return;
739           }
740           (void) GNUNET_NETWORK_socket_close (sock);
741         }
742         /* let's try IP */
743       }
744     }
745     GNUNET_free_non_null (unixpath);
746   }
747 #endif
748
749   hostname = NULL;
750   if ((GNUNET_OK !=
751        GNUNET_CONFIGURATION_get_value_number (cfg, service, "PORT", &port)) ||
752       (port > 65535) ||
753       (GNUNET_OK !=
754        GNUNET_CONFIGURATION_get_value_string (cfg, service, "HOSTNAME",
755                                               &hostname)))
756   {
757     /* UNIXPATH failed (if possible) AND IP failed => error */
758     service_test_error (task, task_cls);
759     return;
760   }
761
762   if (0 == strcmp ("localhost", hostname)
763 #if !LINUX
764       && 0
765 #endif
766       )
767   {
768     /* can test using 'bind' */
769     struct sockaddr_in s_in;
770
771     memset (&s_in, 0, sizeof (s_in));
772 #if HAVE_SOCKADDR_IN_SIN_LEN
773     s_in.sin_len = sizeof (struct sockaddr_in);
774 #endif
775     s_in.sin_family = AF_INET;
776     s_in.sin_port = htons (port);
777
778     sock = GNUNET_NETWORK_socket_create (AF_INET, SOCK_STREAM, 0);
779     if (sock != NULL)
780     {
781       if (GNUNET_OK !=
782           GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_in,
783                                       sizeof (s_in)))
784       {
785         /* failed to bind => service must be running */
786         GNUNET_free (hostname);
787         (void) GNUNET_NETWORK_socket_close (sock);
788         GNUNET_SCHEDULER_add_continuation (task, task_cls,
789                                            GNUNET_SCHEDULER_REASON_PREREQ_DONE);
790         return;
791       }
792       (void) GNUNET_NETWORK_socket_close (sock);
793     }
794   }
795
796   if (0 == strcmp ("ip6-localhost", hostname)
797 #if !LINUX
798       && 0
799 #endif
800       )
801   {
802     /* can test using 'bind' */
803     struct sockaddr_in6 s_in6;
804
805     memset (&s_in6, 0, sizeof (s_in6));
806 #if HAVE_SOCKADDR_IN_SIN_LEN
807     s_in6.sin6_len = sizeof (struct sockaddr_in6);
808 #endif
809     s_in6.sin6_family = AF_INET6;
810     s_in6.sin6_port = htons (port);
811
812     sock = GNUNET_NETWORK_socket_create (AF_INET6, SOCK_STREAM, 0);
813     if (sock != NULL)
814     {
815       if (GNUNET_OK !=
816           GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_in6,
817                                       sizeof (s_in6)))
818       {
819         /* failed to bind => service must be running */
820         GNUNET_free (hostname);
821         (void) GNUNET_NETWORK_socket_close (sock);
822         GNUNET_SCHEDULER_add_continuation (task, task_cls,
823                                            GNUNET_SCHEDULER_REASON_PREREQ_DONE);
824         return;
825       }
826       (void) GNUNET_NETWORK_socket_close (sock);
827     }
828   }
829
830   if (((0 == strcmp ("localhost", hostname)) ||
831        (0 == strcmp ("ip6-localhost", hostname)))
832 #if !LINUX
833       && 0
834 #endif
835       )
836   {
837     /* all binds succeeded => claim service not running right now */
838     GNUNET_free_non_null (hostname);
839     service_test_error (task, task_cls);
840     return;
841   }
842   GNUNET_free_non_null (hostname);
843
844   /* non-localhost, try 'connect' method */
845   conn = GNUNET_CLIENT_connect (service, cfg);
846   if (conn == NULL)
847   {
848     LOG (GNUNET_ERROR_TYPE_INFO,
849          _("Could not connect to service `%s', must not be running.\n"),
850          service);
851     service_test_error (task, task_cls);
852     return;
853   }
854   conn->test_cb = task;
855   conn->test_cb_cls = task_cls;
856   conn->test_deadline = GNUNET_TIME_relative_to_absolute (timeout);
857
858   if (NULL ==
859       GNUNET_CLIENT_notify_transmit_ready (conn,
860                                            sizeof (struct GNUNET_MessageHeader),
861                                            timeout, GNUNET_YES, &write_test,
862                                            conn))
863   {
864     LOG (GNUNET_ERROR_TYPE_WARNING,
865          _("Failure to transmit request to service `%s'\n"), service);
866     service_test_error (task, task_cls);
867     GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
868     return;
869   }
870 }
871
872
873 /**
874  * Connection notifies us about failure or success of
875  * a transmission request.  Either pass it on to our
876  * user or, if possible, retry.
877  *
878  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
879  * @param size number of bytes available for transmission
880  * @param buf where to write them
881  * @return number of bytes written to buf
882  */
883 static size_t
884 client_notify (void *cls, size_t size, void *buf);
885
886
887 /**
888  * This task is run if we should re-try connection to the
889  * service after a while.
890  *
891  * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
892  * @param tc unused
893  */
894 static void
895 client_delayed_retry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
896 {
897   struct GNUNET_CLIENT_TransmitHandle *th = cls;
898   struct GNUNET_TIME_Relative delay;
899
900   th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
901   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
902   {
903 #if DEBUG_CLIENT
904     LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmission failed due to shutdown.\n");
905 #endif
906     th->sock->th = NULL;
907     th->notify (th->notify_cls, 0, NULL);
908     GNUNET_free (th);
909     return;
910   }
911   th->sock->sock =
912       do_connect (th->sock->service_name, th->sock->cfg, th->sock->attempts++);
913   if (NULL == th->sock->sock)
914   {
915     /* could happen if we're out of sockets */
916     delay =
917         GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining
918                                   (th->timeout), th->sock->back_off);
919     th->sock->back_off =
920         GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
921                                   (th->sock->back_off, 2),
922                                   GNUNET_TIME_UNIT_SECONDS);
923 #if DEBUG_CLIENT
924     LOG (GNUNET_ERROR_TYPE_DEBUG,
925          "Transmission failed %u times, trying again in %llums.\n",
926          MAX_ATTEMPTS - th->attempts_left,
927          (unsigned long long) delay.rel_value);
928 #endif
929     th->reconnect_task =
930         GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
931     return;
932   }
933   th->th =
934       GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock, th->size,
935                                                GNUNET_TIME_absolute_get_remaining
936                                                (th->timeout), &client_notify,
937                                                th);
938   if (th->th == NULL)
939   {
940     GNUNET_break (0);
941     th->sock->th = NULL;
942     th->notify (th->notify_cls, 0, NULL);
943     GNUNET_free (th);
944     return;
945   }
946 }
947
948
949 /**
950  * Connection notifies us about failure or success of a transmission
951  * request.  Either pass it on to our user or, if possible, retry.
952  *
953  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
954  * @param size number of bytes available for transmission
955  * @param buf where to write them
956  * @return number of bytes written to buf
957  */
958 static size_t
959 client_notify (void *cls, size_t size, void *buf)
960 {
961   struct GNUNET_CLIENT_TransmitHandle *th = cls;
962   size_t ret;
963   struct GNUNET_TIME_Relative delay;
964
965   th->th = NULL;
966   th->sock->th = NULL;
967   if (buf == NULL)
968   {
969     delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
970     delay.rel_value /= 2;
971     if ((0 !=
972          (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason ())) ||
973         (GNUNET_YES != th->auto_retry) || (0 == --th->attempts_left) ||
974         (delay.rel_value < 1))
975     {
976 #if DEBUG_CLIENT
977       LOG (GNUNET_ERROR_TYPE_DEBUG,
978            "Transmission failed %u times, giving up.\n",
979            MAX_ATTEMPTS - th->attempts_left);
980 #endif
981       GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
982       GNUNET_free (th);
983       return 0;
984     }
985     /* auto-retry */
986 #if DEBUG_CLIENT
987     LOG (GNUNET_ERROR_TYPE_DEBUG,
988          "Failed to connect to `%s', automatically trying again.\n",
989          th->sock->service_name);
990 #endif
991     GNUNET_CONNECTION_destroy (th->sock->sock, GNUNET_NO);
992     th->sock->sock = NULL;
993     delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
994     th->sock->back_off =
995         GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
996                                   (th->sock->back_off, 2),
997                                   GNUNET_TIME_UNIT_SECONDS);
998 #if DEBUG_CLIENT
999     LOG (GNUNET_ERROR_TYPE_DEBUG,
1000          "Transmission failed %u times, trying again in %llums.\n",
1001          MAX_ATTEMPTS - th->attempts_left,
1002          (unsigned long long) delay.rel_value);
1003 #endif
1004     th->sock->th = th;
1005     th->reconnect_task =
1006         GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
1007     return 0;
1008   }
1009   GNUNET_assert (size >= th->size);
1010   ret = th->notify (th->notify_cls, size, buf);
1011   GNUNET_free (th);
1012   return ret;
1013 }
1014
1015
1016 /**
1017  * Ask the client to call us once the specified number of bytes
1018  * are free in the transmission buffer.  May call the notify
1019  * method immediately if enough space is available.
1020  *
1021  * @param sock connection to the service
1022  * @param size number of bytes to send
1023  * @param timeout after how long should we give up (and call
1024  *        notify with buf NULL and size 0)?
1025  * @param auto_retry if the connection to the service dies, should we
1026  *        automatically re-connect and retry (within the timeout period)
1027  *        or should we immediately fail in this case?  Pass GNUNET_YES
1028  *        if the caller does not care about temporary connection errors,
1029  *        for example because the protocol is stateless
1030  * @param notify function to call
1031  * @param notify_cls closure for notify
1032  * @return NULL if our buffer will never hold size bytes,
1033  *         a handle if the notify callback was queued (can be used to cancel)
1034  */
1035 struct GNUNET_CLIENT_TransmitHandle *
1036 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
1037                                      size_t size,
1038                                      struct GNUNET_TIME_Relative timeout,
1039                                      int auto_retry,
1040                                      GNUNET_CONNECTION_TransmitReadyNotify
1041                                      notify, void *notify_cls)
1042 {
1043   struct GNUNET_CLIENT_TransmitHandle *th;
1044
1045   if (NULL != sock->th)
1046   {
1047     /* If this breaks, you most likley called this function twice without waiting
1048      * for completion or canceling the request */
1049     GNUNET_break (0);
1050     return NULL;
1051   }
1052   th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
1053   th->sock = sock;
1054   th->size = size;
1055   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1056   th->auto_retry = auto_retry;
1057   th->notify = notify;
1058   th->notify_cls = notify_cls;
1059   th->attempts_left = MAX_ATTEMPTS;
1060   sock->th = th;
1061   if (sock->sock == NULL)
1062   {
1063     th->reconnect_task =
1064         GNUNET_SCHEDULER_add_delayed (sock->back_off, &client_delayed_retry,
1065                                       th);
1066
1067   }
1068   else
1069   {
1070     th->th =
1071         GNUNET_CONNECTION_notify_transmit_ready (sock->sock, size, timeout,
1072                                                  &client_notify, th);
1073     if (NULL == th->th)
1074     {
1075       GNUNET_break (0);
1076       GNUNET_free (th);
1077       sock->th = NULL;
1078       return NULL;
1079     }
1080   }
1081   return th;
1082 }
1083
1084
1085 /**
1086  * Cancel a request for notification.
1087  *
1088  * @param th handle from the original request.
1089  */
1090 void
1091 GNUNET_CLIENT_notify_transmit_ready_cancel (struct GNUNET_CLIENT_TransmitHandle
1092                                             *th)
1093 {
1094   if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1095   {
1096     GNUNET_assert (NULL == th->th);
1097     GNUNET_SCHEDULER_cancel (th->reconnect_task);
1098     th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1099   }
1100   else
1101   {
1102     GNUNET_assert (NULL != th->th);
1103     GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
1104   }
1105   th->sock->th = NULL;
1106   GNUNET_free (th);
1107 }
1108
1109
1110 /**
1111  * Function called to notify a client about the socket
1112  * begin ready to queue the message.  "buf" will be
1113  * NULL and "size" zero if the socket was closed for
1114  * writing in the meantime.
1115  *
1116  * @param cls closure of type "struct TransmitGetResponseContext*"
1117  * @param size number of bytes available in buf
1118  * @param buf where the callee should write the message
1119  * @return number of bytes written to buf
1120  */
1121 static size_t
1122 transmit_for_response (void *cls, size_t size, void *buf)
1123 {
1124   struct TransmitGetResponseContext *tc = cls;
1125   uint16_t msize;
1126
1127   tc->sock->tag = NULL;
1128   msize = ntohs (tc->hdr->size);
1129   if (NULL == buf)
1130   {
1131 #if DEBUG_CLIENT
1132     LOG (GNUNET_ERROR_TYPE_DEBUG,
1133          _("Could not submit request, not expecting to receive a response.\n"));
1134 #endif
1135     if (NULL != tc->rn)
1136       tc->rn (tc->rn_cls, NULL);
1137     GNUNET_free (tc);
1138     return 0;
1139   }
1140   GNUNET_assert (size >= msize);
1141   memcpy (buf, tc->hdr, msize);
1142   GNUNET_CLIENT_receive (tc->sock, tc->rn, tc->rn_cls,
1143                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
1144   GNUNET_free (tc);
1145   return msize;
1146 }
1147
1148
1149 /**
1150  * Convenience API that combines sending a request
1151  * to the service and waiting for a response.
1152  * If either operation times out, the callback
1153  * will be called with a "NULL" response (in which
1154  * case the connection should probably be destroyed).
1155  *
1156  * @param sock connection to use
1157  * @param hdr message to transmit
1158  * @param timeout when to give up (for both transmission
1159  *         and for waiting for a response)
1160  * @param auto_retry if the connection to the service dies, should we
1161  *        automatically re-connect and retry (within the timeout period)
1162  *        or should we immediately fail in this case?  Pass GNUNET_YES
1163  *        if the caller does not care about temporary connection errors,
1164  *        for example because the protocol is stateless
1165  * @param rn function to call with the response
1166  * @param rn_cls closure for rn
1167  * @return GNUNET_OK on success, GNUNET_SYSERR if a request
1168  *         is already pending
1169  */
1170 int
1171 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
1172                                          const struct GNUNET_MessageHeader *hdr,
1173                                          struct GNUNET_TIME_Relative timeout,
1174                                          int auto_retry,
1175                                          GNUNET_CLIENT_MessageHandler rn,
1176                                          void *rn_cls)
1177 {
1178   struct TransmitGetResponseContext *tc;
1179   uint16_t msize;
1180
1181   if (NULL != sock->th)
1182     return GNUNET_SYSERR;
1183   GNUNET_assert (sock->tag == NULL);
1184   msize = ntohs (hdr->size);
1185   tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
1186   tc->sock = sock;
1187   tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
1188   memcpy (&tc[1], hdr, msize);
1189   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1190   tc->rn = rn;
1191   tc->rn_cls = rn_cls;
1192   if (NULL ==
1193       GNUNET_CLIENT_notify_transmit_ready (sock, msize, timeout, auto_retry,
1194                                            &transmit_for_response, tc))
1195   {
1196     GNUNET_break (0);
1197     GNUNET_free (tc);
1198     return GNUNET_SYSERR;
1199   }
1200   sock->tag = tc;
1201   return GNUNET_OK;
1202 }
1203
1204
1205
1206 /*  end of client.c */