9f0f13e1c5c7d52f8d437fff8eb8de593492dc2c
[oweals/gnunet.git] / src / transport / plugin_transport_http.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_http.c
23  * @brief http transport service plugin
24  * @author Matthias Wachs
25  */
26
27 #include "platform.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_connection_lib.h"
31 #include "gnunet_service_lib.h"
32 #include "gnunet_statistics_service.h"
33 #include "gnunet_transport_service.h"
34 #include "gnunet_resolver_service.h"
35 #include "gnunet_server_lib.h"
36 #include "gnunet_container_lib.h"
37 #include "plugin_transport.h"
38 #include "gnunet_os_lib.h"
39 #include "microhttpd.h"
40 #include <curl/curl.h>
41
42
43 #define DEBUG_CURL GNUNET_NO
44 #define DEBUG_HTTP GNUNET_NO
45 #define DEBUG_CONNECTIONS GNUNET_YES
46
47 #define INBOUND GNUNET_NO
48 #define OUTBOUND GNUNET_YES
49
50 /**
51  * Text of the response sent back after the last bytes of a PUT
52  * request have been received (just to formally obey the HTTP
53  * protocol).
54  */
55 #define HTTP_PUT_RESPONSE "Thank you!"
56
57 /**
58  * After how long do we expire an address that we
59  * learned from another peer if it is not reconfirmed
60  * by anyone?
61  */
62 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
63
64 /**
65  * Page returned if request invalid
66  */
67 #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>"
68
69 /**
70  * Timeout for a http connect
71  */
72 #define HTTP_CONNECT_TIMEOUT 30
73
74 /**
75  * Network format for IPv4 addresses.
76  */
77 struct IPv4HttpAddress
78 {
79   /**
80    * IPv4 address, in network byte order.
81    */
82   uint32_t ipv4_addr GNUNET_PACKED;
83
84   /**
85    * Port number, in network byte order.
86    */
87   uint16_t u_port GNUNET_PACKED;
88
89 };
90
91
92 /**
93  * Network format for IPv6 addresses.
94  */
95 struct IPv6HttpAddress
96 {
97   /**
98    * IPv6 address.
99    */
100   struct in6_addr ipv6_addr GNUNET_PACKED;
101
102   /**
103    * Port number, in network byte order.
104    */
105   uint16_t u6_port GNUNET_PACKED;
106
107 };
108
109
110 /**
111  *  Message to send using http
112  */
113 struct HTTP_Message
114 {
115   /**
116    * next pointer for double linked list
117    */
118   struct HTTP_Message * next;
119
120   /**
121    * previous pointer for double linked list
122    */
123   struct HTTP_Message * prev;
124
125   /**
126    * buffer containing data to send
127    */
128   char *buf;
129
130   /**
131    * amount of data already sent
132    */
133   size_t pos;
134
135   /**
136    * buffer length
137    */
138   size_t size;
139
140   /**
141    * Continuation function to call once the transmission buffer
142    * has again space available.  NULL if there is no
143    * continuation to call.
144    */
145   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
146
147   /**
148    * Closure for transmit_cont.
149    */
150   void *transmit_cont_cls;
151 };
152
153
154 struct HTTP_PeerContext
155 {
156   /**
157    * peer's identity
158    */
159   struct GNUNET_PeerIdentity identity;
160
161   /**
162    * Pointer to the global plugin struct.
163    */
164   struct Plugin *plugin;
165
166   /**
167    * Linked list of connections with this peer
168    * head
169    */
170   struct Session * head;
171
172   /**
173    * Linked list of connections with this peer
174    * tail
175    */
176   struct Session * tail;
177
178   /**
179    * id for next session
180    */
181   size_t session_id_counter;
182 };
183
184
185 struct Session
186 {
187   /**
188    * API requirement.
189    */
190   struct SessionHeader header;
191
192   /**
193    * next session in linked list
194    */
195   struct Session * next;
196
197   /**
198    * previous session in linked list
199    */
200   struct Session * prev;
201
202   /**
203    * address of this session
204    */
205   void * addr;
206
207   /**
208    * address length
209    */
210   size_t addrlen;
211
212   /**
213    * target url
214    */
215   char * url;
216
217   /**
218    * Message queue for outbound messages
219    * head of queue
220    */
221   struct HTTP_Message * pending_msgs_head;
222
223   /**
224    * Message queue for outbound messages
225    * tail of queue
226    */
227   struct HTTP_Message * pending_msgs_tail;
228
229   /**
230    * partner peer this connection belongs to
231    */
232   struct HTTP_PeerContext * peercontext;
233
234   /**
235    * message stream tokenizer for incoming data
236    */
237   struct GNUNET_SERVER_MessageStreamTokenizer *msgtok;
238
239   /**
240    * session direction
241    * outbound: OUTBOUND (GNUNET_YES)
242    * inbound : INBOUND (GNUNET_NO)
243    */
244   unsigned int direction;
245
246   /**
247    * is session connected to send data?
248    */
249   unsigned int send_connected;
250
251   /**
252    * is send connection active?
253    */
254   unsigned int send_active;
255
256   /**
257    * connection disconnect forced (e.g. from transport)
258    */
259   unsigned int send_force_disconnect;
260
261   /**
262    * is session connected to receive data?
263    */
264   unsigned int recv_connected;
265
266   /**
267    * is receive connection active?
268    */
269   unsigned int recv_active;
270
271   /**
272    * connection disconnect forced (e.g. from transport)
273    */
274   unsigned int recv_force_disconnect;
275
276   /**
277    * id for next session
278    */
279   size_t session_id;
280
281   /**
282    * entity managing sending data
283    * outbound session: pointer to curl easy handle
284    */
285   void * send_endpoint;
286
287   /**
288    * entity managing recieving data
289    * outbound session: pointer to curl easy handle
290    */
291   void * recv_endpoint;
292 };
293
294 /**
295  * Encapsulation of all of the state of the plugin.
296  */
297 struct Plugin
298 {
299   /**
300    * Our environment.
301    */
302   struct GNUNET_TRANSPORT_PluginEnvironment *env;
303
304   unsigned int port_inbound;
305
306   struct GNUNET_CONTAINER_MultiHashMap *peers;
307
308   /**
309    * Daemon for listening for new IPv4 connections.
310    */
311   struct MHD_Daemon *http_server_daemon_v4;
312
313   /**
314    * Daemon for listening for new IPv6connections.
315    */
316   struct MHD_Daemon *http_server_daemon_v6;
317
318   /**
319    * Our primary task for http daemon handling IPv4 connections
320    */
321   GNUNET_SCHEDULER_TaskIdentifier http_server_task_v4;
322
323   /**
324    * Our primary task for http daemon handling IPv6 connections
325    */
326   GNUNET_SCHEDULER_TaskIdentifier http_server_task_v6;
327
328   /**
329    * The task sending data
330    */
331   GNUNET_SCHEDULER_TaskIdentifier http_server_task_send;
332
333   /**
334    * cURL Multihandle
335    */
336   CURLM * multi_handle;
337
338   /**
339    * Our ASCII encoded, hashed peer identity
340    * This string is used to distinguish between connections and is added to the urls
341    */
342   struct GNUNET_CRYPTO_HashAsciiEncoded my_ascii_hash_ident;
343 };
344
345
346 /**
347  * Function called for a quick conversion of the binary address to
348  * a numeric address.  Note that the caller must not free the
349  * address and that the next call to this function is allowed
350  * to override the address again.
351  *
352  * @param cls closure
353  * @param addr binary address
354  * @param addrlen length of the address
355  * @return string representing the same address
356  */
357 static const char*
358 http_plugin_address_to_string (void *cls,
359                                    const void *addr,
360                                    size_t addrlen);
361
362 static char * create_url(void * cls, const void * addr, size_t addrlen, size_t id)
363 {
364   struct Plugin *plugin = cls;
365   char *url = NULL;
366
367   GNUNET_assert ((addr!=NULL) && (addrlen != 0));
368   GNUNET_asprintf(&url,
369                   "http://%s/%s;%u",
370                   http_plugin_address_to_string(NULL, addr, addrlen),
371                   (char *) (&plugin->my_ascii_hash_ident),id);
372
373   return url;
374 }
375
376 /**
377  * Removes a message from the linked list of messages
378  * @param con connection to remove message from
379  * @param msg message to remove
380  * @return GNUNET_SYSERR if msg not found, GNUNET_OK on success
381  */
382
383 static int remove_http_message(struct Session * ps, struct HTTP_Message * msg)
384 {
385   GNUNET_CONTAINER_DLL_remove(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
386   GNUNET_free(msg);
387   return GNUNET_OK;
388 }
389
390 static struct Session * get_Session (void * cls, struct HTTP_PeerContext *pc, const void * addr, size_t addr_len)
391 {
392   struct Session * cc = pc->head;
393   struct Session * con = NULL;
394   unsigned int count = 0;
395
396   GNUNET_assert((addr_len == sizeof (struct IPv4HttpAddress)) || (addr_len == sizeof (struct IPv6HttpAddress)));
397   while (cc!=NULL)
398   {
399     if (addr_len == cc->addrlen)
400     {
401       if (0 == memcmp(cc->addr, addr, addr_len))
402       {
403         /* connection can not be used, since it is disconnected */
404         if ((cc->recv_force_disconnect==GNUNET_NO) && (cc->send_force_disconnect==GNUNET_NO))
405           con = cc;
406         break;
407       }
408     }
409     count++;
410     cc=cc->next;
411   }
412   return con;
413 }
414
415
416 /**
417  * Callback called by MHD when a connection is terminated
418  */
419 static void requestCompletedCallback (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
420 {
421   struct Session * ps = *httpSessionCache;
422   if (ps == NULL)
423     return;
424
425 #if DEBUG_CONNECTIONS
426   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connection from peer `%s' was terminated\n", ps, GNUNET_i2s(&ps->peercontext->identity));
427 #endif
428   /* session set to inactive */
429   //ps-> = GNUNET_NO;
430 }
431
432 static void mhd_write_mst_cb (void *cls,
433                               void *client,
434                               const struct GNUNET_MessageHeader *message)
435 {
436
437   struct Session *ps  = cls;
438   struct HTTP_PeerContext *pc = ps->peercontext;
439   GNUNET_assert(ps != NULL);
440   GNUNET_assert(pc != NULL);
441
442   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
443               "Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
444               ntohs(message->type),
445               ntohs(message->size),
446               GNUNET_i2s(&(ps->peercontext)->identity),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
447
448   pc->plugin->env->receive (ps->peercontext->plugin->env->cls,
449                             &pc->identity,
450                             message, 1, ps,
451                             ps->addr,
452                             ps->addrlen);
453 }
454
455 static void curl_write_mst_cb  (void *cls,
456                                 void *client,
457                                 const struct GNUNET_MessageHeader *message)
458 {
459   struct Session *ps  = cls;
460   struct HTTP_PeerContext *pc = ps->peercontext;
461   GNUNET_assert(ps != NULL);
462   GNUNET_assert(pc != NULL);
463
464   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
465               "Forwarding message to transport service, type %u and size %u from `%s' (`%s')\n",
466               ntohs(message->type),
467               ntohs(message->size),
468               GNUNET_i2s(&(pc->identity)),http_plugin_address_to_string(NULL,ps->addr,ps->addrlen));
469
470   pc->plugin->env->receive (pc->plugin->env->cls,
471                             &pc->identity,
472                             message, 1, ps,
473                             ps->addr,
474                             ps->addrlen);
475 }
476
477
478 /**
479  * Check if ip is allowed to connect.
480  */
481 static int
482 acceptPolicyCallback (void *cls,
483                       const struct sockaddr *addr, socklen_t addr_len)
484 {
485 #if 0
486   struct Plugin *plugin = cls;
487 #endif
488   /* Every connection is accepted, nothing more to do here */
489   return MHD_YES;
490 }
491
492 int server_read_callback (void *cls, uint64_t pos, char *buf, int max)
493 {
494   int bytes_read = 0;
495
496   struct Session * ps = cls;
497   struct HTTP_PeerContext * pc;
498   struct HTTP_Message * msg;
499   int res;res=5;
500
501   GNUNET_assert (ps!=NULL);
502   pc = ps->peercontext;
503   msg = ps->pending_msgs_tail;
504
505   if (ps->send_force_disconnect)
506   {
507 #if DEBUG_CONNECTIONS
508     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound forced to disconnect\n",ps);
509 #endif
510     return -1;
511   }
512
513   if (msg!=NULL)
514   {
515     if ((msg->size-msg->pos) <= max)
516       {
517         memcpy(buf,&msg->buf[pos],(msg->size-msg->pos));
518         pos+=(msg->size-msg->pos);
519       }
520       else
521       {
522         memcpy(buf,&msg->buf[pos],max);
523         pos+=max;
524       }
525
526       if (msg->pos==msg->size)
527       {
528         if (NULL!=msg->transmit_cont)
529           msg->transmit_cont (msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
530         res = remove_http_message(ps,msg);
531       }
532   }
533   return bytes_read;
534 }
535
536 /**
537  * Process GET or PUT request received via MHD.  For
538  * GET, queue response that will send back our pending
539  * messages.  For PUT, process incoming data and send
540  * to GNUnet core.  In either case, check if a session
541  * already exists and create a new one if not.
542  */
543 static int
544 accessHandlerCallback (void *cls,
545                        struct MHD_Connection *mhd_connection,
546                        const char *url,
547                        const char *method,
548                        const char *version,
549                        const char *upload_data,
550                        size_t * upload_data_size, void **httpSessionCache)
551 {
552   struct Plugin *plugin = cls;
553   struct MHD_Response *response;
554   const union MHD_ConnectionInfo * conn_info;
555
556   struct sockaddr_in  *addrin;
557   struct sockaddr_in6 *addrin6;
558
559   char address[INET6_ADDRSTRLEN+14];
560   struct GNUNET_PeerIdentity pi_in;
561   size_t id_num = 0;
562
563   struct IPv4HttpAddress ipv4addr;
564   struct IPv6HttpAddress ipv6addr;
565
566   struct HTTP_PeerContext *pc;
567   struct Session *ps;
568   struct Session *ps_tmp;
569
570   int res = GNUNET_NO;
571   int send_error_to_client;
572   void * addr;
573   size_t addr_len;
574
575   GNUNET_assert(cls !=NULL);
576   send_error_to_client = GNUNET_NO;
577
578   if (NULL == *httpSessionCache)
579   {
580     /* check url for peer identity , if invalid send HTTP 404*/
581     size_t len = strlen(&url[1]);
582     char * peer = GNUNET_malloc(104+1);
583
584     if ((len>104) && (url[104]==';'))
585     {
586         char * id = GNUNET_malloc((len-104)+1);
587         strcpy(id,&url[105]);
588         memcpy(peer,&url[1],103);
589         peer[103] = '\0';
590         id_num = strtoul ( id, NULL , 10);
591         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"id is string %s num %u, peer is %s\n",id,id_num,peer);
592         GNUNET_free(id);
593     }
594     res = GNUNET_CRYPTO_hash_from_string (peer, &(pi_in.hashPubKey));
595     GNUNET_free(peer);
596     if ( GNUNET_SYSERR == res )
597     {
598       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
599       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
600       MHD_destroy_response (response);
601       if (res == MHD_YES)
602         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, sent HTTP 1.1/404\n");
603       else
604         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Peer has no valid ident, could not send error\n");
605       return res;
606     }
607   }
608   else
609   {
610     ps = *httpSessionCache;
611     pc = ps->peercontext;
612   }
613
614   if (NULL == *httpSessionCache)
615   {
616     /* get peer context */
617     pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &pi_in.hashPubKey);
618     /* Peer unknown */
619     if (pc==NULL)
620     {
621       pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
622       pc->plugin = plugin;
623       pc->session_id_counter=1;
624       memcpy(&pc->identity, &pi_in, sizeof(struct GNUNET_PeerIdentity));
625       GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
626     }
627
628     conn_info = MHD_get_connection_info(mhd_connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
629     /* Incoming IPv4 connection */
630     if ( AF_INET == conn_info->client_addr->sin_family)
631     {
632       addrin = conn_info->client_addr;
633       inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
634       memcpy(&ipv4addr.ipv4_addr,&(addrin->sin_addr),sizeof(struct in_addr));
635       ipv4addr.u_port = addrin->sin_port;
636       addr = &ipv4addr;
637       addr_len = sizeof(struct IPv4HttpAddress);
638     }
639     /* Incoming IPv6 connection */
640     if ( AF_INET6 == conn_info->client_addr->sin_family)
641     {
642       addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
643       inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
644       memcpy(&ipv6addr.ipv6_addr,&(addrin6->sin6_addr),sizeof(struct in6_addr));
645       ipv6addr.u6_port = addrin6->sin6_port;
646       addr = &ipv6addr;
647       addr_len = sizeof(struct IPv6HttpAddress);
648     }
649
650
651     ps = get_Session(plugin, pc, addr, addr_len);
652
653     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"SEARCHING HTTP SESSION\n");
654     ps_tmp = pc->head;
655     /*
656     while (ps_tmp!=NULL)
657     {
658       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"SEARCHING HTTP SESSION II\n");
659       if ((ps_tmp->session_id == id_num) && (id_num!=0))
660       {
661         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP SESSION FOUND\n");
662         ps=ps_tmp;
663         break;
664       }
665       ps_tmp=ps_tmp->next;
666     }
667      */
668
669     if (ps==NULL)
670     {
671       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"NO HTTP SESSION FOUND\n");
672       ps = GNUNET_malloc(sizeof (struct Session));
673       ps->addr = GNUNET_malloc(addr_len);
674       memcpy(ps->addr,addr,addr_len);
675       ps->addrlen = addr_len;
676       ps->direction=INBOUND;
677       ps->pending_msgs_head = NULL;
678       ps->pending_msgs_tail = NULL;
679       ps->send_connected=GNUNET_NO;
680       ps->send_active=GNUNET_NO;
681       ps->recv_connected=GNUNET_NO;
682       ps->recv_active=GNUNET_NO;
683       ps->peercontext=pc;
684       ps->session_id =id_num;
685       ps->url = create_url (plugin, ps->addr, ps->addrlen, ps->session_id);
686       GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
687     }
688
689     *httpSessionCache = ps;
690     if (ps->msgtok==NULL)
691       ps->msgtok = GNUNET_SERVER_mst_create (&mhd_write_mst_cb, ps);
692
693     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has new an incoming `%s' request from peer `%s' (`%s')\n",
694                 method,
695                 GNUNET_i2s(&pc->identity),
696                 http_plugin_address_to_string(NULL, ps->addr, ps->addrlen));
697   }
698
699   /* Is it a PUT or a GET request */
700   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
701   {
702     if (ps->recv_force_disconnect)
703     {
704 #if DEBUG_CONNECTIONS
705       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound forced to disconnect\n",ps);
706 #endif
707       ps->recv_connected = GNUNET_NO;
708       ps->recv_active = GNUNET_NO;
709       return MHD_NO;
710     }
711     if ((*upload_data_size == 0) && (ps->recv_active==GNUNET_NO))
712     {
713       ps->recv_active = GNUNET_YES;
714       return MHD_YES;
715     }
716
717     /* Transmission of all data complete */
718     if ((*upload_data_size == 0) && (ps->recv_active == GNUNET_YES))
719     {
720       response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
721       res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
722 #if DEBUG_CONNECTIONS
723       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Sent HTTP/1.1: 200 OK as PUT Response\n",ps);
724 #endif
725       MHD_destroy_response (response);
726       ps->recv_active=GNUNET_NO;
727       return MHD_YES;
728     }
729
730     /* Recieving data */
731     if ((*upload_data_size > 0) && (ps->recv_active == GNUNET_YES))
732     {
733       res = GNUNET_SERVER_mst_receive(ps->msgtok, ps, upload_data,*upload_data_size, GNUNET_NO, GNUNET_NO);
734       (*upload_data_size) = 0;
735       return MHD_YES;
736     }
737     else
738       return MHD_NO;
739   }
740   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
741   {
742     if (ps->send_force_disconnect)
743     {
744 #if DEBUG_CONNECTIONS
745       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound forced to disconnect\n",ps);
746 #endif
747       ps->send_connected = GNUNET_NO;
748       ps->send_active = GNUNET_NO;
749       return MHD_NO;
750     }
751     response = MHD_create_response_from_callback(-1,32 * 1024, &server_read_callback, ps, NULL);
752     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
753     MHD_destroy_response (response);
754     return res;
755   }
756   return MHD_NO;
757 }
758
759
760 /**
761  * Call MHD to process pending ipv4 requests and then go back
762  * and schedule the next run.
763  */
764 static void http_server_daemon_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
765 /**
766  * Call MHD to process pending ipv6 requests and then go back
767  * and schedule the next run.
768  */
769 static void http_server_daemon_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
770
771 /**
772  * Function that queries MHD's select sets and
773  * starts the task waiting for them.
774  */
775 static GNUNET_SCHEDULER_TaskIdentifier
776 http_server_daemon_prepare (void * cls, struct MHD_Daemon *daemon_handle)
777 {
778   struct Plugin *plugin = cls;
779   GNUNET_SCHEDULER_TaskIdentifier ret;
780   fd_set rs;
781   fd_set ws;
782   fd_set es;
783   struct GNUNET_NETWORK_FDSet *wrs;
784   struct GNUNET_NETWORK_FDSet *wws;
785   struct GNUNET_NETWORK_FDSet *wes;
786   int max;
787   unsigned long long timeout;
788   int haveto;
789   struct GNUNET_TIME_Relative tv;
790
791   GNUNET_assert(cls !=NULL);
792   ret = GNUNET_SCHEDULER_NO_TASK;
793   FD_ZERO(&rs);
794   FD_ZERO(&ws);
795   FD_ZERO(&es);
796   wrs = GNUNET_NETWORK_fdset_create ();
797   wes = GNUNET_NETWORK_fdset_create ();
798   wws = GNUNET_NETWORK_fdset_create ();
799   max = -1;
800   GNUNET_assert (MHD_YES ==
801                  MHD_get_fdset (daemon_handle,
802                                 &rs,
803                                 &ws,
804                                 &es,
805                                 &max));
806   haveto = MHD_get_timeout (daemon_handle, &timeout);
807   if (haveto == MHD_YES)
808     tv.value = (uint64_t) timeout;
809   else
810     tv = GNUNET_TIME_UNIT_FOREVER_REL;
811   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
812   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
813   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
814   if (daemon_handle == plugin->http_server_daemon_v4)
815   {
816     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
817                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
818                                        GNUNET_SCHEDULER_NO_TASK,
819                                        tv,
820                                        wrs,
821                                        wws,
822                                        &http_server_daemon_v4_run,
823                                        plugin);
824   }
825   if (daemon_handle == plugin->http_server_daemon_v6)
826   {
827     ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
828                                        GNUNET_SCHEDULER_PRIORITY_DEFAULT,
829                                        GNUNET_SCHEDULER_NO_TASK,
830                                        tv,
831                                        wrs,
832                                        wws,
833                                        &http_server_daemon_v6_run,
834                                        plugin);
835   }
836   GNUNET_NETWORK_fdset_destroy (wrs);
837   GNUNET_NETWORK_fdset_destroy (wws);
838   GNUNET_NETWORK_fdset_destroy (wes);
839   return ret;
840 }
841
842 /**
843  * Call MHD to process pending requests and then go back
844  * and schedule the next run.
845  */
846 static void http_server_daemon_v4_run (void *cls,
847                              const struct GNUNET_SCHEDULER_TaskContext *tc)
848 {
849   struct Plugin *plugin = cls;
850
851   GNUNET_assert(cls !=NULL);
852   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
853     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
854
855   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
856     return;
857
858   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v4));
859   plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
860   return;
861 }
862
863
864 /**
865  * Call MHD to process pending requests and then go back
866  * and schedule the next run.
867  */
868 static void http_server_daemon_v6_run (void *cls,
869                              const struct GNUNET_SCHEDULER_TaskContext *tc)
870 {
871   struct Plugin *plugin = cls;
872
873   GNUNET_assert(cls !=NULL);
874   if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
875     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
876
877   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
878     return;
879
880   GNUNET_assert (MHD_YES == MHD_run (plugin->http_server_daemon_v6));
881   plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
882   return;
883 }
884
885 /**
886  * Function setting up curl handle and selecting message to send
887  * @param cls plugin
888  * @param ses session to send data to
889  * @param con connection
890  * @return bytes sent to peer
891  */
892 static ssize_t send_check_connections (void *cls, struct Session *ps);
893
894 static size_t curl_get_header_function( void *ptr, size_t size, size_t nmemb, void *stream)
895 {
896   struct Session * ps = stream;
897
898   char * tmp;
899   size_t len = size * nmemb;
900   long http_result = 0;
901   int res;
902   /* Getting last http result code */
903   if (ps->recv_connected==GNUNET_NO)
904   {
905     GNUNET_assert(NULL!=ps);
906     res = curl_easy_getinfo(ps->recv_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
907     if (CURLE_OK == res)
908     {
909       if (http_result == 200)
910       {
911         ps->recv_connected = GNUNET_YES;
912         ps->recv_active = GNUNET_YES;
913 #if DEBUG_CONNECTIONS
914         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to recieve data\n",ps);
915 #endif
916         // Calling send_check_connections again since receive is established
917         send_check_connections (ps->peercontext->plugin, ps);
918       }
919     }
920   }
921
922   tmp = NULL;
923   if ((size * nmemb) < SIZE_MAX)
924     tmp = GNUNET_malloc (len+1);
925
926   if ((tmp != NULL) && (len > 0))
927   {
928     memcpy(tmp,ptr,len);
929     if (len>=2)
930     {
931       if (tmp[len-2] == 13)
932         tmp[len-2]= '\0';
933     }
934 #if DEBUG_HTTP
935     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Header: `%s' %u \n",tmp, http_result);
936 #endif
937   }
938   if (NULL != tmp)
939     GNUNET_free (tmp);
940
941   return size * nmemb;
942 }
943
944 static size_t curl_put_header_function( void *ptr, size_t size, size_t nmemb, void *stream)
945 {
946   struct Session * ps = stream;
947
948   char * tmp;
949   size_t len = size * nmemb;
950   long http_result = 0;
951   int res;
952
953   /* Getting last http result code */
954   GNUNET_assert(NULL!=ps);
955   res = curl_easy_getinfo(ps->send_endpoint, CURLINFO_RESPONSE_CODE, &http_result);
956   if (CURLE_OK == res)
957   {
958     if ((http_result == 100) && (ps->send_connected==GNUNET_NO))
959     {
960       ps->send_connected = GNUNET_YES;
961       ps->send_active = GNUNET_YES;
962 #if DEBUG_CONNECTIONS
963       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: connected to send data\n",ps);
964 #endif
965     }
966     if ((http_result == 200) && (ps->send_connected==GNUNET_YES))
967     {
968       ps->send_connected = GNUNET_NO;
969       ps->send_active = GNUNET_NO;
970 #if DEBUG_CONNECTIONS
971       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: sending disconnected\n",ps);
972 #endif
973     }
974   }
975
976   tmp = NULL;
977   if ((size * nmemb) < SIZE_MAX)
978     tmp = GNUNET_malloc (len+1);
979
980   if ((tmp != NULL) && (len > 0))
981   {
982     memcpy(tmp,ptr,len);
983     if (len>=2)
984     {
985       if (tmp[len-2] == 13)
986         tmp[len-2]= '\0';
987     }
988 #if DEBUG_HTTP
989     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Header: `%s' %u \n",tmp, http_result);
990 #endif
991   }
992   if (NULL != tmp)
993     GNUNET_free (tmp);
994
995   return size * nmemb;
996 }
997
998 /**
999  * Callback method used with libcurl
1000  * Method is called when libcurl needs to read data during sending
1001  * @param stream pointer where to write data
1002  * @param size size of an individual element
1003  * @param nmemb count of elements that can be written to the buffer
1004  * @param ptr source pointer, passed to the libcurl handle
1005  * @return bytes written to stream
1006  */
1007 static size_t send_curl_send_callback(void *stream, size_t size, size_t nmemb, void *ptr)
1008 {
1009   struct Session * ps = ptr;
1010   struct HTTP_Message * msg = ps->pending_msgs_tail;
1011   size_t bytes_sent;
1012   size_t len;
1013
1014   if (ps->pending_msgs_tail == NULL)
1015   {
1016 #if DEBUG_CONNECTIONS
1017     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: No Message to send, pausing connection\n",ps);
1018 #endif
1019     ps->send_active = GNUNET_NO;
1020     return CURL_READFUNC_PAUSE;
1021   }
1022
1023   msg = ps->pending_msgs_tail;
1024   /* data to send */
1025   if (msg->pos < msg->size)
1026   {
1027     /* data fit in buffer */
1028     if ((msg->size - msg->pos) <= (size * nmemb))
1029     {
1030       len = (msg->size - msg->pos);
1031       memcpy(stream, &msg->buf[msg->pos], len);
1032       msg->pos += len;
1033       bytes_sent = len;
1034     }
1035     else
1036     {
1037       len = size*nmemb;
1038       memcpy(stream, &msg->buf[msg->pos], len);
1039       msg->pos += len;
1040       bytes_sent = len;
1041     }
1042   }
1043   /* no data to send */
1044   else
1045   {
1046     bytes_sent = 0;
1047   }
1048
1049   if ( msg->pos == msg->size)
1050   {
1051 #if DEBUG_CONNECTIONS
1052     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: Message with %u bytes sent, removing message from queue \n",ps, msg->pos);
1053 #endif
1054     /* Calling transmit continuation  */
1055     if (( NULL != ps->pending_msgs_tail) && (NULL != ps->pending_msgs_tail->transmit_cont))
1056       msg->transmit_cont (ps->pending_msgs_tail->transmit_cont_cls,&(ps->peercontext)->identity,GNUNET_OK);
1057     remove_http_message(ps, msg);
1058   }
1059   return bytes_sent;
1060 }
1061
1062 /**
1063 * Callback method used with libcurl
1064 * Method is called when libcurl needs to write data during sending
1065 * @param stream pointer where to write data
1066 * @param size size of an individual element
1067 * @param nmemb count of elements that can be written to the buffer
1068 * @param ptr destination pointer, passed to the libcurl handle
1069 * @return bytes read from stream
1070 */
1071 static size_t send_curl_receive_callback( void *stream, size_t size, size_t nmemb, void *ptr)
1072 {
1073   struct Session * ps = ptr;
1074 #if DEBUG_CONNECTIONS
1075   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: %u bytes recieved\n",ps, size*nmemb);
1076 #endif
1077   GNUNET_SERVER_mst_receive(ps->msgtok, ps, stream, size*nmemb, GNUNET_NO, GNUNET_NO);
1078   return (size * nmemb);
1079
1080 }
1081
1082 /**
1083  * Function setting up file descriptors and scheduling task to run
1084  * @param cls closure
1085  * @param ses session to send data to
1086  * @return bytes sent to peer
1087  */
1088 static size_t send_schedule(void *cls, struct Session* ses );
1089
1090
1091
1092 /**
1093  * Function setting up curl handle and selecting message to send
1094  * @param cls plugin
1095  * @param ses session to send data to
1096  * @param con connection
1097  * @return bytes sent to peer
1098  */
1099 static ssize_t send_check_connections (void *cls, struct Session *ps)
1100 {
1101   struct Plugin *plugin = cls;
1102   int bytes_sent = 0;
1103   CURLMcode mret;
1104   struct HTTP_Message * msg;
1105   struct GNUNET_TIME_Relative timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
1106
1107   GNUNET_assert(cls !=NULL);
1108
1109   if (ps->direction == OUTBOUND)
1110   {
1111     /* RECV DIRECTION */
1112     /* Check if session is connected to receive data, otherwise connect to peer */
1113     if (ps->recv_connected == GNUNET_NO)
1114     {
1115         if (ps->recv_endpoint == NULL)
1116         {
1117           ps->recv_endpoint = curl_easy_init();
1118 #if DEBUG_CURL
1119         curl_easy_setopt(ps->recv_endpoint, CURLOPT_VERBOSE, 1L);
1120 #endif
1121         curl_easy_setopt(ps->recv_endpoint, CURLOPT_URL, ps->url);
1122         curl_easy_setopt(ps->recv_endpoint, CURLOPT_HEADERFUNCTION, &curl_get_header_function);
1123         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEHEADER, ps);
1124         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READFUNCTION, send_curl_send_callback);
1125         curl_easy_setopt(ps->recv_endpoint, CURLOPT_READDATA, ps);
1126         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEFUNCTION, send_curl_receive_callback);
1127         curl_easy_setopt(ps->recv_endpoint, CURLOPT_WRITEDATA, ps);
1128         curl_easy_setopt(ps->recv_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1129         curl_easy_setopt(ps->recv_endpoint, CURLOPT_PRIVATE, ps);
1130         curl_easy_setopt(ps->recv_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1131         curl_easy_setopt(ps->recv_endpoint, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
1132
1133         mret = curl_multi_add_handle(plugin->multi_handle, ps->recv_endpoint);
1134         if (mret != CURLM_OK)
1135         {
1136           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1137                       _("%s failed at %s:%d: `%s'\n"),
1138                       "curl_multi_add_handle", __FILE__, __LINE__,
1139                       curl_multi_strerror (mret));
1140           return -1;
1141         }
1142         bytes_sent = send_schedule (plugin, NULL);
1143         if (ps->msgtok != NULL)
1144           ps->msgtok = GNUNET_SERVER_mst_create (&curl_write_mst_cb, ps);
1145 #if DEBUG_CONNECTIONS
1146         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: inbound not connected, initiating connection\n",ps);
1147 #endif
1148       }
1149     }
1150
1151     /* waiting for receive direction */
1152     if (ps->recv_connected==GNUNET_NO)
1153       return 0;
1154
1155     /* SEND DIRECTION */
1156     /* Check if session is connected to send data, otherwise connect to peer */
1157     if ((ps->send_connected == GNUNET_YES) && (ps->send_endpoint!= NULL))
1158     {
1159       if (ps->send_active == GNUNET_YES)
1160       {
1161 #if DEBUG_CONNECTIONS
1162         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound active, enqueueing message\n",ps);
1163 #endif
1164         return bytes_sent;
1165       }
1166       if (ps->send_active == GNUNET_NO)
1167       {
1168 #if DEBUG_CONNECTIONS
1169         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound paused, unpausing existing connection and enqueueing message\n",ps);
1170 #endif
1171         curl_easy_pause(ps->send_endpoint,CURLPAUSE_CONT);
1172         ps->send_active=GNUNET_YES;
1173         return bytes_sent;
1174       }
1175     }
1176     /* not connected, initiate connection */
1177     if ((ps->send_connected==GNUNET_NO) && (NULL == ps->send_endpoint))
1178       ps->send_endpoint = curl_easy_init();
1179     GNUNET_assert (ps->send_endpoint != NULL);
1180     GNUNET_assert (NULL != ps->pending_msgs_tail);
1181 #if DEBUG_CONNECTIONS
1182     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection %X: outbound not connected, initiating connection\n",ps);
1183 #endif
1184     ps->send_active = GNUNET_NO;
1185     msg = ps->pending_msgs_tail;
1186
1187   #if DEBUG_CURL
1188     curl_easy_setopt(ps->send_endpoint, CURLOPT_VERBOSE, 1L);
1189   #endif
1190     curl_easy_setopt(ps->send_endpoint, CURLOPT_URL, ps->url);
1191     curl_easy_setopt(ps->send_endpoint, CURLOPT_PUT, 1L);
1192     curl_easy_setopt(ps->send_endpoint, CURLOPT_HEADERFUNCTION, &curl_put_header_function);
1193     curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEHEADER, ps);
1194     curl_easy_setopt(ps->send_endpoint, CURLOPT_READFUNCTION, send_curl_send_callback);
1195     curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
1196     curl_easy_setopt(ps->send_endpoint, CURLOPT_WRITEFUNCTION, send_curl_receive_callback);
1197     curl_easy_setopt(ps->send_endpoint, CURLOPT_READDATA, ps);
1198     curl_easy_setopt(ps->send_endpoint, CURLOPT_TIMEOUT, (long) timeout.value);
1199     curl_easy_setopt(ps->send_endpoint, CURLOPT_PRIVATE, ps);
1200     curl_easy_setopt(ps->send_endpoint, CURLOPT_CONNECTTIMEOUT, HTTP_CONNECT_TIMEOUT);
1201     curl_easy_setopt(ps->send_endpoint, CURLOPT_BUFFERSIZE, GNUNET_SERVER_MAX_MESSAGE_SIZE);
1202
1203     mret = curl_multi_add_handle(plugin->multi_handle, ps->send_endpoint);
1204     if (mret != CURLM_OK)
1205     {
1206       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1207                   _("%s failed at %s:%d: `%s'\n"),
1208                   "curl_multi_add_handle", __FILE__, __LINE__,
1209                   curl_multi_strerror (mret));
1210       return -1;
1211     }
1212     bytes_sent = send_schedule (plugin, NULL);
1213     return bytes_sent;
1214   }
1215   if (ps->direction == INBOUND)
1216   {
1217     GNUNET_assert (NULL != ps->pending_msgs_tail);
1218     bytes_sent = 0;
1219     msg = ps->pending_msgs_tail;
1220     if ((ps->recv_connected==GNUNET_YES) && (ps->send_connected==GNUNET_YES))
1221         bytes_sent = msg->size;
1222     return bytes_sent;
1223   }
1224   return 0;
1225 }
1226
1227 static void send_execute (void *cls,
1228              const struct GNUNET_SCHEDULER_TaskContext *tc)
1229 {
1230   struct Plugin *plugin = cls;
1231   static unsigned int handles_last_run;
1232   int running;
1233   struct CURLMsg *msg;
1234   CURLMcode mret;
1235   struct Session *ps = NULL;
1236   struct HTTP_PeerContext *pc = NULL;
1237   struct HTTP_Message * cur_msg = NULL;
1238   long http_result;
1239
1240   GNUNET_assert(cls !=NULL);
1241   plugin->http_server_task_send = GNUNET_SCHEDULER_NO_TASK;
1242   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1243     return;
1244
1245   do
1246     {
1247       running = 0;
1248       mret = curl_multi_perform (plugin->multi_handle, &running);
1249       if (running < handles_last_run)
1250         {
1251           do
1252             {
1253
1254               msg = curl_multi_info_read (plugin->multi_handle, &running);
1255               if (msg == NULL)
1256                 break;
1257               /* get session for affected curl handle */
1258               GNUNET_assert ( msg->easy_handle != NULL );
1259               curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char *) &ps);
1260               GNUNET_assert ( ps != NULL );
1261               pc = ps->peercontext;
1262               GNUNET_assert ( pc != NULL );
1263               switch (msg->msg)
1264                 {
1265
1266                 case CURLMSG_DONE:
1267                   if ( (msg->data.result != CURLE_OK) &&
1268                        (msg->data.result != CURLE_GOT_NOTHING) )
1269                   {
1270                     /* sending msg failed*/
1271                     if (msg->easy_handle == ps->send_endpoint)
1272                     {
1273 #if DEBUG_CONNECTIONS
1274                       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1275                                  _("Connection %X: HTTP PUT to peer `%s' (`%s') failed: `%s' `%s'\n"),
1276                                  ps,
1277                                  GNUNET_i2s(&pc->identity),
1278                                  http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1279                                  "curl_multi_perform",
1280                                  curl_easy_strerror (msg->data.result));
1281 #endif
1282                       ps->send_connected = GNUNET_NO;
1283                       ps->send_active = GNUNET_NO;
1284                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1285                       curl_easy_cleanup(ps->send_endpoint);
1286                       ps->send_endpoint=NULL;
1287                       cur_msg = ps->pending_msgs_tail;
1288                       if (( NULL != cur_msg) && ( NULL != cur_msg->transmit_cont))
1289                         cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1290                     }
1291                     /* GET connection failed */
1292                     if (msg->easy_handle == ps->recv_endpoint)
1293                     {
1294 #if DEBUG_CONNECTIONS
1295                       GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1296                            _("Connection %X: HTTP GET to peer `%s' (`%s') failed: `%s' `%s'\n"),
1297                            ps,
1298                            GNUNET_i2s(&pc->identity),
1299                            http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1300                            "curl_multi_perform",
1301                            curl_easy_strerror (msg->data.result));
1302 #endif
1303                       ps->recv_connected = GNUNET_NO;
1304                       ps->recv_active = GNUNET_NO;
1305                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1306                       curl_easy_cleanup(ps->recv_endpoint);
1307                       ps->recv_endpoint=NULL;
1308                     }
1309                   }
1310                   else
1311                   {
1312                     if (msg->easy_handle == ps->send_endpoint)
1313                     {
1314                       GNUNET_assert (CURLE_OK == curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_result));
1315 #if DEBUG_CONNECTIONS
1316                       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1317                                   "Connection %X: HTTP PUT connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1318                                    ps,
1319                                    GNUNET_i2s(&pc->identity),
1320                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1321                                    http_result);
1322 #endif
1323                       /* Calling transmit continuation  */
1324                       cur_msg = ps->pending_msgs_tail;
1325                       if (( NULL != cur_msg) && (NULL != cur_msg->transmit_cont))
1326                       {
1327                         /* HTTP 1xx : Last message before here was informational */
1328                         if ((http_result >=100) && (http_result < 200))
1329                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1330                         /* HTTP 2xx: successful operations */
1331                         if ((http_result >=200) && (http_result < 300))
1332                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_OK);
1333                         /* HTTP 3xx..5xx: error */
1334                         if ((http_result >=300) && (http_result < 600))
1335                           cur_msg->transmit_cont (cur_msg->transmit_cont_cls,&pc->identity,GNUNET_SYSERR);
1336                       }
1337                       ps->send_connected = GNUNET_NO;
1338                       ps->send_active = GNUNET_NO;
1339                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1340                       curl_easy_cleanup(ps->send_endpoint);
1341                       ps->send_endpoint =NULL;
1342                     }
1343                     if (msg->easy_handle == ps->recv_endpoint)
1344                     {
1345 #if DEBUG_CONNECTIONS
1346                       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1347                                   "Connection %X: HTTP GET connection to peer `%s' (`%s') was closed with HTTP code %u\n",
1348                                    ps,
1349                                    GNUNET_i2s(&pc->identity),
1350                                    http_plugin_address_to_string(NULL, ps->addr, ps->addrlen),
1351                                    http_result);
1352 #endif
1353                       ps->recv_connected = GNUNET_NO;
1354                       ps->recv_active = GNUNET_NO;
1355                       curl_multi_remove_handle(plugin->multi_handle,msg->easy_handle);
1356                       curl_easy_cleanup(ps->recv_endpoint);
1357                       ps->recv_endpoint=NULL;
1358                     }
1359                   }
1360                   if (ps->pending_msgs_tail != NULL)
1361                   {
1362                     if (ps->pending_msgs_tail->pos>0)
1363                       remove_http_message(ps, ps->pending_msgs_tail);
1364                   }
1365                   return;
1366                 default:
1367                   break;
1368                 }
1369
1370             }
1371           while ( (running > 0) );
1372         }
1373       handles_last_run = running;
1374     }
1375   while (mret == CURLM_CALL_MULTI_PERFORM);
1376   send_schedule(plugin, cls);
1377 }
1378
1379
1380 /**
1381  * Function setting up file descriptors and scheduling task to run
1382  * @param ses session to send data to
1383  * @return bytes sent to peer
1384  */
1385 static size_t send_schedule(void *cls, struct Session* ses )
1386 {
1387   struct Plugin *plugin = cls;
1388   fd_set rs;
1389   fd_set ws;
1390   fd_set es;
1391   int max;
1392   struct GNUNET_NETWORK_FDSet *grs;
1393   struct GNUNET_NETWORK_FDSet *gws;
1394   long to;
1395   CURLMcode mret;
1396
1397   GNUNET_assert(cls !=NULL);
1398   max = -1;
1399   FD_ZERO (&rs);
1400   FD_ZERO (&ws);
1401   FD_ZERO (&es);
1402   mret = curl_multi_fdset (plugin->multi_handle, &rs, &ws, &es, &max);
1403   if (mret != CURLM_OK)
1404     {
1405       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1406                   _("%s failed at %s:%d: `%s'\n"),
1407                   "curl_multi_fdset", __FILE__, __LINE__,
1408                   curl_multi_strerror (mret));
1409       return -1;
1410     }
1411   mret = curl_multi_timeout (plugin->multi_handle, &to);
1412   if (mret != CURLM_OK)
1413     {
1414       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1415                   _("%s failed at %s:%d: `%s'\n"),
1416                   "curl_multi_timeout", __FILE__, __LINE__,
1417                   curl_multi_strerror (mret));
1418       return -1;
1419     }
1420
1421   grs = GNUNET_NETWORK_fdset_create ();
1422   gws = GNUNET_NETWORK_fdset_create ();
1423   GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1);
1424   GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1);
1425   plugin->http_server_task_send = GNUNET_SCHEDULER_add_select (plugin->env->sched,
1426                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1427                                    GNUNET_SCHEDULER_NO_TASK,
1428                                    GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 0),
1429                                    grs,
1430                                    gws,
1431                                    &send_execute,
1432                                    plugin);
1433   GNUNET_NETWORK_fdset_destroy (gws);
1434   GNUNET_NETWORK_fdset_destroy (grs);
1435
1436   /* FIXME: return bytes REALLY sent */
1437   return 0;
1438 }
1439
1440
1441 /**
1442  * Function that can be used by the transport service to transmit
1443  * a message using the plugin.   Note that in the case of a
1444  * peer disconnecting, the continuation MUST be called
1445  * prior to the disconnect notification itself.  This function
1446  * will be called with this peer's HELLO message to initiate
1447  * a fresh connection to another peer.
1448  *
1449  * @param cls closure
1450  * @param target who should receive this message
1451  * @param msgbuf the message to transmit
1452  * @param msgbuf_size number of bytes in 'msgbuf'
1453  * @param priority how important is the message (most plugins will
1454  *                 ignore message priority and just FIFO)
1455  * @param timeout how long to wait at most for the transmission (does not
1456  *                require plugins to discard the message after the timeout,
1457  *                just advisory for the desired delay; most plugins will ignore
1458  *                this as well)
1459  * @param session which session must be used (or NULL for "any")
1460  * @param addr the address to use (can be NULL if the plugin
1461  *                is "on its own" (i.e. re-use existing TCP connection))
1462  * @param addrlen length of the address in bytes
1463  * @param force_address GNUNET_YES if the plugin MUST use the given address,
1464  *                GNUNET_NO means the plugin may use any other address and
1465  *                GNUNET_SYSERR means that only reliable existing
1466  *                bi-directional connections should be used (regardless
1467  *                of address)
1468  * @param cont continuation to call once the message has
1469  *        been transmitted (or if the transport is ready
1470  *        for the next transmission call; or if the
1471  *        peer disconnected...); can be NULL
1472  * @param cont_cls closure for cont
1473  * @return number of bytes used (on the physical network, with overheads);
1474  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1475  *         and does NOT mean that the message was not transmitted (DV)
1476  */
1477 static ssize_t
1478 http_plugin_send (void *cls,
1479                   const struct GNUNET_PeerIdentity *target,
1480                   const char *msgbuf,
1481                   size_t msgbuf_size,
1482                   unsigned int priority,
1483                   struct GNUNET_TIME_Relative to,
1484                   struct Session *session,
1485                   const void *addr,
1486                   size_t addrlen,
1487                   int force_address,
1488                   GNUNET_TRANSPORT_TransmitContinuation cont,
1489                   void *cont_cls)
1490 {
1491   struct Plugin *plugin = cls;
1492   struct HTTP_Message *msg;
1493
1494   struct HTTP_PeerContext * pc;
1495   struct Session * ps = NULL;
1496
1497   GNUNET_assert(cls !=NULL);
1498
1499   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
1500   /* Peer unknown */
1501   if (pc==NULL)
1502   {
1503     pc = GNUNET_malloc(sizeof (struct HTTP_PeerContext));
1504     pc->plugin = plugin;
1505     pc->session_id_counter=1;
1506     memcpy(&pc->identity, target, sizeof(struct GNUNET_PeerIdentity));
1507     GNUNET_CONTAINER_multihashmap_put(plugin->peers, &pc->identity.hashPubKey, pc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1508   }
1509   if  ((addr!=NULL) && (addrlen != 0))
1510   {
1511     ps = get_Session(plugin, pc, addr, addrlen);
1512   }
1513   if (ps != NULL)
1514     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Found existing connection to peer %s with given address, using %X\n", GNUNET_i2s(target), ps);
1515
1516   /* session not existing, address not forced -> looking for other session */
1517   if ((ps==NULL) && ((force_address == GNUNET_NO) || (force_address == GNUNET_SYSERR)))
1518   {
1519     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection, but free to choose existing, searching for existing connection to peer %s\n", GNUNET_i2s(target));
1520     /* Choosing different session to peer when possible */
1521     struct Session * tmp = pc->head;
1522     while (tmp!=NULL)
1523     {
1524       if ((tmp->recv_connected) && (tmp->send_connected) && (tmp->recv_force_disconnect==GNUNET_NO) && (tmp->send_force_disconnect==GNUNET_NO))
1525       {
1526         ps = tmp;
1527       }
1528       tmp = tmp->next;
1529     }
1530     if (ps != NULL)
1531      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection to peer %s, selected connection %X\n", GNUNET_i2s(target),ps);
1532     else
1533       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection to peer %s, no connection found\n", GNUNET_i2s(target));
1534   }
1535
1536   /* session not existing, but address forced -> creating new session */
1537   if ((ps==NULL) || ((ps==NULL) && (force_address == GNUNET_YES)))
1538   {
1539     if ((addr!=NULL) && (addrlen!=0))
1540     {
1541       if (force_address == GNUNET_YES)
1542         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection & forced address: creating new connection to peer %s\n", GNUNET_i2s(target));
1543       if (force_address != GNUNET_YES)
1544         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing connection: creating new connection to peer %s\n", GNUNET_i2s(target));
1545
1546       ps = GNUNET_malloc(sizeof (struct Session));
1547       ps->addr = GNUNET_malloc(addrlen);
1548       memcpy(ps->addr,addr,addrlen);
1549       ps->addrlen = addrlen;
1550       ps->direction=OUTBOUND;
1551       ps->recv_connected = GNUNET_NO;
1552       ps->recv_force_disconnect = GNUNET_NO;
1553       ps->send_connected = GNUNET_NO;
1554       ps->send_force_disconnect = GNUNET_NO;
1555       ps->pending_msgs_head = NULL;
1556       ps->pending_msgs_tail = NULL;
1557       ps->peercontext=pc;
1558       ps->session_id = pc->session_id_counter;
1559       pc->session_id_counter++;
1560       ps->url = create_url (plugin, ps->addr, ps->addrlen, ps->session_id);
1561       GNUNET_CONTAINER_DLL_insert(pc->head,pc->tail,ps);
1562     }
1563     else
1564     {
1565       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No existing session & and no address given: no way to send this message to peer `%s'!\n", GNUNET_i2s(target));
1566       return -1;
1567     }
1568   }
1569
1570   char * force = GNUNET_malloc(30);
1571   if (force_address == GNUNET_YES)
1572     strcpy(force,"forced addr.");
1573   if (force_address == GNUNET_NO)
1574     strcpy(force,"any addr.");
1575   if (force_address == GNUNET_SYSERR)
1576     strcpy(force,"reliable bi-direc. address addr.");
1577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Transport tells me to send %u bytes to `%s' %s (%s), session: %X\n",
1578                                       msgbuf_size,
1579                                       GNUNET_i2s(&pc->identity),
1580                                       force,
1581                                       http_plugin_address_to_string(NULL, addr, addrlen),
1582                                       ps);
1583
1584   GNUNET_free(force);
1585   /* create msg */
1586   msg = GNUNET_malloc (sizeof (struct HTTP_Message) + msgbuf_size);
1587   msg->next = NULL;
1588   msg->size = msgbuf_size;
1589   msg->pos = 0;
1590   msg->buf = (char *) &msg[1];
1591   msg->transmit_cont = cont;
1592   msg->transmit_cont_cls = cont_cls;
1593   memcpy (msg->buf,msgbuf, msgbuf_size);
1594   GNUNET_CONTAINER_DLL_insert(ps->pending_msgs_head,ps->pending_msgs_tail,msg);
1595
1596   return send_check_connections (plugin, ps);
1597 }
1598
1599
1600
1601 /**
1602  * Function that can be used to force the plugin to disconnect
1603  * from the given peer and cancel all previous transmissions
1604  * (and their continuationc).
1605  *
1606  * @param cls closure
1607  * @param target peer from which to disconnect
1608  */
1609 static void
1610 http_plugin_disconnect (void *cls,
1611                             const struct GNUNET_PeerIdentity *target)
1612 {
1613
1614   struct Plugin *plugin = cls;
1615   struct HTTP_PeerContext *pc = NULL;
1616   struct Session *ps = NULL;
1617
1618   pc = GNUNET_CONTAINER_multihashmap_get (plugin->peers, &target->hashPubKey);
1619   if (pc==NULL)
1620     return;
1621
1622   ps = pc->head;
1623
1624   while (ps!=NULL)
1625   {
1626     if (ps->direction==OUTBOUND)
1627     {
1628       if (ps->send_endpoint!=NULL)
1629       {
1630         curl_multi_remove_handle(plugin->multi_handle,ps->send_endpoint);
1631         curl_easy_cleanup(ps->send_endpoint);
1632         ps->send_endpoint=NULL;
1633         ps->send_force_disconnect = GNUNET_YES;
1634       }
1635       if (ps->recv_endpoint!=NULL)
1636       {
1637        curl_multi_remove_handle(plugin->multi_handle,ps->recv_endpoint);
1638        curl_easy_cleanup(ps->recv_endpoint);
1639        ps->recv_endpoint=NULL;
1640        ps->recv_force_disconnect = GNUNET_YES;
1641       }
1642     }
1643     if (ps->direction==INBOUND)
1644     {
1645       ps->recv_force_disconnect = GNUNET_YES;
1646       ps->send_force_disconnect = GNUNET_YES;
1647     }
1648     while (ps->pending_msgs_head!=NULL)
1649     {
1650       remove_http_message(ps, ps->pending_msgs_head);
1651     }
1652     ps->recv_connected = GNUNET_NO;
1653     ps->recv_active = GNUNET_NO;
1654     ps->send_connected = GNUNET_NO;
1655     ps->send_active = GNUNET_NO;
1656     ps=ps->next;
1657   }
1658   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"All connections to peer `%s' terminated\n", GNUNET_i2s(target));
1659 }
1660
1661
1662 /**
1663  * Convert the transports address to a nice, human-readable
1664  * format.
1665  *
1666  * @param cls closure
1667  * @param type name of the transport that generated the address
1668  * @param addr one of the addresses of the host, NULL for the last address
1669  *        the specific address format depends on the transport
1670  * @param addrlen length of the address
1671  * @param numeric should (IP) addresses be displayed in numeric form?
1672  * @param timeout after how long should we give up?
1673  * @param asc function to call on each string
1674  * @param asc_cls closure for asc
1675  */
1676 static void
1677 http_plugin_address_pretty_printer (void *cls,
1678                                         const char *type,
1679                                         const void *addr,
1680                                         size_t addrlen,
1681                                         int numeric,
1682                                         struct GNUNET_TIME_Relative timeout,
1683                                         GNUNET_TRANSPORT_AddressStringCallback
1684                                         asc, void *asc_cls)
1685 {
1686   const struct IPv4HttpAddress *t4;
1687   const struct IPv6HttpAddress *t6;
1688   struct sockaddr_in a4;
1689   struct sockaddr_in6 a6;
1690   char * address;
1691   char * ret;
1692   unsigned int port;
1693   unsigned int res;
1694
1695   GNUNET_assert(cls !=NULL);
1696   if (addrlen == sizeof (struct IPv6HttpAddress))
1697   {
1698     address = GNUNET_malloc (INET6_ADDRSTRLEN);
1699     t6 = addr;
1700     a6.sin6_addr = t6->ipv6_addr;
1701     inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1702     port = ntohs(t6->u6_port);
1703   }
1704   else if (addrlen == sizeof (struct IPv4HttpAddress))
1705   {
1706     address = GNUNET_malloc (INET_ADDRSTRLEN);
1707     t4 = addr;
1708     a4.sin_addr.s_addr =  t4->ipv4_addr;
1709     inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1710     port = ntohs(t4->u_port);
1711   }
1712   else
1713   {
1714     /* invalid address */
1715     GNUNET_break_op (0);
1716     asc (asc_cls, NULL);
1717     return;
1718   }
1719   res = GNUNET_asprintf(&ret,"http://%s:%u/",address,port);
1720   GNUNET_free (address);
1721   GNUNET_assert(res != 0);
1722
1723   asc (asc_cls, ret);
1724 }
1725
1726
1727
1728 /**
1729  * Another peer has suggested an address for this
1730  * peer and transport plugin.  Check that this could be a valid
1731  * address.  If so, consider adding it to the list
1732  * of addresses.
1733  *
1734  * @param cls closure
1735  * @param addr pointer to the address
1736  * @param addrlen length of addr
1737  * @return GNUNET_OK if this is a plausible address for this peer
1738  *         and transport
1739  */
1740 static int
1741 http_plugin_address_suggested (void *cls,
1742                                const void *addr, size_t addrlen)
1743 {
1744   struct Plugin *plugin = cls;
1745   struct IPv4HttpAddress *v4;
1746   struct IPv6HttpAddress *v6;
1747   unsigned int port;
1748
1749   GNUNET_assert(cls !=NULL);
1750   if ((addrlen != sizeof (struct IPv4HttpAddress)) &&
1751       (addrlen != sizeof (struct IPv6HttpAddress)))
1752     {
1753       return GNUNET_SYSERR;
1754     }
1755   if (addrlen == sizeof (struct IPv4HttpAddress))
1756     {
1757       v4 = (struct IPv4HttpAddress *) addr;
1758       if (INADDR_LOOPBACK == ntohl(v4->ipv4_addr))
1759       {
1760         return GNUNET_SYSERR;
1761       }
1762       port = ntohs (v4->u_port);
1763       if (port != plugin->port_inbound)
1764       {
1765         return GNUNET_SYSERR;
1766       }
1767     }
1768   else
1769     {
1770       v6 = (struct IPv6HttpAddress *) addr;
1771       if (IN6_IS_ADDR_LINKLOCAL (&v6->ipv6_addr))
1772         {
1773           return GNUNET_SYSERR;
1774         }
1775       port = ntohs (v6->u6_port);
1776       if (port != plugin->port_inbound)
1777       {
1778         return GNUNET_SYSERR;
1779       }
1780     }
1781   return GNUNET_OK;
1782 }
1783
1784
1785 /**
1786  * Function called for a quick conversion of the binary address to
1787  * a numeric address.  Note that the caller must not free the
1788  * address and that the next call to this function is allowed
1789  * to override the address again.
1790  *
1791  * @param cls closure
1792  * @param addr binary address
1793  * @param addrlen length of the address
1794  * @return string representing the same address
1795  */
1796 static const char*
1797 http_plugin_address_to_string (void *cls,
1798                                    const void *addr,
1799                                    size_t addrlen)
1800 {
1801   const struct IPv4HttpAddress *t4;
1802   const struct IPv6HttpAddress *t6;
1803   struct sockaddr_in a4;
1804   struct sockaddr_in6 a6;
1805   char * address;
1806   char * ret;
1807   uint16_t port;
1808   unsigned int res;
1809
1810   if (addrlen == sizeof (struct IPv6HttpAddress))
1811     {
1812       address = GNUNET_malloc (INET6_ADDRSTRLEN);
1813       t6 = addr;
1814       a6.sin6_addr = t6->ipv6_addr;
1815       inet_ntop(AF_INET6, &(a6.sin6_addr),address,INET6_ADDRSTRLEN);
1816       port = ntohs(t6->u6_port);
1817     }
1818   else if (addrlen == sizeof (struct IPv4HttpAddress))
1819     {
1820       address = GNUNET_malloc (INET_ADDRSTRLEN);
1821       t4 = addr;
1822       a4.sin_addr.s_addr =  t4->ipv4_addr;
1823       inet_ntop(AF_INET, &(a4.sin_addr),address,INET_ADDRSTRLEN);
1824       port = ntohs(t4->u_port);
1825     }
1826   else
1827     {
1828       /* invalid address */
1829       return NULL;
1830     }
1831   res = GNUNET_asprintf(&ret,"%s:%u",address,port);
1832   GNUNET_free (address);
1833   GNUNET_assert(res != 0);
1834   return ret;
1835 }
1836
1837 /**
1838  * Add the IP of our network interface to the list of
1839  * our external IP addresses.
1840  *
1841  * @param cls the 'struct Plugin*'
1842  * @param name name of the interface
1843  * @param isDefault do we think this may be our default interface
1844  * @param addr address of the interface
1845  * @param addrlen number of bytes in addr
1846  * @return GNUNET_OK to continue iterating
1847  */
1848 static int
1849 process_interfaces (void *cls,
1850                     const char *name,
1851                     int isDefault,
1852                     const struct sockaddr *addr, socklen_t addrlen)
1853 {
1854   struct Plugin *plugin = cls;
1855   struct IPv4HttpAddress * t4;
1856   struct IPv6HttpAddress * t6;
1857   int af;
1858
1859   GNUNET_assert(cls !=NULL);
1860   af = addr->sa_family;
1861   if (af == AF_INET)
1862     {
1863       t4 = GNUNET_malloc(sizeof(struct IPv4HttpAddress));
1864       if (INADDR_LOOPBACK == ntohl(((struct sockaddr_in *) addr)->sin_addr.s_addr))
1865       {
1866         /* skip loopback addresses */
1867         return GNUNET_OK;
1868       }
1869       t4->ipv4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr;
1870       t4->u_port = htons (plugin->port_inbound);
1871       plugin->env->notify_address(plugin->env->cls,"http",t4, sizeof (struct IPv4HttpAddress), GNUNET_TIME_UNIT_FOREVER_REL);
1872
1873     }
1874   else if (af == AF_INET6)
1875     {
1876       t6 = GNUNET_malloc(sizeof(struct IPv6HttpAddress));
1877       if (IN6_IS_ADDR_LINKLOCAL (&((struct sockaddr_in6 *) addr)->sin6_addr))
1878         {
1879           /* skip link local addresses */
1880           return GNUNET_OK;
1881         }
1882       if (IN6_IS_ADDR_LOOPBACK (&((struct sockaddr_in6 *) addr)->sin6_addr))
1883         {
1884           /* skip loopback addresses */
1885           return GNUNET_OK;
1886         }
1887       memcpy (&t6->ipv6_addr,
1888               &((struct sockaddr_in6 *) addr)->sin6_addr,
1889               sizeof (struct in6_addr));
1890       t6->u6_port = htons (plugin->port_inbound);
1891       plugin->env->notify_address(plugin->env->cls,"http",t6,sizeof (struct IPv6HttpAddress) , GNUNET_TIME_UNIT_FOREVER_REL);
1892     }
1893   return GNUNET_OK;
1894 }
1895
1896 int peer_context_Iterator (void *cls, const GNUNET_HashCode *key, void *value)
1897 {
1898   struct HTTP_PeerContext * pc = value;
1899   struct Session * ps = pc->head;
1900   struct Session * tmp = NULL;
1901   struct HTTP_Message * msg = NULL;
1902   struct HTTP_Message * msg_tmp = NULL;
1903
1904   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing context for peer `%s'\n",GNUNET_i2s(&pc->identity));
1905
1906   while (ps!=NULL)
1907   {
1908     tmp = ps->next;
1909
1910     GNUNET_free(ps->addr);
1911     GNUNET_free(ps->url);
1912     if (ps->msgtok != NULL)
1913       GNUNET_SERVER_mst_destroy (ps->msgtok);
1914
1915     msg = ps->pending_msgs_head;
1916     while (msg!=NULL)
1917     {
1918       msg_tmp = msg->next;
1919       GNUNET_free(msg);
1920       msg = msg_tmp;
1921     }
1922     if (ps->direction==OUTBOUND)
1923     {
1924       if (ps->send_endpoint!=NULL)
1925         curl_easy_cleanup(ps->send_endpoint);
1926       if (ps->recv_endpoint!=NULL)
1927         curl_easy_cleanup(ps->recv_endpoint);
1928     }
1929
1930     GNUNET_free(ps);
1931     ps=tmp;
1932   }
1933   GNUNET_free(pc);
1934   return GNUNET_YES;
1935 }
1936
1937
1938 /**
1939  * Exit point from the plugin.
1940  */
1941 void *
1942 libgnunet_plugin_transport_http_done (void *cls)
1943 {
1944   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1945   struct Plugin *plugin = api->cls;
1946   CURLMcode mret;
1947
1948   GNUNET_assert(cls !=NULL);
1949
1950   if ( plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
1951   {
1952     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v4);
1953     plugin->http_server_task_v4 = GNUNET_SCHEDULER_NO_TASK;
1954   }
1955
1956   if ( plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
1957   {
1958     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_v6);
1959     plugin->http_server_task_v6 = GNUNET_SCHEDULER_NO_TASK;
1960   }
1961
1962   if ( plugin->http_server_task_send != GNUNET_SCHEDULER_NO_TASK)
1963   {
1964     GNUNET_SCHEDULER_cancel(plugin->env->sched, plugin->http_server_task_send);
1965     plugin->http_server_task_send = GNUNET_SCHEDULER_NO_TASK;
1966   }
1967
1968   if (plugin->http_server_daemon_v4 != NULL)
1969   {
1970     MHD_stop_daemon (plugin->http_server_daemon_v4);
1971     plugin->http_server_daemon_v4 = NULL;
1972   }
1973   if (plugin->http_server_daemon_v6 != NULL)
1974   {
1975     MHD_stop_daemon (plugin->http_server_daemon_v6);
1976     plugin->http_server_daemon_v6 = NULL;
1977   }
1978
1979   /* free all peer information */
1980   GNUNET_CONTAINER_multihashmap_iterate (plugin->peers,
1981                                          &peer_context_Iterator,
1982                                          NULL);
1983   GNUNET_CONTAINER_multihashmap_destroy (plugin->peers);
1984
1985   mret = curl_multi_cleanup(plugin->multi_handle);
1986   if ( CURLM_OK != mret)
1987     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"curl multihandle clean up failed");
1988
1989   GNUNET_free (plugin);
1990   GNUNET_free (api);
1991   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unload http plugin complete...\n");
1992   return NULL;
1993 }
1994
1995
1996 /**
1997  * Entry point for the plugin.
1998  */
1999 void *
2000 libgnunet_plugin_transport_http_init (void *cls)
2001 {
2002   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2003   struct Plugin *plugin;
2004   struct GNUNET_TRANSPORT_PluginFunctions *api;
2005   struct GNUNET_TIME_Relative gn_timeout;
2006   long long unsigned int port;
2007
2008   GNUNET_assert(cls !=NULL);
2009   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
2010
2011   plugin = GNUNET_malloc (sizeof (struct Plugin));
2012   plugin->env = env;
2013   plugin->peers = NULL;
2014
2015   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2016   api->cls = plugin;
2017   api->send = &http_plugin_send;
2018   api->disconnect = &http_plugin_disconnect;
2019   api->address_pretty_printer = &http_plugin_address_pretty_printer;
2020   api->check_address = &http_plugin_address_suggested;
2021   api->address_to_string = &http_plugin_address_to_string;
2022
2023   /* Hashing our identity to use it in URLs */
2024   GNUNET_CRYPTO_hash_to_enc ( &(plugin->env->my_identity->hashPubKey), &plugin->my_ascii_hash_ident);
2025
2026   /* Reading port number from config file */
2027   if ((GNUNET_OK !=
2028        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2029                                               "transport-http",
2030                                               "PORT",
2031                                               &port)) ||
2032       (port > 65535) )
2033     {
2034       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2035                        "http",
2036                        _
2037                        ("Require valid port number for transport plugin `%s' in configuration!\n"),
2038                        "transport-http");
2039       libgnunet_plugin_transport_http_done (api);
2040       return NULL;
2041     }
2042   GNUNET_assert ((port > 0) && (port <= 65535));
2043   plugin->port_inbound = port;
2044   gn_timeout = GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT;
2045   if ((plugin->http_server_daemon_v4 == NULL) && (plugin->http_server_daemon_v6 == NULL) && (port != 0))
2046     {
2047     plugin->http_server_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
2048                                        port,
2049                                        &acceptPolicyCallback,
2050                                        plugin , &accessHandlerCallback, plugin,
2051                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
2052                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
2053                                        MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
2054                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
2055                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
2056                                        MHD_OPTION_END);
2057     plugin->http_server_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
2058                                        port,
2059                                        &acceptPolicyCallback,
2060                                        plugin , &accessHandlerCallback, plugin,
2061                                        MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
2062                                        MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
2063                                        MHD_OPTION_CONNECTION_TIMEOUT, (gn_timeout.value / 1000),
2064                                        MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
2065                                        MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
2066                                        MHD_OPTION_END);
2067     }
2068   if (plugin->http_server_daemon_v4 != NULL)
2069     plugin->http_server_task_v4 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v4);
2070   if (plugin->http_server_daemon_v6 != NULL)
2071     plugin->http_server_task_v6 = http_server_daemon_prepare (plugin, plugin->http_server_daemon_v6);
2072
2073   if (plugin->http_server_task_v4 != GNUNET_SCHEDULER_NO_TASK)
2074     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
2075   else if (plugin->http_server_task_v6 != GNUNET_SCHEDULER_NO_TASK)
2076     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
2077   else
2078   {
2079     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"No MHD was started, transport plugin not functional!\n");
2080     libgnunet_plugin_transport_http_done (api);
2081     return NULL;
2082   }
2083
2084   /* Initializing cURL */
2085   curl_global_init(CURL_GLOBAL_ALL);
2086   plugin->multi_handle = curl_multi_init();
2087
2088   if ( NULL == plugin->multi_handle )
2089   {
2090     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2091                      "http",
2092                      _("Could not initialize curl multi handle, failed to start http plugin!\n"),
2093                      "transport-http");
2094     libgnunet_plugin_transport_http_done (api);
2095     return NULL;
2096   }
2097
2098   plugin->peers = GNUNET_CONTAINER_multihashmap_create (10);
2099   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2100
2101   return api;
2102 }
2103
2104 /* end of plugin_transport_http.c */