Revert "int_min instead of int_max. Valgrind said: invalid read"
[elinks.git] / src / session / download.c
blob44d5e84cdf6dad890159cb565b56377062b77445
1 /** Downloads managment
2 * @file */
4 #ifdef HAVE_CONFIG_H
5 #include "config.h"
6 #endif
8 #include <errno.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #ifdef HAVE_SYS_CYGWIN_H
13 #include <sys/cygwin.h>
14 #endif
15 #include <sys/types.h>
16 #ifdef HAVE_FCNTL_H
17 #include <fcntl.h> /* OS/2 needs this after sys/types.h */
18 #endif
19 #include <sys/stat.h>
20 #ifdef HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23 #include <utime.h>
25 #include "elinks.h"
27 #include "bfu/dialog.h"
28 #include "cache/cache.h"
29 #include "config/options.h"
30 #include "dialogs/document.h"
31 #include "dialogs/download.h"
32 #include "dialogs/menu.h"
33 #include "intl/gettext/libintl.h"
34 #include "main/object.h"
35 #include "mime/mime.h"
36 #include "network/connection.h"
37 #include "network/progress.h"
38 #include "network/state.h"
39 #include "osdep/osdep.h"
40 #include "protocol/bittorrent/dialogs.h"
41 #include "protocol/date.h"
42 #include "protocol/protocol.h"
43 #include "protocol/uri.h"
44 #include "session/download.h"
45 #include "session/history.h"
46 #include "session/location.h"
47 #include "session/session.h"
48 #include "session/task.h"
49 #include "terminal/draw.h"
50 #include "terminal/screen.h"
51 #include "terminal/terminal.h"
52 #include "util/conv.h"
53 #include "util/error.h"
54 #include "util/file.h"
55 #include "util/lists.h"
56 #include "util/memlist.h"
57 #include "util/memory.h"
58 #include "util/string.h"
59 #include "util/time.h"
62 /* TODO: tp_*() should be in separate file, I guess? --pasky */
65 INIT_LIST_OF(struct file_download, downloads);
67 int
68 download_is_progressing(struct download *download)
70 return download
71 && download->state == S_TRANS
72 && has_progress(download->progress);
75 int
76 are_there_downloads(void)
78 struct file_download *file_download;
80 foreach (file_download, downloads)
81 if (!file_download->external_handler)
82 return 1;
84 return 0;
88 static void download_data(struct download *download, struct file_download *file_download);
90 struct file_download *
91 init_file_download(struct uri *uri, struct session *ses, unsigned char *file, int fd)
93 struct file_download *file_download;
95 file_download = mem_calloc(1, sizeof(*file_download));
96 if (!file_download) return NULL;
98 /* Actually we could allow fragments in the URI and just change all the
99 * places that compares and shows the URI, but for now it is much
100 * easier this way. */
101 file_download->uri = get_composed_uri(uri, URI_BASE);
102 if (!file_download->uri) {
103 mem_free(file_download);
104 return NULL;
107 init_download_display(file_download);
109 file_download->file = file;
110 file_download->handle = fd;
112 file_download->download.callback = (download_callback_T *) download_data;
113 file_download->download.data = file_download;
114 file_download->ses = ses;
115 /* The tab may be closed, but we will still want to ie. open the
116 * handler on that terminal. */
117 file_download->term = ses->tab->term;
119 object_nolock(file_download, "file_download"); /* Debugging purpose. */
120 add_to_list(downloads, file_download);
122 return file_download;
126 void
127 abort_download(struct file_download *file_download)
129 #if 0
130 /* When hacking to cleanup the download code, remove lots of duplicated
131 * code and implement stuff from bug 435 we should reintroduce this
132 * assertion. Currently it will trigger often and shows that the
133 * download dialog code potentially could access free()d memory. */
134 assert(!is_object_used(file_download));
135 #endif
137 done_download_display(file_download);
139 if (file_download->ses)
140 check_questions_queue(file_download->ses);
142 if (file_download->dlg_data)
143 cancel_dialog(file_download->dlg_data, NULL);
144 cancel_download(&file_download->download, file_download->stop);
145 if (file_download->uri) done_uri(file_download->uri);
147 if (file_download->handle != -1) {
148 prealloc_truncate(file_download->handle, file_download->seek);
149 close(file_download->handle);
152 mem_free_if(file_download->external_handler);
153 if (file_download->file) {
154 if (file_download->delete) unlink(file_download->file);
155 mem_free(file_download->file);
157 del_from_list(file_download);
158 mem_free(file_download);
162 static void
163 kill_downloads_to_file(unsigned char *file)
165 struct file_download *file_download;
167 foreach (file_download, downloads) {
168 if (strcmp(file_download->file, file))
169 continue;
171 file_download = file_download->prev;
172 abort_download(file_download->next);
177 void
178 abort_all_downloads(void)
180 while (!list_empty(downloads))
181 abort_download(downloads.next);
185 void
186 destroy_downloads(struct session *ses)
188 struct file_download *file_download, *next;
189 struct session *s;
191 /* We are supposed to blat all downloads to external handlers belonging
192 * to @ses, but we will refuse to do so if there is another session
193 * bound to this terminal. That looks like the reasonable thing to do,
194 * fulfilling the principle of least astonishment. */
195 foreach (s, sessions) {
196 if (s == ses || s->tab->term != ses->tab->term)
197 continue;
199 foreach (file_download, downloads) {
200 if (file_download->ses != ses)
201 continue;
203 file_download->ses = s;
206 return;
209 foreachsafe (file_download, next, downloads) {
210 if (file_download->ses != ses)
211 continue;
213 if (!file_download->external_handler) {
214 file_download->ses = NULL;
215 continue;
218 abort_download(file_download);
223 static void
224 download_error_dialog(struct file_download *file_download, int saved_errno)
226 unsigned char *emsg = (unsigned char *) strerror(saved_errno);
227 struct session *ses = file_download->ses;
228 struct terminal *term = file_download->term;
230 if (!ses) return;
232 info_box(term, MSGBOX_FREE_TEXT,
233 N_("Download error"), ALIGN_CENTER,
234 msg_text(term, N_("Could not create file '%s':\n%s"),
235 file_download->file, emsg));
238 static int
239 write_cache_entry_to_file(struct cache_entry *cached, struct file_download *file_download)
241 struct fragment *frag;
243 if (file_download->download.progress && file_download->download.progress->seek) {
244 file_download->seek = file_download->download.progress->seek;
245 file_download->download.progress->seek = 0;
246 /* This is exclusive with the prealloc, thus we can perform
247 * this in front of that thing safely. */
248 if (lseek(file_download->handle, file_download->seek, SEEK_SET) < 0) {
249 download_error_dialog(file_download, errno);
250 return 0;
254 foreach (frag, cached->frag) {
255 off_t remain = file_download->seek - frag->offset;
256 int *h = &file_download->handle;
257 ssize_t w;
259 if (remain < 0 || frag->length <= remain)
260 continue;
262 #ifdef USE_OPEN_PREALLOC
263 if (!file_download->seek
264 && (!file_download->download.progress
265 || file_download->download.progress->size > 0)) {
266 close(*h);
267 *h = open_prealloc(file_download->file,
268 O_CREAT|O_WRONLY|O_TRUNC,
269 0666,
270 file_download->download.progress
271 ? file_download->download.progress->size
272 : cached->length);
273 if (*h == -1) {
274 download_error_dialog(file_download, errno);
275 return 0;
277 set_bin(*h);
279 #endif
281 w = safe_write(*h, frag->data + remain, frag->length - remain);
282 if (w == -1) {
283 download_error_dialog(file_download, errno);
284 return 0;
287 file_download->seek += w;
290 return 1;
293 static void
294 abort_download_and_beep(struct file_download *file_download, struct terminal *term)
296 if (term && get_opt_int("document.download.notify_bell")
297 + file_download->notify >= 2) {
298 beep_terminal(term);
301 abort_download(file_download);
304 static void
305 download_data_store(struct download *download, struct file_download *file_download)
307 struct terminal *term = file_download->term;
309 if (!term) {
310 /* No term here, so no beep. --Zas */
311 abort_download(file_download);
312 return;
315 if (is_in_progress_state(download->state)) {
316 if (file_download->dlg_data)
317 redraw_dialog(file_download->dlg_data, 1);
318 return;
321 if (download->state != S_OK) {
322 unsigned char *url = get_uri_string(file_download->uri, URI_PUBLIC);
323 enum connection_state state = download->state;
325 abort_download_and_beep(file_download, term);
327 if (!url) return;
329 info_box(term, MSGBOX_FREE_TEXT,
330 N_("Download error"), ALIGN_CENTER,
331 msg_text(term, N_("Error downloading %s:\n\n%s"),
332 url, get_state_message(state, term)));
333 mem_free(url);
334 return;
337 if (file_download->external_handler) {
338 prealloc_truncate(file_download->handle, file_download->seek);
339 close(file_download->handle);
340 file_download->handle = -1;
341 exec_on_terminal(term, file_download->external_handler,
342 file_download->file,
343 file_download->block ? TERM_EXEC_FG : TERM_EXEC_BG);
344 file_download->delete = 0;
345 abort_download_and_beep(file_download, term);
346 return;
349 if (file_download->notify) {
350 unsigned char *url = get_uri_string(file_download->uri, URI_PUBLIC);
352 /* This is apparently a little racy. Deleting the box item will
353 * update the download browser _after_ the notification dialog
354 * has been drawn whereby it will be hidden. This should make
355 * the download browser update before launcing any
356 * notification. */
357 done_download_display(file_download);
359 if (url) {
360 info_box(term, MSGBOX_FREE_TEXT,
361 N_("Download"), ALIGN_CENTER,
362 msg_text(term, N_("Download complete:\n%s"), url));
363 mem_free(url);
367 if (file_download->remotetime
368 && get_opt_bool("document.download.set_original_time")) {
369 struct utimbuf foo;
371 foo.actime = foo.modtime = file_download->remotetime;
372 utime(file_download->file, &foo);
375 abort_download_and_beep(file_download, term);
378 static void
379 download_data(struct download *download, struct file_download *file_download)
381 struct cache_entry *cached = download->cached;
383 if (!cached || is_in_queued_state(download->state)) {
384 download_data_store(download, file_download);
385 return;
388 if (cached->last_modified)
389 file_download->remotetime = parse_date(&cached->last_modified, NULL, 0, 1);
391 if (cached->redirect && file_download->redirect_cnt++ < MAX_REDIRECTS) {
392 cancel_download(&file_download->download, 0);
394 assertm(compare_uri(cached->uri, file_download->uri, 0),
395 "Redirecting using bad base URI");
397 done_uri(file_download->uri);
399 file_download->uri = get_uri_reference(cached->redirect);
400 file_download->download.state = S_WAIT_REDIR;
402 if (file_download->dlg_data)
403 redraw_dialog(file_download->dlg_data, 1);
405 load_uri(file_download->uri, cached->uri, &file_download->download,
406 PRI_DOWNLOAD, CACHE_MODE_NORMAL,
407 download->progress ? download->progress->start : 0);
409 return;
412 if (!write_cache_entry_to_file(cached, file_download)) {
413 detach_connection(download, file_download->seek);
414 abort_download(file_download);
415 return;
418 detach_connection(download, file_download->seek);
419 download_data_store(download, file_download);
423 /* XXX: We assume that resume is everytime zero in lun's callbacks. */
424 struct lun_hop {
425 struct terminal *term;
426 unsigned char *ofile, *file;
428 void (*callback)(struct terminal *, unsigned char *, void *, int);
429 void *data;
432 enum {
433 COMMON_DOWNLOAD_DO = 0,
434 CONTINUE_DOWNLOAD_DO
437 struct cmdw_hop {
438 int magic; /* Must be first --witekfl */
439 struct session *ses;
440 unsigned char *real_file;
443 struct codw_hop {
444 int magic; /* must be first --witekfl */
445 struct type_query *type_query;
446 unsigned char *real_file;
447 unsigned char *file;
450 struct cdf_hop {
451 unsigned char **real_file;
452 int safe;
454 void (*callback)(struct terminal *, int, void *, int);
455 void *data;
458 static void
459 lun_alternate(void *lun_hop_)
461 struct lun_hop *lun_hop = lun_hop_;
463 lun_hop->callback(lun_hop->term, lun_hop->file, lun_hop->data, 0);
464 mem_free_if(lun_hop->ofile);
465 mem_free(lun_hop);
468 static void
469 lun_cancel(void *lun_hop_)
471 struct lun_hop *lun_hop = lun_hop_;
473 lun_hop->callback(lun_hop->term, NULL, lun_hop->data, 0);
474 mem_free_if(lun_hop->ofile);
475 mem_free_if(lun_hop->file);
476 mem_free(lun_hop);
479 static void
480 lun_overwrite(void *lun_hop_)
482 struct lun_hop *lun_hop = lun_hop_;
484 lun_hop->callback(lun_hop->term, lun_hop->ofile, lun_hop->data, 0);
485 mem_free_if(lun_hop->file);
486 mem_free(lun_hop);
489 static void common_download_do(struct terminal *term, int fd, void *data, int resume);
491 static void
492 lun_resume(void *lun_hop_)
494 struct lun_hop *lun_hop = lun_hop_;
495 struct cdf_hop *cdf_hop = lun_hop->data;
497 int magic = *(int *)cdf_hop->data;
499 if (magic == CONTINUE_DOWNLOAD_DO) {
500 struct cmdw_hop *cmdw_hop = mem_calloc(1, sizeof(*cmdw_hop));
502 if (!cmdw_hop) {
503 lun_cancel(lun_hop);
504 return;
505 } else {
506 struct codw_hop *codw_hop = cdf_hop->data;
507 struct type_query *type_query = codw_hop->type_query;
509 cmdw_hop->magic = COMMON_DOWNLOAD_DO;
510 cmdw_hop->ses = type_query->ses;
511 /* FIXME: Current ses->download_uri is overwritten here --witekfl */
512 cmdw_hop->ses->download_uri = get_uri_reference(type_query->uri);
514 if (type_query->external_handler) mem_free_if(codw_hop->file);
515 tp_cancel(type_query);
516 mem_free(codw_hop);
518 cdf_hop->real_file = &cmdw_hop->real_file;
519 cdf_hop->data = cmdw_hop;
520 cdf_hop->callback = common_download_do;
523 lun_hop->callback(lun_hop->term, lun_hop->ofile, lun_hop->data, 1);
524 mem_free_if(lun_hop->file);
525 mem_free(lun_hop);
529 static void
530 lookup_unique_name(struct terminal *term, unsigned char *ofile, int resume,
531 void (*callback)(struct terminal *, unsigned char *, void *, int),
532 void *data)
534 /* [gettext_accelerator_context(.lookup_unique_name)] */
535 struct lun_hop *lun_hop;
536 unsigned char *file;
537 int overwrite;
539 ofile = expand_tilde(ofile);
541 /* Minor code duplication to prevent useless call to get_opt_int()
542 * if possible. --Zas */
543 if (resume) {
544 callback(term, ofile, data, resume);
545 return;
548 /* !overwrite means always silently overwrite, which may be admitelly
549 * indeed a little confusing ;-) */
550 overwrite = get_opt_int("document.download.overwrite");
551 if (!overwrite) {
552 /* Nothing special to do... */
553 callback(term, ofile, data, resume);
554 return;
557 /* Check if file is a directory, and use a default name if it's the
558 * case. */
559 if (file_is_dir(ofile)) {
560 info_box(term, MSGBOX_FREE_TEXT,
561 N_("Download error"), ALIGN_CENTER,
562 msg_text(term, N_("'%s' is a directory."),
563 ofile));
564 mem_free(ofile);
565 callback(term, NULL, data, 0);
566 return;
569 /* Check if the file already exists (file != ofile). */
570 file = get_unique_name(ofile);
572 if (!file || overwrite == 1 || file == ofile) {
573 /* Still nothing special to do... */
574 if (file != ofile) mem_free(ofile);
575 callback(term, file, data, 0);
576 return;
579 /* overwrite == 2 (ask) and file != ofile (=> original file already
580 * exists) */
582 lun_hop = mem_calloc(1, sizeof(*lun_hop));
583 if (!lun_hop) {
584 if (file != ofile) mem_free(file);
585 mem_free(ofile);
586 callback(term, NULL, data, 0);
587 return;
589 lun_hop->term = term;
590 lun_hop->ofile = ofile;
591 lun_hop->file = (file != ofile) ? file : stracpy(ofile);
592 lun_hop->callback = callback;
593 lun_hop->data = data;
595 msg_box(term, NULL, MSGBOX_FREE_TEXT,
596 N_("File exists"), ALIGN_CENTER,
597 msg_text(term, N_("This file already exists:\n"
598 "%s\n\n"
599 "The alternative filename is:\n"
600 "%s"),
601 empty_string_or_(lun_hop->ofile),
602 empty_string_or_(file)),
603 lun_hop, 4,
604 MSG_BOX_BUTTON(N_("Sa~ve under the alternative name"), lun_alternate, B_ENTER),
605 MSG_BOX_BUTTON(N_("~Overwrite the original file"), lun_overwrite, 0),
606 MSG_BOX_BUTTON(N_("~Resume download of the original file"), lun_resume, 0),
607 MSG_BOX_BUTTON(N_("~Cancel"), lun_cancel, B_ESC));
612 static void
613 create_download_file_do(struct terminal *term, unsigned char *file, void *data,
614 int resume)
616 struct cdf_hop *cdf_hop = data;
617 unsigned char *wd;
618 int h = -1;
619 int saved_errno;
620 #ifdef NO_FILE_SECURITY
621 int sf = 0;
622 #else
623 int sf = cdf_hop->safe;
624 #endif
626 if (!file) goto finish;
628 wd = get_cwd();
629 set_cwd(term->cwd);
631 /* Create parent directories if needed. */
632 mkalldirs(file);
634 /* O_APPEND means repositioning at the end of file before each write(),
635 * thus ignoring seek()s and that can hide mysterious bugs. IMHO.
636 * --pasky */
637 h = open(file, O_CREAT | O_WRONLY | (resume ? 0 : O_TRUNC)
638 | (sf && !resume ? O_EXCL : 0),
639 sf ? 0600 : 0666);
640 saved_errno = errno; /* Saved in case of ... --Zas */
642 if (wd) {
643 set_cwd(wd);
644 mem_free(wd);
647 if (h == -1) {
648 info_box(term, MSGBOX_FREE_TEXT,
649 N_("Download error"), ALIGN_CENTER,
650 msg_text(term, N_("Could not create file '%s':\n%s"),
651 file, strerror(saved_errno)));
653 mem_free(file);
654 goto finish;
656 } else {
657 set_bin(h);
659 if (!cdf_hop->safe) {
660 unsigned char *download_dir = get_opt_str("document.download.directory");
661 int i;
663 safe_strncpy(download_dir, file, MAX_STR_LEN);
665 /* Find the used directory so it's available in history */
666 for (i = strlen(download_dir); i >= 0; i--)
667 if (dir_sep(download_dir[i]))
668 break;
669 download_dir[i + 1] = 0;
673 if (cdf_hop->real_file)
674 *cdf_hop->real_file = file;
675 else
676 mem_free(file);
678 finish:
679 cdf_hop->callback(term, h, cdf_hop->data, resume);
680 mem_free(cdf_hop);
683 void
684 create_download_file(struct terminal *term, unsigned char *fi,
685 unsigned char **real_file, int safe, int resume,
686 void (*callback)(struct terminal *, int, void *, int),
687 void *data)
689 struct cdf_hop *cdf_hop = mem_calloc(1, sizeof(*cdf_hop));
690 unsigned char *wd;
692 if (!cdf_hop) {
693 callback(term, -1, data, 0);
694 return;
697 cdf_hop->real_file = real_file;
698 cdf_hop->safe = safe;
699 cdf_hop->callback = callback;
700 cdf_hop->data = data;
702 /* FIXME: The wd bussiness is probably useless here? --pasky */
703 wd = get_cwd();
704 set_cwd(term->cwd);
706 /* Also the tilde will be expanded here. */
707 lookup_unique_name(term, fi, resume, create_download_file_do, cdf_hop);
709 if (wd) {
710 set_cwd(wd);
711 mem_free(wd);
716 static unsigned char *
717 get_temp_name(struct uri *uri)
719 struct string name;
720 unsigned char *extension;
721 /* FIXME
722 * We use tempnam() here, which is unsafe (race condition), for now.
723 * This should be changed at some time, but it needs an in-depth work
724 * of whole download code. --Zas */
725 unsigned char *nm = tempnam(NULL, ELINKS_TEMPNAME_PREFIX);
727 if (!nm) return NULL;
729 if (!init_string(&name)) {
730 free(nm);
731 return NULL;
734 add_to_string(&name, nm);
735 free(nm);
737 extension = get_extension_from_uri(uri);
738 if (extension) {
739 add_shell_safe_to_string(&name, extension, strlen(extension));
740 mem_free(extension);
743 return name.source;
747 static unsigned char *
748 subst_file(unsigned char *prog, unsigned char *file)
750 struct string name;
751 /* When there is no %s in the mailcap entry, the handler program reads
752 * data from stdin instead of a file. */
753 int input = 1;
755 if (!init_string(&name)) return NULL;
757 while (*prog) {
758 int p;
760 for (p = 0; prog[p] && prog[p] != '%'; p++);
762 add_bytes_to_string(&name, prog, p);
763 prog += p;
765 if (*prog == '%') {
766 input = 0;
767 #if defined(HAVE_CYGWIN_CONV_TO_FULL_WIN32_PATH)
768 #ifdef MAX_PATH
769 unsigned char new_path[MAX_PATH];
770 #else
771 unsigned char new_path[1024];
772 #endif
774 cygwin_conv_to_full_win32_path(file, new_path);
775 add_to_string(&name, new_path);
776 #else
777 add_shell_quoted_to_string(&name, file, strlen(file));
778 #endif
779 prog++;
783 if (input) {
784 struct string s;
786 if (init_string(&s)) {
787 add_to_string(&s, "/bin/cat ");
788 add_shell_quoted_to_string(&s, file, strlen(file));
789 add_to_string(&s, " | ");
790 add_string_to_string(&s, &name);
791 done_string(&name);
792 return s.source;
795 return name.source;
800 static void
801 common_download_do(struct terminal *term, int fd, void *data, int resume)
803 struct file_download *file_download;
804 struct cmdw_hop *cmdw_hop = data;
805 unsigned char *file = cmdw_hop->real_file;
806 struct session *ses = cmdw_hop->ses;
807 struct stat buf;
809 mem_free(cmdw_hop);
811 if (!file || fstat(fd, &buf)) return;
813 file_download = init_file_download(ses->download_uri, ses, file, fd);
814 if (!file_download) return;
816 if (resume) file_download->seek = buf.st_size;
818 display_download(ses->tab->term, file_download, ses);
820 load_uri(file_download->uri, ses->referrer, &file_download->download,
821 PRI_DOWNLOAD, CACHE_MODE_NORMAL, file_download->seek);
824 static void
825 common_download(struct session *ses, unsigned char *file, int resume)
827 struct cmdw_hop *cmdw_hop;
829 if (!ses->download_uri) return;
831 cmdw_hop = mem_calloc(1, sizeof(*cmdw_hop));
832 if (!cmdw_hop) return;
833 cmdw_hop->ses = ses;
834 cmdw_hop->magic = COMMON_DOWNLOAD_DO;
836 kill_downloads_to_file(file);
838 create_download_file(ses->tab->term, file, &cmdw_hop->real_file, 0,
839 resume, common_download_do, cmdw_hop);
842 void
843 start_download(void *ses, unsigned char *file)
845 common_download(ses, file, 0);
848 void
849 resume_download(void *ses, unsigned char *file)
851 common_download(ses, file, 1);
856 static void
857 continue_download_do(struct terminal *term, int fd, void *data, int resume)
859 struct codw_hop *codw_hop = data;
860 struct file_download *file_download = NULL;
861 struct type_query *type_query;
863 assert(codw_hop);
864 assert(codw_hop->type_query);
865 assert(codw_hop->type_query->uri);
866 assert(codw_hop->type_query->ses);
868 type_query = codw_hop->type_query;
869 if (!codw_hop->real_file) goto cancel;
871 file_download = init_file_download(type_query->uri, type_query->ses,
872 codw_hop->real_file, fd);
873 if (!file_download) goto cancel;
875 if (type_query->external_handler) {
876 file_download->external_handler = subst_file(type_query->external_handler,
877 codw_hop->file);
878 file_download->delete = 1;
879 file_download->copiousoutput = type_query->copiousoutput;
880 mem_free(codw_hop->file);
881 mem_free_set(&type_query->external_handler, NULL);
884 file_download->block = !!type_query->block;
886 /* Done here and not in init_file_download() so that the external
887 * handler can become initialized. */
888 display_download(term, file_download, type_query->ses);
890 move_download(&type_query->download, &file_download->download, PRI_DOWNLOAD);
891 done_type_query(type_query);
893 mem_free(codw_hop);
894 return;
896 cancel:
897 if (type_query->external_handler) mem_free_if(codw_hop->file);
898 tp_cancel(type_query);
899 mem_free(codw_hop);
902 static void
903 continue_download(void *data, unsigned char *file)
905 struct type_query *type_query = data;
906 struct codw_hop *codw_hop = mem_calloc(1, sizeof(*codw_hop));
908 if (!codw_hop) {
909 tp_cancel(type_query);
910 return;
913 if (type_query->external_handler) {
914 /* FIXME: get_temp_name() calls tempnam(). --Zas */
915 file = get_temp_name(type_query->uri);
916 if (!file) {
917 mem_free(codw_hop);
918 tp_cancel(type_query);
919 return;
923 codw_hop->type_query = type_query;
924 codw_hop->file = file;
925 codw_hop->magic = CONTINUE_DOWNLOAD_DO;
927 kill_downloads_to_file(file);
929 create_download_file(type_query->ses->tab->term, file,
930 &codw_hop->real_file,
931 !!type_query->external_handler, 0,
932 continue_download_do, codw_hop);
936 static struct type_query *
937 init_type_query(struct session *ses, struct download *download,
938 struct cache_entry *cached)
940 struct type_query *type_query;
942 /* There can be only one ... */
943 foreach (type_query, ses->type_queries)
944 if (compare_uri(type_query->uri, ses->loading_uri, 0))
945 return NULL;
947 type_query = mem_calloc(1, sizeof(*type_query));
948 if (!type_query) return NULL;
950 type_query->uri = get_uri_reference(ses->loading_uri);
951 type_query->ses = ses;
952 type_query->target_frame = null_or_stracpy(ses->task.target.frame);
954 type_query->cached = cached;
955 type_query->cgi = cached->cgi;
956 object_lock(type_query->cached);
958 move_download(download, &type_query->download, PRI_MAIN);
959 download->state = S_OK;
961 add_to_list(ses->type_queries, type_query);
963 return type_query;
966 void
967 done_type_query(struct type_query *type_query)
969 /* Unregister any active download */
970 cancel_download(&type_query->download, 0);
972 object_unlock(type_query->cached);
973 done_uri(type_query->uri);
974 mem_free_if(type_query->external_handler);
975 mem_free_if(type_query->target_frame);
976 del_from_list(type_query);
977 mem_free(type_query);
981 void
982 tp_cancel(void *data)
984 struct type_query *type_query = data;
986 /* XXX: Should we really abort? (1 vs 0 as the last param) --pasky */
987 cancel_download(&type_query->download, 1);
988 done_type_query(type_query);
992 void
993 tp_save(struct type_query *type_query)
995 mem_free_set(&type_query->external_handler, NULL);
996 query_file(type_query->ses, type_query->uri, type_query, continue_download, tp_cancel, 1);
999 /** This button handler uses the add_dlg_button() interface so that pressing
1000 * 'Show header' will not close the type query dialog. */
1001 static widget_handler_status_T
1002 tp_show_header(struct dialog_data *dlg_data, struct widget_data *widget_data)
1004 struct type_query *type_query = widget_data->widget->data;
1006 cached_header_dialog(type_query->ses, type_query->cached);
1008 return EVENT_PROCESSED;
1012 /** @bug FIXME: We need to modify this function to take frame data
1013 * instead, as we want to use this function for frames as well (now,
1014 * when frame has content type text/plain, it is ignored and displayed
1015 * as HTML). */
1016 void
1017 tp_display(struct type_query *type_query)
1019 struct view_state *vs;
1020 struct session *ses = type_query->ses;
1021 struct uri *loading_uri = ses->loading_uri;
1022 unsigned char *target_frame = ses->task.target.frame;
1024 ses->loading_uri = type_query->uri;
1025 ses->task.target.frame = type_query->target_frame;
1026 vs = ses_forward(ses, /* type_query->frame */ 0);
1027 if (vs) vs->plain = 1;
1028 ses->loading_uri = loading_uri;
1029 ses->task.target.frame = target_frame;
1031 if (/* !type_query->frame */ 1) {
1032 struct download *old = &type_query->download;
1033 struct download *new = &cur_loc(ses)->download;
1035 new->callback = (download_callback_T *) doc_loading_callback;
1036 new->data = ses;
1038 move_download(old, new, PRI_MAIN);
1041 display_timer(ses);
1042 done_type_query(type_query);
1045 static void
1046 tp_open(struct type_query *type_query)
1048 if (!type_query->external_handler || !*type_query->external_handler) {
1049 tp_display(type_query);
1050 return;
1053 if (type_query->uri->protocol == PROTOCOL_FILE && !type_query->cgi) {
1054 unsigned char *file = get_uri_string(type_query->uri, URI_PATH);
1055 unsigned char *handler = NULL;
1057 if (file) {
1058 decode_uri(file);
1059 handler = subst_file(type_query->external_handler, file);
1060 mem_free(file);
1063 if (handler) {
1064 exec_on_terminal(type_query->ses->tab->term,
1065 handler, "",
1066 type_query->block ? TERM_EXEC_FG : TERM_EXEC_BG);
1067 mem_free(handler);
1070 done_type_query(type_query);
1071 return;
1074 continue_download(type_query, "");
1078 static void
1079 do_type_query(struct type_query *type_query, unsigned char *ct, struct mime_handler *handler)
1081 /* [gettext_accelerator_context(.do_type_query)] */
1082 struct string filename;
1083 unsigned char *description;
1084 unsigned char *desc_sep;
1085 unsigned char *format, *text, *title;
1086 struct dialog *dlg;
1087 #define TYPE_QUERY_WIDGETS_COUNT 8
1088 int widgets = TYPE_QUERY_WIDGETS_COUNT;
1089 struct terminal *term = type_query->ses->tab->term;
1090 struct memory_list *ml;
1091 struct dialog_data *dlg_data;
1092 int selected_widget;
1094 mem_free_set(&type_query->external_handler, NULL);
1096 if (handler) {
1097 type_query->block = handler->block;
1098 if (!handler->ask) {
1099 type_query->external_handler = stracpy(handler->program);
1100 tp_open(type_query);
1101 return;
1104 /* Start preparing for the type query dialog. */
1105 description = handler->description;
1106 desc_sep = *description ? "; " : "";
1107 title = N_("What to do?");
1109 } else {
1110 title = N_("Unknown type");
1111 description = "";
1112 desc_sep = "";
1115 dlg = calloc_dialog(TYPE_QUERY_WIDGETS_COUNT, MAX_STR_LEN * 2);
1116 if (!dlg) return;
1118 if (init_string(&filename)) {
1119 add_mime_filename_to_string(&filename, type_query->uri);
1121 /* Let's make the filename pretty for display & save */
1122 /* TODO: The filename can be the empty string here. See bug 396. */
1123 #ifdef CONFIG_UTF8
1124 if (term->utf8_cp)
1125 decode_uri_string(&filename);
1126 else
1127 #endif /* CONFIG_UTF8 */
1128 decode_uri_string_for_display(&filename);
1131 text = get_dialog_offset(dlg, TYPE_QUERY_WIDGETS_COUNT);
1132 /* For "default directory index pages" with wrong content-type
1133 * the filename can be NULL, e.g. http://www.spamhaus.org in bug 396. */
1134 if (filename.length) {
1135 format = _("What would you like to do with the file '%s' (type: %s%s%s)?", term);
1136 snprintf(text, MAX_STR_LEN, format, filename.source, ct, desc_sep, description);
1137 } else {
1138 format = _("What would you like to do with the file (type: %s%s%s)?", term);
1139 snprintf(text, MAX_STR_LEN, format, ct, desc_sep, description);
1142 done_string(&filename);
1144 dlg->title = _(title, term);
1145 dlg->layouter = generic_dialog_layouter;
1146 dlg->layout.padding_top = 1;
1147 dlg->layout.fit_datalen = 1;
1148 dlg->udata2 = type_query;
1150 add_dlg_text(dlg, text, ALIGN_LEFT, 0);
1152 /* Add input field or text widget with info about the program handler. */
1153 if (!get_cmd_opt_bool("anonymous")) {
1154 unsigned char *field = mem_calloc(1, MAX_STR_LEN);
1156 if (!field) {
1157 mem_free(dlg);
1158 return;
1161 if (handler && handler->program) {
1162 safe_strncpy(field, handler->program, MAX_STR_LEN);
1165 /* xgettext:no-c-format */
1166 add_dlg_field(dlg, _("Program ('%' will be replaced by the filename)", term),
1167 0, 0, NULL, MAX_STR_LEN, field, NULL);
1168 type_query->external_handler = field;
1170 add_dlg_radio(dlg, _("Block the terminal", term), 0, 0, &type_query->block);
1171 selected_widget = 3;
1173 } else if (handler) {
1174 unsigned char *field = text + MAX_STR_LEN;
1176 format = _("The file will be opened with the program '%s'.", term);
1177 snprintf(field, MAX_STR_LEN, format, handler->program);
1178 add_dlg_text(dlg, field, ALIGN_LEFT, 0);
1180 type_query->external_handler = stracpy(handler->program);
1181 if (!type_query->external_handler) {
1182 mem_free(dlg);
1183 return;
1186 widgets--;
1187 selected_widget = 2;
1189 } else {
1190 widgets -= 2;
1191 selected_widget = 1;
1194 /* Add buttons if they are both usable and allowed. */
1196 if (!get_cmd_opt_bool("anonymous") || handler) {
1197 add_dlg_ok_button(dlg, _("~Open", term), B_ENTER,
1198 (done_handler_T *) tp_open, type_query);
1199 } else {
1200 widgets--;
1203 if (!get_cmd_opt_bool("anonymous")) {
1204 add_dlg_ok_button(dlg, _("Sa~ve", term), B_ENTER,
1205 (done_handler_T *) tp_save, type_query);
1206 } else {
1207 widgets--;
1210 add_dlg_ok_button(dlg, _("~Display", term), B_ENTER,
1211 (done_handler_T *) tp_display, type_query);
1213 if (type_query->cached && type_query->cached->head) {
1214 add_dlg_button(dlg, _("Show ~header", term), B_ENTER,
1215 tp_show_header, type_query);
1216 } else {
1217 widgets--;
1220 add_dlg_ok_button(dlg, _("~Cancel", term), B_ESC,
1221 (done_handler_T *) tp_cancel, type_query);
1223 add_dlg_end(dlg, widgets);
1225 ml = getml(dlg, (void *) NULL);
1226 if (!ml) {
1227 /* XXX: Assume that the allocated @external_handler will be
1228 * freed when releasing the @type_query. */
1229 mem_free(dlg);
1230 return;
1233 dlg_data = do_dialog(term, dlg, ml);
1234 /* Don't focus the text field; we want the user to be able
1235 * to select a button by typing the first letter of its label
1236 * without having to first leave the text field. */
1237 if (dlg_data) {
1238 select_widget_by_id(dlg_data, selected_widget);
1242 struct {
1243 unsigned char *type;
1244 unsigned int plain:1;
1245 } static const known_types[] = {
1246 { "text/html", 0 },
1247 { "text/plain", 1 },
1248 { "application/xhtml+xml", 0 }, /* RFC 3236 */
1249 #if CONFIG_DOM
1250 { "application/docbook+xml", 1 },
1251 { "application/rss+xml", 0 },
1252 { "application/xbel+xml", 1 },
1253 { "application/xbel", 1 },
1254 { "application/x-xbel", 1 },
1255 #endif
1256 { NULL, 1 },
1260 setup_download_handler(struct session *ses, struct download *loading,
1261 struct cache_entry *cached, int frame)
1263 struct mime_handler *handler;
1264 struct view_state *vs;
1265 struct type_query *type_query;
1266 unsigned char *ctype = get_content_type(cached);
1267 int plaintext = 1;
1268 int ret = 0;
1269 int xwin, i;
1271 if (!ctype || !*ctype)
1272 goto plaintext_follow;
1274 for (i = 0; known_types[i].type; i++) {
1275 if (strcasecmp(ctype, known_types[i].type))
1276 continue;
1278 plaintext = known_types[i].plain;
1279 goto plaintext_follow;
1282 xwin = ses->tab->term->environment & ENV_XWIN;
1283 handler = get_mime_type_handler(ctype, xwin);
1285 if (!handler && strlen(ctype) >= 4 && !strncasecmp(ctype, "text", 4))
1286 goto plaintext_follow;
1288 type_query = init_type_query(ses, loading, cached);
1289 if (type_query) {
1290 ret = 1;
1291 type_query->copiousoutput = handler->copiousoutput;
1292 #ifdef CONFIG_BITTORRENT
1293 /* A terrible waste of a good MIME handler here, but we want
1294 * to use the type_query this is easier. */
1295 if ((!strcasecmp(ctype, "application/x-bittorrent")
1296 || !strcasecmp(ctype, "application/x-torrent"))
1297 && !get_cmd_opt_bool("anonymous"))
1298 query_bittorrent_dialog(type_query);
1299 else
1300 #endif
1301 do_type_query(type_query, ctype, handler);
1304 mem_free_if(handler);
1306 return ret;
1308 plaintext_follow:
1309 vs = ses_forward(ses, frame);
1310 if (vs) vs->plain = plaintext;
1311 return 0;