#include "httpd.h" #include "httpd-logging.h" #include "httpd-heap.h" //Use this as a cgi function to redirect one url to another. httpd_cgi_state cgiRedirect(HttpdConnData *connData) { if (connData->conn == NULL) { //Connection aborted. Clean up. return HTTPD_CGI_DONE; } httpdRedirect(connData, (char *) connData->cgiArg); return HTTPD_CGI_DONE; } //Used to spit out a 404 error httpd_cgi_state cgiNotFound(HttpdConnData *connData) { if (connData->conn == NULL) { return HTTPD_CGI_DONE; } httpdStartResponse(connData, 404); httpdEndHeaders(connData); httpdSendStr(connData, "404 File not found."); return HTTPD_CGI_DONE; } //This CGI function redirects to a fixed url of http://[hostname]/ if hostname field of request isn't //already that hostname. Use this in combination with a DNS server that redirects everything to the //ESP in order to load a HTML page as soon as a phone, tablet etc connects to the ESP. Watch out: //this will also redirect connections when the ESP is in STA mode, potentially to a hostname that is not //in the 'official' DNS and so will fail. httpd_cgi_state cgiRedirectToHostname(HttpdConnData *connData) { static const char hostFmt[] = "http://%s/"; char *buff; int isIP = 0; if (connData->conn == NULL) { //Connection aborted. Clean up. return HTTPD_CGI_DONE; } if (connData->hostName == NULL) { http_warn("Huh? No hostname."); return HTTPD_CGI_NOTFOUND; } //Quick and dirty code to see if host is an IP if (strlen(connData->hostName) > 8) { isIP = 1; for (size_t x = 0; x < strlen(connData->hostName); x++) { if (connData->hostName[x] != '.' && (connData->hostName[x] < '0' || connData->hostName[x] > '9')) { isIP = 0; } } } if (isIP) { return HTTPD_CGI_NOTFOUND; } //Check hostname; pass on if the same if (strcmp(connData->hostName, (char *) connData->cgiArg) == 0) { return HTTPD_CGI_NOTFOUND; } //Not the same. Redirect to real hostname. buff = httpdMalloc(strlen((char *) connData->cgiArg) + sizeof(hostFmt)); if (buff == NULL) { //Bail out return HTTPD_CGI_DONE; } sprintf(buff, hostFmt, (char *) connData->cgiArg); http_info("Redirecting to hostname url %s", buff); httpdRedirect(connData, buff); httpdFree(buff); return HTTPD_CGI_DONE; }