documentation cleanup
[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  * Struct to refer to a GNUnet TCP connection.
41  * This is more than just a socket because if the server
42  * drops the connection, the client automatically tries
43  * to reconnect (and for that needs connection information).
44  */
45 struct GNUNET_CLIENT_Connection
46 {
47
48   /**
49    * the socket handle, NULL if not live
50    */
51   struct GNUNET_CONNECTION_Handle *sock;
52
53   /**
54    * Our scheduler.
55    */
56   struct GNUNET_SCHEDULER_Handle *sched;
57
58   /**
59    * Name of the service we interact with.
60    */
61   char *service_name;
62
63   /**
64    * ID of task used for receiving.
65    */
66   GNUNET_SCHEDULER_TaskIdentifier receiver_task;
67
68   /**
69    * Handler for current receiver task.
70    */
71   GNUNET_CLIENT_MessageHandler receiver_handler;
72
73   /**
74    * Closure for receiver_handler.
75    */
76   void *receiver_handler_cls;
77
78   /**
79    * Handler for service test completion (NULL unless in service_test)
80    */
81   GNUNET_SCHEDULER_Task test_cb;
82
83   /**
84    * Closure for test_cb (NULL unless in service_test)
85    */
86   void *test_cb_cls;
87
88   /**
89    * Buffer for received message.
90    */
91   char *received_buf;
92
93   /**
94    * Timeout for receiving a response (absolute time).
95    */
96   struct GNUNET_TIME_Absolute receive_timeout;
97
98   /**
99    * Number of bytes in received_buf that are valid.
100    */
101   size_t received_pos;
102
103   /**
104    * Size of received_buf.
105    */
106   unsigned int received_size;
107
108   /**
109    * Do we have a complete response in received_buf?
110    */
111   int msg_complete;
112
113 };
114
115
116 /**
117  * Get a connection with a service.
118  *
119  * @param sched scheduler to use
120  * @param service_name name of the service
121  * @param cfg configuration to use
122  * @return NULL on error (service unknown to configuration)
123  */
124 struct GNUNET_CLIENT_Connection *
125 GNUNET_CLIENT_connect (struct GNUNET_SCHEDULER_Handle *sched,
126                        const char *service_name,
127                        const struct GNUNET_CONFIGURATION_Handle *cfg)
128 {
129   struct GNUNET_CLIENT_Connection *ret;
130   struct GNUNET_CONNECTION_Handle *sock;
131   char *hostname;
132   unsigned long long port;
133
134   if ((GNUNET_OK !=
135        GNUNET_CONFIGURATION_get_value_number (cfg,
136                                               service_name,
137                                               "PORT",
138                                               &port)) ||
139       (port > 65535) ||
140       (GNUNET_OK !=
141        GNUNET_CONFIGURATION_get_value_string (cfg,
142                                               service_name,
143                                               "HOSTNAME", &hostname)))
144     {
145       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
146                   "Could not determine valid hostname and port for service `%s' from configuration.\n",
147                   service_name);
148       return NULL;
149     }
150   sock = GNUNET_CONNECTION_create_from_connect (sched,
151                                                     hostname,
152                                                     port,
153                                                     GNUNET_SERVER_MAX_MESSAGE_SIZE);
154   GNUNET_free (hostname);
155   if (sock == NULL)
156     return NULL;
157   ret = GNUNET_malloc (sizeof (struct GNUNET_CLIENT_Connection));
158   ret->sock = sock;
159   ret->sched = sched;
160   ret->service_name = GNUNET_strdup (service_name);
161   return ret;
162 }
163
164
165 /**
166  * Receiver task has completed, free rest of client
167  * data structures.
168  */
169 static void
170 finish_cleanup (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
171 {
172   struct GNUNET_CLIENT_Connection *sock = cls;
173
174   GNUNET_array_grow (sock->received_buf, sock->received_size, 0);
175   GNUNET_free (sock->service_name);
176   GNUNET_free (sock);
177 }
178
179
180 /**
181  * Destroy connection with the service.
182  */
183 void
184 GNUNET_CLIENT_disconnect (struct GNUNET_CLIENT_Connection *sock)
185 {
186   GNUNET_assert (sock->sock != NULL);
187   GNUNET_CONNECTION_destroy (sock->sock);
188   sock->sock = NULL;
189   sock->receiver_handler = NULL;
190   GNUNET_SCHEDULER_add_after (sock->sched,
191                               GNUNET_YES,
192                               GNUNET_SCHEDULER_PRIORITY_KEEP,
193                               sock->receiver_task, &finish_cleanup, sock);
194 }
195
196
197 /**
198  * check if message is complete
199  */
200 static void
201 check_complete (struct GNUNET_CLIENT_Connection *conn)
202 {
203   if ((conn->received_pos >= sizeof (struct GNUNET_MessageHeader)) &&
204       (conn->received_pos >=
205        ntohs (((const struct GNUNET_MessageHeader *) conn->
206                received_buf)->size)))
207     conn->msg_complete = GNUNET_YES;
208 }
209
210
211 /**
212  * Callback function for data received from the network.  Note that
213  * both "available" and "errCode" would be 0 if the read simply timed out.
214  *
215  * @param cls closure
216  * @param buf pointer to received data
217  * @param available number of bytes availabe in "buf",
218  *        possibly 0 (on errors)
219  * @param addr address of the sender
220  * @param addrlen size of addr
221  * @param errCode value of errno (on errors receiving)
222  */
223 static void
224 receive_helper (void *cls,
225                 const void *buf,
226                 size_t available,
227                 const struct sockaddr *addr, socklen_t addrlen, int errCode)
228 {
229   struct GNUNET_CLIENT_Connection *conn = cls;
230   struct GNUNET_TIME_Relative remaining;
231
232   GNUNET_assert (conn->msg_complete == GNUNET_NO);
233   conn->receiver_task = GNUNET_SCHEDULER_NO_TASK;
234
235   if ((available == 0) || (conn->sock == NULL) || (errCode != 0))
236     {
237       /* signal timeout! */
238       if (conn->receiver_handler != NULL)
239         {
240           conn->receiver_handler (conn->receiver_handler_cls, NULL);
241           conn->receiver_handler = NULL;
242         }
243       return;
244     }
245
246   /* FIXME: optimize for common fast case where buf contains the
247      entire message and we need no copying... */
248
249
250   /* slow path: append to array */
251   if (conn->received_size < conn->received_pos + available)
252     GNUNET_array_grow (conn->received_buf,
253                        conn->received_size, conn->received_pos + available);
254   memcpy (&conn->received_buf[conn->received_pos], buf, available);
255   conn->received_pos += available;
256   check_complete (conn);
257   /* check for timeout */
258   remaining = GNUNET_TIME_absolute_get_remaining (conn->receive_timeout);
259   if (remaining.value == 0)
260     {
261       /* signal timeout! */
262       conn->receiver_handler (conn->receiver_handler_cls, NULL);
263       return;
264     }
265   /* back to receive -- either for more data or to call callback! */
266   GNUNET_CLIENT_receive (conn,
267                          conn->receiver_handler,
268                          conn->receiver_handler_cls, remaining);
269 }
270
271
272 /**
273  * Continuation to call the receive callback.
274  */
275 static void
276 receive_task (void *scls, const struct GNUNET_SCHEDULER_TaskContext *tc)
277 {
278   struct GNUNET_CLIENT_Connection *sock = scls;
279   GNUNET_CLIENT_MessageHandler handler = sock->receiver_handler;
280   const struct GNUNET_MessageHeader *cmsg = (const struct GNUNET_MessageHeader *) sock->received_buf;
281   void *cls = sock->receiver_handler_cls;
282   uint16_t msize = ntohs (cmsg->size);
283   char mbuf[msize];
284   struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader*) mbuf;
285
286   GNUNET_assert (GNUNET_YES == sock->msg_complete);
287   sock->receiver_task = GNUNET_SCHEDULER_NO_TASK;
288   GNUNET_assert (sock->received_pos >= msize);
289   memcpy (msg, cmsg, msize);
290   memmove (sock->received_buf,
291            &sock->received_buf[msize], sock->received_pos - msize);
292   sock->received_pos -= msize;
293   sock->msg_complete = GNUNET_NO;
294   sock->receiver_handler = NULL;  
295   check_complete (sock);
296   if (handler != NULL)
297     handler (cls, msg);
298 }
299
300
301 /**
302  * Read from the service.
303  *
304  * @param sock the service
305  * @param handler function to call with the message
306  * @param cls closure for handler
307  * @param timeout how long to wait until timing out
308  */
309 void
310 GNUNET_CLIENT_receive (struct GNUNET_CLIENT_Connection *sock,
311                        GNUNET_CLIENT_MessageHandler handler,
312                        void *cls, struct GNUNET_TIME_Relative timeout)
313 {
314   if (sock->sock == NULL)
315     {
316       /* already disconnected, fail instantly! */
317       GNUNET_break (0);         /* this should not happen in well-written code! */
318       handler (cls, NULL);
319       return;
320     }
321   GNUNET_assert (sock->receiver_task ==
322                  GNUNET_SCHEDULER_NO_TASK);
323   sock->receiver_handler = handler;
324   sock->receiver_handler_cls = cls;
325   sock->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
326   if (GNUNET_YES == sock->msg_complete)
327     sock->receiver_task = GNUNET_SCHEDULER_add_after (sock->sched,
328                                                       GNUNET_YES,
329                                                       GNUNET_SCHEDULER_PRIORITY_KEEP,
330                                                       GNUNET_SCHEDULER_NO_TASK,
331                                                       &receive_task, sock);
332   else
333     sock->receiver_task = GNUNET_CONNECTION_receive (sock->sock,
334                                                   GNUNET_SERVER_MAX_MESSAGE_SIZE,
335                                                   timeout,
336                                                   &receive_helper, sock);
337 }
338
339
340 static size_t
341 write_shutdown (void *cls, size_t size, void *buf)
342 {
343   struct GNUNET_MessageHeader *msg;
344
345   if (size < sizeof (struct GNUNET_MessageHeader))
346     return 0;                   /* client disconnected */
347   msg = (struct GNUNET_MessageHeader *) buf;
348   msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN);
349   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
350   return sizeof (struct GNUNET_MessageHeader);
351 }
352
353
354 /**
355  * Request that the service should shutdown.
356  * Afterwards, the connection should be disconnected.
357  *
358  * @param sock the socket connected to the service
359  */
360 void
361 GNUNET_CLIENT_service_shutdown (struct GNUNET_CLIENT_Connection *sock)
362 {
363   GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
364                                         sizeof (struct GNUNET_MessageHeader),
365                                         GNUNET_TIME_UNIT_FOREVER_REL,
366                                         &write_shutdown, NULL);
367 }
368
369
370 /**
371  * Report service unavailable.
372  */
373 static void
374 service_test_error (struct GNUNET_SCHEDULER_Handle *s,
375                     GNUNET_SCHEDULER_Task task, void *task_cls)
376 {
377   GNUNET_SCHEDULER_add_continuation (s,
378                                      GNUNET_YES,
379                                      task,
380                                      task_cls,
381                                      GNUNET_SCHEDULER_REASON_TIMEOUT);
382 }
383
384
385 /**
386  * Receive confirmation from test, service is up.
387  *
388  * @param cls closure
389  * @param msg message received, NULL on timeout or fatal error
390  */
391 static void
392 confirm_handler (void *cls, const struct GNUNET_MessageHeader *msg)
393 {
394   struct GNUNET_CLIENT_Connection *conn = cls;
395   /* We may want to consider looking at the reply in more
396      detail in the future, for example, is this the
397      correct service? FIXME! */
398   if (msg != NULL)
399     {
400 #if DEBUG_CLIENT
401       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
402                   "Received confirmation that service is running.\n");
403 #endif
404       GNUNET_SCHEDULER_add_continuation (conn->sched,
405                                          GNUNET_YES,
406                                          conn->test_cb,
407                                          conn->test_cb_cls,
408                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
409     }
410   else
411     {
412       service_test_error (conn->sched, conn->test_cb, conn->test_cb_cls);
413     }
414   GNUNET_CLIENT_disconnect (conn);
415 }
416
417
418 static size_t
419 write_test (void *cls, size_t size, void *buf)
420 {
421   struct GNUNET_MessageHeader *msg;
422
423   if (size < sizeof (struct GNUNET_MessageHeader))
424     {
425 #if DEBUG_CLIENT
426       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
427                   _("Failure to transmit TEST request.\n"));
428 #endif
429       return 0;                 /* client disconnected */
430     }
431 #if DEBUG_CLIENT
432   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _("Transmitting TEST request.\n"));
433 #endif
434   msg = (struct GNUNET_MessageHeader *) buf;
435   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
436   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
437   return sizeof (struct GNUNET_MessageHeader);
438 }
439
440
441 /**
442  * Wait until the service is running.
443  *
444  * @param sched scheduler to use
445  * @param service name of the service to wait for
446  * @param cfg configuration to use
447  * @param timeout how long to wait at most in ms
448  * @param task task to run if service is running
449  *        (reason will be "PREREQ_DONE" (service running)
450  *         or "TIMEOUT" (service not known to be running))
451  * @param task_cls closure for task
452  */
453 void
454 GNUNET_CLIENT_service_test (struct GNUNET_SCHEDULER_Handle *sched,
455                             const char *service,
456                             const struct GNUNET_CONFIGURATION_Handle *cfg,
457                             struct GNUNET_TIME_Relative timeout,
458                             GNUNET_SCHEDULER_Task task, void *task_cls)
459 {
460   struct GNUNET_CLIENT_Connection *conn;
461
462 #if DEBUG_CLIENT
463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
464               "Testing if service `%s' is running.\n", service);
465 #endif
466   conn = GNUNET_CLIENT_connect (sched, service, cfg);
467   if (conn == NULL)
468     {
469       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
470                   _
471                   ("Could not connect to service `%s', must not be running.\n"),
472                   service);
473       service_test_error (sched, task, task_cls);
474       return;
475     }
476   conn->test_cb = task;
477   conn->test_cb_cls = task_cls;
478   if (NULL ==
479       GNUNET_CONNECTION_notify_transmit_ready (conn->sock,
480                                             sizeof (struct
481                                                     GNUNET_MessageHeader),
482                                             timeout, &write_test, NULL))
483     {
484       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
485                   _("Failure to transmit request to service `%s'\n"),
486                   service);
487       service_test_error (sched, task, task_cls);
488       GNUNET_CLIENT_disconnect (conn);
489       return;
490     }
491   GNUNET_CLIENT_receive (conn, &confirm_handler, conn, timeout);
492 }
493
494
495 /**
496  * Ask the client to call us once the specified number of bytes
497  * are free in the transmission buffer.  May call the notify
498  * method immediately if enough space is available.
499  *
500  * @param sock connection to the service
501  * @param size number of bytes to send
502  * @param timeout after how long should we give up (and call
503  *        notify with buf NULL and size 0)?
504  * @param notify function to call
505  * @param notify_cls closure for notify
506  * @return NULL if our buffer will never hold size bytes,
507  *         a handle if the notify callback was queued (can be used to cancel)
508  */
509 struct GNUNET_CONNECTION_TransmitHandle *
510 GNUNET_CLIENT_notify_transmit_ready (struct GNUNET_CLIENT_Connection *sock,
511                                      size_t size,
512                                      struct GNUNET_TIME_Relative timeout,
513                                      GNUNET_CONNECTION_TransmitReadyNotify
514                                      notify, void *notify_cls)
515 {
516   return GNUNET_CONNECTION_notify_transmit_ready (sock->sock,
517                                                size,
518                                                timeout, notify, notify_cls);
519 }
520
521
522 /**
523  * Context for processing 
524  * "GNUNET_CLIENT_transmit_and_get_response" requests.
525  */
526 struct TARCtx
527 {
528   /**
529    * Client handle.
530    */
531   struct GNUNET_CLIENT_Connection *sock;
532
533   /**
534    * Message to transmit; do not free, allocated
535    * right after this struct.
536    */
537   const struct GNUNET_MessageHeader *hdr;
538
539   /**
540    * Timeout to use.
541    */
542   struct GNUNET_TIME_Absolute timeout;
543
544   /**
545    * Function to call when done.
546    */
547   GNUNET_CLIENT_MessageHandler rn;
548
549   /**
550    * Closure for "rn".
551    */
552   void *rn_cls;
553 };
554
555
556 /**
557  * Function called to notify a client about the socket
558  * begin ready to queue the message.  "buf" will be
559  * NULL and "size" zero if the socket was closed for
560  * writing in the meantime.
561  *
562  * @param cls closure of type "struct TARCtx*"
563  * @param size number of bytes available in buf
564  * @param buf where the callee should write the message
565  * @return number of bytes written to buf
566  */
567 static size_t
568 transmit_for_response (void *cls,
569                        size_t size, 
570                        void *buf)
571 {
572   struct TARCtx *tc = cls;
573   uint16_t msize;
574
575   msize = ntohs(tc->hdr->size);
576   if (NULL == buf)
577     {
578       tc->rn (tc->rn_cls, NULL);
579       GNUNET_free (tc);
580       return 0;
581     }
582   GNUNET_assert (size >= msize);
583   memcpy (buf, tc->hdr, msize);
584   GNUNET_CLIENT_receive (tc->sock,
585                          tc->rn,
586                          tc->rn_cls,
587                          GNUNET_TIME_absolute_get_remaining (tc->timeout));
588   GNUNET_free (tc);
589   return msize;
590 }
591
592
593 /**
594  * Convenience API that combines sending a request
595  * to the service and waiting for a response.
596  * If either operation times out, the callback
597  * will be called with a "NULL" response (in which
598  * case the connection should probably be destroyed).
599  *
600  * @param sock connection to use
601  * @param hdr message to transmit
602  * @param timeout when to give up (for both transmission
603  *         and for waiting for a response)
604  * @param rn function to call with the response
605  * @param rn_cls closure for rn 
606  */
607 void
608 GNUNET_CLIENT_transmit_and_get_response (struct GNUNET_CLIENT_Connection *sock,
609                                          const struct GNUNET_MessageHeader *hdr,
610                                          struct GNUNET_TIME_Relative timeout,
611                                          GNUNET_CLIENT_MessageHandler rn,
612                                          void *rn_cls)
613 {
614   struct TARCtx *tc;
615   uint16_t msize;
616
617   msize = ntohs(hdr->size);
618   tc = GNUNET_malloc(sizeof (struct TARCtx) + msize);
619   tc->sock = sock;
620   tc->hdr = (const struct GNUNET_MessageHeader*) &tc[1]; 
621   memcpy (&tc[1], hdr, msize);
622   tc->timeout = GNUNET_TIME_relative_to_absolute (timeout);
623   tc->rn = rn;
624   tc->rn_cls = rn_cls;
625   GNUNET_CLIENT_notify_transmit_ready (sock,
626                                        msize,
627                                        timeout,
628                                        &transmit_for_response,
629                                        tc);
630 }
631
632
633
634 /*  end of client.c */