forked from stripydog/kplex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial.c
566 lines (506 loc) · 16.5 KB
/
serial.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/* serial.c
* This file is part of kplex
* Copyright Keith Young 2012 - 2014
* For copying information see the file COPYING distributed with this software
*
* This file contains code for serial-like interfaces. This currently
* comprises:
* nmea 0183 serial interfaces
* pseudo ttys
*/
#include "kplex.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#if defined __APPLE__ || defined __NetBSD__ || defined __OpenBSD__
#include <util.h>
#elif defined __FreeBSD__
#include <libutil.h>
#else
#include <pty.h>
#endif
#include <grp.h>
#include <pwd.h>
#define DEFSERIALQSIZE 128
struct if_serial {
int fd;
char *slavename; /* link to pty slave (if it exists) */
int saved; /* Are stored terminal settins valid? */
struct termios otermios; /* To restore previous interface settings
* on exit */
};
/*
* Duplicate struct if_serial
* Args: if_serial to be duplicated
* Returns: pointer to new if_serial
* Should we dup, copy or re-open the fd here?
*/
void *ifdup_serial(void *ifs)
{
struct if_serial *oldif,*newif;
if ((newif = (struct if_serial *) malloc(sizeof(struct if_serial)))
== (struct if_serial *) NULL)
return(NULL);
oldif = (struct if_serial *) ifs;
if ((newif->fd=dup(oldif->fd)) <0) {
free(newif);
return(NULL);
}
newif->slavename=oldif->slavename;
newif->saved=oldif->saved;
memcpy(&newif->otermios,&oldif->otermios,sizeof(struct termios));
return((void *)newif);
}
/*
* Cleanup interface on exit
* Args: pointer to interface
* Returns: Nothing
*/
void cleanup_serial(iface_t *ifa)
{
struct if_serial *ifs = (struct if_serial *)ifa->info;
if (!ifa->pair) {
if (ifs->saved) {
if (tcsetattr(ifs->fd,TCSAFLUSH,&ifs->otermios) < 0) {
if (ifa->type != PTY || errno != EIO)
logwarn("Failed to restore serial line: %s",strerror(errno));
}
}
if (ifs->slavename) {
if (unlink(ifs->slavename) < 0)
logerr(errno,"Failed to remove link %s",ifs->slavename);
free(ifs->slavename);
}
}
close(ifs->fd);
}
/*
* Open terminal (serial interface or pty)
* Args: pathname and direction (input or output)
* Returns: descriptor for opened interface or NULL on failure
*/
int ttyopen(char *device, enum iotype direction)
{
int dev,flags;
struct stat sbuf;
/* Check if device exists and is a character special device */
if (stat(device,&sbuf) < 0) {
logerr(errno,"Could not stat %s",device);
return(-1);
}
if (!S_ISCHR(sbuf.st_mode)){
logerr(0,"%s is not a character device",device);
return(-1);
}
/* Open device (RW for now..let's ignore direction...) */
if ((dev=open(device,
((direction == OUT)?O_WRONLY:(direction == IN)?O_RDONLY:O_RDWR)|O_NOCTTY|O_NONBLOCK)) < 0) {
logerr(errno,"Failed to open %s",device);
return(-1);
}
if ((flags = fcntl(dev,F_GETFL)) < 0)
logerr(errno,"Failed to get flags for %s",device);
else if (fcntl(dev,F_SETFL,flags & ~O_NONBLOCK) < 0)
logerr(errno,"Failed to set %s to non-blocking",device);
return(dev);
}
/*
* Set up terminal attributes
* Args: device file descriptor,pointer to structure to save old termios,
* control flags and a flag indicating if this is a seatalk interface
* All a bit clunky and should be revised
* Returns: 0 on success, -1 otherwise
*/
int ttysetup(int dev,struct termios *otermios_p, int baud, int st)
{
struct termios ttermios,ntermios;
/* Get existing terminal attributes and save them */
if (tcgetattr(dev,otermios_p) < 0) {
logerr(errno,"failed to get terminal attributes");
return(-2);
}
memcpy(&ntermios,otermios_p,sizeof(struct termios));
/* PARMRK is set for seatalk interface as parity errors are how we
* identify commands
*/
ntermios.c_iflag|=(IGNBRK|INPCK);
if (st)
ntermios.c_iflag |= PARMRK;
else
ntermios.c_iflag &= ~PARMRK;
/* disable software flow control */
ntermios.c_cflag &= ~(IXON | IXOFF | IXANY);
/* CS8 1 Stop bit no parity */
ntermios.c_cflag &= ~PARENB;
ntermios.c_cflag &= ~CSTOPB;
ntermios.c_cflag &= ~CSIZE;
ntermios.c_cflag |= CS8;
/* Enable receiver (should be a problem for sender) and ignore hardware
* flow control */
ntermios.c_cflag |= (CLOCAL | CREAD);
/* set baud rate */
cfsetispeed(&ntermios,baud);
cfsetospeed(&ntermios,baud);
ntermios.c_cc[VMIN]=1;
ntermios.c_cc[VTIME]=0;
/* select raw mode */
cfmakeraw(&ntermios);
if (tcsetattr(dev,TCSANOW,&ntermios) < 0) {
logerr(errno,"Failed to set up serial line!");
return(-1);
}
/* Read back terminal attributes to check we set what we needed to */
if (tcgetattr(dev,&ttermios) < 0) {
logerr(errno,"Failed to re-read serial line attributes");
return(-1);
}
if ((ttermios.c_cflag != ntermios.c_cflag) ||
(ttermios.c_iflag != ntermios.c_iflag)) {
logerr(0,"Failed to correctly set up serial line");
return(-1);
}
return(0);
}
/*
* Read from a serial interface
* Args: pointer to interface structure pointer to buffer
* Returns: Number of bytes read, zero on error or end of file
*/
ssize_t read_serial(struct iface *ifa, char *buf)
{
struct if_serial *ifs = (struct if_serial *) ifa->info;
return(read(ifs->fd,buf,BUFSIZ));
}
/*
* Write nmea sentences to serial output
* Args: pointer to interface
* Returns: Nothing. errno supplied to iface_thread_exit()
*/
void write_serial(struct iface *ifa)
{
struct if_serial *ifs = (struct if_serial *) ifa->info;
senblk_t *senblk_p;
int fd=ifs->fd;
int n=0,tlen=0;
char *ptr;
char *tbuf;
if (ifa->tagflags) {
if ((tbuf=malloc(TAGMAX)) == NULL) {
logerr(errno,"Disabing tag output on interface id %u (%s)",
ifa->id,(ifa->name)?ifa->name:"unlabelled");
ifa->tagflags=0;
}
}
while(n >= 0) {
/* NULL return from next_senblk means the queue has been shut
* down. Time to die */
if ((senblk_p = next_senblk(ifa->q)) == NULL)
break;
if (senfilter(senblk_p,ifa->ofilter)) {
senblk_free(senblk_p,ifa->q);
continue;
}
if (ifa->tagflags) {
if ((tlen = gettag(ifa,tbuf,senblk_p)) == 0) {
logerr(errno,"Disabing tag output on interface id %u (%s)",
ifa->id,(ifa->name)?ifa->name:"unlabelled");
ifa->tagflags=0;
free(tbuf);
}
ptr=tbuf;
while(tlen) {
if ((n=write(fd,ptr,tlen)) < 0)
break;
tlen-=n;
ptr+=n;
}
if (tlen) {
senblk_free(senblk_p,ifa->q);
break;
}
}
ptr=senblk_p->data;
tlen=senblk_p->len;
while(tlen) {
if ((n=write(fd,ptr,tlen)) < 0)
break;
tlen-=n;
ptr+=n;
}
senblk_free(senblk_p,ifa->q);
if (tlen)
break;
}
if (ifa->tagflags)
free(tbuf);
iface_thread_exit(errno);
}
/*
* Initialise a serial interface for nmea 0183 data
* Args: interface specification string and pointer to interface structure
* Retuns: Pointer to (completed) interface structure
*/
struct iface *init_serial (struct iface *ifa)
{
char *devname;
struct if_serial *ifs;
int baud=B4800; /* Default for NMEA 0183. AIS will need
explicit baud rate specification */
int ret;
struct kopts *opt;
int qsize=DEFSERIALQSIZE;
for(opt=ifa->options;opt;opt=opt->next) {
if (!strcasecmp(opt->var,"filename"))
devname=opt->val;
else if (!strcasecmp(opt->var,"baud")) {
if (!strcmp(opt->val,"38400"))
baud=B38400;
else if (!strcmp(opt->val,"9600"))
baud=B9600;
else if (!strcmp(opt->val,"4800"))
baud=B4800;
else if (!strcmp(opt->val,"19200"))
baud=B19200;
else if (!strcmp(opt->val,"57600"))
baud=B57600;
else if (!strcmp(opt->val,"115200"))
baud=B115200;
else {
logerr(0,"Unsupported baud rate \'%s\' in interface specification '\%s\'",opt->val,devname);
return(NULL);
}
} else if (!strcasecmp(opt->var,"qsize")) {
if (!(qsize=atoi(opt->val))) {
logerr(0,"Invalid queue size specified: %s",opt->val);
return(NULL);
}
} else {
logerr(0,"unknown interface option %s",opt->var);
return(NULL);
}
}
/* Allocate serial specific data storage */
if ((ifs = malloc(sizeof(struct if_serial))) == NULL) {
logerr(errno,"Could not allocate memory");
return(NULL);
}
/* Open interface or die */
if ((ifs->fd=ttyopen(devname,ifa->direction)) < 0) {
return(NULL);
}
free_options(ifa->options);
/* Set up interface or die */
if ((ret = ttysetup(ifs->fd,&ifs->otermios,baud,0)) < 0) {
if (ret == -1) {
if (tcsetattr(ifs->fd,TCSANOW,&ifs->otermios) < 0) {
logerr(errno,"Failed to reset serial line");
}
}
return(NULL);
}
ifs->saved=1;
ifs->slavename=NULL;
/* Assign pointers to read, write and cleanup routines */
ifa->read=do_read;
ifa->readbuf=read_serial;
ifa->write=write_serial;
ifa->cleanup=cleanup_serial;
/* Allocate queue for outbound interfaces */
if (ifa->direction != IN)
if ((ifa->q =init_q(qsize)) == NULL) {
logerr(errno,"Could not create queue");
cleanup_serial(ifa);
return(NULL);
}
/* Link in serial specific data */
ifa->info=(void *)ifs;
if (ifa->direction == BOTH) {
if ((ifa->next=ifdup(ifa)) == NULL) {
logerr(0,"Interface duplication failed");
cleanup_serial(ifa);
return(NULL);
}
ifa->direction=OUT;
ifa->pair->direction=IN;
}
return(ifa);
}
/*
* Initialise a pty interface. For inputs, this is equivalent to init_serial
* Args: string specifying the interface and pointer to (incomplete) interface
* Returns: Completed interface structure
*/
struct iface *init_pty (struct iface *ifa)
{
char *devname=NULL;
struct if_serial *ifs;
int baud=B4800,slavefd;
int ret;
struct kopts *opt;
int qsize=DEFSERIALQSIZE;
char *master="s";
char *cp;
mode_t perm = 0;
struct passwd *owner;
struct group *group;
uid_t uid=-1;
gid_t gid=-1;
struct stat statbuf;
char slave[PATH_MAX];
for(opt=ifa->options;opt;opt=opt->next) {
if (!strcasecmp(opt->var,"mode")) {
master=opt->val;
if(strcmp(master,"master") && strcmp(master,"slave")) {
logerr(0,"pty mode \'%s\' unsupported: must be master or slave",master);
return(NULL);
}
}
else if (!strcasecmp(opt->var,"filename"))
devname=opt->val;
else if (!strcasecmp(opt->var,"owner")) {
if ((owner=getpwnam(opt->val)) == NULL) {
logerr(0,"No such user '%s'",opt->val);
return(NULL);
}
uid=owner->pw_uid;
} else if (!strcasecmp(opt->var,"group")) {
if ((group=getgrnam(opt->val)) == NULL) {
logerr(0,"No such group '%s'",opt->val);
return(NULL);
}
gid=group->gr_gid;
}
else if (!strcasecmp(opt->var,"perm")) {
for (cp=opt->val;*cp;cp++) {
if (*cp >= '0' && *cp < '8') {
perm <<=3;
perm += (*cp-'0');
} else {
perm = 0;
break;
}
}
perm &= ACCESSPERMS;
if (perm == 0) {
logerr(0,"Invalid permissions for tty device \'%s\'",opt->val);
return 0;
}
} else if (!strcasecmp(opt->var,"baud")) {
if (!strcmp(opt->val,"38400"))
baud=B38400;
else if (!strcmp(opt->val,"9600"))
baud=B9600;
else if (!strcmp(opt->val,"4800"))
baud=B4800;
else if (!strcmp(opt->val,"19200"))
baud=B19200;
else if (!strcmp(opt->val,"57600"))
baud=B57600;
else if (!strcmp(opt->val,"115200"))
baud=B115200;
else {
logerr(0,"Unsupported baud rate \'%s\' in interface specification '\%s\'",opt->val,devname);
return(NULL);
}
} else if (!strcasecmp(opt->var,"qsize")) {
if (!(qsize=atoi(opt->val))) {
logerr(0,"Invalid queue size specified: %s",opt->val);
return(NULL);
}
} else {
logerr(0,"Unknown interface option %s",opt->var);
return(NULL);
}
}
if ((ifs = malloc(sizeof(struct if_serial))) == NULL) {
logerr(errno,"Could not allocate memory");
return(NULL);
}
ifs->saved=0;
ifs->slavename=NULL;
if (*master != 's') {
if (openpty(&ifs->fd,&slavefd,slave,NULL,NULL) < 0) {
logerr(errno,"Error opening pty");
return(NULL);
}
if (gid != -1 || uid != -1) {
if (chown(slave,uid,gid) < 0) {
logerr(errno,"Failed to set ownership or group for slave pty");
return(NULL);
}
}
if (perm != 0) {
if (chmod(slave,perm) < 0) {
logerr(errno,"Failed to set permissions for slave pty");
return(NULL);
}
}
if (devname) {
/* Device name has been specified: Create symlink to slave */
if (lstat(devname,&statbuf) == 0) {
/* file exists */
if (!S_ISLNK(statbuf.st_mode)) {
/* If it's not a symlink already, don't replace it */
logerr(0,"%s: File exists and is not a symbolic link",devname);
return(NULL);
}
/* It's a symlink. remove it */
if (unlink(devname) && errno != ENOENT) {
logerr(errno,"Could not unlink %s",devname);
return(NULL);
}
}
/* link the given name to our new pty */
if (symlink(slave,devname)) {
logerr(errno,"Could not create symbolic link %s for %s",devname,slave);
return(NULL);
}
/* Save the name to unlink it on exit */
if ((ifs->slavename=strdup(devname)) == NULL) {
logerr(errno,"Failed to save device name. Link will not be removed on exit");
}
} else
/* No device name was given: Just print the pty name */
loginfo("Slave pty for output at %s baud is %s",(baud==B4800)?"4800":(baud==B9600)?"9600": "38.4k",slave);
} else {
/* Slave mode: This is no different from a serial line */
if (!devname) {
logerr(0,"Must Specify a filename for slave mode pty");
return(NULL);
}
if ((ifs->fd=ttyopen(devname,ifa->direction)) < 0) {
return(NULL);
}
}
free_options(ifa->options);
if ((ret=ttysetup(ifs->fd,&ifs->otermios,baud,0)) < 0) {
if (ret == -1) {
if (tcsetattr(ifs->fd,TCSANOW,&ifs->otermios) < 0) {
logerr(errno,"Failed to reset serial line");
}
}
return(NULL);
}
ifs->saved=1;
ifa->read=do_read;
ifa->readbuf=read_serial;
ifa->write=write_serial;
ifa->cleanup=cleanup_serial;
if (ifa->direction != IN)
if ((ifa->q =init_q(qsize)) == NULL) {
logerr(errno,"Could not create queue");
cleanup_serial(ifa);
return(NULL);
}
ifa->info=(void *)ifs;
if (ifa->direction == BOTH) {
if ((ifa->next=ifdup(ifa)) == NULL) {
logerr(0,"Interface duplication failed");
cleanup_serial(ifa);
return(NULL);
}
ifa->direction=OUT;
ifa->pair->direction=IN;
}
return(ifa);
}