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