Revert "strcpy -> strlcpy."
[elinks.git] / src / osdep / osdep.c
blobe45716d91832637ae1c65e3ce476553651676cc4
1 /* Features which vary with the OS */
3 #ifdef HAVE_CONFIG_H
4 #include "config.h"
5 #endif
7 #include <errno.h>
8 #ifdef HAVE_IO_H
9 #include <io.h> /* For win32 && set_bin(). */
10 #endif
11 #include <signal.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #ifdef HAVE_SYS_IOCTL_H
16 #include <sys/ioctl.h>
17 #endif
18 #ifdef HAVE_SYS_SIGNAL_H
19 #include <sys/signal.h>
20 #endif
21 #include <sys/types.h>
22 #ifdef HAVE_SYS_SOCKET_H
23 #include <sys/socket.h> /* Need to be after sys/types.h */
24 #endif
25 #ifdef HAVE_FCNTL_H
26 #include <fcntl.h> /* OS/2 needs this after sys/types.h */
27 #endif
29 /* We need to have it here. Stupid BSD. */
30 #ifdef HAVE_NETINET_IN_H
31 #include <netinet/in.h>
32 #endif
33 #ifdef HAVE_ARPA_INET_H
34 #include <arpa/inet.h>
35 #endif
37 /* This is for some exotic TOS mangling when handling passive FTP sockets. */
38 #ifdef HAVE_NETINET_IN_SYSTM_H
39 #include <netinet/in_systm.h>
40 #else
41 #ifdef HAVE_NETINET_IN_SYSTEM_H
42 #include <netinet/in_system.h>
43 #endif
44 #endif
45 #ifdef HAVE_NETINET_IP_H
46 #include <netinet/ip.h>
47 #endif
49 #ifdef HAVE_TERMIOS_H
50 #include <termios.h>
51 #endif
53 #ifdef HAVE_UNISTD_H
54 #include <unistd.h>
55 #endif
57 #ifdef HAVE_LOCALE_H
58 /* For the sake of SunOS, keep this away from files including
59 * intl/gettext/libintl.h because <locale.h> includes system <libintl.h> which
60 * either includes system gettext header or contains gettext function
61 * declarations. */
62 #include <locale.h>
63 #endif
65 #ifdef HAVE_X11
66 #include <X11/Xlib.h>
67 #include <X11/Xutil.h>
68 #endif
71 #include "elinks.h"
73 #include "main/select.h"
74 #include "osdep/osdep.h"
75 #include "osdep/signals.h"
76 #include "terminal/terminal.h"
77 #include "util/conv.h"
78 #include "util/memory.h"
79 #include "util/string.h"
82 /* Set a file descriptor to non-blocking mode. It returns a non-zero value
83 * on error. */
84 int
85 set_nonblocking_fd(int fd)
87 #if defined(O_NONBLOCK) || defined(O_NDELAY)
88 int flags = fcntl(fd, F_GETFL, 0);
90 if (flags < 0) return -1;
91 #if defined(O_NONBLOCK)
92 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
93 #else
94 return fcntl(fd, F_SETFL, flags | O_NDELAY);
95 #endif
97 #elif defined(FIONBIO)
98 int flag = 1;
100 return ioctl(fd, FIONBIO, &flag);
101 #else
102 return 0;
103 #endif
106 /* Set a file descriptor to blocking mode. It returns a non-zero value on
107 * error. */
109 set_blocking_fd(int fd)
111 #if defined(O_NONBLOCK) || defined(O_NDELAY)
112 int flags = fcntl(fd, F_GETFL, 0);
114 if (flags < 0) return -1;
115 #if defined(O_NONBLOCK)
116 return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
117 #else
118 return fcntl(fd, F_SETFL, flags & ~O_NDELAY);
119 #endif
121 #elif defined(FIONBIO)
122 int flag = 0;
124 return ioctl(fd, FIONBIO, &flag);
125 #else
126 return 0;
127 #endif
130 void
131 set_ip_tos_throughput(int socket)
133 #if defined(IP_TOS) && defined(IPTOS_THROUGHPUT)
134 int on = IPTOS_THROUGHPUT;
136 setsockopt(socket, IPPROTO_IP, IP_TOS, (char *) &on, sizeof(on));
137 #endif
141 get_e(unsigned char *env)
143 char *v = getenv(env);
145 return (v ? atoi(v) : 0);
148 unsigned char *
149 get_cwd(void)
151 int bufsize = 128;
152 unsigned char *buf;
154 while (1) {
155 buf = mem_alloc(bufsize);
156 if (!buf) return NULL;
157 if (getcwd(buf, bufsize)) return buf;
158 mem_free(buf);
160 if (errno == EINTR) continue;
161 if (errno != ERANGE) return NULL;
162 bufsize += 128;
165 return NULL;
168 void
169 set_cwd(unsigned char *path)
171 if (path) while (chdir(path) && errno == EINTR);
174 unsigned char *
175 get_shell(void)
177 unsigned char *shell = GETSHELL;
179 if (!shell || !*shell)
180 shell = DEFAULT_SHELL;
182 return shell;
186 /* Terminal size */
188 #if !defined(CONFIG_OS_OS2) && !defined(CONFIG_OS_WIN32)
190 static void
191 sigwinch(void *s)
193 ((void (*)(void)) s)();
196 void
197 handle_terminal_resize(int fd, void (*fn)(void))
199 install_signal_handler(SIGWINCH, sigwinch, fn, 0);
202 void
203 unhandle_terminal_resize(int fd)
205 install_signal_handler(SIGWINCH, NULL, NULL, 0);
208 void
209 get_terminal_size(int fd, int *x, int *y)
211 struct winsize ws;
213 if (ioctl(1, TIOCGWINSZ, &ws) != -1) {
214 *x = ws.ws_col;
215 *y = ws.ws_row;
216 } else {
217 *x = 0;
218 *y = 0;
221 if (!*x) {
222 *x = get_e("COLUMNS");
223 if (!*x) *x = DEFAULT_TERMINAL_WIDTH;
225 if (!*y) {
226 *y = get_e("LINES");
227 if (!*y) *y = DEFAULT_TERMINAL_HEIGHT;
231 #endif
233 /* Pipe */
235 #if defined(CONFIG_OS_UNIX) || defined(CONFIG_OS_BEOS) || defined(CONFIG_OS_RISCOS)
237 void
238 set_bin(int fd)
243 c_pipe(int *fd)
245 return pipe(fd);
248 #elif defined(CONFIG_OS_OS2) || defined(CONFIG_OS_WIN32)
250 void
251 set_bin(int fd)
253 setmode(fd, O_BINARY);
257 c_pipe(int *fd)
259 int r = pipe(fd);
261 if (!r) {
262 set_bin(fd[0]);
263 set_bin(fd[1]);
266 return r;
269 #endif
271 /* Exec */
274 is_twterm(void) /* Check if it make sense to call a twterm. */
276 static int tw = -1;
278 if (tw == -1) tw = !!getenv("TWDISPLAY");
280 return tw;
284 is_gnuscreen(void)
286 static int screen = -1;
288 if (screen == -1) screen = !!getenv("STY");
290 return screen;
294 #if defined(CONFIG_OS_UNIX) || defined(CONFIG_OS_WIN32)
297 is_xterm(void)
299 static int xt = -1;
301 if (xt == -1) {
302 /* Paraphrased from debian bug 228977:
304 * It is not enough to simply check the DISPLAY env variable,
305 * as it is pretty legal to have a DISPLAY set. While these
306 * days this practice is pretty uncommon, it still makes sense
307 * sometimes, especially for people who prefer the text mode
308 * for some reason. Only relying on DISPLAY will results in bad
309 * codes being written to the terminal.
311 * Any real xterm derivative sets WINDOWID as well.
312 * Unfortunately, konsole is an exception, and it needs to be
313 * checked for separately.
315 * FIXME: The code below still fails to detect some terminals
316 * that do support a title (like the popular PuTTY ssh client).
317 * In general, proper xterm detection is a nightmarish task...
319 * -- Adam Borowski <kilobyte@mimuw.edu.pl> */
320 unsigned char *display = getenv("DISPLAY");
321 unsigned char *windowid = getenv("WINDOWID");
323 if (!windowid || !*windowid)
324 windowid = getenv("KONSOLE_DCOP_SESSION");
325 xt = (display && *display && windowid && *windowid);
328 return xt;
331 #endif
333 unsigned int resize_count = 0;
335 #ifndef CONFIG_OS_OS2
337 #if !(defined(CONFIG_OS_BEOS) && defined(HAVE_SETPGID)) && !defined(CONFIG_OS_WIN32)
340 exe(unsigned char *path)
342 return system(path);
345 #endif
347 static unsigned char *clipboard;
349 unsigned char *
350 get_clipboard_text(void)
352 /* The following support for GNU Screen's clipboard is
353 * disabled for two reasons:
355 * 1. It does not actually return the string from that
356 * clipboard, but rather causes the clipboard contents to
357 * appear in stdin. get_clipboard_text is normally called
358 * because the user pressed a Paste key in an input field,
359 * so the characters end up being inserted in that field;
360 * but if there are newlines in the clipboard, then the
361 * field may lose focus, in which case the remaining
362 * characters may trigger arbitrary actions in ELinks.
364 * 2. It pastes from both GNU Screen's clipboard and the ELinks
365 * internal clipboard. Because set_clipboard_text also sets
366 * them both, the same text would typically get pasted twice.
368 * Users can instead use the GNU Screen key bindings to run the
369 * paste command. This method still suffers from problem 1 but
370 * any user of GNU Screen should know that already. */
371 #if 0
372 /* GNU Screen's clipboard */
373 if (is_gnuscreen()) {
374 struct string str;
376 if (!init_string(&str)) return NULL;
378 add_to_string(&str, "screen -X paste .");
379 if (str.length) exe(str.source);
380 if (str.source) done_string(&str);
382 #endif
384 return stracpy(empty_string_or_(clipboard));
387 void
388 set_clipboard_text(unsigned char *data)
390 /* GNU Screen's clipboard */
391 if (is_gnuscreen()) {
392 struct string str;
394 if (!init_string(&str)) return;
396 add_to_string(&str, "screen -X register . ");
397 add_shell_quoted_to_string(&str, data, strlen(data));
399 if (str.length) exe(str.source);
400 if (str.source) done_string(&str);
403 /* Shouldn't complain about leaks. */
404 if (clipboard) free(clipboard);
405 clipboard = strdup(data);
408 /* Set xterm-like term window's title. */
409 void
410 set_window_title(unsigned char *title, int codepage)
412 struct string filtered;
414 #ifndef HAVE_SYS_CYGWIN_H
415 /* Check if we're in a xterm-like terminal. */
416 if (!is_xterm() && !is_gnuscreen()) return;
417 #endif
419 if (!init_string(&filtered)) return;
421 /* Copy title to filtered if different from NULL */
422 if (title) {
423 unsigned char *scan = title;
424 unsigned char *end = title + strlen(title);
426 /* Remove control characters, so that they cannot
427 * interfere with the command we send to the terminal.
428 * However, do not attempt to limit the title length
429 * to terminal width, because the title is usually
430 * drawn in a different font anyway. */
431 /* Note that this is the right place where to do it, since
432 * potential alternative set_window_title() routines might
433 * want to take different precautions. */
434 for (;;) {
435 unsigned char *charbegin = scan;
436 unicode_val_T unicode
437 = cp_to_unicode(codepage, &scan, end);
438 int charlen = scan - charbegin;
440 if (unicode == UCS_NO_CHAR)
441 break;
443 /* This need not recognize all Unicode control
444 * characters. Only those that can make the
445 * terminal misparse the command. */
446 if (unicode < 0x20
447 || (unicode >= 0x7F && unicode < 0xA0))
448 continue;
450 /* If the title is getting too long, truncate
451 * it and add an ellipsis.
453 * xterm entirely rejects 1024-byte or longer
454 * titles. GNU Screen 4.00.03 misparses
455 * titles longer than 765 bytes, and is unable
456 * to display the title in hardstatus if the
457 * title and other stuff together exceed 766
458 * bytes. So set the limit quite a bit lower. */
459 if (filtered.length + charlen >= 600 - 3) {
460 add_to_string(&filtered, "...");
461 break;
464 add_bytes_to_string(&filtered, charbegin, charlen);
468 /* Send terminal escape sequence + title string */
469 printf("\033]0;%s\a", filtered.source);
471 #if 0
472 /* Miciah don't like this so it is disabled because it changes the
473 * default window name. --jonas */
474 /* Set the GNU screen window name */
475 if (is_gnuscreen())
476 printf("\033k%s\033\134", filtered.source);
477 #endif
479 fflush(stdout);
481 done_string(&filtered);
484 #ifdef HAVE_X11
485 static int x_error = 0;
487 static int
488 catch_x_error(void)
490 x_error = 1;
491 return 0;
493 #endif
495 unsigned char *
496 get_window_title(void)
498 #ifdef HAVE_X11
499 /* Following code is stolen from our beloved vim. */
500 unsigned char *winid;
501 Display *display;
502 Window window, root, parent, *children;
503 XTextProperty text_prop;
504 Status status;
505 unsigned int num_children;
506 unsigned char *ret = NULL;
508 if (!is_xterm())
509 return NULL;
511 winid = getenv("WINDOWID");
512 if (!winid)
513 return NULL;
514 window = (Window) atol(winid);
515 if (!window)
516 return NULL;
518 display = XOpenDisplay(NULL);
519 if (!display)
520 return NULL;
522 /* If WINDOWID is bad, we don't want X to abort us. */
523 x_error = 0;
524 XSetErrorHandler((int (*)(Display *, XErrorEvent *)) catch_x_error);
526 status = XGetWMName(display, window, &text_prop);
527 /* status = XGetWMIconName(x11_display, x11_window, &text_prop); */
528 while (!x_error && (!status || !text_prop.value)) {
529 if (!XQueryTree(display, window, &root, &parent, &children, &num_children))
530 break;
531 if (children)
532 XFree((void *) children);
533 if (parent == root || parent == 0)
534 break;
535 window = parent;
536 status = XGetWMName(display, window, &text_prop);
539 if (!x_error && status && text_prop.value) {
540 ret = stracpy(text_prop.value);
541 XFree(text_prop.value);
544 XCloseDisplay(display);
546 return ret;
547 #else
548 /* At least reset the window title to a blank one. */
549 return stracpy("");
550 #endif
554 resize_window(int width, int height, int old_width, int old_height)
556 #ifdef HAVE_X11
557 /* Following code is stolen from our beloved vim. */
558 unsigned char *winid;
559 Display *display;
560 Window window;
561 Status status;
562 XWindowAttributes attributes;
564 if (!is_xterm())
565 return -1;
567 winid = getenv("WINDOWID");
568 if (!winid)
569 return -1;
570 window = (Window) atol(winid);
571 if (!window)
572 return -1;
574 display = XOpenDisplay(NULL);
575 if (!display)
576 return -1;
578 /* If WINDOWID is bad, we don't want X to abort us. */
579 x_error = 0;
580 XSetErrorHandler((int (*)(Display *, XErrorEvent *)) catch_x_error);
582 status = XGetWindowAttributes(display, window, &attributes);
584 while (!x_error && !status) {
585 Window root, parent, *children;
586 unsigned int num_children;
588 if (!XQueryTree(display, window, &root, &parent, &children, &num_children))
589 break;
590 if (children)
591 XFree((void *) children);
592 if (parent == root || parent == 0)
593 break;
594 window = parent;
595 status = XGetWindowAttributes(display, window, &attributes);
598 if (!x_error && status) {
599 XSizeHints *size_hints;
600 long mask;
601 int px_width = 0;
602 int px_height = 0;
604 /* With xterm 210, a window with 80x24 characters at
605 * a 6x13 font appears to have 484x316 pixels; both
606 * the width and height include four extra pixels.
607 * Computing a new size by scaling these values often
608 * results in windows that cannot display as many
609 * characters as was intended. We can do better if we
610 * can find out the actual size of character cells.
611 * If the terminal emulator has set a window size
612 * increment, assume that is the cell size. */
613 size_hints = XAllocSizeHints();
614 if (size_hints != NULL
615 && XGetWMNormalHints(display, window, size_hints, &mask)
616 && (mask & PResizeInc) != 0) {
617 px_width = attributes.width
618 + (width - old_width) * size_hints->width_inc;
619 px_height = attributes.height
620 + (height - old_height) * size_hints->height_inc;
622 if (px_width <= 0 || px_height <= 0) {
623 double ratio_width = (double) attributes.width / old_width;
624 double ratio_height = (double) attributes.height / old_height;
626 px_width = (int) ((double) width * ratio_width);
627 px_height = (int) ((double) height * ratio_height);
630 if (size_hints)
631 XFree(size_hints);
633 status = XResizeWindow(display, window, px_width, px_height);
634 while (!x_error && !status) {
635 Window root, parent, *children;
636 unsigned int num_children;
638 if (!XQueryTree(display, window, &root, &parent, &children, &num_children))
639 break;
640 if (children)
641 XFree((void *) children);
642 if (parent == root || parent == 0)
643 break;
644 window = parent;
645 status = XResizeWindow(display, window, px_width, px_height);
649 XCloseDisplay(display);
651 return 0;
652 #else
653 return -1;
654 #endif
657 #endif
660 /* Threads */
662 #if defined(HAVE_BEGINTHREAD) || defined(CONFIG_OS_BEOS)
664 struct tdata {
665 void (*fn)(void *, int);
666 int h;
667 unsigned char data[1];
670 void
671 bgt(struct tdata *t)
673 #ifdef SIGPIPE
674 signal(SIGPIPE, SIG_IGN);
675 #endif
676 t->fn(t->data, t->h);
677 write(t->h, "x", 1);
678 close(t->h);
679 free(t);
682 #else
685 start_thread(void (*fn)(void *, int), void *ptr, int l)
687 int p[2];
688 pid_t pid;
690 if (c_pipe(p) < 0) return -1;
691 if (set_nonblocking_fd(p[0]) < 0) return -1;
692 if (set_nonblocking_fd(p[1]) < 0) return -1;
694 pid = fork();
695 if (!pid) {
696 struct terminal *term;
698 /* Close input in this thread; otherwise, if it will live
699 * longer than its parent, it'll block the terminal until it'll
700 * quit as well; this way it will hopefully just die unseen and
701 * in background, causing no trouble. */
702 /* Particularly, when async dns resolving was in progress and
703 * someone quitted ELinks, it could make a delay before the
704 * terminal would be really freed and returned to shell. */
705 foreach (term, terminals)
706 if (term->fdin > 0)
707 close(term->fdin);
709 close(p[0]);
710 fn(ptr, p[1]);
711 write(p[1], "x", 1);
712 close(p[1]);
713 /* We use _exit() here instead of exit(), see
714 * http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC6 for
715 * reasons. Fixed by Sven Neumann <sven@convergence.de>. */
716 _exit(0);
718 if (pid == -1) {
719 close(p[0]);
720 close(p[1]);
721 return -1;
724 close(p[1]);
725 return p[0];
728 #endif
731 #ifndef OS2_MOUSE
732 void
733 want_draw(void)
737 void
738 done_draw(void)
741 #endif
744 #if !defined(CONFIG_OS_WIN32)
746 get_output_handle(void)
748 return 1;
752 get_ctl_handle(void)
754 static int fd = -1;
756 if (isatty(0)) return 0;
757 if (fd < 0) fd = open("/dev/tty", O_RDONLY);
758 return fd;
760 #endif
763 #if !defined(CONFIG_OS_BEOS) && !(defined(HAVE_BEGINTHREAD) && defined(HAVE_READ_KBD)) \
764 && !defined(CONFIG_OS_WIN32)
767 get_input_handle(void)
769 return get_ctl_handle();
772 #endif
774 #ifndef CONFIG_OS_WIN32
776 void
777 init_osdep(void)
779 #ifdef HAVE_LOCALE_H
780 setlocale(LC_ALL, "");
781 #endif
784 #endif
786 #if defined(CONFIG_OS_UNIX) || defined(CONFIG_OS_OS2) || defined(CONFIG_OS_RISCOS)
788 void
789 terminate_osdep(void)
793 #endif
795 #ifndef CONFIG_OS_BEOS
797 void
798 block_stdin(void)
802 void
803 unblock_stdin(void)
807 #endif
810 void
811 elinks_cfmakeraw(struct termios *t)
813 /* This elinks_cfmakeraw() intentionally leaves the following
814 * settings unchanged, even though the standard cfmakeraw()
815 * would change some of them:
817 * - c_cflag & CSIZE: number of bits per character.
818 * Bug 54 asked ELinks not to change this.
819 * - c_cflag & (PARENB | PARODD): parity bit in characters.
820 * Bug 54 asked ELinks not to change this.
821 * - c_iflag & (IXON | IXOFF | IXANY): XON/XOFF flow control.
823 * The reasoning is, if the user has set up unusual values for
824 * those settings before starting ELinks, then the terminal
825 * probably expects those values and ELinks should not mess
826 * with them. */
827 t->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL);
828 t->c_oflag &= ~OPOST;
829 t->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
830 t->c_cc[VMIN] = 1;
831 t->c_cc[VTIME] = 0;
834 #if !defined(CONFIG_MOUSE) || (!defined(CONFIG_GPM) && !defined(CONFIG_SYSMOUSE) && !defined(OS2_MOUSE))
836 void *
837 handle_mouse(int cons, void (*fn)(void *, unsigned char *, int),
838 void *data)
840 return NULL;
843 void
844 unhandle_mouse(void *data)
848 void
849 suspend_mouse(void *data)
853 void
854 resume_mouse(void *data)
858 #endif
860 #ifndef CONFIG_OS_WIN32
861 /* Create a bitmask consisting from system-independent envirnoment modifiers.
862 * This is then complemented by system-specific modifiers in an appropriate
863 * get_system_env() routine. */
864 static int
865 get_common_env(void)
867 int env = 0;
869 if (is_xterm()) env |= ENV_XWIN;
870 if (is_twterm()) env |= ENV_TWIN;
871 if (is_gnuscreen()) env |= ENV_SCREEN;
873 /* ENV_CONSOLE is always set now and indicates that we are working w/ a
874 * displaying-capable character-adressed terminal. Sounds purely
875 * theoretically now, but it already makes some things easier and it
876 * could give us interesting opportunities later (after graphical
877 * frontends will be introduced, when working in some mysterious daemon
878 * mode or who knows what ;). --pasky */
879 env |= ENV_CONSOLE;
881 return env;
883 #endif
885 #if defined(CONFIG_OS_UNIX) || defined(CONFIG_OS_RISCOS)
887 get_system_env(void)
889 return get_common_env();
891 #endif
895 can_resize_window(int environment)
897 return !!(environment & (ENV_OS2VIO | ENV_XWIN));
900 #ifndef CONFIG_OS_OS2
902 can_open_os_shell(int environment)
904 return 1;
907 void
908 set_highpri(void)
911 #endif
914 unsigned char *
915 get_system_str(int xwin)
917 return xwin ? SYSTEM_STR "-xwin" : SYSTEM_STR;