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