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