diff --git a/Connector_HTTP/main.cpp b/Connector_HTTP/main.cpp index 11b60bb3..54b25f47 100644 --- a/Connector_HTTP/main.cpp +++ b/Connector_HTTP/main.cpp @@ -26,6 +26,11 @@ namespace Connector_HTTP{ /// Needed for base64_encode function static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + /// Helper for base64_decode function + static inline bool is_base64(unsigned char c) { + return (isalnum(c) || (c == '+') || (c == '/')); + } + /// Used to base64 encode data. Input is the plaintext as std::string, output is the encoded data as std::string. /// \param input Plaintext data to encode. /// \returns Base64 encoded data. @@ -49,6 +54,38 @@ namespace Connector_HTTP{ return ret; }//base64_encode + /// Used to base64 decode data. Input is the encoded data as std::string, output is the plaintext data as std::string. + /// \param input Base64 encoded data to decode. + /// \returns Plaintext decoded data. + std::string base64_decode(std::string const& encoded_string) { + int in_len = encoded_string.size(); + int i = 0; + int j = 0; + int in_ = 0; + unsigned char char_array_4[4], char_array_3[3]; + std::string ret; + while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { + char_array_4[i++] = encoded_string[in_]; in_++; + if (i ==4) { + for (i = 0; i <4; i++){char_array_4[i] = base64_chars.find(char_array_4[i]);} + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + for (i = 0; (i < 3); i++){ret += char_array_3[i];} + i = 0; + } + } + if (i) { + for (j = i; j <4; j++){char_array_4[j] = 0;} + for (j = 0; j <4; j++){char_array_4[j] = base64_chars.find(char_array_4[j]);} + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; + } + return ret; + } + /// Returns AMF-format metadata for Adobe HTTP Dynamic Streaming. std::string GetMetaData( ) { AMF::Object amfreply("container", AMF::AMF0_DDV_CONTAINER); diff --git a/DDV_Controller/Makefile b/DDV_Controller/Makefile index 34c0119d..d34052af 100644 --- a/DDV_Controller/Makefile +++ b/DDV_Controller/Makefile @@ -2,11 +2,16 @@ SRC = main.cpp ../util/json/json_reader.cpp ../util/json/json_value.cpp ../util/ OBJ = $(SRC:.cpp=.o) OUT = DDV_Controller INCLUDES = -CCFLAGS = -Wall -Wextra -funsigned-char -g +DEBUG = 4 +OPTIMIZE = -g +COMPILED_USERNAME = testuser +COMPILED_PASSWORD = 179ad45c6ce2cb97cf1029e212046e81 +#COMPILED_PASSWORD = testpass +CCFLAGS = -Wall -Wextra -funsigned-char $(OPTIMIZE) -DDEBUG=$(DEBUG) -DCOMPILED_USERNAME=$(COMPILED_USERNAME) -DCOMPILED_PASSWORD=$(COMPILED_PASSWORD) CC = $(CROSS)g++ LD = $(CROSS)ld AR = $(CROSS)ar -LIBS = +LIBS = -lssl -lcrypto .SUFFIXES: .cpp .PHONY: clean default default: $(OUT) diff --git a/DDV_Controller/main.cpp b/DDV_Controller/main.cpp index 9d8f1b47..3f7a5f30 100644 --- a/DDV_Controller/main.cpp +++ b/DDV_Controller/main.cpp @@ -23,7 +23,121 @@ #include "../util/http_parser.h" #include "../util/md5.h" #include "../util/json/json.h" +#include "../util/util.h" +#include +#include + +#define defstr(x) #x ///< converts a define name to string + +/// Needed for base64_encode function +static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +/// Helper for base64_decode function +static inline bool is_base64(unsigned char c) { + return (isalnum(c) || (c == '+') || (c == '/')); +} + +/// Used to base64 encode data. Input is the plaintext as std::string, output is the encoded data as std::string. +/// \param input Plaintext data to encode. +/// \returns Base64 encoded data. +std::string base64_encode(std::string const input) { + std::string ret; + unsigned int in_len = input.size(); + char quad[4], triple[3]; + unsigned int i, x, n = 3; + for (x = 0; x < in_len; x = x + 3){ + if ((in_len - x) / 3 == 0){n = (in_len - x) % 3;} + for (i=0; i < 3; i++){triple[i] = '0';} + for (i=0; i < n; i++){triple[i] = input[x + i];} + quad[0] = base64_chars[(triple[0] & 0xFC) >> 2]; // FC = 11111100 + quad[1] = base64_chars[((triple[0] & 0x03) << 4) | ((triple[1] & 0xF0) >> 4)]; // 03 = 11 + quad[2] = base64_chars[((triple[1] & 0x0F) << 2) | ((triple[2] & 0xC0) >> 6)]; // 0F = 1111, C0=11110 + quad[3] = base64_chars[triple[2] & 0x3F]; // 3F = 111111 + if (n < 3){quad[3] = '=';} + if (n < 2){quad[2] = '=';} + for(i=0; i < 4; i++){ret += quad[i];} + } + return ret; +}//base64_encode + +/// Used to base64 decode data. Input is the encoded data as std::string, output is the plaintext data as std::string. +/// \param input Base64 encoded data to decode. +/// \returns Plaintext decoded data. +std::string base64_decode(std::string const& encoded_string) { + int in_len = encoded_string.size(); + int i = 0; + int j = 0; + int in_ = 0; + unsigned char char_array_4[4], char_array_3[3]; + std::string ret; + while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { + char_array_4[i++] = encoded_string[in_]; in_++; + if (i ==4) { + for (i = 0; i <4; i++){char_array_4[i] = base64_chars.find(char_array_4[i]);} + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + for (i = 0; (i < 3); i++){ret += char_array_3[i];} + i = 0; + } + } + if (i) { + for (j = i; j <4; j++){char_array_4[j] = 0;} + for (j = 0; j <4; j++){char_array_4[j] = base64_chars.find(char_array_4[j]);} + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; + } + return ret; +} + +unsigned char __gbv2keypub_der[] = { + 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, + 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, + 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xe5, 0xd7, 0x9c, + 0x7d, 0x73, 0xc6, 0xe6, 0xfb, 0x35, 0x7e, 0xd7, 0x57, 0x99, 0x07, 0xdb, + 0x99, 0x70, 0xc9, 0xd0, 0x3e, 0x53, 0x57, 0x3c, 0x1e, 0x55, 0xda, 0x0f, + 0x69, 0xbf, 0x26, 0x79, 0xc7, 0xb6, 0xdd, 0x8e, 0x83, 0x32, 0x65, 0x74, + 0x0d, 0x74, 0x48, 0x42, 0x49, 0x22, 0x52, 0x58, 0x56, 0xc3, 0xe4, 0x49, + 0x5d, 0xac, 0x6a, 0x94, 0xb1, 0x64, 0x14, 0xbf, 0x4d, 0xd5, 0xd7, 0x3a, + 0xca, 0x5c, 0x1e, 0x6f, 0x42, 0x30, 0xac, 0x29, 0xaa, 0xa0, 0x85, 0xd2, + 0x16, 0xa2, 0x8e, 0x89, 0x12, 0xc4, 0x92, 0x06, 0xea, 0xed, 0x48, 0xf6, + 0xdb, 0xed, 0x4f, 0x62, 0x6c, 0xfa, 0xcf, 0xc2, 0xb9, 0x8d, 0x04, 0xb2, + 0xba, 0x63, 0xc9, 0xcc, 0xee, 0x23, 0x64, 0x46, 0x14, 0x12, 0xc8, 0x38, + 0x67, 0x69, 0x6b, 0xaf, 0xd1, 0x7c, 0xb1, 0xb5, 0x79, 0xe4, 0x4e, 0x3a, + 0xa7, 0xe8, 0x28, 0x89, 0x25, 0xc0, 0xd0, 0xd8, 0xc7, 0xd2, 0x26, 0xaa, + 0xf5, 0xbf, 0x36, 0x55, 0x01, 0x89, 0x58, 0x1f, 0x1e, 0xf5, 0xa5, 0x42, + 0x8f, 0x60, 0x2e, 0xc2, 0xd8, 0x21, 0x0b, 0x6c, 0x8d, 0xbb, 0x72, 0xf2, + 0x19, 0x30, 0xe3, 0x4c, 0x3e, 0x80, 0xe7, 0xf2, 0xe3, 0x89, 0x4f, 0xd4, + 0xee, 0x96, 0x3e, 0x4a, 0x9b, 0xe5, 0x16, 0x01, 0xf1, 0x98, 0xc9, 0x0b, + 0xd6, 0xdf, 0x8a, 0x64, 0x47, 0xc4, 0x44, 0xcc, 0x92, 0x69, 0x28, 0xee, + 0x7d, 0xac, 0xdc, 0x30, 0x56, 0x3a, 0xe7, 0xbc, 0xba, 0x45, 0x16, 0x2c, + 0x4c, 0x46, 0x6b, 0x2b, 0x20, 0xfb, 0x3d, 0x20, 0x35, 0xbb, 0x48, 0x49, + 0x13, 0x65, 0xc9, 0x9a, 0x38, 0x10, 0x84, 0x1a, 0x8c, 0xc9, 0xd7, 0xde, + 0x07, 0x10, 0x5a, 0xfb, 0xb4, 0x95, 0xae, 0x18, 0xf2, 0xe3, 0x15, 0xe8, + 0xad, 0x7e, 0xe5, 0x3c, 0xa8, 0x47, 0x85, 0xd6, 0x1f, 0x54, 0xb5, 0xa3, + 0x79, 0x02, 0x03, 0x01, 0x00, 0x01 +}; ///< The GBv2 public key file. +unsigned int __gbv2keypub_der_len = 294; ///< Length of GBv2 public key data + +RSA * pubkey = 0; ///< Holds the public key for encoding. +/// Attempts to load the public key for encoding. +void RSA_Load(){ + pubkey = d2i_RSAPublicKey(0, (const unsigned char **)(&__gbv2keypub_der), __gbv2keypub_der_len); +} + +/// Attempts to encode the input data using the key loaded with RSA_Load(). +/// Returns raw encoded data as std::string, or empty string on failure. +std::string RSA_enc(std::string & data){ + std::string out = ""; + char * encrypted = (char*)malloc(RSA_size(pubkey)); + int len = RSA_public_encrypt(data.size(), (unsigned char *)data.c_str(), (unsigned char *)encrypted, pubkey, RSA_PKCS1_PADDING); + if (len > 0){out = std::string(encrypted, len);} + free(encrypted); + return out; +} Json::Value Storage = Json::Value(Json::objectValue); ///< Global storage of data. @@ -48,13 +162,14 @@ class ConnectedUser{ Socket::Connection C; HTTP::Parser H; bool Authorized; + bool clientMode; std::string Username; ConnectedUser(Socket::Connection c){ C = c; H.Clean(); Authorized = false; + clientMode = false; } - hasAccess() }; void Log(std::string kind, std::string message){ @@ -83,7 +198,7 @@ void Authorize( Json::Value & Request, Json::Value & Response, ConnectedUser & c return; } } - Log("AUTH", "Failed login attempt "+UserID+" @ "+conn.C.getHost(), Storage); + Log("AUTH", "Failed login attempt "+UserID+" @ "+conn.C.getHost()); } conn.Username = ""; conn.Authorized = false; @@ -96,15 +211,15 @@ void CheckConfig(Json::Value & in, Json::Value & out){ if (in.isObject() && (in.size() > 0)){ for (Json::ValueIterator jit = in.begin(); jit != in.end(); jit++){ if (out.isObject() && out.isMember(jit.memberName())){ - Log("CONF", std::string("Updated configuration value ")+jit.memberName(), Storage); + Log("CONF", std::string("Updated configuration value ")+jit.memberName()); }else{ - Log("CONF", std::string("New configuration value ")+jit.memberName(), Storage); + Log("CONF", std::string("New configuration value ")+jit.memberName()); } } if (out.isObject() && (out.size() > 0)){ for (Json::ValueIterator jit = out.begin(); jit != out.end(); jit++){ if (!in.isMember(jit.memberName())){ - Log("CONF", std::string("Deleted configuration value ")+jit.memberName(), Storage); + Log("CONF", std::string("Deleted configuration value ")+jit.memberName()); } } } @@ -116,15 +231,15 @@ void CheckStreams(Json::Value & in, Json::Value & out){ if (in.isObject() && (in.size() > 0)){ for (Json::ValueIterator jit = in.begin(); jit != in.end(); jit++){ if (out.isObject() && out.isMember(jit.memberName())){ - Log("STRM", std::string("Updated stream ")+jit.memberName(), Storage); + Log("STRM", std::string("Updated stream ")+jit.memberName()); }else{ - Log("STRM", std::string("New stream ")+jit.memberName(), Storage); + Log("STRM", std::string("New stream ")+jit.memberName()); } } if (out.isObject() && (out.size() > 0)){ for (Json::ValueIterator jit = out.begin(); jit != out.end(); jit++){ if (!in.isMember(jit.memberName())){ - Log("STRM", std::string("Deleted stream ")+jit.memberName(), Storage); + Log("STRM", std::string("Deleted stream ")+jit.memberName()); } } } @@ -132,9 +247,14 @@ void CheckStreams(Json::Value & in, Json::Value & out){ out = in; } -int main() { +int main(int argc, char ** argv){ + RSA_Load(); // Load GearBox public key + Util::Config C; + C.confsection = "API"; + C.parseArgs(argc, argv); + C.parseFile(); time_t lastuplink = 0; - Socket::Server API_Socket = Socket::Server(4242, "0.0.0.0", true); + Socket::Server API_Socket = Socket::Server(C.listen_port, C.interface, true); Socket::Server Stats_Socket = Socket::Server("/tmp/ddv_statistics", true); Socket::Connection Incoming; std::vector< ConnectedUser > users; @@ -143,12 +263,11 @@ int main() { Json::Reader JsonParse; std::string jsonp; JsonParse.parse(ReadFile("config.json"), Storage, false); - Storage["config"] = Json::Value(Json::objectValue); - Storage["log"] = Json::Value(Json::arrayValue); - Storage["statistics"] = Json::Value(Json::arrayValue); - Storage["account"]["gearbox"]["password"] = Json::Value("7e0f87b116377621a75a6440ac74dcf4"); + if (!Storage.isMember("config")){Storage["config"] = Json::Value(Json::objectValue);} + if (!Storage.isMember("log")){Storage["log"] = Json::Value(Json::arrayValue);} + if (!Storage.isMember("statistics")){Storage["statistics"] = Json::Value(Json::arrayValue);} while (API_Socket.connected()){ - usleep(10000); //sleep for 10 ms - prevents 100% CPU time + usleep(100000); //sleep for 100 ms - prevents 100% CPU time Incoming = API_Socket.accept(); if (Incoming.connected()){users.push_back(Incoming);} if (users.size() > 0){ @@ -160,43 +279,68 @@ int main() { } if (it->H.Read(it->C)){ Response.clear(); //make sure no data leaks from previous requests - if (!JsonParse.parse(it->H.GetVar("command"), Request, false)){ - Log("HTTP", "Failed to parse JSON: "+it->H.GetVar("command")); - Response["authorize"]["status"] = "INVALID"; - }else{ - std::cout << "Request: " << Request.toStyledString() << std::endl; - Authorize(Request, Response, (*it)); - if (it->Authorized){ - //Parse config and streams from the request. - if (Request.isMember("config")){CheckConfig(Request["config"], Storage["config"]);} - if (Request.isMember("streams")){CheckStreams(Request["streams"], Storage["streams"]);} - //sent current configuration, no matter if it was changed or not - //Response["streams"] = Storage["streams"]; - Response["config"] = Storage["config"]; - //add required data to the current unix time to the config, for syncing reasons - Response["config"]["time"] = (Json::Value::UInt)time(0); - if (!Response["config"].isMember("serverid")){Response["config"]["serverid"] = "";} - //sent any available logs and statistics - Response["log"] = Storage["log"]; - Response["statistics"] = Storage["statistics"]; - //clear log and statistics to prevent useless data transfer - Storage["log"].clear(); - Storage["statistics"].clear(); + if (it->clientMode){ + // In clientMode, requests are reversed. These are connections we initiated to GearBox. + // They are assumed to be authorized, but authorization to gearbox is still done. + // This authorization uses the compiled-in username and password (account). + if (!JsonParse.parse(it->H.body, Request, false)){ + Log("HTTP", "Failed to parse JSON: "+it->H.GetVar("command")); + Response["authorize"]["status"] = "INVALID"; + }else{ + if (Request["authorize"]["status"] != "OK"){ + if (Request["authorize"].isMember("challenge")){ + Response["authorize"]["username"] = defstr(COMPILED_USERNAME); + Response["authorize"]["password"] = md5(defstr(COMPILED_PASSWORD) + Request["authorize"]["challenge"].asString()); + it->H.Clean(); + it->H.SetBody("command="+HTTP::Parser::urlencode(Response.toStyledString())); + it->H.BuildRequest(); + it->C.write(it->H.BuildResponse("200", "OK")); + it->H.Clean(); + } + }else{ + if (Request.isMember("config")){CheckConfig(Request["config"], Storage["config"]);} + if (Request.isMember("streams")){CheckStreams(Request["streams"], Storage["streams"]);} + } } - } - jsonp = ""; - if (it->H.GetVar("callback") != ""){jsonp = it->H.GetVar("callback");} - if (it->H.GetVar("jsonp") != ""){jsonp = it->H.GetVar("jsonp");} - it->H.Clean(); - it->H.protocol = "HTTP/1.0"; - it->H.SetHeader("Content-Type", "text/javascript"); - if (jsonp == ""){ - it->H.SetBody(Response.toStyledString()+"\n\n"); }else{ - it->H.SetBody(jsonp+"("+Response.toStyledString()+");\n\n"); + if (!JsonParse.parse(it->H.GetVar("command"), Request, false)){ + Log("HTTP", "Failed to parse JSON: "+it->H.GetVar("command")); + Response["authorize"]["status"] = "INVALID"; + }else{ + std::cout << "Request: " << Request.toStyledString() << std::endl; + Authorize(Request, Response, (*it)); + if (it->Authorized){ + //Parse config and streams from the request. + if (Request.isMember("config")){CheckConfig(Request["config"], Storage["config"]);} + if (Request.isMember("streams")){CheckStreams(Request["streams"], Storage["streams"]);} + //sent current configuration, no matter if it was changed or not + //Response["streams"] = Storage["streams"]; + Response["config"] = Storage["config"]; + //add required data to the current unix time to the config, for syncing reasons + Response["config"]["time"] = (Json::Value::UInt)time(0); + if (!Response["config"].isMember("serverid")){Response["config"]["serverid"] = "";} + //sent any available logs and statistics + Response["log"] = Storage["log"]; + Response["statistics"] = Storage["statistics"]; + //clear log and statistics to prevent useless data transfer + Storage["log"].clear(); + Storage["statistics"].clear(); + } + } + jsonp = ""; + if (it->H.GetVar("callback") != ""){jsonp = it->H.GetVar("callback");} + if (it->H.GetVar("jsonp") != ""){jsonp = it->H.GetVar("jsonp");} + it->H.Clean(); + it->H.protocol = "HTTP/1.0"; + it->H.SetHeader("Content-Type", "text/javascript"); + if (jsonp == ""){ + it->H.SetBody(Response.toStyledString()+"\n\n"); + }else{ + it->H.SetBody(jsonp+"("+Response.toStyledString()+");\n\n"); + } + it->C.write(it->H.BuildResponse("200", "OK")); + it->H.Clean(); } - it->C.write(it->H.BuildResponse("200", "OK")); - it->H.Clean(); } } } diff --git a/util/http_parser.cpp b/util/http_parser.cpp index da800130..f46e5a2b 100644 --- a/util/http_parser.cpp +++ b/util/http_parser.cpp @@ -16,32 +16,20 @@ void HTTP::Parser::Clean(){ protocol = "HTTP/1.1"; body.clear(); length = 0; - HTTPbuffer.clear(); headers.clear(); vars.clear(); } /// Re-initializes the HTTP::Parser, leaving the internal data buffer alone, then tries to parse a new request or response. -/// First does the same as HTTP::Parser::Clean(), but does not clear the internal data buffer. -/// This function then calls the HTTP::Parser::parse() function, and returns that functions return value. +/// Does the same as HTTP::Parser::Clean(), then returns HTTP::Parser::parse(). bool HTTP::Parser::CleanForNext(){ - seenHeaders = false; - seenReq = false; - method = "GET"; - url = "/"; - protocol = "HTTP/1.1"; - body = ""; - length = 0; - headers.clear(); - vars.clear(); + Clean(); return parse(); } /// Returns a string containing a valid HTTP 1.0 or 1.1 request, ready for sending. /// The request is build from internal variables set before this call is made. -/// To be precise, method, url, protocol, headers and the internal data buffer are used, -/// where the internal data buffer is used as the body of the request. -/// This means you cannot mix receiving and sending, because the body would get corrupted. +/// To be precise, method, url, protocol, headers and body are used. /// \return A string containing a valid HTTP 1.0 or 1.1 request, ready for sending. std::string HTTP::Parser::BuildRequest(){ /// \todo Include GET/POST variable parsing? @@ -51,15 +39,13 @@ std::string HTTP::Parser::BuildRequest(){ tmp += (*it).first + ": " + (*it).second + "\n"; } tmp += "\n"; - tmp += HTTPbuffer; + tmp += body; return tmp; } /// Returns a string containing a valid HTTP 1.0 or 1.1 response, ready for sending. /// The response is partly build from internal variables set before this call is made. -/// To be precise, protocol, headers and the internal data buffer are used, -/// where the internal data buffer is used as the body of the response. -/// This means you cannot mix receiving and sending, because the body would get corrupted. +/// To be precise, protocol, headers and body are used. /// \param code The HTTP response code. Usually you want 200. /// \param message The HTTP response message. Usually you want "OK". /// \return A string containing a valid HTTP 1.0 or 1.1 response, ready for sending. @@ -71,7 +57,7 @@ std::string HTTP::Parser::BuildResponse(std::string code, std::string message){ tmp += (*it).first + ": " + (*it).second + "\n"; } tmp += "\n"; - tmp += HTTPbuffer; + tmp += body; return tmp; } @@ -87,7 +73,7 @@ void HTTP::Parser::Trim(std::string & s){ /// Function that sets the body of a response or request, along with the correct Content-Length header. /// \param s The string to set the body to. void HTTP::Parser::SetBody(std::string s){ - HTTPbuffer = s; + body = s; SetHeader("Content-Length", s.length()); } @@ -95,8 +81,8 @@ void HTTP::Parser::SetBody(std::string s){ /// \param buffer The buffer data to set the body to. /// \param len Length of the buffer data. void HTTP::Parser::SetBody(char * buffer, int len){ - HTTPbuffer = ""; - HTTPbuffer.append(buffer, len); + body = ""; + body.append(buffer, len); SetHeader("Content-Length", len); } @@ -265,8 +251,8 @@ void HTTP::Parser::SendBodyPart(Socket::Connection & conn, std::string bodypart) } } -/// Unescapes URLencoded std::strings. -std::string HTTP::Parser::urlunescape(std::string in){ +/// Unescapes URLencoded std::string data. +std::string HTTP::Parser::urlunescape(const std::string & in){ std::string out; for (unsigned int i = 0; i < in.length(); ++i){ if (in[i] == '%'){ @@ -292,3 +278,33 @@ std::string HTTP::Parser::urlunescape(std::string in){ int HTTP::Parser::unhex(char c){ return( c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : c - 'a' + 10 ); } + +/// URLencodes std::string data. +std::string HTTP::Parser::urlencode(const std::string &c){ + std::string escaped=""; + int max = c.length(); + for(int i=0; i>4; + char dig2 = (dec&0x0F); + if (dig1<= 9) dig1+=48; + if (10<= dig1 && dig1<=15) dig1+=97-10; + if (dig2<= 9) dig2+=48; + if (10<= dig2 && dig2<=15) dig2+=97-10; + std::string r; + r.append(&dig1, 1); + r.append(&dig2, 1); + return r; +} diff --git a/util/http_parser.h b/util/http_parser.h index a38b94e1..6172ac00 100644 --- a/util/http_parser.h +++ b/util/http_parser.h @@ -30,7 +30,8 @@ namespace HTTP{ void SendBodyPart(Socket::Connection & conn, std::string bodypart); void Clean(); bool CleanForNext(); - std::string urlunescape(std::string in); + static std::string urlunescape(const std::string & in); + static std::string urlencode(const std::string & in); std::string body; std::string method; std::string url; @@ -45,6 +46,7 @@ namespace HTTP{ std::map headers; std::map vars; void Trim(std::string & s); - int unhex(char c); ///< Helper function for urlunescape. + static int unhex(char c); + static std::string hex(char dec); };//HTTP::Parser class };//HTTP namespace diff --git a/util/server_setup.cpp b/util/server_setup.cpp index 23a5422e..34327442 100644 --- a/util/server_setup.cpp +++ b/util/server_setup.cpp @@ -159,10 +159,10 @@ int main(int argc, char ** argv){ if (server_socket.connected()){ //if setup success, enter daemon mode if requested if (daemon_mode){ - daemon(1, 0); #if DEBUG >= 3 fprintf(stderr, "Going into background mode...\n"); #endif + daemon(1, 0); } }else{ #if DEBUG >= 1 diff --git a/util/util.cpp b/util/util.cpp index 3f5b6495..687dba58 100644 --- a/util/util.cpp +++ b/util/util.cpp @@ -1,17 +1,19 @@ /// \file util.cpp /// Contains generic functions for managing processes and configuration. -#include "proc.h" +#include "util.h" #include #include #include #include #include -#if DEBUG >= 1 #include -#endif #include #include +#include +#include +#include +#include std::map Util::Procs::plist; bool Util::Procs::handler_set = false; @@ -24,7 +26,7 @@ void Util::setUser(std::string username){ #if DEBUG >= 1 fprintf(stderr, "Error: could not setuid %s: could not get PID\n", username.c_str()); #endif - return 1; + return; }else{ if (setuid(user_info->pw_uid) != 0){ #if DEBUG >= 1 @@ -260,6 +262,77 @@ Util::Config::Config(){ ignore_user = false; } -void parseArgs(int argc, char ** argv){ - -} \ No newline at end of file +/// Parses commandline arguments. +/// Calls exit if an unknown option is encountered, printing a help message. +/// Assumes confsection is set. +void Util::Config::parseArgs(int argc, char ** argv){ + int opt = 0; + static const char *optString = "ndp:i:u:c:h?"; + static const struct option longOpts[] = { + {"help",0,0,'h'}, + {"port",1,0,'p'}, + {"interface",1,0,'i'}, + {"username",1,0,'u'}, + {"no-daemon",0,0,'n'}, + {"daemon",0,0,'d'}, + {"configfile",1,0,'c'} + }; + while ((opt = getopt_long(argc, argv, optString, longOpts, 0)) != -1){ + switch (opt){ + case 'p': listen_port = atoi(optarg); ignore_port = true; break; + case 'i': interface = optarg; ignore_interface = true; break; + case 'n': daemon_mode = false; ignore_daemon = true; break; + case 'd': daemon_mode = true; ignore_daemon = true; break; + case 'c': configfile = optarg; break; + case 'u': username = optarg; ignore_user = true; break; + case 'h': + case '?': + printf("Options: -h[elp], -?, -n[odaemon], -d[aemon], -p[ort] VAL, -i[nterface] VAL, -c[onfigfile] VAL, -u[sername] VAL\n"); + printf("Defaults:\n interface: 0.0.0.0\n port: %i\n daemon mode: true\n configfile: /etc/ddvtech.conf\n username: root\n", listen_port); + printf("Username root means no change to UID, no matter what the UID is.\n"); + printf("If the configfile exists, it is always loaded first. Commandline settings then overwrite the config file.\n"); + printf("\nThis process takes it directives from the %s section of the configfile.\n", confsection.c_str()); + exit(1); + break; + } + }//commandline options parser +} + +/// Parses the configuration file at configfile, if it exists. +/// Assumes confsection is set. +void Util::Config::parseFile(){ + std::ifstream conf(configfile.c_str(), std::ifstream::in); + std::string tmpstr; + bool acc_comm = false; + size_t foundeq; + if (conf.fail()){ + #if DEBUG >= 3 + fprintf(stderr, "Configuration file %s not found - using build-in defaults...\n", configfile.c_str()); + #endif + }else{ + while (conf.good()){ + getline(conf, tmpstr); + if (tmpstr[0] == '['){//new section? check if we care. + if (tmpstr == confsection){acc_comm = true;}else{acc_comm = false;} + }else{ + if (!acc_comm){break;}//skip all lines in this section if we do not care about it + foundeq = tmpstr.find('='); + if (foundeq != std::string::npos){ + if ((tmpstr.substr(0, foundeq) == "port") && !ignore_port){listen_port = atoi(tmpstr.substr(foundeq+1).c_str());} + if ((tmpstr.substr(0, foundeq) == "interface") && !ignore_interface){interface = tmpstr.substr(foundeq+1);} + if ((tmpstr.substr(0, foundeq) == "username") && !ignore_user){username = tmpstr.substr(foundeq+1);} + if ((tmpstr.substr(0, foundeq) == "daemon") && !ignore_daemon){daemon_mode = true;} + if ((tmpstr.substr(0, foundeq) == "nodaemon") && !ignore_daemon){daemon_mode = false;} + }//found equals sign + }//section contents + }//configfile line loop + }//configuration +} + +/// Will turn the current process into a daemon. +/// Works by calling daemon(1,0): +/// Does not change directory to root. +/// Does redirect output to /dev/null +void Util::Daemonize(){ + daemon(1, 0); +} diff --git a/util/util.h b/util/util.h index 4037a9ca..31c8c3aa 100644 --- a/util/util.h +++ b/util/util.h @@ -29,7 +29,7 @@ namespace Util{ }; /// Will set the active user to the named username. - static setUser(std::string user); + void setUser(std::string user); /// Deals with parsing configuration from files or commandline options. class Config{ @@ -39,6 +39,7 @@ namespace Util{ bool ignore_port; bool ignore_user; public: + std::string confsection; std::string configfile; bool daemon_mode; std::string interface; @@ -46,8 +47,9 @@ namespace Util{ std::string username; Config(); void parseArgs(int argc, char ** argv); + void parseFile(); }; - + /// Will turn the current process into a daemon. void Daemonize();