64ab1e23826cf3dc0a71dc3c753bd0220958437e
[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         LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to unixpath `%s'!\n",
281              unixpath);
282         GNUNET_free (unixpath);
283         return sock;
284       }
285     }
286     GNUNET_free_non_null (unixpath);
287   }
288 #endif
289
290   if (GNUNET_YES ==
291       GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
292   {
293     if ((GNUNET_OK !=
294          GNUNET_CONFIGURATION_get_value_number (cfg, service_name, "PORT", &port))
295         || (port > 65535) ||
296         (GNUNET_OK !=
297          GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "HOSTNAME",
298                                                 &hostname)))
299     {
300       LOG (GNUNET_ERROR_TYPE_WARNING,
301            _
302            ("Could not determine valid hostname and port for service `%s' from configuration.\n"),
303            service_name);
304       return NULL;
305     }
306     if (0 == strlen (hostname))
307     {
308       GNUNET_free (hostname);
309       LOG (GNUNET_ERROR_TYPE_WARNING,
310            _("Need a non-empty hostname for service `%s'.\n"), service_name);
311       return NULL;
312     }
313   }
314   else
315   {
316     /* unspecified means 0 (disabled) */
317     port = 0;
318     hostname = NULL;
319   }
320   if (port == 0)
321   {
322 #if AF_UNIX
323     if (0 != (attempt % 2))
324     {
325       /* try UNIX */
326       unixpath = NULL;
327       if ((GNUNET_OK ==
328            GNUNET_CONFIGURATION_get_value_string (cfg, service_name, "UNIXPATH",
329                                                   &unixpath)) &&
330           (0 < strlen (unixpath)))
331       {
332         sock =
333             GNUNET_CONNECTION_create_from_connect_to_unixpath (cfg, unixpath);
334         if (sock != NULL)
335         {
336           GNUNET_free (unixpath);
337           GNUNET_free_non_null (hostname);
338           return sock;
339         }
340       }
341       GNUNET_free_non_null (unixpath);
342     }
343 #endif
344     LOG (GNUNET_ERROR_TYPE_DEBUG,
345          "Port is 0 for service `%s', UNIXPATH did not work, returning NULL!\n",
346          service_name);
347     GNUNET_free_non_null (hostname);
348     return NULL;
349   }
350
351   sock = GNUNET_CONNECTION_create_from_connect (cfg, hostname, port);
352   GNUNET_free (hostname);
353   return sock;
354 }
355
356
357 /**
358  * Get a connection with a service.
359  *
360  * @param service_name name of the service
361  * @param cfg configuration to use
362  * @return NULL on error (service unknown to configuration)
363  */
364 struct GNUNET_CLIENT_Connection *
365 GNUNET_CLIENT_connect (const char *service_name,
366                        const struct GNUNET_CONFIGURATION_Handle *cfg)
367 {
368   struct GNUNET_CLIENT_Connection *ret;
369   struct GNUNET_CONNECTION_Handle *sock;
370
371   sock = do_connect (service_name, cfg, 0);
372   ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
373   ret->attempts = 1;
374   ret->sock = sock;
375   ret->service_name = GNUNET_strdup (service_name);
376   ret->cfg = cfg;
377   ret->back_off = GNUNET_TIME_UNIT_MILLISECONDS;
378   return ret;
379 }
380
381
382 /**
383  * Destroy connection with the service.  This will automatically
384  * cancel any pending "receive" request (however, the handler will
385  * *NOT* be called, not even with a NULL message).  Any pending
386  * transmission request will also be cancelled UNLESS the callback for
387  * the transmission request has already been called, in which case the
388  * transmission 'finish_pending_write' argument determines whether or
389  * not the write is guaranteed to complete before the socket is fully
390  * destroyed (unless, of course, there is an error with the server in
391  * which case the message may still be lost).
392  *
393  * @param finish_pending_write should a transmission already passed to the
394  *          handle be completed?
395  * @param sock handle to the service connection
396  */
397 void
398 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock,
399                           int finish_pending_write)
400 {
401   if (sock->in_receive == GNUNET_YES)
402   {
403     GNUNET_CONNECTION_receive_cancel (sock->sock);
404     sock->in_receive = GNUNET_NO;
405   }
406   if (sock->th != NULL)
407   {
408     GNUNET_CLIENT_notify_transmit_ready_cancel (sock->th);
409     sock->th = NULL;
410   }
411   if (NULL != sock->sock)
412   {
413     GNUNET_CONNECTION_destroy (sock->sock, finish_pending_write);
414     sock->sock = NULL;
415   }
416   if (sock->receive_task != GNUNET_SCHEDULER_NO_TASK)
417   {
418     GNUNET_SCHEDULER_cancel (sock->receive_task);
419     sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
420   }
421   if (sock->tag != NULL)
422   {
423     GNUNET_free (sock->tag);
424     sock->tag = NULL;
425   }
426   sock->receiver_handler = NULL;
427   GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
428   GNUNET_free (sock->service_name);
429   GNUNET_free (sock);
430 }
431
432
433 /**
434  * Check if message is complete
435  */
436 static void
437 check_complete (struct GNUNET_CLIENT_Connection *conn)
438 {
439   if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
440       (conn->received_pos >=
441        ntohs (((const struct GNUNET_MessageHeader *) conn->received_buf)->
442               size)))
443     conn->msg_complete = GNUNET_YES;
444 }
445
446
447 /**
448  * Callback function for data received from the network.  Note that
449  * both "available" and "errCode" would be 0 if the read simply timed out.
450  *
451  * @param cls closure
452  * @param buf pointer to received data
453  * @param available number of bytes availabe in "buf",
454  *        possibly 0 (on errors)
455  * @param addr address of the sender
456  * @param addrlen size of addr
457  * @param errCode value of errno (on errors receiving)
458  */
459 static void
460 receive_helper (void *cls, const void *buf, size_t available,
461                 const struct sockaddr *addr, socklen_t addrlen, int errCode)
462 {
463   struct GNUNET_CLIENT_Connection *conn = cls;
464   struct GNUNET_TIME_Relative remaining;
465   GNUNET_CLIENT_MessageHandler receive_handler;
466   void *receive_handler_cls;
467
468   GNUNET_assert (conn->msg_complete == GNUNET_NO);
469   conn->in_receive = GNUNET_NO;
470   if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
471   {
472     /* signal timeout! */
473     LOG (GNUNET_ERROR_TYPE_DEBUG,
474          "Timeout in receive_helper, available %u, conn->sock %s, errCode `%s'\n",
475          (unsigned int) available, conn->sock == NULL ? "NULL" : "non-NULL",
476          STRERROR (errCode));
477     if (NULL != (receive_handler = conn->receiver_handler))
478     {
479       receive_handler_cls = conn->receiver_handler_cls;
480       conn->receiver_handler = NULL;
481       receive_handler (receive_handler_cls, NULL);
482     }
483     return;
484   }
485
486   /* FIXME: optimize for common fast case where buf contains the
487    * entire message and we need no copying... */
488
489
490   /* slow path: append to array */
491   if (conn->received_size < conn->received_pos + available)
492     GNUNET_array_grow (conn->received_buf, conn->received_size,
493                        conn->received_pos + available);
494   memcpy (&conn->received_buf[conn->received_pos], buf, available);
495   conn->received_pos += available;
496   check_complete (conn);
497   /* check for timeout */
498   remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
499   if (remaining.rel_value == 0)
500   {
501     /* signal timeout! */
502     if (NULL != conn->receiver_handler)
503       conn->receiver_handler (conn->receiver_handler_cls, NULL);
504     return;
505   }
506   /* back to receive -- either for more data or to call callback! */
507   GNUNET_CLIENT_receive (conn, conn->receiver_handler,
508                          conn->receiver_handler_cls, remaining);
509 }
510
511
512 /**
513  * Continuation to call the receive callback.
514  *
515  * @param cls  our handle to the client connection
516  * @param tc scheduler context
517  */
518 static void
519 receive_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
520 {
521   struct GNUNET_CLIENT_Connection *sock = cls;
522   GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
523   const struct GNUNET_MessageHeader *cmsg =
524       (const struct GNUNET_MessageHeader *) sock->received_buf;
525   void *handler_cls = sock->receiver_handler_cls;
526   uint16_t msize = ntohs (cmsg->size);
527   char mbuf[msize];
528   struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) mbuf;
529
530   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received message of type %u and size %u\n",
531        ntohs (cmsg->type), msize);
532   sock->receive_task = GNUNET_SCHEDULER_NO_TASK;
533   GNUNET_assert (GNUNET_YES == sock->msg_complete);
534   GNUNET_assert (sock->received_pos >= msize);
535   memcpy (msg, cmsg, msize);
536   memmove (sock->received_buf, &sock->received_buf[msize],
537            sock->received_pos - msize);
538   sock->received_pos -= msize;
539   sock->msg_complete = GNUNET_NO;
540   sock->receiver_handler = NULL;
541   check_complete (sock);
542   if (handler != NULL)
543     handler (handler_cls, msg);
544 }
545
546
547 /**
548  * Read from the service.
549  *
550  * @param sock the service
551  * @param handler function to call with the message
552  * @param handler_cls closure for handler
553  * @param timeout how long to wait until timing out
554  */
555 void
556 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
557                        GNUNET_CLIENT_MessageHandler handler, void *handler_cls,
558                        struct GNUNET_TIME_Relative timeout)
559 {
560   if (sock->sock == NULL)
561   {
562     /* already disconnected, fail instantly! */
563     GNUNET_break (0);           /* this should not happen in well-written code! */
564     if (NULL != handler)
565       handler (handler_cls, NULL);
566     return;
567   }
568   sock->receiver_handler = handler;
569   sock->receiver_handler_cls = handler_cls;
570   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
571   if (GNUNET_YES == sock->msg_complete)
572   {
573     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == sock->receive_task);
574     sock->receive_task = GNUNET_SCHEDULER_add_now (&receive_task, sock);
575   }
576   else
577   {
578     GNUNET_assert (sock->in_receive == GNUNET_NO);
579     sock->in_receive = GNUNET_YES;
580     LOG (GNUNET_ERROR_TYPE_DEBUG, "calling GNUNET_CONNECTION_receive\n");
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     LOG (GNUNET_ERROR_TYPE_DEBUG,
615          "Received confirmation that service is running.\n");
616     GNUNET_SCHEDULER_add_continuation (conn->test_cb, conn->test_cb_cls,
617                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
618   }
619   else
620   {
621     service_test_error (conn->test_cb, conn->test_cb_cls);
622   }
623   GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
624 }
625
626
627 /**
628  * Send the 'TEST' message to the service.  If successful, prepare to
629  * receive the reply.
630  *
631  * @param cls the 'struct GNUNET_CLIENT_Connection' of the connection to test
632  * @param size number of bytes available in buf
633  * @param buf where to write the message
634  * @return number of bytes written to buf
635  */
636 static size_t
637 write_test (void *cls, size_t size, void *buf)
638 {
639   struct GNUNET_CLIENT_Connection *conn = cls;
640   struct GNUNET_MessageHeader *msg;
641
642   if (size < sizeof (struct GNUNET_MessageHeader))
643   {
644     LOG (GNUNET_ERROR_TYPE_DEBUG, _("Failure to transmit TEST request.\n"));
645     service_test_error (conn->test_cb, conn->test_cb_cls);
646     GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
647     return 0;                   /* client disconnected */
648   }
649   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' request.\n", "TEST");
650   msg = (struct GNUNET_MessageHeader *) buf;
651   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
652   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
653   GNUNET_CLIENT_receive (conn, &confirm_handler, conn,
654                          GNUNET_TIME_absolute_get_remaining
655                          (conn->test_deadline));
656   return sizeof (struct GNUNET_MessageHeader);
657 }
658
659
660 /**
661  * Test if the service is running.  If we are given a UNIXPATH or a local address,
662  * we do this NOT by trying to connect to the service, but by trying to BIND to
663  * the same port.  If the BIND fails, we know the service is running.
664  *
665  * @param service name of the service to wait for
666  * @param cfg configuration to use
667  * @param timeout how long to wait at most
668  * @param task task to run if service is running
669  *        (reason will be "PREREQ_DONE" (service running)
670  *         or "TIMEOUT" (service not known to be running))
671  * @param task_cls closure for task
672  */
673 void
674 GNUNET_CLIENT_service_test (const char *service,
675                             const struct GNUNET_CONFIGURATION_Handle *cfg,
676                             struct GNUNET_TIME_Relative timeout,
677                             GNUNET_SCHEDULER_Task task, void *task_cls)
678 {
679   char *hostname;
680   unsigned long long port;
681   struct GNUNET_NETWORK_Handle *sock;
682   struct GNUNET_CLIENT_Connection *conn;
683
684   LOG (GNUNET_ERROR_TYPE_DEBUG, "Testing if service `%s' is running.\n",
685        service);
686 #ifdef AF_UNIX
687   {
688     /* probe UNIX support */
689     struct sockaddr_un s_un;
690     size_t slen;
691     char *unixpath;
692
693     unixpath = NULL;
694     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? */
695     {
696       if (strlen (unixpath) >= sizeof (s_un.sun_path))
697       {
698         LOG (GNUNET_ERROR_TYPE_WARNING,
699              _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
700              sizeof (s_un.sun_path));
701       }
702       else
703       {
704         sock = GNUNET_NETWORK_socket_create (PF_UNIX, SOCK_STREAM, 0);
705         if (sock != NULL)
706         {
707           memset (&s_un, 0, sizeof (s_un));
708           s_un.sun_family = AF_UNIX;
709           slen = strlen (unixpath) + 1;
710           if (slen >= sizeof (s_un.sun_path))
711             slen = sizeof (s_un.sun_path) - 1;
712           memcpy (s_un.sun_path, unixpath, slen);
713           s_un.sun_path[slen] = '\0';
714           slen = sizeof (struct sockaddr_un);
715 #if LINUX
716           s_un.sun_path[0] = '\0';
717 #endif
718 #if HAVE_SOCKADDR_IN_SIN_LEN
719           s_un.sun_len = (u_char) slen;
720 #endif
721           if (GNUNET_OK !=
722               GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_un,
723                                           slen))
724           {
725             /* failed to bind => service must be running */
726             GNUNET_free (unixpath);
727             (void) GNUNET_NETWORK_socket_close (sock);
728             GNUNET_SCHEDULER_add_continuation (task, task_cls,
729                                                GNUNET_SCHEDULER_REASON_PREREQ_DONE);
730             return;
731           }
732           (void) GNUNET_NETWORK_socket_close (sock);
733         }
734         /* let's try IP */
735       }
736     }
737     GNUNET_free_non_null (unixpath);
738   }
739 #endif
740
741   hostname = NULL;
742   if ((GNUNET_OK !=
743        GNUNET_CONFIGURATION_get_value_number (cfg, service, "PORT", &port)) ||
744       (port > 65535) ||
745       (GNUNET_OK !=
746        GNUNET_CONFIGURATION_get_value_string (cfg, service, "HOSTNAME",
747                                               &hostname)))
748   {
749     /* UNIXPATH failed (if possible) AND IP failed => error */
750     service_test_error (task, task_cls);
751     return;
752   }
753
754   if (0 == strcmp ("localhost", hostname)
755 #if !LINUX
756       && 0
757 #endif
758       )
759   {
760     /* can test using 'bind' */
761     struct sockaddr_in s_in;
762
763     memset (&s_in, 0, sizeof (s_in));
764 #if HAVE_SOCKADDR_IN_SIN_LEN
765     s_in.sin_len = sizeof (struct sockaddr_in);
766 #endif
767     s_in.sin_family = AF_INET;
768     s_in.sin_port = htons (port);
769
770     sock = GNUNET_NETWORK_socket_create (AF_INET, SOCK_STREAM, 0);
771     if (sock != NULL)
772     {
773       if (GNUNET_OK !=
774           GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_in,
775                                       sizeof (s_in)))
776       {
777         /* failed to bind => service must be running */
778         GNUNET_free (hostname);
779         (void) GNUNET_NETWORK_socket_close (sock);
780         GNUNET_SCHEDULER_add_continuation (task, task_cls,
781                                            GNUNET_SCHEDULER_REASON_PREREQ_DONE);
782         return;
783       }
784       (void) GNUNET_NETWORK_socket_close (sock);
785     }
786   }
787
788   if (0 == strcmp ("ip6-localhost", hostname)
789 #if !LINUX
790       && 0
791 #endif
792       )
793   {
794     /* can test using 'bind' */
795     struct sockaddr_in6 s_in6;
796
797     memset (&s_in6, 0, sizeof (s_in6));
798 #if HAVE_SOCKADDR_IN_SIN_LEN
799     s_in6.sin6_len = sizeof (struct sockaddr_in6);
800 #endif
801     s_in6.sin6_family = AF_INET6;
802     s_in6.sin6_port = htons (port);
803
804     sock = GNUNET_NETWORK_socket_create (AF_INET6, SOCK_STREAM, 0);
805     if (sock != NULL)
806     {
807       if (GNUNET_OK !=
808           GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) &s_in6,
809                                       sizeof (s_in6)))
810       {
811         /* failed to bind => service must be running */
812         GNUNET_free (hostname);
813         (void) GNUNET_NETWORK_socket_close (sock);
814         GNUNET_SCHEDULER_add_continuation (task, task_cls,
815                                            GNUNET_SCHEDULER_REASON_PREREQ_DONE);
816         return;
817       }
818       (void) GNUNET_NETWORK_socket_close (sock);
819     }
820   }
821
822   if (((0 == strcmp ("localhost", hostname)) ||
823        (0 == strcmp ("ip6-localhost", hostname)))
824 #if !LINUX
825       && 0
826 #endif
827       )
828   {
829     /* all binds succeeded => claim service not running right now */
830     GNUNET_free_non_null (hostname);
831     service_test_error (task, task_cls);
832     return;
833   }
834   GNUNET_free_non_null (hostname);
835
836   /* non-localhost, try 'connect' method */
837   conn = GNUNET_CLIENT_connect (service, cfg);
838   if (conn == NULL)
839   {
840     LOG (GNUNET_ERROR_TYPE_INFO,
841          _("Could not connect to service `%s', must not be running.\n"),
842          service);
843     service_test_error (task, task_cls);
844     return;
845   }
846   conn->test_cb = task;
847   conn->test_cb_cls = task_cls;
848   conn->test_deadline = GNUNET_TIME_relative_to_absolute (timeout);
849
850   if (NULL ==
851       GNUNET_CLIENT_notify_transmit_ready (conn,
852                                            sizeof (struct GNUNET_MessageHeader),
853                                            timeout, GNUNET_YES, &write_test,
854                                            conn))
855   {
856     LOG (GNUNET_ERROR_TYPE_WARNING,
857          _("Failure to transmit request to service `%s'\n"), service);
858     service_test_error (task, task_cls);
859     GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
860     return;
861   }
862 }
863
864
865 /**
866  * Connection notifies us about failure or success of
867  * a transmission request.  Either pass it on to our
868  * user or, if possible, retry.
869  *
870  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
871  * @param size number of bytes available for transmission
872  * @param buf where to write them
873  * @return number of bytes written to buf
874  */
875 static size_t
876 client_notify (void *cls, size_t size, void *buf);
877
878
879 /**
880  * This task is run if we should re-try connection to the
881  * service after a while.
882  *
883  * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
884  * @param tc unused
885  */
886 static void
887 client_delayed_retry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
888 {
889   struct GNUNET_CLIENT_TransmitHandle *th = cls;
890   struct GNUNET_TIME_Relative delay;
891
892   th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
893   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
894   {
895     LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmission failed due to shutdown.\n");
896     th->sock->th = NULL;
897     th->notify (th->notify_cls, 0, NULL);
898     GNUNET_free (th);
899     return;
900   }
901   th->sock->sock =
902       do_connect (th->sock->service_name, th->sock->cfg, th->sock->attempts++);
903   if (NULL == th->sock->sock)
904   {
905     /* could happen if we're out of sockets */
906     delay =
907         GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining
908                                   (th->timeout), th->sock->back_off);
909     th->sock->back_off =
910         GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
911                                   (th->sock->back_off, 2),
912                                   GNUNET_TIME_UNIT_SECONDS);
913     LOG (GNUNET_ERROR_TYPE_DEBUG,
914          "Transmission failed %u times, trying again in %llums.\n",
915          MAX_ATTEMPTS - th->attempts_left,
916          (unsigned long long) delay.rel_value);
917     th->reconnect_task =
918         GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
919     return;
920   }
921   th->th =
922       GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock, th->size,
923                                                GNUNET_TIME_absolute_get_remaining
924                                                (th->timeout), &client_notify,
925                                                th);
926   if (th->th == NULL)
927   {
928     GNUNET_break (0);
929     th->sock->th = NULL;
930     th->notify (th->notify_cls, 0, NULL);
931     GNUNET_free (th);
932     return;
933   }
934 }
935
936
937 /**
938  * Connection notifies us about failure or success of a transmission
939  * request.  Either pass it on to our user or, if possible, retry.
940  *
941  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
942  * @param size number of bytes available for transmission
943  * @param buf where to write them
944  * @return number of bytes written to buf
945  */
946 static size_t
947 client_notify (void *cls, size_t size, void *buf)
948 {
949   struct GNUNET_CLIENT_TransmitHandle *th = cls;
950   size_t ret;
951   struct GNUNET_TIME_Relative delay;
952
953   th->th = NULL;
954   th->sock->th = NULL;
955   if (buf == NULL)
956   {
957     delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
958     delay.rel_value /= 2;
959     if ((0 !=
960          (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason ())) ||
961         (GNUNET_YES != th->auto_retry) || (0 == --th->attempts_left) ||
962         (delay.rel_value < 1))
963     {
964       LOG (GNUNET_ERROR_TYPE_DEBUG,
965            "Transmission failed %u times, giving up.\n",
966            MAX_ATTEMPTS - th->attempts_left);
967       GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
968       GNUNET_free (th);
969       return 0;
970     }
971     /* auto-retry */
972     LOG (GNUNET_ERROR_TYPE_DEBUG,
973          "Failed to connect to `%s', automatically trying again.\n",
974          th->sock->service_name);
975     GNUNET_CONNECTION_destroy (th->sock->sock, GNUNET_NO);
976     th->sock->sock = NULL;
977     delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
978     th->sock->back_off =
979         GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
980                                   (th->sock->back_off, 2),
981                                   GNUNET_TIME_UNIT_SECONDS);
982     LOG (GNUNET_ERROR_TYPE_DEBUG,
983          "Transmission failed %u times, trying again in %llums.\n",
984          MAX_ATTEMPTS - th->attempts_left,
985          (unsigned long long) delay.rel_value);
986     th->sock->th = th;
987     th->reconnect_task =
988         GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
989     return 0;
990   }
991   GNUNET_assert (size >= th->size);
992   ret = th->notify (th->notify_cls, size, buf);
993   GNUNET_free (th);
994   return ret;
995 }
996
997
998 /**
999  * Ask the client to call us once the specified number of bytes
1000  * are free in the transmission buffer.  May call the notify
1001  * method immediately if enough space is available.
1002  *
1003  * @param sock connection to the service
1004  * @param size number of bytes to send
1005  * @param timeout after how long should we give up (and call
1006  *        notify with buf NULL and size 0)?
1007  * @param auto_retry if the connection to the service dies, should we
1008  *        automatically re-connect and retry (within the timeout period)
1009  *        or should we immediately fail in this case?  Pass GNUNET_YES
1010  *        if the caller does not care about temporary connection errors,
1011  *        for example because the protocol is stateless
1012  * @param notify function to call
1013  * @param notify_cls closure for notify
1014  * @return NULL if our buffer will never hold size bytes,
1015  *         a handle if the notify callback was queued (can be used to cancel)
1016  */
1017 struct GNUNET_CLIENT_TransmitHandle *
1018 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
1019                                      size_t size,
1020                                      struct GNUNET_TIME_Relative timeout,
1021                                      int auto_retry,
1022                                      GNUNET_CONNECTION_TransmitReadyNotify
1023                                      notify, void *notify_cls)
1024 {
1025   struct GNUNET_CLIENT_TransmitHandle *th;
1026
1027   if (NULL != sock->th)
1028   {
1029     /* If this breaks, you most likley called this function twice without waiting
1030      * for completion or canceling the request */
1031     GNUNET_break (0);
1032     return NULL;
1033   }
1034   th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
1035   th->sock = sock;
1036   th->size = size;
1037   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1038   th->auto_retry = auto_retry;
1039   th->notify = notify;
1040   th->notify_cls = notify_cls;
1041   th->attempts_left = MAX_ATTEMPTS;
1042   sock->th = th;
1043   if (sock->sock == NULL)
1044   {
1045     th->reconnect_task =
1046         GNUNET_SCHEDULER_add_delayed (sock->back_off, &client_delayed_retry,
1047                                       th);
1048
1049   }
1050   else
1051   {
1052     th->th =
1053         GNUNET_CONNECTION_notify_transmit_ready (sock->sock, size, timeout,
1054                                                  &client_notify, th);
1055     if (NULL == th->th)
1056     {
1057       GNUNET_break (0);
1058       GNUNET_free (th);
1059       sock->th = NULL;
1060       return NULL;
1061     }
1062   }
1063   return th;
1064 }
1065
1066
1067 /**
1068  * Cancel a request for notification.
1069  *
1070  * @param th handle from the original request.
1071  */
1072 void
1073 GNUNET_CLIENT_notify_transmit_ready_cancel (struct GNUNET_CLIENT_TransmitHandle
1074                                             *th)
1075 {
1076   if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1077   {
1078     GNUNET_assert (NULL == th->th);
1079     GNUNET_SCHEDULER_cancel (th->reconnect_task);
1080     th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1081   }
1082   else
1083   {
1084     GNUNET_assert (NULL != th->th);
1085     GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
1086   }
1087   th->sock->th = NULL;
1088   GNUNET_free (th);
1089 }
1090
1091
1092 /**
1093  * Function called to notify a client about the socket
1094  * begin ready to queue the message.  "buf" will be
1095  * NULL and "size" zero if the socket was closed for
1096  * writing in the meantime.
1097  *
1098  * @param cls closure of type "struct TransmitGetResponseContext*"
1099  * @param size number of bytes available in buf
1100  * @param buf where the callee should write the message
1101  * @return number of bytes written to buf
1102  */
1103 static size_t
1104 transmit_for_response (void *cls, size_t size, void *buf)
1105 {
1106   struct TransmitGetResponseContext *tc = cls;
1107   uint16_t msize;
1108
1109   tc->sock->tag = NULL;
1110   msize = ntohs (tc->hdr->size);
1111   if (NULL == buf)
1112   {
1113     LOG (GNUNET_ERROR_TYPE_DEBUG,
1114          _("Could not submit request, not expecting to receive a response.\n"));
1115     if (NULL != tc->rn)
1116       tc->rn (tc->rn_cls, NULL);
1117     GNUNET_free (tc);
1118     return 0;
1119   }
1120   GNUNET_assert (size >= msize);
1121   memcpy (buf, tc->hdr, msize);
1122   GNUNET_CLIENT_receive (tc->sock, tc->rn, tc->rn_cls,
1123                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
1124   GNUNET_free (tc);
1125   return msize;
1126 }
1127
1128
1129 /**
1130  * Convenience API that combines sending a request
1131  * to the service and waiting for a response.
1132  * If either operation times out, the callback
1133  * will be called with a "NULL" response (in which
1134  * case the connection should probably be destroyed).
1135  *
1136  * @param sock connection to use
1137  * @param hdr message to transmit
1138  * @param timeout when to give up (for both transmission
1139  *         and for waiting for a response)
1140  * @param auto_retry if the connection to the service dies, should we
1141  *        automatically re-connect and retry (within the timeout period)
1142  *        or should we immediately fail in this case?  Pass GNUNET_YES
1143  *        if the caller does not care about temporary connection errors,
1144  *        for example because the protocol is stateless
1145  * @param rn function to call with the response
1146  * @param rn_cls closure for rn
1147  * @return GNUNET_OK on success, GNUNET_SYSERR if a request
1148  *         is already pending
1149  */
1150 int
1151 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
1152                                          const struct GNUNET_MessageHeader *hdr,
1153                                          struct GNUNET_TIME_Relative timeout,
1154                                          int auto_retry,
1155                                          GNUNET_CLIENT_MessageHandler rn,
1156                                          void *rn_cls)
1157 {
1158   struct TransmitGetResponseContext *tc;
1159   uint16_t msize;
1160
1161   if (NULL != sock->th)
1162     return GNUNET_SYSERR;
1163   GNUNET_assert (sock->tag == NULL);
1164   msize = ntohs (hdr->size);
1165   tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
1166   tc->sock = sock;
1167   tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
1168   memcpy (&tc[1], hdr, msize);
1169   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1170   tc->rn = rn;
1171   tc->rn_cls = rn_cls;
1172   if (NULL ==
1173       GNUNET_CLIENT_notify_transmit_ready (sock, msize, timeout, auto_retry,
1174                                            &transmit_for_response, tc))
1175   {
1176     GNUNET_break (0);
1177     GNUNET_free (tc);
1178     return GNUNET_SYSERR;
1179   }
1180   sock->tag = tc;
1181   return GNUNET_OK;
1182 }
1183
1184
1185
1186 /*  end of client.c */