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