int main(int argc, char *argv[]) { struct sockaddr_in si_me, si_other; int s, i, slen = sizeof(si_other) , numbytes; char buf[BUFLEN]; char *message; if (argc != 2){ fprintf(stderr,"usage: %s <port>\n", argv[0]); exit(1); } //create a UDP socket if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){ die("socket"); } // zero out the structure memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(atoi(argv[1])); si_me.sin_addr.s_addr = htonl(INADDR_ANY); //bind socket to port if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1) die("bind"); //receive data if ((numbytes = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1) die("recvfrom()"); parseHeader(buf); //packet #2 if (strcmp(SYN_BIT, "1") == 0){ addHeader(0,1,"1","1", 100); strcpy(buf, header); if (sendto(s, buf, strlen(buf), 0, (struct sockaddr*) &si_other, slen) == -1) die("sendto()"); } if ((numbytes = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1) die("recvfrom()"); if ((numbytes = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1) die("recvfrom()"); message = parseHeader(buf); printf("server: received\n%s\n", message); //packet #5 addHeader(0,1,"1","1", 100); strcpy(buf, header); strcat(buf, "Okay! Sending you test.txt..."); if (sendto(s, buf, strlen(buf), 0, (struct sockaddr*) &si_other, slen) == -1) die("sendto()"); close(s); return 0; }
FetchClient::FetchClient(TCPClient *client, const char *url_str, Buffer *postData, const char *headers) { m_id = 0; m_socket = NULL; m_bDone = false; m_port = 80; m_post = postData; m_state = None; m_code = 0; m_size = UNKNOWN_SIZE; m_client = client; #ifdef USE_OPENSSL m_bHTTPS = false; #endif string url = url_str; string protocol = getToken(url, ':'); if (protocol != "http"){ #ifdef USE_OPENSSL if (protocol == "https"){ m_bHTTPS = true; m_port = 443; }else{ #endif log(L_WARN, "Unsupported protocol %s", url_str); return; #ifdef USE_OPENSSL } #endif } if ((url[0] != '/') && (url[1] != '/')){ log(L_WARN, "Bad url %s", url_str); return; } url = url.substr(2); m_host = getToken(url, '/'); m_uri = "/"; m_uri += url; addHeader("Host", m_host.c_str()); if (postData){ addHeader("Content-Type", ""); addHeader("Content-Length", number(postData->size()).c_str()); } if (headers){ for (const char *h = headers; *h; h += strlen(h) + 1){ string header = h; string key = getToken(header, ':'); unsigned n; for (n = 0; n < header.length(); n++) if (header[n] != ' ') break; header = header.substr(n); addHeader(key.c_str(), header.c_str()); } } m_id = ++FetchManager::manager->m_id; FetchManager::manager->m_clients.push_back(this); m_socket = new ClientSocket(this); log(L_DEBUG, "Start connect %s:%u", m_host.c_str(), m_port); m_socket->connect(m_host.c_str(), m_port, m_client); }
BaseMessage* SuiColorBoxImplementation::generateMessage() { SuiCreatePageMessage* message = new SuiCreatePageMessage(boxID, "Script.ColorPicker"); // Headers. addHeader("ColorPicker", "SelectedIndex"); addHeader("bg.caption.lblTitle", "Text"); StringBuffer id; id << usingObject.get()->getObjectID(); //Set Body Options: addSetting("3", "bg.caption.lblTitle", "Text", "@base_player:swg"); addSetting("3", "ColorPicker", "TargetRangeMax", "500"); addSetting("3", "ColorPicker", "TargetNetworkId", id.toString().toCharArray()); addSetting("3", "ColorPicker", "TargetVariable", variable.toCharArray()); setHandlerText("handleColorizeFrame"); //Generate Packet: generateHeader(message); generateBody(message); generateFooter(message); hasGenerated = true; return message; }
int API_SaveEncryptedPassword() { char* msg = malloc(512); uchar * response_buffer = calloc(1024, 1); uchar password[65]; uchar random[32]; int msglen, retlen, plainlen; RC4_KEY rc4key; int i; char* unencryptedAPICompare = malloc(128); if (!RAND_bytes(random, 32)) { return -1; } RC4_set_key(&rc4key, 16, session_key); RC4(&rc4key, 32, random, random); for(i=0; i<32; i++) { sprintf(password + i*2,"%02x", random[i]); } password[64] = 0; if (response_buffer == NULL) { LOG(ERROR, "[API] SaveEncryptedPassword failed, unable to allocate memory"); return -1; } sprintf((char*) unencryptedAPICompare, "%s~%s~%s~", api_company, timestamp, api_machineID); plainlen = addHeader(&unencryptedAPICompare, api_msgformat); free(unencryptedAPICompare); sprintf((char*) msg, "%s~%s~%s~%s~SaveEncryptedPassword~%s~%s~%d~%s~", api_company, timestamp, api_machineID, api_clientID, api_company, ski, 64, password); msglen = addHeader(&msg, api_msgformat); LOG(VERBOSE, "[API] Save encryption password: %s", msg); RC4_set_key(&rc4key, 16, session_key); RC4(&rc4key, msglen - plainlen, msg + plainlen, msg + plainlen); retlen = tcp_client_send(msg, msglen, response_buffer, 1024, vcasServerAddress, VCAS_Port_SSL+1); free(msg); if (retlen < 8) { free(response_buffer); response_buffer = NULL; return -1; } LOG(DEBUG, "[API] SaveEncryptedPassword completed, size: %d", retlen); free(response_buffer); response_buffer = NULL; return 0; }
httpPoll_t :: httpPoll_t () : h_( 0 ) , file_( "/" ) , state_( idle ) { addHeader( "Keep-Alive", "300" ); addHeader( "Connection", "keep-alive" ); }
bool ExtensionAgentResponse::sendContent(string content) { if (!addHeader("Content-Type", "text/html")) return false; if (!addHeader("Cache-Control", "no-cache")) return false; if (!addHeader("Pragma", "no-cache")) return false; if (!addHeader("Expires", "0")) return false; if (!startResponse(HTTP_STATUS_OK, "success", headers)) return false; return writeContent(content.c_str(), content.size()); }
AsyncWebServerResponse::AsyncWebServerResponse() : _code(0) , _headers(NULL) , _contentType() , _contentLength(0) , _sendContentLength(true) , _chunked(false) , _headLength(0) , _sentLength(0) , _ackedLength(0) , _state(RESPONSE_SETUP) { addHeader("Connection","close"); addHeader("Access-Control-Allow-Origin","*"); }
//------------------------------------------------------------------------------ void ofxHTTPBaseRequest::addHeaders(const NameValueCollection& _headers) { NameValueCollection::ConstIterator iter = _headers.begin(); while(iter != _headers.end()) { addHeader((*iter).first,(*iter).second); ++iter; } }
bool FileEnvProcess::startDetached(const QString& program, const QStringList& arguments, const QString& workingDirectory, qint64* pid) { QByteArray programBa = program.toLatin1(); const char* programCharPtr = programBa.data(); QString* tmpFileNameStrPtr = new QString("/tmp/tmpRideFile.bash"); QFile* tmpRideFilePtr = new QFile(*tmpFileNameStrPtr); tmpRideFilePtr->open(QIODevice::WriteOnly); addHeader(tmpRideFilePtr); tmpRideFilePtr->write(programCharPtr); QByteArray tmpByteArray; for(size_t i = 0; i < arguments.size(); i++) { tmpByteArray.append(arguments.at(i) + "\n"); tmpRideFilePtr->write(tmpByteArray); tmpByteArray.clear(); } tmpRideFilePtr->write("\nrm /tmp/tmpRideFile.bash"); tmpRideFilePtr->write("\necho \"Finished execution.\""); tmpRideFilePtr->close(); QStringList stringlst; stringlst.push_back("+x"); stringlst.push_back("/tmp/tmpRideFile.bash"); QProcess qprocess; qprocess.execute("chmod", stringlst); // Don't run this->startDetached; this would result in infinite recursion!!! return qprocess.startDetached(*tmpFileNameStrPtr, QStringList(), workingDirectory, pid); }
void Message::addHeader(const std::string& name, const std::string& value) { Header header ; header.name = name ; header.value = value ; addHeader(header); }
bool FileEnvProcess::startDetached(const QString& program) { QByteArray programBa = program.toLatin1(); const char* programCharPtr = programBa.data(); QString* tmpFileNameStrPtr = new QString("/tmp/tmpRideFile.bash"); QFile* tmpRideFilePtr = new QFile(*tmpFileNameStrPtr); tmpRideFilePtr->open(QIODevice::WriteOnly); addHeader(tmpRideFilePtr); tmpRideFilePtr->write(programCharPtr); tmpRideFilePtr->write("\nrm /tmp/tmpRideFile.bash"); tmpRideFilePtr->write("\necho \"Finished execution.\""); tmpRideFilePtr->close(); QStringList stringlst; stringlst.push_back("+x"); stringlst.push_back("/tmp/tmpRideFile.bash"); QProcess qprocess; qprocess.setProcessChannelMode(QProcess::MergedChannels); //QByteArray output = qprocess.readAll(); qprocess.execute("chmod", stringlst); int rtn = qprocess.startDetached(*tmpFileNameStrPtr); //don't run this->execute; this would result in infinate recursion!!! //cout << cct::bold("\nOutput: ") << output.data() << cct::bold("\nEnd of output") << endl; return rtn; }
void MTD_FLASHMEM HTTPTemplateResponse::processFileRequest() { FlashFileSystem::Item file; if (m_filename && FlashFileSystem::find(m_filename, &file)) { // found setStatus(STR_200_OK); addHeader(STR_Content_Type, FSTR("text/html; charset=UTF-8")); // replace parameters m_replacer.start((char const *)file.data, (char const *)file.data + file.datalength, &m_params, NULL); // is this a specialized file (contains {%..%} blocks)? if (m_replacer.getBlocks()->getItemsCount() > 0 && m_replacer.getTemplateFilename() != NULL) { // this is a specialized file // load template file file.reset(); if (FlashFileSystem::find(m_replacer.getTemplateFilename(), &file)) { // replace parameters and blocks of template file m_templateReplacer.start((char const *)file.data, (char const *)file.data + file.datalength, &m_params, m_replacer.getBlocks()); // flush resulting content addContent(m_templateReplacer.getResult()); return; } } else { // just flush this file (contains only {{...}} blocks) addContent(m_replacer.getResult()); return; } } // not found setStatus(STR_404_Not_Found); }
void CWatcherWindow::onReceiveWatcherData(KBEngine::MemoryStream& s) { uint8 type = 0; s >> type; if(type == 0) { KBEngine::WatcherPaths watcherPaths; while(s.length() > 0) { std::string path; s >> path; std::string name; s >> name; KBEngine::WATCHER_ID id = 0; s >> id; KBEngine::WATCHER_VALUE_TYPE type; s >> type; KBEngine::WatcherObject* wo = watcherPaths.addWatcherFromStream(path, name, id, type, &s); addHeader(name); addItem(wo); }; }
/** * sendRequest * @param type const char * "GET", "POST", .... * @param payload uint8_t * data for the message body if null not send * @param size size_t size for the message body if 0 not send * @return -1 if no info or > 0 when Content-Length is set by server */ int HTTPClient::sendRequest(const char * type, uint8_t * payload, size_t size) { // connect to server if(!connect()) { return returnError(HTTPC_ERROR_CONNECTION_REFUSED); } if(payload && size > 0) { addHeader("Content-Length", String(size)); } // send Header if(!sendHeader(type)) { return returnError(HTTPC_ERROR_SEND_HEADER_FAILED); } // send Payload if needed if(payload && size > 0) { if(_tcp->write(&payload[0], size) != size) { return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); } } // handle Server Response (Header) return returnError(handleHeaderResponse()); }
void MyNetMailbox::getHeadersRequest() { // LOG_ENTER("MyNetMailbox::getHeadersRequest"); std::string page,url; boost::smatch match; boost::regex re_inbox("<a href=\"([^\"]*)\">.leri</a>"); boost::regex re("<a class=\"subject\" href=\"rbody.php[^\"]*passed_id=([0-9]*)[^\"]*\">([^<>]*)</a>"); // setState(Mailbox::ReadHeadersIP); // request headers boost::replace_first(auth,"web2","webmail"); mserv=auth.substr(0,auth.find("showFolder.php")); page=doGet(auth+"&mailbox=INBOX.Posta_kutusu"); while(1) { std::string::const_iterator pbegin = page.begin(); std::string::const_iterator pend = page.end(); while (regex_search(pbegin, pend, match, re, boost::match_default)) { EmailHeader hdr(match[1], match[2]); // LOG(Log::Debug,"Subject: "+match[2]); // LOG(Log::Debug, "Found header: " + hdr.subject); addHeader(hdr); addHeaderLink(match[1]); pbegin = match[2].second; } if(!regex_search(page,match,re_inbox)) break; url=match[1]; boost::erase_all(url,"amp;"); page=doGet(mserv+url); } // setState(Mailbox::ReadHeadersDone); }
void Transport::replaceHeader(const char *name, const char *value) { ASSERT(name && *name); ASSERT(value); FiberWriteLock lock(this); m_responseHeaders[name].clear(); addHeader(name, value); }
void MTD_FLASHMEM HTTPGPIOResponseHTML::flush() { setStatus(STR_200_OK); addHeader(STR_Content_Type, STR_TEXTHTML); char const* cmd = getRequest().query[FSTR("cmd")]; if (cmd && f_strcmp(cmd, FSTR("set")) == 0) { // set gpio HTTPHelperConfiguration::GPIOSetValue(this); } else if (cmd && f_strcmp(cmd, FSTR("conf")) == 0) { // conf gpio HTTPHelperConfiguration::GPIOConf(this); } char const* gpio = getRequest().query[STR_gpio]; if (gpio) { uint8_t gpion = strtol(gpio, NULL, 10); addContent(GPIO(gpion).read()? STR_1 : STR_0); } HTTPResponse::flush(); }
void HttpResponse::addContentType2 () { // get the extension string fullPath = getUrl(); string strExt; int pos = fullPath.rfind('.'); if ( pos != -1 ) strExt = StringUtil::mid( fullPath, pos ); // add content type string strType = ""; if ( StringUtil::compareNoCase(strExt,".html") ) strType = "text/html"; else if ( StringUtil::compareNoCase(strExt,".xml") ) strType = "text/xml"; else if ( StringUtil::compareNoCase(strExt,".rmvb") ) strType = "application/vnd.rn-realmedia-vbr"; else if ( StringUtil::compareNoCase(strExt,".rm") ) strType = "application/vnd.rn-realmedia"; else if ( StringUtil::compareNoCase(strExt,".wmv") ) strType = "video/x-ms-wmv"; else if ( StringUtil::compareNoCase(strExt,".swf") ) strType = "application/x-shockwave-flash"; if ( strType.size() > 0) addHeader( idParamContentType, strType ); }
/* Set the device into BROADCAST_MODE, which transmits the data automatically. The second argument is the samping rate. */ RValue CHR_6dm::gotoMeasurementMode(SensorData *sensor, int freq) { addHeader(_shared.data); _shared.data[3] = SET_BROADCAST_MODE; _shared.data[4] = 1; RValue ret_val; if (freq < 20 || freq > 300) { return CHR_ErrorCommand; } else { _shared.data[5] = ((freq - 20) * 255) / 280; printf("X = %X\n", _shared.data[5]); } addCheckSum(_shared.data); ret_val = _sending_command(_shared.data); if (ret_val != CHR_OK) return ret_val; serial.ClosePort(); if (pthread_create(&_comm_thread,NULL,CHR_6dm::_communicator,(void*)&_shared) < 0) { perror("Thread Creation"); return CHR_Error; } _shared.measurement_mode = true; return CHR_OK; }
void HTTPRequest::addDefaultHTTPHeaders() { addHeader(HTTPHeader("Host", url.getHost())); if(method != HTTP_METHOD_POST) { return; } if(!headers.contains("content-type")) { if(getFormEncoding() == HTTP_FORM_MULTIPART) { addHeader(HTTPHeader("Content-Type", "multipart/form-data; boundary=\"" +getBoundary() +"\"")); } else if(getFormEncoding() == HTTP_FORM_URL_ENCODED) { addHeader(HTTPHeader("Content-Type", "application/x-www-form-urlencoded")); } } }
result_t HttpResponse::sendHeader(Stream_base* stm, AsyncEvent* ac) { if (!ac) return CHECK_ERROR(CALL_E_NOSYNC); if (m_cookies) { int32_t len, i; m_cookies->get_length(len); for (i = 0; i < len; i++) { Variant v; obj_ptr<object_base> cookie; exlib::string str; m_cookies->_indexed_getter(i, v); cookie = v.object(); if (cookie) { cookie->toString(str); addHeader("Set-Cookie", str); } } m_cookies.Release(); } int32_t pos = shortcut[m_status / 100 - 1] + m_status % 100; exlib::string strCommand; get_protocol(strCommand); strCommand.append(status_lines[pos], status_lines_size[pos]); return m_message->sendHeader(stm, strCommand, ac); }
bool FileEnvProcess::startDetached(const QString& program, const QStringList& arguments) { //cout << "Program: " << program.toStdString() << endl; //cout << "args: " << arguments.at(0).toStdString() << " " << arguments.at(1).toStdString() << endl; QByteArray programBa = program.toLatin1(); const char* programCharPtr = programBa.data(); QString* tmpFileNameStrPtr = new QString("/tmp/tmpRideFile.bash"); QFile* tmpRideFilePtr = new QFile(*tmpFileNameStrPtr); tmpRideFilePtr->open(QIODevice::WriteOnly); addHeader(tmpRideFilePtr); tmpRideFilePtr->write(programCharPtr); tmpRideFilePtr->write(" "); QByteArray tmpByteArray; for(size_t i = 0; i < arguments.size(); i++) { tmpByteArray.append(arguments.at(i) + " "); tmpRideFilePtr->write(tmpByteArray); tmpByteArray.clear(); } tmpRideFilePtr->write("\nrm /tmp/tmpRideFile.bash"); tmpRideFilePtr->write("\necho \"Finished execution.\""); tmpRideFilePtr->close(); QStringList stringlst; stringlst.push_back("+x"); stringlst.push_back("/tmp/tmpRideFile.bash"); QProcess qprocess; qprocess.execute("chmod", stringlst); return qprocess.startDetached(*tmpFileNameStrPtr); //don't run this->execute; this would result in infinate recursion!!! }
// should be called only after setStatus, addHeader and addContent void MTD_FLASHMEM HTTPResponse::flush() { // status line m_httpHandler->getSocket()->writeFmt(FSTR("HTTP/1.1 %s\r\n"), m_status); // HTTPResponse headers addHeader(FSTR("Connection"), FSTR("close")); // user headers for (uint32_t i = 0; i != m_headers.getItemsCount(); ++i) { Fields::Item* item = m_headers[i]; m_httpHandler->getSocket()->writeFmt(FSTR("%s: %s\r\n"), APtr<char>(t_strdup(item->key)).get(), APtr<char>(t_strdup(item->value)).get()); } // content length header m_httpHandler->getSocket()->writeFmt(FSTR("%s: %d\r\n\r\n"), STR_Content_Length, m_content.getItemsCount()); // actual content if (m_content.getItemsCount() > 0) { CharChunksIterator iter = m_content.getIterator(); CharChunkBase* chunk = iter.getCurrentChunk(); while (chunk) { m_httpHandler->getSocket()->write((uint8_t const*)chunk->data, chunk->getItems()); chunk = iter.moveToNextChunk(); } m_content.clear(); } }
void chumby::HTTPResponse::addHeader(const char *name, const char *value) { std::string str_name = name; std::string str_value = value; addHeader(str_name, str_value); }
void Transport::addHeader(CStrRef header) { String name; const char *value; if (splitHeader(header, name, value)) { addHeader(name.data(), value); } }
int API_GetEncryptedPassword() { char* msg = malloc(512); uchar * response_buffer = calloc(1024, 1); int msglen, retlen, plainlen; RC4_KEY rc4key; char* unencryptedAPICompare = malloc(128); if (response_buffer == NULL) { LOG(ERROR, "[API] GetEncryptedPassword failed, unable to allocate memory"); return -1; } sprintf((char*) unencryptedAPICompare, "%s~%s~%s~", api_company, timestamp, api_machineID); plainlen = addHeader(&unencryptedAPICompare, api_msgformat); free(unencryptedAPICompare); sprintf((char*) msg, "%s~%s~%s~%s~GetEncryptedPassword~%s~%s~", api_company, timestamp, api_machineID, api_clientID, api_company, ski); msglen = addHeader(&msg, api_msgformat); LOG(VERBOSE, "[API] Get encryption password: %s", msg); RC4_set_key(&rc4key, 16, session_key); RC4(&rc4key, msglen - plainlen, msg + plainlen, msg + plainlen); retlen = tcp_client_send(msg, msglen, response_buffer, 1024, vcasServerAddress, VCAS_Port_SSL+1); free(msg); if (retlen < 8) { free(response_buffer); response_buffer = NULL; return -1; } RC4_set_key(&rc4key, 16, session_key); RC4(&rc4key, retlen-4, response_buffer+4, response_buffer+4); LOG(DEBUG, "[API] GetEncryptedPassword: %s", response_buffer+8); free(response_buffer); response_buffer = NULL; return 0; }
void RequestString::setURL(std::string URL){ int slashpos; slashpos = URL.find_first_of("/"); hoststr = URL.substr(0, slashpos); dirstr = URL.substr(slashpos); addHeader("HOST", hoststr); }
bool HttpResponse::addHeading2() { if ( _ispartial ) { addStatus( idHttpPartial ); addHeader( idParamContentLength, _contentLength - _rangestart ); char szRange[256]; sprintf( szRange, "bytes %u-%u/%u", _rangestart, _contentLength -1, _contentLength ); addHeader( idParamContentRange, szRange ); } else { addStatus( idHttpOk ); addHeader( idParamContentLength, _contentLength ); } addContentType2(); //addHeader( idParamKeepAlive, "timeout=5, max=100" ); addHeader( idParamConnection, "close" ); addHeader( idParamAcceptRanges, "bytes" ); string strTime = HttpUtil::getHttpDate( NULL ); addHeader( idParamLastModified, strTime ); char szText[32]; sprintf( szText, "0x%.8x", (DWORD)this); addHeader( idParamSetCookie, "this_pointer=" + string(szText) + "; path=/" ); addString( CRLF ); return true; }
void HttpResponse::setHttp501Status() { setStatusCode(HTTP_METHODERROR); setContentType(CONTEXT_TYPE_HTML); addHeader("Server", JOINTCOM_FLAG); setBody("<HTML><TITLE>Method Not FOUND</TITLE>\r\n" "<BODY><P>(CODE: 501)</P>\r\n" "HTTP request method not supported.\r\n" "</BODY></HTML>\r\n"); }
//----------------------------------------------------------------------------- TotalMultipleScoresList::TotalMultipleScoresList( const QVector<Score> &scores, QWidget *parent) : ScoresList(parent), _scores(scores) { // kDebug(11001) << ": TotalMultipleScoresList"; const ScoreInfos &s = internal->scoreInfos(); addHeader(s); for (int i=0; i<scores.size(); i++) addLine(s, i, false); }