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