2 This file is part of GNUnet
3 Copyright (C) 2002--2015 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
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 Affero General Public License for more details.
16 * @file transport/plugin_transport_tcp.c
17 * @brief Implementation of the TCP transport service
18 * @author Christian Grothoff
21 #include "gnunet_hello_lib.h"
22 #include "gnunet_constants.h"
23 #include "gnunet_util_lib.h"
24 #include "gnunet_nat_service.h"
25 #include "gnunet_protocols.h"
26 #include "gnunet_resolver_service.h"
27 #include "gnunet_signatures.h"
28 #include "gnunet_statistics_service.h"
29 #include "gnunet_transport_service.h"
30 #include "gnunet_transport_plugin.h"
31 #include "transport.h"
33 #define LOG(kind,...) GNUNET_log_from (kind, "transport-tcp",__VA_ARGS__)
35 #define PLUGIN_NAME "tcp"
38 * How long until we give up on establishing an NAT connection?
41 #define NAT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
44 * Opaque handle that can be used to cancel
45 * a transmit-ready notification.
47 struct GNUNET_CONNECTION_TransmitHandle;
50 * @brief handle for a server
52 struct GNUNET_SERVER_Handle;
55 * @brief opaque handle for a client of the server
57 struct GNUNET_SERVER_Client;
60 * @brief opaque handle server returns for aborting transmission to a client.
62 struct GNUNET_SERVER_TransmitHandle;
65 * @brief handle for a network connection
67 struct GNUNET_CONNECTION_Handle;
70 * @brief handle for a network service
72 struct LEGACY_SERVICE_Context;
76 * Stops a service that was started with #GNUNET_SERVICE_start().
78 * @param srv service to stop
81 LEGACY_SERVICE_stop (struct LEGACY_SERVICE_Context *srv);
86 * Function called to notify a client about the connection begin ready
87 * to queue more data. @a buf will be NULL and @a size zero if the
88 * connection was closed for writing in the meantime.
91 * @param size number of bytes available in @a buf
92 * @param buf where the callee should write the message
93 * @return number of bytes written to @a buf
96 (*GNUNET_CONNECTION_TransmitReadyNotify) (void *cls,
101 * Credentials for UNIX domain sockets.
103 struct GNUNET_CONNECTION_Credentials
106 * UID of the other end of the connection.
111 * GID of the other end of the connection.
118 * Functions with this signature are called whenever a client
119 * is disconnected on the network level.
122 * @param client identification of the client; NULL
123 * for the last call when the server is destroyed
126 (*GNUNET_SERVER_DisconnectCallback) (void *cls,
127 struct GNUNET_SERVER_Client *client);
131 * Functions with this signature are called whenever a client
132 * is connected on the network level.
135 * @param client identification of the client
138 (*GNUNET_SERVER_ConnectCallback) (void *cls,
139 struct GNUNET_SERVER_Client *client);
145 * Function to call for access control checks.
148 * @param ucred credentials, if available, otherwise NULL
149 * @param addr address
150 * @param addrlen length of address
151 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
152 * for unknown address family (will be denied).
155 (*GNUNET_CONNECTION_AccessCheck) (void *cls,
157 GNUNET_CONNECTION_Credentials *
159 const struct sockaddr * addr,
163 * Callback function for data received from the network. Note that
164 * both "available" and "err" would be 0 if the read simply timed out.
167 * @param buf pointer to received data
168 * @param available number of bytes availabe in "buf",
169 * possibly 0 (on errors)
170 * @param addr address of the sender
171 * @param addrlen size of addr
172 * @param errCode value of errno (on errors receiving)
175 (*GNUNET_CONNECTION_Receiver) (void *cls, const void *buf,
177 const struct sockaddr * addr,
178 socklen_t addrlen, int errCode);
183 * Close the connection and free associated resources. There must
184 * not be any pending requests for reading or writing to the
185 * connection at this time.
187 * @param connection connection to destroy
190 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection);
194 * Signature of a function to create a custom tokenizer.
196 * @param cls closure from #GNUNET_SERVER_set_callbacks
197 * @param client handle to client the tokenzier will be used for
198 * @return handle to custom tokenizer ('mst')
201 (*GNUNET_SERVER_MstCreateCallback) (void *cls,
202 struct GNUNET_SERVER_Client *client);
206 * Signature of a function to destroy a custom tokenizer.
208 * @param cls closure from #GNUNET_SERVER_set_callbacks
209 * @param mst custom tokenizer handle
212 (*GNUNET_SERVER_MstDestroyCallback) (void *cls,
216 * Signature of a function to receive data for a custom tokenizer.
218 * @param cls closure from #GNUNET_SERVER_set_callbacks
219 * @param mst custom tokenizer handle
220 * @param client_identity ID of client for which this is a buffer,
221 * can be NULL (will be passed back to 'cb')
222 * @param buf input data to add
223 * @param size number of bytes in @a buf
224 * @param purge should any excess bytes in the buffer be discarded
225 * (i.e. for packet-based services like UDP)
226 * @param one_shot only call callback once, keep rest of message in buffer
227 * @return #GNUNET_OK if we are done processing (need more data)
228 * #GNUNET_NO if one_shot was set and we have another message ready
229 * #GNUNET_SYSERR if the data stream is corrupt
232 (*GNUNET_SERVER_MstReceiveCallback) (void *cls, void *mst,
233 struct GNUNET_SERVER_Client *client,
239 * Functions with this signature are called whenever a message is
243 * @param client identification of the client
244 * @param message the actual message
247 (*GNUNET_SERVER_MessageCallback) (void *cls,
248 struct GNUNET_SERVER_Client *client,
249 const struct GNUNET_MessageHeader *message);
252 * Message handler. Each struct specifies how to handle on particular
253 * type of message received.
255 struct GNUNET_SERVER_MessageHandler
258 * Function to call for messages of "type".
260 GNUNET_SERVER_MessageCallback callback;
263 * Closure argument for @e callback.
268 * Type of the message this handler covers.
273 * Expected size of messages of this type. Use 0 for
274 * variable-size. If non-zero, messages of the given
275 * type will be discarded (and the connection closed)
276 * if they do not have the right size.
278 uint16_t expected_size;
284 * Options for the service (bitmask).
286 enum LEGACY_SERVICE_Options
289 * Use defaults. Terminates all client connections and the listen
290 * sockets immediately upon receiving the shutdown signal.
292 LEGACY_SERVICE_OPTION_NONE = 0,
295 * Do not trigger server shutdown on signal at all; instead, allow
296 * for the user to terminate the server explicitly when needed
297 * by calling #LEGACY_SERVICE_shutdown().
299 LEGACY_SERVICE_OPTION_MANUAL_SHUTDOWN = 1,
302 * Trigger a SOFT server shutdown on signals, allowing active
303 * non-monitor clients to complete their transactions.
305 LEGACY_SERVICE_OPTION_SOFT_SHUTDOWN = 2
311 * Ask the server to disconnect from the given client. This is the
312 * same as passing #GNUNET_SYSERR to #GNUNET_SERVER_receive_done,
313 * except that it allows dropping of a client even when not handling a
314 * message from that client.
316 * @param client the client to disconnect from
319 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client);
322 * Return user context associated with the given client.
323 * Note: you should probably use the macro (call without the underscore).
325 * @param client client to query
326 * @param size number of bytes in user context struct (for verification only)
327 * @return pointer to user context
330 GNUNET_SERVER_client_get_user_context_ (struct GNUNET_SERVER_Client *client,
335 * Functions with this signature are called whenever a
336 * complete message is received by the tokenizer.
338 * Do not call #GNUNET_SERVER_mst_destroy from within
339 * the scope of this callback.
342 * @param client identification of the client
343 * @param message the actual message
344 * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
347 (*GNUNET_SERVER_MessageTokenizerCallback) (void *cls,
349 const struct GNUNET_MessageHeader *message);
353 * Create a message stream tokenizer.
355 * @param cb function to call on completed messages
356 * @param cb_cls closure for @a cb
357 * @return handle to tokenizer
359 struct GNUNET_SERVER_MessageStreamTokenizer *
360 GNUNET_SERVER_mst_create (GNUNET_SERVER_MessageTokenizerCallback cb,
364 * Add incoming data to the receive buffer and call the
365 * callback for all complete messages.
367 * @param mst tokenizer to use
368 * @param client_identity ID of client for which this is a buffer,
369 * can be NULL (will be passed back to 'cb')
370 * @param buf input data to add
371 * @param size number of bytes in @a buf
372 * @param purge should any excess bytes in the buffer be discarded
373 * (i.e. for packet-based services like UDP)
374 * @param one_shot only call callback once, keep rest of message in buffer
375 * @return #GNUNET_OK if we are done processing (need more data)
376 * #GNUNET_NO if one_shot was set and we have another message ready
377 * #GNUNET_SYSERR if the data stream is corrupt
380 GNUNET_SERVER_mst_receive (struct GNUNET_SERVER_MessageStreamTokenizer *mst,
381 void *client_identity,
382 const char *buf, size_t size,
383 int purge, int one_shot);
388 * Destroys a tokenizer.
390 * @param mst tokenizer to destroy
393 GNUNET_SERVER_mst_destroy (struct GNUNET_SERVER_MessageStreamTokenizer *mst);
397 * Set user context to be associated with the given client.
398 * Note: you should probably use the macro (call without the underscore).
400 * @param client client to query
401 * @param ptr pointer to user context
402 * @param size number of bytes in user context struct (for verification only)
405 GNUNET_SERVER_client_set_user_context_ (struct GNUNET_SERVER_Client *client,
409 * Return user context associated with the given client.
411 * @param client client to query
412 * @param type expected return type (i.e. 'struct Foo')
413 * @return pointer to user context of type 'type *'.
415 #define GNUNET_SERVER_client_get_user_context(client,type) \
416 (type *) GNUNET_SERVER_client_get_user_context_ (client, sizeof (type))
419 * Set user context to be associated with the given client.
421 * @param client client to query
422 * @param value pointer to user context
424 #define GNUNET_SERVER_client_set_user_context(client,value) \
425 GNUNET_SERVER_client_set_user_context_ (client, value, sizeof (*value))
430 * Notify us when the server has enough space to transmit
431 * a message of the given size to the given client.
433 * @param client client to transmit message to
434 * @param size requested amount of buffer space
435 * @param timeout after how long should we give up (and call
436 * notify with buf NULL and size 0)?
437 * @param callback function to call when space is available
438 * @param callback_cls closure for @a callback
439 * @return non-NULL if the notify callback was queued; can be used
440 * to cancel the request using
441 * #GNUNET_SERVER_notify_transmit_ready_cancel.
442 * NULL if we are already going to notify someone else (busy)
444 struct GNUNET_SERVER_TransmitHandle *
445 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
447 struct GNUNET_TIME_Relative timeout,
448 GNUNET_CONNECTION_TransmitReadyNotify callback,
452 * Abort transmission request.
454 * @param th request to abort
457 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th);
463 * Notify the server that the given client handle should
464 * be kept (keeps the connection up if possible, increments
465 * the internal reference counter).
467 * @param client the client to keep
470 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client);
474 * Notify the server that the given client handle is no
475 * longer required. Decrements the reference counter. If
476 * that counter reaches zero an inactive connection maybe
479 * @param client the client to drop
482 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client);
486 * Function called by the service's run
487 * method to run service-specific setup code.
490 * @param server the initialized server
491 * @param cfg configuration to use
494 (*LEGACY_SERVICE_Main) (void *cls,
495 struct GNUNET_SERVER_Handle *server,
496 const struct GNUNET_CONFIGURATION_Handle *cfg);
501 * Suspend accepting connections from the listen socket temporarily.
502 * Resume activity using #GNUNET_SERVER_resume.
504 * @param server server to stop accepting connections.
507 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server);
510 * Notify us when the server has enough space to transmit
511 * a message of the given size to the given client.
513 * @param client client to transmit message to
514 * @param size requested amount of buffer space
515 * @param timeout after how long should we give up (and call
516 * notify with buf NULL and size 0)?
517 * @param callback function to call when space is available
518 * @param callback_cls closure for @a callback
519 * @return non-NULL if the notify callback was queued; can be used
520 * to cancel the request using
521 * #GNUNET_SERVER_notify_transmit_ready_cancel.
522 * NULL if we are already going to notify someone else (busy)
524 struct GNUNET_SERVER_TransmitHandle *
525 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
527 struct GNUNET_TIME_Relative timeout,
528 GNUNET_CONNECTION_TransmitReadyNotify callback,
533 * Add a TCP socket-based connection to the set of handles managed by
534 * this server. Use this function for outgoing (P2P) connections that
535 * we initiated (and where this server should process incoming
538 * @param server the server to use
539 * @param connection the connection to manage (client must
540 * stop using this connection from now on)
541 * @return the client handle
543 struct GNUNET_SERVER_Client *
544 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
545 struct GNUNET_CONNECTION_Handle *connection);
549 * Resume accepting connections from the listen socket.
551 * @param server server to resume accepting connections.
554 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server);
557 * Free resources held by this server.
559 * @param server server to destroy
562 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server);
567 #include "tcp_connection_legacy.c"
568 #include "tcp_server_mst_legacy.c"
569 #include "tcp_server_legacy.c"
570 #include "tcp_service_legacy.c"
572 GNUNET_NETWORK_STRUCT_BEGIN
575 * Initial handshake message for a session.
577 struct WelcomeMessage
580 * Type is #GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
582 struct GNUNET_MessageHeader header;
585 * Identity of the node connecting (TCP client)
587 struct GNUNET_PeerIdentity clientIdentity;
592 * Basically a WELCOME message, but with the purpose
593 * of giving the waiting peer a client handle to use
595 struct TCP_NAT_ProbeMessage
598 * Type is #GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
600 struct GNUNET_MessageHeader header;
603 * Identity of the sender of the message.
605 struct GNUNET_PeerIdentity clientIdentity;
608 GNUNET_NETWORK_STRUCT_END
611 * Context for sending a NAT probe via TCP.
613 struct TCPProbeContext
617 * Active probes are kept in a DLL.
619 struct TCPProbeContext *next;
622 * Active probes are kept in a DLL.
624 struct TCPProbeContext *prev;
629 struct GNUNET_CONNECTION_Handle *sock;
632 * Message to be sent.
634 struct TCP_NAT_ProbeMessage message;
637 * Handle to the transmission.
639 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
642 * Transport plugin handle.
644 struct Plugin *plugin;
648 * Bits in the `options` field of TCP addresses.
650 enum TcpAddressOptions
656 TCP_OPTIONS_NONE = 0,
659 * See #HTTP_OPTIONS_VERIFY_CERTIFICATE.
661 TCP_OPTIONS_RESERVED = 1,
664 * Enable TCP Stealth-style port knocking.
666 TCP_OPTIONS_TCP_STEALTH = 2
669 GNUNET_NETWORK_STRUCT_BEGIN
672 * Network format for IPv4 addresses.
674 struct IPv4TcpAddress
677 * Optional options and flags for this address,
678 * see `enum TcpAddressOptions`
680 uint32_t options GNUNET_PACKED;
683 * IPv4 address, in network byte order.
685 uint32_t ipv4_addr GNUNET_PACKED;
688 * Port number, in network byte order.
690 uint16_t t4_port GNUNET_PACKED;
695 * Network format for IPv6 addresses.
697 struct IPv6TcpAddress
700 * Optional flags for this address
701 * see `enum TcpAddressOptions`
703 uint32_t options GNUNET_PACKED;
708 struct in6_addr ipv6_addr GNUNET_PACKED;
711 * Port number, in network byte order.
713 uint16_t t6_port GNUNET_PACKED;
716 GNUNET_NETWORK_STRUCT_END
719 * Encapsulation of all of the state of the plugin.
724 * Information kept for each message that is yet to
727 struct PendingMessage
731 * This is a doubly-linked list.
733 struct PendingMessage *next;
736 * This is a doubly-linked list.
738 struct PendingMessage *prev;
741 * The pending message
746 * Continuation function to call once the message
747 * has been sent. Can be NULL if there is no
748 * continuation to call.
750 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
753 * Closure for @e transmit_cont.
755 void *transmit_cont_cls;
758 * Timeout value for the pending message.
760 struct GNUNET_TIME_Absolute timeout;
763 * So that the gnunet-service-transport can group messages together,
764 * these pending messages need to accept a message buffer and size
765 * instead of just a `struct GNUNET_MessageHeader`.
772 * Session handle for TCP connections.
774 struct GNUNET_ATS_Session
777 * To whom are we talking to (set to our identity
778 * if we are still waiting for the welcome message)
780 struct GNUNET_PeerIdentity target;
783 * Pointer to the global plugin struct.
785 struct Plugin *plugin;
788 * The client (used to identify this connection)
790 struct GNUNET_SERVER_Client *client;
793 * Task cleaning up a NAT client connection establishment attempt;
795 struct GNUNET_SCHEDULER_Task *nat_connection_timeout;
798 * Messages currently pending for transmission
799 * to this peer, if any.
801 struct PendingMessage *pending_messages_head;
804 * Messages currently pending for transmission
805 * to this peer, if any.
807 struct PendingMessage *pending_messages_tail;
810 * Handle for pending transmission request.
812 struct GNUNET_SERVER_TransmitHandle *transmit_handle;
815 * Address of the other peer.
817 struct GNUNET_HELLO_Address *address;
820 * ID of task used to delay receiving more to throttle sender.
822 struct GNUNET_SCHEDULER_Task *receive_delay_task;
825 * Session timeout task
827 struct GNUNET_SCHEDULER_Task *timeout_task;
830 * When will this session time out?
832 struct GNUNET_TIME_Absolute timeout;
835 * When will we continue to read from the socket?
836 * (used to enforce inbound quota).
838 struct GNUNET_TIME_Absolute receive_delay;
841 * Last activity on this connection. Used to select preferred
844 struct GNUNET_TIME_Absolute last_activity;
847 * Number of bytes waiting for transmission to this peer.
849 unsigned long long bytes_in_queue;
852 * Number of messages waiting for transmission to this peer.
854 unsigned int msgs_in_queue;
857 * Network type of the address.
859 enum GNUNET_ATS_Network_Type scope;
862 * Are we still expecting the welcome message? (#GNUNET_YES/#GNUNET_NO)
864 int expecting_welcome;
867 * Was this session created using NAT traversal?
875 * Context for address to string conversion, closure
876 * for #append_port().
878 struct PrettyPrinterContext
883 struct PrettyPrinterContext *next;
888 struct PrettyPrinterContext *prev;
893 struct Plugin *plugin;
898 struct GNUNET_SCHEDULER_Task *timeout_task;
903 struct GNUNET_RESOLVER_RequestHandle *resolver_handle;
906 * Function to call with the result.
908 GNUNET_TRANSPORT_AddressStringCallback asc;
911 * Clsoure for @e asc.
926 * Port to add after the IP address.
933 * Encapsulation of all of the state of the plugin.
940 struct GNUNET_TRANSPORT_PluginEnvironment *env;
945 struct GNUNET_CONNECTION_Handle *lsock;
948 * Our handle to the NAT module.
950 struct GNUNET_NAT_Handle *nat;
953 * Map from peer identities to sessions for the given peer.
955 struct GNUNET_CONTAINER_MultiPeerMap *sessionmap;
958 * Handle to the network service.
960 struct LEGACY_SERVICE_Context *service;
963 * Handle to the server for this service.
965 struct GNUNET_SERVER_Handle *server;
968 * Copy of the handler array where the closures are
969 * set to this struct's instance.
971 struct GNUNET_SERVER_MessageHandler *handlers;
974 * Map of peers we have tried to contact behind a NAT
976 struct GNUNET_CONTAINER_MultiPeerMap *nat_wait_conns;
979 * List of active TCP probes.
981 struct TCPProbeContext *probe_head;
984 * List of active TCP probes.
986 struct TCPProbeContext *probe_tail;
989 * Function to call about session status changes.
991 GNUNET_TRANSPORT_SessionInfoCallback sic;
994 * Closure for @e sic.
999 * ID of task used to update our addresses when one expires.
1001 struct GNUNET_SCHEDULER_Task *address_update_task;
1004 * Running pretty printers: head
1006 struct PrettyPrinterContext *ppc_dll_head;
1009 * Running pretty printers: tail
1011 struct PrettyPrinterContext *ppc_dll_tail;
1014 * Welcome message used by this peer.
1016 struct WelcomeMessage my_welcome;
1019 * How many more TCP sessions are we allowed to open right now?
1021 unsigned long long max_connections;
1024 * How many more TCP sessions do we have right now?
1026 unsigned long long cur_connections;
1034 * Port that we are actually listening on.
1039 * Port that the user said we would have visible to the
1040 * rest of the world.
1048 * Get the list of addresses that a server for the given service
1051 * @param service_name name of the service
1052 * @param cfg configuration (which specifies the addresses)
1053 * @param addrs set (call by reference) to an array of pointers to the
1054 * addresses the server should bind to and listen on; the
1055 * array will be NULL-terminated (on success)
1056 * @param addr_lens set (call by reference) to an array of the lengths
1057 * of the respective `struct sockaddr` struct in the @a addrs
1058 * array (on success)
1059 * @return number of addresses found on success,
1060 * #GNUNET_SYSERR if the configuration
1061 * did not specify reasonable finding information or
1062 * if it specified a hostname that could not be resolved;
1063 * #GNUNET_NO if the number of addresses configured is
1064 * zero (in this case, `*addrs` and `*addr_lens` will be
1068 get_server_addresses (const char *service_name,
1069 const struct GNUNET_CONFIGURATION_Handle *cfg,
1070 struct sockaddr ***addrs,
1071 socklen_t ** addr_lens)
1074 struct GNUNET_NETWORK_Handle *desc;
1075 unsigned long long port;
1077 struct addrinfo hints;
1078 struct addrinfo *res;
1079 struct addrinfo *pos;
1080 struct addrinfo *next;
1085 struct sockaddr **saddrs;
1086 socklen_t *saddrlens;
1092 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "DISABLEV6"))
1094 if (GNUNET_SYSERR ==
1096 GNUNET_CONFIGURATION_get_value_yesno (cfg, service_name, "DISABLEV6")))
1097 return GNUNET_SYSERR;
1100 disablev6 = GNUNET_NO;
1104 /* probe IPv6 support */
1105 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
1108 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
1111 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
1112 return GNUNET_SYSERR;
1114 LOG (GNUNET_ERROR_TYPE_INFO,
1115 _("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
1116 service_name, STRERROR (errno));
1117 disablev6 = GNUNET_YES;
1121 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
1127 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
1130 GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
1133 LOG (GNUNET_ERROR_TYPE_ERROR,
1134 _("Require valid port number for service `%s' in configuration!\n"),
1139 LOG (GNUNET_ERROR_TYPE_ERROR,
1140 _("Require valid port number for service `%s' in configuration!\n"),
1142 return GNUNET_SYSERR;
1146 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "BINDTO"))
1148 GNUNET_break (GNUNET_OK ==
1149 GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
1150 "BINDTO", &hostname));
1156 abstract = GNUNET_NO;
1159 GNUNET_CONFIGURATION_have_value (cfg, service_name, "UNIXPATH")) &&
1161 GNUNET_CONFIGURATION_get_value_filename (cfg, service_name, "UNIXPATH",
1163 (0 < strlen (unixpath)))
1165 /* probe UNIX support */
1166 struct sockaddr_un s_un;
1168 if (strlen (unixpath) >= sizeof (s_un.sun_path))
1170 LOG (GNUNET_ERROR_TYPE_WARNING,
1171 _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
1172 (unsigned long long) sizeof (s_un.sun_path));
1173 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
1174 LOG (GNUNET_ERROR_TYPE_INFO,
1175 _("Using `%s' instead\n"),
1179 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1181 "USE_ABSTRACT_SOCKETS");
1182 if (GNUNET_SYSERR == abstract)
1183 abstract = GNUNET_NO;
1185 if ((GNUNET_YES != abstract)
1187 GNUNET_DISK_directory_create_for_file (unixpath)))
1188 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1192 if (NULL != unixpath)
1194 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
1197 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
1200 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
1201 GNUNET_free_non_null (hostname);
1202 GNUNET_free (unixpath);
1203 return GNUNET_SYSERR;
1205 LOG (GNUNET_ERROR_TYPE_INFO,
1206 _("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
1209 GNUNET_free (unixpath);
1214 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
1220 if ((0 == port) && (NULL == unixpath))
1222 LOG (GNUNET_ERROR_TYPE_ERROR,
1223 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
1225 GNUNET_free_non_null (hostname);
1226 return GNUNET_SYSERR;
1230 saddrs = GNUNET_malloc (2 * sizeof (struct sockaddr *));
1231 saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
1232 add_unixpath (saddrs, saddrlens, unixpath, abstract);
1233 GNUNET_free_non_null (unixpath);
1234 GNUNET_free_non_null (hostname);
1236 *addr_lens = saddrlens;
1240 if (NULL != hostname)
1242 LOG (GNUNET_ERROR_TYPE_DEBUG,
1243 "Resolving `%s' since that is where `%s' will bind to.\n",
1246 memset (&hints, 0, sizeof (struct addrinfo));
1248 hints.ai_family = AF_INET;
1249 hints.ai_protocol = IPPROTO_TCP;
1250 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
1253 LOG (GNUNET_ERROR_TYPE_ERROR,
1254 _("Failed to resolve `%s': %s\n"),
1256 gai_strerror (ret));
1257 GNUNET_free (hostname);
1258 GNUNET_free_non_null (unixpath);
1259 return GNUNET_SYSERR;
1263 while (NULL != (pos = next))
1265 next = pos->ai_next;
1266 if ((disablev6) && (pos->ai_family == AF_INET6))
1272 LOG (GNUNET_ERROR_TYPE_ERROR,
1273 _("Failed to find %saddress for `%s'.\n"),
1274 disablev6 ? "IPv4 " : "",
1277 GNUNET_free (hostname);
1278 GNUNET_free_non_null (unixpath);
1279 return GNUNET_SYSERR;
1282 if (NULL != unixpath)
1284 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1285 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1287 if (NULL != unixpath)
1289 add_unixpath (saddrs, saddrlens, unixpath, abstract);
1293 while (NULL != (pos = next))
1295 next = pos->ai_next;
1296 if ((disablev6) && (AF_INET6 == pos->ai_family))
1298 if ((IPPROTO_TCP != pos->ai_protocol) && (0 != pos->ai_protocol))
1299 continue; /* not TCP */
1300 if ((SOCK_STREAM != pos->ai_socktype) && (0 != pos->ai_socktype))
1301 continue; /* huh? */
1302 LOG (GNUNET_ERROR_TYPE_DEBUG, "Service `%s' will bind to `%s'\n",
1303 service_name, GNUNET_a2s (pos->ai_addr, pos->ai_addrlen));
1304 if (AF_INET == pos->ai_family)
1306 GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
1307 saddrlens[i] = pos->ai_addrlen;
1308 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1309 GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1310 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1314 GNUNET_assert (AF_INET6 == pos->ai_family);
1315 GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
1316 saddrlens[i] = pos->ai_addrlen;
1317 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1318 GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1319 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1323 GNUNET_free (hostname);
1329 /* will bind against everything, just set port */
1334 if (NULL != unixpath)
1337 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1338 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1339 if (NULL != unixpath)
1341 add_unixpath (saddrs, saddrlens, unixpath, abstract);
1344 saddrlens[i] = sizeof (struct sockaddr_in);
1345 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1346 #if HAVE_SOCKADDR_IN_SIN_LEN
1347 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1349 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1350 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1356 if (NULL != unixpath)
1358 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1359 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1361 if (NULL != unixpath)
1363 add_unixpath (saddrs, saddrlens, unixpath, abstract);
1366 saddrlens[i] = sizeof (struct sockaddr_in6);
1367 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1368 #if HAVE_SOCKADDR_IN_SIN_LEN
1369 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1371 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1372 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1374 saddrlens[i] = sizeof (struct sockaddr_in);
1375 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1376 #if HAVE_SOCKADDR_IN_SIN_LEN
1377 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1379 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1380 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1383 GNUNET_free_non_null (unixpath);
1385 *addr_lens = saddrlens;
1388 /* end ancient copy-and-paste */
1392 * If a session monitor is attached, notify it about the new
1395 * @param plugin our plugin
1396 * @param session session that changed state
1397 * @param state new state of the session
1400 notify_session_monitor (struct Plugin *plugin,
1401 struct GNUNET_ATS_Session *session,
1402 enum GNUNET_TRANSPORT_SessionState state)
1404 struct GNUNET_TRANSPORT_SessionInfo info;
1406 if (NULL == plugin->sic)
1408 memset (&info, 0, sizeof (info));
1410 info.is_inbound = GNUNET_HELLO_address_check_option (session->address,
1411 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
1412 info.num_msg_pending = session->msgs_in_queue;
1413 info.num_bytes_pending = session->bytes_in_queue;
1414 if (NULL != session->receive_delay_task)
1415 info.receive_delay = session->receive_delay;
1416 info.session_timeout = session->timeout;
1417 info.address = session->address;
1418 plugin->sic (plugin->sic_cls,
1425 * Our external IP address/port mapping has changed.
1427 * @param cls closure, the `struct Plugin`
1428 * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
1429 * the previous (now invalid) one
1430 * @param ac address class the address belongs to
1431 * @param addr either the previous or the new public IP address
1432 * @param addrlen actual length of @a addr
1435 tcp_nat_port_map_callback (void *cls,
1437 enum GNUNET_NAT_AddressClass ac,
1438 const struct sockaddr *addr,
1441 struct Plugin *plugin = cls;
1442 struct GNUNET_HELLO_Address *address;
1443 struct IPv4TcpAddress t4;
1444 struct IPv6TcpAddress t6;
1448 LOG (GNUNET_ERROR_TYPE_INFO,
1449 "NAT notification to %s address `%s'\n",
1450 (GNUNET_YES == add_remove) ? "add" : "remove",
1451 GNUNET_a2s (addr, addrlen));
1452 /* convert 'addr' to our internal format */
1453 switch (addr->sa_family)
1456 GNUNET_assert(addrlen == sizeof(struct sockaddr_in));
1457 memset (&t4, 0, sizeof(t4));
1458 t4.options = htonl (plugin->myoptions);
1459 t4.ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1460 t4.t4_port = ((struct sockaddr_in *) addr)->sin_port;
1465 GNUNET_assert(addrlen == sizeof(struct sockaddr_in6));
1466 memset (&t6, 0, sizeof(t6));
1467 GNUNET_memcpy (&t6.ipv6_addr,
1468 &((struct sockaddr_in6 *) addr)->sin6_addr,
1469 sizeof(struct in6_addr));
1470 t6.options = htonl (plugin->myoptions);
1471 t6.t6_port = ((struct sockaddr_in6 *) addr)->sin6_port;
1479 /* modify our published address list */
1480 GNUNET_assert ((args == sizeof (struct IPv4TcpAddress)) ||
1481 (args == sizeof (struct IPv6TcpAddress)));
1482 /* TODO: use 'ac' here in the future... */
1483 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
1487 GNUNET_HELLO_ADDRESS_INFO_NONE);
1488 plugin->env->notify_address (plugin->env->cls,
1491 GNUNET_HELLO_address_free (address);
1496 * Function called for a quick conversion of the binary address to
1497 * a numeric address. Note that the caller must not free the
1498 * address and that the next call to this function is allowed
1499 * to override the address again.
1501 * @param cls closure (`struct Plugin*`)
1502 * @param addr binary address
1503 * @param addrlen length of @a addr
1504 * @return string representing the same address
1507 tcp_plugin_address_to_string (void *cls,
1511 static char rbuf[INET6_ADDRSTRLEN + 12];
1512 char buf[INET6_ADDRSTRLEN];
1516 const struct IPv4TcpAddress *t4;
1517 const struct IPv6TcpAddress *t6;
1524 case sizeof(struct IPv6TcpAddress):
1527 port = ntohs (t6->t6_port);
1528 options = ntohl (t6->options);
1529 GNUNET_memcpy (&a6, &t6->ipv6_addr, sizeof(a6));
1532 case sizeof(struct IPv4TcpAddress):
1535 port = ntohs (t4->t4_port);
1536 options = ntohl (t4->options);
1537 GNUNET_memcpy (&a4, &t4->ipv4_addr, sizeof(a4));
1541 LOG (GNUNET_ERROR_TYPE_WARNING,
1542 _("Unexpected address length: %u bytes\n"),
1543 (unsigned int) addrlen);
1546 if (NULL == inet_ntop (af, sb, buf, INET6_ADDRSTRLEN))
1548 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1552 GNUNET_snprintf (rbuf, sizeof(rbuf),
1553 (af == AF_INET6) ? "%s.%u.[%s]:%u" : "%s.%u.%s:%u",
1563 * Function called to convert a string address to
1566 * @param cls closure (`struct Plugin*`)
1567 * @param addr string address
1568 * @param addrlen length of the address
1569 * @param buf location to store the buffer
1570 * @param added location to store the number of bytes in the buffer.
1571 * If the function returns #GNUNET_SYSERR, its contents are undefined.
1572 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1575 tcp_plugin_string_to_address (void *cls,
1581 struct sockaddr_storage socket_address;
1587 /* Format tcp.options.address:port */
1591 if ((NULL == addr) || (0 == addrlen))
1594 return GNUNET_SYSERR;
1596 if ('\0' != addr[addrlen - 1])
1599 return GNUNET_SYSERR;
1601 if (strlen (addr) != addrlen - 1)
1604 return GNUNET_SYSERR;
1606 plugin = GNUNET_strdup (addr);
1607 optionstr = strchr (plugin, '.');
1608 if (NULL == optionstr)
1611 GNUNET_free(plugin);
1612 return GNUNET_SYSERR;
1614 optionstr[0] = '\0';
1616 options = atol (optionstr);
1617 address = strchr (optionstr, '.');
1618 if (NULL == address)
1621 GNUNET_free(plugin);
1622 return GNUNET_SYSERR;
1628 GNUNET_STRINGS_to_address_ip (address,
1633 GNUNET_free(plugin);
1634 return GNUNET_SYSERR;
1637 GNUNET_free(plugin);
1638 switch (socket_address.ss_family)
1642 struct IPv4TcpAddress *t4;
1643 struct sockaddr_in *in4 = (struct sockaddr_in *) &socket_address;
1644 t4 = GNUNET_new (struct IPv4TcpAddress);
1645 t4->options = htonl (options);
1646 t4->ipv4_addr = in4->sin_addr.s_addr;
1647 t4->t4_port = in4->sin_port;
1649 *added = sizeof(struct IPv4TcpAddress);
1654 struct IPv6TcpAddress *t6;
1655 struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) &socket_address;
1656 t6 = GNUNET_new (struct IPv6TcpAddress);
1657 t6->options = htonl (options);
1658 t6->ipv6_addr = in6->sin6_addr;
1659 t6->t6_port = in6->sin6_port;
1661 *added = sizeof(struct IPv6TcpAddress);
1665 return GNUNET_SYSERR;
1671 * Find the session handle for the given client.
1672 * Currently uses both the hashmap and the client
1673 * context, as the client context is new and the
1674 * logic still needs to be tested.
1676 * @param plugin the plugin
1677 * @param client which client to find the session handle for
1678 * @return NULL if no matching session exists
1680 static struct GNUNET_ATS_Session *
1681 lookup_session_by_client (struct Plugin *plugin,
1682 struct GNUNET_SERVER_Client *client)
1684 return GNUNET_SERVER_client_get_user_context (client,
1685 struct GNUNET_ATS_Session);
1690 * Functions with this signature are called whenever we need
1691 * to close a session due to a disconnect or failure to
1692 * establish a connection.
1694 * @param cls the `struct Plugin`
1695 * @param session session to close down
1696 * @return #GNUNET_OK on success
1699 tcp_plugin_disconnect_session (void *cls,
1700 struct GNUNET_ATS_Session *session)
1702 struct Plugin *plugin = cls;
1703 struct PendingMessage *pm;
1705 LOG (GNUNET_ERROR_TYPE_DEBUG,
1706 "Disconnecting session of peer `%s' address `%s'\n",
1707 GNUNET_i2s (&session->target),
1708 tcp_plugin_address_to_string (session->plugin,
1709 session->address->address,
1710 session->address->address_length));
1712 if (NULL != session->timeout_task)
1714 GNUNET_SCHEDULER_cancel (session->timeout_task);
1715 session->timeout_task = NULL;
1716 session->timeout = GNUNET_TIME_UNIT_ZERO_ABS;
1720 GNUNET_CONTAINER_multipeermap_remove (plugin->sessionmap,
1724 GNUNET_STATISTICS_update (session->plugin->env->stats,
1725 gettext_noop ("# TCP sessions active"),
1731 GNUNET_assert (GNUNET_YES ==
1732 GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns,
1736 if (NULL != session->client)
1737 GNUNET_SERVER_client_set_user_context (session->client,
1740 /* clean up state */
1741 if (NULL != session->transmit_handle)
1743 GNUNET_SERVER_notify_transmit_ready_cancel (session->transmit_handle);
1744 session->transmit_handle = NULL;
1746 session->plugin->env->session_end (session->plugin->env->cls,
1750 if (NULL != session->nat_connection_timeout)
1752 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
1753 session->nat_connection_timeout = NULL;
1756 while (NULL != (pm = session->pending_messages_head))
1758 LOG (GNUNET_ERROR_TYPE_DEBUG,
1759 (NULL != pm->transmit_cont)
1760 ? "Could not deliver message to `%s' at %s.\n"
1761 : "Could not deliver message to `%s' at %s, notifying.\n",
1762 GNUNET_i2s (&session->target),
1763 tcp_plugin_address_to_string (session->plugin,
1764 session->address->address,
1765 session->address->address_length));
1766 GNUNET_STATISTICS_update (session->plugin->env->stats,
1767 gettext_noop ("# bytes currently in TCP buffers"),
1768 -(int64_t) pm->message_size, GNUNET_NO);
1769 GNUNET_STATISTICS_update (session->plugin->env->stats,
1770 gettext_noop ("# bytes discarded by TCP (disconnect)"),
1773 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
1774 session->pending_messages_tail,
1776 GNUNET_assert (0 < session->msgs_in_queue);
1777 session->msgs_in_queue--;
1778 GNUNET_assert (pm->message_size <= session->bytes_in_queue);
1779 session->bytes_in_queue -= pm->message_size;
1780 if (NULL != pm->transmit_cont)
1781 pm->transmit_cont (pm->transmit_cont_cls,
1788 GNUNET_assert (0 == session->msgs_in_queue);
1789 GNUNET_assert (0 == session->bytes_in_queue);
1790 notify_session_monitor (session->plugin,
1792 GNUNET_TRANSPORT_SS_DONE);
1794 if (NULL != session->receive_delay_task)
1796 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
1797 session->receive_delay_task = NULL;
1799 if (NULL != session->client)
1801 GNUNET_SERVER_client_disconnect (session->client);
1802 session->client = NULL;
1804 GNUNET_HELLO_address_free (session->address);
1805 GNUNET_assert (NULL == session->transmit_handle);
1806 GNUNET_free (session);
1812 * Function that is called to get the keepalive factor.
1813 * #GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
1814 * calculate the interval between keepalive packets.
1816 * @param cls closure with the `struct Plugin`
1817 * @return keepalive factor
1820 tcp_plugin_query_keepalive_factor (void *cls)
1827 * Session was idle for too long, so disconnect it
1829 * @param cls the `struct GNUNET_ATS_Session` of the idle session
1832 session_timeout (void *cls)
1834 struct GNUNET_ATS_Session *s = cls;
1835 struct GNUNET_TIME_Relative left;
1837 s->timeout_task = NULL;
1838 left = GNUNET_TIME_absolute_get_remaining (s->timeout);
1839 if (0 != left.rel_value_us)
1841 /* not actually our turn yet, but let's at least update
1842 the monitor, it may think we're about to die ... */
1843 notify_session_monitor (s->plugin,
1845 GNUNET_TRANSPORT_SS_UPDATE);
1846 s->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
1851 LOG (GNUNET_ERROR_TYPE_DEBUG,
1852 "Session %p was idle for %s, disconnecting\n",
1854 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1856 /* call session destroy function */
1857 tcp_plugin_disconnect_session (s->plugin,
1863 * Increment session timeout due to activity.
1865 * @param s session to increment timeout for
1868 reschedule_session_timeout (struct GNUNET_ATS_Session *s)
1870 GNUNET_assert (NULL != s->timeout_task);
1871 s->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1876 * Create a new session. Also queues a welcome message.
1878 * @param plugin the plugin
1879 * @param address the address to create the session for
1880 * @param scope network scope the address is from
1881 * @param client client to use, reference counter must have already been increased
1882 * @param is_nat this a NAT session, we should wait for a client to
1883 * connect to us from an address, then assign that to
1885 * @return new session object
1887 static struct GNUNET_ATS_Session *
1888 create_session (struct Plugin *plugin,
1889 const struct GNUNET_HELLO_Address *address,
1890 enum GNUNET_ATS_Network_Type scope,
1891 struct GNUNET_SERVER_Client *client,
1894 struct GNUNET_ATS_Session *session;
1895 struct PendingMessage *pm;
1897 if (GNUNET_YES != is_nat)
1898 GNUNET_assert (NULL != client);
1900 GNUNET_assert (NULL == client);
1902 LOG (GNUNET_ERROR_TYPE_DEBUG,
1903 "Creating new session for peer `%s' at address %s\n",
1904 GNUNET_i2s (&address->peer),
1905 tcp_plugin_address_to_string (plugin,
1907 address->address_length));
1908 session = GNUNET_new (struct GNUNET_ATS_Session);
1909 session->last_activity = GNUNET_TIME_absolute_get ();
1910 session->plugin = plugin;
1911 session->is_nat = is_nat;
1914 session->client = client;
1915 GNUNET_SERVER_client_set_user_context (client,
1918 session->address = GNUNET_HELLO_address_copy (address);
1919 session->target = address->peer;
1920 session->expecting_welcome = GNUNET_YES;
1921 session->scope = scope;
1922 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
1923 sizeof (struct WelcomeMessage));
1924 pm->msg = (const char *) &pm[1];
1925 pm->message_size = sizeof(struct WelcomeMessage);
1926 GNUNET_memcpy (&pm[1],
1927 &plugin->my_welcome,
1928 sizeof(struct WelcomeMessage));
1929 pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1930 GNUNET_STATISTICS_update (plugin->env->stats,
1931 gettext_noop ("# bytes currently in TCP buffers"),
1934 GNUNET_CONTAINER_DLL_insert (session->pending_messages_head,
1935 session->pending_messages_tail,
1937 session->msgs_in_queue++;
1938 session->bytes_in_queue += pm->message_size;
1939 session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1940 session->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1943 notify_session_monitor (session->plugin,
1945 GNUNET_TRANSPORT_SS_INIT);
1946 if (GNUNET_YES != is_nat)
1948 GNUNET_STATISTICS_update (plugin->env->stats,
1949 gettext_noop ("# TCP sessions active"),
1952 notify_session_monitor (session->plugin,
1954 GNUNET_TRANSPORT_SS_UP);
1958 notify_session_monitor (session->plugin,
1960 GNUNET_TRANSPORT_SS_HANDSHAKE);
1967 * If we have pending messages, ask the server to
1968 * transmit them (schedule the respective tasks, etc.)
1970 * @param session for which session should we do this
1973 process_pending_messages (struct GNUNET_ATS_Session *session);
1977 * Function called to notify a client about the socket
1978 * being ready to queue more data. "buf" will be
1979 * NULL and "size" zero if the socket was closed for
1980 * writing in the meantime.
1982 * @param cls closure
1983 * @param size number of bytes available in @a buf
1984 * @param buf where the callee should write the message
1985 * @return number of bytes written to @a buf
1988 do_transmit (void *cls,
1992 struct GNUNET_ATS_Session *session = cls;
1993 struct GNUNET_PeerIdentity pid;
1994 struct Plugin *plugin;
1995 struct PendingMessage *pos;
1996 struct PendingMessage *hd;
1997 struct PendingMessage *tl;
1998 struct GNUNET_TIME_Absolute now;
2002 session->transmit_handle = NULL;
2003 plugin = session->plugin;
2006 LOG (GNUNET_ERROR_TYPE_DEBUG,
2007 "Timeout trying to transmit to peer `%s', discarding message queue.\n",
2008 GNUNET_i2s (&session->target));
2009 /* timeout; cancel all messages that have already expired */
2013 now = GNUNET_TIME_absolute_get ();
2014 while ( (NULL != (pos = session->pending_messages_head)) &&
2015 (pos->timeout.abs_value_us <= now.abs_value_us) )
2017 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
2018 session->pending_messages_tail,
2020 GNUNET_assert (0 < session->msgs_in_queue);
2021 session->msgs_in_queue--;
2022 GNUNET_assert (pos->message_size <= session->bytes_in_queue);
2023 session->bytes_in_queue -= pos->message_size;
2024 LOG (GNUNET_ERROR_TYPE_DEBUG,
2025 "Failed to transmit %u byte message to `%s'.\n",
2027 GNUNET_i2s (&session->target));
2028 ret += pos->message_size;
2029 GNUNET_CONTAINER_DLL_insert_after (hd,
2034 /* do this call before callbacks (so that if callbacks destroy
2035 * session, they have a chance to cancel actions done by this
2037 process_pending_messages (session);
2038 pid = session->target;
2039 /* no do callbacks and do not use session again since
2040 * the callbacks may abort the session */
2041 while (NULL != (pos = hd))
2043 GNUNET_CONTAINER_DLL_remove (hd,
2046 if (NULL != pos->transmit_cont)
2047 pos->transmit_cont (pos->transmit_cont_cls,
2054 GNUNET_STATISTICS_update (plugin->env->stats,
2055 gettext_noop ("# bytes currently in TCP buffers"), -(int64_t) ret,
2057 GNUNET_STATISTICS_update (plugin->env->stats,
2058 gettext_noop ("# bytes discarded by TCP (timeout)"),
2062 notify_session_monitor (session->plugin,
2064 GNUNET_TRANSPORT_SS_UPDATE);
2067 /* copy all pending messages that would fit */
2072 while (NULL != (pos = session->pending_messages_head))
2074 if (ret + pos->message_size > size)
2076 GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
2077 session->pending_messages_tail,
2079 GNUNET_assert (0 < session->msgs_in_queue);
2080 session->msgs_in_queue--;
2081 GNUNET_assert (pos->message_size <= session->bytes_in_queue);
2082 session->bytes_in_queue -= pos->message_size;
2083 GNUNET_assert(size >= pos->message_size);
2084 LOG (GNUNET_ERROR_TYPE_DEBUG,
2085 "Transmitting message of type %u size %u to peer %s at %s\n",
2086 ntohs (((struct GNUNET_MessageHeader *) pos->msg)->type),
2088 GNUNET_i2s (&session->target),
2089 tcp_plugin_address_to_string (session->plugin,
2090 session->address->address,
2091 session->address->address_length));
2092 /* FIXME: this GNUNET_memcpy can be up to 7% of our total runtime */
2093 GNUNET_memcpy (cbuf,
2096 cbuf += pos->message_size;
2097 ret += pos->message_size;
2098 size -= pos->message_size;
2099 GNUNET_CONTAINER_DLL_insert_tail (hd,
2103 notify_session_monitor (session->plugin,
2105 GNUNET_TRANSPORT_SS_UPDATE);
2106 /* schedule 'continuation' before callbacks so that callbacks that
2107 * cancel everything don't cause us to use a session that no longer
2109 process_pending_messages (session);
2110 session->last_activity = GNUNET_TIME_absolute_get ();
2111 pid = session->target;
2112 /* we'll now call callbacks that may cancel the session; hence
2113 * we should not use 'session' after this point */
2114 while (NULL != (pos = hd))
2116 GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
2117 if (NULL != pos->transmit_cont)
2118 pos->transmit_cont (pos->transmit_cont_cls,
2122 pos->message_size); /* FIXME: include TCP overhead */
2125 GNUNET_assert (NULL == hd);
2126 GNUNET_assert (NULL == tl);
2127 GNUNET_STATISTICS_update (plugin->env->stats,
2128 gettext_noop ("# bytes currently in TCP buffers"),
2131 GNUNET_STATISTICS_update (plugin->env->stats,
2132 gettext_noop ("# bytes transmitted via TCP"),
2140 * If we have pending messages, ask the server to
2141 * transmit them (schedule the respective tasks, etc.)
2143 * @param session for which session should we do this
2146 process_pending_messages (struct GNUNET_ATS_Session *session)
2148 struct PendingMessage *pm;
2150 GNUNET_assert (NULL != session->client);
2151 if (NULL != session->transmit_handle)
2153 if (NULL == (pm = session->pending_messages_head))
2156 session->transmit_handle
2157 = GNUNET_SERVER_notify_transmit_ready (session->client,
2159 GNUNET_TIME_absolute_get_remaining (pm->timeout),
2166 * Function that can be used by the transport service to transmit
2167 * a message using the plugin. Note that in the case of a
2168 * peer disconnecting, the continuation MUST be called
2169 * prior to the disconnect notification itself. This function
2170 * will be called with this peer's HELLO message to initiate
2171 * a fresh connection to another peer.
2173 * @param cls closure
2174 * @param session which session must be used
2175 * @param msgbuf the message to transmit
2176 * @param msgbuf_size number of bytes in @a msgbuf
2177 * @param priority how important is the message (most plugins will
2178 * ignore message priority and just FIFO)
2179 * @param to how long to wait at most for the transmission (does not
2180 * require plugins to discard the message after the timeout,
2181 * just advisory for the desired delay; most plugins will ignore
2183 * @param cont continuation to call once the message has
2184 * been transmitted (or if the transport is ready
2185 * for the next transmission call; or if the
2186 * peer disconnected...); can be NULL
2187 * @param cont_cls closure for @a cont
2188 * @return number of bytes used (on the physical network, with overheads);
2189 * -1 on hard errors (i.e. address invalid); 0 is a legal value
2190 * and does NOT mean that the message was not transmitted (DV)
2193 tcp_plugin_send (void *cls,
2194 struct GNUNET_ATS_Session *session,
2197 unsigned int priority,
2198 struct GNUNET_TIME_Relative to,
2199 GNUNET_TRANSPORT_TransmitContinuation cont,
2202 struct Plugin * plugin = cls;
2203 struct PendingMessage *pm;
2205 /* create new message entry */
2206 pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
2207 pm->msg = (const char *) &pm[1];
2208 GNUNET_memcpy (&pm[1], msgbuf, msgbuf_size);
2209 pm->message_size = msgbuf_size;
2210 pm->timeout = GNUNET_TIME_relative_to_absolute (to);
2211 pm->transmit_cont = cont;
2212 pm->transmit_cont_cls = cont_cls;
2214 LOG (GNUNET_ERROR_TYPE_DEBUG,
2215 "Asked to transmit %u bytes to `%s', added message to list.\n",
2217 GNUNET_i2s (&session->target));
2220 GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
2224 GNUNET_assert (NULL != session->client);
2225 GNUNET_SERVER_client_set_timeout (session->client,
2226 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2227 GNUNET_STATISTICS_update (plugin->env->stats,
2228 gettext_noop ("# bytes currently in TCP buffers"),
2232 /* append pm to pending_messages list */
2233 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
2234 session->pending_messages_tail,
2236 notify_session_monitor (session->plugin,
2238 GNUNET_TRANSPORT_SS_UPDATE);
2239 session->msgs_in_queue++;
2240 session->bytes_in_queue += pm->message_size;
2241 process_pending_messages (session);
2245 GNUNET_CONTAINER_multipeermap_contains_value (plugin->nat_wait_conns,
2249 LOG (GNUNET_ERROR_TYPE_DEBUG,
2250 "This NAT WAIT session for peer `%s' is not yet ready!\n",
2251 GNUNET_i2s (&session->target));
2252 GNUNET_STATISTICS_update (plugin->env->stats,
2253 gettext_noop ("# bytes currently in TCP buffers"), msgbuf_size,
2255 /* append pm to pending_messages list */
2256 GNUNET_CONTAINER_DLL_insert_tail (session->pending_messages_head,
2257 session->pending_messages_tail,
2259 session->msgs_in_queue++;
2260 session->bytes_in_queue += pm->message_size;
2261 notify_session_monitor (session->plugin,
2263 GNUNET_TRANSPORT_SS_HANDSHAKE);
2266 LOG (GNUNET_ERROR_TYPE_ERROR,
2267 "Invalid session %p\n",
2277 return GNUNET_SYSERR; /* session does not exist here */
2282 * Closure for #session_lookup_it().
2284 struct GNUNET_ATS_SessionItCtx
2287 * Address we are looking for.
2289 const struct GNUNET_HELLO_Address *address;
2292 * Where to store the session (if we found it).
2294 struct GNUNET_ATS_Session *result;
2300 * Look for a session by address.
2302 * @param cls the `struct GNUNET_ATS_SessionItCtx`
2304 * @param value a `struct GNUNET_ATS_Session`
2305 * @return #GNUNET_YES to continue looking, #GNUNET_NO if we found the session
2308 session_lookup_it (void *cls,
2309 const struct GNUNET_PeerIdentity *key,
2312 struct GNUNET_ATS_SessionItCtx *si_ctx = cls;
2313 struct GNUNET_ATS_Session *session = value;
2316 GNUNET_HELLO_address_cmp (si_ctx->address,
2319 si_ctx->result = session;
2325 * Task cleaning up a NAT connection attempt after timeout
2327 * @param cls the `struct GNUNET_ATS_Session`
2330 nat_connect_timeout (void *cls)
2332 struct GNUNET_ATS_Session *session = cls;
2334 session->nat_connection_timeout = NULL;
2335 LOG (GNUNET_ERROR_TYPE_DEBUG,
2336 "NAT WAIT connection to `%4s' at `%s' could not be established, removing session\n",
2337 GNUNET_i2s (&session->target),
2338 tcp_plugin_address_to_string (session->plugin,
2339 session->address->address,
2340 session->address->address_length));
2341 tcp_plugin_disconnect_session (session->plugin,
2347 * Function that will be called whenever the transport service wants to
2348 * notify the plugin that a session is still active and in use and
2349 * therefore the session timeout for this session has to be updated
2351 * @param cls closure
2352 * @param peer which peer was the session for
2353 * @param session which session is being updated
2356 tcp_plugin_update_session_timeout (void *cls,
2357 const struct GNUNET_PeerIdentity *peer,
2358 struct GNUNET_ATS_Session *session)
2360 reschedule_session_timeout (session);
2365 * Task to signal the server that we can continue
2366 * receiving from the TCP client now.
2368 * @param cls the `struct GNUNET_ATS_Session *`
2371 delayed_done (void *cls)
2373 struct GNUNET_ATS_Session *session = cls;
2375 session->receive_delay_task = NULL;
2376 reschedule_session_timeout (session);
2377 GNUNET_SERVER_receive_done (session->client,
2383 * Function that will be called whenever the transport service wants to
2384 * notify the plugin that the inbound quota changed and that the plugin
2385 * should update it's delay for the next receive value
2387 * @param cls closure
2388 * @param peer which peer was the session for
2389 * @param session which session is being updated
2390 * @param delay new delay to use for receiving
2393 tcp_plugin_update_inbound_delay (void *cls,
2394 const struct GNUNET_PeerIdentity *peer,
2395 struct GNUNET_ATS_Session *session,
2396 struct GNUNET_TIME_Relative delay)
2398 if (NULL == session->receive_delay_task)
2400 LOG (GNUNET_ERROR_TYPE_DEBUG,
2401 "New inbound delay %s\n",
2402 GNUNET_STRINGS_relative_time_to_string (delay,
2404 session->receive_delay = GNUNET_TIME_relative_to_absolute (delay);
2405 GNUNET_SCHEDULER_cancel (session->receive_delay_task);
2406 session->receive_delay_task = GNUNET_SCHEDULER_add_delayed (delay,
2413 * Create a new session to transmit data to the target
2414 * This session will used to send data to this peer and the plugin will
2415 * notify us by calling the env->session_end function
2417 * @param cls closure
2418 * @param address the address to use
2419 * @return the session if the address is valid, NULL otherwise
2421 static struct GNUNET_ATS_Session *
2422 tcp_plugin_get_session (void *cls,
2423 const struct GNUNET_HELLO_Address *address)
2425 struct Plugin *plugin = cls;
2426 struct GNUNET_ATS_Session *session = NULL;
2430 struct GNUNET_CONNECTION_Handle *sa;
2431 struct sockaddr_in a4;
2432 struct sockaddr_in6 a6;
2433 const struct IPv4TcpAddress *t4;
2434 const struct IPv6TcpAddress *t6;
2435 unsigned int options;
2436 enum GNUNET_ATS_Network_Type net_type;
2437 unsigned int is_natd = GNUNET_NO;
2440 struct GNUNET_NETWORK_Handle *s;
2443 addrlen = address->address_length;
2444 LOG (GNUNET_ERROR_TYPE_DEBUG,
2445 "Trying to get session for `%s' address of peer `%s'\n",
2446 tcp_plugin_address_to_string (plugin,
2448 address->address_length),
2449 GNUNET_i2s (&address->peer));
2451 if (GNUNET_HELLO_address_check_option (address,
2452 GNUNET_HELLO_ADDRESS_INFO_INBOUND))
2458 /* look for existing session */
2460 GNUNET_CONTAINER_multipeermap_contains (plugin->sessionmap,
2463 struct GNUNET_ATS_SessionItCtx si_ctx;
2465 si_ctx.address = address;
2466 si_ctx.result = NULL;
2467 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
2471 if (NULL != si_ctx.result)
2473 session = si_ctx.result;
2474 LOG (GNUNET_ERROR_TYPE_DEBUG,
2475 "Found existing session for `%s' address `%s'\n",
2476 GNUNET_i2s (&address->peer),
2477 tcp_plugin_address_to_string (plugin,
2479 address->address_length));
2482 /* This is a bit of a hack, limiting TCP to never allow more than
2483 one TCP connection to any given peer at the same time.
2484 Without this, peers sometimes disagree about which of the TCP
2485 connections they should use, causing one side to believe that
2486 they transmit successfully, while the other receives nothing. */
2487 return NULL; /* Refuse to have more than one TCP connection per
2488 peer pair at the same time. */
2491 if (addrlen == sizeof(struct IPv6TcpAddress))
2493 GNUNET_assert (NULL != address->address); /* make static analysis happy */
2494 t6 = address->address;
2495 options = t6->options;
2497 memset (&a6, 0, sizeof(a6));
2498 #if HAVE_SOCKADDR_IN_SIN_LEN
2499 a6.sin6_len = sizeof (a6);
2501 a6.sin6_family = AF_INET6;
2502 a6.sin6_port = t6->t6_port;
2503 if (t6->t6_port == 0)
2504 is_natd = GNUNET_YES;
2505 GNUNET_memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
2509 else if (addrlen == sizeof(struct IPv4TcpAddress))
2511 GNUNET_assert(NULL != address->address); /* make static analysis happy */
2512 t4 = address->address;
2513 options = t4->options;
2515 memset (&a4, 0, sizeof(a4));
2516 #if HAVE_SOCKADDR_IN_SIN_LEN
2517 a4.sin_len = sizeof (a4);
2519 a4.sin_family = AF_INET;
2520 a4.sin_port = t4->t4_port;
2521 if (t4->t4_port == 0)
2522 is_natd = GNUNET_YES;
2523 a4.sin_addr.s_addr = t4->ipv4_addr;
2529 GNUNET_STATISTICS_update (plugin->env->stats,
2530 gettext_noop ("# requests to create session with invalid address"),
2536 net_type = plugin->env->get_address_type (plugin->env->cls,
2539 GNUNET_break (net_type != GNUNET_ATS_NET_UNSPECIFIED);
2541 if ( (is_natd == GNUNET_YES) &&
2542 (addrlen == sizeof(struct IPv6TcpAddress)) )
2544 /* NAT client only works with IPv4 addresses */
2548 if (plugin->cur_connections >= plugin->max_connections)
2554 if ( (is_natd == GNUNET_YES) &&
2556 GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
2559 /* Only do one NAT punch attempt per peer identity */
2563 if ( (is_natd == GNUNET_YES) &&
2564 (NULL != plugin->nat) &&
2566 GNUNET_CONTAINER_multipeermap_contains (plugin->nat_wait_conns,
2569 struct sockaddr_in local_sa;
2571 LOG (GNUNET_ERROR_TYPE_DEBUG,
2572 "Found valid IPv4 NAT address (creating session)!\n");
2573 session = create_session (plugin,
2578 session->nat_connection_timeout = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
2579 &nat_connect_timeout,
2581 GNUNET_assert (GNUNET_OK ==
2582 GNUNET_CONTAINER_multipeermap_put (plugin->nat_wait_conns,
2585 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2587 LOG (GNUNET_ERROR_TYPE_DEBUG,
2588 "Created NAT WAIT connection to `%s' at `%s'\n",
2589 GNUNET_i2s (&session->target),
2590 GNUNET_a2s (sb, sbs));
2594 local_sa.sin_family = AF_INET;
2595 local_sa.sin_port = htons (plugin->open_port);
2596 /* We leave sin_address at 0, let the kernel figure it out,
2597 even if our bind() is more specific. (May want to reconsider
2600 GNUNET_NAT_request_reversal (plugin->nat,
2604 LOG (GNUNET_ERROR_TYPE_DEBUG,
2605 "Running NAT client for `%s' at `%s' failed\n",
2606 GNUNET_i2s (&session->target),
2607 GNUNET_a2s (sb, sbs));
2608 tcp_plugin_disconnect_session (plugin,
2613 /* create new outbound session */
2614 if (0 != (options & TCP_OPTIONS_TCP_STEALTH))
2617 s = GNUNET_NETWORK_socket_create (af, SOCK_STREAM, 0);
2620 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
2627 GNUNET_NETWORK_socket_setsockopt (s,
2631 sizeof (struct GNUNET_PeerIdentity))) ||
2633 GNUNET_NETWORK_socket_setsockopt (s,
2635 TCP_STEALTH_INTEGRITY,
2636 &plugin->my_welcome,
2637 sizeof (struct WelcomeMessage))) )
2639 /* TCP STEALTH not supported by kernel */
2640 GNUNET_break (GNUNET_OK ==
2641 GNUNET_NETWORK_socket_close (s));
2646 sa = GNUNET_CONNECTION_connect_socket (s, sb, sbs);
2655 sa = GNUNET_CONNECTION_create_from_sockaddr (af, sb, sbs);
2659 LOG (GNUNET_ERROR_TYPE_DEBUG,
2660 "Failed to create connection to `%s' at `%s'\n",
2661 GNUNET_i2s (&address->peer),
2662 GNUNET_a2s (sb, sbs));
2665 LOG (GNUNET_ERROR_TYPE_DEBUG,
2666 "Asked to transmit to `%s', creating fresh session using address `%s'.\n",
2667 GNUNET_i2s (&address->peer),
2668 GNUNET_a2s (sb, sbs));
2670 session = create_session (plugin,
2673 GNUNET_SERVER_connect_socket (plugin->server,
2676 (void) GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
2679 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2680 /* Send TCP Welcome */
2681 process_pending_messages (session);
2688 * We have been asked to destroy all connections to a particular peer.
2689 * This function is called on each applicable session and must tear it
2692 * @param cls the `struct Plugin *`
2693 * @param key the peer which the session belongs to (unused)
2694 * @param value the `struct GNUNET_ATS_Session`
2695 * @return #GNUNET_YES (continue to iterate)
2698 session_disconnect_it (void *cls,
2699 const struct GNUNET_PeerIdentity *key,
2702 struct Plugin *plugin = cls;
2703 struct GNUNET_ATS_Session *session = value;
2705 GNUNET_STATISTICS_update (session->plugin->env->stats,
2706 gettext_noop ("# transport-service disconnect requests for TCP"),
2709 tcp_plugin_disconnect_session (plugin,
2716 * Function that can be called to force a disconnect from the
2717 * specified neighbour. This should also cancel all previously
2718 * scheduled transmissions. Obviously the transmission may have been
2719 * partially completed already, which is OK. The plugin is supposed
2720 * to close the connection (if applicable) and no longer call the
2721 * transmit continuation(s).
2723 * Finally, plugin MUST NOT call the services's receive function to
2724 * notify the service that the connection to the specified target was
2725 * closed after a getting this call.
2727 * @param cls closure
2728 * @param target peer for which the last transmission is
2732 tcp_plugin_disconnect (void *cls,
2733 const struct GNUNET_PeerIdentity *target)
2735 struct Plugin *plugin = cls;
2737 LOG (GNUNET_ERROR_TYPE_DEBUG,
2738 "Disconnecting peer `%s'\n",
2739 GNUNET_i2s (target));
2740 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessionmap,
2742 &session_disconnect_it,
2744 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->nat_wait_conns,
2746 &session_disconnect_it,
2752 * We are processing an address pretty printing request and finished
2753 * the IP resolution (if applicable). Append our port and forward the
2754 * result. If called with @a hostname NULL, we are done and should
2755 * clean up the pretty printer (otherwise, there might be multiple
2756 * hostnames for the IP address and we might receive more).
2758 * @param cls the `struct PrettyPrinterContext *`
2759 * @param hostname hostname part of the address
2762 append_port (void *cls,
2763 const char *hostname)
2765 struct PrettyPrinterContext *ppc = cls;
2766 struct Plugin *plugin = ppc->plugin;
2769 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2770 "append_port called with hostname `%s'\n",
2772 if (NULL == hostname)
2774 /* Final call, done */
2775 ppc->resolver_handle = NULL;
2776 GNUNET_CONTAINER_DLL_remove (plugin->ppc_dll_head,
2777 plugin->ppc_dll_tail,
2779 ppc->asc (ppc->asc_cls,
2785 if (GNUNET_YES == ppc->ipv6)
2786 GNUNET_asprintf (&ret,
2793 GNUNET_asprintf (&ret,
2799 ppc->asc (ppc->asc_cls,
2807 * Convert the transports address to a nice, human-readable format.
2809 * @param cls closure with the `struct Plugin`
2810 * @param type name of the transport that generated the address
2811 * @param addr one of the addresses of the host, NULL for the last address
2812 * the specific address format depends on the transport
2813 * @param addrlen length of the @a addr
2814 * @param numeric should (IP) addresses be displayed in numeric form?
2815 * @param timeout after how long should we give up?
2816 * @param asc function to call on each string
2817 * @param asc_cls closure for @a asc
2820 tcp_plugin_address_pretty_printer (void *cls,
2825 struct GNUNET_TIME_Relative timeout,
2826 GNUNET_TRANSPORT_AddressStringCallback asc,
2829 struct Plugin *plugin = cls;
2830 struct PrettyPrinterContext *ppc;
2833 struct sockaddr_in a4;
2834 struct sockaddr_in6 a6;
2835 const struct IPv4TcpAddress *t4;
2836 const struct IPv6TcpAddress *t6;
2840 if (sizeof(struct IPv6TcpAddress) == addrlen)
2843 memset (&a6, 0, sizeof(a6));
2844 a6.sin6_family = AF_INET6;
2845 a6.sin6_port = t6->t6_port;
2846 GNUNET_memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
2847 port = ntohs (t6->t6_port);
2848 options = ntohl (t6->options);
2852 else if (sizeof(struct IPv4TcpAddress) == addrlen)
2855 memset (&a4, 0, sizeof(a4));
2856 a4.sin_family = AF_INET;
2857 a4.sin_port = t4->t4_port;
2858 a4.sin_addr.s_addr = t4->ipv4_addr;
2859 port = ntohs (t4->t4_port);
2860 options = ntohl (t4->options);
2866 /* invalid address */
2867 LOG (GNUNET_ERROR_TYPE_WARNING,
2868 _("Unexpected address length: %u bytes\n"),
2869 (unsigned int) addrlen);
2870 asc (asc_cls, NULL, GNUNET_SYSERR);
2871 asc (asc_cls, NULL, GNUNET_OK);
2874 ppc = GNUNET_new (struct PrettyPrinterContext);
2875 ppc->plugin = plugin;
2876 if (addrlen == sizeof(struct IPv6TcpAddress))
2877 ppc->ipv6 = GNUNET_YES;
2879 ppc->ipv6 = GNUNET_NO;
2881 ppc->asc_cls = asc_cls;
2883 ppc->options = options;
2884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2885 "Starting DNS reverse lookup\n");
2886 ppc->resolver_handle = GNUNET_RESOLVER_hostname_get (sb,
2892 if (NULL == ppc->resolver_handle)
2898 GNUNET_CONTAINER_DLL_insert (plugin->ppc_dll_head,
2899 plugin->ppc_dll_tail,
2905 * Function that will be called to check if a binary address for this
2906 * plugin is well-formed and corresponds to an address for THIS peer
2907 * (as per our configuration). Naturally, if absolutely necessary,
2908 * plugins can be a bit conservative in their answer, but in general
2909 * plugins should make sure that the address does not redirect
2910 * traffic to a 3rd party that might try to man-in-the-middle our
2913 * @param cls closure, our `struct Plugin *`
2914 * @param addr pointer to the address
2915 * @param addrlen length of @a addr
2916 * @return #GNUNET_OK if this is a plausible address for this peer
2917 * and transport, #GNUNET_SYSERR if not
2920 tcp_plugin_check_address (void *cls,
2924 struct Plugin *plugin = cls;
2925 const struct IPv4TcpAddress *v4;
2926 const struct IPv6TcpAddress *v6;
2928 if ( (addrlen != sizeof(struct IPv4TcpAddress)) &&
2929 (addrlen != sizeof(struct IPv6TcpAddress)) )
2931 GNUNET_break_op (0);
2932 return GNUNET_SYSERR;
2935 if (addrlen == sizeof(struct IPv4TcpAddress))
2937 struct sockaddr_in s4;
2939 v4 = (const struct IPv4TcpAddress *) addr;
2940 if (0 != memcmp (&v4->options,
2945 return GNUNET_SYSERR;
2947 memset (&s4, 0, sizeof (s4));
2948 s4.sin_family = AF_INET;
2949 #if HAVE_SOCKADDR_IN_SIN_LEN
2950 s4.sin_len = sizeof (s4);
2952 s4.sin_port = v4->t4_port;
2953 s4.sin_addr.s_addr = v4->ipv4_addr;
2956 GNUNET_NAT_test_address (plugin->nat,
2958 sizeof (struct sockaddr_in)))
2959 return GNUNET_SYSERR;
2963 struct sockaddr_in6 s6;
2965 v6 = (const struct IPv6TcpAddress *) addr;
2966 if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
2968 GNUNET_break_op (0);
2969 return GNUNET_SYSERR;
2971 if (0 != memcmp (&v6->options,
2976 return GNUNET_SYSERR;
2978 memset (&s6, 0, sizeof (s6));
2979 s6.sin6_family = AF_INET6;
2980 #if HAVE_SOCKADDR_IN_SIN_LEN
2981 s6.sin6_len = sizeof (s6);
2983 s6.sin6_port = v6->t6_port;
2984 s6.sin6_addr = v6->ipv6_addr;
2987 GNUNET_NAT_test_address (plugin->nat,
2989 sizeof(struct sockaddr_in6)))
2990 return GNUNET_SYSERR;
2997 * We've received a nat probe from this peer via TCP. Finish
2998 * creating the client session and resume sending of queued
3001 * @param cls closure
3002 * @param client identification of the client
3003 * @param message the actual message
3006 handle_tcp_nat_probe (void *cls,
3007 struct GNUNET_SERVER_Client *client,
3008 const struct GNUNET_MessageHeader *message)
3010 struct Plugin *plugin = cls;
3011 struct GNUNET_ATS_Session *session;
3012 const struct TCP_NAT_ProbeMessage *tcp_nat_probe;
3015 struct IPv4TcpAddress *t4;
3016 struct IPv6TcpAddress *t6;
3017 const struct sockaddr_in *s4;
3018 const struct sockaddr_in6 *s6;
3020 LOG (GNUNET_ERROR_TYPE_DEBUG,
3021 "Received NAT probe\n");
3022 /* We have received a TCP NAT probe, meaning we (hopefully) initiated
3023 * a connection to this peer by running gnunet-nat-client. This peer
3024 * received the punch message and now wants us to use the new connection
3025 * as the default for that peer. Do so and then send a WELCOME message
3026 * so we can really be connected!
3028 if (ntohs (message->size) != sizeof(struct TCP_NAT_ProbeMessage))
3031 GNUNET_SERVER_receive_done (client,
3036 tcp_nat_probe = (const struct TCP_NAT_ProbeMessage *) message;
3037 if (0 == memcmp (&tcp_nat_probe->clientIdentity, plugin->env->my_identity,
3038 sizeof(struct GNUNET_PeerIdentity)))
3040 /* refuse connections from ourselves */
3041 GNUNET_SERVER_receive_done (client,
3046 session = GNUNET_CONTAINER_multipeermap_get (plugin->nat_wait_conns,
3047 &tcp_nat_probe->clientIdentity);
3048 if (NULL == session)
3050 LOG (GNUNET_ERROR_TYPE_DEBUG,
3051 "Did NOT find session for NAT probe!\n");
3052 GNUNET_SERVER_receive_done (client,
3056 LOG (GNUNET_ERROR_TYPE_DEBUG,
3057 "Found session for NAT probe!\n");
3059 if (NULL != session->nat_connection_timeout)
3061 GNUNET_SCHEDULER_cancel (session->nat_connection_timeout);
3062 session->nat_connection_timeout = NULL;
3066 GNUNET_SERVER_client_get_address (client,
3071 GNUNET_SERVER_receive_done (client,
3073 tcp_plugin_disconnect_session (plugin,
3077 GNUNET_assert (GNUNET_YES ==
3078 GNUNET_CONTAINER_multipeermap_remove (plugin->nat_wait_conns,
3079 &tcp_nat_probe->clientIdentity,
3081 GNUNET_SERVER_client_set_user_context (client,
3083 (void) GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
3086 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3087 session->last_activity = GNUNET_TIME_absolute_get ();
3088 LOG (GNUNET_ERROR_TYPE_DEBUG,
3089 "Found address `%s' for incoming connection\n",
3090 GNUNET_a2s (vaddr, alen));
3091 switch (((const struct sockaddr *) vaddr)->sa_family)
3095 t4 = GNUNET_new (struct IPv4TcpAddress);
3096 t4->options = htonl (TCP_OPTIONS_NONE);
3097 t4->t4_port = s4->sin_port;
3098 t4->ipv4_addr = s4->sin_addr.s_addr;
3099 session->address = GNUNET_HELLO_address_allocate (&tcp_nat_probe->clientIdentity,
3102 sizeof(struct IPv4TcpAddress),
3103 GNUNET_HELLO_ADDRESS_INFO_NONE);
3107 t6 = GNUNET_new (struct IPv6TcpAddress);
3108 t6->options = htonl (TCP_OPTIONS_NONE);
3109 t6->t6_port = s6->sin6_port;
3110 GNUNET_memcpy (&t6->ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
3111 session->address = GNUNET_HELLO_address_allocate (&tcp_nat_probe->clientIdentity,
3114 sizeof(struct IPv6TcpAddress),
3115 GNUNET_HELLO_ADDRESS_INFO_NONE);
3119 LOG(GNUNET_ERROR_TYPE_DEBUG,
3120 "Bad address for incoming connection!\n");
3122 GNUNET_SERVER_receive_done (client,
3124 tcp_plugin_disconnect_session (plugin,
3128 GNUNET_free (vaddr);
3129 GNUNET_break (NULL == session->client);
3130 session->client = client;
3131 GNUNET_STATISTICS_update (plugin->env->stats,
3132 gettext_noop ("# TCP sessions active"),
3135 process_pending_messages (session);
3136 GNUNET_SERVER_receive_done (client,
3142 * We've received a welcome from this peer via TCP. Possibly create a
3143 * fresh client record and send back our welcome.
3145 * @param cls closure
3146 * @param client identification of the client
3147 * @param message the actual message
3150 handle_tcp_welcome (void *cls,
3151 struct GNUNET_SERVER_Client *client,
3152 const struct GNUNET_MessageHeader *message)
3154 struct Plugin *plugin = cls;
3155 const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
3156 struct GNUNET_HELLO_Address *address;
3157 struct GNUNET_ATS_Session *session;
3160 struct IPv4TcpAddress t4;
3161 struct IPv6TcpAddress t6;
3162 const struct sockaddr_in *s4;
3163 const struct sockaddr_in6 *s6;
3165 if (0 == memcmp (&wm->clientIdentity,
3166 plugin->env->my_identity,
3167 sizeof(struct GNUNET_PeerIdentity)))
3169 /* refuse connections from ourselves */
3171 GNUNET_SERVER_client_get_address (client,
3175 LOG (GNUNET_ERROR_TYPE_INFO,
3176 "Received WELCOME message from my own identity `%s' on address `%s'\n",
3177 GNUNET_i2s (&wm->clientIdentity),
3178 GNUNET_a2s (vaddr, alen));
3179 GNUNET_free (vaddr);
3181 GNUNET_SERVER_receive_done (client,
3187 GNUNET_SERVER_client_get_address (client,
3191 LOG(GNUNET_ERROR_TYPE_DEBUG,
3192 "Received WELCOME message from `%s' on address `%s'\n",
3193 GNUNET_i2s (&wm->clientIdentity),
3194 GNUNET_a2s (vaddr, alen));
3195 GNUNET_free (vaddr);
3197 GNUNET_STATISTICS_update (plugin->env->stats,
3198 gettext_noop ("# TCP WELCOME messages received"),
3201 session = lookup_session_by_client (plugin,
3203 if (NULL != session)
3206 GNUNET_SERVER_client_get_address (client,
3210 LOG (GNUNET_ERROR_TYPE_DEBUG,
3211 "Found existing session %p for peer `%s'\n",
3213 GNUNET_a2s (vaddr, alen));
3214 GNUNET_free (vaddr);
3220 GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
3222 if (alen == sizeof(struct sockaddr_in))
3225 memset (&t4, '\0', sizeof (t4));
3226 t4.options = htonl (TCP_OPTIONS_NONE);
3227 t4.t4_port = s4->sin_port;
3228 t4.ipv4_addr = s4->sin_addr.s_addr;
3229 address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
3233 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
3235 else if (alen == sizeof(struct sockaddr_in6))
3238 memset (&t6, '\0', sizeof (t6));
3239 t6.options = htonl (TCP_OPTIONS_NONE);
3240 t6.t6_port = s6->sin6_port;
3241 GNUNET_memcpy (&t6.ipv6_addr, &s6->sin6_addr, sizeof(struct in6_addr));
3242 address = GNUNET_HELLO_address_allocate (&wm->clientIdentity,
3246 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
3251 GNUNET_free_non_null (vaddr);
3252 GNUNET_SERVER_receive_done (client,
3256 session = create_session (plugin,
3258 plugin->env->get_address_type (plugin->env->cls,
3263 GNUNET_break (GNUNET_ATS_NET_UNSPECIFIED != session->scope);
3264 GNUNET_HELLO_address_free (address);
3265 LOG (GNUNET_ERROR_TYPE_DEBUG,
3266 "Creating new%s session %p for peer `%s' client %p\n",
3267 GNUNET_HELLO_address_check_option (session->address,
3268 GNUNET_HELLO_ADDRESS_INFO_INBOUND)
3271 tcp_plugin_address_to_string (plugin,
3272 session->address->address,
3273 session->address->address_length),
3275 GNUNET_free (vaddr);
3276 (void) GNUNET_CONTAINER_multipeermap_put (plugin->sessionmap,
3279 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
3280 /* Notify transport and ATS about new session */
3281 plugin->env->session_start (plugin->env->cls,
3288 LOG(GNUNET_ERROR_TYPE_DEBUG,
3289 "Did not obtain TCP socket address for incoming connection\n");
3291 GNUNET_SERVER_receive_done (client,
3297 if (GNUNET_YES != session->expecting_welcome)
3299 GNUNET_break_op (0);
3300 GNUNET_SERVER_receive_done (client,
3304 session->last_activity = GNUNET_TIME_absolute_get ();
3305 session->expecting_welcome = GNUNET_NO;
3307 process_pending_messages (session);
3308 GNUNET_SERVER_client_set_timeout (client,
3309 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3310 GNUNET_SERVER_receive_done (client,
3316 * We've received data for this peer via TCP. Unbox,
3317 * compute latency and forward.
3319 * @param cls closure
3320 * @param client identification of the client
3321 * @param message the actual message
3324 handle_tcp_data (void *cls,
3325 struct GNUNET_SERVER_Client *client,
3326 const struct GNUNET_MessageHeader *message)
3328 struct Plugin *plugin = cls;
3329 struct GNUNET_ATS_Session *session;
3330 struct GNUNET_TIME_Relative delay;
3333 type = ntohs (message->type);
3334 if ( (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == type) ||
3335 (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE == type) )
3337 /* We don't want to propagate WELCOME and NAT Probe messages up! */
3338 GNUNET_SERVER_receive_done (client,
3342 session = lookup_session_by_client (plugin, client);
3343 if (NULL == session)
3345 /* No inbound session found */
3349 GNUNET_assert (GNUNET_OK ==
3350 GNUNET_SERVER_client_get_address (client,
3353 LOG (GNUNET_ERROR_TYPE_ERROR,
3354 "Received unexpected %u bytes of type %u from `%s'\n",
3355 (unsigned int) ntohs (message->size),
3356 (unsigned int) ntohs (message->type),
3360 GNUNET_SERVER_receive_done (client,
3362 GNUNET_free_non_null (vaddr);
3365 if (GNUNET_YES == session->expecting_welcome)
3367 /* Session is expecting WELCOME message */
3371 GNUNET_SERVER_client_get_address (client,
3374 LOG (GNUNET_ERROR_TYPE_ERROR,
3375 "Received unexpected %u bytes of type %u from `%s'\n",
3376 (unsigned int) ntohs (message->size),
3377 (unsigned int) ntohs (message->type),
3378 GNUNET_a2s (vaddr, alen));
3380 GNUNET_SERVER_receive_done (client,
3382 GNUNET_free_non_null (vaddr);
3386 session->last_activity = GNUNET_TIME_absolute_get ();
3391 GNUNET_SERVER_client_get_address (client,
3394 LOG (GNUNET_ERROR_TYPE_DEBUG,
3395 "Passing %u bytes of type %u from `%s' at %s to transport service.\n",
3396 (unsigned int) ntohs (message->size),
3397 (unsigned int) ntohs (message->type),
3398 GNUNET_i2s (&session->target),
3399 GNUNET_a2s (vaddr, alen));
3400 GNUNET_free_non_null (vaddr);
3403 GNUNET_STATISTICS_update (plugin->env->stats,
3404 gettext_noop ("# bytes received via TCP"),
3405 ntohs (message->size),
3408 GNUNET_assert (GNUNET_CONTAINER_multipeermap_contains_value (plugin->sessionmap,
3411 delay = plugin->env->receive (plugin->env->cls,
3415 reschedule_session_timeout (session);
3416 if (0 == delay.rel_value_us)
3418 GNUNET_SERVER_receive_done (client,
3423 LOG (GNUNET_ERROR_TYPE_DEBUG,
3424 "Throttling receiving from `%s' for %s\n",
3425 GNUNET_i2s (&session->target),
3426 GNUNET_STRINGS_relative_time_to_string (delay,
3428 GNUNET_SERVER_disable_receive_done_warning (client);
3429 GNUNET_assert (NULL == session->receive_delay_task);
3430 session->receive_delay_task = GNUNET_SCHEDULER_add_delayed (delay,
3438 * Function called whenever a peer is connected on the "SERVER" level.
3439 * Increments number of active connections and suspends server if we
3440 * have reached the limit.
3442 * @param cls closure
3443 * @param client identification of the client
3446 connect_notify (void *cls,
3447 struct GNUNET_SERVER_Client *client)
3449 struct Plugin *plugin = cls;
3453 plugin->cur_connections++;
3454 GNUNET_STATISTICS_set (plugin->env->stats,
3455 gettext_noop ("# TCP server connections active"),
3456 plugin->cur_connections,
3458 GNUNET_STATISTICS_update (plugin->env->stats,
3459 gettext_noop ("# TCP server connect events"),
3462 if (plugin->cur_connections != plugin->max_connections)
3464 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3465 _("TCP connection limit reached, suspending server\n"));
3466 GNUNET_STATISTICS_update (plugin->env->stats,
3467 gettext_noop ("# TCP service suspended"),
3470 GNUNET_SERVER_suspend (plugin->server); /* Maximum number of connections rechead */
3475 * Function called whenever a peer is disconnected on the "SERVER"
3476 * level. Cleans up the connection, decrements number of active
3477 * connections and if applicable resumes listening.
3479 * @param cls closure
3480 * @param client identification of the client
3483 disconnect_notify (void *cls,
3484 struct GNUNET_SERVER_Client *client)
3486 struct Plugin *plugin = cls;
3487 struct GNUNET_ATS_Session *session;
3491 GNUNET_assert (plugin->cur_connections >= 1);
3492 plugin->cur_connections--;
3493 session = lookup_session_by_client (plugin,
3495 if (NULL == session)
3496 return; /* unknown, nothing to do */
3497 LOG (GNUNET_ERROR_TYPE_DEBUG,
3498 "Destroying session of `%s' with %s due to network-level disconnect.\n",
3499 GNUNET_i2s (&session->target),
3500 tcp_plugin_address_to_string (session->plugin,
3501 session->address->address,
3502 session->address->address_length));
3504 if (plugin->cur_connections == plugin->max_connections)
3506 GNUNET_STATISTICS_update (session->plugin->env->stats,
3507 gettext_noop ("# TCP service resumed"),
3510 GNUNET_SERVER_resume (plugin->server); /* Resume server */
3512 GNUNET_STATISTICS_set (plugin->env->stats,
3513 gettext_noop ("# TCP server connections active"),
3514 plugin->cur_connections,
3516 GNUNET_STATISTICS_update (session->plugin->env->stats,
3517 gettext_noop ("# network-level TCP disconnect events"),
3520 tcp_plugin_disconnect_session (plugin,
3526 * We can now send a probe message, copy into buffer to really send.
3528 * @param cls closure, a `struct TCPProbeContext`
3529 * @param size max size to copy
3530 * @param buf buffer to copy message to
3531 * @return number of bytes copied into @a buf
3534 notify_send_probe (void *cls,
3538 struct TCPProbeContext *tcp_probe_ctx = cls;
3539 struct Plugin *plugin = tcp_probe_ctx->plugin;
3542 tcp_probe_ctx->transmit_handle = NULL;
3543 GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
3548 GNUNET_CONNECTION_destroy (tcp_probe_ctx->sock);
3549 GNUNET_free(tcp_probe_ctx);
3552 GNUNET_assert(size >= sizeof(tcp_probe_ctx->message));
3554 &tcp_probe_ctx->message,
3555 sizeof(tcp_probe_ctx->message));
3556 GNUNET_SERVER_connect_socket (tcp_probe_ctx->plugin->server,
3557 tcp_probe_ctx->sock);
3558 ret = sizeof(tcp_probe_ctx->message);
3559 GNUNET_free (tcp_probe_ctx);
3565 * Function called by the NAT subsystem suggesting another peer wants
3566 * to connect to us via connection reversal. Try to connect back to the
3569 * @param cls closure
3570 * @param addr address to try
3571 * @param addrlen number of bytes in @a addr
3574 try_connection_reversal (void *cls,
3575 const struct sockaddr *addr,
3578 struct Plugin *plugin = cls;
3579 struct GNUNET_CONNECTION_Handle *sock;
3580 struct TCPProbeContext *tcp_probe_ctx;
3583 * We have received an ICMP response, ostensibly from a peer
3584 * that wants to connect to us! Send a message to establish a connection.
3586 sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET,
3591 /* failed for some odd reason (out of sockets?); ignore attempt */
3595 tcp_probe_ctx = GNUNET_new (struct TCPProbeContext);
3596 tcp_probe_ctx->message.header.size
3597 = htons (sizeof (struct TCP_NAT_ProbeMessage));
3598 tcp_probe_ctx->message.header.type
3599 = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
3600 tcp_probe_ctx->message.clientIdentity
3601 = *plugin->env->my_identity;
3602 tcp_probe_ctx->plugin = plugin;
3603 tcp_probe_ctx->sock = sock;
3604 GNUNET_CONTAINER_DLL_insert (plugin->probe_head,
3607 tcp_probe_ctx->transmit_handle
3608 = GNUNET_CONNECTION_notify_transmit_ready (sock,
3609 ntohs (tcp_probe_ctx->message.header.size),
3610 GNUNET_TIME_UNIT_FOREVER_REL,
3617 * Function obtain the network type for a session
3619 * @param cls closure (`struct Plugin *`)
3620 * @param session the session
3621 * @return the network type in HBO or #GNUNET_SYSERR
3623 static enum GNUNET_ATS_Network_Type
3624 tcp_plugin_get_network (void *cls,
3625 struct GNUNET_ATS_Session *session)
3627 return session->scope;
3632 * Function obtain the network type for an address.
3634 * @param cls closure (`struct Plugin *`)
3635 * @param address the address
3636 * @return the network type
3638 static enum GNUNET_ATS_Network_Type
3639 tcp_plugin_get_network_for_address (void *cls,
3640 const struct GNUNET_HELLO_Address *address)
3642 struct Plugin *plugin = cls;
3644 struct sockaddr_in a4;
3645 struct sockaddr_in6 a6;
3646 const struct IPv4TcpAddress *t4;
3647 const struct IPv6TcpAddress *t6;
3651 addrlen = address->address_length;
3652 if (addrlen == sizeof(struct IPv6TcpAddress))
3654 GNUNET_assert (NULL != address->address); /* make static analysis happy */
3655 t6 = address->address;
3656 memset (&a6, 0, sizeof(a6));
3657 #if HAVE_SOCKADDR_IN_SIN_LEN
3658 a6.sin6_len = sizeof (a6);
3660 a6.sin6_family = AF_INET6;
3661 a6.sin6_port = t6->t6_port;
3662 GNUNET_memcpy (&a6.sin6_addr, &t6->ipv6_addr, sizeof(struct in6_addr));
3666 else if (addrlen == sizeof(struct IPv4TcpAddress))
3668 GNUNET_assert (NULL != address->address); /* make static analysis happy */
3669 t4 = address->address;
3670 memset (&a4, 0, sizeof(a4));
3671 #if HAVE_SOCKADDR_IN_SIN_LEN
3672 a4.sin_len = sizeof (a4);
3674 a4.sin_family = AF_INET;
3675 a4.sin_port = t4->t4_port;
3676 a4.sin_addr.s_addr = t4->ipv4_addr;
3683 return GNUNET_ATS_NET_UNSPECIFIED;
3685 return plugin->env->get_address_type (plugin->env->cls,
3692 * Return information about the given session to the
3695 * @param cls the `struct Plugin` with the monitor callback (`sic`)
3696 * @param peer peer we send information about
3697 * @param value our `struct GNUNET_ATS_Session` to send information about
3698 * @return #GNUNET_OK (continue to iterate)
3701 send_session_info_iter (void *cls,
3702 const struct GNUNET_PeerIdentity *peer,
3705 struct Plugin *plugin = cls;
3706 struct GNUNET_ATS_Session *session = value;
3708 notify_session_monitor (plugin,
3710 GNUNET_TRANSPORT_SS_INIT);
3711 /* FIXME: cannot tell if this is up or not from current
3713 notify_session_monitor (plugin,
3715 GNUNET_TRANSPORT_SS_UP);
3721 * Begin monitoring sessions of a plugin. There can only
3722 * be one active monitor per plugin (i.e. if there are
3723 * multiple monitors, the transport service needs to
3724 * multiplex the generated events over all of them).
3726 * @param cls closure of the plugin
3727 * @param sic callback to invoke, NULL to disable monitor;
3728 * plugin will being by iterating over all active
3729 * sessions immediately and then enter monitor mode
3730 * @param sic_cls closure for @a sic
3733 tcp_plugin_setup_monitor (void *cls,
3734 GNUNET_TRANSPORT_SessionInfoCallback sic,
3737 struct Plugin *plugin = cls;
3740 plugin->sic_cls = sic_cls;
3743 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
3744 &send_session_info_iter,
3746 /* signal end of first iteration */
3747 sic (sic_cls, NULL, NULL);
3753 * Entry point for the plugin.
3755 * @param cls closure, the `struct GNUNET_TRANSPORT_PluginEnvironment *`
3756 * @return the `struct GNUNET_TRANSPORT_PluginFunctions *` or NULL on error
3759 libgnunet_plugin_transport_tcp_init (void *cls)
3761 static const struct GNUNET_SERVER_MessageHandler my_handlers[] = {
3762 { &handle_tcp_welcome, NULL,
3763 GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
3764 sizeof(struct WelcomeMessage) },
3765 { &handle_tcp_nat_probe, NULL,
3766 GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE,
3767 sizeof(struct TCP_NAT_ProbeMessage) },
3768 { &handle_tcp_data, NULL,
3769 GNUNET_MESSAGE_TYPE_ALL, 0 },
3770 { NULL, NULL, 0, 0 }
3772 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3773 struct GNUNET_TRANSPORT_PluginFunctions *api;
3774 struct Plugin *plugin;
3775 struct LEGACY_SERVICE_Context *service;
3776 unsigned long long aport;
3777 unsigned long long bport;
3778 unsigned long long max_connections;
3780 struct GNUNET_TIME_Relative idle_timeout;
3782 struct GNUNET_NETWORK_Handle *const*lsocks;
3786 struct sockaddr **addrs;
3787 socklen_t *addrlens;
3789 if (NULL == env->receive)
3791 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
3792 initialze the plugin or the API */
3793 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3795 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
3796 api->address_to_string = &tcp_plugin_address_to_string;
3797 api->string_to_address = &tcp_plugin_string_to_address;
3801 GNUNET_assert (NULL != env->cfg);
3803 GNUNET_CONFIGURATION_get_value_number (env->cfg,
3807 max_connections = 128;
3811 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
3815 GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-tcp",
3816 "ADVERTISED-PORT", &aport)) &&
3819 LOG(GNUNET_ERROR_TYPE_ERROR,
3820 _("Require valid port number for service `%s' in configuration!\n"),
3830 service = LEGACY_SERVICE_start ("transport-tcp",
3832 LEGACY_SERVICE_OPTION_NONE);
3833 if (NULL == service)
3835 LOG (GNUNET_ERROR_TYPE_WARNING,
3836 _("Failed to start service.\n"));
3844 plugin = GNUNET_new (struct Plugin);
3845 plugin->sessionmap = GNUNET_CONTAINER_multipeermap_create (max_connections,
3847 plugin->max_connections = max_connections;
3848 plugin->open_port = bport;
3849 plugin->adv_port = aport;
3851 plugin->my_welcome.header.size = htons (sizeof(struct WelcomeMessage));
3852 plugin->my_welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
3853 plugin->my_welcome.clientIdentity = *plugin->env->my_identity;
3855 if ( (NULL != service) &&
3857 GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
3862 plugin->myoptions |= TCP_OPTIONS_TCP_STEALTH;
3863 lsocks = LEGACY_SERVICE_get_listen_sockets (service);
3866 uint32_t len = sizeof (struct WelcomeMessage);
3868 for (i=0;NULL!=lsocks[i];i++)
3871 GNUNET_NETWORK_socket_setsockopt (lsocks[i],
3875 sizeof (struct GNUNET_PeerIdentity))) ||
3877 GNUNET_NETWORK_socket_setsockopt (lsocks[i],
3879 TCP_STEALTH_INTEGRITY_LEN,
3883 /* TCP STEALTH not supported by kernel */
3884 GNUNET_assert (0 == i);
3885 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3886 _("TCP_STEALTH not supported on this platform.\n"));
3892 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3893 _("TCP_STEALTH not supported on this platform.\n"));
3898 if ( (NULL != service) &&
3901 get_server_addresses ("transport-tcp",
3906 for (ret = ret_s-1; ret >= 0; ret--)
3907 LOG (GNUNET_ERROR_TYPE_INFO,
3908 "Binding to address `%s'\n",
3909 GNUNET_a2s (addrs[ret], addrlens[ret]));
3911 = GNUNET_NAT_register (env->cfg,
3914 (unsigned int) ret_s,
3915 (const struct sockaddr **) addrs,
3917 &tcp_nat_port_map_callback,
3918 &try_connection_reversal,
3920 for (ret = ret_s -1; ret >= 0; ret--)
3921 GNUNET_free (addrs[ret]);
3922 GNUNET_free_non_null (addrs);
3923 GNUNET_free_non_null (addrlens);
3927 plugin->nat = GNUNET_NAT_register (plugin->env->cfg,
3934 &try_connection_reversal,
3937 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3939 api->send = &tcp_plugin_send;
3940 api->get_session = &tcp_plugin_get_session;
3941 api->disconnect_session = &tcp_plugin_disconnect_session;
3942 api->query_keepalive_factor = &tcp_plugin_query_keepalive_factor;
3943 api->disconnect_peer = &tcp_plugin_disconnect;
3944 api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
3945 api->check_address = &tcp_plugin_check_address;
3946 api->address_to_string = &tcp_plugin_address_to_string;
3947 api->string_to_address = &tcp_plugin_string_to_address;
3948 api->get_network = &tcp_plugin_get_network;
3949 api->get_network_for_address = &tcp_plugin_get_network_for_address;
3950 api->update_session_timeout = &tcp_plugin_update_session_timeout;
3951 api->update_inbound_delay = &tcp_plugin_update_inbound_delay;
3952 api->setup_monitor = &tcp_plugin_setup_monitor;
3953 plugin->service = service;
3954 if (NULL != service)
3956 plugin->server = LEGACY_SERVICE_get_server (service);
3961 GNUNET_CONFIGURATION_get_value_time (env->cfg,
3966 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
3972 = GNUNET_SERVER_create_with_sockets (NULL,
3978 plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
3979 GNUNET_memcpy (plugin->handlers,
3981 sizeof(my_handlers));
3982 for (i = 0;i < sizeof(my_handlers) / sizeof(struct GNUNET_SERVER_MessageHandler);i++)
3983 plugin->handlers[i].callback_cls = plugin;
3985 GNUNET_SERVER_add_handlers (plugin->server,
3987 GNUNET_SERVER_connect_notify (plugin->server,
3990 GNUNET_SERVER_disconnect_notify (plugin->server,
3993 plugin->nat_wait_conns = GNUNET_CONTAINER_multipeermap_create (16,
3996 LOG (GNUNET_ERROR_TYPE_INFO,
3997 _("TCP transport listening on port %llu\n"),
4000 LOG (GNUNET_ERROR_TYPE_INFO,
4001 _("TCP transport not listening on any port (client only)\n"));
4002 if ( (aport != bport) &&
4004 LOG (GNUNET_ERROR_TYPE_INFO,
4005 _("TCP transport advertises itself as being on port %llu\n"),
4007 /* Initially set connections to 0 */
4008 GNUNET_STATISTICS_set (plugin->env->stats,
4009 gettext_noop ("# TCP sessions active"),
4015 if (NULL != plugin->nat)
4016 GNUNET_NAT_unregister (plugin->nat);
4017 GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
4018 if (NULL != service)
4019 LEGACY_SERVICE_stop (service);
4020 GNUNET_free (plugin);
4021 GNUNET_free_non_null (api);
4027 * Exit point from the plugin.
4029 * @param cls the `struct GNUNET_TRANSPORT_PluginFunctions`
4033 libgnunet_plugin_transport_tcp_done (void *cls)
4035 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
4036 struct Plugin *plugin = api->cls;
4037 struct TCPProbeContext *tcp_probe;
4038 struct PrettyPrinterContext *cur;
4039 struct PrettyPrinterContext *next;
4046 LOG (GNUNET_ERROR_TYPE_DEBUG,
4047 "Shutting down TCP plugin\n");
4049 /* Removing leftover sessions */
4050 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessionmap,
4051 &session_disconnect_it,
4053 /* Removing leftover NAT sessions */
4054 GNUNET_CONTAINER_multipeermap_iterate (plugin->nat_wait_conns,
4055 &session_disconnect_it,
4058 for (cur = plugin->ppc_dll_head; NULL != cur; cur = next)
4061 GNUNET_CONTAINER_DLL_remove (plugin->ppc_dll_head,
4062 plugin->ppc_dll_tail,
4064 GNUNET_RESOLVER_request_cancel (cur->resolver_handle);
4065 cur->asc (cur->asc_cls,
4071 if (NULL != plugin->service)
4072 LEGACY_SERVICE_stop (plugin->service);
4074 GNUNET_SERVER_destroy (plugin->server);
4075 GNUNET_free (plugin->handlers);
4076 if (NULL != plugin->nat)
4077 GNUNET_NAT_unregister (plugin->nat);
4078 while (NULL != (tcp_probe = plugin->probe_head))
4080 GNUNET_CONTAINER_DLL_remove (plugin->probe_head,
4083 GNUNET_CONNECTION_destroy (tcp_probe->sock);
4084 GNUNET_free (tcp_probe);
4086 GNUNET_CONTAINER_multipeermap_destroy (plugin->nat_wait_conns);
4087 GNUNET_CONTAINER_multipeermap_destroy (plugin->sessionmap);
4088 GNUNET_break (0 == plugin->cur_connections);
4089 GNUNET_free (plugin);
4094 /* end of plugin_transport_tcp.c */