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