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