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