initial checkin of https transport
[oweals/gnunet.git] / src / transport / plugin_transport_https.c
1 /*
2      This file is part of GNUnet
3      (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file transport/plugin_transport_https.c
23  * @brief https transport service plugin
24  * @author Matthias Wachs
25  */
26
27 #include "platform.h"
28 #include "gnunet_common.h"
29 #include "gnunet_constants.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_connection_lib.h"
32 #include "gnunet_service_lib.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_transport_service.h"
35 #include "gnunet_resolver_service.h"
36 #include "gnunet_server_lib.h"
37 #include "gnunet_container_lib.h"
38 #include "plugin_transport.h"
39 #include "gnunet_os_lib.h"
40 #include "gnunet_disk_lib.h"
41 #include "microhttpd.h"
42 #include <curl/curl.h>
43
44 #define DEBUG_HTTPS GNUNET_NO
45 #define DEBUG_CURL GNUNET_NO
46 #define DEBUG_CONNECTIONS GNUNET_NO
47 #define DEBUG_SESSION_SELECTION GNUNET_NO
48
49 #define INBOUND GNUNET_NO
50 #define OUTBOUND GNUNET_YES
51
52 /**
53  * Text of the response sent back after the last bytes of a PUT
54  * request have been received (just to formally obey the HTTP
55  * protocol).
56  */
57 #define HTTP_PUT_RESPONSE "Thank you!"
58
59 /**
60  * After how long do we expire an address that we
61  * learned from another peer if it is not reconfirmed
62  * by anyone?
63  */
64 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
65
66 /**
67  * Page returned if request invalid
68  */
69 #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>"
70
71 /**
72  * Timeout for a http connect
73  */
74 #define HTTP_CONNECT_TIMEOUT 30
75
76 /**
77  * Network format for IPv4 addresses.
78  */
79 struct IPv4HttpAddress
80 {
81   /**
82    * IPv4 address, in network byte order.
83    */
84   uint32_t ipv4_addr GNUNET_PACKED;
85
86   /**
87    * Port number, in network byte order.
88    */
89   uint16_t u_port GNUNET_PACKED;
90
91 };
92
93
94 /**
95  * Network format for IPv6 addresses.
96  */
97 struct IPv6HttpAddress
98 {
99   /**
100    * IPv6 address.
101    */
102   struct in6_addr ipv6_addr GNUNET_PACKED;
103
104   /**
105    * Port number, in network byte order.
106    */
107   uint16_t u6_port GNUNET_PACKED;
108
109 };
110
111
112 /**
113  *  Message to send using http
114  */
115 struct HTTP_Message
116 {
117   /**
118    * next pointer for double linked list
119    */
120   struct HTTP_Message * next;
121
122   /**
123    * previous pointer for double linked list
124    */
125   struct HTTP_Message * prev;
126
127   /**
128    * buffer containing data to send
129    */
130   char *buf;
131
132   /**
133    * amount of data already sent
134    */
135   size_t pos;
136
137   /**
138    * buffer length
139    */
140   size_t size;
141
142   /**
143    * Continuation function to call once the transmission buffer
144    * has again space available.  NULL if there is no
145    * continuation to call.
146    */
147   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
148
149   /**
150    * Closure for transmit_cont.
151    */
152   void *transmit_cont_cls;
153 };
154
155
156 struct HTTP_PeerContext
157 {
158   /**
159    * peer's identity
160    */
161   struct GNUNET_PeerIdentity identity;
162
163   /**
164    * Pointer to the global plugin struct.
165    */
166   struct Plugin *plugin;
167
168   /**
169    * Linked list of connections with this peer
170    * head
171    */
172   struct Session * head;
173
174   /**
175    * Linked list of connections with this peer
176    * tail
177    */
178   struct Session * tail;
179
180   /**
181    * id for next session
182    */
183   size_t session_id_counter;
184
185   /**
186    * Last session used to send data
187    */
188   struct Session * last_session;
189 };
190
191
192 struct Session
193 {
194   /**
195    * API requirement.
196    */
197   struct SessionHeader header;
198
199   /**
200    * next session in linked list
201    */
202   struct Session * next;
203
204   /**
205    * previous session in linked list
206    */
207   struct Session * prev;
208
209   /**
210    * address of this session
211    */
212   void * addr;
213
214   /**
215    * address length
216    */
217   size_t addrlen;
218
219   /**
220    * target url
221    */
222   char * url;
223
224   /**
225    * Message queue for outbound messages
226    * head of queue
227    */
228   struct HTTP_Message * pending_msgs_head;
229
230   /**
231    * Message queue for outbound messages
232    * tail of queue
233    */
234   struct HTTP_Message * pending_msgs_tail;
235
236   /**
237    * partner peer this connection belongs to
238    */
239   struct HTTP_PeerContext * peercontext;
240
241   /**
242    * message stream tokenizer for incoming data
243    */
244   struct GNUNET_SERVER_MessageStreamTokenizer *msgtok;
245
246   /**
247    * session direction
248    * outbound: OUTBOUND (GNUNET_YES)
249    * inbound : INBOUND (GNUNET_NO)
250    */
251   unsigned int direction;
252
253   /**
254    * is session connected to send data?
255    */
256   unsigned int send_connected;
257
258   /**
259    * is send connection active?
260    */
261   unsigned int send_active;
262
263   /**
264    * connection disconnect forced (e.g. from transport)
265    */
266   unsigned int send_force_disconnect;
267
268   /**
269    * is session connected to receive data?
270    */
271   unsigned int recv_connected;
272
273   /**
274    * is receive connection active?
275    */
276   unsigned int recv_active;
277
278   /**
279    * connection disconnect forced (e.g. from transport)
280    */
281   unsigned int recv_force_disconnect;
282
283   /**
284    * id for next session
285    * NOTE: 0 is not an ID, zero is not defined. A correct ID is always > 0
286    */
287   size_t session_id;
288
289   /**
290    * entity managing sending data
291    * outbound session: CURL *
292    * inbound session: mhd_connection *
293    */
294   void * send_endpoint;
295
296   /**
297    * entity managing recieving data
298    * outbound session: CURL *
299    * inbound session: mhd_connection *
300    */
301   void * recv_endpoint;
302 };
303
304 /**
305  * Encapsulation of all of the state of the plugin.
306  */
307 struct Plugin
308 {
309   /**
310    * Our environment.
311    */
312   struct GNUNET_TRANSPORT_PluginEnvironment *env;
313
314   /**
315    * Handle for reporting statistics.
316    */
317   struct GNUNET_STATISTICS_Handle *stats;
318
319   unsigned int port_inbound;
320
321   struct GNUNET_CONTAINER_MultiHashMap *peers;
322
323   /**
324    * Daemon for listening for new IPv4 connections.
325    */
326   struct MHD_Daemon *http_server_daemon_v4;
327
328   /**
329    * Daemon for listening for new IPv6connections.
330    */
331   struct MHD_Daemon *http_server_daemon_v6;
332
333   /**
334    * Our primary task for http daemon handling IPv4 connections
335    */
336   GNUNET_SCHEDULER_TaskIdentifier http_server_task_v4;
337
338   /**
339    * Our primary task for http daemon handling IPv6 connections
340    */
341   GNUNET_SCHEDULER_TaskIdentifier http_server_task_v6;
342
343   /**
344    * The task sending data
345    */
346   GNUNET_SCHEDULER_TaskIdentifier http_curl_task;
347
348   /**
349    * cURL Multihandle
350    */
351   CURLM * multi_handle;
352
353   /**
354    * Our ASCII encoded, hashed peer identity
355    * This string is used to distinguish between connections and is added to the urls
356    */
357   struct GNUNET_CRYPTO_HashAsciiEncoded my_ascii_hash_ident;
358
359   struct sockaddr_in * bind4_address;
360   struct sockaddr_in6 * bind6_address;
361   char * bind_hostname;
362   int use_ipv6;
363   int use_ipv4;
364
365   /* The certificate MHD uses as an \0 terminated string */
366   char * cert;
367
368   /* The private key MHD uses as an \0 terminated string */
369   char * key;
370 };
371
372
373 /**
374  * Function called for a quick conversion of the binary address to
375  * a numeric address.  Note that the caller must not free the
376  * address and that the next call to this function is allowed
377  * to override the address again.
378  *
379  * @param cls closure
380  * @param addr binary address
381  * @param addrlen length of the address
382  * @return string representing the same address
383  */
384 static const char*
385 http_plugin_address_to_string (void *cls,
386                                    const void *addr,
387                                    size_t addrlen);
388
389
390 /**
391  * Call MHD to process pending ipv4 requests and then go back
392  * and schedule the next run.
393  */
394 static void http_server_daemon_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
395 /**
396  * Call MHD to process pending ipv6 requests and then go back
397  * and schedule the next run.
398  */
399 static void http_server_daemon_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
400
401 /**
402  * Function setting up curl handle and selecting message to send
403  * @param cls plugin
404  * @param ses session to send data to
405  * @param con connection
406  * @return bytes sent to peer
407  */
408 static ssize_t send_check_connections (void *cls, struct Session *ps);
409
410 /**
411  * Function setting up file descriptors and scheduling task to run
412  * @param cls closure
413  * @param ses session to send data to
414  * @param
415  */
416 static int curl_schedule(void *cls );
417
418
419
420 static char * create_url(void * cls, const void * addr, size_t addrlen, size_t id)
421 {
422   struct Plugin *plugin = cls;
423   char *url = NULL;
424
425   GNUNET_assert ((addr!=NULL) && (addrlen != 0));
426   GNUNET_asprintf(&url,
427                   "https://%s/%s;%u",
428                   http_plugin_address_to_string(NULL, addr, addrlen),
429                   (char *) (&plugin->my_ascii_hash_ident),id);
430
431   return url;
432 }
433
434 /**
435  * Removes a message from the linked list of messages
436  * @param con connection to remove message from
437  * @param msg message to remove
438  * @return GNUNET_SYSERR if msg not found, GNUNET_OK on success
439  */
440 static int remove_http_message (struct Session * ps, struct HTTP_Message * msg)
441 {
442   GNUNET_CONTAINER_DLL_remove(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
443   GNUNET_free(msg);
444   return GNUNET_OK;
445 }
446
447 int remove_peer_context_Iterator (void *cls, const GNUNET_HashCode *key, void *value);
448
449 /**
450  * Removes a session from the linked list of sessions
451  * @param pc peer context
452  * @param ps session
453  * @param call_msg_cont GNUNET_YES to call pending message continuations, otherwise no
454  * @param call_msg_cont_result, result to call message continuations with
455  * @return GNUNET_SYSERR if msg not found, GNUNET_OK on success
456  */
457 static int remove_session (struct HTTP_PeerContext * pc, struct Session * ps,  int call_msg_cont, int call_msg_cont_result)
458 {
459   struct HTTP_Message * msg;
460   struct Plugin * plugin = ps->peercontext->plugin;
461
462 #if DEBUG_CONNECTIONS
463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: removing %s session %X with id %u\n", ps, (ps->direction == INBOUND) ? "inbound" : "outbound", ps, ps->session_id);
464 #endif
465   plugin->env->session_end(plugin, &pc->identity, ps);
466
467   GNUNET_free_non_null (ps->addr);
468   GNUNET_SERVER_mst_destroy (ps->msgtok);
469   GNUNET_free(ps->url);
470
471   if (ps->direction==INBOUND)
472   {
473           if (ps->recv_endpoint != NULL)
474           {
475                   curl_easy_cleanup(ps->recv_endpoint);
476                   ps->recv_endpoint = NULL;
477           }
478           if (ps->send_endpoint != NULL)
479           {
480                   curl_easy_cleanup(ps->send_endpoint);
481                   ps->send_endpoint = NULL;
482           }
483   }
484
485   msg = ps->pending_msgs_head;
486   while (msg!=NULL)
487   {
488     if ((call_msg_cont == GNUNET_YES) && (msg->transmit_cont!=NULL))
489     {
490       msg->transmit_cont (msg->transmit_cont_cls,&pc->identity,call_msg_cont_result);
491     }
492     GNUNET_free(msg);
493     GNUNET_CONTAINER_DLL_remove(ps->pending_msgs_head,ps->pending_msgs_head,msg);
494     msg = ps->pending_msgs_head;
495   }
496
497   GNUNET_CONTAINER_DLL_remove(pc->head,pc->tail,ps);
498   GNUNET_free(ps);
499   ps = NULL;
500
501   /* no sessions left remove peer */
502   if (pc->head==NULL)
503   {
504 #if DEBUG_HTTP
505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No sessions left for peer `%s', removing context\n",GNUNET_i2s(&pc->identity));
506 #endif
507         remove_peer_context_Iterator(plugin, &pc->identity.hashPubKey, pc);
508   }
509
510   return GNUNET_OK;
511 }
512
513 int remove_peer_context_Iterator (void *cls, const GNUNET_HashCode *key, void *value)
514 {
515   struct Plugin *plugin = cls;
516   struct HTTP_PeerContext * pc = value;
517   struct Session * ps = pc->head;
518   struct Session * tmp = NULL;
519   struct HTTP_Message * msg = NULL;
520   struct HTTP_Message * msg_tmp = NULL;
521 #if DEBUG_HTTP
522   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing context for peer `%s'\n",GNUNET_i2s(&pc->identity));
523 #endif
524   GNUNET_CONTAINER_multihashmap_remove (plugin->peers, &pc->identity.hashPubKey, pc);
525   while (ps!=NULL)
526   {
527         plugin->env->session_end(plugin, &pc->identity, ps);
528         tmp = ps->next;
529
530     GNUNET_free_non_null (ps->addr);
531     GNUNET_free(ps->url);
532     if (ps->msgtok != NULL)
533       GNUNET_SERVER_mst_destroy (ps->msgtok);
534
535     msg = ps->pending_msgs_head;
536     while (msg!=NULL)
537     {
538       msg_tmp = msg->next;
539       GNUNET_free(msg);
540       msg = msg_tmp;
541     }
542     if (ps->direction==OUTBOUND)
543     {
544       if (ps->send_endpoint!=NULL)
545         curl_easy_cleanup(ps->send_endpoint);
546       if (ps->recv_endpoint!=NULL)
547         curl_easy_cleanup(ps->recv_endpoint);
548     }
549
550     GNUNET_free(ps);
551     ps=tmp;
552   }
553   GNUNET_free(pc);
554   GNUNET_STATISTICS_update (plugin->env->stats,
555                             gettext_noop ("# HTTP peers active"),
556                             -1,
557                             GNUNET_NO);
558   return GNUNET_YES;
559 }
560
561 /**
562  * Add the IP of our network interface to the list of
563  * our external IP addresses.
564  *
565  * @param cls the 'struct Plugin*'
566  * @param name name of the interface
567  * @param isDefault do we think this may be our default interface
568  * @param addr address of the interface
569  * @param addrlen number of bytes in addr
570  * @return GNUNET_OK to continue iterating
571  */
572 static int
573 process_interfaces (void *cls,
574                     const char *name,
575                     int isDefault,
576                     const struct sockaddr *addr, socklen_t addrlen)
577 {
578   struct Plugin *plugin = cls;
579   struct IPv4HttpAddress * t4;
580   struct IPv6HttpAddress * t6;
581   int af;
582
583
584   GNUNET_assert(cls !=NULL);
585   af = addr->sa_family;
586   if ((af == AF_INET) && (plugin->use_ipv4 == GNUNET_YES) && (plugin->bind6_address == NULL))
587     {
588           struct in_addr bnd_cmp = ((struct sockaddr_in *) addr)->sin_addr;
589       t4 = GNUNET_malloc(sizeof(struct IPv4HttpAddress));
590       /* Not skipping loopback addresses
591       if (INADDR_LOOPBACK == ntohl(((struct sockaddr_in *) addr)->sin_addr.s_addr))
592       {
593
594         return GNUNET_OK;
595       }
596       */
597       t4->ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
598       t4->u_port = htons (plugin->port_inbound);
599       if (plugin->bind4_address != NULL)
600       {
601           if (0 == memcmp(&plugin->bind4_address->sin_addr, &bnd_cmp, sizeof (struct in_addr)))
602           {
603                   plugin->env->notify_address(plugin->env->cls,"https",t4, sizeof (struct IPv4HttpAddress), GNUNET_TIME_UNIT_FOREVER_REL);
604           }
605       }
606       else
607       {
608           plugin->env->notify_address(plugin->env->cls,"https",t4, sizeof (struct IPv4HttpAddress), GNUNET_TIME_UNIT_FOREVER_REL);
609       }
610       GNUNET_free (t4);
611     }
612   else if ((af == AF_INET6) && (plugin->use_ipv6 == GNUNET_YES)  && (plugin->bind4_address == NULL))
613     {
614           struct in6_addr bnd_cmp6 = ((struct sockaddr_in6 *) addr)->sin6_addr;
615       t6 = GNUNET_malloc(sizeof(struct IPv6HttpAddress));
616       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
617         {
618           return GNUNET_OK;
619         }
620
621       if (plugin->bind6_address != NULL)
622       {
623           if (0 == memcmp(&plugin->bind6_address->sin6_addr, &bnd_cmp6, sizeof (struct in6_addr)))
624           {
625               memcpy (&t6->ipv6_addr,
626                       &((struct sockaddr_in6 *) addr)->sin6_addr,
627                       sizeof (struct in6_addr));
628               t6->u6_port = htons (plugin->port_inbound);
629               plugin->env->notify_address(plugin->env->cls,"https",t6,sizeof (struct IPv6HttpAddress) , GNUNET_TIME_UNIT_FOREVER_REL);
630           }
631       }
632       else
633       {
634           memcpy (&t6->ipv6_addr,
635                   &((struct sockaddr_in6 *) addr)->sin6_addr,
636                   sizeof (struct in6_addr));
637           t6->u6_port = htons (plugin->port_inbound);
638           plugin->env->notify_address(plugin->env->cls,"https",t6,sizeof (struct IPv6HttpAddress) , GNUNET_TIME_UNIT_FOREVER_REL);
639       }
640       GNUNET_free (t6);
641     }
642   return GNUNET_OK;
643 }
644
645
646 /**
647  * Callback called by MHD when a connection is terminated
648  */
649 static void mhd_termination_cb (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
650 {
651   struct Session * ps = *httpSessionCache;
652   if (ps == NULL)
653     return;
654   struct HTTP_PeerContext * pc = ps->peercontext;
655
656   if (connection==ps->recv_endpoint)
657   {
658 #if DEBUG_CONNECTIONS
659     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound connection from peer `%s' was terminated\n", ps, GNUNET_i2s(&pc->identity));
660 #endif
661     ps->recv_active = GNUNET_NO;
662     ps->recv_connected = GNUNET_NO;
663     ps->recv_endpoint = NULL;
664   }
665   if (connection==ps->send_endpoint)
666   {
667
668     ps->send_active = GNUNET_NO;
669     ps->send_connected = GNUNET_NO;
670     ps->send_endpoint = NULL;
671 #if DEBUG_CONNECTIONS
672     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound connection from peer `%s' was terminated\n", ps, GNUNET_i2s(&pc->identity));
673 #endif
674   }
675
676   /* if both connections disconnected, remove session */
677   if ((ps->send_connected == GNUNET_NO) && (ps->recv_connected == GNUNET_NO))
678   {
679       GNUNET_STATISTICS_update (pc->plugin->env->stats,
680                             gettext_noop ("# HTTPS inbound sessions for peers active"),
681                             -1,
682                             GNUNET_NO);
683     remove_session(pc,ps,GNUNET_YES,GNUNET_SYSERR);
684   }
685 }
686
687 static void mhd_write_mst_cb (void *cls,
688                               void *client,
689                               const struct GNUNET_MessageHeader *message)
690 {
691
692   struct Session *ps  = cls;
693   struct HTTP_PeerContext *pc = ps->peercontext;
694   GNUNET_assert(ps != NULL);
695   GNUNET_assert(pc != NULL);
696 #if DEBUG_HTTP
697   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
698               "Connection %X: Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
699               ps,
700               ntohs(message->type),
701               ntohs(message->size),
702               GNUNET_i2s(&(ps->peercontext)->identity),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
703 #endif
704   pc->plugin->env->receive (ps->peercontext->plugin->env->cls,
705                             &pc->identity,
706                             message, 1, ps,
707                             NULL,
708                             0);
709 }
710
711 /**
712  * Check if ip is allowed to connect.
713  */
714 static int
715 mhd_accept_cb (void *cls,
716                       const struct sockaddr *addr, socklen_t addr_len)
717 {
718 #if 0
719   struct Plugin *plugin = cls;
720 #endif
721   /* Every connection is accepted, nothing more to do here */
722   return MHD_YES;
723 }
724
725 int mhd_send_callback (void *cls, uint64_t pos, char *buf, int max)
726 {
727   int bytes_read = 0;
728
729   struct Session * ps = cls;
730   struct HTTP_PeerContext * pc;
731   struct HTTP_Message * msg;
732
733   GNUNET_assert (ps!=NULL);
734   pc = ps->peercontext;
735   msg = ps->pending_msgs_tail;
736   if (ps->send_force_disconnect==GNUNET_YES)
737   {
738 #if DEBUG_CONNECTIONS
739     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound forced to disconnect\n",ps);
740 #endif
741     return -1;
742   }
743
744   if (msg!=NULL)
745   {
746     if ((msg->size-msg->pos) <= max)
747     {
748       memcpy(buf,&msg->buf[msg->pos],(msg->size-msg->pos));
749       bytes_read = msg->size-msg->pos;
750       msg->pos+=(msg->size-msg->pos);
751     }
752     else
753     {
754       memcpy(buf,&msg->buf[msg->pos],max);
755       msg->pos+=max;
756       bytes_read = max;
757     }
758
759     if (msg->pos==msg->size)
760     {
761       if (NULL!=msg->transmit_cont)
762         msg->transmit_cont (msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
763       remove_http_message(ps,msg);
764     }
765   }
766   return bytes_read;
767 }
768
769 /**
770  * Process GET or PUT request received via MHD.  For
771  * GET, queue response that will send back our pending
772  * messages.  For PUT, process incoming data and send
773  * to GNUnet core.  In either case, check if a session
774  * already exists and create a new one if not.
775  */
776 static int
777 mdh_access_cb (void *cls,
778                        struct MHD_Connection *mhd_connection,
779                        const char *url,
780                        const char *method,
781                        const char *version,
782                        const char *upload_data,
783                        size_t * upload_data_size, void **httpSessionCache)
784 {
785   struct Plugin *plugin = cls;
786   struct MHD_Response *response;
787   const union MHD_ConnectionInfo * conn_info;
788
789   struct sockaddr_in  *addrin;
790   struct sockaddr_in6 *addrin6;
791
792   char address[INET6_ADDRSTRLEN+14];
793   struct GNUNET_PeerIdentity pi_in;
794   size_t id_num = 0;
795
796   struct IPv4HttpAddress ipv4addr;
797   struct IPv6HttpAddress ipv6addr;
798
799   struct HTTP_PeerContext *pc;
800   struct Session *ps = NULL;
801   struct Session *ps_tmp = NULL;
802
803   int res = GNUNET_NO;
804   int send_error_to_client;
805   void * addr;
806   size_t addr_len;
807
808   GNUNET_assert(cls !=NULL);
809   send_error_to_client = GNUNET_NO;
810
811   if (NULL == *httpSessionCache)
812   {
813     /* check url for peer identity , if invalid send HTTP 404*/
814     size_t len = strlen(&url[1]);
815     char * peer = GNUNET_malloc(104+1);
816
817     if ((len>104) && (url[104]==';'))
818     {
819         char * id = GNUNET_malloc((len-104)+1);
820         strcpy(id,&url[105]);
821         memcpy(peer,&url[1],103);
822         peer[103] = '\0';
823         id_num = strtoul ( id, NULL , 10);
824         GNUNET_free(id);
825     }
826     res = GNUNET_CRYPTO_hash_from_string (peer, &(pi_in.hashPubKey));
827     GNUNET_free(peer);
828     if ( GNUNET_SYSERR == res )
829     {
830       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
831       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
832       MHD_destroy_response (response);
833 #if DEBUG_CONNECTIONS
834       if (res == MHD_YES)
835         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, sent HTTP 1.1/404\n");
836       else
837         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, could not send error\n");
838 #endif
839       return res;
840     }
841   }
842   else
843   {
844     ps = *httpSessionCache;
845     pc = ps->peercontext;
846   }
847
848   if (NULL == *httpSessionCache)
849   {
850     /* get peer context */
851     pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &pi_in.hashPubKey);
852     /* Peer unknown */
853     if (pc==NULL)
854     {
855       pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
856       pc->plugin = plugin;
857       pc->session_id_counter=1;
858       pc->last_session = NULL;
859       memcpy(&pc->identity, &pi_in, sizeof(struct GNUNET_PeerIdentity));
860       GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
861       GNUNET_STATISTICS_update (plugin->env->stats,
862                             gettext_noop ("# HTTP peers active"),
863                             1,
864                             GNUNET_NO);
865     }
866
867     conn_info = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
868     /* Incoming IPv4 connection */
869     if ( AF_INET == conn_info->client_addr->sin_family)
870     {
871       addrin = conn_info->client_addr;
872       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
873       memcpy(&ipv4addr.ipv4_addr,&(addrin->sin_addr),sizeof(struct in_addr));
874       ipv4addr.u_port = addrin->sin_port;
875       addr = &ipv4addr;
876       addr_len = sizeof(struct IPv4HttpAddress);
877     }
878     /* Incoming IPv6 connection */
879     if ( AF_INET6 == conn_info->client_addr->sin_family)
880     {
881       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
882       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
883       memcpy(&ipv6addr.ipv6_addr,&(addrin6->sin6_addr),sizeof(struct in6_addr));
884       ipv6addr.u6_port = addrin6->sin6_port;
885       addr = &ipv6addr;
886       addr_len = sizeof(struct IPv6HttpAddress);
887     }
888
889     ps = NULL;
890     /* only inbound sessions here */
891
892     ps_tmp = pc->head;
893     while (ps_tmp!=NULL)
894     {
895       if ((ps_tmp->direction==INBOUND) && (ps_tmp->session_id == id_num) && (id_num!=0))
896       {
897         if ((ps_tmp->recv_force_disconnect!=GNUNET_YES) && (ps_tmp->send_force_disconnect!=GNUNET_YES))
898         ps=ps_tmp;
899         break;
900       }
901       ps_tmp=ps_tmp->next;
902     }
903
904     if (ps==NULL)
905     {
906       ps = GNUNET_malloc(sizeof (struct Session));
907       ps->addr = GNUNET_malloc(addr_len);
908       memcpy(ps->addr,addr,addr_len);
909       ps->addrlen = addr_len;
910       ps->direction=INBOUND;
911       ps->pending_msgs_head = NULL;
912       ps->pending_msgs_tail = NULL;
913       ps->send_connected=GNUNET_NO;
914       ps->send_active=GNUNET_NO;
915       ps->recv_connected=GNUNET_NO;
916       ps->recv_active=GNUNET_NO;
917       ps->peercontext=pc;
918       ps->session_id =id_num;
919       ps->url = create_url (plugin, ps->addr, ps->addrlen, ps->session_id);
920       GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
921       GNUNET_STATISTICS_update (plugin->env->stats,
922                             gettext_noop ("# HTTPS inbound sessions for peers active"),
923                             1,
924                             GNUNET_NO);
925     }
926
927     *httpSessionCache = ps;
928     if (ps->msgtok==NULL)
929       ps->msgtok = GNUNET_SERVER_mst_create (&mhd_write_mst_cb, ps);
930 #if DEBUG_HTTP
931     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: HTTPS Daemon has new an incoming `%s' request from peer `%s' (`%s')\n",
932                 ps,
933                 method,
934                 GNUNET_i2s(&pc->identity),
935                 http_plugin_address_to_string(NULL, ps->addr, ps->addrlen));
936 #endif
937   }
938
939   /* Is it a PUT or a GET request */
940   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
941   {
942     if (ps->recv_force_disconnect == GNUNET_YES)
943     {
944 #if DEBUG_CONNECTIONS
945       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound connection was forced to disconnect\n",ps);
946 #endif
947       ps->recv_active = GNUNET_NO;
948       return MHD_NO;
949     }
950     if ((*upload_data_size == 0) && (ps->recv_active==GNUNET_NO))
951     {
952       ps->recv_endpoint = mhd_connection;
953       ps->recv_connected = GNUNET_YES;
954       ps->recv_active = GNUNET_YES;
955       ps->recv_force_disconnect = GNUNET_NO;
956 #if DEBUG_CONNECTIONS
957       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound PUT connection connected\n",ps);
958 #endif
959       return MHD_YES;
960     }
961
962     /* Transmission of all data complete */
963     if ((*upload_data_size == 0) && (ps->recv_active == GNUNET_YES))
964     {
965       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
966       res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
967 #if DEBUG_CONNECTIONS
968       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Sent HTTP/1.1: 200 OK as PUT Response\n",ps);
969 #endif
970       MHD_destroy_response (response);
971       ps->recv_active=GNUNET_NO;
972       return MHD_YES;
973     }
974
975     /* Recieving data */
976     if ((*upload_data_size > 0) && (ps->recv_active == GNUNET_YES))
977     {
978       res = GNUNET_SERVER_mst_receive(ps->msgtok, ps, upload_data,*upload_data_size, GNUNET_NO, GNUNET_NO);
979       (*upload_data_size) = 0;
980       return MHD_YES;
981     }
982     else
983       return MHD_NO;
984   }
985   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
986   {
987     if (ps->send_force_disconnect == GNUNET_YES)
988     {
989 #if DEBUG_CONNECTIONS
990       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound connection was  forced to disconnect\n",ps);
991 #endif
992       ps->send_active = GNUNET_NO;
993       return MHD_NO;
994     }
995           ps->send_connected = GNUNET_YES;
996           ps->send_active = GNUNET_YES;
997           ps->send_endpoint = mhd_connection;
998           ps->send_force_disconnect = GNUNET_NO;
999 #if DEBUG_CONNECTIONS
1000           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound GET connection connected\n",ps);
1001 #endif
1002           response = MHD_create_response_from_callback(-1,32 * 1024, &mhd_send_callback, ps, NULL);
1003           res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1004           MHD_destroy_response (response);
1005           return MHD_YES;
1006   }
1007   return MHD_NO;
1008 }
1009
1010 /**
1011  * Function that queries MHD's select sets and
1012  * starts the task waiting for them.
1013  */
1014 static GNUNET_SCHEDULER_TaskIdentifier
1015 http_server_daemon_prepare (void * cls, struct MHD_Daemon *daemon_handle)
1016 {
1017   struct Plugin *plugin = cls;
1018   GNUNET_SCHEDULER_TaskIdentifier ret;
1019   fd_set rs;
1020   fd_set ws;
1021   fd_set es;
1022   struct GNUNET_NETWORK_FDSet *wrs;
1023   struct GNUNET_NETWORK_FDSet *wws;
1024   struct GNUNET_NETWORK_FDSet *wes;
1025   int max;
1026   unsigned long long timeout;
1027   int haveto;
1028   struct GNUNET_TIME_Relative tv;
1029
1030   GNUNET_assert(cls !=NULL);
1031   ret = GNUNET_SCHEDULER_NO_TASK;
1032   FD_ZERO(&rs);
1033   FD_ZERO(&ws);
1034   FD_ZERO(&es);
1035   wrs = GNUNET_NETWORK_fdset_create ();
1036   wes = GNUNET_NETWORK_fdset_create ();
1037   wws = GNUNET_NETWORK_fdset_create ();
1038   max = -1;
1039   GNUNET_assert (MHD_YES ==
1040                  MHD_get_fdset (daemon_handle,
1041                                 &rs,
1042                                 &ws,
1043                                 &es,
1044                                 &max));
1045   haveto = MHD_get_timeout (daemon_handle, &timeout);
1046   if (haveto == MHD_YES)
1047     tv.value = (uint64_t) timeout;
1048   else
1049     tv = GNUNET_TIME_UNIT_FOREVER_REL;
1050   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
1051   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
1052   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
1053   if (daemon_handle == plugin->http_server_daemon_v4)
1054   {
1055         if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1056         {
1057                 GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
1058                 plugin->http_server_daemon_v4 = GNUNET_SCHEDULER_NO_TASK;
1059         }
1060
1061     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1062                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1063                                        GNUNET_SCHEDULER_NO_TASK,
1064                                        tv,
1065                                        wrs,
1066                                        wws,
1067                                        &http_server_daemon_v4_run,
1068                                        plugin);
1069   }
1070   if (daemon_handle == plugin->http_server_daemon_v6)
1071   {
1072         if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1073         {
1074                 GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
1075                 plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1076         }
1077
1078     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1079                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1080                                        GNUNET_SCHEDULER_NO_TASK,
1081                                        tv,
1082                                        wrs,
1083                                        wws,
1084                                        &http_server_daemon_v6_run,
1085                                        plugin);
1086   }
1087   GNUNET_NETWORK_fdset_destroy (wrs);
1088   GNUNET_NETWORK_fdset_destroy (wws);
1089   GNUNET_NETWORK_fdset_destroy (wes);
1090   return ret;
1091 }
1092
1093 /**
1094  * Call MHD to process pending requests and then go back
1095  * and schedule the next run.
1096  */
1097 static void http_server_daemon_v4_run (void *cls,
1098                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1099 {
1100   struct Plugin *plugin = cls;
1101
1102   GNUNET_assert(cls !=NULL);
1103   plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1104
1105   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1106     return;
1107
1108   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v4));
1109   plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
1110   return;
1111 }
1112
1113
1114 /**
1115  * Call MHD to process pending requests and then go back
1116  * and schedule the next run.
1117  */
1118 static void http_server_daemon_v6_run (void *cls,
1119                              const struct GNUNET_SCHEDULER_TaskContext *tc)
1120 {
1121   struct Plugin *plugin = cls;
1122
1123   GNUNET_assert(cls !=NULL);
1124   plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1125
1126   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1127     return;
1128
1129   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v6));
1130   plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
1131   return;
1132 }
1133
1134 static size_t curl_get_header_cb( void *ptr, size_t size, size_t nmemb, void *stream)
1135 {
1136   struct Session * ps = stream;
1137   char * tmp;
1138   size_t len = size * nmemb;
1139   long http_result = 0;
1140   int res;
1141   /* Getting last http result code */
1142   if (ps->recv_connected==GNUNET_NO)
1143   {
1144     GNUNET_assert(NULL!=ps);
1145     res = curl_easy_getinfo(ps->recv_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
1146     if (CURLE_OK == res)
1147     {
1148       if (http_result == 200)
1149       {
1150         ps->recv_connected = GNUNET_YES;
1151         ps->recv_active = GNUNET_YES;
1152 #if DEBUG_CONNECTIONS
1153         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to recieve data\n",ps);
1154 #endif
1155         // Calling send_check_connections again since receive is established
1156         send_check_connections (ps->peercontext->plugin, ps);
1157       }
1158     }
1159   }
1160
1161   tmp = NULL;
1162   if ((size * nmemb) < SIZE_MAX)
1163     tmp = GNUNET_malloc (len+1);
1164
1165   if ((tmp != NULL) && (len > 0))
1166   {
1167     memcpy(tmp,ptr,len);
1168     if (len>=2)
1169     {
1170       if (tmp[len-2] == 13)
1171         tmp[len-2]= '\0';
1172     }
1173 #if DEBUG_CURL
1174     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Header: %s\n",ps,tmp);
1175 #endif
1176   }
1177   if (NULL != tmp)
1178     GNUNET_free (tmp);
1179
1180   return size * nmemb;
1181 }
1182
1183 static size_t curl_put_header_cb( void *ptr, size_t size, size_t nmemb, void *stream)
1184 {
1185   struct Session * ps = stream;
1186
1187   char * tmp;
1188   size_t len = size * nmemb;
1189   long http_result = 0;
1190   int res;
1191
1192   /* Getting last http result code */
1193   GNUNET_assert(NULL!=ps);
1194   res = curl_easy_getinfo(ps->send_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
1195   if (CURLE_OK == res)
1196   {
1197     if ((http_result == 100) && (ps->send_connected==GNUNET_NO))
1198     {
1199       ps->send_connected = GNUNET_YES;
1200       ps->send_active = GNUNET_YES;
1201 #if DEBUG_CONNECTIONS
1202       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to send data\n",ps);
1203 #endif
1204     }
1205     if ((http_result == 200) && (ps->send_connected==GNUNET_YES))
1206     {
1207       ps->send_connected = GNUNET_NO;
1208       ps->send_active = GNUNET_NO;
1209 #if DEBUG_CONNECTIONS
1210       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: sending disconnected\n",ps);
1211 #endif
1212     }
1213   }
1214
1215   tmp = NULL;
1216   if ((size * nmemb) < SIZE_MAX)
1217     tmp = GNUNET_malloc (len+1);
1218
1219   if ((tmp != NULL) && (len > 0))
1220   {
1221     memcpy(tmp,ptr,len);
1222     if (len>=2)
1223     {
1224       if (tmp[len-2] == 13)
1225         tmp[len-2]= '\0';
1226     }
1227   }
1228   if (NULL != tmp)
1229     GNUNET_free (tmp);
1230
1231   return size * nmemb;
1232 }
1233
1234 /**
1235  * Callback method used with libcurl
1236  * Method is called when libcurl needs to read data during sending
1237  * @param stream pointer where to write data
1238  * @param size size of an individual element
1239  * @param nmemb count of elements that can be written to the buffer
1240  * @param ptr source pointer, passed to the libcurl handle
1241  * @return bytes written to stream
1242  */
1243 static size_t curl_send_cb(void *stream, size_t size, size_t nmemb, void *ptr)
1244 {
1245   struct Session * ps = ptr;
1246   struct HTTP_Message * msg = ps->pending_msgs_tail;
1247   size_t bytes_sent;
1248   size_t len;
1249
1250   if (ps->send_active == GNUNET_NO)
1251         return CURL_READFUNC_PAUSE;
1252
1253
1254   if ((ps->pending_msgs_tail == NULL) && (ps->send_active == GNUNET_YES))
1255   {
1256 #if DEBUG_CONNECTIONS
1257     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: No Message to send, pausing connection\n",ps);
1258 #endif
1259     ps->send_active = GNUNET_NO;
1260     return CURL_READFUNC_PAUSE;
1261   }
1262
1263   msg = ps->pending_msgs_tail;
1264   /* data to send */
1265   if (msg->pos < msg->size)
1266   {
1267     /* data fit in buffer */
1268     if ((msg->size - msg->pos) <= (size * nmemb))
1269     {
1270       len = (msg->size - msg->pos);
1271       memcpy(stream, &msg->buf[msg->pos], len);
1272       msg->pos += len;
1273       bytes_sent = len;
1274     }
1275     else
1276     {
1277       len = size*nmemb;
1278       memcpy(stream, &msg->buf[msg->pos], len);
1279       msg->pos += len;
1280       bytes_sent = len;
1281     }
1282   }
1283   /* no data to send */
1284   else
1285   {
1286     bytes_sent = 0;
1287   }
1288
1289   if ( msg->pos == msg->size)
1290   {
1291 #if DEBUG_CONNECTIONS
1292     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Message with %u bytes sent, removing message from queue \n",ps, msg->pos);
1293 #endif
1294     /* Calling transmit continuation  */
1295     if (( NULL != ps->pending_msgs_tail) && (NULL != ps->pending_msgs_tail->transmit_cont))
1296       msg->transmit_cont (ps->pending_msgs_tail->transmit_cont_cls,&(ps->peercontext)->identity,GNUNET_OK);
1297     remove_http_message(ps, msg);
1298   }
1299   return bytes_sent;
1300 }
1301
1302 static void curl_receive_mst_cb  (void *cls,
1303                                 void *client,
1304                                 const struct GNUNET_MessageHeader *message)
1305 {
1306   struct Session *ps  = cls;
1307   struct HTTP_PeerContext *pc = ps->peercontext;
1308   GNUNET_assert(ps != NULL);
1309   GNUNET_assert(pc != NULL);
1310 #if DEBUG_HTTP
1311   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1312               "Connection %X: Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
1313               ps,
1314               ntohs(message->type),
1315               ntohs(message->size),
1316               GNUNET_i2s(&(pc->identity)),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
1317 #endif
1318   pc->plugin->env->receive (pc->plugin->env->cls,
1319                             &pc->identity,
1320                             message, 1, ps,
1321                             ps->addr,
1322                             ps->addrlen);
1323 }
1324
1325
1326 /**
1327 * Callback method used with libcurl
1328 * Method is called when libcurl needs to write data during sending
1329 * @param stream pointer where to write data
1330 * @param size size of an individual element
1331 * @param nmemb count of elements that can be written to the buffer
1332 * @param ptr destination pointer, passed to the libcurl handle
1333 * @return bytes read from stream
1334 */
1335 static size_t curl_receive_cb( void *stream, size_t size, size_t nmemb, void *ptr)
1336 {
1337   struct Session * ps = ptr;
1338 #if DEBUG_CONNECTIONS
1339   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: %u bytes received\n",ps, size*nmemb);
1340 #endif
1341   GNUNET_SERVER_mst_receive(ps->msgtok, ps, stream, size*nmemb, GNUNET_NO, GNUNET_NO);
1342   return (size * nmemb);
1343
1344 }
1345
1346 static void curl_perform (void *cls,
1347              const struct GNUNET_SCHEDULER_TaskContext *tc)
1348 {
1349   struct Plugin *plugin = cls;
1350   static unsigned int handles_last_run;
1351   int running;
1352   struct CURLMsg *msg;
1353   CURLMcode mret;
1354   struct Session *ps = NULL;
1355   struct HTTP_PeerContext *pc = NULL;
1356   struct HTTP_Message * cur_msg = NULL;
1357   long http_result;
1358   char * tmp;
1359
1360   GNUNET_assert(cls !=NULL);
1361
1362   plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1363   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1364     return;
1365
1366   do
1367     {
1368       running = 0;
1369       mret = curl_multi_perform (plugin->multi_handle, &running);
1370       if ((running < handles_last_run) && (running>0))
1371         {
1372           do
1373             {
1374
1375               msg = curl_multi_info_read (plugin->multi_handle, &running);
1376               if (running == 0)
1377                   break;
1378               /* get session for affected curl handle */
1379               GNUNET_assert ( msg->easy_handle != NULL );
1380               curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &tmp);
1381               ps = (struct Session *) tmp;
1382               GNUNET_assert ( ps != NULL );
1383               pc = ps->peercontext;
1384               GNUNET_assert ( pc != NULL );
1385               switch (msg->msg)
1386                 {
1387
1388                 case CURLMSG_DONE:
1389                   if ( (msg->data.result != CURLE_OK) &&
1390                        (msg->data.result != CURLE_GOT_NOTHING) )
1391                   {
1392                     /* sending msg failed*/
1393                     if (msg->easy_handle == ps->send_endpoint)
1394                     {
1395 #if DEBUG_CONNECTIONS
1396                       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1397                                  _("Connection %X: HTTPS PUT to peer `%s' (`%s') failed: `%s' `%s'\n"),
1398                                  ps,
1399                                  GNUNET_i2s(&pc->identity),
1400                                  http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1401                                  "curl_multi_perform",
1402                                  curl_easy_strerror (msg->data.result));
1403 #endif
1404                       ps->send_connected = GNUNET_NO;
1405                       ps->send_active = GNUNET_NO;
1406                       curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint);
1407                       //curl_easy_cleanup(ps->send_endpoint);
1408                       //ps->send_endpoint=NULL;
1409                       cur_msg = ps->pending_msgs_tail;
1410                       if (( NULL != cur_msg) && ( NULL != cur_msg->transmit_cont))
1411                         cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1412                     }
1413                     /* GET connection failed */
1414                     if (msg->easy_handle == ps->recv_endpoint)
1415                     {
1416 #if DEBUG_CONNECTIONS
1417                       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1418                            _("Connection %X: HTTPS GET to peer `%s' (`%s') failed: `%s' `%s'\n"),
1419                            ps,
1420                            GNUNET_i2s(&pc->identity),
1421                            http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1422                            "curl_multi_perform",
1423                            curl_easy_strerror (msg->data.result));
1424 #endif
1425                       ps->recv_connected = GNUNET_NO;
1426                       ps->recv_active = GNUNET_NO;
1427                       curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint);
1428                       //curl_easy_cleanup(ps->recv_endpoint);
1429                       //ps->recv_endpoint=NULL;
1430                     }
1431                   }
1432                   else
1433                   {
1434                     if (msg->easy_handle == ps->send_endpoint)
1435                     {
1436                       GNUNET_assert (CURLE_OK == curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_result));
1437 #if DEBUG_CONNECTIONS
1438                       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1439                                   "Connection %X: HTTPS PUT connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1440                                    ps,
1441                                    GNUNET_i2s(&pc->identity),
1442                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1443                                    http_result);
1444 #endif
1445                       /* Calling transmit continuation  */
1446                       cur_msg = ps->pending_msgs_tail;
1447                       if (( NULL != cur_msg) && (NULL != cur_msg->transmit_cont))
1448                       {
1449                         /* HTTP 1xx : Last message before here was informational */
1450                         if ((http_result >=100) && (http_result < 200))
1451                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1452                         /* HTTP 2xx: successful operations */
1453                         if ((http_result >=200) && (http_result < 300))
1454                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1455                         /* HTTP 3xx..5xx: error */
1456                         if ((http_result >=300) && (http_result < 600))
1457                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1458                       }
1459                       ps->send_connected = GNUNET_NO;
1460                       ps->send_active = GNUNET_NO;
1461                       curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint);
1462                       //curl_easy_cleanup(ps->send_endpoint);
1463                       //ps->send_endpoint =NULL;
1464                     }
1465                     if (msg->easy_handle == ps->recv_endpoint)
1466                     {
1467 #if DEBUG_CONNECTIONS
1468                       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1469                                   "Connection %X: HTTP GET connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1470                                    ps,
1471                                    GNUNET_i2s(&pc->identity),
1472                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1473                                    http_result);
1474 #endif
1475                       ps->recv_connected = GNUNET_NO;
1476                       ps->recv_active = GNUNET_NO;
1477                       curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint);
1478                       //curl_easy_cleanup(ps->recv_endpoint);
1479                       //ps->recv_endpoint=NULL;
1480                     }
1481                   }
1482                   if ((ps->recv_connected == GNUNET_NO) && (ps->send_connected == GNUNET_NO))
1483                     remove_session (pc, ps, GNUNET_YES, GNUNET_SYSERR);
1484                   break;
1485                 default:
1486                   break;
1487                 }
1488
1489             }
1490           while ( (running > 0) );
1491         }
1492       handles_last_run = running;
1493     }
1494   while (mret == CURLM_CALL_MULTI_PERFORM);
1495   curl_schedule(plugin);
1496 }
1497
1498
1499 /**
1500  * Function setting up file descriptors and scheduling task to run
1501  * @param ses session to send data to
1502  * @return GNUNET_SYSERR for hard failure, GNUNET_OK for ok
1503  */
1504 static void
1505 http_plugin_disconnect (void *cls,
1506                             const struct GNUNET_PeerIdentity *target)
1507 {
1508
1509
1510   struct Plugin *plugin = cls;
1511   struct HTTP_PeerContext *pc = NULL;
1512   struct Session *ps = NULL;
1513   //struct Session *tmp = NULL;
1514
1515   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
1516   if (pc==NULL)
1517     return;
1518   ps = pc->head;
1519
1520   while (ps!=NULL)
1521   {
1522     /* Telling transport that session is getting disconnected */
1523     plugin->env->session_end(plugin, target, ps);
1524     if (ps->direction==OUTBOUND)
1525     {
1526       if (ps->send_endpoint!=NULL)
1527       {
1528         //GNUNET_assert(CURLM_OK == curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint));
1529         //curl_easy_cleanup(ps->send_endpoint);
1530         //ps->send_endpoint=NULL;
1531         ps->send_force_disconnect = GNUNET_YES;
1532       }
1533       if (ps->recv_endpoint!=NULL)
1534       {
1535        //GNUNET_assert(CURLM_OK == curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint));
1536        //curl_easy_cleanup(ps->recv_endpoint);
1537        //ps->recv_endpoint=NULL;
1538        ps->recv_force_disconnect = GNUNET_YES;
1539       }
1540     }
1541
1542     if (ps->direction==INBOUND)
1543     {
1544       ps->recv_force_disconnect = GNUNET_YES;
1545       ps->send_force_disconnect = GNUNET_YES;
1546     }
1547
1548     while (ps->pending_msgs_head!=NULL)
1549     {
1550       remove_http_message(ps, ps->pending_msgs_head);
1551     }
1552     ps->recv_active = GNUNET_NO;
1553     ps->send_active = GNUNET_NO;
1554     ps=ps->next;
1555   }
1556 }
1557
1558
1559 static int curl_schedule(void *cls)
1560 {
1561   struct Plugin *plugin = cls;
1562   fd_set rs;
1563   fd_set ws;
1564   fd_set es;
1565   int max;
1566   struct GNUNET_NETWORK_FDSet *grs;
1567   struct GNUNET_NETWORK_FDSet *gws;
1568   long to;
1569   CURLMcode mret;
1570
1571   GNUNET_assert(cls !=NULL);
1572
1573   /* Cancel previous scheduled task */
1574   if (plugin->http_curl_task !=  GNUNET_SCHEDULER_NO_TASK)
1575   {
1576           GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
1577           plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
1578   }
1579   max = -1;
1580   FD_ZERO (&rs);
1581   FD_ZERO (&ws);
1582   FD_ZERO (&es);
1583   mret = curl_multi_fdset (plugin->multi_handle, &rs, &ws, &es, &max);
1584   if (mret != CURLM_OK)
1585     {
1586       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1587                   _("%s failed at %s:%d: `%s'\n"),
1588                   "curl_multi_fdset", __FILE__, __LINE__,
1589                   curl_multi_strerror (mret));
1590       return GNUNET_SYSERR;
1591     }
1592   mret = curl_multi_timeout (plugin->multi_handle, &to);
1593   if (mret != CURLM_OK)
1594     {
1595       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1596                   _("%s failed at %s:%d: `%s'\n"),
1597                   "curl_multi_timeout", __FILE__, __LINE__,
1598                   curl_multi_strerror (mret));
1599       return GNUNET_SYSERR;
1600     }
1601
1602   grs = GNUNET_NETWORK_fdset_create ();
1603   gws = GNUNET_NETWORK_fdset_create ();
1604   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1605   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1606   plugin->http_curl_task = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1607                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1608                                    GNUNET_SCHEDULER_NO_TASK,
1609                                    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 0),
1610                                    grs,
1611                                    gws,
1612                                    &curl_perform,
1613                                    plugin);
1614   GNUNET_NETWORK_fdset_destroy (gws);
1615   GNUNET_NETWORK_fdset_destroy (grs);
1616   return GNUNET_OK;
1617 }
1618
1619 /**
1620  * Function setting up curl handle and selecting message to send
1621  * @param cls plugin
1622  * @param ses session to send data to
1623  * @param con connection
1624  * @return GNUNET_SYSERR on failure, GNUNET_NO if connecting, GNUNET_YES if ok
1625  */
1626 static ssize_t send_check_connections (void *cls, struct Session *ps)
1627 {
1628   struct Plugin *plugin = cls;
1629   CURLMcode mret;
1630   struct HTTP_Message * msg;
1631
1632   struct GNUNET_TIME_Relative timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1633
1634   GNUNET_assert(cls !=NULL);
1635
1636   if (ps->direction == OUTBOUND)
1637   {
1638     /* RECV DIRECTION */
1639     /* Check if session is connected to receive data, otherwise connect to peer */
1640     if (ps->recv_connected == GNUNET_NO)
1641     {
1642         int fresh = GNUNET_NO;
1643         if (ps->recv_endpoint == NULL)
1644         {
1645             fresh = GNUNET_YES;
1646                 ps->recv_endpoint = curl_easy_init();
1647         }
1648 #if DEBUG_CURL
1649         curl_easy_setopt(ps->recv_endpoint, CURLOPT_VERBOSE, 1L);
1650 #endif
1651         curl_easy_setopt(ps->recv_endpoint, CURLOPT_URL, ps->url);
1652         curl_easy_setopt (ps->recv_endpoint, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1653         //curl_easy_setopt (ps->recv_endpoint, CURLOPT_SSL_CIPHER_LIST, cipher_suite);
1654                 curl_easy_setopt(ps->recv_endpoint, CURLOPT_SSL_VERIFYPEER, 0);
1655                 curl_easy_setopt(ps->recv_endpoint, CURLOPT_SSL_VERIFYHOST, 0);
1656         curl_easy_setopt(ps->recv_endpoint, CURLOPT_HEADERFUNCTION, &curl_get_header_cb);
1657         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEHEADER, ps);
1658         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READFUNCTION, curl_send_cb);
1659         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READDATA, ps);
1660         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEFUNCTION, curl_receive_cb);
1661         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEDATA, ps);
1662         curl_easy_setopt(ps->recv_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1663         curl_easy_setopt(ps->recv_endpoint, CURLOPT_PRIVATE, ps);
1664         curl_easy_setopt(ps->recv_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1665         curl_easy_setopt(ps->recv_endpoint, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
1666
1667         if (fresh==GNUNET_YES)
1668         {
1669                         mret = curl_multi_add_handle(plugin->multi_handle, ps->recv_endpoint);
1670                         if (mret != CURLM_OK)
1671                         {
1672                           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1673                                                   _("Connection: %X: %s failed at %s:%d: `%s'\n"),
1674                                                   ps,
1675                                                   "curl_multi_add_handle", __FILE__, __LINE__,
1676                                                   curl_multi_strerror (mret));
1677                           return GNUNET_SYSERR;
1678                         }
1679         }
1680         if (curl_schedule (plugin) == GNUNET_SYSERR)
1681         {
1682 #if DEBUG_CONNECTIONS
1683         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: could not schedule curl task\n",ps);
1684 #endif
1685                 return GNUNET_SYSERR;
1686         }
1687 #if DEBUG_CONNECTIONS
1688         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound not connected, initiating connection\n",ps);
1689 #endif
1690     }
1691
1692     /* waiting for receive direction */
1693     if (ps->recv_connected==GNUNET_NO)
1694       return GNUNET_NO;
1695
1696     /* SEND DIRECTION */
1697     /* Check if session is connected to send data, otherwise connect to peer */
1698     if ((ps->send_connected == GNUNET_YES) && (ps->send_endpoint!= NULL))
1699     {
1700       if (ps->send_active == GNUNET_YES)
1701       {
1702 #if DEBUG_CONNECTIONS
1703         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound active, enqueueing message\n",ps);
1704 #endif
1705         return GNUNET_YES;
1706       }
1707       if (ps->send_active == GNUNET_NO)
1708       {
1709 #if DEBUG_CONNECTIONS
1710         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound paused, unpausing existing connection and enqueueing message\n",ps);
1711 #endif
1712         if (CURLE_OK == curl_easy_pause(ps->send_endpoint,CURLPAUSE_CONT))
1713         {
1714                         ps->send_active=GNUNET_YES;
1715                         return GNUNET_YES;
1716         }
1717         else
1718                 return GNUNET_SYSERR;
1719       }
1720     }
1721     /* not connected, initiate connection */
1722     if (ps->send_connected==GNUNET_NO)
1723     {
1724         int fresh = GNUNET_NO;
1725         if (NULL == ps->send_endpoint)
1726         {
1727                 ps->send_endpoint = curl_easy_init();
1728                 fresh = GNUNET_YES;
1729         }
1730                 GNUNET_assert (ps->send_endpoint != NULL);
1731                 GNUNET_assert (NULL != ps->pending_msgs_tail);
1732 #if DEBUG_CONNECTIONS
1733                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound not connected, initiating connection\n",ps);
1734 #endif
1735                 ps->send_active = GNUNET_NO;
1736                 msg = ps->pending_msgs_tail;
1737
1738 #if DEBUG_CURL
1739                 curl_easy_setopt(ps->send_endpoint, CURLOPT_VERBOSE, 1L);
1740 #endif
1741                 curl_easy_setopt(ps->send_endpoint, CURLOPT_URL, ps->url);
1742                 curl_easy_setopt(ps->send_endpoint, CURLOPT_PUT, 1L);
1743                 curl_easy_setopt(ps->send_endpoint, CURLOPT_HEADERFUNCTION, &curl_put_header_cb);
1744                 curl_easy_setopt(ps->send_endpoint, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1745                 curl_easy_setopt(ps->send_endpoint, CURLOPT_SSL_VERIFYPEER, 0);
1746                 curl_easy_setopt(ps->send_endpoint, CURLOPT_SSL_VERIFYHOST, 0);
1747
1748                 curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEHEADER, ps);
1749                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READFUNCTION, curl_send_cb);
1750                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
1751                 curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEFUNCTION, curl_receive_cb);
1752                 curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
1753                 curl_easy_setopt(ps->send_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1754                 curl_easy_setopt(ps->send_endpoint, CURLOPT_PRIVATE, ps);
1755                 curl_easy_setopt(ps->send_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1756                 curl_easy_setopt(ps->send_endpoint, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
1757
1758                 if (fresh==GNUNET_YES)
1759                 {
1760                         mret = curl_multi_add_handle(plugin->multi_handle, ps->send_endpoint);
1761                         if (mret != CURLM_OK)
1762                         {
1763                           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1764                                                   _("Connection: %X: %s failed at %s:%d: `%s'\n"),
1765                                                   ps,
1766                                                   "curl_multi_add_handle", __FILE__, __LINE__,
1767                                                   curl_multi_strerror (mret));
1768                           return GNUNET_SYSERR;
1769                         }
1770                 }
1771     }
1772     if (curl_schedule (plugin) == GNUNET_SYSERR)
1773         return GNUNET_SYSERR;
1774     return GNUNET_YES;
1775   }
1776   if (ps->direction == INBOUND)
1777   {
1778     GNUNET_assert (NULL != ps->pending_msgs_tail);
1779     if ((ps->recv_connected==GNUNET_YES) && (ps->send_connected==GNUNET_YES) &&
1780         (ps->recv_force_disconnect==GNUNET_NO) && (ps->recv_force_disconnect==GNUNET_NO))
1781         return GNUNET_YES;
1782   }
1783   return GNUNET_SYSERR;
1784 }
1785
1786 static struct Session * send_select_session (void * cls, struct HTTP_PeerContext *pc, const void * addr, size_t addrlen, int force_address, struct Session * session)
1787 {
1788         struct Session * tmp = NULL;
1789         int addr_given = GNUNET_NO;
1790
1791         if ((addr!=NULL) && (addrlen>0))
1792                 addr_given = GNUNET_YES;
1793
1794         if (force_address == GNUNET_YES)
1795         {
1796                 /* check session given as argument */
1797                 if ((session != NULL) && (addr_given == GNUNET_YES))
1798                 {
1799                       if (0 == memcmp(session->addr, addr, addrlen))
1800                       {
1801                         /* connection can not be used, since it is disconnected */
1802                         if ((session->recv_force_disconnect==GNUNET_NO) && (session->send_force_disconnect==GNUNET_NO))
1803                         {
1804 #if DEBUG_SESSION_SELECTION
1805                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using session passed by transport to send to forced address \n", session);
1806 #endif
1807                                 return session;
1808                         }
1809                       }
1810                 }
1811                 /* check last session used */
1812                 if ((pc->last_session != NULL)&& (addr_given == GNUNET_YES))
1813                 {
1814                       if (0 == memcmp(pc->last_session->addr, addr, addrlen))
1815                       {
1816                         /* connection can not be used, since it is disconnected */
1817                         if ((pc->last_session->recv_force_disconnect==GNUNET_NO) && (pc->last_session->send_force_disconnect==GNUNET_NO))
1818                         {
1819 #if DEBUG_SESSION_SELECTION
1820                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using last session used to send to forced address \n", pc->last_session);
1821 #endif
1822                                 return pc->last_session;
1823                         }
1824                       }
1825                 }
1826                 /* find session in existing sessions */
1827                 tmp = pc->head;
1828                 while ((tmp!=NULL) && (addr_given == GNUNET_YES))
1829                 {
1830
1831                           if (0 == memcmp(tmp->addr, addr, addrlen))
1832                       {
1833                         /* connection can not be used, since it is disconnected */
1834                         if ((tmp->recv_force_disconnect==GNUNET_NO) && (tmp->send_force_disconnect==GNUNET_NO))
1835                         {
1836 #if DEBUG_SESSION_SELECTION
1837                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using existing session to send to forced address \n", session);
1838 #endif
1839                                   return session;
1840                         }
1841
1842                       }
1843                           tmp=tmp->next;
1844                 }
1845                 /* no session to use */
1846                 return NULL;
1847         }
1848         if ((force_address == GNUNET_NO) || (force_address == GNUNET_SYSERR))
1849         {
1850                 /* check session given as argument */
1851                 if (session != NULL)
1852                 {
1853                         /* connection can not be used, since it is disconnected */
1854                         if ((session->recv_force_disconnect==GNUNET_NO) && (session->send_force_disconnect==GNUNET_NO))
1855                         {
1856 #if DEBUG_SESSION_SELECTION
1857                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using session passed by transport to send not-forced address \n", session);
1858 #endif
1859                                   return session;
1860                         }
1861
1862                 }
1863                 /* check last session used */
1864                 if (pc->last_session != NULL)
1865                 {
1866                         /* connection can not be used, since it is disconnected */
1867                         if ((pc->last_session->recv_force_disconnect==GNUNET_NO) && (pc->last_session->send_force_disconnect==GNUNET_NO))
1868                         {
1869 #if DEBUG_SESSION_SELECTION
1870                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using last session to send to not-forced address \n", pc->last_session);
1871 #endif
1872                                 return pc->last_session;
1873                         }
1874                 }
1875                 /* find session in existing sessions */
1876                 tmp = pc->head;
1877                 while (tmp!=NULL)
1878                 {
1879                         /* connection can not be used, since it is disconnected */
1880                         if ((tmp->recv_force_disconnect==GNUNET_NO) && (tmp->send_force_disconnect==GNUNET_NO))
1881                         {
1882 #if DEBUG_SESSION_SELECTION
1883                                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session %X selected: Using existing session to send to not-forced address \n", tmp);
1884 #endif
1885                                 return tmp;
1886                         }
1887                         tmp=tmp->next;
1888                 }
1889                 return NULL;
1890         }
1891         return NULL;
1892 }
1893
1894 /**
1895  * Function that can be used by the transport service to transmit
1896  * a message using the plugin.   Note that in the case of a
1897  * peer disconnecting, the continuation MUST be called
1898  * prior to the disconnect notification itself.  This function
1899  * will be called with this peer's HELLO message to initiate
1900  * a fresh connection to another peer.
1901  *
1902  * @param cls closure
1903  * @param target who should receive this message
1904  * @param msgbuf the message to transmit
1905  * @param msgbuf_size number of bytes in 'msgbuf'
1906  * @param priority how important is the message (most plugins will
1907  *                 ignore message priority and just FIFO)
1908  * @param timeout how long to wait at most for the transmission (does not
1909  *                require plugins to discard the message after the timeout,
1910  *                just advisory for the desired delay; most plugins will ignore
1911  *                this as well)
1912  * @param session which session must be used (or NULL for "any")
1913  * @param addr the address to use (can be NULL if the plugin
1914  *                is "on its own" (i.e. re-use existing TCP connection))
1915  * @param addrlen length of the address in bytes
1916  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1917  *                GNUNET_NO means the plugin may use any other address and
1918  *                GNUNET_SYSERR means that only reliable existing
1919  *                bi-directional connections should be used (regardless
1920  *                of address)
1921  * @param cont continuation to call once the message has
1922  *        been transmitted (or if the transport is ready
1923  *        for the next transmission call; or if the
1924  *        peer disconnected...); can be NULL
1925  * @param cont_cls closure for cont
1926  * @return number of bytes used (on the physical network, with overheads);
1927  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1928  *         and does NOT mean that the message was not transmitted (DV)
1929  */
1930 static ssize_t
1931 http_plugin_send (void *cls,
1932                   const struct GNUNET_PeerIdentity *target,
1933                   const char *msgbuf,
1934                   size_t msgbuf_size,
1935                   unsigned int priority,
1936                   struct GNUNET_TIME_Relative to,
1937                   struct Session *session,
1938                   const void *addr,
1939                   size_t addrlen,
1940                   int force_address,
1941                   GNUNET_TRANSPORT_TransmitContinuation cont,
1942                   void *cont_cls)
1943 {
1944   struct Plugin *plugin = cls;
1945   struct HTTP_Message *msg;
1946   struct HTTP_PeerContext * pc;
1947   struct Session * ps = NULL;
1948
1949   GNUNET_assert(cls !=NULL);
1950
1951 #if DEBUG_HTTP
1952   char * force = GNUNET_malloc(40);
1953   if (force_address == GNUNET_YES)
1954     strcpy(force,"forced addr.");
1955   if (force_address == GNUNET_NO)
1956     strcpy(force,"any addr.");
1957   if (force_address == GNUNET_SYSERR)
1958     strcpy(force,"reliable bi-direc. address addr.");
1959
1960   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Transport tells me to send %u bytes to `%s' using %s (%s) and session: %X\n",
1961                                       msgbuf_size,
1962                                       GNUNET_i2s(target),
1963                                       force,
1964                                       http_plugin_address_to_string(NULL, addr, addrlen),
1965                                       session);
1966
1967   GNUNET_free(force);
1968 #endif
1969
1970   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
1971   /* Peer unknown */
1972   if (pc==NULL)
1973   {
1974     pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
1975     pc->plugin = plugin;
1976     pc->session_id_counter=1;
1977     pc->last_session = NULL;
1978     memcpy(&pc->identity, target, sizeof(struct GNUNET_PeerIdentity));
1979     GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1980     GNUNET_STATISTICS_update (plugin->env->stats,
1981                             gettext_noop ("# HTTP peers active"),
1982                             1,
1983                             GNUNET_NO);
1984   }
1985
1986   ps = send_select_session (plugin, pc, addr, addrlen, force_address, session);
1987
1988   /* session not existing, but address forced -> creating new session */
1989   if (ps==NULL)
1990   {
1991     if ((addr!=NULL) && (addrlen!=0))
1992     {
1993       ps = GNUNET_malloc(sizeof (struct Session));
1994 #if DEBUG_SESSION_SELECTION
1995       if (force_address == GNUNET_YES)
1996         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection & forced address: creating new session %X to peer %s\n", ps, GNUNET_i2s(target));
1997       if (force_address != GNUNET_YES)
1998         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection: creating new session %X to peer %s\n", ps, GNUNET_i2s(target));
1999 #endif
2000       if ((addrlen!=0) && (addr!=NULL))
2001       {
2002       ps->addr = GNUNET_malloc(addrlen);
2003       memcpy(ps->addr,addr,addrlen);
2004       ps->addrlen = addrlen;
2005       }
2006       else
2007       {
2008         ps->addr = NULL;
2009         ps->addrlen = 0;
2010       }
2011       ps->direction=OUTBOUND;
2012       ps->recv_connected = GNUNET_NO;
2013       ps->recv_force_disconnect = GNUNET_NO;
2014       ps->send_connected = GNUNET_NO;
2015       ps->send_force_disconnect = GNUNET_NO;
2016       ps->pending_msgs_head = NULL;
2017       ps->pending_msgs_tail = NULL;
2018       ps->peercontext=pc;
2019       ps->session_id = pc->session_id_counter;
2020       pc->session_id_counter++;
2021       ps->url = create_url (plugin, ps->addr, ps->addrlen, ps->session_id);
2022       if (ps->msgtok == NULL)
2023         ps->msgtok = GNUNET_SERVER_mst_create (&curl_receive_mst_cb, ps);
2024       GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
2025 /* FIXME */
2026
2027       GNUNET_STATISTICS_update (plugin->env->stats,
2028                             gettext_noop ("# HTTP outbound sessions for peers active"),
2029                             1,
2030                             GNUNET_NO);
2031     }
2032     else
2033     {
2034 #if DEBUG_HTTP
2035       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing session found & and no address given: no way to send this message to peer `%s'!\n", GNUNET_i2s(target));
2036 #endif
2037       return GNUNET_SYSERR;
2038     }
2039   }
2040
2041   /* create msg */
2042   msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size);
2043   msg->next = NULL;
2044   msg->size = msgbuf_size;
2045   msg->pos = 0;
2046   msg->buf = (char *) &msg[1];
2047   msg->transmit_cont = cont;
2048   msg->transmit_cont_cls = cont_cls;
2049   memcpy (msg->buf,msgbuf, msgbuf_size);
2050   GNUNET_CONTAINER_DLL_insert(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
2051
2052   if (send_check_connections (plugin, ps) != GNUNET_SYSERR)
2053   {
2054           if (force_address != GNUNET_YES)
2055                   pc->last_session = ps;
2056
2057           if (pc->last_session==NULL)
2058                   pc->last_session = ps;
2059           return msg->size;
2060   }
2061   else
2062           return GNUNET_SYSERR;
2063 }
2064
2065
2066
2067 /**
2068  * Function that can be used to force the plugin to disconnect
2069  * from the given peer and cancel all previous transmissions
2070  * (and their continuationc).
2071  *
2072  * @param cls closure
2073  * @param target peer from which to disconnect
2074  */
2075 /**
2076  * Convert the transports address to a nice, human-readable
2077  * format.
2078  *
2079  * @param cls closure
2080  * @param type name of the transport that generated the address
2081  * @param addr one of the addresses of the host, NULL for the last address
2082  *        the specific address format depends on the transport
2083  * @param addrlen length of the address
2084  * @param numeric should (IP) addresses be displayed in numeric form?
2085  * @param timeout after how long should we give up?
2086  * @param asc function to call on each string
2087  * @param asc_cls closure for asc
2088  */
2089 static void
2090 http_plugin_address_pretty_printer (void *cls,
2091                                         const char *type,
2092                                         const void *addr,
2093                                         size_t addrlen,
2094                                         int numeric,
2095                                         struct GNUNET_TIME_Relative timeout,
2096                                         GNUNET_TRANSPORT_AddressStringCallback
2097                                         asc, void *asc_cls)
2098 {
2099   const struct IPv4HttpAddress *t4;
2100   const struct IPv6HttpAddress *t6;
2101   struct sockaddr_in a4;
2102   struct sockaddr_in6 a6;
2103   char * address;
2104   char * ret;
2105   unsigned int port;
2106   unsigned int res;
2107
2108   GNUNET_assert(cls !=NULL);
2109   if (addrlen == sizeof (struct IPv6HttpAddress))
2110   {
2111     address = GNUNET_malloc (INET6_ADDRSTRLEN);
2112     t6 = addr;
2113     a6.sin6_addr = t6->ipv6_addr;
2114     inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
2115     port = ntohs(t6->u6_port);
2116   }
2117   else if (addrlen == sizeof (struct IPv4HttpAddress))
2118   {
2119     address = GNUNET_malloc (INET_ADDRSTRLEN);
2120     t4 = addr;
2121     a4.sin_addr.s_addr =  t4->ipv4_addr;
2122     inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
2123     port = ntohs(t4->u_port);
2124   }
2125   else
2126   {
2127     /* invalid address */
2128     GNUNET_break_op (0);
2129     asc (asc_cls, NULL);
2130     return;
2131   }
2132   res = GNUNET_asprintf(&ret,"http://%s:%u/",address,port);
2133   GNUNET_free (address);
2134   GNUNET_assert(res != 0);
2135   asc (asc_cls, ret);
2136   GNUNET_free_non_null (ret);
2137 }
2138
2139
2140
2141 /**
2142  * Another peer has suggested an address for this
2143  * peer and transport plugin.  Check that this could be a valid
2144  * address.  If so, consider adding it to the list
2145  * of addresses.
2146  *
2147  * @param cls closure
2148  * @param addr pointer to the address
2149  * @param addrlen length of addr
2150  * @return GNUNET_OK if this is a plausible address for this peer
2151  *         and transport
2152  */
2153 static int
2154 http_plugin_address_suggested (void *cls,
2155                                const void *addr, size_t addrlen)
2156 {
2157   struct Plugin *plugin = cls;
2158   struct IPv4HttpAddress *v4;
2159   struct IPv6HttpAddress *v6;
2160   unsigned int port;
2161
2162   GNUNET_assert(cls !=NULL);
2163   if ((addrlen != sizeof (struct IPv4HttpAddress)) &&
2164       (addrlen != sizeof (struct IPv6HttpAddress)))
2165     {
2166       return GNUNET_SYSERR;
2167     }
2168   if (addrlen == sizeof (struct IPv4HttpAddress))
2169     {
2170       v4 = (struct IPv4HttpAddress *) addr;
2171       /* Not skipping loopback
2172       if (INADDR_LOOPBACK == ntohl(v4->ipv4_addr))
2173       {
2174         return GNUNET_SYSERR;
2175       } */
2176       port = ntohs (v4->u_port);
2177       if (port != plugin->port_inbound)
2178       {
2179         return GNUNET_SYSERR;
2180       }
2181     }
2182   if (addrlen == sizeof (struct IPv6HttpAddress))
2183     {
2184       v6 = (struct IPv6HttpAddress *) addr;
2185       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
2186         {
2187           return GNUNET_SYSERR;
2188         }
2189       port = ntohs (v6->u6_port);
2190       if (port != plugin->port_inbound)
2191       {
2192         return GNUNET_SYSERR;
2193       }
2194     }
2195
2196   return GNUNET_OK;
2197 }
2198
2199
2200 /**
2201  * Function called for a quick conversion of the binary address to
2202  * a numeric address.  Note that the caller must not free the
2203  * address and that the next call to this function is allowed
2204  * to override the address again.
2205  *
2206  * @param cls closure
2207  * @param addr binary address
2208  * @param addrlen length of the address
2209  * @return string representing the same address
2210  */
2211 static const char*
2212 http_plugin_address_to_string (void *cls,
2213                                    const void *addr,
2214                                    size_t addrlen)
2215 {
2216   const struct IPv4HttpAddress *t4;
2217   const struct IPv6HttpAddress *t6;
2218   struct sockaddr_in a4;
2219   struct sockaddr_in6 a6;
2220   char * address;
2221   char * ret;
2222   uint16_t port;
2223   unsigned int res;
2224
2225   if (addrlen == sizeof (struct IPv6HttpAddress))
2226     {
2227       address = GNUNET_malloc (INET6_ADDRSTRLEN);
2228       t6 = addr;
2229       a6.sin6_addr = t6->ipv6_addr;
2230       inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
2231       port = ntohs(t6->u6_port);
2232     }
2233   else if (addrlen == sizeof (struct IPv4HttpAddress))
2234     {
2235       address = GNUNET_malloc (INET_ADDRSTRLEN);
2236       t4 = addr;
2237       a4.sin_addr.s_addr =  t4->ipv4_addr;
2238       inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
2239       port = ntohs(t4->u_port);
2240     }
2241   else
2242     {
2243       /* invalid address */
2244       return NULL;
2245     }
2246   res = GNUNET_asprintf(&ret,"%s:%u",address,port);
2247   GNUNET_free (address);
2248   GNUNET_assert(res != 0);
2249   return ret;
2250 }
2251
2252 static char *
2253 load_certificate( const char * file )
2254 {
2255   struct GNUNET_DISK_FileHandle * gn_file;
2256
2257   struct stat fstat;
2258   char * text = NULL;
2259
2260   if (0!=STAT(file, &fstat))
2261           return NULL;
2262   text = GNUNET_malloc (fstat.st_size);
2263   gn_file = GNUNET_DISK_file_open(file,GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_USER_READ);
2264   if (gn_file==NULL)
2265   {
2266           GNUNET_free(text);
2267           return NULL;
2268   }
2269   if (GNUNET_SYSERR == GNUNET_DISK_file_read(gn_file, text, fstat.st_size))
2270   {
2271           GNUNET_free(text);
2272           return NULL;
2273   }
2274   text[fstat.st_size] = '\0';
2275   GNUNET_DISK_file_close(gn_file);
2276
2277   return text;
2278 }
2279
2280
2281 /**
2282  * Exit point from the plugin.
2283  */
2284 void *
2285 libgnunet_plugin_transport_https_done (void *cls)
2286 {
2287   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2288   struct Plugin *plugin = api->cls;
2289   CURLMcode mret;
2290   GNUNET_assert(cls !=NULL);
2291
2292   if (plugin->http_server_daemon_v4 != NULL)
2293   {
2294     MHD_stop_daemon (plugin->http_server_daemon_v4);
2295     plugin->http_server_daemon_v4 = NULL;
2296   }
2297   if (plugin->http_server_daemon_v6 != NULL)
2298   {
2299     MHD_stop_daemon (plugin->http_server_daemon_v6);
2300     plugin->http_server_daemon_v6 = NULL;
2301   }
2302
2303   if ( plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
2304   {
2305     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
2306     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
2307   }
2308
2309   if ( plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
2310   {
2311     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
2312     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
2313   }
2314
2315
2316   /* free all peer information */
2317   if (plugin->peers!=NULL)
2318   {
2319           GNUNET_CONTAINER_multihashmap_iterate (plugin->peers,
2320                                                                                          &remove_peer_context_Iterator,
2321                                                                                          plugin);
2322           GNUNET_CONTAINER_multihashmap_destroy (plugin->peers);
2323   }
2324   if (plugin->multi_handle!=NULL)
2325   {
2326           mret = curl_multi_cleanup(plugin->multi_handle);
2327 #if DEBUG_HTTP
2328           if ( CURLM_OK != mret)
2329                 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed\n");
2330 #endif
2331           plugin->multi_handle = NULL;
2332   }
2333   curl_global_cleanup();
2334
2335   if ( plugin->http_curl_task != GNUNET_SCHEDULER_NO_TASK)
2336   {
2337     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_curl_task);
2338     plugin->http_curl_task = GNUNET_SCHEDULER_NO_TASK;
2339   }
2340
2341   GNUNET_free_non_null (plugin->bind4_address);
2342   GNUNET_free_non_null (plugin->bind6_address);
2343   GNUNET_free_non_null(plugin->bind_hostname);
2344   GNUNET_free (plugin);
2345   GNUNET_free (api);
2346 #if DEBUG_HTTP
2347   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unload http plugin complete...\n");
2348 #endif
2349   return NULL;
2350 }
2351
2352
2353 /**
2354  * Entry point for the plugin.
2355  */
2356 void *
2357 libgnunet_plugin_transport_https_init (void *cls)
2358 {
2359   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2360   struct Plugin *plugin;
2361   struct GNUNET_TRANSPORT_PluginFunctions *api;
2362   struct GNUNET_TIME_Relative gn_timeout;
2363   long long unsigned int port;
2364
2365   char * key_file;
2366   char * cert_file;
2367
2368   GNUNET_assert(cls !=NULL);
2369 #if DEBUG_HTTP
2370   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting https plugin...\n");
2371 #endif
2372
2373   plugin = GNUNET_malloc (sizeof (struct Plugin));
2374   plugin->stats = env->stats;
2375   plugin->env = env;
2376   plugin->peers = NULL;
2377   plugin->bind4_address = NULL;
2378   plugin->use_ipv6  = GNUNET_YES;
2379   plugin->use_ipv4  = GNUNET_YES;
2380
2381   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2382   api->cls = plugin;
2383   api->send = &http_plugin_send;
2384   api->disconnect = &http_plugin_disconnect;
2385   api->address_pretty_printer = &http_plugin_address_pretty_printer;
2386   api->check_address = &http_plugin_address_suggested;
2387   api->address_to_string = &http_plugin_address_to_string;
2388
2389   /* Hashing our identity to use it in URLs */
2390   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &plugin->my_ascii_hash_ident);
2391
2392   /* Use IPv6 yes/no */
2393   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2394                                                                    "transport-https", "USE_IPv6"))
2395     {
2396           plugin->use_ipv6 = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2397                                                                                                            "transport-https",
2398                                                                                                            "USE_IPv6");
2399     }
2400   /* Use IPv4 yes/no */
2401   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2402                                                                    "transport-https", "USE_IPv4"))
2403     {
2404           plugin->use_ipv4 = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2405                                                                                                            "transport-https",
2406                                                                                                            "USE_IPv4");
2407     }
2408   /* Reading port number from config file */
2409   if ((GNUNET_OK !=
2410        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2411                                               "transport-https",
2412                                               "PORT",
2413                                               &port)) ||
2414       (port > 65535) )
2415     {
2416       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2417                        "http",
2418                        _("Require valid port number for transport plugin `%s' in configuration!\n"),
2419                        "transport-https");
2420       libgnunet_plugin_transport_https_done (api);
2421       return NULL;
2422     }
2423
2424   /* Reading ipv4 addresse to bind to from config file */
2425   if ((plugin->use_ipv4==GNUNET_YES) && (GNUNET_CONFIGURATION_have_value (env->cfg,
2426                                                                    "transport-https", "BINDTO4")))
2427   {
2428           GNUNET_break (GNUNET_OK ==
2429                                         GNUNET_CONFIGURATION_get_value_string (env->cfg,
2430                                                                                                                    "transport-https",
2431                                                                                                                    "BINDTO4",
2432                                                                                                                    &plugin->bind_hostname));
2433           plugin->bind4_address = GNUNET_malloc(sizeof(struct sockaddr_in));
2434           plugin->bind4_address->sin_family = AF_INET;
2435           plugin->bind4_address->sin_port = htons (port);
2436
2437           if (inet_pton(AF_INET,plugin->bind_hostname, &plugin->bind4_address->sin_addr)<=0)
2438           {
2439                   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2440                                                    "http",
2441                                                    _("Misconfigured address to bind to in configuration!\n"),
2442                                                    "transport-https");
2443                   GNUNET_free(plugin->bind4_address);
2444                   GNUNET_free(plugin->bind_hostname);
2445                   plugin->bind_hostname = NULL;
2446                   plugin->bind4_address = NULL;
2447           }
2448   }
2449
2450   /* Get private key file from config */
2451   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2452                                                                            "transport-https", "KEY_FILE"))
2453   {
2454                 GNUNET_CONFIGURATION_get_value_string (env->cfg,
2455                                                                                            "transport-https",
2456                                                                                            "KEY_FILE",
2457                                                                                            &key_file);
2458   }
2459   else
2460   {
2461           GNUNET_asprintf(&key_file,"https.key");
2462   }
2463
2464   /* Get private key file from config */
2465   if (GNUNET_CONFIGURATION_have_value (env->cfg,
2466                                                                            "transport-https", "CERT_FILE"))
2467   {
2468           GNUNET_CONFIGURATION_get_value_string (env->cfg,
2469                                                                                          "transport-https",
2470                                                                                      "CERT_FILE",
2471                                                                                      &cert_file);
2472   }
2473   else
2474   {
2475           GNUNET_asprintf(&cert_file,"https.cert");
2476   }
2477
2478   /* Reading ipv4 addresse to bind to from config file */
2479   if ((plugin->use_ipv6==GNUNET_YES) && (GNUNET_CONFIGURATION_have_value (env->cfg,
2480                                                                    "transport-https", "BINDTO6")))
2481   {
2482           GNUNET_break (GNUNET_OK ==
2483                                         GNUNET_CONFIGURATION_get_value_string (env->cfg,
2484                                                                                                                    "transport-https",
2485                                                                                                                    "BINDTO6",
2486                                                                                                                    &plugin->bind_hostname));
2487
2488           plugin->bind6_address = GNUNET_malloc(sizeof(struct sockaddr_in6));
2489           plugin->bind6_address->sin6_family = AF_INET6;
2490           plugin->bind6_address->sin6_port = htons (port);
2491
2492       if (inet_pton(AF_INET6,plugin->bind_hostname, &plugin->bind6_address->sin6_addr)<=0)
2493           {
2494                   GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2495                                                    "http",
2496                                                    _("Misconfigured address to bind to in configuration!\n"),
2497                                                    "transport-https");
2498                   GNUNET_free(plugin->bind6_address);
2499                   GNUNET_free(plugin->bind_hostname);
2500                   plugin->bind_hostname = NULL;
2501                   plugin->bind6_address = NULL;
2502           }
2503   }
2504
2505   /* read key & certificates from file */
2506   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Loading TLS certificate `%s' `%s'\n", key_file, cert_file);
2507
2508   plugin->key = load_certificate( key_file );
2509   plugin->cert = load_certificate( cert_file );
2510
2511   if ((plugin->key==NULL) || (plugin->cert==NULL))
2512   {
2513           char * cmd;
2514           GNUNET_asprintf(&cmd,"gnunet-transport-certificate-creation %s %s", key_file, cert_file);
2515           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No usable TLS certificate found, creating certificate \n");
2516           system(cmd);
2517           GNUNET_free (cmd);
2518
2519           plugin->key = load_certificate( key_file );
2520           plugin->cert = load_certificate( cert_file );
2521
2522           if ((plugin->key==NULL) || (plugin->cert==NULL))
2523           {
2524                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No usable TLS certificate found and creating one failed! \n");
2525                   GNUNET_free (key_file);
2526                   GNUNET_free (cert_file);
2527                   libgnunet_plugin_transport_https_done(api);
2528                   return NULL;
2529           }
2530   }
2531
2532   GNUNET_free (key_file);
2533   GNUNET_free (cert_file);
2534
2535
2536   GNUNET_assert((plugin->key!=NULL) && (plugin->cert!=NULL));
2537   GNUNET_assert ((port > 0) && (port <= 65535));
2538   plugin->port_inbound = port;
2539   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
2540   unsigned int timeout = (gn_timeout.value) / 1000;
2541   if ((plugin->http_server_daemon_v6 == NULL) && (plugin->use_ipv6 == GNUNET_YES) && (port != 0))
2542   {
2543         struct sockaddr * tmp = (struct sockaddr *) plugin->bind6_address;
2544     plugin->http_server_daemon_v6 = MHD_start_daemon (
2545 #if DEBUG_CONNECTIONS
2546                                                                    MHD_USE_DEBUG |
2547 #endif
2548                                                                    MHD_USE_IPv6 | MHD_USE_SSL,
2549                                        port,
2550                                        &mhd_accept_cb,
2551                                        plugin , &mdh_access_cb, plugin,
2552                                        MHD_OPTION_HTTPS_MEM_KEY, plugin->key,
2553                                        MHD_OPTION_HTTPS_MEM_CERT, plugin->cert,
2554                                        MHD_OPTION_SOCK_ADDR, tmp,
2555                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 32,
2556                                        //MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 6,
2557                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) timeout,
2558                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
2559                                        MHD_OPTION_NOTIFY_COMPLETED, &mhd_termination_cb, NULL,
2560                                        MHD_OPTION_END);
2561   }
2562   if ((plugin->http_server_daemon_v4 == NULL) && (plugin->use_ipv4 == GNUNET_YES) && (port != 0))
2563   {
2564   plugin->http_server_daemon_v4 = MHD_start_daemon (
2565 #if DEBUG_CONNECTIONS
2566                                                                    MHD_USE_DEBUG |
2567 #endif
2568                                                                    MHD_NO_FLAG | MHD_USE_SSL,
2569                                        port,
2570                                        &mhd_accept_cb,
2571                                        plugin , &mdh_access_cb, plugin,
2572                                        MHD_OPTION_HTTPS_MEM_KEY, plugin->key,
2573                                        MHD_OPTION_HTTPS_MEM_CERT, plugin->cert,
2574                                        MHD_OPTION_SOCK_ADDR, (struct sockaddr_in *)plugin->bind4_address,
2575                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 32,
2576                                        //MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 6,
2577                                        MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) timeout,
2578                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
2579                                        MHD_OPTION_NOTIFY_COMPLETED, &mhd_termination_cb, NULL,
2580                                        MHD_OPTION_END);
2581   }
2582   if (plugin->http_server_daemon_v4 != NULL)
2583     plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
2584   if (plugin->http_server_daemon_v6 != NULL)
2585     plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
2586
2587
2588   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
2589   {
2590 #if DEBUG_HTTP
2591           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 bound to %s with port %u\n",(plugin->bind_hostname!=NULL) ? plugin->bind_hostname : "every address",port);
2592 #endif
2593   }
2594   else if ((plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK) && (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK))
2595   {
2596 #if DEBUG_HTTP
2597     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv6 bound to %s with port %u\n",(plugin->bind_hostname!=NULL) ? plugin->bind_hostname : "every address", port);
2598 #endif
2599   }
2600   else if ((plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK) && (plugin->http_server_task_v4 == GNUNET_SCHEDULER_NO_TASK))
2601   {
2602 #if DEBUG_HTTP
2603     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 bound to %s with port %u\n",(plugin->bind_hostname!=NULL) ? plugin->bind_hostname : "every address", port);
2604 #endif
2605   }
2606   else
2607   {
2608 #if DEBUG_HTTP
2609     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No MHD was started, transport plugin not functional!\n");
2610 #endif
2611     libgnunet_plugin_transport_https_done (api);
2612     return NULL;
2613   }
2614
2615   /* Initializing cURL */
2616   curl_global_init(CURL_GLOBAL_ALL);
2617   plugin->multi_handle = curl_multi_init();
2618
2619   if ( NULL == plugin->multi_handle )
2620   {
2621     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2622                                    "http",
2623                                    _("Could not initialize curl multi handle, failed to start http plugin!\n"),
2624                                    "transport-https");
2625     libgnunet_plugin_transport_https_done (api);
2626     return NULL;
2627   }
2628
2629   plugin->peers = GNUNET_CONTAINER_multihashmap_create (10);
2630   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2631
2632   return api;
2633 }
2634
2635 /* end of plugin_transport_http.c */