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