-makefile for new test_stream_local (commented)
[oweals/gnunet.git] / src / transport / gnunet-service-transport_clients.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010,2011 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 3, 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 transport/gnunet-service-transport_clients.c
23  * @brief plugin management API
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet-service-transport_blacklist.h"
28 #include "gnunet-service-transport_clients.h"
29 #include "gnunet-service-transport_hello.h"
30 #include "gnunet-service-transport_neighbours.h"
31 #include "gnunet-service-transport_plugins.h"
32 #include "gnunet-service-transport_validation.h"
33 #include "gnunet-service-transport.h"
34 #include "transport.h"
35
36 /**
37  * How many messages can we have pending for a given client process
38  * before we start to drop incoming messages?  We typically should
39  * have only one client and so this would be the primary buffer for
40   * messages, so the number should be chosen rather generously.
41  *
42  * The expectation here is that most of the time the queue is large
43  * enough so that a drop is virtually never required.  Note that
44  * this value must be about as large as 'TOTAL_MSGS' in the
45  * 'test_transport_api_reliability.c', otherwise that testcase may
46  * fail.
47  */
48 #define MAX_PENDING (128 * 1024)
49
50
51 /**
52  * Linked list of messages to be transmitted to the client.  Each
53  * entry is followed by the actual message.
54  */
55 struct ClientMessageQueueEntry
56 {
57   /**
58    * This is a doubly-linked list.
59    */
60   struct ClientMessageQueueEntry *next;
61
62   /**
63    * This is a doubly-linked list.
64    */
65   struct ClientMessageQueueEntry *prev;
66 };
67
68
69 /**
70  * Client connected to the transport service.
71  */
72 struct TransportClient
73 {
74
75   /**
76    * This is a doubly-linked list.
77    */
78   struct TransportClient *next;
79
80   /**
81    * This is a doubly-linked list.
82    */
83   struct TransportClient *prev;
84
85   /**
86    * Handle to the client.
87    */
88   struct GNUNET_SERVER_Client *client;
89
90   /**
91    * Linked list of messages yet to be transmitted to
92    * the client.
93    */
94   struct ClientMessageQueueEntry *message_queue_head;
95
96   /**
97    * Tail of linked list of messages yet to be transmitted to the
98    * client.
99    */
100   struct ClientMessageQueueEntry *message_queue_tail;
101
102   /**
103    * Current transmit request handle.
104    */
105   struct GNUNET_CONNECTION_TransmitHandle *th;
106
107   /**
108    * Length of the list of messages pending for this client.
109    */
110   unsigned int message_count;
111
112   /**
113    * Is this client interested in payload messages?
114    */
115   int send_payload;
116 };
117
118
119 /**
120  * Client monitoring changes of active addresses of our neighbours.
121  */
122 struct MonitoringClient
123 {
124   /**
125    * This is a doubly-linked list.
126    */
127   struct MonitoringClient *next;
128
129   /**
130    * This is a doubly-linked list.
131    */
132   struct MonitoringClient *prev;
133
134   /**
135    * Handle to the client.
136    */
137   struct GNUNET_SERVER_Client *client;
138
139   /**
140    * Peer identity to monitor the addresses of.
141    * Zero to monitor all neighrours.
142    */
143   struct GNUNET_PeerIdentity peer;
144
145 };
146
147
148 /**
149  * Head of linked list of all clients to this service.
150  */
151 static struct TransportClient *clients_head;
152
153 /**
154  * Tail of linked list of all clients to this service.
155  */
156 static struct TransportClient *clients_tail;
157
158 /**
159  * Head of linked list of monitoring clients.
160  */
161 static struct MonitoringClient *monitoring_clients_head;
162
163 /**
164  * Tail of linked list of monitoring clients.
165  */
166 static struct MonitoringClient *monitoring_clients_tail;
167
168 /**
169  * Notification context, to send updates on changes to active addresses
170  * of our neighbours.
171  */
172 struct GNUNET_SERVER_NotificationContext *nc = NULL;
173
174
175 /**
176  * Find the internal handle associated with the given client handle
177  *
178  * @param client server's client handle to look up
179  * @return internal client handle
180  */
181 static struct TransportClient *
182 lookup_client (struct GNUNET_SERVER_Client *client)
183 {
184   struct TransportClient *tc;
185
186   tc = clients_head;
187   while (tc != NULL)
188   {
189     if (tc->client == client)
190       return tc;
191     tc = tc->next;
192   }
193   return NULL;
194 }
195
196
197 /**
198  * Create the internal handle for the given server client handle
199  *
200  * @param client server's client handle to create our internal handle for
201  * @return fresh internal client handle
202  */
203 static struct TransportClient *
204 setup_client (struct GNUNET_SERVER_Client *client)
205 {
206   struct TransportClient *tc;
207
208   GNUNET_assert (lookup_client (client) == NULL);
209   tc = GNUNET_malloc (sizeof (struct TransportClient));
210   tc->client = client;
211
212 #if DEBUG_TRANSPORT
213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p connected\n", tc);
214 #endif
215   return tc;
216 }
217
218
219 /**
220  * Find the handle to the monitoring client associated with the given
221  * client handle
222  *
223  * @param client server's client handle to look up
224  * @return handle to the monitoring client
225  */
226 static struct MonitoringClient *
227 lookup_monitoring_client (struct GNUNET_SERVER_Client *client)
228 {
229   struct MonitoringClient *mc;
230
231   mc = monitoring_clients_head;
232   while (mc != NULL)
233   {
234     if (mc->client == client)
235       return mc;
236     mc = mc->next;
237   }
238   return NULL;
239 }
240
241
242 /**
243  * Setup a new monitoring client using the given server client handle and
244  * the peer identity.
245  *
246  * @param client server's client handle to create our internal handle for
247  * @param peer identity of the peer to monitor the addresses of,
248  *             zero to monitor all neighrours.
249  * @return handle to the new monitoring client
250  */
251 static struct MonitoringClient *
252 setup_monitoring_client (struct GNUNET_SERVER_Client *client,
253                          struct GNUNET_PeerIdentity *peer)
254 {
255   struct MonitoringClient *mc;
256
257   GNUNET_assert (lookup_monitoring_client (client) == NULL);
258   mc = GNUNET_malloc (sizeof (struct MonitoringClient));
259   mc->client = client;
260   mc->peer = *peer;
261   GNUNET_CONTAINER_DLL_insert (monitoring_clients_head,
262                                monitoring_clients_tail,
263                                mc);
264   GNUNET_SERVER_notification_context_add (nc, client);
265
266   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
267               "Client %p started monitoring of the peer `%s'\n",
268               mc, GNUNET_i2s (peer));
269   return mc;
270 }
271
272
273 /**
274  * Function called to notify a client about the socket being ready to
275  * queue more data.  "buf" will be NULL and "size" zero if the socket
276  * was closed for writing in the meantime.
277  *
278  * @param cls closure
279  * @param size number of bytes available in buf
280  * @param buf where the callee should write the message
281  * @return number of bytes written to buf
282  */
283 static size_t
284 transmit_to_client_callback (void *cls, size_t size, void *buf)
285 {
286   struct TransportClient *tc = cls;
287   struct ClientMessageQueueEntry *q;
288   const struct GNUNET_MessageHeader *msg;
289   char *cbuf;
290   uint16_t msize;
291   size_t tsize;
292
293   tc->th = NULL;
294   if (buf == NULL)
295   {
296 #if DEBUG_TRANSPORT
297     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
298                 "Transmission to client failed, closing connection.\n");
299 #endif
300     return 0;
301   }
302   cbuf = buf;
303   tsize = 0;
304   while (NULL != (q = tc->message_queue_head))
305   {
306     msg = (const struct GNUNET_MessageHeader *) &q[1];
307     msize = ntohs (msg->size);
308     if (msize + tsize > size)
309       break;
310 #if DEBUG_TRANSPORT
311     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
312                 "Transmitting message of type %u to client %p.\n",
313                 ntohs (msg->type), tc);
314 #endif
315     GNUNET_CONTAINER_DLL_remove (tc->message_queue_head, tc->message_queue_tail,
316                                  q);
317     tc->message_count--;
318     memcpy (&cbuf[tsize], msg, msize);
319     GNUNET_free (q);
320     tsize += msize;
321   }
322   if (NULL != q)
323   {
324     GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
325     tc->th =
326         GNUNET_SERVER_notify_transmit_ready (tc->client, msize,
327                                              GNUNET_TIME_UNIT_FOREVER_REL,
328                                              &transmit_to_client_callback, tc);
329     GNUNET_assert (tc->th != NULL);
330   }
331   return tsize;
332 }
333
334
335 /**
336  * Queue the given message for transmission to the given client
337  *
338  * @param tc target of the message
339  * @param msg message to transmit
340  * @param may_drop GNUNET_YES if the message can be dropped
341  */
342 static void
343 unicast (struct TransportClient *tc, const struct GNUNET_MessageHeader *msg,
344          int may_drop)
345 {
346   struct ClientMessageQueueEntry *q;
347   uint16_t msize;
348
349   if ((tc->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
350   {
351     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
352                 _
353                 ("Dropping message of type %u and size %u, have %u/%u messages pending\n"),
354                 ntohs (msg->type), ntohs (msg->size), tc->message_count,
355                 MAX_PENDING);
356     GNUNET_STATISTICS_update (GST_stats,
357                               gettext_noop
358                               ("# messages dropped due to slow client"), 1,
359                               GNUNET_NO);
360     return;
361   }
362   msize = ntohs (msg->size);
363   GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
364   q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
365   memcpy (&q[1], msg, msize);
366   GNUNET_CONTAINER_DLL_insert_tail (tc->message_queue_head,
367                                     tc->message_queue_tail, q);
368   tc->message_count++;
369   if (tc->th != NULL)
370     return;
371   tc->th =
372       GNUNET_SERVER_notify_transmit_ready (tc->client, msize,
373                                            GNUNET_TIME_UNIT_FOREVER_REL,
374                                            &transmit_to_client_callback, tc);
375   GNUNET_assert (tc->th != NULL);
376 }
377
378
379 /**
380  * Called whenever a client is disconnected.  Frees our
381  * resources associated with that client.
382  *
383  * @param cls closure
384  * @param client identification of the client
385  */
386 static void
387 client_disconnect_notification (void *cls, struct GNUNET_SERVER_Client *client)
388 {
389   struct TransportClient *tc;
390   struct MonitoringClient *mc;
391   struct ClientMessageQueueEntry *mqe;
392
393   if (client == NULL)
394     return;
395   mc = lookup_monitoring_client (client);
396   if (mc != NULL)
397   {
398     GNUNET_CONTAINER_DLL_remove (monitoring_clients_head,
399                                  monitoring_clients_tail,
400                                  mc);
401     GNUNET_free (mc);
402   }
403   tc = lookup_client (client);
404   if (tc == NULL)
405     return;
406 #if DEBUG_TRANSPORT
407   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
408               "Client %p disconnected, cleaning up.\n", tc);
409 #endif
410   while (NULL != (mqe = tc->message_queue_head))
411   {
412     GNUNET_CONTAINER_DLL_remove (tc->message_queue_head, tc->message_queue_tail,
413                                  mqe);
414     tc->message_count--;
415     GNUNET_free (mqe);
416   }
417   GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, tc);
418   if (tc->th != NULL)
419   {
420     GNUNET_CONNECTION_notify_transmit_ready_cancel (tc->th);
421     tc->th = NULL;
422   }
423   GNUNET_break (0 == tc->message_count);
424   GNUNET_free (tc);
425 }
426
427
428 /**
429  * Function called for each of our connected neighbours.  Notify the
430  * client about the existing neighbour.
431  *
432  * @param cls the 'struct TransportClient' to notify
433  * @param peer identity of the neighbour
434  * @param ats performance data
435  * @param ats_count number of entries in ats (excluding 0-termination)
436  * @param address the address
437  */
438 static void
439 notify_client_about_neighbour (void *cls,
440                                const struct GNUNET_PeerIdentity *peer,
441                                const struct GNUNET_ATS_Information *ats,
442                                uint32_t ats_count,
443                                const struct GNUNET_HELLO_Address *address)
444 {
445   struct TransportClient *tc = cls;
446   struct ConnectInfoMessage *cim;
447   struct GNUNET_ATS_Information *ap;
448   size_t size =
449       sizeof (struct ConnectInfoMessage) +
450       ats_count * sizeof (struct GNUNET_ATS_Information);
451   char buf[size];
452
453   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
454   cim = (struct ConnectInfoMessage *) buf;
455   cim->header.size = htons (size);
456   cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
457   cim->ats_count = htonl (ats_count);
458   cim->id = *peer;
459   ap = (struct GNUNET_ATS_Information *) &cim[1];
460   memcpy (ap, ats, ats_count * sizeof (struct GNUNET_ATS_Information));
461   unicast (tc, &cim->header, GNUNET_NO);
462 }
463
464
465 /**
466  * Initialize a normal client.  We got a start message from this
467  * client, add him to the list of clients for broadcasting of inbound
468  * messages.
469  *
470  * @param cls unused
471  * @param client the client
472  * @param message the start message that was sent
473  */
474 static void
475 clients_handle_start (void *cls, struct GNUNET_SERVER_Client *client,
476                       const struct GNUNET_MessageHeader *message)
477 {
478   const struct StartMessage *start;
479   struct TransportClient *tc;
480   uint32_t options;
481
482   tc = lookup_client (client);
483
484 #if DEBUG_TRANSPORT
485   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
486               "Client %p sent START\n", tc);
487 #endif
488   if (tc != NULL)
489   {
490     /* got 'start' twice from the same client, not allowed */
491 #if DEBUG_TRANSPORT
492     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
493                 "TransportClient %p ServerClient %p sent multiple START messages\n",
494                 tc, tc->client);
495 #endif
496     GNUNET_break (0);
497     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
498     return;
499   }
500   start = (const struct StartMessage *) message;
501   options = ntohl (start->options);
502   if ((0 != (1 & options)) &&
503       (0 !=
504        memcmp (&start->self, &GST_my_identity,
505                sizeof (struct GNUNET_PeerIdentity))))
506   {
507     /* client thinks this is a different peer, reject */
508     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
509                 _
510                 ("Rejecting control connection from peer `%s', which is not me!\n"),
511                 GNUNET_i2s (&start->self));
512     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
513     return;
514   }
515   tc = setup_client (client);
516   tc->send_payload = (0 != (2 & options));
517   unicast (tc, GST_hello_get (), GNUNET_NO);
518   GST_neighbours_iterate (&notify_client_about_neighbour, tc);
519   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, tc);
520   GNUNET_SERVER_receive_done (client, GNUNET_OK);
521 }
522
523
524 /**
525  * Client sent us a HELLO.  Process the request.
526  *
527  * @param cls unused
528  * @param client the client
529  * @param message the HELLO message
530  */
531 static void
532 clients_handle_hello (void *cls, struct GNUNET_SERVER_Client *client,
533                       const struct GNUNET_MessageHeader *message)
534 {
535   GST_validation_handle_hello (message);
536   GNUNET_SERVER_receive_done (client, GNUNET_OK);
537 }
538
539
540 /**
541  * Closure for 'handle_send_transmit_continuation'
542  */
543 struct SendTransmitContinuationContext
544 {
545   /**
546    * Client that made the request.
547    */
548   struct GNUNET_SERVER_Client *client;
549
550   /**
551    * Peer that was the target.
552    */
553   struct GNUNET_PeerIdentity target;
554 };
555
556
557 /**
558  * Function called after the transmission is done.  Notify the client that it is
559  * OK to send the next message.
560  *
561  * @param cls closure
562  * @param success GNUNET_OK on success, GNUNET_NO on failure, GNUNET_SYSERR if we're not connected
563  */
564 static void
565 handle_send_transmit_continuation (void *cls, int success)
566 {
567   struct SendTransmitContinuationContext *stcc = cls;
568   struct SendOkMessage send_ok_msg;
569
570   send_ok_msg.header.size = htons (sizeof (send_ok_msg));
571   send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
572   send_ok_msg.success = htonl (success);
573   send_ok_msg.latency =
574       GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_FOREVER_REL);
575   send_ok_msg.peer = stcc->target;
576   GST_clients_unicast (stcc->client, &send_ok_msg.header, GNUNET_NO);
577   GNUNET_SERVER_client_drop (stcc->client);
578   GNUNET_free (stcc);
579 }
580
581
582 /**
583  * Client asked for transmission to a peer.  Process the request.
584  *
585  * @param cls unused
586  * @param client the client
587  * @param message the send message that was sent
588  */
589 static void
590 clients_handle_send (void *cls, struct GNUNET_SERVER_Client *client,
591                      const struct GNUNET_MessageHeader *message)
592 {
593   const struct OutboundMessage *obm;
594   const struct GNUNET_MessageHeader *obmm;
595   struct SendTransmitContinuationContext *stcc;
596   uint16_t size;
597   uint16_t msize;
598   struct TransportClient *tc;
599
600   tc = lookup_client (client);
601   if (NULL == tc)
602   {
603     /* client asked for transmission before 'START' */
604     GNUNET_break (0);
605     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
606     return;
607   }
608
609   size = ntohs (message->size);
610   if (size <
611       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
612   {
613     GNUNET_break (0);
614     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
615     return;
616   }
617   obm = (const struct OutboundMessage *) message;
618   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
619   msize = size - sizeof (struct OutboundMessage);
620   if (msize < sizeof (struct GNUNET_MessageHeader))
621   {
622     GNUNET_break (0);
623     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
624     return;
625   }
626   GNUNET_STATISTICS_update (GST_stats,
627                             gettext_noop
628                             ("# bytes payload received for other peers"), msize,
629                             GNUNET_NO);
630 #if DEBUG_TRANSPORT
631   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
632               "Received `%s' request from client with target `%4s' and first message of type %u and total size %u\n",
633               "SEND", GNUNET_i2s (&obm->peer), ntohs (obmm->type), msize);
634 #endif
635   if (GNUNET_NO == GST_neighbours_test_connected (&obm->peer))
636   {
637     /* not connected, not allowed to send; can happen due to asynchronous operations */
638 #if DEBUG_TRANSPORT
639     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
640                 "Could not send message to peer `%s': not connected\n",
641                 GNUNET_i2s (&obm->peer));
642 #endif
643     GNUNET_STATISTICS_update (GST_stats,
644                               gettext_noop
645                               ("# bytes payload dropped (other peer was not connected)"),
646                               msize, GNUNET_NO);
647     GNUNET_SERVER_receive_done (client, GNUNET_OK);
648     return;
649   }
650   GNUNET_SERVER_receive_done (client, GNUNET_OK);
651   stcc = GNUNET_malloc (sizeof (struct SendTransmitContinuationContext));
652   stcc->target = obm->peer;
653   stcc->client = client;
654   GNUNET_SERVER_client_keep (client);
655   GST_neighbours_send (&obm->peer, obmm, msize,
656                        GNUNET_TIME_relative_ntoh (obm->timeout),
657                        &handle_send_transmit_continuation, stcc);
658 }
659
660
661 /**
662  * Try to initiate a connection to the given peer if the blacklist
663  * allowed it.
664  *
665  * @param cls closure (unused, NULL)
666  * @param peer identity of peer that was tested
667  * @param result GNUNET_OK if the connection is allowed,
668  *               GNUNET_NO if not
669  */
670 static void
671 try_connect_if_allowed (void *cls, const struct GNUNET_PeerIdentity *peer,
672                         int result)
673 {
674   if (GNUNET_OK != result)
675     return;                     /* not allowed */
676   GST_neighbours_try_connect (peer);
677 }
678
679
680 /**
681  * Handle request connect message
682  *
683  * @param cls closure (always NULL)
684  * @param client identification of the client
685  * @param message the actual message
686  */
687 static void
688 clients_handle_request_connect (void *cls, struct GNUNET_SERVER_Client *client,
689                                 const struct GNUNET_MessageHeader *message)
690 {
691   const struct TransportRequestConnectMessage *trcm =
692       (const struct TransportRequestConnectMessage *) message;
693
694   GNUNET_STATISTICS_update (GST_stats,
695                             gettext_noop
696                             ("# REQUEST CONNECT messages received"), 1,
697                             GNUNET_NO);
698 #if DEBUG_TRANSPORT
699   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
700               "Received a request connect message for peer `%s'\n",
701               GNUNET_i2s (&trcm->peer));
702 #endif
703   (void) GST_blacklist_test_allowed (&trcm->peer, NULL, &try_connect_if_allowed,
704                                      NULL);
705   GNUNET_SERVER_receive_done (client, GNUNET_OK);
706 }
707
708
709 /**
710  * Take the given address and append it to the set of results sent back to
711  * the client.
712  *
713  * @param cls the transmission context used ('struct GNUNET_SERVER_TransmitContext*')
714  * @param buf text to transmit
715  */
716 static void
717 transmit_address_to_client (void *cls, const char *buf)
718 {
719   struct GNUNET_SERVER_TransmitContext *tc = cls;
720
721   if (NULL == buf)
722   {
723     GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
724                                                 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_TO_STRING_REPLY);
725     GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
726     return;
727   }
728   GNUNET_SERVER_transmit_context_append_data (tc, buf, strlen (buf) + 1,
729                                               GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_TO_STRING_REPLY);
730 }
731
732
733 /**
734  * Client asked to resolve an address.  Process the request.
735  *
736  * @param cls unused
737  * @param client the client
738  * @param message the resolution request
739  */
740 static void
741 clients_handle_address_to_string (void *cls,
742                                   struct GNUNET_SERVER_Client *client,
743                                   const struct GNUNET_MessageHeader *message)
744 {
745   const struct AddressLookupMessage *alum;
746   struct GNUNET_TRANSPORT_PluginFunctions *papi;
747   const char *plugin_name;
748   const char *address;
749   uint32_t address_len;
750   uint16_t size;
751   struct GNUNET_SERVER_TransmitContext *tc;
752   struct GNUNET_TIME_Relative rtimeout;
753   int32_t numeric;
754
755   size = ntohs (message->size);
756   if (size < sizeof (struct AddressLookupMessage))
757   {
758     GNUNET_break (0);
759     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
760     return;
761   }
762   alum = (const struct AddressLookupMessage *) message;
763   address_len = ntohs (alum->addrlen);
764   if (size <= sizeof (struct AddressLookupMessage) + address_len)
765   {
766     GNUNET_break (0);
767     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
768     return;
769   }
770   address = (const char *) &alum[1];
771   plugin_name = (const char *) &address[address_len];
772   if (plugin_name[size - sizeof (struct AddressLookupMessage) - address_len - 1]
773       != '\0')
774   {
775     GNUNET_break (0);
776     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
777     return;
778   }
779   rtimeout = GNUNET_TIME_relative_ntoh (alum->timeout);
780   numeric = ntohs (alum->numeric_only);
781   tc = GNUNET_SERVER_transmit_context_create (client);
782   papi = GST_plugins_find (plugin_name);
783   if (NULL == papi)
784   {
785     GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
786                                                 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_TO_STRING_REPLY);
787     GNUNET_SERVER_transmit_context_run (tc, rtimeout);
788     return;
789   }
790   GNUNET_SERVER_disable_receive_done_warning (client);
791   if ((NULL == address) || (0 == address_len))
792   {
793     GNUNET_break_op (0);
794   }
795   papi->address_pretty_printer (papi->cls, plugin_name, address, address_len,
796                                 numeric, rtimeout, &transmit_address_to_client,
797                                 tc);
798 }
799
800
801 /**
802  * Compose AddressIterateResponseMessage using the given peer and address.
803  *
804  * @param peer identity of the peer
805  * @param address the address, NULL on disconnect
806  * @return composed message
807  */
808 static struct AddressIterateResponseMessage *
809 compose_address_iterate_response_message (const struct GNUNET_PeerIdentity
810                                           *peer,
811                                           const struct GNUNET_HELLO_Address
812                                           *address)
813 {
814   struct AddressIterateResponseMessage *msg;
815   size_t size;
816   size_t tlen;
817   size_t alen;
818   char *addr;
819
820   GNUNET_assert (NULL != peer);
821   if (NULL != address)
822   {
823     tlen = strlen (address->transport_name) + 1;
824     alen = address->address_length;
825   }
826   else
827     tlen = alen = 0;
828   size = (sizeof (struct AddressIterateResponseMessage) + alen + tlen);
829   msg = GNUNET_malloc (size);
830   msg->header.size = htons (size);
831   msg->header.type =
832       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_ITERATE_RESPONSE);
833   msg->reserved = htonl (0);
834   msg->peer = *peer;
835   msg->addrlen = htonl (alen);
836   msg->pluginlen = htonl (tlen);
837   if (NULL != address)
838   {
839     addr = (char *) &msg[1];
840     memcpy (addr, address->address, alen);
841     memcpy (&addr[alen], address->transport_name, tlen);
842   }
843   return msg;
844 }
845
846
847 /**
848  * Output the active address of connected neighbours to the given client.
849  *
850  * @param cls the 'struct GNUNET_SERVER_TransmitContext' for transmission to the client
851  * @param peer identity of the neighbour
852  * @param ats performance data
853  * @param ats_count number of entries in ats (excluding 0-termination)
854  * @param address the address
855  */
856 static void
857 output_address (void *cls, const struct GNUNET_PeerIdentity *peer,
858                 const struct GNUNET_ATS_Information *ats, uint32_t ats_count,
859                 const struct GNUNET_HELLO_Address *address)
860 {
861   struct GNUNET_SERVER_TransmitContext *tc = cls;
862   struct AddressIterateResponseMessage *msg;
863
864   msg = compose_address_iterate_response_message (peer, address);
865   GNUNET_SERVER_transmit_context_append_message (tc, &msg->header);
866   GNUNET_free (msg);
867 }
868
869
870 /**
871  * Client asked to obtain information about all actively used addresses
872  * of connected peers
873  * Process the request.
874  *
875  * @param cls unused
876  * @param client the client
877  * @param message the peer address information request
878  */
879 static void
880 clients_handle_address_iterate (void *cls, struct GNUNET_SERVER_Client *client,
881                                 const struct GNUNET_MessageHeader *message)
882 {
883   static struct GNUNET_PeerIdentity all_zeros;
884   struct GNUNET_SERVER_TransmitContext *tc;
885   struct AddressIterateMessage *msg;
886   struct GNUNET_HELLO_Address *address;
887
888   if (ntohs (message->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_ITERATE)
889   {
890     GNUNET_break (0);
891     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
892     return;
893   }
894   if (ntohs (message->size) != sizeof (struct AddressIterateMessage))
895   {
896     GNUNET_break (0);
897     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
898     return;
899   }
900   msg = (struct AddressIterateMessage *) message;
901   if ( (GNUNET_YES != ntohl (msg->one_shot)) &&
902        (NULL != lookup_monitoring_client (client)) )
903   {
904     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
905                 "ServerClient %p tried to start monitoring twice\n",
906                 client);
907     GNUNET_break (0);
908     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
909     return;
910   }
911   GNUNET_SERVER_disable_receive_done_warning (client);
912   tc = GNUNET_SERVER_transmit_context_create (client);
913   if (0 == memcmp (&msg->peer, &all_zeros, sizeof (struct GNUNET_PeerIdentity)))
914   {
915     /* iterate over all neighbours */
916     GST_neighbours_iterate (&output_address, tc);
917   }
918   else
919   {
920     /* just return one neighbour */
921     address = GST_neighbour_get_current_address (&msg->peer);
922     if (address != NULL)
923       output_address (tc, &msg->peer, NULL, 0, address);
924   }
925   if (GNUNET_YES != ntohl (msg->one_shot))
926     setup_monitoring_client (client, &msg->peer);
927   else
928     GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
929                                                 GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_ITERATE_RESPONSE);  
930   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
931 }
932
933
934 /**
935  * Start handling requests from clients.
936  *
937  * @param server server used to accept clients from.
938  */
939 void
940 GST_clients_start (struct GNUNET_SERVER_Handle *server)
941 {
942   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
943     {&clients_handle_start, NULL,
944      GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
945     {&clients_handle_hello, NULL,
946      GNUNET_MESSAGE_TYPE_HELLO, 0},
947     {&clients_handle_send, NULL,
948      GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
949     {&clients_handle_request_connect, NULL,
950      GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT,
951      sizeof (struct TransportRequestConnectMessage)},
952     {&clients_handle_address_to_string, NULL,
953      GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_TO_STRING, 0},
954     {&clients_handle_address_iterate, NULL,
955      GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_ITERATE,
956      sizeof (struct AddressIterateMessage)},
957     {&GST_blacklist_handle_init, NULL,
958      GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT,
959      sizeof (struct GNUNET_MessageHeader)},
960     {&GST_blacklist_handle_reply, NULL,
961      GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY,
962      sizeof (struct BlacklistMessage)},
963     {NULL, NULL, 0, 0}
964   };
965   nc = GNUNET_SERVER_notification_context_create (server, 0);
966   GNUNET_SERVER_add_handlers (server, handlers);
967   GNUNET_SERVER_disconnect_notify (server, &client_disconnect_notification,
968                                    NULL);
969 }
970
971
972 /**
973  * Stop processing clients.
974  */
975 void
976 GST_clients_stop ()
977 {
978   if (NULL != nc)
979   {
980     GNUNET_SERVER_notification_context_destroy (nc);
981     nc = NULL;
982   }
983 }
984
985
986 /**
987  * Broadcast the given message to all of our clients.
988  *
989  * @param msg message to broadcast
990  * @param may_drop GNUNET_YES if the message can be dropped / is payload
991  */
992 void
993 GST_clients_broadcast (const struct GNUNET_MessageHeader *msg, int may_drop)
994 {
995   struct TransportClient *tc;
996
997   for (tc = clients_head; tc != NULL; tc = tc->next)
998   {
999     if ((GNUNET_YES == may_drop) && (GNUNET_YES != tc->send_payload))
1000       continue;                 /* skip, this client does not care about payload */
1001     unicast (tc, msg, may_drop);
1002   }
1003 }
1004
1005
1006 /**
1007  * Send the given message to a particular client
1008  *
1009  * @param client target of the message
1010  * @param msg message to transmit
1011  * @param may_drop GNUNET_YES if the message can be dropped
1012  */
1013 void
1014 GST_clients_unicast (struct GNUNET_SERVER_Client *client,
1015                      const struct GNUNET_MessageHeader *msg, int may_drop)
1016 {
1017   struct TransportClient *tc;
1018
1019   tc = lookup_client (client);
1020   if (NULL == tc)
1021     return;                     /* client got disconnected in the meantime, drop message */
1022   unicast (tc, msg, may_drop);
1023 }
1024
1025
1026 /**
1027  * Broadcast the new active address to all clients monitoring the peer.
1028  *
1029  * @param peer peer this update is about (never NULL)
1030  * @param address address, NULL on disconnect
1031  */
1032 void
1033 GST_clients_broadcast_address_notification (const struct GNUNET_PeerIdentity
1034                                             *peer,
1035                                             const struct GNUNET_HELLO_Address
1036                                             *address)
1037 {
1038   struct AddressIterateResponseMessage *msg;
1039   struct MonitoringClient *mc;
1040   static struct GNUNET_PeerIdentity all_zeros;
1041
1042   msg = compose_address_iterate_response_message (peer, address);
1043   mc = monitoring_clients_head;
1044   while (mc != NULL)
1045   {
1046     if ((0 == memcmp (&mc->peer, &all_zeros,
1047                       sizeof (struct GNUNET_PeerIdentity))) ||
1048         (0 == memcmp (&mc->peer, peer,
1049                       sizeof (struct GNUNET_PeerIdentity))))
1050     {
1051       GNUNET_SERVER_notification_context_unicast (nc, mc->client,
1052                                                   &msg->header, GNUNET_NO);
1053     }
1054
1055     mc = mc->next;
1056   }
1057   GNUNET_free (msg);
1058 }
1059
1060
1061 /* end of file gnunet-service-transport_clients.c */