aboutsummaryrefslogtreecommitdiff
path: root/src/transport/plugin_transport_http.c
blob: 69af301168011f13cdfee5a90b99783635221cfd (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
/*
     This file is part of GNUnet
     (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 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 2, 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_http.c
 * @brief http transport service plugin
 * @author Matthias Wachs
 */

#include "platform.h"
#include "gnunet_constants.h"
#include "gnunet_protocols.h"
#include "gnunet_connection_lib.h"
#include "gnunet_server_lib.h"
#include "gnunet_service_lib.h"
#include "gnunet_statistics_service.h"
#include "gnunet_transport_service.h"
#include "gnunet_resolver_service.h"
#include "gnunet_server_lib.h"
#include "gnunet_container_lib.h"
#include "plugin_transport.h"
#include "gnunet_os_lib.h"
#include "microhttpd.h"
#include <curl/curl.h>


#define DEBUG_CURL GNUNET_YES
#define DEBUG_HTTP GNUNET_NO
#define HTTP_CONNECT_TIMEOUT_DBG 10

/**
 * Text of the response sent back after the last bytes of a PUT
 * request have been received (just to formally obey the HTTP
 * protocol).
 */
#define HTTP_PUT_RESPONSE "Thank you!"

/**
 * After how long do we expire an address that we
 * learned from another peer if it is not reconfirmed
 * by anyone?
 */
#define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)

/**
 * Page returned if request invalid
 */
#define HTTP_ERROR_RESPONSE "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\"><HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>Not Found</H1>The requested URL was not found on this server.<P><HR><ADDRESS></ADDRESS></BODY></HTML>"

/**
 * Timeout for a http connect
 */
#define HTTP_CONNECT_TIMEOUT 30

/**
 * Network format for IPv4 addresses.
 */
struct IPv4HttpAddress
{
  /**
   * IPv4 address, in network byte order.
   */
  uint32_t ipv4_addr GNUNET_PACKED;

  /**
   * Port number, in network byte order.
   */
  uint16_t u_port GNUNET_PACKED;

};


/**
 * Network format for IPv6 addresses.
 */
struct IPv6HttpAddress
{
  /**
   * IPv6 address.
   */
  struct in6_addr ipv6_addr GNUNET_PACKED;

  /**
   * Port number, in network byte order.
   */
  uint16_t u6_port GNUNET_PACKED;

};


/**
 *  Message to send using http
 */
struct HTTP_Message
{
  /**
   * next pointer for double linked list
   */
  struct HTTP_Message * next;

  /**
   * previous pointer for double linked list
   */
  struct HTTP_Message * prev;

  /**
   * buffer containing data to send
   */
  char *buf;

  /**
   * amount of data already sent
   */
  size_t pos;

  /**
   * buffer length
   */
  size_t size;
  
  /**
   * Continuation function to call once the transmission buffer
   * has again space available.  NULL if there is no
   * continuation to call.
   */
  GNUNET_TRANSPORT_TransmitContinuation transmit_cont;

  /**
   * Closure for transmit_cont.
   */
  void *transmit_cont_cls;
};


struct HTTP_Connection_out
{
  struct HTTP_Connection_out * next;

  struct HTTP_Connection_out * prev;

  void * addr;
  size_t addrlen;

  struct HTTP_Message * pending_msgs_head;
  struct HTTP_Message * pending_msgs_tail;

  char * url;
  unsigned int put_connected;
  unsigned int put_send_paused;

  unsigned int get_connected;

  /**
   * curl handle for sending data using HTTP/PUT
   * outbound data
   */
  CURL *put_curl_handle;

  /**
   * curl handle for recieving data using HTTP/GET transmission
   * inbound data
   */
  CURL *get_curl_handle;

  struct Session * session;
};

struct HTTP_Connection_in
{
  struct HTTP_Connection_in * next;

  struct HTTP_Connection_in * prev;

  void * addr;
  size_t addrlen;

  unsigned int connected;
  unsigned int send_paused;

  struct GNUNET_SERVER_MessageStreamTokenizer * msgtok;

  struct Session * session;

  /**
   * Is there a HTTP/PUT in progress?
   */
  int is_put_in_progress;

  /**
   * Is the http request invalid?
   */
  int is_bad_request;
};


/**
 * Session handle for connections.
 */
struct Session
{

  /**
   * API requirement.
   */
  struct SessionHeader header;

  /**
   * Stored in a linked list.
   */
  struct Session *next;

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

  /**
   * To whom are we talking to (set to our identity
   * if we are still waiting for the welcome message)
   */
  struct GNUNET_PeerIdentity identity;

  /**
   * Sender's ip address to distinguish between incoming connections
   */
  void * addr_in;

  size_t addr_in_len;

  void * addr_out;

  size_t addr_out_len;

  /**
   * Did we initiate the connection (GNUNET_YES) or the other peer (GNUNET_NO)?
   */
  int is_client;

  /**
   * At what time did we reset last_received last?
   */
  struct GNUNET_TIME_Absolute last_quota_update;

  /**
   * How many bytes have we received since the "last_quota_update"
   * timestamp?
   */
  uint64_t last_received;

  /**
   * Number of bytes per ms that this peer is allowed
   * to send to us.
   */
  uint32_t quota;

  /**
   * Encoded hash
   */
  struct GNUNET_CRYPTO_HashAsciiEncoded hash;

  /**
   * curl handle for outbound transmissions
   */
  CURL *curl_handle;

  /**
   * Message tokenizer for incoming data
   */
  //struct GNUNET_SERVER_MessageStreamTokenizer * msgtok;

  struct HTTP_Connection_out *outbound_connections_head;
  struct HTTP_Connection_out *outbound_connections_tail;

  struct HTTP_Connection_in *inbound_connections_head;
  struct HTTP_Connection_in *inbound_connections_tail;
};

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

  unsigned int port_inbound;

  /**
   * Hashmap for all existing sessions.
   */
  struct GNUNET_CONTAINER_MultiHashMap *sessions;

  /**
   * Daemon for listening for new IPv4 connections.
   */
  struct MHD_Daemon *http_server_daemon_v4;

  /**
   * Daemon for listening for new IPv6connections.
   */
  struct MHD_Daemon *http_server_daemon_v6;

  /**
   * Our primary task for http daemon handling IPv4 connections
   */
  GNUNET_SCHEDULER_TaskIdentifier http_server_task_v4;

  /**
   * Our primary task for http daemon handling IPv6 connections
   */
  GNUNET_SCHEDULER_TaskIdentifier http_server_task_v6;

  /**
   * The task sending data
   */
  GNUNET_SCHEDULER_TaskIdentifier http_server_task_send;

  /**
   * cURL Multihandle
   */
  CURLM * multi_handle;

  /**
   * Our ASCII encoded, hashed peer identity
   * This string is used to distinguish between connections and is added to the urls
   */
  struct GNUNET_CRYPTO_HashAsciiEncoded my_ascii_hash_ident;
};


/**
 * 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*
http_plugin_address_to_string (void *cls,
                                   const void *addr,
                                   size_t addrlen);

/**
 * Create a new session
 * @param cls plugin as closure
 * @param addr_in address the peer is using inbound
 * @param addr_len_in address length
 * @param addr_out address the peer is using outbound
 * @param addr_len_out address length
 * @param peer identity
 * @return created session object
 */
static struct Session * 
create_session (void * cls, 
		char * addr_in, 
		size_t addrlen_in,
		char * addr_out, 
		size_t addrlen_out, 
		const struct GNUNET_PeerIdentity *peer)
{
  struct Plugin *plugin = cls;
  struct Session * cs = GNUNET_malloc ( sizeof( struct Session) );

  GNUNET_assert(cls !=NULL);
  if (addrlen_in != 0)
  {
    cs->addr_in = GNUNET_malloc (addrlen_in);
    cs->addr_in_len = addrlen_in;
    memcpy(cs->addr_in,addr_in,addrlen_in);
  }

  if (addrlen_out != 0)
  {
    cs->addr_out = GNUNET_malloc (addrlen_out);
    cs->addr_out_len = addrlen_out;
    memcpy(cs->addr_out,addr_out,addrlen_out);
  }
  cs->plugin = plugin;
  memcpy(&cs->identity, peer, sizeof (struct GNUNET_PeerIdentity));
  GNUNET_CRYPTO_hash_to_enc(&cs->identity.hashPubKey,&(cs->hash));
  cs->outbound_connections_head = NULL;
  cs->outbound_connections_tail = NULL;
  return cs;
}

/**
 * Check if session for this peer is already existing, otherwise create it
 * @param cls the plugin used
 * @param p peer to get session for
 * @return session found or created
 */
static struct Session * session_get (void * cls, const struct GNUNET_PeerIdentity *p)
{
  struct Plugin *plugin = cls;
  struct Session *cs;
  unsigned int res;

  cs = GNUNET_CONTAINER_multihashmap_get (plugin->sessions, &p->hashPubKey);
  if (cs == NULL)
  {
    cs = create_session(plugin, NULL, 0, NULL, 0, p);
    res = GNUNET_CONTAINER_multihashmap_put ( plugin->sessions,
                                        &cs->identity.hashPubKey,
                                        cs,
                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
    if (res == GNUNET_OK)
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "New Session `%s' inserted\n", GNUNET_i2s(p));
  }
  return cs;
}

static char * create_url(void * cls, const void * addr, size_t addrlen)
{
  struct Plugin *plugin = cls;
  char *url = NULL;

  GNUNET_assert ((addr!=NULL) && (addrlen != 0));
  GNUNET_asprintf(&url,
                  "http://%s/%s",
                  http_plugin_address_to_string(NULL, addr, addrlen),
                  (char *) (&plugin->my_ascii_hash_ident));

  return url;
}

/**
 * Check if session already knows this address for a outbound connection to this peer
 * If address not in session, add it to the session
 * @param cls the plugin used
 * @param cs the session
 * @param addr address
 * @param addr_len address length
 * @return the found or created address
 */
static struct HTTP_Connection_out * session_check_outbound_address (void * cls, struct Session *cs, const void * addr, size_t addr_len)
{
  struct Plugin *plugin = cls;
  struct HTTP_Connection_out * cc = cs->outbound_connections_head;
  struct HTTP_Connection_out * con = NULL;

  GNUNET_assert((addr_len == sizeof (struct IPv4HttpAddress)) || (addr_len == sizeof (struct IPv6HttpAddress)));

  while (cc!=NULL)
  {
    if (addr_len == cc->addrlen)
    {
      if (0 == memcmp(cc->addr, addr, addr_len))
      {
        con = cc;
        break;
      }
    }
    cc=cc->next;
  }

  if (con==NULL)
  {
    con = GNUNET_malloc(sizeof(struct HTTP_Connection_out) + addr_len);
    con->addrlen = addr_len;
    con->addr=&con[1];
    con->url=create_url(plugin, addr, addr_len);
    con->put_curl_handle = NULL;
    con->put_connected = GNUNET_NO;
    con->get_curl_handle = NULL;
    con->get_connected = GNUNET_NO;
    con->session = cs;
    memcpy(con->addr, addr, addr_len);
    GNUNET_CONTAINER_DLL_insert(cs->outbound_connections_head,cs->outbound_connections_tail,con);
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Created new connection %X to peer `%s'\n",con,GNUNET_i2s(&cs->identity));
  }
  return con;
}


/**
 * Check if session already knows this address for a inbound connection to this peer
 * If address not in session, add it to the session
 * @param cls not needed, can be NULL
 * @param cs the session
 * @param addr address
 * @param addr_len address length
 * @return the found or created address
 */
static struct HTTP_Connection_in * session_check_inbound_address (void * cls, struct Session *cs, const void * addr, size_t addr_len)
{
  struct HTTP_Connection_in * cc = cs->inbound_connections_head;
  struct HTTP_Connection_in * con = NULL;

  GNUNET_assert((addr_len == sizeof (struct IPv4HttpAddress)) || (addr_len == sizeof (struct IPv6HttpAddress)));

  while (cc!=NULL)
  {
    if (addr_len == cc->addrlen)
    {
      if (0 == memcmp(cc->addr, addr, addr_len))
      {
        con = cc;
        break;
      }
    }
    cc=cc->next;
  }


  if (con==NULL)
  {
    con = GNUNET_malloc(sizeof(struct HTTP_Connection_in) + addr_len);
    con->addrlen = addr_len;
    con->addr=&con[1];
    con->connected = GNUNET_NO;
    con->session = cs;
    memcpy(con->addr, addr, addr_len);
    GNUNET_CONTAINER_DLL_insert(cs->inbound_connections_head,cs->inbound_connections_tail,con);
  }

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X for inbound address %s (%s) was found\n",
              con,
              GNUNET_i2s(&cs->identity),
              http_plugin_address_to_string(NULL,con->addr,con->addrlen));
  return con;
}


/**
 * Callback called by MHD when a connection is terminated
 */
static void requestCompletedCallback (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
{
  struct HTTP_Connection_in * con;

  con = *httpSessionCache;
  if (con == NULL)
    return;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection from peer `%s' was terminated\n",GNUNET_i2s(&con->session->identity));
  /* session set to inactive */
  con->is_put_in_progress = GNUNET_NO;
  con->is_bad_request = GNUNET_NO;
}

static void messageTokenizerCallback (void *cls,
                                      void *client,
                                      const struct GNUNET_MessageHeader *message)
{
  struct HTTP_Connection_in * con = cls;
  GNUNET_assert(con != NULL);

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
	      "Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
	      ntohs(message->type),
              ntohs(message->size),
	      GNUNET_i2s(&(con->session->identity)),http_plugin_address_to_string(NULL,con->addr,con->addrlen));

  con->session->plugin->env->receive (con->session->plugin->env->cls,
			    &con->session->identity,
			    message, 1, con->session,
			    NULL,
			    0);
}

/**
 * Check if ip is allowed to connect.
 */
static int
acceptPolicyCallback (void *cls,
                      const struct sockaddr *addr, socklen_t addr_len)
{
#if 0
  struct Plugin *plugin = cls;
#endif
  /* Every connection is accepted, nothing more to do here */
  return MHD_YES;
}

int server_read_callback (void *cls, uint64_t pos, char *buf, int max)
{
  int bytes_read = -1;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "server_read_callback\n");
  return bytes_read;
}

/**
 * Process GET or PUT request received via MHD.  For
 * GET, queue response that will send back our pending
 * messages.  For PUT, process incoming data and send
 * to GNUnet core.  In either case, check if a session
 * already exists and create a new one if not.
 */
static int
accessHandlerCallback (void *cls,
                       struct MHD_Connection *mhd_connection,
                       const char *url,
                       const char *method,
                       const char *version,
                       const char *upload_data,
                       size_t * upload_data_size, void **httpSessionCache)
{
  struct Plugin *plugin = cls;
  struct MHD_Response *response;
  struct Session * cs;
  struct HTTP_Connection_in * con;
  const union MHD_ConnectionInfo * conn_info;
  struct sockaddr_in  *addrin;
  struct sockaddr_in6 *addrin6;
  char address[INET6_ADDRSTRLEN+14];
  struct GNUNET_PeerIdentity pi_in;
  int res = GNUNET_NO;
  int send_error_to_client;
  struct IPv4HttpAddress ipv4addr;
  struct IPv6HttpAddress ipv6addr;

  GNUNET_assert(cls !=NULL);
  send_error_to_client = GNUNET_NO;
  if (NULL == *httpSessionCache)
  {
    /* check url for peer identity , if invalid send HTTP 404*/
    res = GNUNET_CRYPTO_hash_from_string ( &url[1], &(pi_in.hashPubKey));
    if ( GNUNET_SYSERR == res )
    {
      response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
      res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
      MHD_destroy_response (response);
      if (res == MHD_YES)
        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, sent HTTP 1.1/404\n");
      else
        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, could not send error\n");
      return res;
    }
  }
  else
  {
    con = *httpSessionCache;
    cs = con->session;
  }

  if (NULL == *httpSessionCache)
  {
    /* get session for peer identity */
    cs = session_get (plugin ,&pi_in);

    conn_info = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
    /* Incoming IPv4 connection */
    if ( AF_INET == conn_info->client_addr->sin_family)
    {
      addrin = conn_info->client_addr;
      inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
      memcpy(&ipv4addr.ipv4_addr,&(addrin->sin_addr),sizeof(struct in_addr));
      ipv4addr.u_port = addrin->sin_port;
      con = session_check_inbound_address (plugin, cs, (const void *) &ipv4addr, sizeof (struct IPv4HttpAddress));
    }
    /* Incoming IPv6 connection */
    if ( AF_INET6 == conn_info->client_addr->sin_family)
    {
      addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
      inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
      memcpy(&ipv6addr.ipv6_addr,&(addrin6->sin6_addr),sizeof(struct in6_addr));
      ipv6addr.u6_port = addrin6->sin6_port;
      con = session_check_inbound_address (plugin, cs, &ipv6addr, sizeof (struct IPv6HttpAddress));
    }
    /* Set closure and update current session*/

    *httpSessionCache = con;
    if (con->msgtok==NULL)
      con->msgtok = GNUNET_SERVER_mst_create (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1, &messageTokenizerCallback, con);

    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has new an incoming `%s' request from peer `%s' (`%s')\n",
                method,
                GNUNET_i2s(&cs->identity),
                http_plugin_address_to_string(NULL, con->addr, con->addrlen));
  }

  /* Is it a PUT or a GET request */
  if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
  {


    if ((*upload_data_size == 0) && (con->is_put_in_progress==GNUNET_NO))
    {
      con->is_put_in_progress = GNUNET_YES;
      return MHD_YES;
    }

    /* Transmission of all data complete */
    if ((*upload_data_size == 0) && (con->is_put_in_progress == GNUNET_YES))
    {
        response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
        res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Sent HTTP/1.1: 200 OK as PUT Response\n",HTTP_PUT_RESPONSE, strlen (HTTP_PUT_RESPONSE), res );
        MHD_destroy_response (response);
        return MHD_YES;

      con->is_put_in_progress = GNUNET_NO;
      con->is_bad_request = GNUNET_NO;
      return res;
    }

    /* Recieving data */
    if ((*upload_data_size > 0) && (con->is_put_in_progress == GNUNET_YES))
    {
      res = GNUNET_SERVER_mst_receive(con->msgtok, con, upload_data,*upload_data_size, GNUNET_NO, GNUNET_NO);
      (*upload_data_size) = 0;
      return MHD_YES;
    }
    else
      return MHD_NO;
  }
  if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request\n");
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"URL: `%s'\n",url);

    /* check url for peer identity , if invalid send HTTP 404*/
    res = GNUNET_CRYPTO_hash_from_string ( &url[1], &(pi_in.hashPubKey));

    if ( GNUNET_SYSERR == res )
    {
      response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
      res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
      MHD_destroy_response (response);
      if (res == MHD_YES)
        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, sent HTTP 1.1/404\n");
      else
        GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, could not send error\n");
      return res;
    }

    response = MHD_create_response_from_callback(-1,32 * 1024, &server_read_callback, cs, NULL);
    res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
    MHD_destroy_response (response);

    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has new an incoming `%s' request from peer `%s' (`%s')\n",
                method,
                GNUNET_i2s(&cs->identity),
                http_plugin_address_to_string(NULL, con->addr, con->addrlen));

    return res;

  }
  return MHD_NO;
}


/**
 * Call MHD to process pending ipv4 requests and then go back
 * and schedule the next run.
 */
static void http_server_daemon_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
/**
 * Call MHD to process pending ipv6 requests and then go back
 * and schedule the next run.
 */
static void http_server_daemon_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);

/**
 * Function that queries MHD's select sets and
 * starts the task waiting for them.
 */
static GNUNET_SCHEDULER_TaskIdentifier
http_server_daemon_prepare (void * cls, struct MHD_Daemon *daemon_handle)
{
  struct Plugin *plugin = cls;
  GNUNET_SCHEDULER_TaskIdentifier ret;
  fd_set rs;
  fd_set ws;
  fd_set es;
  struct GNUNET_NETWORK_FDSet *wrs;
  struct GNUNET_NETWORK_FDSet *wws;
  struct GNUNET_NETWORK_FDSet *wes;
  int max;
  unsigned long long timeout;
  int haveto;
  struct GNUNET_TIME_Relative tv;

  GNUNET_assert(cls !=NULL);
  ret = GNUNET_SCHEDULER_NO_TASK;
  FD_ZERO(&rs);
  FD_ZERO(&ws);
  FD_ZERO(&es);
  wrs = GNUNET_NETWORK_fdset_create ();
  wes = GNUNET_NETWORK_fdset_create ();
  wws = GNUNET_NETWORK_fdset_create ();
  max = -1;
  GNUNET_assert (MHD_YES ==
                 MHD_get_fdset (daemon_handle,
                                &rs,
                                &ws,
                                &es,
                                &max));
  haveto = MHD_get_timeout (daemon_handle, &timeout);
  if (haveto == MHD_YES)
    tv.value = (uint64_t) timeout;
  else
    tv = GNUNET_TIME_UNIT_FOREVER_REL;
  GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
  GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
  GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
  if (daemon_handle == plugin->http_server_daemon_v4)
  {
    ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
                                       GNUNET_SCHEDULER_PRIORITY_DEFAULT,
                                       GNUNET_SCHEDULER_NO_TASK,
                                       tv,
                                       wrs,
                                       wws,
                                       &http_server_daemon_v4_run,
                                       plugin);
  }
  if (daemon_handle == plugin->http_server_daemon_v6)
  {
    ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
                                       GNUNET_SCHEDULER_PRIORITY_DEFAULT,
                                       GNUNET_SCHEDULER_NO_TASK,
                                       tv,
                                       wrs,
                                       wws,
                                       &http_server_daemon_v6_run,
                                       plugin);
  }
  GNUNET_NETWORK_fdset_destroy (wrs);
  GNUNET_NETWORK_fdset_destroy (wws);
  GNUNET_NETWORK_fdset_destroy (wes);
  return ret;
}

/**
 * Call MHD to process pending requests and then go back
 * and schedule the next run.
 */
static void http_server_daemon_v4_run (void *cls,
                             const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct Plugin *plugin = cls;

  GNUNET_assert(cls !=NULL);
  if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
    plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;

  if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
    return;

  GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v4));
  plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
  return;
}


/**
 * Call MHD to process pending requests and then go back
 * and schedule the next run.
 */
static void http_server_daemon_v6_run (void *cls,
                             const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct Plugin *plugin = cls;

  GNUNET_assert(cls !=NULL);
  if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
    plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;

  if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
    return;

  GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v6));
  plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
  return;
}

/**
 * Removes a message from the linked list of messages
 * @param con connection to remove message from
 * @param msg message to remove
 * @return GNUNET_SYSERR if msg not found, GNUNET_OK on success
 */

static int remove_http_message(struct HTTP_Connection_out * con, struct HTTP_Message * msg)
{
  GNUNET_CONTAINER_DLL_remove(con->pending_msgs_head,con->pending_msgs_tail,msg);
  GNUNET_free(msg);
  return GNUNET_OK;
}


static size_t header_function( void *ptr, size_t size, size_t nmemb, void *stream)
{
  char * tmp;
  size_t len = size * nmemb;

  tmp = NULL;
  if ((size * nmemb) < SIZE_MAX)
    tmp = GNUNET_malloc (len+1);

  if ((tmp != NULL) && (len > 0))
  {
    memcpy(tmp,ptr,len);
    if (len>=2)
    {
      if (tmp[len-2] == 13)
        tmp[len-2]= '\0';
    }
#if DEBUG_HTTP
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Header: `%s'\n",tmp);
#endif
  }
  if (NULL != tmp)
    GNUNET_free (tmp);

  return size * nmemb;
}

/**
 * Callback method used with libcurl
 * Method is called when libcurl needs to read data during sending
 * @param stream pointer where to write data
 * @param size size of an individual element
 * @param nmemb count of elements that can be written to the buffer
 * @param ptr source pointer, passed to the libcurl handle
 * @return bytes written to stream
 */
static size_t send_read_callback(void *stream, size_t size, size_t nmemb, void *ptr)
{
  struct HTTP_Connection_out * con = ptr;
  struct HTTP_Message * msg = con->pending_msgs_tail;
  size_t bytes_sent;
  size_t len;

  if (con->pending_msgs_tail == NULL)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: No Message to send, pausing connection\n",con);
    con->put_send_paused = GNUNET_YES;
    return CURL_READFUNC_PAUSE;
  }

  msg = con->pending_msgs_tail;
  /* data to send */
  if (msg->pos < msg->size)
  {
    /* data fit in buffer */
    if ((msg->size - msg->pos) <= (size * nmemb))
    {
      len = (msg->size - msg->pos);
      memcpy(stream, &msg->buf[msg->pos], len);
      msg->pos += len;
      bytes_sent = len;
    }
    else
    {
      len = size*nmemb;
      memcpy(stream, &msg->buf[msg->pos], len);
      msg->pos += len;
      bytes_sent = len;
    }
  }
  /* no data to send */
  else
  {
    bytes_sent = 0;
  }

  if ( msg->pos == msg->size)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Message with %u bytes sent, removing message from queue \n",con, msg->pos);
    /* Calling transmit continuation  */
    if (( NULL != con->pending_msgs_tail) && (NULL != con->pending_msgs_tail->transmit_cont))
      msg->transmit_cont (con->pending_msgs_tail->transmit_cont_cls,&(con->session)->identity,GNUNET_OK);
    remove_http_message(con, msg);
  }
  return bytes_sent;
}

/**
* Callback method used with libcurl
* Method is called when libcurl needs to write data during sending
* @param stream pointer where to write data
* @param size size of an individual element
* @param nmemb count of elements that can be written to the buffer
* @param ptr destination pointer, passed to the libcurl handle
* @return bytes read from stream
*/
static size_t send_write_callback( void *stream, size_t size, size_t nmemb, void *ptr)
{
  char * data = NULL;

  if ((size * nmemb) < SIZE_MAX)
    data = GNUNET_malloc(size*nmemb +1);
  if (data != NULL)
  {
    memcpy( data, stream, size*nmemb);
    data[size*nmemb] = '\0';
    free (data);
  }
  return (size * nmemb);

}

/**
 * Function setting up file descriptors and scheduling task to run
 * @param cls closure
 * @param ses session to send data to
 * @return bytes sent to peer
 */
static size_t send_schedule(void *cls, struct Session* ses );



/**
 * Function setting up curl handle and selecting message to send
 * @param cls plugin
 * @param ses session to send data to
 * @param con connection
 * @return bytes sent to peer
 */
static ssize_t send_initiate (void *cls, struct Session* ses , struct HTTP_Connection_out *con)
{
  struct Plugin *plugin = cls;
  int bytes_sent = 0;
  CURLMcode mret;
  struct HTTP_Message * msg;
  struct GNUNET_TIME_Relative timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;

  GNUNET_assert(cls !=NULL);

#if 0
  if (con->get_connected == GNUNET_NO)
  {
    if (con->get_curl_handle == NULL)
      con->get_curl_handle = curl_easy_init();

#if DEBUG_CURL
    curl_easy_setopt(con->get_curl_handle, CURLOPT_VERBOSE, 1L);
#endif
    curl_easy_setopt(con->get_curl_handle, CURLOPT_URL, con->url);
    //curl_easy_setopt(con->put_curl_handle, CURLOPT_PUT, 1L);
    curl_easy_setopt(con->get_curl_handle, CURLOPT_HEADERFUNCTION, &header_function);
    curl_easy_setopt(con->get_curl_handle, CURLOPT_WRITEHEADER, con);
    curl_easy_setopt(con->get_curl_handle, CURLOPT_READFUNCTION, send_read_callback);
    curl_easy_setopt(con->get_curl_handle, CURLOPT_READDATA, con);
    curl_easy_setopt(con->get_curl_handle, CURLOPT_WRITEFUNCTION, send_write_callback);
    curl_easy_setopt(con->get_curl_handle, CURLOPT_READDATA, con);
    curl_easy_setopt(con->get_curl_handle, CURLOPT_TIMEOUT, (long) timeout.value);
    curl_easy_setopt(con->get_curl_handle, CURLOPT_PRIVATE, con);
    curl_easy_setopt(con->get_curl_handle, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT_DBG);
    curl_easy_setopt(con->get_curl_handle, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);

    mret = curl_multi_add_handle(plugin->multi_handle, con->get_curl_handle);
    if (mret != CURLM_OK)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _("%s failed at %s:%d: `%s'\n"),
                  "curl_multi_add_handle", __FILE__, __LINE__,
                  curl_multi_strerror (mret));
      return -1;
    }

    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound not connected, initiating connection\n",con);
  }
#endif

  /* PUT already connected, no need to initiate connection */
  if ((con->put_connected == GNUNET_YES) && (con->put_curl_handle != NULL))
  {
    if (con->put_send_paused == GNUNET_NO)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound active, enqueueing message\n",con);
      return bytes_sent;
    }
    if (con->put_send_paused == GNUNET_YES)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound paused, unpausing existing connection and enqueueing message\n",con);
      curl_easy_pause(con->put_curl_handle,CURLPAUSE_CONT);
      con->put_send_paused=GNUNET_NO;
      return bytes_sent;
    }
  }


  /* not connected, initiate connection */
  if ( NULL == con->put_curl_handle)
    con->put_curl_handle = curl_easy_init();
  GNUNET_assert (con->put_curl_handle != NULL);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound not connected, initiating connection\n",con);

  GNUNET_assert (NULL != con->pending_msgs_tail);
  msg = con->pending_msgs_tail;

#if DEBUG_CURL
  curl_easy_setopt(con->put_curl_handle, CURLOPT_VERBOSE, 1L);
#endif
  curl_easy_setopt(con->put_curl_handle, CURLOPT_URL, con->url);
  curl_easy_setopt(con->put_curl_handle, CURLOPT_PUT, 1L);
  curl_easy_setopt(con->put_curl_handle, CURLOPT_HEADERFUNCTION, &header_function);
  curl_easy_setopt(con->put_curl_handle, CURLOPT_WRITEHEADER, con);
  curl_easy_setopt(con->put_curl_handle, CURLOPT_READFUNCTION, send_read_callback);
  curl_easy_setopt(con->put_curl_handle, CURLOPT_READDATA, con);
  curl_easy_setopt(con->put_curl_handle, CURLOPT_WRITEFUNCTION, send_write_callback);
  curl_easy_setopt(con->put_curl_handle, CURLOPT_READDATA, con);
  curl_easy_setopt(con->put_curl_handle, CURLOPT_TIMEOUT, (long) timeout.value);
  curl_easy_setopt(con->put_curl_handle, CURLOPT_PRIVATE, con);
  curl_easy_setopt(con->put_curl_handle, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT_DBG);
  curl_easy_setopt(con->put_curl_handle, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);

  mret = curl_multi_add_handle(plugin->multi_handle, con->put_curl_handle);
  if (mret != CURLM_OK)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                _("%s failed at %s:%d: `%s'\n"),
                "curl_multi_add_handle", __FILE__, __LINE__,
                curl_multi_strerror (mret));
    return -1;
  }
  con->put_connected = GNUNET_YES;
  bytes_sent = send_schedule (plugin, ses);
  return bytes_sent;
}

static void send_execute (void *cls,
             const struct GNUNET_SCHEDULER_TaskContext *tc)
{
  struct Plugin *plugin = cls;
  static unsigned int handles_last_run;
  int running;
  struct CURLMsg *msg;
  CURLMcode mret;
  struct HTTP_Connection_out * con = NULL;
  struct Session * cs = NULL;
  long http_result;

  GNUNET_assert(cls !=NULL);
  plugin->http_server_task_send = GNUNET_SCHEDULER_NO_TASK;
  if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
    return;

  do
    {
      running = 0;
      mret = curl_multi_perform (plugin->multi_handle, &running);
      if (running < handles_last_run)
        {
          do
            {

              msg = curl_multi_info_read (plugin->multi_handle, &running);
              if (msg == NULL)
                break;
              /* get session for affected curl handle */
              GNUNET_assert ( msg->easy_handle != NULL );
              curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char *) &con);
              GNUNET_assert ( con != NULL );
              cs = con->session;
              GNUNET_assert ( cs != NULL );
              switch (msg->msg)
                {

                case CURLMSG_DONE:
                  if ( (msg->data.result != CURLE_OK) &&
                       (msg->data.result != CURLE_GOT_NOTHING) )
                  {


                    GNUNET_log(GNUNET_ERROR_TYPE_INFO,
                               _("Connection %X to peer `%s' (`%s') failed: `%s' `%s'\n"),
                               con,
                               GNUNET_i2s(&cs->identity),
                               http_plugin_address_to_string(NULL, con->addr, con->addrlen),
                               "curl_multi_perform",
                               curl_easy_strerror (msg->data.result));
                    /* sending msg failed*/
                    con->put_connected = GNUNET_NO;
                    curl_easy_cleanup(con->put_curl_handle);
                    con->put_curl_handle=NULL;
                    if (( NULL != con->pending_msgs_tail) && ( NULL != con->pending_msgs_tail->transmit_cont))
                      con->pending_msgs_tail->transmit_cont (con->pending_msgs_tail->transmit_cont_cls,&con->session->identity,GNUNET_SYSERR);

                  }
                  else
                  {
                    GNUNET_assert (CURLE_OK == curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_result));
                    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                                "Send to peer `%s' completed with code %u\n", GNUNET_i2s(&cs->identity), http_result );

                    curl_easy_cleanup(con->put_curl_handle);
                    con->put_connected = GNUNET_NO;
                    con->put_curl_handle=NULL;

                    /* Calling transmit continuation  */
                    if (( NULL != con->pending_msgs_tail) && (NULL != con->pending_msgs_tail->transmit_cont))
                    {
                      /* HTTP 1xx : Last message before here was informational */
                      if ((http_result >=100) && (http_result < 200))
                        con->pending_msgs_tail->transmit_cont (con->pending_msgs_tail->transmit_cont_cls,&cs->identity,GNUNET_OK);
                      /* HTTP 2xx: successful operations */
                      if ((http_result >=200) && (http_result < 300))
                        con->pending_msgs_tail->transmit_cont (con->pending_msgs_tail->transmit_cont_cls,&cs->identity,GNUNET_OK);
                      /* HTTP 3xx..5xx: error */
                      if ((http_result >=300) && (http_result < 600))
                        con->pending_msgs_tail->transmit_cont (con->pending_msgs_tail->transmit_cont_cls,&cs->identity,GNUNET_SYSERR);
                    }
                  }
                  if (con->pending_msgs_tail != NULL)
                  {
                    if (con->pending_msgs_tail->pos>0)
                      remove_http_message(con, con->pending_msgs_tail);
                    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message could not be removed from session `%s'\n", GNUNET_i2s(&cs->identity));
                  }
                  return;
                default:
                  break;
                }

            }
          while ( (running > 0) );
        }
      handles_last_run = running;
    }
  while (mret == CURLM_CALL_MULTI_PERFORM);
  send_schedule(plugin, cls);
}


/**
 * Function setting up file descriptors and scheduling task to run
 * @param ses session to send data to
 * @return bytes sent to peer
 */
static size_t send_schedule(void *cls, struct Session* ses )
{
  struct Plugin *plugin = cls;
  fd_set rs;
  fd_set ws;
  fd_set es;
  int max;
  struct GNUNET_NETWORK_FDSet *grs;
  struct GNUNET_NETWORK_FDSet *gws;
  long to;
  CURLMcode mret;

  GNUNET_assert(cls !=NULL);
  max = -1;
  FD_ZERO (&rs);
  FD_ZERO (&ws);
  FD_ZERO (&es);
  mret = curl_multi_fdset (plugin->multi_handle, &rs, &ws, &es, &max);
  if (mret != CURLM_OK)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _("%s failed at %s:%d: `%s'\n"),
                  "curl_multi_fdset", __FILE__, __LINE__,
                  curl_multi_strerror (mret));
      return -1;
    }
  mret = curl_multi_timeout (plugin->multi_handle, &to);
  if (mret != CURLM_OK)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                  _("%s failed at %s:%d: `%s'\n"),
                  "curl_multi_timeout", __FILE__, __LINE__,
                  curl_multi_strerror (mret));
      return -1;
    }

  grs = GNUNET_NETWORK_fdset_create ();
  gws = GNUNET_NETWORK_fdset_create ();
  GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
  GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
  plugin->http_server_task_send = GNUNET_SCHEDULER_add_select (plugin->env->sched,
                                   GNUNET_SCHEDULER_PRIORITY_DEFAULT,
                                   GNUNET_SCHEDULER_NO_TASK,
                                   GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 0),
                                   grs,
                                   gws,
                                   &send_execute,
                                   plugin);
  GNUNET_NETWORK_fdset_destroy (gws);
  GNUNET_NETWORK_fdset_destroy (grs);

  /* FIXME: return bytes REALLY sent */
  return 0;
}


/**
 * 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 target who should receive this message
 * @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 timeout 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 session which session must be used (or NULL for "any")
 * @param addr the address to use (can be NULL if the plugin
 *                is "on its own" (i.e. re-use existing TCP connection))
 * @param addrlen length of the address in bytes
 * @param force_address GNUNET_YES if the plugin MUST use the given address,
 *                GNUNET_NO means the plugin may use any other address and
 *                GNUNET_SYSERR means that only reliable existing
 *                bi-directional connections should be used (regardless
 *                of address)
 * @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
http_plugin_send (void *cls,
                  const struct GNUNET_PeerIdentity *target,
                  const char *msgbuf,
                  size_t msgbuf_size,
                  unsigned int priority,
                  struct GNUNET_TIME_Relative to,
                  struct Session *session,
                  const void *addr,
                  size_t addrlen,
                  int force_address,
                  GNUNET_TRANSPORT_TransmitContinuation cont,
                  void *cont_cls)
{
  struct Plugin *plugin = cls;
  struct Session *cs;
  struct HTTP_Message *msg;
  struct HTTP_Connection_out *con;
  //unsigned int ret;

  GNUNET_assert(cls !=NULL);
  GNUNET_assert ((addr!=NULL) && (addrlen != 0));

  /* get session from hashmap */
  cs = session_get(plugin, target);
  con = session_check_outbound_address(plugin, cs, addr, addrlen);

  char * force = GNUNET_malloc(30);

  if (force_address == GNUNET_YES)
    strcpy(force,"forced addr.");
  if (force_address == GNUNET_NO)
    strcpy(force,"any addr.");
  if (force_address == GNUNET_SYSERR)
    strcpy(force,"reliable bi-direc. address addr.");
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Transport tells me to send %u bytes to `%s' %s (%s), session: %X\n",
                                      msgbuf_size,
                                      GNUNET_i2s(&cs->identity),
                                      force,
                                      http_plugin_address_to_string(NULL, addr, addrlen),
                                      session);

  //GNUNET_free(force);
  /* create msg */
  msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size);
  msg->next = NULL;
  msg->size = msgbuf_size;
  msg->pos = 0;
  msg->buf = (char *) &msg[1];
  msg->transmit_cont = cont;
  msg->transmit_cont_cls = cont_cls;
  memcpy (msg->buf,msgbuf, msgbuf_size);

  /* must use this address */
  if (force_address == GNUNET_YES)
  {
    /* enqueue in connection message queue */
    GNUNET_CONTAINER_DLL_insert(con->pending_msgs_head,con->pending_msgs_tail,msg);
  }
  /* can use existing connection to send */
  else
  {
    /* enqueue in connection message queue */
    GNUNET_CONTAINER_DLL_insert(con->pending_msgs_head,con->pending_msgs_tail,msg);
  }
  return send_initiate (plugin, cs, con);
}



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

  /* get session from hashmap */
  cs = session_get(plugin, target);
  con = cs->outbound_connections_head;

  while (con!=NULL)
  {
    if (con->put_curl_handle!=NULL)
      curl_easy_cleanup(con->put_curl_handle);
    con->put_curl_handle=NULL;
    con->put_connected = GNUNET_NO;
    while (con->pending_msgs_head!=NULL)
    {
      remove_http_message(con, con->pending_msgs_head);
    }
    con=con->next;
  }
}


/**
 * 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
http_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)
{
  const struct IPv4HttpAddress *t4;
  const struct IPv6HttpAddress *t6;
  struct sockaddr_in a4;
  struct sockaddr_in6 a6;
  char * address;
  char * ret;
  unsigned int port;
  unsigned int res;

  GNUNET_assert(cls !=NULL);
  if (addrlen == sizeof (struct IPv6HttpAddress))
  {
    address = GNUNET_malloc (INET6_ADDRSTRLEN);
    t6 = addr;
    a6.sin6_addr = t6->ipv6_addr;
    inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
    port = ntohs(t6->u6_port);
  }
  else if (addrlen == sizeof (struct IPv4HttpAddress))
  {
    address = GNUNET_malloc (INET_ADDRSTRLEN);
    t4 = addr;
    a4.sin_addr.s_addr =  t4->ipv4_addr;
    inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
    port = ntohs(t4->u_port);
  }
  else
  {
    /* invalid address */
    GNUNET_break_op (0);
    asc (asc_cls, NULL);
    return;
  }
  res = GNUNET_asprintf(&ret,"http://%s:%u/",address,port);
  GNUNET_free (address);
  GNUNET_assert(res != 0);

  asc (asc_cls, ret);
}



/**
 * 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
http_plugin_address_suggested (void *cls,
                               const void *addr, size_t addrlen)
{
  struct Plugin *plugin = cls;
  struct IPv4HttpAddress *v4;
  struct IPv6HttpAddress *v6;
  unsigned int port;

  GNUNET_assert(cls !=NULL);
  if ((addrlen != sizeof (struct IPv4HttpAddress)) &&
      (addrlen != sizeof (struct IPv6HttpAddress)))
    {
      return GNUNET_SYSERR;
    }
  if (addrlen == sizeof (struct IPv4HttpAddress))
    {
      v4 = (struct IPv4HttpAddress *) addr;
      if (INADDR_LOOPBACK == ntohl(v4->ipv4_addr))
      {
        return GNUNET_SYSERR;
      }
      port = ntohs (v4->u_port);
      if (port != plugin->port_inbound)
      {
        return GNUNET_SYSERR;
      }
    }
  else
    {
      v6 = (struct IPv6HttpAddress *) addr;
      if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
        {
          return GNUNET_SYSERR;
        }
      port = ntohs (v6->u6_port);
      if (port != plugin->port_inbound)
      {
        return GNUNET_SYSERR;
      }
    }
  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*
http_plugin_address_to_string (void *cls,
                                   const void *addr,
                                   size_t addrlen)
{
  const struct IPv4HttpAddress *t4;
  const struct IPv6HttpAddress *t6;
  struct sockaddr_in a4;
  struct sockaddr_in6 a6;
  char * address;
  char * ret;
  uint16_t port;
  unsigned int res;

  if (addrlen == sizeof (struct IPv6HttpAddress))
    {
      address = GNUNET_malloc (INET6_ADDRSTRLEN);
      t6 = addr;
      a6.sin6_addr = t6->ipv6_addr;
      inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
      port = ntohs(t6->u6_port);
    }
  else if (addrlen == sizeof (struct IPv4HttpAddress))
    {
      address = GNUNET_malloc (INET_ADDRSTRLEN);
      t4 = addr;
      a4.sin_addr.s_addr =  t4->ipv4_addr;
      inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
      port = ntohs(t4->u_port);
    }
  else
    {
      /* invalid address */
      return NULL;
    }
  res = GNUNET_asprintf(&ret,"%s:%u",address,port);
  GNUNET_free (address);
  GNUNET_assert(res != 0);
  return ret;
}

/**
 * Add the IP of our network interface to the list of
 * our external IP addresses.
 *
 * @param cls the 'struct Plugin*'
 * @param name name of the interface
 * @param isDefault do we think this may be our default interface
 * @param addr address of the interface
 * @param addrlen number of bytes in addr
 * @return GNUNET_OK to continue iterating
 */
static int
process_interfaces (void *cls,
                    const char *name,
                    int isDefault,
                    const struct sockaddr *addr, socklen_t addrlen)
{
  struct Plugin *plugin = cls;
  struct IPv4HttpAddress * t4;
  struct IPv6HttpAddress * t6;
  int af;

  GNUNET_assert(cls !=NULL);
  af = addr->sa_family;
  if (af == AF_INET)
    {
      t4 = GNUNET_malloc(sizeof(struct IPv4HttpAddress));
      if (INADDR_LOOPBACK == ntohl(((struct sockaddr_in *) addr)->sin_addr.s_addr))
      {
        /* skip loopback addresses */
        return GNUNET_OK;
      }
      t4->ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
      t4->u_port = htons (plugin->port_inbound);
      plugin->env->notify_address(plugin->env->cls,"http",t4, sizeof (struct IPv4HttpAddress), GNUNET_TIME_UNIT_FOREVER_REL);

    }
  else if (af == AF_INET6)
    {
      t6 = GNUNET_malloc(sizeof(struct IPv6HttpAddress));
      if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
        {
          /* skip link local addresses */
          return GNUNET_OK;
        }
      if (IN6_IS_ADDR_LOOPBACK (&((struct sockaddr_in6 *) addr)->sin6_addr))
        {
          /* skip loopback addresses */
          return GNUNET_OK;
        }
      memcpy (&t6->ipv6_addr,
              &((struct sockaddr_in6 *) addr)->sin6_addr,
              sizeof (struct in6_addr));
      t6->u6_port = htons (plugin->port_inbound);
      plugin->env->notify_address(plugin->env->cls,"http",t6,sizeof (struct IPv6HttpAddress) , GNUNET_TIME_UNIT_FOREVER_REL);
    }
  return GNUNET_OK;
}
int hashMapFreeIterator (void *cls, const GNUNET_HashCode *key, void *value)
{
  struct Session * cs = value;
  struct HTTP_Connection_out * con = cs->outbound_connections_head;
  struct HTTP_Connection_out * tmp_con = cs->outbound_connections_head;
  struct HTTP_Message * msg = NULL;
  struct HTTP_Message * tmp_msg = NULL;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing session for peer `%s'\n",GNUNET_i2s(&cs->identity));

  /* freeing connections */
  while (con!=NULL)
  {
    GNUNET_free(con->url);
    if (con->put_curl_handle!=NULL)
      curl_easy_cleanup(con->put_curl_handle);
    con->put_curl_handle = NULL;
    msg = con->pending_msgs_head;
    while (msg!=NULL)
    {
      tmp_msg=msg->next;
      GNUNET_free(msg);
      msg = tmp_msg;
    }
    tmp_con=con->next;
    GNUNET_free(con);
    con=tmp_con;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"All sessions freed \n");

  GNUNET_free (cs);
  return GNUNET_YES;
}

/**
 * Exit point from the plugin.
 */
void *
libgnunet_plugin_transport_http_done (void *cls)
{
  struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
  struct Plugin *plugin = api->cls;
  CURLMcode mret;

  GNUNET_assert(cls !=NULL);


  if ( plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
  {
    GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
    plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
  }

  if ( plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
  {
    GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
    plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
  }

  if ( plugin->http_server_task_send != GNUNET_SCHEDULER_NO_TASK)
  {
    GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_send);
    plugin->http_server_task_send = GNUNET_SCHEDULER_NO_TASK;
  }

  if (plugin->http_server_daemon_v4 != NULL)
  {
    MHD_stop_daemon (plugin->http_server_daemon_v4);
    plugin->http_server_daemon_v4 = NULL;
  }
  if (plugin->http_server_daemon_v6 != NULL)
  {
    MHD_stop_daemon (plugin->http_server_daemon_v6);
    plugin->http_server_daemon_v6 = NULL;
  }

  /* free all sessions */
  GNUNET_CONTAINER_multihashmap_iterate (plugin->sessions,
                                         &hashMapFreeIterator,
                                         NULL);

  GNUNET_CONTAINER_multihashmap_destroy (plugin->sessions);

  mret = curl_multi_cleanup(plugin->multi_handle);
  if ( CURLM_OK != mret)
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed");

  GNUNET_free (plugin);
  GNUNET_free (api);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unload http plugin complete...\n");
  return NULL;
}


/**
 * Entry point for the plugin.
 */
void *
libgnunet_plugin_transport_http_init (void *cls)
{
  struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
  struct Plugin *plugin;
  struct GNUNET_TRANSPORT_PluginFunctions *api;
  struct GNUNET_TIME_Relative gn_timeout;
  long long unsigned int port;

  GNUNET_assert(cls !=NULL);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");

  plugin = GNUNET_malloc (sizeof (struct Plugin));
  plugin->env = env;
  plugin->sessions = NULL;

  api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
  api->cls = plugin;
  api->send = &http_plugin_send;
  api->disconnect = &http_plugin_disconnect;
  api->address_pretty_printer = &http_plugin_address_pretty_printer;
  api->check_address = &http_plugin_address_suggested;
  api->address_to_string = &http_plugin_address_to_string;

  /* Hashing our identity to use it in URLs */
  GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &plugin->my_ascii_hash_ident);

  /* Reading port number from config file */
  if ((GNUNET_OK !=
       GNUNET_CONFIGURATION_get_value_number (env->cfg,
                                              "transport-http",
                                              "PORT",
                                              &port)) ||
      (port > 65535) )
    {
      GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
                       "http",
                       _
                       ("Require valid port number for transport plugin `%s' in configuration!\n"),
                       "transport-http");
      libgnunet_plugin_transport_http_done (api);
      return NULL;
    }
  GNUNET_assert ((port > 0) && (port <= 65535));
  plugin->port_inbound = port;
  gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
  if ((plugin->http_server_daemon_v4 == NULL) && (plugin->http_server_daemon_v6 == NULL) && (port != 0))
    {
    plugin->http_server_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
                                       port,
                                       &acceptPolicyCallback,
                                       plugin , &accessHandlerCallback, plugin,
                                       MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
                                       MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
                                       MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
                                       MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
                                       MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
                                       MHD_OPTION_END);
    plugin->http_server_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
                                       port,
                                       &acceptPolicyCallback,
                                       plugin , &accessHandlerCallback, plugin,
                                       MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
                                       MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
                                       MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
                                       MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
                                       MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
                                       MHD_OPTION_END);
    }
  if (plugin->http_server_daemon_v4 != NULL)
    plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
  if (plugin->http_server_daemon_v6 != NULL)
    plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);

  if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
  else if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
  else
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No MHD was started, transport plugin not functional!\n");
    libgnunet_plugin_transport_http_done (api);
    return NULL;
  }

  /* Initializing cURL */
  curl_global_init(CURL_GLOBAL_ALL);
  plugin->multi_handle = curl_multi_init();

  if ( NULL == plugin->multi_handle )
  {
    GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
                     "http",
                     _("Could not initialize curl multi handle, failed to start http plugin!\n"),
                     "transport-http");
    libgnunet_plugin_transport_http_done (api);
    return NULL;
  }

  plugin->sessions = GNUNET_CONTAINER_multihashmap_create (10);
  GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);

  return api;
}

/* end of plugin_transport_http.c */