Re-add HTTP post support by moving to res_http_post.c
[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: 111213 $")
36
37 #include <sys/stat.h>
38 #include <fcntl.h>
39 #include <gmime/gmime.h>
40
41 #include "asterisk/linkedlists.h"
42 #include "asterisk/http.h"
43 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
44 #include "asterisk/tcptls.h"
45 #include "asterisk/manager.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/module.h"
48 #include "asterisk/ast_version.h"
49
50 #define MAX_PREFIX 80
51
52 /* just a little structure to hold callback info for gmime */
53 struct mime_cbinfo {
54         int count;
55         const char *post_dir;
56 };
57
58 /* all valid URIs must be prepended by the string in prefix. */
59 static char prefix[MAX_PREFIX];
60
61 static void post_raw(GMimePart *part, const char *post_dir, const char *fn)
62 {
63         char filename[PATH_MAX];
64         GMimeDataWrapper *content;
65         GMimeStream *stream;
66         int fd;
67
68         snprintf(filename, sizeof(filename), "%s/%s", post_dir, fn);
69
70         ast_debug(1, "Posting raw data to %s\n", filename);
71
72         if ((fd = open(filename, O_CREAT | O_WRONLY, 0666)) == -1) {
73                 ast_log(LOG_WARNING, "Unable to open %s for writing file from a POST!\n", filename);
74
75                 return;
76         }
77
78         stream = g_mime_stream_fs_new(fd);
79
80         content = g_mime_part_get_content_object(part);
81         g_mime_data_wrapper_write_to_stream(content, stream);
82         g_mime_stream_flush(stream);
83
84         g_object_unref(content);
85         g_object_unref(stream);
86 }
87
88 static GMimeMessage *parse_message(FILE *f)
89 {
90         GMimeMessage *message;
91         GMimeParser *parser;
92         GMimeStream *stream;
93
94         stream = g_mime_stream_file_new(f);
95
96         parser = g_mime_parser_new_with_stream(stream);
97         g_mime_parser_set_respect_content_length(parser, 1);
98         
99         g_object_unref(stream);
100
101         message = g_mime_parser_construct_message(parser);
102
103         g_object_unref(parser);
104
105         return message;
106 }
107
108 static void process_message_callback(GMimeObject *part, gpointer user_data)
109 {
110         struct mime_cbinfo *cbinfo = user_data;
111
112         cbinfo->count++;
113
114         /* We strip off the headers before we get here, so should only see GMIME_IS_PART */
115         if (GMIME_IS_MESSAGE_PART(part)) {
116                 ast_log(LOG_WARNING, "Got unexpected GMIME_IS_MESSAGE_PART\n");
117                 return;
118         } else if (GMIME_IS_MESSAGE_PARTIAL(part)) {
119                 ast_log(LOG_WARNING, "Got unexpected GMIME_IS_MESSAGE_PARTIAL\n");
120                 return;
121         } else if (GMIME_IS_MULTIPART(part)) {
122                 GList *l;
123                 
124                 ast_log(LOG_WARNING, "Got unexpected GMIME_IS_MULTIPART, trying to process subparts\n");
125                 l = GMIME_MULTIPART(part)->subparts;
126                 while (l) {
127                         process_message_callback(l->data, cbinfo);
128                         l = l->next;
129                 }
130         } else if (GMIME_IS_PART(part)) {
131                 const char *filename;
132
133                 if (ast_strlen_zero(filename = g_mime_part_get_filename(GMIME_PART(part)))) {
134                         ast_debug(1, "Skipping part with no filename\n");
135                         return;
136                 }
137
138                 post_raw(GMIME_PART(part), cbinfo->post_dir, filename);
139         } else {
140                 ast_log(LOG_ERROR, "Encountered unknown MIME part. This should never happen!\n");
141         }
142 }
143
144 static int process_message(GMimeMessage *message, const char *post_dir)
145 {
146         struct mime_cbinfo cbinfo = {
147                 .count = 0,
148                 .post_dir = post_dir,
149         };
150
151         g_mime_message_foreach_part(message, process_message_callback, &cbinfo);
152
153         return cbinfo.count;
154 }
155
156 static struct ast_str *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 *vars, struct ast_variable *headers, int *status, char **title, int *contentlength)
157 {
158         struct ast_variable *var;
159         unsigned long ident = 0;
160         char buf[4096];
161         FILE *f;
162         size_t res;
163         int content_len = 0;
164         struct ast_str *post_dir;
165         GMimeMessage *message;
166         int message_count = 0;
167
168         if (!urih) {
169                 return ast_http_error((*status = 400),
170                            (*title = ast_strdup("Missing URI handle")),
171                            NULL, "There was an error parsing the request");
172         }
173
174         for (var = vars; var; var = var->next) {
175                 if (strcasecmp(var->name, "mansession_id")) {
176                         continue;
177                 }
178
179                 if (sscanf(var->value, "%lx", &ident) != 1) {
180                         return ast_http_error((*status = 400),
181                                               (*title = ast_strdup("Bad Request")),
182                                               NULL, "The was an error parsing the request.");
183                 }
184
185                 if (!astman_verify_session_writepermissions(ident, EVENT_FLAG_CONFIG)) {
186                         return ast_http_error((*status = 401),
187                                               (*title = ast_strdup("Unauthorized")),
188                                               NULL, "You are not authorized to make this request.");
189                 }
190
191                 break;
192         }
193
194         if (!var) {
195                 return ast_http_error((*status = 401),
196                                       (*title = ast_strdup("Unauthorized")),
197                                       NULL, "You are not authorized to make this request.");
198         }
199
200         if (!(f = tmpfile())) {
201                 ast_log(LOG_ERROR, "Could not create temp file.\n");
202                 return NULL;
203         }
204
205         for (var = headers; var; var = var->next) {
206                 if (!strcasecmp(var->name, "Content-Length")) {
207                         if ((sscanf(var->value, "%u", &content_len)) != 1) {
208                                 ast_log(LOG_ERROR, "Invalid Content-Length in POST request!\n");
209                                 fclose(f);
210
211                                 return NULL;
212                         }
213                         ast_debug(1, "Got a Content-Length of %d\n", content_len);
214                 } else if (!strcasecmp(var->name, "Content-Type")) {
215                         fprintf(f, "Content-Type: %s\r\n\r\n", var->value);
216                 }
217         }
218
219         for (res = sizeof(buf); content_len; content_len -= res) {
220                 if (content_len < res) {
221                         res = content_len;
222                 }
223                 fread(buf, 1, res, ser->f);
224                 fwrite(buf, 1, res, f);
225         }
226
227         if (fseek(f, SEEK_SET, 0)) {
228                 ast_log(LOG_ERROR, "Failed to seek temp file back to beginning.\n");
229                 fclose(f);
230
231                 return NULL;
232         }
233
234         post_dir = urih->data;
235
236         message = parse_message(f); /* Takes ownership and will close f */
237
238         if (!message) {
239                 ast_log(LOG_ERROR, "Error parsing MIME data\n");
240
241                 return ast_http_error((*status = 400),
242                                       (*title = ast_strdup("Bad Request")),
243                                       NULL, "The was an error parsing the request.");
244         }
245
246         if (!(message_count = process_message(message, post_dir->str))) {
247                 ast_log(LOG_ERROR, "Invalid MIME data, found no parts!\n");
248
249                 return ast_http_error((*status = 400),
250                                       (*title = ast_strdup("Bad Request")),
251                                       NULL, "The was an error parsing the request.");
252         }
253
254         return ast_http_error((*status = 200),
255                               (*title = ast_strdup("OK")),
256                               NULL, "File successfully uploaded.");
257 }
258
259 static int __ast_http_post_load(int reload)
260 {
261         struct ast_config *cfg;
262         struct ast_variable *v;
263         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
264
265         if ((cfg = ast_config_load2("http.conf", "http", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
266                 return 0;
267         }
268
269         if (reload) {
270                 ast_http_uri_unlink_all_with_key(__FILE__);
271         }
272
273         if (cfg) {
274                 for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
275                         if (!strcasecmp(v->name, "prefix")) {
276                                 ast_copy_string(prefix, v->value, sizeof(prefix));
277                                 if (prefix[strlen(prefix)] == '/') {
278                                         prefix[strlen(prefix)] = '\0';
279                                 }
280                         }
281                 }
282
283                 for (v = ast_variable_browse(cfg, "post_mappings"); v; v = v->next) {
284                         struct ast_http_uri *urih;
285                         struct ast_str *ds;
286
287                         if (!(urih = ast_calloc(sizeof(*urih), 1))) {
288                                 return -1;
289                         }
290
291                         if (!(ds = ast_str_create(32)))
292                                 return -1;
293
294
295                         urih->description = ast_strdup("HTTP POST mapping");
296                         urih->uri = ast_strdup(v->name);
297                         ast_str_set(&ds, 0, "%s/%s", prefix, v->value);
298                         urih->data = ds;
299                         urih->has_subtree = 0;
300                         urih->supports_get = 0;
301                         urih->supports_post = 1;
302                         urih->callback = http_post_callback;
303                         urih->key = __FILE__;
304
305                         ast_http_uri_link(urih);
306                 }
307
308                 ast_config_destroy(cfg);
309         }
310         return 0;
311 }
312
313 static int unload_module(void)
314 {
315         ast_http_uri_unlink_all_with_key(__FILE__);
316
317         return 0;
318 }
319
320 static int reload(void)
321 {
322
323         __ast_http_post_load(1);
324
325         return AST_MODULE_LOAD_SUCCESS;
326 }
327
328 static int load_module(void)
329 {
330         g_mime_init(0);
331
332         __ast_http_post_load(0);
333
334         return AST_MODULE_LOAD_SUCCESS;
335 }
336
337 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "HTTP POST support",
338         .load = load_module,
339         .unload = unload_module,
340         .reload = reload,
341 );