iconv: Bail out of the loop when an illegal sequence of bytes occurs.
[elinks/elinks-j605.git] / src / session / session.c
blob244a97ea69e4a56955fe1874494c4842e0170eb9
1 /** Sessions managment - you'll find things here which you wouldn't expect
2 * @file */
4 #ifdef HAVE_CONFIG_H
5 #include "config.h"
6 #endif
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
12 #include "elinks.h"
14 #include "bfu/dialog.h"
15 #include "bookmarks/bookmarks.h"
16 #include "cache/cache.h"
17 #include "config/home.h"
18 #include "config/options.h"
19 #include "dialogs/menu.h"
20 #include "dialogs/status.h"
21 #include "document/document.h"
22 #include "document/html/frames.h"
23 #include "document/refresh.h"
24 #include "document/renderer.h"
25 #include "document/view.h"
26 #include "globhist/globhist.h"
27 #include "intl/gettext/libintl.h"
28 #include "main/event.h"
29 #include "main/object.h"
30 #include "main/timer.h"
31 #include "network/connection.h"
32 #include "network/state.h"
33 #include "osdep/newwin.h"
34 #include "protocol/protocol.h"
35 #include "protocol/uri.h"
36 #ifdef CONFIG_SCRIPTING_SPIDERMONKEY
37 # include "scripting/smjs/smjs.h"
38 #endif
39 #include "session/download.h"
40 #include "session/history.h"
41 #include "session/location.h"
42 #include "session/session.h"
43 #include "session/task.h"
44 #include "terminal/tab.h"
45 #include "terminal/terminal.h"
46 #include "terminal/window.h"
47 #include "util/conv.h"
48 #include "util/error.h"
49 #include "util/memlist.h"
50 #include "util/memory.h"
51 #include "util/string.h"
52 #include "util/time.h"
53 #include "viewer/text/draw.h"
54 #include "viewer/text/form.h"
55 #include "viewer/text/link.h"
56 #include "viewer/text/view.h"
59 struct file_to_load {
60 LIST_HEAD(struct file_to_load);
62 struct session *ses;
63 unsigned int req_sent:1;
64 int pri;
65 struct cache_entry *cached;
66 unsigned char *target_frame;
67 struct uri *uri;
68 struct download download;
71 /** This structure and related functions are used to maintain information
72 * for instances opened in new windows. We store all related session info like
73 * URI and base session to clone from so that when the new instance connects
74 * we can look up this information. In case of failure the session information
75 * has a timeout */
76 struct session_info {
77 LIST_HEAD(struct session_info);
79 int id;
80 timer_id_T timer;
81 struct session *ses;
82 struct uri *uri;
83 struct uri *referrer;
84 enum task_type task;
85 enum cache_mode cache_mode;
88 #define file_to_load_is_active(ftl) ((ftl)->req_sent && is_in_progress_state((ftl)->download.state))
91 INIT_LIST_OF(struct session, sessions);
93 enum remote_session_flags remote_session_flags;
96 static struct file_to_load *request_additional_file(struct session *,
97 unsigned char *,
98 struct uri *, int);
100 static window_handler_T tabwin_func;
103 static INIT_LIST_OF(struct session_info, session_info);
104 static int session_info_id = 1;
106 static struct session_info *
107 get_session_info(int id)
109 struct session_info *info;
111 foreach (info, session_info) {
112 struct session *ses;
114 if (info->id != id) continue;
116 /* Make sure the info->ses session is still with us. */
117 foreach (ses, sessions)
118 if (ses == info->ses)
119 return info;
121 info->ses = NULL;
122 return info;
125 return NULL;
128 static void
129 done_session_info(struct session_info *info)
131 del_from_list(info);
132 kill_timer(&info->timer);
134 if (info->uri) done_uri(info->uri);
135 if (info->referrer) done_uri(info->referrer);
136 mem_free(info);
139 void
140 done_saved_session_info(void)
142 while (!list_empty(session_info))
143 done_session_info(session_info.next);
146 /** Timer callback for session_info.timer. As explained in install_timer(),
147 * this function must erase the expired timer ID from all variables. */
148 static void
149 session_info_timeout(int id)
151 struct session_info *info = get_session_info(id);
153 if (!info) return;
154 info->timer = TIMER_ID_UNDEF;
155 /* The expired timer ID has now been erased. */
156 done_session_info(info);
160 add_session_info(struct session *ses, struct uri *uri, struct uri *referrer,
161 enum cache_mode cache_mode, enum task_type task)
163 struct session_info *info = mem_calloc(1, sizeof(*info));
165 if (!info) return -1;
167 info->id = session_info_id++;
168 /* I don't know what a reasonable start up time for a new instance is
169 * but it won't hurt to have a few seconds atleast. --jonas */
170 install_timer(&info->timer, (milliseconds_T) 10000,
171 (void (*)(void *)) session_info_timeout,
172 (void *) (long) info->id);
174 info->ses = ses;
175 info->task = task;
176 info->cache_mode = cache_mode;
178 if (uri) info->uri = get_uri_reference(uri);
179 if (referrer) info->referrer = get_uri_reference(referrer);
181 add_to_list(session_info, info);
183 return info->id;
186 static struct session *
187 init_saved_session(struct terminal *term, int id)
189 struct session_info *info = get_session_info(id);
190 struct session *ses;
192 if (!info) return NULL;
194 ses = init_session(info->ses, term, info->uri, 0);
196 if (!ses) {
197 done_session_info(info);
198 return ses;
201 /* Only do the ses_goto()-thing for target=_blank. */
202 if (info->uri && info->task != TASK_NONE) {
203 /* The init_session() call would have started the download but
204 * not with the requested cache mode etc. so interrupt that
205 * download . */
206 abort_loading(ses, 1);
208 ses->reloadlevel = info->cache_mode;
209 set_session_referrer(ses, info->referrer);
210 ses_goto(ses, info->uri, NULL, NULL, info->cache_mode,
211 info->task, 0);
214 done_session_info(info);
216 return ses;
219 static struct session *
220 get_master_session(void)
222 struct session *ses;
224 foreach (ses, sessions)
225 if (ses->tab->term->master) {
226 struct window *current_tab = get_current_tab(ses->tab->term);
228 return current_tab ? current_tab->data : NULL;
231 return NULL;
234 /** @relates session */
235 struct download *
236 get_current_download(struct session *ses)
238 struct download *download = NULL;
240 if (!ses) return NULL;
242 if (ses->task.type)
243 download = &ses->loading;
244 else if (have_location(ses))
245 download = &cur_loc(ses)->download;
247 if (download && is_in_state(download->state, S_OK)) {
248 struct file_to_load *ftl;
250 foreach (ftl, ses->more_files)
251 if (file_to_load_is_active(ftl))
252 return &ftl->download;
255 /* Note that @download isn't necessarily NULL here,
256 * if @ses->more_files is empty. -- Miciah */
257 return download;
260 void
261 print_error_dialog(struct session *ses, struct connection_state state,
262 struct uri *uri, enum connection_priority priority)
264 struct string msg;
265 unsigned char *uristring;
267 /* Don't show error dialogs for missing CSS stylesheets */
268 if (priority == PRI_CSS
269 || !init_string(&msg))
270 return;
272 uristring = uri ? get_uri_string(uri, URI_PUBLIC) : NULL;
273 if (uristring) {
274 #ifdef CONFIG_UTF8
275 if (ses->tab->term->utf8_cp)
276 decode_uri(uristring);
277 else
278 #endif /* CONFIG_UTF8 */
279 decode_uri_for_display(uristring);
280 add_format_to_string(&msg,
281 _("Unable to retrieve %s", ses->tab->term),
282 uristring);
283 mem_free(uristring);
284 add_to_string(&msg, ":\n\n");
287 add_to_string(&msg, get_state_message(state, ses->tab->term));
289 info_box(ses->tab->term, MSGBOX_FREE_TEXT,
290 N_("Error"), ALIGN_CENTER,
291 msg.source);
293 /* TODO: retry */
296 static void
297 abort_files_load(struct session *ses, int interrupt)
299 while (1) {
300 struct file_to_load *ftl;
301 int more = 0;
303 foreach (ftl, ses->more_files) {
304 if (!file_to_load_is_active(ftl))
305 continue;
307 more = 1;
308 cancel_download(&ftl->download, interrupt);
311 if (!more) break;
315 void
316 free_files(struct session *ses)
318 struct file_to_load *ftl;
320 abort_files_load(ses, 0);
321 foreach (ftl, ses->more_files) {
322 if (ftl->cached) object_unlock(ftl->cached);
323 if (ftl->uri) done_uri(ftl->uri);
324 mem_free_if(ftl->target_frame);
326 free_list(ses->more_files);
332 static void request_frameset(struct session *, struct frameset_desc *, int);
334 static void
335 request_frame(struct session *ses, unsigned char *name,
336 struct uri *uri, int depth)
338 struct location *loc = cur_loc(ses);
339 struct frame *frame;
341 assertm(have_location(ses), "request_frame: no location");
342 if_assert_failed return;
344 foreach (frame, loc->frames) {
345 struct document_view *doc_view;
347 if (c_strcasecmp(frame->name, name))
348 continue;
350 foreach (doc_view, ses->scrn_frames) {
351 if (doc_view->vs == &frame->vs && doc_view->document->frame_desc) {
352 request_frameset(ses, doc_view->document->frame_desc, depth);
353 return;
357 request_additional_file(ses, name, frame->vs.uri, PRI_FRAME);
358 return;
361 frame = mem_calloc(1, sizeof(*frame));
362 if (!frame) return;
364 frame->name = stracpy(name);
365 if (!frame->name) {
366 mem_free(frame);
367 return;
370 init_vs(&frame->vs, uri, -1);
372 add_to_list(loc->frames, frame);
374 request_additional_file(ses, name, frame->vs.uri, PRI_FRAME);
377 static void
378 request_frameset(struct session *ses, struct frameset_desc *frameset_desc, int depth)
380 int i;
382 if (depth > HTML_MAX_FRAME_DEPTH) return;
384 depth++; /* Inheritation counter (recursion brake ;) */
386 for (i = 0; i < frameset_desc->n; i++) {
387 struct frame_desc *frame_desc = &frameset_desc->frame_desc[i];
389 if (frame_desc->subframe) {
390 request_frameset(ses, frame_desc->subframe, depth);
391 } else if (frame_desc->name && frame_desc->uri) {
392 request_frame(ses, frame_desc->name,
393 frame_desc->uri, depth);
398 #ifdef CONFIG_CSS
399 static inline void
400 load_css_imports(struct session *ses, struct document_view *doc_view)
402 struct document *document = doc_view->document;
403 struct uri *uri;
404 int index;
406 if (!document) return;
408 foreach_uri (uri, index, &document->css_imports) {
409 request_additional_file(ses, "", uri, PRI_CSS);
412 #else
413 #define load_css_imports(ses, doc_view)
414 #endif
416 #ifdef CONFIG_ECMASCRIPT
417 static inline void
418 load_ecmascript_imports(struct session *ses, struct document_view *doc_view)
420 struct document *document = doc_view->document;
421 struct uri *uri;
422 int index;
424 if (!document) return;
426 foreach_uri (uri, index, &document->ecmascript_imports) {
427 request_additional_file(ses, "", uri, /* XXX */ PRI_CSS);
430 #else
431 #define load_ecmascript_imports(ses, doc_view)
432 #endif
434 NONSTATIC_INLINE void
435 load_frames(struct session *ses, struct document_view *doc_view)
437 struct document *document = doc_view->document;
439 if (!document || !document->frame_desc) return;
440 request_frameset(ses, document->frame_desc, 0);
442 foreach (doc_view, ses->scrn_frames) {
443 load_css_imports(ses, doc_view);
444 load_ecmascript_imports(ses, doc_view);
448 /** Timer callback for session.display_timer. As explained in install_timer(),
449 * this function must erase the expired timer ID from all variables. */
450 void
451 display_timer(struct session *ses)
453 timeval_T start, stop, duration;
454 milliseconds_T t;
456 timeval_now(&start);
457 draw_formatted(ses, 3);
458 timeval_now(&stop);
459 timeval_sub(&duration, &start, &stop);
461 t = mult_ms(timeval_to_milliseconds(&duration), DISPLAY_TIME);
462 if (t < DISPLAY_TIME_MIN) t = DISPLAY_TIME_MIN;
463 install_timer(&ses->display_timer, t,
464 (void (*)(void *)) display_timer,
465 ses);
466 /* The expired timer ID has now been erased. */
468 load_frames(ses, ses->doc_view);
469 load_css_imports(ses, ses->doc_view);
470 load_ecmascript_imports(ses, ses->doc_view);
471 process_file_requests(ses);
475 struct questions_entry {
476 LIST_HEAD(struct questions_entry);
478 void (*callback)(struct session *, void *);
479 void *data;
482 INIT_LIST_OF(struct questions_entry, questions_queue);
485 void
486 check_questions_queue(struct session *ses)
488 while (!list_empty(questions_queue)) {
489 struct questions_entry *q = questions_queue.next;
491 q->callback(ses, q->data);
492 del_from_list(q);
493 mem_free(q);
497 void
498 add_questions_entry(void (*callback)(struct session *, void *), void *data)
500 struct questions_entry *q = mem_alloc(sizeof(*q));
502 if (!q) return;
504 q->callback = callback;
505 q->data = data;
506 add_to_list(questions_queue, q);
509 #ifdef CONFIG_SCRIPTING
510 static void
511 maybe_pre_format_html(struct cache_entry *cached, struct session *ses)
513 struct fragment *fragment;
514 static int pre_format_html_event = EVENT_NONE;
516 if (!cached || cached->preformatted)
517 return;
519 /* The script called from here may indirectly call
520 * garbage_collection(). If the refcount of the cache entry
521 * were 0, it could then be freed, and the
522 * cached->preformatted assignment at the end of this function
523 * would crash. Normally, the document has a reference to the
524 * cache entry, and that suffices. However, if the cache
525 * entry was loaded to satisfy e.g. USEMAP="imgmap.html#map",
526 * then cached->object.refcount == 0 here, and must be
527 * incremented.
529 * cached->object.refcount == 0 is safe while the cache entry
530 * is being loaded, because garbage_collection() calls
531 * is_entry_used(), which checks whether any connection is
532 * using the cache entry. But loading has ended before this
533 * point. */
534 object_lock(cached);
536 fragment = get_cache_fragment(cached);
537 if (!fragment) goto unlock_and_return;
539 /* We cannot do anything if the data are fragmented. */
540 if (!list_is_singleton(cached->frag)) goto unlock_and_return;
542 set_event_id(pre_format_html_event, "pre-format-html");
543 trigger_event(pre_format_html_event, ses, cached);
545 /* XXX: Keep this after the trigger_event, because hooks might call
546 * normalize_cache_entry()! */
547 cached->preformatted = 1;
549 unlock_and_return:
550 object_unlock(cached);
552 #endif
554 static int
555 check_incomplete_redirects(struct cache_entry *cached)
557 assert(cached);
559 cached = follow_cached_redirects(cached);
560 if (cached && !cached->redirect) {
561 /* XXX: This is not quite true, but does that difference
562 * matter here? */
563 return cached->incomplete;
566 return 0;
570 session_is_loading(struct session *ses)
572 struct download *download = get_current_download(ses);
574 if (!download) return 0;
576 if (!is_in_result_state(download->state))
577 return 1;
579 /* The validness of download->cached (especially the download struct in
580 * ses->loading) is hard to maintain so check before using it.
581 * Related to bug 559. */
582 if (download->cached
583 && cache_entry_is_valid(download->cached)
584 && check_incomplete_redirects(download->cached))
585 return 1;
587 return 0;
590 void
591 doc_loading_callback(struct download *download, struct session *ses)
593 int submit = 0;
595 if (is_in_result_state(download->state)) {
596 #ifdef CONFIG_SCRIPTING
597 maybe_pre_format_html(download->cached, ses);
598 #endif
599 kill_timer(&ses->display_timer);
601 draw_formatted(ses, 1);
603 if (get_cmd_opt_bool("auto-submit")) {
604 if (!list_empty(ses->doc_view->document->forms)) {
605 get_cmd_opt_bool("auto-submit") = 0;
606 submit = 1;
610 load_frames(ses, ses->doc_view);
611 load_css_imports(ses, ses->doc_view);
612 load_ecmascript_imports(ses, ses->doc_view);
613 process_file_requests(ses);
615 start_document_refreshes(ses);
617 if (!is_in_state(download->state, S_OK)) {
618 print_error_dialog(ses, download->state,
619 ses->doc_view->document->uri,
620 download->pri);
623 } else if (is_in_transfering_state(download->state)
624 && ses->display_timer == TIMER_ID_UNDEF) {
625 display_timer(ses);
628 check_questions_queue(ses);
629 print_screen_status(ses);
631 #ifdef CONFIG_GLOBHIST
632 if (download->pri != PRI_CSS) {
633 unsigned char *title = ses->doc_view->document->title;
634 struct uri *uri;
636 if (download->conn)
637 uri = download->conn->proxied_uri;
638 else if (download->cached)
639 uri = download->cached->uri;
640 else
641 uri = NULL;
643 if (uri)
644 add_global_history_item(struri(uri), title, time(NULL));
646 #endif
648 if (submit) auto_submit_form(ses);
651 static void
652 file_loading_callback(struct download *download, struct file_to_load *ftl)
654 if (ftl->download.cached && ftl->cached != ftl->download.cached) {
655 if (ftl->cached) object_unlock(ftl->cached);
656 ftl->cached = ftl->download.cached;
657 object_lock(ftl->cached);
660 /* FIXME: We need to do content-type check here! However, we won't
661 * handle properly the "Choose action" dialog now :(. */
662 if (ftl->cached && !ftl->cached->redirect_get && download->pri != PRI_CSS) {
663 struct session *ses = ftl->ses;
664 struct uri *loading_uri = ses->loading_uri;
665 unsigned char *target_frame = null_or_stracpy(ses->task.target.frame);
667 ses->loading_uri = ftl->uri;
668 mem_free_set(&ses->task.target.frame, null_or_stracpy(ftl->target_frame));
669 setup_download_handler(ses, &ftl->download, ftl->cached, 1);
670 ses->loading_uri = loading_uri;
671 mem_free_set(&ses->task.target.frame, target_frame);
674 doc_loading_callback(download, ftl->ses);
677 static struct file_to_load *
678 request_additional_file(struct session *ses, unsigned char *name, struct uri *uri, int pri)
680 struct file_to_load *ftl;
682 if (uri->protocol == PROTOCOL_UNKNOWN) {
683 return NULL;
686 /* XXX: We cannot run the external handler here, because
687 * request_additional_file() is called many times for a single URL
688 * (normally the foreach() right below catches them all). Anyway,
689 * having <frame src="mailto:foo"> would be just weird, wouldn't it?
690 * --pasky */
691 if (get_protocol_external_handler(ses->tab->term, uri)) {
692 return NULL;
695 foreach (ftl, ses->more_files) {
696 if (compare_uri(ftl->uri, uri, URI_BASE)) {
697 if (ftl->pri > pri) {
698 ftl->pri = pri;
699 move_download(&ftl->download, &ftl->download, pri);
701 return NULL;
705 ftl = mem_calloc(1, sizeof(*ftl));
706 if (!ftl) return NULL;
708 ftl->uri = get_uri_reference(uri);
709 ftl->target_frame = stracpy(name);
710 ftl->download.callback = (download_callback_T *) file_loading_callback;
711 ftl->download.data = ftl;
712 ftl->pri = pri;
713 ftl->ses = ses;
715 add_to_list(ses->more_files, ftl);
717 return ftl;
720 static void
721 load_additional_file(struct file_to_load *ftl, enum cache_mode cache_mode)
723 struct document_view *doc_view = current_frame(ftl->ses);
724 struct uri *referrer = doc_view && doc_view->document
725 ? doc_view->document->uri : NULL;
727 load_uri(ftl->uri, referrer, &ftl->download, ftl->pri, cache_mode, -1);
730 void
731 process_file_requests(struct session *ses)
733 if (ses->status.processing_file_requests) return;
734 ses->status.processing_file_requests = 1;
736 while (1) {
737 struct file_to_load *ftl;
738 int more = 0;
740 foreach (ftl, ses->more_files) {
741 if (ftl->req_sent)
742 continue;
744 ftl->req_sent = 1;
746 load_additional_file(ftl, CACHE_MODE_NORMAL);
747 more = 1;
750 if (!more) break;
753 ses->status.processing_file_requests = 0;
757 static void
758 dialog_goto_url_open(void *data)
760 dialog_goto_url((struct session *) data, NULL);
763 /** @returns 0 if the first session was not properly initialized and
764 * setup_session() should be called on the session as well. */
765 static int
766 setup_first_session(struct session *ses, struct uri *uri)
768 /* [gettext_accelerator_context(setup_first_session)] */
769 struct terminal *term = ses->tab->term;
771 if (!*get_opt_str("protocol.http.user_agent", NULL)) {
772 info_box(term, 0,
773 N_("Warning"), ALIGN_CENTER,
774 N_("You have an empty string in protocol.http.user_agent - "
775 "this was a default value in the past, substituted by "
776 "default ELinks User-Agent string. However, currently "
777 "this means that NO User-Agent HEADER "
778 "WILL BE SENT AT ALL - if this is really what you want, "
779 "set its value to \" \", otherwise please delete the line "
780 "with this setting from your configuration file (if you "
781 "have no idea what I'm talking about, just do this), so "
782 "that the correct default setting will be used. Apologies for "
783 "any inconvience caused."));
786 if (!get_opt_bool("config.saving_style_w", NULL)) {
787 struct option *opt = get_opt_rec(config_options, "config.saving_style_w");
788 opt->value.number = 1;
789 option_changed(ses, opt);
790 if (get_opt_int("config.saving_style", NULL) != 3) {
791 info_box(term, 0,
792 N_("Warning"), ALIGN_CENTER,
793 N_("You have option config.saving_style set to "
794 "a de facto obsolete value. The configuration "
795 "saving algorithms of ELinks were changed from "
796 "the last time you upgraded ELinks. Now, only "
797 "those options which you actually changed are "
798 "saved to the configuration file, instead of "
799 "all the options. This simplifies our "
800 "situation greatly when we see that some option "
801 "has an inappropriate default value or we need to "
802 "change the semantics of some option in a subtle way. "
803 "Thus, we recommend you change the value of "
804 "config.saving_style option to 3 in order to get "
805 "the \"right\" behaviour. Apologies for any "
806 "inconvience caused."));
810 if (first_use) {
811 /* Only open the goto URL dialog if no URI was passed on the
812 * command line. */
813 void *handler = uri ? NULL : dialog_goto_url_open;
815 first_use = 0;
817 msg_box(term, NULL, 0,
818 N_("Welcome"), ALIGN_CENTER,
819 N_("Welcome to ELinks!\n\n"
820 "Press ESC for menu. Documentation is available in "
821 "Help menu."),
822 ses, 1,
823 MSG_BOX_BUTTON(N_("~OK"), handler, B_ENTER | B_ESC));
825 /* If there is no URI the goto dialog will pop up so there is
826 * no need to call setup_session(). */
827 if (!uri) return 1;
829 #ifdef CONFIG_BOOKMARKS
830 } else if (!uri && get_opt_bool("ui.sessions.auto_restore", NULL)) {
831 unsigned char *folder; /* UTF-8 */
833 folder = get_auto_save_bookmark_foldername_utf8();
834 if (folder) {
835 open_bookmark_folder(ses, folder);
836 mem_free(folder);
838 return 1;
839 #endif
842 /* If there's a URI to load we have to call */
843 return 0;
846 /** First load the current URI of the base session. In most cases it will just
847 * be fetched from the cache so that the new tab will not appear ``empty' while
848 * loading the real URI or showing the goto URL dialog. */
849 static void
850 setup_session(struct session *ses, struct uri *uri, struct session *base)
852 if (base && have_location(base)) {
853 ses_load(ses, get_uri_reference(cur_loc(base)->vs.uri),
854 NULL, NULL, CACHE_MODE_ALWAYS, TASK_FORWARD);
855 if (ses->doc_view && ses->doc_view->vs
856 && base->doc_view && base->doc_view->vs) {
857 struct view_state *vs = ses->doc_view->vs;
859 destroy_vs(vs, 1);
860 copy_vs(vs, base->doc_view->vs);
862 ses->doc_view->vs = vs;
866 if (uri) {
867 goto_uri(ses, uri);
869 } else if (!goto_url_home(ses)) {
870 if (get_opt_bool("ui.startup_goto_dialog", NULL)) {
871 dialog_goto_url_open(ses);
876 /** @relates session */
877 struct session *
878 init_session(struct session *base_session, struct terminal *term,
879 struct uri *uri, int in_background)
881 struct session *ses = mem_calloc(1, sizeof(*ses));
883 if (!ses) return NULL;
885 ses->tab = init_tab(term, ses, tabwin_func);
886 if (!ses->tab) {
887 mem_free(ses);
888 return NULL;
891 ses->option = copy_option(config_options,
892 CO_SHALLOW | CO_NO_LISTBOX_ITEM);
893 create_history(&ses->history);
894 init_list(ses->scrn_frames);
895 init_list(ses->more_files);
896 init_list(ses->type_queries);
897 ses->task.type = TASK_NONE;
898 ses->display_timer = TIMER_ID_UNDEF;
900 #ifdef CONFIG_LEDS
901 init_led_panel(&ses->status.leds);
902 ses->status.ssl_led = register_led(ses, 0);
903 ses->status.insert_mode_led = register_led(ses, 1);
904 ses->status.ecmascript_led = register_led(ses, 2);
905 ses->status.popup_led = register_led(ses, 3);
907 ses->status.download_led = register_led(ses, 5);
908 #endif
909 ses->status.force_show_status_bar = -1;
910 ses->status.force_show_title_bar = -1;
912 add_to_list(sessions, ses);
914 /* Update the status -- most importantly the info about whether to the
915 * show the title, tab and status bar -- _before_ loading the URI so
916 * the document cache is not filled with useless documents if the
917 * content is already cached.
919 * For big document it also reduces memory usage quite a bit because
920 * (atleast that is my interpretation --jonas) the old document will
921 * have a chance to be released before rendering a new one. A few
922 * numbers when opening a new tab while viewing debians package list
923 * for unstable:
925 * 9307 jonas 15 0 34252 30m 5088 S 0.0 12.2 0:03.63 elinks-old
926 * 9305 jonas 15 0 17060 13m 5088 S 0.0 5.5 0:02.07 elinks-new
928 update_status();
930 /* Check if the newly inserted session is the only in the list and do
931 * the special setup for the first session, */
932 if (!list_is_singleton(sessions) || !setup_first_session(ses, uri)) {
933 setup_session(ses, uri, base_session);
936 if (!in_background)
937 switch_to_tab(term, get_tab_number(ses->tab), -1);
939 if (!term->main_menu) activate_bfu_technology(ses, -1);
940 return ses;
943 static void
944 init_remote_session(struct session *ses, enum remote_session_flags *remote_ptr,
945 struct uri *uri)
947 enum remote_session_flags remote = *remote_ptr;
949 if (remote & SES_REMOTE_CURRENT_TAB) {
950 goto_uri(ses, uri);
951 /* Mask out the current tab flag */
952 *remote_ptr = remote & ~SES_REMOTE_CURRENT_TAB;
954 /* Remote session was masked out. Open all following URIs in
955 * new tabs, */
956 if (!*remote_ptr)
957 *remote_ptr = SES_REMOTE_NEW_TAB;
959 } else if (remote & SES_REMOTE_NEW_TAB) {
960 /* FIXME: This is not perfect. Doing multiple -remote
961 * with no URLs will make the goto dialogs
962 * inaccessible. Maybe we should not support this kind
963 * of thing or make the window focus detecting code
964 * more intelligent. --jonas */
965 open_uri_in_new_tab(ses, uri, 0, 0);
967 if (remote & SES_REMOTE_PROMPT_URL) {
968 dialog_goto_url_open(ses);
971 } else if (remote & SES_REMOTE_NEW_WINDOW) {
972 /* FIXME: It is quite rude because we just take the first
973 * possibility and should maybe make it possible to specify
974 * new-screen etc via -remote "openURL(..., new-*)" --jonas */
975 if (!can_open_in_new(ses->tab->term))
976 return;
978 open_uri_in_new_window(ses, uri, NULL,
979 ses->tab->term->environment,
980 CACHE_MODE_NORMAL, TASK_NONE);
982 } else if (remote & SES_REMOTE_ADD_BOOKMARK) {
983 #ifdef CONFIG_BOOKMARKS
984 int uri_cp;
986 if (!uri) return;
987 /** @todo Bug 1066: What is the encoding of struri()?
988 * This code currently assumes the system charset.
989 * It might be best to keep URIs in plain ASCII and
990 * then have a function that reversibly converts them
991 * to IRIs for display in a given encoding. */
992 uri_cp = get_cp_index("System");
993 add_bookmark_cp(NULL, 1, uri_cp, struri(uri), struri(uri));
994 #endif
996 } else if (remote & SES_REMOTE_INFO_BOX) {
997 unsigned char *text;
999 if (!uri) return;
1001 text = memacpy(uri->data, uri->datalen);
1002 if (!text) return;
1004 info_box(ses->tab->term, MSGBOX_FREE_TEXT,
1005 N_("Error"), ALIGN_CENTER,
1006 text);
1008 } else if (remote & SES_REMOTE_PROMPT_URL) {
1009 dialog_goto_url_open(ses);
1015 struct string *
1016 encode_session_info(struct string *info,
1017 LIST_OF(struct string_list_item) *url_list)
1019 struct string_list_item *url;
1021 if (!init_string(info)) return NULL;
1023 foreach (url, *url_list) {
1024 struct string *str = &url->string;
1026 add_bytes_to_string(info, str->source, str->length + 1);
1029 return info;
1032 /** Older elinks versions (up to and including 0.9.1) sends no magic variable and if
1033 * this is detected we fallback to the old session info format. For this format
1034 * the magic member of terminal_info hold the length of the URI string. The
1035 * old format is handled by the default label in the switch.
1037 * The new session info format supports extraction of multiple URIS from the
1038 * terminal_info data member. The magic variable controls how to interpret
1039 * the fields:
1041 * - INTERLINK_NORMAL_MAGIC means use the terminal_info session_info
1042 * variable as an id for a saved session.
1044 * - INTERLINK_REMOTE_MAGIC means use the terminal_info session_info
1045 * variable as the remote session flags. */
1047 decode_session_info(struct terminal *term, struct terminal_info *info)
1049 int len = info->length;
1050 struct session *base_session = NULL;
1051 enum remote_session_flags remote = 0;
1052 unsigned char *str;
1054 switch (info->magic) {
1055 case INTERLINK_NORMAL_MAGIC:
1056 /* Lookup if there are any saved sessions that should be
1057 * resumed using the session_info as an id. The id is derived
1058 * from the value of -base-session command line option in the
1059 * connecting instance.
1061 * At the moment it is only used when opening instances in new
1062 * window to figure out how to initialize it when the new
1063 * instance connects to the master.
1065 * We don't need to handle it for the old format since new
1066 * instances connecting this way will always be of the same
1067 * origin as the master. */
1068 if (init_saved_session(term, info->session_info))
1069 return 1;
1070 break;
1072 case INTERLINK_REMOTE_MAGIC:
1073 /* This could mean some fatal bug but I am unsure if we can
1074 * actually assert it since people could pour all kinds of crap
1075 * down the socket. */
1076 if (!info->session_info) {
1077 INTERNAL("Remote magic with no remote flags");
1078 return 0;
1081 remote = info->session_info;
1083 /* If processing session info from a -remote instance we want
1084 * to hook up with the master so we can handle request for
1085 * stuff in current tab. */
1086 base_session = get_master_session();
1087 if (!base_session) return 0;
1089 break;
1091 default:
1092 /* The old format calculates the session_info and magic members
1093 * as part of the data that should be decoded so we have to
1094 * substract it to get the size of the actual URI data. */
1095 len -= sizeof(info->session_info) + sizeof(info->magic);
1097 /* Extract URI containing @magic bytes */
1098 if (info->magic <= 0 || info->magic > len)
1099 len = 0;
1100 else
1101 len = info->magic;
1104 if (len <= 0) {
1105 if (!remote)
1106 return !!init_session(base_session, term, NULL, 0);
1108 /* Even though there are no URIs we still have to
1109 * handle remote stuff. */
1110 init_remote_session(base_session, &remote, NULL);
1111 return 0;
1114 str = info->data;
1116 /* Extract multiple (possible) NUL terminated URIs */
1117 while (len > 0) {
1118 unsigned char *end = memchr(str, 0, len);
1119 int urilength = end ? end - str : len;
1120 struct uri *uri = NULL;
1121 unsigned char *uristring = memacpy(str, urilength);
1123 if (uristring) {
1124 uri = get_hooked_uri(uristring, base_session, term->cwd);
1125 mem_free(uristring);
1128 len -= urilength + 1;
1129 str += urilength + 1;
1131 if (remote) {
1132 if (!uri) continue;
1134 init_remote_session(base_session, &remote, uri);
1136 } else {
1137 int backgrounded = !list_empty(term->windows);
1138 int bad_url = !uri;
1139 struct session *ses;
1141 if (!uri)
1142 uri = get_uri("about:blank", 0);
1144 ses = init_session(base_session, term, uri, backgrounded);
1145 if (!ses) {
1146 /* End loop if initialization fails */
1147 len = 0;
1148 } else if (bad_url) {
1149 print_error_dialog(ses, connection_state(S_BAD_URL),
1150 NULL, PRI_MAIN);
1155 if (uri) done_uri(uri);
1158 /* If we only initialized remote sessions or didn't manage to add any
1159 * new tabs return zero so the terminal will be destroyed ASAP. */
1160 return remote ? 0 : !list_empty(term->windows);
1164 void
1165 abort_loading(struct session *ses, int interrupt)
1167 if (have_location(ses)) {
1168 struct location *loc = cur_loc(ses);
1170 cancel_download(&loc->download, interrupt);
1171 abort_files_load(ses, interrupt);
1173 abort_preloading(ses, interrupt);
1176 static void
1177 destroy_session(struct session *ses)
1179 struct document_view *doc_view;
1181 assert(ses);
1182 if_assert_failed return;
1184 #ifdef CONFIG_SCRIPTING_SPIDERMONKEY
1185 smjs_detach_session_object(ses);
1186 #endif
1187 destroy_downloads(ses);
1188 abort_loading(ses, 0);
1189 free_files(ses);
1190 if (ses->doc_view) {
1191 detach_formatted(ses->doc_view);
1192 mem_free(ses->doc_view);
1195 foreach (doc_view, ses->scrn_frames)
1196 detach_formatted(doc_view);
1198 free_list(ses->scrn_frames);
1200 destroy_history(&ses->history);
1201 set_session_referrer(ses, NULL);
1203 if (ses->loading_uri) done_uri(ses->loading_uri);
1205 kill_timer(&ses->display_timer);
1207 while (!list_empty(ses->type_queries))
1208 done_type_query(ses->type_queries.next);
1210 if (ses->download_uri) done_uri(ses->download_uri);
1211 mem_free_if(ses->search_word);
1212 mem_free_if(ses->last_search_word);
1213 mem_free_if(ses->status.last_title);
1214 #ifdef CONFIG_ECMASCRIPT
1215 mem_free_if(ses->status.window_status);
1216 #endif
1217 if (ses->option) {
1218 delete_option(ses->option);
1219 ses->option = NULL;
1221 del_from_list(ses);
1224 void
1225 reload(struct session *ses, enum cache_mode cache_mode)
1227 reload_frame(ses, NULL, cache_mode);
1230 void
1231 reload_frame(struct session *ses, unsigned char *name,
1232 enum cache_mode cache_mode)
1234 abort_loading(ses, 0);
1236 if (cache_mode == CACHE_MODE_INCREMENT) {
1237 cache_mode = CACHE_MODE_NEVER;
1238 if (ses->reloadlevel < CACHE_MODE_NEVER)
1239 cache_mode = ++ses->reloadlevel;
1240 } else {
1241 ses->reloadlevel = cache_mode;
1244 if (have_location(ses)) {
1245 struct location *loc = cur_loc(ses);
1246 struct file_to_load *ftl;
1248 #ifdef CONFIG_ECMASCRIPT
1249 loc->vs.ecmascript_fragile = 1;
1250 #endif
1252 /* FIXME: When reloading use loading_callback and set up a
1253 * session task so that the reloading will work even when the
1254 * reloaded document contains redirects. This is needed atleast
1255 * when reloading HTTP auth document after the user has entered
1256 * credentials. */
1257 loc->download.data = ses;
1258 loc->download.callback = (download_callback_T *) doc_loading_callback;
1260 mem_free_set(&ses->task.target.frame, null_or_stracpy(name));
1262 load_uri(loc->vs.uri, ses->referrer, &loc->download, PRI_MAIN, cache_mode, -1);
1264 foreach (ftl, ses->more_files) {
1265 if (file_to_load_is_active(ftl))
1266 continue;
1268 ftl->download.data = ftl;
1269 ftl->download.callback = (download_callback_T *) file_loading_callback;
1271 load_additional_file(ftl, cache_mode);
1277 struct frame *
1278 ses_find_frame(struct session *ses, unsigned char *name)
1280 struct location *loc = cur_loc(ses);
1281 struct frame *frame;
1283 assertm(have_location(ses), "ses_request_frame: no location yet");
1284 if_assert_failed return NULL;
1286 foreachback (frame, loc->frames)
1287 if (!c_strcasecmp(frame->name, name))
1288 return frame;
1290 return NULL;
1293 void
1294 set_session_referrer(struct session *ses, struct uri *referrer)
1296 if (ses->referrer) done_uri(ses->referrer);
1297 ses->referrer = referrer ? get_uri_reference(referrer) : NULL;
1300 static void
1301 tabwin_func(struct window *tab, struct term_event *ev)
1303 struct session *ses = tab->data;
1305 switch (ev->ev) {
1306 case EVENT_ABORT:
1307 if (ses) destroy_session(ses);
1308 if (!list_empty(sessions)) update_status();
1309 break;
1310 case EVENT_INIT:
1311 case EVENT_RESIZE:
1312 tab->resize = 1;
1313 /* fall-through */
1314 case EVENT_REDRAW:
1315 if (!ses || ses->tab != get_current_tab(ses->tab->term))
1316 break;
1318 draw_formatted(ses, tab->resize);
1319 if (tab->resize) {
1320 load_frames(ses, ses->doc_view);
1321 process_file_requests(ses);
1322 tab->resize = 0;
1324 print_screen_status(ses);
1325 break;
1326 case EVENT_KBD:
1327 case EVENT_MOUSE:
1328 if (!ses) break;
1329 /* This check is related to bug 296 */
1330 assert(ses->tab == get_current_tab(ses->tab->term));
1331 send_event(ses, ev);
1332 break;
1337 * Gets the url being viewed by this session. Writes it into @a str.
1338 * A maximum of @a str_size bytes (including null) will be written.
1339 * @relates session
1341 unsigned char *
1342 get_current_url(struct session *ses, unsigned char *str, size_t str_size)
1344 struct uri *uri;
1345 int length;
1347 assert(str && str_size > 0);
1349 uri = have_location(ses) ? cur_loc(ses)->vs.uri : ses->loading_uri;
1351 /* Not looking or loading anything */
1352 if (!uri) return NULL;
1354 /* Ensure that the url size is not greater than str_size.
1355 * We can't just happily strncpy(str, here, str_size)
1356 * because we have to stop at POST_CHAR, not only at NULL. */
1357 length = int_min(get_real_uri_length(uri), str_size - 1);
1359 return safe_strncpy(str, struri(uri), length + 1);
1363 * Gets the title of the page being viewed by this session. Writes it into
1364 * @a str. A maximum of @a str_size bytes (including null) will be written.
1365 * @relates session
1367 unsigned char *
1368 get_current_title(struct session *ses, unsigned char *str, size_t str_size)
1370 struct document_view *doc_view = current_frame(ses);
1372 assert(str && str_size > 0);
1374 /* Ensure that the title is defined */
1375 /* TODO: Try globhist --jonas */
1376 if (doc_view && doc_view->document->title)
1377 return safe_strncpy(str, doc_view->document->title, str_size);
1379 return NULL;
1383 * Gets the url of the link currently selected. Writes it into @a str.
1384 * A maximum of @a str_size bytes (including null) will be written.
1385 * @relates session
1387 unsigned char *
1388 get_current_link_url(struct session *ses, unsigned char *str, size_t str_size)
1390 struct link *link = get_current_session_link(ses);
1392 assert(str && str_size > 0);
1394 if (!link) return NULL;
1396 return safe_strncpy(str, link->where ? link->where : link->where_img, str_size);
1399 /** get_current_link_name: returns the name of the current link
1400 * (the text between @<A> and @</A>), @a str is a preallocated string,
1401 * @a str_size includes the null char.
1402 * @relates session */
1403 unsigned char *
1404 get_current_link_name(struct session *ses, unsigned char *str, size_t str_size)
1406 struct link *link = get_current_session_link(ses);
1407 unsigned char *where, *name = NULL;
1409 assert(str && str_size > 0);
1411 if (!link) return NULL;
1413 where = link->where ? link->where : link->where_img;
1414 #ifdef CONFIG_GLOBHIST
1416 struct global_history_item *item;
1418 item = get_global_history_item(where);
1419 if (item) name = item->title;
1421 #endif
1422 if (!name) name = get_link_name(link);
1423 if (!name) name = where;
1425 return safe_strncpy(str, name, str_size);
1428 struct link *
1429 get_current_link_in_view(struct document_view *doc_view)
1431 struct link *link = get_current_link(doc_view);
1433 return link && !link_is_form(link) ? link : NULL;
1436 /** @relates session */
1437 struct link *
1438 get_current_session_link(struct session *ses)
1440 return get_current_link_in_view(current_frame(ses));
1443 /** @relates session */
1445 eat_kbd_repeat_count(struct session *ses)
1447 int count = ses->kbdprefix.repeat_count;
1449 set_kbd_repeat_count(ses, 0);
1451 /* Clear status bar when prefix is eaten (bug 930) */
1452 print_screen_status(ses);
1453 return count;
1456 /** @relates session */
1458 set_kbd_repeat_count(struct session *ses, int new_count)
1460 int old_count = ses->kbdprefix.repeat_count;
1462 if (new_count == old_count)
1463 return old_count;
1465 ses->kbdprefix.repeat_count = new_count;
1467 /* Update the status bar. */
1468 print_screen_status(ses);
1470 /* Clear the old link highlighting. */
1471 draw_formatted(ses, 0);
1473 if (new_count != 0) {
1474 struct document_view *doc_view = current_frame(ses);
1476 highlight_links_with_prefixes_that_start_with_n(ses->tab->term,
1477 doc_view,
1478 new_count);
1481 return new_count;