-fix use of possibly wrong or uninitialized session
[oweals/gnunet.git] / src / transport / gnunet-service-transport_clients.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010-2014 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 /**
122  * Context for address to string operations
123  */
124 struct AddressToStringContext
125 {
126   /**
127    * This is a doubly-linked list.
128    */
129   struct AddressToStringContext *next;
130
131   /**
132    * This is a doubly-linked list.
133    */
134   struct AddressToStringContext *prev;
135
136   /**
137    * Transmission context
138    */
139   struct GNUNET_SERVER_TransmitContext* tc;
140 };
141
142
143 /**
144  * Client monitoring changes of active addresses of our neighbours.
145  */
146 struct MonitoringClient
147 {
148   /**
149    * This is a doubly-linked list.
150    */
151   struct MonitoringClient *next;
152
153   /**
154    * This is a doubly-linked list.
155    */
156   struct MonitoringClient *prev;
157
158   /**
159    * Handle to the client.
160    */
161   struct GNUNET_SERVER_Client *client;
162
163   /**
164    * Peer identity to monitor the addresses of.
165    * Zero to monitor all neighrours.
166    */
167   struct GNUNET_PeerIdentity peer;
168
169 };
170
171
172 /**
173  * Head of linked list of all clients to this service.
174  */
175 static struct TransportClient *clients_head;
176
177 /**
178  * Tail of linked list of all clients to this service.
179  */
180 static struct TransportClient *clients_tail;
181
182 /**
183  * Head of linked list of all pending address iterations
184  */
185 struct AddressToStringContext *a2s_head;
186
187 /**
188  * Tail of linked list of all pending address iterations
189  */
190 struct AddressToStringContext *a2s_tail;
191
192 /**
193  * Head of linked list of monitoring clients.
194  */
195 static struct MonitoringClient *peer_monitoring_clients_head;
196
197 /**
198  * Tail of linked list of monitoring clients.
199  */
200 static struct MonitoringClient *peer_monitoring_clients_tail;
201
202 /**
203  * Head of linked list of validation monitoring clients.
204  */
205 static struct MonitoringClient *val_monitoring_clients_head;
206
207 /**
208  * Tail of linked list of validation monitoring clients.
209  */
210 static struct MonitoringClient *val_monitoring_clients_tail;
211
212 /**
213  * Notification context, to send updates on changes to active addresses
214  * of our neighbours.
215  */
216 static struct GNUNET_SERVER_NotificationContext *peer_nc;
217
218 /**
219  * Notification context, to send updates on changes to active addresses
220  * of our neighbours.
221  */
222 static struct GNUNET_SERVER_NotificationContext *val_nc;
223
224 /**
225  * Notification context, to send updates on changes to active plugin
226  * connections.
227  */
228 static struct GNUNET_SERVER_NotificationContext *plugin_nc;
229
230 /**
231  * Plugin monitoring client we are currently syncing, NULL if all
232  * monitoring clients are in sync.
233  */
234 static struct GNUNET_SERVER_Client *sync_client;
235
236
237 /**
238  * Find the internal handle associated with the given client handle
239  *
240  * @param client server's client handle to look up
241  * @return internal client handle
242  */
243 static struct TransportClient *
244 lookup_client (struct GNUNET_SERVER_Client *client)
245 {
246   struct TransportClient *tc;
247
248   for (tc = clients_head; NULL != tc; tc = tc->next)
249     if (tc->client == client)
250       return tc;
251   return NULL;
252 }
253
254
255 /**
256  * Create the internal handle for the given server client handle
257  *
258  * @param client server's client handle to create our internal handle for
259  * @return fresh internal client handle
260  */
261 static struct TransportClient *
262 setup_client (struct GNUNET_SERVER_Client *client)
263 {
264   struct TransportClient *tc;
265
266   GNUNET_assert (NULL == lookup_client (client));
267   tc = GNUNET_new (struct TransportClient);
268   tc->client = client;
269   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
270               "Client %p connected\n",
271               tc);
272   return tc;
273 }
274
275
276 /**
277  * Find the handle to the monitoring client associated with the given
278  * client handle
279  *
280  * @param head the head of the client queue to look in
281  * @param client server's client handle to look up
282  * @return handle to the monitoring client
283  */
284 static struct MonitoringClient *
285 lookup_monitoring_client (struct MonitoringClient *head,
286                           struct GNUNET_SERVER_Client *client)
287 {
288   struct MonitoringClient *mc;
289
290   for (mc = head; NULL != mc; mc = mc->next)
291     if (mc->client == client)
292       return mc;
293   return NULL;
294 }
295
296
297 /**
298  * Setup a new monitoring client using the given server client handle and
299  * the peer identity.
300  *
301  * @param client server's client handle to create our internal handle for
302  * @param peer identity of the peer to monitor the addresses of,
303  *             zero to monitor all neighrours.
304  * @return handle to the new monitoring client
305  */
306 static struct MonitoringClient *
307 setup_peer_monitoring_client (struct GNUNET_SERVER_Client *client,
308                               const struct GNUNET_PeerIdentity *peer)
309 {
310   struct MonitoringClient *mc;
311   static struct GNUNET_PeerIdentity all_zeros;
312
313   GNUNET_assert (NULL ==
314                  lookup_monitoring_client (peer_monitoring_clients_head,
315                                            client));
316   mc = GNUNET_new (struct MonitoringClient);
317   mc->client = client;
318   mc->peer = *peer;
319   GNUNET_CONTAINER_DLL_insert (peer_monitoring_clients_head,
320                                peer_monitoring_clients_tail,
321                                mc);
322   GNUNET_SERVER_client_mark_monitor (client);
323   GNUNET_SERVER_notification_context_add (peer_nc, client);
324
325   if (0 != memcmp (peer, &all_zeros, sizeof (struct GNUNET_PeerIdentity)))
326     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
327                 "Client %p started monitoring of the peer `%s'\n",
328                 mc,
329                 GNUNET_i2s (peer));
330   else
331     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
332                 "Client %p started monitoring all peers\n",
333                 mc);
334   return mc;
335 }
336
337
338 /**
339  * Setup a new monitoring client using the given server client handle and
340  * the peer identity.
341  *
342  * @param client server's client handle to create our internal handle for
343  * @param peer identity of the peer to monitor the addresses of,
344  *             zero to monitor all neighrours.
345  * @return handle to the new monitoring client
346  */
347 static struct MonitoringClient *
348 setup_val_monitoring_client (struct GNUNET_SERVER_Client *client,
349                              struct GNUNET_PeerIdentity *peer)
350 {
351   struct MonitoringClient *mc;
352   static struct GNUNET_PeerIdentity all_zeros;
353
354   GNUNET_assert (NULL ==
355                  lookup_monitoring_client (val_monitoring_clients_head,
356                                            client));
357   mc = GNUNET_new (struct MonitoringClient);
358   mc->client = client;
359   mc->peer = *peer;
360   GNUNET_CONTAINER_DLL_insert (val_monitoring_clients_head,
361                                val_monitoring_clients_tail,
362                                mc);
363   GNUNET_SERVER_notification_context_add (val_nc, client);
364
365   if (0 != memcmp (peer,
366                    &all_zeros,
367                    sizeof (struct GNUNET_PeerIdentity)))
368     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
369                 "Client %p started monitoring of the peer `%s'\n",
370                 mc, GNUNET_i2s (peer));
371   else
372     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
373               "Client %p started monitoring all peers\n", mc);
374   return mc;
375 }
376
377
378 /**
379  * Function called to notify a client about the socket being ready to
380  * queue more data.  "buf" will be NULL and "size" zero if the socket
381  * was closed for writing in the meantime.
382  *
383  * @param cls closure
384  * @param size number of bytes available in @a buf
385  * @param buf where the callee should write the message
386  * @return number of bytes written to @a buf
387  */
388 static size_t
389 transmit_to_client_callback (void *cls,
390                              size_t size,
391                              void *buf)
392 {
393   struct TransportClient *tc = cls;
394   struct ClientMessageQueueEntry *q;
395   const struct GNUNET_MessageHeader *msg;
396   char *cbuf;
397   uint16_t msize;
398   size_t tsize;
399
400   tc->th = NULL;
401   if (NULL == buf)
402   {
403     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
404                 "Transmission to client failed, closing connection.\n");
405     return 0;
406   }
407   cbuf = buf;
408   tsize = 0;
409   while (NULL != (q = tc->message_queue_head))
410   {
411     msg = (const struct GNUNET_MessageHeader *) &q[1];
412     msize = ntohs (msg->size);
413     if (msize + tsize > size)
414       break;
415     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
416                 "Transmitting message of type %u to client %p.\n",
417                 ntohs (msg->type), tc);
418     GNUNET_CONTAINER_DLL_remove (tc->message_queue_head,
419                                  tc->message_queue_tail,
420                                  q);
421     tc->message_count--;
422     memcpy (&cbuf[tsize], msg, msize);
423     GNUNET_free (q);
424     tsize += msize;
425   }
426   if (NULL != q)
427   {
428     GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
429     tc->th =
430         GNUNET_SERVER_notify_transmit_ready (tc->client, msize,
431                                              GNUNET_TIME_UNIT_FOREVER_REL,
432                                              &transmit_to_client_callback, tc);
433     GNUNET_assert (NULL != tc->th);
434   }
435   return tsize;
436 }
437
438
439 /**
440  * Queue the given message for transmission to the given client
441  *
442  * @param tc target of the message
443  * @param msg message to transmit
444  * @param may_drop #GNUNET_YES if the message can be dropped
445  */
446 static void
447 unicast (struct TransportClient *tc,
448          const struct GNUNET_MessageHeader *msg,
449          int may_drop)
450 {
451   struct ClientMessageQueueEntry *q;
452   uint16_t msize;
453
454   if (NULL == msg)
455   {
456     GNUNET_break (0);
457     return;
458   }
459
460   if ((tc->message_count >= MAX_PENDING) && (GNUNET_YES == may_drop))
461   {
462     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
463                 _("Dropping message of type %u and size %u, have %u/%u messages pending\n"),
464                 ntohs (msg->type),
465                 ntohs (msg->size),
466                 tc->message_count,
467                 MAX_PENDING);
468     GNUNET_STATISTICS_update (GST_stats,
469                               gettext_noop
470                               ("# messages dropped due to slow client"), 1,
471                               GNUNET_NO);
472     return;
473   }
474   msize = ntohs (msg->size);
475   GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
476   q = GNUNET_malloc (sizeof (struct ClientMessageQueueEntry) + msize);
477   memcpy (&q[1], msg, msize);
478   GNUNET_CONTAINER_DLL_insert_tail (tc->message_queue_head,
479                                     tc->message_queue_tail, q);
480   tc->message_count++;
481   if (NULL != tc->th)
482     return;
483   tc->th =
484       GNUNET_SERVER_notify_transmit_ready (tc->client, msize,
485                                            GNUNET_TIME_UNIT_FOREVER_REL,
486                                            &transmit_to_client_callback, tc);
487   GNUNET_assert (NULL != tc->th);
488 }
489
490
491 /**
492  * Called whenever a client is disconnected.  Frees our
493  * resources associated with that client.
494  *
495  * @param cls closure
496  * @param client identification of the client
497  */
498 static void
499 client_disconnect_notification (void *cls,
500                                 struct GNUNET_SERVER_Client *client)
501 {
502   struct TransportClient *tc;
503   struct MonitoringClient *mc;
504   struct ClientMessageQueueEntry *mqe;
505
506   if (client == NULL)
507     return;
508   mc = lookup_monitoring_client (peer_monitoring_clients_head,
509                                  client);
510   if (mc != NULL)
511   {
512     GNUNET_CONTAINER_DLL_remove (peer_monitoring_clients_head,
513                                  peer_monitoring_clients_tail,
514                                  mc);
515     GNUNET_free (mc);
516   }
517   mc = lookup_monitoring_client (val_monitoring_clients_head,
518                                  client);
519   if (mc != NULL)
520   {
521     GNUNET_CONTAINER_DLL_remove (val_monitoring_clients_head,
522                                  val_monitoring_clients_tail,
523                                  mc);
524     GNUNET_free (mc);
525   }
526   tc = lookup_client (client);
527   if (tc == NULL)
528     return;
529   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
530               "Client %p disconnected, cleaning up.\n", tc);
531   while (NULL != (mqe = tc->message_queue_head))
532   {
533     GNUNET_CONTAINER_DLL_remove (tc->message_queue_head, tc->message_queue_tail,
534                                  mqe);
535     tc->message_count--;
536     GNUNET_free (mqe);
537   }
538   GNUNET_CONTAINER_DLL_remove (clients_head, clients_tail, tc);
539   if (tc->th != NULL)
540   {
541     GNUNET_SERVER_notify_transmit_ready_cancel (tc->th);
542     tc->th = NULL;
543   }
544   GNUNET_break (0 == tc->message_count);
545   GNUNET_free (tc);
546 }
547
548
549 /**
550  * Function called for each of our connected neighbours.  Notify the
551  * client about the existing neighbour.
552  *
553  * @param cls the `struct TransportClient *` to notify
554  * @param peer identity of the neighbour
555  * @param address the address
556  * @param state the current state of the peer
557  * @param state_timeout the time out for the state
558  * @param bandwidth_in inbound bandwidth in NBO
559  * @param bandwidth_out outbound bandwidth in NBO
560  */
561 static void
562 notify_client_about_neighbour (void *cls,
563                                const struct GNUNET_PeerIdentity *peer,
564                                const struct GNUNET_HELLO_Address *address,
565                                enum GNUNET_TRANSPORT_PeerState state,
566                                struct GNUNET_TIME_Absolute state_timeout,
567                                struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
568                                struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
569 {
570   struct TransportClient *tc = cls;
571   struct ConnectInfoMessage *cim;
572   size_t size = sizeof (struct ConnectInfoMessage);
573   char buf[size] GNUNET_ALIGN;
574
575   if (GNUNET_NO == GST_neighbours_test_connected (peer))
576     return;
577
578   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
579   cim = (struct ConnectInfoMessage *) buf;
580   cim->header.size = htons (size);
581   cim->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
582   cim->id = *peer;
583   cim->quota_in = bandwidth_in;
584   cim->quota_out = bandwidth_out;
585   unicast (tc, &cim->header, GNUNET_NO);
586 }
587
588
589 /**
590  * Initialize a normal client.  We got a start message from this
591  * client, add him to the list of clients for broadcasting of inbound
592  * messages.
593  *
594  * @param cls unused
595  * @param client the client
596  * @param message the start message that was sent
597  */
598 static void
599 clients_handle_start (void *cls,
600                       struct GNUNET_SERVER_Client *client,
601                       const struct GNUNET_MessageHeader *message)
602 {
603   const struct StartMessage *start;
604   struct TransportClient *tc;
605   uint32_t options;
606
607   tc = lookup_client (client);
608
609   GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
610               "Client %p sent START\n", tc);
611   if (tc != NULL)
612   {
613     /* got 'start' twice from the same client, not allowed */
614     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
615                 "TransportClient %p ServerClient %p sent multiple START messages\n",
616                 tc, tc->client);
617     GNUNET_break (0);
618     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
619     return;
620   }
621   start = (const struct StartMessage *) message;
622   options = ntohl (start->options);
623   if ((0 != (1 & options)) &&
624       (0 !=
625        memcmp (&start->self, &GST_my_identity,
626                sizeof (struct GNUNET_PeerIdentity))))
627   {
628     /* client thinks this is a different peer, reject */
629     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
630                 _("Rejecting control connection from peer `%s', which is not me!\n"),
631                 GNUNET_i2s (&start->self));
632     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
633     return;
634   }
635   tc = setup_client (client);
636   tc->send_payload = (0 != (2 & options));
637   unicast (tc, GST_hello_get (), GNUNET_NO);
638   GST_neighbours_iterate (&notify_client_about_neighbour, tc);
639   GNUNET_CONTAINER_DLL_insert (clients_head, clients_tail, tc);
640   GNUNET_SERVER_receive_done (client, GNUNET_OK);
641 }
642
643
644 /**
645  * Client sent us a HELLO.  Process the request.
646  *
647  * @param cls unused
648  * @param client the client
649  * @param message the HELLO message
650  */
651 static void
652 clients_handle_hello (void *cls, struct GNUNET_SERVER_Client *client,
653                       const struct GNUNET_MessageHeader *message)
654 {
655   GST_validation_handle_hello (message);
656   GNUNET_SERVER_receive_done (client, GNUNET_OK);
657 }
658
659
660 /**
661  * Closure for #handle_send_transmit_continuation()
662  */
663 struct SendTransmitContinuationContext
664 {
665   /**
666    * Client that made the request.
667    */
668   struct GNUNET_SERVER_Client *client;
669
670   /**
671    * Peer that was the target.
672    */
673   struct GNUNET_PeerIdentity target;
674 };
675
676
677 /**
678  * Function called after the transmission is done.  Notify the client that it is
679  * OK to send the next message.
680  *
681  * @param cls closure
682  * @param success #GNUNET_OK on success, #GNUNET_NO on failure, #GNUNET_SYSERR if we're not connected
683  * @param bytes_payload bytes payload sent
684  * @param bytes_on_wire bytes sent on wire
685  */
686 static void
687 handle_send_transmit_continuation (void *cls, int success,
688                                    size_t bytes_payload,
689                                    size_t bytes_on_wire)
690 {
691   struct SendTransmitContinuationContext *stcc = cls;
692   struct SendOkMessage send_ok_msg;
693
694   if (GNUNET_OK == success)
695     GST_neighbours_notify_payload_sent (&stcc->target, bytes_payload);
696
697   send_ok_msg.header.size = htons (sizeof (send_ok_msg));
698   send_ok_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK);
699   send_ok_msg.bytes_msg = htonl (bytes_payload);
700   send_ok_msg.bytes_physical = htonl (bytes_on_wire);
701   send_ok_msg.success = htonl (success);
702   send_ok_msg.latency =
703       GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_FOREVER_REL);
704   send_ok_msg.peer = stcc->target;
705   GST_clients_unicast (stcc->client, &send_ok_msg.header, GNUNET_NO);
706   GNUNET_SERVER_client_drop (stcc->client);
707   GNUNET_free (stcc);
708 }
709
710
711 /**
712  * Client asked for transmission to a peer.  Process the request.
713  *
714  * @param cls unused
715  * @param client the client
716  * @param message the send message that was sent
717  */
718 static void
719 clients_handle_send (void *cls,
720                      struct GNUNET_SERVER_Client *client,
721                      const struct GNUNET_MessageHeader *message)
722 {
723   const struct OutboundMessage *obm;
724   const struct GNUNET_MessageHeader *obmm;
725   struct SendTransmitContinuationContext *stcc;
726   uint16_t size;
727   uint16_t msize;
728   struct TransportClient *tc;
729
730   tc = lookup_client (client);
731   if (NULL == tc)
732   {
733     /* client asked for transmission before 'START' */
734     GNUNET_break (0);
735     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
736     return;
737   }
738
739   size = ntohs (message->size);
740   if (size <
741       sizeof (struct OutboundMessage) + sizeof (struct GNUNET_MessageHeader))
742   {
743     GNUNET_break (0);
744     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
745     return;
746   }
747   obm = (const struct OutboundMessage *) message;
748   obmm = (const struct GNUNET_MessageHeader *) &obm[1];
749   msize = size - sizeof (struct OutboundMessage);
750   if (msize < sizeof (struct GNUNET_MessageHeader))
751   {
752     GNUNET_break (0);
753     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
754     return;
755   }
756
757   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
758               "Received `%s' request from client with target `%4s' and first message of type %u and total size %u\n",
759               "SEND",
760               GNUNET_i2s (&obm->peer),
761               ntohs (obmm->type),
762               msize);
763   if (GNUNET_NO == GST_neighbours_test_connected (&obm->peer))
764   {
765     /* not connected, not allowed to send; can happen due to asynchronous operations */
766     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
767                 "Could not send message to peer `%s': not connected\n",
768                 GNUNET_i2s (&obm->peer));
769     GNUNET_STATISTICS_update (GST_stats,
770                               gettext_noop
771                               ("# bytes payload dropped (other peer was not connected)"),
772                               msize, GNUNET_NO);
773     GNUNET_SERVER_receive_done (client, GNUNET_OK);
774     return;
775   }
776   GNUNET_SERVER_receive_done (client, GNUNET_OK);
777   stcc = GNUNET_new (struct SendTransmitContinuationContext);
778   stcc->target = obm->peer;
779   stcc->client = client;
780   GNUNET_SERVER_client_keep (client);
781   GST_manipulation_send (&obm->peer, obmm, msize,
782                        GNUNET_TIME_relative_ntoh (obm->timeout),
783                        &handle_send_transmit_continuation, stcc);
784 }
785
786
787 /**
788  * Try to initiate a connection to the given peer if the blacklist
789  * allowed it.
790  *
791  * @param cls closure (unused, NULL)
792  * @param peer identity of peer that was tested
793  * @param result #GNUNET_OK if the connection is allowed,
794  *               #GNUNET_NO if not
795  */
796 static void
797 try_connect_if_allowed (void *cls,
798                         const struct GNUNET_PeerIdentity *peer,
799                         int result)
800 {
801   if (GNUNET_OK != result)
802   {
803     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
804                 _("Blacklist refuses connection attempt to peer `%s'\n"),
805                 GNUNET_i2s (peer));
806     return;                     /* not allowed */
807   }
808
809   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
810               _("Blacklist allows connection attempt to peer `%s'\n"),
811               GNUNET_i2s (peer));
812
813   GST_neighbours_try_connect (peer);
814 }
815
816
817 /**
818  * Handle request connect message
819  *
820  * @param cls closure (always NULL)
821  * @param client identification of the client
822  * @param message the actual message
823  */
824 static void
825 clients_handle_request_connect (void *cls,
826                                 struct GNUNET_SERVER_Client *client,
827                                 const struct GNUNET_MessageHeader *message)
828 {
829   const struct TransportRequestConnectMessage *trcm =
830       (const struct TransportRequestConnectMessage *) message;
831
832   if (GNUNET_YES == ntohl (trcm->connect))
833   {
834     GNUNET_STATISTICS_update (GST_stats,
835                               gettext_noop
836                               ("# REQUEST CONNECT messages received"), 1,
837                               GNUNET_NO);
838
839     if (0 == memcmp (&trcm->peer, &GST_my_identity,
840                   sizeof (struct GNUNET_PeerIdentity)))
841     {
842       GNUNET_break_op (0);
843       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
844                   "Received a request connect message myself `%s'\n",
845                   GNUNET_i2s (&trcm->peer));
846     }
847     else
848     {
849       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
850                   _("Received a request connect message for peer `%s'\n"),
851                   GNUNET_i2s (&trcm->peer));
852
853       (void) GST_blacklist_test_allowed (&trcm->peer, NULL, &try_connect_if_allowed,
854                                        NULL);
855     }
856   }
857   else if (GNUNET_NO == ntohl (trcm->connect))
858   {
859     GNUNET_STATISTICS_update (GST_stats,
860                               gettext_noop
861                               ("# REQUEST DISCONNECT messages received"), 1,
862                               GNUNET_NO);
863
864     if (0 == memcmp (&trcm->peer, &GST_my_identity,
865                   sizeof (struct GNUNET_PeerIdentity)))
866     {
867       GNUNET_break_op (0);
868       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
869                   "Received a request disconnect message myself `%s'\n",
870                   GNUNET_i2s (&trcm->peer));
871     }
872     else
873     {
874       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
875                   _("Received a request disconnect message for peer `%s'\n"),
876                   GNUNET_i2s (&trcm->peer));
877       (void) GST_neighbours_force_disconnect (&trcm->peer);
878     }
879   }
880   else
881   {
882     GNUNET_break_op (0);
883     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
884     return;
885   }
886   GNUNET_SERVER_receive_done (client, GNUNET_OK);
887 }
888
889
890 /**
891  * Take the given address and append it to the set of results sent back to
892  * the client.  This function may be called serveral times for a single
893  * conversion.   The last invocation will be with a @a address of
894  * NULL and a @a res of #GNUNET_OK.  Thus, to indicate conversion
895  * errors, the callback might be called first with @a address NULL and
896  * @a res being #GNUNET_SYSERR.  In that case, there will still be a
897  * subsequent call later with @a address NULL and @a res #GNUNET_OK.
898  *
899  * @param cls the transmission context used (`struct GNUNET_SERVER_TransmitContext *`)
900  * @param buf text to transmit (contains the human-readable address, or NULL)
901  * @param res #GNUNET_OK if conversion was successful, #GNUNET_SYSERR on error,
902  *            never #GNUNET_NO
903  */
904 static void
905 transmit_address_to_client (void *cls,
906                             const char *buf,
907                             int res)
908 {
909   struct AddressToStringContext *actx = cls;
910   struct AddressToStringResultMessage *atsm;
911   size_t len;
912   size_t slen;
913
914   GNUNET_assert ( (GNUNET_OK == res) ||
915                   (GNUNET_SYSERR == res) );
916   if (NULL == buf)
917   {
918     len = sizeof (struct AddressToStringResultMessage);
919     atsm = GNUNET_malloc (len);
920     atsm->header.size = ntohs (len);
921     atsm->header.type = ntohs (GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_TO_STRING_REPLY);
922     if (GNUNET_OK == res)
923     {
924       /* this was the last call, transmit */
925       atsm->res = htonl (GNUNET_OK);
926       atsm->addr_len = htonl (0);
927       GNUNET_SERVER_transmit_context_append_message (actx->tc,
928                                                      (const struct GNUNET_MessageHeader *) atsm);
929       GNUNET_SERVER_transmit_context_run (actx->tc,
930                                           GNUNET_TIME_UNIT_FOREVER_REL);
931       GNUNET_CONTAINER_DLL_remove (a2s_head,
932                                    a2s_tail,
933                                    actx);
934       GNUNET_free (atsm);
935       GNUNET_free (actx);
936       return;
937     }
938     if (GNUNET_SYSERR == res)
939     {
940       /* address conversion failed, but there will be more callbacks */
941       atsm->res = htonl (GNUNET_SYSERR);
942       atsm->addr_len = htonl (0);
943       GNUNET_SERVER_transmit_context_append_message (actx->tc,
944                                                      (const struct GNUNET_MessageHeader *) atsm);
945       GNUNET_free (atsm);
946       return;
947     }
948   }
949   GNUNET_assert (GNUNET_OK == res);
950   /* succesful conversion, append*/
951   slen = strlen (buf) + 1;
952   len = sizeof (struct AddressToStringResultMessage) + slen;
953   atsm = GNUNET_malloc (len);
954   atsm->header.size = ntohs (len);
955   atsm->header.type = ntohs (GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_TO_STRING_REPLY);
956   atsm->res = htonl (GNUNET_YES);
957   atsm->addr_len = htonl (slen);
958   memcpy (&atsm[1],
959           buf,
960           slen);
961   GNUNET_SERVER_transmit_context_append_message (actx->tc,
962                                                  (const struct GNUNET_MessageHeader *) atsm);
963   GNUNET_free (atsm);
964 }
965
966
967 /**
968  * Client asked to resolve an address.  Process the request.
969  *
970  * @param cls unused
971  * @param client the client
972  * @param message the resolution request
973  */
974 static void
975 clients_handle_address_to_string (void *cls,
976                                   struct GNUNET_SERVER_Client *client,
977                                   const struct GNUNET_MessageHeader *message)
978 {
979   const struct AddressLookupMessage *alum;
980   struct GNUNET_TRANSPORT_PluginFunctions *papi;
981   const char *plugin_name;
982   const char *address;
983   uint32_t address_len;
984   uint16_t size;
985   struct GNUNET_SERVER_TransmitContext *tc;
986   struct AddressToStringContext *actx;
987   struct AddressToStringResultMessage atsm;
988   struct GNUNET_TIME_Relative rtimeout;
989   int32_t numeric;
990
991   size = ntohs (message->size);
992   if (size < sizeof (struct AddressLookupMessage))
993   {
994     GNUNET_break (0);
995     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
996     return;
997   }
998   alum = (const struct AddressLookupMessage *) message;
999   address_len = ntohs (alum->addrlen);
1000   if (size <= sizeof (struct AddressLookupMessage) + address_len)
1001   {
1002     GNUNET_break (0);
1003     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1004     return;
1005   }
1006   address = (const char *) &alum[1];
1007   plugin_name = (const char *) &address[address_len];
1008   if ('\0' != plugin_name[size - sizeof (struct AddressLookupMessage) - address_len - 1])
1009   {
1010     GNUNET_break (0);
1011     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1012     return;
1013   }
1014   rtimeout = GNUNET_TIME_relative_ntoh (alum->timeout);
1015   numeric = ntohs (alum->numeric_only);
1016   tc = GNUNET_SERVER_transmit_context_create (client);
1017   papi = GST_plugins_printer_find (plugin_name);
1018   if (NULL == papi)
1019   {
1020     atsm.header.size = ntohs (sizeof (struct AddressToStringResultMessage));
1021     atsm.header.type = ntohs (GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_TO_STRING_REPLY);
1022     atsm.res = htonl (GNUNET_SYSERR);
1023     atsm.addr_len = htonl (0);
1024     GNUNET_SERVER_transmit_context_append_message (tc,
1025                                                    &atsm.header);
1026     atsm.header.size = ntohs (sizeof (struct AddressToStringResultMessage));
1027     atsm.header.type = ntohs (GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_TO_STRING_REPLY);
1028     atsm.res = htonl (GNUNET_OK);
1029     atsm.addr_len = htonl (0);
1030     GNUNET_SERVER_transmit_context_append_message (tc,
1031                                                    &atsm.header);
1032     GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
1033     return;
1034   }
1035   actx = GNUNET_new (struct AddressToStringContext);
1036   actx->tc = tc;
1037   GNUNET_CONTAINER_DLL_insert (a2s_head, a2s_tail, actx);
1038   GNUNET_SERVER_disable_receive_done_warning (client);
1039   papi->address_pretty_printer (papi->cls,
1040                                 plugin_name,
1041                                 address, address_len,
1042                                 numeric,
1043                                 rtimeout,
1044                                 &transmit_address_to_client,
1045                                 actx);
1046 }
1047
1048
1049 /**
1050  * Compose #PeerIterateResponseMessage using the given peer and address.
1051  *
1052  * @param peer identity of the peer
1053  * @param address the address, NULL on disconnect
1054  * @return composed message
1055  */
1056 static struct PeerIterateResponseMessage *
1057 compose_address_iterate_response_message (const struct GNUNET_PeerIdentity *peer,
1058                                           const struct GNUNET_HELLO_Address *address)
1059 {
1060   struct PeerIterateResponseMessage *msg;
1061   size_t size;
1062   size_t tlen;
1063   size_t alen;
1064   char *addr;
1065
1066   GNUNET_assert (NULL != peer);
1067   if (NULL != address)
1068   {
1069     tlen = strlen (address->transport_name) + 1;
1070     alen = address->address_length;
1071   }
1072   else
1073     tlen = alen = 0;
1074   size = (sizeof (struct PeerIterateResponseMessage) + alen + tlen);
1075   msg = GNUNET_malloc (size);
1076   msg->header.size = htons (size);
1077   msg->header.type =
1078       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_MONITOR_PEER_RESPONSE);
1079   msg->reserved = htonl (0);
1080   msg->peer = *peer;
1081   msg->addrlen = htonl (alen);
1082   msg->pluginlen = htonl (tlen);
1083
1084   if (NULL != address)
1085   {
1086     msg->local_address_info = htonl((uint32_t) address->local_info);
1087     addr = (char *) &msg[1];
1088     memcpy (addr, address->address, alen);
1089     memcpy (&addr[alen], address->transport_name, tlen);
1090   }
1091   return msg;
1092 }
1093
1094
1095 /**
1096  * Compose #PeerIterateResponseMessage using the given peer and address.
1097  *
1098  * @param peer identity of the peer
1099  * @param address the address, NULL on disconnect
1100  * @return composed message
1101  */
1102 static struct ValidationIterateResponseMessage *
1103 compose_validation_iterate_response_message (const struct GNUNET_PeerIdentity *peer,
1104                                              const struct GNUNET_HELLO_Address *address)
1105 {
1106   struct ValidationIterateResponseMessage *msg;
1107   size_t size;
1108   size_t tlen;
1109   size_t alen;
1110   char *addr;
1111
1112   GNUNET_assert (NULL != peer);
1113   if (NULL != address)
1114   {
1115     tlen = strlen (address->transport_name) + 1;
1116     alen = address->address_length;
1117   }
1118   else
1119     tlen = alen = 0;
1120   size = (sizeof (struct ValidationIterateResponseMessage) + alen + tlen);
1121   msg = GNUNET_malloc (size);
1122   msg->header.size = htons (size);
1123   msg->header.type =
1124       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_MONITOR_VALIDATION_RESPONSE);
1125   msg->reserved = htonl (0);
1126   msg->peer = *peer;
1127   msg->addrlen = htonl (alen);
1128   msg->pluginlen = htonl (tlen);
1129
1130   if (NULL != address)
1131   {
1132     msg->local_address_info = htonl((uint32_t) address->local_info);
1133     addr = (char *) &msg[1];
1134     memcpy (addr, address->address, alen);
1135     memcpy (&addr[alen], address->transport_name, tlen);
1136   }
1137   return msg;
1138 }
1139
1140
1141 /**
1142  * Context for #send_validation_information() and
1143  * #send_peer_information().
1144  */
1145 struct IterationContext
1146 {
1147   /**
1148    * Context to use for the transmission.
1149    */
1150   struct GNUNET_SERVER_TransmitContext *tc;
1151
1152   /**
1153    * Which peers do we care about?
1154    */
1155   struct GNUNET_PeerIdentity id;
1156
1157   /**
1158    * #GNUNET_YES if @e id should be ignored because we want all peers.
1159    */
1160   int all;
1161 };
1162
1163
1164 /**
1165  * Output information of validation entries to the given client.
1166  *
1167  * @param cls the `struct IterationContext *`
1168  * @param peer identity of the neighbour
1169  * @param address the address
1170  * @param last_validation point in time when last validation was performed
1171  * @param valid_until point in time how long address is valid
1172  * @param next_validation point in time when next validation will be performed
1173  * @param state state of validation notification
1174  */
1175 static void
1176 send_validation_information (void *cls,
1177                              const struct GNUNET_PeerIdentity *peer,
1178                              const struct GNUNET_HELLO_Address *address,
1179                              struct GNUNET_TIME_Absolute last_validation,
1180                              struct GNUNET_TIME_Absolute valid_until,
1181                              struct GNUNET_TIME_Absolute next_validation,
1182                              enum GNUNET_TRANSPORT_ValidationState state)
1183 {
1184   struct IterationContext *pc = cls;
1185   struct ValidationIterateResponseMessage *msg;
1186
1187   if ( (GNUNET_YES == pc->all) ||
1188        (0 == memcmp (peer, &pc->id, sizeof (pc->id))) )
1189   {
1190     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1191         "Sending information about for validation entry for peer `%s' using address `%s'\n",
1192         GNUNET_i2s(peer), (address != NULL) ? GST_plugins_a2s (address) : "<none>");
1193     msg = compose_validation_iterate_response_message (peer, address);
1194     msg->last_validation = GNUNET_TIME_absolute_hton(last_validation);
1195     msg->valid_until = GNUNET_TIME_absolute_hton(valid_until);
1196     msg->next_validation = GNUNET_TIME_absolute_hton(next_validation);
1197     msg->state = htonl ((uint32_t) state);
1198     GNUNET_SERVER_transmit_context_append_message (pc->tc, &msg->header);
1199     GNUNET_free (msg);
1200   }
1201 }
1202
1203
1204 /**
1205  * Output information of neighbours to the given client.
1206  *
1207  * @param cls the `struct PeerIterationContext *`
1208  * @param peer identity of the neighbour
1209  * @param address the address
1210  * @param state current state this peer is in
1211  * @param state_timeout timeout for the current state of the peer
1212  * @param bandwidth_in inbound quota in NBO
1213  * @param bandwidth_out outbound quota in NBO
1214  */
1215 static void
1216 send_peer_information (void *cls,
1217                        const struct GNUNET_PeerIdentity *peer,
1218                        const struct GNUNET_HELLO_Address *address,
1219                        enum GNUNET_TRANSPORT_PeerState state,
1220                        struct GNUNET_TIME_Absolute state_timeout,
1221                        struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1222                        struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
1223 {
1224   struct IterationContext *pc = cls;
1225   struct PeerIterateResponseMessage *msg;
1226
1227   if ( (GNUNET_YES == pc->all) ||
1228        (0 == memcmp (peer, &pc->id, sizeof (pc->id))) )
1229   {
1230     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1231         "Sending information about `%s' using address `%s' in state `%s'\n",
1232         GNUNET_i2s(peer),
1233         (address != NULL) ? GST_plugins_a2s (address) : "<none>",
1234         GNUNET_TRANSPORT_ps2s (state));
1235     msg = compose_address_iterate_response_message (peer, address);
1236     msg->state = htonl (state);
1237     msg->state_timeout = GNUNET_TIME_absolute_hton(state_timeout);
1238     GNUNET_SERVER_transmit_context_append_message (pc->tc, &msg->header);
1239     GNUNET_free (msg);
1240   }
1241 }
1242
1243
1244 /**
1245  * Client asked to obtain information about a specific or all peers
1246  * Process the request.
1247  *
1248  * @param cls unused
1249  * @param client the client
1250  * @param message the peer address information request
1251  */
1252 static void
1253 clients_handle_monitor_peers (void *cls,
1254                               struct GNUNET_SERVER_Client *client,
1255                               const struct GNUNET_MessageHeader *message)
1256 {
1257   static struct GNUNET_PeerIdentity all_zeros;
1258   struct GNUNET_SERVER_TransmitContext *tc;
1259   const struct PeerMonitorMessage *msg;
1260   struct IterationContext pc;
1261
1262   msg = (const struct PeerMonitorMessage *) message;
1263   if ( (GNUNET_YES != ntohl (msg->one_shot)) &&
1264        (NULL != lookup_monitoring_client (peer_monitoring_clients_head, client)) )
1265   {
1266     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1267                 "ServerClient %p tried to start monitoring twice\n",
1268                 client);
1269     GNUNET_break (0);
1270     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1271     return;
1272   }
1273   GNUNET_SERVER_disable_receive_done_warning (client);
1274   GNUNET_SERVER_client_mark_monitor (client);
1275   pc.tc = tc = GNUNET_SERVER_transmit_context_create (client);
1276
1277   /* Send initial list */
1278   if (0 == memcmp (&msg->peer, &all_zeros, sizeof (struct GNUNET_PeerIdentity)))
1279   {
1280     /* iterate over all neighbours */
1281     pc.all = GNUNET_YES;
1282     pc.id = msg->peer;
1283   }
1284   else
1285   {
1286     /* just return one neighbour */
1287     pc.all = GNUNET_NO;
1288     pc.id = msg->peer;
1289   }
1290   GST_neighbours_iterate (&send_peer_information, &pc);
1291
1292   if (GNUNET_YES != ntohl (msg->one_shot))
1293   {
1294     setup_peer_monitoring_client (client, &msg->peer);
1295   }
1296   else
1297   {
1298     GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
1299         GNUNET_MESSAGE_TYPE_TRANSPORT_MONITOR_PEER_RESPONSE);
1300   }
1301
1302   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
1303 }
1304
1305
1306 /**
1307  * Client asked to obtain information about a specific or all validation
1308  * processes
1309  *
1310  * @param cls unused
1311  * @param client the client
1312  * @param message the peer address information request
1313  */
1314 static void
1315 clients_handle_monitor_validation (void *cls,
1316                                    struct GNUNET_SERVER_Client *client,
1317                                    const struct GNUNET_MessageHeader *message)
1318 {
1319   static struct GNUNET_PeerIdentity all_zeros;
1320   struct GNUNET_SERVER_TransmitContext *tc;
1321   struct PeerMonitorMessage *msg;
1322   struct IterationContext pc;
1323
1324   if (ntohs (message->type) != GNUNET_MESSAGE_TYPE_TRANSPORT_MONITOR_VALIDATION_REQUEST)
1325   {
1326     GNUNET_break (0);
1327     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1328     return;
1329   }
1330   if (ntohs (message->size) != sizeof (struct ValidationMonitorMessage))
1331   {
1332     GNUNET_break (0);
1333     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1334     return;
1335   }
1336   msg = (struct PeerMonitorMessage *) message;
1337   if ( (GNUNET_YES != ntohl (msg->one_shot)) &&
1338        (NULL != lookup_monitoring_client (val_monitoring_clients_head, client)) )
1339   {
1340     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1341                 "ServerClient %p tried to start monitoring twice\n",
1342                 client);
1343     GNUNET_break (0);
1344     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1345     return;
1346   }
1347   GNUNET_SERVER_disable_receive_done_warning (client);
1348   GNUNET_SERVER_client_mark_monitor (client);
1349   pc.tc = tc = GNUNET_SERVER_transmit_context_create (client);
1350
1351   /* Send initial list */
1352   if (0 == memcmp (&msg->peer, &all_zeros, sizeof (struct GNUNET_PeerIdentity)))
1353   {
1354     /* iterate over all neighbours */
1355     pc.all = GNUNET_YES;
1356     pc.id = msg->peer;
1357   }
1358   else
1359   {
1360     /* just return one neighbour */
1361     pc.all = GNUNET_NO;
1362     pc.id = msg->peer;
1363   }
1364
1365   GST_validation_iterate (&send_validation_information, &pc);
1366
1367   if (GNUNET_YES != ntohl (msg->one_shot))
1368   {
1369     setup_val_monitoring_client (client, &msg->peer);
1370   }
1371   else
1372   {
1373     GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
1374         GNUNET_MESSAGE_TYPE_TRANSPORT_MONITOR_VALIDATION_RESPONSE);
1375   }
1376   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
1377 }
1378
1379
1380 /**
1381  * Function called by the plugin with information about the
1382  * current sessions managed by the plugin (for monitoring).
1383  *
1384  * @param cls closure
1385  * @param session session handle this information is about,
1386  *        NULL to indicate that we are "in sync" (initial
1387  *        iteration complete)
1388  * @param info information about the state of the session,
1389  *        NULL if @a session is also NULL and we are
1390  *        merely signalling that the initial iteration is over
1391  */
1392 static void
1393 plugin_session_info_cb (void *cls,
1394                         struct Session *session,
1395                         const struct GNUNET_TRANSPORT_SessionInfo *info)
1396 {
1397   struct TransportPluginMonitorMessage *msg;
1398   struct GNUNET_MessageHeader sync;
1399   size_t size;
1400   size_t slen;
1401   uint16_t alen;
1402   char *name;
1403   char *addr;
1404
1405   if (0 == GNUNET_SERVER_notification_context_get_size (plugin_nc))
1406   {
1407     fprintf (stderr, "UNSUB!\n");
1408     GST_plugins_monitor_subscribe (NULL, NULL);
1409     return;
1410   }
1411   if ( (NULL == info) &&
1412        (NULL == session) )
1413   {
1414     /* end of initial iteration */
1415     if (NULL != sync_client)
1416     {
1417       sync.size = htons (sizeof (struct GNUNET_MessageHeader));
1418       sync.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_MONITOR_PLUGIN_SYNC);
1419       GNUNET_SERVER_notification_context_unicast (plugin_nc,
1420                                                   sync_client,
1421                                                   &sync,
1422                                                   GNUNET_NO);
1423       sync_client = NULL;
1424     }
1425     return;
1426   }
1427   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1428               "Plugin event for peer %s on transport %s\n",
1429               GNUNET_i2s (&info->address->peer),
1430               info->address->transport_name);
1431   slen = strlen (info->address->transport_name) + 1;
1432   alen = info->address->address_length;
1433   size = sizeof (struct TransportPluginMonitorMessage) + slen + alen;
1434   if (size > UINT16_MAX)
1435   {
1436     GNUNET_break (0);
1437     return;
1438   }
1439   msg = GNUNET_malloc (size);
1440   msg->header.size = htons (size);
1441   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_MONITOR_PLUGIN_EVENT);
1442   msg->session_state = htons ((uint16_t) info->state);
1443   msg->is_inbound = htons ((int16_t) info->is_inbound);
1444   msg->msgs_pending = htonl (info->num_msg_pending);
1445   msg->bytes_pending = htonl (info->num_bytes_pending);
1446   msg->timeout = GNUNET_TIME_absolute_hton (info->session_timeout);
1447   msg->delay = GNUNET_TIME_absolute_hton (info->receive_delay);
1448   msg->peer = info->address->peer;
1449   msg->session_id = (uint64_t) (intptr_t) session;
1450   msg->plugin_name_len = htons (slen);
1451   msg->plugin_address_len = htons (alen);
1452   name = (char *) &msg[1];
1453   memcpy (name, info->address->transport_name, slen);
1454   addr = &name[slen + 1];
1455   memcpy (addr, info->address->address, alen);
1456   if (NULL != sync_client)
1457     GNUNET_SERVER_notification_context_unicast (plugin_nc,
1458                                                 sync_client,
1459                                                 &msg->header,
1460                                                 GNUNET_NO);
1461   else
1462     GNUNET_SERVER_notification_context_broadcast (plugin_nc,
1463                                                   &msg->header,
1464                                                   GNUNET_NO);
1465   GNUNET_free (msg);
1466 }
1467
1468
1469 /**
1470  * Client asked to obtain information about all plugin connections.
1471  *
1472  * @param cls unused
1473  * @param client the client
1474  * @param message the peer address information request
1475  */
1476 static void
1477 clients_handle_monitor_plugins (void *cls,
1478                                 struct GNUNET_SERVER_Client *client,
1479                                 const struct GNUNET_MessageHeader *message)
1480 {
1481   GNUNET_SERVER_client_mark_monitor (client);
1482   GNUNET_SERVER_disable_receive_done_warning (client);
1483   GNUNET_SERVER_notification_context_add (plugin_nc, client);
1484   sync_client = client;
1485   GST_plugins_monitor_subscribe (&plugin_session_info_cb, NULL);
1486 }
1487
1488
1489 /**
1490  * Start handling requests from clients.
1491  *
1492  * @param server server used to accept clients from.
1493  */
1494 void
1495 GST_clients_start (struct GNUNET_SERVER_Handle *server)
1496 {
1497   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1498     {&clients_handle_start, NULL,
1499      GNUNET_MESSAGE_TYPE_TRANSPORT_START, sizeof (struct StartMessage)},
1500     {&clients_handle_hello, NULL,
1501      GNUNET_MESSAGE_TYPE_HELLO, 0},
1502     {&clients_handle_send, NULL,
1503      GNUNET_MESSAGE_TYPE_TRANSPORT_SEND, 0},
1504     {&clients_handle_request_connect, NULL,
1505      GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT,
1506      sizeof (struct TransportRequestConnectMessage)},
1507     {&clients_handle_address_to_string, NULL,
1508      GNUNET_MESSAGE_TYPE_TRANSPORT_ADDRESS_TO_STRING, 0},
1509     {&clients_handle_monitor_peers, NULL,
1510      GNUNET_MESSAGE_TYPE_TRANSPORT_MONITOR_PEER_REQUEST,
1511      sizeof (struct PeerMonitorMessage)},
1512     {&clients_handle_monitor_validation, NULL,
1513      GNUNET_MESSAGE_TYPE_TRANSPORT_MONITOR_VALIDATION_REQUEST,
1514      sizeof (struct ValidationMonitorMessage)},
1515     {&GST_blacklist_handle_init, NULL,
1516      GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_INIT,
1517      sizeof (struct GNUNET_MessageHeader)},
1518     {&GST_blacklist_handle_reply, NULL,
1519      GNUNET_MESSAGE_TYPE_TRANSPORT_BLACKLIST_REPLY,
1520      sizeof (struct BlacklistMessage)},
1521     {&GST_manipulation_set_metric, NULL,
1522      GNUNET_MESSAGE_TYPE_TRANSPORT_TRAFFIC_METRIC, 0},
1523     {&clients_handle_monitor_plugins, NULL,
1524      GNUNET_MESSAGE_TYPE_TRANSPORT_MONITOR_PLUGIN_START,
1525      sizeof (struct GNUNET_MessageHeader) },
1526     {NULL, NULL, 0, 0}
1527   };
1528   peer_nc = GNUNET_SERVER_notification_context_create (server, 0);
1529   val_nc = GNUNET_SERVER_notification_context_create (server, 0);
1530   plugin_nc = GNUNET_SERVER_notification_context_create (server, 0);
1531   GNUNET_SERVER_add_handlers (server, handlers);
1532   GNUNET_SERVER_disconnect_notify (server,
1533                                    &client_disconnect_notification,
1534                                    NULL);
1535 }
1536
1537
1538 /**
1539  * Stop processing clients.
1540  */
1541 void
1542 GST_clients_stop ()
1543 {
1544   struct AddressToStringContext *cur;
1545
1546   while (NULL != (cur = a2s_head))
1547   {
1548     GNUNET_SERVER_transmit_context_destroy (cur->tc, GNUNET_NO);
1549     GNUNET_CONTAINER_DLL_remove (a2s_head, a2s_tail, cur);
1550     GNUNET_free (cur);
1551   }
1552   if (NULL != peer_nc)
1553   {
1554     GNUNET_SERVER_notification_context_destroy (peer_nc);
1555     peer_nc = NULL;
1556   }
1557   if (NULL != val_nc)
1558   {
1559     GNUNET_SERVER_notification_context_destroy (val_nc);
1560     val_nc = NULL;
1561   }
1562   if (NULL != plugin_nc)
1563   {
1564     GNUNET_SERVER_notification_context_destroy (plugin_nc);
1565     plugin_nc = NULL;
1566   }
1567 }
1568
1569
1570 /**
1571  * Broadcast the given message to all of our clients.
1572  *
1573  * @param msg message to broadcast
1574  * @param may_drop #GNUNET_YES if the message can be dropped / is payload
1575  */
1576 void
1577 GST_clients_broadcast (const struct GNUNET_MessageHeader *msg,
1578                        int may_drop)
1579 {
1580   struct TransportClient *tc;
1581
1582   for (tc = clients_head; NULL != tc; tc = tc->next)
1583   {
1584     if ((GNUNET_YES == may_drop) && (GNUNET_YES != tc->send_payload))
1585       continue;                 /* skip, this client does not care about payload */
1586     unicast (tc, msg, may_drop);
1587   }
1588 }
1589
1590
1591 /**
1592  * Send the given message to a particular client
1593  *
1594  * @param client target of the message
1595  * @param msg message to transmit
1596  * @param may_drop #GNUNET_YES if the message can be dropped
1597  */
1598 void
1599 GST_clients_unicast (struct GNUNET_SERVER_Client *client,
1600                      const struct GNUNET_MessageHeader *msg,
1601                      int may_drop)
1602 {
1603   struct TransportClient *tc;
1604
1605   tc = lookup_client (client);
1606   if (NULL == tc)
1607     return;                     /* client got disconnected in the meantime, drop message */
1608   unicast (tc, msg, may_drop);
1609 }
1610
1611
1612 /**
1613  * Broadcast the new active address to all clients monitoring the peer.
1614  *
1615  * @param peer peer this update is about (never NULL)
1616  * @param address address, NULL on disconnect
1617  * @param state the current state of the peer
1618  * @param state_timeout the time out for the state
1619  */
1620 void
1621 GST_clients_broadcast_peer_notification (const struct GNUNET_PeerIdentity *peer,
1622                                          const struct GNUNET_HELLO_Address *address,
1623                                          enum GNUNET_TRANSPORT_PeerState state,
1624                                          struct GNUNET_TIME_Absolute state_timeout)
1625 {
1626   static struct GNUNET_PeerIdentity all_zeros;
1627   struct PeerIterateResponseMessage *msg;
1628   struct MonitoringClient *mc;
1629
1630   msg = compose_address_iterate_response_message (peer, address);
1631   msg->state = htonl (state);
1632   msg->state_timeout = GNUNET_TIME_absolute_hton (state_timeout);
1633   mc = peer_monitoring_clients_head;
1634   while (mc != NULL)
1635   {
1636     if ((0 == memcmp (&mc->peer, &all_zeros,
1637                       sizeof (struct GNUNET_PeerIdentity))) ||
1638         (0 == memcmp (&mc->peer, peer,
1639                       sizeof (struct GNUNET_PeerIdentity))))
1640     {
1641       GNUNET_SERVER_notification_context_unicast (peer_nc, mc->client,
1642                                                   &msg->header, GNUNET_NO);
1643     }
1644
1645     mc = mc->next;
1646   }
1647   GNUNET_free (msg);
1648 }
1649
1650 /**
1651  * Broadcast the new validation changes to all clients monitoring the peer.
1652  *
1653  * @param peer peer this update is about (never NULL)
1654  * @param address address, NULL on disconnect
1655  * @param last_validation point in time when last validation was performed
1656  * @param valid_until point in time how long address is valid
1657  * @param next_validation point in time when next validation will be performed
1658  * @param state state of validation notification
1659  */
1660 void
1661 GST_clients_broadcast_validation_notification (const struct GNUNET_PeerIdentity *peer,
1662                                                const struct GNUNET_HELLO_Address *address,
1663                                                struct GNUNET_TIME_Absolute last_validation,
1664                                                struct GNUNET_TIME_Absolute valid_until,
1665                                                struct GNUNET_TIME_Absolute next_validation,
1666                                                enum GNUNET_TRANSPORT_ValidationState state)
1667 {
1668   struct ValidationIterateResponseMessage *msg;
1669   struct MonitoringClient *mc;
1670   static struct GNUNET_PeerIdentity all_zeros;
1671
1672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1673               "Sending information about for validation entry for peer `%s' using address `%s'\n",
1674               GNUNET_i2s(peer), (address != NULL) ? GST_plugins_a2s (address) : "<none>");
1675
1676   msg = compose_validation_iterate_response_message (peer, address);
1677   msg->last_validation = GNUNET_TIME_absolute_hton(last_validation);
1678   msg->valid_until = GNUNET_TIME_absolute_hton(valid_until);
1679   msg->next_validation = GNUNET_TIME_absolute_hton(next_validation);
1680   msg->state = htonl ((uint32_t) state);
1681   mc = val_monitoring_clients_head;
1682   while (mc != NULL)
1683   {
1684     if ((0 == memcmp (&mc->peer, &all_zeros,
1685                       sizeof (struct GNUNET_PeerIdentity))) ||
1686         (0 == memcmp (&mc->peer, peer,
1687                       sizeof (struct GNUNET_PeerIdentity))))
1688     {
1689       GNUNET_SERVER_notification_context_unicast (val_nc, mc->client,
1690                                                   &msg->header, GNUNET_NO);
1691
1692     }
1693     mc = mc->next;
1694   }
1695   GNUNET_free (msg);
1696 }
1697
1698
1699 /* end of file gnunet-service-transport_clients.c */