Disable sockets and a few other things when using NACL.
[mono.git] / mono / metadata / console-unix.c
1 /*
2  * console-io.c: ConsoleDriver internal calls for Unix systems.
3  *
4  * Author:
5  *      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6  *
7  * Copyright (C) 2005-2009 Novell, Inc. (http://www.novell.com)
8  */
9 #if defined(__native_client__)
10 #include "console-null.c"
11 #else
12
13 #include <config.h>
14 #include <glib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <fcntl.h>
18 #include <errno.h>
19 #include <signal.h>
20 #ifdef HAVE_SYS_TIME_H
21 #    include <sys/time.h>
22 #endif
23 #include <sys/types.h>
24 #ifdef HAVE_UNISTD_H
25 #    include <unistd.h>
26 #endif
27 #include <mono/metadata/appdomain.h>
28 #include <mono/metadata/object-internals.h>
29 #include <mono/metadata/class-internals.h>
30 #include <mono/metadata/domain-internals.h>
31 #include <mono/metadata/metadata.h>
32 #include <mono/metadata/threadpool.h>
33
34 /* On solaris, curses.h must come before both termios.h and term.h */
35 #ifdef HAVE_CURSES_H
36 #    include <curses.h>
37 #endif
38 #ifdef HAVE_TERMIOS_H
39 #    include <termios.h>
40 #endif
41 #ifdef HAVE_TERM_H
42 #    include <term.h>
43 #endif
44
45 /* Needed for FIONREAD under solaris */
46 #ifdef HAVE_SYS_FILIO_H
47 #    include <sys/filio.h>
48 #endif
49 #ifdef HAVE_SYS_IOCTL_H
50 #    include <sys/ioctl.h>
51 #endif
52
53 #include <mono/metadata/console-io.h>
54 #include <mono/metadata/exception.h>
55
56 static gboolean setup_finished;
57 static gboolean atexit_called;
58
59 /* The string used to return the terminal to its previous state */
60 static gchar *teardown_str;
61
62 /* The string used to set the terminal into keypad xmit mode after SIGCONT is received */
63 static gchar *keypad_xmit_str;
64
65 #ifdef HAVE_TERMIOS_H
66 /* This is the last state used by Mono, used after a CONT signal is received */
67 static struct termios mono_attr;
68 #endif
69
70 /* static void console_restore_signal_handlers (void); */
71 static void console_set_signal_handlers (void);
72
73 void
74 mono_console_init (void)
75 {
76         int fd;
77
78         /* Make sure the standard file descriptors are opened */
79         fd = open ("/dev/null", O_RDWR);
80         while (fd >= 0 && fd < 3) {
81                 fd = open ("/dev/null", O_RDWR);
82         }
83         close (fd);
84 }
85
86 static struct termios initial_attr;
87
88 MonoBoolean
89 ves_icall_System_ConsoleDriver_Isatty (HANDLE handle)
90 {
91         MONO_ARCH_SAVE_REGS;
92
93         return isatty (GPOINTER_TO_INT (handle));
94 }
95
96 static MonoBoolean
97 set_property (gint property, gboolean value)
98 {
99         struct termios attr;
100         gboolean callset = FALSE;
101         gboolean check;
102         
103         MONO_ARCH_SAVE_REGS;
104
105         if (tcgetattr (STDIN_FILENO, &attr) == -1)
106                 return FALSE;
107
108         check = (attr.c_lflag & property) != 0;
109         if ((value || check) && !(value && check)) {
110                 callset = TRUE;
111                 if (value)
112                         attr.c_lflag |= property;
113                 else
114                         attr.c_lflag &= ~property;
115         }
116
117         if (!callset)
118                 return TRUE;
119
120         if (tcsetattr (STDIN_FILENO, TCSANOW, &attr) == -1)
121                 return FALSE;
122
123         mono_attr = attr;
124         return TRUE;
125 }
126
127 MonoBoolean
128 ves_icall_System_ConsoleDriver_SetEcho (MonoBoolean want_echo)
129 {
130         
131         return set_property (ECHO, want_echo);
132 }
133
134 MonoBoolean
135 ves_icall_System_ConsoleDriver_SetBreak (MonoBoolean want_break)
136 {
137         return set_property (IGNBRK, !want_break);
138 }
139
140 gint32
141 ves_icall_System_ConsoleDriver_InternalKeyAvailable (gint32 timeout)
142 {
143         fd_set rfds;
144         struct timeval tv;
145         struct timeval *tvptr;
146         div_t divvy;
147         int ret, nbytes;
148
149         MONO_ARCH_SAVE_REGS;
150
151         do {
152                 FD_ZERO (&rfds);
153                 FD_SET (STDIN_FILENO, &rfds);
154                 if (timeout >= 0) {
155                         divvy = div (timeout, 1000);
156                         tv.tv_sec = divvy.quot;
157                         tv.tv_usec = divvy.rem;
158                         tvptr = &tv;
159                 } else {
160                         tvptr = NULL;
161                 }
162                 ret = select (STDIN_FILENO + 1, &rfds, NULL, NULL, tvptr);
163         } while (ret == -1 && errno == EINTR);
164
165         if (ret > 0) {
166                 nbytes = 0;
167                 ret = ioctl (STDIN_FILENO, FIONREAD, &nbytes);
168                 if (ret >= 0)
169                         ret = nbytes;
170         }
171
172         return (ret > 0) ? ret : 0;
173 }
174
175 static gint32 cols_and_lines;
176
177 #ifdef TIOCGWINSZ
178 static int
179 terminal_get_dimensions (void)
180 {
181         struct winsize ws;
182         int ret;
183         int save_errno = errno;
184         
185         if (ioctl (STDIN_FILENO, TIOCGWINSZ, &ws) == 0){
186                 ret = (ws.ws_col << 16) | ws.ws_row;
187                 errno = save_errno;
188                 return ret;
189         } 
190         return -1;
191 }
192 #else
193 static int
194 terminal_get_dimensions (void)
195 {
196         return -1;
197 }
198 #endif
199
200 static void
201 tty_teardown (void)
202 {
203         MONO_ARCH_SAVE_REGS;
204
205         if (!setup_finished)
206                 return;
207
208         if (teardown_str != NULL) {
209                 write (STDOUT_FILENO, teardown_str, strlen (teardown_str));
210                 g_free (teardown_str);
211                 teardown_str = NULL;
212         }
213
214         tcflush (STDIN_FILENO, TCIFLUSH);
215         tcsetattr (STDIN_FILENO, TCSANOW, &initial_attr);
216         set_property (ECHO, TRUE);
217         setup_finished = FALSE;
218 }
219
220 static void
221 do_console_cancel_event (void)
222 {
223         static MonoClassField *cancel_handler_field;
224         MonoDomain *domain = mono_domain_get ();
225         MonoClass *klass;
226         MonoDelegate *load_value;
227         MonoMethod *method;
228         MonoMethodMessage *msg;
229         MonoMethod *im;
230         MonoVTable *vtable;
231
232         if (!domain->domain)
233                 return;
234
235         klass = mono_class_from_name (mono_defaults.corlib, "System", "Console");
236         if (klass == NULL)
237                 return;
238
239         if (cancel_handler_field == NULL) {
240                 cancel_handler_field = mono_class_get_field_from_name (klass, "cancel_handler");
241                 g_assert (cancel_handler_field);
242         }
243
244         vtable = mono_class_vtable_full (domain, klass, FALSE);
245         if (vtable == NULL)
246                 return;
247         mono_field_static_get_value (vtable, cancel_handler_field, &load_value);
248         if (load_value == NULL)
249                 return;
250
251         klass = load_value->object.vtable->klass;
252         method = mono_class_get_method_from_name (klass, "BeginInvoke", -1);
253         g_assert (method != NULL);
254         im = mono_get_delegate_invoke (method->klass);
255         msg = mono_method_call_message_new (method, NULL, im, NULL, NULL);
256         mono_thread_pool_add ((MonoObject *) load_value, msg, NULL, NULL);
257 }
258
259 static gboolean in_sigint;
260 static void
261 sigint_handler (int signo)
262 {
263         int save_errno;
264         MONO_ARCH_SAVE_REGS;
265
266         if (in_sigint)
267                 return;
268
269         in_sigint = TRUE;
270         save_errno = errno;
271         do_console_cancel_event ();
272         errno = save_errno;
273         in_sigint = FALSE;
274 }
275
276 static struct sigaction save_sigcont, save_sigint, save_sigwinch;
277
278 static void
279 sigcont_handler (int signo, void *the_siginfo, void *data)
280 {
281         // Ignore error, there is not much we can do in the sigcont handler.
282         tcsetattr (STDIN_FILENO, TCSANOW, &mono_attr);
283
284         if (keypad_xmit_str != NULL)
285                 write (STDOUT_FILENO, keypad_xmit_str, strlen (keypad_xmit_str));
286
287         // Call previous handler
288         if (save_sigcont.sa_sigaction != NULL &&
289             save_sigcont.sa_sigaction != (void *)SIG_DFL &&
290             save_sigcont.sa_sigaction != (void *)SIG_IGN)
291                 (*save_sigcont.sa_sigaction) (signo, the_siginfo, data);
292 }
293
294 static void
295 sigwinch_handler (int signo, void *the_siginfo, void *data)
296 {
297         int dims = terminal_get_dimensions ();
298         if (dims != -1)
299                 cols_and_lines = dims;
300         
301         // Call previous handler
302         if (save_sigwinch.sa_sigaction != NULL &&
303             save_sigwinch.sa_sigaction != (void *)SIG_DFL &&
304             save_sigwinch.sa_sigaction != (void *)SIG_IGN)
305                 (*save_sigwinch.sa_sigaction) (signo, the_siginfo, data);
306 }
307
308 /*
309  * console_set_signal_handlers:
310  *
311  * Installs various signals handlers for the use of the console, as
312  * follows:
313  *
314  * SIGCONT: this is received after the application has resumed execution
315  * if it was suspended with Control-Z before.   This signal handler needs
316  * to resend the terminal sequence to send keyboard in keypad mode (this
317  * is the difference between getting a cuu1 code or a kcuu1 code for up-arrow
318  * for example
319  *
320  * SIGINT: invokes the System.Console.DoConsoleCancelEvent method using
321  * a thread from the thread pool which notifies all registered cancel_event
322  * listeners.
323  *
324  * SIGWINCH: is used to track changes to the console window when a GUI
325  * terminal is resized.    It sets an internal variable that is checked
326  * by System.Console when the Terminfo driver has been activated.
327  */
328 static void
329 console_set_signal_handlers ()
330 {
331         struct sigaction sigcont, sigint, sigwinch;
332
333         memset (&sigcont, 0, sizeof (struct sigaction));
334         memset (&sigint, 0, sizeof (struct sigaction));
335         memset (&sigwinch, 0, sizeof (struct sigaction));
336         
337         // Continuing
338         sigcont.sa_handler = (void *) sigcont_handler;
339         sigcont.sa_flags = 0;
340         sigemptyset (&sigcont.sa_mask);
341         sigaction (SIGCONT, &sigcont, &save_sigcont);
342         
343         // Interrupt handler
344         sigint.sa_handler = sigint_handler;
345         sigint.sa_flags = 0;
346         sigemptyset (&sigint.sa_mask);
347         sigaction (SIGINT, &sigint, &save_sigint);
348
349         // Window size changed
350         sigwinch.sa_handler = (void *) sigwinch_handler;
351         sigwinch.sa_flags = 0;
352         sigemptyset (&sigwinch.sa_mask);
353         sigaction (SIGWINCH, &sigwinch, &save_sigwinch);
354 }
355
356 #if currently_unuused
357 //
358 // Currently unused, should we ever call the restore handler?
359 // Perhaps before calling into Process.Start?
360 //
361 void
362 console_restore_signal_handlers ()
363 {
364         sigaction (SIGCONT, &save_sigcont, NULL);
365         sigaction (SIGINT, &save_sigint, NULL);
366         sigaction (SIGWINCH, &save_sigwinch, NULL);
367 }
368 #endif
369
370 static void
371 set_control_chars (MonoArray *control_chars, const guchar *cc)
372 {
373         /* The index into the array comes from corlib/System/ControlCharacters.cs */
374 #ifdef VINTR
375         mono_array_set (control_chars, gchar, 0, cc [VINTR]);
376 #endif
377 #ifdef VQUIT
378         mono_array_set (control_chars, gchar, 1, cc [VQUIT]);
379 #endif
380 #ifdef VERASE
381         mono_array_set (control_chars, gchar, 2, cc [VERASE]);
382 #endif
383 #ifdef VKILL
384         mono_array_set (control_chars, gchar, 3, cc [VKILL]);
385 #endif
386 #ifdef VEOF
387         mono_array_set (control_chars, gchar, 4, cc [VEOF]);
388 #endif
389 #ifdef VTIME
390         mono_array_set (control_chars, gchar, 5, cc [VTIME]);
391 #endif
392 #ifdef VMIN
393         mono_array_set (control_chars, gchar, 6, cc [VMIN]);
394 #endif
395 #ifdef VSWTC
396         mono_array_set (control_chars, gchar, 7, cc [VSWTC]);
397 #endif
398 #ifdef VSTART
399         mono_array_set (control_chars, gchar, 8, cc [VSTART]);
400 #endif
401 #ifdef VSTOP
402         mono_array_set (control_chars, gchar, 9, cc [VSTOP]);
403 #endif
404 #ifdef VSUSP
405         mono_array_set (control_chars, gchar, 10, cc [VSUSP]);
406 #endif
407 #ifdef VEOL
408         mono_array_set (control_chars, gchar, 11, cc [VEOL]);
409 #endif
410 #ifdef VREPRINT
411         mono_array_set (control_chars, gchar, 12, cc [VREPRINT]);
412 #endif
413 #ifdef VDISCARD
414         mono_array_set (control_chars, gchar, 13, cc [VDISCARD]);
415 #endif
416 #ifdef VWERASE
417         mono_array_set (control_chars, gchar, 14, cc [VWERASE]);
418 #endif
419 #ifdef VLNEXT
420         mono_array_set (control_chars, gchar, 15, cc [VLNEXT]);
421 #endif
422 #ifdef VEOL2
423         mono_array_set (control_chars, gchar, 16, cc [VEOL2]);
424 #endif
425 }
426
427 MonoBoolean
428 ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardown, MonoArray **control_chars, int **size)
429 {
430         int dims;
431
432         MONO_ARCH_SAVE_REGS;
433
434         dims = terminal_get_dimensions ();
435         if (dims == -1){
436                 int cols = 0, rows = 0;
437                                       
438                 char *str = getenv ("COLUMNS");
439                 if (str != NULL)
440                         cols = atoi (str);
441                 str = getenv ("LINES");
442                 if (str != NULL)
443                         rows = atoi (str);
444
445                 if (cols != 0 && rows != 0)
446                         cols_and_lines = (cols << 16) | rows;
447                 else
448                         cols_and_lines = -1;
449         } else {
450                 cols_and_lines = dims;
451         }
452         
453         *size = &cols_and_lines;
454
455         /* 17 is the number of entries set in set_control_chars() above.
456          * NCCS is the total size, but, by now, we only care about those 17 values*/
457         mono_gc_wbarrier_generic_store (control_chars, (MonoObject*) mono_array_new (mono_domain_get (), mono_defaults.byte_class, 17));
458         if (tcgetattr (STDIN_FILENO, &initial_attr) == -1)
459                 return FALSE;
460
461         mono_attr = initial_attr;
462         mono_attr.c_lflag &= ~(ICANON);
463         mono_attr.c_iflag &= ~(IXON|IXOFF);
464         mono_attr.c_cc [VMIN] = 1;
465         mono_attr.c_cc [VTIME] = 0;
466 #ifdef VDSUSP
467         /* Disable C-y being used as a suspend character on OSX */
468         mono_attr.c_cc [VDSUSP] = 255;
469 #endif
470         if (tcsetattr (STDIN_FILENO, TCSANOW, &mono_attr) == -1)
471                 return FALSE;
472
473         set_control_chars (*control_chars, mono_attr.c_cc);
474         /* If initialized from another appdomain... */
475         if (setup_finished)
476                 return TRUE;
477
478         keypad_xmit_str = keypad != NULL ? mono_string_to_utf8 (keypad) : NULL;
479         
480         console_set_signal_handlers ();
481         setup_finished = TRUE;
482         if (!atexit_called) {
483                 if (teardown != NULL)
484                         teardown_str = mono_string_to_utf8 (teardown);
485
486                 atexit (tty_teardown);
487         }
488
489         return TRUE;
490 }
491 #endif /* #if defined(__native_client__) */
492