Ejemplo n.º 1
0
void WebServer::continueConnection(struct mg_connection* mgConnection) {
	if (unfinishedConnection.count(mgConnection->sock) == 0) return;

	HTTPResponse httpResponse = HTTPResponse(mgConnection);

	FILE* file = unfinishedConnection[mgConnection->sock];
	auto pData = (char*) malloc(MAX_CHUNK_LENGTH);
	size_t length = fread(pData, 1, MAX_CHUNK_LENGTH, file);

	httpResponse.sendChunk(pData, length);
	if (length < MAX_CHUNK_LENGTH) {
		fclose(file);
		httpResponse.closeConnection();
		unfinishedConnection.erase(mgConnection->sock);
		httpResponse.sendChunk("", 0);
	}
	free(pData);
}
Ejemplo n.º 2
0
/**
 * @brief Process an incoming HTTP request.
 *
 * We look at the path of the request and see if it has a matching path handler.  If it does,
 * we invoke the handler function.  If it does not, we try and find a file on the file system
 * that would resolve to the path.
 *
 * @param [in] mgConnection The network connection on which the request was received.
 * @param [in] message The message representing the request.
 */
void WebServer::processRequest(struct mg_connection* mgConnection, struct http_message* message) {
	ESP_LOGD(LOG_TAG, "WebServer::processRequest: Matching: %.*s", (int) message->uri.len, message->uri.p);
	HTTPResponse httpResponse = HTTPResponse(mgConnection);

	/*
	 * Iterate through each of the path handlers looking for a match with the method and specified path.
	 */
	std::vector<PathHandler>::iterator it;
	for (it = m_pathHandlers.begin(); it != m_pathHandlers.end(); ++it) {
		if ((*it).match(message->method.p, message->method.len, message->uri.p)) {
			HTTPRequest httpRequest(message);
			(*it).invoke(&httpRequest, &httpResponse);
			ESP_LOGD(LOG_TAG, "Found a match!!");
			return;
		}
	} // End of examine path handlers.

	// Because we reached here, it means that we did NOT match a handler.  Now we want to attempt
	// to retrieve the corresponding file content.
	std::string filePath;
	filePath.reserve(httpResponse.getRootPath().length() + message->uri.len + 1);
	filePath += httpResponse.getRootPath();
	filePath.append(message->uri.p, message->uri.len);
	ESP_LOGD(LOG_TAG, "Opening file: %s", filePath.c_str());
	FILE* file = nullptr;

	if (strcmp(filePath.c_str(), "/") != 0) {
		file = fopen(filePath.c_str(), "rb");
	}
	if (file != nullptr) {
		auto pData = (uint8_t*)malloc(MAX_CHUNK_LENGTH);
		size_t read = fread(pData, 1, MAX_CHUNK_LENGTH, file);

		if (read >= MAX_CHUNK_LENGTH) {
			httpResponse.sendChunkHead();
			httpResponse.sendChunk((char*) pData, read);
			fclose(unfinishedConnection[mgConnection->sock]);
			unfinishedConnection[mgConnection->sock] = file;
		} else {
			fclose(file);
			httpResponse.sendData(pData, read);
		}
		free(pData);
	} else {
		// Handle unable to open file
		httpResponse.setStatus(404); // Not found
		httpResponse.sendData("");
	}
} // processRequest