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