17 #include "web_client.h"
19 // http://stackoverflow.com/questions/7666509/hash-function-for-string
20 unsigned long simple_hash(const char *name)
23 unsigned long hash = 5381;
26 while((i = *s++)) hash = ((hash << 5) + hash) + i;
28 // fprintf(stderr, "HASH: %lu %s\n", hash, name);
33 void strreverse(char* begin, char* end)
37 aux = *end, *end-- = *begin, *begin++ = aux;
40 char *mystrsep(char **ptr, char *s)
43 while ( p && !p[0] && *ptr ) p = strsep(ptr, s);
48 // it trims spaces before and after each value
49 // it accepts quoted values in single or double quotes
50 char *qstrsep(char **ptr)
52 if(!*ptr || !**ptr) return NULL;
56 // skip leading spaces
57 while(isspace(*p)) p++;
59 // if the first char is a quote, assume quoted
60 if(*p == '"' || *p == '\'') {
63 while(*p && *p != q) p++;
75 while(*p && !isspace(*p)) p++;
87 // skip leading spaces
88 while(*s && isspace(*s)) s++;
89 if(!*s || *s == '#') return NULL;
91 // skip tailing spaces
92 int c = strlen(s) - 1;
93 while(c >= 0 && isspace(s[c])) {
97 if(c < 0) return NULL;
102 void *mymmap(const char *filename, unsigned long size, int flags)
108 fd = open(filename, O_RDWR|O_CREAT|O_NOATIME, 0664);
110 if(lseek(fd, size, SEEK_SET) == (long)size) {
111 if(write(fd, "", 1) == 1) {
113 if(ftruncate(fd, size))
114 error("Cannot truncate file '%s' to size %ld. Will use the larger file.", filename, size);
116 mem = mmap(NULL, size, PROT_READ|PROT_WRITE, flags, fd, 0);
118 if(madvise(mem, size, MADV_SEQUENTIAL|MADV_DONTFORK|MADV_WILLNEED) != 0)
119 error("Cannot advise the kernel about the memory usage of file '%s'.", filename);
122 else error("Cannot write to file '%s' at position %ld.", filename, size);
124 else error("Cannot seek file '%s' to size %ld.", filename, size);
128 else error("Cannot create/open file '%s'.", filename);
133 int savememory(const char *filename, void *mem, unsigned long size)
135 char tmpfilename[FILENAME_MAX + 1];
137 snprintf(tmpfilename, FILENAME_MAX, "%s.%ld.tmp", filename, (long)getpid());
139 int fd = open(tmpfilename, O_RDWR|O_CREAT|O_NOATIME, 0664);
141 error("Cannot create/open file '%s'.", filename);
145 if(write(fd, mem, size) != (long)size) {
146 error("Cannot write to file '%s' %ld bytes.", filename, (long)size);
154 if(rename(tmpfilename, filename)) {
155 error("Cannot rename '%s' to '%s'", tmpfilename, filename);
162 void log_allocations(void)
169 if(mi.uordblks > mem) {
171 struct web_client *w;
172 for(w = web_clients; w ; w = w->next) clients++;
174 info("Allocated memory increased from %d to %d (increased by %d bytes). There are %d web clients connected.", mem, mi.uordblks, mi.uordblks - mem, clients);
179 int fd_is_valid(int fd) {
180 return fcntl(fd, F_GETFD) != -1 || errno != EBADF;