]> git.saurik.com Git - apt.git/blob - test/interactive-helper/aptwebserver.cc
3c476ad056905da92f127dbf5b4e76ca4978d059
[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 bool sendHead(int client, int httpcode, std::list<std::string> &headers) { /*{{{*/
82 string response("HTTP/1.1 ");
83 response.append(httpcodeToStr(httpcode));
84 headers.push_front(response);
85
86 headers.push_back("Server: APT webserver");
87
88 std::string date("Date: ");
89 date.append(TimeRFC1123(time(NULL)));
90 headers.push_back(date);
91
92 std::clog << ">>> RESPONSE >>>" << std::endl;
93 bool Success = true;
94 for (std::list<std::string>::const_iterator h = headers.begin();
95 Success == true && h != headers.end(); ++h) {
96 Success &= FileFd::Write(client, h->c_str(), h->size());
97 Success &= FileFd::Write(client, "\r\n", 2);
98 std::clog << *h << std::endl;
99 }
100 Success &= FileFd::Write(client, "\r\n", 2);
101 std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
102 return Success;
103 } /*}}}*/
104
105 bool sendFile(int client, FileFd &data) { /*{{{*/
106 bool Success = true;
107 char buffer[500];
108 unsigned long long actual = 0;
109 while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true) {
110 if (actual == 0)
111 break;
112 Success &= FileFd::Write(client, buffer, actual);
113 }
114 Success &= FileFd::Write(client, "\r\n", 2);
115 return Success;
116 } /*}}}*/
117
118 bool sendData(int client, std::string &data) { /*{{{*/
119 bool Success = true;
120 Success &= FileFd::Write(client, data.c_str(), data.size());
121 Success &= FileFd::Write(client, "\r\n", 2);
122 return Success;
123 } /*}}}*/
124
125 void sendError(int client, int httpcode, string request, bool content) { /*{{{*/
126 std::list<std::string> headers;
127 sendHead(client, httpcode, headers);
128 if (content == false)
129 return;
130 string response("<html><head><title>");
131 response.append(httpcodeToStr(httpcode)).append("</title></head>");
132 response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
133 response.append("This error is a result of the request: <pre>");
134 response.append(request).append("</pre></body></html>");
135 sendData(client, response);
136 } /*}}}*/
137
138 int main(int argc, const char *argv[])
139 {
140 CommandLine::Args Args[] = {
141 {0, "simulate-paywall", "aptwebserver::Simulate-Paywall",
142 CommandLine::Boolean},
143 {0, "port", "aptwebserver::port", CommandLine::HasArg},
144 {0,0,0,0}
145 };
146
147 CommandLine CmdL(Args, _config);
148 if(pkgInitConfig(*_config) == false || CmdL.Parse(argc,argv) == false) {
149 _error->DumpErrors();
150 exit(1);
151 }
152
153 // create socket, bind and listen to it {{{
154 int sock = socket(AF_INET6, SOCK_STREAM, 0);
155 if(sock < 0 ) {
156 _error->Errno("aptwerbserver", "Couldn't create socket");
157 _error->DumpErrors(std::cerr);
158 return 1;
159 }
160
161 // get the port
162 int const port = _config->FindI("aptwebserver::port", 8080);
163 bool const simulate_broken_server = _config->FindB("aptwebserver::Simulate-Paywall", false);
164
165 // ensure that we accept all connections: v4 or v6
166 int const iponly = 0;
167 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
168 // to not linger to an address
169 int const enable = 1;
170 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
171
172 struct sockaddr_in6 locAddr;
173 memset(&locAddr, 0, sizeof(locAddr));
174 locAddr.sin6_family = AF_INET6;
175 locAddr.sin6_port = htons(port);
176 locAddr.sin6_addr = in6addr_any;
177
178 if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0) {
179 _error->Errno("aptwerbserver", "Couldn't bind");
180 _error->DumpErrors(std::cerr);
181 return 2;
182 }
183
184 if (simulate_broken_server) {
185 std::clog << "Simulating a broken web server that return nonsense "
186 "for all querries" << std::endl;
187 } else {
188 std::clog << "Serving ANY file on port: " << port << std::endl;
189 }
190
191 listen(sock, 1);
192
193 std::vector<std::string> messages;
194 int client;
195 while ((client = accept(sock, NULL, NULL)) != -1) {
196 std::clog << "ACCEPT client " << client
197 << " on socket " << sock << std::endl;
198
199 while (ReadMessages(client, messages)) {
200 for (std::vector<std::string>::const_iterator m = messages.begin();
201 m != messages.end(); ++m) {
202 std::clog << ">>> REQUEST >>>>" << std::endl << *m
203 << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
204 std::list<std::string> headers;
205 bool sendContent = true;
206 if (strncmp(m->c_str(), "HEAD ", 5) == 0)
207 sendContent = false;
208 if (strncmp(m->c_str(), "GET ", 4) != 0)
209 sendError(client, 501, *m, true);
210
211 std::string host = LookupTag(*m, "Host", "");
212 if (host.empty() == true) {
213 // RFC 2616 ยง14.23 Host
214 sendError(client, 400, *m, sendContent);
215 continue;
216 }
217
218 size_t const filestart = m->find(' ', 5);
219 string filename = m->substr(5, filestart - 5);
220
221 if (simulate_broken_server == true) {
222 sendHead(client, 200, headers);
223 string data("ni ni ni");
224 sendData(client, data);
225 }
226 else if (RealFileExists(filename) == false)
227 sendError(client, 404, *m, sendContent);
228 else {
229 FileFd data(filename, FileFd::ReadOnly);
230 std::string condition = LookupTag(*m, "If-Modified-Since", "");
231 if (condition.empty() == false) {
232 time_t cache;
233 if (RFC1123StrToTime(condition.c_str(), cache) == true &&
234 cache >= data.ModificationTime()) {
235 sendError(client, 304, *m, false);
236 continue;
237 }
238 }
239 addFileHeaders(headers, data);
240 sendHead(client, 200, headers);
241 if (sendContent == true)
242 sendFile(client, data);
243 }
244 }
245 _error->DumpErrors(std::cerr);
246 messages.clear();
247 }
248
249 std::clog << "CLOSE client " << client
250 << " on socket " << sock << std::endl;
251 close(client);
252 }
253 return 0;
254 }