aboutsummaryrefslogtreecommitdiff
path: root/src/util
diff options
context:
space:
mode:
Diffstat (limited to 'src/util')
-rw-r--r--src/util/Makefile.am83
-rw-r--r--src/util/connection.c1648
-rw-r--r--src/util/helper.c23
-rw-r--r--src/util/mq.c86
-rw-r--r--src/util/server.c1752
-rw-r--r--src/util/service.c1697
-rw-r--r--src/util/test_connection.c167
-rw-r--r--src/util/test_connection_addressing.c186
-rw-r--r--src/util/test_connection_receive_cancel.c160
-rw-r--r--src/util/test_connection_timeout.c129
-rw-r--r--src/util/test_connection_timeout_no_connect.c76
-rw-r--r--src/util/test_connection_transmit_cancel.c76
-rw-r--r--src/util/test_server.c302
-rw-r--r--src/util/test_server_disconnect.c166
-rw-r--r--src/util/test_server_mst_interrupt.c60
-rw-r--r--src/util/test_server_with_client.c198
-rw-r--r--src/util/test_server_with_client_unix.c176
17 files changed, 15 insertions, 6970 deletions
diff --git a/src/util/Makefile.am b/src/util/Makefile.am
index df319fe77..4418fcfee 100644
--- a/src/util/Makefile.am
+++ b/src/util/Makefile.am
@@ -68,7 +68,6 @@ libgnunetutil_la_SOURCES = \
68 common_logging.c \ 68 common_logging.c \
69 configuration.c \ 69 configuration.c \
70 configuration_loader.c \ 70 configuration_loader.c \
71 connection.c \
72 container_bloomfilter.c \ 71 container_bloomfilter.c \
73 container_heap.c \ 72 container_heap.c \
74 container_meta_data.c \ 73 container_meta_data.c \
@@ -108,16 +107,10 @@ libgnunetutil_la_SOURCES = \
108 program.c \ 107 program.c \
109 resolver_api.c resolver.h \ 108 resolver_api.c resolver.h \
110 scheduler.c \ 109 scheduler.c \
111 server.c \
112 server_mst.c \
113 server_nc.c \
114 server_tc.c \
115 service.c \
116 service_new.c \ 110 service_new.c \
117 signal.c \ 111 signal.c \
118 strings.c \ 112 strings.c \
119 time.c \ 113 time.c \
120 socks.c \
121 speedup.c speedup.h 114 speedup.c speedup.h
122 115
123libgnunetutil_la_LIBADD = \ 116libgnunetutil_la_LIBADD = \
@@ -263,14 +256,13 @@ if HAVE_BENCHMARKS
263endif 256endif
264 257
265if HAVE_SSH_KEY 258if HAVE_SSH_KEY
266 SSH_USING_TESTS = test_socks.nc 259# SSH_USING_TESTS = test_socks.nc
267endif 260endif
268 261
269check_PROGRAMS = \ 262check_PROGRAMS = \
270 test_bio \ 263 test_bio \
271 test_client.nc \ 264 test_client.nc \
272 $(TEST_CLIENT_UNIX_NC) \ 265 $(TEST_CLIENT_UNIX_NC) \
273 $(SSH_USING_TESTS) \
274 test_common_allocation \ 266 test_common_allocation \
275 test_common_endian \ 267 test_common_endian \
276 test_common_logging \ 268 test_common_logging \
@@ -298,12 +290,6 @@ check_PROGRAMS = \
298 test_crypto_rsa \ 290 test_crypto_rsa \
299 test_disk \ 291 test_disk \
300 test_getopt \ 292 test_getopt \
301 test_connection.nc \
302 test_connection_addressing.nc \
303 test_connection_receive_cancel.nc \
304 test_connection_timeout.nc \
305 test_connection_timeout_no_connect.nc \
306 test_connection_transmit_cancel.nc \
307 test_mq \ 293 test_mq \
308 test_os_network \ 294 test_os_network \
309 test_peer \ 295 test_peer \
@@ -312,11 +298,6 @@ check_PROGRAMS = \
312 test_resolver_api.nc \ 298 test_resolver_api.nc \
313 test_scheduler \ 299 test_scheduler \
314 test_scheduler_delay \ 300 test_scheduler_delay \
315 test_server.nc \
316 test_server_disconnect.nc \
317 test_server_with_client.nc \
318 test_server_mst_interrupt.nc \
319 $(SERVER_CLIENT_UNIX) \
320 test_service \ 301 test_service \
321 test_strings \ 302 test_strings \
322 test_strings_to_data \ 303 test_strings_to_data \
@@ -337,11 +318,6 @@ test_connection_transmit_cancel.log: test_connection_timeout_no_connect.log
337test_connection_receive_cancel.log: test_connection_transmit_cancel.log 318test_connection_receive_cancel.log: test_connection_transmit_cancel.log
338test_connection_timeout.log: test_connection_receive_cancel.log 319test_connection_timeout.log: test_connection_receive_cancel.log
339test_resolver_api.log: test_connection_timeout.log 320test_resolver_api.log: test_connection_timeout.log
340test_server.log: test_resolver_api.log
341test_server_disconnect.log: test_server.log
342test_server_with_client.log: test_server_disconnect.log
343test_server_mst_interrupt.log: test_server_with_client.log
344test_client_unix.log: test_server_mst_interrupt.log
345 321
346test_bio_SOURCES = \ 322test_bio_SOURCES = \
347 test_bio.c 323 test_bio.c
@@ -518,36 +494,6 @@ test_getopt_SOURCES = \
518test_getopt_LDADD = \ 494test_getopt_LDADD = \
519 libgnunetutil.la 495 libgnunetutil.la
520 496
521test_connection_nc_SOURCES = \
522 test_connection.c
523test_connection_nc_LDADD = \
524 libgnunetutil.la
525
526test_connection_addressing_nc_SOURCES = \
527 test_connection_addressing.c
528test_connection_addressing_nc_LDADD = \
529 libgnunetutil.la
530
531test_connection_receive_cancel_nc_SOURCES = \
532 test_connection_receive_cancel.c
533test_connection_receive_cancel_nc_LDADD = \
534 libgnunetutil.la
535
536test_connection_timeout_nc_SOURCES = \
537 test_connection_timeout.c
538test_connection_timeout_nc_LDADD = \
539 libgnunetutil.la
540
541test_connection_timeout_no_connect_nc_SOURCES = \
542 test_connection_timeout_no_connect.c
543test_connection_timeout_no_connect_nc_LDADD = \
544 libgnunetutil.la
545
546test_connection_transmit_cancel_nc_SOURCES = \
547 test_connection_transmit_cancel.c
548test_connection_transmit_cancel_nc_LDADD = \
549 libgnunetutil.la
550
551test_mq_SOURCES = \ 497test_mq_SOURCES = \
552 test_mq.c 498 test_mq.c
553test_mq_LDADD = \ 499test_mq_LDADD = \
@@ -588,32 +534,6 @@ test_scheduler_delay_SOURCES = \
588test_scheduler_delay_LDADD = \ 534test_scheduler_delay_LDADD = \
589 libgnunetutil.la 535 libgnunetutil.la
590 536
591test_server_mst_interrupt_nc_SOURCES = \
592 test_server_mst_interrupt.c
593test_server_mst_interrupt_nc_LDADD = \
594 libgnunetutil.la
595
596test_server_nc_SOURCES = \
597 test_server.c
598test_server_nc_LDADD = \
599 libgnunetutil.la
600
601test_server_disconnect_nc_SOURCES = \
602 test_server_disconnect.c
603test_server_disconnect_nc_LDADD = \
604 libgnunetutil.la
605
606test_server_with_client_nc_SOURCES = \
607 test_server_with_client.c
608test_server_with_client_nc_LDADD = \
609 libgnunetutil.la
610
611test_server_with_client_unix_SOURCES = \
612 test_server_with_client_unix.c
613test_server_with_client_unix_LDADD = \
614 libgnunetutil.la
615
616
617test_service_SOURCES = \ 537test_service_SOURCES = \
618 test_service.c 538 test_service.c
619test_service_LDADD = \ 539test_service_LDADD = \
@@ -624,7 +544,6 @@ test_strings_SOURCES = \
624test_strings_LDADD = \ 544test_strings_LDADD = \
625 libgnunetutil.la 545 libgnunetutil.la
626 546
627
628test_strings_to_data_SOURCES = \ 547test_strings_to_data_SOURCES = \
629 test_strings_to_data.c 548 test_strings_to_data.c
630test_strings_to_data_LDADD = \ 549test_strings_to_data_LDADD = \
diff --git a/src/util/connection.c b/src/util/connection.c
deleted file mode 100644
index e822b264f..000000000
--- a/src/util/connection.c
+++ /dev/null
@@ -1,1648 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009-2013 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20
21/**
22 * @file util/connection.c
23 * @brief TCP connection management
24 * @author Christian Grothoff
25 *
26 * This code is rather complex. Only modify it if you
27 * 1) Have a NEW testcase showing that the new code
28 * is needed and correct
29 * 2) All EXISTING testcases pass with the new code
30 * These rules should apply in general, but for this
31 * module they are VERY, VERY important.
32 */
33#include "platform.h"
34#include "gnunet_util_lib.h"
35#include "gnunet_resolver_service.h"
36
37
38#define LOG(kind,...) GNUNET_log_from (kind, "util-connection", __VA_ARGS__)
39
40#define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-connection", syscall)
41
42
43/**
44 * Transmission handle. There can only be one for each connection.
45 */
46struct GNUNET_CONNECTION_TransmitHandle
47{
48
49 /**
50 * Function to call if the send buffer has notify_size
51 * bytes available.
52 */
53 GNUNET_CONNECTION_TransmitReadyNotify notify_ready;
54
55 /**
56 * Closure for notify_ready.
57 */
58 void *notify_ready_cls;
59
60 /**
61 * Our connection handle.
62 */
63 struct GNUNET_CONNECTION_Handle *connection;
64
65 /**
66 * Timeout for receiving (in absolute time).
67 */
68 struct GNUNET_TIME_Absolute transmit_timeout;
69
70 /**
71 * Task called on timeout.
72 */
73 struct GNUNET_SCHEDULER_Task * timeout_task;
74
75 /**
76 * At what number of bytes available in the
77 * write buffer should the notify method be called?
78 */
79 size_t notify_size;
80
81};
82
83
84/**
85 * During connect, we try multiple possible IP addresses
86 * to find out which one might work.
87 */
88struct AddressProbe
89{
90
91 /**
92 * This is a linked list.
93 */
94 struct AddressProbe *next;
95
96 /**
97 * This is a doubly-linked list.
98 */
99 struct AddressProbe *prev;
100
101 /**
102 * The address; do not free (allocated at the end of this struct).
103 */
104 const struct sockaddr *addr;
105
106 /**
107 * Underlying OS's socket.
108 */
109 struct GNUNET_NETWORK_Handle *sock;
110
111 /**
112 * Connection for which we are probing.
113 */
114 struct GNUNET_CONNECTION_Handle *connection;
115
116 /**
117 * Lenth of addr.
118 */
119 socklen_t addrlen;
120
121 /**
122 * Task waiting for the connection to finish connecting.
123 */
124 struct GNUNET_SCHEDULER_Task * task;
125};
126
127
128/**
129 * @brief handle for a network connection
130 */
131struct GNUNET_CONNECTION_Handle
132{
133
134 /**
135 * Configuration to use.
136 */
137 const struct GNUNET_CONFIGURATION_Handle *cfg;
138
139 /**
140 * Linked list of sockets we are currently trying out
141 * (during connect).
142 */
143 struct AddressProbe *ap_head;
144
145 /**
146 * Linked list of sockets we are currently trying out
147 * (during connect).
148 */
149 struct AddressProbe *ap_tail;
150
151 /**
152 * Network address of the other end-point, may be NULL.
153 */
154 struct sockaddr *addr;
155
156 /**
157 * Pointer to the hostname if connection was
158 * created using DNS lookup, otherwise NULL.
159 */
160 char *hostname;
161
162 /**
163 * Underlying OS's socket, set to NULL after fatal errors.
164 */
165 struct GNUNET_NETWORK_Handle *sock;
166
167 /**
168 * Function to call on data received, NULL if no receive is pending.
169 */
170 GNUNET_CONNECTION_Receiver receiver;
171
172 /**
173 * Closure for @e receiver.
174 */
175 void *receiver_cls;
176
177 /**
178 * Pointer to our write buffer.
179 */
180 char *write_buffer;
181
182 /**
183 * Current size of our @e write_buffer.
184 */
185 size_t write_buffer_size;
186
187 /**
188 * Current write-offset in @e write_buffer (where
189 * would we write next).
190 */
191 size_t write_buffer_off;
192
193 /**
194 * Current read-offset in @e write_buffer (how many
195 * bytes have already been sent).
196 */
197 size_t write_buffer_pos;
198
199 /**
200 * Length of @e addr.
201 */
202 socklen_t addrlen;
203
204 /**
205 * Read task that we may need to wait for.
206 */
207 struct GNUNET_SCHEDULER_Task *read_task;
208
209 /**
210 * Write task that we may need to wait for.
211 */
212 struct GNUNET_SCHEDULER_Task *write_task;
213
214 /**
215 * Handle to a pending DNS lookup request.
216 */
217 struct GNUNET_RESOLVER_RequestHandle *dns_active;
218
219 /**
220 * The handle we return for #GNUNET_CONNECTION_notify_transmit_ready().
221 */
222 struct GNUNET_CONNECTION_TransmitHandle nth;
223
224 /**
225 * Timeout for receiving (in absolute time).
226 */
227 struct GNUNET_TIME_Absolute receive_timeout;
228
229 /**
230 * Maximum number of bytes to read (for receiving).
231 */
232 size_t max;
233
234 /**
235 * Port to connect to.
236 */
237 uint16_t port;
238
239 /**
240 * When shutdown, do not ever actually close the socket, but
241 * free resources. Only should ever be set if using program
242 * termination as a signal (because only then will the leaked
243 * socket be freed!)
244 */
245 int8_t persist;
246
247 /**
248 * Usually 0. Set to 1 if this handle is in use, and should
249 * #GNUNET_CONNECTION_destroy() be called right now, the action needs
250 * to be deferred by setting it to -1.
251 */
252 int8_t destroy_later;
253
254 /**
255 * Handle to subsequent connection after proxy handshake completes,
256 */
257 struct GNUNET_CONNECTION_Handle *proxy_handshake;
258
259};
260
261
262/**
263 * Set the persist option on this connection handle. Indicates
264 * that the underlying socket or fd should never really be closed.
265 * Used for indicating process death.
266 *
267 * @param connection the connection to set persistent
268 */
269void
270GNUNET_CONNECTION_persist_ (struct GNUNET_CONNECTION_Handle *connection)
271{
272 connection->persist = GNUNET_YES;
273}
274
275
276/**
277 * Disable the "CORK" feature for communication with the given connection,
278 * forcing the OS to immediately flush the buffer on transmission
279 * instead of potentially buffering multiple messages. Essentially
280 * reduces the OS send buffers to zero.
281 * Used to make sure that the last messages sent through the connection
282 * reach the other side before the process is terminated.
283 *
284 * @param connection the connection to make flushing and blocking
285 * @return #GNUNET_OK on success
286 */
287int
288GNUNET_CONNECTION_disable_corking (struct GNUNET_CONNECTION_Handle *connection)
289{
290 return GNUNET_NETWORK_socket_disable_corking (connection->sock);
291}
292
293
294/**
295 * Create a connection handle by boxing an existing OS socket. The OS
296 * socket should henceforth be no longer used directly.
297 * #GNUNET_connection_destroy() will close it.
298 *
299 * @param osSocket existing socket to box
300 * @return the boxed connection handle
301 */
302struct GNUNET_CONNECTION_Handle *
303GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
304{
305 struct GNUNET_CONNECTION_Handle *connection;
306
307 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
308 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
309 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
310 connection->sock = osSocket;
311 return connection;
312}
313
314
315/**
316 * Create a connection handle by accepting on a listen socket. This
317 * function may block if the listen socket has no connection ready.
318 *
319 * @param access_cb function to use to check if access is allowed
320 * @param access_cb_cls closure for @a access_cb
321 * @param lsock listen socket
322 * @return the connection handle, NULL on error
323 */
324struct GNUNET_CONNECTION_Handle *
325GNUNET_CONNECTION_create_from_accept (GNUNET_CONNECTION_AccessCheck access_cb,
326 void *access_cb_cls,
327 struct GNUNET_NETWORK_Handle *lsock)
328{
329 struct GNUNET_CONNECTION_Handle *connection;
330 char addr[128];
331 socklen_t addrlen;
332 struct GNUNET_NETWORK_Handle *sock;
333 int aret;
334 struct sockaddr_in *v4;
335 struct sockaddr_in6 *v6;
336 struct sockaddr *sa;
337 void *uaddr;
338#ifdef SO_PEERCRED
339 struct ucred uc;
340 socklen_t olen;
341#endif
342 struct GNUNET_CONNECTION_Credentials *gcp;
343#if HAVE_GETPEEREID || defined(SO_PEERCRED) || HAVE_GETPEERUCRED
344 struct GNUNET_CONNECTION_Credentials gc;
345
346 gc.uid = 0;
347 gc.gid = 0;
348#endif
349
350 addrlen = sizeof (addr);
351 sock =
352 GNUNET_NETWORK_socket_accept (lsock,
353 (struct sockaddr *) &addr,
354 &addrlen);
355 if (NULL == sock)
356 {
357 if (EAGAIN != errno)
358 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
359 return NULL;
360 }
361 if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
362 {
363 GNUNET_break (0);
364 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
365 return NULL;
366 }
367
368 sa = (struct sockaddr *) addr;
369 v6 = (struct sockaddr_in6 *) addr;
370 if ( (AF_INET6 == sa->sa_family) &&
371 (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)) )
372 {
373 /* convert to V4 address */
374 v4 = GNUNET_new (struct sockaddr_in);
375 memset (v4, 0, sizeof (struct sockaddr_in));
376 v4->sin_family = AF_INET;
377#if HAVE_SOCKADDR_IN_SIN_LEN
378 v4->sin_len = (u_char) sizeof (struct sockaddr_in);
379#endif
380 GNUNET_memcpy (&v4->sin_addr,
381 &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
382 sizeof (struct in_addr)],
383 sizeof (struct in_addr));
384 v4->sin_port = v6->sin6_port;
385 uaddr = v4;
386 addrlen = sizeof (struct sockaddr_in);
387 }
388 else
389 {
390 uaddr = GNUNET_malloc (addrlen);
391 GNUNET_memcpy (uaddr, addr, addrlen);
392 }
393 gcp = NULL;
394 if (AF_UNIX == sa->sa_family)
395 {
396#if HAVE_GETPEEREID
397 /* most BSDs */
398 if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock),
399 &gc.uid,
400 &gc.gid))
401 gcp = &gc;
402#else
403#ifdef SO_PEERCRED
404 /* largely traditional GNU/Linux */
405 olen = sizeof (uc);
406 if ( (0 ==
407 getsockopt (GNUNET_NETWORK_get_fd (sock),
408 SOL_SOCKET,
409 SO_PEERCRED,
410 &uc,
411 &olen)) &&
412 (olen == sizeof (uc)) )
413 {
414 gc.uid = uc.uid;
415 gc.gid = uc.gid;
416 gcp = &gc;
417 }
418#else
419#if HAVE_GETPEERUCRED
420 /* this is for Solaris 10 */
421 ucred_t *uc;
422
423 uc = NULL;
424 if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
425 {
426 gc.uid = ucred_geteuid (uc);
427 gc.gid = ucred_getegid (uc);
428 gcp = &gc;
429 }
430 ucred_free (uc);
431#endif
432#endif
433#endif
434 }
435
436 if ( (NULL != access_cb) &&
437 (GNUNET_YES != (aret = access_cb (access_cb_cls,
438 gcp,
439 uaddr,
440 addrlen))) )
441 {
442 if (GNUNET_NO == aret)
443 LOG (GNUNET_ERROR_TYPE_INFO,
444 _("Access denied to `%s'\n"),
445 GNUNET_a2s (uaddr,
446 addrlen));
447 GNUNET_break (GNUNET_OK ==
448 GNUNET_NETWORK_socket_shutdown (sock,
449 SHUT_RDWR));
450 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
451 GNUNET_free (uaddr);
452 return NULL;
453 }
454 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
455 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
456 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
457 connection->addr = uaddr;
458 connection->addrlen = addrlen;
459 connection->sock = sock;
460 LOG (GNUNET_ERROR_TYPE_INFO,
461 _("Accepting connection from `%s': %p\n"),
462 GNUNET_a2s (uaddr,
463 addrlen),
464 connection);
465 return connection;
466}
467
468
469/**
470 * Obtain the network address of the other party.
471 *
472 * @param connection the client to get the address for
473 * @param addr where to store the address
474 * @param addrlen where to store the length of the @a addr
475 * @return #GNUNET_OK on success
476 */
477int
478GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
479 void **addr,
480 size_t *addrlen)
481{
482 if ((NULL == connection->addr) || (0 == connection->addrlen))
483 return GNUNET_NO;
484 *addr = GNUNET_malloc (connection->addrlen);
485 GNUNET_memcpy (*addr, connection->addr, connection->addrlen);
486 *addrlen = connection->addrlen;
487 return GNUNET_OK;
488}
489
490
491/**
492 * Tell the receiver callback that we had an IO error.
493 *
494 * @param connection connection to signal error
495 * @param errcode error code to send
496 */
497static void
498signal_receive_error (struct GNUNET_CONNECTION_Handle *connection,
499 int errcode)
500{
501 GNUNET_CONNECTION_Receiver receiver;
502
503 LOG (GNUNET_ERROR_TYPE_DEBUG,
504 "Receive encounters error (%s), connection closed (%p)\n",
505 STRERROR (errcode),
506 connection);
507 GNUNET_assert (NULL != (receiver = connection->receiver));
508 connection->receiver = NULL;
509 receiver (connection->receiver_cls,
510 NULL,
511 0,
512 connection->addr,
513 connection->addrlen,
514 errcode);
515}
516
517
518/**
519 * Tell the receiver callback that a timeout was reached.
520 *
521 * @param connection connection to signal for
522 */
523static void
524signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
525{
526 GNUNET_CONNECTION_Receiver receiver;
527
528 LOG (GNUNET_ERROR_TYPE_DEBUG,
529 "Connection signals timeout to receiver (%p)!\n",
530 connection);
531 GNUNET_assert (NULL != (receiver = connection->receiver));
532 connection->receiver = NULL;
533 receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
534}
535
536
537/**
538 * We failed to transmit data to the service, signal the error.
539 *
540 * @param connection handle that had trouble
541 * @param ecode error code (errno)
542 */
543static void
544signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
545 int ecode)
546{
547 GNUNET_CONNECTION_TransmitReadyNotify notify;
548
549 LOG (GNUNET_ERROR_TYPE_DEBUG,
550 "Transmission encounterd error (%s), connection closed (%p)\n",
551 STRERROR (ecode),
552 connection);
553 if (NULL != connection->sock)
554 {
555 (void) GNUNET_NETWORK_socket_shutdown (connection->sock,
556 SHUT_RDWR);
557 GNUNET_break (GNUNET_OK ==
558 GNUNET_NETWORK_socket_close (connection->sock));
559 connection->sock = NULL;
560 GNUNET_assert (NULL == connection->write_task);
561 }
562 if (NULL != connection->read_task)
563 {
564 /* send errors trigger read errors... */
565 GNUNET_SCHEDULER_cancel (connection->read_task);
566 connection->read_task = NULL;
567 signal_receive_timeout (connection);
568 return;
569 }
570 if (NULL == connection->nth.notify_ready)
571 return; /* nobody to tell about it */
572 notify = connection->nth.notify_ready;
573 connection->nth.notify_ready = NULL;
574 notify (connection->nth.notify_ready_cls,
575 0,
576 NULL);
577}
578
579
580/**
581 * We've failed for good to establish a connection (timeout or
582 * no more addresses to try).
583 *
584 * @param connection the connection we tried to establish
585 */
586static void
587connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
588{
589 LOG (GNUNET_ERROR_TYPE_INFO,
590 "Failed to establish TCP connection to `%s:%u', no further addresses to try.\n",
591 connection->hostname,
592 connection->port);
593 GNUNET_break (NULL == connection->ap_head);
594 GNUNET_break (NULL == connection->ap_tail);
595 GNUNET_break (GNUNET_NO == connection->dns_active);
596 GNUNET_break (NULL == connection->sock);
597 GNUNET_assert (NULL == connection->write_task);
598 GNUNET_assert (NULL == connection->proxy_handshake);
599
600 /* signal errors for jobs that used to wait on the connection */
601 connection->destroy_later = 1;
602 if (NULL != connection->receiver)
603 signal_receive_error (connection,
604 ECONNREFUSED);
605 if (NULL != connection->nth.notify_ready)
606 {
607 GNUNET_assert (NULL != connection->nth.timeout_task);
608 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
609 connection->nth.timeout_task = NULL;
610 signal_transmit_error (connection,
611 ECONNREFUSED);
612 }
613 if (-1 == connection->destroy_later)
614 {
615 /* do it now */
616 connection->destroy_later = 0;
617 GNUNET_CONNECTION_destroy (connection);
618 return;
619 }
620 connection->destroy_later = 0;
621}
622
623
624/**
625 * We are ready to transmit (or got a timeout).
626 *
627 * @param cls our connection handle
628 */
629static void
630transmit_ready (void *cls);
631
632
633/**
634 * This function is called once we either timeout or have data ready
635 * to read.
636 *
637 * @param cls connection to read from
638 */
639static void
640receive_ready (void *cls);
641
642
643/**
644 * We've succeeded in establishing a connection.
645 *
646 * @param connection the connection we tried to establish
647 */
648static void
649connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
650{
651 LOG (GNUNET_ERROR_TYPE_DEBUG,
652 "Connection to `%s' succeeded! (%p)\n",
653 GNUNET_a2s (connection->addr,
654 connection->addrlen),
655 connection);
656 /* trigger jobs that waited for the connection */
657 if (NULL != connection->receiver)
658 {
659 LOG (GNUNET_ERROR_TYPE_DEBUG,
660 "Connection succeeded, starting with receiving data (%p)\n",
661 connection);
662 GNUNET_assert (NULL == connection->read_task);
663 connection->read_task =
664 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
665 (connection->receive_timeout),
666 connection->sock,
667 &receive_ready, connection);
668 }
669 if (NULL != connection->nth.notify_ready)
670 {
671 LOG (GNUNET_ERROR_TYPE_DEBUG,
672 "Connection succeeded, starting with sending data (%p)\n",
673 connection);
674 GNUNET_assert (connection->nth.timeout_task != NULL);
675 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
676 connection->nth.timeout_task = NULL;
677 GNUNET_assert (connection->write_task == NULL);
678 connection->write_task =
679 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
680 (connection->nth.transmit_timeout), connection->sock,
681 &transmit_ready, connection);
682 }
683}
684
685
686/**
687 * Scheduler let us know that we're either ready to write on the
688 * socket OR connect timed out. Do the right thing.
689 *
690 * @param cls the `struct AddressProbe *` with the address that we are probing
691 */
692static void
693connect_probe_continuation (void *cls)
694{
695 struct AddressProbe *ap = cls;
696 struct GNUNET_CONNECTION_Handle *connection = ap->connection;
697 const struct GNUNET_SCHEDULER_TaskContext *tc;
698 struct AddressProbe *pos;
699 int error;
700 socklen_t len;
701
702 GNUNET_assert (NULL != ap->sock);
703 GNUNET_CONTAINER_DLL_remove (connection->ap_head,
704 connection->ap_tail,
705 ap);
706 len = sizeof (error);
707 errno = 0;
708 error = 0;
709 tc = GNUNET_SCHEDULER_get_task_context ();
710 if ( (0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
711 (GNUNET_OK !=
712 GNUNET_NETWORK_socket_getsockopt (ap->sock,
713 SOL_SOCKET,
714 SO_ERROR,
715 &error,
716 &len)) ||
717 (0 != error) )
718 {
719 GNUNET_break (GNUNET_OK ==
720 GNUNET_NETWORK_socket_close (ap->sock));
721 GNUNET_free (ap);
722 if ( (NULL == connection->ap_head) &&
723 (GNUNET_NO == connection->dns_active) &&
724 (NULL == connection->proxy_handshake) )
725 connect_fail_continuation (connection);
726 return;
727 }
728 GNUNET_assert (NULL == connection->sock);
729 connection->sock = ap->sock;
730 GNUNET_assert (NULL == connection->addr);
731 connection->addr = GNUNET_malloc (ap->addrlen);
732 GNUNET_memcpy (connection->addr, ap->addr, ap->addrlen);
733 connection->addrlen = ap->addrlen;
734 GNUNET_free (ap);
735 /* cancel all other attempts */
736 while (NULL != (pos = connection->ap_head))
737 {
738 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
739 GNUNET_SCHEDULER_cancel (pos->task);
740 GNUNET_CONTAINER_DLL_remove (connection->ap_head,
741 connection->ap_tail,
742 pos);
743 GNUNET_free (pos);
744 }
745 connect_success_continuation (connection);
746}
747
748
749/**
750 * Try to establish a connection given the specified address.
751 * This function is called by the resolver once we have a DNS reply.
752 *
753 * @param cls our `struct GNUNET_CONNECTION_Handle *`
754 * @param addr address to try, NULL for "last call"
755 * @param addrlen length of @a addr
756 */
757static void
758try_connect_using_address (void *cls,
759 const struct sockaddr *addr,
760 socklen_t addrlen)
761{
762 struct GNUNET_CONNECTION_Handle *connection = cls;
763 struct AddressProbe *ap;
764 struct GNUNET_TIME_Relative delay;
765
766 if (NULL == addr)
767 {
768 connection->dns_active = NULL;
769 if ((NULL == connection->ap_head) &&
770 (NULL == connection->sock) &&
771 (NULL == connection->proxy_handshake))
772 connect_fail_continuation (connection);
773 return;
774 }
775 if (NULL != connection->sock)
776 return; /* already connected */
777 GNUNET_assert (NULL == connection->addr);
778 /* try to connect */
779 LOG (GNUNET_ERROR_TYPE_DEBUG,
780 "Trying to connect using address `%s:%u/%s:%u'\n",
781 connection->hostname,
782 connection->port,
783 GNUNET_a2s (addr, addrlen),
784 connection->port);
785 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
786 ap->addr = (const struct sockaddr *) &ap[1];
787 GNUNET_memcpy (&ap[1], addr, addrlen);
788 ap->addrlen = addrlen;
789 ap->connection = connection;
790
791 switch (ap->addr->sa_family)
792 {
793 case AF_INET:
794 ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
795 break;
796 case AF_INET6:
797 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
798 break;
799 default:
800 GNUNET_break (0);
801 GNUNET_free (ap);
802 return; /* not supported by us */
803 }
804 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family,
805 SOCK_STREAM, 0);
806 if (NULL == ap->sock)
807 {
808 GNUNET_free (ap);
809 return; /* not supported by OS */
810 }
811 LOG (GNUNET_ERROR_TYPE_INFO,
812 "Trying to connect to `%s' (%p)\n",
813 GNUNET_a2s (ap->addr, ap->addrlen),
814 connection);
815 if ((GNUNET_OK !=
816 GNUNET_NETWORK_socket_connect (ap->sock,
817 ap->addr,
818 ap->addrlen)) &&
819 (EINPROGRESS != errno))
820 {
821 /* maybe refused / unsupported address, try next */
822 LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
823 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
824 GNUNET_free (ap);
825 return;
826 }
827 GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
828 delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
829 if (NULL != connection->nth.notify_ready)
830 delay = GNUNET_TIME_relative_min (delay,
831 GNUNET_TIME_absolute_get_remaining (connection->nth.transmit_timeout));
832 if (NULL != connection->receiver)
833 delay = GNUNET_TIME_relative_min (delay,
834 GNUNET_TIME_absolute_get_remaining (connection->receive_timeout));
835 ap->task = GNUNET_SCHEDULER_add_write_net (delay,
836 ap->sock,
837 &connect_probe_continuation,
838 ap);
839}
840
841
842/**
843 * Create a connection handle by (asynchronously) connecting to a host.
844 * This function returns immediately, even if the connection has not
845 * yet been established. This function only creates TCP connections.
846 *
847 * @param cfg configuration to use
848 * @param hostname name of the host to connect to
849 * @param port port to connect to
850 * @return the connection handle
851 */
852struct GNUNET_CONNECTION_Handle *
853GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
854 const char *hostname,
855 uint16_t port)
856{
857 struct GNUNET_CONNECTION_Handle *connection;
858
859 GNUNET_assert (0 < strlen (hostname)); /* sanity check */
860 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
861 connection->cfg = cfg;
862 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
863 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
864 connection->port = port;
865 connection->hostname = GNUNET_strdup (hostname);
866 connection->dns_active =
867 GNUNET_RESOLVER_ip_get (connection->hostname,
868 AF_UNSPEC,
869 GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
870 &try_connect_using_address,
871 connection);
872 return connection;
873}
874
875
876/**
877 * Create a connection handle by connecting to a UNIX domain service.
878 * This function returns immediately, even if the connection has not
879 * yet been established. This function only creates UNIX connections.
880 *
881 * @param cfg configuration to use
882 * @param unixpath path to connect to
883 * @return the connection handle, NULL on systems without UNIX support
884 */
885struct GNUNET_CONNECTION_Handle *
886GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct GNUNET_CONFIGURATION_Handle *cfg,
887 const char *unixpath)
888{
889#ifdef AF_UNIX
890 struct GNUNET_CONNECTION_Handle *connection;
891 struct sockaddr_un *un;
892
893 GNUNET_assert (0 < strlen (unixpath)); /* sanity check */
894 un = GNUNET_new (struct sockaddr_un);
895 un->sun_family = AF_UNIX;
896 strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
897#ifdef LINUX
898 {
899 int abstract;
900
901 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
902 "TESTING",
903 "USE_ABSTRACT_SOCKETS");
904 if (GNUNET_YES == abstract)
905 un->sun_path[0] = '\0';
906 }
907#endif
908#if HAVE_SOCKADDR_UN_SUN_LEN
909 un->sun_len = (u_char) sizeof (struct sockaddr_un);
910#endif
911 connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
912 connection->cfg = cfg;
913 connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
914 connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
915 connection->port = 0;
916 connection->hostname = NULL;
917 connection->addr = (struct sockaddr *) un;
918 connection->addrlen = sizeof (struct sockaddr_un);
919 connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX,
920 SOCK_STREAM,
921 0);
922 if (NULL == connection->sock)
923 {
924 GNUNET_free (connection->addr);
925 GNUNET_free (connection->write_buffer);
926 GNUNET_free (connection);
927 return NULL;
928 }
929 if ( (GNUNET_OK !=
930 GNUNET_NETWORK_socket_connect (connection->sock,
931 connection->addr,
932 connection->addrlen)) &&
933 (EINPROGRESS != errno) )
934 {
935 /* Just return; we expect everything to work eventually so don't fail HARD */
936 GNUNET_break (GNUNET_OK ==
937 GNUNET_NETWORK_socket_close (connection->sock));
938 connection->sock = NULL;
939 return connection;
940 }
941 connect_success_continuation (connection);
942 return connection;
943#else
944 return NULL;
945#endif
946}
947
948
949/**
950 * Create a connection handle by (asynchronously) connecting to a host.
951 * This function returns immediately, even if the connection has not
952 * yet been established. This function only creates TCP connections.
953 *
954 * @param s socket to connect
955 * @param serv_addr server address
956 * @param addrlen length of @a serv_addr
957 * @return the connection handle
958 */
959struct GNUNET_CONNECTION_Handle *
960GNUNET_CONNECTION_connect_socket (struct GNUNET_NETWORK_Handle *s,
961 const struct sockaddr *serv_addr,
962 socklen_t addrlen)
963{
964 struct GNUNET_CONNECTION_Handle *connection;
965
966 if ( (GNUNET_OK !=
967 GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
968 (EINPROGRESS != errno) )
969 {
970 /* maybe refused / unsupported address, try next */
971 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG,
972 "connect");
973 LOG (GNUNET_ERROR_TYPE_DEBUG,
974 "Attempt to connect to `%s' failed\n",
975 GNUNET_a2s (serv_addr,
976 addrlen));
977 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
978 return NULL;
979 }
980 connection = GNUNET_CONNECTION_create_from_existing (s);
981 connection->addr = GNUNET_malloc (addrlen);
982 GNUNET_memcpy (connection->addr, serv_addr, addrlen);
983 connection->addrlen = addrlen;
984 LOG (GNUNET_ERROR_TYPE_INFO,
985 "Trying to connect to `%s' (%p)\n",
986 GNUNET_a2s (serv_addr, addrlen),
987 connection);
988 return connection;
989}
990
991
992/**
993 * Create a connection handle by creating a socket and
994 * (asynchronously) connecting to a host. This function returns
995 * immediately, even if the connection has not yet been established.
996 * This function only creates TCP connections.
997 *
998 * @param af_family address family to use
999 * @param serv_addr server address
1000 * @param addrlen length of @a serv_addr
1001 * @return the connection handle
1002 */
1003struct GNUNET_CONNECTION_Handle *
1004GNUNET_CONNECTION_create_from_sockaddr (int af_family,
1005 const struct sockaddr *serv_addr,
1006 socklen_t addrlen)
1007{
1008 struct GNUNET_NETWORK_Handle *s;
1009
1010 s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
1011 if (NULL == s)
1012 {
1013 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
1014 "socket");
1015 return NULL;
1016 }
1017 return GNUNET_CONNECTION_connect_socket (s,
1018 serv_addr,
1019 addrlen);
1020}
1021
1022
1023/**
1024 * Check if connection is valid (no fatal errors have happened so far).
1025 * Note that a connection that is still trying to connect is considered
1026 * valid.
1027 *
1028 * @param connection connection to check
1029 * @return #GNUNET_YES if valid, #GNUNET_NO otherwise
1030 */
1031int
1032GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
1033{
1034 if ((NULL != connection->ap_head) ||
1035 (NULL != connection->dns_active) ||
1036 (NULL != connection->proxy_handshake))
1037 return GNUNET_YES; /* still trying to connect */
1038 if ( (0 != connection->destroy_later) ||
1039 (NULL == connection->sock) )
1040 return GNUNET_NO;
1041 return GNUNET_YES;
1042}
1043
1044
1045/**
1046 * Close the connection and free associated resources. There must
1047 * not be any pending requests for reading or writing to the
1048 * connection at this time.
1049 *
1050 * @param connection connection to destroy
1051 */
1052void
1053GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
1054{
1055 struct AddressProbe *pos;
1056
1057 if (0 != connection->destroy_later)
1058 {
1059 connection->destroy_later = -1;
1060 return;
1061 }
1062 LOG (GNUNET_ERROR_TYPE_DEBUG,
1063 "Shutting down connection (%p)\n",
1064 connection);
1065 GNUNET_assert (NULL == connection->nth.notify_ready);
1066 GNUNET_assert (NULL == connection->receiver);
1067 if (NULL != connection->write_task)
1068 {
1069 GNUNET_SCHEDULER_cancel (connection->write_task);
1070 connection->write_task = NULL;
1071 connection->write_buffer_off = 0;
1072 }
1073 if (NULL != connection->read_task)
1074 {
1075 GNUNET_SCHEDULER_cancel (connection->read_task);
1076 connection->read_task = NULL;
1077 }
1078 if (NULL != connection->nth.timeout_task)
1079 {
1080 GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
1081 connection->nth.timeout_task = NULL;
1082 }
1083 connection->nth.notify_ready = NULL;
1084 if (NULL != connection->dns_active)
1085 {
1086 GNUNET_RESOLVER_request_cancel (connection->dns_active);
1087 connection->dns_active = NULL;
1088 }
1089 if (NULL != connection->proxy_handshake)
1090 {
1091 /* GNUNET_CONNECTION_destroy (connection->proxy_handshake); */
1092 connection->proxy_handshake->destroy_later = -1;
1093 connection->proxy_handshake = NULL; /* Not leaked ??? */
1094 }
1095 while (NULL != (pos = connection->ap_head))
1096 {
1097 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
1098 GNUNET_SCHEDULER_cancel (pos->task);
1099 GNUNET_CONTAINER_DLL_remove (connection->ap_head,
1100 connection->ap_tail,
1101 pos);
1102 GNUNET_free (pos);
1103 }
1104 if ( (NULL != connection->sock) &&
1105 (GNUNET_YES != connection->persist) )
1106 {
1107 if ((GNUNET_OK !=
1108 GNUNET_NETWORK_socket_shutdown (connection->sock,
1109 SHUT_RDWR)) &&
1110 (ENOTCONN != errno) &&
1111 (ECONNRESET != errno) )
1112 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1113 "shutdown");
1114 }
1115 if (NULL != connection->sock)
1116 {
1117 if (GNUNET_YES != connection->persist)
1118 {
1119 GNUNET_break (GNUNET_OK ==
1120 GNUNET_NETWORK_socket_close (connection->sock));
1121 }
1122 else
1123 {
1124 GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1125 * leak the socket in this special case) ... */
1126 }
1127 }
1128 GNUNET_free_non_null (connection->addr);
1129 GNUNET_free_non_null (connection->hostname);
1130 GNUNET_free (connection->write_buffer);
1131 GNUNET_free (connection);
1132}
1133
1134
1135/**
1136 * This function is called once we either timeout
1137 * or have data ready to read.
1138 *
1139 * @param cls connection to read from
1140 */
1141static void
1142receive_ready (void *cls)
1143{
1144 struct GNUNET_CONNECTION_Handle *connection = cls;
1145 const struct GNUNET_SCHEDULER_TaskContext *tc;
1146 char buffer[connection->max];
1147 ssize_t ret;
1148 GNUNET_CONNECTION_Receiver receiver;
1149
1150 connection->read_task = NULL;
1151 tc = GNUNET_SCHEDULER_get_task_context ();
1152 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1153 {
1154 LOG (GNUNET_ERROR_TYPE_DEBUG,
1155 "Receive from `%s' encounters error: timeout (%s, %p)\n",
1156 GNUNET_a2s (connection->addr,
1157 connection->addrlen),
1158 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout),
1159 GNUNET_YES),
1160 connection);
1161 signal_receive_timeout (connection);
1162 return;
1163 }
1164 if (NULL == connection->sock)
1165 {
1166 /* connect failed for good */
1167 signal_receive_error (connection, ECONNREFUSED);
1168 return;
1169 }
1170 GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready,
1171 connection->sock));
1172RETRY:
1173 ret = GNUNET_NETWORK_socket_recv (connection->sock,
1174 buffer,
1175 connection->max);
1176 if (-1 == ret)
1177 {
1178 if (EINTR == errno)
1179 goto RETRY;
1180 signal_receive_error (connection, errno);
1181 return;
1182 }
1183 LOG (GNUNET_ERROR_TYPE_DEBUG,
1184 "receive_ready read %u/%u bytes from `%s' (%p)!\n",
1185 (unsigned int) ret,
1186 connection->max,
1187 GNUNET_a2s (connection->addr,
1188 connection->addrlen),
1189 connection);
1190 GNUNET_assert (NULL != (receiver = connection->receiver));
1191 connection->receiver = NULL;
1192 receiver (connection->receiver_cls,
1193 buffer,
1194 ret,
1195 connection->addr,
1196 connection->addrlen,
1197 0);
1198}
1199
1200
1201/**
1202 * Receive data from the given connection. Note that this function
1203 * will call @a receiver asynchronously using the scheduler. It will
1204 * "immediately" return. Note that there MUST only be one active
1205 * receive call per connection at any given point in time (so do not
1206 * call receive again until the receiver callback has been invoked).
1207 *
1208 * @param connection connection handle
1209 * @param max maximum number of bytes to read
1210 * @param timeout maximum amount of time to wait
1211 * @param receiver function to call with received data
1212 * @param receiver_cls closure for @a receiver
1213 */
1214void
1215GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection,
1216 size_t max,
1217 struct GNUNET_TIME_Relative timeout,
1218 GNUNET_CONNECTION_Receiver receiver,
1219 void *receiver_cls)
1220{
1221 GNUNET_assert ((NULL == connection->read_task) &&
1222 (NULL == connection->receiver));
1223 GNUNET_assert (NULL != receiver);
1224 connection->receiver = receiver;
1225 connection->receiver_cls = receiver_cls;
1226 connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1227 connection->max = max;
1228 if (NULL != connection->sock)
1229 {
1230 connection->read_task =
1231 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1232 (connection->receive_timeout),
1233 connection->sock,
1234 &receive_ready,
1235 connection);
1236 return;
1237 }
1238 if ((NULL == connection->dns_active) &&
1239 (NULL == connection->ap_head) &&
1240 (NULL == connection->proxy_handshake))
1241 {
1242 connection->receiver = NULL;
1243 receiver (receiver_cls,
1244 NULL, 0,
1245 NULL, 0,
1246 ETIMEDOUT);
1247 return;
1248 }
1249}
1250
1251
1252/**
1253 * Cancel receive job on the given connection. Note that the
1254 * receiver callback must not have been called yet in order
1255 * for the cancellation to be valid.
1256 *
1257 * @param connection connection handle
1258 * @return closure of the original receiver callback closure
1259 */
1260void *
1261GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1262{
1263 if (NULL != connection->read_task)
1264 {
1265 GNUNET_assert (connection ==
1266 GNUNET_SCHEDULER_cancel (connection->read_task));
1267 connection->read_task = NULL;
1268 }
1269 connection->receiver = NULL;
1270 return connection->receiver_cls;
1271}
1272
1273
1274/**
1275 * Try to call the transmit notify method (check if we do
1276 * have enough space available first)!
1277 *
1278 * @param connection connection for which we should do this processing
1279 * @return #GNUNET_YES if we were able to call notify
1280 */
1281static int
1282process_notify (struct GNUNET_CONNECTION_Handle *connection)
1283{
1284 size_t used;
1285 size_t avail;
1286 size_t size;
1287 GNUNET_CONNECTION_TransmitReadyNotify notify;
1288
1289 LOG (GNUNET_ERROR_TYPE_DEBUG,
1290 "process_notify is running\n");
1291 GNUNET_assert (NULL == connection->write_task);
1292 if (NULL == (notify = connection->nth.notify_ready))
1293 {
1294 LOG (GNUNET_ERROR_TYPE_DEBUG,
1295 "No one to notify\n");
1296 return GNUNET_NO;
1297 }
1298 used = connection->write_buffer_off - connection->write_buffer_pos;
1299 avail = connection->write_buffer_size - used;
1300 size = connection->nth.notify_size;
1301 if (size > avail)
1302 {
1303 LOG (GNUNET_ERROR_TYPE_DEBUG,
1304 "Not enough buffer\n");
1305 return GNUNET_NO;
1306 }
1307 connection->nth.notify_ready = NULL;
1308 if (connection->write_buffer_size - connection->write_buffer_off < size)
1309 {
1310 /* need to compact */
1311 memmove (connection->write_buffer,
1312 &connection->write_buffer[connection->write_buffer_pos],
1313 used);
1314 connection->write_buffer_off -= connection->write_buffer_pos;
1315 connection->write_buffer_pos = 0;
1316 }
1317 avail = connection->write_buffer_size - connection->write_buffer_off;
1318 GNUNET_assert (avail >= size);
1319 size =
1320 notify (connection->nth.notify_ready_cls, avail,
1321 &connection->write_buffer[connection->write_buffer_off]);
1322 GNUNET_assert (size <= avail);
1323 if (0 != size)
1324 connection->write_buffer_off += size;
1325 return GNUNET_YES;
1326}
1327
1328
1329/**
1330 * Task invoked by the scheduler when a call to transmit
1331 * is timing out (we never got enough buffer space to call
1332 * the callback function before the specified timeout
1333 * expired).
1334 *
1335 * This task notifies the client about the timeout.
1336 *
1337 * @param cls the `struct GNUNET_CONNECTION_Handle`
1338 */
1339static void
1340transmit_timeout (void *cls)
1341{
1342 struct GNUNET_CONNECTION_Handle *connection = cls;
1343 GNUNET_CONNECTION_TransmitReadyNotify notify;
1344
1345 connection->nth.timeout_task = NULL;
1346 LOG (GNUNET_ERROR_TYPE_DEBUG,
1347 "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1348 connection->hostname,
1349 connection->port,
1350 GNUNET_a2s (connection->addr,
1351 connection->addrlen),
1352 connection);
1353 notify = connection->nth.notify_ready;
1354 GNUNET_assert (NULL != notify);
1355 connection->nth.notify_ready = NULL;
1356 notify (connection->nth.notify_ready_cls,
1357 0,
1358 NULL);
1359}
1360
1361
1362/**
1363 * Task invoked by the scheduler when we failed to connect
1364 * at the time of being asked to transmit.
1365 *
1366 * This task notifies the client about the error.
1367 *
1368 * @param cls the `struct GNUNET_CONNECTION_Handle`
1369 */
1370static void
1371connect_error (void *cls)
1372{
1373 struct GNUNET_CONNECTION_Handle *connection = cls;
1374 GNUNET_CONNECTION_TransmitReadyNotify notify;
1375
1376 LOG (GNUNET_ERROR_TYPE_DEBUG,
1377 "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1378 connection->nth.notify_size,
1379 connection->hostname,
1380 connection->port,
1381 connection);
1382 connection->write_task = NULL;
1383 notify = connection->nth.notify_ready;
1384 connection->nth.notify_ready = NULL;
1385 notify (connection->nth.notify_ready_cls,
1386 0,
1387 NULL);
1388}
1389
1390
1391/**
1392 * We are ready to transmit (or got a timeout).
1393 *
1394 * @param cls our connection handle
1395 */
1396static void
1397transmit_ready (void *cls)
1398{
1399 struct GNUNET_CONNECTION_Handle *connection = cls;
1400 GNUNET_CONNECTION_TransmitReadyNotify notify;
1401 const struct GNUNET_SCHEDULER_TaskContext *tc;
1402 ssize_t ret;
1403 size_t have;
1404
1405 LOG (GNUNET_ERROR_TYPE_DEBUG,
1406 "transmit_ready running (%p).\n",
1407 connection);
1408 GNUNET_assert (NULL != connection->write_task);
1409 connection->write_task = NULL;
1410 GNUNET_assert (NULL == connection->nth.timeout_task);
1411 tc = GNUNET_SCHEDULER_get_task_context ();
1412 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1413 {
1414 LOG (GNUNET_ERROR_TYPE_DEBUG,
1415 "Transmit to `%s' fails, time out reached (%p).\n",
1416 GNUNET_a2s (connection->addr,
1417 connection->addrlen),
1418 connection);
1419 notify = connection->nth.notify_ready;
1420 GNUNET_assert (NULL != notify);
1421 connection->nth.notify_ready = NULL;
1422 notify (connection->nth.notify_ready_cls, 0, NULL);
1423 return;
1424 }
1425 GNUNET_assert (NULL != connection->sock);
1426 if (NULL == tc->write_ready)
1427 {
1428 /* special circumstances (in particular, PREREQ_DONE after
1429 * connect): not yet ready to write, but no "fatal" error either.
1430 * Hence retry. */
1431 goto SCHEDULE_WRITE;
1432 }
1433 if (! GNUNET_NETWORK_fdset_isset (tc->write_ready,
1434 connection->sock))
1435 {
1436 GNUNET_assert (NULL == connection->write_task);
1437 /* special circumstances (in particular, shutdown): not yet ready
1438 * to write, but no "fatal" error either. Hence retry. */
1439 goto SCHEDULE_WRITE;
1440 }
1441 GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1442 if ((NULL != connection->nth.notify_ready) &&
1443 (connection->write_buffer_size < connection->nth.notify_size))
1444 {
1445 connection->write_buffer =
1446 GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1447 connection->write_buffer_size = connection->nth.notify_size;
1448 }
1449 process_notify (connection);
1450 have = connection->write_buffer_off - connection->write_buffer_pos;
1451 if (0 == have)
1452 {
1453 /* no data ready for writing, terminate write loop */
1454 return;
1455 }
1456 GNUNET_assert (have <= connection->write_buffer_size);
1457 GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1458 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1459RETRY:
1460 ret =
1461 GNUNET_NETWORK_socket_send (connection->sock,
1462 &connection->write_buffer[connection->write_buffer_pos],
1463 have);
1464 if (-1 == ret)
1465 {
1466 if (EINTR == errno)
1467 goto RETRY;
1468 if (NULL != connection->write_task)
1469 {
1470 GNUNET_SCHEDULER_cancel (connection->write_task);
1471 connection->write_task = NULL;
1472 }
1473 signal_transmit_error (connection, errno);
1474 return;
1475 }
1476 LOG (GNUNET_ERROR_TYPE_DEBUG,
1477 "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1478 (unsigned int) ret,
1479 have,
1480 GNUNET_a2s (connection->addr,
1481 connection->addrlen),
1482 connection);
1483 connection->write_buffer_pos += ret;
1484 if (connection->write_buffer_pos == connection->write_buffer_off)
1485 {
1486 /* transmitted all pending data */
1487 connection->write_buffer_pos = 0;
1488 connection->write_buffer_off = 0;
1489 }
1490 if ( (0 == connection->write_buffer_off) &&
1491 (NULL == connection->nth.notify_ready) )
1492 return; /* all data sent! */
1493 /* not done writing, schedule more */
1494SCHEDULE_WRITE:
1495 LOG (GNUNET_ERROR_TYPE_DEBUG,
1496 "Re-scheduling transmit_ready (more to do) (%p).\n",
1497 connection);
1498 have = connection->write_buffer_off - connection->write_buffer_pos;
1499 GNUNET_assert ( (NULL != connection->nth.notify_ready) ||
1500 (have > 0) );
1501 if (NULL == connection->write_task)
1502 connection->write_task =
1503 GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1504 NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1505 GNUNET_TIME_absolute_get_remaining
1506 (connection->nth.transmit_timeout),
1507 connection->sock,
1508 &transmit_ready, connection);
1509}
1510
1511
1512/**
1513 * Ask the connection to call us once the specified number of bytes
1514 * are free in the transmission buffer. Will never call the @a notify
1515 * callback in this task, but always first go into the scheduler.
1516 *
1517 * @param connection connection
1518 * @param size number of bytes to send
1519 * @param timeout after how long should we give up (and call
1520 * @a notify with buf NULL and size 0)?
1521 * @param notify function to call
1522 * @param notify_cls closure for @a notify
1523 * @return non-NULL if the notify callback was queued,
1524 * NULL if we are already going to notify someone else (busy)
1525 */
1526struct GNUNET_CONNECTION_TransmitHandle *
1527GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1528 size_t size,
1529 struct GNUNET_TIME_Relative timeout,
1530 GNUNET_CONNECTION_TransmitReadyNotify notify,
1531 void *notify_cls)
1532{
1533 if (NULL != connection->nth.notify_ready)
1534 {
1535 GNUNET_assert (0);
1536 return NULL;
1537 }
1538 GNUNET_assert (NULL != notify);
1539 GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1540 GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1541 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1542 GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1543 connection->nth.notify_ready = notify;
1544 connection->nth.notify_ready_cls = notify_cls;
1545 connection->nth.connection = connection;
1546 connection->nth.notify_size = size;
1547 connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1548 GNUNET_assert (NULL == connection->nth.timeout_task);
1549 if ((NULL == connection->sock) &&
1550 (NULL == connection->ap_head) &&
1551 (NULL == connection->dns_active) &&
1552 (NULL == connection->proxy_handshake))
1553 {
1554 if (NULL != connection->write_task)
1555 GNUNET_SCHEDULER_cancel (connection->write_task);
1556 connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error,
1557 connection);
1558 return &connection->nth;
1559 }
1560 if (NULL != connection->write_task)
1561 return &connection->nth; /* previous transmission still in progress */
1562 if (NULL != connection->sock)
1563 {
1564 /* connected, try to transmit now */
1565 LOG (GNUNET_ERROR_TYPE_DEBUG,
1566 "Scheduling transmission (%p).\n",
1567 connection);
1568 connection->write_task =
1569 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1570 (connection->nth.transmit_timeout),
1571 connection->sock,
1572 &transmit_ready, connection);
1573 return &connection->nth;
1574 }
1575 /* not yet connected, wait for connection */
1576 LOG (GNUNET_ERROR_TYPE_DEBUG,
1577 "Need to wait to schedule transmission for connection, adding timeout task (%p).\n",
1578 connection);
1579 connection->nth.timeout_task =
1580 GNUNET_SCHEDULER_add_delayed (timeout,
1581 &transmit_timeout,
1582 connection);
1583 return &connection->nth;
1584}
1585
1586
1587/**
1588 * Cancel the specified transmission-ready notification.
1589 *
1590 * @param th notification to cancel
1591 */
1592void
1593GNUNET_CONNECTION_notify_transmit_ready_cancel (struct GNUNET_CONNECTION_TransmitHandle *th)
1594{
1595 GNUNET_assert (NULL != th->notify_ready);
1596 th->notify_ready = NULL;
1597 if (NULL != th->timeout_task)
1598 {
1599 GNUNET_SCHEDULER_cancel (th->timeout_task);
1600 th->timeout_task = NULL;
1601 }
1602 if (NULL != th->connection->write_task)
1603 {
1604 GNUNET_SCHEDULER_cancel (th->connection->write_task);
1605 th->connection->write_task = NULL;
1606 }
1607}
1608
1609
1610/**
1611 * Create a connection to be proxied using a given connection.
1612 *
1613 * @param cph connection to proxy server
1614 * @return connection to be proxied
1615 */
1616struct GNUNET_CONNECTION_Handle *
1617GNUNET_CONNECTION_create_proxied_from_handshake (struct GNUNET_CONNECTION_Handle *cph)
1618{
1619 struct GNUNET_CONNECTION_Handle *proxied = GNUNET_CONNECTION_create_from_existing (NULL);
1620
1621 proxied->proxy_handshake = cph;
1622 return proxied;
1623}
1624
1625
1626/**
1627 * Activate proxied connection and destroy initial proxy handshake connection.
1628 * There must not be any pending requests for reading or writing to the
1629 * proxy hadshake connection at this time.
1630 *
1631 * @param proxied connection connection to proxy server
1632 */
1633void
1634GNUNET_CONNECTION_acivate_proxied (struct GNUNET_CONNECTION_Handle *proxied)
1635{
1636 struct GNUNET_CONNECTION_Handle *cph = proxied->proxy_handshake;
1637
1638 GNUNET_assert (NULL != cph);
1639 GNUNET_assert (NULL == proxied->sock);
1640 GNUNET_assert (NULL != cph->sock);
1641 proxied->sock = cph->sock;
1642 cph->sock = NULL;
1643 GNUNET_CONNECTION_destroy (cph);
1644 connect_success_continuation (proxied);
1645}
1646
1647
1648/* end of connection.c */
diff --git a/src/util/helper.c b/src/util/helper.c
index cdb1b01d4..1a79c477a 100644
--- a/src/util/helper.c
+++ b/src/util/helper.c
@@ -27,6 +27,7 @@
27 */ 27 */
28#include "platform.h" 28#include "platform.h"
29#include "gnunet_util_lib.h" 29#include "gnunet_util_lib.h"
30#include "gnunet_mst_lib.h"
30 31
31 32
32/** 33/**
@@ -107,7 +108,7 @@ struct GNUNET_HELPER_Handle
107 /** 108 /**
108 * The Message-Tokenizer that tokenizes the messages comming from the helper 109 * The Message-Tokenizer that tokenizes the messages comming from the helper
109 */ 110 */
110 struct GNUNET_SERVER_MessageStreamTokenizer *mst; 111 struct GNUNET_MessageStreamTokenizer *mst;
111 112
112 /** 113 /**
113 * The exception callback 114 * The exception callback
@@ -272,7 +273,10 @@ GNUNET_HELPER_wait (struct GNUNET_HELPER_Handle *h)
272 } 273 }
273 /* purge MST buffer */ 274 /* purge MST buffer */
274 if (NULL != h->mst) 275 if (NULL != h->mst)
275 (void) GNUNET_SERVER_mst_receive (h->mst, NULL, NULL, 0, GNUNET_YES, GNUNET_NO); 276 (void) GNUNET_MST_from_buffer (h->mst,
277 NULL, 0,
278 GNUNET_YES,
279 GNUNET_NO);
276 return ret; 280 return ret;
277} 281}
278 282
@@ -373,10 +377,10 @@ helper_read (void *cls)
373 h->fh_from_helper, 377 h->fh_from_helper,
374 &helper_read, h); 378 &helper_read, h);
375 if (GNUNET_SYSERR == 379 if (GNUNET_SYSERR ==
376 GNUNET_SERVER_mst_receive (h->mst, 380 GNUNET_MST_from_buffer (h->mst,
377 NULL, 381 buf, t,
378 buf, t, 382 GNUNET_NO,
379 GNUNET_NO, GNUNET_NO)) 383 GNUNET_NO))
380 { 384 {
381 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 385 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
382 _("Failed to parse inbound message from helper `%s'\n"), 386 _("Failed to parse inbound message from helper `%s'\n"),
@@ -487,7 +491,7 @@ struct GNUNET_HELPER_Handle *
487GNUNET_HELPER_start (int with_control_pipe, 491GNUNET_HELPER_start (int with_control_pipe,
488 const char *binary_name, 492 const char *binary_name,
489 char *const binary_argv[], 493 char *const binary_argv[],
490 GNUNET_SERVER_MessageTokenizerCallback cb, 494 GNUNET_MessageTokenizerCallback cb,
491 GNUNET_HELPER_ExceptionCallback exp_cb, 495 GNUNET_HELPER_ExceptionCallback exp_cb,
492 void *cb_cls) 496 void *cb_cls)
493{ 497{
@@ -508,7 +512,8 @@ GNUNET_HELPER_start (int with_control_pipe,
508 h->binary_argv[c] = NULL; 512 h->binary_argv[c] = NULL;
509 h->cb_cls = cb_cls; 513 h->cb_cls = cb_cls;
510 if (NULL != cb) 514 if (NULL != cb)
511 h->mst = GNUNET_SERVER_mst_create (cb, h->cb_cls); 515 h->mst = GNUNET_MST_create (cb,
516 h->cb_cls);
512 h->exp_cb = exp_cb; 517 h->exp_cb = exp_cb;
513 h->retry_back_off = 0; 518 h->retry_back_off = 0;
514 start_helper (h); 519 start_helper (h);
@@ -544,7 +549,7 @@ GNUNET_HELPER_destroy (struct GNUNET_HELPER_Handle *h)
544 GNUNET_free (sh); 549 GNUNET_free (sh);
545 } 550 }
546 if (NULL != h->mst) 551 if (NULL != h->mst)
547 GNUNET_SERVER_mst_destroy (h->mst); 552 GNUNET_MST_destroy (h->mst);
548 GNUNET_free (h->binary_name); 553 GNUNET_free (h->binary_name);
549 for (c = 0; h->binary_argv[c] != NULL; c++) 554 for (c = 0; h->binary_argv[c] != NULL; c++)
550 GNUNET_free (h->binary_argv[c]); 555 GNUNET_free (h->binary_argv[c]);
diff --git a/src/util/mq.c b/src/util/mq.c
index 25cf24e11..e644994e8 100644
--- a/src/util/mq.c
+++ b/src/util/mq.c
@@ -708,92 +708,6 @@ GNUNET_MQ_msg_nested_mh_ (struct GNUNET_MessageHeader **mhp,
708 708
709 709
710/** 710/**
711 * Transmit a queued message to the session's client.
712 *
713 * @param cls consensus session
714 * @param size number of bytes available in @a buf
715 * @param buf where the callee should write the message
716 * @return number of bytes written to @a buf
717 */
718static size_t
719transmit_queued (void *cls,
720 size_t size,
721 void *buf)
722{
723 struct GNUNET_MQ_Handle *mq = cls;
724 struct ServerClientSocketState *state = GNUNET_MQ_impl_state (mq);
725 const struct GNUNET_MessageHeader *msg = GNUNET_MQ_impl_current (mq);
726 size_t msg_size;
727
728 GNUNET_assert (NULL != buf);
729 msg_size = ntohs (msg->size);
730 GNUNET_assert (size >= msg_size);
731 GNUNET_memcpy (buf, msg, msg_size);
732 state->th = NULL;
733
734 GNUNET_MQ_impl_send_continue (mq);
735
736 return msg_size;
737}
738
739
740static void
741server_client_destroy_impl (struct GNUNET_MQ_Handle *mq,
742 void *impl_state)
743{
744 struct ServerClientSocketState *state = impl_state;
745
746 if (NULL != state->th)
747 {
748 GNUNET_SERVER_notify_transmit_ready_cancel (state->th);
749 state->th = NULL;
750 }
751
752 GNUNET_assert (NULL != mq);
753 GNUNET_assert (NULL != state);
754 GNUNET_SERVER_client_drop (state->client);
755 GNUNET_free (state);
756}
757
758
759static void
760server_client_send_impl (struct GNUNET_MQ_Handle *mq,
761 const struct GNUNET_MessageHeader *msg,
762 void *impl_state)
763{
764 GNUNET_assert (NULL != mq);
765
766 LOG (GNUNET_ERROR_TYPE_DEBUG,
767 "Sending message of type %u and size %u\n",
768 ntohs (msg->type), ntohs (msg->size));
769
770 struct ServerClientSocketState *state = impl_state;
771 state->th = GNUNET_SERVER_notify_transmit_ready (state->client,
772 ntohs (msg->size),
773 GNUNET_TIME_UNIT_FOREVER_REL,
774 &transmit_queued,
775 mq);
776}
777
778
779struct GNUNET_MQ_Handle *
780GNUNET_MQ_queue_for_server_client (struct GNUNET_SERVER_Client *client)
781{
782 struct GNUNET_MQ_Handle *mq;
783 struct ServerClientSocketState *scss;
784
785 mq = GNUNET_new (struct GNUNET_MQ_Handle);
786 scss = GNUNET_new (struct ServerClientSocketState);
787 mq->impl_state = scss;
788 scss->client = client;
789 GNUNET_SERVER_client_keep (client);
790 mq->send_impl = &server_client_send_impl;
791 mq->destroy_impl = &server_client_destroy_impl;
792 return mq;
793}
794
795
796/**
797 * Associate the assoc_data in mq with a unique request id. 711 * Associate the assoc_data in mq with a unique request id.
798 * 712 *
799 * @param mq message queue, id will be unique for the queue 713 * @param mq message queue, id will be unique for the queue
diff --git a/src/util/server.c b/src/util/server.c
deleted file mode 100644
index 83c30e328..000000000
--- a/src/util/server.c
+++ /dev/null
@@ -1,1752 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009-2013 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20
21/**
22 * @file util/server.c
23 * @brief library for building GNUnet network servers
24 * @author Christian Grothoff
25 */
26
27#include "platform.h"
28#include "gnunet_util_lib.h"
29#include "gnunet_protocols.h"
30
31#define LOG(kind,...) GNUNET_log_from (kind, "util-server", __VA_ARGS__)
32
33#define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-server", syscall)
34
35#define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-server", syscall, filename)
36
37
38/**
39 * List of arrays of message handlers.
40 */
41struct HandlerList
42{
43 /**
44 * This is a linked list.
45 */
46 struct HandlerList *next;
47
48 /**
49 * NULL-terminated array of handlers.
50 */
51 const struct GNUNET_SERVER_MessageHandler *handlers;
52};
53
54
55/**
56 * List of arrays of message handlers.
57 */
58struct NotifyList
59{
60 /**
61 * This is a doubly linked list.
62 */
63 struct NotifyList *next;
64
65 /**
66 * This is a doubly linked list.
67 */
68 struct NotifyList *prev;
69
70 /**
71 * Function to call.
72 */
73 GNUNET_SERVER_DisconnectCallback callback;
74
75 /**
76 * Closure for callback.
77 */
78 void *callback_cls;
79};
80
81
82/**
83 * @brief handle for a server
84 */
85struct GNUNET_SERVER_Handle
86{
87 /**
88 * List of handlers for incoming messages.
89 */
90 struct HandlerList *handlers;
91
92 /**
93 * Head of list of our current clients.
94 */
95 struct GNUNET_SERVER_Client *clients_head;
96
97 /**
98 * Head of list of our current clients.
99 */
100 struct GNUNET_SERVER_Client *clients_tail;
101
102 /**
103 * Head of linked list of functions to call on disconnects by clients.
104 */
105 struct NotifyList *disconnect_notify_list_head;
106
107 /**
108 * Tail of linked list of functions to call on disconnects by clients.
109 */
110 struct NotifyList *disconnect_notify_list_tail;
111
112 /**
113 * Head of linked list of functions to call on connects by clients.
114 */
115 struct NotifyList *connect_notify_list_head;
116
117 /**
118 * Tail of linked list of functions to call on connects by clients.
119 */
120 struct NotifyList *connect_notify_list_tail;
121
122 /**
123 * Function to call for access control.
124 */
125 GNUNET_CONNECTION_AccessCheck access_cb;
126
127 /**
128 * Closure for @e access_cb.
129 */
130 void *access_cb_cls;
131
132 /**
133 * NULL-terminated array of sockets used to listen for new
134 * connections.
135 */
136 struct GNUNET_NETWORK_Handle **listen_sockets;
137
138 /**
139 * After how long should an idle connection time
140 * out (on write).
141 */
142 struct GNUNET_TIME_Relative idle_timeout;
143
144 /**
145 * Task scheduled to do the listening.
146 */
147 struct GNUNET_SCHEDULER_Task * listen_task;
148
149 /**
150 * Alternative function to create a MST instance.
151 */
152 GNUNET_SERVER_MstCreateCallback mst_create;
153
154 /**
155 * Alternative function to destroy a MST instance.
156 */
157 GNUNET_SERVER_MstDestroyCallback mst_destroy;
158
159 /**
160 * Alternative function to give data to a MST instance.
161 */
162 GNUNET_SERVER_MstReceiveCallback mst_receive;
163
164 /**
165 * Closure for 'mst_'-callbacks.
166 */
167 void *mst_cls;
168
169 /**
170 * Do we ignore messages of types that we do not understand or do we
171 * require that a handler is found (and if not kill the connection)?
172 */
173 int require_found;
174
175 /**
176 * Set to #GNUNET_YES once we are in 'soft' shutdown where we wait for
177 * all non-monitor clients to disconnect before we call
178 * #GNUNET_SERVER_destroy. See test_monitor_clients(). Set to
179 * #GNUNET_SYSERR once the final destroy task has been scheduled
180 * (we cannot run it in the same task).
181 */
182 int in_soft_shutdown;
183};
184
185
186/**
187 * Handle server returns for aborting transmission to a client.
188 */
189struct GNUNET_SERVER_TransmitHandle
190{
191 /**
192 * Function to call to get the message.
193 */
194 GNUNET_CONNECTION_TransmitReadyNotify callback;
195
196 /**
197 * Closure for @e callback
198 */
199 void *callback_cls;
200
201 /**
202 * Active connection transmission handle.
203 */
204 struct GNUNET_CONNECTION_TransmitHandle *cth;
205
206};
207
208
209/**
210 * @brief handle for a client of the server
211 */
212struct GNUNET_SERVER_Client
213{
214
215 /**
216 * This is a doubly linked list.
217 */
218 struct GNUNET_SERVER_Client *next;
219
220 /**
221 * This is a doubly linked list.
222 */
223 struct GNUNET_SERVER_Client *prev;
224
225 /**
226 * Processing of incoming data.
227 */
228 void *mst;
229
230 /**
231 * Server that this client belongs to.
232 */
233 struct GNUNET_SERVER_Handle *server;
234
235 /**
236 * Client closure for callbacks.
237 */
238 struct GNUNET_CONNECTION_Handle *connection;
239
240 /**
241 * User context value, manipulated using
242 * 'GNUNET_SERVER_client_{get/set}_user_context' functions.
243 */
244 void *user_context;
245
246 /**
247 * ID of task used to restart processing.
248 */
249 struct GNUNET_SCHEDULER_Task * restart_task;
250
251 /**
252 * Task that warns about missing calls to #GNUNET_SERVER_receive_done.
253 */
254 struct GNUNET_SCHEDULER_Task * warn_task;
255
256 /**
257 * Time when the warn task was started.
258 */
259 struct GNUNET_TIME_Absolute warn_start;
260
261 /**
262 * Last activity on this socket (used to time it out
263 * if reference_count == 0).
264 */
265 struct GNUNET_TIME_Absolute last_activity;
266
267 /**
268 * Transmission handle we return for this client from
269 * #GNUNET_SERVER_notify_transmit_ready.
270 */
271 struct GNUNET_SERVER_TransmitHandle th;
272
273 /**
274 * After how long should an idle connection time
275 * out (on write).
276 */
277 struct GNUNET_TIME_Relative idle_timeout;
278
279 /**
280 * Number of external entities with a reference to
281 * this client object.
282 */
283 unsigned int reference_count;
284
285 /**
286 * Was processing if incoming messages suspended while
287 * we were still processing data already received?
288 * This is a counter saying how often processing was
289 * suspended (once per handler invoked).
290 */
291 unsigned int suspended;
292
293 /**
294 * Last size given when user context was initialized; used for
295 * sanity check.
296 */
297 size_t user_context_size;
298
299 /**
300 * Are we currently in the "process_client_buffer" function (and
301 * will hence restart the receive job on exit if suspended == 0 once
302 * we are done?). If this is set, then "receive_done" will
303 * essentially only decrement suspended; if this is not set, then
304 * "receive_done" may need to restart the receive process (either
305 * from the side-buffer or via select/recv).
306 */
307 int in_process_client_buffer;
308
309 /**
310 * We're about to close down this client.
311 */
312 int shutdown_now;
313
314 /**
315 * Are we currently trying to receive? (#GNUNET_YES if we are,
316 * #GNUNET_NO if we are not, #GNUNET_SYSERR if data is already
317 * available in MST).
318 */
319 int receive_pending;
320
321 /**
322 * Persist the file handle for this client no matter what happens,
323 * force the OS to close once the process actually dies. Should only
324 * be used in special cases!
325 */
326 int persist;
327
328 /**
329 * Is this client a 'monitor' client that should not be counted
330 * when deciding on destroying the server during soft shutdown?
331 * (see also #GNUNET_SERVICE_start)
332 */
333 int is_monitor;
334
335 /**
336 * Type of last message processed (for warn_no_receive_done).
337 */
338 uint16_t warn_type;
339};
340
341
342
343/**
344 * Return user context associated with the given client.
345 * Note: you should probably use the macro (call without the underscore).
346 *
347 * @param client client to query
348 * @param size number of bytes in user context struct (for verification only)
349 * @return pointer to user context
350 */
351void *
352GNUNET_SERVER_client_get_user_context_ (struct GNUNET_SERVER_Client *client,
353 size_t size)
354{
355 if ((0 == client->user_context_size) &&
356 (NULL == client->user_context))
357 return NULL; /* never set */
358 GNUNET_assert (size == client->user_context_size);
359 return client->user_context;
360}
361
362
363/**
364 * Set user context to be associated with the given client.
365 * Note: you should probably use the macro (call without the underscore).
366 *
367 * @param client client to query
368 * @param ptr pointer to user context
369 * @param size number of bytes in user context struct (for verification only)
370 */
371void
372GNUNET_SERVER_client_set_user_context_ (struct GNUNET_SERVER_Client *client,
373 void *ptr,
374 size_t size)
375{
376 if (NULL == ptr)
377 {
378 client->user_context_size = 0;
379 client->user_context = ptr;
380 return;
381 }
382 client->user_context_size = size;
383 client->user_context = ptr;
384}
385
386
387/**
388 * Scheduler says our listen socket is ready. Process it!
389 *
390 * @param cls handle to our server for which we are processing the listen
391 * socket
392 */
393static void
394process_listen_socket (void *cls)
395{
396 struct GNUNET_SERVER_Handle *server = cls;
397 const struct GNUNET_SCHEDULER_TaskContext *tc;
398 struct GNUNET_CONNECTION_Handle *sock;
399 unsigned int i;
400
401 server->listen_task = NULL;
402 tc = GNUNET_SCHEDULER_get_task_context ();
403 for (i = 0; NULL != server->listen_sockets[i]; i++)
404 {
405 if (GNUNET_NETWORK_fdset_isset (tc->read_ready,
406 server->listen_sockets[i]))
407 {
408 sock =
409 GNUNET_CONNECTION_create_from_accept (server->access_cb,
410 server->access_cb_cls,
411 server->listen_sockets[i]);
412 if (NULL != sock)
413 {
414 LOG (GNUNET_ERROR_TYPE_DEBUG,
415 "Server accepted incoming connection.\n");
416 (void) GNUNET_SERVER_connect_socket (server,
417 sock);
418 }
419 }
420 }
421 /* listen for more! */
422 GNUNET_SERVER_resume (server);
423}
424
425
426/**
427 * Create and initialize a listen socket for the server.
428 *
429 * @param server_addr address to listen on
430 * @param socklen length of @a server_addr
431 * @return NULL on error, otherwise the listen socket
432 */
433static struct GNUNET_NETWORK_Handle *
434open_listen_socket (const struct sockaddr *server_addr,
435 socklen_t socklen)
436{
437 struct GNUNET_NETWORK_Handle *sock;
438 uint16_t port;
439 int eno;
440
441 switch (server_addr->sa_family)
442 {
443 case AF_INET:
444 port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
445 break;
446 case AF_INET6:
447 port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
448 break;
449 case AF_UNIX:
450 port = 0;
451 break;
452 default:
453 GNUNET_break (0);
454 port = 0;
455 break;
456 }
457 sock = GNUNET_NETWORK_socket_create (server_addr->sa_family, SOCK_STREAM, 0);
458 if (NULL == sock)
459 {
460 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
461 errno = 0;
462 return NULL;
463 }
464 /* bind the socket */
465 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, server_addr, socklen))
466 {
467 eno = errno;
468 if (EADDRINUSE != errno)
469 {
470 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
471 * fail if we already took the port on IPv6; if both IPv4 and
472 * IPv6 binds fail, then our caller will log using the
473 * errno preserved in 'eno' */
474 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
475 "bind");
476 if (0 != port)
477 LOG (GNUNET_ERROR_TYPE_ERROR,
478 _("`%s' failed for port %d (%s).\n"),
479 "bind",
480 port,
481 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
482 eno = 0;
483 }
484 else
485 {
486 if (0 != port)
487 LOG (GNUNET_ERROR_TYPE_WARNING,
488 _("`%s' failed for port %d (%s): address already in use\n"),
489 "bind", port,
490 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
491 else if (AF_UNIX == server_addr->sa_family)
492 {
493 LOG (GNUNET_ERROR_TYPE_WARNING,
494 _("`%s' failed for `%s': address already in use\n"),
495 "bind",
496 GNUNET_a2s (server_addr, socklen));
497 }
498 }
499 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
500 errno = eno;
501 return NULL;
502 }
503 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
504 {
505 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
506 "listen");
507 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
508 errno = 0;
509 return NULL;
510 }
511 if (0 != port)
512 LOG (GNUNET_ERROR_TYPE_DEBUG,
513 "Server starts to listen on port %u.\n",
514 port);
515 return sock;
516}
517
518
519/**
520 * Create a new server.
521 *
522 * @param access_cb function for access control
523 * @param access_cb_cls closure for @a access_cb
524 * @param lsocks NULL-terminated array of listen sockets
525 * @param idle_timeout after how long should we timeout idle connections?
526 * @param require_found if #GNUNET_YES, connections sending messages of unknown type
527 * will be closed
528 * @return handle for the new server, NULL on error
529 * (typically, "port" already in use)
530 */
531struct GNUNET_SERVER_Handle *
532GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access_cb,
533 void *access_cb_cls,
534 struct GNUNET_NETWORK_Handle **lsocks,
535 struct GNUNET_TIME_Relative idle_timeout,
536 int require_found)
537{
538 struct GNUNET_SERVER_Handle *server;
539
540 server = GNUNET_new (struct GNUNET_SERVER_Handle);
541 server->idle_timeout = idle_timeout;
542 server->listen_sockets = lsocks;
543 server->access_cb = access_cb;
544 server->access_cb_cls = access_cb_cls;
545 server->require_found = require_found;
546 if (NULL != lsocks)
547 GNUNET_SERVER_resume (server);
548 return server;
549}
550
551
552/**
553 * Create a new server.
554 *
555 * @param access_cb function for access control
556 * @param access_cb_cls closure for @a access_cb
557 * @param server_addr address to listen on (including port), NULL terminated array
558 * @param socklen length of server_addr
559 * @param idle_timeout after how long should we timeout idle connections?
560 * @param require_found if YES, connections sending messages of unknown type
561 * will be closed
562 * @return handle for the new server, NULL on error
563 * (typically, "port" already in use)
564 */
565struct GNUNET_SERVER_Handle *
566GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access_cb,
567 void *access_cb_cls,
568 struct sockaddr *const *server_addr,
569 const socklen_t * socklen,
570 struct GNUNET_TIME_Relative idle_timeout,
571 int require_found)
572{
573 struct GNUNET_NETWORK_Handle **lsocks;
574 unsigned int i;
575 unsigned int j;
576 unsigned int k;
577 int seen;
578
579 i = 0;
580 while (NULL != server_addr[i])
581 i++;
582 if (i > 0)
583 {
584 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
585 i = 0;
586 j = 0;
587 while (NULL != server_addr[i])
588 {
589 seen = 0;
590 for (k=0;k<i;k++)
591 if ( (socklen[k] == socklen[i]) &&
592 (0 == memcmp (server_addr[k], server_addr[i], socklen[i])) )
593 {
594 seen = 1;
595 break;
596 }
597 if (0 != seen)
598 {
599 /* duplicate address, skip */
600 i++;
601 continue;
602 }
603 lsocks[j] = open_listen_socket (server_addr[i], socklen[i]);
604 if (NULL != lsocks[j])
605 j++;
606 i++;
607 }
608 if (0 == j)
609 {
610 if (0 != errno)
611 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
612 GNUNET_free (lsocks);
613 lsocks = NULL;
614 }
615 }
616 else
617 {
618 lsocks = NULL;
619 }
620 return GNUNET_SERVER_create_with_sockets (access_cb,
621 access_cb_cls,
622 lsocks,
623 idle_timeout,
624 require_found);
625}
626
627
628/**
629 * Set the 'monitor' flag on this client. Clients which have been
630 * marked as 'monitors' won't prevent the server from shutting down
631 * once '#GNUNET_SERVER_stop_listening()' has been invoked. The idea is
632 * that for "normal" clients we likely want to allow them to process
633 * their requests; however, monitor-clients are likely to 'never'
634 * disconnect during shutdown and thus will not be considered when
635 * determining if the server should continue to exist after
636 * #GNUNET_SERVER_destroy() has been called.
637 *
638 * @param client the client to set the 'monitor' flag on
639 */
640void
641GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
642{
643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
644 "Marking client as monitor!\n");
645 client->is_monitor = GNUNET_YES;
646}
647
648
649/**
650 * Helper function for #test_monitor_clients() to trigger
651 * #GNUNET_SERVER_destroy() after the stack has unwound.
652 *
653 * @param cls the `struct GNUNET_SERVER_Handle *` to destroy
654 */
655static void
656do_destroy (void *cls)
657{
658 struct GNUNET_SERVER_Handle *server = cls;
659
660 GNUNET_SERVER_destroy (server);
661}
662
663
664/**
665 * Check if only 'monitor' clients are left. If so, destroy the
666 * server completely.
667 *
668 * @param server server to test for full shutdown
669 */
670static void
671test_monitor_clients (struct GNUNET_SERVER_Handle *server)
672{
673 struct GNUNET_SERVER_Client *client;
674
675 if (GNUNET_YES != server->in_soft_shutdown)
676 return;
677 for (client = server->clients_head; NULL != client; client = client->next)
678 if (GNUNET_NO == client->is_monitor)
679 return; /* not done yet */
680 server->in_soft_shutdown = GNUNET_SYSERR;
681 (void) GNUNET_SCHEDULER_add_now (&do_destroy, server);
682}
683
684
685/**
686 * Suspend accepting connections from the listen socket temporarily.
687 *
688 * @param server server to stop accepting connections.
689 */
690void
691GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
692{
693 if (NULL != server->listen_task)
694 {
695 GNUNET_SCHEDULER_cancel (server->listen_task);
696 server->listen_task = NULL;
697 }
698}
699
700
701/**
702 * Resume accepting connections from the listen socket.
703 *
704 * @param server server to stop accepting connections.
705 */
706void
707GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
708{
709 struct GNUNET_NETWORK_FDSet *r;
710 unsigned int i;
711
712 if (NULL == server->listen_sockets)
713 return;
714 if (NULL == server->listen_sockets[0])
715 return; /* nothing to do, no listen sockets! */
716 if (NULL == server->listen_sockets[1])
717 {
718 /* simplified method: no fd set needed; this is then much simpler
719 and much more efficient */
720 server->listen_task =
721 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
722 GNUNET_SCHEDULER_PRIORITY_HIGH,
723 server->listen_sockets[0],
724 &process_listen_socket, server);
725 return;
726 }
727 r = GNUNET_NETWORK_fdset_create ();
728 i = 0;
729 while (NULL != server->listen_sockets[i])
730 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
731 server->listen_task =
732 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
733 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
734 &process_listen_socket, server);
735 GNUNET_NETWORK_fdset_destroy (r);
736}
737
738
739/**
740 * Stop the listen socket and get ready to shutdown the server
741 * once only 'monitor' clients are left.
742 *
743 * @param server server to stop listening on
744 */
745void
746GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
747{
748 unsigned int i;
749
750 LOG (GNUNET_ERROR_TYPE_DEBUG,
751 "Server in soft shutdown\n");
752 if (NULL != server->listen_task)
753 {
754 GNUNET_SCHEDULER_cancel (server->listen_task);
755 server->listen_task = NULL;
756 }
757 if (NULL != server->listen_sockets)
758 {
759 i = 0;
760 while (NULL != server->listen_sockets[i])
761 GNUNET_break (GNUNET_OK ==
762 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
763 GNUNET_free (server->listen_sockets);
764 server->listen_sockets = NULL;
765 }
766 if (GNUNET_NO == server->in_soft_shutdown)
767 server->in_soft_shutdown = GNUNET_YES;
768 test_monitor_clients (server);
769}
770
771
772/**
773 * Free resources held by this server.
774 *
775 * @param server server to destroy
776 */
777void
778GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
779{
780 struct HandlerList *hpos;
781 struct NotifyList *npos;
782 unsigned int i;
783
784 LOG (GNUNET_ERROR_TYPE_DEBUG,
785 "Server shutting down.\n");
786 if (NULL != server->listen_task)
787 {
788 GNUNET_SCHEDULER_cancel (server->listen_task);
789 server->listen_task = NULL;
790 }
791 if (NULL != server->listen_sockets)
792 {
793 i = 0;
794 while (NULL != server->listen_sockets[i])
795 GNUNET_break (GNUNET_OK ==
796 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
797 GNUNET_free (server->listen_sockets);
798 server->listen_sockets = NULL;
799 }
800 while (NULL != server->clients_head)
801 GNUNET_SERVER_client_disconnect (server->clients_head);
802 while (NULL != (hpos = server->handlers))
803 {
804 server->handlers = hpos->next;
805 GNUNET_free (hpos);
806 }
807 while (NULL != (npos = server->disconnect_notify_list_head))
808 {
809 npos->callback (npos->callback_cls,
810 NULL);
811 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
812 server->disconnect_notify_list_tail,
813 npos);
814 GNUNET_free (npos);
815 }
816 while (NULL != (npos = server->connect_notify_list_head))
817 {
818 npos->callback (npos->callback_cls,
819 NULL);
820 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
821 server->connect_notify_list_tail,
822 npos);
823 GNUNET_free (npos);
824 }
825 GNUNET_free (server);
826}
827
828
829/**
830 * Add additional handlers to an existing server.
831 *
832 * @param server the server to add handlers to
833 * @param handlers array of message handlers for
834 * incoming messages; the last entry must
835 * have "NULL" for the "callback"; multiple
836 * entries for the same type are allowed,
837 * they will be called in order of occurence.
838 * These handlers can be removed later;
839 * the handlers array must exist until removed
840 * (or server is destroyed).
841 */
842void
843GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
844 const struct GNUNET_SERVER_MessageHandler *handlers)
845{
846 struct HandlerList *p;
847
848 p = GNUNET_new (struct HandlerList);
849 p->handlers = handlers;
850 p->next = server->handlers;
851 server->handlers = p;
852}
853
854
855/**
856 * Change functions used by the server to tokenize the message stream.
857 * (very rarely used).
858 *
859 * @param server server to modify
860 * @param create new tokenizer initialization function
861 * @param destroy new tokenizer destruction function
862 * @param receive new tokenizer receive function
863 * @param cls closure for @a create, @a receive, @a destroy
864 */
865void
866GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
867 GNUNET_SERVER_MstCreateCallback create,
868 GNUNET_SERVER_MstDestroyCallback destroy,
869 GNUNET_SERVER_MstReceiveCallback receive,
870 void *cls)
871{
872 server->mst_create = create;
873 server->mst_destroy = destroy;
874 server->mst_receive = receive;
875 server->mst_cls = cls;
876}
877
878
879/**
880 * Task run to warn about missing calls to #GNUNET_SERVER_receive_done.
881 *
882 * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
883 */
884static void
885warn_no_receive_done (void *cls)
886{
887 struct GNUNET_SERVER_Client *client = cls;
888
889 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
890 client->warn_task =
891 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
892 &warn_no_receive_done, client);
893 LOG (GNUNET_ERROR_TYPE_WARNING,
894 _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
895 (unsigned int) client->warn_type,
896 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start),
897 GNUNET_YES));
898}
899
900
901/**
902 * Disable the warning the server issues if a message is not acknowledged
903 * in a timely fashion. Use this call if a client is intentionally delayed
904 * for a while. Only applies to the current message.
905 *
906 * @param client client for which to disable the warning
907 */
908void
909GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
910{
911 if (NULL != client->warn_task)
912 {
913 GNUNET_SCHEDULER_cancel (client->warn_task);
914 client->warn_task = NULL;
915 }
916}
917
918
919/**
920 * Inject a message into the server, pretend it came
921 * from the specified client. Delivery of the message
922 * will happen instantly (if a handler is installed;
923 * otherwise the call does nothing).
924 *
925 * @param server the server receiving the message
926 * @param sender the "pretended" sender of the message
927 * can be NULL!
928 * @param message message to transmit
929 * @return #GNUNET_OK if the message was OK and the
930 * connection can stay open
931 * #GNUNET_SYSERR if the connection to the
932 * client should be shut down
933 */
934int
935GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
936 struct GNUNET_SERVER_Client *sender,
937 const struct GNUNET_MessageHeader *message)
938{
939 struct HandlerList *pos;
940 const struct GNUNET_SERVER_MessageHandler *mh;
941 unsigned int i;
942 uint16_t type;
943 uint16_t size;
944 int found;
945
946 type = ntohs (message->type);
947 size = ntohs (message->size);
948 LOG (GNUNET_ERROR_TYPE_INFO,
949 "Received message of type %u and size %u from client\n",
950 type, size);
951 found = GNUNET_NO;
952 for (pos = server->handlers; NULL != pos; pos = pos->next)
953 {
954 i = 0;
955 while (pos->handlers[i].callback != NULL)
956 {
957 mh = &pos->handlers[i];
958 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
959 {
960 if ((0 != mh->expected_size) && (mh->expected_size != size))
961 {
962#if GNUNET8_NETWORK_IS_DEAD
963 LOG (GNUNET_ERROR_TYPE_WARNING,
964 "Expected %u bytes for message of type %u, got %u\n",
965 mh->expected_size, mh->type, size);
966 GNUNET_break_op (0);
967#else
968 LOG (GNUNET_ERROR_TYPE_DEBUG,
969 "Expected %u bytes for message of type %u, got %u\n",
970 mh->expected_size, mh->type, size);
971#endif
972 return GNUNET_SYSERR;
973 }
974 if (NULL != sender)
975 {
976 if ( (0 == sender->suspended) &&
977 (NULL == sender->warn_task) )
978 {
979 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
980 sender->warn_start = GNUNET_TIME_absolute_get ();
981 sender->warn_task =
982 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
983 &warn_no_receive_done,
984 sender);
985 sender->warn_type = type;
986 }
987 sender->suspended++;
988 }
989 mh->callback (mh->callback_cls, sender, message);
990 found = GNUNET_YES;
991 }
992 i++;
993 }
994 }
995 if (GNUNET_NO == found)
996 {
997 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
998 "Received message of unknown type %d\n", type);
999 if (GNUNET_YES == server->require_found)
1000 return GNUNET_SYSERR;
1001 }
1002 return GNUNET_OK;
1003}
1004
1005
1006/**
1007 * We are receiving an incoming message. Process it.
1008 *
1009 * @param cls our closure (handle for the client)
1010 * @param buf buffer with data received from network
1011 * @param available number of bytes available in buf
1012 * @param addr address of the sender
1013 * @param addrlen length of @a addr
1014 * @param errCode code indicating errors receiving, 0 for success
1015 */
1016static void
1017process_incoming (void *cls,
1018 const void *buf,
1019 size_t available,
1020 const struct sockaddr *addr,
1021 socklen_t addrlen,
1022 int errCode);
1023
1024
1025/**
1026 * Process messages from the client's message tokenizer until either
1027 * the tokenizer is empty (and then schedule receiving more), or
1028 * until some handler is not immediately done (then wait for restart_processing)
1029 * or shutdown.
1030 *
1031 * @param client the client to process, RC must have already been increased
1032 * using #GNUNET_SERVER_client_keep and will be decreased by one in this
1033 * function
1034 * @param ret #GNUNET_NO to start processing from the buffer,
1035 * #GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
1036 * #GNUNET_SYSERR if we should instantly abort due to error in a previous step
1037 */
1038static void
1039process_mst (struct GNUNET_SERVER_Client *client,
1040 int ret)
1041{
1042 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
1043 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
1044 {
1045 if (GNUNET_OK == ret)
1046 {
1047 LOG (GNUNET_ERROR_TYPE_DEBUG,
1048 "Server re-enters receive loop, timeout: %s.\n",
1049 GNUNET_STRINGS_relative_time_to_string (client->idle_timeout, GNUNET_YES));
1050 client->receive_pending = GNUNET_YES;
1051 GNUNET_CONNECTION_receive (client->connection,
1052 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1053 client->idle_timeout,
1054 &process_incoming,
1055 client);
1056 break;
1057 }
1058 LOG (GNUNET_ERROR_TYPE_DEBUG,
1059 "Server processes additional messages instantly.\n");
1060 if (NULL != client->server->mst_receive)
1061 ret =
1062 client->server->mst_receive (client->server->mst_cls, client->mst,
1063 client, NULL, 0, GNUNET_NO, GNUNET_YES);
1064 else
1065 ret =
1066 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1067 GNUNET_YES);
1068 }
1069 LOG (GNUNET_ERROR_TYPE_DEBUG,
1070 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1071 ret, client->server,
1072 client->shutdown_now,
1073 client->suspended);
1074 if (GNUNET_NO == ret)
1075 {
1076 LOG (GNUNET_ERROR_TYPE_DEBUG,
1077 "Server has more data pending but is suspended.\n");
1078 client->receive_pending = GNUNET_SYSERR; /* data pending */
1079 }
1080 if ( (GNUNET_SYSERR == ret) ||
1081 (GNUNET_YES == client->shutdown_now) )
1082 GNUNET_SERVER_client_disconnect (client);
1083}
1084
1085
1086/**
1087 * We are receiving an incoming message. Process it.
1088 *
1089 * @param cls our closure (handle for the client)
1090 * @param buf buffer with data received from network
1091 * @param available number of bytes available in buf
1092 * @param addr address of the sender
1093 * @param addrlen length of @a addr
1094 * @param errCode code indicating errors receiving, 0 for success
1095 */
1096static void
1097process_incoming (void *cls,
1098 const void *buf,
1099 size_t available,
1100 const struct sockaddr *addr,
1101 socklen_t addrlen,
1102 int errCode)
1103{
1104 struct GNUNET_SERVER_Client *client = cls;
1105 struct GNUNET_SERVER_Handle *server = client->server;
1106 struct GNUNET_TIME_Absolute end;
1107 struct GNUNET_TIME_Absolute now;
1108 int ret;
1109
1110 GNUNET_assert (GNUNET_YES == client->receive_pending);
1111 client->receive_pending = GNUNET_NO;
1112 now = GNUNET_TIME_absolute_get ();
1113 end = GNUNET_TIME_absolute_add (client->last_activity,
1114 client->idle_timeout);
1115
1116 if ( (NULL == buf) &&
1117 (0 == available) &&
1118 (NULL == addr) &&
1119 (0 == errCode) &&
1120 (GNUNET_YES != client->shutdown_now) &&
1121 (NULL != server) &&
1122 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1123 (end.abs_value_us > now.abs_value_us) )
1124 {
1125 /* wait longer, timeout changed (i.e. due to us sending) */
1126 LOG (GNUNET_ERROR_TYPE_DEBUG,
1127 "Receive time out, but no disconnect due to sending (%p)\n",
1128 client);
1129 client->receive_pending = GNUNET_YES;
1130 GNUNET_CONNECTION_receive (client->connection,
1131 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1132 GNUNET_TIME_absolute_get_remaining (end),
1133 &process_incoming,
1134 client);
1135 return;
1136 }
1137 if ( (NULL == buf) ||
1138 (0 == available) ||
1139 (0 != errCode) ||
1140 (NULL == server) ||
1141 (GNUNET_YES == client->shutdown_now) ||
1142 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)) )
1143 {
1144 /* other side closed connection, error connecting, etc. */
1145 LOG (GNUNET_ERROR_TYPE_DEBUG,
1146 "Failed to connect or other side closed connection (%p)\n",
1147 client);
1148 GNUNET_SERVER_client_disconnect (client);
1149 return;
1150 }
1151 LOG (GNUNET_ERROR_TYPE_DEBUG,
1152 "Server receives %u bytes from `%s'.\n",
1153 (unsigned int) available,
1154 GNUNET_a2s (addr, addrlen));
1155 GNUNET_SERVER_client_keep (client);
1156 client->last_activity = now;
1157
1158 if (NULL != server->mst_receive)
1159 {
1160 ret = client->server->mst_receive (client->server->mst_cls,
1161 client->mst,
1162 client,
1163 buf,
1164 available,
1165 GNUNET_NO,
1166 GNUNET_YES);
1167 }
1168 else if (NULL != client->mst)
1169 {
1170 ret =
1171 GNUNET_SERVER_mst_receive (client->mst,
1172 client,
1173 buf,
1174 available,
1175 GNUNET_NO,
1176 GNUNET_YES);
1177 }
1178 else
1179 {
1180 GNUNET_break (0);
1181 return;
1182 }
1183 process_mst (client,
1184 ret);
1185 GNUNET_SERVER_client_drop (client);
1186}
1187
1188
1189/**
1190 * Task run to start again receiving from the network
1191 * and process requests.
1192 *
1193 * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
1194 */
1195static void
1196restart_processing (void *cls)
1197{
1198 struct GNUNET_SERVER_Client *client = cls;
1199
1200 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1201 client->restart_task = NULL;
1202 if (GNUNET_NO == client->receive_pending)
1203 {
1204 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1205 client->receive_pending = GNUNET_YES;
1206 GNUNET_CONNECTION_receive (client->connection,
1207 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1208 client->idle_timeout,
1209 &process_incoming,
1210 client);
1211 return;
1212 }
1213 LOG (GNUNET_ERROR_TYPE_DEBUG,
1214 "Server continues processing messages still in the buffer.\n");
1215 GNUNET_SERVER_client_keep (client);
1216 client->receive_pending = GNUNET_NO;
1217 process_mst (client,
1218 GNUNET_NO);
1219 GNUNET_SERVER_client_drop (client);
1220}
1221
1222
1223/**
1224 * This function is called whenever our inbound message tokenizer has
1225 * received a complete message.
1226 *
1227 * @param cls closure (struct GNUNET_SERVER_Handle)
1228 * @param client identification of the client (`struct GNUNET_SERVER_Client *`)
1229 * @param message the actual message
1230 *
1231 * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
1232 */
1233static int
1234client_message_tokenizer_callback (void *cls,
1235 void *client,
1236 const struct GNUNET_MessageHeader *message)
1237{
1238 struct GNUNET_SERVER_Handle *server = cls;
1239 struct GNUNET_SERVER_Client *sender = client;
1240 int ret;
1241
1242 LOG (GNUNET_ERROR_TYPE_DEBUG,
1243 "Tokenizer gives server message of type %u and size %u from client\n",
1244 ntohs (message->type), ntohs (message->size));
1245 sender->in_process_client_buffer = GNUNET_YES;
1246 ret = GNUNET_SERVER_inject (server, sender, message);
1247 sender->in_process_client_buffer = GNUNET_NO;
1248 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1249 {
1250 GNUNET_SERVER_client_disconnect (sender);
1251 return GNUNET_SYSERR;
1252 }
1253 return GNUNET_OK;
1254}
1255
1256
1257/**
1258 * Add a TCP socket-based connection to the set of handles managed by
1259 * this server. Use this function for outgoing (P2P) connections that
1260 * we initiated (and where this server should process incoming
1261 * messages).
1262 *
1263 * @param server the server to use
1264 * @param connection the connection to manage (client must
1265 * stop using this connection from now on)
1266 * @return the client handle
1267 */
1268struct GNUNET_SERVER_Client *
1269GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1270 struct GNUNET_CONNECTION_Handle *connection)
1271{
1272 struct GNUNET_SERVER_Client *client;
1273 struct NotifyList *n;
1274
1275 client = GNUNET_new (struct GNUNET_SERVER_Client);
1276 client->connection = connection;
1277 client->server = server;
1278 client->last_activity = GNUNET_TIME_absolute_get ();
1279 client->idle_timeout = server->idle_timeout;
1280 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1281 server->clients_tail,
1282 client);
1283 if (NULL != server->mst_create)
1284 client->mst =
1285 server->mst_create (server->mst_cls, client);
1286 else
1287 client->mst =
1288 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback,
1289 server);
1290 GNUNET_assert (NULL != client->mst);
1291 for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1292 n->callback (n->callback_cls, client);
1293 client->receive_pending = GNUNET_YES;
1294 GNUNET_CONNECTION_receive (client->connection,
1295 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1296 client->idle_timeout,
1297 &process_incoming,
1298 client);
1299 return client;
1300}
1301
1302
1303/**
1304 * Change the timeout for a particular client. Decreasing the timeout
1305 * may not go into effect immediately (only after the previous timeout
1306 * times out or activity happens on the socket).
1307 *
1308 * @param client the client to update
1309 * @param timeout new timeout for activities on the socket
1310 */
1311void
1312GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1313 struct GNUNET_TIME_Relative timeout)
1314{
1315 client->idle_timeout = timeout;
1316}
1317
1318
1319/**
1320 * Notify the server that the given client handle should
1321 * be kept (keeps the connection up if possible, increments
1322 * the internal reference counter).
1323 *
1324 * @param client the client to keep
1325 */
1326void
1327GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1328{
1329 client->reference_count++;
1330}
1331
1332
1333/**
1334 * Notify the server that the given client handle is no
1335 * longer required. Decrements the reference counter. If
1336 * that counter reaches zero an inactive connection maybe
1337 * closed.
1338 *
1339 * @param client the client to drop
1340 */
1341void
1342GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1343{
1344 GNUNET_assert (client->reference_count > 0);
1345 client->reference_count--;
1346 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1347 GNUNET_SERVER_client_disconnect (client);
1348}
1349
1350
1351/**
1352 * Obtain the network address of the other party.
1353 *
1354 * @param client the client to get the address for
1355 * @param addr where to store the address
1356 * @param addrlen where to store the length of the @a addr
1357 * @return #GNUNET_OK on success
1358 */
1359int
1360GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1361 void **addr, size_t * addrlen)
1362{
1363 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1364}
1365
1366
1367/**
1368 * Ask the server to notify us whenever a client disconnects.
1369 * This function is called whenever the actual network connection
1370 * is closed; the reference count may be zero or larger than zero
1371 * at this point.
1372 *
1373 * @param server the server manageing the clients
1374 * @param callback function to call on disconnect
1375 * @param callback_cls closure for @a callback
1376 */
1377void
1378GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1379 GNUNET_SERVER_DisconnectCallback callback,
1380 void *callback_cls)
1381{
1382 struct NotifyList *n;
1383
1384 n = GNUNET_new (struct NotifyList);
1385 n->callback = callback;
1386 n->callback_cls = callback_cls;
1387 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1388 server->disconnect_notify_list_tail,
1389 n);
1390}
1391
1392
1393/**
1394 * Ask the server to notify us whenever a client connects.
1395 * This function is called whenever the actual network connection
1396 * is opened. If the server is destroyed before this
1397 * notification is explicitly cancelled, the 'callback' will
1398 * once be called with a 'client' argument of NULL to indicate
1399 * that the server itself is now gone (and that the callback
1400 * won't be called anymore and also can no longer be cancelled).
1401 *
1402 * @param server the server manageing the clients
1403 * @param callback function to call on sconnect
1404 * @param callback_cls closure for @a callback
1405 */
1406void
1407GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1408 GNUNET_SERVER_ConnectCallback callback,
1409 void *callback_cls)
1410{
1411 struct NotifyList *n;
1412 struct GNUNET_SERVER_Client *client;
1413
1414 n = GNUNET_new (struct NotifyList);
1415 n->callback = callback;
1416 n->callback_cls = callback_cls;
1417 GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1418 server->connect_notify_list_tail,
1419 n);
1420 for (client = server->clients_head; NULL != client; client = client->next)
1421 callback (callback_cls, client);
1422}
1423
1424
1425/**
1426 * Ask the server to stop notifying us whenever a client connects.
1427 *
1428 * @param server the server manageing the clients
1429 * @param callback function to call on connect
1430 * @param callback_cls closure for @a callback
1431 */
1432void
1433GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1434 GNUNET_SERVER_DisconnectCallback callback,
1435 void *callback_cls)
1436{
1437 struct NotifyList *pos;
1438
1439 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1440 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1441 break;
1442 if (NULL == pos)
1443 {
1444 GNUNET_break (0);
1445 return;
1446 }
1447 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1448 server->disconnect_notify_list_tail,
1449 pos);
1450 GNUNET_free (pos);
1451}
1452
1453
1454/**
1455 * Ask the server to stop notifying us whenever a client disconnects.
1456 *
1457 * @param server the server manageing the clients
1458 * @param callback function to call on disconnect
1459 * @param callback_cls closure for @a callback
1460 */
1461void
1462GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1463 GNUNET_SERVER_ConnectCallback callback,
1464 void *callback_cls)
1465{
1466 struct NotifyList *pos;
1467
1468 for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1469 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1470 break;
1471 if (NULL == pos)
1472 {
1473 GNUNET_break (0);
1474 return;
1475 }
1476 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1477 server->connect_notify_list_tail,
1478 pos);
1479 GNUNET_free (pos);
1480}
1481
1482
1483/**
1484 * Destroy the connection that is passed in via @a cls. Used
1485 * as calling #GNUNET_CONNECTION_destroy from within a function
1486 * that was itself called from within process_notify() of
1487 * 'connection.c' is not allowed (see #2329).
1488 *
1489 * @param cls connection to destroy
1490 */
1491static void
1492destroy_connection (void *cls)
1493{
1494 struct GNUNET_CONNECTION_Handle *connection = cls;
1495
1496 GNUNET_CONNECTION_destroy (connection);
1497}
1498
1499
1500/**
1501 * Ask the server to disconnect from the given client.
1502 * This is the same as returning #GNUNET_SYSERR from a message
1503 * handler, except that it allows dropping of a client even
1504 * when not handling a message from that client.
1505 *
1506 * @param client the client to disconnect from
1507 */
1508void
1509GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1510{
1511 struct GNUNET_SERVER_Handle *server = client->server;
1512 struct NotifyList *n;
1513
1514 LOG (GNUNET_ERROR_TYPE_DEBUG,
1515 "Client is being disconnected from the server.\n");
1516 if (NULL != client->restart_task)
1517 {
1518 GNUNET_SCHEDULER_cancel (client->restart_task);
1519 client->restart_task = NULL;
1520 }
1521 if (NULL != client->warn_task)
1522 {
1523 GNUNET_SCHEDULER_cancel (client->warn_task);
1524 client->warn_task = NULL;
1525 }
1526 if (GNUNET_YES == client->receive_pending)
1527 {
1528 GNUNET_CONNECTION_receive_cancel (client->connection);
1529 client->receive_pending = GNUNET_NO;
1530 }
1531 client->shutdown_now = GNUNET_YES;
1532 client->reference_count++; /* make sure nobody else clean up client... */
1533 if ( (NULL != client->mst) &&
1534 (NULL != server) )
1535 {
1536 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1537 server->clients_tail,
1538 client);
1539 if (NULL != server->mst_destroy)
1540 server->mst_destroy (server->mst_cls,
1541 client->mst);
1542 else
1543 GNUNET_SERVER_mst_destroy (client->mst);
1544 client->mst = NULL;
1545 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1546 n->callback (n->callback_cls,
1547 client);
1548 }
1549 client->reference_count--;
1550 if (client->reference_count > 0)
1551 {
1552 LOG (GNUNET_ERROR_TYPE_DEBUG,
1553 "RC of %p still positive, not destroying everything.\n",
1554 client);
1555 client->server = NULL;
1556 return;
1557 }
1558 if (GNUNET_YES == client->in_process_client_buffer)
1559 {
1560 LOG (GNUNET_ERROR_TYPE_DEBUG,
1561 "Still processing inputs of %p, not destroying everything.\n",
1562 client);
1563 return;
1564 }
1565 LOG (GNUNET_ERROR_TYPE_DEBUG,
1566 "RC of %p now zero, destroying everything.\n",
1567 client);
1568 if (GNUNET_YES == client->persist)
1569 GNUNET_CONNECTION_persist_ (client->connection);
1570 if (NULL != client->th.cth)
1571 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1572 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1573 client->connection);
1574 /* need to cancel again, as it might have been re-added
1575 in the meantime (i.e. during callbacks) */
1576 if (NULL != client->warn_task)
1577 {
1578 GNUNET_SCHEDULER_cancel (client->warn_task);
1579 client->warn_task = NULL;
1580 }
1581 if (GNUNET_YES == client->receive_pending)
1582 {
1583 GNUNET_CONNECTION_receive_cancel (client->connection);
1584 client->receive_pending = GNUNET_NO;
1585 }
1586 GNUNET_free (client);
1587 /* we might be in soft-shutdown, test if we're done */
1588 if (NULL != server)
1589 test_monitor_clients (server);
1590}
1591
1592
1593/**
1594 * Disable the "CORK" feature for communication with the given client,
1595 * forcing the OS to immediately flush the buffer on transmission
1596 * instead of potentially buffering multiple messages.
1597 *
1598 * @param client handle to the client
1599 * @return #GNUNET_OK on success
1600 */
1601int
1602GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1603{
1604 return GNUNET_CONNECTION_disable_corking (client->connection);
1605}
1606
1607
1608/**
1609 * Wrapper for transmission notification that calls the original
1610 * callback and update the last activity time for our connection.
1611 *
1612 * @param cls the `struct GNUNET_SERVER_Client *`
1613 * @param size number of bytes we can transmit
1614 * @param buf where to copy the message
1615 * @return number of bytes actually transmitted
1616 */
1617static size_t
1618transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1619{
1620 struct GNUNET_SERVER_Client *client = cls;
1621 GNUNET_CONNECTION_TransmitReadyNotify callback;
1622
1623 client->th.cth = NULL;
1624 callback = client->th.callback;
1625 client->th.callback = NULL;
1626 client->last_activity = GNUNET_TIME_absolute_get ();
1627 return callback (client->th.callback_cls, size, buf);
1628}
1629
1630
1631/**
1632 * Notify us when the server has enough space to transmit
1633 * a message of the given size to the given client.
1634 *
1635 * @param client client to transmit message to
1636 * @param size requested amount of buffer space
1637 * @param timeout after how long should we give up (and call
1638 * notify with buf NULL and size 0)?
1639 * @param callback function to call when space is available
1640 * @param callback_cls closure for @a callback
1641 * @return non-NULL if the notify callback was queued; can be used
1642 * to cancel the request using
1643 * #GNUNET_SERVER_notify_transmit_ready_cancel().
1644 * NULL if we are already going to notify someone else (busy)
1645 */
1646struct GNUNET_SERVER_TransmitHandle *
1647GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1648 size_t size,
1649 struct GNUNET_TIME_Relative timeout,
1650 GNUNET_CONNECTION_TransmitReadyNotify callback,
1651 void *callback_cls)
1652{
1653 if (NULL != client->th.callback)
1654 return NULL;
1655 client->th.callback_cls = callback_cls;
1656 client->th.callback = callback;
1657 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1658 timeout,
1659 &transmit_ready_callback_wrapper,
1660 client);
1661 return &client->th;
1662}
1663
1664
1665/**
1666 * Abort transmission request.
1667 *
1668 * @param th request to abort
1669 */
1670void
1671GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1672{
1673 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1674 th->cth = NULL;
1675 th->callback = NULL;
1676}
1677
1678
1679/**
1680 * Set the persistent flag on this client, used to setup client connection
1681 * to only be killed when the service it's connected to is actually dead.
1682 *
1683 * @param client the client to set the persistent flag on
1684 */
1685void
1686GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1687{
1688 client->persist = GNUNET_YES;
1689}
1690
1691
1692/**
1693 * Resume receiving from this client, we are done processing the
1694 * current request. This function must be called from within each
1695 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1696 *
1697 * @param client client we were processing a message of
1698 * @param success #GNUNET_OK to keep the connection open and
1699 * continue to receive
1700 * #GNUNET_NO to close the connection (normal behavior)
1701 * #GNUNET_SYSERR to close the connection (signal
1702 * serious error)
1703 */
1704void
1705GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client,
1706 int success)
1707{
1708 if (NULL == client)
1709 return;
1710 GNUNET_assert (client->suspended > 0);
1711 client->suspended--;
1712 if (GNUNET_OK != success)
1713 {
1714 LOG (GNUNET_ERROR_TYPE_DEBUG,
1715 "GNUNET_SERVER_receive_done called with failure indication\n");
1716 if ( (client->reference_count > 0) || (client->suspended > 0) )
1717 client->shutdown_now = GNUNET_YES;
1718 else
1719 GNUNET_SERVER_client_disconnect (client);
1720 return;
1721 }
1722 if (client->suspended > 0)
1723 {
1724 LOG (GNUNET_ERROR_TYPE_DEBUG,
1725 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1726 return;
1727 }
1728 if (NULL != client->warn_task)
1729 {
1730 GNUNET_SCHEDULER_cancel (client->warn_task);
1731 client->warn_task = NULL;
1732 }
1733 if (GNUNET_YES == client->in_process_client_buffer)
1734 {
1735 LOG (GNUNET_ERROR_TYPE_DEBUG,
1736 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1737 return;
1738 }
1739 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1740 {
1741 GNUNET_SERVER_client_disconnect (client);
1742 return;
1743 }
1744 LOG (GNUNET_ERROR_TYPE_DEBUG,
1745 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1746 GNUNET_assert (NULL == client->restart_task);
1747 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing,
1748 client);
1749}
1750
1751
1752/* end of server.c */
diff --git a/src/util/service.c b/src/util/service.c
deleted file mode 100644
index 496904fb1..000000000
--- a/src/util/service.c
+++ /dev/null
@@ -1,1697 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009, 2012 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20
21/**
22 * @file util/service.c
23 * @brief functions related to starting services
24 * @author Christian Grothoff
25 */
26#include "platform.h"
27#include "gnunet_util_lib.h"
28#include "gnunet_protocols.h"
29#include "gnunet_constants.h"
30#include "gnunet_resolver_service.h"
31#include "speedup.h"
32
33#if HAVE_MALLINFO
34#include <malloc.h>
35#include "gauger.h"
36#endif
37
38
39#define LOG(kind,...) GNUNET_log_from (kind, "util-service", __VA_ARGS__)
40
41#define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-service", syscall)
42
43#define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-service", syscall, filename)
44
45
46/* ******************* access control ******************** */
47
48/**
49 * Check if the given IP address is in the list of IP addresses.
50 *
51 * @param list a list of networks
52 * @param add the IP to check (in network byte order)
53 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
54 */
55static int
56check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
57 const struct in_addr *add)
58{
59 unsigned int i;
60
61 if (NULL == list)
62 return GNUNET_NO;
63 i = 0;
64 while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
65 {
66 if ((add->s_addr & list[i].netmask.s_addr) ==
67 (list[i].network.s_addr & list[i].netmask.s_addr))
68 return GNUNET_YES;
69 i++;
70 }
71 return GNUNET_NO;
72}
73
74
75/**
76 * Check if the given IP address is in the list of IP addresses.
77 *
78 * @param list a list of networks
79 * @param ip the IP to check (in network byte order)
80 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
81 */
82static int
83check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
84 const struct in6_addr *ip)
85{
86 unsigned int i;
87 unsigned int j;
88 struct in6_addr zero;
89
90 if (NULL == list)
91 return GNUNET_NO;
92 memset (&zero, 0, sizeof (struct in6_addr));
93 i = 0;
94NEXT:
95 while (0 != memcmp (&zero, &list[i].network, sizeof (struct in6_addr)))
96 {
97 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
98 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
99 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
100 {
101 i++;
102 goto NEXT;
103 }
104 return GNUNET_YES;
105 }
106 return GNUNET_NO;
107}
108
109
110/* ****************** service struct ****************** */
111
112
113/**
114 * Context for "service_task".
115 */
116struct GNUNET_SERVICE_Context
117{
118 /**
119 * Our configuration.
120 */
121 const struct GNUNET_CONFIGURATION_Handle *cfg;
122
123 /**
124 * Handle for the server.
125 */
126 struct GNUNET_SERVER_Handle *server;
127
128 /**
129 * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
130 * listen sockets.
131 */
132 struct sockaddr **addrs;
133
134 /**
135 * Name of our service.
136 */
137 const char *service_name;
138
139 /**
140 * Main service-specific task to run.
141 */
142 GNUNET_SERVICE_Main task;
143
144 /**
145 * Closure for @e task.
146 */
147 void *task_cls;
148
149 /**
150 * IPv4 addresses that are not allowed to connect.
151 */
152 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_denied;
153
154 /**
155 * IPv6 addresses that are not allowed to connect.
156 */
157 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_denied;
158
159 /**
160 * IPv4 addresses that are allowed to connect (if not
161 * set, all are allowed).
162 */
163 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_allowed;
164
165 /**
166 * IPv6 addresses that are allowed to connect (if not
167 * set, all are allowed).
168 */
169 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_allowed;
170
171 /**
172 * My (default) message handlers. Adjusted copy
173 * of "defhandlers".
174 */
175 struct GNUNET_SERVER_MessageHandler *my_handlers;
176
177 /**
178 * Array of the lengths of the entries in addrs.
179 */
180 socklen_t *addrlens;
181
182 /**
183 * NULL-terminated array of listen sockets we should take over.
184 */
185 struct GNUNET_NETWORK_Handle **lsocks;
186
187 /**
188 * Task ID of the shutdown task.
189 */
190 struct GNUNET_SCHEDULER_Task *shutdown_task;
191
192 /**
193 * Idle timeout for server.
194 */
195 struct GNUNET_TIME_Relative timeout;
196
197 /**
198 * Overall success/failure of the service start.
199 */
200 int ret;
201
202 /**
203 * If we are daemonizing, this FD is set to the
204 * pipe to the parent. Send '.' if we started
205 * ok, '!' if not. -1 if we are not daemonizing.
206 */
207 int ready_confirm_fd;
208
209 /**
210 * Do we close connections if we receive messages
211 * for which we have no handler?
212 */
213 int require_found;
214
215 /**
216 * Do we require a matching UID for UNIX domain socket connections?
217 * #GNUNET_NO means that the UID does not have to match (however,
218 * @e match_gid may still impose other access control checks).
219 */
220 int match_uid;
221
222 /**
223 * Do we require a matching GID for UNIX domain socket connections?
224 * Ignored if @e match_uid is #GNUNET_YES. Note that this is about
225 * checking that the client's UID is in our group OR that the
226 * client's GID is our GID. If both "match_gid" and @e match_uid are
227 * #GNUNET_NO, all users on the local system have access.
228 */
229 int match_gid;
230
231 /**
232 * Our options.
233 */
234 enum GNUNET_SERVICE_Options options;
235
236};
237
238
239/* ****************** message handlers ****************** */
240
241/**
242 * Send a 'TEST' message back to the client.
243 *
244 * @param cls the 'struct GNUNET_SERVER_Client' to send TEST to
245 * @param size number of bytes available in 'buf'
246 * @param buf where to copy the message
247 * @return number of bytes written to 'buf'
248 */
249static size_t
250write_test (void *cls, size_t size, void *buf)
251{
252 struct GNUNET_SERVER_Client *client = cls;
253 struct GNUNET_MessageHeader *msg;
254
255 if (size < sizeof (struct GNUNET_MessageHeader))
256 {
257 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
258 return 0; /* client disconnected */
259 }
260 msg = (struct GNUNET_MessageHeader *) buf;
261 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
262 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
263 GNUNET_SERVER_receive_done (client, GNUNET_OK);
264 return sizeof (struct GNUNET_MessageHeader);
265}
266
267
268/**
269 * Handler for TEST message.
270 *
271 * @param cls closure (refers to service)
272 * @param client identification of the client
273 * @param message the actual message
274 */
275static void
276handle_test (void *cls, struct GNUNET_SERVER_Client *client,
277 const struct GNUNET_MessageHeader *message)
278{
279 /* simply bounce message back to acknowledge */
280 if (NULL ==
281 GNUNET_SERVER_notify_transmit_ready (client,
282 sizeof (struct GNUNET_MessageHeader),
283 GNUNET_TIME_UNIT_FOREVER_REL,
284 &write_test, client))
285 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
286}
287
288
289/**
290 * Default handlers for all services. Will be copied and the
291 * "callback_cls" fields will be replaced with the specific service
292 * struct.
293 */
294static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
295 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
296 sizeof (struct GNUNET_MessageHeader)},
297 {NULL, NULL, 0, 0}
298};
299
300
301/* ****************** service core routines ************** */
302
303
304/**
305 * Check if access to the service is allowed from the given address.
306 *
307 * @param cls closure
308 * @param uc credentials, if available, otherwise NULL
309 * @param addr address
310 * @param addrlen length of address
311 * @return #GNUNET_YES to allow, #GNUNET_NO to deny, #GNUNET_SYSERR
312 * for unknown address family (will be denied).
313 */
314static int
315check_access (void *cls, const struct GNUNET_CONNECTION_Credentials *uc,
316 const struct sockaddr *addr, socklen_t addrlen)
317{
318 struct GNUNET_SERVICE_Context *sctx = cls;
319 const struct sockaddr_in *i4;
320 const struct sockaddr_in6 *i6;
321 int ret;
322
323 switch (addr->sa_family)
324 {
325 case AF_INET:
326 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
327 i4 = (const struct sockaddr_in *) addr;
328 ret = ((NULL == sctx->v4_allowed) ||
329 (check_ipv4_listed (sctx->v4_allowed, &i4->sin_addr))) &&
330 ((NULL == sctx->v4_denied) ||
331 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
332 break;
333 case AF_INET6:
334 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
335 i6 = (const struct sockaddr_in6 *) addr;
336 ret = ((NULL == sctx->v6_allowed) ||
337 (check_ipv6_listed (sctx->v6_allowed, &i6->sin6_addr))) &&
338 ((NULL == sctx->v6_denied) ||
339 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
340 break;
341#ifndef WINDOWS
342 case AF_UNIX:
343 ret = GNUNET_OK; /* controlled using file-system ACL now */
344 break;
345#endif
346 default:
347 LOG (GNUNET_ERROR_TYPE_WARNING, _("Unknown address family %d\n"),
348 addr->sa_family);
349 return GNUNET_SYSERR;
350 }
351 if (GNUNET_OK != ret)
352 {
353 LOG (GNUNET_ERROR_TYPE_WARNING,
354 _("Access from `%s' denied to service `%s'\n"),
355 GNUNET_a2s (addr, addrlen),
356 sctx->service_name);
357 }
358 return ret;
359}
360
361
362/**
363 * Get the name of the file where we will
364 * write the PID of the service.
365 *
366 * @param sctx service context
367 * @return name of the file for the process ID
368 */
369static char *
370get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
371{
372 char *pif;
373
374 if (GNUNET_OK !=
375 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->service_name,
376 "PIDFILE", &pif))
377 return NULL;
378 return pif;
379}
380
381
382/**
383 * Parse an IPv4 access control list.
384 *
385 * @param ret location where to write the ACL (set)
386 * @param sctx service context to use to get the configuration
387 * @param option name of the ACL option to parse
388 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
389 * no ACL configured)
390 */
391static int
392process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret,
393 struct GNUNET_SERVICE_Context *sctx,
394 const char *option)
395{
396 char *opt;
397
398 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, option))
399 {
400 *ret = NULL;
401 return GNUNET_OK;
402 }
403 GNUNET_break (GNUNET_OK ==
404 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
405 sctx->service_name,
406 option, &opt));
407 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt)))
408 {
409 LOG (GNUNET_ERROR_TYPE_WARNING,
410 _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
411 opt, sctx->service_name, option);
412 GNUNET_free (opt);
413 return GNUNET_SYSERR;
414 }
415 GNUNET_free (opt);
416 return GNUNET_OK;
417}
418
419
420/**
421 * Parse an IPv6 access control list.
422 *
423 * @param ret location where to write the ACL (set)
424 * @param sctx service context to use to get the configuration
425 * @param option name of the ACL option to parse
426 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
427 * no ACL configured)
428 */
429static int
430process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret,
431 struct GNUNET_SERVICE_Context *sctx,
432 const char *option)
433{
434 char *opt;
435
436 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, option))
437 {
438 *ret = NULL;
439 return GNUNET_OK;
440 }
441 GNUNET_break (GNUNET_OK ==
442 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
443 sctx->service_name,
444 option, &opt));
445 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt)))
446 {
447 LOG (GNUNET_ERROR_TYPE_WARNING,
448 _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
449 opt, sctx->service_name, option);
450 GNUNET_free (opt);
451 return GNUNET_SYSERR;
452 }
453 GNUNET_free (opt);
454 return GNUNET_OK;
455}
456
457
458/**
459 * Add the given UNIX domain path as an address to the
460 * list (as the first entry).
461 *
462 * @param saddrs array to update
463 * @param saddrlens where to store the address length
464 * @param unixpath path to add
465 * @param abstract #GNUNET_YES to add an abstract UNIX domain socket. This
466 * parameter is ignore on systems other than LINUX
467 */
468static void
469add_unixpath (struct sockaddr **saddrs,
470 socklen_t *saddrlens,
471 const char *unixpath,
472 int abstract)
473{
474#ifdef AF_UNIX
475 struct sockaddr_un *un;
476
477 un = GNUNET_new (struct sockaddr_un);
478 un->sun_family = AF_UNIX;
479 strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
480#ifdef LINUX
481 if (GNUNET_YES == abstract)
482 un->sun_path[0] = '\0';
483#endif
484#if HAVE_SOCKADDR_UN_SUN_LEN
485 un->sun_len = (u_char) sizeof (struct sockaddr_un);
486#endif
487 *saddrs = (struct sockaddr *) un;
488 *saddrlens = sizeof (struct sockaddr_un);
489#else
490 /* this function should never be called
491 * unless AF_UNIX is defined! */
492 GNUNET_assert (0);
493#endif
494}
495
496
497/**
498 * Get the list of addresses that a server for the given service
499 * should bind to.
500 *
501 * @param service_name name of the service
502 * @param cfg configuration (which specifies the addresses)
503 * @param addrs set (call by reference) to an array of pointers to the
504 * addresses the server should bind to and listen on; the
505 * array will be NULL-terminated (on success)
506 * @param addr_lens set (call by reference) to an array of the lengths
507 * of the respective `struct sockaddr` struct in the @a addrs
508 * array (on success)
509 * @return number of addresses found on success,
510 * #GNUNET_SYSERR if the configuration
511 * did not specify reasonable finding information or
512 * if it specified a hostname that could not be resolved;
513 * #GNUNET_NO if the number of addresses configured is
514 * zero (in this case, `*addrs` and `*addr_lens` will be
515 * set to NULL).
516 */
517int
518GNUNET_SERVICE_get_server_addresses (const char *service_name,
519 const struct GNUNET_CONFIGURATION_Handle *cfg,
520 struct sockaddr ***addrs,
521 socklen_t ** addr_lens)
522{
523 int disablev6;
524 struct GNUNET_NETWORK_Handle *desc;
525 unsigned long long port;
526 char *unixpath;
527 struct addrinfo hints;
528 struct addrinfo *res;
529 struct addrinfo *pos;
530 struct addrinfo *next;
531 unsigned int i;
532 int resi;
533 int ret;
534 int abstract;
535 struct sockaddr **saddrs;
536 socklen_t *saddrlens;
537 char *hostname;
538
539 *addrs = NULL;
540 *addr_lens = NULL;
541 desc = NULL;
542 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "DISABLEV6"))
543 {
544 if (GNUNET_SYSERR ==
545 (disablev6 =
546 GNUNET_CONFIGURATION_get_value_yesno (cfg, service_name, "DISABLEV6")))
547 return GNUNET_SYSERR;
548 }
549 else
550 disablev6 = GNUNET_NO;
551
552 if (! disablev6)
553 {
554 /* probe IPv6 support */
555 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
556 if (NULL == desc)
557 {
558 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
559 (EACCES == errno))
560 {
561 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
562 return GNUNET_SYSERR;
563 }
564 LOG (GNUNET_ERROR_TYPE_INFO,
565 _("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
566 service_name, STRERROR (errno));
567 disablev6 = GNUNET_YES;
568 }
569 else
570 {
571 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
572 desc = NULL;
573 }
574 }
575
576 port = 0;
577 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
578 {
579 if (GNUNET_OK !=
580 GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
581 "PORT", &port))
582 {
583 LOG (GNUNET_ERROR_TYPE_ERROR,
584 _("Require valid port number for service `%s' in configuration!\n"),
585 service_name);
586 }
587 if (port > 65535)
588 {
589 LOG (GNUNET_ERROR_TYPE_ERROR,
590 _("Require valid port number for service `%s' in configuration!\n"),
591 service_name);
592 return GNUNET_SYSERR;
593 }
594 }
595
596 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "BINDTO"))
597 {
598 GNUNET_break (GNUNET_OK ==
599 GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
600 "BINDTO", &hostname));
601 }
602 else
603 hostname = NULL;
604
605 unixpath = NULL;
606 abstract = GNUNET_NO;
607#ifdef AF_UNIX
608 if ((GNUNET_YES ==
609 GNUNET_CONFIGURATION_have_value (cfg, service_name, "UNIXPATH")) &&
610 (GNUNET_OK ==
611 GNUNET_CONFIGURATION_get_value_filename (cfg, service_name, "UNIXPATH",
612 &unixpath)) &&
613 (0 < strlen (unixpath)))
614 {
615 /* probe UNIX support */
616 struct sockaddr_un s_un;
617
618 if (strlen (unixpath) >= sizeof (s_un.sun_path))
619 {
620 LOG (GNUNET_ERROR_TYPE_WARNING,
621 _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
622 (unsigned long long) sizeof (s_un.sun_path));
623 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
624 LOG (GNUNET_ERROR_TYPE_INFO,
625 _("Using `%s' instead\n"),
626 unixpath);
627 }
628#ifdef LINUX
629 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
630 "TESTING",
631 "USE_ABSTRACT_SOCKETS");
632 if (GNUNET_SYSERR == abstract)
633 abstract = GNUNET_NO;
634#endif
635 if ((GNUNET_YES != abstract)
636 && (GNUNET_OK !=
637 GNUNET_DISK_directory_create_for_file (unixpath)))
638 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
639 "mkdir",
640 unixpath);
641 }
642 if (NULL != unixpath)
643 {
644 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
645 if (NULL == desc)
646 {
647 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
648 (EACCES == errno))
649 {
650 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
651 GNUNET_free_non_null (hostname);
652 GNUNET_free (unixpath);
653 return GNUNET_SYSERR;
654 }
655 LOG (GNUNET_ERROR_TYPE_INFO,
656 _("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
657 service_name,
658 STRERROR (errno));
659 GNUNET_free (unixpath);
660 unixpath = NULL;
661 }
662 else
663 {
664 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
665 desc = NULL;
666 }
667 }
668#endif
669
670 if ((0 == port) && (NULL == unixpath))
671 {
672 LOG (GNUNET_ERROR_TYPE_ERROR,
673 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
674 service_name);
675 GNUNET_free_non_null (hostname);
676 return GNUNET_SYSERR;
677 }
678 if (0 == port)
679 {
680 saddrs = GNUNET_malloc (2 * sizeof (struct sockaddr *));
681 saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
682 add_unixpath (saddrs, saddrlens, unixpath, abstract);
683 GNUNET_free_non_null (unixpath);
684 GNUNET_free_non_null (hostname);
685 *addrs = saddrs;
686 *addr_lens = saddrlens;
687 return 1;
688 }
689
690 if (NULL != hostname)
691 {
692 LOG (GNUNET_ERROR_TYPE_DEBUG,
693 "Resolving `%s' since that is where `%s' will bind to.\n",
694 hostname,
695 service_name);
696 memset (&hints, 0, sizeof (struct addrinfo));
697 if (disablev6)
698 hints.ai_family = AF_INET;
699 hints.ai_protocol = IPPROTO_TCP;
700 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
701 (NULL == res))
702 {
703 LOG (GNUNET_ERROR_TYPE_ERROR,
704 _("Failed to resolve `%s': %s\n"),
705 hostname,
706 gai_strerror (ret));
707 GNUNET_free (hostname);
708 GNUNET_free_non_null (unixpath);
709 return GNUNET_SYSERR;
710 }
711 next = res;
712 i = 0;
713 while (NULL != (pos = next))
714 {
715 next = pos->ai_next;
716 if ((disablev6) && (pos->ai_family == AF_INET6))
717 continue;
718 i++;
719 }
720 if (0 == i)
721 {
722 LOG (GNUNET_ERROR_TYPE_ERROR,
723 _("Failed to find %saddress for `%s'.\n"),
724 disablev6 ? "IPv4 " : "",
725 hostname);
726 freeaddrinfo (res);
727 GNUNET_free (hostname);
728 GNUNET_free_non_null (unixpath);
729 return GNUNET_SYSERR;
730 }
731 resi = i;
732 if (NULL != unixpath)
733 resi++;
734 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
735 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
736 i = 0;
737 if (NULL != unixpath)
738 {
739 add_unixpath (saddrs, saddrlens, unixpath, abstract);
740 i++;
741 }
742 next = res;
743 while (NULL != (pos = next))
744 {
745 next = pos->ai_next;
746 if ((disablev6) && (AF_INET6 == pos->ai_family))
747 continue;
748 if ((IPPROTO_TCP != pos->ai_protocol) && (0 != pos->ai_protocol))
749 continue; /* not TCP */
750 if ((SOCK_STREAM != pos->ai_socktype) && (0 != pos->ai_socktype))
751 continue; /* huh? */
752 LOG (GNUNET_ERROR_TYPE_DEBUG, "Service `%s' will bind to `%s'\n",
753 service_name, GNUNET_a2s (pos->ai_addr, pos->ai_addrlen));
754 if (AF_INET == pos->ai_family)
755 {
756 GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
757 saddrlens[i] = pos->ai_addrlen;
758 saddrs[i] = GNUNET_malloc (saddrlens[i]);
759 GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
760 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
761 }
762 else
763 {
764 GNUNET_assert (AF_INET6 == pos->ai_family);
765 GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
766 saddrlens[i] = pos->ai_addrlen;
767 saddrs[i] = GNUNET_malloc (saddrlens[i]);
768 GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
769 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
770 }
771 i++;
772 }
773 GNUNET_free (hostname);
774 freeaddrinfo (res);
775 resi = i;
776 }
777 else
778 {
779 /* will bind against everything, just set port */
780 if (disablev6)
781 {
782 /* V4-only */
783 resi = 1;
784 if (NULL != unixpath)
785 resi++;
786 i = 0;
787 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
788 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
789 if (NULL != unixpath)
790 {
791 add_unixpath (saddrs, saddrlens, unixpath, abstract);
792 i++;
793 }
794 saddrlens[i] = sizeof (struct sockaddr_in);
795 saddrs[i] = GNUNET_malloc (saddrlens[i]);
796#if HAVE_SOCKADDR_IN_SIN_LEN
797 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
798#endif
799 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
800 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
801 }
802 else
803 {
804 /* dual stack */
805 resi = 2;
806 if (NULL != unixpath)
807 resi++;
808 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
809 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
810 i = 0;
811 if (NULL != unixpath)
812 {
813 add_unixpath (saddrs, saddrlens, unixpath, abstract);
814 i++;
815 }
816 saddrlens[i] = sizeof (struct sockaddr_in6);
817 saddrs[i] = GNUNET_malloc (saddrlens[i]);
818#if HAVE_SOCKADDR_IN_SIN_LEN
819 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
820#endif
821 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
822 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
823 i++;
824 saddrlens[i] = sizeof (struct sockaddr_in);
825 saddrs[i] = GNUNET_malloc (saddrlens[i]);
826#if HAVE_SOCKADDR_IN_SIN_LEN
827 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
828#endif
829 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
830 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
831 }
832 }
833 GNUNET_free_non_null (unixpath);
834 *addrs = saddrs;
835 *addr_lens = saddrlens;
836 return resi;
837}
838
839
840#ifdef MINGW
841/**
842 * Read listen sockets from the parent process (ARM).
843 *
844 * @param sctx service context to initialize
845 * @return #GNUNET_YES if ok, #GNUNET_NO if not ok (must bind yourself),
846 * and #GNUNET_SYSERR on error.
847 */
848static int
849receive_sockets_from_parent (struct GNUNET_SERVICE_Context *sctx)
850{
851 const char *env_buf;
852 int fail;
853 uint64_t count;
854 uint64_t i;
855 HANDLE lsocks_pipe;
856
857 env_buf = getenv ("GNUNET_OS_READ_LSOCKS");
858 if ((NULL == env_buf) || (strlen (env_buf) <= 0))
859 return GNUNET_NO;
860 /* Using W32 API directly here, because this pipe will
861 * never be used outside of this function, and it's just too much of a bother
862 * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
863 */
864 lsocks_pipe = (HANDLE) strtoul (env_buf, NULL, 10);
865 if ( (0 == lsocks_pipe) || (INVALID_HANDLE_VALUE == lsocks_pipe))
866 return GNUNET_NO;
867 fail = 1;
868 do
869 {
870 int ret;
871 int fail2;
872 DWORD rd;
873
874 ret = ReadFile (lsocks_pipe, &count, sizeof (count), &rd, NULL);
875 if ((0 == ret) || (sizeof (count) != rd) || (0 == count))
876 break;
877 sctx->lsocks =
878 GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (count + 1));
879
880 fail2 = 1;
881 for (i = 0; i < count; i++)
882 {
883 WSAPROTOCOL_INFOA pi;
884 uint64_t size;
885 SOCKET s;
886
887 ret = ReadFile (lsocks_pipe, &size, sizeof (size), &rd, NULL);
888 if ( (0 == ret) || (sizeof (size) != rd) || (sizeof (pi) != size) )
889 break;
890 ret = ReadFile (lsocks_pipe, &pi, sizeof (pi), &rd, NULL);
891 if ( (0 == ret) || (sizeof (pi) != rd))
892 break;
893 s = WSASocketA (pi.iAddressFamily, pi.iSocketType, pi.iProtocol, &pi, 0, WSA_FLAG_OVERLAPPED);
894 sctx->lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
895 if (NULL == sctx->lsocks[i])
896 break;
897 else if (i == count - 1)
898 fail2 = 0;
899 }
900 if (fail2)
901 break;
902 sctx->lsocks[count] = NULL;
903 fail = 0;
904 }
905 while (fail);
906
907 CloseHandle (lsocks_pipe);
908
909 if (fail)
910 {
911 LOG (GNUNET_ERROR_TYPE_ERROR,
912 _("Could not access a pre-bound socket, will try to bind myself\n"));
913 for (i = 0; (i < count) && (NULL != sctx->lsocks[i]); i++)
914 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[i]));
915 GNUNET_free_non_null (sctx->lsocks);
916 sctx->lsocks = NULL;
917 return GNUNET_NO;
918 }
919 return GNUNET_YES;
920}
921#endif
922
923
924/**
925 * Setup addr, addrlen, idle_timeout
926 * based on configuration!
927 *
928 * Configuration may specify:
929 * - PORT (where to bind to for TCP)
930 * - UNIXPATH (where to bind to for UNIX domain sockets)
931 * - TIMEOUT (after how many ms does an inactive service timeout);
932 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
933 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
934 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
935 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
936 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
937 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
938 *
939 * @param sctx service context to initialize
940 * @return #GNUNET_OK if configuration succeeded
941 */
942static int
943setup_service (struct GNUNET_SERVICE_Context *sctx)
944{
945 struct GNUNET_TIME_Relative idleout;
946 int tolerant;
947
948#ifndef MINGW
949 const char *nfds;
950 unsigned int cnt;
951 int flags;
952#endif
953
954 if (GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, "TIMEOUT"))
955 {
956 if (GNUNET_OK !=
957 GNUNET_CONFIGURATION_get_value_time (sctx->cfg, sctx->service_name,
958 "TIMEOUT", &idleout))
959 {
960 LOG (GNUNET_ERROR_TYPE_ERROR,
961 _("Specified value for `%s' of service `%s' is invalid\n"),
962 "TIMEOUT", sctx->service_name);
963 return GNUNET_SYSERR;
964 }
965 sctx->timeout = idleout;
966 }
967 else
968 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
969
970 if (GNUNET_CONFIGURATION_have_value
971 (sctx->cfg, sctx->service_name, "TOLERANT"))
972 {
973 if (GNUNET_SYSERR ==
974 (tolerant =
975 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
976 "TOLERANT")))
977 {
978 LOG (GNUNET_ERROR_TYPE_ERROR,
979 _("Specified value for `%s' of service `%s' is invalid\n"),
980 "TOLERANT", sctx->service_name);
981 return GNUNET_SYSERR;
982 }
983 }
984 else
985 tolerant = GNUNET_NO;
986
987#ifndef MINGW
988 errno = 0;
989 if ((NULL != (nfds = getenv ("LISTEN_FDS"))) &&
990 (1 == SSCANF (nfds, "%u", &cnt)) && (cnt > 0) && (cnt < FD_SETSIZE) &&
991 (cnt + 4 < FD_SETSIZE))
992 {
993 sctx->lsocks =
994 GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (cnt + 1));
995 while (0 < cnt--)
996 {
997 flags = fcntl (3 + cnt, F_GETFD);
998 if ((flags < 0) || (0 != (flags & FD_CLOEXEC)) ||
999 (NULL ==
1000 (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
1001 {
1002 LOG (GNUNET_ERROR_TYPE_ERROR,
1003 _
1004 ("Could not access pre-bound socket %u, will try to bind myself\n"),
1005 (unsigned int) 3 + cnt);
1006 cnt++;
1007 while (sctx->lsocks[cnt] != NULL)
1008 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
1009 GNUNET_free (sctx->lsocks);
1010 sctx->lsocks = NULL;
1011 break;
1012 }
1013 }
1014 unsetenv ("LISTEN_FDS");
1015 }
1016#else
1017 if (getenv ("GNUNET_OS_READ_LSOCKS") != NULL)
1018 {
1019 receive_sockets_from_parent (sctx);
1020 putenv ("GNUNET_OS_READ_LSOCKS=");
1021 }
1022#endif
1023
1024 if ((NULL == sctx->lsocks) &&
1025 (GNUNET_SYSERR ==
1026 GNUNET_SERVICE_get_server_addresses (sctx->service_name, sctx->cfg,
1027 &sctx->addrs, &sctx->addrlens)))
1028 return GNUNET_SYSERR;
1029 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1030 sctx->match_uid =
1031 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
1032 "UNIX_MATCH_UID");
1033 sctx->match_gid =
1034 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
1035 "UNIX_MATCH_GID");
1036 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1037 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1038 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1039 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1040
1041 return GNUNET_OK;
1042}
1043
1044
1045/**
1046 * Get the name of the user that'll be used
1047 * to provide the service.
1048 *
1049 * @param sctx service context
1050 * @return value of the 'USERNAME' option
1051 */
1052static char *
1053get_user_name (struct GNUNET_SERVICE_Context *sctx)
1054{
1055 char *un;
1056
1057 if (GNUNET_OK !=
1058 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->service_name,
1059 "USERNAME", &un))
1060 return NULL;
1061 return un;
1062}
1063
1064
1065/**
1066 * Write PID file.
1067 *
1068 * @param sctx service context
1069 * @param pid PID to write (should be equal to 'getpid()'
1070 * @return #GNUNET_OK on success (including no work to be done)
1071 */
1072static int
1073write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1074{
1075 FILE *pidfd;
1076 char *pif;
1077 char *user;
1078 char *rdir;
1079 int len;
1080
1081 if (NULL == (pif = get_pid_file_name (sctx)))
1082 return GNUNET_OK; /* no file desired */
1083 user = get_user_name (sctx);
1084 rdir = GNUNET_strdup (pif);
1085 len = strlen (rdir);
1086 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1087 len--;
1088 rdir[len] = '\0';
1089 if (0 != ACCESS (rdir, F_OK))
1090 {
1091 /* we get to create a directory -- and claim it
1092 * as ours! */
1093 (void) GNUNET_DISK_directory_create (rdir);
1094 if ((NULL != user) && (0 < strlen (user)))
1095 GNUNET_DISK_file_change_owner (rdir, user);
1096 }
1097 if (0 != ACCESS (rdir, W_OK | X_OK))
1098 {
1099 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1100 GNUNET_free (rdir);
1101 GNUNET_free_non_null (user);
1102 GNUNET_free (pif);
1103 return GNUNET_SYSERR;
1104 }
1105 GNUNET_free (rdir);
1106 pidfd = FOPEN (pif, "w");
1107 if (NULL == pidfd)
1108 {
1109 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1110 GNUNET_free (pif);
1111 GNUNET_free_non_null (user);
1112 return GNUNET_SYSERR;
1113 }
1114 if (0 > FPRINTF (pidfd, "%u", pid))
1115 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1116 GNUNET_break (0 == FCLOSE (pidfd));
1117 if ((NULL != user) && (0 < strlen (user)))
1118 GNUNET_DISK_file_change_owner (pif, user);
1119 GNUNET_free_non_null (user);
1120 GNUNET_free (pif);
1121 return GNUNET_OK;
1122}
1123
1124
1125/**
1126 * Task run during shutdown. Stops the server/service.
1127 *
1128 * @param cls the `struct GNUNET_SERVICE_Context`
1129 */
1130static void
1131shutdown_task (void *cls)
1132{
1133 struct GNUNET_SERVICE_Context *service = cls;
1134 struct GNUNET_SERVER_Handle *server = service->server;
1135
1136 service->shutdown_task = NULL;
1137 if (0 != (service->options & GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN))
1138 GNUNET_SERVER_stop_listening (server);
1139 else
1140 GNUNET_SERVER_destroy (server);
1141}
1142
1143
1144/**
1145 * Initial task for the service.
1146 *
1147 * @param cls service context
1148 */
1149static void
1150service_task (void *cls)
1151{
1152 struct GNUNET_SERVICE_Context *sctx = cls;
1153 unsigned int i;
1154
1155 (void) GNUNET_SPEEDUP_start_ (sctx->cfg);
1156 GNUNET_RESOLVER_connect (sctx->cfg);
1157 if (NULL != sctx->lsocks)
1158 sctx->server
1159 = GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1160 sctx->timeout, sctx->require_found);
1161 else
1162 sctx->server
1163 = GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1164 sctx->timeout, sctx->require_found);
1165 if (NULL == sctx->server)
1166 {
1167 if (NULL != sctx->addrs)
1168 for (i = 0; NULL != sctx->addrs[i]; i++)
1169 LOG (GNUNET_ERROR_TYPE_INFO,
1170 _("Failed to start `%s' at `%s'\n"),
1171 sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1172 sctx->ret = GNUNET_SYSERR;
1173 return;
1174 }
1175#ifndef WINDOWS
1176 if (NULL != sctx->addrs)
1177 for (i = 0; NULL != sctx->addrs[i]; i++)
1178 if ((AF_UNIX == sctx->addrs[i]->sa_family)
1179 && ('\0' != ((const struct sockaddr_un *)sctx->addrs[i])->sun_path[0]))
1180 GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sctx->addrs[i])->sun_path,
1181 sctx->match_uid,
1182 sctx->match_gid);
1183#endif
1184
1185
1186 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1187 {
1188 /* install a task that will kill the server
1189 * process if the scheduler ever gets a shutdown signal */
1190 sctx->shutdown_task = GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1191 sctx);
1192 }
1193 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1194 GNUNET_memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1195 i = 0;
1196 while (NULL != sctx->my_handlers[i].callback)
1197 sctx->my_handlers[i++].callback_cls = sctx;
1198 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1199 if (-1 != sctx->ready_confirm_fd)
1200 {
1201 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1202 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1203 sctx->ready_confirm_fd = -1;
1204 write_pid_file (sctx, getpid ());
1205 }
1206 if (NULL != sctx->addrs)
1207 {
1208 i = 0;
1209 while (NULL != sctx->addrs[i])
1210 {
1211 LOG (GNUNET_ERROR_TYPE_INFO, _("Service `%s' runs at %s\n"),
1212 sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1213 i++;
1214 }
1215 }
1216 sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1217}
1218
1219
1220/**
1221 * Detach from terminal.
1222 *
1223 * @param sctx service context
1224 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1225 */
1226static int
1227detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1228{
1229#ifndef MINGW
1230 pid_t pid;
1231 int nullfd;
1232 int filedes[2];
1233
1234 if (0 != PIPE (filedes))
1235 {
1236 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
1237 return GNUNET_SYSERR;
1238 }
1239 pid = fork ();
1240 if (pid < 0)
1241 {
1242 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
1243 return GNUNET_SYSERR;
1244 }
1245 if (0 != pid)
1246 {
1247 /* Parent */
1248 char c;
1249
1250 GNUNET_break (0 == CLOSE (filedes[1]));
1251 c = 'X';
1252 if (1 != READ (filedes[0], &c, sizeof (char)))
1253 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
1254 fflush (stdout);
1255 switch (c)
1256 {
1257 case '.':
1258 exit (0);
1259 case 'I':
1260 LOG (GNUNET_ERROR_TYPE_INFO, _("Service process failed to initialize\n"));
1261 break;
1262 case 'S':
1263 LOG (GNUNET_ERROR_TYPE_INFO,
1264 _("Service process could not initialize server function\n"));
1265 break;
1266 case 'X':
1267 LOG (GNUNET_ERROR_TYPE_INFO,
1268 _("Service process failed to report status\n"));
1269 break;
1270 }
1271 exit (1); /* child reported error */
1272 }
1273 GNUNET_break (0 == CLOSE (0));
1274 GNUNET_break (0 == CLOSE (1));
1275 GNUNET_break (0 == CLOSE (filedes[0]));
1276 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1277 if (nullfd < 0)
1278 return GNUNET_SYSERR;
1279 /* set stdin/stdout to /dev/null */
1280 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1281 {
1282 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
1283 (void) CLOSE (nullfd);
1284 return GNUNET_SYSERR;
1285 }
1286 (void) CLOSE (nullfd);
1287 /* Detach from controlling terminal */
1288 pid = setsid ();
1289 if (-1 == pid)
1290 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid");
1291 sctx->ready_confirm_fd = filedes[1];
1292#else
1293 /* FIXME: we probably need to do something else
1294 * elsewhere in order to fork the process itself... */
1295 FreeConsole ();
1296#endif
1297 return GNUNET_OK;
1298}
1299
1300
1301/**
1302 * Set user ID.
1303 *
1304 * @param sctx service context
1305 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1306 */
1307static int
1308set_user_id (struct GNUNET_SERVICE_Context *sctx)
1309{
1310 char *user;
1311
1312 if (NULL == (user = get_user_name (sctx)))
1313 return GNUNET_OK; /* keep */
1314#ifndef MINGW
1315 struct passwd *pws;
1316
1317 errno = 0;
1318 pws = getpwnam (user);
1319 if (NULL == pws)
1320 {
1321 LOG (GNUNET_ERROR_TYPE_ERROR,
1322 _("Cannot obtain information about user `%s': %s\n"), user,
1323 errno == 0 ? _("No such user") : STRERROR (errno));
1324 GNUNET_free (user);
1325 return GNUNET_SYSERR;
1326 }
1327 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1328#if HAVE_INITGROUPS
1329 (0 != initgroups (user, pws->pw_gid)) ||
1330#endif
1331 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1332 {
1333 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1334 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1335 {
1336 LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot change user/group to `%s': %s\n"),
1337 user, STRERROR (errno));
1338 GNUNET_free (user);
1339 return GNUNET_SYSERR;
1340 }
1341 }
1342#endif
1343 GNUNET_free (user);
1344 return GNUNET_OK;
1345}
1346
1347
1348/**
1349 * Delete the PID file that was created by our parent.
1350 *
1351 * @param sctx service context
1352 */
1353static void
1354pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1355{
1356 char *pif = get_pid_file_name (sctx);
1357
1358 if (NULL == pif)
1359 return; /* no PID file */
1360 if (0 != UNLINK (pif))
1361 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1362 GNUNET_free (pif);
1363}
1364
1365
1366/**
1367 * Run a standard GNUnet service startup sequence (initialize loggers
1368 * and configuration, parse options).
1369 *
1370 * @param argc number of command line arguments
1371 * @param argv command line arguments
1372 * @param service_name our service name
1373 * @param options service options
1374 * @param task main task of the service
1375 * @param task_cls closure for @a task
1376 * @return #GNUNET_SYSERR on error, #GNUNET_OK
1377 * if we shutdown nicely
1378 */
1379int
1380GNUNET_SERVICE_run (int argc, char *const *argv,
1381 const char *service_name,
1382 enum GNUNET_SERVICE_Options options,
1383 GNUNET_SERVICE_Main task,
1384 void *task_cls)
1385{
1386#define HANDLE_ERROR do { GNUNET_break (0); goto shutdown; } while (0)
1387
1388 int err;
1389 int ret;
1390 char *cfg_fn;
1391 char *opt_cfg_fn;
1392 char *loglev;
1393 char *logfile;
1394 int do_daemonize;
1395 unsigned int i;
1396 unsigned long long skew_offset;
1397 unsigned long long skew_variance;
1398 long long clock_offset;
1399 struct GNUNET_SERVICE_Context sctx;
1400 struct GNUNET_CONFIGURATION_Handle *cfg;
1401 const char *xdg;
1402
1403 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1404 GNUNET_GETOPT_OPTION_CFG_FILE (&opt_cfg_fn),
1405 {'d', "daemonize", NULL,
1406 gettext_noop ("do daemonize (detach from terminal)"), 0,
1407 GNUNET_GETOPT_set_one, &do_daemonize},
1408 GNUNET_GETOPT_OPTION_HELP (NULL),
1409 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1410 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1411 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION " " VCS_VERSION),
1412 GNUNET_GETOPT_OPTION_END
1413 };
1414 err = 1;
1415 do_daemonize = 0;
1416 logfile = NULL;
1417 loglev = NULL;
1418 opt_cfg_fn = NULL;
1419 xdg = getenv ("XDG_CONFIG_HOME");
1420 if (NULL != xdg)
1421 GNUNET_asprintf (&cfg_fn,
1422 "%s%s%s",
1423 xdg,
1424 DIR_SEPARATOR_STR,
1425 GNUNET_OS_project_data_get ()->config_file);
1426 else
1427 cfg_fn = GNUNET_strdup (GNUNET_OS_project_data_get ()->user_config_file);
1428 memset (&sctx, 0, sizeof (sctx));
1429 sctx.options = options;
1430 sctx.ready_confirm_fd = -1;
1431 sctx.ret = GNUNET_OK;
1432 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1433 sctx.task = task;
1434 sctx.task_cls = task_cls;
1435 sctx.service_name = service_name;
1436 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1437
1438 /* setup subsystems */
1439 ret = GNUNET_GETOPT_run (service_name, service_options, argc, argv);
1440 if (GNUNET_SYSERR == ret)
1441 goto shutdown;
1442 if (GNUNET_NO == ret)
1443 {
1444 err = 0;
1445 goto shutdown;
1446 }
1447 if (GNUNET_OK != GNUNET_log_setup (service_name, loglev, logfile))
1448 HANDLE_ERROR;
1449 if (NULL == opt_cfg_fn)
1450 opt_cfg_fn = GNUNET_strdup (cfg_fn);
1451 if (GNUNET_YES == GNUNET_DISK_file_test (opt_cfg_fn))
1452 {
1453 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, opt_cfg_fn))
1454 {
1455 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1456 _("Malformed configuration file `%s', exit ...\n"),
1457 opt_cfg_fn);
1458 goto shutdown;
1459 }
1460 }
1461 else
1462 {
1463 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, NULL))
1464 {
1465 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1466 _("Malformed configuration, exit ...\n"));
1467 goto shutdown;
1468 }
1469 if (0 != strcmp (opt_cfg_fn, cfg_fn))
1470 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1471 _("Could not access configuration file `%s'\n"),
1472 opt_cfg_fn);
1473 }
1474 if (GNUNET_OK != setup_service (&sctx))
1475 goto shutdown;
1476 if ((1 == do_daemonize) && (GNUNET_OK != detach_terminal (&sctx)))
1477 HANDLE_ERROR;
1478 if (GNUNET_OK != set_user_id (&sctx))
1479 goto shutdown;
1480 LOG (GNUNET_ERROR_TYPE_DEBUG,
1481 "Service `%s' runs with configuration from `%s'\n",
1482 service_name,
1483 opt_cfg_fn);
1484 if ((GNUNET_OK ==
1485 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1486 "SKEW_OFFSET", &skew_offset)) &&
1487 (GNUNET_OK ==
1488 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1489 "SKEW_VARIANCE", &skew_variance)))
1490 {
1491 clock_offset = skew_offset - skew_variance;
1492 GNUNET_TIME_set_offset (clock_offset);
1493 LOG (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll ms\n", clock_offset);
1494 }
1495 /* actually run service */
1496 err = 0;
1497 GNUNET_SCHEDULER_run (&service_task, &sctx);
1498 /* shutdown */
1499 if ((1 == do_daemonize) && (NULL != sctx.server))
1500 pid_file_delete (&sctx);
1501 GNUNET_free_non_null (sctx.my_handlers);
1502
1503shutdown:
1504 if (-1 != sctx.ready_confirm_fd)
1505 {
1506 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1507 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "write");
1508 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1509 }
1510#if HAVE_MALLINFO
1511 {
1512 char *counter;
1513
1514 if ( (GNUNET_YES ==
1515 GNUNET_CONFIGURATION_have_value (sctx.cfg, service_name,
1516 "GAUGER_HEAP")) &&
1517 (GNUNET_OK ==
1518 GNUNET_CONFIGURATION_get_value_string (sctx.cfg, service_name,
1519 "GAUGER_HEAP",
1520 &counter)) )
1521 {
1522 struct mallinfo mi;
1523
1524 mi = mallinfo ();
1525 GAUGER (service_name, counter, mi.usmblks, "blocks");
1526 GNUNET_free (counter);
1527 }
1528 }
1529#endif
1530 GNUNET_SPEEDUP_stop_ ();
1531 GNUNET_CONFIGURATION_destroy (cfg);
1532 i = 0;
1533 if (NULL != sctx.addrs)
1534 while (NULL != sctx.addrs[i])
1535 GNUNET_free (sctx.addrs[i++]);
1536 GNUNET_free_non_null (sctx.addrs);
1537 GNUNET_free_non_null (sctx.addrlens);
1538 GNUNET_free_non_null (logfile);
1539 GNUNET_free_non_null (loglev);
1540 GNUNET_free (cfg_fn);
1541 GNUNET_free_non_null (opt_cfg_fn);
1542 GNUNET_free_non_null (sctx.v4_denied);
1543 GNUNET_free_non_null (sctx.v6_denied);
1544 GNUNET_free_non_null (sctx.v4_allowed);
1545 GNUNET_free_non_null (sctx.v6_allowed);
1546
1547 return err ? GNUNET_SYSERR : sctx.ret;
1548}
1549
1550
1551/**
1552 * Run a service startup sequence within an existing
1553 * initialized system.
1554 *
1555 * @param service_name our service name
1556 * @param cfg configuration to use
1557 * @param options service options
1558 * @return NULL on error, service handle
1559 */
1560struct GNUNET_SERVICE_Context *
1561GNUNET_SERVICE_start (const char *service_name,
1562 const struct GNUNET_CONFIGURATION_Handle *cfg,
1563 enum GNUNET_SERVICE_Options options)
1564{
1565 int i;
1566 struct GNUNET_SERVICE_Context *sctx;
1567
1568 sctx = GNUNET_new (struct GNUNET_SERVICE_Context);
1569 sctx->ready_confirm_fd = -1; /* no daemonizing */
1570 sctx->ret = GNUNET_OK;
1571 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1572 sctx->service_name = service_name;
1573 sctx->cfg = cfg;
1574 sctx->options = options;
1575
1576 /* setup subsystems */
1577 if (GNUNET_OK != setup_service (sctx))
1578 {
1579 GNUNET_SERVICE_stop (sctx);
1580 return NULL;
1581 }
1582 if (NULL != sctx->lsocks)
1583 sctx->server =
1584 GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1585 sctx->timeout, sctx->require_found);
1586 else
1587 sctx->server =
1588 GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1589 sctx->timeout, sctx->require_found);
1590
1591 if (NULL == sctx->server)
1592 {
1593 GNUNET_SERVICE_stop (sctx);
1594 return NULL;
1595 }
1596#ifndef WINDOWS
1597 if (NULL != sctx->addrs)
1598 for (i = 0; NULL != sctx->addrs[i]; i++)
1599 if ((AF_UNIX == sctx->addrs[i]->sa_family)
1600 && ('\0' != ((const struct sockaddr_un *)sctx->addrs[i])->sun_path[0]))
1601 GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sctx->addrs[i])->sun_path,
1602 sctx->match_uid,
1603 sctx->match_gid);
1604#endif
1605 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1606 GNUNET_memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1607 i = 0;
1608 while ((sctx->my_handlers[i].callback != NULL))
1609 sctx->my_handlers[i++].callback_cls = sctx;
1610 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1611 return sctx;
1612}
1613
1614
1615/**
1616 * Obtain the server used by a service. Note that the server must NOT
1617 * be destroyed by the caller.
1618 *
1619 * @param ctx the service context returned from the start function
1620 * @return handle to the server for this service, NULL if there is none
1621 */
1622struct GNUNET_SERVER_Handle *
1623GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1624{
1625 return ctx->server;
1626}
1627
1628
1629/**
1630 * Get the NULL-terminated array of listen sockets for this service.
1631 *
1632 * @param ctx service context to query
1633 * @return NULL if there are no listen sockets, otherwise NULL-terminated
1634 * array of listen sockets.
1635 */
1636struct GNUNET_NETWORK_Handle *const*
1637GNUNET_SERVICE_get_listen_sockets (struct GNUNET_SERVICE_Context *ctx)
1638{
1639 return ctx->lsocks;
1640}
1641
1642
1643/**
1644 * Stop a service that was started with "GNUNET_SERVICE_start".
1645 *
1646 * @param sctx the service context returned from the start function
1647 */
1648void
1649GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1650{
1651 unsigned int i;
1652
1653#if HAVE_MALLINFO
1654 {
1655 char *counter;
1656
1657 if ( (GNUNET_YES ==
1658 GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name,
1659 "GAUGER_HEAP")) &&
1660 (GNUNET_OK ==
1661 GNUNET_CONFIGURATION_get_value_string (sctx->cfg, sctx->service_name,
1662 "GAUGER_HEAP",
1663 &counter)) )
1664 {
1665 struct mallinfo mi;
1666
1667 mi = mallinfo ();
1668 GAUGER (sctx->service_name, counter, mi.usmblks, "blocks");
1669 GNUNET_free (counter);
1670 }
1671 }
1672#endif
1673 if (NULL != sctx->shutdown_task)
1674 {
1675 GNUNET_SCHEDULER_cancel (sctx->shutdown_task);
1676 sctx->shutdown_task = NULL;
1677 }
1678 if (NULL != sctx->server)
1679 GNUNET_SERVER_destroy (sctx->server);
1680 GNUNET_free_non_null (sctx->my_handlers);
1681 if (NULL != sctx->addrs)
1682 {
1683 i = 0;
1684 while (NULL != sctx->addrs[i])
1685 GNUNET_free (sctx->addrs[i++]);
1686 GNUNET_free (sctx->addrs);
1687 }
1688 GNUNET_free_non_null (sctx->addrlens);
1689 GNUNET_free_non_null (sctx->v4_denied);
1690 GNUNET_free_non_null (sctx->v6_denied);
1691 GNUNET_free_non_null (sctx->v4_allowed);
1692 GNUNET_free_non_null (sctx->v6_allowed);
1693 GNUNET_free (sctx);
1694}
1695
1696
1697/* end of service.c */
diff --git a/src/util/test_connection.c b/src/util/test_connection.c
deleted file mode 100644
index eaca75c2e..000000000
--- a/src/util/test_connection.c
+++ /dev/null
@@ -1,167 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * @file util/test_connection.c
22 * @brief tests for connection.c
23 */
24#include "platform.h"
25#include "gnunet_util_lib.h"
26
27#define PORT 12435
28
29
30static struct GNUNET_CONNECTION_Handle *csock;
31
32static struct GNUNET_CONNECTION_Handle *asock;
33
34static struct GNUNET_CONNECTION_Handle *lsock;
35
36static size_t sofar;
37
38static struct GNUNET_NETWORK_Handle *ls;
39
40static struct GNUNET_CONFIGURATION_Handle *cfg;
41
42/**
43 * Create and initialize a listen socket for the server.
44 *
45 * @return -1 on error, otherwise the listen socket
46 */
47static struct GNUNET_NETWORK_Handle *
48open_listen_socket ()
49{
50 const static int on = 1;
51 struct sockaddr_in sa;
52 struct GNUNET_NETWORK_Handle *desc;
53
54 memset (&sa, 0, sizeof (sa));
55#if HAVE_SOCKADDR_IN_SIN_LEN
56 sa.sin_len = sizeof (sa);
57#endif
58 sa.sin_port = htons (PORT);
59 sa.sin_family = AF_INET;
60 desc = GNUNET_NETWORK_socket_create (AF_INET, SOCK_STREAM, 0);
61 GNUNET_assert (desc != NULL);
62 if (GNUNET_NETWORK_socket_setsockopt
63 (desc, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
64 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "setsockopt");
65 GNUNET_assert (GNUNET_OK ==
66 GNUNET_NETWORK_socket_bind (desc, (const struct sockaddr *) &sa,
67 sizeof (sa)));
68 GNUNET_NETWORK_socket_listen (desc, 5);
69 return desc;
70}
71
72static void
73receive_check (void *cls, const void *buf, size_t available,
74 const struct sockaddr *addr, socklen_t addrlen, int errCode)
75{
76 int *ok = cls;
77
78 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Receive validates incoming data\n");
79 GNUNET_assert (buf != NULL); /* no timeout */
80 if (0 == memcmp (&"Hello World"[sofar], buf, available))
81 sofar += available;
82 if (sofar < 12)
83 {
84 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Receive needs more data\n");
85 GNUNET_CONNECTION_receive (asock, 1024,
86 GNUNET_TIME_relative_multiply
87 (GNUNET_TIME_UNIT_SECONDS, 5), &receive_check,
88 cls);
89 }
90 else
91 {
92 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Receive closes accepted socket\n");
93 *ok = 0;
94 GNUNET_CONNECTION_destroy (asock);
95 GNUNET_CONNECTION_destroy (csock);
96 }
97}
98
99
100static void
101run_accept (void *cls)
102{
103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Test accepts connection\n");
104 asock = GNUNET_CONNECTION_create_from_accept (NULL, NULL, ls);
105 GNUNET_assert (asock != NULL);
106 GNUNET_assert (GNUNET_YES == GNUNET_CONNECTION_check (asock));
107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Test destroys listen socket\n");
108 GNUNET_CONNECTION_destroy (lsock);
109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
110 "Test asks to receive on accepted socket\n");
111 GNUNET_CONNECTION_receive (asock, 1024,
112 GNUNET_TIME_relative_multiply
113 (GNUNET_TIME_UNIT_SECONDS, 5), &receive_check,
114 cls);
115}
116
117
118static size_t
119make_hello (void *cls, size_t size, void *buf)
120{
121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
122 "Test prepares to transmit on connect socket\n");
123 GNUNET_assert (size >= 12);
124 strcpy ((char *) buf, "Hello World");
125 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Test destroys client socket\n");
126 return 12;
127}
128
129
130static void
131task (void *cls)
132{
133 ls = open_listen_socket ();
134 lsock = GNUNET_CONNECTION_create_from_existing (ls);
135 GNUNET_assert (lsock != NULL);
136 csock = GNUNET_CONNECTION_create_from_connect (cfg, "localhost", PORT);
137 GNUNET_assert (csock != NULL);
138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Test asks for write notification\n");
139 GNUNET_assert (NULL !=
140 GNUNET_CONNECTION_notify_transmit_ready (csock, 12,
141 GNUNET_TIME_UNIT_SECONDS,
142 &make_hello, NULL));
143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Test prepares to accept\n");
144 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, ls, &run_accept,
145 cls);
146}
147
148
149int
150main (int argc, char *argv[])
151{
152 int ok;
153
154 GNUNET_log_setup ("test_connection",
155 "WARNING",
156 NULL);
157
158 ok = 1;
159 cfg = GNUNET_CONFIGURATION_create ();
160 GNUNET_CONFIGURATION_set_value_string (cfg, "resolver", "HOSTNAME",
161 "localhost");
162 GNUNET_SCHEDULER_run (&task, &ok);
163 GNUNET_CONFIGURATION_destroy (cfg);
164 return ok;
165}
166
167/* end of test_connection.c */
diff --git a/src/util/test_connection_addressing.c b/src/util/test_connection_addressing.c
deleted file mode 100644
index a6345b10a..000000000
--- a/src/util/test_connection_addressing.c
+++ /dev/null
@@ -1,186 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * @file util/test_connection_addressing.c
22 * @brief tests for connection.c
23 */
24#include "platform.h"
25#include "gnunet_util_lib.h"
26
27
28#define PORT 12435
29
30
31static struct GNUNET_CONNECTION_Handle *csock;
32
33static struct GNUNET_CONNECTION_Handle *asock;
34
35static struct GNUNET_CONNECTION_Handle *lsock;
36
37static size_t sofar;
38
39static struct GNUNET_NETWORK_Handle *ls;
40
41
42
43/**
44 * Create and initialize a listen socket for the server.
45 *
46 * @return NULL on error, otherwise the listen socket
47 */
48static struct GNUNET_NETWORK_Handle *
49open_listen_socket ()
50{
51 const static int on = 1;
52 struct sockaddr_in sa;
53 struct GNUNET_NETWORK_Handle *desc;
54
55 memset (&sa, 0, sizeof (sa));
56#if HAVE_SOCKADDR_IN_SIN_LEN
57 sa.sin_len = sizeof (sa);
58#endif
59 sa.sin_family = AF_INET;
60 sa.sin_port = htons (PORT);
61 desc = GNUNET_NETWORK_socket_create (AF_INET, SOCK_STREAM, 0);
62 GNUNET_assert (desc != 0);
63 if (GNUNET_NETWORK_socket_setsockopt
64 (desc, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
65 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "setsockopt");
66 if (GNUNET_OK !=
67 GNUNET_NETWORK_socket_bind (desc, (const struct sockaddr *) &sa,
68 sizeof (sa)))
69 {
70 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
71 "bind");
72 GNUNET_assert (0);
73 }
74 GNUNET_NETWORK_socket_listen (desc, 5);
75 return desc;
76}
77
78
79static void
80receive_check (void *cls, const void *buf, size_t available,
81 const struct sockaddr *addr, socklen_t addrlen, int errCode)
82{
83 int *ok = cls;
84
85 GNUNET_assert (buf != NULL); /* no timeout */
86 if (0 == memcmp (&"Hello World"[sofar], buf, available))
87 sofar += available;
88 if (sofar < 12)
89 {
90 GNUNET_CONNECTION_receive (asock, 1024,
91 GNUNET_TIME_relative_multiply
92 (GNUNET_TIME_UNIT_SECONDS, 5), &receive_check,
93 cls);
94 }
95 else
96 {
97 *ok = 0;
98 GNUNET_CONNECTION_destroy (csock);
99 GNUNET_CONNECTION_destroy (asock);
100 }
101}
102
103
104static void
105run_accept (void *cls)
106{
107 void *addr;
108 size_t alen;
109 struct sockaddr_in *v4;
110 struct sockaddr_in expect;
111
112 asock = GNUNET_CONNECTION_create_from_accept (NULL, NULL, ls);
113 GNUNET_assert (asock != NULL);
114 GNUNET_assert (GNUNET_YES == GNUNET_CONNECTION_check (asock));
115 GNUNET_assert (GNUNET_OK ==
116 GNUNET_CONNECTION_get_address (asock, &addr, &alen));
117 GNUNET_assert (alen == sizeof (struct sockaddr_in));
118 v4 = addr;
119 memset (&expect, 0, sizeof (expect));
120#if HAVE_SOCKADDR_IN_SIN_LEN
121 expect.sin_len = sizeof (expect);
122#endif
123 expect.sin_family = AF_INET;
124 expect.sin_port = v4->sin_port;
125 expect.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
126 GNUNET_assert (0 == memcmp (&expect, v4, alen));
127 GNUNET_free (addr);
128 GNUNET_CONNECTION_destroy (lsock);
129 GNUNET_CONNECTION_receive (asock, 1024,
130 GNUNET_TIME_relative_multiply
131 (GNUNET_TIME_UNIT_SECONDS, 5), &receive_check,
132 cls);
133}
134
135static size_t
136make_hello (void *cls, size_t size, void *buf)
137{
138 GNUNET_assert (size >= 12);
139 strcpy ((char *) buf, "Hello World");
140 return 12;
141}
142
143
144static void
145task (void *cls)
146{
147 struct sockaddr_in v4;
148
149 ls = open_listen_socket ();
150 lsock = GNUNET_CONNECTION_create_from_existing (ls);
151 GNUNET_assert (lsock != NULL);
152
153#if HAVE_SOCKADDR_IN_SIN_LEN
154 v4.sin_len = sizeof (v4);
155#endif
156 v4.sin_family = AF_INET;
157 v4.sin_port = htons (PORT);
158 v4.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
159 csock =
160 GNUNET_CONNECTION_create_from_sockaddr (AF_INET,
161 (const struct sockaddr *) &v4,
162 sizeof (v4));
163 GNUNET_assert (csock != NULL);
164 GNUNET_assert (NULL !=
165 GNUNET_CONNECTION_notify_transmit_ready (csock, 12,
166 GNUNET_TIME_UNIT_SECONDS,
167 &make_hello, NULL));
168 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, ls, &run_accept,
169 cls);
170}
171
172
173int
174main (int argc, char *argv[])
175{
176 int ok;
177
178 GNUNET_log_setup ("test_connection_addressing",
179 "WARNING",
180 NULL);
181 ok = 1;
182 GNUNET_SCHEDULER_run (&task, &ok);
183 return ok;
184}
185
186/* end of test_connection_addressing.c */
diff --git a/src/util/test_connection_receive_cancel.c b/src/util/test_connection_receive_cancel.c
deleted file mode 100644
index 9c0ab699e..000000000
--- a/src/util/test_connection_receive_cancel.c
+++ /dev/null
@@ -1,160 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * @file util/test_connection_receive_cancel.c
22 * @brief tests for connection.c
23 */
24#include "platform.h"
25#include "gnunet_util_lib.h"
26
27#define PORT 12435
28
29
30static struct GNUNET_CONNECTION_Handle *csock;
31
32static struct GNUNET_CONNECTION_Handle *asock;
33
34static struct GNUNET_CONNECTION_Handle *lsock;
35
36static struct GNUNET_NETWORK_Handle *ls;
37
38static struct GNUNET_CONFIGURATION_Handle *cfg;
39
40
41/**
42 * Create and initialize a listen socket for the server.
43 *
44 * @return NULL on error, otherwise the listen socket
45 */
46static struct GNUNET_NETWORK_Handle *
47open_listen_socket ()
48{
49 const static int on = 1;
50 struct sockaddr_in sa;
51 struct GNUNET_NETWORK_Handle *desc;
52
53 memset (&sa, 0, sizeof (sa));
54#if HAVE_SOCKADDR_IN_SIN_LEN
55 sa.sin_len = sizeof (sa);
56#endif
57 sa.sin_family = AF_INET;
58 sa.sin_port = htons (PORT);
59 desc = GNUNET_NETWORK_socket_create (AF_INET, SOCK_STREAM, 0);
60 GNUNET_assert (desc != NULL);
61 if (GNUNET_NETWORK_socket_setsockopt
62 (desc, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
63 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
64 "setsockopt");
65 GNUNET_assert (GNUNET_OK ==
66 GNUNET_NETWORK_socket_bind (desc, (const struct sockaddr *) &sa,
67 sizeof (sa)));
68 GNUNET_NETWORK_socket_listen (desc, 5);
69 return desc;
70}
71
72
73static void
74dead_receive (void *cls,
75 const void *buf,
76 size_t available,
77 const struct sockaddr *addr,
78 socklen_t addrlen,
79 int errCode)
80{
81 GNUNET_assert (0);
82}
83
84
85static void
86run_accept_cancel (void *cls)
87{
88 asock = GNUNET_CONNECTION_create_from_accept (NULL, NULL, ls);
89 GNUNET_assert (asock != NULL);
90 GNUNET_assert (GNUNET_YES == GNUNET_CONNECTION_check (asock));
91 GNUNET_CONNECTION_destroy (lsock);
92 GNUNET_CONNECTION_receive (asock, 1024,
93 GNUNET_TIME_relative_multiply
94 (GNUNET_TIME_UNIT_SECONDS, 5),
95 &dead_receive, cls);
96}
97
98
99static void
100receive_cancel_task (void *cls)
101{
102 int *ok = cls;
103
104 GNUNET_CONNECTION_receive_cancel (asock);
105 GNUNET_CONNECTION_destroy (csock);
106 GNUNET_CONNECTION_destroy (asock);
107 *ok = 0;
108}
109
110
111static void
112task_receive_cancel (void *cls)
113{
114 ls = open_listen_socket ();
115 lsock = GNUNET_CONNECTION_create_from_existing (ls);
116 GNUNET_assert (lsock != NULL);
117 csock = GNUNET_CONNECTION_create_from_connect (cfg, "localhost", PORT);
118 GNUNET_assert (csock != NULL);
119 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
120 ls,
121 &run_accept_cancel,
122 cls);
123 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
124 &receive_cancel_task,
125 cls);
126}
127
128
129/**
130 * Main method, starts scheduler with task_timeout.
131 */
132static int
133check_receive_cancel ()
134{
135 int ok;
136
137 ok = 1;
138 cfg = GNUNET_CONFIGURATION_create ();
139 GNUNET_CONFIGURATION_set_value_string (cfg,
140 "resolver",
141 "HOSTNAME",
142 "localhost");
143 GNUNET_SCHEDULER_run (&task_receive_cancel, &ok);
144 GNUNET_CONFIGURATION_destroy (cfg);
145 return ok;
146}
147
148
149int
150main (int argc, char *argv[])
151{
152 int ret = 0;
153
154 GNUNET_log_setup ("test_connection_receive_cancel", "WARNING", NULL);
155 ret += check_receive_cancel ();
156
157 return ret;
158}
159
160/* end of test_connection_receive_cancel.c */
diff --git a/src/util/test_connection_timeout.c b/src/util/test_connection_timeout.c
deleted file mode 100644
index e78cec669..000000000
--- a/src/util/test_connection_timeout.c
+++ /dev/null
@@ -1,129 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * @file util/test_connection_timeout.c
22 * @brief tests for connection.c
23 */
24#include "platform.h"
25#include "gnunet_util_lib.h"
26
27#define PORT 12435
28
29static struct GNUNET_CONNECTION_Handle *csock;
30
31static struct GNUNET_CONNECTION_Handle *lsock;
32
33static struct GNUNET_NETWORK_Handle *ls;
34
35static struct GNUNET_CONFIGURATION_Handle *cfg;
36
37
38/**
39 * Create and initialize a listen socket for the server.
40 *
41 * @return NULL on error, otherwise the listen socket
42 */
43static struct GNUNET_NETWORK_Handle *
44open_listen_socket ()
45{
46 const static int on = 1;
47 struct sockaddr_in sa;
48 struct GNUNET_NETWORK_Handle *desc;
49
50 memset (&sa, 0, sizeof (sa));
51#if HAVE_SOCKADDR_IN_SIN_LEN
52 sa.sin_len = sizeof (sa);
53#endif
54 sa.sin_family = AF_INET;
55 sa.sin_port = htons (PORT);
56 desc = GNUNET_NETWORK_socket_create (AF_INET, SOCK_STREAM, 0);
57 GNUNET_assert (desc != NULL);
58 if (GNUNET_NETWORK_socket_setsockopt
59 (desc, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
60 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "setsockopt");
61 GNUNET_assert (GNUNET_OK ==
62 GNUNET_NETWORK_socket_bind (desc, (const struct sockaddr *) &sa,
63 sizeof (sa)));
64 GNUNET_NETWORK_socket_listen (desc, 5);
65 return desc;
66}
67
68
69static size_t
70send_kilo (void *cls, size_t size, void *buf)
71{
72 int *ok = cls;
73
74 if (size == 0)
75 {
76 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got the desired timeout!\n");
77 GNUNET_assert (buf == NULL);
78 *ok = 0;
79 GNUNET_CONNECTION_destroy (lsock);
80 GNUNET_CONNECTION_destroy (csock);
81 return 0;
82 }
83 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending kilo to fill buffer.\n");
84 GNUNET_assert (size >= 1024);
85 memset (buf, 42, 1024);
86
87 GNUNET_assert (NULL !=
88 GNUNET_CONNECTION_notify_transmit_ready (csock, 1024,
89 GNUNET_TIME_UNIT_SECONDS,
90 &send_kilo, cls));
91 return 1024;
92}
93
94
95static void
96task_timeout (void *cls)
97{
98
99 ls = open_listen_socket ();
100 lsock = GNUNET_CONNECTION_create_from_existing (ls);
101 GNUNET_assert (lsock != NULL);
102 csock = GNUNET_CONNECTION_create_from_connect (cfg, "localhost", PORT);
103 GNUNET_assert (csock != NULL);
104 GNUNET_assert (NULL !=
105 GNUNET_CONNECTION_notify_transmit_ready (csock, 1024,
106 GNUNET_TIME_UNIT_SECONDS,
107 &send_kilo, cls));
108}
109
110
111int
112main (int argc, char *argv[])
113{
114 int ok;
115
116 GNUNET_log_setup ("test_connection_timeout",
117 "WARNING",
118 NULL);
119
120 ok = 1;
121 cfg = GNUNET_CONFIGURATION_create ();
122 GNUNET_CONFIGURATION_set_value_string (cfg, "resolver", "HOSTNAME",
123 "localhost");
124 GNUNET_SCHEDULER_run (&task_timeout, &ok);
125 GNUNET_CONFIGURATION_destroy (cfg);
126 return ok;
127}
128
129/* end of test_connection_timeout.c */
diff --git a/src/util/test_connection_timeout_no_connect.c b/src/util/test_connection_timeout_no_connect.c
deleted file mode 100644
index ebcd4b71e..000000000
--- a/src/util/test_connection_timeout_no_connect.c
+++ /dev/null
@@ -1,76 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * @file util/test_connection_timeout_no_connect.c
22 * @brief tests for connection.c, doing timeout which connect failure
23 */
24#include "platform.h"
25#include "gnunet_util_lib.h"
26
27#define PORT 13425
28
29static struct GNUNET_CONNECTION_Handle *csock;
30
31static struct GNUNET_CONFIGURATION_Handle *cfg;
32
33static size_t
34handle_timeout (void *cls, size_t size, void *buf)
35{
36 int *ok = cls;
37
38 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received timeout signal.\n");
39 GNUNET_assert (size == 0);
40 GNUNET_assert (buf == NULL);
41 *ok = 0;
42 return 0;
43}
44
45
46static void
47task_timeout (void *cls)
48{
49 csock = GNUNET_CONNECTION_create_from_connect (cfg, "localhost", PORT);
50 GNUNET_assert (csock != NULL);
51 GNUNET_assert (NULL !=
52 GNUNET_CONNECTION_notify_transmit_ready (csock, 1024,
53 GNUNET_TIME_UNIT_SECONDS,
54 &handle_timeout,
55 cls));
56}
57
58
59int
60main (int argc, char *argv[])
61{
62 int ok;
63
64 GNUNET_log_setup ("test_connection_timeout_no_connect",
65 "WARNING",
66 NULL);
67 ok = 1;
68 cfg = GNUNET_CONFIGURATION_create ();
69 GNUNET_CONFIGURATION_set_value_string (cfg, "resolver", "HOSTNAME",
70 "localhost");
71 GNUNET_SCHEDULER_run (&task_timeout, &ok);
72 GNUNET_CONFIGURATION_destroy (cfg);
73 return ok;
74}
75
76/* end of test_connection_timeout_no_connect.c */
diff --git a/src/util/test_connection_transmit_cancel.c b/src/util/test_connection_transmit_cancel.c
deleted file mode 100644
index 9ef0720ed..000000000
--- a/src/util/test_connection_transmit_cancel.c
+++ /dev/null
@@ -1,76 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * @file util/test_connection_transmit_cancel.c
22 * @brief tests for connection.c
23 */
24#include "platform.h"
25#include "gnunet_util_lib.h"
26
27#define PORT 12435
28
29static struct GNUNET_CONFIGURATION_Handle *cfg;
30
31
32static size_t
33not_run (void *cls, size_t size, void *buf)
34{
35 GNUNET_assert (0);
36 return 0;
37}
38
39
40static void
41task_transmit_cancel (void *cls)
42{
43 int *ok = cls;
44 struct GNUNET_CONNECTION_TransmitHandle *th;
45 struct GNUNET_CONNECTION_Handle *csock;
46
47 csock = GNUNET_CONNECTION_create_from_connect (cfg, "localhost", PORT);
48 GNUNET_assert (csock != NULL);
49 th = GNUNET_CONNECTION_notify_transmit_ready (csock, 12,
50 GNUNET_TIME_UNIT_MINUTES,
51 &not_run, cls);
52 GNUNET_assert (NULL != th);
53 GNUNET_CONNECTION_notify_transmit_ready_cancel (th);
54 GNUNET_CONNECTION_destroy (csock);
55 *ok = 0;
56}
57
58
59int
60main (int argc, char *argv[])
61{
62 int ok;
63
64 GNUNET_log_setup ("test_connection_transmit_cancel",
65 "WARNING",
66 NULL);
67 ok = 1;
68 cfg = GNUNET_CONFIGURATION_create ();
69 GNUNET_CONFIGURATION_set_value_string (cfg, "resolver", "HOSTNAME",
70 "localhost");
71 GNUNET_SCHEDULER_run (&task_transmit_cancel, &ok);
72 GNUNET_CONFIGURATION_destroy (cfg);
73 return ok;
74}
75
76/* end of test_connection_transmit_cancel.c */
diff --git a/src/util/test_server.c b/src/util/test_server.c
deleted file mode 100644
index 8003adbf4..000000000
--- a/src/util/test_server.c
+++ /dev/null
@@ -1,302 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009, 2010, 2014, 2016 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * @file util/test_server.c
22 * @brief tests for server.c
23 */
24#include "platform.h"
25#include "gnunet_util_lib.h"
26
27/**
28 * TCP port to use for the server.
29 */
30#define PORT 12435
31
32/**
33 * Timeout to use for operations.
34 */
35#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2)
36
37/**
38 * Test message type.
39 */
40#define MY_TYPE 128
41
42/**
43 * Test message type.
44 */
45#define MY_TYPE2 129
46
47/**
48 * Handle for the server.
49 */
50static struct GNUNET_SERVER_Handle *server;
51
52/**
53 * Handle for the client.
54 */
55static struct GNUNET_MQ_Handle *mq;
56
57/**
58 * Handle of the server for the client.
59 */
60static struct GNUNET_SERVER_Client *argclient;
61
62/**
63 * Our configuration.
64 */
65static struct GNUNET_CONFIGURATION_Handle *cfg;
66
67/**
68 * Number indiciating in which phase of the test we are.
69 */
70static int ok;
71
72
73/**
74 * Final task invoked to clean up.
75 *
76 * @param cls NULL
77 */
78static void
79finish_up (void *cls)
80{
81 GNUNET_assert (7 == ok);
82 ok = 0;
83 GNUNET_SERVER_destroy (server);
84 GNUNET_MQ_destroy (mq);
85 GNUNET_CONFIGURATION_destroy (cfg);
86}
87
88
89/**
90 * The server has received the second message, initiate clean up.
91 *
92 * @param cls NULL
93 * @param client client we got the message from
94 * @param message the message
95 */
96static void
97recv_fin_cb (void *cls,
98 struct GNUNET_SERVER_Client *client,
99 const struct GNUNET_MessageHeader *message)
100{
101 GNUNET_assert (6 == ok);
102 ok = 7;
103 GNUNET_SERVER_receive_done (client, GNUNET_OK);
104 GNUNET_SCHEDULER_add_now (&finish_up, NULL);
105}
106
107
108/**
109 * We have received the reply from the server, check that we are at
110 * the right stage and queue the next message to the server. Cleans
111 * up #argclient.
112 *
113 * @param cls NULL
114 * @param msg message we got from the server
115 */
116static void
117handle_reply (void *cls,
118 const struct GNUNET_MessageHeader *msg)
119{
120 struct GNUNET_MQ_Envelope *env;
121 struct GNUNET_MessageHeader *m;
122
123 GNUNET_assert (4 == ok);
124 ok = 6;
125 env = GNUNET_MQ_msg (m,
126 MY_TYPE2);
127 GNUNET_MQ_send (mq,
128 env);
129}
130
131
132/**
133 * Send a reply of type #MY_TYPE from the server to the client.
134 * Checks that we are in the right phase and transmits the
135 * reply. Cleans up #argclient state.
136 *
137 * @param cls NULL
138 * @param size number of bytes we are allowed to send
139 * @param buf where to copy the reply
140 * @return number of bytes written to @a buf
141 */
142static size_t
143reply_msg (void *cls,
144 size_t size,
145 void *buf)
146{
147 struct GNUNET_MessageHeader msg;
148
149 GNUNET_assert (3 == ok);
150 ok = 4;
151 GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
152 msg.type = htons (MY_TYPE);
153 msg.size = htons (sizeof (struct GNUNET_MessageHeader));
154 GNUNET_memcpy (buf, &msg, sizeof (struct GNUNET_MessageHeader));
155 GNUNET_assert (NULL != argclient);
156 GNUNET_SERVER_receive_done (argclient, GNUNET_OK);
157 GNUNET_SERVER_client_drop (argclient);
158 argclient = NULL;
159 return sizeof (struct GNUNET_MessageHeader);
160}
161
162
163/**
164 * Function called whenever the server receives a message of
165 * type #MY_TYPE. Checks that we are at the stage where
166 * we expect the first message, then sends a reply. Stores
167 * the handle to the client in #argclient.
168 *
169 * @param cls NULL
170 * @param client client that sent the message
171 * @param message the message we received
172 */
173static void
174recv_cb (void *cls,
175 struct GNUNET_SERVER_Client *client,
176 const struct GNUNET_MessageHeader *message)
177{
178 GNUNET_assert (2 == ok);
179 ok = 3;
180 argclient = client;
181 GNUNET_SERVER_client_keep (argclient);
182 GNUNET_assert (sizeof (struct GNUNET_MessageHeader) == ntohs (message->size));
183 GNUNET_assert (MY_TYPE == ntohs (message->type));
184 GNUNET_assert (NULL !=
185 GNUNET_SERVER_notify_transmit_ready (client,
186 ntohs (message->size),
187 TIMEOUT,
188 &reply_msg,
189 NULL));
190}
191
192
193/**
194 * Message handlers for the server.
195 */
196static struct GNUNET_SERVER_MessageHandler handlers[] = {
197 {&recv_cb, NULL, MY_TYPE, sizeof (struct GNUNET_MessageHeader)},
198 {&recv_fin_cb, NULL, MY_TYPE2, sizeof (struct GNUNET_MessageHeader)},
199 {NULL, NULL, 0, 0}
200};
201
202
203/**
204 * Generic error handler, called with the appropriate error code and
205 * the same closure specified at the creation of the message queue.
206 * Not every message queue implementation supports an error handler.
207 *
208 * @param cls closure with the `struct GNUNET_STATISTICS_Handle *`
209 * @param error error code
210 */
211static void
212mq_error_handler (void *cls,
213 enum GNUNET_MQ_Error error)
214{
215 GNUNET_assert (0); /* should never happen */
216}
217
218
219/**
220 * First task run by the scheduler. Initializes the server and
221 * a client and asks for a transmission from the client to the
222 * server.
223 *
224 * @param cls NULL
225 */
226static void
227task (void *cls)
228{
229 struct sockaddr_in sa;
230 struct sockaddr *sap[2];
231 socklen_t slens[2];
232 struct GNUNET_MQ_Envelope *env;
233 struct GNUNET_MessageHeader *msg;
234 struct GNUNET_MQ_MessageHandler chandlers[] = {
235 GNUNET_MQ_hd_fixed_size (reply,
236 MY_TYPE,
237 struct GNUNET_MessageHeader,
238 cls),
239 GNUNET_MQ_handler_end ()
240 };
241
242 sap[0] = (struct sockaddr *) &sa;
243 slens[0] = sizeof (sa);
244 sap[1] = NULL;
245 slens[1] = 0;
246 memset (&sa, 0, sizeof (sa));
247#if HAVE_SOCKADDR_IN_SIN_LEN
248 sa.sin_len = sizeof (sa);
249#endif
250 sa.sin_family = AF_INET;
251 sa.sin_port = htons (PORT);
252 server = GNUNET_SERVER_create (NULL, NULL,
253 sap, slens,
254 TIMEOUT, GNUNET_NO);
255 GNUNET_assert (server != NULL);
256 GNUNET_SERVER_add_handlers (server, handlers);
257 cfg = GNUNET_CONFIGURATION_create ();
258 GNUNET_CONFIGURATION_set_value_number (cfg,
259 "test-server",
260 "PORT",
261 PORT);
262 GNUNET_CONFIGURATION_set_value_string (cfg,
263 "test-server",
264 "HOSTNAME",
265 "localhost");
266 GNUNET_CONFIGURATION_set_value_string (cfg,
267 "resolver",
268 "HOSTNAME",
269 "localhost");
270 mq = GNUNET_CLIENT_connect (cfg,
271 "test-server",
272 chandlers,
273 &mq_error_handler,
274 NULL);
275 GNUNET_assert (NULL != mq);
276 ok = 2;
277 env = GNUNET_MQ_msg (msg,
278 MY_TYPE);
279 GNUNET_MQ_send (mq,
280 env);
281}
282
283
284/**
285 * Runs the test.
286 *
287 * @param argc length of @a argv
288 * @param argv command line arguments (ignored)
289 * @return 0 on success, otherwise phase of failure
290 */
291int
292main (int argc, char *argv[])
293{
294 GNUNET_log_setup ("test_server",
295 "WARNING",
296 NULL);
297 ok = 1;
298 GNUNET_SCHEDULER_run (&task, &ok);
299 return ok;
300}
301
302/* end of test_server.c */
diff --git a/src/util/test_server_disconnect.c b/src/util/test_server_disconnect.c
deleted file mode 100644
index c3d003e90..000000000
--- a/src/util/test_server_disconnect.c
+++ /dev/null
@@ -1,166 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009, 2010, 2016 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * @file util/test_server_disconnect.c
22 * @brief tests for server.c, specifically GNUNET_SERVER_client_disconnect
23 */
24#include "platform.h"
25#include "gnunet_util_lib.h"
26
27
28#define PORT 12435
29
30#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250)
31
32#define MY_TYPE 128
33
34static struct GNUNET_SERVER_Handle *server;
35
36static struct GNUNET_MQ_Handle *mq;
37
38static struct GNUNET_CONFIGURATION_Handle *cfg;
39
40static int ok;
41
42
43static void
44finish_up (void *cls)
45{
46 GNUNET_assert (ok == 5);
47 ok = 0;
48 GNUNET_SERVER_destroy (server);
49 GNUNET_MQ_destroy (mq);
50 GNUNET_CONFIGURATION_destroy (cfg);
51}
52
53
54static void
55notify_disconnect (void *cls,
56 struct GNUNET_SERVER_Client *clientarg)
57{
58 if (NULL == clientarg)
59 return;
60 GNUNET_assert (ok == 4);
61 ok = 5;
62 GNUNET_SCHEDULER_add_now (&finish_up, NULL);
63}
64
65
66static void
67server_disconnect (void *cls)
68{
69 struct GNUNET_SERVER_Client *argclient = cls;
70
71 GNUNET_assert (ok == 3);
72 ok = 4;
73 GNUNET_SERVER_client_disconnect (argclient);
74 GNUNET_SERVER_client_drop (argclient);
75}
76
77
78static void
79recv_cb (void *cls,
80 struct GNUNET_SERVER_Client *client,
81 const struct GNUNET_MessageHeader *message)
82{
83 GNUNET_assert (ok == 2);
84 ok = 3;
85 GNUNET_SERVER_client_keep (client);
86 GNUNET_SCHEDULER_add_now (&server_disconnect, client);
87 GNUNET_assert (sizeof (struct GNUNET_MessageHeader) == ntohs (message->size));
88 GNUNET_assert (MY_TYPE == ntohs (message->type));
89 GNUNET_SERVER_receive_done (client, GNUNET_OK);
90}
91
92
93static struct GNUNET_SERVER_MessageHandler handlers[] = {
94 {&recv_cb, NULL, MY_TYPE, sizeof (struct GNUNET_MessageHeader)},
95 {NULL, NULL, 0, 0}
96};
97
98
99static void
100task (void *cls)
101{
102 struct sockaddr_in sa;
103 struct sockaddr *sap[2];
104 socklen_t slens[2];
105 struct GNUNET_MQ_Envelope *env;
106 struct GNUNET_MessageHeader *msg;
107
108 sap[0] = (struct sockaddr *) &sa;
109 slens[0] = sizeof (sa);
110 sap[1] = NULL;
111 slens[1] = 0;
112 memset (&sa, 0, sizeof (sa));
113#if HAVE_SOCKADDR_IN_SIN_LEN
114 sa.sin_len = sizeof (sa);
115#endif
116 sa.sin_family = AF_INET;
117 sa.sin_port = htons (PORT);
118 server = GNUNET_SERVER_create (NULL, NULL, sap, slens, TIMEOUT, GNUNET_NO);
119 GNUNET_assert (server != NULL);
120 GNUNET_SERVER_add_handlers (server, handlers);
121 GNUNET_SERVER_disconnect_notify (server, &notify_disconnect, NULL);
122 cfg = GNUNET_CONFIGURATION_create ();
123 GNUNET_CONFIGURATION_set_value_number (cfg, "test-server", "PORT", PORT);
124 GNUNET_CONFIGURATION_set_value_string (cfg, "test-server", "HOSTNAME",
125 "localhost");
126 GNUNET_CONFIGURATION_set_value_string (cfg, "resolver", "HOSTNAME",
127 "localhost");
128 mq = GNUNET_CLIENT_connect (cfg,
129 "test-server",
130 NULL,
131 NULL,
132 NULL);
133 GNUNET_assert (NULL != mq);
134 ok = 2;
135 env = GNUNET_MQ_msg (msg,
136 MY_TYPE);
137 GNUNET_MQ_send (mq,
138 env);
139}
140
141
142/**
143 * Main method, starts scheduler with task1,
144 * checks that "ok" is correct at the end.
145 */
146static int
147check ()
148{
149 ok = 1;
150 GNUNET_SCHEDULER_run (&task, &ok);
151 return ok;
152}
153
154
155int
156main (int argc, char *argv[])
157{
158 int ret = 0;
159
160 GNUNET_log_setup ("test_server_disconnect", "WARNING", NULL);
161 ret += check ();
162
163 return ret;
164}
165
166/* end of test_server_disconnect.c */
diff --git a/src/util/test_server_mst_interrupt.c b/src/util/test_server_mst_interrupt.c
deleted file mode 100644
index 3141a75bd..000000000
--- a/src/util/test_server_mst_interrupt.c
+++ /dev/null
@@ -1,60 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009, 2010 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * @file util/test_server_mst_interrupt.c
22 * @brief test for interrupt message processing in server_mst.c
23 */
24#include "platform.h"
25#include "gnunet_protocols.h"
26#include "gnunet_util_lib.h"
27
28static struct GNUNET_SERVER_MessageStreamTokenizer * mst;
29
30
31/* Callback destroying mst with data in buffer */
32static int
33mst_cb (void *cls, void *client,
34 const struct GNUNET_MessageHeader * message)
35{
36 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MST gave me message, destroying\n");
37 GNUNET_SERVER_mst_destroy (mst);
38 return GNUNET_SYSERR;
39}
40
41
42int
43main (int argc, char *argv[])
44{
45 struct GNUNET_PeerIdentity id;
46 struct GNUNET_MessageHeader msg[2];
47
48 GNUNET_log_setup ("test_server_mst_interrupt", "WARNING", NULL);
49 memset (&id, 0, sizeof (id));
50 msg[0].size = htons (sizeof (msg));
51 msg[0].type = htons (sizeof (GNUNET_MESSAGE_TYPE_DUMMY));
52 mst = GNUNET_SERVER_mst_create(mst_cb, NULL);
53 GNUNET_SERVER_mst_receive (mst, &id,
54 (const char *) &msg, 2 * sizeof (msg),
55 GNUNET_NO, GNUNET_NO);
56 /* If we reach this line, it did not crash */
57 return 0;
58}
59
60/* end of test_server_mst_interrupt.c */
diff --git a/src/util/test_server_with_client.c b/src/util/test_server_with_client.c
deleted file mode 100644
index 63bfda00c..000000000
--- a/src/util/test_server_with_client.c
+++ /dev/null
@@ -1,198 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009, 2016 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * @file util/test_server_with_client.c
22 * @brief tests for server.c and client.c,
23 * specifically disconnect_notify,
24 * client_get_address and receive_done (resume processing)
25 */
26#include "platform.h"
27#include "gnunet_util_lib.h"
28
29#define PORT 22335
30
31#define MY_TYPE 128
32
33
34static struct GNUNET_SERVER_Handle *server;
35
36static struct GNUNET_MQ_Handle *mq;
37
38static struct GNUNET_CONFIGURATION_Handle *cfg;
39
40static int ok;
41
42
43static void
44send_done (void *cls)
45{
46 struct GNUNET_SERVER_Client *argclient = cls;
47
48 GNUNET_assert (ok == 3);
49 ok++;
50 GNUNET_SERVER_receive_done (argclient, GNUNET_OK);
51}
52
53
54static void
55recv_cb (void *cls,
56 struct GNUNET_SERVER_Client *argclient,
57 const struct GNUNET_MessageHeader *message)
58{
59 void *addr;
60 size_t addrlen;
61 struct sockaddr_in sa;
62 struct sockaddr_in *have;
63
64 GNUNET_assert (GNUNET_OK ==
65 GNUNET_SERVER_client_get_address (argclient,
66 &addr,
67 &addrlen));
68
69 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
70 have = addr;
71 memset (&sa, 0, sizeof (sa));
72#if HAVE_SOCKADDR_IN_SIN_LEN
73 sa.sin_len = sizeof (sa);
74#endif
75 sa.sin_family = AF_INET;
76 sa.sin_port = have->sin_port;
77 sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
78 GNUNET_assert (0 == memcmp (&sa, addr, addrlen));
79 GNUNET_free (addr);
80 switch (ok)
81 {
82 case 2:
83 ok++;
84 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
85 (GNUNET_TIME_UNIT_MILLISECONDS, 50),
86 &send_done,
87 argclient);
88 break;
89 case 4:
90 ok++;
91 GNUNET_MQ_destroy (mq);
92 GNUNET_SERVER_receive_done (argclient,
93 GNUNET_OK);
94 break;
95 default:
96 GNUNET_assert (0);
97 }
98
99}
100
101
102static void
103clean_up (void *cls)
104{
105 GNUNET_SERVER_destroy (server);
106 server = NULL;
107 GNUNET_CONFIGURATION_destroy (cfg);
108 cfg = NULL;
109}
110
111
112/**
113 * Functions with this signature are called whenever a client
114 * is disconnected on the network level.
115 *
116 * @param cls closure
117 * @param client identification of the client
118 */
119static void
120notify_disconnect (void *cls,
121 struct GNUNET_SERVER_Client *client)
122{
123 if (client == NULL)
124 return;
125 GNUNET_assert (ok == 5);
126 ok = 0;
127 GNUNET_SCHEDULER_add_now (&clean_up, NULL);
128}
129
130
131static struct GNUNET_SERVER_MessageHandler handlers[] = {
132 {&recv_cb, NULL, MY_TYPE, sizeof (struct GNUNET_MessageHeader)},
133 {NULL, NULL, 0, 0}
134};
135
136
137static void
138task (void *cls)
139{
140 struct sockaddr_in sa;
141 struct sockaddr *sap[2];
142 socklen_t slens[2];
143 struct GNUNET_MQ_Envelope *env;
144 struct GNUNET_MessageHeader *msg;
145
146 sap[0] = (struct sockaddr *) &sa;
147 slens[0] = sizeof (sa);
148 sap[1] = NULL;
149 slens[1] = 0;
150 memset (&sa, 0, sizeof (sa));
151#if HAVE_SOCKADDR_IN_SIN_LEN
152 sa.sin_len = sizeof (sa);
153#endif
154 sa.sin_family = AF_INET;
155 sa.sin_port = htons (PORT);
156 server =
157 GNUNET_SERVER_create (NULL, NULL, sap, slens,
158 GNUNET_TIME_relative_multiply
159 (GNUNET_TIME_UNIT_MILLISECONDS, 250), GNUNET_NO);
160 GNUNET_assert (server != NULL);
161 handlers[0].callback_cls = cls;
162 GNUNET_SERVER_add_handlers (server, handlers);
163 GNUNET_SERVER_disconnect_notify (server, &notify_disconnect, cls);
164 cfg = GNUNET_CONFIGURATION_create ();
165 GNUNET_CONFIGURATION_set_value_number (cfg, "test", "PORT", PORT);
166 GNUNET_CONFIGURATION_set_value_string (cfg, "test", "HOSTNAME", "localhost");
167 GNUNET_CONFIGURATION_set_value_string (cfg, "resolver", "HOSTNAME",
168 "localhost");
169 mq = GNUNET_CLIENT_connect (cfg,
170 "test",
171 NULL,
172 NULL,
173 NULL);
174 GNUNET_assert (NULL != mq);
175 ok = 2;
176 env = GNUNET_MQ_msg (msg,
177 MY_TYPE);
178 GNUNET_MQ_send (mq,
179 env);
180 env = GNUNET_MQ_msg (msg,
181 MY_TYPE);
182 GNUNET_MQ_send (mq,
183 env);
184}
185
186
187int
188main (int argc, char *argv[])
189{
190 GNUNET_log_setup ("test_server_with_client",
191 "WARNING",
192 NULL);
193 ok = 1;
194 GNUNET_SCHEDULER_run (&task, NULL);
195 return ok;
196}
197
198/* end of test_server_with_client.c */
diff --git a/src/util/test_server_with_client_unix.c b/src/util/test_server_with_client_unix.c
deleted file mode 100644
index 8fabbe210..000000000
--- a/src/util/test_server_with_client_unix.c
+++ /dev/null
@@ -1,176 +0,0 @@
1/*
2 This file is part of GNUnet.
3 Copyright (C) 2009, 2016 GNUnet e.V.
4
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
19*/
20/**
21 * @file util/test_server_with_client_unix.c
22 * @brief tests for server.c and client.c,
23 * specifically disconnect_notify,
24 * client_get_address and receive_done (resume processing)
25 */
26#include "platform.h"
27#include "gnunet_util_lib.h"
28
29#define MY_TYPE 128
30
31
32static struct GNUNET_SERVER_Handle *server;
33
34static struct GNUNET_MQ_Handle *mq;
35
36static struct GNUNET_CONFIGURATION_Handle *cfg;
37
38static int ok;
39
40
41static void
42send_done (void *cls)
43{
44 struct GNUNET_SERVER_Client *argclient = cls;
45
46 GNUNET_assert (ok == 3);
47 ok++;
48 GNUNET_SERVER_receive_done (argclient, GNUNET_OK);
49}
50
51
52static void
53recv_cb (void *cls,
54 struct GNUNET_SERVER_Client *argclient,
55 const struct GNUNET_MessageHeader *message)
56{
57 switch (ok)
58 {
59 case 2:
60 ok++;
61 (void) GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
62 (GNUNET_TIME_UNIT_MILLISECONDS, 50),
63 &send_done,
64 argclient);
65 break;
66 case 4:
67 ok++;
68 GNUNET_MQ_destroy (mq);
69 GNUNET_SERVER_receive_done (argclient, GNUNET_OK);
70 break;
71 default:
72 GNUNET_assert (0);
73 }
74
75}
76
77
78static void
79clean_up (void *cls)
80{
81 GNUNET_SERVER_destroy (server);
82 server = NULL;
83 GNUNET_CONFIGURATION_destroy (cfg);
84 cfg = NULL;
85}
86
87
88/**
89 * Functions with this signature are called whenever a client
90 * is disconnected on the network level.
91 *
92 * @param cls closure
93 * @param client identification of the client
94 */
95static void
96notify_disconnect (void *cls,
97 struct GNUNET_SERVER_Client *client)
98{
99 if (client == NULL)
100 return;
101 GNUNET_assert (ok == 5);
102 ok = 0;
103 (void) GNUNET_SCHEDULER_add_now (&clean_up, NULL);
104}
105
106
107static struct GNUNET_SERVER_MessageHandler handlers[] = {
108 {&recv_cb, NULL, MY_TYPE, sizeof (struct GNUNET_MessageHeader)},
109 {NULL, NULL, 0, 0}
110};
111
112
113static void
114task (void *cls)
115{
116 struct sockaddr_un un;
117 const char *unixpath = "/tmp/testsock";
118 struct sockaddr *sap[2];
119 socklen_t slens[2];
120 struct GNUNET_MQ_Envelope *env;
121 struct GNUNET_MessageHeader *msg;
122
123 memset (&un, 0, sizeof (un));
124 un.sun_family = AF_UNIX;
125 strncpy(un.sun_path, unixpath, sizeof (un.sun_path) - 1);
126#if HAVE_SOCKADDR_UN_SUN_LEN
127 un.sun_len = (u_char) sizeof (un);
128#endif
129
130 sap[0] = (struct sockaddr *) &un;
131 slens[0] = sizeof (un);
132 sap[1] = NULL;
133 slens[1] = 0;
134 server =
135 GNUNET_SERVER_create (NULL, NULL, sap, slens,
136 GNUNET_TIME_relative_multiply
137 (GNUNET_TIME_UNIT_MILLISECONDS, 250), GNUNET_NO);
138 GNUNET_assert (server != NULL);
139 handlers[0].callback_cls = cls;
140 GNUNET_SERVER_add_handlers (server, handlers);
141 GNUNET_SERVER_disconnect_notify (server, &notify_disconnect, cls);
142 cfg = GNUNET_CONFIGURATION_create ();
143
144 GNUNET_CONFIGURATION_set_value_string (cfg, "test", "UNIXPATH", unixpath);
145 GNUNET_CONFIGURATION_set_value_string (cfg, "resolver", "HOSTNAME",
146 "localhost");
147 mq = GNUNET_CLIENT_connect (cfg,
148 "test",
149 NULL,
150 NULL,
151 NULL);
152 GNUNET_assert (NULL != mq);
153 ok = 2;
154 env = GNUNET_MQ_msg (msg,
155 MY_TYPE);
156 GNUNET_MQ_send (mq,
157 env);
158 env = GNUNET_MQ_msg (msg,
159 MY_TYPE);
160 GNUNET_MQ_send (mq,
161 env);
162}
163
164
165int
166main (int argc, char *argv[])
167{
168 GNUNET_log_setup ("test_server_with_client_unix",
169 "WARNING",
170 NULL);
171 ok = 1;
172 GNUNET_SCHEDULER_run (&task, NULL);
173 return ok;
174}
175
176/* end of test_server_with_client_unix.c */