source: trunk/oscam-http-helpers.c@ 4382

Last change on this file since 4382 was 4382, checked in by Admin, 10 years ago

Introducing cs_malloc/cs_realloc functions so that it's easier to log and handle errors. It's usage is demonstrated in oscam-http and oscam-http-helpers. Furthermore, some huge cleanups were done through the webinterface (the helpers module should be fine regarding threading issues now) and the oscam-log is now a bit safer by replacing the sprintfs through snprintfs (not only regarding BufferOverflows, but also Null strings dont lead to a crashing OSCam - at least on my debian).

File size: 16.0 KB
Line 
1//FIXME Not checked on threadsafety yet; after checking please remove this line
2#include "globals.h"
3#ifdef WEBIF
4#include "oscam-http.h"
5
6/* Adds a name->value-mapping or appends to it. You will get a reference back which you may freely
7 use (but you should not call free/realloc on this!)*/
8char *tpl_addVar(struct templatevars *vars, int append, char *name, char *value){
9 int i;
10 char *tmp,*result = NULL;
11 for(i = (*vars).varscnt-1; i >= 0; --i){
12 if(strcmp((*vars).names[i], name) == 0){
13 result = (*vars).values[i];
14 break;
15 }
16 }
17 if(result == NULL){
18 if((*vars).varsalloc <= (*vars).varscnt){
19 if(!cs_realloc(&(*vars).names, (*vars).varsalloc * 2 * sizeof(char**), -1)) return value;
20 if(!cs_realloc(&(*vars).values, (*vars).varsalloc * 2 * sizeof(char**), -1)) return value;
21 (*vars).varsalloc = (*vars).varscnt * 2;
22 }
23 if(!cs_malloc(&tmp,(strlen(name) + 1) * sizeof(char), -1)) return value;
24 strcpy(tmp, name);
25 (*vars).names[(*vars).varscnt] = tmp;
26 if(!cs_malloc(&tmp,(strlen(value) + 1) * sizeof(char), -1)){
27 free((*vars).names[(*vars).varscnt]);
28 return value;
29 }
30 strcpy(tmp, value);
31 (*vars).values[(*vars).varscnt] = tmp;
32 (*vars).varscnt = (*vars).varscnt + 1;
33 } else {
34 int newlen = strlen(value);
35 if(append == 1){
36 int oldlen = strlen((*vars).values[i]);
37 if(!cs_malloc(&tmp, (oldlen + newlen + 1) * sizeof(char), -1)) return value;
38 memcpy(tmp, (*vars).values[i], oldlen);
39 strcpy(tmp + oldlen, value);
40 } else {
41 if(!cs_malloc(&tmp, (newlen + 1) * sizeof(char), -1)) return value;
42 strcpy(tmp, value);
43 }
44 free((*vars).values[i]);
45 (*vars).values[i] = tmp;
46 }
47 return tmp;
48}
49
50/* Allows to add a char array which has been allocated by malloc. It will automatically get
51 freed when calling tpl_clear(). Please do NOT free the memory yourself or realloc
52 it after having added the array here! */
53char *tpl_addTmp(struct templatevars *vars, char *value){
54 if((*vars).tmpalloc <= (*vars).tmpcnt){
55 if(!cs_realloc (&(*vars).tmp, (*vars).tmpalloc * 2 * sizeof(char**), -1)) return value;
56 (*vars).tmpalloc = (*vars).tmpcnt * 2;
57 }
58 (*vars).tmp[(*vars).tmpcnt] = value;
59 (*vars).tmpcnt++;
60 return value;
61}
62
63/* Allows to do a dynamic printf without knowing and defining the needed memory size. If you specify
64 varname, the printf-result will be added/appended to the varlist. You will always get a reference
65 back which you may freely use (but you should not call free/realloc on this!)*/
66char *tpl_printf(struct templatevars *vars, int append, char *varname, char *fmtstring, ...){
67 unsigned int needed;
68 char test[1];
69 va_list argptr;
70
71 va_start(argptr,fmtstring);
72 needed = vsnprintf(test, 1, fmtstring, argptr);
73 va_end(argptr);
74
75 char *result;
76 if(!cs_malloc(&result, (needed + 1) * sizeof(char), -1)) return "";
77 va_start(argptr,fmtstring);
78 vsnprintf(result, needed + 1, fmtstring, argptr);
79 va_end(argptr);
80
81 if(varname == NULL) tpl_addTmp(vars, result);
82 else {
83 char *tmp = tpl_addVar(vars, append, varname, result);
84 free(result);
85 result = tmp;
86 }
87 return result;
88}
89
90/* Returns the value for a name or an empty string if nothing was found. */
91char *tpl_getVar(struct templatevars *vars, char *name){
92 int i;
93 char *result = NULL;
94 for(i = (*vars).varscnt-1; i >= 0; --i){
95 if(strcmp((*vars).names[i], name) == 0){
96 result = (*vars).values[i];
97 break;
98 }
99 }
100 if(result == NULL) return "";
101 else return result;
102}
103
104/* Initializes all variables for a templatevar-structure and returns a pointer to it. Make
105 sure to call tpl_clear() when you are finished or you'll run into a memory leak! */
106struct templatevars *tpl_create(){
107 struct templatevars *vars;
108 if(!cs_malloc(&vars, sizeof(struct templatevars), -1)) return NULL;
109 (*vars).varsalloc = 64;
110 (*vars).varscnt = 0;
111 (*vars).tmpalloc = 64;
112 (*vars).tmpcnt = 0;
113 if(!cs_malloc(&(*vars).names, (*vars).varsalloc * sizeof(char**), -1)){
114 free(vars);
115 return NULL;
116 }
117 if(!cs_malloc(&(*vars).values, (*vars).varsalloc * sizeof(char**), -1)){
118 free((*vars).names);
119 free(vars);
120 return NULL;
121 };
122 if(!cs_malloc(&(*vars).tmp, (*vars).tmpalloc * sizeof(char**), -1)){
123 free((*vars).names);
124 free((*vars).values);
125 free(vars);
126 return NULL;
127 };
128 return vars;
129}
130
131/* Clears all allocated memory for the specified templatevar-structure. */
132void tpl_clear(struct templatevars *vars){
133 int i;
134 for(i = (*vars).varscnt-1; i >= 0; --i){
135 free((*vars).names[i]);
136 free((*vars).values[i]);
137 }
138 free((*vars).names);
139 free((*vars).values);
140 for(i = (*vars).tmpcnt-1; i >= 0; --i){
141 free((*vars).tmp[i]);
142 }
143 free((*vars).tmp);
144 free(vars);
145}
146
147/* Creates a path to a template file. You need to set the resultsize to the correct size of result. */
148char *tpl_getTplPath(const char *name, const char *path, char *result, unsigned int resultsize){
149 char *pch;
150 if((strlen(path) + strlen(name) + 6) <= resultsize){
151 strcpy(result, path);
152 strcat(result, name);
153 strcat(result, ".tpl");
154 result[resultsize - 1] = '\0';
155 for(pch = result + strlen(path); pch[0] != '\0'; ++pch){
156 if(pch[0] == '/' || pch[0] == '\\') pch[0] = ' ';
157 }
158 } else result[0] = '\0';
159 return result;
160}
161
162/* Returns an unparsed template either from disk or from internal templates.
163 Note: You must free() the result after using it and you may get NULL if an error occured!*/
164char *tpl_getUnparsedTpl(const char* name){
165 int i;
166 int tplcnt = sizeof(tpl)/sizeof(char *);
167 int tplmapcnt = sizeof(tplmap)/sizeof(char *);
168 char *result;
169
170 for(i = 0; i < tplcnt; ++i){
171 if(strcmp(name, tpl[i]) == 0) break;
172 }
173
174 if(strlen(cfg->http_tpl) > 0){
175 char path[255];
176 if(strlen(tpl_getTplPath(name, cfg->http_tpl, path, 255)) > 0 && file_exists(path)){
177 FILE *fp;
178 char buffer[1024];
179 int read, allocated = 1025, size = 0;
180 if(!cs_malloc(&result, allocated * sizeof(char), -1)) return NULL;
181 if((fp = fopen(path,"r"))!=NULL){
182 while((read = fread(&buffer,sizeof(char),1024,fp)) > 0){
183 if(allocated < size + read + 1) {
184 allocated += size + 1024;
185 if(!cs_realloc(&result, allocated * sizeof(char), -1)) return NULL;
186 }
187 memcpy(result + size, buffer, read);
188 size += read;
189 }
190 result[size] = '\0';
191 fclose (fp);
192 return result;
193 }
194 }
195 }
196 if(i >= 0 && i < tplmapcnt){
197 int len = (strlen(tplmap[i])) + 1;
198 if(!cs_malloc(&result, len * sizeof(char), -1)) return NULL;
199 memcpy(result, tplmap[i], len);
200 } else {
201 if(!cs_malloc(&result, 1 * sizeof(char), -1)) return NULL;
202 result[0] = '\0';
203 }
204 return result;
205}
206
207/* Returns the specified template with all variables/other templates replaced or an
208 empty string if the template doesn't exist. Do not free the result yourself, it
209 will get automatically cleaned up! */
210char *tpl_getTpl(struct templatevars *vars, const char* name){
211 char *tplorg = tpl_getUnparsedTpl(name);
212 if(!tplorg) return "";
213 char *tplend = tplorg + strlen(tplorg);
214 char *pch, *pch2, *tpl=tplorg;
215 char varname[33];
216
217 int tmp,respos = 0;
218 int allocated = 2 * strlen(tpl) + 1;
219 char *result;
220 if(!cs_malloc(&result, allocated * sizeof(char), -1)) return "";
221
222 while(tpl < tplend){
223 if(tpl[0] == '#' && tpl[1] == '#' && tpl[2] != '#'){
224 pch2 = tpl;
225 pch = tpl + 2;
226 while(pch[0] != '\0' && (pch[0] != '#' || pch[1] != '#')) ++pch;
227 if(pch - pch2 < 32 && pch[0] == '#' && pch[1] == '#'){
228 memcpy(varname, pch2 + 2, pch - pch2 - 2);
229 varname[pch - pch2 - 2] = '\0';
230 if(strncmp(varname, "TPL", 3) == 0){
231 pch2 = tpl_getTpl(vars, varname + 3);
232 } else {
233 pch2 = tpl_getVar(vars, varname);
234 }
235 tmp = strlen(pch2);
236 if(tmp + respos + 2 >= allocated){
237 allocated = tmp + respos + 256;
238 if(!cs_realloc(&result, allocated * sizeof(char), -1)) return "";
239 }
240 memcpy(result + respos, pch2, tmp);
241 respos += tmp;
242 tpl = pch + 2;
243 }
244 } else {
245 if(respos + 2 >= allocated){
246 allocated = respos + 256;
247 if(!cs_realloc(&result, allocated * sizeof(char), -1)) return "";
248 }
249 result[respos] = tpl[0];
250 ++respos;
251 ++tpl;
252 }
253 }
254 free(tplorg);
255 result[respos] = '\0';
256 tpl_addTmp(vars, result);
257 return result;
258}
259
260/* Saves all templates to the specified paths. Existing files will be overwritten! */
261int tpl_saveIncludedTpls(const char *path){
262 int tplcnt = sizeof(tpl)/sizeof(char *);
263 int tplmapcnt = sizeof(tplmap)/sizeof(char *);
264 int i, cnt = 0;
265 char tmp[256];
266 FILE *fp;
267 for(i = 0; i < tplcnt && i < tplmapcnt; ++i){
268 if(strlen(tpl_getTplPath(tpl[i], path, tmp, 256)) > 0 && (fp = fopen(tmp,"w")) != NULL){
269 fwrite(tplmap[i], sizeof(char), strlen(tplmap[i]), fp);
270 fclose (fp);
271 ++cnt;
272 }
273 }
274 return cnt;
275}
276
277/* Parses a value in an authentication string by removing all quotes/whitespace. Note that the original array is modified. */
278char *parse_auth_value(char *value){
279 char *pch = value;
280 char *pch2;
281 value = strstr(value, "=");
282 if(value != NULL){
283 do{
284 ++value;
285 } while (value[0] == ' ' || value[0] == '"');
286 pch = value;
287 for(pch2 = value + strlen(value) - 1; pch2 >= value && (pch2[0] == ' ' || pch2[0] == '"' || pch2[0] == '\r' || pch2[0] == '\n'); --pch2) pch2[0] = '\0';
288 }
289 return pch;
290}
291
292/* Calculates the currently valid nonce value and copies it to result. Please note that result needs to be at least (MD5_DIGEST_LENGTH * 2) + 1 large. */
293void calculate_nonce(char *result){
294 char noncetmp[128];
295 unsigned char md5tmp[MD5_DIGEST_LENGTH];
296 sprintf(noncetmp, "%d:%s", (int)time(NULL)/AUTHNONCEVALIDSECS, noncekey);
297 char_to_hex(MD5((unsigned char*)noncetmp, strlen(noncetmp), md5tmp), MD5_DIGEST_LENGTH, (unsigned char*)result, hex2ascii);
298}
299
300/* Checks if authentication is correct. Returns -1 if not correct, 1 if correct and 2 if nonce isn't valid anymore.
301 Note that authstring will be modified. */
302int check_auth(char *authstring, char *method, char *path, char *expectednonce){
303 int authok = 0, uriok = 0;
304 char *authnonce = "";
305 char *authnc = "";
306 char *authcnonce = "";
307 char *authresponse = "";
308 char *uri = "";
309 char *username = "";
310 char *expectedPassword = cfg->http_pwd;
311 char *pch = authstring + 22;
312 char *pch2;
313
314 pch = strtok (pch,",");
315 while (pch != NULL){
316 pch2 = pch;
317 while(pch2[0] == ' ' && pch2[0] != '\0') ++pch2;
318 if(strncmp(pch2, "nonce", 5) == 0){
319 authnonce=parse_auth_value(pch2);
320 } else if (strncmp(pch2, "nc", 2) == 0){
321 authnc=parse_auth_value(pch2);
322 } else if (strncmp(pch2, "cnonce", 6) == 0){
323 authcnonce=parse_auth_value(pch2);
324 } else if (strncmp(pch2, "response", 8) == 0){
325 authresponse=parse_auth_value(pch2);
326 } else if (strncmp(pch2, "uri", 3) == 0){
327 uri=parse_auth_value(pch2);
328 } else if (strncmp(pch2, "username", 8) == 0){
329 username=parse_auth_value(pch2);
330 }
331 pch = strtok (NULL, ",");
332 }
333
334 if(strncmp(uri, path, strlen(path)) == 0) uriok = 1;
335 else {
336 pch2 = uri;
337 for(pch = uri; pch[0] != '\0'; ++pch) {
338 if(pch[0] == '/') pch2 = pch;
339 }
340 if(strncmp(pch2, path, strlen(path)) == 0) uriok = 1;
341 }
342 if(uriok == 1 && strcmp(username, cfg->http_user) == 0){
343 char A1tmp[3 + strlen(username) + strlen(AUTHREALM) + strlen(expectedPassword)];
344 char A1[(MD5_DIGEST_LENGTH * 2) + 1], A2[(MD5_DIGEST_LENGTH * 2) + 1], A3[(MD5_DIGEST_LENGTH * 2) + 1];
345 unsigned char md5tmp[MD5_DIGEST_LENGTH];
346 sprintf(A1tmp, "%s:%s:%s", username, AUTHREALM, expectedPassword);
347 char_to_hex(MD5((unsigned char*)A1tmp, strlen(A1tmp), md5tmp), MD5_DIGEST_LENGTH, (unsigned char*)A1, hex2ascii);
348
349 char A2tmp[2 + strlen(method) + strlen(uri)];
350 sprintf(A2tmp, "%s:%s", method, uri);
351 char_to_hex(MD5((unsigned char*)A2tmp, strlen(A2tmp), md5tmp), MD5_DIGEST_LENGTH, (unsigned char*)A2, hex2ascii);
352
353 char A3tmp[10 + strlen(A1) + strlen(A2) + strlen(authnonce) + strlen(authnc) + strlen(authcnonce)];
354 sprintf(A3tmp, "%s:%s:%s:%s:auth:%s", A1, authnonce, authnc, authcnonce, A2);
355 char_to_hex(MD5((unsigned char*)A3tmp, strlen(A3tmp), md5tmp), MD5_DIGEST_LENGTH, (unsigned char*)A3, hex2ascii);
356
357 if(strcmp(A3, authresponse) == 0) {
358 if(strcmp(expectednonce, authnonce) == 0) authok = 1;
359 else authok = 2;
360 }
361 }
362 return authok;
363}
364
365#ifdef WITH_SSL
366#include <openssl/crypto.h>
367#include <openssl/ssl.h>
368#include <openssl/err.h>
369#endif
370
371int webif_write(char *buf, FILE* f) {
372#ifdef WITH_SSL
373 if (cfg->http_use_ssl) {
374 return SSL_write((SSL*)f, buf, strlen(buf));
375 } else
376#endif
377 return fwrite(buf, 1, strlen(buf), f);
378}
379
380int webif_read(char *buf, int num, FILE *f) {
381#ifdef WITH_SSL
382 if (cfg->http_use_ssl) {
383 return SSL_read((SSL*)f, buf, num);
384 } else
385#endif
386 return read(fileno(f), buf, num);
387}
388
389void send_headers(FILE *f, int status, char *title, char *extra, char *mime){
390
391 time_t now;
392 char timebuf[32];
393 char buf[sizeof(PROTOCOL) + sizeof(SERVER) + strlen(title) + (extra == NULL?0:strlen(extra)+2) + (mime == NULL?0:strlen(mime)+2) + 256];
394 char *pos = buf;
395
396 pos += sprintf(pos, "%s %d %s\r\n", PROTOCOL, status, title);
397 pos += sprintf(pos, "Server: %s\r\n", SERVER);
398
399 now = time(NULL);
400 strftime(timebuf, sizeof(timebuf), RFC1123FMT, gmtime(&now));
401 pos += sprintf(pos, "Date: %s\r\n", timebuf);
402
403 if (extra)
404 pos += sprintf(pos, "%s\r\n", extra);
405
406 if (mime)
407 pos += sprintf(pos, "Content-Type: %s\r\n", mime);
408
409 pos += sprintf(pos, "Cache-Control: no-store, no-cache, must-revalidate\r\n");
410 pos += sprintf(pos, "Expires: Sat, 26 Jul 1997 05:00:00 GMT\r\n");
411 pos += sprintf(pos, "Last-Modified: %s\r\n", timebuf);
412 pos += sprintf(pos, "Connection: close\r\n");
413 pos += sprintf(pos, "\r\n");
414 webif_write(buf, f);
415}
416
417
418
419/*
420 * function for sending files.
421 */
422void send_file(FILE *f, char *filename){
423 int fileno = 0;
424
425 if (!strcmp(filename, "CSS")){
426 filename = cfg->http_css;
427 fileno = 1;
428 } else if (!strcmp(filename, "JS")){
429 filename = cfg->http_jscript;
430 fileno = 2;
431 }
432
433 if(strlen(filename) > 0 && file_exists(filename) == 1){
434 FILE *fp;
435 char buffer[1024];
436 int read;
437
438 if((fp = fopen(filename, "r"))==NULL) return;
439 while((read = fread(buffer,sizeof(char), 1023, fp)) > 0) {
440 buffer[read] = '\0';
441 webif_write(buffer, f);
442 }
443
444 fclose (fp);
445 } else {
446 if (fileno == 1)
447 webif_write(CSS, f);
448 else if (fileno == 2)
449 webif_write(JSCRIPT, f);
450 }
451}
452
453void send_error(FILE *f, int status, char *title, char *extra, char *text){
454 char buf[1024];
455 send_headers(f, status, title, extra, "text/html");
456 sprintf(buf, "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\r\n", status, title);
457 sprintf(buf+strlen(buf), "<BODY><H4>%d %s</H4>\r\n", status, title);
458 sprintf(buf+strlen(buf), "%s\r\n", text);
459 sprintf(buf+strlen(buf), "</BODY></HTML>\r\n");
460 webif_write(buf, f);
461}
462
463void send_error500(FILE *f){
464 send_error(f, 500, "Internal Server Error", NULL, "An internal error has occured.");
465}
466
467char *getParam(struct uriparams *params, char *name){
468 int i;
469 for(i=(*params).paramcount-1; i>=0; --i){
470 if(strcmp((*params).params[i], name) == 0) return (*params).values[i];
471 }
472 return "";
473}
474
475char *getParamDef(struct uriparams *params, char *name, char* def){
476 int i;
477 for(i=(*params).paramcount-1; i>=0; --i){
478 if(strcmp((*params).params[i], name) == 0) return (*params).values[i];
479 }
480 return def;
481}
482
483/* XML-Escapes a char array. The returned reference will be automatically cleaned through the templatevars-mechanism tpl_clear().
484 Do not call free() or realloc on the returned reference or you will get memory corruption! */
485char *xml_encode(struct templatevars *vars, char *chartoencode) {
486 int i, pos = 0, len = strlen(chartoencode);
487 char *result;
488 /* In worst case, every character could get converted to 6 chars (we only support ASCII, for Unicode it would be 7)*/
489 char encoded[len * 6 + 1], buffer[7];
490 for (i = 0; i < len; ++i){
491 switch(chartoencode[i]) {
492 case '&': memcpy(encoded + pos, "&amp;", 5); pos+=5; break;
493 case '<': memcpy(encoded + pos, "&lt;", 4); pos+=4; break;
494 case '>': memcpy(encoded + pos, "&gt;", 4); pos+=4; break;
495 case '"': memcpy(encoded + pos, "&quot;", 6); pos+=6; break;
496 case '\'': memcpy(encoded + pos, "&apos;", 6); pos+=6; break;
497
498 default:
499 if ( (unsigned int)chartoencode[i] < 32 || (unsigned int)chartoencode[i] > 127 ) {
500 snprintf(buffer, 7, "&#%d;", chartoencode[i] + 256);
501 memcpy(encoded + pos, buffer, strlen(buffer));
502 pos+=strlen(buffer);
503
504 } else {
505 encoded[pos] = chartoencode[i];
506 ++pos;
507 }
508
509 }
510 }
511 /* Allocate the needed memory size and store it in the templatevars */
512 if(!cs_malloc(&result, pos + 1, -1)) return "";
513 memcpy(result, encoded, pos);
514 result[pos] = '\0';
515 return tpl_addTmp(vars, result);
516}
517#endif
Note: See TracBrowser for help on using the repository browser.