const string HTTPServer::guessContentType ( MyString path ) const { if ( path.endsWith ( ".html" ) || path.endsWith ( ".htm" ) ) return "text/html"; /* else if (path.endsWith(".txt") || path.endsWith(".java")) return "text/plain"; else if (path.endsWith(".gif")) return "image/gif"; else if (path.endsWith(".class")) return "application/octet-stream"; else if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return "image/jpeg";*/ else return "text/plain"; }
void HTTPServer::onUrlRequested ( MyString req, SOCKET sock ) { if ( req.find ( ".." ) !=-1 || req.find ( "/.ht" ) !=-1 || req.endsWith ( "~" ) ) { // evil hacker trying to read non-wwwhome or secret file errorReport ( sock, "403", "Forbidden", "You don't have permission to access the requested URL." ); } else { MyString path = req; MyFile f ( path ); if ( f.isDirectory() && !path.endsWith ( "/" ) ) { // redirect browser if referring to directory without final '/' path += "/"; } if ( f.isDirectory() ) { #if defined(FULLDEBUG) || defined(DEBUG) mLog ( "Is a directory: " + path ); #endif // if directory, implicitly add 'index.html' string header; header = ( string ) "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n"; string length = "Content-Length: "; string html_header = "<html><body>"; // out all files here string files; getDirFiles ( path, &files ); string html_footer = "</body></html>\r\n\r\n"; string data = html_header + files + html_footer; //count content-length. stringstream sstm; sstm << data.length(); length += sstm.str() + "\r\n\r\n"; data = header + length + html_header + files + html_footer; int n = write ( sock, data.c_str(), data.length() +1 ); if ( n < 0 ) { mLog ( "ERROR writing to socket" ); exit ( 1 ); } #ifdef FULLDEBUG mLog ( "Wrote: " + data ); #endif } else { try { // send files MyString temp; temp = ( string ) "HTTP/1.0 200 OK\r\n"; temp += "Content-Type: " + guessContentType ( path ) + "\r\n"; string data; parseFile ( sock, path, &data ); // send raw file //count content-length. string length = "Content-Length: "; stringstream sstm; sstm << data.length(); length += sstm.str() + "\r\n\r\n"; temp += length + data; int n = write ( sock, temp.c_str(), temp.length() ); if ( n < 0 ) { mLog ( "ERROR writing to socket" ); exit ( 1 ); } #if defined(DEBUG) || defined(FULLDEBUG) mLog ( "200 OK" ); #endif } catch ( ... ) { // file not found errorReport ( sock, "404", "Not Found", "The requested URL was not found on this server." ); }//try-catch }//else }//else }