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