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