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