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