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