]> git.sesse.net Git - cubemap/blob - input.cpp
When create_input() fails, give an error message instead of crashing.
[cubemap] / input.cpp
1 #include <string.h>
2 #include <string>
3
4 #include "httpinput.h"
5 #include "input.h"
6 #include "state.pb.h"
7
8 using namespace std;
9
10 // Extremely rudimentary URL parsing.
11 bool parse_url(const string &url, string *protocol, string *host, string *port, string *path)
12 {
13         if (url.find("http://") != 0) {
14                 return false;
15         }
16
17         *protocol = "http";
18         
19         string rest = url.substr(strlen("http://"));
20         size_t split = rest.find_first_of(":/");
21         if (split == string::npos) {
22                 // http://foo
23                 *host = rest;
24                 *port = "http";
25                 *path = "/";
26                 return true;
27         }
28
29         *host = string(rest.begin(), rest.begin() + split);
30         char ch = rest[split];  // Colon or slash.
31         rest = string(rest.begin() + split + 1, rest.end());
32
33         if (ch == ':') {
34                 // Parse the port.
35                 split = rest.find_first_of('/');
36                 if (split == string::npos) {
37                         // http://foo:1234
38                         *port = rest;
39                         *path = "/";
40                         return true;
41                 } else {
42                         // http://foo:1234/bar
43                         *port = string(rest.begin(), rest.begin() + split);
44                         *path = string(rest.begin() + split, rest.end());
45                         return true;
46                 }
47         }
48
49         // http://foo/bar
50         *port = "http";
51         *path = rest;
52         return true;
53 }
54
55 Input *create_input(const std::string &stream_id, const std::string &url)
56 {
57         string protocol, host, port, path;
58         if (!parse_url(url, &protocol, &host, &port, &path)) {
59                 return NULL;
60         }
61         if (protocol == "http") {
62                 return new HTTPInput(stream_id, url);
63         }
64         return NULL;
65 }
66
67 Input *create_input(const InputProto &serialized)
68 {
69         string protocol, host, port, path;
70         if (!parse_url(serialized.url(), &protocol, &host, &port, &path)) {
71                 return NULL;
72         }
73         if (protocol == "http") {
74                 return new HTTPInput(serialized);
75         }
76         return NULL;
77 }
78
79 Input::~Input() {}
80