-add adv port
[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   th->client->connection =
949       do_connect (th->client->service_name, th->client->cfg, th->client->attempts++);
950   th->client->first_message = GNUNET_YES;
951   if (NULL == th->client->connection)
952   {
953     /* could happen if we're out of sockets */
954     delay =
955         GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining
956                                   (th->timeout), th->client->back_off);
957     th->client->back_off =
958         GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
959                                   (th->client->back_off, 2),
960                                   GNUNET_TIME_UNIT_SECONDS);
961     LOG (GNUNET_ERROR_TYPE_DEBUG,
962          "Transmission failed %u times, trying again in %s.\n",
963          MAX_ATTEMPTS - th->attempts_left,
964          GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
965     th->reconnect_task =
966         GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
967     return;
968   }
969   th->th =
970       GNUNET_CONNECTION_notify_transmit_ready (th->client->connection, th->size,
971                                                GNUNET_TIME_absolute_get_remaining
972                                                (th->timeout), &client_notify,
973                                                th);
974   if (NULL == th->th)
975   {
976     GNUNET_break (0);
977     th->client->th = NULL;
978     th->notify (th->notify_cls, 0, NULL);
979     GNUNET_free (th);
980     return;
981   }
982 }
983
984
985 /**
986  * Connection notifies us about failure or success of a transmission
987  * request.  Either pass it on to our user or, if possible, retry.
988  *
989  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
990  * @param size number of bytes available for transmission
991  * @param buf where to write them
992  * @return number of bytes written to buf
993  */
994 static size_t
995 client_notify (void *cls, size_t size, void *buf)
996 {
997   struct GNUNET_CLIENT_TransmitHandle *th = cls;
998   struct GNUNET_CLIENT_Connection *client = th->client;
999   size_t ret;
1000   struct GNUNET_TIME_Relative delay;
1001
1002   th->th = NULL;
1003   client->th = NULL;
1004   if (NULL == buf)
1005   {
1006     delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
1007     delay.rel_value /= 2;
1008     if ((GNUNET_YES != th->auto_retry) || (0 == --th->attempts_left) ||
1009         (delay.rel_value < 1))
1010     {
1011       LOG (GNUNET_ERROR_TYPE_DEBUG,
1012            "Transmission failed %u times, giving up.\n",
1013            MAX_ATTEMPTS - th->attempts_left);
1014       GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
1015       GNUNET_free (th);
1016       return 0;
1017     }
1018     /* auto-retry */
1019     LOG (GNUNET_ERROR_TYPE_DEBUG,
1020          "Failed to connect to `%s', automatically trying again.\n",
1021          client->service_name);
1022     if (GNUNET_YES == client->in_receive)
1023     {
1024       GNUNET_CONNECTION_receive_cancel (client->connection);
1025       client->in_receive = GNUNET_NO;
1026     }    
1027     GNUNET_CONNECTION_destroy (client->connection);
1028     client->connection = NULL;
1029     delay = GNUNET_TIME_relative_min (delay, client->back_off);
1030     client->back_off =
1031         GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply
1032                                   (client->back_off, 2),
1033                                   GNUNET_TIME_UNIT_SECONDS);
1034     LOG (GNUNET_ERROR_TYPE_DEBUG,
1035          "Transmission failed %u times, trying again in %s.\n",
1036          MAX_ATTEMPTS - th->attempts_left,
1037          GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1038     client->th = th;
1039     th->reconnect_task =
1040         GNUNET_SCHEDULER_add_delayed (delay, &client_delayed_retry, th);
1041     return 0;
1042   }
1043   GNUNET_assert (size >= th->size);
1044   ret = th->notify (th->notify_cls, size, buf);
1045   GNUNET_free (th);
1046   return ret;
1047 }
1048
1049
1050 /**
1051  * Ask the client to call us once the specified number of bytes
1052  * are free in the transmission buffer.  May call the notify
1053  * method immediately if enough space is available.
1054  *
1055  * @param client connection to the service
1056  * @param size number of bytes to send
1057  * @param timeout after how long should we give up (and call
1058  *        notify with buf NULL and size 0)?
1059  * @param auto_retry if the connection to the service dies, should we
1060  *        automatically re-connect and retry (within the timeout period)
1061  *        or should we immediately fail in this case?  Pass GNUNET_YES
1062  *        if the caller does not care about temporary connection errors,
1063  *        for example because the protocol is stateless
1064  * @param notify function to call
1065  * @param notify_cls closure for notify
1066  * @return NULL if our buffer will never hold size bytes,
1067  *         a handle if the notify callback was queued (can be used to cancel)
1068  */
1069 struct GNUNET_CLIENT_TransmitHandle *
1070 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *client,
1071                                      size_t size,
1072                                      struct GNUNET_TIME_Relative timeout,
1073                                      int auto_retry,
1074                                      GNUNET_CONNECTION_TransmitReadyNotify
1075                                      notify, void *notify_cls)
1076 {
1077   struct GNUNET_CLIENT_TransmitHandle *th;
1078
1079   if (NULL != client->th)
1080   {
1081     /* If this breaks, you most likley called this function twice without waiting
1082      * for completion or canceling the request */
1083     GNUNET_break (0);
1084     return NULL;
1085   }
1086   th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
1087   th->client = client;
1088   th->size = size;
1089   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1090   /* always auto-retry on first message to service */
1091   th->auto_retry = (GNUNET_YES == client->first_message) ? GNUNET_YES : auto_retry;
1092   client->first_message = GNUNET_NO;
1093   th->notify = notify;
1094   th->notify_cls = notify_cls;
1095   th->attempts_left = MAX_ATTEMPTS;
1096   client->th = th;
1097   if (NULL == client->connection)
1098   {
1099     th->reconnect_task =
1100         GNUNET_SCHEDULER_add_delayed (client->back_off, &client_delayed_retry,
1101                                       th);
1102
1103   }
1104   else
1105   {
1106     th->th =
1107         GNUNET_CONNECTION_notify_transmit_ready (client->connection, size, timeout,
1108                                                  &client_notify, th);
1109     if (NULL == th->th)
1110     {
1111       GNUNET_break (0);
1112       GNUNET_free (th);
1113       client->th = NULL;
1114       return NULL;
1115     }
1116   }
1117   return th;
1118 }
1119
1120
1121 /**
1122  * Cancel a request for notification.
1123  *
1124  * @param th handle from the original request.
1125  */
1126 void
1127 GNUNET_CLIENT_notify_transmit_ready_cancel (struct GNUNET_CLIENT_TransmitHandle
1128                                             *th)
1129 {
1130   if (GNUNET_SCHEDULER_NO_TASK != th->reconnect_task)
1131   {
1132     GNUNET_assert (NULL == th->th);
1133     GNUNET_SCHEDULER_cancel (th->reconnect_task);
1134     th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1135   }
1136   else
1137   {
1138     GNUNET_assert (NULL != th->th);
1139     GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
1140   }
1141   th->client->th = NULL;
1142   GNUNET_free (th);
1143 }
1144
1145
1146 /**
1147  * Function called to notify a client about the socket
1148  * begin ready to queue the message.  "buf" will be
1149  * NULL and "size" zero if the socket was closed for
1150  * writing in the meantime.
1151  *
1152  * @param cls closure of type "struct TransmitGetResponseContext*"
1153  * @param size number of bytes available in buf
1154  * @param buf where the callee should write the message
1155  * @return number of bytes written to buf
1156  */
1157 static size_t
1158 transmit_for_response (void *cls, size_t size, void *buf)
1159 {
1160   struct TransmitGetResponseContext *tc = cls;
1161   uint16_t msize;
1162
1163   tc->client->tag = NULL;
1164   msize = ntohs (tc->hdr->size);
1165   if (NULL == buf)
1166   {
1167     LOG (GNUNET_ERROR_TYPE_DEBUG,
1168          _("Could not submit request, not expecting to receive a response.\n"));
1169     if (NULL != tc->rn)
1170       tc->rn (tc->rn_cls, NULL);
1171     GNUNET_free (tc);
1172     return 0;
1173   }
1174   GNUNET_assert (size >= msize);
1175   memcpy (buf, tc->hdr, msize);
1176   GNUNET_CLIENT_receive (tc->client, tc->rn, tc->rn_cls,
1177                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
1178   GNUNET_free (tc);
1179   return msize;
1180 }
1181
1182
1183 /**
1184  * Convenience API that combines sending a request
1185  * to the service and waiting for a response.
1186  * If either operation times out, the callback
1187  * will be called with a "NULL" response (in which
1188  * case the connection should probably be destroyed).
1189  *
1190  * @param client connection to use
1191  * @param hdr message to transmit
1192  * @param timeout when to give up (for both transmission
1193  *         and for waiting for a response)
1194  * @param auto_retry if the connection to the service dies, should we
1195  *        automatically re-connect and retry (within the timeout period)
1196  *        or should we immediately fail in this case?  Pass GNUNET_YES
1197  *        if the caller does not care about temporary connection errors,
1198  *        for example because the protocol is stateless
1199  * @param rn function to call with the response
1200  * @param rn_cls closure for rn
1201  * @return GNUNET_OK on success, GNUNET_SYSERR if a request
1202  *         is already pending
1203  */
1204 int
1205 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *client,
1206                                          const struct GNUNET_MessageHeader *hdr,
1207                                          struct GNUNET_TIME_Relative timeout,
1208                                          int auto_retry,
1209                                          GNUNET_CLIENT_MessageHandler rn,
1210                                          void *rn_cls)
1211 {
1212   struct TransmitGetResponseContext *tc;
1213   uint16_t msize;
1214
1215   if (NULL != client->th)
1216     return GNUNET_SYSERR;
1217   GNUNET_assert (NULL == client->tag);
1218   msize = ntohs (hdr->size);
1219   tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
1220   tc->client = client;
1221   tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
1222   memcpy (&tc[1], hdr, msize);
1223   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1224   tc->rn = rn;
1225   tc->rn_cls = rn_cls;
1226   if (NULL ==
1227       GNUNET_CLIENT_notify_transmit_ready (client, msize, timeout, auto_retry,
1228                                            &transmit_for_response, tc))
1229   {
1230     GNUNET_break (0);
1231     GNUNET_free (tc);
1232     return GNUNET_SYSERR;
1233   }
1234   client->tag = tc;
1235   return GNUNET_OK;
1236 }
1237
1238
1239
1240 /*  end of client.c */