Merge pull request #2668 from lambdageek/dev/monoerror-mono_security
[mono.git] / support / serial.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2
3 /* serial port functions
4  *
5  * Author: Chris Toshok <toshok@ximian.com>
6  */
7
8 #include "map.h"
9 #include "mph.h"
10
11 #include <termios.h>
12 #include <unistd.h>
13 #include <fcntl.h>
14 #include <string.h>
15 #include <errno.h>
16 #if defined(HAVE_POLL_H)
17 #include <poll.h>
18 #elif defined(HAVE_SYS_POLL_H)
19 #include <sys/poll.h>
20 #endif
21 #include <sys/ioctl.h>
22
23 /* This is for ASYNC_*, serial_struct on linux */
24 #if defined(HAVE_LINUX_SERIAL_H)
25 #include <linux/serial.h>
26 #endif
27
28 #include <glib.h>
29
30 /* This is for FIONREAD on solaris */
31 #if defined(sun)
32 #include <sys/filio.h>
33 #endif
34
35 /* sys/time.h (for timeval) is required when using osx 10.3 (but not 10.4) */
36 /* IOKit is a private framework in iOS, so exclude there */
37 #if defined(__APPLE__) && !defined(HOST_IOS) && !defined(HOST_WATCHOS) && !defined(HOST_APPLETVOS)
38 #define HAVE_IOKIT 1
39 #endif
40
41 #if defined(HAVE_IOKIT)
42 #include <sys/time.h>
43 #include <IOKit/IOKitLib.h>
44 #include <IOKit/serial/IOSerialKeys.h>
45 #include <IOKit/serial/ioss.h>
46 #include <IOKit/IOBSD.h>
47 #endif
48
49 /* This is a copy of System.IO.Ports.Handshake */
50 typedef enum {
51         NoneHandshake = 0,
52         XOnXOff = 1,
53         RequestToSend = 2,
54         RequestToSendXOnXOff = 3
55 } MonoHandshake;
56
57 /* This is a copy of System.IO.Ports.Parity */
58 typedef enum {
59         NoneParity = 0,
60         Odd = 1,
61         Even = 2,
62         Mark = 3,
63         Space = 4
64 } MonoParity;
65
66 /* This is a copy of System.IO.Ports.StopBits */
67 typedef enum {
68         NoneStopBits = 0,
69         One = 1,
70         Two = 2,
71         OnePointFive = 3
72 } MonoStopBits;
73
74 /* This is a copy of System.IO.Ports.SerialSignal */
75 typedef enum {
76         NoneSignal,
77         Cd = 1, /* Carrier detect */
78         Cts = 2, /* Clear to send */
79         Dsr = 4, /* Data set ready */
80         Dtr = 8, /* Data terminal ready */
81         Rts = 16  /* Request to send */
82 } MonoSerialSignal;
83
84 /*
85  * Silence the compiler, we do not need these prototypes to be public, since these are only
86  * used by P/Invoke
87  */
88
89 int              open_serial (char *devfile);
90 int              close_serial (int unix_fd);
91 guint32          read_serial (int fd, guchar *buffer, int offset, int count);
92 int              write_serial (int fd, guchar *buffer, int offset, int count, int timeout);
93 int              discard_buffer (int fd, gboolean input);
94 gint32           get_bytes_in_buffer (int fd, gboolean input);
95 gboolean         is_baud_rate_legal (int baud_rate);
96 int              setup_baud_rate (int baud_rate, gboolean *custom_baud_rate);
97 gboolean         set_attributes (int fd, int baud_rate, MonoParity parity, int dataBits, MonoStopBits stopBits, MonoHandshake handshake);
98 MonoSerialSignal get_signals (int fd, gint32 *error);
99 gint32           set_signal (int fd, MonoSerialSignal signal, gboolean value);
100 int              breakprop (int fd);
101 gboolean         poll_serial (int fd, gint32 *error, int timeout);
102 void            *list_serial_devices (void);
103
104 int
105 open_serial (char *devfile)
106 {
107         int fd;
108         fd = open (devfile, O_RDWR | O_NOCTTY | O_NONBLOCK);
109
110         return fd;
111 }
112
113 int
114 close_serial (int unix_fd)
115 {
116         // Linus writes: do not retry close after EINTR
117         return close (unix_fd);
118 }
119
120 guint32
121 read_serial (int fd, guchar *buffer, int offset, int count)
122 {
123         guint32 n;
124  
125         n = read (fd, buffer + offset, count);
126
127         return (guint32) n;
128 }
129
130 int
131 write_serial (int fd, guchar *buffer, int offset, int count, int timeout)
132 {
133         struct pollfd pinfo;
134         guint32 n;
135
136         pinfo.fd = fd;
137         pinfo.events = POLLOUT;
138         pinfo.revents = POLLOUT;
139
140         n = count;
141
142         while (n > 0)
143         {
144                 ssize_t t;
145                         
146                 if (timeout != 0) {
147                         int c;
148                         
149                         while ((c = poll (&pinfo, 1, timeout)) == -1 && errno == EINTR)
150                                 ;
151                         if (c == -1)
152                                 return -1;
153                 }               
154
155                 do {
156                         t = write (fd, buffer + offset, n);
157                 } while (t == -1 && errno == EINTR);
158
159                 if (t < 0)
160                         return -1;
161                 
162                 offset += t;
163                 n -= t; 
164         }
165  
166         return 0;
167 }
168
169 int
170 discard_buffer (int fd, gboolean input)
171 {
172         return tcflush(fd, input ? TCIFLUSH : TCOFLUSH);
173 }
174
175 gint32
176 get_bytes_in_buffer (int fd, gboolean input)
177 {
178         gint32 retval;
179
180         if (ioctl (fd, input ? FIONREAD : TIOCOUTQ, &retval) == -1) {
181                 return -1;
182         }
183
184         return retval;
185 }
186
187 gboolean
188 is_baud_rate_legal (int baud_rate)
189 {
190         gboolean ignore = FALSE;
191         return setup_baud_rate (baud_rate, &ignore) != -1;
192 }
193
194 int
195 setup_baud_rate (int baud_rate, gboolean *custom_baud_rate)
196 {
197         switch (baud_rate)
198         {
199 /*Some values are not defined on OSX and *BSD */
200 #if defined(B921600)
201         case 921600:
202             baud_rate = B921600;
203             break;
204 #endif
205 #if defined(B460800)
206         case 460800:
207             baud_rate = B460800;
208             break;
209 #endif
210         case 230400: 
211             baud_rate = B230400;
212             break;
213         case 115200: 
214             baud_rate = B115200;
215             break;
216         case 57600:
217             baud_rate = B57600;
218             break;
219         case 38400: 
220             baud_rate = B38400;
221             break;
222         case 19200: 
223             baud_rate = B19200;
224             break;
225         case 9600: 
226                 baud_rate = B9600;
227                 break;
228         case 4800: 
229             baud_rate = B4800;
230                 break;
231         case 2400: 
232             baud_rate = B2400;
233                 break;
234         case 1800: 
235             baud_rate = B1800;
236                 break;
237         case 1200: 
238             baud_rate = B1200;
239                 break;
240         case 600: 
241             baud_rate = B600;
242             break;
243         case 300: 
244             baud_rate = B300;
245             break;
246         case 200: 
247             baud_rate = B200;
248             break;
249         case 150: 
250             baud_rate = B150;
251             break;
252         case 134: 
253             baud_rate = B134;
254             break;
255         case 110: 
256             baud_rate = B110;
257             break;
258         case 75: 
259             baud_rate = B75;
260             break;
261         case 50:
262 #ifdef B50
263             baud_rate = B50;
264 #else
265             baud_rate = -1;
266             break;
267 #endif
268         case 0:
269 #ifdef B0
270             baud_rate = B0;
271 #else
272             baud_rate = -1;
273 #endif
274             break;
275         default:
276                 *custom_baud_rate = TRUE;
277                 break;
278         }
279         return baud_rate;
280 }
281
282 gboolean
283 set_attributes (int fd, int baud_rate, MonoParity parity, int dataBits, MonoStopBits stopBits, MonoHandshake handshake)
284 {
285         struct termios newtio;
286         gboolean custom_baud_rate = FALSE;
287
288         if (tcgetattr (fd, &newtio) == -1)
289                 return FALSE;
290
291         newtio.c_cflag |=  (CLOCAL | CREAD);
292         newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ISIG | IEXTEN );
293         newtio.c_oflag &= ~(OPOST);
294         newtio.c_iflag = IGNBRK;
295
296         /* setup baudrate */
297         baud_rate = setup_baud_rate (baud_rate, &custom_baud_rate);
298
299         /* char lenght */
300         newtio.c_cflag &= ~CSIZE;
301         switch (dataBits)
302         {
303         case 5: 
304             newtio.c_cflag |= CS5;
305             break;
306         case 6: 
307             newtio.c_cflag |= CS6;
308             break;
309         case 7: 
310             newtio.c_cflag |= CS7;
311             break;
312         case 8:
313         default:
314                 newtio.c_cflag |= CS8;
315                 break;
316         }
317
318         /* stopbits */
319         switch (stopBits)
320         {
321         case NoneStopBits:
322                 /* Unhandled */
323                 break;
324         case One: /* One */
325                 /* do nothing, the default is one stop bit */
326             newtio.c_cflag &= ~CSTOPB;
327                 break;
328         case Two: /* Two */
329                 newtio.c_cflag |= CSTOPB;
330                 break;
331         case OnePointFive: /* OnePointFive */
332                 /* XXX unhandled */
333                 break;
334         }
335
336         /* parity */
337         newtio.c_iflag &= ~(INPCK | ISTRIP );
338
339         switch (parity)
340         {
341         case NoneParity: /* None */
342             newtio.c_cflag &= ~(PARENB | PARODD);
343             break;
344             
345         case Odd: /* Odd */
346             newtio.c_cflag |= PARENB | PARODD;
347             break;
348             
349         case Even: /* Even */
350             newtio.c_cflag &= ~(PARODD);
351             newtio.c_cflag |= (PARENB);
352             break;
353             
354         case Mark: /* Mark */
355             /* XXX unhandled */
356             break;
357         case Space: /* Space */
358             /* XXX unhandled */
359             break;
360         }
361
362         newtio.c_iflag &= ~(IXOFF | IXON);
363 #ifdef CRTSCTS
364         newtio.c_cflag &= ~CRTSCTS;
365 #endif /* def CRTSCTS */
366
367         switch (handshake)
368         {
369         case NoneHandshake: /* None */
370                 /* do nothing */
371                 break;
372         case RequestToSend: /* RequestToSend (RTS) */
373 #ifdef CRTSCTS
374                 newtio.c_cflag |= CRTSCTS;
375 #endif /* def CRTSCTS */
376                 break;
377         case RequestToSendXOnXOff: /* RequestToSendXOnXOff (RTS + XON/XOFF) */
378 #ifdef CRTSCTS
379                 newtio.c_cflag |= CRTSCTS;
380 #endif /* def CRTSCTS */
381                 /* fall through */
382         case XOnXOff: /* XOnXOff */
383             newtio.c_iflag |= IXOFF | IXON;
384                 break;
385         }
386
387         if (custom_baud_rate == FALSE) {
388                 if (cfsetospeed (&newtio, baud_rate) < 0 || cfsetispeed (&newtio, baud_rate) < 0)
389                         return FALSE;
390         } else {
391 #if __linux__ || defined(HAVE_IOKIT)
392
393                 /* On Linux to set a custom baud rate, we must set the
394                  * "standard" baud_rate to 38400.   On Apple we set it purely
395                  * so that tcsetattr has something to use (and report back later), but
396                  * the Apple specific API is still opaque to these APIs, see:
397                  * https://developer.apple.com/library/mac/samplecode/SerialPortSample/Listings/SerialPortSample_SerialPortSample_c.html#//apple_ref/doc/uid/DTS10000454-SerialPortSample_SerialPortSample_c-DontLinkElementID_4
398                  */
399                 if (cfsetospeed (&newtio, B38400) < 0 || cfsetispeed (&newtio, B38400) < 0)
400                         return FALSE;
401 #endif
402         }
403
404         if (tcsetattr (fd, TCSANOW, &newtio) < 0)
405                 return FALSE;
406
407         if (custom_baud_rate == TRUE){
408 #if defined(HAVE_LINUX_SERIAL_H)
409                 struct serial_struct ser;
410
411                 if (ioctl (fd, TIOCGSERIAL, &ser) < 0)
412                 {
413                         return FALSE;
414                 }
415
416                 ser.custom_divisor = ser.baud_base / baud_rate;
417                 ser.flags &= ~ASYNC_SPD_MASK;
418                 ser.flags |= ASYNC_SPD_CUST;
419
420                 if (ioctl (fd, TIOCSSERIAL, &ser) < 0)
421                 {
422                         return FALSE;
423                 }
424 #elif defined(HAVE_IOKIT)
425                 speed_t speed = baud_rate;
426                 if (ioctl(fd, IOSSIOSPEED, &speed) == -1)
427                         return FALSE;
428 #else
429                 /* Don't know how to set custom baud rate on this platform. */
430                 return FALSE;
431 #endif
432         }
433
434         return TRUE;
435 }
436
437
438 static gint32
439 get_signal_code (MonoSerialSignal signal)
440 {
441         switch (signal) {
442                 case Cd:
443                         return TIOCM_CAR;
444                 case Cts:
445                         return TIOCM_CTS;
446                 case Dsr:
447                         return TIOCM_DSR;
448                 case Dtr:
449                         return TIOCM_DTR;
450                 case Rts:
451                         return TIOCM_RTS;
452                 default:
453                         return 0;
454         }
455
456         /* Not reached */
457         return 0;
458 }
459
460 static MonoSerialSignal
461 get_mono_signal_codes (int signals)
462 {
463         MonoSerialSignal retval = NoneSignal;
464
465         if ((signals & TIOCM_CAR) != 0)
466                 retval |= Cd;
467         if ((signals & TIOCM_CTS) != 0)
468                 retval |= Cts;
469         if ((signals & TIOCM_DSR) != 0)
470                 retval |= Dsr;
471         if ((signals & TIOCM_DTR) != 0)
472                 retval |= Dtr;
473         if ((signals & TIOCM_RTS) != 0)
474                 retval |= Rts;
475
476         return retval;
477 }
478
479 MonoSerialSignal
480 get_signals (int fd, gint32 *error)
481 {
482         int signals;
483
484         *error = 0;
485         
486         if (ioctl (fd, TIOCMGET, &signals) == -1) {
487                 *error = -1;
488                 return NoneSignal;
489         }
490         
491         return get_mono_signal_codes (signals);
492 }
493
494 gint32
495 set_signal (int fd, MonoSerialSignal signal, gboolean value)
496 {
497         int signals, expected, activated;
498
499         expected = get_signal_code (signal);
500         if (ioctl (fd, TIOCMGET, &signals) == -1)
501                 return -1;
502         
503         activated = (signals & expected) != 0;
504         if (activated == value) /* Already set */
505                 return 1;
506         
507         if (value)
508                 signals |= expected;
509         else
510                 signals &= ~expected;
511         
512         if (ioctl (fd, TIOCMSET, &signals) == -1)
513                 return -1;
514         
515         return 1;
516 }
517
518 int
519 breakprop (int fd)
520 {
521         return tcsendbreak (fd, 0);
522 }
523
524 gboolean
525 poll_serial (int fd, gint32 *error, int timeout)
526 {
527         struct pollfd pinfo;
528         
529         *error = 0;
530         
531         pinfo.fd = fd;
532         pinfo.events = POLLIN;
533         pinfo.revents = 0;
534
535         while (poll (&pinfo, 1, timeout) == -1 && errno == EINTR) {
536                 /* EINTR is an OK condition, we should not throw in the upper layer an IOException */
537                 if (errno != EINTR){
538                         *error = -1;
539                         return FALSE;
540                 }
541         }
542
543         return (pinfo.revents & POLLIN) != 0 ? 1 : 0;
544 }
545
546 /*
547  * mono internals should not be used here.
548  * this serial stuff needs to be implemented with icalls.
549  * make this at least compile until the code is moved elsewhere
550  * defined(linux) is wrong, too
551  */
552 void*
553 list_serial_devices (void)
554 {
555         return NULL;
556 }
557
558 #if 0
559 MonoArray *
560 list_serial_devices (void)
561 {
562         MonoArray *array;
563 #if defined(linux)
564         /* Linux serial files are of the form ttyS[0-9]+ */
565         GSList *l, *list = NULL;
566         GDir* dir = g_dir_open ("/dev", 0, NULL);
567         const char *filename;
568         int i = 0;
569
570         while ((filename = g_dir_read_name (dir))) {
571                 if (filename) {
572                         if (!strncmp (filename, "ttyS", 4))
573                                 list = g_slist_append (list, g_strconcat ("/dev/", filename, NULL));
574                 }
575         }
576
577         g_dir_close (dir);
578   
579         array = mono_array_new (mono_domain_get (), mono_get_string_class (), g_slist_length (list));
580         for (l = list; l; l = l->next) {
581                 mono_array_set (array, gpointer, i++, mono_string_new (mono_domain_get (), (char*)l->data));
582                 g_free (l->data);
583         }
584
585         g_slist_free (list);
586
587 #else
588 #warning "list_serial_devices isn't ported to this OS"
589 #endif
590
591         return array;
592 }
593 #endif
594