]> git.tdb.fi Git - libs/net.git/blob - source/http/server.cpp
667403e86788c9228e179e1f9677feb1552fb6cc
[libs/net.git] / source / http / server.cpp
1 #include <exception>
2 #include <typeinfo>
3 #include <msp/core/maputils.h>
4 #include <msp/core/refptr.h>
5 #include <msp/debug/demangle.h>
6 #include <msp/net/inet.h>
7 #include <msp/net/resolve.h>
8 #include <msp/net/streamsocket.h>
9 #include <msp/strings/format.h>
10 #include <msp/strings/utils.h>
11 #include "request.h"
12 #include "response.h"
13 #include "server.h"
14
15 using namespace std;
16
17 namespace Msp {
18 namespace Http {
19
20 Server::Server():
21         sock(Net::INET6),
22         event_disp(0)
23 { }
24
25 Server::Server(unsigned port):
26         sock(Net::INET6),
27         event_disp(0)
28 {
29         listen(port);
30 }
31
32 // Avoid emitting sigc::signal destructor in files including server.h
33 Server::~Server()
34 {
35 }
36
37 void Server::listen(unsigned port)
38 {
39         RefPtr<Net::SockAddr> addr = Net::resolve("*", format("%d", port), Net::INET6);
40         sock.listen(*addr, 8);
41         sock.signal_data_available.connect(sigc::mem_fun(this, &Server::data_available));
42 }
43
44 unsigned Server::get_port() const
45 {
46         const Net::SockAddr &addr = sock.get_local_address();
47         if(addr.get_family()==Net::INET)
48                 return static_cast<const Net::InetAddr &>(addr).get_port();
49         return 0;
50 }
51
52 void Server::use_event_dispatcher(IO::EventDispatcher *ed)
53 {
54         if(event_disp)
55         {
56                 event_disp->remove(sock);
57                 for(list<Client>::iterator i=clients.begin(); i!=clients.end(); ++i)
58                         event_disp->remove(*i->sock);
59         }
60         event_disp = ed;
61         if(event_disp)
62         {
63                 event_disp->add(sock);
64                 for(list<Client>::iterator i=clients.begin(); i!=clients.end(); ++i)
65                         event_disp->add(*i->sock);
66         }
67 }
68
69 void Server::delay_response(Response &resp)
70 {
71         get_client_by_response(resp).async = true;
72 }
73
74 void Server::submit_response(Response &resp)
75 {
76         Client &cl = get_client_by_response(resp);
77         if(cl.async)
78                 send_response(cl, *cl.response);
79 }
80
81 void Server::cancel_keepalive(Response &resp)
82 {
83         get_client_by_response(resp).keepalive = false;
84 }
85
86 void Server::close_connections(const Time::TimeDelta &timeout)
87 {
88         IO::Poller poller;
89         for(list<Client>::iterator i=clients.begin(); i!=clients.end(); ++i)
90         {
91                 i->sock->shutdown(IO::M_WRITE);
92                 poller.set_object(*i->sock, IO::P_INPUT);
93         }
94
95         while(!clients.empty() && poller.poll(timeout))
96         {
97                 const vector<IO::Poller::PolledObject> &result = poller.get_result();
98                 for(vector<IO::Poller::PolledObject>::const_iterator i=result.begin(); i!=result.end(); ++i)
99                         for(list<Client>::iterator j=clients.begin(); j!=clients.end(); ++j)
100                                 if(j->sock.get()==i->object)
101                                 {
102                                         poller.set_object(*j->sock, IO::P_NONE);
103                                         clients.erase(j);
104                                         break;
105                                 }
106         }
107 }
108
109 void Server::data_available()
110 {
111         Net::StreamSocket *csock = sock.accept();
112         clients.push_back(Client(csock));
113         csock->signal_data_available.connect(sigc::bind(sigc::mem_fun(this, &Server::client_data_available), sigc::ref(clients.back())));
114         csock->signal_end_of_file.connect(sigc::bind(sigc::mem_fun(this, &Server::client_end_of_file), sigc::ref(clients.back())));
115         if(event_disp)
116                 event_disp->add(*csock);
117 }
118
119 void Server::client_data_available(Client &cl)
120 {
121         for(list<Client>::iterator i=clients.begin(); i!=clients.end(); ++i)
122                 if(i->stale && &*i!=&cl)
123                 {
124                         clients.erase(i);
125                         break;
126                 }
127
128         try
129         {
130                 char rbuf[4096];
131                 unsigned len = cl.sock->read(rbuf, sizeof(rbuf));
132                 if(cl.stale)
133                         return;
134                 cl.in_buf.append(rbuf, len);
135         }
136         catch(const exception &)
137         {
138                 cl.stale = true;
139                 return;
140         }
141
142         RefPtr<Response> response;
143         if(!cl.request)
144         {
145                 if(cl.in_buf.find("\r\n\r\n")!=string::npos || cl.in_buf.find("\n\n")!=string::npos)
146                 {
147                         try
148                         {
149                                 cl.request = new Request(Request::parse(cl.in_buf));
150
151                                 string addr_str = cl.sock->get_peer_address().str();
152                                 string::size_type colon = addr_str.find(':');
153                                 cl.request->set_header("-Client-Host", addr_str.substr(0, colon));
154
155                                 if(cl.request->get_method()!="GET" && cl.request->get_method()!="POST")
156                                 {
157                                         response = new Response(NOT_IMPLEMENTED);
158                                         response->add_content("Method not implemented\n");
159                                 }
160                                 else if(cl.request->get_path()[0]!='/')
161                                 {
162                                         response = new Response(BAD_REQUEST);
163                                         response->add_content("Path must be absolute\n");
164                                 }
165                         }
166                         catch(const exception &e)
167                         {
168                                 response = new Response(BAD_REQUEST);
169                                 response->add_content(format("An error occurred while parsing request headers:\ntype: %s\nwhat: %s",
170                                         Debug::demangle(typeid(e).name()), e.what()));
171                         }
172                         cl.in_buf = string();
173                 }
174         }
175         else
176         {
177                 unsigned len = cl.request->parse_content(cl.in_buf);
178                 cl.in_buf.erase(0, len);
179         }
180
181         if(cl.request && cl.request->is_complete() && !response)
182         {
183                 cl.keepalive = false;
184                 if(cl.request->has_header("Connection"))
185                         cl.keepalive = !strcasecmp(cl.request->get_header("Connection"), "keep-alive");
186
187                 response = new Response(NONE);
188                 try
189                 {
190                         cl.response = response.get();
191                         responses[cl.response] = &cl;
192                         signal_request.emit(*cl.request, *response);
193                         if(cl.async)
194                                 response.release();
195                         else
196                         {
197                                 responses.erase(cl.response);
198                                 cl.response = 0;
199                                 if(response->get_status()==NONE)
200                                 {
201                                         response = new Response(NOT_FOUND);
202                                         response->add_content("The requested resource was not found\n");
203                                 }
204                         }
205                 }
206                 catch(const exception &e)
207                 {
208                         responses.erase(cl.response);
209                         cl.response = 0;
210                         response = new Response(INTERNAL_ERROR);
211                         response->add_content(format("An error occurred while processing the request:\ntype: %s\nwhat: %s",
212                                 Debug::demangle(typeid(e).name()), e.what()));
213                 }
214         }
215
216         if(response)
217                 send_response(cl, *response);
218 }
219
220 void Server::send_response(Client &cl, Response &resp)
221 {
222         if(cl.keepalive)
223                 resp.set_header("Connection", "keep-alive");
224
225         try
226         {
227                 cl.sock->write(resp.str());
228         }
229         catch(const exception &)
230         {
231                 cl.stale = true;
232                 return;
233         }
234
235         cl.async = false;
236         if(cl.keepalive)
237         {
238                 delete cl.request;
239                 cl.request = 0;
240                 delete cl.response;
241                 cl.response = 0;
242         }
243         else
244         {
245                 cl.sock->shutdown(IO::M_WRITE);
246                 cl.stale = true;
247         }
248 }
249
250 void Server::client_end_of_file(Client &cl)
251 {
252         cl.stale = true;
253 }
254
255 Server::Client &Server::get_client_by_response(Response &resp)
256 {
257         return *get_item(responses, &resp);
258 }
259
260
261 Server::Client::Client(RefPtr<Net::StreamSocket> s):
262         sock(s),
263         request(0),
264         response(0),
265         keepalive(false),
266         async(false),
267         stale(false)
268 { }
269
270 Server::Client::~Client()
271 {
272         delete request;
273         delete response;
274 }
275
276 } // namespace Http
277 } // namespace Msp