aboutsummaryrefslogtreecommitdiff
path: root/src/transport/plugin_transport_wlan.c
blob: 124594e90dcd1303610c8bbc63a9ddd298ea0316 (plain) (blame)
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
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
/*
  This file is part of GNUnet
  (C) 2010, 2011, 2012 Christian Grothoff (and other contributing authors)

  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., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.
*/

/**
 * @file transport/plugin_transport_wlan.c
 * @brief transport plugin for wlan
 * @author David Brodski
 * @author Christian Grothoff
 */
#include "platform.h"
#include "gnunet_hello_lib.h"
#include "gnunet_protocols.h"
#include "gnunet_util_lib.h"
#include "gnunet_statistics_service.h"
#include "gnunet_transport_service.h"
#include "gnunet_transport_plugin.h"
#include "plugin_transport_wlan.h"
#include "gnunet_common.h"
#include "gnunet_crypto_lib.h"
#include "gnunet_fragmentation_lib.h"
#include "gnunet_constants.h"

#define LOG(kind,...) GNUNET_log_from (kind, "transport-wlan",__VA_ARGS__)

#define PLUGIN_NAME "wlan"

/**
 * Max size of packet (that we give to the WLAN driver for transmission)
 */
#define WLAN_MTU 1430

/**
 * time out of a mac endpoint
 */
#define MACENDPOINT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2)

/**
 * We reduce the frequence of HELLO beacons in relation to
 * the number of MAC addresses currently visible to us.
 * This is the multiplication factor.
 */
#define HELLO_BEACON_SCALING_FACTOR GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2)

/**
 * Maximum number of messages in defragmentation queue per MAC
 */
#define MESSAGES_IN_DEFRAG_QUEUE_PER_MAC 2

/**
 * Link layer control fields for better compatibility
 * (i.e. GNUnet over WLAN is not IP-over-WLAN).
 */
#define WLAN_LLC_DSAP_FIELD 0x1f
#define WLAN_LLC_SSAP_FIELD 0x1f


GNUNET_NETWORK_STRUCT_BEGIN
/**
 * Header for messages which need fragmentation.  This is the format of
 * a message we obtain AFTER defragmentation.  We then need to check
 * the CRC and then tokenize the payload and pass it to the
 * 'receive' callback.
 */
struct WlanHeader
{

  /**
   * Message type is GNUNET_MESSAGE_TYPE_WLAN_DATA.
   */
  struct GNUNET_MessageHeader header;

  /**
   * CRC32 checksum (only over the payload), in NBO.
   */
  uint32_t crc GNUNET_PACKED;

  /**
   * Sender of the message.
   */
  struct GNUNET_PeerIdentity sender;

  /**
   * Target of the message.
   */
  struct GNUNET_PeerIdentity target;

  /* followed by payload, possibly including
     multiple messages! */

};


struct WlanAddress
{
  uint32_t options GNUNET_PACKED;

  struct GNUNET_TRANSPORT_WLAN_MacAddress mac;
};


GNUNET_NETWORK_STRUCT_END


/**
 * Information kept for each message that is yet to be fragmented and
 * transmitted.
 */
struct PendingMessage
{
  /**
   * next entry in the DLL
   */
  struct PendingMessage *next;

  /**
   * previous entry in the DLL
   */
  struct PendingMessage *prev;

  /**
   * The pending message
   */
  struct WlanHeader *msg;

  /**
   * Continuation function to call once the message
   * has been sent.  Can be NULL if there is no
   * continuation to call.
   */
  GNUNET_TRANSPORT_TransmitContinuation transmit_cont;

  /**
   * Cls for transmit_cont
   */
  void *transmit_cont_cls;

  /**
   * Timeout task (for this message).
   */
  GNUNET_SCHEDULER_TaskIdentifier timeout_task;

};


/**
 * Session handle for connections with other peers.
 */
struct Session
{
  /**
   * To whom are we talking to (set to our identity
   * if we are still waiting for the welcome message)
   */
  struct GNUNET_PeerIdentity target;

  /**
   * API requirement (must be first).
   */
  struct SessionHeader header;

  /**
   * We keep all sessions in a DLL at their respective
   * 'struct MACEndpoint'.
   */
  struct Session *next;

  /**
   * We keep all sessions in a DLL at their respective
   * 'struct MACEndpoint'.
   */
  struct Session *prev;

  /**
   * MAC endpoint with the address of this peer.
   */
  struct MacEndpoint *mac;

  /**
   * Address associated with this session and MAC endpoint
   */
  struct GNUNET_HELLO_Address *address;

  /**
   * Head of messages currently pending for transmission to this peer.
   */
  struct PendingMessage *pending_message_head;

  /**
   * Tail of messages currently pending for transmission to this peer.
   */
  struct PendingMessage *pending_message_tail;

  /**
   * When should this session time out?
   */
  struct GNUNET_TIME_Absolute timeout;

  /**
   * Timeout task (for the session).
   */
  GNUNET_SCHEDULER_TaskIdentifier timeout_task;
};


/**
 * Struct for messages that are being fragmented in a MAC's transmission queue.
 */
struct FragmentMessage
{

  /**
   * This is a doubly-linked list.
   */
  struct FragmentMessage *next;

  /**
   * This is a doubly-linked list.
   */
  struct FragmentMessage *prev;

  /**
   * MAC endpoint this message belongs to
   */
  struct MacEndpoint *macendpoint;

  /**
   * Fragmentation context
   */
  struct GNUNET_FRAGMENT_Context *fragcontext;

  /**
   * Transmission handle to helper (to cancel if the frag context
   * is destroyed early for some reason).
   */
  struct GNUNET_HELPER_SendHandle *sh;

  /**
   * Intended recipient.
   */
  struct GNUNET_PeerIdentity target;

  /**
   * Timeout value for the message.
   */
  struct GNUNET_TIME_Absolute timeout;

  /**
   * Timeout task.
   */
  GNUNET_SCHEDULER_TaskIdentifier timeout_task;

  /**
   * Continuation to call when we're done with this message.
   */
  GNUNET_TRANSPORT_TransmitContinuation cont;

  /**
   * Closure for 'cont'
   */
  void *cont_cls;

  /**
   * Size of original message
   */
  size_t size_payload;

  /**
   * Number of bytes used to transmit message
   */
  size_t size_on_wire;

};


/**
 * Struct to represent one network card connection
 */
struct MacEndpoint
{

  /**
   * We keep all MACs in a DLL in the plugin.
   */
  struct MacEndpoint *next;

  /**
   * We keep all MACs in a DLL in the plugin.
   */
  struct MacEndpoint *prev;

  /**
   * Pointer to the global plugin struct.
   */
  struct Plugin *plugin;

  /**
   * Head of sessions that use this MAC.
   */
  struct Session *sessions_head;

  /**
   * Tail of sessions that use this MAC.
   */
  struct Session *sessions_tail;

  /**
   * Head of messages we are currently sending to this MAC.
   */
  struct FragmentMessage *sending_messages_head;

  /**
   * Tail of messages we are currently sending to this MAC.
   */
  struct FragmentMessage *sending_messages_tail;

  /**
   * Defrag context for this MAC
   */
  struct GNUNET_DEFRAGMENT_Context *defrag;

  /**
   * When should this endpoint time out?
   */
  struct GNUNET_TIME_Absolute timeout;

  /**
   * Timeout task.
   */
  GNUNET_SCHEDULER_TaskIdentifier timeout_task;

  /**
   * count of messages in the fragment out queue for this mac endpoint
   */
  unsigned int fragment_messages_out_count;

  /**
   * peer MAC address
   */
  struct WlanAddress wlan_addr;

  /**
   * Message delay for fragmentation context
   */
  struct GNUNET_TIME_Relative msg_delay;

  /**
   * ACK delay for fragmentation context
   */
  struct GNUNET_TIME_Relative ack_delay;

  /**
   * Desired transmission power for this MAC
   */
  uint16_t tx_power;

  /**
   * Desired transmission rate for this MAC
   */
  uint8_t rate;

  /**
   * Antenna we should use for this MAC
   */
  uint8_t antenna;

};


/**
 * Encapsulation of all of the state of the plugin.
 */
struct Plugin
{
  /**
   * Our environment.
   */
  struct GNUNET_TRANSPORT_PluginEnvironment *env;

  /**
   * Handle to helper process for priviledged operations.
   */
  struct GNUNET_HELPER_Handle *suid_helper;

  /**
   * ARGV-vector for the helper (all helpers take only the binary
   * name, one actual argument, plus the NULL terminator for 'argv').
   */
  char * helper_argv[3];

  /**
   * The interface of the wlan card given to us by the user.
   */
  char *interface;

  /**
   * Tokenizer for demultiplexing of data packets resulting from defragmentation.
   */
  struct GNUNET_SERVER_MessageStreamTokenizer *fragment_data_tokenizer;

  /**
   * Tokenizer for demultiplexing of data packets received from the suid helper
   */
  struct GNUNET_SERVER_MessageStreamTokenizer *helper_payload_tokenizer;

  /**
   * Tokenizer for demultiplexing of data packets that follow the WLAN Header
   */
  struct GNUNET_SERVER_MessageStreamTokenizer *wlan_header_payload_tokenizer;

  /**
   * Head of list of open connections.
   */
  struct MacEndpoint *mac_head;

  /**
   * Tail of list of open connections.
   */
  struct MacEndpoint *mac_tail;

  /**
   * Number of connections
   */
  unsigned int mac_count;

  /**
   * Task that periodically sends a HELLO beacon via the helper.
   */
  GNUNET_SCHEDULER_TaskIdentifier beacon_task;

  /**
   * Tracker for bandwidth limit
   */
  struct GNUNET_BANDWIDTH_Tracker tracker;

  /**
   * The mac_address of the wlan card given to us by the helper.
   */
  struct GNUNET_TRANSPORT_WLAN_MacAddress mac_address;

  /**
   * Have we received a control message with our MAC address yet?
   */
  int have_mac;

  /**
   * Options for addresses
   */
  uint32_t options;

};


/**
 * Information associated with a message.  Can contain
 * the session or the MAC endpoint associated with the
 * message (or both).
 */
struct MacAndSession
{
  /**
   * NULL if the identity of the other peer is not known.
   */
  struct Session *session;

  /**
   * MAC address of the other peer, NULL if not known.
   */
  struct MacEndpoint *endpoint;
};

/**
 * Function called for a quick conversion of the binary address to
 * a numeric address.  Note that the caller must not free the
 * address and that the next call to this function is allowed
 * to override the address again.
 *
 * @param cls closure
 * @param addr binary address
 * @param addrlen length of the address
 * @return string representing the same address
 */
static const char *
wlan_plugin_address_to_string (void *cls, const void *addr, size_t addrlen);

/**
 * Print MAC addresses nicely.
 *
 * @param mac the mac address
 * @return string to a static buffer with the human-readable mac, will be overwritten during the next call to this function
 */
static const char *
mac_to_string (const struct GNUNET_TRANSPORT_WLAN_MacAddress * mac)
{
  static char macstr[20];

  GNUNET_snprintf (macstr, sizeof (macstr), "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X",
  								 mac->mac[0], mac->mac[1],
                   mac->mac[2], mac->mac[3], mac->mac[4], mac->mac[5]);
  return macstr;
}


/**
 * Fill the radiotap header
 *
 * @param endpoint pointer to the endpoint, can be NULL
 * @param header pointer to the radiotap header
 * @param size total message size
 */
static void
get_radiotap_header (struct MacEndpoint *endpoint,
		     struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *header,
		     uint16_t size)
{
  header->header.type = ntohs (GNUNET_MESSAGE_TYPE_WLAN_DATA_TO_HELPER);
  header->header.size = ntohs (size);
  if (NULL != endpoint)
  {
    header->rate = endpoint->rate;
    header->tx_power = endpoint->tx_power;
    header->antenna = endpoint->antenna;
  }
  else
  {
    header->rate = 255;
    header->tx_power = 0;
    header->antenna = 0;
  }
}


/**
 * Generate the WLAN hardware header for one packet
 *
 * @param plugin the plugin handle
 * @param header address to write the header to
 * @param to_mac_addr address of the recipient
 * @param size size of the whole packet, needed to calculate the time to send the packet
 */
static void
get_wlan_header (struct Plugin *plugin,
		 struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame *header,
		 const struct GNUNET_TRANSPORT_WLAN_MacAddress *to_mac_addr,
		 unsigned int size)
{
  const int rate = 11000000;

  header->frame_control = htons (IEEE80211_FC0_TYPE_DATA);
  header->addr1 = *to_mac_addr;
  header->addr2 = plugin->mac_address;
  header->addr3 = mac_bssid_gnunet;
  header->duration = GNUNET_htole16 ((size * 1000000) / rate + 290);
  header->sequence_control = 0; // FIXME?
  header->llc[0] = WLAN_LLC_DSAP_FIELD;
  header->llc[1] = WLAN_LLC_SSAP_FIELD;
  header->llc[2] = 0;  // FIXME?
  header->llc[3] = 0;  // FIXME?
}


/**
 * Send an ACK for a fragment we received.
 *
 * @param cls the 'struct MacEndpoint' the ACK must be sent to
 * @param msg_id id of the message
 * @param hdr pointer to the hdr where the ack is stored
 */
static void
send_ack (void *cls, uint32_t msg_id,
	  const struct GNUNET_MessageHeader *hdr)
{
  struct MacEndpoint *endpoint = cls;
  struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage* radio_header;
  uint16_t msize = ntohs (hdr->size);
  size_t size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + msize;
  char buf[size];

  if (NULL == endpoint)
  {
    GNUNET_break (0);
    return;
  }

  if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
  {
    GNUNET_break (0);
    return;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Sending ACK to helper\n");
  radio_header = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *) buf;
  get_radiotap_header (endpoint, radio_header, size);
  get_wlan_header (endpoint->plugin,
		   &radio_header->frame,
		   &endpoint->wlan_addr.mac,
		   sizeof (endpoint->wlan_addr.mac));
  memcpy (&radio_header[1], hdr, msize);
  if (NULL !=
      GNUNET_HELPER_send (endpoint->plugin->suid_helper,
			  &radio_header->header,
			  GNUNET_NO /* dropping ACKs is bad */,
			  NULL, NULL))
    GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# WLAN ACKs sent"),
			      1, GNUNET_NO);
}


/**
 * Handles the data after all fragments are put together
 *
 * @param cls macendpoint this messages belongs to
 * @param hdr pointer to the data
 */
static void
wlan_data_message_handler (void *cls, const struct GNUNET_MessageHeader *hdr)
{
  struct MacEndpoint *endpoint = cls;
  struct Plugin *plugin = endpoint->plugin;
  struct MacAndSession mas;

  GNUNET_STATISTICS_update (plugin->env->stats,
			    _("# WLAN messages defragmented"), 1,
			    GNUNET_NO);
  mas.session = NULL;
  mas.endpoint = endpoint;
  (void) GNUNET_SERVER_mst_receive (plugin->fragment_data_tokenizer,
				    &mas,
				    (const char *) hdr,
				    ntohs (hdr->size),
				    GNUNET_YES, GNUNET_NO);
}


/**
 * Free a session
 *
 * @param cls our `struct Plugin`.
 * @param session the session free
 */
static int
wlan_plugin_disconnect_session (void *cls,
                                struct Session *session)
{
  struct MacEndpoint *endpoint = session->mac;
  struct PendingMessage *pm;

  endpoint->plugin->env->session_end (endpoint->plugin->env->cls,
				      session->address,
				      session);
  while (NULL != (pm = session->pending_message_head))
  {
    GNUNET_CONTAINER_DLL_remove (session->pending_message_head,
                                 session->pending_message_tail, pm);
    if (GNUNET_SCHEDULER_NO_TASK != pm->timeout_task)
    {
      GNUNET_SCHEDULER_cancel (pm->timeout_task);
      pm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
    }
    GNUNET_free (pm->msg);
    GNUNET_free (pm);
  }
  GNUNET_CONTAINER_DLL_remove (endpoint->sessions_head,
			       endpoint->sessions_tail,
                               session);
  if (session->timeout_task != GNUNET_SCHEDULER_NO_TASK)
  {
    GNUNET_SCHEDULER_cancel (session->timeout_task);
    session->timeout_task = GNUNET_SCHEDULER_NO_TASK;
  }
  GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
                            _("# WLAN sessions allocated"), -1,
                            GNUNET_NO);
  GNUNET_HELLO_address_free (session->address);
  GNUNET_free (session);
  return GNUNET_OK;
}


/**
 * Function that is called to get the keepalive factor.
 * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
 * calculate the interval between keepalive packets.
 *
 * @param cls closure with the `struct Plugin`
 * @return keepalive factor
 */
static unsigned int
wlan_plugin_query_keepalive_factor (void *cls)
{
  return 3;
}


/**
 * A session is timing out.  Clean up.
 *
 * @param cls pointer to the Session
 * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
 */
static void
session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct Session *session = cls;
  struct GNUNET_TIME_Relative timeout;

  session->timeout_task = GNUNET_SCHEDULER_NO_TASK;
  timeout = GNUNET_TIME_absolute_get_remaining (session->timeout);
  if (0 == timeout.rel_value_us)
  {
    wlan_plugin_disconnect_session (session->mac->plugin,
                                    session);
    return;
  }
  session->timeout_task =
    GNUNET_SCHEDULER_add_delayed (timeout, &session_timeout, session);
}



/**
 * Lookup a new session
 *
 * @param endpoint pointer to the mac endpoint of the peer
 * @param peer peer identity to use for this session
 * @return returns the session or NULL
 */
static struct Session *
lookup_session (struct MacEndpoint *endpoint,
                const struct GNUNET_PeerIdentity *peer)
{
  struct Session *session;

  for (session = endpoint->sessions_head; NULL != session; session = session->next)
    if (0 == memcmp (peer, &session->target, sizeof (struct GNUNET_PeerIdentity)))
    {
      session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
      return session;
    }
  return NULL;
}

/**
 * Create a new session
 *
 * @param endpoint pointer to the mac endpoint of the peer
 * @param peer peer identity to use for this session
 * @return returns the session or NULL
 */
static struct Session *
create_session (struct MacEndpoint *endpoint,
                const struct GNUNET_PeerIdentity *peer)
{
  struct Session *session;

  GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# WLAN sessions allocated"), 1,
                            GNUNET_NO);
  session = GNUNET_new (struct Session);
  GNUNET_CONTAINER_DLL_insert_tail (endpoint->sessions_head,
                                    endpoint->sessions_tail,
				    session);
  session->address = GNUNET_HELLO_address_allocate (peer, PLUGIN_NAME,
      &endpoint->wlan_addr, sizeof (endpoint->wlan_addr),
      GNUNET_HELLO_ADDRESS_INFO_NONE);
  session->mac = endpoint;
  session->target = *peer;
  session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
  session->timeout_task =
      GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, &session_timeout, session);
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Created new session %p for peer `%s' with endpoint %s\n",
       session,
       GNUNET_i2s (peer),
       mac_to_string (&endpoint->wlan_addr.mac));

  return session;
}


/**
 * Look up a session for a peer and create a new session if none is found
 *
 * @param endpoint pointer to the mac endpoint of the peer
 * @param peer peer identity to use for this session
 * @return returns the session
 */
static struct Session *
get_session (struct MacEndpoint *endpoint,
                const struct GNUNET_PeerIdentity *peer)
{
  struct Session *session;
  if (NULL != (session = lookup_session (endpoint, peer)))
  	return session;
  return create_session (endpoint, peer);
}


/**
 * Function called once we have successfully given the fragment
 * message to the SUID helper process and we are thus ready for
 * the next fragment.
 *
 * @param cls the 'struct FragmentMessage'
 * @param result result of the operation (#GNUNET_OK on success, #GNUNET_NO if the helper died, #GNUNET_SYSERR
 *        if the helper was stopped)
 */
static void
fragment_transmission_done (void *cls,
			    int result)
{
  struct FragmentMessage *fm = cls;


  fm->sh = NULL;
  GNUNET_FRAGMENT_context_transmission_done (fm->fragcontext);
}


/**
 * Transmit a fragment of a message.
 *
 * @param cls 'struct FragmentMessage' this fragment message belongs to
 * @param hdr pointer to the start of the fragment message
 */
static void
transmit_fragment (void *cls,
		   const struct GNUNET_MessageHeader *hdr)
{
  struct FragmentMessage *fm = cls;
  struct MacEndpoint *endpoint = fm->macendpoint;
  size_t size;
  uint16_t msize;

  if (NULL == endpoint)
  {
  	GNUNET_break (0);
  	return;
  }

  msize = ntohs (hdr->size);
  size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + msize;
  {
    char buf[size];
    struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *radio_header;

    radio_header = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *) buf;
    get_radiotap_header (endpoint, radio_header, size);
    get_wlan_header (endpoint->plugin,
		     &radio_header->frame,
		     &endpoint->wlan_addr.mac,
		     sizeof (endpoint->wlan_addr.mac));
    memcpy (&radio_header[1], hdr, msize);
    GNUNET_assert (NULL == fm->sh);
    fm->sh = GNUNET_HELPER_send (endpoint->plugin->suid_helper,
				 &radio_header->header,
				 GNUNET_NO,
				 &fragment_transmission_done, fm);
    fm->size_on_wire += size;
    if (NULL != fm->sh)
      GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# WLAN message fragments sent"),
				1, GNUNET_NO);
    else
      GNUNET_FRAGMENT_context_transmission_done (fm->fragcontext);
    GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
                              "# bytes currently in WLAN buffers",
                              -msize, GNUNET_NO);
    GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
                              "# bytes transmitted via WLAN",
                              msize, GNUNET_NO);
  }
}


/**
 * Frees the space of a message in the fragment queue (send queue)
 *
 * @param fm message to free
 */
static void
free_fragment_message (struct FragmentMessage *fm)
{
  struct MacEndpoint *endpoint = fm->macendpoint;

  GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# WLAN messages pending (with fragmentation)"),
			    -1, GNUNET_NO);
  GNUNET_CONTAINER_DLL_remove (endpoint->sending_messages_head,
                               endpoint->sending_messages_tail, fm);
  if (NULL != fm->sh)
  {
    GNUNET_HELPER_send_cancel (fm->sh);
    fm->sh = NULL;
  }
  GNUNET_FRAGMENT_context_destroy (fm->fragcontext,
                                   &endpoint->msg_delay,
                                   &endpoint->ack_delay);
  if (fm->timeout_task != GNUNET_SCHEDULER_NO_TASK)
  {
    GNUNET_SCHEDULER_cancel (fm->timeout_task);
    fm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
  }
  GNUNET_free (fm);
}


/**
 * A FragmentMessage has timed out.  Remove it.
 *
 * @param cls pointer to the 'struct FragmentMessage'
 * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
 */
static void
fragmentmessage_timeout (void *cls,
                         const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct FragmentMessage *fm = cls;

  fm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
  if (NULL != fm->cont)
  {
    fm->cont (fm->cont_cls, &fm->target, GNUNET_SYSERR, fm->size_payload, fm->size_on_wire);
    fm->cont = NULL;
  }
  free_fragment_message (fm);
}


/**
 * Transmit a message to the given destination with fragmentation.
 *
 * @param endpoint desired destination
 * @param timeout how long can the message wait?
 * @param target peer that should receive the message
 * @param msg message to transmit
 * @param payload_size bytes of payload
 * @param cont continuation to call once the message has
 *        been transmitted (or if the transport is ready
 *        for the next transmission call; or if the
 *        peer disconnected...); can be NULL
 * @param cont_cls closure for cont
 */
static void
send_with_fragmentation (struct MacEndpoint *endpoint,
			 struct GNUNET_TIME_Relative timeout,
			 const struct GNUNET_PeerIdentity *target,
			 const struct GNUNET_MessageHeader *msg,
			 size_t payload_size,
			 GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)

{
  struct FragmentMessage *fm;
  struct Plugin *plugin;

  plugin = endpoint->plugin;
  fm = GNUNET_new (struct FragmentMessage);
  fm->macendpoint = endpoint;
  fm->target = *target;
  fm->size_payload = payload_size;
  fm->size_on_wire = 0;
  fm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
  fm->cont = cont;
  fm->cont_cls = cont_cls;
  /* 1 MBit/s typical data rate, 1430 byte fragments => ~100 ms per message */
  fm->fragcontext =
    GNUNET_FRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
				    &plugin->tracker,
				    endpoint->msg_delay,
				    endpoint->ack_delay,
				    msg,
				    &transmit_fragment, fm);
  fm->timeout_task =
    GNUNET_SCHEDULER_add_delayed (timeout,
				  &fragmentmessage_timeout, fm);
  GNUNET_CONTAINER_DLL_insert_tail (endpoint->sending_messages_head,
				    endpoint->sending_messages_tail,
				    fm);
}


/**
 * Free a MAC endpoint.
 *
 * @param endpoint pointer to the MacEndpoint to free
 */
static void
free_macendpoint (struct MacEndpoint *endpoint)
{
  struct Plugin *plugin = endpoint->plugin;
  struct FragmentMessage *fm;
  struct Session *session;

  GNUNET_STATISTICS_update (plugin->env->stats,
			    _("# WLAN MAC endpoints allocated"), -1, GNUNET_NO);
  while (NULL != (session = endpoint->sessions_head))
    wlan_plugin_disconnect_session (plugin,
                                    session);
  while (NULL != (fm = endpoint->sending_messages_head))
    free_fragment_message (fm);
  GNUNET_CONTAINER_DLL_remove (plugin->mac_head,
			       plugin->mac_tail,
			       endpoint);

  if (NULL != endpoint->defrag)
  {
    GNUNET_DEFRAGMENT_context_destroy(endpoint->defrag);
    endpoint->defrag = NULL;
  }

  plugin->mac_count--;
  if (GNUNET_SCHEDULER_NO_TASK != endpoint->timeout_task)
  {
    GNUNET_SCHEDULER_cancel (endpoint->timeout_task);
    endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
  }
  GNUNET_free (endpoint);
}


/**
 * A MAC endpoint is timing out.  Clean up.
 *
 * @param cls pointer to the MacEndpoint
 * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
 */
static void
macendpoint_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct MacEndpoint *endpoint = cls;
  struct GNUNET_TIME_Relative timeout;

  endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
  timeout = GNUNET_TIME_absolute_get_remaining (endpoint->timeout);
  if (0 == timeout.rel_value_us)
  {
    free_macendpoint (endpoint);
    return;
  }
  endpoint->timeout_task =
    GNUNET_SCHEDULER_add_delayed (timeout, &macendpoint_timeout,
				  endpoint);
}


/**
 * Find (or create) a MacEndpoint with a specific MAC address
 *
 * @param plugin pointer to the plugin struct
 * @param mac the MAC address of the endpoint
 * @return handle to our data structure for this MAC
 */
static struct MacEndpoint *
create_macendpoint (struct Plugin *plugin, struct WlanAddress *mac)
{
  struct MacEndpoint *pos;

  for (pos = plugin->mac_head; NULL != pos; pos = pos->next)
  {
    if (0 == memcmp (mac, &pos->wlan_addr, sizeof (pos->wlan_addr)))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, "Found existing MAC endpoint `%s'\n",
        wlan_plugin_address_to_string(NULL, &pos->wlan_addr.mac, sizeof (pos->wlan_addr)));
      return pos;
    }
  }
  pos = GNUNET_new (struct MacEndpoint);
  pos->wlan_addr = (*mac);
  pos->plugin = plugin;
  pos->defrag =
    GNUNET_DEFRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
				      MESSAGES_IN_DEFRAG_QUEUE_PER_MAC,
				      pos,
				      &wlan_data_message_handler,
				      &send_ack);

  pos->msg_delay = GNUNET_TIME_UNIT_MILLISECONDS;
  pos->ack_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
  pos->timeout = GNUNET_TIME_relative_to_absolute (MACENDPOINT_TIMEOUT);
  pos->timeout_task =
      GNUNET_SCHEDULER_add_delayed (MACENDPOINT_TIMEOUT, &macendpoint_timeout,
                                    pos);
  GNUNET_CONTAINER_DLL_insert (plugin->mac_head, plugin->mac_tail, pos);
  plugin->mac_count++;
  GNUNET_STATISTICS_update (plugin->env->stats, _("# WLAN MAC endpoints allocated"),
			    1, GNUNET_NO);
  LOG (GNUNET_ERROR_TYPE_DEBUG, "New MAC endpoint `%s'\n",
       wlan_plugin_address_to_string(NULL, &pos->wlan_addr, sizeof (struct WlanAddress)));
  return pos;
}


/**
 * Function obtain the network type for a session
 *
 * @param cls closure ('struct Plugin*')
 * @param session the session
 * @return the network type in HBO or GNUNET_SYSERR
 */
static enum GNUNET_ATS_Network_Type
wlan_get_network (void *cls,
		  struct Session *session)
{
  GNUNET_assert (NULL != session);
  return GNUNET_ATS_NET_WLAN;
}


/**
 * Creates a new outbound session the transport service will use to send data to the
 * peer
 *
 * @param cls the plugin
 * @param address the address
 * @return the session or NULL of max connections exceeded
 */
static struct Session *
wlan_plugin_get_session (void *cls,
			 const struct GNUNET_HELLO_Address *address)
{
  struct Plugin *plugin = cls;
  struct MacEndpoint *endpoint;

  if (NULL == address)
    return NULL;
  if (sizeof (struct WlanAddress) != address->address_length)
  {
    GNUNET_break (0);
    return NULL;
  }
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Service asked to create session for peer `%s' with MAC `%s'\n",
       GNUNET_i2s (&address->peer),
       wlan_plugin_address_to_string(NULL, address->address, address->address_length));
  endpoint = create_macendpoint (plugin, (struct WlanAddress *) address->address);
  return get_session (endpoint, &address->peer);
}


/**
 * Function that can be used to force the plugin to disconnect
 * from the given peer and cancel all previous transmissions
 * (and their continuation).
 *
 * @param cls closure
 * @param target peer from which to disconnect
 */
static void
wlan_plugin_disconnect_peer (void *cls,
                             const struct GNUNET_PeerIdentity *target)
{
  struct Plugin *plugin = cls;
  struct Session *session;
  struct MacEndpoint *endpoint;

  for (endpoint = plugin->mac_head; NULL != endpoint; endpoint = endpoint->next)
    for (session = endpoint->sessions_head; NULL != session; session = session->next)
      if (0 == memcmp (target, &session->target,
		       sizeof (struct GNUNET_PeerIdentity)))
      {
        wlan_plugin_disconnect_session (plugin, session);
	break; /* inner-loop only (in case peer has another MAC as well!) */
      }
}


/**
 * Function that can be used by the transport service to transmit
 * a message using the plugin.   Note that in the case of a
 * peer disconnecting, the continuation MUST be called
 * prior to the disconnect notification itself.  This function
 * will be called with this peer's HELLO message to initiate
 * a fresh connection to another peer.
 *
 * @param cls closure
 * @param session which session must be used
 * @param msgbuf the message to transmit
 * @param msgbuf_size number of bytes in 'msgbuf'
 * @param priority how important is the message (most plugins will
 *                 ignore message priority and just FIFO)
 * @param to how long to wait at most for the transmission (does not
 *                require plugins to discard the message after the timeout,
 *                just advisory for the desired delay; most plugins will ignore
 *                this as well)
 * @param cont continuation to call once the message has
 *        been transmitted (or if the transport is ready
 *        for the next transmission call; or if the
 *        peer disconnected...); can be NULL
 * @param cont_cls closure for cont
 * @return number of bytes used (on the physical network, with overheads);
 *         -1 on hard errors (i.e. address invalid); 0 is a legal value
 *         and does NOT mean that the message was not transmitted (DV)
 */
static ssize_t
wlan_plugin_send (void *cls,
                  struct Session *session,
                  const char *msgbuf, size_t msgbuf_size,
                  unsigned int priority,
                  struct GNUNET_TIME_Relative to,
                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
{
  struct Plugin *plugin = cls;
  struct WlanHeader *wlanheader;
  size_t size = msgbuf_size + sizeof (struct WlanHeader);
  char buf[size] GNUNET_ALIGN;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Transmitting %u bytes of payload to peer `%s' (starting with %u byte message of type %u)\n",
       msgbuf_size,
       GNUNET_i2s (&session->target),
       (unsigned int) ntohs (((struct GNUNET_MessageHeader*)msgbuf)->size),
       (unsigned int) ntohs (((struct GNUNET_MessageHeader*)msgbuf)->type));
  wlanheader = (struct WlanHeader *) buf;
  wlanheader->header.size = htons (msgbuf_size + sizeof (struct WlanHeader));
  wlanheader->header.type = htons (GNUNET_MESSAGE_TYPE_WLAN_DATA);
  wlanheader->sender = *plugin->env->my_identity;
  wlanheader->target = session->target;
  wlanheader->crc = htonl (GNUNET_CRYPTO_crc32_n (msgbuf, msgbuf_size));
  memcpy (&wlanheader[1], msgbuf, msgbuf_size);

  GNUNET_STATISTICS_update (plugin->env->stats,
                            "# bytes currently in WLAN buffers",
                            msgbuf_size, GNUNET_NO);

  send_with_fragmentation (session->mac,
			   to,
			   &session->target,
			   &wlanheader->header,
			   msgbuf_size,
			   cont, cont_cls);
  return size;
}


/**
 * We have received data from the WLAN via some session.  Process depending
 * on the message type (HELLO, DATA, FRAGMENTATION or FRAGMENTATION-ACK).
 *
 * @param cls pointer to the plugin
 * @param client pointer to the session this message belongs to
 * @param hdr start of the message
 */
static int
process_data (void *cls, void *client, const struct GNUNET_MessageHeader *hdr)
{
  struct Plugin *plugin = cls;
  struct GNUNET_HELLO_Address *address;
  struct MacAndSession *mas = client;
  struct MacAndSession xmas;
  struct GNUNET_ATS_Information ats;
  struct FragmentMessage *fm;
  struct GNUNET_PeerIdentity tmpsource;
  const struct WlanHeader *wlanheader;
  int ret;
  uint16_t msize;

  ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
  ats.value = htonl (GNUNET_ATS_NET_WLAN);
  msize = ntohs (hdr->size);

  GNUNET_STATISTICS_update (plugin->env->stats,
                            "# bytes received via WLAN",
                            msize, GNUNET_NO);

  switch (ntohs (hdr->type))
  {
  case GNUNET_MESSAGE_TYPE_HELLO:

    if (GNUNET_OK !=
	GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hdr, &tmpsource))
    {
      GNUNET_break_op (0);
      break;
    }
    if (NULL == mas->endpoint)
    {
      GNUNET_break (0);
      break;
    }

    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "Processing %u bytes of HELLO from peer `%s' at MAC %s\n",
	 (unsigned int) msize,
	 GNUNET_i2s (&tmpsource),
	 wlan_plugin_address_to_string (NULL, &mas->endpoint->wlan_addr,
	     sizeof (mas->endpoint->wlan_addr)));

    GNUNET_STATISTICS_update (plugin->env->stats,
			      _("# HELLO messages received via WLAN"), 1,
			      GNUNET_NO);

    address = GNUNET_HELLO_address_allocate (&tmpsource, PLUGIN_NAME,
        &mas->endpoint->wlan_addr, sizeof (mas->endpoint->wlan_addr),
        GNUNET_HELLO_ADDRESS_INFO_INBOUND);
    plugin->env->receive (plugin->env->cls,
        address, mas->session, hdr);
    plugin->env->update_address_metrics (plugin->env->cls,
        address, mas->session, &ats, 1);
    GNUNET_HELLO_address_free (address);
    break;
  case GNUNET_MESSAGE_TYPE_FRAGMENT:
    if (NULL == mas->endpoint)
    {
      GNUNET_break (0);
      break;
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "Processing %u bytes of FRAGMENT from MAC %s\n",
	 (unsigned int) msize,
	 wlan_plugin_address_to_string (NULL, &mas->endpoint->wlan_addr,
	     sizeof (mas->endpoint->wlan_addr)));
    GNUNET_STATISTICS_update (plugin->env->stats,
                              _("# fragments received via WLAN"), 1, GNUNET_NO);
    (void) GNUNET_DEFRAGMENT_process_fragment (mas->endpoint->defrag,
					      hdr);
    break;
  case GNUNET_MESSAGE_TYPE_FRAGMENT_ACK:
    if (NULL == mas->endpoint)
    {
      GNUNET_break (0);
      break;
    }
    GNUNET_STATISTICS_update (plugin->env->stats, _("# ACKs received via WLAN"),
			      1, GNUNET_NO);
    for (fm = mas->endpoint->sending_messages_head; NULL != fm; fm = fm->next)
    {
      ret = GNUNET_FRAGMENT_process_ack (fm->fragcontext, hdr);
      if (GNUNET_OK == ret)
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG,
	     "Got last ACK, finished message transmission to `%s' (%p)\n",
             wlan_plugin_address_to_string (NULL, &mas->endpoint->wlan_addr,
                 sizeof (mas->endpoint->wlan_addr)),
	     fm);
	mas->endpoint->timeout = GNUNET_TIME_relative_to_absolute (MACENDPOINT_TIMEOUT);
	if (NULL != fm->cont)
	{
	  fm->cont (fm->cont_cls, &fm->target, GNUNET_OK, fm->size_payload, fm->size_on_wire);
	  fm->cont = NULL;
	}
        free_fragment_message (fm);
        break;
      }
      if (GNUNET_NO == ret)
      {
        LOG (GNUNET_ERROR_TYPE_DEBUG,
	     "Got an ACK, message transmission to `%s' not yet finished\n",
             wlan_plugin_address_to_string (NULL, &mas->endpoint->wlan_addr,
                 sizeof (mas->endpoint->wlan_addr)));
        break;
      }
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "ACK not matched against any active fragmentation with MAC `%s'\n",
         wlan_plugin_address_to_string (NULL, &mas->endpoint->wlan_addr,
             sizeof (mas->endpoint->wlan_addr)));
    break;
  case GNUNET_MESSAGE_TYPE_WLAN_DATA:
    if (NULL == mas->endpoint)
    {
      GNUNET_break (0);
      break;
    }
    if (msize < sizeof (struct WlanHeader))
    {
      GNUNET_break (0);
      break;
    }
    wlanheader = (const struct WlanHeader *) hdr;
    if (0 != memcmp (&wlanheader->target,
		     plugin->env->my_identity,
		     sizeof (struct GNUNET_PeerIdentity)))
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG,
	   "WLAN data for `%s', not for me, ignoring\n",
	   GNUNET_i2s (&wlanheader->target));
      break;
    }
    if (ntohl (wlanheader->crc) !=
	GNUNET_CRYPTO_crc32_n (&wlanheader[1], msize - sizeof (struct WlanHeader)))
    {
      GNUNET_STATISTICS_update (plugin->env->stats,
				_("# WLAN DATA messages discarded due to CRC32 error"), 1,
				GNUNET_NO);
      break;
    }
    xmas.endpoint = mas->endpoint;
    if (NULL == (xmas.session = lookup_session (mas->endpoint, &wlanheader->sender)))
    {
      xmas.session = create_session (mas->endpoint, &wlanheader->sender);
      address = GNUNET_HELLO_address_allocate (&wlanheader->sender, PLUGIN_NAME,
          &mas->endpoint->wlan_addr, sizeof (struct WlanAddress),
          GNUNET_HELLO_ADDRESS_INFO_NONE);
      plugin->env->session_start (NULL, address, xmas.session, NULL, 0);
      LOG (GNUNET_ERROR_TYPE_DEBUG,
          "Notifying transport about peer `%s''s new session %p \n",
          GNUNET_i2s (&wlanheader->sender), xmas.session);
      GNUNET_HELLO_address_free (address);
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG,
    		"Processing %u bytes of WLAN DATA from peer `%s'\n",
	 (unsigned int) msize,
	 GNUNET_i2s (&wlanheader->sender));
    (void) GNUNET_SERVER_mst_receive (plugin->wlan_header_payload_tokenizer,
				      &xmas,
				      (const char *) &wlanheader[1],
				      msize - sizeof (struct WlanHeader),
				      GNUNET_YES, GNUNET_NO);
    break;
  default:
    if (NULL == mas->endpoint)
    {
      GNUNET_break (0);
      break;
    }
    if (NULL == mas->session)
    {
      GNUNET_break (0);
      break;
    }
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "Received packet with %u bytes of type %u from peer %s\n",
	 (unsigned int) msize,
	 (unsigned int) ntohs (hdr->type),
	 GNUNET_i2s (&mas->session->target));
    plugin->env->receive (plugin->env->cls,
        mas->session->address,
        mas->session,
        hdr);
    plugin->env->update_address_metrics (plugin->env->cls,
        mas->session->address,
        mas->session,
        &ats, 1);
    break;
  }
  return GNUNET_OK;
}


/**
 * Function used for to process the data from the suid process
 *
 * @param cls the plugin handle
 * @param client client that send the data (not used)
 * @param hdr header of the GNUNET_MessageHeader
 */
static int
handle_helper_message (void *cls, void *client,
		       const struct GNUNET_MessageHeader *hdr)
{
  struct Plugin *plugin = cls;
  struct GNUNET_HELLO_Address *my_address;
  const struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *rxinfo;
  const struct GNUNET_TRANSPORT_WLAN_HelperControlMessage *cm;
  struct WlanAddress wa;
  struct MacAndSession mas;
  uint16_t msize;

  msize = ntohs (hdr->size);
  switch (ntohs (hdr->type))
  {
  case GNUNET_MESSAGE_TYPE_WLAN_HELPER_CONTROL:
    if (msize != sizeof (struct GNUNET_TRANSPORT_WLAN_HelperControlMessage))
    {
      GNUNET_break (0);
      break;
    }
    cm = (const struct GNUNET_TRANSPORT_WLAN_HelperControlMessage *) hdr;
    if (GNUNET_YES == plugin->have_mac)
    {
      if (0 == memcmp (&plugin->mac_address,
		       &cm->mac,
		       sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
	break; /* no change */
      /* remove old address */
      memset (&wa, 0, sizeof (struct WlanAddress));
      wa.mac = plugin->mac_address;
      wa.options = htonl(plugin->options);
      my_address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
          PLUGIN_NAME, &wa, sizeof (wa), GNUNET_HELLO_ADDRESS_INFO_NONE);
      plugin->env->notify_address (plugin->env->cls, GNUNET_NO, my_address);
      GNUNET_HELLO_address_free (my_address);
    }
    plugin->mac_address = cm->mac;
    plugin->have_mac = GNUNET_YES;

    memset (&wa, 0, sizeof (struct WlanAddress));
    wa.mac = plugin->mac_address;
    wa.options = htonl(plugin->options);
    my_address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
        PLUGIN_NAME, &wa, sizeof (wa), GNUNET_HELLO_ADDRESS_INFO_NONE);

    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "Received WLAN_HELPER_CONTROL message with MAC address `%s' for peer `%s'\n",
	 mac_to_string (&cm->mac),
	 GNUNET_i2s (plugin->env->my_identity));
    plugin->env->notify_address (plugin->env->cls, GNUNET_YES, my_address);
    GNUNET_HELLO_address_free (my_address);
    break;
  case GNUNET_MESSAGE_TYPE_WLAN_DATA_FROM_HELPER:
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "Got data message from helper with %u bytes\n",
	 msize);
    GNUNET_STATISTICS_update (plugin->env->stats,
                              _("# DATA messages received via WLAN"), 1,
                              GNUNET_NO);
    if (msize < sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage))
    {
      GNUNET_break (0);
      LOG (GNUNET_ERROR_TYPE_DEBUG,
	   "Size of packet is too small (%u bytes)\n",
	   msize);
      break;
    }
    rxinfo = (const struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *) hdr;

    /* check if message is actually for us */
    if (0 != memcmp (&rxinfo->frame.addr3, &mac_bssid_gnunet,
		     sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
    {
      /* Not the GNUnet BSSID */
      break;
    }
    if ( (0 != memcmp (&rxinfo->frame.addr1, &bc_all_mac,
		       sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress))) &&
	 (0 != memcmp (&rxinfo->frame.addr1, &plugin->mac_address,
		       sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress))) )
    {
      /* Neither broadcast nor specifically for us */
      break;
    }
    if (0 == memcmp (&rxinfo->frame.addr2, &plugin->mac_address,
		     sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
    {
      /* packet is FROM us, thus not FOR us */
      break;
    }

    GNUNET_STATISTICS_update (plugin->env->stats,
			      _("# WLAN DATA messages processed"),
			      1, GNUNET_NO);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "Receiving %u bytes of data from MAC `%s'\n",
	 (unsigned int) (msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage)),
	 mac_to_string (&rxinfo->frame.addr2));
    wa.mac = rxinfo->frame.addr2;
    wa.options = htonl (0);
    mas.endpoint = create_macendpoint (plugin, &wa);
    mas.session = NULL;
    (void) GNUNET_SERVER_mst_receive (plugin->helper_payload_tokenizer,
				      &mas,
				      (const char*) &rxinfo[1],
				      msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage),
				      GNUNET_YES, GNUNET_NO);
    break;
  default:
    GNUNET_break (0);
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "Unexpected message of type %u (%u bytes)",
	 ntohs (hdr->type), ntohs (hdr->size));
    break;
  }
  return GNUNET_OK;
}



/**
 * Task to (periodically) send a HELLO beacon
 *
 * @param cls pointer to the plugin struct
 * @param tc scheduler context
 */
static void
send_hello_beacon (void *cls,
		   const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct Plugin *plugin = cls;
  uint16_t size;
  uint16_t hello_size;
  struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *radioHeader;
  const struct GNUNET_MessageHeader *hello;

  hello = plugin->env->get_our_hello ();
  hello_size = GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello);
  GNUNET_assert (sizeof (struct WlanHeader) + hello_size <= WLAN_MTU);
  size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + hello_size;
  {
    char buf[size] GNUNET_ALIGN;

    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "Sending %u byte HELLO beacon\n",
	 (unsigned int) size);
    radioHeader = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage*) buf;
    get_radiotap_header (NULL, radioHeader, size);
    get_wlan_header (plugin, &radioHeader->frame, &bc_all_mac, size);
    memcpy (&radioHeader[1], hello, hello_size);
    if (NULL !=
	GNUNET_HELPER_send (plugin->suid_helper,
			    &radioHeader->header,
			    GNUNET_YES /* can drop */,
			    NULL, NULL))
      GNUNET_STATISTICS_update (plugin->env->stats, _("# HELLO beacons sent via WLAN"),
				1, GNUNET_NO);
  }
  plugin->beacon_task =
    GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
				  (HELLO_BEACON_SCALING_FACTOR,
				   plugin->mac_count + 1),
				  &send_hello_beacon,
				  plugin);

}


/**
 * Another peer has suggested an address for this
 * peer and transport plugin.  Check that this could be a valid
 * address.  If so, consider adding it to the list
 * of addresses.
 *
 * @param cls closure
 * @param addr pointer to the address
 * @param addrlen length of addr
 * @return GNUNET_OK if this is a plausible address for this peer
 *         and transport
 */
static int
wlan_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
{
  struct Plugin *plugin = cls;
  struct WlanAddress *wa = (struct WlanAddress *) addr;

  if (addrlen != sizeof (struct WlanAddress))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (GNUNET_YES != plugin->have_mac)
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "Rejecting MAC `%s': I don't know my MAC!\n",
	 mac_to_string (addr));
    return GNUNET_NO; /* don't know my MAC */
  }
  if (0 != memcmp (&wa->mac,
		   &plugin->mac_address,
		   sizeof (wa->mac)))
  {
    LOG (GNUNET_ERROR_TYPE_DEBUG,
	 "Rejecting MAC `%s': not my MAC!\n",
	 mac_to_string (addr));
    return GNUNET_NO; /* not my MAC */
  }
  return GNUNET_OK;
}


/**
 * Function called for a quick conversion of the binary address to
 * a numeric address.  Note that the caller must not free the
 * address and that the next call to this function is allowed
 * to override the address again.
 *
 * @param cls closure
 * @param addr binary address
 * @param addrlen length of the address
 * @return string representing the same address
 */
static const char *
wlan_plugin_address_to_string (void *cls, const void *addr, size_t addrlen)
{
  const struct GNUNET_TRANSPORT_WLAN_MacAddress *mac;
  static char macstr[36];

  if (sizeof (struct WlanAddress) != addrlen)
  {
    GNUNET_break (0);
    return NULL;
  }
  mac = &((struct WlanAddress *) addr)->mac;
  GNUNET_snprintf (macstr, sizeof (macstr), "%s.%u.%s",
  		PLUGIN_NAME, ntohl (((struct WlanAddress *) addr)->options),
  		mac_to_string (mac));
  return macstr;
}


/**
 * Convert the transports address to a nice, human-readable format.
 *
 * @param cls closure
 * @param type name of the transport that generated the address
 * @param addr one of the addresses of the host, NULL for the last address
 *        the specific address format depends on the transport
 * @param addrlen length of the address
 * @param numeric should (IP) addresses be displayed in numeric form?
 * @param timeout after how long should we give up?
 * @param asc function to call on each string
 * @param asc_cls closure for asc
 */
static void
wlan_plugin_address_pretty_printer (void *cls, const char *type,
                                    const void *addr, size_t addrlen,
                                    int numeric,
                                    struct GNUNET_TIME_Relative timeout,
                                    GNUNET_TRANSPORT_AddressStringCallback asc,
                                    void *asc_cls)
{
  char *ret;

  if (sizeof (struct WlanAddress) != addrlen)
  {
    /* invalid address  */
    LOG (GNUNET_ERROR_TYPE_WARNING,
	 _("WLAN address with invalid size encountered\n"));
    asc (asc_cls, NULL);
    return;
  }
  ret = GNUNET_strdup (wlan_plugin_address_to_string(NULL, addr, addrlen));
  asc (asc_cls, ret);
  GNUNET_free (ret);
  asc (asc_cls, NULL);
}


/**
 * Exit point from the plugin.
 *
 * @param cls pointer to the api struct
 */
void *
libgnunet_plugin_transport_wlan_done (void *cls)
{
  struct WlanAddress wa;
  struct GNUNET_HELLO_Address *address;
  struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
  struct Plugin *plugin = api->cls;
  struct MacEndpoint *endpoint;
  struct MacEndpoint *endpoint_next;

  if (NULL == plugin)
  {
    GNUNET_free (api);
    return NULL;
  }

  if (GNUNET_YES == plugin->have_mac)
  {
    memset (&wa, 0, sizeof(wa));
    wa.options = htonl (plugin->options);
    wa.mac = plugin->mac_address;
    address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
        PLUGIN_NAME, &wa, sizeof (struct WlanAddress),
        GNUNET_HELLO_ADDRESS_INFO_NONE);

    plugin->env->notify_address (plugin->env->cls, GNUNET_NO, address);
    plugin->have_mac = GNUNET_NO;

    GNUNET_HELLO_address_free (address);
  }

  if (GNUNET_SCHEDULER_NO_TASK != plugin->beacon_task)
  {
    GNUNET_SCHEDULER_cancel (plugin->beacon_task);
    plugin->beacon_task = GNUNET_SCHEDULER_NO_TASK;
  }
  if (NULL != plugin->suid_helper)
  {
    GNUNET_HELPER_stop (plugin->suid_helper, GNUNET_NO);
    plugin->suid_helper = NULL;
  }
  endpoint_next = plugin->mac_head;
  while (NULL != (endpoint = endpoint_next))
  {
    endpoint_next = endpoint->next;
    free_macendpoint (endpoint);
  }
  if (NULL != plugin->fragment_data_tokenizer)
  {
    GNUNET_SERVER_mst_destroy (plugin->fragment_data_tokenizer);
    plugin->fragment_data_tokenizer = NULL;
  }
  if (NULL != plugin->wlan_header_payload_tokenizer)
  {
    GNUNET_SERVER_mst_destroy (plugin->wlan_header_payload_tokenizer);
    plugin->wlan_header_payload_tokenizer = NULL;
  }
  if (NULL != plugin->helper_payload_tokenizer)
  {
    GNUNET_SERVER_mst_destroy (plugin->helper_payload_tokenizer);
    plugin->helper_payload_tokenizer = NULL;
  }
  GNUNET_free_non_null (plugin->interface);
  GNUNET_free (plugin);
  GNUNET_free (api);
  return NULL;
}


/**
 * Function called to convert a string address to
 * a binary address.
 *
 * @param cls closure ('struct Plugin*')
 * @param addr string address
 * @param addrlen length of the address
 * @param buf location to store the buffer
 * @param added location to store the number of bytes in the buffer.
 *        If the function returns GNUNET_SYSERR, its contents are undefined.
 * @return GNUNET_OK on success, GNUNET_SYSERR on failure
 */
static int
wlan_string_to_address (void *cls, const char *addr, uint16_t addrlen,
			void **buf, size_t *added)
{
  struct WlanAddress *wa;
  unsigned int a[6];
  unsigned int i;
  char plugin[5];
  uint32_t options;

  if ((NULL == addr) || (addrlen == 0))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if ('\0' != addr[addrlen - 1])
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  if (strlen (addr) != addrlen - 1)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }

  if (8 != SSCANF (addr,
		   "%4s.%u.%X:%X:%X:%X:%X:%X",
		   plugin, &options,
		   &a[0], &a[1], &a[2], &a[3], &a[4], &a[5]))
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  wa = GNUNET_new (struct WlanAddress);
  for (i=0;i<6;i++)
    wa->mac.mac[i] = a[i];
  wa->options = htonl (0);
  *buf = wa;
  *added = sizeof (struct WlanAddress);
  return GNUNET_OK;
}


static void
wlan_plugin_update_session_timeout (void *cls,
                                  const struct GNUNET_PeerIdentity *peer,
                                  struct Session *session)
{
  if (session->timeout_task != GNUNET_SCHEDULER_NO_TASK)
    GNUNET_SCHEDULER_cancel (session->timeout_task);

  session->timeout_task = GNUNET_SCHEDULER_add_delayed (
      GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, &session_timeout, session);
}

/**
 * Entry point for the plugin.
 *
 * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
 * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
 */
void *
libgnunet_plugin_transport_wlan_init (void *cls)
{
  struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
  struct GNUNET_TRANSPORT_PluginFunctions *api;
  struct Plugin *plugin;
  char *interface;
  unsigned long long testmode;
  char *binary;

  /* check for 'special' mode */
  if (NULL == env->receive)
  {
    /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
       initialze the plugin or the API */
    api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
    api->cls = NULL;
    api->address_pretty_printer = &wlan_plugin_address_pretty_printer;
    api->address_to_string = &wlan_plugin_address_to_string;
    api->string_to_address = &wlan_string_to_address;
    return api;
  }

  testmode = 0;
  /* check configuration */
  if ( (GNUNET_YES ==
	GNUNET_CONFIGURATION_have_value (env->cfg, "transport-wlan", "TESTMODE")) &&
       ( (GNUNET_SYSERR ==
	  GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-wlan",
						 "TESTMODE", &testmode)) ||
	 (testmode > 2) ) )
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
			       "transport-wlan", "TESTMODE");
    return NULL;
  }
  binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-transport-wlan");
  if ( (0 == testmode) &&
       (GNUNET_YES != GNUNET_OS_check_helper_binary (binary, GNUNET_YES, NULL)) )
  {
    LOG (GNUNET_ERROR_TYPE_ERROR,
	 _("Helper binary `%s' not SUID, cannot run WLAN transport\n"),
	 "gnunet-helper-transport-wlan");
    GNUNET_free (binary);
    return NULL;
  }
    GNUNET_free (binary);
  if (GNUNET_YES !=
      GNUNET_CONFIGURATION_get_value_string
      (env->cfg, "transport-wlan", "INTERFACE",
       &interface))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
			       "transport-wlan", "INTERFACE");
    return NULL;
  }

  plugin = GNUNET_new (struct Plugin);
  plugin->interface = interface;
  plugin->env = env;
  GNUNET_STATISTICS_set (plugin->env->stats, _("# WLAN sessions allocated"),
                         0, GNUNET_NO);
  GNUNET_STATISTICS_set (plugin->env->stats, _("# WLAN MAC endpoints allocated"),
                         0, 0);
  GNUNET_BANDWIDTH_tracker_init (&plugin->tracker, NULL, NULL,
                                 GNUNET_BANDWIDTH_value_init (100 * 1024 *
                                                              1024 / 8), 100);
  plugin->fragment_data_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
  plugin->wlan_header_payload_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
  plugin->helper_payload_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
  plugin->beacon_task = GNUNET_SCHEDULER_add_now (&send_hello_beacon,
						  plugin);

  plugin->options = 0;

  /* some compilers do not like switch on 'long long'... */
  switch ((unsigned int) testmode)
  {
  case 0: /* normal */
    plugin->helper_argv[0] = (char *) "gnunet-helper-transport-wlan";
    plugin->helper_argv[1] = interface;
    plugin->helper_argv[2] = NULL;
    plugin->suid_helper = GNUNET_HELPER_start (GNUNET_NO,
					       "gnunet-helper-transport-wlan",
					       plugin->helper_argv,
					       &handle_helper_message,
					       NULL,
					       plugin);
    break;
  case 1: /* testmode, peer 1 */
    plugin->helper_argv[0] = (char *) "gnunet-helper-transport-wlan-dummy";
    plugin->helper_argv[1] = (char *) "1";
    plugin->helper_argv[2] = NULL;
    plugin->suid_helper = GNUNET_HELPER_start (GNUNET_NO,
					       "gnunet-helper-transport-wlan-dummy",
					       plugin->helper_argv,
					       &handle_helper_message,
					       NULL,
					       plugin);
    break;
  case 2: /* testmode, peer 2 */
    plugin->helper_argv[0] = (char *) "gnunet-helper-transport-wlan-dummy";
    plugin->helper_argv[1] = (char *) "2";
    plugin->helper_argv[2] = NULL;
    plugin->suid_helper = GNUNET_HELPER_start (GNUNET_NO,
					       "gnunet-helper-transport-wlan-dummy",
					       plugin->helper_argv,
					       &handle_helper_message,
					       NULL,
					       plugin);
    break;
  default:
    GNUNET_assert (0);
  }

  api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
  api->cls = plugin;
  api->send = &wlan_plugin_send;
  api->get_session = &wlan_plugin_get_session;
  api->disconnect_peer = &wlan_plugin_disconnect_peer;
  api->disconnect_session = &wlan_plugin_disconnect_session;
  api->query_keepalive_factor = &wlan_plugin_query_keepalive_factor;
  api->address_pretty_printer = &wlan_plugin_address_pretty_printer;
  api->check_address = &wlan_plugin_address_suggested;
  api->address_to_string = &wlan_plugin_address_to_string;
  api->string_to_address = &wlan_string_to_address;
  api->get_network = &wlan_get_network;
  api->update_session_timeout = &wlan_plugin_update_session_timeout;
  return api;
}


/* end of plugin_transport_wlan.c */