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