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