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