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