-
Notifications
You must be signed in to change notification settings - Fork 13
/
repeater.cpp
2096 lines (1744 loc) · 74.1 KB
/
repeater.cpp
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
// ///////////////////////////////////////////////////////////////////////////
// Copyright (C) 2002 Ultr@VNC Team Members. All Rights Reserved.
//
// 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.
//
// Program is based on the
// http://www.imasy.or.jp/~gotoh/ssh/connect.c
// Written By Shun-ichi GOTO <[email protected]>
//
// If the source code for the program is not available from the place
// from which you received this file, check
// http://ultravnc.sourceforge.net/
//
// Linux port (C) 2005- Jari Korhonen, [email protected]
//////////////////////////////////////////////////////////////////////
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <memory.h>
#include <errno.h>
#include <assert.h>
#include <stdarg.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <netdb.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pwd.h> //for getpwnam() in dropPrivileges()
#include "commondefines.h"
#include "repeaterproc.h"
#include "readini.h"
#include "repeaterutil.h"
#include "repeaterevents.h"
#include "repeater.h"
#define REPEATER_VERSION "0.17"
#define RFB_PROTOCOL_VERSION_FORMAT "RFB %03d.%03d\n"
#define RFB_PROTOCOL_MAJOR_VERSION 0
#define RFB_PROTOCOL_MINOR_VERSION 0
#define SIZE_RFBPROTOCOLVERSIONMSG 12
#define RFB_PORT_OFFSET 5900 //servers 1st display is in this port number
#define MAX_IDLE_CONNECTION_TIME 600 //Seconds
#define MAX_HOST_NAME_LEN 250
#define MAX_PATH 250
#define MAX_HANDSHAKE_LEN 100
#define UNKNOWN_REPINFO_IND 999999 //Notice: This should always be bigger than maxSessions
#define LISTEN_BACKLOG 5 //Listen() queues 5 connections
//connectionFrom defines for acceptConnection(). Used also in connectionRemover()
#define CONNECTION_FROM_SERVER 0
#define CONNECTION_FROM_VIEWER 1
//Use safer openbsd stringfuncs: strlcpy, strlcat
#include "openbsd_stringfuncs.h"
char DEFAULT_INI_FILE_PATH_AND_NAME[] = "/etc/uvnc/uvncrepeater.ini";
typedef char rfbProtocolVersionMsg[SIZE_RFBPROTOCOLVERSIONMSG+1]; /* allow extra byte for null */
typedef struct _repeaterInfo {
int socket;
//Code is used for cross-connection between servers and viewers
//In Mode 2, Server/Viewer sends IdCode string "ID:xxxxx", where xxxxx is some positive (1 or bigger) long integer number
//In Mode 1, Repeater "invents" a non-used code (negative number) and assigns that to both Server/Viewer
//code == 0 means that entry in servers[] / viewers[] table is free
long code;
unsigned long timeStamp;
//Ip address of peer
addrParts peerIp;
//There are 3 connection levels (using variables "code" and "active"):
//A. code==0,active==false: fully idle, no connection attempt detected
//B. code==non-zero,active==false: server/viewer has connected, waiting for other end to connect
//C. code==non-zero,active=true: doRepeater() running on viewer/server connection, fully active
//-after viewer/server disconnects or some error in doRepeater, returns both to level A
//(and closes respective sockets)
//This logic means, that when one end disconnects, BOTH ends need to reconnect.
//This is not a bug, it is a feature ;-)
bool active;
} repeaterInfo;
static repeaterInfo *servers[MAX_SESSIONS_MAX];
static repeaterInfo *viewers[MAX_SESSIONS_MAX];
//Server handshake strings for use when respective viewer connects later
typedef struct _handShakeInfo
{
char handShake[MAX_HANDSHAKE_LEN];
int handShakeLength;
} handShakeInfo;
static handShakeInfo *handShakes[MAX_SESSIONS_MAX];
//mode1ConnCode is used in Mode1 to "invent" code field in repeaterInfo, when new Mode1 connection from
//viewer is accepted. This is just decremented for each new Mode 1 connection to ensure unique number
//for each Mode 1 session
//Values for this are: 0=program has just started, -1....MIN_INVENTED_CONN_CODE: Codes for each session
#define MIN_INVENTED_CONN_CODE -1000000
static long mode1ConnCode;
//This structure (and repeaterProcs[] table) is used for
//keeping track of child processes running doRepeater
//and cleaning up after they exit
typedef struct _repeaterProcInfo
{
long code;
pid_t pid;
} repeaterProcInfo;
static repeaterProcInfo *repeaterProcs[MAX_SESSIONS_MAX];
//This structure keeps information of ports/socket used when
//routeConnections() listens for new incoming connections
typedef struct _listenPortInfo {
int socket;
int port;
} listenPortInfo;
//Repeater "events" interface uses this variable. Various "events"
//are sent to interface using function sendRepeaterEvent()
//and later handled with function handleRepeaterEvents(), which forks a child
//process to handle the grunt work of event posting
//Child process is later cleaned up calling function cleanUpAfterEventProc()
static repeaterEvent event;
//stopped==true means that user wants program to stop (has pressed ctrl+c)
//From version 0.08 onwards, function fatal() also sets stopped == TRUE to achieve clean shutdown
static bool stopped;
static int nonBlockingRead(int sock, char *buf, int len, int timeOut);
static int findViewerList(long code);
static void cleanUpAfterRepeaterProcs(void);
static void logLineStart(const char *prefix);
static int connectWithTimeout(int socket, const struct sockaddr *addr, socklen_t addrlen, int timeOutSecs);
//Global functions
//Global functions
//Global functions
void debug(int msgLevel, const char *fmt, ...)
{
va_list args;
if (msgLevel <= loggingLevel) {
logLineStart("UltraVnc");
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
}
void fatal(const char *fmt, ...)
{
va_list args;
logLineStart("UltraVnc FATAL");
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
//Close program down cleanly (as if user just pressed ctrl+c, of course
//log file will show FATAL message in case program shuts down)
stopped = true;
}
//Try to connect to event listener, return connected socket if success, -1 if error
//parameter listenerIp holds eventlistener's ip address on return (or "" in case of error)
int openConnectionToEventListener(const char *host, unsigned short port, char *listenerIp, int listenerIpSize)
{
int s;
struct sockaddr_in saddr;
struct hostent *h;
h = gethostbyname(host);
if (NULL == h) {
debug(LEVEL_2, "openConnectionToEventListener(): can't resolve hostname: %s\n", host);
return -1;
}
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port);
//Interesting;-) typecast / indirection thing copied from "Beej's Guide to network programming".
//See http://beej.us/guide/bgnet/ for more info
saddr.sin_addr = *((struct in_addr *)h->h_addr);
memset(&(saddr.sin_zero), '\0', 8); // zero the rest of the struct
strlcpy(listenerIp, inet_ntoa(saddr.sin_addr), listenerIpSize);
debug(LEVEL_3, "openConnectionToEventListener(): connecting to %s:%u\n", listenerIp, port);
s = socket(AF_INET, SOCK_STREAM, 0);
//Trying to connect with timeout
if (connectWithTimeout(s, (struct sockaddr *) &saddr, sizeof(saddr), TIMEOUT_10SECS) != 0) {
debug(LEVEL_2, "openConnectionToEventListener(): connectWithTimeout() failed.\n");
close(s);
strlcpy(listenerIp, "", listenerIpSize);
return -1;
}
else
return s;
}
//Try to write exact number of bytes to socket
//return 1 if things went OK,
//return -2 in case of timeout
//return -1 in case of error
int writeExact(int sock, char *buf, int len, int timeOutSecs)
{
int n;
int timeOutCtr;
debug(LEVEL_3, "writeExact(): start\n");
timeOutCtr=0;
while ((len > 0) && (timeOutCtr < timeOutSecs)) {
n = send(sock, buf, len, MSG_DONTWAIT);
if (n > 0) {
buf += n;
len -= n;
}
else if (n == 0) {
debug(LEVEL_3, "writeExact(): send returned 0\n");
return -1;
}
else {
//send() returned -1 to indicate some error
//Because we use non-blocking in send(), we have to
//handle EAGAIN by incrementing timeout counter
if (errno == EAGAIN) {
debug(LEVEL_3, "writeExact(): EAGAIN detected\n");
sleep(1);
timeOutCtr++;
}
else {
debug(LEVEL_3, "writeExact(): send() returned error, errno = %d (%s)\n", errno, strerror(errno));
return -1;
}
}
}
if (timeOutCtr < timeOutSecs) {
debug(LEVEL_3, "writeExact(): returning normally\n");
return 1;
}
else {
debug(LEVEL_3, "writeExact(): timeout error\n");
return -2;
}
}
//Local functions
//Local functions
//Local functions
//Standard log line start common for all types of messages: debug / fatal
static void logLineStart(const char *prefix)
{
time_t errTime;
char buf[MY_TMP_BUF_LEN];
char *lf;
errTime = time(NULL);
//ctime() adds '\n' to line end, change that to space
strlcpy(buf, ((errTime != -1) ? ctime(&errTime) : ""), MY_TMP_BUF_LEN);
lf = strchr(buf, '\n');
if (NULL != lf)
*lf = ' ';
fprintf(stderr, "%s %s> ", prefix, buf);
}
//Allocate memory for various lists of repeater when program starts
//This routine is needed from version 0.12,
//because lists are not statically allocated anymore
//but can be dynamically changed via ini file setting
//Return true if Ok, false if error
static bool allocateMemoryForRepeaterLists(int numSessions)
{
int ii;
for(ii = 0; ii < MAX_SESSIONS_MAX; ii++) {
handShakes[ii] = NULL;
repeaterProcs[ii] = NULL;
servers[ii] = NULL;
viewers[ii] = NULL;
}
for(ii = 0; ii < numSessions; ii++) {
handShakes[ii] = (handShakeInfo *) calloc(1, sizeof(handShakeInfo));
if (handShakes[ii] == NULL)
return false;
repeaterProcs[ii] = (repeaterProcInfo *) calloc(1, sizeof(repeaterProcInfo));
if (repeaterProcs[ii] == NULL)
return false;
servers[ii] = (repeaterInfo *) calloc(1, sizeof(repeaterInfo));
if (servers[ii] == NULL)
return false;
viewers[ii] = (repeaterInfo *) calloc(1, sizeof(repeaterInfo));
if (viewers[ii] == NULL)
return false;
}
return true;
}
//Free memory of various repeater lists (if allocated)
static void freeMemoryOfRepeaterLists(void)
{
int ii;
for(ii = 0; ii < MAX_SESSIONS_MAX; ii++) {
if (handShakes[ii] != NULL) {
free(handShakes[ii]);
handShakes[ii] = NULL;
}
if (repeaterProcs[ii] != NULL) {
free(repeaterProcs[ii]);
repeaterProcs[ii] = NULL;
}
if (servers[ii] != NULL) {
free(servers[ii]);
servers[ii] = NULL;
}
if (viewers[ii] != NULL) {
free(viewers[ii]);
viewers[ii] = NULL;
}
}
}
//Clean various lists of repeater when program starts
static void cleanLists(void)
{
int ii;
for (ii = 0; ii < maxSessions; ii++) {
memset(handShakes[ii], 0, sizeof(handShakeInfo));
memset(repeaterProcs[ii], 0, sizeof(repeaterProcInfo));
memset(servers[ii], 0, sizeof(repeaterInfo));
memset(viewers[ii], 0, sizeof(repeaterInfo));
}
}
static void addRepeaterProcList(long code, pid_t pid)
{
int i;
for (i = 0; i < maxSessions; i++) {
if (repeaterProcs[i] -> code == 0) {
debug(LEVEL_3, "addRepeaterProcList(): Added proc to index=%d, pid=%d, code=%ld\n", i, pid, code);
repeaterProcs[i] -> code = code;
repeaterProcs[i] -> pid = pid;
return;
}
}
debug(LEVEL_2, "addRepeaterProcList(): Warning, no free process slots found\n");
}
static void removeRepeaterProcList(pid_t pid)
{
int i;
for (i = 0; i < maxSessions; i++) {
if (repeaterProcs[i] -> pid == pid) {
debug(LEVEL_3, "removeRepeaterProcList(): Removing proc from index=%d, pid=%d\n", i, pid);
repeaterProcs[i] -> code = 0;
repeaterProcs[i] -> pid = 0;
return;
}
}
debug(LEVEL_2, "removeRepeaterProcList(): Warning, did not find any process to remove\n");
}
static int findRepeaterProcList(pid_t pid)
{
int i;
for (i = 0; i < maxSessions; i++) {
if (repeaterProcs[i] -> pid == pid) {
debug(LEVEL_3, "findRepeaterProcList(): proc found at index=%d, pid=%d, code = %ld\n",
i, pid, repeaterProcs[i] -> code);
return i;
}
}
debug(LEVEL_2, "findRepeaterProcList(): Warning, did not find any proc (pid=%d)\n", pid);
return UNKNOWN_REPINFO_IND;
}
static int addServerList(int socket, long code, char *peerIp)
{
int i;
for (i = 0; i < maxSessions; i++) {
if (servers[i] -> code == 0) {
debug(LEVEL_3, "addServerList(): Server added to list: code = %ld, index = %d\n", code, i);
servers[i] -> code = code;
servers[i] -> socket = socket;
servers[i] -> peerIp = getAddrPartsFromString(peerIp);
servers[i] -> timeStamp = time(NULL); /* 1 second accuracy is enough ? */
servers[i] -> active = false;
return i;
}
}
debug(LEVEL_2, "addServerList(): Warning, no table slots available\n");
return -1; //Not added
}
static void removeServerList(long code)
{
int i;
for (i = 0; i < maxSessions; i++) {
if (servers[i] -> code == code) {
debug(LEVEL_3, "removeServerList(): Server Removed from list: code = %ld, index = %d\n", code, i);
servers[i] -> code = 0;
servers[i] -> active = false;
return;
}
}
debug(LEVEL_2, "removeServerList(): Warning, server not found (code = %ld)\n", code);
}
static void setServerActive(long code)
{
int i;
for (i = 0; i < maxSessions; i++) {
if (servers[i] -> code == code) {
servers[i] -> active = true;
debug(LEVEL_3, "setServerActive(): activated server at index = %d, code = %ld\n", i, servers[i] -> code);
return;
}
}
debug(LEVEL_2, "setServerActive(): server not found (code = %ld)\n", code);
}
static int findServerList(long code)
{
int i;
for (i = 0; i < maxSessions; i++) {
if (servers[i] -> code == code) {
debug(LEVEL_3, "findServerList(): server found at index %d, code = %ld\n", i, servers[i] -> code);
return i;
}
}
debug(LEVEL_2, "findServerList(): server not found (code = %ld)\n", code);
return UNKNOWN_REPINFO_IND;
}
static int addViewerList(int socket, long code, char *peerIp)
{
int i;
for (i = 0; i < maxSessions; i++) {
if (viewers[i] -> code == 0) {
debug(LEVEL_3, "addViewerList(): Viewer added to list: code = %ld, index = %d\n", code, i);
viewers[i] -> code = code;
viewers[i] -> socket = socket;
viewers[i] -> peerIp = getAddrPartsFromString(peerIp);
viewers[i] -> timeStamp = time(NULL);
viewers[i] -> active = false;
return i;
}
}
debug(LEVEL_2, "addViewerList(): Warning, no table slots available\n");
return -1; //Not added
}
static void removeViewerList(long code)
{
int i;
for (i = 0; i < maxSessions; i++) {
if (viewers[i] -> code == code) {
debug(LEVEL_3, "removeViewerList(): Viewer removed from list: code = %ld, index = %d\n", code, i);
viewers[i] -> code = 0;
viewers[i] -> active = false;
return;
}
}
debug(LEVEL_2, "removeViewerList(): Warning, viewer not found (code = %ld)\n", code);
}
static void setViewerActive(long code)
{
int i;
for (i = 0; i < maxSessions; i++) {
if (viewers[i] -> code == code) {
viewers[i] -> active = true;
debug(LEVEL_3, "setViewerActive(): activated viewer at index %d, code = %ld\n", i, viewers[i] -> code);
return;
}
}
debug(LEVEL_2, "setViewerActive(): Warning, viewer not found (code = %ld)\n", code);
}
static int findViewerList(long code)
{
int i;
for (i = 0; i < maxSessions; i++) {
if (viewers[i] -> code == code) {
debug(LEVEL_3, "findViewerList(): viewer found at index %d, code = %ld\n", i, viewers[i] -> code);
return i;
}
}
debug(LEVEL_2, "findViewerList(): Warning, viewer not found (code = %ld)\n", code);
return UNKNOWN_REPINFO_IND;
}
//Check IdCode string, require that 1st 3 characters of IdCode are 'I','D',':'
static bool checkIdCode(char *IdCode)
{
if ((IdCode[0] != 'I') || (IdCode[1] != 'D') || (IdCode[2] != ':')) {
debug(LEVEL_3, "checkIdCode(): %s is not IdCode string\n", IdCode);
return false;
}
return true;
}
//Parse IdCode string of format "ID:xxxxx", where xxxxx is some positive (non-zero) long integer number
//Return -1 on error, xxxxx on success
static long parseId(char *IdCode)
{
unsigned int ii;
//PFaf 20101122: Minor correction due to compiler warning
//int retVal;
long retVal;
debug(LEVEL_3, "parseId(): IdCode = %s\n", IdCode);
//Require that 1st 3 characters of IdCode are 'I','D',':'
if (false == checkIdCode(IdCode)) {
debug(LEVEL_3, "parseId(): IdCode format error, does not start ""ID:"" \n");
return -1;
}
else {
//Require that all other characters of IdCode are digits
for (ii = 3; ii < strlen(IdCode); ii++) {
if (!isdigit(IdCode[ii])) {
debug(LEVEL_3, "parseId(): IdCode format error, code should consist of decimal digits\n");
return -1;
}
}
retVal = strtol(&(IdCode[3]), NULL, 10);
if (retVal <= 0) {
debug(LEVEL_3, "parseId(): IdCode format error, code should be positive long integer number\n");
return -1;
}
else if (retVal == LONG_MAX) {
debug(LEVEL_3, "parseId(): IdCode format error, code is too big\n");
return -1;
}
return retVal;
}
}
//Return value: n > 0: number of bytes read
//-1: recv() error
//-2: timeout error
static int nonBlockingRead(int sock, char *buf, int len, int timeOut)
{
int n;
int timeOutCtr;
int numRead = 0;
debug(LEVEL_3, "nonBlockingRead(): start\n");
timeOutCtr=0;
while ((len > 0) && (timeOutCtr < timeOut)) {
n = recv(sock, buf, len, MSG_DONTWAIT);
if (n > 0) {
buf += n;
len -= n;
numRead += n;
}
else {
if (n == -1) {
//recv() returned -1 to indicate some error
//Because we use non-blocking in recv(), we have to
//handle EAGAIN by incrementing timeout counter
if (errno == EAGAIN) {
sleep(1);
timeOutCtr++;
}
}
else {
debug(LEVEL_2, "nonBlockingRead(): recv() returned error, errno= %d (%s)\n", errno, strerror(errno));
return -1; //return value of recv() was unknown
}
}
}
if (timeOutCtr < timeOut) {
debug(LEVEL_3, "nonBlockingRead(): returning normally\n");
return numRead;
}
else {
//In case of timeout, return number of bytes received if > 0,
//otherwise return -2 to indicate timeout
if (numRead > 0) {
debug(LEVEL_3, "nonBlockingRead(): returning %d bytes\n", numRead);
return numRead;
}
else {
debug(LEVEL_3, "nonBlockingRead(): timeout error\n");
return -2;
}
}
}
//Function determines if connection is "too old" (older thar MAX_IDLE_CONNECTION_TIME)
bool isConnectionTooOld(unsigned long timeStamp)
{
unsigned long tick = time(NULL);
if ((tick - timeStamp) > MAX_IDLE_CONNECTION_TIME)
return true;
else
return false;
}
//Function determines if connection is inactive
bool isExistingConnectionInactive(bool active, bool existing)
{
if ((existing) && (!active))
return true;
else
return false;
}
//Function determines if connection is broken
bool isPeerDisconnected(int socket, int connectionFrom)
{
ssize_t n;
char buf[SIZE_RFBPROTOCOLVERSIONMSG+1];
buf[SIZE_RFBPROTOCOLVERSIONMSG] = '\0';
n = recv(socket, buf, SIZE_RFBPROTOCOLVERSIONMSG, MSG_DONTWAIT);
if (n == 0) {
debug(LEVEL_3, "isPeerDisconnected: recv() returned 0 (peer has disconnected orderly)\n");
return true; //peer has disconnected orderly
}
else if (n == -1) {
//recv() returned -1 to indicate some error
if (errno == EAGAIN) {
//Because we use non-blocking in recv(), EAGAIN is ok
return false;
}
else {
debug(LEVEL_2, "isPeerDisconnected: recv() returned error, errno = %d (%s)\n", errno, strerror(errno));
return true;
}
}
else if (n >= 1) {
//peer has sent data OK
debug(LEVEL_3, "isPeerDisconnected: recv() returned: %s\n", buf);
return false;
}
else {
//unknown error
debug(LEVEL_2, "isPeerDisconnected: recv() returned error, errno = %d (%s)\n", errno, strerror(errno));
return true;
}
}
//Remove [old idle | broken] [viewer | server] connection
static void connectionRemover(int connectionFrom, repeaterInfo *rI, int index)
{
bool fRemove;
char removalReason[MY_TMP_BUF_LEN];
fRemove = false;
strlcpy(removalReason, "", MY_TMP_BUF_LEN);
if (isExistingConnectionInactive(rI -> active, (rI -> code != 0))) {
if (isConnectionTooOld(rI -> timeStamp)) {
//Existing connection has been idle for too long, remove
fRemove = true;
snprintf(removalReason, MY_TMP_BUF_LEN, "%s", "idle connection too old");
}
else if (isPeerDisconnected(rI -> socket, connectionFrom)) {
//Peer has closed the connection before another peer appeared, remove
fRemove = true;
snprintf(removalReason, MY_TMP_BUF_LEN, "%s", "peer has disconnected");
}
if (fRemove) {
//Send VIEWER_DISCONNECT / SERVER_DISCONNECT to event interface
if (useEventInterface) {
repeaterEvent event;
connectionEvent connEv;
event.eventNum = (connectionFrom == CONNECTION_FROM_VIEWER) ? VIEWER_DISCONNECT : SERVER_DISCONNECT;
event.timeStamp = time(NULL);
event.repeaterProcessId = getpid();
connEv.tableIndex = index;
connEv.code = rI -> code;
connEv.connMode = (rI -> code < 0) ? CONN_MODE1 : CONN_MODE2;
connEv.peerIp = rI -> peerIp;
memcpy(event.extraInfo, &connEv, sizeof(connectionEvent));
if (false == sendRepeaterEvent(event)) {
debug(LEVEL_1, "connectionRemover(): Warning, event fifo is full\n");
}
}
//Remove & close connection
close(rI -> socket);
debug(LEVEL_1, "connectionRemover(): Removing %s %ld at index %d (%s)\n",
(connectionFrom == CONNECTION_FROM_VIEWER) ? "viewer" : "server",
rI -> code,
index,
removalReason);
if (connectionFrom == CONNECTION_FROM_VIEWER)
removeViewerList(rI -> code);
else
removeServerList(rI -> code);
}
}
}
//This function is periodically called from routeConnections() to remove
//servers / viewers that did not receive any matching other end connection
static void removeOldOrBrokenConnections(void)
{
int ii;
for (ii = 0; ii < maxSessions; ii++) {
//Remove old inactive viewers
connectionRemover(CONNECTION_FROM_VIEWER, viewers[ii], ii);
//Remove old inactive servers
connectionRemover(CONNECTION_FROM_SERVER, servers[ii], ii);
}
}
//Parse [hostname / ip address] / [port number / display number] combination
//Return true if success, false if error
static bool parseHostAndPort(char *id, char *host, int hostLen, int *port)
{
int tmpPort;
char *colonPos;
debug(LEVEL_3, "parseHostAndPort() start: id = %s\n", id);
colonPos = strchr(id, ':');
if (hostLen < (int) strlen(id)) {
debug(LEVEL_3, "parseHostAndPort(): Id string too long\n");
return false;
}
if (colonPos == NULL) {
// No colon -- use default port number
tmpPort = RFB_PORT_OFFSET;
strlcpy(host, id, hostLen);
}
else {
strlcpy(host, id, (colonPos-id)+1);
if (colonPos[1] == ':') {
// Two colons -- interpret as a port number
if (sscanf(colonPos + 2, "%d", &tmpPort) != 1) {
debug(LEVEL_3, "parseHostAndPort(): sscanf error 1\n");
return false;
}
}
else {
// One colon -- interpret as a display number or port
// number
if (sscanf(colonPos + 1, "%d", &tmpPort) != 1) {
return false;
}
// RealVNC method - If port < 100 interpret as display
// number else as Port number
if (tmpPort < 100)
tmpPort += RFB_PORT_OFFSET;
}
}
*port = tmpPort;
debug(LEVEL_3, "parseHostAndPort() end: host = %s, port = %d\n", host, tmpPort);
return true;
}
//Connect-with-timeout function borrowed from unix sockets faq
//Maybe Java guys have some point when talking about exception handling ;-)
static int connectWithTimeout(int socket, const struct sockaddr *addr, socklen_t addrlen, int timeOutSecs)
{
int res;
long arg;
fd_set myset;
struct timeval tv;
int valopt;
socklen_t lon;
//First, set socket non-blocking
arg = fcntl(socket, F_GETFL, NULL);
if (arg < 0) {
debug(LEVEL_2, "connectWithTimeout(): error in fcntl(..., F_GETFL) (%s)\n", strerror(errno));
return -1;
}
arg |= O_NONBLOCK;
if (fcntl(socket, F_SETFL, arg) < 0) {
debug(LEVEL_2, "connectWithTimeout(): error in fcntl(..., F_SETFL) (%s)\n", strerror(errno));
return -1;
}
//Try to connect with timeout
res = connect(socket, addr, addrlen);
if (res < 0) {
if (errno == EINPROGRESS) {
debug(LEVEL_3, "connectWithTimeout(): EINPROGRESS in connect() - selecting\n");
do {
tv.tv_sec = timeOutSecs;
tv.tv_usec = 0;
FD_ZERO(&myset);
FD_SET(socket, &myset);
res = select(socket + 1, NULL, &myset, NULL, &tv);
if ((res < 0) && (errno != EINTR)) {
debug(LEVEL_3, "connectWithTimeout(): Error connecting %d (%s)\n", errno, strerror(errno));
return -1;
}
else if (res > 0) {
// Socket selected for write, check if connection was succesful
lon = sizeof(int);
if (getsockopt(socket, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon) < 0) {
debug(LEVEL_2, "connectWithTimeout(): Error in getsockopt() %d (%s)\n", errno, strerror(errno));
return -1;
}
// Check the value returned...
if (valopt) {
debug(LEVEL_2, "connectWithTimeout(): Error in delayed connection() %d (%s)\n",
valopt, strerror(valopt));
return -1;
}
else {
debug(LEVEL_3, "connectWithTimeout(): connected OK\n");
break;
}
}
else {
debug(LEVEL_3, "connectWithTimeout(): Timeout in select() - Cancelling!\n");
return -1;
}
} while (1);
}
else {
debug(LEVEL_3, "connectWithTimeout(): Error connecting %d (%s)\n", errno, strerror(errno));
return -1;
}
}
//Set to blocking mode again...
if ((arg = fcntl(socket, F_GETFL, NULL)) < 0) {
debug(LEVEL_2, "connectWithTimeout(): Error fcntl(..., F_GETFL) (%s)\n", strerror(errno));
return -1;
}
arg &= (~O_NONBLOCK);
if (fcntl(socket, F_SETFL, arg) < 0) {
debug(LEVEL_2, "connectWithTimeout(): Error fcntl(..., F_SETFL) (%s)\n", strerror(errno));
return -1;
}
return 0;
}
//check intended Mode 1 server address against list of denied addresses/ranges in repeater.ini
//return true if denied address, false otherwise
static bool isServerAddressDenied(addrParts srvAddr)
{
int ii;
for(ii = 0; ii < SERVERS_LIST_SIZE; ii++) {
if (((srvAddr.a == srvListDeny[ii].a) || (srvListDeny[ii].a == 0)) &&
((srvAddr.b == srvListDeny[ii].b) || (srvListDeny[ii].b == 0)) &&
((srvAddr.c == srvListDeny[ii].c) || (srvListDeny[ii].c == 0)) &&
((srvAddr.d == srvListDeny[ii].d) || (srvListDeny[ii].d == 0)) ) {
debug(LEVEL_3, "isServerAddressDenied(): address is in deny list, denying (%d.%d.%d.%d)\n",
srvAddr.a,srvAddr.b,srvAddr.c,srvAddr.d);
return true;
}
}
return false;
}
//check intended Mode 1 server address against list of allowed addresses/ranges in repeater.ini
//return true if allowed address, false otherwise
static bool isServerAddressAllowed(char *serverIp)
{
int ii;
addrParts srvAddr;
bool allow;
srvAddr = getAddrPartsFromString(serverIp);
for(ii = 0; ii < SERVERS_LIST_SIZE; ii++) {
allow = true;
//List 255 == denied
if ((srvListAllow[ii].a == 255) || (srvListAllow[ii].b == 255) ||
(srvListAllow[ii].c == 255) || (srvListAllow[ii].d == 255))
allow = false;
//server 255 == denied