aboutsummaryrefslogtreecommitdiff
path: root/src/nat/gnunet-service-nat.c
blob: 1ebf75608ea81a7abbafc297e4bf76aae3e6afbe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
/*
  This file is part of GNUnet.
  Copyright (C) 2016 GNUnet e.V.

  GNUnet is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
  by the Free Software Foundation; either version 3, or (at your
  option) any later version.

  GNUnet is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with GNUnet; see the file COPYING.  If not, write to the
  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
 */

/**
 * @file nat/gnunet-service-nat.c
 * @brief network address translation traversal service
 * @author Christian Grothoff
 *
 * The purpose of this service is to enable transports to 
 * traverse NAT routers, by providing traversal options and
 * knowledge about the local network topology.
 *
 * TODO:
 * - implement UPnPC/PMP-based NAT traversal
 * - implement autoconfig
 * - implement NEW logic for external IP detection
 */
#include "platform.h"
#include <math.h>
#include "gnunet_util_lib.h"
#include "gnunet_protocols.h"
#include "gnunet_signatures.h"
#include "gnunet_statistics_service.h"
#include "gnunet_nat_service.h"
#include "gnunet-service-nat_stun.h"
#include "gnunet-service-nat_helper.h"
#include "nat.h"
#include <gcrypt.h>


/**
 * How often should we ask the OS about a list of active
 * network interfaces?
 */
#define SCAN_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)


/**
 * Internal data structure we track for each of our clients.
 */
struct ClientHandle
{

  /**
   * Kept in a DLL.
   */
  struct ClientHandle *next;
  
  /**
   * Kept in a DLL.
   */
  struct ClientHandle *prev;

  /**
   * Underlying handle for this client with the service.
   */ 
  struct GNUNET_SERVICE_Client *client;

  /**
   * Message queue for communicating with the client.
   */
  struct GNUNET_MQ_Handle *mq;

  /**
   * Array of addresses used by the service.
   */
  struct sockaddr **addrs;
  
  /**
   * What does this client care about?
   */
  enum GNUNET_NAT_RegisterFlags flags;

  /**
   * Is any of the @e addrs in a reserved subnet for NAT?
   */
  int natted_address;
  
  /**
   * Port we would like as we are configured to use this one for
   * advertising (in addition to the one we are binding to).
   */
  uint16_t adv_port;

  /**
   * Number of addresses that this service is bound to.
   */
  uint16_t num_addrs;
  
  /**
   * Client's IPPROTO, e.g. IPPROTO_UDP or IPPROTO_TCP.
   */
  uint8_t proto;

};


/**
 * List of local addresses this system has.
 */
struct LocalAddressList
{
  /**
   * This is a linked list.
   */
  struct LocalAddressList *next;

  /**
   * Previous entry.
   */
  struct LocalAddressList *prev;

  /**
   * The address itself (i.e. `struct sockaddr_in` or `struct
   * sockaddr_in6`, in the respective byte order).
   */
  struct sockaddr_storage addr;

  /**
   * Address family.
   */
  int af;

  /**
   * What type of address is this?
   */
  enum GNUNET_NAT_AddressClass ac;
  
};


/**
 * External IP address as given to us via some STUN server.
 */
struct StunExternalIP
{
  /**
   * Kept in a DLL.
   */ 
  struct StunExternalIP *next;

  /**
   * Kept in a DLL.
   */ 
  struct StunExternalIP *prev;

  /**
   * Task we run to remove this entry when it is stale.
   */
  struct GNUNET_SCHEDULER_Task *timeout_task;

  /**
   * Our external IP address as reported by the 
   * STUN server.
   */
  struct sockaddr_in external_addr;

  /**
   * Address of the reporting STUN server.  Used to 
   * detect when a STUN server changes its opinion
   * to more quickly remove stale results.
   */
  struct sockaddr_storage stun_server_addr;

  /**
   * Number of bytes used in @e stun_server_addr.
   */
  size_t stun_server_addr_len;
};


/**
 * Timeout to use when STUN data is considered stale.
 */
static struct GNUNET_TIME_Relative stun_stale_timeout;

/**
 * Handle to our current configuration.
 */
static const struct GNUNET_CONFIGURATION_Handle *cfg;

/**
 * Handle to the statistics service.
 */
static struct GNUNET_STATISTICS_Handle *stats;

/**
 * Task scheduled to periodically scan our network interfaces.
 */
static struct GNUNET_SCHEDULER_Task *scan_task;

/**
 * Head of client DLL.
 */
static struct ClientHandle *ch_head;
  
/**
 * Tail of client DLL.
 */
static struct ClientHandle *ch_tail;

/**
 * Head of DLL of local addresses.
 */
static struct LocalAddressList *lal_head;

/**
 * Tail of DLL of local addresses.
 */
static struct LocalAddressList *lal_tail;

/**
 * Kept in a DLL.
 */ 
static struct StunExternalIP *se_head;

/**
 * Kept in a DLL.
 */ 
static struct StunExternalIP *se_tail;


/**
 * Free the DLL starting at #lal_head.
 */ 
static void
destroy_lal ()
{
  struct LocalAddressList *lal;

  while (NULL != (lal = lal_head))
  {
    GNUNET_CONTAINER_DLL_remove (lal_head,
				 lal_tail,
				 lal);
    GNUNET_free (lal);
  }
}


/**
 * Check validity of #GNUNET_MESSAGE_TYPE_NAT_REGISTER message from
 * client.
 *
 * @param cls client who sent the message
 * @param message the message received
 * @return #GNUNET_OK if message is well-formed
 */
static int
check_register (void *cls,
		const struct GNUNET_NAT_RegisterMessage *message)
{
  uint16_t num_addrs = ntohs (message->num_addrs);
  const char *off = (const char *) &message[1];
  size_t left = ntohs (message->header.size) - sizeof (*message);

  for (unsigned int i=0;i<num_addrs;i++)
  {
    size_t alen;
    const struct sockaddr *sa = (const struct sockaddr *) off;

    if (sizeof (sa_family_t) > left)
    {
      GNUNET_break (0);
      return GNUNET_SYSERR;
    }
    switch (sa->sa_family)
    {
    case AF_INET:
      alen = sizeof (struct sockaddr_in);
      break;
    case AF_INET6:
      alen = sizeof (struct sockaddr_in6);
      break;
#if AF_UNIX
    case AF_UNIX:
      alen = sizeof (struct sockaddr_un);
      break;
#endif
    default:
      GNUNET_break (0);
      return GNUNET_SYSERR;      
    }
    if (alen > left)
    {
      GNUNET_break (0);
      return GNUNET_SYSERR;      
    }
  }  
  return GNUNET_OK; 
}


/**
 * Check if @a ip is in @a network with @a bits netmask.
 *
 * @param network to test
 * @param ip IP address to test
 * @param bits bitmask for the network
 * @return #GNUNET_YES if @a ip is in @a network
 */
static int
match_ipv4 (const char *network,
	    const struct in_addr *ip,
	    uint8_t bits)
{
  struct in_addr net;
  
  if (0 == bits)
    return GNUNET_YES;
  GNUNET_assert (1 == inet_pton (AF_INET,
				 network,
				 &net));
  return ! ((ip->s_addr ^ net.s_addr) & htonl (0xFFFFFFFFu << (32 - bits)));
}


/**
 * Check if @a ip is in @a network with @a bits netmask.
 *
 * @param network to test
 * @param ip IP address to test
 * @param bits bitmask for the network
 * @return #GNUNET_YES if @a ip is in @a network
 */
static int
match_ipv6 (const char *network,
	    const struct in6_addr *ip,
	    uint8_t bits)
{
  struct in6_addr net;
  struct in6_addr mask;
  unsigned int off;
  
  if (0 == bits)
    return GNUNET_YES;
  GNUNET_assert (1 == inet_pton (AF_INET,
				 network,
				 &net));
  memset (&mask, 0, sizeof (mask));
  off = 0;
  while (bits > 8)
  {
    mask.s6_addr[off++] = 0xFF;
    bits -= 8;
  }
  while (bits > 0)
  {
    mask.s6_addr[off] = (mask.s6_addr[off] >> 1) + 0x80;
    bits--;
  }
  for (unsigned j = 0; j < sizeof (struct in6_addr) / sizeof (uint32_t); j++)
    if (((((uint32_t *) ip)[j] & ((uint32_t *) &mask)[j])) !=
	(((uint32_t *) &net)[j] & ((int *) &mask)[j]))
      return GNUNET_NO;
  return GNUNET_YES;
}


/**
 * Test if the given IPv4 address is in a known range
 * for private networks.
 *
 * @param ip address to test
 * @return #GNUNET_YES if @a ip is in a NAT range
 */
static int
is_nat_v4 (const struct in_addr *ip)
{
  return
    match_ipv4 ("10.0.0.0", ip, 8) || /* RFC 1918 */
    match_ipv4 ("100.64.0.0", ip, 10) || /* CG-NAT, RFC 6598 */
    match_ipv4 ("192.168.0.0", ip, 12) || /* RFC 1918 */
    match_ipv4 ("169.254.0.0", ip, 16) || /* AUTO, RFC 3927 */
    match_ipv4 ("172.16.0.0", ip, 16);  /* RFC 1918 */
}


/**
 * Test if the given IPv6 address is in a known range
 * for private networks.
 *
 * @param ip address to test
 * @return #GNUNET_YES if @a ip is in a NAT range
 */
static int
is_nat_v6 (const struct in6_addr *ip)
{
  return
    match_ipv6 ("fc00::", ip, 7) || /* RFC 4193 */
    match_ipv6 ("fec0::", ip, 10) || /* RFC 3879 */
    match_ipv6 ("fe80::", ip, 10); /* RFC 4291, link-local */
}


/**
 * Handler for #GNUNET_MESSAGE_TYPE_NAT_REGISTER message from client.
 * We remember the client for updates upon future NAT events.
 *
 * @param cls client who sent the message
 * @param message the message received
 */
static void
handle_register (void *cls,
		 const struct GNUNET_NAT_RegisterMessage *message)
{
  struct ClientHandle *ch = cls;
  const char *off;
  size_t left;

  if ( (0 != ch->proto) ||
       (NULL != ch->addrs) )
  {
    /* double registration not allowed */
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (ch->client);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Received REGISTER message from client\n");
  ch->flags = message->flags;
  ch->proto = message->proto;
  ch->adv_port = ntohs (message->adv_port);
  ch->num_addrs = ntohs (message->adv_port);
  ch->addrs = GNUNET_new_array (ch->num_addrs,
				struct sockaddr *);
  left = ntohs (message->header.size) - sizeof (*message);
  off = (const char *) &message[1];
  for (unsigned int i=0;i<ch->num_addrs;i++)
  {
    size_t alen;
    const struct sockaddr *sa = (const struct sockaddr *) off;

    if (sizeof (sa_family_t) > left)
    {
      GNUNET_break (0);
      GNUNET_SERVICE_client_drop (ch->client);
      return;
    }
    switch (sa->sa_family)
    {
    case AF_INET:
      {
	const struct sockaddr_in *s4 = (const struct sockaddr_in *) sa;
	
	alen = sizeof (struct sockaddr_in);
	if (is_nat_v4 (&s4->sin_addr))
	  ch->natted_address = GNUNET_YES;
      }
      break;
    case AF_INET6:
      {
	const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *) sa;
	
	alen = sizeof (struct sockaddr_in6);
	if (is_nat_v6 (&s6->sin6_addr))
	  ch->natted_address = GNUNET_YES;
      }
      break;
#if AF_UNIX
    case AF_UNIX:
      alen = sizeof (struct sockaddr_un);
      break;
#endif
    default:
      GNUNET_break (0);
      GNUNET_SERVICE_client_drop (ch->client);
      return;      
    }
    GNUNET_assert (alen <= left);
    ch->addrs[i] = GNUNET_malloc (alen);
    GNUNET_memcpy (ch->addrs[i],
		   sa,
		   alen);    
    off += alen;
  }  
  GNUNET_SERVICE_client_continue (ch->client);
}


/**
 * Check validity of #GNUNET_MESSAGE_TYPE_NAT_HANDLE_STUN message from
 * client.
 *
 * @param cls client who sent the message
 * @param message the message received
 * @return #GNUNET_OK if message is well-formed
 */
static int
check_stun (void *cls,
	    const struct GNUNET_NAT_HandleStunMessage *message)
{
  size_t sa_len = ntohs (message->sender_addr_size);
  size_t expect = sa_len + ntohs (message->payload_size);
  
  if (ntohs (message->header.size) - sizeof (*message) != expect)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (sa_len < sizeof (sa_family_t))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Notify all clients about our external IP address
 * as reported by the STUN server.
 *
 * @param ip the external IP
 * @param add #GNUNET_YES to add, #GNUNET_NO to remove
 */
static void
notify_clients_stun_change (const struct sockaddr_in *ip,
			    int add)
{
  for (struct ClientHandle *ch = ch_head;
       NULL != ch;
       ch = ch->next)
  {
    struct sockaddr_in v4;
    struct GNUNET_NAT_AddressChangeNotificationMessage *msg;
    struct GNUNET_MQ_Envelope *env;
    
    if (! ch->natted_address)
      continue;
    v4 = *ip;
    v4.sin_port = htons (ch->adv_port);
    env = GNUNET_MQ_msg_extra (msg,
			       sizeof (v4),
			       GNUNET_MESSAGE_TYPE_NAT_ADDRESS_CHANGE);
    msg->add_remove = htonl ((int32_t) add);
    msg->addr_class = htonl (GNUNET_NAT_AC_GLOBAL_EXTERN |
			     GNUNET_NAT_AC_GLOBAL);
    GNUNET_memcpy (&msg[1],
		   &v4,
		   sizeof (v4));
    GNUNET_MQ_send (ch->mq,
		    env);
  }
}


/**
 * Function to be called when we decide that an
 * external IP address as told to us by a STUN
 * server has gone stale.
 *
 * @param cls the `struct StunExternalIP` to drop
 */
static void
stun_ip_timeout (void *cls)
{
  struct StunExternalIP *se = cls;

  se->timeout_task = NULL;
  notify_clients_stun_change (&se->external_addr,
			      GNUNET_NO);
  GNUNET_CONTAINER_DLL_remove (se_head,
			       se_tail,
			       se);
  GNUNET_free (se);
}


/**
 * Handler for #GNUNET_MESSAGE_TYPE_NAT_HANDLE_STUN message from
 * client.
 *
 * @param cls client who sent the message
 * @param message the message received
 */
static void
handle_stun (void *cls,
	     const struct GNUNET_NAT_HandleStunMessage *message)
{
  struct ClientHandle *ch = cls;
  const char *buf = (const char *) &message[1];
  const struct sockaddr *sa;
  const void *payload;
  size_t sa_len;
  size_t payload_size;
  struct sockaddr_in external_addr;

  sa_len = ntohs (message->sender_addr_size);
  payload_size = ntohs (message->payload_size);
  sa = (const struct sockaddr *) &buf[0];
  payload = (const struct sockaddr *) &buf[sa_len];
  switch (sa->sa_family)
  {
  case AF_INET:
    if (sa_len != sizeof (struct sockaddr_in))
    {
      GNUNET_break (0);
      GNUNET_SERVICE_client_drop (ch->client);
      return;
    }
    break;
  case AF_INET6:
    if (sa_len != sizeof (struct sockaddr_in6))
    {
      GNUNET_break (0);
      GNUNET_SERVICE_client_drop (ch->client);
      return;
    }
    break;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Received HANDLE_STUN message from client\n");
  if (GNUNET_OK ==
      GNUNET_NAT_stun_handle_packet_ (payload,
				      payload_size,
				      &external_addr))
  {     
    /* We now know that a server at "sa" claims that
       we are visible at IP "external_addr". 

       We should (for some fixed period of time) tell
       all of our clients that listen to a NAT'ed address
       that they might want to consider the given 'external_ip'
       as their public IP address (this includes TCP and UDP
       clients, even if only UDP sends STUN requests).

       If we do not get a renewal, the "external_addr" should be
       removed again.  The timeout frequency should be configurable
       (with a sane default), so that the UDP plugin can tell how
       often to re-request STUN.
    */
    struct StunExternalIP *se;

    /* Check if we had a prior response from this STUN server */
    for (se = se_head; NULL != se; se = se->next)
    {
      if ( (se->stun_server_addr_len != sa_len) ||
	   (0 != memcmp (sa,
			 &se->stun_server_addr,
			 sa_len)) )
	continue; /* different STUN server */
      if (0 != memcmp (&external_addr,
		       &se->external_addr,
		       sizeof (struct sockaddr_in)))
      {
	/* external IP changed, update! */
	notify_clients_stun_change (&se->external_addr,
				    GNUNET_NO);
	se->external_addr = external_addr;
	notify_clients_stun_change (&se->external_addr,
				    GNUNET_YES);
      }
      /* update timeout */
      GNUNET_SCHEDULER_cancel (se->timeout_task);
      se->timeout_task
	= GNUNET_SCHEDULER_add_delayed (stun_stale_timeout,
					&stun_ip_timeout,
					se);
      return;
    }
    /* STUN server is completely new, create fresh entry */
    se = GNUNET_new (struct StunExternalIP);
    se->external_addr = external_addr;
    GNUNET_memcpy (&se->stun_server_addr,
		   sa,
		   sa_len);
    se->stun_server_addr_len = sa_len;
    se->timeout_task = GNUNET_SCHEDULER_add_delayed (stun_stale_timeout,
						     &stun_ip_timeout,
						     se);
    GNUNET_CONTAINER_DLL_insert (se_head,
				 se_tail,
				 se);
    notify_clients_stun_change (&se->external_addr,
				GNUNET_NO);
  }
  GNUNET_SERVICE_client_continue (ch->client);
}


/**
 * Check validity of
 * #GNUNET_MESSAGE_TYPE_NAT_REQUEST_CONNECTION_REVERSAL message from
 * client.
 *
 * @param cls client who sent the message
 * @param message the message received
 * @return #GNUNET_OK if message is well-formed
 */
static int
check_request_connection_reversal (void *cls,
				   const struct GNUNET_NAT_RequestConnectionReversalMessage *message)
{
  size_t expect;

  expect = ntohs (message->local_addr_size)
    + ntohs (message->remote_addr_size);
  if (ntohs (message->header.size) - sizeof (*message) != expect)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  return GNUNET_OK;
}


/**
 * Handler for #GNUNET_MESSAGE_TYPE_NAT_REQUEST_CONNECTION_REVERSAL
 * message from client.
 *
 * @param cls client who sent the message
 * @param message the message received
 */
static void
handle_request_connection_reversal (void *cls,
				    const struct GNUNET_NAT_RequestConnectionReversalMessage *message)
{
  struct ClientHandle *ch = cls;
  const char *buf = (const char *) &message[1];
  size_t local_sa_len = ntohs (message->local_addr_size);
  size_t remote_sa_len = ntohs (message->remote_addr_size);
  const struct sockaddr *local_sa = (const struct sockaddr *) &buf[0];
  const struct sockaddr *remote_sa = (const struct sockaddr *) &buf[local_sa_len];
  const struct sockaddr_in *l4 = NULL;
  const struct sockaddr_in *r4;
  int ret;
  
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Received REQUEST CONNECTION REVERSAL message from client\n");
  switch (local_sa->sa_family)
  {
  case AF_INET:
    if (local_sa_len != sizeof (struct sockaddr_in))
    {
      GNUNET_break (0);
      GNUNET_SERVICE_client_drop (ch->client);
      return;
    }
    l4 = (const struct sockaddr_in *) local_sa;    
    break;
  case AF_INET6:
    if (local_sa_len != sizeof (struct sockaddr_in6))
    {
      GNUNET_break (0);
      GNUNET_SERVICE_client_drop (ch->client);
      return;
    }
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		_("Connection reversal for IPv6 not supported yet\n"));
    ret = GNUNET_SYSERR;
    break;
  default:
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (ch->client);
    return;
  }
  switch (remote_sa->sa_family)
  {
  case AF_INET:
    if (remote_sa_len != sizeof (struct sockaddr_in))
    {
      GNUNET_break (0);
      GNUNET_SERVICE_client_drop (ch->client);
      return;
    }
    r4 = (const struct sockaddr_in *) remote_sa;
    ret = GN_request_connection_reversal (&l4->sin_addr,
					  ntohs (l4->sin_port),
					  &r4->sin_addr);
    break;
  case AF_INET6:
    if (remote_sa_len != sizeof (struct sockaddr_in6))
    {
      GNUNET_break (0);
      GNUNET_SERVICE_client_drop (ch->client);
      return;
    }
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
		_("Connection reversal for IPv6 not supported yet\n"));
    ret = GNUNET_SYSERR;
    break;
  default:
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (ch->client);
    return;
  }
  if (GNUNET_OK != ret)
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
		_("Connection reversal request failed\n"));  
  GNUNET_SERVICE_client_continue (ch->client);
}


/**
 * Check validity of #GNUNET_MESSAGE_TYPE_NAT_REQUEST_AUTO_CFG message
 * from client.
 *
 * @param cls client who sent the message
 * @param message the message received
 * @return #GNUNET_OK if message is well-formed
 */
static int
check_autoconfig_request (void *cls,
			  const struct GNUNET_NAT_AutoconfigRequestMessage *message)
{
  return GNUNET_OK;  /* checked later */
}


/**
 * Handler for #GNUNET_MESSAGE_TYPE_NAT_REQUEST_AUTO_CFG message from
 * client.
 *
 * @param cls client who sent the message
 * @param message the message received
 */
static void
handle_autoconfig_request (void *cls,
			   const struct GNUNET_NAT_AutoconfigRequestMessage *message)
{
  struct ClientHandle *ch = cls;
  size_t left = ntohs (message->header.size);
  struct GNUNET_CONFIGURATION_Handle *c;

  c = GNUNET_CONFIGURATION_create ();
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_deserialize (c,
					(const char *) &message[1],
					left,
					GNUNET_NO))
  {
    GNUNET_break (0);
    GNUNET_SERVICE_client_drop (ch->client);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Received REQUEST_AUTO_CONFIG message from client\n");
  // FIXME: actually handle request...
  GNUNET_CONFIGURATION_destroy (c);
  GNUNET_SERVICE_client_continue (ch->client);
}


/**
 * Task run during shutdown.
 *
 * @param cls unused
 */
static void
shutdown_task (void *cls)
{
  struct StunExternalIP *se;

  while (NULL != (se = se_head))
  {
    GNUNET_CONTAINER_DLL_remove (se_head,
				 se_tail,
				 se);
    GNUNET_SCHEDULER_cancel (se->timeout_task);
    GNUNET_free (se);
  }
  if (NULL != scan_task)
  {
    GNUNET_SCHEDULER_cancel (scan_task);
    scan_task = NULL;
  }
  if (NULL != stats)
  {
    GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
    stats = NULL;
  }
  destroy_lal ();
}


/**
 * Closure for #ifc_proc.
 */
struct IfcProcContext
{

  /** 
   * Head of DLL of local addresses.
   */
  struct LocalAddressList *lal_head;

  /**
   * Tail of DLL of local addresses.
   */
  struct LocalAddressList *lal_tail;

};


/**
 * Callback function invoked for each interface found.  Adds them
 * to our new address list.
 *
 * @param cls a `struct IfcProcContext *`
 * @param name name of the interface (can be NULL for unknown)
 * @param isDefault is this presumably the default interface
 * @param addr address of this interface (can be NULL for unknown or unassigned)
 * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
 * @param netmask the network mask (can be NULL for unknown or unassigned)
 * @param addrlen length of the address
 * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
 */
static int
ifc_proc (void *cls,
	  const char *name,
	  int isDefault,
	  const struct sockaddr *addr,
	  const struct sockaddr *broadcast_addr,
	  const struct sockaddr *netmask,
	  socklen_t addrlen)
{
  struct IfcProcContext *ifc_ctx = cls;
  struct LocalAddressList *lal;
  size_t alen;
  const struct in_addr *ip4;
  const struct in6_addr *ip6;
  enum GNUNET_NAT_AddressClass ac;

  switch (addr->sa_family)
  {
  case AF_INET:
    alen = sizeof (struct sockaddr_in);
    ip4 = &((const struct sockaddr_in *) addr)->sin_addr;
    if (match_ipv4 ("127.0.0.0", ip4, 8))
      ac = GNUNET_NAT_AC_LOOPBACK;
    else if (is_nat_v4 (ip4))
      ac = GNUNET_NAT_AC_LAN;
    else
      ac = GNUNET_NAT_AC_GLOBAL;
    break;
  case AF_INET6:
    alen = sizeof (struct sockaddr_in6);
    ip6 = &((const struct sockaddr_in6 *) addr)->sin6_addr;
    if (match_ipv6 ("::1", ip6, 128))
      ac = GNUNET_NAT_AC_LOOPBACK;
    else if (is_nat_v6 (ip6))
      ac = GNUNET_NAT_AC_LAN;
    else
      ac = GNUNET_NAT_AC_GLOBAL;
    if ( (ip6->s6_addr[11] == 0xFF) &&
	 (ip6->s6_addr[12] == 0xFE) )
    {
      /* contains a MAC, be extra careful! */
      ac |= GNUNET_NAT_AC_PRIVATE;
    }
    break;
#if AF_UNIX
  case AF_UNIX:
    GNUNET_break (0);
    return GNUNET_OK;
#endif
  default:
    GNUNET_break (0);
    return GNUNET_OK;
  }
  lal = GNUNET_malloc (sizeof (*lal));
  lal->af = addr->sa_family;
  lal->ac = ac;
  GNUNET_memcpy (&lal->addr,
		 addr,
		 alen);
  GNUNET_CONTAINER_DLL_insert (ifc_ctx->lal_head,
			       ifc_ctx->lal_tail,
			       lal);
  return GNUNET_OK;
}


/**
 * Notify client about a change in the list
 * of addresses this peer has.
 *
 * @param delta the entry in the list that changed
 * @param ch client to contact
 * @param add #GNUNET_YES to add, #GNUNET_NO to remove
 * @param addr the address that changed
 * @param addr_len number of bytes in @a addr
 */
static void
notify_client (struct LocalAddressList *delta,
	       struct ClientHandle *ch,
	       int add,
	       const void *addr,
	       size_t addr_len)
{
  struct GNUNET_MQ_Envelope *env;
  struct GNUNET_NAT_AddressChangeNotificationMessage *msg;

  env = GNUNET_MQ_msg_extra (msg,
			     addr_len,
			     GNUNET_MESSAGE_TYPE_NAT_ADDRESS_CHANGE);
  msg->add_remove = htonl (add);
  msg->addr_class = htonl (delta->ac);
  GNUNET_memcpy (&msg[1],
		 addr,
		 addr_len);
  GNUNET_MQ_send (ch->mq,
		  env);
}	     	       


/**
 * Notify all clients about a change in the list
 * of addresses this peer has.
 *
 * @param delta the entry in the list that changed
 * @param add #GNUNET_YES to add, #GNUNET_NO to remove
 */
static void
notify_clients (struct LocalAddressList *delta,
		int add)
{
  for (struct ClientHandle *ch = ch_head;
       NULL != ch;
       ch = ch->next)
  {
    size_t alen;
    struct sockaddr_in v4;
    struct sockaddr_in6 v6;
    
    if (0 == (ch->flags & GNUNET_NAT_RF_ADDRESSES))
      continue;
    switch (delta->af)
    {
    case AF_INET:
      alen = sizeof (struct sockaddr_in);
      GNUNET_memcpy (&v4,
		     &delta->addr,
		     alen);
      for (unsigned int i=0;i<ch->num_addrs;i++)
      {
	const struct sockaddr_in *c4;
	
	if (AF_INET != ch->addrs[i]->sa_family)
	  continue; /* IPv4 not relevant */
	c4 = (const struct sockaddr_in *) ch->addrs[i];
	v4.sin_port = c4->sin_port;
	notify_client (delta,
		       ch,
		       add,
		       &v4,
		       alen);
      }
      break;
    case AF_INET6:
      alen = sizeof (struct sockaddr_in6);
      GNUNET_memcpy (&v6,
		     &delta->addr,
		     alen);
      for (unsigned int i=0;i<ch->num_addrs;i++)
      {
	const struct sockaddr_in6 *c6;
	
	if (AF_INET6 != ch->addrs[i]->sa_family)
	  continue; /* IPv4 not relevant */
	c6 = (const struct sockaddr_in6 *) ch->addrs[i];
	v6.sin6_port = c6->sin6_port;
	notify_client (delta,
		       ch,
		       add,
		       &v6,
		       alen);
      }
      break;
    default:
      GNUNET_break (0);
      continue;
    }
  }
}


/**
 * Task we run periodically to scan for network interfaces.
 *
 * @param cls NULL
 */ 
static void
run_scan (void *cls)
{
  struct IfcProcContext ifc_ctx;
  int found;
  
  scan_task = GNUNET_SCHEDULER_add_delayed (SCAN_FREQ,
					    &run_scan,
					    NULL);
  memset (&ifc_ctx,
	  0,
	  sizeof (ifc_ctx));
  GNUNET_OS_network_interfaces_list (&ifc_proc,
				     &ifc_ctx);
  for (struct LocalAddressList *lal = lal_head;
       NULL != lal;
       lal = lal->next)
  {
    found = GNUNET_NO;
    for (struct LocalAddressList *pos = ifc_ctx.lal_head;
	 NULL != pos;
	 pos = pos->next)
    {
      if ( (pos->af == lal->af) &&
	   (0 == memcmp (&lal->addr,
			 &pos->addr,
			 (AF_INET == lal->af)
			 ? sizeof (struct sockaddr_in)
			 : sizeof (struct sockaddr_in6))) )
	found = GNUNET_YES;
    }
    if (GNUNET_NO == found)
      notify_clients (lal,
		      GNUNET_NO);
  }

  for (struct LocalAddressList *pos = ifc_ctx.lal_head;
       NULL != pos;
       pos = pos->next)
  {
    found = GNUNET_NO;
    for (struct LocalAddressList *lal = lal_head;
	 NULL != lal;
	 lal = lal->next)
    {
      if ( (pos->af == lal->af) &&
	   (0 == memcmp (&lal->addr,
			 &pos->addr,
			 (AF_INET == lal->af)
			 ? sizeof (struct sockaddr_in)
			 : sizeof (struct sockaddr_in6))) )
	found = GNUNET_YES;
    }
    if (GNUNET_NO == found)
      notify_clients (pos,
		      GNUNET_YES);
  }

  destroy_lal ();
  lal_head = ifc_ctx.lal_head;
  lal_tail = ifc_ctx.lal_tail;
}


/**
 * Handle network size estimate clients.
 *
 * @param cls closure
 * @param c configuration to use
 * @param service the initialized service
 */
static void
run (void *cls,
     const struct GNUNET_CONFIGURATION_Handle *c,
     struct GNUNET_SERVICE_Handle *service)
{
  cfg = c;
  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_time (cfg,
					   "NAT",
					   "STUN_STALE",
					   &stun_stale_timeout))
    stun_stale_timeout = GNUNET_TIME_UNIT_HOURS;
  GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
				 NULL);
  stats = GNUNET_STATISTICS_create ("nat",
				    cfg);
  scan_task = GNUNET_SCHEDULER_add_now (&run_scan,
					NULL);
}


/**
 * Callback called when a client connects to the service.
 *
 * @param cls closure for the service
 * @param c the new client that connected to the service
 * @param mq the message queue used to send messages to the client
 * @return a `struct ClientHandle`
 */
static void *
client_connect_cb (void *cls,
		   struct GNUNET_SERVICE_Client *c,
		   struct GNUNET_MQ_Handle *mq)
{
  struct ClientHandle *ch;

  ch = GNUNET_new (struct ClientHandle);
  ch->mq = mq;
  ch->client = c;
  GNUNET_CONTAINER_DLL_insert (ch_head,
			       ch_tail,
			       ch);
  return ch;
}


/**
 * Callback called when a client disconnected from the service
 *
 * @param cls closure for the service
 * @param c the client that disconnected
 * @param internal_cls a `struct ClientHandle *`
 */
static void
client_disconnect_cb (void *cls,
		      struct GNUNET_SERVICE_Client *c,
		      void *internal_cls)
{
  struct ClientHandle *ch = internal_cls;

  GNUNET_CONTAINER_DLL_remove (ch_head,
			       ch_tail,
			       ch);
  for (unsigned int i=0;i<ch->num_addrs;i++)
    GNUNET_free_non_null (ch->addrs[i]);
  GNUNET_free_non_null (ch->addrs);
  GNUNET_free (ch);
}


/**
 * Define "main" method using service macro.
 */
GNUNET_SERVICE_MAIN
("nat",
 GNUNET_SERVICE_OPTION_NONE,
 &run,
 &client_connect_cb,
 &client_disconnect_cb,
 NULL,
 GNUNET_MQ_hd_var_size (register,
			GNUNET_MESSAGE_TYPE_NAT_REGISTER,
			struct GNUNET_NAT_RegisterMessage,
			NULL),
 GNUNET_MQ_hd_var_size (stun,
			GNUNET_MESSAGE_TYPE_NAT_HANDLE_STUN,
			struct GNUNET_NAT_HandleStunMessage,
			NULL),
 GNUNET_MQ_hd_var_size (request_connection_reversal,
			GNUNET_MESSAGE_TYPE_NAT_REQUEST_CONNECTION_REVERSAL,
			struct GNUNET_NAT_RequestConnectionReversalMessage,
			NULL),
 GNUNET_MQ_hd_var_size (autoconfig_request,
			GNUNET_MESSAGE_TYPE_NAT_REQUEST_AUTO_CFG,
			struct GNUNET_NAT_AutoconfigRequestMessage,
			NULL),
 GNUNET_MQ_handler_end ());


#if defined(LINUX) && defined(__GLIBC__)
#include <malloc.h>

/**
 * MINIMIZE heap size (way below 128k) since this process doesn't need much.
 */
void __attribute__ ((constructor))
GNUNET_ARM_memory_init ()
{
  mallopt (M_TRIM_THRESHOLD, 4 * 1024);
  mallopt (M_TOP_PAD, 1 * 1024);
  malloc_trim (0);
}
#endif

/* end of gnunet-service-nat.c */