void ESP8266WebServerEx::redirect(const char* homePath) { uint16_t port = g_ModuleSettings.data.port; String url; if ( !homePath ) return; url.reserve(50); url = "http://"; url += GetHost(); url += homePath; String content; content.reserve(250); content = "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta http-equiv=\"refresh\" content=\"0; URL='"; content += url; content += "'\" />\n<title>Login</title>\n</head>\n<body onload=\"window.location='"; content += url; content += "';\">\n</body>\n</html>"; sendHeader("Location",url); sendHeader("Cache-Control","no-cache"); sendHeader("Pragma","no-cache"); TRACE("Redirect..."); send(302,"text/html",content); }
/* client function that performs the pull method */ int clientPull(int sock) { int numSongs=numSongsInDir(); if(numSongs) { if(!sendHeader(2, numSongs*sizeof(song), numSongs, sock)) fatal_error("send header has failed\n"); song *songs=createSongArray(numSongs); if(!songs) fatal_error("creating song array failed\n"); if(sendSongArray(songs,numSongs,sock)!=sizeof(song)*numSongs) fatal_error("sending song array failed\n"); free(songs); } else { if(!sendHeader(2, 0, 0, sock)) fatal_error("send header has failed\n"); } header *rcvHead= receiveHeader(sock); if(!rcvHead) fatal_error("error receiving rcv header\n"); if(!rcvHead->indexes) { fprintf(stderr,"You have all the songs that are on the server.\n\n"); } else { song *rcvSongs=recvSongArray(rcvHead->indexes,sock); if(!rcvSongs) fatal_error("error receiving song array\n"); fprintf(stderr, "The following songs have been added to your directory:\n"); int i; for(i=0;i<rcvHead->indexes;i++) { FILE *file = fopen(rcvSongs[i].title,"w+"); if(!receiveFile(file, rcvSongs[i].lenOfSong, sock)) fatal_error("receive file failed\n"); fclose(file); fprintf(stderr, "%s\n",rcvSongs[i].title); } fprintf(stderr,"\n"); free(rcvSongs); } free(rcvHead); return 1; }
void Sender::startSending() { std::thread SendThread( [&]() { do { try { IMessage *msg = sendQ.deQ(); /*Message* msg = dynamic_cast<Message*>(imsg); map<string, string> header = msg->getHeader();*/ if (msg->getCommand() == "send_stop") break; else if (msg->getCommand() == "file_upload") { if (connectToPeer(msg->getRecvIP(), stoi(msg->getRecvPort()))) { if (sendFile(msg)) { } } else Verbose::show("Connection failed!\n"); } else if (msg->getCommand() == "ack") { if (connectToPeer(msg->getRecvIP(), stoi(msg->getRecvPort()))) sendHeader(msg); } else { if (connectToPeer(msg->getRecvIP(), stoi(msg->getRecvPort()))) { sendHeader(msg); sendBody(msg); } } } catch (exception ex) { string s = ex.what(); Verbose::show("\n In send Thread: " + s); } } while (1); } ); SendThread.detach(); }
void ESP8266WebServer::requestAuthentication(HTTPAuthMethod mode, const char* realm, const String& authFailMsg){ if(realm==NULL){ _srealm = "Login Required"; }else{ _srealm = String(realm); } if(mode==BASIC_AUTH){ sendHeader("WWW-Authenticate", "Basic realm=\"" + _srealm + "\""); }else{ _snonce=_getRandomHexString(); _sopaque=_getRandomHexString(); sendHeader("WWW-Authenticate", "Digest realm=\"" +_srealm + "\", qop=\"auth\", nonce=\""+_snonce+"\", opaque=\""+_sopaque+"\""); } send(401,"text/html",authFailMsg); }
void ClientConnection::onSocketConnect() { TraceS(this) << "On connect" << endl; // Set the connection to active _active = true; // Emit the connect signal so raw connections like // websockets can kick off the data flow Connect.emit(this); // Start the outgoing send stream if there are // any queued packets or adapters attached // startInputStream(); // startOutputStream(); // Flush queued packets if (!_outgoingBuffer.empty()) { for (const auto & packet : _outgoingBuffer) { Outgoing.write(packet.c_str(), packet.length()); } _outgoingBuffer.clear(); } // Send the outgoing HTTP header if it hasn't already been sent. // Note the first call to socket().send() will flush headers. // Note if there are stream adapters we wait for the stream to push // through any custom headers. See ChunkedAdapter::emitHeader if (Outgoing.numAdapters() == 0) { TraceS(this) << "On connect: Send header" << endl; sendHeader(); } }
bool lwSimpleHTTPClient::post(const char* sensor, double value,unsigned int digits) { bool ret; if (client.connect(LEWEISERVER,80)) { sendHeader(); client.println(lengthOfInt((int)value)+LENTH+strlen(sensor)+digits); client.println("Connection: close"); client.println(); client.print("[{\"Name\":\""); client.print(sensor); client.print("\",\"Value\":\""); client.print(value,digits); client.println ("\"}]"); #ifdef DEBUGGING Serial.println(lengthOfInt((int)value)+LENTH+strlen(sensor)+digits); Serial.println("Connection: close"); Serial.println(""); //必须的空白行 Serial.print("[{\"Name\":\""); Serial.print(sensor); Serial.print("\",\"Value\":\""); Serial.print(value, digits); Serial.println ("\"}]"); #endif // DEBUGGING ret= true; } else ret=false; exitHere: client.stop(); return ret; }
void ClientConnection::onSocketConnect(net::Socket& socket) { // LTrace("On connect") // Set the connection to active _active = true; // Emit the connect signal so raw connections like // websockets can kick off the data flow Connect.emit(); // Flush queued packets if (!_outgoingBuffer.empty()) { // LTrace("Sending buffered: ", _outgoingBuffer.size()) for (const auto& packet : _outgoingBuffer) { send(packet.c_str(), packet.length()); } _outgoingBuffer.clear(); } else { // Send the header sendHeader(); } // Send the outgoing HTTP header if it hasn't already been sent. // Note the first call to socket().send() will flush headers. // Note if there are stream adapters we wait for the stream to push // through any custom headers. See ChunkedAdapter::emitHeader //if (Outgoing.numAdapters() == 0) { // // LTrace("On connect: Send header") // sendHeader(); //} }
/* client function that performs the list method */ int clientList(int sock) { if(!sendHeader(0,0,0, sock)) fatal_error("send header has failed\n"); header *rcvHead= receiveHeader(sock); if(!rcvHead) fatal_error("error receiving rcv header\n"); if(!rcvHead->indexes&&!rcvHead->length) { free(rcvHead); fprintf(stderr,"There are no songs on the server.\n\n"); return 1; } song *songs=recvSongArray(rcvHead->indexes,sock); if(!songs) fatal_error("error receiving song array\n"); fprintf(stderr,"Songs on the server are:\n"); int i; for(i=0;i<rcvHead->indexes;i++) { fprintf(stderr,"%s\n",songs[i].title); } fprintf(stderr,"\n"); free((void*)rcvHead); free((void*)songs); return 1; }
/* sever function that performs the leave method */ int serverLeave(int sock) { if(!sendHeader(3,0,0, sock)) fatal_error("send header has failed\n"); return 1; }
void sendChannel1() { sendHeader(1); //analog inputs for(uint8_t i=0;i < sizeOfArray(channel1);i++) { AnalogInputs::Name name = pgm::read(&channel1[i]); uint16_t v = AnalogInputs::getRealValue(name); printUInt(v); printD(); } for(uint8_t i=0;i<MAX_BANANCE_CELLS;i++) { printUInt(TheveninMethod::getReadableRthCell(i)); printD(); } printUInt(TheveninMethod::getReadableBattRth()); printD(); printUInt(TheveninMethod::getReadableWiresRth()); printD(); printUInt(Monitor::getChargeProcent()); printD(); printUInt(Monitor::getETATime()); printD(); sendEnd(); }
void selectFile(char *filename) { int filesize; char path[1024]; FILE *file; if(filename == NULL) return; sprintf(path, "/ESIEACloud/%s/%s", actualSession->login, filename); fprintf(stderr, "path: %s\n", path); file = fopen(path, "r"); if(file == NULL) fprintf(stderr, "Ah bah le fichier ne s'ouvre pas\n"); fseek(file, 0L, SEEK_END); filesize = ftell(file); fseek(file, 0L, SEEK_SET); if(file == NULL) sprintf(actualSession->header, "Content-Type: text/html\r\n\r\nFile Not Found"); else sprintf(actualSession->header, "Content-Description: File Transfer\r\n" "Content-Type: application/octet-stream\r\n" "Content-Disposition: attachment; filename=%s\r\n" "Content-Transfer-Encoding: binary\r\n" "Expires: 0\r\n" "Cache-Control: must-revalidate, post-check=0, pre-check=0\r\n" "Pragma: public\r\nContent-Length: %d\r\n" "\r\n", filename, filesize ); sendHeader(); sendFile(file); }
void Junxion::sendData() { sendHeader(DATA_RESPONSE, _dataSize); // Send digital input states uint16_t state = 0; uint8_t pos = 0; for (uint8_t i = 0; i < _digitalInputCount; ++i) { if (_digitalInputs[i].active) { state = state | (1 << pos); } ++pos; if (pos >= 16) { sendInt16(state); state = 0; pos = 0; } } if (pos > 0) { sendInt16(state); } // Send analog pin states for (uint8_t i = 0; i < _analogInputCount; ++i) { sendInt16(_analogInputs[i].value); } }
/** * 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 Settings::sendSysInfo() { if ( debug ) { Serial.println ( "[I] Getting sysinfo json" ); } sendHeader ( 200, "text/json", getSysInfoSize () ); String json = "{"; json += "\"freememory\":\"" + ( String ) ESP.getFreeHeap () + "\","; json += "\"deauthpackets\":\"" + ( String ) deauthpackets + "\","; json += "\"beaconpackets\":\"" + ( String ) beaconpackets + "\","; json += "\"uptime\":\"" + ( String ) millis () + "\","; json += "\"ipaddress\":\"" + ( String ) WiFi.localIP ().toString () + "\","; json += "\"gateway\":\"" + ( String ) WiFi.gatewayIP ().toString () + "\","; json += "\"bootmode\":\"" + ( String ) ESP.getBootMode () + "\","; json += "\"bootversion\":\"" + ( String ) ESP.getBootVersion () + "\","; json += "\"sdkversion\":\"" + ( String ) ESP.getSdkVersion () + "\","; json += "\"chipid\":\"" + ( String ) ESP.getChipId () + "\","; json += "\"flashchipid\":\"" + ( String ) ESP.getFlashChipId () + "\","; json += "\"flashchipsize\":\"" + ( String ) ESP.getFlashChipSize () + "\","; json += "\"flashchiprealsize\":\"" + ( String ) ESP.getFlashChipRealSize () + "\"}"; sendToBuffer ( json ); sendBuffer (); if ( debug ) { Serial.println ( "\n[+] Done" ); } }
void NodeVersionLoader::startDownload() { auto self = shared_from_this(); checkThread(); auto& item = currentDownloadItem(); { std::lock_guard<std::mutex> lock(downloadQueueMutex); --item.retryCount; } state = State::Connecting; log.setChannel("Download:" + item.version); std::string fileName; auto ver = item.version; try { onNeedsDownloadFileName(ver, fileName); if (fileName.empty()) { MSCThrow(InvalidOperationException("File name is empty.")); } } catch (...) { downloadFailed("Failed to determine the downloaded file path.: " + boost::current_exception_diagnostic_information()); return; } try { file.reset(new std::ofstream(fileName.c_str(), std::ios::out | std::ios::trunc | std::ios::binary)); file->exceptions(std::ios::failbit | std::ios::badbit); } catch (...) { file.reset(); downloadFailed("Failed to open the destination file '" + fileName + "'.: " + boost::current_exception_diagnostic_information()); return; } BOOST_LOG_SEV(log, LogLevel::Info) << "Connecting to the master server."; socket.async_connect(endpoint, [this, self, &item](const error_code& error) { checkThread(); if (disposed) { downloadCancelled(); return; } if (error) { downloadFailed(error.message()); return; } sendHeader(); }); }
void RequestHandler::sendFile(TCPSocket* sock, const std::string& file, HeaderFieldsMap& hdr_fields, int64_t off_beg, int64_t off_end) { int64_t size = FileSystem::Path(file).size(); // File doesn't exist or isn't accessible. if (size < 0) { sendResponse404(sock); return; } // Requested end offset is larger than file size. if (off_end > size) { sendResponse416(sock); return; } // Send full file. if ((off_beg < 0) && (off_end < 0)) { sendHeader(sock, STATUS_LINE_200, size, &hdr_fields); if (!sock->writeFile(file.c_str(), size - 1)) DUNE_ERR("HTTPHandle", "failed to send file: " << System::Error::getLastMessage()); return; } // Send partial content. if (off_end < 0) off_end = size - 1; if (off_beg < 0) off_beg = 0; std::ostringstream os; os << "bytes " << off_beg << "-" << off_end << "/" << size; hdr_fields.insert(std::make_pair("Content-Range", os.str())); sendHeader(sock, STATUS_LINE_206, off_end - off_beg + 1, &hdr_fields); if (!sock->writeFile(file.c_str(), off_end, off_beg)) DUNE_ERR("HTTPHandle", "failed to send file: " << System::Error::getLastMessage()); }
void sendChannel3() { sendHeader(3); printUInt(StackInfo::getNeverUsedStackSize()); printD(); printUInt(StackInfo::getFreeStackSize()); printD(); sendEnd(); }
void MailSender::sendMail() { if (!_mail) return; sendHeader(); sendContent(); sendEnd(); }
bool Network::sendFile(const char* file_name) { if (!validate()) return false; if (!Utils::hasPermissions(file_name, Utils::P_READ)) { Utils::error("File not found or insufficient permissions"); return false; } size_t file_size = Utils::getFileSize(file_name); if (!sendHeader(file_name, file_size)) { this->error = "Failed to send header"; return false; } std::ifstream fin(file_name, std::ifstream::binary); char buffer[CHUNK_SIZE]; size_t total_sent = 0; float last_progress = 0.0f; int bar_width = 70; unsigned int read_size = file_size > sizeof(buffer) ? sizeof(buffer) : file_size; while (read_size != 0 && (fin.read(buffer, read_size))) { std::streamsize s = fin.gcount(); if (!sendData(buffer, s)) { this->error = "Failed to send all data"; return false; } total_sent += s; read_size = file_size - total_sent > sizeof(buffer) ? sizeof(buffer) : file_size - total_sent; // Progress bar ------ float progress = (float) total_sent / (float) file_size; if (int(progress * 100.0) == last_progress) continue; std::cout << "["; int pos = bar_width * progress; for (int i = 0; i < bar_width; ++i) std::cout << (i < pos ? "=" : (i == pos ? ">" : " ")); std::cout << "] " << int(progress * 100.0) << "%\r" << std::flush; last_progress = int(progress * 100.0); } std::cout << "["; for (int i = 0; i < bar_width; ++i) std::cout << "="; std::cout << "] " << "100%" << std::endl; return true; }
void Response::sync() { if (hasClose) return; if (!hasHeader) { sendHeader(); } std::cout << buffer.str() << std::flush; reset(); hasSync = true; }
void ESP8266WebServerEx::SetSessionId(const String& id) { String cookie; cookie.reserve(50); cookie = m_sessionId; cookie += id; cookie += "; Path=/; Max-Age="; cookie += SESSION_EXPIRE_TIME; sendHeader("Set-Cookie",cookie); }
void SellStockReqMsg::send(QIODevice* connection) { // Domyślnie BigEndian QDataStream out(connection); sendHeader(out); out << static_cast<qint32>(m_stockId) << static_cast<qint32>(m_amount) << static_cast<qint32>(m_price); }
/***************************************************************************** * * Handle the processing of a HEAD request type. * * file: client socket stream * url: unverified url requested in the GET request * *****************************************************************************/ static int reqHead(FILE *file, char *url) { ++headCount; /* Special processing for status requests */ if (!strcmp(url, "/status")) return(sendStatus(file, 0)); return(sendHeader(file, url)); }
void handle(int sock, char* buf, fd_set *set, int i){ printf("sending HTTP header to back to socket %d\n", sock); httpRequest details = parseRequest(buf); sendHeader(sock, details.returncode, details.filename); sendFile(sock, details.filename); //close(sock); //FD_CLR(sock, set); //client_sockets[i] = 0; }
////////////////////////////////////////////////////////////////////////////////////////////////// // check if system date is valid and send the date header. ////////////////////////////////////////////////////////////////////////////////////////////////// void ESP8266WebServerEx::sendDateHeader(char* buf) { time_t t = now(); // if time is accurate, then try to send a Date header Wed, 15 Nov 1995 06:25:24 GMT if ( year(t)>2015 ) { char dow[5]; strncpy(dow,dayShortStr(weekday(t)),4); dow[3] = 0; sprintf(buf,"%s, %02u %s %04u %02u:%02u:%02u GMT",dow,day(t),monthShortStr(month(t)),year(t),hour(t),minute(t),second(t)); sendHeader("Date",buf); } }
void replanificarMapFallado(t_job* job, t_map* map){ int idNodoNuevo = *(map->idNodoOpcion2); int idBloqueNuevo = *(map->idBloqueOpcion2); bool by_idNodo(t_nodo* n) { return (*(n->id) == idNodoNuevo); } t_nodo* nodo = list_find(nodosList, (void*)by_idNodo); //guardo valores anteriores int idNodoViejo = *(map->idNodo); int idBloqueViejo = *(map->idBloque); //actualizo el map *(map->idNodo) = idNodoNuevo; *(map->idBloque) = idBloqueNuevo; list_add(job->maps, map); char* mensajeAJob = string_new(); string_append(&mensajeAJob, MAP); string_append(&mensajeAJob, "*"); char* resultFileName = string_new(); string_append(&resultFileName, TEMPLATE); string_append(&mensajeAJob, nodo->ip); string_append(&mensajeAJob, ","); string_append(&mensajeAJob, nodo->puerto); string_append(&mensajeAJob, ","); string_append(&mensajeAJob, string_itoa(idNodoNuevo)); string_append(&mensajeAJob, ","); string_append(&mensajeAJob, string_itoa(idBloqueNuevo)); string_append(&mensajeAJob, ","); string_append(&mensajeAJob, string_duplicate(resultFileName)); string_append(&mensajeAJob, string_itoa(idNodoNuevo)); string_append(&mensajeAJob, string_itoa(idBloqueNuevo)); if(strlen(mensajeAJob) > 999){ char* nuevoheader = string_new(); string_append(&nuevoheader, SOY_MARTA); //1 digito string_append(&nuevoheader, string_itoa(strlen(mensajeAJob)));//4 digitos enviar(*(job->socket), "9999", 4); //falso header enviar(*(job->socket), nuevoheader, 5); //header de 5 }else{ sendHeader(SOY_MARTA, strlen(mensajeAJob), *(job->socket)); } enviar(*(job->socket), mensajeAJob, strlen(mensajeAJob)); printf("Replanificacion nodo %d, bloque %d enviada a job.\nNuevo map en nodo %d, bloque %d\n", idNodoViejo, idBloqueViejo, idNodoNuevo, idBloqueNuevo); }
////////////////////////////////////////////////////////////////////////////////////////////////// // send data to client. Data is read from ROM // expire is # of seconds the cache will be expired. ////////////////////////////////////////////////////////////////////////////////////////////////// void ESP8266WebServerEx::sendEx(int code, const char* content_type, const char* data, size_t contentLength, bool bGzip, unsigned long expire) { if ( !VerifyCookie(content_type) ) return; String header; char buf[34]; if ( bGzip ) sendHeader("Content-Encoding", "gzip"); sendDateHeader(buf); if ( expire ) { sprintf(buf,"max-age=%lu",expire); sendHeader("Cache-Control",buf); sprintf(buf,"%lu",(unsigned long)contentLength); sendHeader("ETag",buf); } _prepareHeader(header, code, content_type, contentLength); _currentClient.write(header.c_str(), header.length()); sendWebData(data,contentLength); }
char *version_getVersion(Plugin *plugin) { PipeInfo pipeinfo; openPipes(&pipeinfo, plugin); sendHeader(&pipeinfo, plugin, PC_GetVersion); pipe_finishCommand(pipeinfo.out); char *version = pipe_readString(pipeinfo.in); closePipes(&pipeinfo); return version; }
void regutil_storeCertificates(Plugin *plugin, const char *certs) { PipeInfo pipeinfo; openPipes(&pipeinfo, plugin); sendHeader(&pipeinfo, plugin, PC_StoreCertificates); pipe_sendOptionalString(pipeinfo.out, certs); plugin->lastError = waitReply(&pipeinfo); closePipes(&pipeinfo); }
void sendChannel3() { sendHeader(3); #ifdef ENABLE_STACK_INFO //ENABLE_SERIAL_LOG printUInt(StackInfo::getNeverUsedStackSize()); printD(); printUInt(StackInfo::getFreeStackSize()); printD(); #endif sendEnd(); }