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