]> git.saurik.com Git - apt.git/blob - test/interactive-helper/aptwebserver.cc
cleanup, thanks to donkult for his feedback
[apt.git] / test / interactive-helper / aptwebserver.cc
1 #include <apt-pkg/strutl.h>
2 #include <apt-pkg/fileutl.h>
3 #include <apt-pkg/error.h>
4 #include <apt-pkg/cmndline.h>
5 #include <apt-pkg/configuration.h>
6 #include <apt-pkg/init.h>
7
8 #include <vector>
9 #include <string>
10 #include <list>
11 #include <sstream>
12
13 #include <sys/socket.h>
14 #include <sys/types.h>
15 #include <netinet/in.h>
16 #include <unistd.h>
17 #include <errno.h>
18 #include <time.h>
19 #include <stdlib.h>
20
21 char const * const httpcodeToStr(int httpcode) { /*{{{*/
22 switch (httpcode) {
23 // Informational 1xx
24 case 100: return "100 Continue";
25 case 101: return "101 Switching Protocols";
26 // Successful 2xx
27 case 200: return "200 OK";
28 case 201: return "201 Created";
29 case 202: return "202 Accepted";
30 case 203: return "203 Non-Authoritative Information";
31 case 204: return "204 No Content";
32 case 205: return "205 Reset Content";
33 case 206: return "206 Partial Conent";
34 // Redirections 3xx
35 case 300: return "300 Multiple Choices";
36 case 301: return "301 Moved Permanently";
37 case 302: return "302 Found";
38 case 303: return "303 See Other";
39 case 304: return "304 Not Modified";
40 case 305: return "304 Use Proxy";
41 case 307: return "307 Temporary Redirect";
42 // Client errors 4xx
43 case 400: return "400 Bad Request";
44 case 401: return "401 Unauthorized";
45 case 402: return "402 Payment Required";
46 case 403: return "403 Forbidden";
47 case 404: return "404 Not Found";
48 case 405: return "405 Method Not Allowed";
49 case 406: return "406 Not Acceptable";
50 case 407: return "Proxy Authentication Required";
51 case 408: return "Request Time-out";
52 case 409: return "Conflict";
53 case 410: return "Gone";
54 case 411: return "Length Required";
55 case 412: return "Precondition Failed";
56 case 413: return "Request Entity Too Large";
57 case 414: return "Request-URI Too Large";
58 case 415: return "Unsupported Media Type";
59 case 416: return "Requested range not satisfiable";
60 case 417: return "Expectation Failed";
61 // Server error 5xx
62 case 500: return "Internal Server Error";
63 case 501: return "Not Implemented";
64 case 502: return "Bad Gateway";
65 case 503: return "Service Unavailable";
66 case 504: return "Gateway Time-out";
67 case 505: return "HTTP Version not supported";
68 }
69 return NULL;
70 } /*}}}*/
71
72 void addFileHeaders(std::list<std::string> &headers, FileFd &data) { /*{{{*/
73 std::ostringstream contentlength;
74 contentlength << "Content-Length: " << data.FileSize();
75 headers.push_back(contentlength.str());
76
77 std::string lastmodified("Last-Modified: ");
78 lastmodified.append(TimeRFC1123(data.ModificationTime()));
79 headers.push_back(lastmodified);
80 } /*}}}*/
81
82 void addDataHeaders(std::list<std::string> &headers, std::string &data) {/*{{{*/
83 std::ostringstream contentlength;
84 contentlength << "Content-Length: " << data.size();
85 headers.push_back(contentlength.str());
86 } /*}}}*/
87
88 bool sendHead(int client, int httpcode, std::list<std::string> &headers) { /*{{{*/
89 string response("HTTP/1.1 ");
90 response.append(httpcodeToStr(httpcode));
91 headers.push_front(response);
92
93 headers.push_back("Server: APT webserver");
94
95 std::string date("Date: ");
96 date.append(TimeRFC1123(time(NULL)));
97 headers.push_back(date);
98
99 std::clog << ">>> RESPONSE >>>" << std::endl;
100 bool Success = true;
101 for (std::list<std::string>::const_iterator h = headers.begin();
102 Success == true && h != headers.end(); ++h) {
103 Success &= FileFd::Write(client, h->c_str(), h->size());
104 Success &= FileFd::Write(client, "\r\n", 2);
105 std::clog << *h << std::endl;
106 }
107 Success &= FileFd::Write(client, "\r\n", 2);
108 std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
109 return Success;
110 } /*}}}*/
111
112 bool sendFile(int client, FileFd &data) { /*{{{*/
113 bool Success = true;
114 char buffer[500];
115 unsigned long long actual = 0;
116 while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true) {
117 if (actual == 0)
118 break;
119 Success &= FileFd::Write(client, buffer, actual);
120 }
121 Success &= FileFd::Write(client, "\r\n", 2);
122 return Success;
123 } /*}}}*/
124
125 bool sendData(int client, std::string &data) { /*{{{*/
126 bool Success = true;
127 Success &= FileFd::Write(client, data.c_str(), data.size());
128 Success &= FileFd::Write(client, "\r\n", 2);
129 return Success;
130 } /*}}}*/
131
132 void sendError(int client, int httpcode, string request, bool content) { /*{{{*/
133 std::list<std::string> headers;
134 string response;
135 if (content == true) {
136 response.append("<html><head><title>");
137 response.append(httpcodeToStr(httpcode)).append("</title></head>");
138 response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
139 response.append("This error is a result of the request: <pre>");
140 response.append(request).append("</pre></body></html>");
141 addDataHeaders(headers, response);
142 }
143 sendHead(client, httpcode, headers);
144 sendData(client, response);
145 } /*}}}*/
146
147 int main(int argc, const char *argv[])
148 {
149 CommandLine::Args Args[] = {
150 {0, "simulate-paywall", "aptwebserver::Simulate-Paywall",
151 CommandLine::Boolean},
152 {0, "port", "aptwebserver::port", CommandLine::HasArg},
153 {0,0,0,0}
154 };
155
156 CommandLine CmdL(Args, _config);
157 if(CmdL.Parse(argc,argv) == false) {
158 _error->DumpErrors();
159 exit(1);
160 }
161
162 // create socket, bind and listen to it {{{
163 int sock = socket(AF_INET6, SOCK_STREAM, 0);
164 if(sock < 0 ) {
165 _error->Errno("aptwerbserver", "Couldn't create socket");
166 _error->DumpErrors(std::cerr);
167 return 1;
168 }
169
170 // get the port
171 int const port = _config->FindI("aptwebserver::port", 8080);
172 bool const simulate_broken_server = _config->FindB("aptwebserver::Simulate-Paywall", false);
173
174 // ensure that we accept all connections: v4 or v6
175 int const iponly = 0;
176 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
177 // to not linger to an address
178 int const enable = 1;
179 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
180
181 struct sockaddr_in6 locAddr;
182 memset(&locAddr, 0, sizeof(locAddr));
183 locAddr.sin6_family = AF_INET6;
184 locAddr.sin6_port = htons(port);
185 locAddr.sin6_addr = in6addr_any;
186
187 if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0) {
188 _error->Errno("aptwerbserver", "Couldn't bind");
189 _error->DumpErrors(std::cerr);
190 return 2;
191 }
192
193 if (simulate_broken_server) {
194 std::clog << "Simulating a broken web server that return nonsense "
195 "for all querries" << std::endl;
196 } else {
197 std::clog << "Serving ANY file on port: " << port << std::endl;
198 }
199
200 listen(sock, 1);
201
202 std::vector<std::string> messages;
203 int client;
204 while ((client = accept(sock, NULL, NULL)) != -1) {
205 std::clog << "ACCEPT client " << client
206 << " on socket " << sock << std::endl;
207
208 while (ReadMessages(client, messages)) {
209 for (std::vector<std::string>::const_iterator m = messages.begin();
210 m != messages.end(); ++m) {
211 std::clog << ">>> REQUEST >>>>" << std::endl << *m
212 << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
213 std::list<std::string> headers;
214 bool sendContent = true;
215 if (strncmp(m->c_str(), "HEAD ", 5) == 0)
216 sendContent = false;
217 if (strncmp(m->c_str(), "GET ", 4) != 0)
218 sendError(client, 501, *m, true);
219
220 std::string host = LookupTag(*m, "Host", "");
221 if (host.empty() == true) {
222 // RFC 2616 ยง14.23 Host
223 sendError(client, 400, *m, sendContent);
224 continue;
225 }
226
227 size_t const filestart = m->find(' ', 5);
228 string filename = m->substr(5, filestart - 5);
229
230 if (simulate_broken_server == true) {
231 string data("ni ni ni\n");
232 addDataHeaders(headers, data);
233 sendHead(client, 200, headers);
234 sendData(client, data);
235 }
236 else if (RealFileExists(filename) == false)
237 sendError(client, 404, *m, sendContent);
238 else {
239 FileFd data(filename, FileFd::ReadOnly);
240 std::string condition = LookupTag(*m, "If-Modified-Since", "");
241 if (condition.empty() == false) {
242 time_t cache;
243 if (RFC1123StrToTime(condition.c_str(), cache) == true &&
244 cache >= data.ModificationTime()) {
245 sendError(client, 304, *m, false);
246 continue;
247 }
248 }
249 addFileHeaders(headers, data);
250 sendHead(client, 200, headers);
251 if (sendContent == true)
252 sendFile(client, data);
253 }
254 }
255 _error->DumpErrors(std::cerr);
256 messages.clear();
257 }
258
259 std::clog << "CLOSE client " << client
260 << " on socket " << sock << std::endl;
261 close(client);
262 }
263 return 0;
264 }