cloning cfg to make client shutdown function useful
[oweals/gnunet.git] / src / util / client.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2006, 2008, 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/client.c
23  * @brief code for access to services
24  * @author Christian Grothoff
25  *
26  * Generic TCP code for reliable, record-oriented TCP
27  * connections between clients and service providers.
28  */
29
30 #include "platform.h"
31 #include "gnunet_common.h"
32 #include "gnunet_client_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_server_lib.h"
35 #include "gnunet_scheduler_lib.h"
36
37 #define DEBUG_CLIENT GNUNET_NO
38
39
40 /**
41  * How often do we re-try tranmsitting requests before giving up?
42  * Note that if we succeeded transmitting a request but failed to read
43  * a response, we do NOT re-try.
44  */
45 #define MAX_ATTEMPTS 10
46
47
48 /**
49  * Handle for a transmission request.
50  */
51 struct GNUNET_CLIENT_TransmitHandle 
52 {
53   /**
54    * Connection state.
55    */
56   struct GNUNET_CLIENT_Connection *sock;
57
58   /**
59    * Function to call to get the data for transmission.
60    */
61   GNUNET_CONNECTION_TransmitReadyNotify notify;
62
63   /**
64    * Closure for notify.
65    */
66   void *notify_cls;
67
68   /**
69    * Handle to the transmission with the underlying
70    * connection.
71    */
72   struct GNUNET_CONNECTION_TransmitHandle *th;
73
74   /**
75    * Timeout.
76    */
77   struct GNUNET_TIME_Absolute timeout;
78
79   /**
80    * If we are re-trying and are delaying to do so,
81    * handle to the scheduled task managing the delay.
82    */
83   GNUNET_SCHEDULER_TaskIdentifier task;
84
85   /**
86    * Number of bytes requested.
87    */
88   size_t size;
89
90   /**
91    * Are we allowed to re-try to connect without telling
92    * the user (of this API) about the connection troubles?
93    */
94   int auto_retry;
95
96   /**
97    * Number of attempts left for transmitting the request.  We may
98    * fail the first time (say because the service is not yet up), in
99    * which case (if auto_retry is set) we wait a bit and re-try
100    * (timeout permitting).
101    */
102   unsigned int attempts_left;
103
104 };
105
106
107
108 /**
109  * Struct to refer to a GNUnet TCP connection.
110  * This is more than just a socket because if the server
111  * drops the connection, the client automatically tries
112  * to reconnect (and for that needs connection information).
113  */
114 struct GNUNET_CLIENT_Connection
115 {
116
117   /**
118    * the socket handle, NULL if not live
119    */
120   struct GNUNET_CONNECTION_Handle *sock;
121
122   /**
123    * Our scheduler.
124    */
125   struct GNUNET_SCHEDULER_Handle *sched;
126
127   /**
128    * Our configuration.
129    */
130   struct GNUNET_CONFIGURATION_Handle *cfg;
131   
132   /**
133    * Name of the service we interact with.
134    */
135   char *service_name;
136
137   /**
138    * Handler for current receiver task.
139    */
140   GNUNET_CLIENT_MessageHandler receiver_handler;
141
142   /**
143    * Closure for receiver_handler.
144    */
145   void *receiver_handler_cls;
146
147   /**
148    * Handle for a pending transmission request, NULL if there is
149    * none pending.
150    */
151   struct GNUNET_CLIENT_TransmitHandle *th;
152
153   /**
154    * Handler for service test completion (NULL unless in service_test)
155    */
156   GNUNET_SCHEDULER_Task test_cb;
157
158   /**
159    * Closure for test_cb (NULL unless in service_test)
160    */
161   void *test_cb_cls;
162
163   /**
164    * Buffer for received message.
165    */
166   char *received_buf;
167
168   /**
169    * Timeout for receiving a response (absolute time).
170    */
171   struct GNUNET_TIME_Absolute receive_timeout;
172
173   /**
174    * Number of bytes in received_buf that are valid.
175    */
176   size_t received_pos;
177
178   /**
179    * Size of received_buf.
180    */
181   unsigned int received_size;
182
183   /**
184    * Do we have a complete response in received_buf?
185    */
186   int msg_complete;
187
188   /**
189    * Are we currently busy doing receive-processing?
190    * GNUNET_YES if so, GNUNET_NO if not, GNUNET_SYSERR
191    * if the handle should be destroyed as soon as the
192    * receive processing is done.
193    */
194   int in_receive;
195
196 };
197
198
199 static struct GNUNET_CONNECTION_Handle *
200 do_connect (struct GNUNET_SCHEDULER_Handle *sched,
201             const char *service_name,
202             const struct GNUNET_CONFIGURATION_Handle *cfg)
203 {
204   struct GNUNET_CONNECTION_Handle *sock;
205   char *hostname;
206   unsigned long long port;
207
208   if ((GNUNET_OK !=
209        GNUNET_CONFIGURATION_get_value_number (cfg,
210                                               service_name,
211                                               "PORT",
212                                               &port)) ||
213       (port > 65535) ||
214       (GNUNET_OK !=
215        GNUNET_CONFIGURATION_get_value_string (cfg,
216                                               service_name,
217                                               "HOSTNAME", &hostname)))
218     {
219       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
220                   _("Could not determine valid hostname and port for service `%s' from configuration.\n"),
221                   service_name);
222       return NULL;
223     }
224   if (0 == strlen (hostname))
225     {
226       GNUNET_free (hostname);
227       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
228                   _("Need a non-empty hostname for service `%s'.\n"),
229                   service_name);
230       return NULL;
231     }
232   sock = GNUNET_CONNECTION_create_from_connect (sched,
233                                                 cfg,
234                                                 hostname,
235                                                 port,
236                                                 GNUNET_SERVER_MAX_MESSAGE_SIZE);
237   GNUNET_free (hostname);
238   return sock;
239 }
240
241
242 /**
243  * Get a connection with a service.
244  *
245  * @param sched scheduler to use
246  * @param service_name name of the service
247  * @param cfg configuration to use
248  * @return NULL on error (service unknown to configuration)
249  */
250 struct GNUNET_CLIENT_Connection *
251 GNUNET_CLIENT_connect (struct GNUNET_SCHEDULER_Handle *sched,
252                        const char *service_name,
253                        const struct GNUNET_CONFIGURATION_Handle *cfg)
254 {
255   struct GNUNET_CLIENT_Connection *ret;
256   struct GNUNET_CONNECTION_Handle *sock;
257
258   sock = do_connect (sched, service_name, cfg);
259   if (sock == NULL)
260     return NULL;
261   ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
262   ret->sock = sock;
263   ret->sched = sched;
264   ret->service_name = GNUNET_strdup (service_name);
265   ret->cfg = GNUNET_CONFIGURATION_dup (cfg);
266   return ret;
267 }
268
269
270 /**
271  * Receiver task has completed, free rest of client
272  * data structures.
273  */
274 static void
275 finish_cleanup (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
276 {
277   struct GNUNET_CLIENT_Connection *sock = cls;
278
279   if (sock->th != NULL)
280     GNUNET_CLIENT_notify_transmit_ready_cancel (sock->th);    
281   GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
282   GNUNET_free (sock->service_name);
283   GNUNET_CONFIGURATION_destroy (sock->cfg);
284   GNUNET_free (sock);
285 }
286
287
288 /**
289  * Destroy connection with the service.  This will automatically
290  * cancel any pending "receive" request (however, the handler will
291  * *NOT* be called, not even with a NULL message).  Any pending
292  * transmission request will also be cancelled UNLESS the callback for
293  * the transmission request has already been called, in which case the
294  * transmission is guaranteed to complete before the socket is fully
295  * destroyed.
296  *
297  * @param sock handle to the service connection
298  */
299 void
300 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock)
301 {
302   GNUNET_assert (sock->sock != NULL);
303   GNUNET_CONNECTION_destroy (sock->sock);
304   sock->sock = NULL;
305   sock->receiver_handler = NULL;
306   if (sock->in_receive == GNUNET_YES)
307     sock->in_receive = GNUNET_SYSERR;
308   else
309     GNUNET_SCHEDULER_add_after (sock->sched,
310                                 GNUNET_YES,
311                                 GNUNET_SCHEDULER_PRIORITY_KEEP,
312                                 GNUNET_SCHEDULER_NO_TASK,
313                                 &finish_cleanup, sock);
314 }
315
316
317 /**
318  * Check if message is complete
319  */
320 static void
321 check_complete (struct GNUNET_CLIENT_Connection *conn)
322 {
323   if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
324       (conn->received_pos >=
325        ntohs (((const struct GNUNET_MessageHeader *) conn->
326                received_buf)->size)))
327     conn->msg_complete = GNUNET_YES;
328 }
329
330
331 /**
332  * Callback function for data received from the network.  Note that
333  * both "available" and "errCode" would be 0 if the read simply timed out.
334  *
335  * @param cls closure
336  * @param buf pointer to received data
337  * @param available number of bytes availabe in "buf",
338  *        possibly 0 (on errors)
339  * @param addr address of the sender
340  * @param addrlen size of addr
341  * @param errCode value of errno (on errors receiving)
342  */
343 static void
344 receive_helper (void *cls,
345                 const void *buf,
346                 size_t available,
347                 const struct sockaddr *addr, socklen_t addrlen, int errCode)
348 {
349   struct GNUNET_CLIENT_Connection *conn = cls;
350   struct GNUNET_TIME_Relative remaining;
351
352   GNUNET_assert (conn->msg_complete == GNUNET_NO);
353   if (GNUNET_SYSERR == conn->in_receive)
354     GNUNET_SCHEDULER_add_after (conn->sched,
355                                 GNUNET_YES,
356                                 GNUNET_SCHEDULER_PRIORITY_KEEP,
357                                 GNUNET_SCHEDULER_NO_TASK,
358                                 &finish_cleanup, 
359                                 conn);
360   conn->in_receive = GNUNET_NO;
361   if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
362     {
363       /* signal timeout! */
364       if (conn->receiver_handler != NULL)
365         {
366           conn->receiver_handler (conn->receiver_handler_cls, NULL);
367           conn->receiver_handler = NULL;
368         }
369       return;
370     }
371
372   /* FIXME: optimize for common fast case where buf contains the
373      entire message and we need no copying... */
374
375
376   /* slow path: append to array */
377   if (conn->received_size < conn->received_pos + available)
378     GNUNET_array_grow (conn->received_buf,
379                        conn->received_size, conn->received_pos + available);
380   memcpy (&conn->received_buf[conn->received_pos], buf, available);
381   conn->received_pos += available;
382   check_complete (conn);
383   /* check for timeout */
384   remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
385   if (remaining.value == 0)
386     {
387       /* signal timeout! */
388       conn->receiver_handler (conn->receiver_handler_cls, NULL);
389       return;
390     }
391   /* back to receive -- either for more data or to call callback! */
392   GNUNET_CLIENT_receive (conn,
393                          conn->receiver_handler,
394                          conn->receiver_handler_cls, remaining);
395 }
396
397
398 /**
399  * Continuation to call the receive callback.
400  */
401 static void
402 receive_task (void *scls, const struct GNUNET_SCHEDULER_TaskContext *tc)
403 {
404   struct GNUNET_CLIENT_Connection *sock = scls;
405   GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
406   const struct GNUNET_MessageHeader *cmsg = (const struct GNUNET_MessageHeader *) sock->received_buf;
407   void *cls = sock->receiver_handler_cls;
408   uint16_t msize = ntohs (cmsg->size);
409   char mbuf[msize];
410   struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader*) mbuf;
411
412   if (GNUNET_SYSERR == sock->in_receive)
413     GNUNET_SCHEDULER_add_after (sock->sched,
414                                 GNUNET_YES,
415                                 GNUNET_SCHEDULER_PRIORITY_KEEP,
416                                 GNUNET_SCHEDULER_NO_TASK,
417                                 &finish_cleanup, 
418                                 sock);
419   sock->in_receive = GNUNET_NO;
420   GNUNET_assert (GNUNET_YES == sock->msg_complete);
421   GNUNET_assert (sock->received_pos >= msize);
422   memcpy (msg, cmsg, msize);
423   memmove (sock->received_buf,
424            &sock->received_buf[msize], sock->received_pos - msize);
425   sock->received_pos -= msize;
426   sock->msg_complete = GNUNET_NO;
427   sock->receiver_handler = NULL;  
428   check_complete (sock);
429   if (handler != NULL)
430     handler (cls, msg);
431 }
432
433
434 /**
435  * Read from the service.
436  *
437  * @param sock the service
438  * @param handler function to call with the message
439  * @param handler_cls closure for handler
440  * @param timeout how long to wait until timing out
441  */
442 void
443 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
444                        GNUNET_CLIENT_MessageHandler handler,
445                        void *handler_cls, struct GNUNET_TIME_Relative timeout)
446 {
447   if (sock->sock == NULL)
448     {
449       /* already disconnected, fail instantly! */
450       GNUNET_break (0);         /* this should not happen in well-written code! */
451       handler (handler_cls, NULL);
452       return;
453     }
454   sock->receiver_handler = handler;
455   sock->receiver_handler_cls = handler_cls;
456   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
457   sock->in_receive = GNUNET_YES;
458   if (GNUNET_YES == sock->msg_complete)
459     GNUNET_SCHEDULER_add_after (sock->sched,
460                                 GNUNET_YES,
461                                 GNUNET_SCHEDULER_PRIORITY_KEEP,
462                                 GNUNET_SCHEDULER_NO_TASK,
463                                 &receive_task, sock);
464   else
465     GNUNET_CONNECTION_receive (sock->sock,
466                                GNUNET_SERVER_MAX_MESSAGE_SIZE,
467                                timeout,
468                                &receive_helper, sock);
469 }
470
471
472 /**
473  * If possible, write a shutdown message to the target
474  * buffer and destroy the client connection.
475  *
476  * @param cls the "struct GNUNET_CLIENT_Connection" to destroy
477  * @param size number of bytes available in buf
478  * @param buf NULL on error, otherwise target buffer
479  * @return number of bytes written to buf
480  */
481 static size_t
482 write_shutdown (void *cls, size_t size, void *buf)
483 {
484   struct GNUNET_MessageHeader *msg;
485   struct GNUNET_CLIENT_Connection *sock = cls;
486
487   GNUNET_CLIENT_disconnect (sock);
488   if (size < sizeof (struct GNUNET_MessageHeader))
489     {
490       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
491                   _("Failed to transmit shutdown request to client.\n"));
492       return 0;                   /* client disconnected */
493     }
494   msg = (struct GNUNET_MessageHeader *) buf;
495   msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN);
496   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
497   return sizeof (struct GNUNET_MessageHeader);
498 }
499
500
501 /**
502  * Request that the service should shutdown.
503  * Afterwards, the connection should be disconnected.
504  *
505  * @param sock the socket connected to the service
506  */
507 void
508 GNUNET_CLIENT_service_shutdown (struct GNUNET_CLIENT_Connection *sock)
509 {
510   GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
511                                            sizeof (struct GNUNET_MessageHeader),
512                                            GNUNET_TIME_UNIT_FOREVER_REL,
513                                            &write_shutdown, sock);
514 }
515
516
517 /**
518  * Report service unavailable.
519  */
520 static void
521 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
522                     GNUNET_SCHEDULER_Task task, void *task_cls)
523 {
524   GNUNET_SCHEDULER_add_continuation (s,
525                                      GNUNET_YES,
526                                      task,
527                                      task_cls,
528                                      GNUNET_SCHEDULER_REASON_TIMEOUT);
529 }
530
531
532 /**
533  * Receive confirmation from test, service is up.
534  *
535  * @param cls closure
536  * @param msg message received, NULL on timeout or fatal error
537  */
538 static void
539 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
540 {
541   struct GNUNET_CLIENT_Connection *conn = cls;
542   /* We may want to consider looking at the reply in more
543      detail in the future, for example, is this the
544      correct service? FIXME! */
545   if (msg != NULL)
546     {
547 #if DEBUG_CLIENT
548       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
549                   "Received confirmation that service is running.\n");
550 #endif
551       GNUNET_SCHEDULER_add_continuation (conn->sched,
552                                          GNUNET_YES,
553                                          conn->test_cb,
554                                          conn->test_cb_cls,
555                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
556     }
557   else
558     {
559       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
560     }
561   GNUNET_CLIENT_disconnect (conn);
562 }
563
564
565 static size_t
566 write_test (void *cls, size_t size, void *buf)
567 {
568   struct GNUNET_MessageHeader *msg;
569
570   if (size < sizeof (struct GNUNET_MessageHeader))
571     {
572 #if DEBUG_CLIENT
573       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
574                   _("Failure to transmit TEST request.\n"));
575 #endif
576       return 0;                 /* client disconnected */
577     }
578 #if DEBUG_CLIENT
579   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Transmitting TEST request.\n"));
580 #endif
581   msg = (struct GNUNET_MessageHeader *) buf;
582   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
583   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
584   return sizeof (struct GNUNET_MessageHeader);
585 }
586
587
588 /**
589  * Wait until the service is running.
590  *
591  * @param sched scheduler to use
592  * @param service name of the service to wait for
593  * @param cfg configuration to use
594  * @param timeout how long to wait at most in ms
595  * @param task task to run if service is running
596  *        (reason will be "PREREQ_DONE" (service running)
597  *         or "TIMEOUT" (service not known to be running))
598  * @param task_cls closure for task
599  */
600 void
601 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
602                             const char *service,
603                             const struct GNUNET_CONFIGURATION_Handle *cfg,
604                             struct GNUNET_TIME_Relative timeout,
605                             GNUNET_SCHEDULER_Task task, void *task_cls)
606 {
607   struct GNUNET_CLIENT_Connection *conn;
608
609 #if DEBUG_CLIENT
610   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
611               "Testing if service `%s' is running.\n", service);
612 #endif
613   conn = GNUNET_CLIENT_connect (sched, service, cfg);
614   if (conn == NULL)
615     {
616       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
617                   _
618                   ("Could not connect to service `%s', must not be running.\n"),
619                   service);
620       service_test_error (sched, task, task_cls);
621       return;
622     }
623   conn->test_cb = task;
624   conn->test_cb_cls = task_cls;
625   if (NULL ==
626       GNUNET_CONNECTION_notify_transmit_ready (conn->sock,
627                                             sizeof (struct
628                                                     GNUNET_MessageHeader),
629                                             timeout, &write_test, NULL))
630     {
631       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
632                   _("Failure to transmit request to service `%s'\n"),
633                   service);
634       service_test_error (sched, task, task_cls);
635       GNUNET_CLIENT_disconnect (conn);
636       return;
637     }
638   GNUNET_CLIENT_receive (conn, &confirm_handler, conn, timeout);
639 }
640
641
642 /**
643  * Connection notifies us about failure or success of
644  * a transmission request.  Either pass it on to our
645  * user or, if possible, retry.
646  *
647  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
648  * @param size number of bytes available for transmission
649  * @param buf where to write them
650  * @return number of bytes written to buf
651  */
652 static size_t
653 client_notify (void *cls,
654                size_t size,
655                void *buf);
656
657
658
659 /**
660  * This task is run if we should re-try connection to the
661  * service after a while.
662  *
663  * @param cls our "struct GNUNET_CLIENT_TransmitHandle" of the request
664  * @param tc unused
665  */
666 static void
667 client_delayed_retry (void *cls,
668                       const struct GNUNET_SCHEDULER_TaskContext *tc)
669 {
670   struct GNUNET_CLIENT_TransmitHandle *th = cls;
671
672   th->task = GNUNET_SCHEDULER_NO_TASK;
673   th->th = GNUNET_CONNECTION_notify_transmit_ready (th->sock->sock,
674                                                     th->size,
675                                                     GNUNET_TIME_absolute_get_remaining (th->timeout), 
676                                                     &client_notify, 
677                                                     th);
678   if (th->th == NULL)
679     {
680       GNUNET_break (0);
681       th->notify (th->notify_cls, 0, NULL);
682       GNUNET_free (th);
683       return;             
684     }
685 }
686
687
688 /**
689  * Connection notifies us about failure or success of
690  * a transmission request.  Either pass it on to our
691  * user or, if possible, retry.
692  *
693  * @param cls our "struct GNUNET_CLIENT_TransmissionHandle"
694  * @param size number of bytes available for transmission
695  * @param buf where to write them
696  * @return number of bytes written to buf
697  */
698 static size_t
699 client_notify (void *cls,
700                size_t size,
701                void *buf)
702 {
703   struct GNUNET_CLIENT_TransmitHandle *th = cls;
704   size_t ret;
705   struct GNUNET_TIME_Relative delay;
706   
707   th->th = NULL;
708   th->sock->th = NULL;
709   if (buf == NULL)
710     {
711       delay = GNUNET_TIME_absolute_get_remaining (th->timeout);
712       delay.value /= 2;
713       if ( (GNUNET_YES != th->auto_retry) ||
714            (0 == --th->attempts_left) ||
715            (delay.value < 1) )
716         {
717           GNUNET_break (0 == th->notify (th->notify_cls,
718                                          0,
719                                          NULL));
720           GNUNET_free (th);
721           return 0;
722         }
723       /* auto-retry */
724       GNUNET_CONNECTION_destroy (th->sock->sock);
725       th->sock->sock = do_connect (th->sock->sched, 
726                                    th->sock->service_name,
727                                    th->sock->cfg);
728       GNUNET_assert (NULL != th->sock->sock);
729       delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_SECONDS);
730       th->task = GNUNET_SCHEDULER_add_delayed (th->sock->sched,
731                                                GNUNET_NO,
732                                                GNUNET_SCHEDULER_PRIORITY_KEEP,
733                                                GNUNET_SCHEDULER_NO_TASK,
734                                                delay,
735                                                &client_delayed_retry,
736                                                th);
737       th->sock->th = th;
738       return 0;
739     }
740   GNUNET_assert (size >= th->size);
741   ret = th->notify (th->notify_cls,
742                     size,
743                     buf);
744   GNUNET_free (th);
745   return ret;
746 }
747
748
749 /**
750  * Ask the client to call us once the specified number of bytes
751  * are free in the transmission buffer.  May call the notify
752  * method immediately if enough space is available.
753  *
754  * @param sock connection to the service
755  * @param size number of bytes to send
756  * @param timeout after how long should we give up (and call
757  *        notify with buf NULL and size 0)?
758  * @param auto_retry if the connection to the service dies, should we
759  *        automatically re-connect and retry (within the timeout period)
760  *        or should we immediately fail in this case?  Pass GNUNET_YES
761  *        if the caller does not care about temporary connection errors,
762  *        for example because the protocol is stateless
763  * @param notify function to call
764  * @param notify_cls closure for notify
765  * @return NULL if our buffer will never hold size bytes,
766  *         a handle if the notify callback was queued (can be used to cancel)
767  */
768 struct GNUNET_CLIENT_TransmitHandle *
769 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
770                                      size_t size,
771                                      struct GNUNET_TIME_Relative timeout,
772                                      int auto_retry,
773                                      GNUNET_CONNECTION_TransmitReadyNotify
774                                      notify, void *notify_cls)
775 {
776   struct GNUNET_CLIENT_TransmitHandle *th;
777
778   if (NULL != sock->th)
779     return NULL;
780   th = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_TransmitHandle));
781   th->sock = sock;
782   th->size = size;
783   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
784   th->auto_retry = auto_retry;
785   th->notify = notify;
786   th->notify_cls = notify_cls;
787   th->attempts_left = MAX_ATTEMPTS;
788   th->th = GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
789                                                     size,
790                                                     timeout, 
791                                                     &client_notify, 
792                                                     th);
793   if (NULL == th->th)
794     {
795       GNUNET_break (0);
796       GNUNET_free (th);
797       return NULL;
798     }
799   sock->th = th;
800   return th;
801 }
802
803
804 /**
805  * Cancel a request for notification.
806  * 
807  * @param th handle from the original request.
808  */
809 void
810 GNUNET_CLIENT_notify_transmit_ready_cancel (struct GNUNET_CLIENT_TransmitHandle *th)
811 {
812   if (th->task != GNUNET_SCHEDULER_NO_TASK)
813     {
814       GNUNET_break (NULL == th->th);
815       GNUNET_SCHEDULER_cancel (th->sock->sched,
816                                th->task);      
817     }
818   else
819     {
820       GNUNET_break (NULL != th->th);
821       GNUNET_CONNECTION_notify_transmit_ready_cancel (th->th);
822     }
823   th->sock->th = NULL;
824   GNUNET_free (th);
825 }
826
827
828 /**
829  * Context for processing 
830  * "GNUNET_CLIENT_transmit_and_get_response" requests.
831  */
832 struct TARCtx
833 {
834   /**
835    * Client handle.
836    */
837   struct GNUNET_CLIENT_Connection *sock;
838
839   /**
840    * Message to transmit; do not free, allocated
841    * right after this struct.
842    */
843   const struct GNUNET_MessageHeader *hdr;
844
845   /**
846    * Timeout to use.
847    */
848   struct GNUNET_TIME_Absolute timeout;
849
850   /**
851    * Function to call when done.
852    */
853   GNUNET_CLIENT_MessageHandler rn;
854
855   /**
856    * Closure for "rn".
857    */
858   void *rn_cls;
859 };
860
861
862 /**
863  * Function called to notify a client about the socket
864  * begin ready to queue the message.  "buf" will be
865  * NULL and "size" zero if the socket was closed for
866  * writing in the meantime.
867  *
868  * @param cls closure of type "struct TARCtx*"
869  * @param size number of bytes available in buf
870  * @param buf where the callee should write the message
871  * @return number of bytes written to buf
872  */
873 static size_t
874 transmit_for_response (void *cls,
875                        size_t size, 
876                        void *buf)
877 {
878   struct TARCtx *tc = cls;
879   uint16_t msize;
880
881   msize = ntohs(tc->hdr->size);
882   if (NULL == buf)
883     {
884       tc->rn (tc->rn_cls, NULL);
885       GNUNET_free (tc);
886       return 0;
887     }
888   GNUNET_assert (size >= msize);
889   memcpy (buf, tc->hdr, msize);
890   GNUNET_CLIENT_receive (tc->sock,
891                          tc->rn,
892                          tc->rn_cls,
893                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
894   GNUNET_free (tc);
895   return msize;
896 }
897
898
899 /**
900  * Convenience API that combines sending a request
901  * to the service and waiting for a response.
902  * If either operation times out, the callback
903  * will be called with a "NULL" response (in which
904  * case the connection should probably be destroyed).
905  *
906  * @param sock connection to use
907  * @param hdr message to transmit
908  * @param timeout when to give up (for both transmission
909  *         and for waiting for a response)
910  * @param auto_retry if the connection to the service dies, should we
911  *        automatically re-connect and retry (within the timeout period)
912  *        or should we immediately fail in this case?  Pass GNUNET_YES
913  *        if the caller does not care about temporary connection errors,
914  *        for example because the protocol is stateless
915  * @param rn function to call with the response
916  * @param rn_cls closure for rn 
917  * @return GNUNET_OK on success, GNUNET_SYSERR if a request
918  *         is already pending
919  */
920 int
921 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
922                                          const struct GNUNET_MessageHeader *hdr,
923                                          struct GNUNET_TIME_Relative timeout,
924                                          int auto_retry,
925                                          GNUNET_CLIENT_MessageHandler rn,
926                                          void *rn_cls)
927 {
928   struct TARCtx *tc;
929   uint16_t msize;
930
931   if (NULL != sock->th)
932     return GNUNET_SYSERR;
933   msize = ntohs(hdr->size);
934   tc = GNUNET_malloc(sizeof (struct TARCtx) + msize);
935   tc->sock = sock;
936   tc->hdr = (const struct GNUNET_MessageHeader*) &tc[1]; 
937   memcpy (&tc[1], hdr, msize);
938   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
939   tc->rn = rn;
940   tc->rn_cls = rn_cls;
941   if (NULL == GNUNET_CLIENT_notify_transmit_ready (sock,
942                                                    msize,
943                                                    timeout,
944                                                    auto_retry,
945                                                    &transmit_for_response,
946                                                    tc))
947     {
948       GNUNET_break (0);
949       GNUNET_free (tc);
950       return GNUNET_SYSERR;
951     }
952   return GNUNET_OK;
953 }
954
955
956
957 /*  end of client.c */