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