UNREGISTER instead of REGISTER in unload_module().
[asterisk/asterisk.git] / res / res_http_post.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file 
21  * \brief HTTP POST upload support for Asterisk HTTP server
22  *
23  * \author Terry Wilson <twilson@digium.com
24  *
25  * \ref AstHTTP - AMI over the http protocol
26  */
27
28 /*** MODULEINFO
29         <depend>gmime</depend>
30  ***/
31
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <sys/stat.h>
38 #include <fcntl.h>
39 #include <gmime/gmime.h>
40 #if defined (__OpenBSD__) || defined(__FreeBSD__)
41 #include <libgen.h>
42 #endif
43
44 #include "asterisk/linkedlists.h"
45 #include "asterisk/http.h"
46 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
47 #include "asterisk/tcptls.h"
48 #include "asterisk/manager.h"
49 #include "asterisk/cli.h"
50 #include "asterisk/module.h"
51 #include "asterisk/ast_version.h"
52
53 #define MAX_PREFIX 80
54
55 /* just a little structure to hold callback info for gmime */
56 struct mime_cbinfo {
57         int count;
58         const char *post_dir;
59 };
60
61 /* all valid URIs must be prepended by the string in prefix. */
62 static char prefix[MAX_PREFIX];
63
64 static void post_raw(GMimePart *part, const char *post_dir, const char *fn)
65 {
66         char filename[PATH_MAX];
67         GMimeDataWrapper *content;
68         GMimeStream *stream;
69         int fd;
70
71         snprintf(filename, sizeof(filename), "%s/%s", post_dir, fn);
72
73         ast_debug(1, "Posting raw data to %s\n", filename);
74
75         if ((fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0666)) == -1) {
76                 ast_log(LOG_WARNING, "Unable to open %s for writing file from a POST!\n", filename);
77
78                 return;
79         }
80
81         stream = g_mime_stream_fs_new(fd);
82
83         content = g_mime_part_get_content_object(part);
84         g_mime_data_wrapper_write_to_stream(content, stream);
85         g_mime_stream_flush(stream);
86
87         g_object_unref(content);
88         g_object_unref(stream);
89 }
90
91 static GMimeMessage *parse_message(FILE *f)
92 {
93         GMimeMessage *message;
94         GMimeParser *parser;
95         GMimeStream *stream;
96
97         stream = g_mime_stream_file_new(f);
98
99         parser = g_mime_parser_new_with_stream(stream);
100         g_mime_parser_set_respect_content_length(parser, 1);
101         
102         g_object_unref(stream);
103
104         message = g_mime_parser_construct_message(parser);
105
106         g_object_unref(parser);
107
108         return message;
109 }
110
111 static void process_message_callback(GMimeObject *part, gpointer user_data)
112 {
113         struct mime_cbinfo *cbinfo = user_data;
114
115         cbinfo->count++;
116
117         /* We strip off the headers before we get here, so should only see GMIME_IS_PART */
118         if (GMIME_IS_MESSAGE_PART(part)) {
119                 ast_log(LOG_WARNING, "Got unexpected GMIME_IS_MESSAGE_PART\n");
120                 return;
121         } else if (GMIME_IS_MESSAGE_PARTIAL(part)) {
122                 ast_log(LOG_WARNING, "Got unexpected GMIME_IS_MESSAGE_PARTIAL\n");
123                 return;
124         } else if (GMIME_IS_MULTIPART(part)) {
125                 GList *l;
126                 
127                 ast_log(LOG_WARNING, "Got unexpected GMIME_IS_MULTIPART, trying to process subparts\n");
128                 l = GMIME_MULTIPART(part)->subparts;
129                 while (l) {
130                         process_message_callback(l->data, cbinfo);
131                         l = l->next;
132                 }
133         } else if (GMIME_IS_PART(part)) {
134                 const char *filename;
135
136                 if (ast_strlen_zero(filename = g_mime_part_get_filename(GMIME_PART(part)))) {
137                         ast_debug(1, "Skipping part with no filename\n");
138                         return;
139                 }
140
141                 post_raw(GMIME_PART(part), cbinfo->post_dir, filename);
142         } else {
143                 ast_log(LOG_ERROR, "Encountered unknown MIME part. This should never happen!\n");
144         }
145 }
146
147 static int process_message(GMimeMessage *message, const char *post_dir)
148 {
149         struct mime_cbinfo cbinfo = {
150                 .count = 0,
151                 .post_dir = post_dir,
152         };
153
154         g_mime_message_foreach_part(message, process_message_callback, &cbinfo);
155
156         return cbinfo.count;
157 }
158
159 /* Find a sequence of bytes within a binary array. */
160 static int find_sequence(char * inbuf, int inlen, char * matchbuf, int matchlen)
161 {
162         int current;
163         int comp;
164         int found = 0;
165
166         for (current = 0; current < inlen-matchlen; current++, inbuf++) {
167                 if (*inbuf == *matchbuf) {
168                         found=1;
169                         for (comp = 1; comp < matchlen; comp++) {
170                                 if (inbuf[comp] != matchbuf[comp]) {
171                                         found = 0;
172                                         break;
173                                 }
174                         }
175                         if (found) {
176                                 break;
177                         }
178                 }
179         }
180         if (found) {
181                 return current;
182         } else {
183                 return -1;
184         }
185 }
186
187 /*
188 * The following is a work around to deal with how IE7 embeds the local file name
189 * within the Mime header using full WINDOWS file path with backslash directory delimiters.
190 * This section of code attempts to isolate the directory path and remove it
191 * from what is written into the output file.  In addition, it changes
192 * esc chars (i.e. backslashes) to forward slashes.
193 * This function has two modes.  The first to find a boundary marker.  The
194 * second is to find the filename immediately after the boundary.
195 */
196 static int readmimefile(FILE * fin, FILE * fout, char * boundary, int contentlen)
197 {
198         int find_filename = 0;
199         char buf[4096];
200         int marker;
201         int x;
202         int char_in_buf = 0;
203         int num_to_read;
204         int boundary_len;
205         char * path_end, * path_start, * filespec;
206
207         if (NULL == fin || NULL == fout || NULL == boundary || 0 >= contentlen) {
208                 return -1;
209         }
210
211         boundary_len = strlen(boundary);
212         while (0 < contentlen || 0 < char_in_buf) {
213                 /* determine how much I will read into the buffer */
214                 if (contentlen > sizeof(buf) - char_in_buf) {
215                         num_to_read = sizeof(buf)- char_in_buf;
216                 } else {
217                         num_to_read = contentlen;
218                 }
219
220                 if (0 < num_to_read) {
221                         if (fread(&(buf[char_in_buf]), 1, num_to_read, fin) < num_to_read) {
222                                 ast_log(LOG_WARNING, "fread() failed: %s\n", strerror(errno));
223                                 num_to_read = 0;
224                         }
225                         contentlen -= num_to_read;
226                         char_in_buf += num_to_read;
227                 }
228                 /* If I am looking for the filename spec */
229                 if (find_filename) {
230                         path_end = filespec = NULL;
231                         x = strlen("filename=\"");
232                         marker = find_sequence(buf, char_in_buf, "filename=\"", x );
233                         if (0 <= marker) {
234                                 marker += x;  /* Index beyond the filename marker */
235                                 path_start = &buf[marker];
236                                 for (path_end = path_start, x = 0; x < char_in_buf-marker; x++, path_end++) {
237                                         if ('\\' == *path_end) {        /* convert backslashses to forward slashes */
238                                                 *path_end = '/';
239                                         }
240                                         if ('\"' == *path_end) {        /* If at the end of the file name spec */
241                                                 *path_end = '\0';               /* temporarily null terminate the file spec for basename */
242                                                 filespec = basename(path_start);
243                                                 *path_end = '\"';
244                                                 break;
245                                         }
246                                 }
247                         }
248                         if (filespec) { /* If the file name path was found in the header */
249                                 if (fwrite(buf, 1, marker, fout) != marker) {
250                                         ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
251                                 }
252                                 x = (int)(path_end+1 - filespec);
253                                 if (fwrite(filespec, 1, x, fout) != x) {
254                                         ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
255                                 }
256                                 x = (int)(path_end+1 - buf);
257                                 memmove(buf, &(buf[x]), char_in_buf-x);
258                                 char_in_buf -= x;
259                         }
260                         find_filename = 0;
261                 } else { /* I am looking for the boundary marker */
262                         marker = find_sequence(buf, char_in_buf, boundary, boundary_len);
263                         if (0 > marker) {
264                                 if (char_in_buf < (boundary_len)) {
265                                         /*no possibility to find the boundary, write all you have */
266                                         if (fwrite(buf, 1, char_in_buf, fout) != char_in_buf) {
267                                                 ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
268                                         }
269                                         char_in_buf = 0;
270                                 } else {
271                                         /* write all except for area where the boundary marker could be */
272                                         if (fwrite(buf, 1, char_in_buf -(boundary_len -1), fout) != char_in_buf - (boundary_len - 1)) {
273                                                 ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
274                                         }
275                                         x = char_in_buf -(boundary_len -1);
276                                         memmove(buf, &(buf[x]), char_in_buf-x);
277                                         char_in_buf = (boundary_len -1);
278                                 }
279                         } else {
280                                 /* write up through the boundary, then look for filename in the rest */
281                                 if (fwrite(buf, 1, marker + boundary_len, fout) != marker + boundary_len) {
282                                         ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
283                                 }
284                                 x = marker + boundary_len;
285                                 memmove(buf, &(buf[x]), char_in_buf-x);
286                                 char_in_buf -= marker + boundary_len;
287                                 find_filename =1;
288                         }
289                 }
290         }
291         return 0;
292 }
293
294 static int http_post_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_vars, struct ast_variable *headers)
295 {
296         struct ast_variable *var, *cookies;
297         unsigned long ident = 0;
298         FILE *f;
299         int content_len = 0;
300         struct ast_str *post_dir;
301         GMimeMessage *message;
302         int message_count = 0;
303         char * boundary_marker = NULL;
304
305         if (method != AST_HTTP_POST) {
306                 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
307                 return -1;
308         }
309
310         if (!astman_is_authed(ast_http_manid_from_vars(headers))) {
311                 ast_http_error(ser, 403, "Access Denied", "Sorry, I cannot let you do that, Dave.");
312                 return -1;
313         }
314
315         if (!urih) {
316                 ast_http_error(ser, 400, "Missing URI handle", "There was an error parsing the request");
317                 return -1;
318         }
319
320         cookies = ast_http_get_cookies(headers);
321         for (var = cookies; var; var = var->next) {
322                 if (!strcasecmp(var->name, "mansession_id")) {
323                         sscanf(var->value, "%30lx", &ident);
324                         break;
325                 }
326         }
327         if (cookies) {
328                 ast_variables_destroy(cookies);
329         }
330
331         if (ident == 0) {
332                 ast_http_error(ser, 401, "Unauthorized", "You are not authorized to make this request.");
333                 return -1;
334         }
335         if (!astman_verify_session_writepermissions(ident, EVENT_FLAG_CONFIG)) {
336                 ast_http_error(ser, 401, "Unauthorized", "You are not authorized to make this request.");
337                 return -1;
338         }
339
340         if (!(f = tmpfile())) {
341                 ast_log(LOG_ERROR, "Could not create temp file.\n");
342                 ast_http_error(ser, 500, "Internal server error", "Could not create temp file.");
343                 return -1;
344         }
345
346         for (var = headers; var; var = var->next) {
347                 fprintf(f, "%s: %s\r\n", var->name, var->value);
348
349                 if (!strcasecmp(var->name, "Content-Length")) {
350                         if ((sscanf(var->value, "%30u", &content_len)) != 1) {
351                                 ast_log(LOG_ERROR, "Invalid Content-Length in POST request!\n");
352                                 fclose(f);
353                                 ast_http_error(ser, 500, "Internal server error", "Invalid Content-Length in POST request!");
354                                 return -1;
355                         }
356                         ast_debug(1, "Got a Content-Length of %d\n", content_len);
357                 } else if (!strcasecmp(var->name, "Content-Type")) {
358                         boundary_marker = strstr(var->value, "boundary=");
359                         if (boundary_marker) {
360                                 boundary_marker += strlen("boundary=");
361                         }
362                 }
363         }
364
365         fprintf(f, "\r\n");
366
367         if (0 > readmimefile(ser->f, f, boundary_marker, content_len)) {
368                 if (option_debug) {
369                         ast_log(LOG_DEBUG, "Cannot find boundary marker in POST request.\n");
370                 }
371                 fclose(f);
372
373                 return -1;
374         }
375
376         if (fseek(f, SEEK_SET, 0)) {
377                 ast_log(LOG_ERROR, "Failed to seek temp file back to beginning.\n");
378                 fclose(f);
379                 ast_http_error(ser, 500, "Internal server error", "Failed to seek temp file back to beginning.");
380                 return -1;
381         }
382
383         post_dir = urih->data;
384
385         message = parse_message(f); /* Takes ownership and will close f */
386
387         if (!message) {
388                 ast_log(LOG_ERROR, "Error parsing MIME data\n");
389
390                 ast_http_error(ser, 400, "Bad Request", "The was an error parsing the request.");
391                 return -1;
392         }
393
394         if (!(message_count = process_message(message, ast_str_buffer(post_dir)))) {
395                 ast_log(LOG_ERROR, "Invalid MIME data, found no parts!\n");
396                 g_object_unref(message);
397                 ast_http_error(ser, 400, "Bad Request", "The was an error parsing the request.");
398                 return -1;
399         }
400         g_object_unref(message);
401
402         ast_http_error(ser, 200, "OK", "File successfully uploaded.");
403         return 0;
404 }
405
406 static int __ast_http_post_load(int reload)
407 {
408         struct ast_config *cfg;
409         struct ast_variable *v;
410         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
411
412         cfg = ast_config_load2("http.conf", "http", config_flags);
413         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
414                 return 0;
415         }
416
417         if (reload) {
418                 ast_http_uri_unlink_all_with_key(__FILE__);
419         }
420
421         if (cfg) {
422                 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
423                         if (!strcasecmp(v->name, "prefix")) {
424                                 ast_copy_string(prefix, v->value, sizeof(prefix));
425                                 if (prefix[strlen(prefix)] == '/') {
426                                         prefix[strlen(prefix)] = '\0';
427                                 }
428                         }
429                 }
430
431                 for (v = ast_variable_browse(cfg, "post_mappings"); v; v = v->next) {
432                         struct ast_http_uri *urih;
433                         struct ast_str *ds;
434
435                         if (!(urih = ast_calloc(sizeof(*urih), 1))) {
436                                 ast_config_destroy(cfg);
437                                 return -1;
438                         }
439
440                         if (!(ds = ast_str_create(32))) {
441                                 ast_free(urih);
442                                 ast_config_destroy(cfg);
443                                 return -1;
444                         }
445
446                         urih->description = ast_strdup("HTTP POST mapping");
447                         urih->uri = ast_strdup(v->name);
448                         ast_str_set(&ds, 0, "%s", v->value);
449                         urih->data = ds;
450                         urih->has_subtree = 0;
451                         urih->callback = http_post_callback;
452                         urih->key = __FILE__;
453                         urih->mallocd = urih->dmallocd = 1;
454
455                         ast_http_uri_link(urih);
456                 }
457
458                 ast_config_destroy(cfg);
459         }
460         return 0;
461 }
462
463 static int unload_module(void)
464 {
465         ast_http_uri_unlink_all_with_key(__FILE__);
466
467         return 0;
468 }
469
470 static int reload(void)
471 {
472         __ast_http_post_load(1);
473
474         return AST_MODULE_LOAD_SUCCESS;
475 }
476
477 static int load_module(void)
478 {
479         g_mime_init(0);
480
481         __ast_http_post_load(0);
482
483         return AST_MODULE_LOAD_SUCCESS;
484 }
485
486 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "HTTP POST support",
487         .load = load_module,
488         .unload = unload_module,
489         .reload = reload,
490 );