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