File: mod_backhand.c

package info (click to toggle)
libapache-mod-backhand 1.2.1-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,048 kB
  • ctags: 513
  • sloc: ansic: 3,650; cpp: 661; sh: 467; makefile: 120
file content (1569 lines) | stat: -rw-r--r-- 51,176 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
/* ======================================================================
 * Copyright (c) 1998-1999 The Johns Hopkins University.
 * All rights reserved.
 * The following code was written by Theo Schlossnagle for use in the
 * Backhand project at The Center for Networking and Distributed Systems
 * at The Johns Hopkins University.
 * Please refer to the LICENSE file before using this software.
 * ======================================================================
*/

#include "config.h"

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#ifdef HAVE_DLFCN_H
#include <dlfcn.h>
#endif

#include "httpd.h"
#include "http_config.h"
#include "http_conf_globals.h"
#include "http_log.h"
#include "http_main.h"
#include "http_request.h"
#include "http_protocol.h"

#define IN_MODULE
#include "mod_backhand.h"
#include "back_util.h"
#include "apue.h"
#include "builtins.h"

#include "stolenstatics.c"

static table *static_calls_made = NULL;
static int umbilical=-1;

static char UD_DN[MAXPATHLEN]; /* for process to process file descriptors */
static char *moderator_pid_filename = NULL;
static StatsSI *sins;
static int nsins=0;
static pool *backhand_pool = NULL;
static ACL *UDPacl = NULL;
int serverstats_shmid = -1;
int serverstats_shmkey = IPC_PRIVATE;
serverstat *serverstats = NULL;
int mod_backhand_personal_arriba=-1;

/* BECUASE we handle requests in a serial fashion, we can set this in
   the first phase and use it later without worry of it being munged.
   This allows us to call makedecision only once and not have to store
   the results in the r->notes which is time consuming. */

static ServerSlot remote_machine = {MB_HTTP_PROXY, MB_HOSTTYPE_IP, -1};
static ServerSlot invalid_machine = {MB_HTTP_PROXY, MB_HOSTTYPE_IP, -1};

static void initialize_statistics(serverstat *stats);
static void backhand_child_cleanup_shm(void *data);
static void backhand_cleanup_shm(void *data);
static void establish_umbilical(server_rec *s);
static void close_umbilical();

/* Our module declaration (So people can find us) */
module backhand_module;

static void setup_module_cells(server_rec *s) {
  if (backhand_pool == NULL) {
    struct shmid_ds shmbuf;
    
    backhand_pool = ap_make_sub_pool(NULL);
    /* Now let us allocate some shared memory for server statistics */
    /* We put it in the pool under the guise of cleanliness */
    if ((serverstats_shmid = shmget(serverstats_shmkey, SERVERSTATS_SIZE,
				    IPC_CREAT | SHM_R | SHM_W)) == -1) {
#ifdef LINUX
      if (errno == ENOSYS) {
	ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, s,
		     "httpd: Your kernel was built without CONFIG_SYSVIPC\n"
		     "httpd: please consult the Apache FAQ for details");
      }
#endif
      ap_log_error(APLOG_MARK, APLOG_EMERG, s,
		   "could not call shmget");
      exit(APEXIT_INIT);
    }
    ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, s,
		 "created shared memory segment #%d", serverstats_shmid);
    if ((serverstats =
	 (serverstat *)shmat(serverstats_shmid,
			     0, 0)) == (serverstat *)-1 ) {
      ap_log_error(APLOG_MARK, APLOG_EMERG, s, "shmat error");
    } else { /* only worry about permissions if we attached the segment */

      /* Block the alarms for a register like alloc.h says to */
      ap_block_alarms();
      ap_register_cleanup(backhand_pool, NULL,
			  backhand_cleanup_shm, backhand_child_cleanup_shm);
      ap_unblock_alarms();

      if (shmctl(serverstats_shmid, IPC_STAT, &shmbuf) != 0) {
	ap_log_error(APLOG_MARK, APLOG_ERR, s,
		     "shmctl() could not stat segment #%d",
		     serverstats_shmid);
      } else {
	shmbuf.shm_perm.uid = ap_user_id;
	shmbuf.shm_perm.gid = ap_group_id;
	shmbuf.shm_perm.mode = 0600;
	if (shmctl(serverstats_shmid, IPC_SET, &shmbuf) != 0) {
	  ap_log_error(APLOG_MARK, APLOG_ERR, s,
		       "shmctl(., IPC_SET, [%d,%d]) could not set segment #%d",
		       shmbuf.shm_perm.uid, shmbuf.shm_perm.gid,
		       serverstats_shmid);
	}
      }
    }
    /* Now remove it??? Yeah remove it.. just marks it for removal
       IPC_RMID    is  used  to mark the segment as destroyed. It
                   will actually  be  destroyed  after  the  last
                   detach.   (I.e., when the shm_nattch member of
                   the associated structure  shmid_ds  is  zero.)
                   The  user  must  be the owner, creator, or the
                   super-user.
    */
    if (shmctl(serverstats_shmid, IPC_RMID, NULL) != 0) {
      ap_log_error(APLOG_MARK, APLOG_WARNING, s,
		   "shmctl: IPC_RMID: can't remove shared memory segment #%d",
		   serverstats_shmid);
    }
    initialize_statistics(serverstats);
  }
  /*
   * Likewise for the table of routine/environment pairs we visit outside of
   * request context.
   */
  if (static_calls_made == NULL) {
    static_calls_made = ap_make_table(backhand_pool, 16);
  };
}

static const char *setup_pid_file(cmd_parms *cmd, void *mconfig,
				  char *word) {
  mbcfg *cfg = (mbcfg *) mconfig;
  
  cfg->local = 1;
 
  if(moderator_pid_filename) free(moderator_pid_filename);
  moderator_pid_filename = strdup(word);
  return NULL;
}

static const char *setup_sock_un(cmd_parms *cmd, void *mconfig,
				 char *word) {
  mbcfg *cfg = (mbcfg *) mconfig;
  
  cfg->local = 1;
  
  strncpy(UD_DN, word, MAXPATHLEN);
  UD_DN[MAXPATHLEN-1] = '\0';
  return NULL;
}

static const char *setupbroadcasting(cmd_parms *cmd, void *mconfig,
				     char *word1, char *word2) {
  int a, b, c, d, port=0, ttl, i, adup=0;
  mbcfg *cfg = (mbcfg *) mconfig;
  struct sockaddr_in sin;
  struct in_addr from;
  unsigned int webport=0;
  char buffer[1000]; /* People just don't name systems long than that */
  
  cfg->local = 1;
  
  memset(&sin, 0, sizeof(struct sockaddr_in));
  memset(&from, 0, sizeof(struct sockaddr_in));
  if(!word2) { /* Not two args, just one -- shuffle and set first to hst ip */
    struct hostent *he;
    word2=word1;
    if(gethostname(buffer, sizeof buffer)!=0 ||
       (he = gethostbyname(buffer))==NULL) {
      ap_log_error(APLOG_MARK, APLOG_ERR, cmd->server,
		   "gethostname failed.");
      exit(-1);
    }
    memcpy(&from, he->h_addr_list[0], sizeof(struct in_addr));    
  } else if(word1) {
    if(strchr(word1, ':')) {
      sscanf(word1, "%d.%d.%d.%d:%u", &a, &b, &c, &d, &webport);
      if(webport)
	from.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
      webport=htons(webport);
    } else {
      sscanf(word1, "%d.%d.%d.%d", &a, &b, &c, &d);
      if(d)
	from.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
    }
  }
  if(strchr(word2, ',')) {
    /* Multicast! */
    if(word2) sscanf(word2, "%d.%d.%d.%d:%d,%d", &a, &b, &c, &d, &port, &ttl);
    if(ttl!=0) {
      /* We set the family to ttl and fix it later before we use it */
      sin.sin_family = ttl;
      sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
      sin.sin_port = htons(port);
    }
  } else {
    if(word2) sscanf(word2, "%d.%d.%d.%d:%d", &a, &b, &c, &d, &port);
    if(port!=0) {
      sin.sin_family = AF_INET;
      sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
      sin.sin_port = htons(port);
    }
  }
  if(sin.sin_port) {
    for(i=0;i<nsins;i++)
      if(memcmp(&sin, &sins[i].sin, sizeof(struct sockaddr_in))==0 &&
	 memcmp(&from, &sins[i].from, sizeof(struct in_addr))==0) {
	adup=1;
	break;
      }
    if(!adup) { /* We didn't find a duplicate... add it */
      if(nsins)
	sins =
	  (StatsSI *)realloc(sins,
			     (nsins+1)*sizeof(StatsSI));
      else
	sins =
	  (StatsSI *)malloc((nsins+1)*sizeof(StatsSI));
      memcpy(&sins[nsins].from, &from, sizeof(struct in_addr));
      sins[nsins].webport = webport;
      memcpy(&sins[nsins].sin, &sin, sizeof(struct sockaddr_in));
      nsins++;
    }
  }
  return NULL;
}

static const char *setupUDPacl(cmd_parms *cmd, void *mconfig,
			       char *word) {
  int a, b, c, d, mask=-1;
  mbcfg *cfg = (mbcfg *) mconfig;
  ACL *acl;
  if(mconfig)
    cfg->local = 1;

  if(UDPacl==NULL) {
    char hostname[MAXHOSTNAMELEN];
    struct hostent h_ent;
    gethostname(hostname, MAXHOSTNAMELEN);

    UDPacl = (ACL *)malloc(sizeof(ACL));
    
    memcpy(&h_ent, gethostbyname(hostname), sizeof(h_ent));
    memcpy(&UDPacl->ip.s_addr, h_ent.h_addr, sizeof(struct in_addr));
    UDPacl->mask.s_addr = htonl(1);
    UDPacl->next = NULL;
  }

  acl = UDPacl;
  while(acl->next != NULL) acl=acl->next;
  if(word) {
    if(strchr(word, '/'))
      sscanf(word, "%d.%d.%d.%d/%d", &a, &b, &c, &d, &mask);
    else {
      sscanf(word, "%d.%d.%d.%d", &a, &b, &c, &d);
      mask = 1;
    }
  }
  if(mask>=0 && mask<=32) {
    acl->next = (ACL *)malloc(sizeof(ACL));
    acl=acl->next;
    acl->next=NULL;
    acl->ip.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
    acl->mask.s_addr = htonl(0xffffffff << (32-mask));
  }
  return NULL;
}

#if 0
static mbcfg *our_rconfig(request_rec *r)
{  
  return (mbcfg *) ap_get_module_config(r->request_config, &backhand_module);
}
#endif

static void initialize_statistics(serverstat *stats) {
  /* Nuttin */
}
static void backhand_child_cleanup_shm(void *data) {
  /* Nuttin */
}
static void backhand_cleanup_shm(void *data) {
  /* We need to detach AND delete the shared memory segment we allocated */
  /* data is just some dummy ata in the pool, but we will be nice and
     point data to the correct shmaddr */
  
  if((serverstats!=(serverstat *)NULL) && (serverstats_shmid>0)) {
    /* Let's detach the shmaddr that datapoints to */
    shmdt(serverstats);
    if (shmctl(serverstats_shmid, IPC_RMID, NULL) != 0) {
      /* do something? We are exiting anyway. */
      ;
    }
  }
}
static const char *cmd_backhand_loglevel(cmd_parms *cmd,
					 void *mconfig, char *word1) {
  mbcfg *cfg = (mbcfg *) mconfig;
  static char ll_error[256];
  char *copy,*param,*tok;
  int i;
  param = copy = strdup(word1);
  while((tok = strtok(param, ","))!=NULL) {
    param = NULL;
    i=0;
    while(LogLevels[i].aString) {
      if(!strcasecmp(LogLevels[i].aString, tok+1))
	break;
      i++;
    }
    if(!LogLevels[i].aString) {
      ap_snprintf(ll_error, sizeof ll_error,
		  "No such BackhandLogLevel token: %s", tok+1);
      return ll_error;
    }
    switch(*word1) {
    case '-':
      cfg->loglevel &= ~(LogLevels[i].bits);
      break;
    case '+':
    default:
      cfg->loglevel |= LogLevels[i].bits;
      break;
    }
  }
  free(copy);
  return NULL;
}

static const char *cmd_backhand_connectionpools(cmd_parms *cmd,
					        void *mconfig, char *word1) {
  static char *sr_error = "BackhandConnectionPools (On|Off)";
  mbcfg *cfg = (mbcfg *) mconfig;
  if(!strcasecmp(word1, "on")) {
    cfg->connectionpools = MBCP_ON;
  } else if (!strcasecmp(word1, "off")) {
    cfg->connectionpools = MBCP_OFF;
  } else {
    return sr_error;
  }
  return NULL;
}

static const char *cmd_backhand_sredir(cmd_parms *cmd,
					 void *mconfig, char *word1) {
  static char *sr_error = "BackhandSelfRedirect (On|Off)";
  mbcfg *cfg = (mbcfg *) mconfig;
  if(!strcasecmp(word1, "on")) {
    cfg->selfredirect = MBSR_ON;
  } else if (!strcasecmp(word1, "off")) {
    cfg->selfredirect = MBSR_OFF;
  } else {
    return sr_error;
  }
  return NULL;
}

static const char *cmd_backhand(cmd_parms *cmd, void *mconfig, char *word1,
			       char *word2) {
  int i;
  char *err = NULL;
  static char errbuf[1024];
  mbcfg *cfg = (mbcfg *) mconfig;
  cfg->local = 1;
  /* Simple Builtin Function name */
  for(i=0;i<_BuiltinCount;i++)
    if(strcmp(word1, BuiltinFuncsTable[i].aName)==0) {
      struct cpd *newfunc;
      if(!cfg->dfunc)
	newfunc = cfg->dfunc = (struct cpd *)malloc(sizeof(struct cpd));
      else {
	newfunc=cfg->dfunc;
	while(newfunc->next) newfunc=newfunc->next;
	newfunc->next = (struct cpd *)malloc(sizeof(struct cpd));
	newfunc=newfunc->next;
      }
      newfunc->next=NULL;
      newfunc->aName = BuiltinFuncsTable[i].aName;
      newfunc->aFunc = BuiltinFuncsTable[i].aFunc;
      newfunc->aString = (word2)?strdup(word2):word2;
      break;
    }
  if(i==_BuiltinCount) {
    ap_snprintf(errbuf, sizeof errbuf,
		"%s is an unknown Backhand candidacy function.", word1);
    err = errbuf;
  }
  return err;
}

static const char *cmd_backhand_so(cmd_parms *cmd, void *mconfig, char *word1,
				   char *word2, char *word3) {
  int strsize;
  DecisionFunc our_addr;
  ap_os_dso_handle_t *handle;
  const char *error;
  char *szFilename=ap_server_root_relative(cmd->pool, word1);
  mbcfg *cfg = (mbcfg *) mconfig;
  struct cpd *newfunc;
  cfg->local = 1;
  handle = ap_os_dso_load(szFilename);
  if(!handle)
    return ap_os_dso_error();
  our_addr = (DecisionFunc)ap_os_dso_sym(handle, word2);
  if((error = ap_os_dso_error())!=NULL)
    return error;
  if(!cfg->dfunc)
    newfunc = cfg->dfunc = (struct cpd *)malloc(sizeof(struct cpd));
  else {
    newfunc=cfg->dfunc;
    while(newfunc->next) newfunc=newfunc->next;
    newfunc->next = (struct cpd *)malloc(sizeof(struct cpd));
    newfunc=newfunc->next;
  }
  newfunc->next=NULL;
  strsize = strlen(word1)+strlen(word2)+3;
  newfunc->aName = (char *)malloc(strsize);
  ap_snprintf(newfunc->aName, strsize, "%s::%s", word1, word2);
  newfunc->aFunc = our_addr;
  newfunc->aString = (word3)?strdup(word3):NULL;
  return NULL;
}

/* static int myiter(void *nuttin, const char *key, const char *val) {
   char buffer[800];
   ap_snprintf(buffer, 800, "%s: %s<BR>\n", key, val);
   strcat(nuttin, buffer);
   return 1;
   }
*/

static int build_request_headers(void *nuttin,
				 const char *key, const char *val) {
  char buffer[DEFAULT_LIMIT_REQUEST_FIELDSIZE + 2];
  ap_snprintf(buffer, DEFAULT_LIMIT_REQUEST_FIELDSIZE+2, "%s: %s\n", key, val);
  strcat(nuttin, buffer);
  return 1;
}

static ServerSlot makedecision(request_rec *r) {
  struct cpd *aCPD;
  mbcfg *cfg;
  mbcfg *scfg;
  int j=0, i=0, loglevel;
  int ncand;
  ServerSlot candidates[MAXSERVERS];
  /* Veto forwarding if we are receiving a proxied session! */
  /* This should technically never happen because we have checked this
     before we call this function */
  if(ap_table_get(r->notes, "ProxiedFrom") ||
     ap_table_get(r->headers_in, "BackhandProxied")) {
    return invalid_machine;
  }
  cfg = our_dconfig(r);
  scfg = our_sconfig(r->server);
  loglevel = ((cfg)?(cfg->loglevel):0)|((scfg)?(scfg->loglevel):0);
  for(j=0;j<MAXSERVERS;j++) {
    if(serverstats[j].hostname[0]) {
      candidates[i].redirect = MB_HTTP_PROXY;
      candidates[i].hosttype = MB_HOSTTYPE_NAME;
      candidates[i++].id=j;
    }
  }
  if((aCPD = cfg->dfunc)==NULL)
    return invalid_machine;
  ncand=i;
  for(;aCPD!=NULL;aCPD=aCPD->next) {
    /* Send in some candidates and augment it */
    int oc=ncand;
    char buffer[MAXSERVERS*4];
    aCPD->aFunc(r, candidates, &ncand, aCPD->aString);
    if (loglevel & MBLL_DCSN3) {
      ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL,
		   "Func executed for %s [%s(%s)] (%d -> %d)", 
		   cfg->loc, aCPD->aName,
		   aCPD->aString?aCPD->aString:"NULL",
		   oc, ncand);
      ap_snprintf(buffer, sizeof buffer, "New server list: [ ");
      for(oc=0;oc<ncand;oc++)
        ap_snprintf(buffer+strlen(buffer), sizeof buffer-strlen(buffer),
		    "%d ", candidates[oc].id);
      ap_snprintf(buffer+strlen(buffer), sizeof buffer-strlen(buffer), "]");
      ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL, buffer);
    }
  }
  if(loglevel & MBLL_DCSN3) {
    ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL,
		 "All funcs executed -> %s", 
		 (ncand>0)?serverstats[candidates[0].id].hostname:"local");
  }
  /* Make our important decisions here... */
  return (ncand>0)?candidates[0]:invalid_machine;
}

static JMP_BUF passfdbuf;

static void recv_fd_timeout(int sig) {
  ap_longjmp(passfdbuf, sig);
}

static int backhand_redirection(request_rec *r) {
  int rv, clientka;
  static char buffer[RBUFLEN], *tmp;
  static char header[20000];
  const char *nowarn;
  long tatime;
  struct timeval start, end;
  mbcfg *cfg;
  mbcfg *scfg;
  int loglevel;
  int usepool = MBSR_INHERIT;

  if(remote_machine.id>=0) {
    int mbcs, size, ssize, tsize, remaining, cl, keepalive, ntries, chunked;
    int clr=-1;
    BUFF *myconn;
    table *myconn_headers_rcvd;
    table *cookies_rcvd;
    char mbcsp_request[MBCSP_REQ_SIZE], *content=(char *)NULL;
    struct in_addr tempaddr;
    int recvfd_failed;
    int umbilical_consecutive_attempts;

    cfg = our_dconfig(r);
    scfg = our_sconfig(r->server);
    loglevel = ((cfg)?(cfg->loglevel):0)|((scfg)?(scfg->loglevel):0);

    if(remote_machine.redirect) {
      char portstring[6] = "\0";
      char protocol[6] = "\0";
      unsigned short port;
      int n;
      if(loglevel & MBLL_DCSN3)
        ap_log_error(APLOG_MARK, APLOG_ERR, NULL,
		     "HTTP Redirection %s [%d]",
		     (remote_machine.hosttype)?"by IP":"by name",
		     remote_machine.id);

      if (ap_is_HTTP_REDIRECT(r->status)) {
	n = r->status;
	r->status = HTTP_OK; /* make Apache kernel happy */
      }
      else {
	n = REDIRECT;
      }
      /* now do the redirection */
      port = ntohs(serverstats[remote_machine.id].contact.sin_port);
      if(port!=80 && port!=443) ap_snprintf(portstring, 6, ":%d", port);
      if(port==443) strcpy(protocol, "https");
      else strcpy(protocol, "http");
      if(remote_machine.hosttype == MB_HOSTTYPE_IP) {
	ap_snprintf(buffer, RBUFLEN, "%s://%s%s%s", protocol,
		    inet_ntoa(serverstats[remote_machine.id].contact.sin_addr),
		    portstring, r->uri);
      } else {
      	const char *rhost = ap_table_get(r->notes, "Backhand-Redirect-Host");
	if(!rhost) rhost=serverstats[remote_machine.id].hostname;
	ap_snprintf(buffer, RBUFLEN, "%s://%s%s%s", protocol, rhost, portstring,
		    r->uri);	
      }
      if ( r->args != NULL ) { /* If we've get a Query String */
        ap_snprintf(buffer, RBUFLEN, "%s?%s", buffer, r->args);
      }
      ap_table_setn(r->headers_out, "Location", buffer);
      return n;
    }

    if(cfg->connectionpools == MBCP_INHERIT) {
      usepool = scfg->connectionpools;
    } else {
      usepool = cfg->connectionpools;
    }
    /* If it isn't explicitly off, then we assume it is on */
    if(usepool != MBCP_OFF) {
      usepool = MBCP_ON;
    }

    /* Make our decision */
    gettimeofday(&start, NULL);

    /* Build our request */
    tempaddr = r->connection->remote_addr.sin_addr;
    ap_snprintf(header, sizeof header, "%s\n", r->the_request);
    clientka = ap_find_token(r->pool,
			     ap_table_get(r->headers_in, "Connection"),
			     "Keep-Alive");
    if(r->proto_num >= HTTP_VERSION(1,1))
      clientka = 1;
    ap_table_setn(r->headers_in, "Connection", "Keep-Alive");
    ap_table_setn(r->headers_in, "BackhandProxied", inet_ntoa(tempaddr));
    ap_table_do(build_request_headers, header, r->headers_in, NULL);
    ap_table_unset(r->headers_in, "BackhandProxied");
    strcat(header, "\n");
    
    /* Get our socket */
    /* We only try once if we are not using connection pooling */
    if(usepool == MBCP_OFF)
      ntries=1;
    else
      ntries=10;
    do {
      ntries--;
      if(ntries<0) {
	if(content) free(content);
	if(loglevel & MBLL_MBCS4) {
	  ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		       "mod_backhand: Tried... failed");
	}
	goto local_handle;
      }
      if(usepool == MBCP_OFF) {
	mbcs = new_session(&serverstats[remote_machine.id].contact);
      } else {
	memcpy(mbcsp_request+1,
	       &serverstats[remote_machine.id].contact.sin_addr,
	       sizeof(struct in_addr));
	mbcsp_request[0] = MBCSP_GET;
	/* Apparently this next stanza can hang on BSD?! */
	recvfd_failed = 1;
	umbilical_consecutive_attempts = 0;
	while(recvfd_failed) {
	  if(write(umbilical, mbcsp_request, MBCSP_REQ_SIZE) != MBCSP_REQ_SIZE) {
	    if(loglevel & MBLL_MBCS3) {
	      ap_log_error(APLOG_MARK, APLOG_ERR, NULL,
			   "mod_backhand: MBCSP error (making request)");
	    }
	    goto local_handle;
	  }
	  if(ap_setjmp(passfdbuf) == 0) {
	    recvfd_failed = 1;
	    umbilical_consecutive_attempts++;
	    ap_set_callback_and_alarm(recv_fd_timeout, 5);
	    if((mbcs = recv_fd(umbilical))<0) {
	      if(loglevel & MBLL_MBCS3) {
		ap_log_error(APLOG_MARK, APLOG_ERR, NULL,
			     "mod_backhand: MBCSP error (recv file descriptor)");
	      }
	      ap_set_callback_and_alarm(NULL, 0);
	      goto local_handle;
	    }
	    recvfd_failed = 0;
	  }
	  ap_set_callback_and_alarm(NULL, 0);
	  if(recvfd_failed) {
	    if(umbilical_consecutive_attempts > 1) {
	      ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
			   "mod_backhand: child %d hung talking to moderator. Die!", getpid());
	      exit(0);
	    }
	    close_umbilical();
	    establish_umbilical(NULL);
	  }
	}
	if(loglevel & MBLL_MBCS2) {
	  ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		       "mod_backhand: Received fd(%d).",
		       mbcs);
	}
	/* End fetching file descriptors from moderator */
      }
      if(loglevel & MBLL_MBCS1) {
	ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		     "mod_backhand: Check 1");
      }
      myconn = ap_bcreate(r->pool, B_RDWR | B_SOCKET);
      ap_bpushfd(myconn, mbcs, mbcs);
      
      /* Set a failsafe timeout */
      ap_hard_timeout("backhand proxying ", r);

      /* Submit request our request */
      if(loglevel & MBLL_MBCS1) {
	ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		     "mod_backhand: Check 2");
      }
      tmp = header;
      tsize = strlen(header);
      ssize=0;
      while((ssize<tsize) &&
	    (size=ap_bwrite(myconn, tmp+ssize, tsize-ssize))>0)
	ssize+=size;
      if(loglevel & MBLL_MBCS1) {
	ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		     "mod_backhand: Check 3 --\n\n%s", header);
      }
      /* Now read content length from request if it is there (for POST etc.)
	 and send any submission down the pipe to the other server as well */
      if(clr<0) {
	nowarn = ap_table_get(r->headers_in, "Content-length");
	if(nowarn) cl=atoi(nowarn); else cl=-1;
	if(cl>0) {
	  if(loglevel & MBLL_MBCS1) {
	    ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
			 "mod_backhand: Check 4 -- reading %d more bytes", cl);
	  }
	  if((content = (char *)malloc(cl+1))==NULL) {
	    ap_bclose(myconn);
	    ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
			 "Failed malloc");
	    goto local_handle;
	  }
	  content[cl] = '\0';
	  remaining=cl;
	  ssize=0;
	  tmp=content;
	  while(remaining>0 && (size=ap_bread(r->connection->client, tmp,
					      remaining))>0) {
	    tmp+=size;
	    remaining-=size;
	  }
	}
	clr=1;
      }
      if(cl>0 && clr>=0) {
	tmp = content;
	tsize=cl;
	ssize=0;
	if(loglevel & MBLL_MBCS1) {
	  ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		       "mod_backhand: Check 5 -- writing %d more bytes: [%s]",
		       cl, content);
	}
	while((ssize<tsize) &&
	      (size=ap_bwrite(myconn, tmp+ssize, tsize-ssize))>0)
	  ssize+=size;
      }
      /* Flush everything and wait for a response from the other server */
      ap_bflush(myconn);
      
      /* Got a connection, let's read the mime headers they are sending
	 in front of it (we need Content-length and Keepalive info */
      ap_clear_table(r->headers_out);
      rv = b_get_mime_headers_out(myconn, r,
                                  &myconn_headers_rcvd, &cookies_rcvd);
      if(r->status == 100)
        rv = b_get_mime_headers_out(myconn, r,
                                    &myconn_headers_rcvd, &cookies_rcvd);
      ap_overlap_tables(r->headers_out, myconn_headers_rcvd,
      			AP_OVERLAP_TABLES_SET);
      if(!ap_is_empty_table(cookies_rcvd)) {
        ap_table_unset(r->headers_out, "Set-Cookie");
        r->headers_out =
          ap_overlay_tables(r->pool, r->headers_out, cookies_rcvd);
      }
      if(rv<0) {
	ap_bclose(myconn);
	close(mbcs);
	mbcs=-1;
      }
      if(loglevel & MBLL_MBCS1) {
	ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		     "mod_backhand: Check 6 -- headers(%d)", rv);
      }
    } while(mbcs==-1);
    /* We have sent it successfully */
    if(content) free(content);
    if((nowarn = ap_table_get(r->headers_out, "Content-type")) != NULL) {
      r->content_type = ap_pstrdup(r->pool, nowarn);
      ap_table_unset(r->headers_out, "Content-type");
    }
    keepalive = ap_find_token(r->pool,
			      ap_table_get(r->headers_out,
					   "Connection"), "Keep-Alive");
    nowarn = ap_table_get(r->headers_out, "Content-length");
    chunked = ap_find_token(r->pool,
			      ap_table_get(r->headers_out,
					   "Transfer-Encoding"), "chunked");
    if(nowarn) cl=atoi(nowarn); else cl=-1;
    
    /* Special cases defined by RFC */
    if((r->status == 304) || (r->status == 204) || (r->status < 200))
      cl = 0;
    
    if(loglevel & MBLL_MBCS1) {
      if(cl>0)
	ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		     "mod_backhand: Check 7 (Content-length: %d) (%s)",
		     cl, keepalive?"Keep-Alive":"wimpy");
      else if(chunked)
	ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		     "mod_backhand: Check 7 (Chunked) (%s)",
		     keepalive?"Keep-Alive":"wimpy");      
    }
    if(clientka) {
      ap_table_unset(r->headers_out, "Connection");
      r->connection->keepalive = 1;
    } else {
      ap_table_setn(r->headers_out, "Connection", "close");
    }
    
    ap_send_http_header(r);
    
    /* Now we read from the other server until done */
    if(cl>0) {
      remaining=cl;
      while(remaining>0 && (size=ap_bread(myconn, buffer,
					  MIN(RBUFLEN,remaining)))>0) {
	tsize=size;
	ssize=0;
	while((ssize<tsize) && 
	      (size=ap_rwrite(buffer+ssize, tsize-ssize, r))>0)
	  ssize+=size;
	remaining-=tsize;
      }
    } else if(chunked) {
      remaining=0;
      tsize=0;
      while((size = get_response_block(myconn, &remaining, buffer, RBUFLEN))>0) {
	tsize=size;
	ssize=0;
	while((ssize<tsize) && 
	      (size=ap_rwrite(buffer+ssize, tsize-ssize, r))>0)
	  ssize+=size;	
      }
      if(size<0) {
	keepalive = 0;
      }
    } else if(cl==-1 && !keepalive) {
      while((size=ap_bread(myconn, buffer, RBUFLEN))>0) {
	tsize=size;
	ssize=0;
	while((ssize<tsize) && 
	      (size=ap_rwrite(buffer+ssize, tsize-ssize, r))>0)
	  ssize+=size;
	remaining-=tsize;
      }
    }
    if(loglevel & MBLL_MBCS1) {
      ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		   "mod_backhand: Check 8");
    }
    ap_bflush(myconn);
    if(usepool == MBCP_OFF) {
    } else {
      if(keepalive) {
	/* Give the socket back */
	mbcsp_request[0] = MBCSP_PUT;
	if(loglevel & MBLL_MBCS2) {
	  ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		       "mod_backhand: (%d) Sending back fd(%d).",
		       getpid(), mbcs);
	}
	if(write(umbilical, mbcsp_request, MBCSP_REQ_SIZE) != MBCSP_REQ_SIZE) {
	  if(loglevel & MBLL_MBCS3) {
	    ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
			 "mod_backhand: MBCSP error (making request)");
	  }
	} else {
	  if(send_fd(umbilical,mbcs)!=0) {
	    if(loglevel & MBLL_MBCS3) {
	      ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
			   "mod_backhand: MBCSP error (send file descriptor)");
	    }
	  }
	}
      }
    }
    ap_kill_timeout(r);
    ap_bclose(myconn);
    gettimeofday(&end, NULL);
    end.tv_sec -= start.tv_sec;
    start.tv_sec = 0L;
    end.tv_sec *= 1000L;
    tatime = (end.tv_sec + end.tv_usec/1000 - start.tv_usec/1000);
    serverstats[0].tatime = ((serverstats[0].numbacked*serverstats[0].tatime)+
			     tatime)/(serverstats[0].numbacked+1);
    serverstats[0].numbacked++;
    if(serverstats[0].numbacked>1000) serverstats[0].numbacked=10;
    if(loglevel & MBLL_MBCS2) {
      ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		   "mod_backhand: Request tally %d [%d]",
		   serverstats[0].tatime, serverstats[0].numbacked);
    }
    return OK;
  }
 local_handle:
  ap_kill_timeout(r);
  ap_internal_redirect(r->uri, r);
  if(loglevel & MBLL_MBCS3) {
    ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
		 "mod_backhand: "
		 "could not get valid connection -- forced local");
  }
  return OK;
}
static int backhand_handler(request_rec *r)
{
  mbcfg *dcfg;
  char *tmp;
  int refresh;
  
  dcfg = our_dconfig(r);

  r->content_type = "text/html";
  ap_soft_timeout("redirect it", r);
  ap_send_http_header(r);
  if (r->header_only) {
    ap_kill_timeout(r);
    return OK;
  }
  
  ap_rputs("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n", r);
  ap_rputs("<HTML>\n", r);
  if(r->args && (tmp=strstr(r->args, "refresh=") )&&
     (refresh=atoi(tmp+8))>0) {
    ap_rprintf(r, "<META HTTP-EQUIV=\"Refresh\" content=\"%d; URL=HTTP:?%s\">",
	       refresh, r->args);
  }
  ap_rputs(" <HEAD>\n", r);
  ap_rputs("  <TITLE>mod_backhand Module\n", r);
  ap_rputs("  </TITLE>\n", r);
  ap_rputs(" </HEAD>\n", r);
  ap_rputs(" <BODY bgcolor=#ffffff text=#000000>\n", r);
  ap_rputs(" <CENTER>\n", r);
  ap_rputs(" <TABLE BORDER=0 CELLPADDING=4 CELLSPACING=4>", r);
#define TABLE_TOP "<TABLE BORDER=0 CELLPADDING=2 CELLSPACING=0 BGCOLOR=#000000>\n  <TR><TD><TABLE BORDER=0 CELLPADDING=2 CELLSPACING=0 WIDTH=100% BGCOLOR=#ffffff>\n"
#define TABLE_BOTTOM "</TABLE></TD></TR>\n  </TABLE>"
  ap_rputs(" <TR><TD valign=top>" TABLE_TOP "<TR><TD align=right>", r);
  ap_rputs(" <A HREF=\"http://www.backhand.org/\"><IMG SRC=\"/icons/backhand.jpg\" WIDTH=408 HEIGHT=144 BORDER=0></A><BR><A HREF=\"http://www.cnds.jhu.edu/\"><IMG SRC=\"/icons/cndsbar_mini.jpg\" WIDTH=263 HEIGHT=45 BORDER=0></A>", r);
  ap_rputs(" </TD></TR>" TABLE_BOTTOM "</TD>", r);
  ap_rputs(" <TD valign=top align=left>" TABLE_TOP, r);

  ap_rprintf(r, "<TR><TD align=right><B>Local Machine Name:</B></TD><TD>%s</TD></TR>",
	     r->server->server_hostname);
  ap_rprintf(r, "<TR><TD align=right><B>Apache Version String:</B></TD><TD>&nbsp;</TD></TR><TR><TD COLSPAN=2>&nbsp;&nbsp;&nbsp;&nbsp;%s</TD></TR>",
	     ap_get_server_version());
  ap_rprintf(r, "<TR><TD align=right><B>Server built:</B></TD><TD>%s</TD></TR>",
	     ap_get_server_built());
  ap_rprintf(r, "<TR><TD align=right><B>REMOTE_ADDR:</B></TD><TD>%s</TD></TR>", r->connection->remote_ip);
  ap_rputs(TABLE_BOTTOM "</TD></TR>", r);

  ap_rputs("<TR><TD COLSPAN=2>" TABLE_TOP "<TR><TD valign=top>", r);
  html_print_serverstats_table(r);
  ap_rputs("</TD></TR>" TABLE_BOTTOM, r);
  ap_rputs("</TD></TR></TABLE>\n", r);
  ap_rputs("</CENTER>\n", r);
  ap_rputs(" </BODY>\n", r);
  ap_rputs("</HTML>\n", r);
  ap_kill_timeout(r);
  return OK;
}

static void backhand_init(server_rec *s, pool *p) {
  char *note;
  char *sname = s->server_hostname;
  char buffer[MAXPATHLEN];
  int i=0;
  ACL *ptr;
  int mpid=0;

  setup_module_cells(s);
  /* Make sure we are in the UDPacl */

  setupUDPacl(NULL,NULL,NULL);

  if(getppid() == 1) {
    int i, afd, staterror;
    struct stat unused;
    daemon_params data;
    /* Apache calls this function twice!  How annoying!  We only want to do
	the dirty work the second time.  The first is for "configtest" */  
    ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s,
		 "mod_backhand -- UnixSocketDir set to %s",
		 UD_DN);
    for(i=0;i<nsins;i++) {
      unsigned int a,b,c,d,port,ttl;
      a = ntohl(sins[i].sin.sin_addr.s_addr);
      d = (a) & 0xff;
      c = (a >> 8) & 0xff;
      b = (a >> 16) & 0xff;
      a >>= 24;
      port = ntohs(sins[i].sin.sin_port);
      if(ismulticast(sins[i].sin)) {
	ttl = sins[i].sin.sin_family;
	ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s,
		     "mod_backhand -- Multicast %d.%d.%d.%d:%d TTL[%d] added",
		     a,b,c,d,port,ttl);
      } else {
	ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s,
		     "mod_backhand -- Broadcast %d.%d.%d.%d:%d added",
		     a,b,c,d,port);
      }
    }
    for(ptr=UDPacl; ((ptr=ptr->next)!=NULL);) {
      unsigned int a,b,c,d,mask,cm=0;
      a = ntohl(ptr->ip.s_addr);
      d = (a) & 0xff;
      c = (a >> 8) & 0xff;
      b = (a >> 16) & 0xff;
      a >>= 24;
      mask = ntohl(ptr->mask.s_addr);
      while(mask) {
	mask<<=1;
	cm++;
      }
      ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s,
		   "mod_backhand -- Multicast accept %d.%d.%d.%d/%d",
		   a,b,c,d,cm);
    }

    /*
     * Start the broadcasting
     */
    data.backhand_pool = backhand_pool;
    data.sins = sins;
    data.nsins = nsins;
    data.server = s;
    data.UDPacl = UDPacl;
    data.UD_DN = UD_DN;
      
    ap_snprintf(buffer, MAXPATHLEN,
		"%s/mod_backhand-Arriba",
		UD_DN);
    staterror = stat(buffer, &unused);
    if(mod_backhand_personal_arriba<0) {
      if(!staterror) {
	/* We have written it to a file (this is a graceful restart) */
	if((afd = open(buffer, O_RDONLY))>=0) {
	  read(afd, buffer, sizeof(buffer));
	  mod_backhand_personal_arriba = atoi(buffer);
	  close(afd);
	}
      }
      /* We could not get it from the file if we tried so we
       * PAINFULLY rediscover it and write it to a file */
      if(mod_backhand_personal_arriba<0) {
	mod_backhand_personal_arriba=0;
	backhand_initstat();
	if((afd = open(buffer, O_CREAT | O_WRONLY | O_TRUNC, 0600))>=0) {
	  ap_snprintf(buffer, MAXPATHLEN, "%d",
		      mod_backhand_personal_arriba);
	  write(afd, buffer, strlen(buffer));
	  close(afd);
	}
      }
    }
    mpid=ap_spawn_child(p, broadcast_my_stats,
			&data, kill_always,
			NULL, NULL, NULL);
    ap_snprintf(buffer, MAXPATHLEN,
		"backhand_init(%d) spawning moderator (PID %d)",
		getpid(), mpid);
    ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s, buffer);
    for(i=0;i<10;i++) {
      ap_snprintf(buffer, MAXPATHLEN, "%s/bparent", UD_DN);
      afd = cli_conn(buffer, UD_DN);
      if(afd<0) {
	sleep(1);
        ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s,
		     "waiting for mod_backhand moderator to start");
      } else {
	close(afd);
        ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s,
		     "mod_backhand moderator ready to go");
	if(moderator_pid_filename) {
	  int mpfd;
	  char pidbuffer[10];
	  mpfd = open(moderator_pid_filename, O_CREAT|O_TRUNC|O_WRONLY, 0640);
	  if(mpfd < 0) {
            ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s,
		         "mod_backhand moderator can't write to PID file");
	  } else {
	    ap_snprintf(pidbuffer, 10, "%d\n", mpid);
	    write(mpfd, pidbuffer, strlen(pidbuffer));
	    close(mpfd);
	  }
	}
	i=-1;
	break;
      }
    }
    if(i>0) {
      ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s,
		   "mod_backhand moderator not ready!!! could be bad.");
    }
#if MODULE_MAGIC_NUMBER >= 19980507
    if(!strstr(ap_get_server_version(), MOD_BACKHAND_STRING_VERSION)) {
      ap_add_version_component(MOD_BACKHAND_STRING_VERSION);
    }
#endif
  }
}

static void establish_umbilical(server_rec *s) {
  char buffer[MAXPATHLEN];
  ap_snprintf(buffer, MAXPATHLEN, "%s/bparent", UD_DN);
  umbilical = cli_conn(buffer, UD_DN);
  if(umbilical < 0) {
    ap_log_error(APLOG_MARK, APLOG_ERR, s,
		 "Child %d failed to establish umbilical to moderator!",
		 getpid());
    exit(0);
  }
}
static void close_umbilical() {
  char mbcsp_request[MBCSP_REQ_SIZE];
  mbcsp_request[0] = MBCSP_CLOSE;
  /* We don't care about the rest of the structure of the return value
     this is simply a courtesy */
  write(umbilical, mbcsp_request, MBCSP_REQ_SIZE);
  close(umbilical);
  umbilical = -1;
}
static void backhand_child_init(server_rec *s, pool *p) {
  setup_module_cells(s);
  establish_umbilical(s);
}

static void backhand_child_exit(server_rec *s, pool *p) {
  /*
   * Close the umbilical
   */
  /*
  close_umbilical();
  umbilical=-1;
  */
}

static void *backhand_create_dir_config(pool *p, char *dirspec) {
  mbcfg *cfg;
  
  /*
   * Allocate the space for our record from the pool supplied.
   */
  cfg = (mbcfg *) ap_pcalloc(p, sizeof(mbcfg));
  /*
   * Now fill in the defaults.  If there are any `parent' configuration
   * records, they'll get merged as part of a separate callback.
   */
  cfg->local = 0;
  cfg->congenital = 0;
  cfg->loglevel = MBLL_NONE;
  cfg->connectionpools = MBCP_INHERIT;
  cfg->selfredirect = MBSR_INHERIT;
  cfg->cmode = CONFIG_MODE_DIRECTORY;
  cfg->dfunc = NULL;

  return (void *) cfg;
}

static void *backhand_merge_dir_config(pool *p, void *parent_conf,
				       void *newloc_conf) {
  mbcfg *merged_config = (mbcfg *) ap_pcalloc(p, sizeof(mbcfg));
  mbcfg *pconf = (mbcfg *) parent_conf;
  mbcfg *nconf = (mbcfg *) newloc_conf;
  
  /*
   * Some things get copied directly from the more-specific record, rather
   * than getting merged.
   */
  merged_config->local = nconf->local;
  merged_config->loc = ap_pstrdup(p, nconf->loc);
  /*
   * Others, like the setting of the `congenital' flag, get ORed in.  The
   * setting of that particular flag, for instance, is TRUE if it was ever
   * true anywhere in the upstream configuration.
   */
  merged_config->congenital = (pconf->congenital | pconf->local);
  /*
   * If we're merging records for two different types of environment (server
   * and directory), mark the new record appropriately.  Otherwise, inherit
   * the current value.
   */
  merged_config->cmode =
    (pconf->cmode == nconf->cmode) ? pconf->cmode : CONFIG_MODE_COMBO;
  /*
   * Now just record our being called in the trace list.  Include the
   * locations we were asked to merge.
   */
  merged_config->loglevel =
    ( nconf->loglevel ) ? nconf->loglevel : pconf->loglevel;
  merged_config->connectionpools =
    ( nconf->connectionpools ) ? nconf->connectionpools:pconf->connectionpools;
  merged_config->selfredirect =
    ( nconf->selfredirect ) ? nconf->selfredirect : pconf->selfredirect;
  merged_config->dfunc = 
    ( nconf->dfunc != NULL ) ? nconf->dfunc : pconf->dfunc;
  
  return (void *) merged_config;
}

static void *backhand_create_server_config(pool *p, server_rec *s) {
  mbcfg *cfg;
  
  /*
   * As with the backhand_create_dir_config() reoutine, we allocate and fill
   * in an empty record.
   */
  cfg = (mbcfg *) ap_pcalloc(p, sizeof(mbcfg));
  cfg->local = 0;
  cfg->congenital = 0;
  cfg->cmode = CONFIG_MODE_SERVER;
  cfg->loglevel = MBLL_NONE;
  cfg->connectionpools = MBCP_INHERIT;
  cfg->selfredirect = MBSR_INHERIT;
  cfg->dfunc = NULL;
  return (void *) cfg;
}

static void *backhand_merge_server_config(pool *p, void *server1_conf,
					  void *server2_conf) {
  mbcfg *merged_config = (mbcfg *) ap_pcalloc(p, sizeof(mbcfg));
  mbcfg *s1conf = (mbcfg *) server1_conf;
  mbcfg *s2conf = (mbcfg *) server2_conf;
  
  /*
   * Our inheritance rules are our own, and part of our module's semantics.
   * Basically, just note whence we came.
   */
  merged_config->cmode =
    (s1conf->cmode == s2conf->cmode) ? s1conf->cmode : CONFIG_MODE_COMBO;
  merged_config->local = s2conf->local;
  merged_config->congenital = (s1conf->congenital | s1conf->local);
  merged_config->loc = ap_pstrdup(p, s2conf->loc);
  merged_config->loglevel =
    (s2conf->loglevel) ? s2conf->loglevel : s1conf->loglevel;
  merged_config->connectionpools =
    (s2conf->connectionpools) ? s2conf->connectionpools:s1conf->connectionpools;
  merged_config->selfredirect =
    (s2conf->selfredirect) ? s2conf->selfredirect : s1conf->selfredirect;
  merged_config->dfunc =
    (s2conf->dfunc != NULL) ? s1conf->dfunc : s2conf->dfunc;
  return (void *) merged_config;
}

static int backhand_post_read_request(request_rec *r) {
  mbcfg *cfg;
  mbcfg *scfg;
  int loglevel;
  char buffer[2000];
  const char *bps;
  struct in_addr new_in_addr;
  
  cfg = our_dconfig(r);
  scfg = our_sconfig(r->server);
  loglevel = ((cfg)?(cfg->loglevel):0)|((scfg)?(scfg->loglevel):0);
  /*
   * We want to check for a "BackhandProxied: IPAddr" header and then
   * we authroize that request via IP ACL and then we change the
   * the incoming in_addr and remote IP in the connection.
   * Do this only if there is a Backhand directive! (local || congenital)
   */
  bps = ap_table_get(r->headers_in, "BackhandProxied");
  
  if(bps) {
    if(ap_is_initial_req(r)) {
      if(inet_aton(bps, &new_in_addr) &&
	 matchACL(UDPacl, &r->connection->remote_addr.sin_addr)!=NULL &&
	 memcmp(&new_in_addr, &r->connection->remote_addr.sin_addr,
		sizeof(struct in_addr))) {
        char *newip;
	/* Proxied directive -> ACL passed -> Not ALREADY done */
        ap_table_set(r->notes, "ProxiedFrom",
		     newip=inet_ntoa(r->connection->remote_addr.sin_addr));
	
	ap_snprintf(buffer, sizeof buffer,
		    "BackhandProxied directive encountered and ACCEPTED (%s->%s)<BR>\n",
		    r->connection->remote_ip,
		    inet_ntoa(new_in_addr));
	memcpy(&r->connection->remote_addr.sin_addr,
	       &new_in_addr, sizeof(struct in_addr));
	r->connection->remote_ip = ap_pstrdup(r->connection->pool,
					      inet_ntoa(new_in_addr));
      } else {
	/* Something went wrong... not allowed to go wrong */
	ap_snprintf(buffer, sizeof buffer,
		    "BackhandProxied directive encountered and DENIED (%s->%s)<BR>\n",
		    r->connection->remote_ip,
		    inet_ntoa(new_in_addr));
      }
    } else {
      if(r->main && r->connection && r->main->connection) {
	/* We do this (if ...) because one time I ran into
	   r->connection not being there? As this causes a seg fault,
	   we wish to avoid this... */
	memcpy(&r->connection->remote_addr.sin_addr,
	       &r->main->connection->remote_addr.sin_addr,
	       sizeof(struct in_addr));
	r->connection->remote_ip = ap_pstrdup(r->connection->pool,
					      r->main->connection->remote_ip);
      }
    }
  } else {
      request_rec *subr;
      mbcfg *tmpcfg;
      ap_table_setn(r->notes, "BackhandProxyRequest", "YES");
      subr = ap_sub_req_lookup_uri(r->uri, r);
      tmpcfg = (mbcfg *)our_dconfig(subr);
      if(strncmp(subr->uri, "backhand:", 9)==0 &&
	 tmpcfg->local && tmpcfg->congenital) {
	const char *rhost = ap_table_get(subr->notes, "Backhand-Redirect-Host");
	if(rhost) ap_table_set(r->notes, "Backhand-Redirect-Host", rhost);
	r->uri = ap_pstrcat(r->pool, "backhand:", r->uri, NULL);
	r->filename = ap_pstrdup(r->pool, r->uri);
	r->handler = "backhand-redirection";
	if(loglevel & MBLL_DCSN1) {
	  ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL,
		       "(Postread =>) = { Backhanding to %d }", 
		       remote_machine.id);
	  ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL,
		       "(Postread =>) = { %s, %s, %s }", 
		       r->uri, r->handler, r->content_type);
	}
	ap_destroy_sub_req(subr);
	return OK;
    }
  }
  if(loglevel & MBLL_DCSN1) {
    ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL,
		 "(Postread =>) = { DECLINED }");
  }
  return DECLINED;
}

static int backhand_translate_handler(request_rec *r) {
  mbcfg *cfg;
  mbcfg *scfg;
  int loglevel;

  cfg = our_dconfig(r);
  scfg = our_sconfig(r->server);
  loglevel = ((cfg)?(cfg->loglevel):0)|((scfg)?(scfg->loglevel):0);

  if(loglevel & MBLL_DCSN1) {
    ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL,
		 "(Translate <=) = { %s, %s, %s }", 
		 r->uri, r->handler, r->content_type);
  }
  if(strncmp(r->uri, "backhand:", 9)!=0) {
    if(loglevel & MBLL_DCSN1) {
      ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL,
		   "(Translate =>) = { %s, %s, %s }", 
		   r->uri, r->handler, r->content_type);
    }
    return DECLINED;
  }
  memmove(r->uri, &r->uri[9], strlen(&r->uri[9])+1);
  return OK;
}

static int backhand_type_checker(request_rec *r) {
  mbcfg *cfg;
  mbcfg *scfg;
  const char *bhpr;
  int loglevel;
  int sredir = MBSR_INHERIT;

  cfg = our_dconfig(r);
  scfg = our_sconfig(r->server);
  loglevel = ((cfg)?(cfg->loglevel):0)|((scfg)?(scfg->loglevel):0);
  if(cfg->selfredirect == MBSR_INHERIT) {
    sredir = scfg->selfredirect;    
  } else {
    sredir = cfg->selfredirect;
  }
  if(loglevel & MBLL_DCSN1) {
    ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL,
		 "(Type <=) = { %s, %s, %s }", 
		 r->handler, r->uri, r->content_type);
  }
  /* Reset this to local for last minute remote redirection */
  if(!ap_is_initial_req(r) && cfg->local && cfg->congenital &&
     (bhpr = ap_table_get((r->main)?r->main->notes:r->notes,
			  "BackhandProxyRequest")) &&
     strncmp(bhpr, "YES", 3)==0) {
    remote_machine = makedecision(r);
    if(remote_machine.id>=0 &&
       ((sredir==MBSR_ON) || (remote_machine.id>0))) {
      r->content_type = "backhand/redirect";
      r->uri = ap_pstrcat(r->pool, "backhand:", r->uri, NULL);
      r->filename = ap_pstrcat(r->pool, "backhand:", r->filename, NULL);
      r->handler = "backhand-redirection";
    }
  }
  if(r->handler && !strcmp(r->handler, "backhand-redirection")) {
    if(loglevel & MBLL_DCSN1) {
      ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL,
		   "(Type =>) = *{ %s, %s, %s }", 
		   r->handler, r->uri, r->content_type);
    }
    return OK;
  }
  if(loglevel & MBLL_DCSN1) {
    ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL,
		 "(Type =>) = { %s, %s, %s }", 
		 r->handler, r->uri, r->content_type);
  }
  return DECLINED;
}

/* We need to reset the r->connection values back to what Apache thinks
   they were after the request has been complete serviced.  Otherwise,
   if KeepAlives are enabled, the remote_addr will be wrong for the next
   pipelined HTTP request. */

static int backhand_conn_addr_reset(request_rec *r) {
  const char *bps, *real;
  struct in_addr new_in_addr;
  mbcfg *cfg;
  mbcfg *scfg;
  int loglevel;

  bps = ap_table_get(r->headers_in, "BackhandProxied");
  real= ap_table_get(r->notes, "ProxiedFrom");
  if(bps && real) {
    if(inet_aton(real, &new_in_addr)) {
      cfg = our_dconfig(r);
      scfg = our_sconfig(r->server);
      loglevel = ((cfg)?(cfg->loglevel):0)|((scfg)?(scfg->loglevel):0);
      memcpy(&r->connection->remote_addr.sin_addr,
               &new_in_addr, sizeof(struct in_addr));
      if(loglevel & MBLL_NET3)
	ap_log_error(APLOG_MARK, APLOG_NOTICE|APLOG_NOERRNO, NULL,
		     "Reseting connection remote_addr to %s", real);
    }
  }
  return OK;
}

static int backhand_header_parser(request_rec *r) {
  mbcfg *cfg;
  const char *bps;
  cfg = our_dconfig(r);
  if((bps = ap_table_get(r->notes, "ProxiedFrom"))!=NULL) {
    ap_table_setn(r->headers_in, "BackhandProxied", bps);
    return OK;
  }  
  return DECLINED;
}

static const command_rec backhand_cmds[] =
{
  {
    "BackhandModeratorPIDFile",  /* directive name */
    setup_pid_file,              /* config action routine */
    NULL,                        /* argument to include in call */
    RSRC_CONF,                   /* where available */
    TAKE1,                       /* arguments */
    "Backhand directive - File to hold PID of the moderator process"
                                 /* directive description */
  },
  {
    "UnixSocketDir",        /* directive name */
    setup_sock_un,          /* config action routine */
    NULL,                   /* argument to include in call */
    RSRC_CONF,              /* where available */
    TAKE1,                  /* arguments */
    "Backhand directive - Directory for AF_UNIXs to listen for fd requests"
                            /* directive description */
  },
  {
    "MulticastStats",       /* directive name */
    setupbroadcasting,      /* config action routine */
    NULL,                   /* argument to include in call */
    RSRC_CONF,              /* where available */
    TAKE12,                 /* arguments */
    "Backhand directive - where to (broad|multi)cast fromip toip:toport,ttl"
                            /* directive description */
  },
  {
    "AcceptStats",          /* directive name */
    setupUDPacl,            /* config action routine */
    NULL,                   /* argument to include in call */
    RSRC_CONF,              /* where available */
    TAKE1,                  /* arguments */
    "Backhand directive - from where to accept broadcasts"
                            /* directive description */
  },
  {
    "BackhandLogLevel",     /* directive name */
    cmd_backhand_loglevel,  /* config action routine */
    NULL,                   /* argument to include in call */
    OR_ALL,                 /* where available */
    TAKE1,                  /* arguments */
    "BackhandLogLevel directive - log flags"
                            /* directive description */
  },
  {
    "BackhandConnectionPools", /* directive name */
    cmd_backhand_connectionpools,    /* config action routine */
    NULL,                   /* argument to include in call */
    OR_ALL,                 /* where available */
    TAKE1,                  /* arguments */
    "BackhandConnectionPools directive - use moderator for pooling?"
                            /* directive description */
  },
  {
    "BackhandSelfRedirect", /* directive name */
    cmd_backhand_sredir,    /* config action routine */
    NULL,                   /* argument to include in call */
    OR_ALL,                 /* where available */
    TAKE1,                  /* arguments */
    "BackhandSelfRedirect directive - proxy to me?"
                            /* directive description */
  },
  {
    "Backhand",             /* directive name */
    cmd_backhand,           /* config action routine */
    NULL,                   /* argument to include in call */
    ACCESS_CONF,            /* where available */
    TAKE12,                 /* arguments */
    "Backhand directive - function [arg]"
                            /* directive description */
  },
  {
    "BackhandFromSO",       /* directive name */
    cmd_backhand_so,        /* config action routine */
    NULL,                   /* argument to include in call */
    ACCESS_CONF,            /* where available */
    TAKE23,                 /* arguments */
    "Backhand directive - sharedlib function [arg]"
                            /* directive description */
  },
  {NULL}
};

static const handler_rec backhand_handlers[] =
{
  {"backhand-handler", backhand_handler},
  {"backhand-redirection", backhand_redirection},
  {NULL}
};


/* Last, but not least! The grand finale */

module backhand_module =
{
  STANDARD_MODULE_STUFF,
  backhand_init,                 /* module initializer */
  backhand_create_dir_config,    /* per-directory config creator */
  backhand_merge_dir_config,     /* dir config merger */
  backhand_create_server_config, /* server config creator */
  backhand_merge_server_config,  /* server config merger */
  backhand_cmds,                 /* command table */
  backhand_handlers,             /* list of handlers */
  backhand_translate_handler,    /* [2] filename-to-URI translation */
  NULL,                          /* [5] check/validate user_id */
  NULL,                          /* [6] check user_id is valid */
  NULL,                          /* [4] check access by host address */
  backhand_type_checker,         /* [7] MIME type checker/setter */
  NULL,                          /* [8] fixups */
  backhand_conn_addr_reset,      /* [10] logger */
#if MODULE_MAGIC_NUMBER >= 19970103
  backhand_header_parser,        /* [3] header parser */
#endif
#if MODULE_MAGIC_NUMBER >= 19970719
  backhand_child_init,           /* process initializer */
#endif
#if MODULE_MAGIC_NUMBER >= 19970728
  backhand_child_exit,           /* process exit/cleanup */
#endif
#if MODULE_MAGIC_NUMBER >= 19970902
  backhand_post_read_request     /* [1] post read_request handling */
#endif
};