├── .gitignore ├── Makefile ├── README.md ├── httpserver.cpp ├── httpserver.h ├── indexfile.cpp ├── indexfile.h ├── kv.cpp ├── kv.vcxproj ├── levenshtein.cpp ├── mapfile.hpp ├── md5.cpp ├── md5.h ├── mongoose.c ├── mongoose.h └── msw ├── trayicon.cpp ├── trayicon.h └── winmain.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | obj/ 2 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | OBJDIR = obj 2 | C_FILES := $(wildcard *.c) 3 | CPP_FILES := $(wildcard *.cpp) 4 | #OBJ_FILES := $(addprefix obj/,$(notdir $(CPP_FILES:.cpp=.obj))) $(addprefix obj/,$(notdir $(C_FILES:.c=.obj))) 5 | 6 | ifdef SYSTEMROOT 7 | RM = del /Q 8 | CC = cl 9 | LIBS = user32.lib shell32.lib 10 | OBJSUF = .obj 11 | LINK_FLAGS = /Fe$(OBJDIR)/kv 12 | CFLAGS = /Fo$@ 13 | C_FILES := $(wildcard *.c) $(wildcard msw/*.c) 14 | CPP_FILES := $(wildcard *.cpp) $(wildcard msw/*.cpp) 15 | else 16 | RM = rm -f 17 | CC = g++ 18 | CFLAGS = -DHAVE_MMAP -o $@ 19 | #OBJ_FILES := $(CPP_FILES:.cpp=.o) $(C_FILES:.c=.o) 20 | OBJSUF = .o 21 | LINK_FLAGS = -pthread -o $(OBJDIR)/kv 22 | endif 23 | 24 | OBJ_FILES := $(addprefix $(OBJDIR)/,$(CPP_FILES:.cpp=$(OBJSUF))) $(addprefix $(OBJDIR)/,$(C_FILES:.c=$(OBJSUF))) 25 | 26 | all: $(OBJDIR) kv.exe 27 | 28 | $(OBJDIR): 29 | mkdir -p $(OBJDIR)/msw 30 | 31 | kv.exe: $(OBJ_FILES) 32 | $(CC) $(LINK_FLAGS) $^ $(LIBS) 33 | 34 | $(OBJDIR)/%$(OBJSUF): %.cpp 35 | $(CC) -c $(CFLAGS) $(CPPFLAGS) $< 36 | 37 | $(OBJDIR)/%$(OBJSUF): %.c 38 | $(CC) -c $(CFLAGS) $(CPPFLAGS) $< 39 | 40 | clean: 41 | rm -rf $(OBJDIR)/ 42 | 43 | test: 44 | echo $(OBJ_FILES) 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #Command line dictionary tool -- `kv` 2 | 3 | The `kv` can 4 | 5 | * extract plain text from a dictionary of StarDict, for example, 6 | 7 | kv extract oxford.idx 8 | 9 | * build a dictionary of StarDict from a plain text file, like, 10 | 11 | kv build oxford.txt 12 | 13 | * query by keyword from a specified dictionary, 14 | 15 | kv query oxford.idx key 16 | 17 | * httpd service 18 | 19 | kv.exe server oxford.idx 20 | 21 | Then you can access http://localhost:8080/ to query word, the feature can work with [a chrome extension](https://github.com/brookhong/kv.crx) to query word on web page. 22 | 23 | The plain text file should be formated like this: 24 | 25 | #key1 26 | ;explanation of key1 27 | #key2 28 | ;explanation of key2 29 | more explanation of key2 30 | #key3 31 | ;explanation of key3 32 | #key4 33 | #key5 34 | ;explanation of key4 and key5 35 | more and more 36 | 37 | If you have `#` in your values, you can use another key marker such as `_KEY_STARTER_`, then tell `kv` about it with option `-k`. 38 | Explanations must be started with semicolon(;). 39 | 40 | ## Build Instructions 41 | cd kv 42 | make 43 | -------------------------------------------------------------------------------- /httpserver.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #include "mongoose.h" 5 | #include "httpserver.h" 6 | string queryDict(const char *idxFileName, const char *keyword); 7 | 8 | static const char *html_form = 9 | "" 10 | "
" 11 | "Word: " 12 | "" 13 | "
"; 14 | 15 | static int handler(struct mg_connection *conn) { 16 | char var1[500]; 17 | 18 | if (strcmp(conn->uri, "/query") == 0) { 19 | // User has submitted a form, show submitted data and a variable value 20 | // Parse form data. var1 and var2 are guaranteed to be NUL-terminated 21 | mg_get_var(conn, "word", var1, sizeof(var1)); 22 | 23 | // Send reply to the client, showing submitted form values. 24 | // POST data is in conn->content, data length is in conn->content_len 25 | mg_send_header(conn, "Content-Type", "text/plain; charset=UTF-8"); 26 | string ret = queryDict((const char *)conn->server_param, var1); 27 | mg_printf_data(conn, "%s\n", ret.c_str()); 28 | } else { 29 | // Show HTML form. 30 | mg_send_data(conn, html_form, strlen(html_form)); 31 | } 32 | 33 | return 1; 34 | } 35 | 36 | int stopped = 0; 37 | 38 | void _httpServer(void *pv) { 39 | HTTPD *p = (HTTPD*)pv; 40 | static string sIdxFile = p->idxFileName; 41 | struct mg_server *server = mg_create_server((void*)sIdxFile.c_str()); 42 | mg_set_option(server, "listening_port", p->port); 43 | mg_add_uri_handler(server, "/", handler); 44 | printf("Starting on port %s\n", mg_get_option(server, "listening_port")); 45 | while (!stopped) { 46 | mg_poll_server(server, 1000); 47 | } 48 | mg_destroy_server(&server); 49 | } 50 | 51 | #ifndef _WIN32 52 | int httpServer(const char *idxFileName, const char *port) { 53 | HTTPD httpd; 54 | httpd.idxFileName = idxFileName; 55 | httpd.port = port; 56 | _httpServer(&httpd); 57 | return 0; 58 | } 59 | #endif 60 | -------------------------------------------------------------------------------- /httpserver.h: -------------------------------------------------------------------------------- 1 | #ifndef _HTTPSERVER_H 2 | #define _HTTPSERVER_H 3 | 4 | typedef struct _HTTPD{ 5 | const char * idxFileName; 6 | const char * port; 7 | }HTTPD; 8 | 9 | void _httpServer(void *pv); 10 | 11 | #endif 12 | -------------------------------------------------------------------------------- /indexfile.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Brook Hong 3 | * 4 | * The MIT License 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining 7 | * a copy of this software and associated documentation files 8 | * (the "Software"), to deal in the Software without restriction, 9 | * including without limitation the rights to use, copy, modify, 10 | * merge, publish, distribute, sublicense, and/or sell copies of the 11 | * Software, and to permit persons to whom the Software is furnished 12 | * to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be included 15 | * in all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 20 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 21 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 22 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | * 25 | */ 26 | #include "indexfile.h" 27 | const char *IndexFile::CACHE_MAGIC="StarDict's Cache, Version: 0.1"; 28 | 29 | void switchEndianness( void * lpMem ) 30 | { 31 | unsigned char * p = (unsigned char*)lpMem; 32 | p[0] = p[0] ^ p[3]; 33 | p[3] = p[0] ^ p[3]; 34 | p[0] = p[0] ^ p[3]; 35 | p[1] = p[1] ^ p[2]; 36 | p[2] = p[1] ^ p[2]; 37 | p[1] = p[1] ^ p[2]; 38 | } 39 | 40 | int i_strcmp(const char *s1, const char *s2) 41 | { 42 | #ifdef _WIN32 43 | int cmp = _stricmp(s1, s2); 44 | #else 45 | int cmp = strcasecmp(s1, s2); 46 | #endif 47 | return cmp; 48 | } 49 | 50 | int file_exist(const char *filename) { 51 | struct stat buffer; 52 | return (stat (filename, &buffer) == 0); 53 | } 54 | 55 | void IndexFile::page_t::fill(char *data, int nent, long idx_) 56 | { 57 | idx=idx_; 58 | char *p=data; 59 | long len; 60 | for (int i=0; i255. 84 | return wordentry_buf; 85 | } 86 | 87 | inline const char *IndexFile::get_first_on_page_key(long page_idx) 88 | { 89 | if (page_idxmiddle.idx) { 94 | if (page_idx==last.idx) 95 | return last.keystr.c_str(); 96 | return read_first_on_page_key(page_idx); 97 | } else 98 | return middle.keystr.c_str(); 99 | } 100 | 101 | bool IndexFile::load_cache(const string& url) 102 | { 103 | string cacheFile = url+".oft"; 104 | 105 | struct stat idxstat, cachestat; 106 | if (stat(url.c_str(), &idxstat)!=0 || stat(cacheFile.c_str(), &cachestat)!=0) 107 | return false; 108 | if (cachestat.st_mtime0) { 233 | idx = INVALID_INDEX; 234 | return false; 235 | } else { 236 | iFrom=0; 237 | iThisIndex=0; 238 | while (iFrom<=iTo) { 239 | iThisIndex=(iFrom+iTo)/2; 240 | cmpint = i_strcmp(str, get_first_on_page_key(iThisIndex)); 241 | if (cmpint>0) 242 | iFrom=iThisIndex+1; 243 | else if (cmpint<0) 244 | iTo=iThisIndex-1; 245 | else { 246 | bFound=true; 247 | break; 248 | } 249 | } 250 | if (!bFound) 251 | idx = iTo; //prev 252 | else 253 | idx = iThisIndex; 254 | } 255 | if (!bFound) { 256 | unsigned long netr=load_page(idx); 257 | iFrom=1; // Needn't search the first word anymore. 258 | iTo=netr-1; 259 | iThisIndex=0; 260 | while (iFrom<=iTo) { 261 | iThisIndex=(iFrom+iTo)/2; 262 | cmpint = i_strcmp(str, page.entries[iThisIndex].keystr); 263 | if (cmpint>0) 264 | iFrom=iThisIndex+1; 265 | else if (cmpint<0) 266 | iTo=iThisIndex-1; 267 | else { 268 | bFound=true; 269 | break; 270 | } 271 | } 272 | idx*=ENTR_PER_PAGE; 273 | if (!bFound) 274 | idx += iFrom; //next 275 | else 276 | idx += iThisIndex; 277 | } else { 278 | idx*=ENTR_PER_PAGE; 279 | } 280 | return bFound; 281 | } 282 | static bool isEnglish(const char *str) 283 | { 284 | int i = 0; 285 | while(str[i]!=0 && isascii(str[i])) { 286 | i++; 287 | } 288 | return (str[i] == 0); 289 | } 290 | static inline bool isVowel(char ch) 291 | { 292 | return( ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' ); 293 | } 294 | bool IndexFile::lookupWithGrammar(const char *str, long &idx) 295 | { 296 | // * http://www.eslcafe.com/grammar/verb_forms_and_tenses04.html 297 | // windows goes plies studies 298 | // * http://www.eslcafe.com/grammar/verb_forms_and_tenses05.html 299 | // talking whistling hoping hiking 300 | // * http://www.eslcafe.com/grammar/verb_forms_and_tenses06.html 301 | // suing gluing aching hogging cheating 302 | // * http://www.eslcafe.com/grammar/verb_forms_and_tenses07.html 303 | // * http://www.eslcafe.com/grammar/verb_forms_and_tenses08.html 304 | // * http://www.eslcafe.com/grammar/simple_past_tense02.html 305 | // filled baked buried stopped 306 | // * http://www.englisch-hilfen.de/en/grammar/adjektive_steig.htm 307 | // higher newest hotter biggest dirtier larger easiest largest 308 | string word(str); 309 | int len = word.length(); 310 | if(len < 4 || !isEnglish(str)) { 311 | return false; 312 | } 313 | string ending3 = word.substr(len-3,3); 314 | string ending2 = word.substr(len-2,2); 315 | 316 | for(int i=0;i sWords; 320 | if(word[len-1] == 's' || word[len-1] == 'd' 321 | || (word[len-1] == 'y' && word[len-2] == 'l' && word[len-3] == 'l' ) ) { 322 | sWords.push_back(string(word).replace(len-1, 1, "")); 323 | } 324 | if(ending2 == "ed" || ending2 == "er") { 325 | sWords.push_back(string(word).replace(len-2, 2, "")); 326 | } 327 | if(ending3 == "ing" || ending3 == "est") { 328 | sWords.push_back(string(word).replace(len-3, 3, "")); 329 | } 330 | if(ending3 == "est") { 331 | // est->e 332 | sWords.push_back(string(word).replace(len-2, 2, "")); 333 | if(word[len-4] == 'i') { 334 | // iest->y 335 | sWords.push_back(string(word).replace(len-4, 4, "y")); 336 | } 337 | } 338 | if(len>4 && (!isVowel(word[len-4]) || word[len-4] == 'u')) { 339 | // [d]ies->y,[d]ied->y,[p]ier->y 340 | if(ending3 == "ies" || ending3 == "ied" || ending3 == "ier") { 341 | sWords.push_back(string(word).replace(len-3, 3, "y")); 342 | } 343 | else if(ending3 == "ing") { 344 | // [m|u]ing->e 345 | sWords.push_back(string(word).replace(len-3, 3, "e")); 346 | } 347 | } 348 | if(len>6 && isVowel(word[len-6]) && !isVowel(word[len-5]) && word[len-5] == word[len-4] 349 | && (ending3 == "ing" || ending3 == "est")) { 350 | // [og]ging->,[ot]test-> 351 | sWords.push_back(string(word).replace(len-4, 4, "")); 352 | } 353 | if(len>5 && isVowel(word[len-5]) && !isVowel(word[len-4]) && word[len-4] == word[len-3] 354 | && (ending2 == "er" || ending2 == "ed")) { 355 | // [op]ped->,[ot]ter-> 356 | sWords.push_back(string(word).replace(len-3, 3, "")); 357 | } 358 | if(!isVowel(word[len-3]) && ending2 == "er") { 359 | // [t]er->r 360 | sWords.push_back(string(word).replace(len-1, 1, "")); 361 | } 362 | if( word[len-3] == 's' || word[len-3] == 'x' || word[len-3] == 'o' 363 | || (word[len-3] == 'h' && (word[len-4] == 's' || word[len-4] == 'c')) ) { 364 | // [s|x|sh|ch|o]es-> 365 | if(ending2 == "es") { 366 | sWords.push_back(string(word).replace(len-2, 2, "")); 367 | } 368 | } 369 | if(ending3 == "ied" || ending3 == "ily") { 370 | // ied->y,ily->y 371 | sWords.push_back(string(word).replace(len-3, 3, "y")); 372 | } 373 | if(ending2 == "ve") { 374 | // ve->s 375 | sWords.push_back(string(word).replace(len-2, 2, "s")); 376 | } 377 | if(!isVowel(word[len-2]) && word[len-1] == 'y') { 378 | // [bl]y->e 379 | sWords.push_back(string(word).replace(len-1, 1, "e")); 380 | } 381 | for(int i=0; i &frs) 389 | { 390 | if(strlen(str) < 5) { 391 | return false; 392 | } 393 | unsigned int distance = 3; 394 | FuzzyResult fr; 395 | int i, j, npages = (wordcount+(ENTR_PER_PAGE-1))/ENTR_PER_PAGE; 396 | for(i=0; i0; 416 | } 417 | bool IndexFile::lookupPartial(const char *str, list &frs) 418 | { 419 | if(strlen(str) < 3) { 420 | return false; 421 | } 422 | FuzzyResult fr; 423 | int i, j, npages = (wordcount+(ENTR_PER_PAGE-1))/ENTR_PER_PAGE; 424 | for(i=0; i0; 444 | } 445 | -------------------------------------------------------------------------------- /indexfile.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Brook Hong 3 | * 4 | * The MIT License 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining 7 | * a copy of this software and associated documentation files 8 | * (the "Software"), to deal in the Software without restriction, 9 | * including without limitation the rights to use, copy, modify, 10 | * merge, publish, distribute, sublicense, and/or sell copies of the 11 | * Software, and to permit persons to whom the Software is furnished 12 | * to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be included 15 | * in all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 20 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 21 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 22 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | * 25 | */ 26 | #ifndef _INDEXFILE_HPP_ 27 | #define _INDEXFILE_HPP_ 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include "mapfile.hpp" 36 | using namespace std; 37 | 38 | const int INVALID_INDEX=-100; 39 | 40 | void switchEndianness( void * lpMem ); 41 | int i_strcmp(const char *s1, const char *s2); 42 | int file_exist(const char *filename); 43 | unsigned int levenshtein (const char *word1, const char *word2); 44 | 45 | struct FuzzyResult { 46 | unsigned int distance; 47 | int idx; 48 | bool operator < (const FuzzyResult& rhs) const { 49 | return distance < rhs.distance; 50 | } 51 | }; 52 | class IndexFile { 53 | public: 54 | unsigned int wordentry_offset; 55 | unsigned int wordentry_size; 56 | IndexFile() : idxfile(NULL) {} 57 | ~IndexFile(); 58 | bool load(const string& url, unsigned long wc, unsigned long fsize); 59 | const char *get_key(long idx); 60 | const char *get_entry(long idx, string &value); 61 | void get_data(long idx); 62 | const char *get_key_and_data(long idx); 63 | bool lookup(const char *str, long &idx); 64 | bool lookupWithGrammar(const char *str, long &idx); 65 | bool lookupFuzzy(const char *str, list &frs); 66 | bool lookupPartial(const char *str, list &frs); 67 | 68 | private: 69 | static const int ENTR_PER_PAGE=32; 70 | static const char *CACHE_MAGIC; 71 | 72 | string fullfilename; 73 | vector wordoffset; 74 | FILE *idxfile; 75 | unsigned long wordcount; 76 | 77 | char wordentry_buf[256+sizeof(unsigned int)*2]; // The length of "word_str" should be less than 256. See src/tools/DICTFILE_FORMAT. 78 | struct index_entry { 79 | long idx; 80 | string keystr; 81 | void assign(long i, const string& str) { 82 | idx=i; 83 | keystr.assign(str); 84 | } 85 | }; 86 | index_entry first, last, middle, real_last; 87 | 88 | struct page_entry { 89 | char *keystr; 90 | unsigned int off, size; 91 | }; 92 | vector page_data; 93 | struct page_t { 94 | long idx; 95 | page_entry entries[ENTR_PER_PAGE]; 96 | 97 | page_t(): idx(-1) {} 98 | void fill(char *data, int nent, long idx_); 99 | } page; 100 | unsigned long load_page(long page_idx); 101 | const char *read_first_on_page_key(long page_idx); 102 | const char *get_first_on_page_key(long page_idx); 103 | bool load_cache(const string& url); 104 | bool save_cache(const string& url); 105 | }; 106 | #endif 107 | -------------------------------------------------------------------------------- /kv.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Brook Hong 3 | * 4 | * The MIT License 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining 7 | * a copy of this software and associated documentation files 8 | * (the "Software"), to deal in the Software without restriction, 9 | * including without limitation the rights to use, copy, modify, 10 | * merge, publish, distribute, sublicense, and/or sell copies of the 11 | * Software, and to permit persons to whom the Software is furnished 12 | * to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be included 15 | * in all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 20 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 21 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 22 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | * 25 | * 26 | * BUILD INSTRUCTIONS 27 | * LINUX : g++ -DHAVE_MMAP kv.cpp md5.cpp indexfile.cpp levenshtein.cpp mongoose.c 28 | * WINDOWS : cl -D_WIN32 kv.cpp md5.cpp indexfile.cpp levenshtein.cpp mongoose.c 29 | */ 30 | #include "mapfile.hpp" 31 | #include "indexfile.h" 32 | #include "md5.h" 33 | #include 34 | #include 35 | 36 | string gKeyMarker = "#"; 37 | string gPort = "8080"; 38 | struct Index { 39 | int m_nKeyLen; 40 | int m_nOffset; 41 | int m_nSize; 42 | Index() { 43 | m_nKeyLen = 0; 44 | m_nSize = 0; 45 | m_nOffset = 0; 46 | } 47 | Index(int kLen, int eLen, int eOff) { 48 | m_nKeyLen = kLen; 49 | m_nSize = eLen; 50 | m_nOffset = eOff; 51 | } 52 | }; 53 | 54 | bool createMapFile(const char *fileName, MapFile &map_file) { 55 | struct stat buf; 56 | return (stat(fileName, &buf) == 0 && map_file.open(fileName, buf.st_size)); 57 | } 58 | 59 | void buildDict(const char *txtFile, string& bookName) { 60 | MapFile map_file; 61 | if(!createMapFile(txtFile, map_file)) { 62 | return; 63 | } 64 | char *p = map_file.begin(); 65 | string fileName = txtFile; 66 | size_t period = fileName.find_last_of("."); 67 | fileName.replace(period,fileName.length()-period,".dict"); 68 | ofstream fDictData(fileName.c_str(), ios_base::binary); 69 | fileName.replace(fileName.length()-5,4,".ifo"); 70 | fileName.erase(fileName.length()-1); 71 | ofstream fIfo(fileName.c_str(), ios_base::binary); 72 | fileName.replace(fileName.length()-4,4,".idx"); 73 | ofstream fIdx(fileName.c_str(), ios_base::binary); 74 | size_t lenKeyMarker = gKeyMarker.length(); 75 | p += lenKeyMarker; 76 | char *keyStart = p, *valueStart = 0; 77 | int keyLen = 0, offset = 0, wordCount = 0; 78 | map idxMap; 79 | map synonyms; 80 | map::iterator itci; 81 | map digestMap; 82 | for(;;p++) { 83 | if(*p == '\n') { 84 | if(keyStart && !valueStart) { 85 | keyLen = p-keyStart; 86 | if(*(p+1) == '\r') { 87 | keyLen -= 1; 88 | } 89 | string key(keyStart, keyLen); 90 | if(key.find("\r") != string::npos) { 91 | printf("Invalid input file.\n"); 92 | return; 93 | } 94 | } 95 | } else if(*p == ';') { 96 | if(keyLen && !valueStart) { 97 | valueStart = p+1; 98 | } 99 | } else if(*p == '\0' || strncmp(p, gKeyMarker.c_str(), lenKeyMarker) == 0) { 100 | if(keyLen && *(p-1) == '\n') { 101 | if(valueStart) { 102 | int expLen = p-valueStart-1; 103 | int iOff = offset; 104 | 105 | string value(valueStart, expLen); 106 | string digest = md5(value); 107 | if(digestMap.count(digest)) { 108 | Index & idx = digestMap[digest]; 109 | expLen = idx.m_nSize; 110 | iOff = idx.m_nOffset; 111 | } else { 112 | fDictData.write(valueStart, expLen); 113 | offset += expLen; 114 | digestMap[digest] = Index(0, expLen, iOff); 115 | } 116 | idxMap[keyStart] = Index(keyLen, expLen, iOff); 117 | for(itci = synonyms.begin(); itci != synonyms.end(); itci++) { 118 | idxMap[itci->first] = Index(itci->second, expLen, iOff); 119 | wordCount++; 120 | } 121 | 122 | wordCount++; 123 | keyLen = 0; 124 | valueStart = 0; 125 | synonyms.clear(); 126 | } else { 127 | synonyms[keyStart] = keyLen; 128 | } 129 | keyStart = p+lenKeyMarker; 130 | p += lenKeyMarker-1; 131 | } 132 | if(*p == '\0') { 133 | break; 134 | } 135 | } 136 | } 137 | char** idxVector = (char**)malloc(wordCount*sizeof(char*)); 138 | int* lenVector = (int*)malloc(wordCount*sizeof(int)); 139 | map::iterator it; 140 | offset = 0; 141 | for(it = idxMap.begin(); it != idxMap.end(); it++) { 142 | string str(it->first, it->second.m_nKeyLen); 143 | int start = 0, pos, end = offset-1; 144 | while(start<=end) { 145 | pos = (start+end)/2; 146 | string s(idxVector[pos], lenVector[pos]); 147 | int cmp = i_strcmp(str.c_str(), s.c_str()); 148 | if(cmp < 0) { 149 | end = pos-1; 150 | } else { 151 | start = pos+1; 152 | } 153 | } 154 | for(int i = offset; i > start; i--) { 155 | idxVector[i] = idxVector[i-1]; 156 | lenVector[i] = lenVector[i-1]; 157 | } 158 | idxVector[start] = it->first; 159 | lenVector[start] = it->second.m_nKeyLen; 160 | offset++; 161 | } 162 | for(int i = 0; i < wordCount; i++) { 163 | keyStart = idxVector[i]; 164 | Index aIdx = idxMap[keyStart]; 165 | fIdx.write(keyStart, aIdx.m_nKeyLen); 166 | fIdx.write("\0",1); 167 | switchEndianness(&(aIdx.m_nSize)); 168 | switchEndianness(&(aIdx.m_nOffset)); 169 | fIdx.write((char*)&aIdx.m_nOffset, 4); 170 | fIdx.write((char*)&aIdx.m_nSize, 4); 171 | } 172 | free(idxVector); 173 | free(lenVector); 174 | fIdx.close(); 175 | struct stat buf; 176 | stat(fileName.c_str(), &buf); 177 | fIfo << "StarDict's dict ifo file\nversion=2.4.2\n"; 178 | fIfo << "wordcount="; 179 | fIfo << wordCount; 180 | fIfo << "\nidxfilesize="; 181 | fIfo << buf.st_size; 182 | fIfo << "\nbookname="; 183 | if(bookName == "") { 184 | bookName = txtFile; 185 | } 186 | fIfo << bookName; 187 | fIfo << "\nauthor=brook hong"; 188 | fIfo << "\nwebsite=https://github.com/brookhong"; 189 | 190 | time_t rawtime; 191 | struct tm * timeinfo; 192 | char sDate[80]; 193 | time ( &rawtime ); 194 | timeinfo = localtime ( &rawtime ); 195 | strftime (sDate,80,"%Y.%m.%d %H:%M:%S",timeinfo); 196 | 197 | fIfo << "\ndate="; 198 | fIfo << sDate; 199 | fIfo << "\nsametypesequence=m"; 200 | fIfo << endl; 201 | fIfo.close(); 202 | } 203 | void extractDict(const char *idxFileName) { 204 | MapFile map_file; 205 | if(!createMapFile(idxFileName, map_file)) { 206 | return; 207 | } 208 | char *p = map_file.begin(); 209 | Index aIdx; 210 | string sDictFile = idxFileName; 211 | sDictFile.replace(sDictFile.length()-4,5,".dict"); 212 | ifstream fDictData(sDictFile.c_str()); 213 | sDictFile.replace(sDictFile.length()-5,4,".txt"); 214 | sDictFile.erase(sDictFile.length()-1); 215 | ofstream fOut(sDictFile.c_str(), ios_base::binary); 216 | char * pExplanation; 217 | unsigned int maxWordLen = 0; 218 | unsigned int maxExpLen = 0; 219 | string maxLenString; 220 | size_t wordLen = 0; 221 | char * sWord = 0; 222 | while(p) { 223 | sWord = p; 224 | wordLen = strlen(p); 225 | if(wordLen>maxWordLen) { 226 | maxWordLen = wordLen; 227 | maxLenString = p; 228 | } 229 | p += wordLen+1; 230 | aIdx.m_nOffset = *(unsigned int*)p; 231 | switchEndianness(&(aIdx.m_nOffset)); 232 | p += 4; 233 | aIdx.m_nSize = *(unsigned int*)p; 234 | switchEndianness(&(aIdx.m_nSize)); 235 | if(aIdx.m_nSize == 0) { 236 | break; 237 | } 238 | p += 4; 239 | maxExpLen = (aIdx.m_nSize>maxExpLen)?aIdx.m_nSize:maxExpLen; 240 | pExplanation = (char*)malloc(aIdx.m_nSize); 241 | fDictData.seekg(aIdx.m_nOffset,ios::beg); 242 | fDictData.read(pExplanation,aIdx.m_nSize); 243 | fOut.write(gKeyMarker.c_str(),gKeyMarker.length()); 244 | fOut.write(sWord,wordLen); 245 | fOut.write("\n",1); 246 | fOut.write(";",1); 247 | fOut.write(pExplanation,aIdx.m_nSize); 248 | fOut.write("\n",1); 249 | free(pExplanation); 250 | } 251 | fOut.write(gKeyMarker.c_str(),gKeyMarker.length()); 252 | printf("Max Word Length\t\t: %u\n" 253 | "Max Explanation Length\t: %u\n" 254 | "Longest Word\t\t: %s\n", 255 | maxWordLen,maxExpLen,maxLenString.c_str()); 256 | fOut.close(); 257 | } 258 | std::string string_format(const std::string fmt, ...) { 259 | int size = 100; 260 | std::string str; 261 | va_list ap; 262 | while (1) { 263 | str.resize(size); 264 | va_start(ap, fmt); 265 | int n = vsnprintf((char *)str.c_str(), size, fmt.c_str(), ap); 266 | va_end(ap); 267 | if (n > -1 && n < size) { 268 | str.resize(n); 269 | return str; 270 | } 271 | if (n > -1) 272 | size = n + 1; 273 | else 274 | size *= 2; 275 | } 276 | return str; 277 | } 278 | string queryDict(const char *idxFileName, const char *keyword) { 279 | string result; 280 | string fileName = idxFileName; 281 | if(!file_exist(idxFileName) || strlen(idxFileName) < 4) { 282 | result = string(idxFileName) + " is not a valid idx file.\n"; 283 | } else { 284 | fileName.replace(fileName.length()-4,4,".ifo"); 285 | if(!file_exist(fileName.c_str())) { 286 | result = fileName + " not exists\n"; 287 | } else { 288 | ifstream fIfo(fileName.c_str()); 289 | char line[256]; 290 | unsigned int wc = 0, idxFileSize = 0; 291 | while((wc == 0 || idxFileSize == 0) && !fIfo.eof()){ 292 | fIfo.getline(line, 256); 293 | if(strncmp(line, "wordcount=", 10) == 0) { 294 | sscanf(line, "wordcount=%u\n", &wc); 295 | } else if(strncmp(line, "idxfilesize=", 12) == 0) { 296 | sscanf(line, "idxfilesize=%u\n", &idxFileSize); 297 | } 298 | } 299 | 300 | IndexFile idxFile; 301 | long cur = INVALID_INDEX; 302 | list results; 303 | if( idxFile.load(idxFileName, wc, idxFileSize) 304 | && (idxFile.lookup(keyword, cur) 305 | || idxFile.lookupWithGrammar(keyword, cur) 306 | || idxFile.lookupFuzzy(keyword, results) 307 | || idxFile.lookupPartial(keyword, results) 308 | ) ) { 309 | if(results.size() > 0) { 310 | list::iterator it; 311 | for(it = results.begin(); it != results.end(); it++) { 312 | string value, key; 313 | key = idxFile.get_entry(it->idx, value); 314 | result += string_format("\n%s(%d)\n%s\n", key.c_str(), it->distance, value.c_str()); 315 | } 316 | } else { 317 | string value, key; 318 | key = idxFile.get_entry(cur, value); 319 | result = value; 320 | } 321 | } 322 | } 323 | } 324 | return result; 325 | } 326 | int showUsage() { 327 | printf( "kv -- a simple dict tool to build dict(StarDict), extract dict and query\n\n" 328 | "Build\n\tkv build [-t ] [-k <key marker>] <plain txt file>\n\n" 329 | "\tThe plain text file should be formated as below:\n" 330 | "--------------------------------------------------------------------------------\n" 331 | "#key1\n" 332 | ";explainations must be started with semicolon, explanation of key1\n" 333 | "#key2\n" 334 | ";explanation of key2\n" 335 | "more explanation of key2\n" 336 | "#key3\n" 337 | ";explanation of key3\n" 338 | "#key4\n" 339 | "#key5\n" 340 | ";explanation of key4 and key5\n" 341 | "more and more\n" 342 | "--------------------------------------------------------------------------------\n" 343 | "\tIf you have `#` in your values, you can use another key marker such as `_KEY_STARTER_`, then tell `kv` about it with option `-k`.\n" 344 | "\tExplanations must be started with semicolon(;).\n" 345 | "Extract\n\tkv extract <.idx file>\n\n" 346 | "Query\n\tkv query <.idx file> <keyword>\n\n" 347 | "Server\n\tkv server [-p <port>] <.idx file>\n\n" 348 | "Example\n\tkv build -k '_KEY_STARTER_' test.txt\n" 349 | "\tkv query ./test.idx key\n" 350 | "\tkv server -p 127.0.0.1:9078 ./test.idx\n\n" 351 | ); 352 | return 1; 353 | } 354 | 355 | int httpServer(const char *idxFileName, const char *port); 356 | int main(int argc,char** argv) 357 | { 358 | if(argc < 2) { 359 | return showUsage(); 360 | } else { 361 | int i = 2; 362 | string sBookName; 363 | while(i<argc) { 364 | if(argv[i][0] == '-') { 365 | switch (argv[i][1]) { 366 | case 't': 367 | if(++i < argc) { 368 | sBookName = argv[i]; 369 | } else { 370 | return showUsage(); 371 | } 372 | break; 373 | case 'k': 374 | if(++i < argc) { 375 | gKeyMarker = argv[i]; 376 | } else { 377 | return showUsage(); 378 | } 379 | break; 380 | case 'p': 381 | if(++i < argc) { 382 | gPort = argv[i]; 383 | } else { 384 | return showUsage(); 385 | } 386 | default: 387 | break; 388 | } 389 | i++; 390 | } else { 391 | break; 392 | } 393 | } 394 | if(i == argc) { 395 | return showUsage(); 396 | } 397 | 398 | if(0 == strcmp(argv[1],"build")) { 399 | buildDict(argv[i], sBookName); 400 | } else if(0 == strcmp(argv[1],"extract")) { 401 | extractDict(argv[i]); 402 | } else if(0 == strcmp(argv[1],"query")) { 403 | if(i+1 < argc) { 404 | string ret = queryDict(argv[i], argv[i+1]); 405 | printf("%s\n", ret.c_str()); 406 | } else { 407 | return showUsage(); 408 | } 409 | } else if(0 == strcmp(argv[1],"server")) { 410 | return httpServer(argv[i], gPort.c_str()); 411 | } else { 412 | return showUsage(); 413 | } 414 | } 415 | return 0; 416 | } 417 | -------------------------------------------------------------------------------- /kv.vcxproj: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="utf-8"?> 2 | <Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 3 | <ItemGroup Label="ProjectConfigurations"> 4 | <ProjectConfiguration Include="Debug|Win32"> 5 | <Configuration>Debug</Configuration> 6 | <Platform>Win32</Platform> 7 | </ProjectConfiguration> 8 | <ProjectConfiguration Include="Release|Win32"> 9 | <Configuration>Release</Configuration> 10 | <Platform>Win32</Platform> 11 | </ProjectConfiguration> 12 | </ItemGroup> 13 | <PropertyGroup Label="Globals"> 14 | <ProjectGuid>{140EEC94-2B41-4AC4-9BDC-E30B673E296C}</ProjectGuid> 15 | <Keyword>Win32Proj</Keyword> 16 | <RootNamespace>kv</RootNamespace> 17 | </PropertyGroup> 18 | <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> 19 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> 20 | <ConfigurationType>Application</ConfigurationType> 21 | <UseDebugLibraries>true</UseDebugLibraries> 22 | <PlatformToolset>v120</PlatformToolset> 23 | <CharacterSet>MultiByte</CharacterSet> 24 | </PropertyGroup> 25 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> 26 | <ConfigurationType>Application</ConfigurationType> 27 | <UseDebugLibraries>false</UseDebugLibraries> 28 | <PlatformToolset>v120</PlatformToolset> 29 | <WholeProgramOptimization>true</WholeProgramOptimization> 30 | <CharacterSet>MultiByte</CharacterSet> 31 | </PropertyGroup> 32 | <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> 33 | <ImportGroup Label="ExtensionSettings"> 34 | </ImportGroup> 35 | <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> 36 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 37 | </ImportGroup> 38 | <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> 39 | <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> 40 | </ImportGroup> 41 | <PropertyGroup Label="UserMacros" /> 42 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> 43 | <LinkIncremental>true</LinkIncremental> 44 | </PropertyGroup> 45 | <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> 46 | <LinkIncremental>false</LinkIncremental> 47 | </PropertyGroup> 48 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> 49 | <ClCompile> 50 | <PrecompiledHeader> 51 | </PrecompiledHeader> 52 | <WarningLevel>Level3</WarningLevel> 53 | <Optimization>Disabled</Optimization> 54 | <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions> 55 | <SDLCheck>false</SDLCheck> 56 | </ClCompile> 57 | <Link> 58 | <SubSystem>Console</SubSystem> 59 | <GenerateDebugInformation>true</GenerateDebugInformation> 60 | </Link> 61 | </ItemDefinitionGroup> 62 | <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> 63 | <ClCompile> 64 | <WarningLevel>Level3</WarningLevel> 65 | <PrecompiledHeader> 66 | </PrecompiledHeader> 67 | <Optimization>MaxSpeed</Optimization> 68 | <FunctionLevelLinking>true</FunctionLevelLinking> 69 | <IntrinsicFunctions>true</IntrinsicFunctions> 70 | <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions> 71 | <SDLCheck>false</SDLCheck> 72 | </ClCompile> 73 | <Link> 74 | <SubSystem>Console</SubSystem> 75 | <GenerateDebugInformation>true</GenerateDebugInformation> 76 | <EnableCOMDATFolding>true</EnableCOMDATFolding> 77 | <OptimizeReferences>true</OptimizeReferences> 78 | </Link> 79 | </ItemDefinitionGroup> 80 | <ItemGroup> 81 | <ClCompile Include="indexfile.cpp" /> 82 | <ClCompile Include="kv.cpp" /> 83 | <ClCompile Include="levenshtein.cpp" /> 84 | <ClCompile Include="md5.cpp" /> 85 | <ClCompile Include="msw\httpserver.cpp" /> 86 | <ClCompile Include="msw\mongoose.c" /> 87 | <ClCompile Include="msw\trayicon.cpp" /> 88 | <ClCompile Include="msw\winmain.cpp" /> 89 | </ItemGroup> 90 | <ItemGroup> 91 | <ClInclude Include="mapfile.hpp" /> 92 | </ItemGroup> 93 | <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> 94 | <ImportGroup Label="ExtensionTargets"> 95 | </ImportGroup> 96 | </Project> -------------------------------------------------------------------------------- /levenshtein.cpp: -------------------------------------------------------------------------------- 1 | # include <string.h> 2 | # include <stdlib.h> 3 | 4 | # ifdef LEV_CASE_INSENSITIVE 5 | # include <ctype.h> 6 | # define eq(x, y) (tolower(x) == tolower(y)) 7 | # else 8 | # define eq(x, y) ((x) == (y)) 9 | # endif 10 | 11 | # define min(x, y) ((x) < (y) ? (x) : (y)) 12 | 13 | unsigned int levenshtein (const char *word1, const char *word2) { 14 | unsigned int len1 = strlen(word1), 15 | len2 = strlen(word2); 16 | unsigned int *v = (unsigned int *)calloc(len2 + 1, sizeof(unsigned int)); 17 | unsigned int i, j, current, next, cost; 18 | 19 | /* strip common prefixes */ 20 | while (len1 > 0 && len2 > 0 && eq(word1[0], word2[0])) 21 | word1++, word2++, len1--, len2--; 22 | 23 | /* handle degenerate cases */ 24 | if (!len1) return len2; 25 | if (!len2) return len1; 26 | 27 | /* initialize the column vector */ 28 | for (j = 0; j < len2 + 1; j++) 29 | v[j] = j; 30 | 31 | for (i = 0; i < len1; i++) { 32 | /* set the value of the first row */ 33 | current = i + 1; 34 | /* for each row in the column, compute the cost */ 35 | for (j = 0; j < len2; j++) { 36 | /* 37 | * cost of replacement is 0 if the two chars are the same, or have 38 | * been transposed with the chars immediately before. otherwise 1. 39 | */ 40 | cost = !(eq(word1[i], word2[j]) || (i && j && 41 | eq(word1[i-1], word2[j]) && eq(word1[i],word2[j-1]))); 42 | /* find the least cost of insertion, deletion, or replacement */ 43 | next = min(min( v[j+1] + 1, 44 | current + 1 ), 45 | v[j] + cost ); 46 | /* stash the previous row's cost in the column vector */ 47 | v[j] = current; 48 | /* make the cost of the next transition current */ 49 | current = next; 50 | } 51 | /* keep the final cost at the bottom of the column */ 52 | v[len2] = next; 53 | } 54 | free(v); 55 | return next; 56 | } 57 | 58 | # ifdef TEST 59 | # include <stdio.h> 60 | 61 | int main (int argc, char **argv) { 62 | unsigned int distance; 63 | if (argc < 3) return -1; 64 | distance = levenshtein(argv[1], argv[2]); 65 | printf("%s vs %s: %u\n", argv[1], argv[2],distance); 66 | } 67 | # endif 68 | -------------------------------------------------------------------------------- /mapfile.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Brook Hong 3 | * 4 | * The MIT License 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining 7 | * a copy of this software and associated documentation files 8 | * (the "Software"), to deal in the Software without restriction, 9 | * including without limitation the rights to use, copy, modify, 10 | * merge, publish, distribute, sublicense, and/or sell copies of the 11 | * Software, and to permit persons to whom the Software is furnished 12 | * to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be included 15 | * in all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 20 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 21 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 22 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | * 25 | */ 26 | #ifndef _MAPFILE_HPP_ 27 | #define _MAPFILE_HPP_ 28 | 29 | #ifdef HAVE_MMAP 30 | #include <sys/types.h> 31 | #include <fcntl.h> 32 | #include <sys/mman.h> 33 | #include <unistd.h> 34 | #endif 35 | #ifdef _WIN32 36 | #include <windows.h> 37 | #include <time.h> 38 | #endif 39 | 40 | class MapFile { 41 | public: 42 | MapFile(void) { 43 | data = 0; 44 | #ifdef HAVE_MMAP 45 | mmap_fd = -1; 46 | #elif defined(_WIN32) 47 | hFile = 0; 48 | hFileMap = 0; 49 | #endif 50 | } 51 | ~MapFile(); 52 | bool open(const char *file_name, unsigned long file_size); 53 | void close(); 54 | inline char *begin(void) { return data; } 55 | private: 56 | char *data; 57 | unsigned long size; 58 | #ifdef HAVE_MMAP 59 | int mmap_fd; 60 | #elif defined(_WIN32) 61 | HANDLE hFile; 62 | HANDLE hFileMap; 63 | #endif 64 | }; 65 | 66 | inline bool MapFile::open(const char *file_name, unsigned long file_size) 67 | { 68 | size=file_size; 69 | #ifdef HAVE_MMAP 70 | if ((mmap_fd = ::open(file_name, O_RDONLY)) < 0) { 71 | return false; 72 | } 73 | data = (char *)mmap( 0, file_size, PROT_READ, MAP_SHARED, mmap_fd, 0); 74 | if ((void *)data == (void *)(-1)) { 75 | data=0; 76 | return false; 77 | } 78 | #elif defined( _WIN32) 79 | hFile = CreateFile(file_name, GENERIC_READ, 0, 0, OPEN_ALWAYS, 80 | FILE_ATTRIBUTE_NORMAL, 0); 81 | hFileMap = CreateFileMapping(hFile, 0, PAGE_READONLY, 0, 82 | file_size, 0); 83 | data = (char *)MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, file_size); 84 | #else 85 | return false; 86 | #endif 87 | 88 | return true; 89 | } 90 | 91 | inline void MapFile::close() 92 | { 93 | if (!data) 94 | return; 95 | #ifdef HAVE_MMAP 96 | munmap(data, size); 97 | ::close(mmap_fd); 98 | #else 99 | # ifdef _WIN32 100 | UnmapViewOfFile(data); 101 | CloseHandle(hFileMap); 102 | CloseHandle(hFile); 103 | # endif 104 | #endif 105 | data = 0; 106 | } 107 | inline MapFile::~MapFile() 108 | { 109 | close(); 110 | } 111 | 112 | #endif//!_MAPFILE_HPP_ 113 | -------------------------------------------------------------------------------- /md5.cpp: -------------------------------------------------------------------------------- 1 | /* MD5 2 | converted to C++ class by Frank Thilo (thilo@unix-ag.org) 3 | for bzflag (http://www.bzflag.org) 4 | 5 | based on: 6 | 7 | md5.h and md5.c 8 | reference implemantion of RFC 1321 9 | 10 | Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All 11 | rights reserved. 12 | 13 | License to copy and use this software is granted provided that it 14 | is identified as the "RSA Data Security, Inc. MD5 Message-Digest 15 | Algorithm" in all material mentioning or referencing this software 16 | or this function. 17 | 18 | License is also granted to make and use derivative works provided 19 | that such works are identified as "derived from the RSA Data 20 | Security, Inc. MD5 Message-Digest Algorithm" in all material 21 | mentioning or referencing the derived work. 22 | 23 | RSA Data Security, Inc. makes no representations concerning either 24 | the merchantability of this software or the suitability of this 25 | software for any particular purpose. It is provided "as is" 26 | without express or implied warranty of any kind. 27 | 28 | These notices must be retained in any copies of any part of this 29 | documentation and/or software. 30 | 31 | */ 32 | 33 | /* interface header */ 34 | #include "md5.h" 35 | 36 | /* system implementation headers */ 37 | #include <stdio.h> 38 | 39 | #include <cstring> 40 | 41 | // Constants for MD5Transform routine. 42 | #define S11 7 43 | #define S12 12 44 | #define S13 17 45 | #define S14 22 46 | #define S21 5 47 | #define S22 9 48 | #define S23 14 49 | #define S24 20 50 | #define S31 4 51 | #define S32 11 52 | #define S33 16 53 | #define S34 23 54 | #define S41 6 55 | #define S42 10 56 | #define S43 15 57 | #define S44 21 58 | 59 | /////////////////////////////////////////////// 60 | 61 | // F, G, H and I are basic MD5 functions. 62 | inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) { 63 | return ( x&y ) | ( ~x&z ); 64 | } 65 | 66 | inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) { 67 | return ( x&z ) | ( y&~z ); 68 | } 69 | 70 | inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) { 71 | return x^y^z; 72 | } 73 | 74 | inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) { 75 | return y ^ (x | ~z); 76 | } 77 | 78 | // rotate_left rotates x left n bits. 79 | inline MD5::uint4 MD5::rotate_left(uint4 x, int n) { 80 | return (x << n) | (x >> (32-n)); 81 | } 82 | 83 | // FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. 84 | // Rotation is separate from addition to prevent recomputation. 85 | inline void MD5::FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { 86 | a = rotate_left(a+ F(b,c,d) + x + ac, s) + b; 87 | } 88 | 89 | inline void MD5::GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { 90 | a = rotate_left(a + G(b,c,d) + x + ac, s) + b; 91 | } 92 | 93 | inline void MD5::HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { 94 | a = rotate_left(a + H(b,c,d) + x + ac, s) + b; 95 | } 96 | 97 | inline void MD5::II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { 98 | a = rotate_left(a + I(b,c,d) + x + ac, s) + b; 99 | } 100 | 101 | ////////////////////////////////////////////// 102 | 103 | // default ctor, just initailize 104 | MD5::MD5() 105 | { 106 | init(); 107 | } 108 | 109 | ////////////////////////////////////////////// 110 | 111 | // nifty shortcut ctor, compute MD5 for string and finalize it right away 112 | MD5::MD5(const std::string &text) 113 | { 114 | init(); 115 | update(text.c_str(), text.length()); 116 | finalize(); 117 | } 118 | 119 | ////////////////////////////// 120 | 121 | void MD5::init() 122 | { 123 | finalized=false; 124 | 125 | count[0] = 0; 126 | count[1] = 0; 127 | 128 | // load magic initialization constants. 129 | state[0] = 0x67452301; 130 | state[1] = 0xefcdab89; 131 | state[2] = 0x98badcfe; 132 | state[3] = 0x10325476; 133 | } 134 | 135 | ////////////////////////////// 136 | 137 | // decodes input (unsigned char) into output (uint4). Assumes len is a multiple of 4. 138 | void MD5::decode(uint4 output[], const uint1 input[], size_type len) 139 | { 140 | for (unsigned int i = 0, j = 0; j < len; i++, j += 4) 141 | output[i] = ((uint4)input[j]) | (((uint4)input[j+1]) << 8) | 142 | (((uint4)input[j+2]) << 16) | (((uint4)input[j+3]) << 24); 143 | } 144 | 145 | ////////////////////////////// 146 | 147 | // encodes input (uint4) into output (unsigned char). Assumes len is 148 | // a multiple of 4. 149 | void MD5::encode(uint1 output[], const uint4 input[], size_type len) 150 | { 151 | for (size_type i = 0, j = 0; j < len; i++, j += 4) { 152 | output[j] = input[i] & 0xff; 153 | output[j+1] = (input[i] >> 8) & 0xff; 154 | output[j+2] = (input[i] >> 16) & 0xff; 155 | output[j+3] = (input[i] >> 24) & 0xff; 156 | } 157 | } 158 | 159 | ////////////////////////////// 160 | 161 | // apply MD5 algo on a block 162 | void MD5::transform(const uint1 block[blocksize]) 163 | { 164 | uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; 165 | decode (x, block, blocksize); 166 | 167 | /* Round 1 */ 168 | FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ 169 | FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ 170 | FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ 171 | FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ 172 | FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ 173 | FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ 174 | FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ 175 | FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ 176 | FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ 177 | FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ 178 | FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ 179 | FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ 180 | FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ 181 | FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ 182 | FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ 183 | FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ 184 | 185 | /* Round 2 */ 186 | GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ 187 | GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ 188 | GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ 189 | GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ 190 | GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ 191 | GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ 192 | GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ 193 | GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ 194 | GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ 195 | GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ 196 | GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ 197 | GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ 198 | GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ 199 | GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ 200 | GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ 201 | GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ 202 | 203 | /* Round 3 */ 204 | HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ 205 | HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ 206 | HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ 207 | HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ 208 | HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ 209 | HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ 210 | HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ 211 | HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ 212 | HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ 213 | HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ 214 | HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ 215 | HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ 216 | HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ 217 | HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ 218 | HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ 219 | HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ 220 | 221 | /* Round 4 */ 222 | II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ 223 | II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ 224 | II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ 225 | II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ 226 | II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ 227 | II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ 228 | II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ 229 | II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ 230 | II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ 231 | II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ 232 | II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ 233 | II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ 234 | II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ 235 | II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ 236 | II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ 237 | II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ 238 | 239 | state[0] += a; 240 | state[1] += b; 241 | state[2] += c; 242 | state[3] += d; 243 | 244 | // Zeroize sensitive information. 245 | memset(x, 0, sizeof x); 246 | } 247 | 248 | ////////////////////////////// 249 | 250 | // MD5 block update operation. Continues an MD5 message-digest 251 | // operation, processing another message block 252 | void MD5::update(const unsigned char input[], size_type length) 253 | { 254 | // compute number of bytes mod 64 255 | size_type index = count[0] / 8 % blocksize; 256 | 257 | // Update number of bits 258 | if ((count[0] += (length << 3)) < (length << 3)) 259 | count[1]++; 260 | count[1] += (length >> 29); 261 | 262 | // number of bytes we need to fill in buffer 263 | size_type firstpart = 64 - index; 264 | 265 | size_type i; 266 | 267 | // transform as many times as possible. 268 | if (length >= firstpart) 269 | { 270 | // fill buffer first, transform 271 | memcpy(&buffer[index], input, firstpart); 272 | transform(buffer); 273 | 274 | // transform chunks of blocksize (64 bytes) 275 | for (i = firstpart; i + blocksize <= length; i += blocksize) 276 | transform(&input[i]); 277 | 278 | index = 0; 279 | } 280 | else 281 | i = 0; 282 | 283 | // buffer remaining input 284 | memcpy(&buffer[index], &input[i], length-i); 285 | } 286 | 287 | ////////////////////////////// 288 | 289 | // for convenience provide a verson with signed char 290 | void MD5::update(const char input[], size_type length) 291 | { 292 | update((const unsigned char*)input, length); 293 | } 294 | 295 | ////////////////////////////// 296 | 297 | // MD5 finalization. Ends an MD5 message-digest operation, writing the 298 | // the message digest and zeroizing the context. 299 | MD5& MD5::finalize() 300 | { 301 | static unsigned char padding[64] = { 302 | 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 303 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 304 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 305 | }; 306 | 307 | if (!finalized) { 308 | // Save number of bits 309 | unsigned char bits[8]; 310 | encode(bits, count, 8); 311 | 312 | // pad out to 56 mod 64. 313 | size_type index = count[0] / 8 % 64; 314 | size_type padLen = (index < 56) ? (56 - index) : (120 - index); 315 | update(padding, padLen); 316 | 317 | // Append length (before padding) 318 | update(bits, 8); 319 | 320 | // Store state in digest 321 | encode(digest, state, 16); 322 | 323 | // Zeroize sensitive information. 324 | memset(buffer, 0, sizeof buffer); 325 | memset(count, 0, sizeof count); 326 | 327 | finalized=true; 328 | } 329 | 330 | return *this; 331 | } 332 | 333 | ////////////////////////////// 334 | 335 | // return hex representation of digest as string 336 | std::string MD5::hexdigest() const 337 | { 338 | if (!finalized) 339 | return ""; 340 | 341 | char buf[33]; 342 | for (int i=0; i<16; i++) 343 | sprintf(buf+i*2, "%02x", digest[i]); 344 | buf[32]=0; 345 | 346 | return std::string(buf); 347 | } 348 | 349 | ////////////////////////////// 350 | 351 | std::ostream& operator<<(std::ostream& out, MD5 md5) 352 | { 353 | return out << md5.hexdigest(); 354 | } 355 | 356 | ////////////////////////////// 357 | 358 | std::string md5(const std::string str) 359 | { 360 | MD5 md5 = MD5(str); 361 | 362 | return md5.hexdigest(); 363 | } 364 | -------------------------------------------------------------------------------- /md5.h: -------------------------------------------------------------------------------- 1 | /* MD5 2 | converted to C++ class by Frank Thilo (thilo@unix-ag.org) 3 | for bzflag (http://www.bzflag.org) 4 | 5 | based on: 6 | 7 | md5.h and md5.c 8 | reference implementation of RFC 1321 9 | 10 | Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All 11 | rights reserved. 12 | 13 | License to copy and use this software is granted provided that it 14 | is identified as the "RSA Data Security, Inc. MD5 Message-Digest 15 | Algorithm" in all material mentioning or referencing this software 16 | or this function. 17 | 18 | License is also granted to make and use derivative works provided 19 | that such works are identified as "derived from the RSA Data 20 | Security, Inc. MD5 Message-Digest Algorithm" in all material 21 | mentioning or referencing the derived work. 22 | 23 | RSA Data Security, Inc. makes no representations concerning either 24 | the merchantability of this software or the suitability of this 25 | software for any particular purpose. It is provided "as is" 26 | without express or implied warranty of any kind. 27 | 28 | These notices must be retained in any copies of any part of this 29 | documentation and/or software. 30 | 31 | */ 32 | 33 | #ifndef BZF_MD5_H 34 | #define BZF_MD5_H 35 | 36 | #include <string> 37 | #include <iostream> 38 | 39 | 40 | // a small class for calculating MD5 hashes of strings or byte arrays 41 | // it is not meant to be fast or secure 42 | // 43 | // usage: 1) feed it blocks of uchars with update() 44 | // 2) finalize() 45 | // 3) get hexdigest() string 46 | // or 47 | // MD5(std::string).hexdigest() 48 | // 49 | // assumes that char is 8 bit and int is 32 bit 50 | class MD5 51 | { 52 | public: 53 | typedef unsigned int size_type; // must be 32bit 54 | 55 | MD5(); 56 | MD5(const std::string& text); 57 | void update(const unsigned char *buf, size_type length); 58 | void update(const char *buf, size_type length); 59 | MD5& finalize(); 60 | std::string hexdigest() const; 61 | friend std::ostream& operator<<(std::ostream&, MD5 md5); 62 | 63 | private: 64 | void init(); 65 | typedef unsigned char uint1; // 8bit 66 | typedef unsigned int uint4; // 32bit 67 | enum {blocksize = 64}; // VC6 won't eat a const static int here 68 | 69 | void transform(const uint1 block[blocksize]); 70 | static void decode(uint4 output[], const uint1 input[], size_type len); 71 | static void encode(uint1 output[], const uint4 input[], size_type len); 72 | 73 | bool finalized; 74 | uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk 75 | uint4 count[2]; // 64bit counter for number of bits (lo, hi) 76 | uint4 state[4]; // digest so far 77 | uint1 digest[16]; // the result 78 | 79 | // low level logic operations 80 | static inline uint4 F(uint4 x, uint4 y, uint4 z); 81 | static inline uint4 G(uint4 x, uint4 y, uint4 z); 82 | static inline uint4 H(uint4 x, uint4 y, uint4 z); 83 | static inline uint4 I(uint4 x, uint4 y, uint4 z); 84 | static inline uint4 rotate_left(uint4 x, int n); 85 | static inline void FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); 86 | static inline void GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); 87 | static inline void HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); 88 | static inline void II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); 89 | }; 90 | 91 | std::string md5(const std::string str); 92 | 93 | #endif 94 | -------------------------------------------------------------------------------- /mongoose.c: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com> 2 | // Copyright (c) 2013-2014 Cesanta Software Limited 3 | // All rights reserved 4 | // 5 | // This library is dual-licensed: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License version 2 as 7 | // published by the Free Software Foundation. For the terms of this 8 | // license, see <http://www.gnu.org/licenses/>. 9 | // 10 | // You are free to use this library under the terms of the GNU General 11 | // Public License, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13 | // See the GNU General Public License for more details. 14 | // 15 | // Alternatively, you can license this library under a commercial 16 | // license, as set out in <http://cesanta.com/>. 17 | 18 | #undef UNICODE // Use ANSI WinAPI functions 19 | #undef _UNICODE // Use multibyte encoding on Windows 20 | #define _MBCS // Use multibyte encoding on Windows 21 | #define _INTEGRAL_MAX_BITS 64 // Enable _stati64() on Windows 22 | #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005+ 23 | #undef WIN32_LEAN_AND_MEAN // Let windows.h always include winsock2.h 24 | #define _XOPEN_SOURCE 600 // For flockfile() on Linux 25 | #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++ 26 | #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX 27 | #define _LARGEFILE_SOURCE // Enable fseeko() and ftello() functions 28 | #define _FILE_OFFSET_BITS 64 // Enable 64-bit file offsets 29 | 30 | #ifdef _MSC_VER 31 | #pragma warning (disable : 4127) // FD_SET() emits warning, disable it 32 | #pragma warning (disable : 4204) // missing c99 support 33 | #endif 34 | 35 | #include <sys/types.h> 36 | #include <sys/stat.h> 37 | #include <stddef.h> 38 | #include <stdio.h> 39 | #include <stdlib.h> 40 | #include <string.h> 41 | #include <fcntl.h> 42 | #include <assert.h> 43 | #include <errno.h> 44 | #include <time.h> 45 | #include <ctype.h> 46 | #include <stdarg.h> 47 | 48 | #ifdef _WIN32 49 | #include <windows.h> 50 | #include <process.h> // For _beginthread 51 | #include <io.h> // For _lseeki64 52 | #include <direct.h> // For _mkdir 53 | typedef int socklen_t; 54 | typedef HANDLE pid_t; 55 | typedef SOCKET sock_t; 56 | typedef unsigned char uint8_t; 57 | typedef unsigned int uint32_t; 58 | typedef unsigned short uint16_t; 59 | typedef unsigned __int64 uint64_t; 60 | typedef __int64 int64_t; 61 | typedef CRITICAL_SECTION mutex_t; 62 | typedef struct _stati64 file_stat_t; 63 | #pragma comment(lib, "ws2_32.lib") 64 | #define snprintf _snprintf 65 | #define vsnprintf _vsnprintf 66 | #define INT64_FMT "I64d" 67 | #ifndef EINPROGRESS 68 | #define EINPROGRESS WSAEINPROGRESS 69 | #endif 70 | #define mutex_init(x) InitializeCriticalSection(x) 71 | #define mutex_destroy(x) DeleteCriticalSection(x) 72 | #define mutex_lock(x) EnterCriticalSection(x) 73 | #define mutex_unlock(x) LeaveCriticalSection(x) 74 | #define get_thread_id() ((unsigned long) GetCurrentThreadId()) 75 | #define S_ISDIR(x) ((x) & _S_IFDIR) 76 | #define sleep(x) Sleep((x) * 1000) 77 | #define stat(x, y) mg_stat((x), (y)) 78 | #define fopen(x, y) mg_fopen((x), (y)) 79 | #define open(x, y) mg_open((x), (y)) 80 | #define lseek(x, y, z) _lseeki64((x), (y), (z)) 81 | #define mkdir(x, y) _mkdir(x) 82 | #define to64(x) _atoi64(x) 83 | #define flockfile(x) 84 | #define funlockfile(x) 85 | #ifndef va_copy 86 | #define va_copy(x,y) x = y 87 | #endif // MINGW #defines va_copy 88 | #ifndef __func__ 89 | #define STRX(x) #x 90 | #define STR(x) STRX(x) 91 | #define __func__ __FILE__ ":" STR(__LINE__) 92 | #endif 93 | #else 94 | #include <dirent.h> 95 | #include <inttypes.h> 96 | #include <pthread.h> 97 | #include <pwd.h> 98 | #include <signal.h> 99 | #include <unistd.h> 100 | #include <netdb.h> 101 | #include <arpa/inet.h> // For inet_pton() when MONGOOSE_USE_IPV6 is defined 102 | #include <netinet/in.h> 103 | #include <sys/socket.h> 104 | #include <sys/select.h> 105 | #define closesocket(x) close(x) 106 | typedef int sock_t; 107 | typedef pthread_mutex_t mutex_t; 108 | typedef struct stat file_stat_t; 109 | #define mutex_init(x) pthread_mutex_init(x, NULL) 110 | #define mutex_destroy(x) pthread_mutex_destroy(x) 111 | #define mutex_lock(x) pthread_mutex_lock(x) 112 | #define mutex_unlock(x) pthread_mutex_unlock(x) 113 | #define get_thread_id() ((unsigned long) pthread_self()) 114 | #define INVALID_SOCKET ((sock_t) -1) 115 | #define INT64_FMT PRId64 116 | #define to64(x) strtoll(x, NULL, 10) 117 | #define __cdecl 118 | #define O_BINARY 0 119 | #endif 120 | 121 | #ifdef MONGOOSE_USE_SSL 122 | #ifdef __APPLE__ 123 | #pragma GCC diagnostic ignored "-Wdeprecated-declarations" 124 | #endif 125 | #include <openssl/ssl.h> 126 | #endif 127 | 128 | #include "mongoose.h" 129 | 130 | struct ll { struct ll *prev, *next; }; 131 | #define LINKED_LIST_INIT(N) ((N)->next = (N)->prev = (N)) 132 | #define LINKED_LIST_DECLARE_AND_INIT(H) struct ll H = { &H, &H } 133 | #define LINKED_LIST_ENTRY(P,T,N) ((T *)((char *)(P) - offsetof(T, N))) 134 | #define LINKED_LIST_IS_EMPTY(N) ((N)->next == (N)) 135 | #define LINKED_LIST_FOREACH(H,N,T) \ 136 | for (N = (H)->next, T = (N)->next; N != (H); N = (T), T = (N)->next) 137 | #define LINKED_LIST_ADD_TO_FRONT(H,N) do { ((H)->next)->prev = (N); \ 138 | (N)->next = ((H)->next); (N)->prev = (H); (H)->next = (N); } while (0) 139 | #define LINKED_LIST_ADD_TO_TAIL(H,N) do { ((H)->prev)->next = (N); \ 140 | (N)->prev = ((H)->prev); (N)->next = (H); (H)->prev = (N); } while (0) 141 | #define LINKED_LIST_REMOVE(N) do { ((N)->next)->prev = ((N)->prev); \ 142 | ((N)->prev)->next = ((N)->next); LINKED_LIST_INIT(N); } while (0) 143 | 144 | #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) 145 | #define MAX_REQUEST_SIZE 16384 146 | #define IOBUF_SIZE 8192 147 | #define MAX_PATH_SIZE 8192 148 | #define LUA_SCRIPT_PATTERN "**.lp$" 149 | #define CGI_ENVIRONMENT_SIZE 4096 150 | #define MAX_CGI_ENVIR_VARS 64 151 | #define ENV_EXPORT_TO_CGI "MONGOOSE_CGI" 152 | #define PASSWORDS_FILE_NAME ".htpasswd" 153 | 154 | #ifndef MONGOOSE_USE_WEBSOCKET_PING_INTERVAL 155 | #define MONGOOSE_USE_WEBSOCKET_PING_INTERVAL 5 156 | #endif 157 | 158 | // Extra HTTP headers to send in every static file reply 159 | #if !defined(MONGOOSE_USE_EXTRA_HTTP_HEADERS) 160 | #define MONGOOSE_USE_EXTRA_HTTP_HEADERS "" 161 | #endif 162 | 163 | #ifndef MONGOOSE_USE_POST_SIZE_LIMIT 164 | #define MONGOOSE_USE_POST_SIZE_LIMIT 0 165 | #endif 166 | 167 | #ifndef MONGOOSE_USE_IDLE_TIMEOUT_SECONDS 168 | #define MONGOOSE_USE_IDLE_TIMEOUT_SECONDS 30 169 | #endif 170 | 171 | #ifdef MONGOOSE_ENABLE_DEBUG 172 | #define DBG(x) do { printf("%-20s ", __func__); printf x; putchar('\n'); \ 173 | fflush(stdout); } while(0) 174 | #else 175 | #define DBG(x) 176 | #endif 177 | 178 | #ifdef MONGOOSE_NO_FILESYSTEM 179 | #define MONGOOSE_NO_AUTH 180 | #define MONGOOSE_NO_CGI 181 | #define MONGOOSE_NO_DAV 182 | #define MONGOOSE_NO_DIRECTORY_LISTING 183 | #define MONGOOSE_NO_LOGGING 184 | #endif 185 | 186 | union socket_address { 187 | struct sockaddr sa; 188 | struct sockaddr_in sin; 189 | #ifdef MONGOOSE_USE_IPV6 190 | struct sockaddr_in6 sin6; 191 | #endif 192 | }; 193 | 194 | struct vec { 195 | const char *ptr; 196 | int len; 197 | }; 198 | 199 | struct uri_handler { 200 | struct ll link; 201 | char *uri; 202 | mg_handler_t handler; 203 | }; 204 | 205 | // For directory listing and WevDAV support 206 | struct dir_entry { 207 | struct connection *conn; 208 | char *file_name; 209 | file_stat_t st; 210 | }; 211 | 212 | // NOTE(lsm): this enum shoulds be in sync with the config_options. 213 | enum { 214 | ACCESS_CONTROL_LIST, 215 | #ifndef MONGOOSE_NO_FILESYSTEM 216 | ACCESS_LOG_FILE, AUTH_DOMAIN, CGI_INTERPRETER, 217 | CGI_PATTERN, DAV_AUTH_FILE, DOCUMENT_ROOT, ENABLE_DIRECTORY_LISTING, 218 | #endif 219 | EXTRA_MIME_TYPES, 220 | #ifndef MONGOOSE_NO_FILESYSTEM 221 | GLOBAL_AUTH_FILE, 222 | #endif 223 | HIDE_FILES_PATTERN, 224 | #ifndef MONGOOSE_NO_FILESYSTEM 225 | INDEX_FILES, 226 | #endif 227 | LISTENING_PORT, 228 | #ifndef _WIN32 229 | RUN_AS_USER, 230 | #endif 231 | #ifdef MONGOOSE_USE_SSL 232 | SSL_CERTIFICATE, 233 | #endif 234 | URL_REWRITES, NUM_OPTIONS 235 | }; 236 | 237 | static const char *static_config_options[] = { 238 | "access_control_list", NULL, 239 | #ifndef MONGOOSE_NO_FILESYSTEM 240 | "access_log_file", NULL, 241 | "auth_domain", "mydomain.com", 242 | "cgi_interpreter", NULL, 243 | "cgi_pattern", "**.cgi$|**.pl$|**.php$", 244 | "dav_auth_file", NULL, 245 | "document_root", NULL, 246 | "enable_directory_listing", "yes", 247 | #endif 248 | "extra_mime_types", NULL, 249 | #ifndef MONGOOSE_NO_FILESYSTEM 250 | "global_auth_file", NULL, 251 | #endif 252 | "hide_files_patterns", NULL, 253 | #ifndef MONGOOSE_NO_FILESYSTEM 254 | "index_files","index.html,index.htm,index.cgi,index.php,index.lp", 255 | #endif 256 | "listening_port", NULL, 257 | #ifndef _WIN32 258 | "run_as_user", NULL, 259 | #endif 260 | #ifdef MONGOOSE_USE_SSL 261 | "ssl_certificate", NULL, 262 | #endif 263 | "url_rewrites", NULL, 264 | NULL 265 | }; 266 | 267 | struct mg_server { 268 | sock_t listening_sock; 269 | union socket_address lsa; // Listening socket address 270 | struct ll active_connections; 271 | struct ll uri_handlers; 272 | mg_handler_t error_handler; 273 | char *config_options[NUM_OPTIONS]; 274 | void *server_data; 275 | #ifdef MONGOOSE_USE_SSL 276 | SSL_CTX *ssl_ctx; // Server SSL context 277 | SSL_CTX *client_ssl_ctx; // Client SSL context 278 | #endif 279 | sock_t ctl[2]; // Control socketpair. Used to wake up from select() call 280 | }; 281 | 282 | // Expandable IO buffer 283 | struct iobuf { 284 | char *buf; // Buffer that holds the data 285 | int size; // Buffer size 286 | int len; // Number of bytes currently in a buffer 287 | }; 288 | 289 | // Local endpoint representation 290 | union endpoint { 291 | int fd; // Opened regular local file 292 | sock_t cgi_sock; // CGI socket 293 | void *ssl; // SSL descriptor 294 | struct uri_handler *uh; // URI handler user function 295 | }; 296 | 297 | enum endpoint_type { EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT }; 298 | enum connection_flags { 299 | CONN_CLOSE = 1, // Connection must be closed at the end of the poll 300 | CONN_SPOOL_DONE = 2, // All data has been buffered for sending 301 | CONN_SSL_HANDS_SHAKEN = 4, // SSL handshake has completed. Only for SSL 302 | CONN_HEADERS_SENT = 8, // User callback has sent HTTP headers 303 | CONN_BUFFER = 16, // CGI only. Holds data send until CGI prints 304 | // all HTTP headers 305 | CONN_CONNECTING = 32, // HTTP client is doing non-blocking connect() 306 | CONN_LONG_RUNNING = 64 // Long-running URI handlers 307 | }; 308 | 309 | struct connection { 310 | struct mg_connection mg_conn; // XXX: Must be first 311 | struct ll link; // Linkage to server->active_connections 312 | struct mg_server *server; 313 | sock_t client_sock; // Connected client 314 | struct iobuf local_iobuf; 315 | struct iobuf remote_iobuf; 316 | union endpoint endpoint; 317 | enum endpoint_type endpoint_type; 318 | time_t birth_time; 319 | time_t last_activity_time; 320 | char *path_info; 321 | char *request; 322 | int64_t num_bytes_sent; // Total number of bytes sent 323 | int64_t cl; // Reply content length, for Range support 324 | int request_len; // Request length, including last \r\n after last header 325 | int flags; // CONN_* flags: CONN_CLOSE, CONN_SPOOL_DONE, etc 326 | mg_handler_t handler; // Callback for HTTP client 327 | #ifdef MONGOOSE_USE_SSL 328 | SSL *ssl; // SSL descriptor 329 | #endif 330 | }; 331 | 332 | static void close_local_endpoint(struct connection *conn); 333 | 334 | static const struct { 335 | const char *extension; 336 | size_t ext_len; 337 | const char *mime_type; 338 | } static_builtin_mime_types[] = { 339 | {".html", 5, "text/html"}, 340 | {".htm", 4, "text/html"}, 341 | {".shtm", 5, "text/html"}, 342 | {".shtml", 6, "text/html"}, 343 | {".css", 4, "text/css"}, 344 | {".js", 3, "application/x-javascript"}, 345 | {".ico", 4, "image/x-icon"}, 346 | {".gif", 4, "image/gif"}, 347 | {".jpg", 4, "image/jpeg"}, 348 | {".jpeg", 5, "image/jpeg"}, 349 | {".png", 4, "image/png"}, 350 | {".svg", 4, "image/svg+xml"}, 351 | {".txt", 4, "text/plain"}, 352 | {".torrent", 8, "application/x-bittorrent"}, 353 | {".wav", 4, "audio/x-wav"}, 354 | {".mp3", 4, "audio/x-mp3"}, 355 | {".mid", 4, "audio/mid"}, 356 | {".m3u", 4, "audio/x-mpegurl"}, 357 | {".ogg", 4, "application/ogg"}, 358 | {".ram", 4, "audio/x-pn-realaudio"}, 359 | {".xml", 4, "text/xml"}, 360 | {".json", 5, "text/json"}, 361 | {".xslt", 5, "application/xml"}, 362 | {".xsl", 4, "application/xml"}, 363 | {".ra", 3, "audio/x-pn-realaudio"}, 364 | {".doc", 4, "application/msword"}, 365 | {".exe", 4, "application/octet-stream"}, 366 | {".zip", 4, "application/x-zip-compressed"}, 367 | {".xls", 4, "application/excel"}, 368 | {".tgz", 4, "application/x-tar-gz"}, 369 | {".tar", 4, "application/x-tar"}, 370 | {".gz", 3, "application/x-gunzip"}, 371 | {".arj", 4, "application/x-arj-compressed"}, 372 | {".rar", 4, "application/x-arj-compressed"}, 373 | {".rtf", 4, "application/rtf"}, 374 | {".pdf", 4, "application/pdf"}, 375 | {".swf", 4, "application/x-shockwave-flash"}, 376 | {".mpg", 4, "video/mpeg"}, 377 | {".webm", 5, "video/webm"}, 378 | {".mpeg", 5, "video/mpeg"}, 379 | {".mov", 4, "video/quicktime"}, 380 | {".mp4", 4, "video/mp4"}, 381 | {".m4v", 4, "video/x-m4v"}, 382 | {".asf", 4, "video/x-ms-asf"}, 383 | {".avi", 4, "video/x-msvideo"}, 384 | {".bmp", 4, "image/bmp"}, 385 | {".ttf", 4, "application/x-font-ttf"}, 386 | {NULL, 0, NULL} 387 | }; 388 | 389 | #ifndef MONGOOSE_NO_THREADS 390 | void *mg_start_thread(void *(*f)(void *), void *p) { 391 | #ifdef _WIN32 392 | return (void *) _beginthread((void (__cdecl *)(void *)) f, 0, p); 393 | #else 394 | pthread_t thread_id = (pthread_t) 0; 395 | pthread_attr_t attr; 396 | 397 | (void) pthread_attr_init(&attr); 398 | (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 399 | 400 | #if MONGOOSE_USE_STACK_SIZE > 1 401 | (void) pthread_attr_setstacksize(&attr, MONGOOSE_USE_STACK_SIZE); 402 | #endif 403 | 404 | pthread_create(&thread_id, &attr, f, p); 405 | pthread_attr_destroy(&attr); 406 | 407 | return (void *) thread_id; 408 | #endif 409 | } 410 | #endif // MONGOOSE_NO_THREADS 411 | 412 | #ifdef _WIN32 413 | // Encode 'path' which is assumed UTF-8 string, into UNICODE string. 414 | // wbuf and wbuf_len is a target buffer and its length. 415 | static void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) { 416 | char buf[MAX_PATH_SIZE * 2], buf2[MAX_PATH_SIZE * 2], *p; 417 | 418 | strncpy(buf, path, sizeof(buf)); 419 | buf[sizeof(buf) - 1] = '\0'; 420 | 421 | // Trim trailing slashes 422 | p = buf + strlen(buf) - 1; 423 | while (p > buf && p[0] == '\\' || p[0] == '/') *p-- = '\0'; 424 | //change_slashes_to_backslashes(buf); 425 | 426 | // Convert to Unicode and back. If doubly-converted string does not 427 | // match the original, something is fishy, reject. 428 | memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); 429 | MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len); 430 | WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2), 431 | NULL, NULL); 432 | if (strcmp(buf, buf2) != 0) { 433 | wbuf[0] = L'\0'; 434 | } 435 | } 436 | 437 | static int mg_stat(const char *path, file_stat_t *st) { 438 | wchar_t wpath[MAX_PATH_SIZE]; 439 | to_wchar(path, wpath, ARRAY_SIZE(wpath)); 440 | DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st))); 441 | return _wstati64(wpath, st); 442 | } 443 | 444 | static FILE *mg_fopen(const char *path, const char *mode) { 445 | wchar_t wpath[MAX_PATH_SIZE], wmode[10]; 446 | to_wchar(path, wpath, ARRAY_SIZE(wpath)); 447 | to_wchar(mode, wmode, ARRAY_SIZE(wmode)); 448 | return _wfopen(wpath, wmode); 449 | } 450 | 451 | static int mg_open(const char *path, int flag) { 452 | wchar_t wpath[MAX_PATH_SIZE]; 453 | to_wchar(path, wpath, ARRAY_SIZE(wpath)); 454 | return _wopen(wpath, flag); 455 | } 456 | #endif 457 | 458 | static void set_close_on_exec(int fd) { 459 | #ifdef _WIN32 460 | (void) SetHandleInformation((HANDLE) fd, HANDLE_FLAG_INHERIT, 0); 461 | #else 462 | fcntl(fd, F_SETFD, FD_CLOEXEC); 463 | #endif 464 | } 465 | 466 | static void set_non_blocking_mode(sock_t sock) { 467 | #ifdef _WIN32 468 | unsigned long on = 1; 469 | ioctlsocket(sock, FIONBIO, &on); 470 | #else 471 | int flags = fcntl(sock, F_GETFL, 0); 472 | fcntl(sock, F_SETFL, flags | O_NONBLOCK); 473 | #endif 474 | } 475 | 476 | // A helper function for traversing a comma separated list of values. 477 | // It returns a list pointer shifted to the next value, or NULL if the end 478 | // of the list found. 479 | // Value is stored in val vector. If value has form "x=y", then eq_val 480 | // vector is initialized to point to the "y" part, and val vector length 481 | // is adjusted to point only to "x". 482 | static const char *next_option(const char *list, struct vec *val, 483 | struct vec *eq_val) { 484 | if (list == NULL || *list == '\0') { 485 | // End of the list 486 | list = NULL; 487 | } else { 488 | val->ptr = list; 489 | if ((list = strchr(val->ptr, ',')) != NULL) { 490 | // Comma found. Store length and shift the list ptr 491 | val->len = list - val->ptr; 492 | list++; 493 | } else { 494 | // This value is the last one 495 | list = val->ptr + strlen(val->ptr); 496 | val->len = list - val->ptr; 497 | } 498 | 499 | if (eq_val != NULL) { 500 | // Value has form "x=y", adjust pointers and lengths 501 | // so that val points to "x", and eq_val points to "y". 502 | eq_val->len = 0; 503 | eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len); 504 | if (eq_val->ptr != NULL) { 505 | eq_val->ptr++; // Skip over '=' character 506 | eq_val->len = val->ptr + val->len - eq_val->ptr; 507 | val->len = (eq_val->ptr - val->ptr) - 1; 508 | } 509 | } 510 | } 511 | 512 | return list; 513 | } 514 | 515 | static int spool(struct iobuf *io, const void *buf, int len) { 516 | static const double mult = 1.2; 517 | char *p = NULL; 518 | int new_len = 0; 519 | 520 | assert(io->len >= 0); 521 | assert(io->len <= io->size); 522 | 523 | //DBG(("1. %d %d %d", len, io->len, io->size)); 524 | if (len <= 0) { 525 | } else if ((new_len = io->len + len) < io->size) { 526 | memcpy(io->buf + io->len, buf, len); 527 | io->len = new_len; 528 | } else if ((p = (char *) realloc(io->buf, (int) (new_len * mult))) != NULL) { 529 | io->buf = p; 530 | memcpy(io->buf + io->len, buf, len); 531 | io->len = new_len; 532 | io->size = (int) (new_len * mult); 533 | } else { 534 | len = 0; 535 | } 536 | //DBG(("%d %d %d", len, io->len, io->size)); 537 | 538 | return len; 539 | } 540 | 541 | // Like snprintf(), but never returns negative value, or a value 542 | // that is larger than a supplied buffer. 543 | static int mg_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) { 544 | int n; 545 | if (buflen < 1) return 0; 546 | n = vsnprintf(buf, buflen, fmt, ap); 547 | if (n < 0) { 548 | n = 0; 549 | } else if (n >= (int) buflen) { 550 | n = (int) buflen - 1; 551 | } 552 | buf[n] = '\0'; 553 | return n; 554 | } 555 | 556 | static int mg_snprintf(char *buf, size_t buflen, const char *fmt, ...) { 557 | va_list ap; 558 | int n; 559 | va_start(ap, fmt); 560 | n = mg_vsnprintf(buf, buflen, fmt, ap); 561 | va_end(ap); 562 | return n; 563 | } 564 | 565 | // Check whether full request is buffered. Return: 566 | // -1 if request is malformed 567 | // 0 if request is not yet fully buffered 568 | // >0 actual request length, including last \r\n\r\n 569 | static int get_request_len(const char *s, int buf_len) { 570 | const unsigned char *buf = (unsigned char *) s; 571 | int i; 572 | 573 | for (i = 0; i < buf_len; i++) { 574 | // Control characters are not allowed but >=128 are. 575 | // Abort scan as soon as one malformed character is found. 576 | if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) { 577 | return -1; 578 | } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') { 579 | return i + 2; 580 | } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' && 581 | buf[i + 2] == '\n') { 582 | return i + 3; 583 | } 584 | } 585 | 586 | return 0; 587 | } 588 | 589 | // Skip the characters until one of the delimiters characters found. 590 | // 0-terminate resulting word. Skip the rest of the delimiters if any. 591 | // Advance pointer to buffer to the next word. Return found 0-terminated word. 592 | static char *skip(char **buf, const char *delimiters) { 593 | char *p, *begin_word, *end_word, *end_delimiters; 594 | 595 | begin_word = *buf; 596 | end_word = begin_word + strcspn(begin_word, delimiters); 597 | end_delimiters = end_word + strspn(end_word, delimiters); 598 | 599 | for (p = end_word; p < end_delimiters; p++) { 600 | *p = '\0'; 601 | } 602 | 603 | *buf = end_delimiters; 604 | 605 | return begin_word; 606 | } 607 | 608 | // Parse HTTP headers from the given buffer, advance buffer to the point 609 | // where parsing stopped. 610 | static void parse_http_headers(char **buf, struct mg_connection *ri) { 611 | size_t i; 612 | 613 | for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) { 614 | ri->http_headers[i].name = skip(buf, ": "); 615 | ri->http_headers[i].value = skip(buf, "\r\n"); 616 | if (ri->http_headers[i].name[0] == '\0') 617 | break; 618 | ri->num_headers = i + 1; 619 | } 620 | } 621 | 622 | static const char *status_code_to_str(int status_code) { 623 | switch (status_code) { 624 | case 200: return "OK"; 625 | case 201: return "Created"; 626 | case 204: return "No Content"; 627 | case 301: return "Moved Permanently"; 628 | case 302: return "Found"; 629 | case 304: return "Not Modified"; 630 | case 400: return "Bad Request"; 631 | case 403: return "Forbidden"; 632 | case 404: return "Not Found"; 633 | case 405: return "Method Not Allowed"; 634 | case 409: return "Conflict"; 635 | case 411: return "Length Required"; 636 | case 413: return "Request Entity Too Large"; 637 | case 415: return "Unsupported Media Type"; 638 | case 423: return "Locked"; 639 | case 500: return "Server Error"; 640 | case 501: return "Not Implemented"; 641 | default: return "Server Error"; 642 | } 643 | } 644 | 645 | static void send_http_error(struct connection *conn, int code, 646 | const char *fmt, ...) { 647 | const char *message = status_code_to_str(code); 648 | const char *rewrites = conn->server->config_options[URL_REWRITES]; 649 | char headers[200], body[200]; 650 | struct vec a, b; 651 | va_list ap; 652 | int body_len, headers_len, match_code; 653 | 654 | conn->mg_conn.status_code = code; 655 | 656 | // Invoke error handler if it is set 657 | if (conn->server->error_handler != NULL && 658 | conn->server->error_handler(&conn->mg_conn)) { 659 | close_local_endpoint(conn); 660 | return; 661 | } 662 | 663 | // Handle error code rewrites 664 | while ((rewrites = next_option(rewrites, &a, &b)) != NULL) { 665 | if ((match_code = atoi(a.ptr)) > 0 && match_code == code) { 666 | conn->mg_conn.status_code = 302; 667 | mg_printf(&conn->mg_conn, "HTTP/1.1 %d Moved\r\n" 668 | "Location: %.*s?code=%d&orig_uri=%s\r\n\r\n", 669 | conn->mg_conn.status_code, b.len, b.ptr, code, 670 | conn->mg_conn.uri); 671 | close_local_endpoint(conn); 672 | return; 673 | } 674 | } 675 | 676 | body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message); 677 | if (fmt != NULL) { 678 | body[body_len++] = '\n'; 679 | va_start(ap, fmt); 680 | body_len += mg_snprintf(body + body_len, sizeof(body) - body_len, fmt, ap); 681 | va_end(ap); 682 | } 683 | if (code >= 300 && code <= 399) { 684 | // 3xx errors do not have body 685 | body_len = 0; 686 | } 687 | headers_len = mg_snprintf(headers, sizeof(headers), 688 | "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n" 689 | "Content-Type: text/plain\r\n\r\n", 690 | code, message, body_len); 691 | spool(&conn->remote_iobuf, headers, headers_len); 692 | spool(&conn->remote_iobuf, body, body_len); 693 | close_local_endpoint(conn); // This will write to the log file 694 | } 695 | 696 | // Print message to buffer. If buffer is large enough to hold the message, 697 | // return buffer. If buffer is to small, allocate large enough buffer on heap, 698 | // and return allocated buffer. 699 | static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap) { 700 | va_list ap_copy; 701 | int len; 702 | 703 | // Windows is not standard-compliant, and vsnprintf() returns -1 if 704 | // buffer is too small. Also, older versions of msvcrt.dll do not have 705 | // _vscprintf(). However, if size is 0, vsnprintf() behaves correctly. 706 | // Therefore, we make two passes: on first pass, get required message length. 707 | // On second pass, actually print the message. 708 | va_copy(ap_copy, ap); 709 | len = vsnprintf(NULL, 0, fmt, ap_copy); 710 | 711 | if (len > (int) size && 712 | (size = len + 1) > 0 && 713 | (*buf = (char *) malloc(size)) == NULL) { 714 | len = -1; // Allocation failed, mark failure 715 | } else { 716 | va_copy(ap_copy, ap); 717 | vsnprintf(*buf, size, fmt, ap_copy); 718 | } 719 | 720 | return len; 721 | } 722 | 723 | static void write_chunk(struct connection *conn, const char *buf, int len) { 724 | char chunk_size[50]; 725 | int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len); 726 | spool(&conn->remote_iobuf, chunk_size, n); 727 | spool(&conn->remote_iobuf, buf, len); 728 | spool(&conn->remote_iobuf, "\r\n", 2); 729 | } 730 | 731 | int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap, 732 | int chunked) { 733 | char mem[IOBUF_SIZE], *buf = mem; 734 | int len; 735 | 736 | if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) { 737 | if (chunked) { 738 | write_chunk((struct connection *) conn, buf, len); 739 | } else { 740 | len = mg_write(conn, buf, (size_t) len); 741 | } 742 | } 743 | if (buf != mem && buf != NULL) { 744 | free(buf); 745 | } 746 | 747 | return len; 748 | } 749 | 750 | int mg_printf(struct mg_connection *conn, const char *fmt, ...) { 751 | int len; 752 | va_list ap; 753 | va_start(ap, fmt); 754 | len = mg_vprintf(conn, fmt, ap, 0); 755 | va_end(ap); 756 | return len; 757 | } 758 | 759 | static int mg_socketpair(sock_t sp[2]) { 760 | struct sockaddr_in sa; 761 | sock_t sock, ret = -1; 762 | socklen_t len = sizeof(sa); 763 | 764 | sp[0] = sp[1] = INVALID_SOCKET; 765 | 766 | (void) memset(&sa, 0, sizeof(sa)); 767 | sa.sin_family = AF_INET; 768 | sa.sin_port = htons(0); 769 | sa.sin_addr.s_addr = htonl(0x7f000001); 770 | 771 | if ((sock = socket(AF_INET, SOCK_STREAM, 0)) != INVALID_SOCKET && 772 | !bind(sock, (struct sockaddr *) &sa, len) && 773 | !listen(sock, 1) && 774 | !getsockname(sock, (struct sockaddr *) &sa, &len) && 775 | (sp[0] = socket(AF_INET, SOCK_STREAM, 6)) != -1 && 776 | !connect(sp[0], (struct sockaddr *) &sa, len) && 777 | (sp[1] = accept(sock,(struct sockaddr *) &sa, &len)) != INVALID_SOCKET) { 778 | set_close_on_exec(sp[0]); 779 | set_close_on_exec(sp[1]); 780 | ret = 0; 781 | } else { 782 | if (sp[0] != INVALID_SOCKET) closesocket(sp[0]); 783 | if (sp[1] != INVALID_SOCKET) closesocket(sp[1]); 784 | sp[0] = sp[1] = INVALID_SOCKET; 785 | } 786 | closesocket(sock); 787 | 788 | return ret; 789 | } 790 | 791 | static int is_error(int n) { 792 | return n == 0 || (n < 0 && errno != EINTR && errno != EAGAIN); 793 | } 794 | 795 | static void discard_leading_iobuf_bytes(struct iobuf *io, int n) { 796 | if (n >= 0 && n <= io->len) { 797 | memmove(io->buf, io->buf + n, io->len - n); 798 | io->len -= n; 799 | } 800 | } 801 | 802 | #ifndef MONGOOSE_NO_CGI 803 | #ifdef _WIN32 804 | struct threadparam { 805 | sock_t s; 806 | HANDLE hPipe; 807 | }; 808 | 809 | static int wait_until_ready(sock_t sock, int for_read) { 810 | fd_set set; 811 | FD_ZERO(&set); 812 | FD_SET(sock, &set); 813 | select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0); 814 | return 1; 815 | } 816 | 817 | static void *push_to_stdin(void *arg) { 818 | struct threadparam *tp = arg; 819 | int n, sent, stop = 0; 820 | DWORD k; 821 | char buf[IOBUF_SIZE]; 822 | 823 | while (!stop && wait_until_ready(tp->s, 1) && 824 | (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) { 825 | if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue; 826 | for (sent = 0; !stop && sent < n; sent += k) { 827 | if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1; 828 | } 829 | } 830 | DBG(("%s", "FORWARED EVERYTHING TO CGI")); 831 | CloseHandle(tp->hPipe); 832 | free(tp); 833 | _endthread(); 834 | return NULL; 835 | } 836 | 837 | static void *pull_from_stdout(void *arg) { 838 | struct threadparam *tp = arg; 839 | int k, stop = 0; 840 | DWORD n, sent; 841 | char buf[IOBUF_SIZE]; 842 | 843 | while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) { 844 | for (sent = 0; !stop && sent < n; sent += k) { 845 | if (wait_until_ready(tp->s, 0) && 846 | (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1; 847 | } 848 | } 849 | DBG(("%s", "EOF FROM CGI")); 850 | CloseHandle(tp->hPipe); 851 | shutdown(tp->s, 2); // Without this, IO thread may get truncated data 852 | closesocket(tp->s); 853 | free(tp); 854 | _endthread(); 855 | return NULL; 856 | } 857 | 858 | static void spawn_stdio_thread(sock_t sock, HANDLE hPipe, 859 | void *(*func)(void *)) { 860 | struct threadparam *tp = malloc(sizeof(*tp)); 861 | if (tp != NULL) { 862 | tp->s = sock; 863 | tp->hPipe = hPipe; 864 | mg_start_thread(func, tp); 865 | } 866 | } 867 | 868 | static void abs_path(const char *utf8_path, char *abs_path, size_t len) { 869 | wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE]; 870 | to_wchar(utf8_path, buf, ARRAY_SIZE(buf)); 871 | GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL); 872 | WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0); 873 | } 874 | 875 | static pid_t start_process(char *interp, const char *cmd, const char *env, 876 | const char *envp[], const char *dir, sock_t sock) { 877 | STARTUPINFOW si = {0}; 878 | PROCESS_INFORMATION pi = {0}; 879 | HANDLE a[2], b[2], me = GetCurrentProcess(); 880 | wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE]; 881 | char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE], 882 | cmdline[MAX_PATH_SIZE], *p; 883 | DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS; 884 | FILE *fp; 885 | 886 | si.cb = sizeof(si); 887 | si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; 888 | si.wShowWindow = SW_HIDE; 889 | si.hStdError = GetStdHandle(STD_ERROR_HANDLE); 890 | 891 | CreatePipe(&a[0], &a[1], NULL, 0); 892 | CreatePipe(&b[0], &b[1], NULL, 0); 893 | DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags); 894 | DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags); 895 | 896 | if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) { 897 | buf[0] = buf[1] = '\0'; 898 | fgets(buf, sizeof(buf), fp); 899 | buf[sizeof(buf) - 1] = '\0'; 900 | if (buf[0] == '#' && buf[1] == '!') { 901 | interp = buf + 2; 902 | for (p = interp + strlen(interp); 903 | isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0'; 904 | } 905 | fclose(fp); 906 | } 907 | 908 | if (interp != NULL) { 909 | abs_path(interp, buf4, ARRAY_SIZE(buf4)); 910 | interp = buf4; 911 | } 912 | abs_path(dir, buf5, ARRAY_SIZE(buf5)); 913 | to_wchar(dir, full_dir, ARRAY_SIZE(full_dir)); 914 | mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"", 915 | interp ? interp : "", interp ? " " : "", cmd); 916 | to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd)); 917 | 918 | if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, 919 | (void *) env, full_dir, &si, &pi) != 0) { 920 | spawn_stdio_thread(sock, a[1], push_to_stdin); 921 | spawn_stdio_thread(sock, b[0], pull_from_stdout); 922 | } else { 923 | CloseHandle(a[1]); 924 | CloseHandle(b[0]); 925 | closesocket(sock); 926 | } 927 | DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess)); 928 | 929 | CloseHandle(si.hStdOutput); 930 | CloseHandle(si.hStdInput); 931 | CloseHandle(a[0]); 932 | CloseHandle(b[1]); 933 | CloseHandle(pi.hThread); 934 | CloseHandle(pi.hProcess); 935 | 936 | return pi.hProcess; 937 | } 938 | #else 939 | static pid_t start_process(const char *interp, const char *cmd, const char *env, 940 | const char *envp[], const char *dir, sock_t sock) { 941 | char buf[500]; 942 | pid_t pid = fork(); 943 | (void) env; 944 | 945 | if (pid == 0) { 946 | chdir(dir); 947 | dup2(sock, 0); 948 | dup2(sock, 1); 949 | closesocket(sock); 950 | 951 | // After exec, all signal handlers are restored to their default values, 952 | // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's 953 | // implementation, SIGCHLD's handler will leave unchanged after exec 954 | // if it was set to be ignored. Restore it to default action. 955 | signal(SIGCHLD, SIG_DFL); 956 | 957 | if (interp == NULL) { 958 | execle(cmd, cmd, NULL, envp); 959 | } else { 960 | execle(interp, interp, cmd, NULL, envp); 961 | } 962 | snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n" 963 | "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp, 964 | interp == NULL ? "" : " ", cmd, strerror(errno)); 965 | send(1, buf, strlen(buf), 0); 966 | exit(EXIT_FAILURE); // exec call failed 967 | } 968 | 969 | return pid; 970 | } 971 | #endif // _WIN32 972 | 973 | // This structure helps to create an environment for the spawned CGI program. 974 | // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings, 975 | // last element must be NULL. 976 | // However, on Windows there is a requirement that all these VARIABLE=VALUE\0 977 | // strings must reside in a contiguous buffer. The end of the buffer is 978 | // marked by two '\0' characters. 979 | // We satisfy both worlds: we create an envp array (which is vars), all 980 | // entries are actually pointers inside buf. 981 | struct cgi_env_block { 982 | struct mg_connection *conn; 983 | char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer 984 | const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[] 985 | int len; // Space taken 986 | int nvars; // Number of variables in envp[] 987 | }; 988 | 989 | // Append VARIABLE=VALUE\0 string to the buffer, and add a respective 990 | // pointer into the vars array. 991 | static char *addenv(struct cgi_env_block *block, const char *fmt, ...) { 992 | int n, space; 993 | char *added; 994 | va_list ap; 995 | 996 | // Calculate how much space is left in the buffer 997 | space = sizeof(block->buf) - block->len - 2; 998 | assert(space >= 0); 999 | 1000 | // Make a pointer to the free space int the buffer 1001 | added = block->buf + block->len; 1002 | 1003 | // Copy VARIABLE=VALUE\0 string into the free space 1004 | va_start(ap, fmt); 1005 | n = mg_vsnprintf(added, (size_t) space, fmt, ap); 1006 | va_end(ap); 1007 | 1008 | // Make sure we do not overflow buffer and the envp array 1009 | if (n > 0 && n + 1 < space && 1010 | block->nvars < (int) ARRAY_SIZE(block->vars) - 2) { 1011 | // Append a pointer to the added string into the envp array 1012 | block->vars[block->nvars++] = added; 1013 | // Bump up used length counter. Include \0 terminator 1014 | block->len += n + 1; 1015 | } 1016 | 1017 | return added; 1018 | } 1019 | 1020 | static void addenv2(struct cgi_env_block *blk, const char *name) { 1021 | const char *s; 1022 | if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s); 1023 | } 1024 | 1025 | static void prepare_cgi_environment(struct connection *conn, 1026 | const char *prog, 1027 | struct cgi_env_block *blk) { 1028 | struct mg_connection *ri = &conn->mg_conn; 1029 | const char *s, *slash; 1030 | char *p, **opts = conn->server->config_options; 1031 | int i; 1032 | 1033 | blk->len = blk->nvars = 0; 1034 | blk->conn = ri; 1035 | 1036 | addenv(blk, "SERVER_NAME=%s", opts[AUTH_DOMAIN]); 1037 | addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]); 1038 | addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]); 1039 | addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION); 1040 | 1041 | // Prepare the environment block 1042 | addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1"); 1043 | addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1"); 1044 | addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP 1045 | 1046 | // TODO(lsm): fix this for IPv6 case 1047 | //addenv(blk, "SERVER_PORT=%d", ri->remote_port); 1048 | 1049 | addenv(blk, "REQUEST_METHOD=%s", ri->request_method); 1050 | addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip); 1051 | addenv(blk, "REMOTE_PORT=%d", ri->remote_port); 1052 | addenv(blk, "REQUEST_URI=%s%s%s", ri->uri, 1053 | ri->query_string == NULL ? "" : "?", 1054 | ri->query_string == NULL ? "" : ri->query_string); 1055 | 1056 | // SCRIPT_NAME 1057 | if (conn->path_info != NULL) { 1058 | addenv(blk, "SCRIPT_NAME=%.*s", 1059 | (int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri); 1060 | addenv(blk, "PATH_INFO=%s", conn->path_info); 1061 | } else { 1062 | s = strrchr(prog, '/'); 1063 | slash = strrchr(ri->uri, '/'); 1064 | addenv(blk, "SCRIPT_NAME=%.*s%s", 1065 | slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri, 1066 | s == NULL ? prog : s); 1067 | } 1068 | 1069 | addenv(blk, "SCRIPT_FILENAME=%s", prog); 1070 | addenv(blk, "PATH_TRANSLATED=%s", prog); 1071 | #ifdef MONGOOSE_USE_SSL 1072 | addenv(blk, "HTTPS=%s", conn->ssl != NULL ? "on" : "off"); 1073 | #else 1074 | addenv(blk, "HTTPS=%s", "off"); 1075 | #endif 1076 | 1077 | if ((s = mg_get_header(ri, "Content-Type")) != NULL) 1078 | addenv(blk, "CONTENT_TYPE=%s", s); 1079 | 1080 | if (ri->query_string != NULL) 1081 | addenv(blk, "QUERY_STRING=%s", ri->query_string); 1082 | 1083 | if ((s = mg_get_header(ri, "Content-Length")) != NULL) 1084 | addenv(blk, "CONTENT_LENGTH=%s", s); 1085 | 1086 | addenv2(blk, "PATH"); 1087 | addenv2(blk, "PERLLIB"); 1088 | addenv2(blk, ENV_EXPORT_TO_CGI); 1089 | 1090 | #if defined(_WIN32) 1091 | addenv2(blk, "COMSPEC"); 1092 | addenv2(blk, "SYSTEMROOT"); 1093 | addenv2(blk, "SystemDrive"); 1094 | addenv2(blk, "ProgramFiles"); 1095 | addenv2(blk, "ProgramFiles(x86)"); 1096 | addenv2(blk, "CommonProgramFiles(x86)"); 1097 | #else 1098 | addenv2(blk, "LD_LIBRARY_PATH"); 1099 | #endif // _WIN32 1100 | 1101 | // Add all headers as HTTP_* variables 1102 | for (i = 0; i < ri->num_headers; i++) { 1103 | p = addenv(blk, "HTTP_%s=%s", 1104 | ri->http_headers[i].name, ri->http_headers[i].value); 1105 | 1106 | // Convert variable name into uppercase, and change - to _ 1107 | for (; *p != '=' && *p != '\0'; p++) { 1108 | if (*p == '-') 1109 | *p = '_'; 1110 | *p = (char) toupper(* (unsigned char *) p); 1111 | } 1112 | } 1113 | 1114 | blk->vars[blk->nvars++] = NULL; 1115 | blk->buf[blk->len++] = '\0'; 1116 | 1117 | assert(blk->nvars < (int) ARRAY_SIZE(blk->vars)); 1118 | assert(blk->len > 0); 1119 | assert(blk->len < (int) sizeof(blk->buf)); 1120 | } 1121 | 1122 | static const char cgi_status[] = "HTTP/1.1 200 OK\r\n"; 1123 | 1124 | static void open_cgi_endpoint(struct connection *conn, const char *prog) { 1125 | struct cgi_env_block blk; 1126 | char dir[MAX_PATH_SIZE], *p = NULL; 1127 | sock_t fds[2]; 1128 | 1129 | prepare_cgi_environment(conn, prog, &blk); 1130 | // CGI must be executed in its own directory. 'dir' must point to the 1131 | // directory containing executable program, 'p' must point to the 1132 | // executable program name relative to 'dir'. 1133 | mg_snprintf(dir, sizeof(dir), "%s", prog); 1134 | if ((p = strrchr(dir, '/')) != NULL) { 1135 | *p++ = '\0'; 1136 | } else { 1137 | dir[0] = '.', dir[1] = '\0'; 1138 | p = (char *) prog; 1139 | } 1140 | 1141 | // Try to create socketpair in a loop until success. mg_socketpair() 1142 | // can be interrupted by a signal and fail. 1143 | // TODO(lsm): use sigaction to restart interrupted syscall 1144 | do { 1145 | mg_socketpair(fds); 1146 | } while (fds[0] == INVALID_SOCKET); 1147 | 1148 | if (start_process(conn->server->config_options[CGI_INTERPRETER], 1149 | prog, blk.buf, blk.vars, dir, fds[1]) > 0) { 1150 | conn->endpoint_type = EP_CGI; 1151 | conn->endpoint.cgi_sock = fds[0]; 1152 | spool(&conn->remote_iobuf, cgi_status, sizeof(cgi_status) - 1); 1153 | conn->mg_conn.status_code = 200; 1154 | conn->flags |= CONN_BUFFER; 1155 | } else { 1156 | closesocket(fds[0]); 1157 | send_http_error(conn, 500, "start_process(%s) failed", prog); 1158 | } 1159 | 1160 | #ifndef _WIN32 1161 | closesocket(fds[1]); // On Windows, CGI stdio thread closes that socket 1162 | #endif 1163 | } 1164 | 1165 | static void read_from_cgi(struct connection *conn) { 1166 | struct iobuf *io = &conn->remote_iobuf; 1167 | char buf[IOBUF_SIZE], buf2[sizeof(buf)], *s = buf2; 1168 | const char *status = "500"; 1169 | struct mg_connection c; 1170 | int len, s_len = sizeof(cgi_status) - 1, 1171 | n = recv(conn->endpoint.cgi_sock, buf, sizeof(buf), 0); 1172 | 1173 | DBG(("%p %d", conn, n)); 1174 | if (is_error(n)) { 1175 | close_local_endpoint(conn); 1176 | } else if (n > 0) { 1177 | spool(&conn->remote_iobuf, buf, n); 1178 | if (conn->flags & CONN_BUFFER) { 1179 | len = get_request_len(io->buf + s_len, io->len - s_len); 1180 | if (len == 0) return; 1181 | if (len > 0) { 1182 | memset(&c, 0, sizeof(c)); 1183 | memcpy(buf2, io->buf + s_len, len); 1184 | buf2[len - 1] = '\0'; 1185 | parse_http_headers(&s, &c); 1186 | if (mg_get_header(&c, "Location") != NULL) { 1187 | status = "302"; 1188 | } else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) { 1189 | status = "200"; 1190 | } 1191 | } 1192 | memcpy(io->buf + 9, status, 3); 1193 | conn->mg_conn.status_code = atoi(status); 1194 | conn->flags &= ~CONN_BUFFER; 1195 | } 1196 | } 1197 | } 1198 | 1199 | static void forward_post_data(struct connection *conn) { 1200 | struct iobuf *io = &conn->local_iobuf; 1201 | int n = send(conn->endpoint.cgi_sock, io->buf, io->len, 0); 1202 | discard_leading_iobuf_bytes(io, n); 1203 | } 1204 | #endif // !MONGOOSE_NO_CGI 1205 | 1206 | // 'sa' must be an initialized address to bind to 1207 | static sock_t open_listening_socket(union socket_address *sa) { 1208 | sock_t on = 1, sock = INVALID_SOCKET; 1209 | 1210 | if ((sock = socket(sa->sa.sa_family, SOCK_STREAM, 6)) == INVALID_SOCKET || 1211 | setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) || 1212 | bind(sock, &sa->sa, sa->sa.sa_family == AF_INET ? 1213 | sizeof(sa->sin) : sizeof(sa->sa)) != 0 || 1214 | listen(sock, SOMAXCONN) != 0) { 1215 | closesocket(sock); 1216 | sock = INVALID_SOCKET; 1217 | } 1218 | 1219 | return sock; 1220 | } 1221 | 1222 | static char *mg_strdup(const char *str) { 1223 | char *copy = (char *) malloc(strlen(str) + 1); 1224 | if (copy != NULL) { 1225 | strcpy(copy, str); 1226 | } 1227 | return copy; 1228 | } 1229 | 1230 | static int isbyte(int n) { 1231 | return n >= 0 && n <= 255; 1232 | } 1233 | 1234 | static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) { 1235 | int n, a, b, c, d, slash = 32, len = 0; 1236 | 1237 | if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 || 1238 | sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && 1239 | isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && 1240 | slash >= 0 && slash < 33) { 1241 | len = n; 1242 | *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d; 1243 | *mask = slash ? 0xffffffffU << (32 - slash) : 0; 1244 | } 1245 | 1246 | return len; 1247 | } 1248 | 1249 | // Verify given socket address against the ACL. 1250 | // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. 1251 | static int check_acl(const char *acl, uint32_t remote_ip) { 1252 | int allowed, flag; 1253 | uint32_t net, mask; 1254 | struct vec vec; 1255 | 1256 | // If any ACL is set, deny by default 1257 | allowed = acl == NULL ? '+' : '-'; 1258 | 1259 | while ((acl = next_option(acl, &vec, NULL)) != NULL) { 1260 | flag = vec.ptr[0]; 1261 | if ((flag != '+' && flag != '-') || 1262 | parse_net(&vec.ptr[1], &net, &mask) == 0) { 1263 | return -1; 1264 | } 1265 | 1266 | if (net == (remote_ip & mask)) { 1267 | allowed = flag; 1268 | } 1269 | } 1270 | 1271 | return allowed == '+'; 1272 | } 1273 | 1274 | static void sockaddr_to_string(char *buf, size_t len, 1275 | const union socket_address *usa) { 1276 | buf[0] = '\0'; 1277 | #if defined(MONGOOSE_USE_IPV6) 1278 | inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ? 1279 | (void *) &usa->sin.sin_addr : 1280 | (void *) &usa->sin6.sin6_addr, buf, len); 1281 | #elif defined(_WIN32) 1282 | // Only Windoze Vista (and newer) have inet_ntop() 1283 | strncpy(buf, inet_ntoa(usa->sin.sin_addr), len); 1284 | #else 1285 | inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len); 1286 | #endif 1287 | } 1288 | 1289 | static struct connection *accept_new_connection(struct mg_server *server) { 1290 | union socket_address sa; 1291 | socklen_t len = sizeof(sa); 1292 | sock_t sock = INVALID_SOCKET; 1293 | struct connection *conn = NULL; 1294 | 1295 | // NOTE(lsm): on Windows, sock is always > FD_SETSIZE 1296 | if ((sock = accept(server->listening_sock, &sa.sa, &len)) == INVALID_SOCKET) { 1297 | } else if (!check_acl(server->config_options[ACCESS_CONTROL_LIST], 1298 | ntohl(* (uint32_t *) &sa.sin.sin_addr))) { 1299 | // NOTE(lsm): check_acl doesn't work for IPv6 1300 | closesocket(sock); 1301 | } else if ((conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) { 1302 | closesocket(sock); 1303 | #ifdef MONGOOSE_USE_SSL 1304 | } else if (server->ssl_ctx != NULL && 1305 | ((conn->ssl = SSL_new(server->ssl_ctx)) == NULL || 1306 | SSL_set_fd(conn->ssl, sock) != 1)) { 1307 | DBG(("SSL error")); 1308 | closesocket(sock); 1309 | free(conn); 1310 | conn = NULL; 1311 | #endif 1312 | } else { 1313 | set_close_on_exec(sock); 1314 | set_non_blocking_mode(sock); 1315 | conn->server = server; 1316 | conn->client_sock = sock; 1317 | sockaddr_to_string(conn->mg_conn.remote_ip, 1318 | sizeof(conn->mg_conn.remote_ip), &sa); 1319 | conn->mg_conn.remote_port = ntohs(sa.sin.sin_port); 1320 | conn->mg_conn.server_param = server->server_data; 1321 | LINKED_LIST_ADD_TO_FRONT(&server->active_connections, &conn->link); 1322 | DBG(("added conn %p", conn)); 1323 | } 1324 | 1325 | return conn; 1326 | } 1327 | 1328 | static void close_conn(struct connection *conn) { 1329 | LINKED_LIST_REMOVE(&conn->link); 1330 | closesocket(conn->client_sock); 1331 | close_local_endpoint(conn); 1332 | DBG(("%p %d %d", conn, conn->flags, conn->endpoint_type)); 1333 | free(conn->request); // It's OK to free(NULL), ditto below 1334 | free(conn->path_info); 1335 | free(conn->remote_iobuf.buf); 1336 | free(conn->local_iobuf.buf); 1337 | #ifdef MONGOOSE_USE_SSL 1338 | if (conn->ssl != NULL) SSL_free(conn->ssl); 1339 | #endif 1340 | free(conn); 1341 | } 1342 | 1343 | // Protect against directory disclosure attack by removing '..', 1344 | // excessive '/' and '\' characters 1345 | static void remove_double_dots_and_double_slashes(char *s) { 1346 | char *p = s; 1347 | 1348 | while (*s != '\0') { 1349 | *p++ = *s++; 1350 | if (s[-1] == '/' || s[-1] == '\\') { 1351 | // Skip all following slashes, backslashes and double-dots 1352 | while (s[0] != '\0') { 1353 | if (s[0] == '/' || s[0] == '\\') { s++; } 1354 | else if (s[0] == '.' && s[1] == '.') { s += 2; } 1355 | else { break; } 1356 | } 1357 | } 1358 | } 1359 | *p = '\0'; 1360 | } 1361 | 1362 | int mg_url_decode(const char *src, int src_len, char *dst, 1363 | int dst_len, int is_form_url_encoded) { 1364 | int i, j, a, b; 1365 | #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') 1366 | 1367 | for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { 1368 | if (src[i] == '%' && i < src_len - 2 && 1369 | isxdigit(* (const unsigned char *) (src + i + 1)) && 1370 | isxdigit(* (const unsigned char *) (src + i + 2))) { 1371 | a = tolower(* (const unsigned char *) (src + i + 1)); 1372 | b = tolower(* (const unsigned char *) (src + i + 2)); 1373 | dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b)); 1374 | i += 2; 1375 | } else if (is_form_url_encoded && src[i] == '+') { 1376 | dst[j] = ' '; 1377 | } else { 1378 | dst[j] = src[i]; 1379 | } 1380 | } 1381 | 1382 | dst[j] = '\0'; // Null-terminate the destination 1383 | 1384 | return i >= src_len ? j : -1; 1385 | } 1386 | 1387 | static int is_valid_http_method(const char *method) { 1388 | return !strcmp(method, "GET") || !strcmp(method, "POST") || 1389 | !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") || 1390 | !strcmp(method, "PUT") || !strcmp(method, "DELETE") || 1391 | !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND") 1392 | || !strcmp(method, "MKCOL"); 1393 | } 1394 | 1395 | // Parse HTTP request, fill in mg_request structure. 1396 | // This function modifies the buffer by NUL-terminating 1397 | // HTTP request components, header names and header values. 1398 | // Note that len must point to the last \n of HTTP headers. 1399 | static int parse_http_message(char *buf, int len, struct mg_connection *ri) { 1400 | int is_request, n; 1401 | 1402 | // Reset the connection. Make sure that we don't touch fields that are 1403 | // set elsewhere: remote_ip, remote_port, server_param 1404 | ri->request_method = ri->uri = ri->http_version = ri->query_string = NULL; 1405 | ri->num_headers = ri->status_code = ri->is_websocket = ri->content_len = 0; 1406 | 1407 | buf[len - 1] = '\0'; 1408 | 1409 | // RFC says that all initial whitespaces should be ingored 1410 | while (*buf != '\0' && isspace(* (unsigned char *) buf)) { 1411 | buf++; 1412 | } 1413 | ri->request_method = skip(&buf, " "); 1414 | ri->uri = skip(&buf, " "); 1415 | ri->http_version = skip(&buf, "\r\n"); 1416 | 1417 | // HTTP message could be either HTTP request or HTTP response, e.g. 1418 | // "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." 1419 | is_request = is_valid_http_method(ri->request_method); 1420 | if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) || 1421 | (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) { 1422 | len = -1; 1423 | } else { 1424 | if (is_request) { 1425 | ri->http_version += 5; 1426 | } 1427 | parse_http_headers(&buf, ri); 1428 | 1429 | if ((ri->query_string = strchr(ri->uri, '?')) != NULL) { 1430 | *(char *) ri->query_string++ = '\0'; 1431 | } 1432 | n = (int) strlen(ri->uri); 1433 | mg_url_decode(ri->uri, n, (char *) ri->uri, n + 1, 0); 1434 | remove_double_dots_and_double_slashes((char *) ri->uri); 1435 | } 1436 | 1437 | return len; 1438 | } 1439 | 1440 | static int lowercase(const char *s) { 1441 | return tolower(* (const unsigned char *) s); 1442 | } 1443 | 1444 | static int mg_strcasecmp(const char *s1, const char *s2) { 1445 | int diff; 1446 | 1447 | do { 1448 | diff = lowercase(s1++) - lowercase(s2++); 1449 | } while (diff == 0 && s1[-1] != '\0'); 1450 | 1451 | return diff; 1452 | } 1453 | 1454 | static int mg_strncasecmp(const char *s1, const char *s2, size_t len) { 1455 | int diff = 0; 1456 | 1457 | if (len > 0) 1458 | do { 1459 | diff = lowercase(s1++) - lowercase(s2++); 1460 | } while (diff == 0 && s1[-1] != '\0' && --len > 0); 1461 | 1462 | return diff; 1463 | } 1464 | 1465 | // Return HTTP header value, or NULL if not found. 1466 | const char *mg_get_header(const struct mg_connection *ri, const char *s) { 1467 | int i; 1468 | 1469 | for (i = 0; i < ri->num_headers; i++) 1470 | if (!mg_strcasecmp(s, ri->http_headers[i].name)) 1471 | return ri->http_headers[i].value; 1472 | 1473 | return NULL; 1474 | } 1475 | 1476 | #ifndef MONGOOSE_NO_FILESYSTEM 1477 | // Perform case-insensitive match of string against pattern 1478 | static int match_prefix(const char *pattern, int pattern_len, const char *str) { 1479 | const char *or_str; 1480 | int i, j, len, res; 1481 | 1482 | if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) { 1483 | res = match_prefix(pattern, or_str - pattern, str); 1484 | return res > 0 ? res : 1485 | match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str); 1486 | } 1487 | 1488 | i = j = 0; 1489 | res = -1; 1490 | for (; i < pattern_len; i++, j++) { 1491 | if (pattern[i] == '?' && str[j] != '\0') { 1492 | continue; 1493 | } else if (pattern[i] == '$') { 1494 | return str[j] == '\0' ? j : -1; 1495 | } else if (pattern[i] == '*') { 1496 | i++; 1497 | if (pattern[i] == '*') { 1498 | i++; 1499 | len = (int) strlen(str + j); 1500 | } else { 1501 | len = (int) strcspn(str + j, "/"); 1502 | } 1503 | if (i == pattern_len) { 1504 | return j + len; 1505 | } 1506 | do { 1507 | res = match_prefix(pattern + i, pattern_len - i, str + j + len); 1508 | } while (res == -1 && len-- > 0); 1509 | return res == -1 ? -1 : j + res + len; 1510 | } else if (lowercase(&pattern[i]) != lowercase(&str[j])) { 1511 | return -1; 1512 | } 1513 | } 1514 | return j; 1515 | } 1516 | 1517 | // Return 1 if real file has been found, 0 otherwise 1518 | static int convert_uri_to_file_name(struct connection *conn, char *buf, 1519 | size_t buf_len, file_stat_t *st) { 1520 | struct vec a, b; 1521 | const char *rewrites = conn->server->config_options[URL_REWRITES], 1522 | *root = conn->server->config_options[DOCUMENT_ROOT], 1523 | *cgi_pat = conn->server->config_options[CGI_PATTERN], 1524 | *uri = conn->mg_conn.uri; 1525 | char *p; 1526 | int match_len; 1527 | 1528 | // No filesystem access 1529 | if (root == NULL) return 0; 1530 | 1531 | // Handle URL rewrites 1532 | mg_snprintf(buf, buf_len, "%s%s", root, uri); 1533 | while ((rewrites = next_option(rewrites, &a, &b)) != NULL) { 1534 | if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) { 1535 | mg_snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.ptr, uri + match_len); 1536 | break; 1537 | } 1538 | } 1539 | 1540 | if (stat(buf, st) == 0) return 1; 1541 | 1542 | #ifndef MONGOOSE_NO_CGI 1543 | // Support PATH_INFO for CGI scripts. 1544 | for (p = buf + strlen(root) + 2; *p != '\0'; p++) { 1545 | if (*p == '/') { 1546 | *p = '\0'; 1547 | if (match_prefix(cgi_pat, strlen(cgi_pat), buf) > 0 && !stat(buf, st)) { 1548 | DBG(("!!!! [%s]", buf)); 1549 | *p = '/'; 1550 | conn->path_info = mg_strdup(p); 1551 | *p = '\0'; 1552 | return 1; 1553 | } 1554 | *p = '/'; 1555 | } 1556 | } 1557 | #endif 1558 | 1559 | return 0; 1560 | } 1561 | #endif // MONGOOSE_NO_FILESYSTEM 1562 | 1563 | static int should_keep_alive(const struct mg_connection *conn) { 1564 | const char *method = conn->request_method; 1565 | const char *http_version = conn->http_version; 1566 | const char *header = mg_get_header(conn, "Connection"); 1567 | return method != NULL && (!strcmp(method, "GET") || 1568 | ((struct connection *) conn)->endpoint_type == EP_USER) && 1569 | ((header != NULL && !mg_strcasecmp(header, "keep-alive")) || 1570 | (header == NULL && http_version && !strcmp(http_version, "1.1"))); 1571 | } 1572 | 1573 | int mg_write(struct mg_connection *c, const void *buf, int len) { 1574 | return spool(&((struct connection *) c)->remote_iobuf, buf, len); 1575 | } 1576 | 1577 | void mg_send_status(struct mg_connection *c, int status) { 1578 | if (c->status_code == 0) { 1579 | c->status_code = status; 1580 | mg_printf(c, "HTTP/1.1 %d %s\r\n", status, status_code_to_str(status)); 1581 | } 1582 | } 1583 | 1584 | void mg_send_header(struct mg_connection *c, const char *name, const char *v) { 1585 | if (c->status_code == 0) { 1586 | c->status_code = 200; 1587 | mg_printf(c, "HTTP/1.1 %d %s\r\n", 200, status_code_to_str(200)); 1588 | } 1589 | mg_printf(c, "%s: %s\r\n", name, v); 1590 | } 1591 | 1592 | static void terminate_headers(struct mg_connection *c) { 1593 | struct connection *conn = (struct connection *) c; 1594 | if (!(conn->flags & CONN_HEADERS_SENT)) { 1595 | mg_send_header(c, "Transfer-Encoding", "chunked"); 1596 | mg_write(c, "\r\n", 2); 1597 | conn->flags |= CONN_HEADERS_SENT; 1598 | } 1599 | } 1600 | 1601 | void mg_send_data(struct mg_connection *c, const void *data, int data_len) { 1602 | terminate_headers(c); 1603 | write_chunk((struct connection *) c, (const char *) data, data_len); 1604 | } 1605 | 1606 | void mg_printf_data(struct mg_connection *c, const char *fmt, ...) { 1607 | va_list ap; 1608 | 1609 | terminate_headers(c); 1610 | 1611 | va_start(ap, fmt); 1612 | mg_vprintf(c, fmt, ap, 1); 1613 | va_end(ap); 1614 | } 1615 | 1616 | #if !defined(NO_WEBSOCKET) || !defined(MONGOOSE_NO_AUTH) 1617 | static int is_big_endian(void) { 1618 | static const int n = 1; 1619 | return ((char *) &n)[0] == 0; 1620 | } 1621 | #endif 1622 | 1623 | #ifndef MONGOOSE_NO_WEBSOCKET 1624 | // START OF SHA-1 code 1625 | // Copyright(c) By Steve Reid <steve@edmweb.com> 1626 | #define SHA1HANDSOFF 1627 | #if defined(__sun) 1628 | #include "solarisfixes.h" 1629 | #endif 1630 | 1631 | union char64long16 { unsigned char c[64]; uint32_t l[16]; }; 1632 | 1633 | #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) 1634 | 1635 | static uint32_t blk0(union char64long16 *block, int i) { 1636 | // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN 1637 | if (!is_big_endian()) { 1638 | block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) | 1639 | (rol(block->l[i], 8) & 0x00FF00FF); 1640 | } 1641 | return block->l[i]; 1642 | } 1643 | 1644 | #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ 1645 | ^block->l[(i+2)&15]^block->l[i&15],1)) 1646 | #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30); 1647 | #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); 1648 | #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); 1649 | #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); 1650 | #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); 1651 | 1652 | typedef struct { 1653 | uint32_t state[5]; 1654 | uint32_t count[2]; 1655 | unsigned char buffer[64]; 1656 | } SHA1_CTX; 1657 | 1658 | static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) { 1659 | uint32_t a, b, c, d, e; 1660 | union char64long16 block[1]; 1661 | 1662 | memcpy(block, buffer, 64); 1663 | a = state[0]; 1664 | b = state[1]; 1665 | c = state[2]; 1666 | d = state[3]; 1667 | e = state[4]; 1668 | R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); 1669 | R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); 1670 | R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); 1671 | R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); 1672 | R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); 1673 | R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); 1674 | R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); 1675 | R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); 1676 | R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); 1677 | R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); 1678 | R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); 1679 | R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); 1680 | R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); 1681 | R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); 1682 | R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); 1683 | R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); 1684 | R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); 1685 | R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); 1686 | R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); 1687 | R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); 1688 | state[0] += a; 1689 | state[1] += b; 1690 | state[2] += c; 1691 | state[3] += d; 1692 | state[4] += e; 1693 | // Erase working structures. The order of operations is important, 1694 | // used to ensure that compiler doesn't optimize those out. 1695 | memset(block, 0, sizeof(block)); 1696 | a = b = c = d = e = block[0].l[0]; 1697 | } 1698 | 1699 | static void SHA1Init(SHA1_CTX* context) { 1700 | context->state[0] = 0x67452301; 1701 | context->state[1] = 0xEFCDAB89; 1702 | context->state[2] = 0x98BADCFE; 1703 | context->state[3] = 0x10325476; 1704 | context->state[4] = 0xC3D2E1F0; 1705 | context->count[0] = context->count[1] = 0; 1706 | } 1707 | 1708 | static void SHA1Update(SHA1_CTX* context, const unsigned char* data, 1709 | uint32_t len) { 1710 | uint32_t i, j; 1711 | 1712 | j = context->count[0]; 1713 | if ((context->count[0] += len << 3) < j) 1714 | context->count[1]++; 1715 | context->count[1] += (len>>29); 1716 | j = (j >> 3) & 63; 1717 | if ((j + len) > 63) { 1718 | memcpy(&context->buffer[j], data, (i = 64-j)); 1719 | SHA1Transform(context->state, context->buffer); 1720 | for ( ; i + 63 < len; i += 64) { 1721 | SHA1Transform(context->state, &data[i]); 1722 | } 1723 | j = 0; 1724 | } 1725 | else i = 0; 1726 | memcpy(&context->buffer[j], &data[i], len - i); 1727 | } 1728 | 1729 | static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) { 1730 | unsigned i; 1731 | unsigned char finalcount[8], c; 1732 | 1733 | for (i = 0; i < 8; i++) { 1734 | finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] 1735 | >> ((3-(i & 3)) * 8) ) & 255); 1736 | } 1737 | c = 0200; 1738 | SHA1Update(context, &c, 1); 1739 | while ((context->count[0] & 504) != 448) { 1740 | c = 0000; 1741 | SHA1Update(context, &c, 1); 1742 | } 1743 | SHA1Update(context, finalcount, 8); 1744 | for (i = 0; i < 20; i++) { 1745 | digest[i] = (unsigned char) 1746 | ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); 1747 | } 1748 | memset(context, '\0', sizeof(*context)); 1749 | memset(&finalcount, '\0', sizeof(finalcount)); 1750 | } 1751 | // END OF SHA1 CODE 1752 | 1753 | static void base64_encode(const unsigned char *src, int src_len, char *dst) { 1754 | static const char *b64 = 1755 | "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 1756 | int i, j, a, b, c; 1757 | 1758 | for (i = j = 0; i < src_len; i += 3) { 1759 | a = src[i]; 1760 | b = i + 1 >= src_len ? 0 : src[i + 1]; 1761 | c = i + 2 >= src_len ? 0 : src[i + 2]; 1762 | 1763 | dst[j++] = b64[a >> 2]; 1764 | dst[j++] = b64[((a & 3) << 4) | (b >> 4)]; 1765 | if (i + 1 < src_len) { 1766 | dst[j++] = b64[(b & 15) << 2 | (c >> 6)]; 1767 | } 1768 | if (i + 2 < src_len) { 1769 | dst[j++] = b64[c & 63]; 1770 | } 1771 | } 1772 | while (j % 4 != 0) { 1773 | dst[j++] = '='; 1774 | } 1775 | dst[j++] = '\0'; 1776 | } 1777 | 1778 | static void send_websocket_handshake(struct mg_connection *conn, 1779 | const char *key) { 1780 | static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; 1781 | char buf[500], sha[20], b64_sha[sizeof(sha) * 2]; 1782 | SHA1_CTX sha_ctx; 1783 | 1784 | mg_snprintf(buf, sizeof(buf), "%s%s", key, magic); 1785 | SHA1Init(&sha_ctx); 1786 | SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf)); 1787 | SHA1Final((unsigned char *) sha, &sha_ctx); 1788 | base64_encode((unsigned char *) sha, sizeof(sha), b64_sha); 1789 | mg_snprintf(buf, sizeof(buf), "%s%s%s", 1790 | "HTTP/1.1 101 Switching Protocols\r\n" 1791 | "Upgrade: websocket\r\n" 1792 | "Connection: Upgrade\r\n" 1793 | "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n"); 1794 | 1795 | mg_write(conn, buf, strlen(buf)); 1796 | } 1797 | 1798 | static int deliver_websocket_frame(struct connection *conn) { 1799 | // Having buf unsigned char * is important, as it is used below in arithmetic 1800 | unsigned char *buf = (unsigned char *) conn->local_iobuf.buf; 1801 | int i, len, buf_len = conn->local_iobuf.len, frame_len = 0, 1802 | mask_len = 0, header_len = 0, data_len = 0, buffered = 0; 1803 | 1804 | if (buf_len >= 2) { 1805 | len = buf[1] & 127; 1806 | mask_len = buf[1] & 128 ? 4 : 0; 1807 | if (len < 126 && buf_len >= mask_len) { 1808 | data_len = len; 1809 | header_len = 2 + mask_len; 1810 | } else if (len == 126 && buf_len >= 4 + mask_len) { 1811 | header_len = 4 + mask_len; 1812 | data_len = ((((int) buf[2]) << 8) + buf[3]); 1813 | } else if (buf_len >= 10 + mask_len) { 1814 | header_len = 10 + mask_len; 1815 | data_len = (int) (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) + 1816 | htonl(* (uint32_t *) &buf[6]); 1817 | } 1818 | } 1819 | 1820 | frame_len = header_len + data_len; 1821 | buffered = frame_len > 0 && frame_len <= buf_len; 1822 | 1823 | if (buffered) { 1824 | conn->mg_conn.content_len = data_len; 1825 | conn->mg_conn.content = (char *) buf + header_len; 1826 | conn->mg_conn.wsbits = buf[0]; 1827 | 1828 | // Apply mask if necessary 1829 | if (mask_len > 0) { 1830 | for (i = 0; i < data_len; i++) { 1831 | buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4]; 1832 | } 1833 | } 1834 | 1835 | // Call the handler and remove frame from the iobuf 1836 | if (conn->endpoint.uh->handler(&conn->mg_conn)) { 1837 | conn->flags |= CONN_SPOOL_DONE; 1838 | } 1839 | discard_leading_iobuf_bytes(&conn->local_iobuf, frame_len); 1840 | } 1841 | 1842 | return buffered; 1843 | } 1844 | 1845 | int mg_websocket_write(struct mg_connection* conn, int opcode, 1846 | const char *data, size_t data_len) { 1847 | unsigned char *copy; 1848 | size_t copy_len = 0; 1849 | int retval = -1; 1850 | 1851 | if ((copy = (unsigned char *) malloc(data_len + 10)) == NULL) { 1852 | return -1; 1853 | } 1854 | 1855 | copy[0] = 0x80 + (opcode & 0x0f); 1856 | 1857 | // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 1858 | if (data_len < 126) { 1859 | // Inline 7-bit length field 1860 | copy[1] = data_len; 1861 | memcpy(copy + 2, data, data_len); 1862 | copy_len = 2 + data_len; 1863 | } else if (data_len <= 0xFFFF) { 1864 | // 16-bit length field 1865 | copy[1] = 126; 1866 | * (uint16_t *) (copy + 2) = (uint16_t) htons((uint16_t) data_len); 1867 | memcpy(copy + 4, data, data_len); 1868 | copy_len = 4 + data_len; 1869 | } else { 1870 | // 64-bit length field 1871 | copy[1] = 127; 1872 | * (uint32_t *) (copy + 2) = (uint32_t) 1873 | htonl((uint32_t) ((uint64_t) data_len >> 32)); 1874 | * (uint32_t *) (copy + 6) = (uint32_t) htonl(data_len & 0xffffffff); 1875 | memcpy(copy + 10, data, data_len); 1876 | copy_len = 10 + data_len; 1877 | } 1878 | 1879 | if (copy_len > 0) { 1880 | retval = mg_write(conn, copy, copy_len); 1881 | } 1882 | free(copy); 1883 | 1884 | return retval; 1885 | } 1886 | 1887 | static void send_websocket_handshake_if_requested(struct mg_connection *conn) { 1888 | const char *ver = mg_get_header(conn, "Sec-WebSocket-Version"), 1889 | *key = mg_get_header(conn, "Sec-WebSocket-Key"); 1890 | if (ver != NULL && key != NULL) { 1891 | conn->is_websocket = 1; 1892 | send_websocket_handshake(conn, key); 1893 | } 1894 | } 1895 | 1896 | static void ping_idle_websocket_connection(struct connection *conn, time_t t) { 1897 | if (t - conn->last_activity_time > MONGOOSE_USE_WEBSOCKET_PING_INTERVAL) { 1898 | mg_websocket_write(&conn->mg_conn, 0x9, "", 0); 1899 | } 1900 | } 1901 | #else 1902 | #define ping_idle_websocket_connection(conn, t) 1903 | #endif // !MONGOOSE_NO_WEBSOCKET 1904 | 1905 | static void write_terminating_chunk(struct connection *conn) { 1906 | mg_write(&conn->mg_conn, "0\r\n\r\n", 5); 1907 | } 1908 | 1909 | static void call_uri_handler(struct connection *conn) { 1910 | conn->mg_conn.content = conn->local_iobuf.buf; 1911 | if (conn->endpoint.uh->handler(&conn->mg_conn)) { 1912 | if (conn->flags & CONN_HEADERS_SENT) { 1913 | write_terminating_chunk(conn); 1914 | } 1915 | close_local_endpoint(conn); 1916 | } else { 1917 | conn->flags |= CONN_LONG_RUNNING; 1918 | } 1919 | } 1920 | 1921 | static void callback_http_client_on_connect(struct connection *conn) { 1922 | int ok = 1; 1923 | socklen_t len = sizeof(ok); 1924 | 1925 | conn->flags &= ~CONN_CONNECTING; 1926 | if (getsockopt(conn->client_sock, SOL_SOCKET, SO_ERROR, (char *) &ok, 1927 | &len) == 0 && ok == 0) { 1928 | #ifdef MONGOOSE_USE_SSL 1929 | if (conn->ssl != NULL) { 1930 | int res = SSL_connect(conn->ssl), ssl_err = SSL_get_error(conn->ssl, res); 1931 | //DBG(("%p res %d %d", conn, res, ssl_err)); 1932 | if (res == 1) { 1933 | conn->flags = CONN_SSL_HANDS_SHAKEN; 1934 | } else if (res == 0 || ssl_err == 2 || ssl_err == 3) { 1935 | conn->flags |= CONN_CONNECTING; 1936 | return; // Call us again 1937 | } else { 1938 | ok = 1; 1939 | } 1940 | } 1941 | #endif 1942 | } 1943 | conn->mg_conn.status_code = ok == 0 ? MG_CONNECT_SUCCESS : MG_CONNECT_FAILURE; 1944 | if (conn->handler(&conn->mg_conn) || ok != 0) { 1945 | conn->flags |= CONN_CLOSE; 1946 | } 1947 | } 1948 | 1949 | static void write_to_socket(struct connection *conn) { 1950 | struct iobuf *io = &conn->remote_iobuf; 1951 | int n = 0; 1952 | 1953 | if (conn->endpoint_type == EP_CLIENT && conn->flags & CONN_CONNECTING) { 1954 | callback_http_client_on_connect(conn); 1955 | return; 1956 | } 1957 | 1958 | #ifdef MONGOOSE_USE_SSL 1959 | if (conn->ssl != NULL) { 1960 | n = SSL_write(conn->ssl, io->buf, io->len); 1961 | } else 1962 | #endif 1963 | { n = send(conn->client_sock, io->buf, io->len, 0); } 1964 | 1965 | DBG(("%p Written %d of %d(%d): [%.*s ...]", 1966 | conn, n, io->len, io->size, io->len < 40 ? io->len : 40, io->buf)); 1967 | 1968 | if (is_error(n)) { 1969 | conn->flags |= CONN_CLOSE; 1970 | } else if (n > 0) { 1971 | discard_leading_iobuf_bytes(io, n); 1972 | conn->num_bytes_sent += n; 1973 | } 1974 | 1975 | if (io->len == 0 && conn->flags & CONN_SPOOL_DONE) { 1976 | conn->flags |= CONN_CLOSE; 1977 | } 1978 | } 1979 | 1980 | const char *mg_get_mime_type(const char *path) { 1981 | const char *ext; 1982 | size_t i, path_len; 1983 | 1984 | path_len = strlen(path); 1985 | 1986 | for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) { 1987 | ext = path + (path_len - static_builtin_mime_types[i].ext_len); 1988 | if (path_len > static_builtin_mime_types[i].ext_len && 1989 | mg_strcasecmp(ext, static_builtin_mime_types[i].extension) == 0) { 1990 | return static_builtin_mime_types[i].mime_type; 1991 | } 1992 | } 1993 | 1994 | return "text/plain"; 1995 | } 1996 | 1997 | static struct uri_handler *find_uri_handler(struct mg_server *server, 1998 | const char *uri) { 1999 | struct ll *lp, *tmp; 2000 | struct uri_handler *uh; 2001 | 2002 | LINKED_LIST_FOREACH(&server->uri_handlers, lp, tmp) { 2003 | uh = LINKED_LIST_ENTRY(lp, struct uri_handler, link); 2004 | if (!strncmp(uh->uri, uri, strlen(uh->uri))) return uh; 2005 | } 2006 | 2007 | return NULL; 2008 | } 2009 | 2010 | #ifndef MONGOOSE_NO_FILESYSTEM 2011 | // Convert month to the month number. Return -1 on error, or month number 2012 | static int get_month_index(const char *s) { 2013 | static const char *month_names[] = { 2014 | "Jan", "Feb", "Mar", "Apr", "May", "Jun", 2015 | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" 2016 | }; 2017 | int i; 2018 | 2019 | for (i = 0; i < (int) ARRAY_SIZE(month_names); i++) 2020 | if (!strcmp(s, month_names[i])) 2021 | return i; 2022 | 2023 | return -1; 2024 | } 2025 | 2026 | static int num_leap_years(int year) { 2027 | return year / 4 - year / 100 + year / 400; 2028 | } 2029 | 2030 | // Parse UTC date-time string, and return the corresponding time_t value. 2031 | static time_t parse_date_string(const char *datetime) { 2032 | static const unsigned short days_before_month[] = { 2033 | 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 2034 | }; 2035 | char month_str[32]; 2036 | int second, minute, hour, day, month, year, leap_days, days; 2037 | time_t result = (time_t) 0; 2038 | 2039 | if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", 2040 | &day, month_str, &year, &hour, &minute, &second) == 6) || 2041 | (sscanf(datetime, "%d %3s %d %d:%d:%d", 2042 | &day, month_str, &year, &hour, &minute, &second) == 6) || 2043 | (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", 2044 | &day, month_str, &year, &hour, &minute, &second) == 6) || 2045 | (sscanf(datetime, "%d-%3s-%d %d:%d:%d", 2046 | &day, month_str, &year, &hour, &minute, &second) == 6)) && 2047 | year > 1970 && 2048 | (month = get_month_index(month_str)) != -1) { 2049 | leap_days = num_leap_years(year) - num_leap_years(1970); 2050 | year -= 1970; 2051 | days = year * 365 + days_before_month[month] + (day - 1) + leap_days; 2052 | result = days * 24 * 3600 + hour * 3600 + minute * 60 + second; 2053 | } 2054 | 2055 | return result; 2056 | } 2057 | 2058 | // Look at the "path" extension and figure what mime type it has. 2059 | // Store mime type in the vector. 2060 | static void get_mime_type(const struct mg_server *server, const char *path, 2061 | struct vec *vec) { 2062 | struct vec ext_vec, mime_vec; 2063 | const char *list, *ext; 2064 | size_t path_len; 2065 | 2066 | path_len = strlen(path); 2067 | 2068 | // Scan user-defined mime types first, in case user wants to 2069 | // override default mime types. 2070 | list = server->config_options[EXTRA_MIME_TYPES]; 2071 | while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) { 2072 | // ext now points to the path suffix 2073 | ext = path + path_len - ext_vec.len; 2074 | if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) { 2075 | *vec = mime_vec; 2076 | return; 2077 | } 2078 | } 2079 | 2080 | vec->ptr = mg_get_mime_type(path); 2081 | vec->len = strlen(vec->ptr); 2082 | } 2083 | 2084 | static const char *suggest_connection_header(const struct mg_connection *conn) { 2085 | return should_keep_alive(conn) ? "keep-alive" : "close"; 2086 | } 2087 | 2088 | static void construct_etag(char *buf, size_t buf_len, const file_stat_t *st) { 2089 | mg_snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", 2090 | (unsigned long) st->st_mtime, (int64_t) st->st_size); 2091 | } 2092 | 2093 | // Return True if we should reply 304 Not Modified. 2094 | static int is_not_modified(const struct connection *conn, 2095 | const file_stat_t *stp) { 2096 | char etag[64]; 2097 | const char *ims = mg_get_header(&conn->mg_conn, "If-Modified-Since"); 2098 | const char *inm = mg_get_header(&conn->mg_conn, "If-None-Match"); 2099 | construct_etag(etag, sizeof(etag), stp); 2100 | return (inm != NULL && !mg_strcasecmp(etag, inm)) || 2101 | (ims != NULL && stp->st_mtime <= parse_date_string(ims)); 2102 | } 2103 | 2104 | // For given directory path, substitute it to valid index file. 2105 | // Return 0 if index file has been found, -1 if not found. 2106 | // If the file is found, it's stats is returned in stp. 2107 | static int find_index_file(struct connection *conn, char *path, 2108 | size_t path_len, file_stat_t *stp) { 2109 | const char *list = conn->server->config_options[INDEX_FILES]; 2110 | file_stat_t st; 2111 | struct vec filename_vec; 2112 | size_t n = strlen(path), found = 0; 2113 | 2114 | // The 'path' given to us points to the directory. Remove all trailing 2115 | // directory separator characters from the end of the path, and 2116 | // then append single directory separator character. 2117 | while (n > 0 && path[n - 1] == '/') { 2118 | n--; 2119 | } 2120 | path[n] = '/'; 2121 | 2122 | // Traverse index files list. For each entry, append it to the given 2123 | // path and see if the file exists. If it exists, break the loop 2124 | while ((list = next_option(list, &filename_vec, NULL)) != NULL) { 2125 | 2126 | // Ignore too long entries that may overflow path buffer 2127 | if (filename_vec.len > (int) (path_len - (n + 2))) 2128 | continue; 2129 | 2130 | // Prepare full path to the index file 2131 | strncpy(path + n + 1, filename_vec.ptr, filename_vec.len); 2132 | path[n + 1 + filename_vec.len] = '\0'; 2133 | 2134 | //DBG(("[%s]", path)); 2135 | 2136 | // Does it exist? 2137 | if (!stat(path, &st)) { 2138 | // Yes it does, break the loop 2139 | *stp = st; 2140 | found = 1; 2141 | break; 2142 | } 2143 | } 2144 | 2145 | // If no index file exists, restore directory path 2146 | if (!found) { 2147 | path[n] = '\0'; 2148 | } 2149 | 2150 | return found; 2151 | } 2152 | 2153 | static int parse_range_header(const char *header, int64_t *a, int64_t *b) { 2154 | return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b); 2155 | } 2156 | 2157 | static void gmt_time_string(char *buf, size_t buf_len, time_t *t) { 2158 | strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t)); 2159 | } 2160 | 2161 | static void open_file_endpoint(struct connection *conn, const char *path, 2162 | file_stat_t *st) { 2163 | char date[64], lm[64], etag[64], range[64], headers[500]; 2164 | const char *msg = "OK", *hdr; 2165 | time_t curtime = time(NULL); 2166 | int64_t r1, r2; 2167 | struct vec mime_vec; 2168 | int n; 2169 | 2170 | conn->endpoint_type = EP_FILE; 2171 | set_close_on_exec(conn->endpoint.fd); 2172 | conn->mg_conn.status_code = 200; 2173 | 2174 | get_mime_type(conn->server, path, &mime_vec); 2175 | conn->cl = st->st_size; 2176 | range[0] = '\0'; 2177 | 2178 | // If Range: header specified, act accordingly 2179 | r1 = r2 = 0; 2180 | hdr = mg_get_header(&conn->mg_conn, "Range"); 2181 | if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && 2182 | r1 >= 0 && r2 >= 0) { 2183 | conn->mg_conn.status_code = 206; 2184 | conn->cl = n == 2 ? (r2 > conn->cl ? conn->cl : r2) - r1 + 1: conn->cl - r1; 2185 | mg_snprintf(range, sizeof(range), "Content-Range: bytes " 2186 | "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n", 2187 | r1, r1 + conn->cl - 1, (int64_t) st->st_size); 2188 | msg = "Partial Content"; 2189 | lseek(conn->endpoint.fd, r1, SEEK_SET); 2190 | } 2191 | 2192 | // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to 2193 | // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 2194 | gmt_time_string(date, sizeof(date), &curtime); 2195 | gmt_time_string(lm, sizeof(lm), &st->st_mtime); 2196 | construct_etag(etag, sizeof(etag), st); 2197 | 2198 | n = mg_snprintf(headers, sizeof(headers), 2199 | "HTTP/1.1 %d %s\r\n" 2200 | "Date: %s\r\n" 2201 | "Last-Modified: %s\r\n" 2202 | "Etag: %s\r\n" 2203 | "Content-Type: %.*s\r\n" 2204 | "Content-Length: %" INT64_FMT "\r\n" 2205 | "Connection: %s\r\n" 2206 | "Accept-Ranges: bytes\r\n" 2207 | "%s%s\r\n", 2208 | conn->mg_conn.status_code, msg, date, lm, etag, 2209 | (int) mime_vec.len, mime_vec.ptr, conn->cl, 2210 | suggest_connection_header(&conn->mg_conn), 2211 | range, MONGOOSE_USE_EXTRA_HTTP_HEADERS); 2212 | spool(&conn->remote_iobuf, headers, n); 2213 | 2214 | if (!strcmp(conn->mg_conn.request_method, "HEAD")) { 2215 | conn->flags |= CONN_SPOOL_DONE; 2216 | close(conn->endpoint.fd); 2217 | conn->endpoint_type = EP_NONE; 2218 | } 2219 | } 2220 | 2221 | #endif // MONGOOSE_NO_FILESYSTEM 2222 | 2223 | static void call_uri_handler_if_data_is_buffered(struct connection *conn) { 2224 | struct iobuf *loc = &conn->local_iobuf; 2225 | struct mg_connection *c = &conn->mg_conn; 2226 | 2227 | #ifndef MONGOOSE_NO_WEBSOCKET 2228 | if (conn->mg_conn.is_websocket) { 2229 | do { } while (deliver_websocket_frame(conn)); 2230 | } else 2231 | #endif 2232 | if ((size_t) loc->len >= c->content_len) { 2233 | call_uri_handler(conn); 2234 | } 2235 | } 2236 | 2237 | #if !defined(NO_DIRECTORY_LISTING) || !defined(MONGOOSE_NO_DAV) 2238 | 2239 | #ifdef _WIN32 2240 | struct dirent { 2241 | char d_name[MAX_PATH_SIZE]; 2242 | }; 2243 | 2244 | typedef struct DIR { 2245 | HANDLE handle; 2246 | WIN32_FIND_DATAW info; 2247 | struct dirent result; 2248 | } DIR; 2249 | 2250 | // Implementation of POSIX opendir/closedir/readdir for Windows. 2251 | static DIR *opendir(const char *name) { 2252 | DIR *dir = NULL; 2253 | wchar_t wpath[MAX_PATH_SIZE]; 2254 | DWORD attrs; 2255 | 2256 | if (name == NULL) { 2257 | SetLastError(ERROR_BAD_ARGUMENTS); 2258 | } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) { 2259 | SetLastError(ERROR_NOT_ENOUGH_MEMORY); 2260 | } else { 2261 | to_wchar(name, wpath, ARRAY_SIZE(wpath)); 2262 | attrs = GetFileAttributesW(wpath); 2263 | if (attrs != 0xFFFFFFFF && 2264 | ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) { 2265 | (void) wcscat(wpath, L"\\*"); 2266 | dir->handle = FindFirstFileW(wpath, &dir->info); 2267 | dir->result.d_name[0] = '\0'; 2268 | } else { 2269 | free(dir); 2270 | dir = NULL; 2271 | } 2272 | } 2273 | 2274 | return dir; 2275 | } 2276 | 2277 | static int closedir(DIR *dir) { 2278 | int result = 0; 2279 | 2280 | if (dir != NULL) { 2281 | if (dir->handle != INVALID_HANDLE_VALUE) 2282 | result = FindClose(dir->handle) ? 0 : -1; 2283 | 2284 | free(dir); 2285 | } else { 2286 | result = -1; 2287 | SetLastError(ERROR_BAD_ARGUMENTS); 2288 | } 2289 | 2290 | return result; 2291 | } 2292 | 2293 | static struct dirent *readdir(DIR *dir) { 2294 | struct dirent *result = 0; 2295 | 2296 | if (dir) { 2297 | if (dir->handle != INVALID_HANDLE_VALUE) { 2298 | result = &dir->result; 2299 | (void) WideCharToMultiByte(CP_UTF8, 0, 2300 | dir->info.cFileName, -1, result->d_name, 2301 | sizeof(result->d_name), NULL, NULL); 2302 | 2303 | if (!FindNextFileW(dir->handle, &dir->info)) { 2304 | (void) FindClose(dir->handle); 2305 | dir->handle = INVALID_HANDLE_VALUE; 2306 | } 2307 | 2308 | } else { 2309 | SetLastError(ERROR_FILE_NOT_FOUND); 2310 | } 2311 | } else { 2312 | SetLastError(ERROR_BAD_ARGUMENTS); 2313 | } 2314 | 2315 | return result; 2316 | } 2317 | #endif // _WIN32 POSIX opendir/closedir/readdir implementation 2318 | 2319 | static int must_hide_file(struct connection *conn, const char *path) { 2320 | const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$"; 2321 | const char *pattern = conn->server->config_options[HIDE_FILES_PATTERN]; 2322 | return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 || 2323 | (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0); 2324 | } 2325 | 2326 | static int scan_directory(struct connection *conn, const char *dir, 2327 | struct dir_entry **arr) { 2328 | char path[MAX_PATH_SIZE]; 2329 | struct dir_entry *p; 2330 | struct dirent *dp; 2331 | int arr_size = 0, arr_ind = 0, inc = 100; 2332 | DIR *dirp; 2333 | 2334 | *arr = NULL; 2335 | if ((dirp = (opendir(dir))) == NULL) return 0; 2336 | 2337 | while ((dp = readdir(dirp)) != NULL) { 2338 | // Do not show current dir and hidden files 2339 | if (!strcmp(dp->d_name, ".") || 2340 | !strcmp(dp->d_name, "..") || 2341 | must_hide_file(conn, dp->d_name)) { 2342 | continue; 2343 | } 2344 | mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name); 2345 | 2346 | // Resize the array if nesessary 2347 | if (arr_ind >= arr_size) { 2348 | if ((p = (struct dir_entry *) 2349 | realloc(*arr, (inc + arr_size) * sizeof(**arr))) != NULL) { 2350 | // Memset new chunk to zero, otherwize st_mtime will have garbage which 2351 | // can make strftime() segfault, see 2352 | // http://code.google.com/p/mongoose/issues/detail?id=79 2353 | memset(p + arr_size, 0, sizeof(**arr) * inc); 2354 | 2355 | *arr = p; 2356 | arr_size += inc; 2357 | } 2358 | } 2359 | 2360 | if (arr_ind < arr_size) { 2361 | (*arr)[arr_ind].conn = conn; 2362 | (*arr)[arr_ind].file_name = strdup(dp->d_name); 2363 | stat(path, &(*arr)[arr_ind].st); 2364 | arr_ind++; 2365 | } 2366 | } 2367 | closedir(dirp); 2368 | 2369 | return arr_ind; 2370 | } 2371 | 2372 | static void mg_url_encode(const char *src, char *dst, size_t dst_len) { 2373 | static const char *dont_escape = "._-$,;~()"; 2374 | static const char *hex = "0123456789abcdef"; 2375 | const char *end = dst + dst_len - 1; 2376 | 2377 | for (; *src != '\0' && dst < end; src++, dst++) { 2378 | if (isalnum(*(const unsigned char *) src) || 2379 | strchr(dont_escape, * (const unsigned char *) src) != NULL) { 2380 | *dst = *src; 2381 | } else if (dst + 2 < end) { 2382 | dst[0] = '%'; 2383 | dst[1] = hex[(* (const unsigned char *) src) >> 4]; 2384 | dst[2] = hex[(* (const unsigned char *) src) & 0xf]; 2385 | dst += 2; 2386 | } 2387 | } 2388 | 2389 | *dst = '\0'; 2390 | } 2391 | #endif // !NO_DIRECTORY_LISTING || !MONGOOSE_NO_DAV 2392 | 2393 | #ifndef MONGOOSE_NO_DIRECTORY_LISTING 2394 | 2395 | static void print_dir_entry(const struct dir_entry *de) { 2396 | char size[64], mod[64], href[MAX_PATH_SIZE * 3], chunk[MAX_PATH_SIZE * 4]; 2397 | int64_t fsize = de->st.st_size; 2398 | int is_dir = S_ISDIR(de->st.st_mode), n; 2399 | const char *slash = is_dir ? "/" : ""; 2400 | 2401 | if (is_dir) { 2402 | mg_snprintf(size, sizeof(size), "%s", "[DIRECTORY]"); 2403 | } else { 2404 | // We use (signed) cast below because MSVC 6 compiler cannot 2405 | // convert unsigned __int64 to double. 2406 | if (fsize < 1024) { 2407 | mg_snprintf(size, sizeof(size), "%d", (int) fsize); 2408 | } else if (fsize < 0x100000) { 2409 | mg_snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0); 2410 | } else if (fsize < 0x40000000) { 2411 | mg_snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576); 2412 | } else { 2413 | mg_snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824); 2414 | } 2415 | } 2416 | strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.st_mtime)); 2417 | mg_url_encode(de->file_name, href, sizeof(href)); 2418 | n = mg_snprintf(chunk, sizeof(chunk), 2419 | "<tr><td><a href=\"%s%s%s\">%s%s</a></td>" 2420 | "<td> %s</td><td>  %s</td></tr>\n", 2421 | de->conn->mg_conn.uri, href, slash, de->file_name, slash, 2422 | mod, size); 2423 | write_chunk((struct connection *) de->conn, chunk, n); 2424 | } 2425 | 2426 | // Sort directory entries by size, or name, or modification time. 2427 | // On windows, __cdecl specification is needed in case if project is built 2428 | // with __stdcall convention. qsort always requires __cdels callback. 2429 | static int __cdecl compare_dir_entries(const void *p1, const void *p2) { 2430 | const struct dir_entry *a = (const struct dir_entry *) p1, 2431 | *b = (const struct dir_entry *) p2; 2432 | const char *qs = a->conn->mg_conn.query_string ? 2433 | a->conn->mg_conn.query_string : "na"; 2434 | int cmp_result = 0; 2435 | 2436 | if (S_ISDIR(a->st.st_mode) && !S_ISDIR(b->st.st_mode)) { 2437 | return -1; // Always put directories on top 2438 | } else if (!S_ISDIR(a->st.st_mode) && S_ISDIR(b->st.st_mode)) { 2439 | return 1; // Always put directories on top 2440 | } else if (*qs == 'n') { 2441 | cmp_result = strcmp(a->file_name, b->file_name); 2442 | } else if (*qs == 's') { 2443 | cmp_result = a->st.st_size == b->st.st_size ? 0 : 2444 | a->st.st_size > b->st.st_size ? 1 : -1; 2445 | } else if (*qs == 'd') { 2446 | cmp_result = a->st.st_mtime == b->st.st_mtime ? 0 : 2447 | a->st.st_mtime > b->st.st_mtime ? 1 : -1; 2448 | } 2449 | 2450 | return qs[1] == 'd' ? -cmp_result : cmp_result; 2451 | } 2452 | 2453 | static void send_directory_listing(struct connection *conn, const char *dir) { 2454 | char buf[2000]; 2455 | struct dir_entry *arr = NULL; 2456 | int i, num_entries, sort_direction = conn->mg_conn.query_string != NULL && 2457 | conn->mg_conn.query_string[1] == 'd' ? 'a' : 'd'; 2458 | 2459 | conn->mg_conn.status_code = 200; 2460 | mg_snprintf(buf, sizeof(buf), "%s", 2461 | "HTTP/1.1 200 OK\r\n" 2462 | "Transfer-Encoding: Chunked\r\n" 2463 | "Content-Type: text/html; charset=utf-8\r\n\r\n"); 2464 | spool(&conn->remote_iobuf, buf, strlen(buf)); 2465 | 2466 | mg_snprintf(buf, sizeof(buf), 2467 | "<html><head><title>Index of %s" 2468 | "" 2469 | "

Index of %s

"
2470 |               ""
2471 |               ""
2472 |               ""
2473 |               "",
2474 |               conn->mg_conn.uri, conn->mg_conn.uri,
2475 |               sort_direction, sort_direction, sort_direction);
2476 |   write_chunk(conn, buf, strlen(buf));
2477 | 
2478 |   num_entries = scan_directory(conn, dir, &arr);
2479 |   qsort(arr, num_entries, sizeof(arr[0]), compare_dir_entries);
2480 |   for (i = 0; i < num_entries; i++) {
2481 |     print_dir_entry(&arr[i]);
2482 |     free(arr[i].file_name);
2483 |   }
2484 |   free(arr);
2485 | 
2486 |   write_terminating_chunk(conn);
2487 |   close_local_endpoint(conn);
2488 | }
2489 | #endif  // MONGOOSE_NO_DIRECTORY_LISTING
2490 | 
2491 | #ifndef MONGOOSE_NO_DAV
2492 | static void print_props(struct connection *conn, const char *uri,
2493 |                         file_stat_t *stp) {
2494 |   char mtime[64], buf[MAX_PATH_SIZE + 200];
2495 | 
2496 |   gmt_time_string(mtime, sizeof(mtime), &stp->st_mtime);
2497 |   mg_snprintf(buf, sizeof(buf),
2498 |       ""
2499 |        "%s"
2500 |        ""
2501 |         ""
2502 |          "%s"
2503 |          "%" INT64_FMT ""
2504 |          "%s"
2505 |         ""
2506 |         "HTTP/1.1 200 OK"
2507 |        ""
2508 |       "\n",
2509 |       uri, S_ISDIR(stp->st_mode) ? "" : "",
2510 |       (int64_t) stp->st_size, mtime);
2511 |   spool(&conn->remote_iobuf, buf, strlen(buf));
2512 | }
2513 | 
2514 | static void handle_propfind(struct connection *conn, const char *path,
2515 |                             file_stat_t *stp) {
2516 |   static const char header[] = "HTTP/1.1 207 Multi-Status\r\n"
2517 |     "Connection: close\r\n"
2518 |     "Content-Type: text/xml; charset=utf-8\r\n\r\n"
2519 |     ""
2520 |     "\n";
2521 |   static const char footer[] = "";
2522 |   const char *depth = mg_get_header(&conn->mg_conn, "Depth"),
2523 |         *list_dir = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
2524 | 
2525 |   conn->mg_conn.status_code = 207;
2526 |   spool(&conn->remote_iobuf, header, sizeof(header) - 1);
2527 | 
2528 |   // Print properties for the requested resource itself
2529 |   print_props(conn, conn->mg_conn.uri, stp);
2530 | 
2531 |   // If it is a directory, print directory entries too if Depth is not 0
2532 |   if (S_ISDIR(stp->st_mode) && !mg_strcasecmp(list_dir, "yes") &&
2533 |       (depth == NULL || strcmp(depth, "0") != 0)) {
2534 |     struct dir_entry *arr = NULL;
2535 |     int i, num_entries = scan_directory(conn, path, &arr);
2536 | 
2537 |     for (i = 0; i < num_entries; i++) {
2538 |       char buf[MAX_PATH_SIZE], buf2[sizeof(buf) * 3];
2539 |       struct dir_entry *de = &arr[i];
2540 | 
2541 |       mg_snprintf(buf, sizeof(buf), "%s%s", de->conn->mg_conn.uri,
2542 |                   de->file_name);
2543 |       mg_url_encode(buf, buf2, sizeof(buf2) - 1);
2544 |       print_props(conn, buf, &de->st);
2545 |     }
2546 |   }
2547 | 
2548 |   spool(&conn->remote_iobuf, footer, sizeof(footer) - 1);
2549 |   close_local_endpoint(conn);
2550 | }
2551 | 
2552 | static void handle_mkcol(struct connection *conn, const char *path) {
2553 |   int status_code = 500;
2554 | 
2555 |   if (conn->mg_conn.content_len > 0) {
2556 |     status_code = 415;
2557 |   } else if (!mkdir(path, 0755)) {
2558 |     status_code = 201;
2559 |   } else if (errno == EEXIST) {
2560 |     status_code = 405;
2561 |   } else if (errno == EACCES) {
2562 |     status_code = 403;
2563 |   } else if (errno == ENOENT) {
2564 |     status_code = 409;
2565 |   }
2566 |   send_http_error(conn, status_code, NULL);
2567 | }
2568 | 
2569 | static int remove_directory(const char *dir) {
2570 |   char path[MAX_PATH_SIZE];
2571 |   struct dirent *dp;
2572 |   file_stat_t st;
2573 |   DIR *dirp;
2574 | 
2575 |   if ((dirp = opendir(dir)) == NULL) return 0;
2576 | 
2577 |   while ((dp = readdir(dirp)) != NULL) {
2578 |     if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
2579 |     mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
2580 |     stat(path, &st);
2581 |     if (S_ISDIR(st.st_mode)) {
2582 |       remove_directory(path);
2583 |     } else {
2584 |       remove(path);
2585 |     }
2586 |   }
2587 |   closedir(dirp);
2588 |   rmdir(dir);
2589 | 
2590 |   return 1;
2591 | }
2592 | 
2593 | static void handle_delete(struct connection *conn, const char *path) {
2594 |   file_stat_t st;
2595 | 
2596 |   if (!stat(path, &st)) {
2597 |     send_http_error(conn, 404, NULL);
2598 |   } else if (S_ISDIR(st.st_mode)) {
2599 |     remove_directory(path);
2600 |     send_http_error(conn, 204, NULL);
2601 |   } else if (!remove(path) == 0) {
2602 |     send_http_error(conn, 204, NULL);
2603 |   } else {
2604 |     send_http_error(conn, 423, NULL);
2605 |   }
2606 | }
2607 | 
2608 | // For a given PUT path, create all intermediate subdirectories
2609 | // for given path. Return 0 if the path itself is a directory,
2610 | // or -1 on error, 1 if OK.
2611 | static int put_dir(const char *path) {
2612 |   char buf[MAX_PATH_SIZE];
2613 |   const char *s, *p;
2614 |   file_stat_t st;
2615 | 
2616 |   // Create intermediate directories if they do not exist
2617 |   for (s = p = path + 1; (p = strchr(s, '/')) != NULL; s = ++p) {
2618 |     if (p - path >= (int) sizeof(buf)) return -1; // Buffer overflow
2619 |     memcpy(buf, path, p - path);
2620 |     buf[p - path] = '\0';
2621 |     if (stat(buf, &st) != 0 && mkdir(buf, 0755) != 0) return -1;
2622 |     if (p[1] == '\0') return 0;  // Path is a directory itself
2623 |   }
2624 | 
2625 |   return 1;
2626 | }
2627 | 
2628 | static void handle_put(struct connection *conn, const char *path) {
2629 |   file_stat_t st;
2630 |   const char *range, *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
2631 |   int64_t r1, r2;
2632 |   int rc;
2633 | 
2634 |   conn->mg_conn.status_code = !stat(path, &st) ? 200 : 201;
2635 |   if ((rc = put_dir(path)) == 0) {
2636 |     mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\n\r\n",
2637 |               conn->mg_conn.status_code);
2638 |     close_local_endpoint(conn);
2639 |   } else if (rc == -1) {
2640 |     send_http_error(conn, 500, "put_dir: %s", strerror(errno));
2641 |   } else if (cl_hdr == NULL) {
2642 |     send_http_error(conn, 411, NULL);
2643 | #ifdef _WIN32
2644 |     //On Windows, open() is a macro with 2 params
2645 |   } else if ((conn->endpoint.fd =
2646 |               open(path, O_RDWR | O_CREAT | O_TRUNC)) < 0) {
2647 | #else
2648 |   } else if ((conn->endpoint.fd =
2649 |               open(path, O_RDWR | O_CREAT | O_TRUNC, 0644)) < 0) {
2650 | #endif
2651 |     send_http_error(conn, 500, "open(%s): %s", path, strerror(errno));
2652 |   } else {
2653 |     DBG(("PUT [%s] %d", path, conn->local_iobuf.len));
2654 |     conn->endpoint_type = EP_PUT;
2655 |     set_close_on_exec(conn->endpoint.fd);
2656 |     range = mg_get_header(&conn->mg_conn, "Content-Range");
2657 |     conn->cl = to64(cl_hdr);
2658 |     r1 = r2 = 0;
2659 |     if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
2660 |       conn->mg_conn.status_code = 206;
2661 |       lseek(conn->endpoint.fd, r1, SEEK_SET);
2662 |       conn->cl = r2 > r1 ? r2 - r1 + 1: conn->cl - r1;
2663 |     }
2664 |     mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
2665 |               conn->mg_conn.status_code);
2666 |   }
2667 | }
2668 | 
2669 | static void forward_put_data(struct connection *conn) {
2670 |   struct iobuf *io = &conn->local_iobuf;
2671 |   int n = write(conn->endpoint.fd, io->buf, io->len);
2672 |   if (n > 0) {
2673 |     discard_leading_iobuf_bytes(io, n);
2674 |     conn->cl -= n;
2675 |     if (conn->cl <= 0) {
2676 |       close_local_endpoint(conn);
2677 |     }
2678 |   }
2679 | }
2680 | #endif //  MONGOOSE_NO_DAV
2681 | 
2682 | static void send_options(struct connection *conn) {
2683 |   static const char reply[] = "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, "
2684 |     "CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL\r\nDAV: 1\r\n\r\n";
2685 |   spool(&conn->remote_iobuf, reply, sizeof(reply) - 1);
2686 |   conn->flags |= CONN_SPOOL_DONE;
2687 | }
2688 | 
2689 | #ifndef MONGOOSE_NO_AUTH
2690 | void mg_send_digest_auth_request(struct mg_connection *c) {
2691 |   struct connection *conn = (struct connection *) c;
2692 |   c->status_code = 401;
2693 |   mg_printf(c,
2694 |             "HTTP/1.1 401 Unauthorized\r\n"
2695 |             "WWW-Authenticate: Digest qop=\"auth\", "
2696 |             "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
2697 |             conn->server->config_options[AUTH_DOMAIN],
2698 |             (unsigned long) time(NULL));
2699 | }
2700 | 
2701 | // Use the global passwords file, if specified by auth_gpass option,
2702 | // or search for .htpasswd in the requested directory.
2703 | static FILE *open_auth_file(struct connection *conn, const char *path) {
2704 |   char name[MAX_PATH_SIZE];
2705 |   const char *p, *gpass = conn->server->config_options[GLOBAL_AUTH_FILE];
2706 |   file_stat_t st;
2707 |   FILE *fp = NULL;
2708 | 
2709 |   if (gpass != NULL) {
2710 |     // Use global passwords file
2711 |     fp = fopen(gpass, "r");
2712 |   } else if (!stat(path, &st) && S_ISDIR(st.st_mode)) {
2713 |     mg_snprintf(name, sizeof(name), "%s%c%s", path, '/', PASSWORDS_FILE_NAME);
2714 |     fp = fopen(name, "r");
2715 |   } else {
2716 |     // Try to find .htpasswd in requested directory.
2717 |     if ((p = strrchr(path, '/')) == NULL) p = path;
2718 |     mg_snprintf(name, sizeof(name), "%.*s%c%s",
2719 |                 (int) (p - path), path, '/', PASSWORDS_FILE_NAME);
2720 |     fp = fopen(name, "r");
2721 |   }
2722 | 
2723 |   return fp;
2724 | }
2725 | 
2726 | #if !defined(HAVE_MD5) && !defined(MONGOOSE_NO_AUTH)
2727 | typedef struct MD5Context {
2728 |   uint32_t buf[4];
2729 |   uint32_t bits[2];
2730 |   unsigned char in[64];
2731 | } MD5_CTX;
2732 | 
2733 | static void byteReverse(unsigned char *buf, unsigned longs) {
2734 |   uint32_t t;
2735 | 
2736 |   // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
2737 |   if (is_big_endian()) {
2738 |     do {
2739 |       t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
2740 |         ((unsigned) buf[1] << 8 | buf[0]);
2741 |       * (uint32_t *) buf = t;
2742 |       buf += 4;
2743 |     } while (--longs);
2744 |   }
2745 | }
2746 | 
2747 | #define F1(x, y, z) (z ^ (x & (y ^ z)))
2748 | #define F2(x, y, z) F1(z, x, y)
2749 | #define F3(x, y, z) (x ^ y ^ z)
2750 | #define F4(x, y, z) (y ^ (x | ~z))
2751 | 
2752 | #define MD5STEP(f, w, x, y, z, data, s) \
2753 |   ( w += f(x, y, z) + data,  w = w<>(32-s),  w += x )
2754 | 
2755 | // Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
2756 | // initialization constants.
2757 | static void MD5Init(MD5_CTX *ctx) {
2758 |   ctx->buf[0] = 0x67452301;
2759 |   ctx->buf[1] = 0xefcdab89;
2760 |   ctx->buf[2] = 0x98badcfe;
2761 |   ctx->buf[3] = 0x10325476;
2762 | 
2763 |   ctx->bits[0] = 0;
2764 |   ctx->bits[1] = 0;
2765 | }
2766 | 
2767 | static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
2768 |   register uint32_t a, b, c, d;
2769 | 
2770 |   a = buf[0];
2771 |   b = buf[1];
2772 |   c = buf[2];
2773 |   d = buf[3];
2774 | 
2775 |   MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
2776 |   MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
2777 |   MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
2778 |   MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
2779 |   MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
2780 |   MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
2781 |   MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
2782 |   MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
2783 |   MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
2784 |   MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
2785 |   MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
2786 |   MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
2787 |   MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
2788 |   MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
2789 |   MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
2790 |   MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
2791 | 
2792 |   MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
2793 |   MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
2794 |   MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
2795 |   MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
2796 |   MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
2797 |   MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
2798 |   MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
2799 |   MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
2800 |   MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
2801 |   MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
2802 |   MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
2803 |   MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
2804 |   MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
2805 |   MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
2806 |   MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
2807 |   MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
2808 | 
2809 |   MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
2810 |   MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
2811 |   MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
2812 |   MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
2813 |   MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
2814 |   MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
2815 |   MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
2816 |   MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
2817 |   MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
2818 |   MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
2819 |   MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
2820 |   MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
2821 |   MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
2822 |   MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
2823 |   MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
2824 |   MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
2825 | 
2826 |   MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
2827 |   MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
2828 |   MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
2829 |   MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
2830 |   MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
2831 |   MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
2832 |   MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
2833 |   MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
2834 |   MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
2835 |   MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
2836 |   MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
2837 |   MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
2838 |   MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
2839 |   MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
2840 |   MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
2841 |   MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
2842 | 
2843 |   buf[0] += a;
2844 |   buf[1] += b;
2845 |   buf[2] += c;
2846 |   buf[3] += d;
2847 | }
2848 | 
2849 | static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
2850 |   uint32_t t;
2851 | 
2852 |   t = ctx->bits[0];
2853 |   if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
2854 |     ctx->bits[1]++;
2855 |   ctx->bits[1] += len >> 29;
2856 | 
2857 |   t = (t >> 3) & 0x3f;
2858 | 
2859 |   if (t) {
2860 |     unsigned char *p = (unsigned char *) ctx->in + t;
2861 | 
2862 |     t = 64 - t;
2863 |     if (len < t) {
2864 |       memcpy(p, buf, len);
2865 |       return;
2866 |     }
2867 |     memcpy(p, buf, t);
2868 |     byteReverse(ctx->in, 16);
2869 |     MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2870 |     buf += t;
2871 |     len -= t;
2872 |   }
2873 | 
2874 |   while (len >= 64) {
2875 |     memcpy(ctx->in, buf, 64);
2876 |     byteReverse(ctx->in, 16);
2877 |     MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2878 |     buf += 64;
2879 |     len -= 64;
2880 |   }
2881 | 
2882 |   memcpy(ctx->in, buf, len);
2883 | }
2884 | 
2885 | static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
2886 |   unsigned count;
2887 |   unsigned char *p;
2888 |   uint32_t *a;
2889 | 
2890 |   count = (ctx->bits[0] >> 3) & 0x3F;
2891 | 
2892 |   p = ctx->in + count;
2893 |   *p++ = 0x80;
2894 |   count = 64 - 1 - count;
2895 |   if (count < 8) {
2896 |     memset(p, 0, count);
2897 |     byteReverse(ctx->in, 16);
2898 |     MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2899 |     memset(ctx->in, 0, 56);
2900 |   } else {
2901 |     memset(p, 0, count - 8);
2902 |   }
2903 |   byteReverse(ctx->in, 14);
2904 | 
2905 |   a = (uint32_t *)ctx->in;
2906 |   a[14] = ctx->bits[0];
2907 |   a[15] = ctx->bits[1];
2908 | 
2909 |   MD5Transform(ctx->buf, (uint32_t *) ctx->in);
2910 |   byteReverse((unsigned char *) ctx->buf, 4);
2911 |   memcpy(digest, ctx->buf, 16);
2912 |   memset((char *) ctx, 0, sizeof(*ctx));
2913 | }
2914 | #endif // !HAVE_MD5
2915 | 
2916 | 
2917 | 
2918 | // Stringify binary data. Output buffer must be twice as big as input,
2919 | // because each byte takes 2 bytes in string representation
2920 | static void bin2str(char *to, const unsigned char *p, size_t len) {
2921 |   static const char *hex = "0123456789abcdef";
2922 | 
2923 |   for (; len--; p++) {
2924 |     *to++ = hex[p[0] >> 4];
2925 |     *to++ = hex[p[0] & 0x0f];
2926 |   }
2927 |   *to = '\0';
2928 | }
2929 | 
2930 | // Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
2931 | char *mg_md5(char buf[33], ...) {
2932 |   unsigned char hash[16];
2933 |   const char *p;
2934 |   va_list ap;
2935 |   MD5_CTX ctx;
2936 | 
2937 |   MD5Init(&ctx);
2938 | 
2939 |   va_start(ap, buf);
2940 |   while ((p = va_arg(ap, const char *)) != NULL) {
2941 |     MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
2942 |   }
2943 |   va_end(ap);
2944 | 
2945 |   MD5Final(hash, &ctx);
2946 |   bin2str(buf, hash, sizeof(hash));
2947 |   return buf;
2948 | }
2949 | 
2950 | // Check the user's password, return 1 if OK
2951 | static int check_password(const char *method, const char *ha1, const char *uri,
2952 |                           const char *nonce, const char *nc, const char *cnonce,
2953 |                           const char *qop, const char *response) {
2954 |   char ha2[32 + 1], expected_response[32 + 1];
2955 | 
2956 | #if 0
2957 |   // Check for authentication timeout
2958 |   if ((unsigned long) time(NULL) - (unsigned long) to64(nonce) > 3600) {
2959 |     return 0;
2960 |   }
2961 | #endif
2962 | 
2963 |   mg_md5(ha2, method, ":", uri, NULL);
2964 |   mg_md5(expected_response, ha1, ":", nonce, ":", nc,
2965 |       ":", cnonce, ":", qop, ":", ha2, NULL);
2966 | 
2967 |   return mg_strcasecmp(response, expected_response) == 0;
2968 | }
2969 | 
2970 | 
2971 | // Authorize against the opened passwords file. Return 1 if authorized.
2972 | int mg_authorize_digest(struct mg_connection *c, FILE *fp) {
2973 |   struct connection *conn = (struct connection *) c;
2974 |   const char *hdr;
2975 |   char line[256], f_user[256], ha1[256], f_domain[256], user[100], nonce[100],
2976 |        uri[MAX_REQUEST_SIZE], cnonce[100], resp[100], qop[100], nc[100];
2977 | 
2978 |   if (c == NULL || fp == NULL) return 0;
2979 |   if ((hdr = mg_get_header(c, "Authorization")) == NULL ||
2980 |       mg_strncasecmp(hdr, "Digest ", 7) != 0) return 0;
2981 |   if (!mg_parse_header(hdr, "username", user, sizeof(user))) return 0;
2982 |   if (!mg_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce))) return 0;
2983 |   if (!mg_parse_header(hdr, "response", resp, sizeof(resp))) return 0;
2984 |   if (!mg_parse_header(hdr, "uri", uri, sizeof(uri))) return 0;
2985 |   if (!mg_parse_header(hdr, "qop", qop, sizeof(qop))) return 0;
2986 |   if (!mg_parse_header(hdr, "nc", nc, sizeof(nc))) return 0;
2987 |   if (!mg_parse_header(hdr, "nonce", nonce, sizeof(nonce))) return 0;
2988 | 
2989 |   while (fgets(line, sizeof(line), fp) != NULL) {
2990 |     if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) == 3 &&
2991 |         !strcmp(user, f_user) &&
2992 |         // NOTE(lsm): due to a bug in MSIE, we do not compare URIs
2993 |         !strcmp(conn->server->config_options[AUTH_DOMAIN], f_domain))
2994 |       return check_password(c->request_method, ha1, uri,
2995 |                             nonce, nc, cnonce, qop, resp);
2996 |   }
2997 |   return 0;
2998 | }
2999 | 
3000 | 
3001 | // Return 1 if request is authorised, 0 otherwise.
3002 | static int is_authorized(struct connection *conn, const char *path) {
3003 |   FILE *fp;
3004 |   int authorized = 1;
3005 | 
3006 |   if ((fp = open_auth_file(conn, path)) != NULL) {
3007 |     authorized = mg_authorize_digest(&conn->mg_conn, fp);
3008 |     fclose(fp);
3009 |   }
3010 | 
3011 |   return authorized;
3012 | }
3013 | 
3014 | static int is_authorized_for_dav(struct connection *conn) {
3015 |   const char *auth_file = conn->server->config_options[DAV_AUTH_FILE];
3016 |   FILE *fp;
3017 |   int authorized = 0;
3018 | 
3019 |   if (auth_file != NULL && (fp = fopen(auth_file, "r")) != NULL) {
3020 |     authorized = mg_authorize_digest(&conn->mg_conn, fp);
3021 |     fclose(fp);
3022 |   }
3023 | 
3024 |   return authorized;
3025 | }
3026 | 
3027 | static int is_dav_mutation(const struct connection *conn) {
3028 |   const char *s = conn->mg_conn.request_method;
3029 |   return s && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
3030 |                !strcmp(s, "MKCOL"));
3031 | }
3032 | #endif // MONGOOSE_NO_AUTH
3033 | 
3034 | int parse_header(const char *str, int str_len, const char *var_name, char *buf,
3035 |                  size_t buf_size) {
3036 |   int ch = ' ', len = 0, n = strlen(var_name);
3037 |   const char *p, *end = str + str_len, *s = NULL;
3038 | 
3039 |   if (buf != NULL && buf_size > 0) buf[0] = '\0';
3040 | 
3041 |   // Find where variable starts
3042 |   for (s = str; s != NULL && s + n < end; s++) {
3043 |     if ((s == str || s[-1] == ' ') && s[n] == '=' &&
3044 |         !memcmp(s, var_name, n)) break;
3045 |   }
3046 | 
3047 |   if (s != NULL && &s[n + 1] < end) {
3048 |     s += n + 1;
3049 |     if (*s == '"' || *s == '\'') ch = *s++;
3050 |     p = s;
3051 |     while (p < end && p[0] != ch && len < (int) buf_size) {
3052 |       if (p[0] == '\\' && p[1] == ch) p++;
3053 |       buf[len++] = *p++;
3054 |     }
3055 |     if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
3056 |       len = 0;
3057 |     } else {
3058 |       if (len > 0 && s[len - 1] == ',') len--;
3059 |       if (len > 0 && s[len - 1] == ';') len--;
3060 |       buf[len] = '\0';
3061 |     }
3062 |   }
3063 | 
3064 |   return len;
3065 | }
3066 | 
3067 | int mg_parse_header(const char *s, const char *var_name, char *buf,
3068 |                     size_t buf_size) {
3069 |   return parse_header(s, s == NULL ? 0 : strlen(s), var_name, buf, buf_size);
3070 | }
3071 | 
3072 | #ifdef MONGOOSE_USE_LUA
3073 | #include "lua_5.2.1.h"
3074 | 
3075 | #ifdef _WIN32
3076 | static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
3077 |                   int offset) {
3078 |   HANDLE fh = (HANDLE) _get_osfhandle(fd);
3079 |   HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
3080 |   void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
3081 |   CloseHandle(mh);
3082 |   return p;
3083 | }
3084 | #define munmap(x, y)  UnmapViewOfFile(x)
3085 | #define MAP_FAILED NULL
3086 | #define MAP_PRIVATE 0
3087 | #define PROT_READ 0
3088 | #else
3089 | #include 
3090 | #endif
3091 | 
3092 | static void reg_string(struct lua_State *L, const char *name, const char *val) {
3093 |   lua_pushstring(L, name);
3094 |   lua_pushstring(L, val);
3095 |   lua_rawset(L, -3);
3096 | }
3097 | 
3098 | static void reg_int(struct lua_State *L, const char *name, int val) {
3099 |   lua_pushstring(L, name);
3100 |   lua_pushinteger(L, val);
3101 |   lua_rawset(L, -3);
3102 | }
3103 | 
3104 | static void reg_function(struct lua_State *L, const char *name,
3105 |                          lua_CFunction func, struct mg_connection *conn) {
3106 |   lua_pushstring(L, name);
3107 |   lua_pushlightuserdata(L, conn);
3108 |   lua_pushcclosure(L, func, 1);
3109 |   lua_rawset(L, -3);
3110 | }
3111 | 
3112 | static int lua_write(lua_State *L) {
3113 |   int i, num_args;
3114 |   const char *str;
3115 |   size_t size;
3116 |   struct mg_connection *conn = (struct mg_connection *)
3117 |     lua_touserdata(L, lua_upvalueindex(1));
3118 | 
3119 |   num_args = lua_gettop(L);
3120 |   for (i = 1; i <= num_args; i++) {
3121 |     if (lua_isstring(L, i)) {
3122 |       str = lua_tolstring(L, i, &size);
3123 |       mg_write(conn, str, size);
3124 |     }
3125 |   }
3126 | 
3127 |   return 0;
3128 | }
3129 | 
3130 | static int lsp_sock_close(lua_State *L) {
3131 |   if (lua_gettop(L) > 0 && lua_istable(L, -1)) {
3132 |     lua_getfield(L, -1, "sock");
3133 |     closesocket((sock_t) lua_tonumber(L, -1));
3134 |   } else {
3135 |     return luaL_error(L, "invalid :close() call");
3136 |   }
3137 |   return 1;
3138 | }
3139 | 
3140 | static int lsp_sock_recv(lua_State *L) {
3141 |   char buf[2000];
3142 |   int n;
3143 | 
3144 |   if (lua_gettop(L) > 0 && lua_istable(L, -1)) {
3145 |     lua_getfield(L, -1, "sock");
3146 |     n = recv((sock_t) lua_tonumber(L, -1), buf, sizeof(buf), 0);
3147 |     if (n <= 0) {
3148 |       lua_pushnil(L);
3149 |     } else {
3150 |       lua_pushlstring(L, buf, n);
3151 |     }
3152 |   } else {
3153 |     return luaL_error(L, "invalid :close() call");
3154 |   }
3155 |   return 1;
3156 | }
3157 | 
3158 | static int lsp_sock_send(lua_State *L) {
3159 |   const char *buf;
3160 |   size_t len, sent = 0;
3161 |   int n, sock;
3162 | 
3163 |   if (lua_gettop(L) > 1 && lua_istable(L, -2) && lua_isstring(L, -1)) {
3164 |     buf = lua_tolstring(L, -1, &len);
3165 |     lua_getfield(L, -2, "sock");
3166 |     sock = (int) lua_tonumber(L, -1);
3167 |     while (sent < len) {
3168 |       if ((n = send(sock, buf + sent, len - sent, 0)) <= 0) break;
3169 |       sent += n;
3170 |     }
3171 |     lua_pushnumber(L, sent);
3172 |   } else {
3173 |     return luaL_error(L, "invalid :close() call");
3174 |   }
3175 |   return 1;
3176 | }
3177 | 
3178 | static const struct luaL_Reg luasocket_methods[] = {
3179 |   {"close", lsp_sock_close},
3180 |   {"send", lsp_sock_send},
3181 |   {"recv", lsp_sock_recv},
3182 |   {NULL, NULL}
3183 | };
3184 | 
3185 | static sock_t conn2(const char *host, int port) {
3186 |   struct sockaddr_in sin;
3187 |   struct hostent *he = NULL;
3188 |   sock_t sock = INVALID_SOCKET;
3189 | 
3190 |   if (host != NULL &&
3191 |       (he = gethostbyname(host)) != NULL &&
3192 |     (sock = socket(PF_INET, SOCK_STREAM, 0)) != INVALID_SOCKET) {
3193 |     set_close_on_exec(sock);
3194 |     sin.sin_family = AF_INET;
3195 |     sin.sin_port = htons((uint16_t) port);
3196 |     sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
3197 |     if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
3198 |       closesocket(sock);
3199 |       sock = INVALID_SOCKET;
3200 |     }
3201 |   }
3202 |   return sock;
3203 | }
3204 | 
3205 | static int lsp_connect(lua_State *L) {
3206 |   sock_t sock;
3207 | 
3208 |   if (lua_isstring(L, -2) && lua_isnumber(L, -1)) {
3209 |     sock = conn2(lua_tostring(L, -2), (int) lua_tonumber(L, -1));
3210 |     if (sock == INVALID_SOCKET) {
3211 |       lua_pushnil(L);
3212 |     } else {
3213 |       lua_newtable(L);
3214 |       reg_int(L, "sock", sock);
3215 |       reg_string(L, "host", lua_tostring(L, -4));
3216 |       luaL_getmetatable(L, "luasocket");
3217 |       lua_setmetatable(L, -2);
3218 |     }
3219 |   } else {
3220 |     return luaL_error(L, "connect(host,port): invalid parameter given.");
3221 |   }
3222 |   return 1;
3223 | }
3224 | 
3225 | static void prepare_lua_environment(struct mg_connection *ri, lua_State *L) {
3226 |   extern void luaL_openlibs(lua_State *);
3227 |   int i;
3228 | 
3229 |   luaL_openlibs(L);
3230 | #ifdef MONGOOSE_USE_LUA_SQLITE3
3231 |   { extern int luaopen_lsqlite3(lua_State *); luaopen_lsqlite3(L); }
3232 | #endif
3233 | 
3234 |   luaL_newmetatable(L, "luasocket");
3235 |   lua_pushliteral(L, "__index");
3236 |   luaL_newlib(L, luasocket_methods);
3237 |   lua_rawset(L, -3);
3238 |   lua_pop(L, 1);
3239 |   lua_register(L, "connect", lsp_connect);
3240 | 
3241 |   if (ri == NULL) return;
3242 | 
3243 |   // Register mg module
3244 |   lua_newtable(L);
3245 |   reg_function(L, "write", lua_write, ri);
3246 | 
3247 |   // Export request_info
3248 |   lua_pushstring(L, "request_info");
3249 |   lua_newtable(L);
3250 |   reg_string(L, "request_method", ri->request_method);
3251 |   reg_string(L, "uri", ri->uri);
3252 |   reg_string(L, "http_version", ri->http_version);
3253 |   reg_string(L, "query_string", ri->query_string);
3254 |   reg_string(L, "remote_ip", ri->remote_ip);
3255 |   reg_int(L, "remote_port", ri->remote_port);
3256 |   lua_pushstring(L, "content");
3257 |   lua_pushlstring(L, ri->content == NULL ? "" : ri->content, 0);
3258 |   lua_rawset(L, -3);
3259 |   reg_int(L, "content_len", ri->content_len);
3260 |   reg_int(L, "num_headers", ri->num_headers);
3261 |   lua_pushstring(L, "http_headers");
3262 |   lua_newtable(L);
3263 |   for (i = 0; i < ri->num_headers; i++) {
3264 |     reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);
3265 |   }
3266 |   lua_rawset(L, -3);
3267 |   lua_rawset(L, -3);
3268 | 
3269 |   lua_setglobal(L, "mg");
3270 | 
3271 |   // Register default mg.onerror function
3272 |   (void) luaL_dostring(L, "mg.onerror = function(e) mg.write('\\nLua "
3273 |                        "error:\\n', debug.traceback(e, 1)) end");
3274 | }
3275 | 
3276 | static int lua_error_handler(lua_State *L) {
3277 |   const char *error_msg =  lua_isstring(L, -1) ?  lua_tostring(L, -1) : "?\n";
3278 | 
3279 |   lua_getglobal(L, "mg");
3280 |   if (!lua_isnil(L, -1)) {
3281 |     lua_getfield(L, -1, "write");   // call mg.write()
3282 |     lua_pushstring(L, error_msg);
3283 |     lua_pushliteral(L, "\n");
3284 |     lua_call(L, 2, 0);
3285 |     (void) luaL_dostring(L, "mg.write(debug.traceback(), '\\n')");
3286 |   } else {
3287 |     printf("Lua error: [%s]\n", error_msg);
3288 |     (void) luaL_dostring(L, "print(debug.traceback(), '\\n')");
3289 |   }
3290 |   // TODO(lsm): leave the stack balanced
3291 | 
3292 |   return 0;
3293 | }
3294 | 
3295 | static void lsp(struct connection *conn, const char *p, int len, lua_State *L) {
3296 |   int i, j, pos = 0;
3297 | 
3298 |   for (i = 0; i < len; i++) {
3299 |     if (p[i] == '<' && p[i + 1] == '?') {
3300 |       for (j = i + 1; j < len ; j++) {
3301 |         if (p[j] == '?' && p[j + 1] == '>') {
3302 |           mg_write(&conn->mg_conn, p + pos, i - pos);
3303 |           if (luaL_loadbuffer(L, p + (i + 2), j - (i + 2), "") == LUA_OK) {
3304 |             lua_pcall(L, 0, LUA_MULTRET, 0);
3305 |           }
3306 |           pos = j + 2;
3307 |           i = pos - 1;
3308 |           break;
3309 |         }
3310 |       }
3311 |     }
3312 |   }
3313 |   if (i > pos) mg_write(&conn->mg_conn, p + pos, i - pos);
3314 | }
3315 | 
3316 | static void handle_lsp_request(struct connection *conn, const char *path,
3317 |                                file_stat_t *st) {
3318 |   void *p = NULL;
3319 |   lua_State *L = NULL;
3320 |   FILE *fp = NULL;
3321 | 
3322 |   if ((fp = fopen(path, "r")) == NULL ||
3323 |       (p = mmap(NULL, st->st_size, PROT_READ, MAP_PRIVATE,
3324 |                 fileno(fp), 0)) == MAP_FAILED ||
3325 |       (L = luaL_newstate()) == NULL) {
3326 |     send_http_error(conn, 500, "mmap(%s): %s", path, strerror(errno));
3327 |   } else {
3328 |     // We're not sending HTTP headers here, Lua page must do it.
3329 |     prepare_lua_environment(&conn->mg_conn, L);
3330 |     lua_pushcclosure(L, &lua_error_handler, 0);
3331 |     lua_pushglobaltable(L);
3332 |     lsp(conn, p, (int) st->st_size, L);
3333 |     close_local_endpoint(conn);
3334 |   }
3335 | 
3336 |   if (L != NULL) lua_close(L);
3337 |   if (p != NULL) munmap(p, st->st_size);
3338 |   if (fp != NULL) fclose(fp);
3339 | }
3340 | #endif // MONGOOSE_USE_LUA
3341 | 
3342 | static void open_local_endpoint(struct connection *conn) {
3343 | #ifndef MONGOOSE_NO_FILESYSTEM
3344 |   static const char lua_pat[] = LUA_SCRIPT_PATTERN;
3345 |   file_stat_t st;
3346 |   char path[MAX_PATH_SIZE];
3347 |   int exists = 0, is_directory = 0;
3348 |   const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
3349 |   const char *dir_lst = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
3350 | #endif
3351 | 
3352 |   // Call URI handler if one is registered for this URI
3353 |   conn->endpoint.uh = find_uri_handler(conn->server, conn->mg_conn.uri);
3354 |   if (conn->endpoint.uh != NULL) {
3355 |     conn->endpoint_type = EP_USER;
3356 |     conn->mg_conn.content = conn->local_iobuf.buf;
3357 | #if MONGOOSE_USE_POST_SIZE_LIMIT > 1
3358 |     {
3359 |       const char *cl = mg_get_header(&conn->mg_conn, "Content-Length");
3360 |       if (!strcmp(conn->mg_conn.request_method, "POST") &&
3361 |           (cl == NULL || to64(cl) > USE_POST_SIZE_LIMIT)) {
3362 |         send_http_error(conn, 500, "POST size > %zu",
3363 |                         (size_t) USE_POST_SIZE_LIMIT);
3364 |       }
3365 |     }
3366 | #endif
3367 |     return;
3368 |   }
3369 | 
3370 | #ifdef MONGOOSE_NO_FILESYSTEM
3371 |   send_http_error(conn, 404, NULL);
3372 | #else
3373 |   exists = convert_uri_to_file_name(conn, path, sizeof(path), &st);
3374 |   is_directory = S_ISDIR(st.st_mode);
3375 | 
3376 |   if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
3377 |     send_options(conn);
3378 |   } else if (conn->server->config_options[DOCUMENT_ROOT] == NULL) {
3379 |     send_http_error(conn, 404, NULL);
3380 | #ifndef MONGOOSE_NO_AUTH
3381 |   } else if ((!is_dav_mutation(conn) && !is_authorized(conn, path)) ||
3382 |              (is_dav_mutation(conn) && !is_authorized_for_dav(conn))) {
3383 |     mg_send_digest_auth_request(&conn->mg_conn);
3384 |     close_local_endpoint(conn);
3385 | #endif
3386 | #ifndef MONGOOSE_NO_DAV
3387 |   } else if (!strcmp(conn->mg_conn.request_method, "PROPFIND")) {
3388 |     handle_propfind(conn, path, &st);
3389 |   } else if (!strcmp(conn->mg_conn.request_method, "MKCOL")) {
3390 |     handle_mkcol(conn, path);
3391 |   } else if (!strcmp(conn->mg_conn.request_method, "DELETE")) {
3392 |     handle_delete(conn, path);
3393 |   } else if (!strcmp(conn->mg_conn.request_method, "PUT")) {
3394 |     handle_put(conn, path);
3395 | #endif
3396 |   } else if (!exists || must_hide_file(conn, path)) {
3397 |     send_http_error(conn, 404, NULL);
3398 |   } else if (is_directory &&
3399 |              conn->mg_conn.uri[strlen(conn->mg_conn.uri) - 1] != '/') {
3400 |     conn->mg_conn.status_code = 301;
3401 |     mg_printf(&conn->mg_conn, "HTTP/1.1 301 Moved Permanently\r\n"
3402 |               "Location: %s/\r\n\r\n", conn->mg_conn.uri);
3403 |     close_local_endpoint(conn);
3404 |   } else if (is_directory && !find_index_file(conn, path, sizeof(path), &st)) {
3405 |     if (!mg_strcasecmp(dir_lst, "yes")) {
3406 | #ifndef MONGOOSE_NO_DIRECTORY_LISTING
3407 |       send_directory_listing(conn, path);
3408 | #else
3409 |       send_http_error(conn, 501, NULL);
3410 | #endif
3411 |     } else {
3412 |       send_http_error(conn, 403, NULL);
3413 |     }
3414 |   } else if (match_prefix(lua_pat, sizeof(lua_pat) - 1, path) > 0) {
3415 | #ifdef MONGOOSE_USE_LUA
3416 |     handle_lsp_request(conn, path, &st);
3417 | #else
3418 |     send_http_error(conn, 501, NULL);
3419 | #endif
3420 |   } else if (match_prefix(cgi_pat, strlen(cgi_pat), path) > 0) {
3421 | #if !defined(MONGOOSE_NO_CGI)
3422 |     open_cgi_endpoint(conn, path);
3423 | #else
3424 |     send_http_error(conn, 501, NULL);
3425 | #endif // !MONGOOSE_NO_CGI
3426 |   } else if (is_not_modified(conn, &st)) {
3427 |     send_http_error(conn, 304, NULL);
3428 |   } else if ((conn->endpoint.fd = open(path, O_RDONLY | O_BINARY)) != -1) {
3429 |     // O_BINARY is required for Windows, otherwise in default text mode
3430 |     // two bytes \r\n will be read as one.
3431 |     open_file_endpoint(conn, path, &st);
3432 |   } else {
3433 |     send_http_error(conn, 404, NULL);
3434 |   }
3435 | #endif  // MONGOOSE_NO_FILESYSTEM
3436 | }
3437 | 
3438 | static void send_continue_if_expected(struct connection *conn) {
3439 |   static const char expect_response[] = "HTTP/1.1 100 Continue\r\n\r\n";
3440 |   const char *expect_hdr = mg_get_header(&conn->mg_conn, "Expect");
3441 | 
3442 |   if (expect_hdr != NULL && !mg_strcasecmp(expect_hdr, "100-continue")) {
3443 |     spool(&conn->remote_iobuf, expect_response, sizeof(expect_response) - 1);
3444 |   }
3445 | }
3446 | 
3447 | static int is_valid_uri(const char *uri) {
3448 |   // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
3449 |   // URI can be an asterisk (*) or should start with slash.
3450 |   return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
3451 | }
3452 | 
3453 | static void try_http_parse_and_set_content_length(struct connection *conn) {
3454 |   struct iobuf *io = &conn->local_iobuf;
3455 | 
3456 |   if (conn->request_len == 0 &&
3457 |       (conn->request_len = get_request_len(io->buf, io->len)) > 0) {
3458 |     // If request is buffered in, remove it from the iobuf. This is because
3459 |     // iobuf could be reallocated, and pointers in parsed request could
3460 |     // become invalid.
3461 |     conn->request = (char *) malloc(conn->request_len);
3462 |     memcpy(conn->request, io->buf, conn->request_len);
3463 |     DBG(("%p [%.*s]", conn, conn->request_len, conn->request));
3464 |     discard_leading_iobuf_bytes(io, conn->request_len);
3465 |     conn->request_len = parse_http_message(conn->request, conn->request_len,
3466 |                                            &conn->mg_conn);
3467 |     if (conn->request_len > 0) {
3468 |       const char *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
3469 |       conn->cl = cl_hdr == NULL ? 0 : to64(cl_hdr);
3470 |       conn->mg_conn.content_len = (long int) conn->cl;
3471 |     }
3472 |   }
3473 | }
3474 | 
3475 | static void process_request(struct connection *conn) {
3476 |   struct iobuf *io = &conn->local_iobuf;
3477 | 
3478 |   try_http_parse_and_set_content_length(conn);
3479 |   DBG(("%p %d %d %d [%.*s]", conn, conn->request_len, io->len, conn->flags,
3480 |        io->len, io->buf));
3481 |   if (conn->request_len < 0 ||
3482 |       (conn->request_len > 0 && !is_valid_uri(conn->mg_conn.uri))) {
3483 |     send_http_error(conn, 400, NULL);
3484 |   } else if (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE) {
3485 |     send_http_error(conn, 413, NULL);
3486 |   } else if (conn->request_len > 0 &&
3487 |              strcmp(conn->mg_conn.http_version, "1.0") != 0 &&
3488 |              strcmp(conn->mg_conn.http_version, "1.1") != 0) {
3489 |     send_http_error(conn, 505, NULL);
3490 |   } else if (conn->request_len > 0 && conn->endpoint_type == EP_NONE) {
3491 | #ifndef MONGOOSE_NO_WEBSOCKET
3492 |     send_websocket_handshake_if_requested(&conn->mg_conn);
3493 | #endif
3494 |     send_continue_if_expected(conn);
3495 |     open_local_endpoint(conn);
3496 |   }
3497 | 
3498 | #ifndef MONGOOSE_NO_CGI
3499 |   if (conn->endpoint_type == EP_CGI && io->len > 0) {
3500 |     forward_post_data(conn);
3501 |   }
3502 | #endif
3503 |   if (conn->endpoint_type == EP_USER) {
3504 |     call_uri_handler_if_data_is_buffered(conn);
3505 |   }
3506 | #ifndef MONGOOSE_NO_DAV
3507 |   if (conn->endpoint_type == EP_PUT && io->len > 0) {
3508 |     forward_put_data(conn);
3509 |   }
3510 | #endif
3511 | }
3512 | 
3513 | static void call_http_client_handler(struct connection *conn, int code) {
3514 |   conn->mg_conn.status_code = code;
3515 |   // For responses without Content-Lengh, use the whole buffer
3516 |   if (conn->cl == 0 && code == MG_DOWNLOAD_SUCCESS) {
3517 |     conn->mg_conn.content_len = conn->local_iobuf.len;
3518 |   }
3519 |   conn->mg_conn.content = conn->local_iobuf.buf;
3520 |   if (conn->handler(&conn->mg_conn) || code == MG_CONNECT_FAILURE ||
3521 |       code == MG_DOWNLOAD_FAILURE) {
3522 |     conn->flags |= CONN_CLOSE;
3523 |   }
3524 |   discard_leading_iobuf_bytes(&conn->local_iobuf, conn->mg_conn.content_len);
3525 |   conn->flags = conn->mg_conn.status_code = 0;
3526 |   conn->cl = conn->num_bytes_sent = conn->request_len = 0;
3527 |   free(conn->request);
3528 |   conn->request = NULL;
3529 | }
3530 | 
3531 | static void process_response(struct connection *conn) {
3532 |   struct iobuf *io = &conn->local_iobuf;
3533 | 
3534 |   try_http_parse_and_set_content_length(conn);
3535 |   DBG(("%p %d %d [%.*s]", conn, conn->request_len, io->len,
3536 |        io->len > 40 ? 40 : io->len, io->buf));
3537 |   if (conn->request_len < 0 ||
3538 |       (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE)) {
3539 |     call_http_client_handler(conn, MG_DOWNLOAD_FAILURE);
3540 |   }
3541 |   if (io->len >= conn->cl) {
3542 |     call_http_client_handler(conn, MG_DOWNLOAD_SUCCESS);
3543 |   }
3544 | }
3545 | 
3546 | static void read_from_socket(struct connection *conn) {
3547 |   char buf[IOBUF_SIZE];
3548 |   int n = 0;
3549 | 
3550 |   if (conn->endpoint_type == EP_CLIENT && conn->flags & CONN_CONNECTING) {
3551 |     callback_http_client_on_connect(conn);
3552 |     return;
3553 |   }
3554 | 
3555 | #ifdef MONGOOSE_USE_SSL
3556 |   if (conn->ssl != NULL) {
3557 |     if (conn->flags & CONN_SSL_HANDS_SHAKEN) {
3558 |       n = SSL_read(conn->ssl, buf, sizeof(buf));
3559 |     } else {
3560 |       if (SSL_accept(conn->ssl) == 1) {
3561 |         conn->flags |= CONN_SSL_HANDS_SHAKEN;
3562 |       }
3563 |       return;
3564 |     }
3565 |   } else
3566 | #endif
3567 |   {
3568 |     n = recv(conn->client_sock, buf, sizeof(buf), 0);
3569 |   }
3570 | 
3571 |   DBG(("%p %d %d (1)", conn, n, conn->flags));
3572 |   if (is_error(n)) {
3573 |     if (conn->endpoint_type == EP_CLIENT && conn->local_iobuf.len > 0) {
3574 |       call_http_client_handler(conn, MG_DOWNLOAD_SUCCESS);
3575 |     }
3576 |     conn->flags |= CONN_CLOSE;
3577 |   } else if (n > 0) {
3578 |     spool(&conn->local_iobuf, buf, n);
3579 |     if (conn->endpoint_type == EP_CLIENT) {
3580 |       process_response(conn);
3581 |     } else {
3582 |       process_request(conn);
3583 |     }
3584 |   }
3585 |   DBG(("%p %d %d (2)", conn, n, conn->flags));
3586 | }
3587 | 
3588 | int mg_connect(struct mg_server *server, const char *host, int port,
3589 |                int use_ssl, mg_handler_t handler, void *param) {
3590 |   sock_t sock = INVALID_SOCKET;
3591 |   struct sockaddr_in sin;
3592 |   struct hostent *he = NULL;
3593 |   struct connection *conn = NULL;
3594 |   int connect_ret_val;
3595 | 
3596 |   if (host == NULL || (he = gethostbyname(host)) == NULL ||
3597 |       (sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) return 0;
3598 | #ifndef MONGOOSE_USE_SSL
3599 |   if (use_ssl) return 0;
3600 | #endif
3601 | 
3602 |   sin.sin_family = AF_INET;
3603 |   sin.sin_port = htons((uint16_t) port);
3604 |   sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
3605 |   set_non_blocking_mode(sock);
3606 | 
3607 |   connect_ret_val = connect(sock, (struct sockaddr *) &sin, sizeof(sin));
3608 |   if (connect_ret_val != 0 && errno != EINPROGRESS) {
3609 |     return 0;
3610 |   } else if ((conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) {
3611 |     closesocket(sock);
3612 |     return 0;
3613 |   }
3614 | 
3615 |   conn->client_sock = sock;
3616 |   conn->endpoint_type = EP_CLIENT;
3617 |   conn->handler = handler;
3618 |   conn->mg_conn.server_param = server->server_data;
3619 |   conn->mg_conn.connection_param = param;
3620 |   conn->birth_time = conn->last_activity_time = time(NULL);
3621 |   conn->flags = CONN_CONNECTING;
3622 |   conn->mg_conn.status_code = MG_CONNECT_FAILURE;
3623 | #ifdef MONGOOSE_USE_SSL
3624 |   if (use_ssl && (conn->ssl = SSL_new(server->client_ssl_ctx)) != NULL) {
3625 |     SSL_set_fd(conn->ssl, sock);
3626 |   }
3627 | #endif
3628 |   LINKED_LIST_ADD_TO_FRONT(&server->active_connections, &conn->link);
3629 |   DBG(("%p %s:%d", conn, host, port));
3630 | 
3631 |   if (connect_ret_val == 0) {
3632 |     callback_http_client_on_connect(conn);
3633 | #if 0
3634 |     conn->mg_conn.status_code = MG_CONNECT_SUCCESS;
3635 |     conn->flags &= ~CONN_CONNECTING;
3636 |     conn->mg_conn.content = conn->local_iobuf.buf;
3637 |     handler(&conn->mg_conn);
3638 | #endif
3639 |   }
3640 | 
3641 |   return 1;
3642 | }
3643 | 
3644 | #ifndef MONGOOSE_NO_LOGGING
3645 | static void log_header(const struct mg_connection *conn, const char *header,
3646 |                        FILE *fp) {
3647 |   const char *header_value;
3648 | 
3649 |   if ((header_value = mg_get_header(conn, header)) == NULL) {
3650 |     (void) fprintf(fp, "%s", " -");
3651 |   } else {
3652 |     (void) fprintf(fp, " \"%s\"", header_value);
3653 |   }
3654 | }
3655 | 
3656 | static void log_access(const struct connection *conn, const char *path) {
3657 |   const struct mg_connection *c = &conn->mg_conn;
3658 |   FILE *fp = (path == NULL) ?  NULL : fopen(path, "a+");
3659 |   char date[64], user[100];
3660 | 
3661 |   if (fp == NULL) return;
3662 |   strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",
3663 |            localtime(&conn->birth_time));
3664 | 
3665 |   flockfile(fp);
3666 |   mg_parse_header(mg_get_header(&conn->mg_conn, "Authorization"), "username",
3667 |                   user, sizeof(user));
3668 |   fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
3669 |           c->remote_ip, user[0] == '\0' ? "-" : user, date,
3670 |           c->request_method ? c->request_method : "-",
3671 |           c->uri ? c->uri : "-", c->http_version,
3672 |           c->status_code, conn->num_bytes_sent);
3673 |   log_header(c, "Referer", fp);
3674 |   log_header(c, "User-Agent", fp);
3675 |   fputc('\n', fp);
3676 |   fflush(fp);
3677 | 
3678 |   funlockfile(fp);
3679 |   fclose(fp);
3680 | }
3681 | #endif
3682 | 
3683 | static void close_local_endpoint(struct connection *conn) {
3684 |   // Must be done before free()
3685 |   int keep_alive = should_keep_alive(&conn->mg_conn) &&
3686 |     (conn->endpoint_type == EP_FILE || conn->endpoint_type == EP_USER);
3687 |   DBG(("%p %d %d %d", conn, conn->endpoint_type, keep_alive, conn->flags));
3688 | 
3689 |   switch (conn->endpoint_type) {
3690 |     case EP_PUT: close(conn->endpoint.fd); break;
3691 |     case EP_FILE: close(conn->endpoint.fd); break;
3692 |     case EP_CGI: closesocket(conn->endpoint.cgi_sock); break;
3693 |     default: break;
3694 |   }
3695 | 
3696 | #ifndef MONGOOSE_NO_LOGGING
3697 |   if (conn->mg_conn.status_code > 0 && conn->endpoint_type != EP_CLIENT &&
3698 |       conn->mg_conn.status_code != 400) {
3699 |     log_access(conn, conn->server->config_options[ACCESS_LOG_FILE]);
3700 |   }
3701 | #endif
3702 | 
3703 |   // Gobble possible POST data sent to the URI handler
3704 |   discard_leading_iobuf_bytes(&conn->local_iobuf, conn->mg_conn.content_len);
3705 |   conn->endpoint_type = EP_NONE;
3706 |   conn->flags = conn->mg_conn.status_code = 0;
3707 |   conn->cl = conn->num_bytes_sent = conn->request_len = 0;
3708 |   free(conn->request);
3709 |   conn->request = NULL;
3710 | 
3711 |   if (keep_alive) {
3712 |     process_request(conn);  // Can call us recursively if pipelining is used
3713 |   } else {
3714 |     conn->flags |= conn->remote_iobuf.len == 0 ? CONN_CLOSE : CONN_SPOOL_DONE;
3715 |   }
3716 | }
3717 | 
3718 | static void transfer_file_data(struct connection *conn) {
3719 |   char buf[IOBUF_SIZE];
3720 |   int n = read(conn->endpoint.fd, buf, conn->cl < (int64_t) sizeof(buf) ?
3721 |                (int) conn->cl : (int) sizeof(buf));
3722 | 
3723 |   if (is_error(n)) {
3724 |     close_local_endpoint(conn);
3725 |   } else if (n > 0) {
3726 |     conn->cl -= n;
3727 |     spool(&conn->remote_iobuf, buf, n);
3728 |     if (conn->cl <= 0) {
3729 |       close_local_endpoint(conn);
3730 |     }
3731 |   }
3732 | }
3733 | 
3734 | static void execute_iteration(struct mg_server *server) {
3735 |   struct ll *lp, *tmp;
3736 |   struct connection *conn;
3737 |   union { mg_handler_t f; void *p; } msg[2];
3738 | 
3739 |   recv(server->ctl[1], (void *) msg, sizeof(msg), 0);
3740 |   LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
3741 |     conn = LINKED_LIST_ENTRY(lp, struct connection, link);
3742 |     conn->mg_conn.connection_param = msg[1].p;
3743 |     msg[0].f(&conn->mg_conn);
3744 |   }
3745 | }
3746 | 
3747 | void add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
3748 |   FD_SET(sock, set);
3749 |   if (sock > *max_fd) {
3750 |     *max_fd = sock;
3751 |   }
3752 | }
3753 | 
3754 | unsigned int mg_poll_server(struct mg_server *server, int milliseconds) {
3755 |   struct ll *lp, *tmp;
3756 |   struct connection *conn;
3757 |   struct timeval tv;
3758 |   fd_set read_set, write_set;
3759 |   sock_t max_fd = -1;
3760 |   time_t current_time = time(NULL), expire_time = current_time -
3761 |     MONGOOSE_USE_IDLE_TIMEOUT_SECONDS;
3762 | 
3763 |   if (server->listening_sock == INVALID_SOCKET) return 0;
3764 | 
3765 |   FD_ZERO(&read_set);
3766 |   FD_ZERO(&write_set);
3767 |   add_to_set(server->listening_sock, &read_set, &max_fd);
3768 |   add_to_set(server->ctl[1], &read_set, &max_fd);
3769 | 
3770 |   LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
3771 |     conn = LINKED_LIST_ENTRY(lp, struct connection, link);
3772 |     add_to_set(conn->client_sock, &read_set, &max_fd);
3773 |     if (conn->endpoint_type == EP_CLIENT && (conn->flags & CONN_CONNECTING)) {
3774 |       add_to_set(conn->client_sock, &write_set, &max_fd);
3775 |     }
3776 |     if (conn->endpoint_type == EP_FILE) {
3777 |       transfer_file_data(conn);
3778 |     } else if (conn->endpoint_type == EP_CGI) {
3779 |       add_to_set(conn->endpoint.cgi_sock, &read_set, &max_fd);
3780 |     }
3781 |     if (conn->remote_iobuf.len > 0 && !(conn->flags & CONN_BUFFER)) {
3782 |       add_to_set(conn->client_sock, &write_set, &max_fd);
3783 |     } else if (conn->flags & CONN_CLOSE) {
3784 |       close_conn(conn);
3785 |     }
3786 |   }
3787 | 
3788 |   tv.tv_sec = milliseconds / 1000;
3789 |   tv.tv_usec = (milliseconds % 1000) * 1000;
3790 | 
3791 |   if (select(max_fd + 1, &read_set, &write_set, NULL, &tv) > 0) {
3792 |     if (FD_ISSET(server->ctl[1], &read_set)) {
3793 |       execute_iteration(server);
3794 |     }
3795 | 
3796 |     // Accept new connections
3797 |     if (FD_ISSET(server->listening_sock, &read_set)) {
3798 |       while ((conn = accept_new_connection(server)) != NULL) {
3799 |         conn->birth_time = conn->last_activity_time = current_time;
3800 |       }
3801 |     }
3802 | 
3803 |     // Read/write from clients
3804 |     LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
3805 |       conn = LINKED_LIST_ENTRY(lp, struct connection, link);
3806 |       if (FD_ISSET(conn->client_sock, &read_set)) {
3807 |         conn->last_activity_time = current_time;
3808 |         read_from_socket(conn);
3809 |       }
3810 | #ifndef MONGOOSE_NO_CGI
3811 |       if (conn->endpoint_type == EP_CGI &&
3812 |           FD_ISSET(conn->endpoint.cgi_sock, &read_set)) {
3813 |         read_from_cgi(conn);
3814 |       }
3815 | #endif
3816 |       if (FD_ISSET(conn->client_sock, &write_set)) {
3817 |         if (conn->endpoint_type == EP_CLIENT &&
3818 |             (conn->flags & CONN_CONNECTING)) {
3819 |           read_from_socket(conn);
3820 |         } else if (!(conn->flags & CONN_BUFFER)) {
3821 |           conn->last_activity_time = current_time;
3822 |           write_to_socket(conn);
3823 |         }
3824 |       }
3825 |     }
3826 |   }
3827 | 
3828 |   // Close expired connections and those that need to be closed
3829 |   LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
3830 |     conn = LINKED_LIST_ENTRY(lp, struct connection, link);
3831 |     if (conn->mg_conn.is_websocket) {
3832 |       ping_idle_websocket_connection(conn, current_time);
3833 |     }
3834 |     if (conn->flags & CONN_LONG_RUNNING) {
3835 |       conn->mg_conn.wsbits = conn->flags & CONN_CLOSE ? 1 : 0;
3836 |       call_uri_handler(conn);
3837 |     }
3838 |     if (conn->flags & CONN_CLOSE || conn->last_activity_time < expire_time) {
3839 |       close_conn(conn);
3840 |     }
3841 |   }
3842 | 
3843 |   return (unsigned int) current_time;
3844 | }
3845 | 
3846 | void mg_destroy_server(struct mg_server **server) {
3847 |   int i;
3848 |   struct ll *lp, *tmp;
3849 | 
3850 |   if (server != NULL && *server != NULL) {
3851 |     struct mg_server *s = *server;
3852 |     // Do one last poll, see https://github.com/cesanta/mongoose/issues/286
3853 |     mg_poll_server(s, 0);
3854 |     closesocket(s->listening_sock);
3855 |     closesocket(s->ctl[0]);
3856 |     closesocket(s->ctl[1]);
3857 |     LINKED_LIST_FOREACH(&s->active_connections, lp, tmp) {
3858 |       close_conn(LINKED_LIST_ENTRY(lp, struct connection, link));
3859 |     }
3860 |     LINKED_LIST_FOREACH(&s->uri_handlers, lp, tmp) {
3861 |       free(LINKED_LIST_ENTRY(lp, struct uri_handler, link)->uri);
3862 |       free(LINKED_LIST_ENTRY(lp, struct uri_handler, link));
3863 |     }
3864 |     for (i = 0; i < (int) ARRAY_SIZE(s->config_options); i++) {
3865 |       free(s->config_options[i]);  // It is OK to free(NULL)
3866 |     }
3867 | #ifdef MONGOOSE_USE_SSL
3868 |     if (s->ssl_ctx != NULL) SSL_CTX_free((*server)->ssl_ctx);
3869 |     if (s->client_ssl_ctx != NULL) SSL_CTX_free(s->client_ssl_ctx);
3870 | #endif
3871 |     free(s);
3872 |     *server = NULL;
3873 |   }
3874 | }
3875 | 
3876 | // Apply function to all active connections.
3877 | void mg_iterate_over_connections(struct mg_server *server, mg_handler_t handler,
3878 |                                  void *param) {
3879 |   // Send closure (function + parameter) to the IO thread to execute
3880 |   union { mg_handler_t f; void *p; } msg[2];
3881 |   msg[0].f = handler;
3882 |   msg[1].p = param;
3883 |   send(server->ctl[0], (void *) msg, sizeof(msg), 0);
3884 | }
3885 | 
3886 | void mg_add_uri_handler(struct mg_server *server, const char *uri,
3887 |                         mg_handler_t handler) {
3888 |   struct uri_handler *p = (struct uri_handler *) malloc(sizeof(*p));
3889 |   if (p != NULL) {
3890 |     LINKED_LIST_ADD_TO_FRONT(&server->uri_handlers, &p->link);
3891 |     p->uri = mg_strdup(uri);
3892 |     p->handler = handler;
3893 |   }
3894 | }
3895 | 
3896 | static int get_var(const char *data, size_t data_len, const char *name,
3897 |                    char *dst, size_t dst_len) {
3898 |   const char *p, *e, *s;
3899 |   size_t name_len;
3900 |   int len;
3901 | 
3902 |   if (dst == NULL || dst_len == 0) {
3903 |     len = -2;
3904 |   } else if (data == NULL || name == NULL || data_len == 0) {
3905 |     len = -1;
3906 |     dst[0] = '\0';
3907 |   } else {
3908 |     name_len = strlen(name);
3909 |     e = data + data_len;
3910 |     len = -1;
3911 |     dst[0] = '\0';
3912 | 
3913 |     // data is "var1=val1&var2=val2...". Find variable first
3914 |     for (p = data; p + name_len < e; p++) {
3915 |       if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
3916 |           !mg_strncasecmp(name, p, name_len)) {
3917 | 
3918 |         // Point p to variable value
3919 |         p += name_len + 1;
3920 | 
3921 |         // Point s to the end of the value
3922 |         s = (const char *) memchr(p, '&', (size_t)(e - p));
3923 |         if (s == NULL) {
3924 |           s = e;
3925 |         }
3926 |         assert(s >= p);
3927 | 
3928 |         // Decode variable into destination buffer
3929 |         len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
3930 | 
3931 |         // Redirect error code from -1 to -2 (destination buffer too small).
3932 |         if (len == -1) {
3933 |           len = -2;
3934 |         }
3935 |         break;
3936 |       }
3937 |     }
3938 |   }
3939 | 
3940 |   return len;
3941 | }
3942 | 
3943 | int mg_get_var(const struct mg_connection *conn, const char *name,
3944 |                char *dst, size_t dst_len) {
3945 |   int len = get_var(conn->query_string, conn->query_string == NULL ? 0 :
3946 |                     strlen(conn->query_string), name, dst, dst_len);
3947 |   if (len < 0) {
3948 |     len = get_var(conn->content, conn->content_len, name, dst, dst_len);
3949 |   }
3950 |   return len;
3951 | }
3952 | 
3953 | static int get_line_len(const char *buf, int buf_len) {
3954 |   int len = 0;
3955 |   while (len < buf_len && buf[len] != '\n') len++;
3956 |   return buf[len] == '\n' ? len + 1: -1;
3957 | }
3958 | 
3959 | int mg_parse_multipart(const char *buf, int buf_len,
3960 |                        char *var_name, int var_name_len,
3961 |                        char *file_name, int file_name_len,
3962 |                        const char **data, int *data_len) {
3963 |   static const char cd[] = "Content-Disposition: ";
3964 |   //struct mg_connection c;
3965 |   int hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
3966 |   //char *p;
3967 | 
3968 |   if (buf == NULL || buf_len <= 0) return 0;
3969 |   if ((hl = get_request_len(buf, buf_len)) <= 0) return 0;
3970 |   if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
3971 | 
3972 |   // Get boundary length
3973 |   bl = get_line_len(buf, buf_len);
3974 | 
3975 |   // Loop through headers, fetch variable name and file name
3976 |   var_name[0] = file_name[0] = '\0';
3977 |   for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) {
3978 |     if (mg_strncasecmp(cd, buf + n, cdl) == 0) {
3979 |       parse_header(buf + n + cdl, ll - (cdl + 2), "name",
3980 |                    var_name, var_name_len);
3981 |       parse_header(buf + n + cdl, ll - (cdl + 2), "filename",
3982 |                    file_name, file_name_len);
3983 |     }
3984 |   }
3985 | 
3986 |   // Scan body, search for terminating boundary
3987 |   for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
3988 |     if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
3989 |       if (data_len != NULL) *data_len = (pos - 2) - hl;
3990 |       if (data != NULL) *data = buf + hl;
3991 |       return pos;
3992 |     }
3993 |   }
3994 | 
3995 |   return 0;
3996 | }
3997 | 
3998 | const char **mg_get_valid_option_names(void) {
3999 |   return static_config_options;
4000 | }
4001 | 
4002 | static int get_option_index(const char *name) {
4003 |   int i;
4004 | 
4005 |   for (i = 0; static_config_options[i * 2] != NULL; i++) {
4006 |     if (strcmp(static_config_options[i * 2], name) == 0) {
4007 |       return i;
4008 |     }
4009 |   }
4010 |   return -1;
4011 | }
4012 | 
4013 | static void set_default_option_values(char **opts) {
4014 |   const char *value, **all_opts = mg_get_valid_option_names();
4015 |   int i;
4016 | 
4017 |   for (i = 0; all_opts[i * 2] != NULL; i++) {
4018 |     value = all_opts[i * 2 + 1];
4019 |     if (opts[i] == NULL && value != NULL) {
4020 |       opts[i] = mg_strdup(value);
4021 |     }
4022 |   }
4023 | }
4024 | 
4025 | // Valid listening port spec is: [ip_address:]port, e.g. "80", "127.0.0.1:3128"
4026 | static int parse_port_string(const char *str, union socket_address *sa) {
4027 |   unsigned int a, b, c, d, port;
4028 |   int len = 0;
4029 | #ifdef MONGOOSE_USE_IPV6
4030 |   char buf[100];
4031 | #endif
4032 | 
4033 |   // MacOS needs that. If we do not zero it, subsequent bind() will fail.
4034 |   // Also, all-zeroes in the socket address means binding to all addresses
4035 |   // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
4036 |   memset(sa, 0, sizeof(*sa));
4037 |   sa->sin.sin_family = AF_INET;
4038 | 
4039 |   if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
4040 |     // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080
4041 |     sa->sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
4042 |     sa->sin.sin_port = htons((uint16_t) port);
4043 | #if defined(MONGOOSE_USE_IPV6)
4044 |   } else if (sscanf(str, "[%49[^]]]:%u%n", buf, &port, &len) == 2 &&
4045 |              inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
4046 |     // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080
4047 |     sa->sin6.sin6_family = AF_INET6;
4048 |     sa->sin6.sin6_port = htons((uint16_t) port);
4049 | #endif
4050 |   } else if (sscanf(str, "%u%n", &port, &len) == 1) {
4051 |     // If only port is specified, bind to IPv4, INADDR_ANY
4052 |     sa->sin.sin_port = htons((uint16_t) port);
4053 |   } else {
4054 |     port = 0;   // Parsing failure. Make port invalid.
4055 |   }
4056 | 
4057 |   return port > 0 && port < 0xffff && str[len] == '\0';
4058 | }
4059 | 
4060 | const char *mg_set_option(struct mg_server *server, const char *name,
4061 |                           const char *value) {
4062 |   int ind = get_option_index(name);
4063 |   const char *error_msg = NULL;
4064 | 
4065 |   if (ind < 0) {
4066 |     error_msg = "No such option";
4067 |   } else {
4068 |     if (server->config_options[ind] != NULL) {
4069 |       free(server->config_options[ind]);
4070 |     }
4071 |     server->config_options[ind] = mg_strdup(value);
4072 |     DBG(("%s [%s]", name, value));
4073 | 
4074 |     if (ind == LISTENING_PORT) {
4075 |       if (server->listening_sock != INVALID_SOCKET) {
4076 |         closesocket(server->listening_sock);
4077 |       }
4078 |       parse_port_string(server->config_options[LISTENING_PORT], &server->lsa);
4079 |       server->listening_sock = open_listening_socket(&server->lsa);
4080 |       if (server->listening_sock == INVALID_SOCKET) {
4081 |         error_msg = "Cannot bind to port";
4082 |       } else {
4083 |         set_non_blocking_mode(server->listening_sock);
4084 |       }
4085 | #ifndef _WIN32
4086 |     } else if (ind == RUN_AS_USER) {
4087 |       struct passwd *pw;
4088 |       if ((pw = getpwnam(value)) == NULL) {
4089 |         error_msg = "Unknown user";
4090 |       } else if (setgid(pw->pw_gid) != 0) {
4091 |         error_msg = "setgid() failed";
4092 |       } else if (setuid(pw->pw_uid) != 0) {
4093 |         error_msg = "setuid() failed";
4094 |       }
4095 | #endif
4096 | #ifdef MONGOOSE_USE_SSL
4097 |     } else if (ind == SSL_CERTIFICATE) {
4098 |       //SSL_library_init();
4099 |       if ((server->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
4100 |         error_msg = "SSL_CTX_new() failed";
4101 |       } else if (SSL_CTX_use_certificate_file(server->ssl_ctx, value, 1) == 0 ||
4102 |                  SSL_CTX_use_PrivateKey_file(server->ssl_ctx, value, 1) == 0) {
4103 |         error_msg = "Cannot load PEM file";
4104 |       } else {
4105 |         SSL_CTX_use_certificate_chain_file(server->ssl_ctx, value);
4106 |       }
4107 | #endif
4108 |     }
4109 |   }
4110 | 
4111 |   return error_msg;
4112 | }
4113 | 
4114 | 
4115 | void mg_set_http_error_handler(struct mg_server *server, mg_handler_t handler) {
4116 |   server->error_handler = handler;
4117 | }
4118 | 
4119 | void mg_set_listening_socket(struct mg_server *server, int sock) {
4120 |   if (server->listening_sock != INVALID_SOCKET) {
4121 |     closesocket(server->listening_sock);
4122 |   }
4123 |   server->listening_sock = (sock_t) sock;
4124 | }
4125 | 
4126 | int mg_get_listening_socket(struct mg_server *server) {
4127 |   return server->listening_sock;
4128 | }
4129 | 
4130 | const char *mg_get_option(const struct mg_server *server, const char *name) {
4131 |   const char **opts = (const char **) server->config_options;
4132 |   int i = get_option_index(name);
4133 |   return i == -1 ? NULL : opts[i] == NULL ? "" : opts[i];
4134 | }
4135 | 
4136 | struct mg_server *mg_create_server(void *server_data) {
4137 |   struct mg_server *server = (struct mg_server *) calloc(1, sizeof(*server));
4138 | 
4139 | #ifdef _WIN32
4140 |   WSADATA data;
4141 |   WSAStartup(MAKEWORD(2, 2), &data);
4142 | #else
4143 |   // Ignore SIGPIPE signal, so if browser cancels the request, it
4144 |   // won't kill the whole process.
4145 |   signal(SIGPIPE, SIG_IGN);
4146 | #endif
4147 | 
4148 |   LINKED_LIST_INIT(&server->active_connections);
4149 |   LINKED_LIST_INIT(&server->uri_handlers);
4150 | 
4151 |   // Create control socket pair. Do it in a loop to protect from
4152 |   // interrupted syscalls in mg_socketpair().
4153 |   do {
4154 |     mg_socketpair(server->ctl);
4155 |   } while (server->ctl[0] == INVALID_SOCKET);
4156 | 
4157 | #ifdef MONGOOSE_USE_SSL
4158 |   SSL_library_init();
4159 |   server->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method());
4160 | #endif
4161 | 
4162 |   server->server_data = server_data;
4163 |   server->listening_sock = INVALID_SOCKET;
4164 |   set_default_option_values(server->config_options);
4165 | 
4166 |   return server;
4167 | }
4168 | 


--------------------------------------------------------------------------------
/mongoose.h:
--------------------------------------------------------------------------------
  1 | // Copyright (c) 2004-2013 Sergey Lyubka 
  2 | // Copyright (c) 2013-2014 Cesanta Software Limited
  3 | // All rights reserved
  4 | //
  5 | // This library is dual-licensed: you can redistribute it and/or modify
  6 | // it under the terms of the GNU General Public License version 2 as
  7 | // published by the Free Software Foundation. For the terms of this
  8 | // license, see .
  9 | //
 10 | // You are free to use this library under the terms of the GNU General
 11 | // Public License, but WITHOUT ANY WARRANTY; without even the implied
 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 13 | // See the GNU General Public License for more details.
 14 | //
 15 | // Alternatively, you can license this library under a commercial
 16 | // license, as set out in .
 17 | //
 18 | // NOTE: Detailed API documentation is at http://cesanta.com/#docs
 19 | 
 20 | #ifndef MONGOOSE_HEADER_INCLUDED
 21 | #define  MONGOOSE_HEADER_INCLUDED
 22 | 
 23 | #define MONGOOSE_VERSION "5.2"
 24 | 
 25 | #include       // required for FILE
 26 | #include      // required for size_t
 27 | 
 28 | #ifdef __cplusplus
 29 | extern "C" {
 30 | #endif // __cplusplus
 31 | 
 32 | // This structure contains information about HTTP request.
 33 | struct mg_connection {
 34 |   const char *request_method; // "GET", "POST", etc
 35 |   const char *uri;            // URL-decoded URI
 36 |   const char *http_version;   // E.g. "1.0", "1.1"
 37 |   const char *query_string;   // URL part after '?', not including '?', or NULL
 38 | 
 39 |   char remote_ip[48];         // Max IPv6 string length is 45 characters
 40 |   int remote_port;            // Client's port
 41 | 
 42 |   int num_headers;            // Number of HTTP headers
 43 |   struct mg_header {
 44 |     const char *name;         // HTTP header name
 45 |     const char *value;        // HTTP header value
 46 |   } http_headers[30];
 47 | 
 48 |   char *content;              // POST (or websocket message) data, or NULL
 49 |   size_t content_len;       // content length
 50 | 
 51 |   int is_websocket;           // Connection is a websocket connection
 52 |   int status_code;            // HTTP status code for HTTP error handler
 53 |   int wsbits;                 // First byte of the websocket frame
 54 |   void *server_param;         // Parameter passed to mg_add_uri_handler()
 55 |   void *connection_param;     // Placeholder for connection-specific data
 56 | };
 57 | 
 58 | struct mg_server; // Opaque structure describing server instance
 59 | typedef int (*mg_handler_t)(struct mg_connection *);
 60 | 
 61 | // Server management functions
 62 | struct mg_server *mg_create_server(void *server_param);
 63 | void mg_destroy_server(struct mg_server **);
 64 | const char *mg_set_option(struct mg_server *, const char *opt, const char *val);
 65 | unsigned int mg_poll_server(struct mg_server *, int milliseconds);
 66 | void mg_add_uri_handler(struct mg_server *, const char *uri, mg_handler_t);
 67 | void mg_set_http_error_handler(struct mg_server *, mg_handler_t);
 68 | const char **mg_get_valid_option_names(void);
 69 | const char *mg_get_option(const struct mg_server *server, const char *name);
 70 | void mg_set_listening_socket(struct mg_server *, int sock);
 71 | int mg_get_listening_socket(struct mg_server *);
 72 | void mg_iterate_over_connections(struct mg_server *, mg_handler_t, void *);
 73 | 
 74 | // Connection management functions
 75 | void mg_send_status(struct mg_connection *, int status_code);
 76 | void mg_send_header(struct mg_connection *, const char *name, const char *val);
 77 | void mg_send_data(struct mg_connection *, const void *data, int data_len);
 78 | void mg_printf_data(struct mg_connection *, const char *format, ...);
 79 | 
 80 | int mg_websocket_write(struct mg_connection *, int opcode,
 81 |                        const char *data, size_t data_len);
 82 | 
 83 | // Deprecated in favor of mg_send_* interface
 84 | int mg_write(struct mg_connection *, const void *buf, int len);
 85 | int mg_printf(struct mg_connection *conn, const char *fmt, ...);
 86 | 
 87 | 
 88 | const char *mg_get_header(const struct mg_connection *, const char *name);
 89 | const char *mg_get_mime_type(const char *file_name);
 90 | int mg_get_var(const struct mg_connection *conn, const char *var_name,
 91 |                char *buf, size_t buf_len);
 92 | int mg_parse_header(const char *hdr, const char *var_name, char *buf, size_t);
 93 | int mg_parse_multipart(const char *buf, int buf_len,
 94 |                        char *var_name, int var_name_len,
 95 |                        char *file_name, int file_name_len,
 96 |                        const char **data, int *data_len);
 97 | 
 98 | // Utility functions
 99 | void *mg_start_thread(void *(*func)(void *), void *param);
100 | char *mg_md5(char buf[33], ...);
101 | int mg_authorize_digest(struct mg_connection *c, FILE *fp);
102 | void mg_send_digest_auth_request(struct mg_connection *conn);
103 | 
104 | // HTTP client interface
105 | enum {
106 |   MG_CONNECT_SUCCESS, MG_CONNECT_FAILURE,
107 |   MG_DOWNLOAD_SUCCESS, MG_DOWNLOAD_FAILURE
108 | };
109 | int mg_connect(struct mg_server *, const char *host, int port, int use_ssl,
110 |                mg_handler_t handler, void *param);
111 | 
112 | #ifdef __cplusplus
113 | }
114 | #endif // __cplusplus
115 | 
116 | #endif // MONGOOSE_HEADER_INCLUDED
117 | 


--------------------------------------------------------------------------------
/msw/trayicon.cpp:
--------------------------------------------------------------------------------
 1 | #include "trayicon.h"
 2 | 
 3 | static LRESULT CALLBACK WindowProc( HWND hWnd, UINT uMsg, WPARAM wParam,
 4 |         LPARAM lParam )
 5 | {
 6 |     static NOTIFYICONDATA nid;
 7 |     static HMENU hPopMenu;
 8 |     switch ( uMsg ) {
 9 |         // trayicon
10 |         case WM_CREATE:
11 |             {
12 |                 memset( &nid, 0, sizeof( nid ) );
13 | 
14 |                 nid.cbSize              = sizeof( nid );
15 |                 nid.hWnd                = hWnd;
16 |                 nid.uID                 = IDI_TRAY;
17 |                 nid.uFlags              = NIF_ICON | NIF_MESSAGE | NIF_TIP;
18 |                 nid.uCallbackMessage    = WM_TRAYMSG;
19 |                 TCHAR    szIconFile[512];
20 |                 GetSystemDirectory( szIconFile, sizeof( szIconFile ) );
21 |                 if ( szIconFile[ lstrlen( szIconFile ) - 1 ] != '\\' )
22 |                     lstrcat( szIconFile, _T("\\") );
23 |                 lstrcat( szIconFile, _T("shell32.dll") );
24 |                 ExtractIconEx( szIconFile, 17, NULL, &(nid.hIcon), 1 );
25 |                 lstrcpy( nid.szTip, HELP_ABOUT);
26 |                 Shell_NotifyIcon( NIM_ADD, &nid );
27 | 
28 |                 hPopMenu = CreatePopupMenu();
29 |                 AppendMenu( hPopMenu, MF_STRING, MENU_CONFIG,  "&About..." );
30 |                 AppendMenu( hPopMenu, MF_STRING, MENU_EXIT,    "E&xit" );
31 |                 SetMenuDefaultItem( hPopMenu, MENU_CONFIG, FALSE );
32 |             }
33 |             break;
34 |         case WM_TRAYMSG:
35 |             {
36 |                 switch ( lParam )
37 |                 {
38 |                     case WM_RBUTTONUP:
39 |                         {
40 |                             POINT pnt;
41 |                             GetCursorPos( &pnt );
42 |                             SetForegroundWindow( hWnd ); // needed to get keyboard focus
43 |                             TrackPopupMenu( hPopMenu, TPM_LEFTALIGN, pnt.x, pnt.y, 0, hWnd, NULL );
44 |                         }
45 |                         break;
46 |                     case WM_LBUTTONDBLCLK:
47 |                         SendMessage( hWnd, WM_COMMAND, MENU_CONFIG, 0 );
48 |                         return 0;
49 |                 }
50 |             }
51 |             break;
52 |         case WM_COMMAND:
53 |             {
54 |                 switch ( LOWORD( wParam ) )
55 |                 {
56 |                     case MENU_CONFIG:
57 |                         MessageBox( hWnd, HELP_ABOUT, THIS_TITLE,
58 |                                 MB_ICONINFORMATION | MB_OK );
59 |                         return 0;
60 |                     case MENU_EXIT:
61 |                         PostMessage( hWnd, WM_CLOSE, 0, 0 );
62 |                         return 0;
63 |                     default:
64 |                         // This happens when the right-click menu is canceled.
65 |                         return 0;
66 |                 }
67 |             }
68 |             break;
69 |         case WM_CLOSE:
70 |             if ( app_close_listener )
71 |                 (*app_close_listener)( hWnd );
72 |             PostQuitMessage( 0 );
73 |             return DefWindowProc( hWnd, uMsg, wParam, lParam );
74 |         default:
75 |             return DefWindowProc( hWnd, uMsg, wParam, lParam );
76 |     }
77 |     return 0;
78 | }
79 | 
80 | void RegisterApplicationClass( HINSTANCE hInstance )
81 | {
82 |     WNDCLASSEX wclx;
83 |     memset( &wclx, 0, sizeof( wclx ) );
84 | 
85 |     wclx.cbSize         = sizeof( wclx );
86 |     wclx.style          = 0;
87 |     wclx.lpfnWndProc    = &WindowProc;
88 |     wclx.cbClsExtra     = 0;
89 |     wclx.cbWndExtra     = 0;
90 |     wclx.hInstance      = hInstance;
91 |     wclx.hCursor        = LoadCursor( NULL, IDC_ARROW );
92 |     wclx.hbrBackground  = (HBRUSH)( COLOR_BTNFACE + 1 );    //  COLOR_* + 1 is
93 |     //  special magic.
94 |     wclx.lpszMenuName   = NULL;
95 |     wclx.lpszClassName  = THIS_CLASSNAME;
96 | 
97 |     RegisterClassEx( &wclx );
98 | }
99 | 


--------------------------------------------------------------------------------
/msw/trayicon.h:
--------------------------------------------------------------------------------
 1 | #ifndef _TRAYICON_H
 2 | #define _TRAYICON_H
 3 | 
 4 | #include 
 5 | #include 
 6 | 
 7 | #define HELP_ABOUT _T("KV Command line dictionary tool.\n\nhttps://github.com/brookhong/kv")
 8 | 
 9 | #define THIS_CLASSNAME      _T("KV")
10 | #define THIS_TITLE          _T("KV")
11 | 
12 | #define IDI_TRAY       100
13 | #define WM_TRAYMSG     101
14 | #define MENU_CONFIG    32
15 | #define MENU_EXIT      33
16 | 
17 | 
18 | void app_close_listener( HWND );
19 | void    RegisterApplicationClass( HINSTANCE hInstance );
20 | 
21 | #endif
22 | 


--------------------------------------------------------------------------------
/msw/winmain.cpp:
--------------------------------------------------------------------------------
  1 | #include "trayicon.h"
  2 | #include "shellapi.h"
  3 | #include "../httpserver.h"
  4 | #include 
  5 | 
  6 | LRESULT (*WindowProc_fallback)( HWND, UINT, WPARAM, LPARAM );
  7 | LRESULT app_window_proc( HWND, UINT, WPARAM, LPARAM );
  8 | 
  9 | //  Entry point
 10 | /*int WINAPI WinMain( HINSTANCE hInst, HINSTANCE prev, LPSTR cmdline, int show )*/
 11 | int _inMain( HINSTANCE hInst )
 12 | {
 13 |     HWND    hWnd;
 14 |     MSG     msg;
 15 |     BOOL    bRet;
 16 | 
 17 |     //  Detect previous instance, and bail if there is one.
 18 |     if ( FindWindow( THIS_CLASSNAME, THIS_TITLE ) )
 19 |         return 0;
 20 | 
 21 |     //  We have to have a window, even though we never show it.  This is
 22 |     //  because the tray icon uses window messages to send notifications to
 23 |     //  its owner.  Starting with Windows 2000, you can make some kind of
 24 |     //  "message target" window that just has a message queue and nothing
 25 |     //  much else, but we'll be backwardly compatible here.
 26 |     RegisterApplicationClass( hInst );
 27 | 
 28 |     hWnd = CreateWindow( THIS_CLASSNAME, THIS_TITLE,
 29 |             0, 0, 0, 100, 100, NULL, NULL, hInst, NULL );
 30 | 
 31 |     if ( ! hWnd ) {
 32 |         MessageBox( NULL, _T("Ack! I can't create the window!"), THIS_TITLE,
 33 |                 MB_ICONERROR | MB_OK | MB_TOPMOST );
 34 |         return 1;
 35 |     }
 36 | 
 37 |     WindowProc_fallback = &app_window_proc;
 38 | 
 39 |     //  Message loop
 40 |     while ( TRUE ) {
 41 |         bRet = GetMessage( &msg, NULL, 0, 0 );
 42 |         if ( bRet == 0 || bRet == -1)
 43 |             break;
 44 |         TranslateMessage( &msg );
 45 |         DispatchMessage( &msg );
 46 |     }
 47 | 
 48 |     UnregisterClass( THIS_CLASSNAME, hInst );
 49 | 
 50 |     return msg.wParam;
 51 | }
 52 | 
 53 | LRESULT app_window_proc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
 54 | {
 55 |     switch ( uMsg )
 56 |     {
 57 |         default:
 58 |             return DefWindowProc( hWnd, uMsg, wParam, lParam );
 59 |     }
 60 | }
 61 | 
 62 | extern int stopped;
 63 | void app_close_listener( HWND hWnd )
 64 | {
 65 |     stopped = 1;
 66 | }
 67 | void bg(LPSTR cmdline)
 68 | {
 69 |    PROCESS_INFORMATION procinfo;
 70 |    STARTUPINFOA startinfo;
 71 |    BOOL rc;
 72 | 
 73 |    /* Init the STARTUPINFOA struct. */
 74 |    memset(&startinfo, 0, sizeof(startinfo));
 75 |    startinfo.cb = sizeof(startinfo);
 76 | 
 77 |    rc = CreateProcess(NULL,
 78 |                       cmdline,        // command line
 79 |                       NULL,             // process security attributes
 80 |                       NULL,             // primary thread security attributes
 81 |                       TRUE,             // handles are inherited
 82 |                       DETACHED_PROCESS, // creation flags
 83 |                       NULL,             // use parent's environment
 84 |                       NULL,             // use parent's current directory
 85 |                       &startinfo,       // STARTUPINFO pointer
 86 |                       &procinfo);       // receives PROCESS_INFORMATION
 87 |    // Cleanup handles
 88 |    CloseHandle(procinfo.hProcess);
 89 |    CloseHandle(procinfo.hThread);
 90 | 
 91 |    ExitProcess(0);
 92 | }
 93 | 
 94 | int httpServer(const char *idxFileName, const char *port) {
 95 |     if(GetConsoleWindow() == NULL) {
 96 |         HTTPD httpd;
 97 |         httpd.idxFileName = idxFileName;
 98 |         httpd.port = port;
 99 |         _beginthread( _httpServer, 0, (void*)&httpd );
100 |         _inMain(NULL);
101 |     } else {
102 |         bg(GetCommandLine());
103 |     }
104 |     return 0;
105 | }
106 | 


--------------------------------------------------------------------------------
NameModifiedSize