1 |
|
|
/** |
2 |
|
|
* This file is part of the CernVM File System |
3 |
|
|
*/ |
4 |
|
|
|
5 |
|
|
#ifndef __STDC_FORMAT_MACROS |
6 |
|
|
#define __STDC_FORMAT_MACROS |
7 |
|
|
#endif |
8 |
|
|
|
9 |
|
|
#include "cvmfs_config.h" |
10 |
|
|
#include "uri_map.h" |
11 |
|
|
|
12 |
|
|
#include <inttypes.h> |
13 |
|
|
|
14 |
|
|
#include <cassert> |
15 |
|
|
|
16 |
|
|
using namespace std; // NOLINT |
17 |
|
|
|
18 |
|
|
WebRequest::WebRequest(const struct mg_request_info *req) { |
19 |
|
|
string method = req->request_method; |
20 |
|
|
if (method == "GET") |
21 |
|
|
verb_ = WebRequest::kGet; |
22 |
|
|
else if (method == "PUT") |
23 |
|
|
verb_ = WebRequest::kPut; |
24 |
|
|
else if (method == "POST") |
25 |
|
|
verb_ = WebRequest::kPost; |
26 |
|
|
else if (method == "DELETE") |
27 |
|
|
verb_ = WebRequest::kDelete; |
28 |
|
|
else |
29 |
|
|
verb_ = WebRequest::kUnknown; |
30 |
|
|
uri_ = req->uri; |
31 |
|
|
} |
32 |
|
|
|
33 |
|
|
|
34 |
|
|
//------------------------------------------------------------------------------ |
35 |
|
|
|
36 |
|
|
|
37 |
|
|
void WebReply::Send(Code code, const string &msg, struct mg_connection *conn) { |
38 |
|
|
string header; |
39 |
|
|
switch (code) { |
40 |
|
|
case k200: header = "HTTP/1.1 200 OK\r\n"; break; |
41 |
|
|
case k400: header = "HTTP/1.1 400 Bad Request\r\n"; break; |
42 |
|
|
case k404: header = "HTTP/1.1 404 Not Found\r\n"; break; |
43 |
|
|
case k405: header = "HTTP/1.1 405 Method Not Allowed\r\n"; break; |
44 |
|
|
case k500: header = "HTTP/1.1 500 Internal Server Error\r\n"; break; |
45 |
|
|
default: assert(false); |
46 |
|
|
} |
47 |
|
|
mg_printf(conn, |
48 |
|
|
"%s" |
49 |
|
|
"Content-Type: text/plain\r\n" |
50 |
|
|
"Content-Length: %" PRIuPTR "\r\n" |
51 |
|
|
"\r\n" |
52 |
|
|
"%s", header.c_str(), msg.length(), msg.c_str()); |
53 |
|
|
} |
54 |
|
|
|
55 |
|
|
|
56 |
|
|
//------------------------------------------------------------------------------ |
57 |
|
|
|
58 |
|
|
|
59 |
|
|
void UriMap::Clear() { |
60 |
|
|
rules_.clear(); |
61 |
|
|
} |
62 |
|
|
|
63 |
|
|
void UriMap::Register(const WebRequest &request, UriHandler *handler) { |
64 |
|
|
Pathspec path_spec(request.uri()); |
65 |
|
|
assert(path_spec.IsValid() && path_spec.IsAbsolute()); |
66 |
|
|
rules_.push_back(Match(path_spec, request.verb(), handler)); |
67 |
|
|
} |
68 |
|
|
|
69 |
|
|
|
70 |
|
|
UriHandler *UriMap::Route(const WebRequest &request) { |
71 |
|
|
for (unsigned i = 0; i < rules_.size(); ++i) { |
72 |
|
|
if ( (rules_[i].uri_spec.IsPrefixMatching(request.uri())) && |
73 |
|
|
(rules_[i].verb == request.verb()) ) |
74 |
|
|
{ |
75 |
|
|
return rules_[i].handler; |
76 |
|
|
} |
77 |
|
|
} |
78 |
|
|
return NULL; |
79 |
|
|
} |
80 |
|
|
|
81 |
|
|
|
82 |
|
|
bool UriMap::IsKnownUri(const std::string &uri) { |
83 |
|
|
for (unsigned i = 0; i < rules_.size(); ++i) { |
84 |
|
|
if (rules_[i].uri_spec.IsPrefixMatching(uri)) |
85 |
|
|
return true; |
86 |
|
|
} |
87 |
|
|
return false; |
88 |
|
|
} |