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