-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselector.c
1812 lines (1590 loc) · 60.5 KB
/
selector.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
// src/aksl/selector.c 2017-10-25 Alan U. Kennington.
/*-----------------------------------------------------------------------------
Copyright (C) 1989-2018, Alan U. Kennington.
You may distribute this software under the terms of Alan U. Kennington's
modified Artistic Licence, as specified in the accompanying LICENCE file.
-----------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------
Functions in this file:
dispatch
select_handler::
select_handler
stdin_handler::
handler
cdev_handler::
handler
udp_delay_handler::
copy_pkt
handler
udp_handler::
handler
udp_port_hand::
action
udp_hand_set::
open
tcp_handler::
event_type_string
open
open
handler
write
print
tcp_context::
find_fd
find_from
m_tcp_handler::
event_type_string
open
handler
print
fdtype::
print
selector::
selector
print
set_timer
set_timer_rel
cancel_timer
set_wait_time
set_fd_mask
clear_fd_mask
get_event
------------------------------------------------------------------------------*/
// AKSL header files:
#include "aksl/selector.h"
#ifndef AKSL_CHARBUF_H
#include "aksl/charbuf.h"
#endif
#ifndef AKSL_NUMPRINT_H
#include "aksl/numprint.h"
#endif
// System header files:
#if defined(SOLARIS) && defined(HAVE_FCNTL_H)
#ifndef AKSL_X_FCNTL_H
#define AKSL_X_FCNTL_H
#include <fcntl.h>
#endif
#endif
#if !defined(SOLARIS) && !defined(WIN32) && defined(HAVE_SYS_IOCTL_H)
#ifndef AKSL_X_SYS_IOCTL_H
#define AKSL_X_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#endif
#ifndef AKSL_X_ERRNO_H
#define AKSL_X_ERRNO_H
#include <errno.h>
#endif
// Get perror() declaration for linux.
#ifdef linux
#ifndef AKSL_X_STDIO_H
#define AKSL_X_STDIO_H
#include <stdio.h>
#endif
#endif
// Upper limit on wait time for select() function:
const double t_selmax = 1e8;
// Special kludge-oriented handler for cancelling timers efficiently:
// [This could save hundreds of nanoseconds.]
static select_handler _cancel_timer_handler;
select_handler* cancel_timer_handler = &_cancel_timer_handler;
// Fast block memory allocation.
bmem_define(timer, bmem0);
/*------------------------------------------------------------------------------
If the given "delay" parameter is positive, the given packet is copied to a
udp_delay_handler object, which is registered with "sel0" for sending later.
Otherwise, the UDP packet is sent immediately.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Important note: it is assumed that this function is called just after an event
has been handled by "sel0", in which case the time parameter t() is correct.
Otherwise, the wrong time will be used!!!!
------------------------------------------------------------------------------*/
//----------------------//
// dispatch //
//----------------------//
int dispatch(selector& sel0, int fd, nbytes& buf, sockaddr_in& to,
double delay) {
int ret1 = 0;
if (delay > 0) { // Send the packet later:
udp_delay_handler* pdh = new udp_delay_handler;
// Set attributes of pdh:
pdh->copy_pkt(fd, buf, to);
// Register the timer event:
pdh->delete_me = true;
sel0.set_timer(sel0.t() + delay, pdh);
}
else { // Send the packet straight away:
// Forward transfer (hope it doesn't block!):
ret1 = sendto(fd, buf, to);
if (ret1 < 0) {
cout << "dispatch(): "
"error while sending UDP packet." << endl;
perror("sendto");
}
}
return ret1;
} // End of function dispatch.
//----------------------------------//
// select_handler::select_handler //
//----------------------------------//
select_handler::select_handler() {
psel = 0;
delete_me = false;
fd = -1;
type = sNULL;
} // End of function select_handler::select_handler.
/*------------------------------------------------------------------------------
This handler should be called whenever the select() call on standard input
finds that there are bytes to be read.
No assumptions are made about whether stdin is non-blocking. A select() call
is made before each read() call.
------------------------------------------------------------------------------*/
//--------------------------//
// stdin_handler::handler //
//--------------------------//
int stdin_handler::handler() {
// Clear out the old info:
delete[] bytes;
bytes = 0;
n_bytes = 0;
// Check sanity of fd:
if (fd != 0)
return -1;
// Handle only read-events:
if (type != sREAD)
return -1;
// Receive the (hopefully non-blocking) input:
const int smallbuf_size = 512;
char smallbuf[smallbuf_size];
charbuf cbuf; // Infinite buffer for collecting large input.
for (;;) {
// Re-poll the standard input before risking getting blocked:
fd_set rfds0;
FD_ZERO(&rfds0);
FD_SET(fd, &rfds0);
timeval timeout;
timeval_set_zero(timeout);
int x = select(fd + 1, &rfds0, (fd_set*)0, (fd_set*)0, &timeout);
if (x < 0) {
cout << "stdin_handler::handler() error calling select()" << endl;
perror("select");
return -1;
}
if (x <= 0)
break;
// Risk getting blocked by reading stdin:
int len = read(fd, smallbuf, smallbuf_size);
if (len < 0) {
cout << "stdin_handler::handler() error calling select()" << endl;
perror("select");
return -1;
}
if (len == 0)
break;
// Save the bytes in the temporary buffer:
cbuf.append_bytes(smallbuf, len);
}
// Copy from large buffer to new string:
bytes = cbuf.copy();
n_bytes = (int)cbuf.n_bytes();
// Take the appropriate action for the new input:
int err = action(bytes, n_bytes);
// Return negative value to force return to selector caller:
return (err < 0) ? -1 : 0;
} // End of function stdin_handler::handler.
/*------------------------------------------------------------------------------
This handler should be called whenever the select() call on standard input
finds that there are bytes to be read.
No assumptions are made about whether cdev is non-blocking. A select() call
is made before each read() call.
------------------------------------------------------------------------------*/
//--------------------------//
// cdev_handler::handler //
//--------------------------//
int cdev_handler::handler() {
// Clear out the old info:
buf.clear();
// Check sanity of fd:
// if (fd != 0)
// return -1;
// Handle only read-events:
if (type != sREAD)
return -1;
// Receive the (hopefully non-blocking) input:
int len = buf.read(fd);
if (len < 0) {
cout << "cdev_handler::handler() error calling read()" << endl;
perror("read");
return -1;
}
// Take the appropriate action for the new input:
int err = action();
// Return negative value to force return to selector caller:
return (err < 0) ? -1 : 0;
} // End of function cdev_handler::handler.
//------------------------------//
// udp_delay_handler::copy_pkt //
//------------------------------//
void udp_delay_handler::copy_pkt(int fd1, nbytes& buf, sockaddr_in& to) {
fd0 = fd1;
buf0 = buf;
to0 = to; // Struct copy.
} // End of function udp_delay_handler::copy_pkt.
//------------------------------//
// udp_delay_handler::handler //
//------------------------------//
int udp_delay_handler::handler() {
if (fd0 < 0 || buf0.empty())
return 0;
// UDP transmission (hope it doesn't block!):
int ret1 = sendto(fd0, buf0, to0);
if (ret1 < 0) {
cout << "udp_delay_handler::handler: Error sending delayed UDP packet."
<< endl;
perror("sendto");
}
return 0;
} // End of function udp_delay_handler::handler.
/*------------------------------------------------------------------------------
This handler should be called whenever the select() call on a UDP socket
finds that there are bytes to be read.
------------------------------------------------------------------------------*/
//----------------------//
// udp_handler::handler //
//----------------------//
int udp_handler::handler() {
// Check sanity of fd:
if (fd < 0)
return -1;
// Handle only read-events:
if (type != sREAD)
return -1;
// Receive the UDP packet on a non-blocking socket:
int ret = buf.recvfrom(fd);
// Check if recvfrom() had an error:
if (ret < 0) {
cout << "udp_handler::handler() error calling recvfrom()" << endl;
perror("recvfrom");
return -1;
}
// Check that the packet is at least an IP packet:
if (buf.from.sa_family != AF_INET || buf.fromlen != sizeof(sockaddr_in)) {
cout << "udp_handler::handler: received non-UDP packet." << endl;
return -1;
}
// Parse out the IP address and UDP port number of the sender:
fromhost = ntohl(((sockaddr_in*)&buf.from)->sin_addr.s_addr);
fromport = ntohs(((sockaddr_in*)&buf.from)->sin_port);
// Note: could at this point provide an optional cached address look-up of
// fromhost via inet_ntoa. But maybe this would be better in akslip.[ch].
// Take the appropriate action for the UDP packet:
int err = action();
// Return negative value to force return to selector caller:
return (err < 0) ? -1 : 0;
} // End of function udp_handler::handler.
//----------------------//
// udp_port_hand::action//
//----------------------//
int udp_port_hand::action() {
if (trace >= 10) {
cout << "Entered udp_port_hand::action()." << NL;
cout << "Number of handlers = " << handlers.length() << endl;
}
if (!get_selector()) {
if (trace >= 5)
cout << "udp_port_hand::action() failed to get selector." << endl;
return -1;
}
int err = -1;
Forall(voidptr, p, handlers) {
if (trace >= 10)
cout << "Checking UDP handler." << endl;
// Read a handler out of the chain of handlers:
udp_handler* ph0 = (udp_handler*)p->i;
if (!ph0)
continue; // Should never happen.
// Copy event info from *this (very slow -- should use reference):
ph0->set_selector(*get_selector());
ph0->fd = fd;
ph0->type = type;
ph0->buf = buf;
ph0->fromhost = fromhost;
ph0->fromport = fromport;
// Call the handler:
err = ph0->action();
if (trace >= 10)
cout << "Received " << err << " from UDP handler." << endl;
// Here should delete the handler if "delete_me" is set:
// ....
// If the event was handled okay, exit from function:
if (err >= 0)
break;
// Otherwise loop around to the next handler in the chain.
}
return err;
} // End of function udp_port_hand::action.
/*------------------------------------------------------------------------------
This just registers a new handler for a given local port. It is upt to the
handler to service the event if it can. Otherwise, it must indicate that the
event is not serviced, so that the next handler in the chain can handle it.
The returned udp_port_hand pointer is not supposed to be used for anything.
But a null return pointer means that the function failed.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Warning: the positivity of loc_port is not required here. If this results in the
kernel allocating the port number, then things will not be implemented as
intended. For instance, the second time you open port 0, you might not get a new
port number allocation. You would then re-use an existing port, which might not
be what you really wanted.
------------------------------------------------------------------------------*/
//----------------------//
// udp_hand_set::open //
//----------------------//
udp_port_hand* udp_hand_set::open(uint16 loc_port, uint32 loc_ip,
udp_handler* ph0, selector& sel0) {
if (trace >= 10)
cout << "Entering udp_hand_set::open()." << endl;
// Test arguments for sanity:
if (!ph0)
return 0;
// Open the local port (in a cached manner):
udp_port* p0 = port_set.open(loc_port, loc_ip);
if (!p0 || p0->fd() < 0)
return 0;
if (trace >= 10) {
cout << "udp_hand_set::open(): opened port_set:\n";
cout << "loc_port = " << loc_port << NL;
cout << "loc_ip = " << loc_ip << NL;
cout << flush;
}
// The file descriptor for the port:
int fd0 = p0->fd();
// Try to find the port in the list of handlers:
udp_port_hand* pph0 = 0;
forall(pph0, port_hands)
if (pph0->p0 == p0)
break;
// If this local port is new, create a new object for it:
if (!pph0) {
if (trace >= 10)
cout << "udp_hand_set::open() creating new udp_port_hand." << endl;
pph0 = new udp_port_hand(p0);
port_hands.append(pph0);
}
// Add the new handler to the list (sorted by "ph0", no duplicates!):
pph0->handlers.add((void*)ph0);
if (trace >= 10) {
cout << "udp_hand_set::open() added udp_handler.\n";
cout << "ph0 = 0x" << hex8(uint32(ph0)) << endl;
}
// Register the port with the selector:
sel0.set_fd_mask(fd0, sREAD, pph0);
return pph0;
} // End of function udp_hand_set::open.
//----------------------------------//
// tcp_handler::event_type_string //
//----------------------------------//
const char* tcp_handler::event_type_string(tcp_event_t t) {
switch(t) {
case tcpNULL:
return "null";
case tcpCALLING:
return "calling";
case tcpOPEN:
return "open";
case tcpDATA:
return "data";
case tcpCLOSE:
return "close";
} // End of switch(t).
return "[unknown TCP event]";
} // End of function tcp_handler::event_type_string.
/*------------------------------------------------------------------------------
This opens the TCP port in the passive mode.
------------------------------------------------------------------------------*/
//----------------------//
// tcp_handler::open //
//----------------------//
int tcp_handler::open(selector& sel0,
uint16 loc_port, uint32 loc_ip, int backlog) {
// If it's already open, ignore the request.
if (fd_cntl >= 0)
return eBAD_ARGUMENT;
// Clear everything:
buf.clear();
clear_in(from);
fromhost = 0;
fromport = 0;
fd_cntl = -1;
fd_data = -1;
tcp_open_return = 0;
if (trace >= 10)
cout << "tcp_handler::open: calling tcp_open()...\n";
int fd0 = tcp_open(loc_port, loc_ip, backlog);
if (trace >= 10)
cout << "tcp_handler::open: tcp_open() returned " << fd0 << DOTNL;
if (fd0 < 0) {
cout << "tcp_handler::open: failed to open TCP port "
<< ipstring(loc_ip) << "/" << loc_port << NL;
tcp_open_return = fd0;
return eOPEN_FAILED;
}
// Set the control port fd:
fd_cntl = fd0;
// Register the port and this handler with the selector:
if (trace >= 10)
cout << "tcp_handler::open: calling sel0.set_fd_mask()...\n";
sel0.set_fd_mask(fd0, sREAD, this);
active = false;
return 0;
} // End of function tcp_handler::open.
/*------------------------------------------------------------------------------
This opens the TCP port in the active mode.
Note: this function may block for a while.
Should really do this as some sort of a separate thread [joke].
------------------------------------------------------------------------------*/
//----------------------//
// tcp_handler::open //
//----------------------//
int tcp_handler::open(selector& sel0, uint16 rem_port, uint32 rem_ip,
uint16 loc_port, uint32 loc_ip) {
// If it's already open, ignore the request.
if (fd_cntl >= 0)
return -1;
// Clear everything:
buf.clear();
fromhost = rem_ip;
fromport = rem_port;
set_in(from, fromhost, fromport);
fd_cntl = -1; // Not used.
fd_data = -1;
tcp_open_return = 0;
if (trace >= 10)
cout << "tcp_handler::open: calling tcp_open()...\n";
int fd0 = -1;
int err = tcp_open(rem_port, rem_ip, loc_port, loc_ip, fd0);
if (trace >= 10) {
cout << "tcp_handler::open: tcp_open() return value = " << err;
if (err < 0)
cout << " (" << error_str(err) << ")";
cout << ", fd = " << fd0 << DOTNL;
}
if (err < 0) {
tcp_open_return = err;
if (err == eIN_PROGRESS) {
connect_in_progress = true;
event_type = tcpCALLING;
// Must queue data until the connection is ready.
}
else if (err < 0) {
cout << "tcp_handler::open: failed to open TCP conn: "
<< ipstring(loc_ip) << "/" << loc_port << " to ";
cout << ipstring(rem_ip) << "/" << rem_port << NL;
return -1;
}
}
else
event_type = tcpOPEN;
// Set the control port fd: [this is actually the data port!!!]
fd_data = fd0;
// Register the port and this handler with the selector:
if (trace >= 10)
cout << "tcp_handler::open: calling sel0.set_fd_mask()...\n";
sel0.set_fd_mask(fd0, (sREAD | sWRITE), this);
active = true;
err = action();
if (trace >= 5) {
cout << "tcp_handler::open(): action() returned "
<< err << "." << endl;
}
// Return negative value to force return to selector caller:
return (err < 0) ? -1 : 0;
// return 0;
} // End of function tcp_handler::open.
/*------------------------------------------------------------------------------
This handler should be called whenever the select() call on a TCP socket
finds that there are bytes to be read or some other event occurs.
------------------------------------------------------------------------------*/
//----------------------//
// tcp_handler::handler //
//----------------------//
int tcp_handler::handler() {
if (fd < 0) {
if (trace >= 5)
cout << "tcp_handler::handler called with fd < 0." << endl;
return -1;
}
if (!active && fd == fd_cntl) { // The control socket.
if (trace >= 5)
cout << "tcp_handler::handler called with fd == fd_cntl." << endl;
if (type != sREAD) {
cout << "tcp_handler::handler: non-read event for fd_cntl." << endl;
return -1;
}
// If this happens, then a second remote port is calling while a
// connection is already in progress.
if (fd_data >= 0) {
cout << "tcp_handler::handler:"
" read event for fd_cntl when fd_data open.\n";
cout << "(This is a serious error!)" << endl;
}
int fd0 = accept_in(fd_cntl, from);
if (fd0 < 0) {
cout << "tcp_handler::handler(): could not accept TCP socket.\n";
return -1;
}
// Register the new data socket and this handler with the selector:
// (...and also turn off arrival of new connections...)
if (get_selector()) {
get_selector()->set_fd_mask(fd0, sREAD, this);
get_selector()->clear_fd_mask(fd_cntl, sREAD);
}
// Make a copy of the new data fd:
fd_data = fd0;
// Parse out the IP address and TCP port number of the sender:
fromhost = ntohl(from.sin_addr.s_addr);
fromport = ntohs(from.sin_port);
// Note: could provide an optional cached address look-up here of
// fromhost via inet_ntoa. But this might be better in akslip.[ch].
// ....
// Give any derived class a chance to take an action on event arrival:
event_type = tcpOPEN;
int err = action();
if (trace >= 5) {
cout << "tcp_handler::handler: action() returned "
<< err << "." << endl;
}
// Return negative value to force return to selector caller:
return (err < 0) ? -1 : 0;
// return 0;
}
else if (fd == fd_data) { // The data socket (active or passive).
if (trace >= 5)
cout << "tcp_handler::handler called with fd == fd_data." << endl;
if (!active && fd_cntl < 0) {
cout << "tcp_handler::handler:"
" read event for fd_data when fd_cntl closed." << endl;
return -1;
}
// It might be a delayed TCP connect():
if (type == sWRITE && active && connect_in_progress) {
if (trace >= 10)
cout << "tcp_handler::handler: calling tcp_reopen()...\n";
int fd0 = tcp_reopen(fd_data, fromport, fromhost);
if (trace >= 10) {
cout << "tcp_handler::handler: tcp_reopen() returned " << fd0;
if (fd0 < 0)
cout << " (" << error_str(fd0) << ")";
cout << DOTNL;
}
if (fd0 == eIN_PROGRESS) {
connect_in_progress = true;
// Give derived class a chance to take action on event arrival:
event_type = tcpCALLING;
int err = action();
if (trace >= 5) {
cout << "tcp_handler::handler: action() returned "
<< err << "." << endl;
}
// Must queue data until the connection is ready.
return (err < 0) ? -1 : 0;
}
else if (fd0 < 0) {
cout << "tcp_handler::handler: failed to reopen TCP conn. to "
<< ipstring(fromhost) << "/" << fromport << endl;
return -1;
}
else
event_type = tcpOPEN;
// Clear write-events on the control/data port fd:
fd_data = fd0; // Is this sensible?
connect_in_progress = false;
get_selector()->clear_fd_mask(fd_data, sWRITE);
if (tx_data_wait.n_bytes() > 0) {
// Write the saved-up bytes:
char* pc = tx_data_wait.copy();
int err = ::write(fd_data, pc, int(tx_data_wait.n_bytes()));
if (trace >= 5) {
cout << "tcp_handler::handler(): wrote "
<< int(tx_data_wait.n_bytes())
<< " bytes to TCP socket.\n";
cout << "result from ::write() was " << err << NL;
}
delete[] pc;
if (err < 0) {
cout << "tcp_handler::handler(): error writing to fd_data."
<< endl;
perror("write");
return 0;
}
tx_data_wait.clear();
}
// Give derived class a chance to take action on event arrival:
event_type = tcpOPEN;
int err = action();
if (trace >= 5) {
cout << "tcp_handler::handler: action() returned "
<< err << "." << endl;
}
return (err < 0) ? -1 : 0;
// return 0;
}
// At this point, we have fd == fd_data and
// either (type != sWRITE) or (!active) or (!connect_in_progress).
// We should not get a write-event except when active and connecting.
if (type != sREAD) {
cout << "tcp_handler::handler: non-read event for fd_data." << endl;
return -1;
}
// At this point, fd == fd_data and the event is a read-event.
// Read the data:
int n_bytes = buf.read_append(fd_data);
if (trace >= 5) {
cout << "tcp_handler::handler: buf.read_append() returned "
<< n_bytes << " byte" << plural_s(n_bytes) << DOTNL;
}
if (n_bytes < 0) {
cout << "tcp_handler::handler: TCP socket read error. fd_data = "
<< fd_data << endl;
perror("read");
return -1;
}
// If the number of bytes is 0, then the socket has been closed:
if (n_bytes == 0) {
// Un-register the new port and this handler with the selector:
// (...and re-register the control port...)
if (get_selector()) {
get_selector()->clear_fd_mask(fd_data, sREAD);
get_selector()->set_fd_mask(fd_cntl, sREAD, this);
}
::close(fd_data);
fd_data = -1;
clear_in(from);
fromhost = 0;
fromport = 0;
if (trace >= 5)
cout << "tcp_handler::handler: TCP connection closed." << endl;
// Give derived class a chance to take an action on closing:
event_type = tcpCLOSE;
int err = action();
if (trace >= 5) {
cout << "tcp_handler::handler: action() returned "
<< err << "." << endl;
}
// Return negative value to force return to selector caller:
return (err < 0) ? -1 : 0;
// return 0;
}
// Take the appropriate action for the TCP packet:
event_type = tcpDATA;
int err = action();
if (trace >= 5) {
cout << "tcp_handler::handler: action() returned "
<< err << "." << endl;
}
// Return negative value to force return to selector caller:
return (err < 0) ? -1 : 0;
}
// Case that the fd etc. are not recognised:
if (trace >= 5) {
cout << "tcp_handler::handler() called with fd == "
<< fd << "." << endl;
}
return -1;
} // End of function tcp_handler::handler.
/*------------------------------------------------------------------------------
Return the number of bytes written successfully to the TCP port.
------------------------------------------------------------------------------*/
//----------------------//
// tcp_handler::write //
//----------------------//
int tcp_handler::write(const char* nbuf, int n) {
if (trace >= 10) {
cout << "tcp_handler::write(): number of bytes = " << n << NL;
print(cout);
}
if (!nbuf || n <= 0)
return 0;
if (!open() || (active && connect_in_progress)) {
tx_data_wait.append_bytes(nbuf, n);
return 0;
}
int err = ::write(fd_data, nbuf, n);
if (err < 0) {
cout << "tcp_handler::write(): error writing to TCP port." << endl;
perror("write");
return 0;
}
// Return number of bytes written:
return err;
} // End of function tcp_handler::write.
/*------------------------------------------------------------------------------
Return the number of bytes written successfully to the TCP port.
------------------------------------------------------------------------------*/
//----------------------//
// tcp_handler::write //
//----------------------//
/*------------------------------------------------------------------------------
int tcp_handler::write(const nbytes& nbuf) {
if (trace >= 10) {
cout << "tcp_handler::write(): number of bytes = " << nbuf.n_bytes()
<< NL;
print(cout);
}
if (nbuf.empty())
return 0;
if (!open() || (active && connect_in_progress)) {
tx_data_wait.append_bytes(nbuf);
return 0;
}
int err = ::write(fd_data, nbuf.bytes(), nbuf.n_bytes());
if (err < 0) {
cout << "tcp_handler::write(): error writing to TCP port." << endl;
perror("write");
return 0;
}
// Return number of bytes written:
return err;
} // End of function tcp_handler::write.
------------------------------------------------------------------------------*/
//----------------------//
// tcp_handler::print //
//----------------------//
void tcp_handler::print(ostream& os) {
os << "tcp_handler state:\n";
os << "active = " << be_string(active) << NL;
os << "remote host/port = " << ipstring(fromhost)
<< "/" << fromport << NL;
os << "fd_cntl = " << fd_cntl << ", fd_data = " << fd_data << NL;
os << "connect_in_progress = " << be_string(connect_in_progress) << NL;
os << "buf contains " << buf.n_bytes() << " bytes\n";
os << "tx_data_wait contains " << tx_data_wait.n_bytes()
<< " bytes\n";
} // End of function tcp_handler::print.
//--------------------------//
// tcp_contextlist::find_fd //
//--------------------------//
tcp_context* tcp_contextlist::find_fd(int fd) {
tcp_context* tcp0 = 0;
forall(tcp0, *this)
if (tcp0->fd_data == fd)
break;
return tcp0;
} // End of function tcp_contextlist::find_fd.
//------------------------------//
// tcp_contextlist::find_from //
//------------------------------//
tcp_context* tcp_contextlist::find_from(const sockaddr_in& from) {
tcp_context* tcp0 = 0;
forall(tcp0, *this)
if (equal_in(tcp0->from, from))
break;
return tcp0;
} // End of function tcp_contextlist::find_from.
/*------------------------------------------------------------------------------
This is (currently) the same as the tcp_handler:: function of the same name.
------------------------------------------------------------------------------*/
//----------------------------------//
// m_tcp_handler::event_type_string //
//----------------------------------//
const char* m_tcp_handler::event_type_string(tcp_event_t t) {
switch(t) {
case tcpNULL:
return "null";
case tcpCALLING:
return "calling";
case tcpOPEN:
return "open";
case tcpDATA:
return "data";
case tcpCLOSE:
return "close";
} // End of switch(t).
return "[unknown TCP event]";
} // End of function m_tcp_handler::event_type_string.
/*------------------------------------------------------------------------------
This opens the TCP control socket in the passive mode.
There is only 1 control socket, but there may be many data sockets.
------------------------------------------------------------------------------*/
//----------------------//
// m_tcp_handler::open //
//----------------------//
int m_tcp_handler::open(selector& sel0,
uint16 loc_port, uint32 loc_ip, int backlog) {
// If it's already open, ignore the request.
if (fd_cntl >= 0)
return eBAD_ARGUMENT;
// Clear some variables in case of error-return.
fd_cntl = -1;
if (trace >= 10)
cout << "m_tcp_handler::open: calling tcp_open()...\n";
int fd0 = tcp_open(loc_port, loc_ip, backlog);
if (trace >= 10)
cout << "m_tcp_handler::open: tcp_open() returned " << fd0 << DOTNL;
if (fd0 < 0) {
cout << "m_tcp_handler::open: failed to open TCP port "
<< ipstring(loc_ip) << ":" << loc_port << NL;
return eOPEN_FAILED;
}
// Set the control port fd:
fd_cntl = fd0;
// Register the port and this handler with the selector:
if (trace >= 10)
cout << "m_tcp_handler::open: calling sel0.set_fd_mask()...\n";
sel0.set_fd_mask(fd0, sREAD, this);
return 0;
} // End of function m_tcp_handler::open.
/*------------------------------------------------------------------------------
This handler is called whenever the select() call on a TCP socket finds that
there are bytes to be read or some other event occurs.
Unlike the single data-socket version, this multiple data-socket handler must
use the "from" address for a data-socket to retrieve the context descriptor for
the connection.
------------------------------------------------------------------------------*/
//--------------------------//
// m_tcp_handler::handler //
//--------------------------//
int m_tcp_handler::handler() {
if (fd < 0) {
if (trace >= 5)
cout << "m_tcp_handler::handler called with fd < 0." << endl;
return -1;
}
if (fd == fd_cntl) { // The event is for the control socket.
if (trace >= 5)
cout << "m_tcp_handler::handler called with fd == fd_cntl." << endl;
if (type != sREAD) {
cout << "m_tcp_handler::handler:"
" non-read event for control socket." << endl;
return -1;
}
// A read-event on the control socket means "new connection".
int fd0 = accept_in(fd_cntl, from);
if (fd0 < 0) {
cout << "m_tcp_handler::handler(): could not accept TCP socket.\n";
return -1;
}
// Register the new data socket and this handler with the selector.
// (...and don't turn off arrival of new connections...)
if (get_selector()) { // Should always be non-zero.
get_selector()->set_fd_mask(fd0, sREAD, this);
}
// Parse the IP address and TCP port number from the sender.
fromhost = ntohl(from.sin_addr.s_addr);
fromport = ntohs(from.sin_port);