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