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