/
balance.c
2471 lines (2168 loc) · 69.5 KB
/
balance.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
/*
* balance.fm - a balancing tcp proxy
*
* Copyright (c) 2012-2009,2010 by Marcus Holland-Moritz (marcus@last.fm)
* and Last.fm Ltd. (http://last.fm), London, UK.
*
* Copyright (c) 2000-2009,2010 by Thomas Obermair (obermair@acm.org)
* and Inlab Software GmbH (info@inlab.de), Gruenwald, Germany.
* All rights reserved.
*
* Thanks to Bernhard Niederhammer for the initial idea and heavy
* testing on *big* machines ...
*
* For license terms, see the file COPYING in this directory.
*
* This program is dedicated to Richard Stevens...
*
* 1.0.0
* Forked balance.fm from balance 3.54; see debian/changelog for details
* or get the lastest git repository from:
*
* https://github.com/mhx/balance.fm
*
* 3.54
* fixed hash_fold bug regarding incoming IPv4 and IPv6 source addresses
* 3.52
* thanks to David J. Jilk from Standing Cloud, Inc. for the following:
* added "nobuffer" functionality to interactive shell IO
* added new "assign" interactive command
* fixed locking bug
* 3.50
* new option -6 forces IPv6 bind (hints.ai_family = AF_INET6)
* 3.49
* ftok() patch applied (thanks to Vladan Djeric)
* 3.48
* Problems with setting IPV6_V6ONLY socket option are now handled
* more nicely with a syslog warning message
* 3.42
* Balance compiles now on systems where IPV6_V6ONLY is undefined
* 3.35
* bugfix in autodisable code (thanks to Michael Durket)
* 3.34
* syslog logging added (finally)
* -a autodisable option added (thanks to Mitsuru IWASAKI)
* 3.33
* SO_KEEPALIVE switched on (suggested and implemented by A. Fluegel)
* new option -M to use a memory mapped file instead of IPC shared memory
* 3.32
* /var/run/balance may already exist (thanks to Thomas Steudten)
* 3.31
* TCP_NODELAY properly switched on (thanks to Kurt J. Lidl).
* 3.30
* Code cleanups and fixes (thanks to Kurt J. Lidl)
* 3.28
* Code cleanup's (thanks to Thomas Steudten)
* MRTG-Interface (thanks to Brian McCann for the suggestion)
* 3.26
* bugfix: master process was not found with balance -i
* unused variable pid removed (BSD)
* 3.24
* bugfix in channel/group argument parsing (thanks to Enrique G. Paredes)
* permisions+error messages improvements (thanks to Wojciech Sobczuk)
* 3.22
* writelock and channelcount patch from Stoyan Genov
* balance exit codes fix from Chris Wilson
* /var/run/balance is tried to be autocreated (if not there)
* close of 0,1,2 on background operation
* 3.19
* -h changed to -H
* 3.17
* -h option added
* thanks to Werner Maier
* 3.16
* fixed missing save_tmout initialization
* thanks to Eric Andresen
* 3.15
* first -B support
* 3.14
* -Wall cleanup
* 3.12
* alarm(0) added, thanks to Jon Christensen
* 3.11
* Bugfix
* 3.10
* Bugfix for RedHat 7.2
* 3.9
* Moved rendezvous file to /var/run and cleaned main(), thanks to
* Kayne Naughton
* 3.8
* move to sigaction(), thanks to Kayne Naughton
* 3.5
* Select-Timeout, thanks to Jeff Buhlmann
* 3.2
* Hash groups and some other improvements
* 2.24:
* 'channel 2 overload' problem fixed, thanks to Ed "KuroiNeko"
* 2.26:
* 'endless loop error' fixed, thanks to Anthony Baxter
* 2.27:
* strcmp on NULL removed, thanks to Jay. D. Allen
* 2.28:
* bsent and breceived now unsigned to avoid negative values,
* thanks to Anthony Baxter
* 2.29:
* error in setaddress() fixed, thanks to Dirk Datzert
* 2.30:
* fixing #includes for *bsd compability
* 2.31:
* 2.32:
* redefied SIGCHLD handling to be compatible with FreeBSD 4.3,
* BSD/OS 4.2 and BSD/OS 4.0.1
* 2.33
* finally included SO_REUSEADDR
*
*/
#include "balance.h"
// TODO: those need to be set automatically from the debian/changelog
static int release = 1;
static int subrelease = 0;
static int patchlevel = 0;
static char rendezvousfile[FILENAMELEN];
static int rendezvousfd;
#ifndef NO_MMAP
static int shmfilefd;
#endif
COMMON *common;
static int hashfailover = 0;
static int autodisable = 0;
static int debugflag = 0;
static int foreground = 0;
static int packetdump = 0;
static int interactive = 0;
static int shmmapfile = 0;
static int bindipv6 = 0;
static int no_std_handles = 0;
static int sockbufsize = 32768;
static int connect_timeout;
static volatile sig_atomic_t interrupted = 0;
static char *bindhost = NULL;
static char *outbindhost = NULL;
static struct timeval sel_tmout = { 0, 0 }; /* seconds, microseconds */
static struct timeval save_tmout = { 0, 0 }; /* seconds, microseconds */
static KEEPALIVE keepalive_server = { 0, 0, 0 };
static KEEPALIVE keepalive_client = { 0, 0, 0 };
static void log_msg(int priority, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if (no_std_handles) {
vsyslog(priority, fmt, ap);
} else {
fprintf(stderr, "balance.fm: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
fflush(stderr);
}
va_end(ap);
}
static void log_perror(int priority, const char *str)
{
const char *err = strerror(errno);
if (no_std_handles) {
syslog(priority, "%s: %s", str, err);
} else {
fprintf(stderr, "balance.fm: %s: %s\n", str, err);
fflush(stderr);
}
}
static void debug(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if (debugflag && !no_std_handles) {
vfprintf(stderr, fmt, ap);
fflush(stderr);
}
va_end(ap);
}
int err_dump(const char *text)
{
log_msg(LOG_ERR, "%s", text);
exit(EX_UNAVAILABLE);
}
static int create_serversocket(const char *node, const char *service)
{
struct addrinfo hints;
struct addrinfo *results;
int srv_socket, status, sockopton, sockoptoff;
bzero(&hints, sizeof(hints));
hints.ai_flags = AI_PASSIVE;
if(bindipv6) {
debug("using AF_INET6\n");
hints.ai_family = AF_INET6;
} else {
debug("using AF_UNSPEC\n");
hints.ai_family = AF_UNSPEC;
}
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
status = getaddrinfo(node, service, &hints, &results);
if(status != 0) {
log_msg(LOG_ERR, "error at getaddrinfo: %s", gai_strerror(status));
log_msg(LOG_ERR, "exiting.");
exit(EX_OSERR);
}
if(results == NULL) {
log_msg(LOG_ERR, "no matching results at getaddrinfo");
log_msg(LOG_ERR, "exiting");
exit(EX_OSERR);
}
srv_socket = socket(results->ai_family, results->ai_socktype, results->ai_protocol);
if(srv_socket < 0) {
log_perror(LOG_ERR, "socket");
exit(EX_OSERR);
}
sockoptoff = 0;
#if defined(IPV6_V6ONLY)
status = setsockopt(srv_socket, IPPROTO_IPV6, IPV6_V6ONLY, (char*) &sockoptoff, sizeof(sockoptoff));
if(status < 0) {
syslog(LOG_WARNING,"setsockopt(IPV6_V6ONLY=0) failed");
}
#endif
sockopton = 1;
status = setsockopt(srv_socket, SOL_SOCKET, SO_REUSEADDR, (char*) &sockopton, sizeof(sockopton));
if(status < 0) {
log_perror(LOG_ERR, "setsockopt(SO_REUSEADDR=1)");
exit(EX_OSERR);
}
status = bind(srv_socket, results->ai_addr, results->ai_addrlen);
if(status < 0) {
log_perror(LOG_ERR, "bind");
exit(EX_OSERR);
}
status = listen(srv_socket, SOMAXCONN);
if(status < 0) {
log_perror(LOG_ERR, "listen");
exit(EX_OSERR);
}
return(srv_socket);
}
/* locking ... */
static int a_readlock(off_t start __attribute__((unused)), off_t len __attribute__((unused)))
{
int rc;
struct flock fdata;
fdata.l_type = F_RDLCK;
fdata.l_whence = SEEK_SET;
fdata.l_start = 0;
fdata.l_len = 0;
// fdata.l_sysid=0;
// fdata.l_pid=0;
repeat:
if ((rc = fcntl(rendezvousfd, F_SETLKW, &fdata)) < 0) {
if (errno == EINTR) {
goto repeat; // 8-)
} else {
log_perror(LOG_ERR, "readlock");
exit(EX_OSERR);
}
}
return (rc);
}
static void b_readlock(void)
{
a_readlock(0, 0);
}
static void c_readlock(int group, int channel)
{
a_readlock(((char *) &(grp_channel(common, group, channel))) -
(char *) common, sizeof(CHANNEL));
}
static int a_writelock(off_t start __attribute__((unused)), off_t len __attribute__((unused)))
{
int rc;
struct flock fdata;
fdata.l_type = F_WRLCK;
fdata.l_whence = SEEK_SET;
fdata.l_start = 0;
fdata.l_len = 0;
// fdata.l_sysid=0;
// fdata.l_pid=0;
repeat:
if ((rc = fcntl(rendezvousfd, F_SETLKW, &fdata)) < 0) {
if (errno == EINTR) {
goto repeat; // 8-)
} else {
log_perror(LOG_ERR, "a_writelock");
exit(EX_OSERR);
}
}
return (rc);
}
static void b_writelock(void)
{
a_writelock(0, 0);
}
static void c_writelock(int group, int channel)
{
a_writelock(((char *) &(grp_channel(common, group, channel))) -
(char *) common, sizeof(CHANNEL));
}
static int a_unlock(off_t start __attribute__((unused)), off_t len __attribute__((unused)))
{
int rc;
struct flock fdata;
fdata.l_type = F_UNLCK;
fdata.l_whence = SEEK_SET;
fdata.l_start = 0;
fdata.l_len = 0;
// fdata.l_sysid=0;
// fdata.l_pid=0;
repeat:
if ((rc = fcntl(rendezvousfd, F_SETLK, &fdata)) < 0) {
if (errno == EINTR) {
goto repeat; // 8-)
} else {
log_perror(LOG_ERR, "a_unlock");
exit(EX_OSERR);
}
}
return (rc);
}
static void b_unlock(void)
{
a_unlock(0, 0);
}
static void c_unlock(int group, int channel)
{
a_unlock(((char *) &(grp_channel(common, group, channel))) -
(char *) common, sizeof(CHANNEL));
}
static void *shm_malloc(const char *file, size_t size, bool create, int *p_shmid)
{
char *data = NULL;
key_t key;
int shmid = 0;
if(shmmapfile){
#ifndef NO_MMAP
char shmfile[FILENAMELEN];
strcpy(shmfile, file);
strcat(shmfile, SHMFILESUFFIX);
shmfilefd = open(shmfile, O_RDWR | O_CREAT, 0644);
if(shmfilefd < 0) {
log_msg(LOG_WARNING, "Warning: Cannot open file `%s', switching to IPC", shmfile);
shmmapfile = 0;
}
if(shmmapfile) {
if(ftruncate(shmfilefd, size) < 0) {
log_msg(LOG_WARNING, "Warning: Cannot set file size on `%s', switching to IPC", shmfile);
close(shmfilefd);
shmmapfile = 0;
}
}
if(shmmapfile) {
data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, shmfilefd, 0);
if(!data || data == MAP_FAILED) {
log_msg(LOG_WARNING, "Warning: Cannot map file `%s', switching to IPC", shmfile);
close(shmfilefd);
shmmapfile = 0;
}
}
#endif
}
if(!shmmapfile){
#if defined (__SVR4) && defined (__sun)
/* vdjeric:
Solaris ftok() causes frequent collisions because it uses
only the lower 12 bits of the inode number in the 'key'.
See: http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=4265917
*/
FILE *rendezvousfp = NULL;
struct timeval ct;
long int seed;
int i;
if ((rendezvousfp = fdopen(rendezvousfd, "w+")) == NULL) {
log_perror(LOG_ERR, "fdopen");
exit(EX_OSERR);
}
if ((fscanf(rendezvousfp, "0x%x\n", &key)) <= 0) {
gettimeofday(&ct, NULL);
seed = ct.tv_usec * getpid();
srand(seed);
/* Solaris rand() returns values between 0 and 0x7fff,
so generate key byte by byte */
key = 0;
for (i = 0; i < sizeof(key); i++) {
key = (key << 8) | (rand() & 0xff);
}
if(fseek(rendezvousfp, 0, SEEK_SET) == -1) {
log_perror(LOG_ERR, "fseek");
exit(EX_OSERR);
}
if (fprintf(rendezvousfp, "0x%08x\n", key) == -1) {
log_perror(LOG_ERR, "fprintf");
exit(EX_OSERR);
}
fflush(rendezvousfp);
}
#else
if ((key = ftok(file, 'x')) == -1) {
log_perror(LOG_ERR, "ftok");
exit(EX_OSERR);
}
#endif
if ((shmid = shmget(key, 0, 0644)) == -1) {
if (errno == ENOENT) {
if (!create) {
return NULL;
}
} else {
log_perror(LOG_ERR, "shmget");
exit(EX_OSERR);
}
} else {
debug("shared memory segment already exists\n");
struct shmid_ds shminfo;
if (shmctl(shmid, IPC_STAT, &shminfo) < 0) {
log_perror(LOG_ERR, "shmctl");
exit(EX_OSERR);
}
if (shminfo.shm_segsz != size) {
debug("shared memory segment is incompatible\n");
if (shminfo.shm_nattch == 0) {
debug("attempting to remove incompatible shared memory segment\n");
/* attempt to remove segment if no one is attached (yes, there's a race condition here... oh well) */
if (shmctl(shmid, IPC_RMID, NULL) < 0) {
log_perror(LOG_ERR, "shmctl");
exit(EX_OSERR);
}
} else {
log_msg(LOG_ERR, "cannot attach to incompatible memory segment and unable to remove it (key=0x%08x, size=%u)",
(unsigned) key, (unsigned) shminfo.shm_segsz);
exit(EX_SOFTWARE);
}
}
}
int flags = 0644;
if (create) {
flags |= IPC_CREAT;
}
if ((shmid = shmget(key, size, flags)) == -1) {
if (errno == ENOENT && !create) {
return NULL;
}
log_perror(LOG_ERR, "shmget");
exit(EX_OSERR);
}
data = shmat(shmid, (void *) 0, 0);
if (data == (char *) (-1)) {
log_perror(LOG_ERR, "shmat");
exit(EX_OSERR);
}
}
if (p_shmid) {
*p_shmid = shmid;
}
return data;
}
void shm_destroy(int shmid)
{
/* ensure that the last attached process cleans up after itself */
if (shmctl(shmid, IPC_RMID, NULL) < 0) {
log_perror(LOG_ERR, "shmctl");
exit(EX_OSERR);
}
}
/* readable output of a packet (-p) */
static void print_packet(const unsigned char *s, int l)
{
int i, cc;
cc = 0;
for (i = 0; i < l; i++) {
if (isprint(s[i]) && isascii(s[i])) {
if (s[i] == '\\') {
printf("\\\\");
cc += 2;
} else {
printf("%c", s[i]);
cc++;
}
} else {
printf("\\%02X", s[i]);
cc += 3;
if (s[i] == '\n') {
printf("\n");
cc = 0;
}
}
if (cc > 80) {
printf("\n");
cc = 0;
}
}
printf("\n");
}
static bool safe_atoi(int *result, const char *str)
{
char *end;
int i = strtol(str, &end, 0);
if (end > str && *end == '\0') {
*result = i;
return true;
}
return false;
}
static bool getport(int *result, const char *port)
{
struct servent *sp;
sp = getservbyname(port, "tcp");
if (sp == NULL) {
int i;
if (safe_atoi(&i, port) && i > 0) {
*result = i;
return true;
}
log_msg(LOG_ERR, "invalid port number [%s]", port);
return false;
}
*result = ntohs(sp->s_port);
return true;
}
static void setipaddress(struct in_addr *ipaddr, const char *string)
{
struct hostent *hent;
hent = gethostbyname(string);
if (hent == NULL) {
if ((ipaddr->s_addr = inet_addr(string)) == INADDR_NONE) {
log_msg(LOG_ERR, "unknown or invalid address [%s]", string);
exit(EX_DATAERR);
}
} else {
memcpy(ipaddr, hent->h_addr, hent->h_length);
}
}
static bool setaddress(struct in_addr *ipaddr, int *port, const char *string,
int default_port, int *maxc, bool exit_on_error)
{
char *dup_string = strdup(string);
if (dup_string == NULL) {
log_perror(LOG_ERR, "strdup");
if (exit_on_error) {
exit(EX_OSERR);
}
return false;
}
const char *host_string = dup_string;
const char *port_string = NULL;
const char *maxc_string = NULL;
char *p = index(dup_string, ':');
if (p != NULL) {
*p = '\0';
port_string = p + 1;
p = index(port_string, ':');
if (p != NULL) {
*p = '\0';
maxc_string = p + 1;
}
}
struct hostent *hent = gethostbyname(host_string);
int exitcode = 0;
in_addr_t in_addr = INADDR_NONE;
int portnum = default_port;
int maxcnum = 0;
if (hent == NULL) {
in_addr = inet_addr(host_string);
if (in_addr == INADDR_NONE) {
log_msg(LOG_ERR, "unknown or invalid address [%s]", dup_string);
exitcode = EX_DATAERR;
}
}
if (exitcode == 0 && port_string != NULL) {
if (!getport(&portnum, port_string)) {
exitcode = EX_DATAERR;
}
}
if (exitcode == 0 && maxc_string != NULL) {
if (!safe_atoi(&maxcnum, maxc_string)) {
log_msg(LOG_ERR, "invalid max connections [%s]", maxc_string);
exitcode = EX_DATAERR;
}
}
free(dup_string);
if (exitcode == 0) {
if (hent != NULL) {
memcpy(ipaddr, hent->h_addr, hent->h_length);
} else {
ipaddr->s_addr = in_addr;
}
*port = portnum;
if (maxc) {
*maxc = maxcnum;
}
return true;
}
if (exit_on_error) {
exit(exitcode);
}
return false;
}
static int forward(int fromfd, int tofd, int groupindex, int channelindex)
{
ssize_t rc;
unsigned char buffer[MAXTXSIZE];
rc = read(fromfd, buffer, MAXTXSIZE);
if (packetdump) {
printf("-> %d\n", (int) rc);
print_packet(buffer, rc);
}
if (rc <= 0) {
return (-1);
} else {
if (writen(tofd, buffer, rc) != rc) {
return (-1);
}
c_writelock(groupindex, channelindex);
chn_bsent(common, groupindex, channelindex) += rc;
c_unlock(groupindex, channelindex);
}
return (0);
}
static int backward(int fromfd, int tofd, int groupindex, int channelindex)
{
ssize_t rc;
unsigned char buffer[MAXTXSIZE];
rc = read(fromfd, buffer, MAXTXSIZE);
if (packetdump) {
printf("-< %d\n", (int) rc);
print_packet(buffer, rc);
}
if (rc <= 0) {
return (-1);
} else {
if (writen(tofd, buffer, rc) != rc) {
return (-1);
}
c_writelock(groupindex, channelindex);
chn_breceived(common, groupindex, channelindex) += rc;
c_unlock(groupindex, channelindex);
}
return (0);
}
static void set_socket_options(int s, const KEEPALIVE *ka)
{
int optval = 1;
/* failure is acceptable */
(void) setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(optval));
(void) setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval));
#if BALANCE_CAN_KEEPALIVE
if (ka->time > 0)
{
optval = ka->time;
if (setsockopt(s, SOL_TCP, TCP_KEEPIDLE, &optval, sizeof(optval)) < 0) {
log_perror(LOG_ERR, "setsockopt(TCP_KEEPIDLE)");
exit(EX_OSERR);
}
optval = ka->intvl;
if (setsockopt(s, SOL_TCP, TCP_KEEPINTVL, &optval, sizeof(optval)) < 0) {
log_perror(LOG_ERR, "setsockopt(TCP_KEEPINTVL)");
exit(EX_OSERR);
}
optval = ka->probes;
if (setsockopt(s, SOL_TCP, TCP_KEEPCNT, &optval, sizeof(optval)) < 0) {
log_perror(LOG_ERR, "setsockopt(TCP_KEEPCNT)");
exit(EX_OSERR);
}
}
#endif
}
/*
* the connection is really established, let's transfer the data
* as efficient as possible :-)
*/
static void stream2(int clientfd, int serverfd, int groupindex, int channelindex)
{
fd_set readfds;
int fdset_width;
int sr;
fdset_width = ((clientfd > serverfd) ? clientfd : serverfd) + 1;
set_socket_options(clientfd, &keepalive_client);
set_socket_options(serverfd, &keepalive_server);
for (;;) {
FD_ZERO(&readfds);
FD_SET(clientfd, &readfds);
FD_SET(serverfd, &readfds);
/*
* just in case this system modifies the timeout values,
* refresh the values from a saved copy of them.
*/
sel_tmout = save_tmout;
for (;;) {
if (sel_tmout.tv_sec || sel_tmout.tv_usec) {
sr = select(fdset_width, &readfds, NULL, NULL, &sel_tmout);
} else {
sr = select(fdset_width, &readfds, NULL, NULL, NULL);
}
if ((save_tmout.tv_sec || save_tmout.tv_usec) && !sr) {
c_writelock(groupindex, channelindex);
chn_c(common, groupindex, channelindex) -= 1;
c_unlock(groupindex, channelindex);
log_msg(LOG_ERR, "timed out after %d seconds", (int) save_tmout.tv_sec);
exit(EX_UNAVAILABLE);
}
if (sr < 0 && errno != EINTR) {
log_perror(LOG_ERR, "select");
c_writelock(groupindex, channelindex);
chn_c(common, groupindex, channelindex) -= 1;
c_unlock(groupindex, channelindex);
exit(EX_UNAVAILABLE);
}
if (sr > 0)
break;
}
if (FD_ISSET(clientfd, &readfds)) {
if (forward(clientfd, serverfd, groupindex, channelindex) < 0) {
break;
}
} else {
if (backward(serverfd, clientfd, groupindex, channelindex) < 0) {
break;
}
}
}
c_writelock(groupindex, channelindex);
chn_c(common, groupindex, channelindex) -= 1;
c_unlock(groupindex, channelindex);
exit(EX_OK);
}
static void alrm_handler(int signo __attribute__((unused)))
{
}
static void quit_handler(int signo __attribute__((unused)))
{
interrupted = 1;
}
static void chld_handler(int signo __attribute__((unused)))
{
int status;
int pid;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
b_writelock();
if (pid == common->monitor_pid) {
common->monitor_pid = -1;
}
b_unlock();
}
}
/*
* a channel in a group is selected and we try to establish a connection
*/
static void *stream(int arg, int groupindex, int index, const void *client_address,
int client_address_size)
{
int startindex;
int sockfd;
int clientfd;
struct sigaction alrm_action;
struct sockaddr_in serv_addr;
startindex = index; // lets keep where we start...
clientfd = arg;
for (;;) {
debug("trying group %d channel %d ... ", groupindex, index);
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
log_perror(LOG_ERR, "socket");
exit(EX_OSERR);
}
(void) setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sockbufsize,
sizeof(sockbufsize));
(void) setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &sockbufsize,
sizeof(sockbufsize));
/*
* if -B is specified, balance tries to bind to it even on
* outgoing connections
*/
if (outbindhost != NULL) {
struct sockaddr_in outbind_addr;
bzero(&outbind_addr, sizeof(outbind_addr));
outbind_addr.sin_family = AF_INET;
setipaddress(&outbind_addr.sin_addr, outbindhost);
if (bind
(sockfd, (struct sockaddr *) &outbind_addr,
sizeof(outbind_addr)) < 0) {
}
}
b_readlock();
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr =
chn_ipaddr(common, groupindex, index).s_addr;
serv_addr.sin_port = htons(chn_port(common, groupindex, index));
b_unlock();
alrm_action.sa_handler = alrm_handler;
alrm_action.sa_flags = 0; // don't restart !
sigemptyset(&alrm_action.sa_mask);
sigaction(SIGALRM, &alrm_action, NULL);
alarm(connect_timeout);
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
if (errno == EINTR) {
debug("timeout group %d channel %d\n", groupindex, index);
} else {
debug("connection refused group %d channel %d\n", groupindex, index);
}
/* here we've received an error (either 'timeout' or 'connection refused')
* let's start some magical failover mechanisms
*/
c_writelock(groupindex, index);
chn_c(common, groupindex, index)--;
if(autodisable) {
if(chn_status(common, groupindex, index) == CS_ENABLED) {
log_msg(LOG_NOTICE, "connection failed group %d channel %d", groupindex, index);
log_msg(LOG_NOTICE, "%s:%d needs to be enabled manually using balance.fm -i after the problem is solved", inet_ntoa(serv_addr.sin_addr), ntohs(serv_addr.sin_port));
chn_status(common, groupindex, index) = CS_DISABLED_SOFT;
}
}
c_unlock(groupindex, index);
b_readlock();
for (;;) {
for (;;) {
if (grp_type(common, groupindex) == GROUP_RR || hashfailover == 1) {
index++;
if (index >= grp_nchannels(common, groupindex)) {
index = 0;
}
if (index == startindex) {
index = -1; // Giveup
break;
}
if (chn_status(common, groupindex, index) == CS_ENABLED &&
(chn_maxc(common, groupindex, index) == 0 ||
(chn_c(common, groupindex, index) <
chn_maxc(common, groupindex, index)))) {
break; // new index found
} else {
continue;
}
} else if (grp_type(common, groupindex) == GROUP_HASH) {
// If the current group is type hash, we giveup immediately
index = -1;
break;
} else {
err_dump("PANIC: invalid group in stream()");
}
}
if (index >= 0) {
// neuer index in groupindex-group found...
break;
} else {
again:
groupindex++;
if (groupindex >= MAXGROUPS) {
// giveup, index=-1.
break;
} else {
if (grp_type(common, groupindex) == GROUP_RR) {
if (grp_nchannels(common, groupindex) > 0) {
index = grp_current(common, groupindex);
startindex = index; // This fixes the "endless loop error"
// with all hosts being down and one
// in the last group... (from Anthony Baxter)
} else {
goto again;
}
break;
} else if (grp_type(common, groupindex) == GROUP_HASH) {
unsigned int uindex;
uindex = hash_fold(&(((struct sockaddr_in6 *) &client_address)->sin6_addr), client_address_size);
debug("HASH-method: fold returns %u\n", uindex);
index = uindex % grp_nchannels(common, groupindex);
debug("modulo %d gives %d\n", grp_nchannels(common, groupindex), index);
if (chn_status(common, groupindex, index) == CS_ENABLED &&
(chn_maxc(common, groupindex, index) == 0 ||
(chn_c(common, groupindex, index) <
chn_maxc(common, groupindex, index)))
) {
break;
} else {
goto again; // next group !