forked from cminyard/ser2net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataxfer.c
4366 lines (3788 loc) · 108 KB
/
dataxfer.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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ser2net - A program for allowing telnet connection to serial ports
* Copyright (C) 2001 Corey Minyard <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* This code handles the actual transfer of data between the serial
ports and the TCP ports. */
#include <sys/time.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <syslog.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <fcntl.h>
#include "ser2net.h"
#include "dataxfer.h"
#include "selector.h"
#include "utils.h"
#include "telnet.h"
#include "devio.h"
#include "buffer.h"
#include "locking.h"
#include "led.h"
#define SERIAL "term"
#define NET "tcp "
/** BASED ON sshd.c FROM openssh.com */
#ifdef HAVE_TCPD_H
#include <tcpd.h>
static char *progname = "ser2net";
#endif /* HAVE_TCPD_H */
/* States for the net_to_dev_state and dev_to_net_state. */
#define PORT_UNCONNECTED 0 /* The TCP port is not connected
to anything right now. */
#define PORT_WAITING_INPUT 1 /* Waiting for input from the
input side. */
#define PORT_WAITING_OUTPUT_CLEAR 2 /* Waiting for output to clear
so I can send data. */
#define PORT_CLOSING 3 /* Waiting for output close
string to be sent. */
char *state_str[] = { "unconnected", "waiting input", "waiting output",
"closing" };
#define PORT_DISABLED 0 /* The port is not open. */
#define PORT_RAW 1 /* Port will not do telnet negotiation. */
#define PORT_RAWLP 2 /* Port will not do telnet negotiation and
termios setting, open for output only. */
#define PORT_TELNET 3 /* Port will do telnet negotiation. */
char *enabled_str[] = { "off", "raw", "rawlp", "telnet" };
typedef struct trace_info_s
{
int hexdump; /* output each block as a hexdump */
int timestamp; /* preceed each line with a timestamp */
char *filename; /* open file. NULL if not used */
int fd; /* open file. -1 if not used */
} trace_info_t;
typedef struct port_info port_info_t;
typedef struct net_info net_info_t;
struct net_info {
port_info_t *port; /* My port. */
bool closing; /* Is the connection in the process
of closing? */
int fd; /* When connected, the file
descriptor for the network
port used for I/O. */
bool remote_fixed; /* Tells if the remote address was
set in the configuration, and
cannot be changed. */
struct sockaddr_storage remote; /* The socket address of who
is connected to this port. */
struct sockaddr *raddr; /* Points to remote, for convenience. */
socklen_t raddrlen;
struct sockaddr *udpraddr; /* Points to remote, only for UDP,
so sendto's addr will be NULL on
TCP. */
socklen_t udpraddrlen;
unsigned int bytes_received; /* Number of bytes read from the
network port. */
unsigned int bytes_sent; /* Number of bytes written to the
network port. */
struct sbuf *banner; /* Outgoing banner */
unsigned int write_pos; /* Our current position in the
output buffer where we need
to start writing next. */
bool data_to_write; /* There is data to write on
this network port. */
void (*write_handler)(port_info_t *, net_info_t *);
/* Data for the telnet processing */
telnet_data_t tn_data;
bool sending_tn_data; /* Are we sending tn data at the moment? */
int timeout_left; /* The amount of time left (in
seconds) before the timeout
goes off. */
sel_runner_t *runshutdown; /* Used to run things at the
base context. This way we
don't have to worry that we
are running inside a
handler context that needs
to be waited for exit. */
/*
* If a user gets kicked, store the information for the new user
* here since we have already accepted the connection or received
* the packet, we have to store it someplace.
*/
int new_fd;
struct sockaddr_storage new_remote;
socklen_t new_raddrlen;
unsigned char *new_buf;
int new_buf_len;
};
struct port_remaddr
{
char *name;
struct sockaddr_storage addr;
socklen_t addrlen;
bool is_port_set;
struct port_remaddr *next;
};
struct port_info
{
DEFINE_LOCK(, lock)
int enabled; /* If PORT_DISABLED, the port
is disabled and the TCP
accept port is not
operational. If PORT_RAW,
the port is enabled and
will not do any telnet
negotiations. If
PORT_RAWLP, the port is enabled
only for output without any
termios setting - it allows
to redirect /dev/lpX devices If
PORT_TELNET, the port is
enabled and it will do
telnet negotiations. */
int timeout; /* The number of seconds to
wait without any I/O before
we shut the port down. */
sel_timer_t *timer; /* Used to timeout when the no
I/O has been seen for a
certain period of time. */
sel_timer_t *send_timer; /* Used to delay a bit when
waiting for characters to
batch up as many characters
as possible. */
bool send_timer_running;
sel_runner_t *runshutdown; /* Used to run things at the
base context. This way we
don't have to worry that we
are running inside a
handler context that needs
to be waited for exit. */
int chardelay; /* The amount of time to wait after
receiving a character before
sending it, unless we receive
another character. Based on
bit rate. */
int bps; /* Bits per second rate. */
int bpc; /* Bits per character. */
bool enable_chardelay;
int chardelay_scale; /* The number of character
periods to wait for the
next character, in tenths of
a character period. */
int chardelay_min; /* The minimum chardelay, in
microseconds. */
int chardelay_max; /* Maximum amount of time to
wait before sending the data. */
struct timeval send_time; /* When using chardelay, the
time when we will send the
data, no matter what, set
by chardelay_max. */
int (*netread)(int fd, port_info_t *port, int *readerr,
net_info_t **netcon);
struct port_remaddr *remaddrs;
bool remaddr_set;
/* Information about the network port. */
char *portname; /* The name given for the port. */
int is_stdio; /* Do stdio on the port? */
struct addrinfo *ai; /* The address list for the portname. */
bool dgram; /* Is this a datagram (UDP) port? */
struct opensocks *acceptfds; /* The file descriptor used to
accept connections on the
TCP port. */
unsigned int nr_acceptfds;
waiter_t *accept_waiter; /* Wait for accept changes. */
unsigned int max_connections; /* Maximum number of TCP connections
we can accept at a time for this
port. */
net_info_t *netcons;
unsigned int dev_bytes_received; /* Number of bytes read from the
device. */
unsigned int dev_bytes_sent; /* Number of bytes written to the
device. */
/* Information use when transferring information from the network port
to the terminal device. */
int net_to_dev_state; /* State of transferring
data from the network port
to the device. */
int net_to_dev_bufsize;
struct sbuf net_to_dev; /* Buffer struct for
network to device
transfers. */
struct controller_info *net_monitor; /* If non-null, send any input
received from the network port
to this controller port. */
struct sbuf *devstr; /* Outgoing string */
/* Information use when transferring information from the terminal
device to the network port. */
int dev_to_net_state; /* State of transferring
data from the device to
the network port. */
int dev_to_net_bufsize;
struct sbuf dev_to_net; /* Buffer struct for
device to network
transfers. */
struct controller_info *dev_monitor; /* If non-null, send any input
received from the device
to this controller port. */
struct port_info *next; /* Used to keep a linked list
of these. */
int config_num; /* Keep track of what configuration this was last
updated under. Setting to -1 means to delete
the port when the current session is done. */
struct port_info *new_config; /* If the port is reconfigged while
open, this will hold the new
configuration that should be
loaded when the current session
is done. */
/* Is RFC 2217 mode enabled? */
int is_2217;
/* Masks for RFC 2217 */
unsigned char linestate_mask;
unsigned char modemstate_mask;
unsigned char last_modemstate;
/* Allow RFC 2217 mode */
int allow_2217;
/* Send a break if we get a sync command? */
int telnet_brk_on_sync;
/* kickolduser mode */
int kickolduser_mode;
/* Banner to display at startup, or NULL if none. */
char *bannerstr;
/* RFC 2217 signature. */
char *signaturestr;
/* String to send to device at startup, or NULL if none. */
char *openstr;
/* String to send to device at close, or NULL if none. */
char *closestr;
/*
* Close on string to shutdown connection when received from
* serial side, or NULL if none.
*/
char *closeon;
unsigned int closeon_pos;
unsigned int closeon_len;
/*
* Close the session when all the output has been written to the
* network port.
*/
bool close_on_output_done;
/*
* File to read/write trace, NULL if none. If the same, then
* trace information is in the same file, only one open is done.
*/
trace_info_t trace_read;
trace_info_t trace_write;
trace_info_t trace_both;
/*
* Pointers to the above, that way if two are the same file we can just
* set up one and point both to it.
*/
trace_info_t *tr;
trace_info_t *tw;
trace_info_t *tb;
struct devio io; /* For handling I/O operation to the device */
void (*dev_write_handler)(port_info_t *);
#if HAVE_DECL_TIOCSRS485
struct serial_rs485 *rs485conf;
#endif
/*
* LED to flash for serial traffic
*/
struct led_s *led_tx;
struct led_s *led_rx;
};
#define for_each_connection(port, netcon) \
for (netcon = port->netcons; \
netcon < &(port->netcons[port->max_connections]); \
netcon++)
DEFINE_LOCK_INIT(static, ports_lock)
port_info_t *ports = NULL; /* Linked list of ports. */
static void shutdown_one_netcon(net_info_t *netcon, char *reason);
static void shutdown_port(port_info_t *port, char *reason);
static void disable_accept_ports(port_info_t *port);
static void enable_accept_ports(port_info_t *port);
/* The init sequence we use. */
static unsigned char telnet_init_seq[] = {
TN_IAC, TN_WILL, TN_OPT_SUPPRESS_GO_AHEAD,
TN_IAC, TN_WILL, TN_OPT_ECHO,
TN_IAC, TN_DONT, TN_OPT_ECHO,
TN_IAC, TN_DO, TN_OPT_BINARY_TRANSMISSION,
};
/* Our telnet command table. */
static void com_port_handler(void *cb_data, unsigned char *option, int len);
static int com_port_will(void *cb_data);
static struct telnet_cmd telnet_cmds[] =
{
/* I will, I do, sent will, sent do */
{ TN_OPT_SUPPRESS_GO_AHEAD, 0, 1, 1, 0, },
{ TN_OPT_ECHO, 0, 1, 1, 1, },
{ TN_OPT_BINARY_TRANSMISSION, 1, 1, 0, 1, },
{ TN_OPT_COM_PORT, 1, 1, 0, 0, 0, 0,
com_port_handler, com_port_will },
{ TELNET_CMD_END_OPTION }
};
static int
syslog_eprint(struct absout *e, const char *str, ...)
{
va_list ap;
va_start(ap, str);
vsyslog(LOG_ERR, str, ap);
va_end(ap);
return 0;
}
static struct absout syslog_eout = {
.out = syslog_eprint,
};
static void
add_usec_to_timeval(struct timeval *tv, int usec)
{
tv->tv_usec += usec;
while (usec >= 1000000) {
usec -= 1000000;
tv->tv_sec += 1;
}
}
static int
sub_timeval_us(struct timeval *left,
struct timeval *right)
{
struct timeval dest;
dest.tv_sec = left->tv_sec - right->tv_sec;
dest.tv_usec = left->tv_usec - right->tv_usec;
while (dest.tv_usec < 0) {
dest.tv_usec += 1000000;
dest.tv_sec--;
}
return (dest.tv_sec * 1000000) + dest.tv_usec;
}
/*
* Generic output function for using a controller output for
* abstract I/O.
*/
static int
cntrl_absout(struct absout *o, const char *str, ...)
{
va_list ap;
int rv;
va_start(ap, str);
rv = controller_voutputf(o->data, str, ap);
va_end(ap);
return rv;
}
/*
* Like above but does a new line at the end of the output, generally
* for error output.
*/
static int
cntrl_abserrout(struct absout *o, const char *str, ...)
{
va_list ap;
int rv;
va_start(ap, str);
rv = controller_voutputf(o->data, str, ap);
va_end(ap);
rv += controller_outputf(o->data, "\r\n");
return rv;
}
static int
num_connected_net(port_info_t *port, bool include_closing)
{
net_info_t *netcon;
int count = 0;
for_each_connection(port, netcon) {
if (!include_closing && netcon->closing)
continue;
if (netcon->fd != -1)
count++;
}
return count;
}
static net_info_t *
first_live_net_con(port_info_t *port)
{
net_info_t *netcon;
for_each_connection(port, netcon) {
if (netcon->fd != -1)
return netcon;
}
return NULL;
}
static int
init_port_data(port_info_t *port)
{
port->enabled = PORT_DISABLED;
port->net_to_dev_state = PORT_UNCONNECTED;
port->dev_to_net_state = PORT_UNCONNECTED;
port->trace_read.fd = -1;
port->trace_write.fd = -1;
port->trace_both.fd = -1;
#if HAVE_DECL_TIOCSRS485
port->rs485conf = NULL;
#endif
port->allow_2217 = find_default_int("remctl");
port->telnet_brk_on_sync = find_default_int("telnet_brk_on_sync");
port->kickolduser_mode = find_default_int("kickolduser");
port->enable_chardelay = find_default_int("chardelay");
port->chardelay_scale = find_default_int("chardelay-scale");
port->chardelay_min = find_default_int("chardelay-min");
port->chardelay_max = find_default_int("chardelay-max");
port->dev_to_net_bufsize = find_default_int("dev-to-tcp-bufsize");
port->net_to_dev_bufsize = find_default_int("tcp-to-dev-bufsize");
port->max_connections = find_default_int("max-connections");
if (buffer_init(&port->net_to_dev, NULL, port->net_to_dev_bufsize))
return ENOMEM;
if (buffer_init(&port->dev_to_net, NULL, port->dev_to_net_bufsize))
return ENOMEM;
port->led_tx = NULL;
port->led_rx = NULL;
return 0;
}
static void
reset_timer(net_info_t *netcon)
{
netcon->timeout_left = netcon->port->timeout;
}
static int
timestamp(trace_info_t *t, char *buf, int size)
{
time_t result;
if (!t->timestamp)
return 0;
result = time(NULL);
return strftime(buf, size, "%Y/%m/%d %H:%M:%S ", localtime(&result));
}
static int
trace_write_end(char *out, int size, unsigned char *start, int col)
{
int pos = 0, w;
strncat(out, " |", size - pos);
pos += 2;
for(w = 0; w < col; w++) {
pos += snprintf(out + pos, size - pos, "%c",
isprint(start[w]) ? start[w] : '.');
}
strncat(out + pos, "|\n", size - pos);
pos += 2;
return pos;
}
int
trace_write(port_info_t *port, trace_info_t *t, unsigned char *buf,
unsigned int buf_len, char *prefix)
{
int rv = 0, w, col = 0, pos, file = t->fd;
unsigned int q;
static char out[1024];
unsigned char *start;
if (buf_len == 0)
return 0;
if (!t->hexdump)
return write(file, buf, buf_len);
pos = timestamp(t, out, sizeof(out));
pos += snprintf(out + pos, sizeof(out) - pos, "%s ", prefix);
start = buf;
for (q = 0; q < buf_len; q++) {
pos += snprintf(out + pos, sizeof(out) - pos, "%02x ", buf[q]);
col++;
if (col >= 8) {
trace_write_end(out + pos, sizeof(out) - pos, start, col);
rv = write(file, out, strlen(out));
if (rv < 0)
return rv;
pos = timestamp(t, out, sizeof(out));
pos += snprintf(out + pos, sizeof(out) - pos, "%s ", prefix);
col = 0;
start = buf + q + 1;
}
}
if (col > 0) {
for (w = 8; w > col; w--) {
strncat(out + pos, " ", sizeof(out) - pos);
pos += 3;
}
trace_write_end(out + pos, sizeof(out) - pos, start, col);
rv = write(file, out, strlen(out));
if (rv < 0)
return rv;
}
return buf_len;
}
static void
do_trace(port_info_t *port, trace_info_t *t, unsigned char *buf,
unsigned int buf_len, char *prefix)
{
int rv;
while (buf_len > 0) {
retry_write:
rv = trace_write(port, t, buf, buf_len, prefix);
if (rv == -1) {
char errbuf[128];
int err = errno;
if (err == EINTR)
goto retry_write;
/* Fatal error writing to the file, log it and close the file. */
if (strerror_r(err, errbuf, sizeof(errbuf)) == -1)
syslog(LOG_ERR, "Unable write to trace file on port %s: %d",
port->portname, err);
else
syslog(LOG_ERR, "Unable to write to trace file on port %s: %s",
port->portname, errbuf);
close(t->fd);
t->fd = -1;
return;
}
/* Handle a partial write */
buf_len -= rv;
buf += rv;
}
}
static void
hf_out(port_info_t *port, char *buf, int len)
{
if (port->tr && port->tr->timestamp)
write_ignore_fail(port->tr->fd, buf, len);
/* don't output to write file if it's the same as read file */
if (port->tw && port->tw != port->tr && port->tw->timestamp)
write_ignore_fail(port->tw->fd, buf, len);
/* don't output to both file if it's the same as read or write file */
if (port->tb && port->tb != port->tr && port->tb != port->tw
&& port->tb->timestamp)
write_ignore_fail(port->tb->fd, buf, len);
}
static void
header_trace(port_info_t *port, net_info_t *netcon)
{
static char buf[1024];
static trace_info_t tr = { 1, 1, NULL, -1 };
int len = 0, err;
char portstr[NI_MAXSERV];
len += timestamp(&tr, buf, sizeof(buf));
len += snprintf(buf + len, sizeof(buf) - len, "OPEN (");
err = getnameinfo(netcon->raddr, netcon->raddrlen,
buf + len, sizeof(buf) - len,
portstr, sizeof(portstr), NI_NUMERICHOST);
if (err) {
len += snprintf(buf + len, sizeof(buf) - len,
"unknown:%s\n", gai_strerror(err));
} else {
len += strlen(buf + len);
if ((sizeof(buf) - len) > 2) {
buf[len] = ':';
len++;
}
strncpy(buf + len, portstr, sizeof(buf) - len);
len += strlen(buf + len);
}
len += snprintf(buf + len, sizeof(buf) - len, ")\n");
hf_out(port, buf, len);
}
static void
footer_trace(port_info_t *port, char *type, char *reason)
{
static char buf[1024];
static trace_info_t tr = { 1, 1, NULL, -1 };
int len = 0;
len += timestamp(&tr, buf, sizeof(buf));
len += snprintf(buf + len, sizeof(buf), "CLOSE %s (%s)\n", type, reason);
hf_out(port, buf, len);
}
static bool
any_net_data_to_write(port_info_t *port)
{
net_info_t *netcon;
for_each_connection(port, netcon) {
if (netcon->data_to_write)
return true;
}
return false;
}
static void
handle_net_send_one(port_info_t *port, net_info_t *netcon)
{
int count = 0;
if (netcon->sending_tn_data)
/* We are sending telnet data, stop the reader for now. */
goto no_send;
retry_write:
count = net_write(netcon->fd,
port->dev_to_net.buf, port->dev_to_net.cursize,
0, netcon->udpraddr, netcon->udpraddrlen);
if (count == -1) {
if (errno == EINTR) {
/* EINTR means we were interrupted, just retry. */
goto retry_write;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* This was due to O_NONBLOCK, we need to shut off the reader
and start the writer monitor. */
port->io.f->read_handler_enable(&port->io, 0);
sel_set_fd_write_handler(ser2net_sel, netcon->fd,
SEL_FD_HANDLER_ENABLED);
port->dev_to_net_state = PORT_WAITING_OUTPUT_CLEAR;
} else if (errno == EPIPE) {
shutdown_one_netcon(netcon, "EPIPE");
} else {
/* Some other bad error. */
syslog(LOG_ERR, "The network write for port %s had error: %m",
port->portname);
shutdown_one_netcon(netcon, "network write error");
}
} else {
netcon->bytes_sent += count;
if (port->dev_to_net.cursize != count) {
/* We didn't write all the data, shut off the reader and
start the write monitor. */
no_send:
netcon->write_pos = count;
netcon->data_to_write = true;
port->io.f->read_handler_enable(&port->io, 0);
sel_set_fd_write_handler(ser2net_sel, netcon->fd,
SEL_FD_HANDLER_ENABLED);
port->dev_to_net_state = PORT_WAITING_OUTPUT_CLEAR;
} else if (port->close_on_output_done) {
shutdown_one_netcon(netcon, "closeon sequence found");
}
}
reset_timer(netcon);
}
static void
handle_net_send(port_info_t *port)
{
net_info_t *netcon;
for_each_connection(port, netcon) {
if (netcon->fd == -1)
continue;
handle_net_send_one(port, netcon);
}
if (!any_net_data_to_write(port))
port->dev_to_net.cursize = 0;
}
void
send_timeout(selector_t *sel,
sel_timer_t *timer,
void *data)
{
port_info_t *port = (port_info_t *) data;
LOCK(port->lock);
if (port->dev_to_net_state == PORT_CLOSING) {
UNLOCK(port->lock);
return;
}
port->send_timer_running = false;
if (port->dev_to_net.cursize > 0)
handle_net_send(port);
UNLOCK(port->lock);
}
static void
disable_all_net_read(port_info_t *port)
{
net_info_t *netcon;
for_each_connection(port, netcon) {
if (netcon->fd != -1)
sel_set_fd_read_handler(ser2net_sel, netcon->fd,
SEL_FD_HANDLER_DISABLED);
}
if (port->dgram)
disable_accept_ports(port);
}
static void
enable_all_net_read(port_info_t *port)
{
net_info_t *netcon;
for_each_connection(port, netcon) {
if (netcon->fd != -1)
sel_set_fd_read_handler(ser2net_sel, netcon->fd,
SEL_FD_HANDLER_ENABLED);
}
if (port->dgram)
enable_accept_ports(port);
}
/* Data is ready to read on the serial port. */
static void
handle_dev_fd_read(struct devio *io)
{
port_info_t *port = (port_info_t *) io->user_data;
int count;
int curend;
bool send_now = false;
LOCK(port->lock);
curend = port->dev_to_net.cursize;
if (port->enabled == PORT_TELNET) {
/* Leave room for IACs. */
count = port->io.f->read(&port->io, port->dev_to_net.buf + curend,
(port->dev_to_net.maxsize - curend) / 2);
} else {
count = port->io.f->read(&port->io, port->dev_to_net.buf + curend,
port->dev_to_net.maxsize - curend);
}
if (count <= 0) {
if (curend != 0) {
/* We still have data to send. */
send_now = true;
count = 0;
goto do_send;
}
if (count < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
/* Nothing to read, just return. */
goto out_unlock;
/* Got an error on the read, shut down the port. */
syslog(LOG_ERR, "dev read error for device %s: %m", port->portname);
shutdown_port(port, "dev read error");
} else if (count == 0) {
/* The port got closed somehow, shut it down. */
shutdown_port(port, "closed port");
}
goto out_unlock;
}
if (port->dev_monitor != NULL && count > 0) {
controller_write(port->dev_monitor,
(char *) port->dev_to_net.buf + curend,
count);
}
do_send:
if (port->closeon) {
int i;
for (i = 0; i < count; i++) {
if (port->dev_to_net.buf[i] == port->closeon[port->closeon_pos]) {
port->closeon_pos++;
if (port->closeon_pos >= port->closeon_len) {
port->close_on_output_done = true;
/* Ignore everything after the closeon string */
count = i + 1;
break;
}
} else {
port->closeon_pos = 0;
}
}
}
if (port->tr)
/* Do read tracing, ignore errors. */
do_trace(port, port->tr, port->dev_to_net.buf, count, SERIAL);
if (port->tb)
/* Do both tracing, ignore errors. */
do_trace(port, port->tb, port->dev_to_net.buf, count, SERIAL);
if (port->led_rx) {
led_flash(port->led_rx);
}
port->dev_bytes_received += count;
if (port->enabled == PORT_TELNET) {
int i, j;
/* Double the IACs on a telnet stream. This will fit because
we only use half the buffer for telnet connections. */
for (i = 0; i < count; i++) {
if (port->dev_to_net.buf[i] == TN_IAC) {
for (j = count; j > i; j--)
port->dev_to_net.buf[j + 1] = port->dev_to_net.buf[j];
count++;
i++;
port->dev_to_net.buf[i] = TN_IAC;
}
}
}
port->dev_to_net.cursize += count;
if (send_now || port->dev_to_net.cursize == port->dev_to_net.maxsize ||
port->chardelay == 0) {
send_it:
handle_net_send(port);
} else {
struct timeval then;
int delay;
sel_get_monotonic_time(&then);
if (port->send_timer_running) {
sel_stop_timer(port->send_timer);
} else {
port->send_time = then;
add_usec_to_timeval(&port->send_time, port->chardelay_max);
}
delay = sub_timeval_us(&port->send_time, &then);
if (delay > port->chardelay)
delay = port->chardelay;
else if (delay < 0) {
port->send_timer_running = false;
goto send_it;
}
add_usec_to_timeval(&then, delay);
sel_start_timer(port->send_timer, &then);
port->send_timer_running = true;
}
out_unlock:
UNLOCK(port->lock);
}
/* The serial port has room to write some data. This is only activated
if a write fails to complete, it is deactivated as soon as writing
is available again. */
static void
dev_fd_write(port_info_t *port, struct sbuf *buf)
{
int reterr, buferr;
reterr = buffer_io_write(&port->io, buf, &buferr);
if (reterr == -1) {
syslog(LOG_ERR, "The dev write for port %s had error: %m",
port->portname);
shutdown_port(port, "dev write error");
return;
}
if (buffer_cursize(buf) == 0) {
/* We are done writing, turn the reader back on. */
enable_all_net_read(port);
port->io.f->write_handler_enable(&port->io, 0);
port->net_to_dev_state = PORT_WAITING_INPUT;
}
}
static void
handle_dev_fd_normal_write(port_info_t *port)
{
dev_fd_write(port, &port->net_to_dev);
}
static void