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