int ICACHE_FLASH_ATTR stledOps(HttpdConnData *connData) { int i, r; jsmn_parser p; jsmntok_t t[16]; /* We expect no more than 16 tokens */ char *json = connData->post->buff; if (connData->requestType == HTTPD_METHOD_OPTIONS) { sendJSON(connData); HTTPD_SEND_STR("{\"status\":\"ok\"}\r\n\r\n"); return HTTPD_CGI_DONE; } else if (connData->requestType == HTTPD_METHOD_GET) { sendJSON(connData); HTTPD_PRINTF("{\"status_led\": \"%s\"}\r\n\r\n", opStr[opState]); return HTTPD_CGI_DONE; } jsmn_init(&p); r = jsmn_parse(&p, json, strlen(json), t, sizeof(t)/sizeof(t[0])); if (r < 0) { ERROR("[json] Failed to parse JSON: %d", r); goto err; } else DEBUG("[json]: OK. %d tokens\n", r); /* Assume the top-level element is an object */ if (r < 1 || t[0].type != JSMN_OBJECT) { ERROR("Object expected\n"); goto err; } /* Loop over all keys of the root object */ for (i = 1; i < r; ) { if (jsonEq(json, &t[i], "status_led") && i + 1 < r) { if (jsonEq(json, &t[i+1], "on")) stledSet(STLED_ON); else if (jsonEq(json, &t[i+1], "off")) stledSet(STLED_OFF); else if (jsonEq(json, &t[i+1], "blink")) stledSet(STLED_BLINK_SLOW); else if (jsonEq(json, &t[i+1], "blink_fast")) stledSet(STLED_BLINK_FAST); else if (jsonEq(json, &t[i+1], "blink_slow")) stledSet(STLED_BLINK_SLOW); else if (jsonEq(json, &t[i+1], "blink_hb")) stledSet(STLED_BLINK_HB); i += 2; } else { //os_printf("BAD token %d: %s [%d,%d] sz=%d\n", i, type[t[i].type], t[i].start, t[i].end, t[i].size); ERROR("BAD token %d: type=%d [%d,%d] sz=%d", i, t[i].type, t[i].start, t[i].end, t[i].size); i++; } } sendOK(connData, "OK"); return HTTPD_CGI_DONE; err: sendOK(connData, "Error"); // FIXME return HTTPD_CGI_DONE; }
void AdminConnection::processLogin(){ InputFrame::Ptr recvframe( new InputFrame(version, paddingfilter) ); if (readFrame(recvframe)) { try { if(recvframe->getType() == ft02_Login){ std::string username, password; if ( getAuth( recvframe, username, password ) ) { bool authenticated = false; try{ if(username == Settings::getSettings()->get("admin_user") && password == Settings::getSettings()->get("admin_pass")) authenticated = true; }catch(std::exception e){ } if(authenticated){ sendOK( recvframe, "Welcome" ); INFO("Admin login ok by %s", username.c_str()); logextid = Logger::getLogger()->addLog( LogSink::Ptr( new AdminLogger( boost::dynamic_pointer_cast<AdminConnection>(shared_from_this()) ) ) ); status = READY; } else { throw FrameException( fec_FrameError, "Admin Login Error - bad username or password"); // TODO - should be a const or enum, Login error } } }else{ throw FrameException( fec_FrameError, "Wrong type of frame in this state, wanted login"); } } catch ( FrameException& exception ) { // This might be overkill later, but now let's log it DEBUG( "AdminConnection caught FrameException : %s", exception.what() ); sendFail( recvframe, exception.getErrorCode(), exception.getErrorMessage() ); } } }
void Session::handleMODE(const std::string& arg) { if (arg == "S") sendOK(); else sendReply(504, "Command not implemented for that parameter."); }
void UPnP::processPacket(BaseLib::Http& http) { try { BaseLib::Http::Header& header = http.getHeader(); if(header.method != "M-SEARCH" || header.fields.find("st") == header.fields.end() || header.host.empty()) return; BaseLib::HelperFunctions::toLower(header.fields.at("st")); if(header.fields.at("st") == "urn:schemas-upnp-org:device:basic:1" || header.fields.at("st") == "urn:schemas-upnp-org:device:basic:1.0" || header.fields.at("st") == "ssdp:all" || header.fields.at("st") == "upnp:rootdevice" || header.fields.at("st") == _st) { if(GD::bl->debugLevel >= 5) _out.printDebug("Debug: Discovery packet received from " + header.host); std::pair<std::string, std::string> address = BaseLib::HelperFunctions::splitLast(header.host, ':'); int32_t port = BaseLib::Math::getNumber(address.second, false); if(!address.first.empty() && port > 0) { int32_t mx = 500; if(header.fields.find("mx") != header.fields.end()) mx = BaseLib::Math::getNumber(header.fields.at("mx"), false) * 1000; std::this_thread::sleep_for(std::chrono::milliseconds(20)); //Wait for 0 to mx seconds for load balancing if(mx > 500) { mx = BaseLib::HelperFunctions::getRandomNumber(0, mx - 500); GD::out.printDebug("Debug: Sleeping " + std::to_string(mx) + "ms before sending response."); std::this_thread::sleep_for(std::chrono::milliseconds(mx)); } sendOK(address.first, port, header.fields.at("st") == "upnp:rootdevice"); std::this_thread::sleep_for(std::chrono::milliseconds(100)); sendNotify(); } } } catch(const std::exception& ex) { _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what()); } catch(BaseLib::Exception& ex) { _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what()); } catch(...) { _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__); } }
void Session::handlePORT(const std::string& arg) { unsigned parts[6]; if (std::sscanf(arg.c_str(), "%u,%u,%u,%u,%u,%u", parts, parts + 1, parts + 2, parts + 3, parts + 4, parts + 5) != 6) { sendReply(504, "Command not implemented for that parameter."); return; } uint32_t addr = (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]; uint16_t port = (parts[4] << 8) | parts[5]; m_data_addr = addr; m_data_port = port; m_data_pasv = false; sendOK(); }
void Janitor::tidyUp() { size_t found; std::string status; std::string problem; bool flapping; time_t deltatime; mongo::auto_ptr<mongo::DBClientCursor> cursor = c->query( config->reportColl, mongo::BSONObj() ); while( cursor->more() ) { const std::string coll = config->reportColl; mongo::BSONObj p = cursor->next(); status = p.getStringField( "status" ); found = status.find( "PROBLEM" ); flapping = p.getBoolField( "flapping" ); deltatime = time( 0 ) - p.getIntField( "new_timestamp" ); problem = p.getStringField( "problem"); if( flapping && deltatime > flaptime && found == 0 ) { mongo::BSONObjBuilder* b; b = new mongo::BSONObjBuilder; b->append( "flapping" , !flapping ); b->append( "status", "OK" ); mongo::BSONObj tp = b->obj(); c->update( coll, mongo::BSONObjBuilder().append( "problem", problem.c_str() ).obj(), BSON( "$set" << tp), 1, 0 ); delete b; sendOK( problem ); } } }
void testChannel(void) { sendOK(); }
void changeMotorState(unsigned char side, unsigned char state) { motors_changeMotorState(side, state); sendOK(); }
/*Respond Client Request Function Variable Definition: -- request: client request line -- header: client header lines -- client_socket: socket connected to the client Return Value: NULL */ void respondClientRequest(char *request, RTSP_HEADER *header, int client_socket) { char method[STRING_SIZE]; //method field: SETUP, PLAY, PAUSE, or TEARDOWN char url[STRING_SIZE]; //url field: for example, rtsp://localhost:5678/movie.Mjpeg char version[STRING_SIZE]; //rtsp version field: RTSP/1.0 char field_value[HALFBUF_SIZE]; //field value string u_int32 cseq_number = 0; //cseq number //Initialize method, url, version, and field_value buffer memset(method, 0, STRING_SIZE); memset(url, 0, STRING_SIZE); memset(version, 0, STRING_SIZE); memset(field_value, 0, HALFBUF_SIZE); //Test the client RTSP Request Line if (!syntaxChecking(request, REQUEST_LINE)) { //400 Bad Request: the request could not be understood by the server sendBadRequest("Request Line is syntactically incorrect!", client_socket); return; } //Get the method, url, and rtsp version sscanf(request, "%s%s%s", method, url, version); //Decode the URL(if it has %HEX code) decodeURL(url); //Test the method if (methodNotAllow(method)) { //405 Method Not Allowed: the method field is neither "SETUP", "PLAY", "PAUSE" nor "TEARDOWN" sendMethodNotAllowed(method, client_socket); return; } //Test the Requested URL else if (!syntaxChecking(url, URL_FORMAT)) { //400 Bad Request: the request could not be understood by the server sendBadRequest("Requested URL is syntactically incorrect!", client_socket); return; } //Test the RTSP version else if (!syntaxChecking(version, RTSP_VERSION)) { //400 Bad Request: the request could not be understood by the server sendBadRequest("RTSP Version is syntactically incorrect!", client_socket); return; } //Test the RTSP version 1.0 else if (!syntaxChecking(version, RTSP_VERSION_1)) { //505 RTSP Version Not Supported: the requested RTSP protocol version is not supported by server sendRTSPVersionNotSupported(version, client_socket); return; } #ifdef DEBUG RTSP_HEADER *debug_header_node; DEBUG_START; fputs("RTSP request header lines:\n", stdout); //Output the RTSP request header lines for (debug_header_node = header->next; debug_header_node != NULL; debug_header_node = debug_header_node->next) { fputs(debug_header_node->field_name, stdout); fputs(": ", stdout); fputs(debug_header_node->field_value, stdout); fputc('\n', stdout); } DEBUG_END; #endif //Test the Header Line if (headerLinesIncorrect(header, field_value)) { //400 Bad Request: the request could not be understood by the server sendBadRequest(field_value, client_socket); return; } //Test the "CSeq" field else if (fieldNotExist(header, "cseq", field_value)) { //400 Bad Request: the request could not be understood by the server sendBadRequest("CSeq field does not exist!", client_socket); return; } //Test the "Session" field else if ((!methodIsSetup(method)) && fieldNotExist(header, "session", field_value)) { //400 Bad Request: the request could not be understood by the server sendBadRequest("Session field does not exist!", client_socket); return; } //Test the "Transport" field else if (methodIsSetup(method) && fieldNotExist(header, "transport", field_value)) { //400 Bad Request: the request could not be understood by the server sendBadRequest("Transport field does not exist!", client_socket); return; } //Test the "Range" field else if ((!(fieldNotExist(header, "range", field_value))) && (!syntaxChecking(field_value, RANGE_FORMAT))) { //400 Bad Request: the request could not be understood by the server sendBadRequest("Range field value(npt=number[-number]) is syntactically incorrect!", client_socket); return; } //Test the "If-Modified-Since" field else if ((!(fieldNotExist(header, "if-modified-since", field_value))) && (!syntaxChecking(field_value, TIME_FORMAT))) { //400 Bad Request: the request could not be understood by the server sendBadRequest("If-Modified-Since field value(time format) is syntactically incorrect!", client_socket); return; } //Now we are sure that the request message is SYNTACTICALLY CORRECT //Get the Requested File or Directory's name pathBelowCurrentDirectory(url); printf("Requested File or Directory is %s\n", url); //Test the requested file on the server if (urlNotExist(url)) { //404 Not Found: the requested document does not exist on this server sendNotFound(url, client_socket); return; } //Test the requested url is a directory else if (urlIsADirectory(url)) { //404 Not Found: the requested document does not exist on this server sendNotFound(url, client_socket); return; } //Test the method is valid in special state else if (methodIsNotValidInState(method)) { //455 Method is not valid in this state: the method is not valid in this state sendMethodNotValidInThisState(method, client_socket); return; } //Get the RTSP Request Message information cseq_number = getRTSPInfo(header); //Test the "Session" field's value if (cseq_number == 0) { //454 Session Not Found: the session id is not equal to the server's sendSessionNotFound(client_socket); return; } //Test the protocol type else if (strcmp(protocol_type, PROTOCOL_TYPE) != 0) { //461 Unsupported Transport: the transport protocol is not supported by the server sendUnsupportedTransport(protocol_type, client_socket); return; } //Test the "If-Modified-Since" field else if (fieldNotExist(header, "if-modified-since", field_value)) { //200 OK: the request is good sendOK(url, method, cseq_number, client_socket); return; } //Test the "If-Modified-Since" field value else if (compareModifiedTime(url, field_value)) { //304 Not Modified: the request does not Modified since If-Modified-Since field sendNotModified(url, cseq_number, client_socket); return; } else { //200 OK: the request is good sendOK(url, method, cseq_number, client_socket); return; } }
/// Process data received by UART /// void simpleBinary::processSerial() { while (serial->available() > 0) { int data = serial->read(); serbuf[serbuflen++] = data; } if(serbuflen > 3) { receiveTime = millis(); if(serbuf[0] == _uartAddress) { int address; char crc; switch(serbuf[1]) { //new data case (char)0xD0: if(serbuf[2] == 0x01) { //force all output data as new through user function forceAllNewData(); } if(serbuf[2] == 0x00 || serbuf[2] == 0x01) { crc = CRC8::evalCRC(serbuf,3); if(crc != serbuf[3]) sendWrongData(crc); else checkNewData(); } else sendUnknownData(); serbuflen = 0; break; //read data case (char)0xD1: if(serbuflen < 5) break; address = serbuf[2] | (serbuf[3] << 8); crc = CRC8::evalCRC(serbuf,4); if(crc != serbuf[4]) sendWrongData(crc); else readData(address); serbuflen = 0; break; //write byte case (char)0xDA: if(serbuflen < 6) break; //address address = serbuf[2] | (serbuf[3] << 8); //crc check crc = CRC8::evalCRC(serbuf,5); if(serbuf[5] != crc) sendWrongData(crc); else { //check address if(!checkAddress(address)) sendInvalidAddress(); //write data into memory if(saveByte(address,serbuf+4)) sendOK(); else sendSavingError(); } //clear buffer serbuflen = 0; break; //write word case (char)0xDB: if(serbuflen < 7) break; //address address = serbuf[2] | (serbuf[3] << 8); //crc check crc = CRC8::evalCRC(serbuf,6); if(serbuf[6] != crc) sendWrongData(crc); else { //check address if(!checkAddress(address)) sendInvalidAddress(); //write data into memory if(saveWord(address,serbuf+4)) sendOK(); else sendSavingError(); } //clear buffer serbuflen = 0; break; //write dword case (char)0xDC: case (char)0xDD: if(serbuflen < 9) break; //address address = serbuf[2] | (serbuf[3] << 8); //crc check crc = CRC8::evalCRC(serbuf,8); if(serbuf[8] != crc) sendWrongData(crc); else { //check address if(!checkAddress(address)) sendInvalidAddress(); //write data into memory if(saveDword(address,serbuf+4)) sendOK(); else sendSavingError(); } //clear buffer serbuflen = 0; break; //write array case (char)0xDE: if(serbuflen < 6) break; int datalen; datalen = (serbuf[4] | (serbuf[5] << 8)); //correct packet length check if(serbuflen < 7 + datalen) break; //address address = serbuf[2] | (serbuf[3] << 8); //crc check crc = CRC8::evalCRC(serbuf,6+datalen); if(serbuf[7+datalen] != crc) sendWrongData(crc); else { //check address if(!checkAddress(address)) sendInvalidAddress(); char *pData = serbuf + 6; //write data into memory if(saveArray(address,pData, datalen)) sendOK(); else sendSavingError(); } //clear buffer serbuflen = 0; break; default: serbuflen = 0; sendUnknownData(); break; } } else { serbuflen = 0; return; } } }
void Session::handleNOOP(const std::string& arg) { (void)arg; sendOK(); }
int main(int argc, char * argv[]) { struct sockaddr_in sockname, client; struct sigaction sa; char *ep, *inbuff, *tmp; char outbuff[256]; int clientlen, sd; u_short port; u_long p; pid_t pid; /* daemonize */ #ifndef DEBUG /* don't daemonize if we compile with -DDEBUG */ if (daemon(1,1) == -1) err(1, "daemon() failed"); #endif /* check params */ if (argc != 4) usage(); errno = 0; p = strtoul(argv[1], &ep, 10); if (&argv[1] == '\0' || *ep != '\0'){ /* parameter wasn't a number, or was empty */ fprintf(stderr, "%s - not a number\n", argv[1]); usage(); } if ((errno == ERANGE && p == ULONG_MAX) || (p > USHRT_MAX)) { /* It's a number, but it either can't fit in an unsigned * long, or it is too big for an unsigned short */ fprintf(stderr, "%s - value out of range\n", argv[1]); usage(); } /* Ensure argv[2] is a valid directory */ if (chdir(argv[2]) == -1) err(1, "chdir failed"); /* TODO : Ensure argv[3] is a valid file */ LOG_FILE = argv[3]; /* now safe to do this */ port = p; memset(&sockname, 0, sizeof(sockname)); sockname.sin_family = AF_INET; sockname.sin_port = htons(port); sockname.sin_addr.s_addr = htonl(INADDR_ANY); sd = socket(AF_INET, SOCK_STREAM, 0); if (sd == -1) err(1, "socket failed"); if (bind(sd, (struct sockaddr *) &sockname, sizeof(sockname)) == -1) err(1, "bind failed"); if (listen(sd, 3) == -1) err(1, "listen failed"); /* We are now bound and listening for connections on "sd" */ /* Catch SIGCHLD to stop zombie children wandering around */ sa.sa_handler = kidhandler; sigemptyset(&sa.sa_mask); /* allow system calls (accept) to restart if interrupted by SIGCHLD */ sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) err(1, "sigaction failed"); /* main loop. Accept connections and do stuff */ for(;;) { int clientsd; ssize_t written, w; clientlen = sizeof(&client); clientsd = accept(sd, (struct sockaddr *)&client, &clientlen); if (clientsd == -1) err(1, "accept failed"); /* fork child to deal with each connection */ pid = fork(); if (pid == -1) internalError((struct sockaddr *)&client, "fork failed", NULL); if (pid == 0) { char * getLine, *fName; int valid, written; long lSize; FILE * fp; /* Parse GET */ inbuff = malloc(12800*sizeof(char)); fName = malloc(256*sizeof(char)); if (inbuff == NULL || fName == NULL) internalError(&client, "malloc failed", NULL); readSocket(clientsd, inbuff, 12800); getLine = malloc(256*sizeof(char)); if (getLine == NULL) internalError(&client, "malloc failed", NULL); valid = checkGET(inbuff, fName, getLine); fName++; if (valid == 0) { /* BAD REQUEST */ sendBadRequestError(clientsd); logBadRequest(getIPString(&client), getLine); } else { /* GET is good. Try reading file & sending */ fp = fopen(fName, "r"); if (fp == NULL) { if (errno == ENOENT) { sendNotFoundError(clientsd); logNotFound( getIPString(&client), getLine); } else if (errno == EACCES) { sendForbiddenError(clientsd); logForbidden( getIPString(&client), getLine); } else internalError(&client, "fopen failed", getLine); } else { /* get file size */ fseek(fp, sizeof(char), SEEK_END); lSize = ftell(fp); rewind(fp); /* send OK and file */ sendOK(clientsd, lSize); written = sendFile(fp, clientsd); logOK(getIPString(&client), getLine, written, lSize-1); } fclose(fp); } /* Clean up */ fName--; free(getLine); free(inbuff); free(fName); fName = NULL; getLine = NULL; inbuff = NULL; exit(0); } close(clientsd); } }
/*Respond Client Request Function Variable Definition: -- request: client request line -- header: client header lines -- client_socket: socket connected to the client Return Value: NULL */ void respondClientRequest(char *request, struct http_header *header, int client_socket){ char method[STRING_SIZE]; //method field: GET or HEAD char url[STRING_SIZE]; //url field: /TestServer char version[STRING_SIZE]; //http version field: HTTP/1.1 char field_value[HALFBUF_SIZE]; //field value string bool modified_signal; //whether if-modified-since field exist //Initialize method, url and version buffer memset(method, 0, STRING_SIZE); memset(url, 0, STRING_SIZE); memset(version, 0, STRING_SIZE); memset(field_value, 0, HALFBUF_SIZE); //Test the client HTTP Request Line if (!syntaxChecking(request, 'R')){ //400 Bad Request: the request could not be understood by the server sendBadRequest("Request Line is syntactically incorrect!", client_socket); return; } //Get the method, url, and http version // NC: i don't think this works: need sscanf(request, "%s %s %s", method, url, version); sscanf(request, "%s%s%s", method, url, version); //Decode the URL(if it has %HEX code) decodeURL(url); //Test the method if ((strcmp(method, "GET") != 0) && (strcmp(method, "HEAD") != 0)){ //405 Method Not Allowed: the method field is neither "GET" nor "HEAD" sendMethodNotAllowed(method, client_socket); return; } //Test the Requested URL else if (!syntaxChecking(url, 'U')){ // NC: but, "the only legal Request-URI is the abs_path “/TestServer”. Generate a 404 Response to all other Request-URIs." // #17: -1 //400 Bad Request: the request could not be understood by the server sendBadRequest("Requested URL is syntactically incorrect!", client_socket); return; } //Test the HTTP version else if (!syntaxChecking(version, 'V')){ //400 Bad Request: the request could not be understood by the server sendBadRequest("HTTP Version is syntactically incorrect!", client_socket); return; } else if (!syntaxChecking(version, 'O')){ //505 HTTP Version Not Supported: the requested HTTP protocol version is not supported by server sendHTTPVersionNotSupported(version, client_socket); return; } //Test the Header Line if (headerLinesIncorrect(header, field_value)){ //400 Bad Request: the request could not be understood by the server sendBadRequest(field_value, client_socket); return; } //Test the "Host" field else if (fieldNotExist(header, "host", field_value)){ //400 Bad Request: the request could not be understood by the server sendBadRequest("Host field does not exist!", client_socket); return; } else if (!syntaxChecking(field_value, 'I')){ //400 Bad Request: the request could not be understood by the server sendBadRequest("Host field value(domain name, IP address, or port format) is syntactically incorrect!", client_socket); return; } //Test the "If-Modified-Since" field else if ((!(modified_signal = fieldNotExist(header, "if-modified-since", field_value))) && (!syntaxChecking(field_value, 'T'))){ //400 Bad Request: the request could not be understood by the server sendBadRequest("If-Modified-Since field value(time format) is syntactically incorrect!", client_socket); return; } //Now we are sure that the request message is SYNTACTICALLY CORRECT //Get the Requested File or Directory's name pathBelowCurrentDirectory(url); printf("Requested File or Directory is %s\n", url); // NC: but OUR server doesn't do this //Test the requested file on the server if (urlNotExist(url)){ //404 Not Found: the requested document does not exist on this server sendNotFound(url, client_socket); } else if (urlIsADirectory(url)){ //List the File Name of Directory sendFileNameInDirectory(url, method, client_socket); } else if (modified_signal){ //200 OK: the request is good sendOK(url, method, client_socket); } else if (compareModifiedTime(url, field_value)){ //304 Not Modified: the request does not Modified since If-Modified-Since field sendNotModified(url, client_socket); } else{ //200 OK: the request is good sendOK(url, method, client_socket); } return; }