a05c5bf75c28cbc2bca2ee3ce725a7e453afc6a8
[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     {
820       /* can test using 'bind' */
821       struct sockaddr_in s_in;
822       
823       memset (&s_in, 0, sizeof (s_in));
824 #if HAVE_SOCKADDR_IN_SIN_LEN
825       s_in.sin_len = saddrlens[1];
826 #endif
827       s_in.sin_family = AF_INET;
828       s_in.sin_port = htons (port);
829
830       sock =  GNUNET_NETWORK_socket_create (AF_INET, SOCK_STREAM, 0);
831       if (sock != NULL)
832         {
833           if (GNUNET_OK !=
834               GNUNET_NETWORK_socket_bind (sock,
835                                           (const struct sockaddr*) &s_in,
836                                           sizeof (s_in)))
837             {
838               /* failed to bind => service must be running */
839               GNUNET_free (hostname);
840               (void) GNUNET_NETWORK_socket_close (sock);
841               GNUNET_SCHEDULER_add_continuation (task,
842                                                  task_cls,
843                                                  GNUNET_SCHEDULER_REASON_PREREQ_DONE);
844               return;
845             }
846           (void) GNUNET_NETWORK_socket_close (sock);
847         }        
848     }
849
850   if (0 == strcmp ("ip6-localhost", hostname)) 
851     {
852       /* can test using 'bind' */
853       struct sockaddr_in6 s_in6;
854       
855       memset (&s_in6, 0, sizeof (s_in6));
856 #if HAVE_SOCKADDR_IN_SIN_LEN
857       s_in6.sin6_len = saddrlens[1];
858 #endif
859       s_in6.sin6_family = AF_INET6;
860       s_in6.sin6_port = htons (port);
861
862       sock =  GNUNET_NETWORK_socket_create (AF_INET6, SOCK_STREAM, 0);
863       if (sock != NULL)
864         {
865           if (GNUNET_OK !=
866               GNUNET_NETWORK_socket_bind (sock,
867                                           (const struct sockaddr*) &s_in6,
868                                           sizeof (s_in6)))
869             {
870               /* failed to bind => service must be running */
871               GNUNET_free (hostname);
872               (void) GNUNET_NETWORK_socket_close (sock);
873               GNUNET_SCHEDULER_add_continuation (task,
874                                                  task_cls,
875                                                  GNUNET_SCHEDULER_REASON_PREREQ_DONE);
876               return;
877             }
878           (void) GNUNET_NETWORK_socket_close (sock);
879         }        
880     }
881
882   if ( (0 == strcmp ("localhost", hostname)) ||
883        (0 == strcmp ("ip6-localhost", hostname)) )
884     {
885       /* all binds succeeded => claim service not running right now */
886       GNUNET_free_non_null (hostname);
887       service_test_error (task, task_cls);
888       return;
889     }   
890   GNUNET_free_non_null (hostname);
891
892   /* non-localhost, try 'connect' method */
893   conn = GNUNET_CLIENT_connect (service, cfg);
894   if (conn == NULL)
895     {
896       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
897                   _
898                   ("Could not connect to service `%s', must not be running.\n"),
899                   service);
900       service_test_error (task, task_cls);
901       return;
902     }
903   conn->test_cb = task;
904   conn->test_cb_cls = task_cls;
905   conn->test_deadline = GNUNET_TIME_relative_to_absolute (timeout);
906
907   if (NULL == GNUNET_CLIENT_notify_transmit_ready (conn,
908                                                    sizeof (struct GNUNET_MessageHeader),
909                                                    timeout,
910                                                    GNUNET_YES,
911                                                    &write_test, conn))  
912     {
913       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
914                   _("Failure to transmit request to service `%s'\n"),
915                   service);
916       service_test_error (task, task_cls);
917       GNUNET_CLIENT_disconnect (conn, GNUNET_NO);
918       return;
919     }
920 }
921
922
923 /**
924  * Connection notifies us about failure or success of
925  * a transmission request.  Either pass it on to our
926  * user or, if possible, retry.
927  *
928  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
929  * @param size number of bytes available for transmission
930  * @param buf where to write them
931  * @return number of bytes written to buf
932  */
933 static size_t client_notify (void *cls, size_t size, void *buf);
934
935
936 /**
937  * This task is run if we should re-try connection to the
938  * service after a while.
939  *
940  * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
941  * @param tc unused
942  */
943 static void
944 client_delayed_retry (void *cls,
945                       const struct GNUNET_SCHEDULER_TaskContext *tc)
946 {
947   struct GNUNET_CLIENT_TransmitHandle *th = cls;
948   struct GNUNET_TIME_Relative delay;
949
950   th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
951   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
952     {
953 #if DEBUG_CLIENT
954       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
955                   "Transmission failed due to shutdown.\n");
956 #endif
957       th->sock->th = NULL;
958       th->notify (th->notify_cls, 0, NULL);
959       GNUNET_free (th);
960       return;
961     }
962   th->sock->sock = do_connect (th->sock->service_name,
963                                th->sock->cfg,
964                                th->sock->attempts++);
965   if (NULL == th->sock->sock)
966     {
967       /* could happen if we're out of sockets */
968       delay = GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining (th->timeout), 
969                                         th->sock->back_off);
970       th->sock->back_off 
971         = GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply (th->sock->back_off, 2),
972                                     GNUNET_TIME_UNIT_SECONDS);
973 #if DEBUG_CLIENT
974       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
975                   "Transmission failed %u times, trying again in %llums.\n",
976                   MAX_ATTEMPTS - th->attempts_left,
977                   (unsigned long long) delay.rel_value);
978 #endif
979       th->reconnect_task = GNUNET_SCHEDULER_add_delayed (delay,
980                                                          &client_delayed_retry,
981                                                          th);
982       return;      
983     }
984   GNUNET_CONNECTION_ignore_shutdown (th->sock->sock,
985                                      th->sock->ignore_shutdown);
986   th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
987                                                     th->size,
988                                                     GNUNET_TIME_absolute_get_remaining
989                                                     (th->timeout),
990                                                     &client_notify, th);
991   if (th->th == NULL)
992     {
993       GNUNET_break (0);
994       th->sock->th = NULL;
995       th->notify (th->notify_cls, 0, NULL);
996       GNUNET_free (th);
997       return;
998     }
999 }
1000
1001
1002 /**
1003  * Connection notifies us about failure or success of a transmission
1004  * request.  Either pass it on to our user or, if possible, retry.
1005  *
1006  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
1007  * @param size number of bytes available for transmission
1008  * @param buf where to write them
1009  * @return number of bytes written to buf
1010  */
1011 static size_t
1012 client_notify (void *cls, size_t size, void *buf)
1013 {
1014   struct GNUNET_CLIENT_TransmitHandle *th = cls;
1015   size_t ret;
1016   struct GNUNET_TIME_Relative delay;
1017
1018   th->th = NULL;
1019   th->sock->th = NULL;
1020   if (buf == NULL)
1021     {
1022       delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
1023       delay.rel_value /= 2;
1024       if ( (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & GNUNET_SCHEDULER_get_reason ())) ||
1025            (GNUNET_YES != th->auto_retry) ||
1026            (0 == --th->attempts_left) || 
1027            (delay.rel_value < 1) )
1028         {
1029 #if DEBUG_CLIENT
1030           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1031                       "Transmission failed %u times, giving up.\n",
1032                       MAX_ATTEMPTS - th->attempts_left);
1033 #endif
1034           GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
1035           GNUNET_free (th);
1036           return 0;
1037         }
1038       /* auto-retry */
1039 #if DEBUG_CLIENT
1040       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1041                   "Failed to connect to `%s', automatically trying again.\n",
1042                   th->sock->service_name);
1043 #endif
1044       GNUNET_CONNECTION_destroy (th->sock->sock, GNUNET_NO);
1045       th->sock->sock = NULL;
1046       delay = GNUNET_TIME_relative_min (delay, th->sock->back_off);
1047       th->sock->back_off 
1048         = GNUNET_TIME_relative_min (GNUNET_TIME_relative_multiply (th->sock->back_off, 2),
1049                                     GNUNET_TIME_UNIT_SECONDS);
1050 #if DEBUG_CLIENT
1051       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1052                   "Transmission failed %u times, trying again in %llums.\n",
1053                   MAX_ATTEMPTS - th->attempts_left,
1054                   (unsigned long long) delay.rel_value);
1055 #endif
1056       th->sock->th = th;
1057       th->reconnect_task = GNUNET_SCHEDULER_add_delayed (delay,
1058                                                          &client_delayed_retry,
1059                                                          th);
1060       return 0;
1061     }
1062   GNUNET_assert (size >= th->size);
1063   ret = th->notify (th->notify_cls, size, buf);
1064   GNUNET_free (th);
1065   return ret;
1066 }
1067
1068
1069 /**
1070  * Ask the client to call us once the specified number of bytes
1071  * are free in the transmission buffer.  May call the notify
1072  * method immediately if enough space is available.
1073  *
1074  * @param sock connection to the service
1075  * @param size number of bytes to send
1076  * @param timeout after how long should we give up (and call
1077  *        notify with buf NULL and size 0)?
1078  * @param auto_retry if the connection to the service dies, should we
1079  *        automatically re-connect and retry (within the timeout period)
1080  *        or should we immediately fail in this case?  Pass GNUNET_YES
1081  *        if the caller does not care about temporary connection errors,
1082  *        for example because the protocol is stateless
1083  * @param notify function to call
1084  * @param notify_cls closure for notify
1085  * @return NULL if our buffer will never hold size bytes,
1086  *         a handle if the notify callback was queued (can be used to cancel)
1087  */
1088 struct GNUNET_CLIENT_TransmitHandle *
1089 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
1090                                      size_t size,
1091                                      struct GNUNET_TIME_Relative timeout,
1092                                      int auto_retry,
1093                                      GNUNET_CONNECTION_TransmitReadyNotify
1094                                      notify, void *notify_cls)
1095 {
1096   struct GNUNET_CLIENT_TransmitHandle *th;
1097
1098   if (NULL != sock->th)
1099     {
1100       /* If this breaks, you most likley called this function twice without waiting
1101        * for completion or canceling the request */
1102       GNUNET_break (0);
1103       return NULL;
1104     }
1105   th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
1106   th->sock = sock;
1107   th->size = size;
1108   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1109   th->auto_retry = auto_retry;
1110   th->notify = notify;
1111   th->notify_cls = notify_cls;
1112   th->attempts_left = MAX_ATTEMPTS;
1113   sock->th = th;
1114   if (sock->sock == NULL)
1115     {
1116       th->reconnect_task = GNUNET_SCHEDULER_add_delayed (sock->back_off,
1117                                                          &client_delayed_retry,
1118                                                          th);
1119       
1120     }
1121   else
1122     {
1123       th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
1124                                                         size,
1125                                                         timeout,
1126                                                         &client_notify, th);
1127       if (NULL == th->th)
1128         {
1129           GNUNET_break (0);
1130           GNUNET_free (th);
1131           sock->th = NULL;
1132           return NULL;
1133         }
1134     }
1135   return th;
1136 }
1137
1138
1139 /**
1140  * Cancel a request for notification.
1141  * 
1142  * @param th handle from the original request.
1143  */
1144 void
1145 GNUNET_CLIENT_notify_transmit_ready_cancel (struct
1146                                             GNUNET_CLIENT_TransmitHandle *th)
1147 {
1148   if (th->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1149     {
1150       GNUNET_assert (NULL == th->th);
1151       GNUNET_SCHEDULER_cancel (th->reconnect_task);
1152       th->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1153     }
1154   else
1155     {
1156       GNUNET_assert (NULL != th->th);
1157       GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
1158     }
1159   th->sock->th = NULL;
1160   GNUNET_free (th);
1161 }
1162
1163
1164 /**
1165  * Function called to notify a client about the socket
1166  * begin ready to queue the message.  "buf" will be
1167  * NULL and "size" zero if the socket was closed for
1168  * writing in the meantime.
1169  *
1170  * @param cls closure of type "struct TransmitGetResponseContext*"
1171  * @param size number of bytes available in buf
1172  * @param buf where the callee should write the message
1173  * @return number of bytes written to buf
1174  */
1175 static size_t
1176 transmit_for_response (void *cls, size_t size, void *buf)
1177 {
1178   struct TransmitGetResponseContext *tc = cls;
1179   uint16_t msize;
1180
1181   tc->sock->tag = NULL;
1182   msize = ntohs (tc->hdr->size);
1183   if (NULL == buf)
1184     {
1185 #if DEBUG_CLIENT 
1186       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1187                   _("Could not submit request, not expecting to receive a response.\n"));
1188 #endif
1189       if (NULL != tc->rn)
1190         tc->rn (tc->rn_cls, NULL);
1191       GNUNET_free (tc);
1192       return 0;
1193     }
1194   GNUNET_assert (size >= msize);
1195   memcpy (buf, tc->hdr, msize);
1196   GNUNET_CLIENT_receive (tc->sock,
1197                          tc->rn,
1198                          tc->rn_cls,
1199                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
1200   GNUNET_free (tc);
1201   return msize;
1202 }
1203
1204
1205 /**
1206  * Convenience API that combines sending a request
1207  * to the service and waiting for a response.
1208  * If either operation times out, the callback
1209  * will be called with a "NULL" response (in which
1210  * case the connection should probably be destroyed).
1211  *
1212  * @param sock connection to use
1213  * @param hdr message to transmit
1214  * @param timeout when to give up (for both transmission
1215  *         and for waiting for a response)
1216  * @param auto_retry if the connection to the service dies, should we
1217  *        automatically re-connect and retry (within the timeout period)
1218  *        or should we immediately fail in this case?  Pass GNUNET_YES
1219  *        if the caller does not care about temporary connection errors,
1220  *        for example because the protocol is stateless
1221  * @param rn function to call with the response
1222  * @param rn_cls closure for rn 
1223  * @return GNUNET_OK on success, GNUNET_SYSERR if a request
1224  *         is already pending
1225  */
1226 int
1227 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection
1228                                          *sock,
1229                                          const struct GNUNET_MessageHeader
1230                                          *hdr,
1231                                          struct GNUNET_TIME_Relative timeout,
1232                                          int auto_retry,
1233                                          GNUNET_CLIENT_MessageHandler rn,
1234                                          void *rn_cls)
1235 {
1236   struct TransmitGetResponseContext *tc;
1237   uint16_t msize;
1238
1239   if (NULL != sock->th)
1240     return GNUNET_SYSERR;
1241   GNUNET_assert (sock->tag == NULL);
1242   msize = ntohs (hdr->size);
1243   tc = GNUNET_malloc (sizeof (struct TransmitGetResponseContext) + msize);
1244   tc->sock = sock;
1245   tc->hdr = (const struct GNUNET_MessageHeader *) &tc[1];
1246   memcpy (&tc[1], hdr, msize);
1247   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1248   tc->rn = rn;
1249   tc->rn_cls = rn_cls;
1250   if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
1251                                                    msize,
1252                                                    timeout,
1253                                                    auto_retry,
1254                                                    &transmit_for_response,
1255                                                    tc))
1256     {
1257       GNUNET_break (0);
1258       GNUNET_free (tc);
1259       return GNUNET_SYSERR;
1260     }
1261   sock->tag = tc;
1262   return GNUNET_OK;
1263 }
1264
1265
1266
1267 /*  end of client.c */