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