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