Add cluster_port parameter for Multiple clusters
[l2tpns.git] / cluster.c
1 // L2TPNS Clustering Stuff
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <stdarg.h>
6 #include <unistd.h>
7 #include <inttypes.h>
8 #include <sys/file.h>
9 #include <sys/stat.h>
10 #include <sys/socket.h>
11 #include <netinet/in.h>
12 #include <arpa/inet.h>
13 #include <sys/ioctl.h>
14 #include <net/if.h>
15 #include <string.h>
16 #include <malloc.h>
17 #include <errno.h>
18 #include <libcli.h>
19
20 #include "dhcp6.h"
21 #include "l2tpns.h"
22 #include "cluster.h"
23 #include "util.h"
24 #include "tbf.h"
25 #include "pppoe.h"
26
27 #ifdef BGP
28 #include "bgp.h"
29 #endif
30 /*
31 * All cluster packets have the same format.
32 *
33 * One or more instances of
34 * a 32 bit 'type' id.
35 * a 32 bit 'extra' data dependant on the 'type'.
36 * zero or more bytes of structure data, dependant on the type.
37 *
38 */
39
40 // Module variables.
41 extern int cluster_sockfd; // The filedescriptor for the cluster communications port.
42
43 in_addr_t my_address = 0; // The network address of my ethernet port.
44 static int walk_session_number = 0; // The next session to send when doing the slow table walk.
45 static int walk_bundle_number = 0; // The next bundle to send when doing the slow table walk.
46 static int walk_tunnel_number = 0; // The next tunnel to send when doing the slow table walk.
47 int forked = 0; // Sanity check: CLI must not diddle with heartbeat table
48
49 #define MAX_HEART_SIZE (8192) // Maximum size of heartbeat packet. Must be less than max IP packet size :)
50 #define MAX_CHANGES (MAX_HEART_SIZE/(sizeof(sessiont) + sizeof(int) ) - 2) // Assumes a session is the biggest type!
51
52 static struct {
53 int type;
54 int id;
55 } cluster_changes[MAX_CHANGES]; // Queue of changed structures that need to go out when next heartbeat.
56
57 static struct {
58 int seq;
59 int size;
60 uint8_t data[MAX_HEART_SIZE];
61 } past_hearts[HB_HISTORY_SIZE]; // Ring buffer of heartbeats that we've recently sent out. Needed so
62 // we can re-transmit if needed.
63
64 static struct {
65 in_addr_t peer;
66 uint32_t basetime;
67 clockt timestamp;
68 int uptodate;
69 } peers[CLUSTER_MAX_SIZE]; // List of all the peers we've heard from.
70 static int num_peers; // Number of peers in list.
71
72 static int rle_decompress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize);
73 static int rle_compress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize);
74
75 //
76 // Create a listening socket
77 //
78 // This joins the cluster multi-cast group.
79 //
80 int cluster_init()
81 {
82 struct sockaddr_in addr;
83 struct sockaddr_in interface_addr;
84 struct ip_mreq mreq;
85 struct ifreq ifr;
86 int opt;
87
88 config->cluster_undefined_sessions = MAXSESSION-1;
89 config->cluster_undefined_bundles = MAXBUNDLE-1;
90 config->cluster_undefined_tunnels = MAXTUNNEL-1;
91
92 if (!config->cluster_address)
93 return 0;
94 if (!*config->cluster_interface)
95 return 0;
96
97 cluster_sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
98
99 memset(&addr, 0, sizeof(addr));
100 addr.sin_family = AF_INET;
101 addr.sin_port = htons(config->cluster_port);
102 addr.sin_addr.s_addr = INADDR_ANY;
103 setsockopt(cluster_sockfd, SOL_SOCKET, SO_REUSEADDR, &addr, sizeof(addr));
104
105 opt = fcntl(cluster_sockfd, F_GETFL, 0);
106 fcntl(cluster_sockfd, F_SETFL, opt | O_NONBLOCK);
107
108 if (bind(cluster_sockfd, (void *) &addr, sizeof(addr)) < 0)
109 {
110 LOG(0, 0, 0, "Failed to bind cluster socket: %s\n", strerror(errno));
111 return -1;
112 }
113
114 strcpy(ifr.ifr_name, config->cluster_interface);
115 if (ioctl(cluster_sockfd, SIOCGIFADDR, &ifr) < 0)
116 {
117 LOG(0, 0, 0, "Failed to get interface address for (%s): %s\n", config->cluster_interface, strerror(errno));
118 return -1;
119 }
120
121 memcpy(&interface_addr, &ifr.ifr_addr, sizeof(interface_addr));
122 my_address = interface_addr.sin_addr.s_addr;
123
124 // Join multicast group.
125 mreq.imr_multiaddr.s_addr = config->cluster_address;
126 mreq.imr_interface = interface_addr.sin_addr;
127
128
129 opt = 0; // Turn off multicast loopback.
130 setsockopt(cluster_sockfd, IPPROTO_IP, IP_MULTICAST_LOOP, &opt, sizeof(opt));
131
132 if (config->cluster_mcast_ttl != 1)
133 {
134 uint8_t ttl = 0;
135 if (config->cluster_mcast_ttl > 0)
136 ttl = config->cluster_mcast_ttl < 256 ? config->cluster_mcast_ttl : 255;
137
138 setsockopt(cluster_sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
139 }
140
141 if (setsockopt(cluster_sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
142 {
143 LOG(0, 0, 0, "Failed to setsockopt (join mcast group): %s\n", strerror(errno));
144 return -1;
145 }
146
147 if (setsockopt(cluster_sockfd, IPPROTO_IP, IP_MULTICAST_IF, &interface_addr, sizeof(interface_addr)) < 0)
148 {
149 LOG(0, 0, 0, "Failed to setsockopt (set mcast interface): %s\n", strerror(errno));
150 return -1;
151 }
152
153 config->cluster_last_hb = TIME;
154 config->cluster_seq_number = -1;
155
156 return cluster_sockfd;
157 }
158
159
160 //
161 // Send a chunk of data to the entire cluster (usually via the multicast
162 // address ).
163 //
164
165 static int cluster_send_data(void *data, int datalen)
166 {
167 struct sockaddr_in addr = {0};
168
169 if (!cluster_sockfd) return -1;
170 if (!config->cluster_address) return 0;
171
172 addr.sin_addr.s_addr = config->cluster_address;
173 addr.sin_port = htons(config->cluster_port);
174 addr.sin_family = AF_INET;
175
176 LOG(5, 0, 0, "Cluster send data: %d bytes\n", datalen);
177
178 if (sendto(cluster_sockfd, data, datalen, MSG_NOSIGNAL, (void *) &addr, sizeof(addr)) < 0)
179 {
180 LOG(0, 0, 0, "sendto: %s\n", strerror(errno));
181 return -1;
182 }
183
184 return 0;
185 }
186
187 //
188 // Add a chunk of data to a heartbeat packet.
189 // Maintains the format. Assumes that the caller
190 // has passed in a big enough buffer!
191 //
192 static void add_type(uint8_t **p, int type, int more, uint8_t *data, int size)
193 {
194 *((uint32_t *) (*p)) = type;
195 *p += sizeof(uint32_t);
196
197 *((uint32_t *)(*p)) = more;
198 *p += sizeof(uint32_t);
199
200 if (data && size > 0) {
201 memcpy(*p, data, size);
202 *p += size;
203 }
204 }
205
206 // advertise our presence via BGP or gratuitous ARP
207 static void advertise_routes(void)
208 {
209 #ifdef BGP
210 if (bgp_configured)
211 bgp_enable_routing(1);
212 else
213 #endif /* BGP */
214 if (config->send_garp)
215 send_garp(config->bind_address); // Start taking traffic.
216 }
217
218 // withdraw our routes (BGP only)
219 static void withdraw_routes(void)
220 {
221 #ifdef BGP
222 if (bgp_configured)
223 bgp_enable_routing(0);
224 #endif /* BGP */
225 }
226
227 static void cluster_uptodate(void)
228 {
229 if (config->cluster_iam_uptodate)
230 return;
231
232 if (config->cluster_undefined_sessions || config->cluster_undefined_tunnels || config->cluster_undefined_bundles)
233 return;
234
235 config->cluster_iam_uptodate = 1;
236
237 LOG(0, 0, 0, "Now uptodate with master.\n");
238 advertise_routes();
239 }
240
241 //
242 // Send a unicast UDP packet to a peer with 'data' as the
243 // contents.
244 //
245 static int peer_send_data(in_addr_t peer, uint8_t *data, int size)
246 {
247 struct sockaddr_in addr = {0};
248
249 if (!cluster_sockfd) return -1;
250 if (!config->cluster_address) return 0;
251
252 if (!peer) // Odd??
253 return -1;
254
255 addr.sin_addr.s_addr = peer;
256 addr.sin_port = htons(config->cluster_port);
257 addr.sin_family = AF_INET;
258
259 LOG_HEX(5, "Peer send", data, size);
260
261 if (sendto(cluster_sockfd, data, size, MSG_NOSIGNAL, (void *) &addr, sizeof(addr)) < 0)
262 {
263 LOG(0, 0, 0, "sendto: %s\n", strerror(errno));
264 return -1;
265 }
266
267 return 0;
268 }
269
270 //
271 // Send a structured message to a peer with a single element of type 'type'.
272 //
273 static int peer_send_message(in_addr_t peer, int type, int more, uint8_t *data, int size)
274 {
275 uint8_t buf[65536]; // Vast overkill.
276 uint8_t *p = buf;
277
278 LOG(4, 0, 0, "Sending message to peer (type %d, more %d, size %d)\n", type, more, size);
279 add_type(&p, type, more, data, size);
280
281 return peer_send_data(peer, buf, (p-buf) );
282 }
283
284 // send a packet to the master
285 static int _forward_packet(uint8_t *data, int size, in_addr_t addr, int port, int type)
286 {
287 uint8_t buf[65536]; // Vast overkill.
288 uint8_t *p = buf;
289
290 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
291 return -1;
292
293 LOG(4, 0, 0, "Forwarding packet from %s to master (size %d)\n", fmtaddr(addr, 0), size);
294
295 STAT(c_forwarded);
296 add_type(&p, type, addr, (uint8_t *) &port, sizeof(port)); // ick. should be uint16_t
297 memcpy(p, data, size);
298 p += size;
299
300 return peer_send_data(config->cluster_master_address, buf, (p - buf));
301 }
302
303 //
304 // Forward a state changing packet to the master.
305 //
306 // The master just processes the payload as if it had
307 // received it off the tun device.
308 //(note: THIS ROUTINE WRITES TO pack[-6]).
309 int master_forward_packet(uint8_t *data, int size, in_addr_t addr, uint16_t port, uint16_t indexudp)
310 {
311 uint8_t *p = data - (3 * sizeof(uint32_t));
312 uint8_t *psave = p;
313 uint32_t indexandport = port | ((indexudp << 16) & 0xFFFF0000);
314
315 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
316 return -1;
317
318 LOG(4, 0, 0, "Forwarding packet from %s to master (size %d)\n", fmtaddr(addr, 0), size);
319
320 STAT(c_forwarded);
321 add_type(&p, C_FORWARD, addr, (uint8_t *) &indexandport, sizeof(indexandport));
322
323 return peer_send_data(config->cluster_master_address, psave, size + (3 * sizeof(uint32_t)));
324 }
325
326 // Forward PPPOE packet to the master.
327 //(note: THIS ROUTINE WRITES TO pack[-4]).
328 int master_forward_pppoe_packet(uint8_t *data, int size, uint8_t codepad)
329 {
330 uint8_t *p = data - (2 * sizeof(uint32_t));
331 uint8_t *psave = p;
332
333 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
334 return -1;
335
336 LOG(4, 0, 0, "Forward PPPOE packet to master, code %s (size %d)\n", get_string_codepad(codepad), size);
337
338 STAT(c_forwarded);
339 add_type(&p, C_PPPOE_FORWARD, codepad, NULL, 0);
340
341 return peer_send_data(config->cluster_master_address, psave, size + (2 * sizeof(uint32_t)));
342 }
343
344 // Forward a DAE RADIUS packet to the master.
345 int master_forward_dae_packet(uint8_t *data, int size, in_addr_t addr, int port)
346 {
347 return _forward_packet(data, size, addr, port, C_FORWARD_DAE);
348 }
349
350 //
351 // Forward a throttled packet to the master for handling.
352 //
353 // The master just drops the packet into the appropriate
354 // token bucket queue, and lets normal processing take care
355 // of it.
356 //
357 int master_throttle_packet(int tbfid, uint8_t *data, int size)
358 {
359 uint8_t buf[65536]; // Vast overkill.
360 uint8_t *p = buf;
361
362 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
363 return -1;
364
365 LOG(4, 0, 0, "Throttling packet master (size %d, tbfid %d)\n", size, tbfid);
366
367 add_type(&p, C_THROTTLE, tbfid, data, size);
368
369 return peer_send_data(config->cluster_master_address, buf, (p-buf) );
370
371 }
372
373 //
374 // Forward a walled garden packet to the master for handling.
375 //
376 // The master just writes the packet straight to the tun
377 // device (where is will normally loop through the
378 // firewall rules, and come back in on the tun device)
379 //
380 // (Note that this must be called with the tun header
381 // as the start of the data).
382 int master_garden_packet(sessionidt s, uint8_t *data, int size)
383 {
384 uint8_t buf[65536]; // Vast overkill.
385 uint8_t *p = buf;
386
387 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
388 return -1;
389
390 LOG(4, 0, 0, "Walled garden packet to master (size %d)\n", size);
391
392 add_type(&p, C_GARDEN, s, data, size);
393
394 return peer_send_data(config->cluster_master_address, buf, (p-buf));
395
396 }
397
398 //
399 // Forward a MPPP packet to the master for handling.
400 //
401 // (Note that this must be called with the tun header
402 // as the start of the data).
403 // (i.e. this routine writes to data[-8]).
404 int master_forward_mppp_packet(sessionidt s, uint8_t *data, int size)
405 {
406 uint8_t *p = data - (2 * sizeof(uint32_t));
407 uint8_t *psave = p;
408
409 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
410 return -1;
411
412 LOG(4, 0, 0, "Forward MPPP packet to master (size %d)\n", size);
413
414 add_type(&p, C_MPPP_FORWARD, s, NULL, 0);
415
416 return peer_send_data(config->cluster_master_address, psave, size + (2 * sizeof(uint32_t)));
417
418 }
419
420 //
421 // Send a chunk of data as a heartbeat..
422 // We save it in the history buffer as we do so.
423 //
424 static void send_heartbeat(int seq, uint8_t *data, int size)
425 {
426 int i;
427
428 if (size > sizeof(past_hearts[0].data))
429 {
430 LOG(0, 0, 0, "Tried to heartbeat something larger than the maximum packet!\n");
431 kill(0, SIGTERM);
432 exit(1);
433 }
434 i = seq % HB_HISTORY_SIZE;
435 past_hearts[i].seq = seq;
436 past_hearts[i].size = size;
437 memcpy(&past_hearts[i].data, data, size); // Save it.
438 cluster_send_data(data, size);
439 }
440
441 //
442 // Send an 'i am alive' message to every machine in the cluster.
443 //
444 void cluster_send_ping(time_t basetime)
445 {
446 uint8_t buff[100 + sizeof(pingt)];
447 uint8_t *p = buff;
448 pingt x;
449
450 if (config->cluster_iam_master && basetime) // We're heartbeating so no need to ping.
451 return;
452
453 LOG(5, 0, 0, "Sending cluster ping...\n");
454
455 x.ver = 1;
456 x.addr = config->bind_address;
457 x.undef = config->cluster_undefined_sessions + config->cluster_undefined_tunnels + config->cluster_undefined_bundles;
458 x.basetime = basetime;
459
460 add_type(&p, C_PING, basetime, (uint8_t *) &x, sizeof(x));
461 cluster_send_data(buff, (p-buff) );
462 }
463
464 //
465 // Walk the session counters looking for non-zero ones to send
466 // to the master. We send up to 600 of them at one time.
467 // We examine a maximum of 3000 sessions.
468 // (50k max session should mean that we normally
469 // examine the entire session table every 25 seconds).
470
471 #define MAX_B_RECS (600)
472 void master_update_counts(void)
473 {
474 int i, c;
475 bytest b[MAX_B_RECS+1];
476
477 if (config->cluster_iam_master) // Only happens on the slaves.
478 return;
479
480 if (!config->cluster_master_address) // If we don't have a master, skip it for a while.
481 return;
482
483 i = MAX_B_RECS * 5; // Examine max 3000 sessions;
484 if (config->cluster_highest_sessionid > i)
485 i = config->cluster_highest_sessionid;
486
487 for ( c = 0; i > 0 ; --i) {
488 // Next session to look at.
489 walk_session_number++;
490 if ( walk_session_number > config->cluster_highest_sessionid)
491 walk_session_number = 1;
492
493 if (!sess_local[walk_session_number].cin && !sess_local[walk_session_number].cout)
494 continue; // Unchanged. Skip it.
495
496 b[c].sid = walk_session_number;
497 b[c].pin = sess_local[walk_session_number].pin;
498 b[c].pout = sess_local[walk_session_number].pout;
499 b[c].cin = sess_local[walk_session_number].cin;
500 b[c].cout = sess_local[walk_session_number].cout;
501
502 // Reset counters.
503 sess_local[walk_session_number].pin = sess_local[walk_session_number].pout = 0;
504 sess_local[walk_session_number].cin = sess_local[walk_session_number].cout = 0;
505
506 if (++c > MAX_B_RECS) // Send a max of 600 elements in a packet.
507 break;
508 }
509
510 if (!c) // Didn't find any that changes. Get out of here!
511 return;
512
513
514 // Forward the data to the master.
515 LOG(4, 0, 0, "Sending byte counters to master (%d elements)\n", c);
516 peer_send_message(config->cluster_master_address, C_BYTES, c, (uint8_t *) &b, sizeof(b[0]) * c);
517 return;
518 }
519
520 //
521 // On the master, check how our slaves are going. If
522 // one of them's not up-to-date we'll heartbeat faster.
523 // If we don't have any of them, then we need to turn
524 // on our own packet handling!
525 //
526 void cluster_check_slaves(void)
527 {
528 int i;
529 static int have_peers = 0;
530 int had_peers = have_peers;
531 clockt t = TIME;
532
533 if (!config->cluster_iam_master)
534 return; // Only runs on the master...
535
536 config->cluster_iam_uptodate = 1; // cleared in loop below
537
538 for (i = have_peers = 0; i < num_peers; i++)
539 {
540 if ((peers[i].timestamp + config->cluster_hb_timeout) < t)
541 continue; // Stale peer! Skip them.
542
543 if (!peers[i].basetime)
544 continue; // Shutdown peer! Skip them.
545
546 if (peers[i].uptodate)
547 have_peers++;
548 else
549 config->cluster_iam_uptodate = 0; // Start fast heartbeats
550 }
551
552 // in a cluster, withdraw/add routes when we get a peer/lose peers
553 if (have_peers != had_peers)
554 {
555 if (had_peers < config->cluster_master_min_adv &&
556 have_peers >= config->cluster_master_min_adv)
557 withdraw_routes();
558
559 else if (had_peers >= config->cluster_master_min_adv &&
560 have_peers < config->cluster_master_min_adv)
561 advertise_routes();
562 }
563 }
564
565 //
566 // Check that we have a master. If it's been too
567 // long since we heard from a master then hold an election.
568 //
569 void cluster_check_master(void)
570 {
571 int i, count, high_unique_id = 0;
572 int last_free = 0;
573 clockt t = TIME;
574 static int probed = 0;
575 int have_peers;
576
577 if (config->cluster_iam_master)
578 return; // Only runs on the slaves...
579
580 // If the master is late (missed 2 hearbeats by a second and a
581 // hair) it may be that the switch has dropped us from the
582 // multicast group, try unicasting probes to the master
583 // which will hopefully respond with a unicast heartbeat that
584 // will allow us to limp along until the querier next runs.
585 if (config->cluster_master_address
586 && TIME > (config->cluster_last_hb + 2 * config->cluster_hb_interval + 11))
587 {
588 if (!probed || (TIME > (probed + 2 * config->cluster_hb_interval)))
589 {
590 probed = TIME;
591 LOG(1, 0, 0, "Heartbeat from master %.1fs late, probing...\n",
592 0.1 * (TIME - (config->cluster_last_hb + config->cluster_hb_interval)));
593
594 peer_send_message(config->cluster_master_address,
595 C_LASTSEEN, config->cluster_seq_number, NULL, 0);
596 }
597 } else { // We got a recent heartbeat; reset the probe flag.
598 probed = 0;
599 }
600
601 if (TIME < (config->cluster_last_hb + config->cluster_hb_timeout))
602 return; // Everything's ok!
603
604 config->cluster_last_hb = TIME + 1; // Just the one election thanks.
605 config->cluster_master_address = 0;
606
607 LOG(0, 0, 0, "Master timed out! Holding election...\n");
608
609 // In the process of shutting down, can't be master
610 if (main_quit)
611 return;
612
613 for (i = have_peers = 0; i < num_peers; i++)
614 {
615 if ((peers[i].timestamp + config->cluster_hb_timeout) < t)
616 continue; // Stale peer! Skip them.
617
618 if (!peers[i].basetime)
619 continue; // Shutdown peer! Skip them.
620
621 if (peers[i].basetime < basetime) {
622 LOG(1, 0, 0, "Expecting %s to become master\n", fmtaddr(peers[i].peer, 0));
623 return; // They'll win the election. Get out of here.
624 }
625
626 if (peers[i].basetime == basetime &&
627 peers[i].peer > my_address) {
628 LOG(1, 0, 0, "Expecting %s to become master\n", fmtaddr(peers[i].peer, 0));
629 return; // They'll win the election. Wait for them to come up.
630 }
631
632 if (peers[i].uptodate)
633 have_peers++;
634 }
635
636 // Wow. it's been ages since I last heard a heartbeat
637 // and I'm better than an of my peers so it's time
638 // to become a master!!!
639
640 config->cluster_iam_master = 1;
641 pppoe_send_garp(); // gratuitous arp of the pppoe interface
642
643 LOG(0, 0, 0, "I am declaring myself the master!\n");
644
645 if (have_peers < config->cluster_master_min_adv)
646 advertise_routes();
647 else
648 withdraw_routes();
649
650 if (config->cluster_seq_number == -1)
651 config->cluster_seq_number = 0;
652
653 //
654 // Go through and mark all the tunnels as defined.
655 // Count the highest used tunnel number as well.
656 //
657 config->cluster_highest_tunnelid = 0;
658 for (i = 0; i < MAXTUNNEL; ++i) {
659 if (tunnel[i].state == TUNNELUNDEF)
660 tunnel[i].state = TUNNELFREE;
661
662 if (tunnel[i].state != TUNNELFREE && i > config->cluster_highest_tunnelid)
663 config->cluster_highest_tunnelid = i;
664 }
665
666 //
667 // Go through and mark all the bundles as defined.
668 // Count the highest used bundle number as well.
669 //
670 config->cluster_highest_bundleid = 0;
671 for (i = 0; i < MAXBUNDLE; ++i) {
672 if (bundle[i].state == BUNDLEUNDEF)
673 bundle[i].state = BUNDLEFREE;
674
675 if (bundle[i].state != BUNDLEFREE && i > config->cluster_highest_bundleid)
676 config->cluster_highest_bundleid = i;
677 }
678
679 //
680 // Go through and mark all the sessions as being defined.
681 // reset the idle timeouts.
682 // add temporary byte counters to permanent ones.
683 // Re-string the free list.
684 // Find the ID of the highest session.
685 last_free = 0;
686 high_unique_id = 0;
687 config->cluster_highest_sessionid = 0;
688 for (i = 0, count = 0; i < MAXSESSION; ++i) {
689 if (session[i].tunnel == T_UNDEF) {
690 session[i].tunnel = T_FREE;
691 ++count;
692 }
693
694 if (!session[i].opened) { // Unused session. Add to free list.
695 memset(&session[i], 0, sizeof(session[i]));
696 session[i].tunnel = T_FREE;
697 session[last_free].next = i;
698 session[i].next = 0;
699 last_free = i;
700 continue;
701 }
702
703 // Reset idle timeouts..
704 session[i].last_packet = session[i].last_data = time_now;
705
706 // Reset die relative to our uptime rather than the old master's
707 if (session[i].die) session[i].die = TIME;
708
709 // Accumulate un-sent byte/packet counters.
710 increment_counter(&session[i].cin, &session[i].cin_wrap, sess_local[i].cin);
711 increment_counter(&session[i].cout, &session[i].cout_wrap, sess_local[i].cout);
712 session[i].cin_delta += sess_local[i].cin;
713 session[i].cout_delta += sess_local[i].cout;
714
715 session[i].pin += sess_local[i].pin;
716 session[i].pout += sess_local[i].pout;
717
718 sess_local[i].cin = sess_local[i].cout = 0;
719 sess_local[i].pin = sess_local[i].pout = 0;
720
721 sess_local[i].radius = 0; // Reset authentication as the radius blocks aren't up to date.
722
723 if (session[i].unique_id >= high_unique_id) // This is different to the index into the session table!!!
724 high_unique_id = session[i].unique_id+1;
725
726 session[i].tbf_in = session[i].tbf_out = 0; // Remove stale pointers from old master.
727 throttle_session(i, session[i].throttle_in, session[i].throttle_out);
728
729 config->cluster_highest_sessionid = i;
730 }
731
732 session[last_free].next = 0; // End of chain.
733 last_id = high_unique_id; // Keep track of the highest used session ID.
734
735 become_master();
736
737 rebuild_address_pool();
738
739 // If we're not the very first master, this is a big issue!
740 if (count > 0)
741 LOG(0, 0, 0, "Warning: Fixed %d uninitialized sessions in becoming master!\n", count);
742
743 config->cluster_undefined_sessions = 0;
744 config->cluster_undefined_bundles = 0;
745 config->cluster_undefined_tunnels = 0;
746 config->cluster_iam_uptodate = 1; // assume all peers are up-to-date
747
748 // FIXME. We need to fix up the tunnel control message
749 // queue here! There's a number of other variables we
750 // should also update.
751 }
752
753
754 //
755 // Check that our session table is validly matching what the
756 // master has in mind.
757 //
758 // In particular, if we have too many sessions marked 'undefined'
759 // we fix it up here, and we ensure that the 'first free session'
760 // pointer is valid.
761 //
762 static void cluster_check_sessions(int highsession, int freesession_ptr, int highbundle, int hightunnel)
763 {
764 int i;
765
766 sessionfree = freesession_ptr; // Keep the freesession ptr valid.
767
768 if (config->cluster_iam_uptodate)
769 return;
770
771 if (highsession > config->cluster_undefined_sessions && highbundle > config->cluster_undefined_bundles && hightunnel > config->cluster_undefined_tunnels)
772 return;
773
774 // Clear out defined sessions, counting the number of
775 // undefs remaining.
776 config->cluster_undefined_sessions = 0;
777 for (i = 1 ; i < MAXSESSION; ++i) {
778 if (i > highsession) {
779 if (session[i].tunnel == T_UNDEF) session[i].tunnel = T_FREE; // Defined.
780 continue;
781 }
782
783 if (session[i].tunnel == T_UNDEF)
784 ++config->cluster_undefined_sessions;
785 }
786
787 // Clear out defined bundles, counting the number of
788 // undefs remaining.
789 config->cluster_undefined_bundles = 0;
790 for (i = 1 ; i < MAXBUNDLE; ++i) {
791 if (i > highbundle) {
792 if (bundle[i].state == BUNDLEUNDEF) bundle[i].state = BUNDLEFREE; // Defined.
793 continue;
794 }
795
796 if (bundle[i].state == BUNDLEUNDEF)
797 ++config->cluster_undefined_bundles;
798 }
799
800 // Clear out defined tunnels, counting the number of
801 // undefs remaining.
802 config->cluster_undefined_tunnels = 0;
803 for (i = 1 ; i < MAXTUNNEL; ++i) {
804 if (i > hightunnel) {
805 if (tunnel[i].state == TUNNELUNDEF) tunnel[i].state = TUNNELFREE; // Defined.
806 continue;
807 }
808
809 if (tunnel[i].state == TUNNELUNDEF)
810 ++config->cluster_undefined_tunnels;
811 }
812
813
814 if (config->cluster_undefined_sessions || config->cluster_undefined_tunnels || config->cluster_undefined_bundles) {
815 LOG(2, 0, 0, "Cleared undefined sessions/bundles/tunnels. %d sess (high %d), %d bund (high %d), %d tunn (high %d)\n",
816 config->cluster_undefined_sessions, highsession, config->cluster_undefined_bundles, highbundle, config->cluster_undefined_tunnels, hightunnel);
817 return;
818 }
819
820 // Are we up to date?
821
822 if (!config->cluster_iam_uptodate)
823 cluster_uptodate();
824 }
825
826 static int hb_add_type(uint8_t **p, int type, int id)
827 {
828 switch (type) {
829 case C_CSESSION: { // Compressed C_SESSION.
830 uint8_t c[sizeof(sessiont) * 2]; // Bigger than worst case.
831 uint8_t *d = (uint8_t *) &session[id];
832 uint8_t *orig = d;
833 int size;
834
835 size = rle_compress( &d, sizeof(sessiont), c, sizeof(c) );
836
837 // Did we compress the full structure, and is the size actually
838 // reduced??
839 if ( (d - orig) == sizeof(sessiont) && size < sizeof(sessiont) ) {
840 add_type(p, C_CSESSION, id, c, size);
841 break;
842 }
843 // Failed to compress : Fall through.
844 }
845 case C_SESSION:
846 add_type(p, C_SESSION, id, (uint8_t *) &session[id], sizeof(sessiont));
847 break;
848
849 case C_CBUNDLE: { // Compressed C_BUNDLE
850 uint8_t c[sizeof(bundlet) * 2]; // Bigger than worst case.
851 uint8_t *d = (uint8_t *) &bundle[id];
852 uint8_t *orig = d;
853 int size;
854
855 size = rle_compress( &d, sizeof(bundlet), c, sizeof(c) );
856
857 // Did we compress the full structure, and is the size actually
858 // reduced??
859 if ( (d - orig) == sizeof(bundlet) && size < sizeof(bundlet) ) {
860 add_type(p, C_CBUNDLE, id, c, size);
861 break;
862 }
863 // Failed to compress : Fall through.
864 }
865
866 case C_BUNDLE:
867 add_type(p, C_BUNDLE, id, (uint8_t *) &bundle[id], sizeof(bundlet));
868 break;
869
870 case C_CTUNNEL: { // Compressed C_TUNNEL
871 uint8_t c[sizeof(tunnelt) * 2]; // Bigger than worst case.
872 uint8_t *d = (uint8_t *) &tunnel[id];
873 uint8_t *orig = d;
874 int size;
875
876 size = rle_compress( &d, sizeof(tunnelt), c, sizeof(c) );
877
878 // Did we compress the full structure, and is the size actually
879 // reduced??
880 if ( (d - orig) == sizeof(tunnelt) && size < sizeof(tunnelt) ) {
881 add_type(p, C_CTUNNEL, id, c, size);
882 break;
883 }
884 // Failed to compress : Fall through.
885 }
886 case C_TUNNEL:
887 add_type(p, C_TUNNEL, id, (uint8_t *) &tunnel[id], sizeof(tunnelt));
888 break;
889 default:
890 LOG(0, 0, 0, "Found an invalid type in heart queue! (%d)\n", type);
891 kill(0, SIGTERM);
892 exit(1);
893 }
894 return 0;
895 }
896
897 //
898 // Send a heartbeat, incidently sending out any queued changes..
899 //
900 void cluster_heartbeat()
901 {
902 int i, count = 0, tcount = 0, bcount = 0;
903 uint8_t buff[MAX_HEART_SIZE + sizeof(heartt) + sizeof(int) ];
904 heartt h;
905 uint8_t *p = buff;
906
907 if (!config->cluster_iam_master) // Only the master does this.
908 return;
909
910 config->cluster_table_version += config->cluster_num_changes;
911
912 // Fill out the heartbeat header.
913 memset(&h, 0, sizeof(h));
914
915 h.version = HB_VERSION;
916 h.seq = config->cluster_seq_number;
917 h.basetime = basetime;
918 h.clusterid = config->bind_address; // Will this do??
919 h.basetime = basetime;
920 h.highsession = config->cluster_highest_sessionid;
921 h.freesession = sessionfree;
922 h.hightunnel = config->cluster_highest_tunnelid;
923 h.highbundle = config->cluster_highest_bundleid;
924 h.size_sess = sizeof(sessiont); // Just in case.
925 h.size_bund = sizeof(bundlet);
926 h.size_tunn = sizeof(tunnelt);
927 h.interval = config->cluster_hb_interval;
928 h.timeout = config->cluster_hb_timeout;
929 h.table_version = config->cluster_table_version;
930
931 add_type(&p, C_HEARTBEAT, HB_VERSION, (uint8_t *) &h, sizeof(h));
932
933 for (i = 0; i < config->cluster_num_changes; ++i) {
934 hb_add_type(&p, cluster_changes[i].type, cluster_changes[i].id);
935 }
936
937 if (p > (buff + sizeof(buff))) { // Did we somehow manage to overun the buffer?
938 LOG(0, 0, 0, "FATAL: Overran the heartbeat buffer! This is fatal. Exiting. (size %d)\n", (int) (p - buff));
939 kill(0, SIGTERM);
940 exit(1);
941 }
942
943 //
944 // Fill out the packet with sessions from the session table...
945 // (not forgetting to leave space so we can get some tunnels in too )
946 while ( (p + sizeof(uint32_t) * 2 + sizeof(sessiont) * 2 ) < (buff + MAX_HEART_SIZE) ) {
947
948 if (!walk_session_number) // session #0 isn't valid.
949 ++walk_session_number;
950
951 if (count >= config->cluster_highest_sessionid) // If we're a small cluster, don't go wild.
952 break;
953
954 hb_add_type(&p, C_CSESSION, walk_session_number);
955 walk_session_number = (1+walk_session_number)%(config->cluster_highest_sessionid+1); // +1 avoids divide by zero.
956
957 ++count; // Count the number of extra sessions we're sending.
958 }
959
960 //
961 // Fill out the packet with tunnels from the tunnel table...
962 // This effectively means we walk the tunnel table more quickly
963 // than the session table. This is good because stuffing up a
964 // tunnel is a much bigger deal than stuffing up a session.
965 //
966 while ( (p + sizeof(uint32_t) * 2 + sizeof(tunnelt) ) < (buff + MAX_HEART_SIZE) ) {
967
968 if (!walk_tunnel_number) // tunnel #0 isn't valid.
969 ++walk_tunnel_number;
970
971 if (tcount >= config->cluster_highest_tunnelid)
972 break;
973
974 hb_add_type(&p, C_CTUNNEL, walk_tunnel_number);
975 walk_tunnel_number = (1+walk_tunnel_number)%(config->cluster_highest_tunnelid+1); // +1 avoids divide by zero.
976
977 ++tcount;
978 }
979
980 //
981 // Fill out the packet with bundles from the bundle table...
982 while ( (p + sizeof(uint32_t) * 2 + sizeof(bundlet) ) < (buff + MAX_HEART_SIZE) ) {
983
984 if (!walk_bundle_number) // bundle #0 isn't valid.
985 ++walk_bundle_number;
986
987 if (bcount >= config->cluster_highest_bundleid)
988 break;
989
990 hb_add_type(&p, C_CBUNDLE, walk_bundle_number);
991 walk_bundle_number = (1+walk_bundle_number)%(config->cluster_highest_bundleid+1); // +1 avoids divide by zero.
992 ++bcount;
993 }
994
995 //
996 // Did we do something wrong?
997 if (p > (buff + sizeof(buff))) { // Did we somehow manage to overun the buffer?
998 LOG(0, 0, 0, "Overran the heartbeat buffer now! This is fatal. Exiting. (size %d)\n", (int) (p - buff));
999 kill(0, SIGTERM);
1000 exit(1);
1001 }
1002
1003 LOG(4, 0, 0, "Sending v%d heartbeat #%d, change #%" PRIu64 " with %d changes "
1004 "(%d x-sess, %d x-bundles, %d x-tunnels, %d highsess, %d highbund, %d hightun, size %d)\n",
1005 HB_VERSION, h.seq, h.table_version, config->cluster_num_changes,
1006 count, bcount, tcount, config->cluster_highest_sessionid, config->cluster_highest_bundleid,
1007 config->cluster_highest_tunnelid, (int) (p - buff));
1008
1009 config->cluster_num_changes = 0;
1010
1011 send_heartbeat(h.seq, buff, (p-buff) ); // Send out the heartbeat to the cluster, keeping a copy of it.
1012
1013 config->cluster_seq_number = (config->cluster_seq_number+1)%HB_MAX_SEQ; // Next seq number to use.
1014 }
1015
1016 //
1017 // A structure of type 'type' has changed; Add it to the queue to send.
1018 //
1019 static int type_changed(int type, int id)
1020 {
1021 int i;
1022
1023 for (i = 0 ; i < config->cluster_num_changes ; ++i)
1024 {
1025 if ( cluster_changes[i].id == id && cluster_changes[i].type == type)
1026 {
1027 // Already marked for change, remove it
1028 --config->cluster_num_changes;
1029 memmove(&cluster_changes[i],
1030 &cluster_changes[i+1],
1031 (config->cluster_num_changes - i) * sizeof(cluster_changes[i]));
1032 break;
1033 }
1034 }
1035
1036 cluster_changes[config->cluster_num_changes].type = type;
1037 cluster_changes[config->cluster_num_changes].id = id;
1038 ++config->cluster_num_changes;
1039
1040 if (config->cluster_num_changes > MAX_CHANGES)
1041 cluster_heartbeat(); // flush now
1042
1043 return 1;
1044 }
1045
1046 // A particular session has been changed!
1047 int cluster_send_session(int sid)
1048 {
1049 if (!config->cluster_iam_master) {
1050 LOG(0, sid, 0, "I'm not a master, but I just tried to change a session!\n");
1051 return -1;
1052 }
1053
1054 if (forked) {
1055 LOG(0, sid, 0, "cluster_send_session called from child process!\n");
1056 return -1;
1057 }
1058
1059 return type_changed(C_CSESSION, sid);
1060 }
1061
1062 // A particular bundle has been changed!
1063 int cluster_send_bundle(int bid)
1064 {
1065 if (!config->cluster_iam_master) {
1066 LOG(0, 0, bid, "I'm not a master, but I just tried to change a bundle!\n");
1067 return -1;
1068 }
1069
1070 return type_changed(C_CBUNDLE, bid);
1071 }
1072
1073 // A particular tunnel has been changed!
1074 int cluster_send_tunnel(int tid)
1075 {
1076 if (!config->cluster_iam_master) {
1077 LOG(0, 0, tid, "I'm not a master, but I just tried to change a tunnel!\n");
1078 return -1;
1079 }
1080
1081 return type_changed(C_CTUNNEL, tid);
1082 }
1083
1084
1085 //
1086 // We're a master, and a slave has just told us that it's
1087 // missed a packet. We'll resend it every packet since
1088 // the last one it's seen.
1089 //
1090 static int cluster_catchup_slave(int seq, in_addr_t slave)
1091 {
1092 int s;
1093 int diff;
1094
1095 LOG(1, 0, 0, "Slave %s sent LASTSEEN with seq %d\n", fmtaddr(slave, 0), seq);
1096 if (!config->cluster_iam_master) {
1097 LOG(1, 0, 0, "Got LASTSEEN but I'm not a master! Redirecting it to %s.\n",
1098 fmtaddr(config->cluster_master_address, 0));
1099
1100 peer_send_message(slave, C_MASTER, config->cluster_master_address, NULL, 0);
1101 return 0;
1102 }
1103
1104 diff = config->cluster_seq_number - seq; // How many packet do we need to send?
1105 if (diff < 0)
1106 diff += HB_MAX_SEQ;
1107
1108 if (diff >= HB_HISTORY_SIZE) { // Ouch. We don't have the packet to send it!
1109 LOG(0, 0, 0, "A slave asked for message %d when our seq number is %d. Killing it.\n",
1110 seq, config->cluster_seq_number);
1111 return peer_send_message(slave, C_KILL, seq, NULL, 0);// Kill the slave. Nothing else to do.
1112 }
1113
1114 LOG(1, 0, 0, "Sending %d catchup packets to slave %s\n", diff, fmtaddr(slave, 0) );
1115
1116 // Now resend every packet that it missed, in order.
1117 while (seq != config->cluster_seq_number) {
1118 s = seq % HB_HISTORY_SIZE;
1119 if (seq != past_hearts[s].seq) {
1120 LOG(0, 0, 0, "Tried to re-send heartbeat for %s but %d doesn't match %d! (%d,%d)\n",
1121 fmtaddr(slave, 0), seq, past_hearts[s].seq, s, config->cluster_seq_number);
1122 return -1; // What to do here!?
1123 }
1124 peer_send_data(slave, past_hearts[s].data, past_hearts[s].size);
1125 seq = (seq+1)%HB_MAX_SEQ; // Increment to next seq number.
1126 }
1127 return 0; // All good!
1128 }
1129
1130 //
1131 // We've heard from another peer! Add it to the list
1132 // that we select from at election time.
1133 //
1134 static int cluster_add_peer(in_addr_t peer, time_t basetime, pingt *pp, int size)
1135 {
1136 int i;
1137 in_addr_t clusterid;
1138 pingt p;
1139
1140 // Allow for backward compatability.
1141 // Just the ping packet into a new structure to allow
1142 // for the possibility that we might have received
1143 // more or fewer elements than we were expecting.
1144 if (size > sizeof(p))
1145 size = sizeof(p);
1146
1147 memset( (void *) &p, 0, sizeof(p) );
1148 memcpy( (void *) &p, (void *) pp, size);
1149
1150 clusterid = p.addr;
1151 if (clusterid != config->bind_address)
1152 {
1153 // Is this for us?
1154 LOG(4, 0, 0, "Skipping ping from %s (different cluster)\n", fmtaddr(peer, 0));
1155 return 0;
1156 }
1157
1158 for (i = 0; i < num_peers ; ++i)
1159 {
1160 if (peers[i].peer != peer)
1161 continue;
1162
1163 // This peer already exists. Just update the timestamp.
1164 peers[i].basetime = basetime;
1165 peers[i].timestamp = TIME;
1166 peers[i].uptodate = !p.undef;
1167 break;
1168 }
1169
1170 // Is this the master shutting down??
1171 if (peer == config->cluster_master_address) {
1172 LOG(3, 0, 0, "Master %s %s\n", fmtaddr(config->cluster_master_address, 0),
1173 basetime ? "has restarted!" : "shutting down...");
1174
1175 config->cluster_master_address = 0;
1176 config->cluster_last_hb = 0; // Force an election.
1177 cluster_check_master();
1178 }
1179
1180 if (i >= num_peers)
1181 {
1182 LOG(4, 0, 0, "Adding %s as a peer\n", fmtaddr(peer, 0));
1183
1184 // Not found. Is there a stale slot to re-use?
1185 for (i = 0; i < num_peers ; ++i)
1186 {
1187 if (!peers[i].basetime) // Shutdown
1188 break;
1189
1190 if ((peers[i].timestamp + config->cluster_hb_timeout * 10) < TIME) // Stale.
1191 break;
1192 }
1193
1194 if (i >= CLUSTER_MAX_SIZE)
1195 {
1196 // Too many peers!!
1197 LOG(0, 0, 0, "Tried to add %s as a peer, but I already have %d of them!\n", fmtaddr(peer, 0), i);
1198 return -1;
1199 }
1200
1201 peers[i].peer = peer;
1202 peers[i].basetime = basetime;
1203 peers[i].timestamp = TIME;
1204 peers[i].uptodate = !p.undef;
1205 if (i == num_peers)
1206 ++num_peers;
1207
1208 LOG(1, 0, 0, "Added %s as a new peer. Now %d peers\n", fmtaddr(peer, 0), num_peers);
1209 }
1210
1211 return 1;
1212 }
1213
1214 // A slave responds with C_MASTER when it gets a message which should have gone to a master.
1215 static int cluster_set_master(in_addr_t peer, in_addr_t master)
1216 {
1217 if (config->cluster_iam_master) // Sanity...
1218 return 0;
1219
1220 LOG(3, 0, 0, "Peer %s set the master to %s...\n", fmtaddr(peer, 0),
1221 fmtaddr(master, 1));
1222
1223 config->cluster_master_address = master;
1224 if (master)
1225 {
1226 // catchup with new master
1227 peer_send_message(master, C_LASTSEEN, config->cluster_seq_number, NULL, 0);
1228
1229 // delay next election
1230 config->cluster_last_hb = TIME;
1231 }
1232
1233 // run election (or reset "probed" if master was set)
1234 cluster_check_master();
1235 return 0;
1236 }
1237
1238 /* Handle the slave updating the byte counters for the master. */
1239 //
1240 // Note that we don't mark the session as dirty; We rely on
1241 // the slow table walk to propogate this back out to the slaves.
1242 //
1243 static int cluster_handle_bytes(uint8_t *data, int size)
1244 {
1245 bytest *b;
1246
1247 b = (bytest *) data;
1248
1249 LOG(3, 0, 0, "Got byte counter update (size %d)\n", size);
1250
1251 /* Loop around, adding the byte
1252 counts to each of the sessions. */
1253
1254 while (size >= sizeof(*b) ) {
1255 if (b->sid > MAXSESSION) {
1256 LOG(0, 0, 0, "Got C_BYTES with session #%d!\n", b->sid);
1257 return -1; /* Abort processing */
1258 }
1259
1260 session[b->sid].pin += b->pin;
1261 session[b->sid].pout += b->pout;
1262
1263 increment_counter(&session[b->sid].cin, &session[b->sid].cin_wrap, b->cin);
1264 increment_counter(&session[b->sid].cout, &session[b->sid].cout_wrap, b->cout);
1265
1266 session[b->sid].cin_delta += b->cin;
1267 session[b->sid].cout_delta += b->cout;
1268
1269 if (b->cin)
1270 session[b->sid].last_packet = session[b->sid].last_data = time_now;
1271 else if (b->cout)
1272 session[b->sid].last_data = time_now;
1273
1274 size -= sizeof(*b);
1275 ++b;
1276 }
1277
1278 if (size != 0)
1279 LOG(0, 0, 0, "Got C_BYTES with %d bytes of trailing junk!\n", size);
1280
1281 return size;
1282 }
1283
1284 //
1285 // Handle receiving a session structure in a heartbeat packet.
1286 //
1287 static int cluster_recv_session(int more, uint8_t *p)
1288 {
1289 if (more >= MAXSESSION) {
1290 LOG(0, 0, 0, "DANGER: Received a heartbeat session id > MAXSESSION!\n");
1291 return -1;
1292 }
1293
1294 if (session[more].tunnel == T_UNDEF) {
1295 if (config->cluster_iam_uptodate) { // Sanity.
1296 LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined session!\n");
1297 } else {
1298 --config->cluster_undefined_sessions;
1299 }
1300 }
1301
1302 load_session(more, (sessiont *) p); // Copy session into session table..
1303
1304 LOG(5, more, 0, "Received session update (%d undef)\n", config->cluster_undefined_sessions);
1305
1306 if (!config->cluster_iam_uptodate)
1307 cluster_uptodate(); // Check to see if we're up to date.
1308
1309 return 0;
1310 }
1311
1312 static int cluster_recv_bundle(int more, uint8_t *p)
1313 {
1314 if (more >= MAXBUNDLE) {
1315 LOG(0, 0, 0, "DANGER: Received a bundle id > MAXBUNDLE!\n");
1316 return -1;
1317 }
1318
1319 if (bundle[more].state == BUNDLEUNDEF) {
1320 if (config->cluster_iam_uptodate) { // Sanity.
1321 LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined bundle!\n");
1322 } else {
1323 --config->cluster_undefined_bundles;
1324 }
1325 }
1326
1327 memcpy(&bundle[more], p, sizeof(bundle[more]) );
1328
1329 LOG(5, 0, more, "Received bundle update\n");
1330
1331 if (!config->cluster_iam_uptodate)
1332 cluster_uptodate(); // Check to see if we're up to date.
1333
1334 return 0;
1335 }
1336
1337 static int cluster_recv_tunnel(int more, uint8_t *p)
1338 {
1339 if (more >= MAXTUNNEL) {
1340 LOG(0, 0, 0, "DANGER: Received a tunnel session id > MAXTUNNEL!\n");
1341 return -1;
1342 }
1343
1344 if (tunnel[more].state == TUNNELUNDEF) {
1345 if (config->cluster_iam_uptodate) { // Sanity.
1346 LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined tunnel!\n");
1347 } else {
1348 --config->cluster_undefined_tunnels;
1349 }
1350 }
1351
1352 memcpy(&tunnel[more], p, sizeof(tunnel[more]) );
1353
1354 //
1355 // Clear tunnel control messages. These are dynamically allocated.
1356 // If we get unlucky, this may cause the tunnel to drop!
1357 //
1358 tunnel[more].controls = tunnel[more].controle = NULL;
1359 tunnel[more].controlc = 0;
1360
1361 LOG(5, 0, more, "Received tunnel update\n");
1362
1363 if (!config->cluster_iam_uptodate)
1364 cluster_uptodate(); // Check to see if we're up to date.
1365
1366 return 0;
1367 }
1368
1369
1370 // pre v6 heartbeat session structure
1371 struct oldsession {
1372 sessionidt next;
1373 sessionidt far;
1374 tunnelidt tunnel;
1375 uint8_t flags;
1376 struct {
1377 uint8_t phase;
1378 uint8_t lcp:4;
1379 uint8_t ipcp:4;
1380 uint8_t ipv6cp:4;
1381 uint8_t ccp:4;
1382 } ppp;
1383 char reserved_1[2];
1384 in_addr_t ip;
1385 int ip_pool_index;
1386 uint32_t unique_id;
1387 char reserved_2[4];
1388 uint32_t magic;
1389 uint32_t pin, pout;
1390 uint32_t cin, cout;
1391 uint32_t cin_wrap, cout_wrap;
1392 uint32_t cin_delta, cout_delta;
1393 uint16_t throttle_in;
1394 uint16_t throttle_out;
1395 uint8_t filter_in;
1396 uint8_t filter_out;
1397 uint16_t mru;
1398 clockt opened;
1399 clockt die;
1400 uint32_t session_timeout;
1401 uint32_t idle_timeout;
1402 time_t last_packet;
1403 time_t last_data;
1404 in_addr_t dns1, dns2;
1405 routet route[MAXROUTE];
1406 uint16_t tbf_in;
1407 uint16_t tbf_out;
1408 int random_vector_length;
1409 uint8_t random_vector[MAXTEL];
1410 char user[MAXUSER];
1411 char called[MAXTEL];
1412 char calling[MAXTEL];
1413 uint32_t tx_connect_speed;
1414 uint32_t rx_connect_speed;
1415 clockt timeout;
1416 uint32_t mrru;
1417 uint8_t mssf;
1418 epdist epdis;
1419 bundleidt bundle;
1420 in_addr_t snoop_ip;
1421 uint16_t snoop_port;
1422 uint8_t walled_garden;
1423 uint8_t ipv6prefixlen;
1424 struct in6_addr ipv6route;
1425 char reserved_3[11];
1426 };
1427
1428 struct oldsessionV7 {
1429 sessionidt next; // next session in linked list
1430 sessionidt far; // far end session ID
1431 tunnelidt tunnel; // near end tunnel ID
1432 uint8_t flags; // session flags: see SESSION_*
1433 struct {
1434 uint8_t phase; // PPP phase
1435 uint8_t lcp:4; // LCP state
1436 uint8_t ipcp:4; // IPCP state
1437 uint8_t ipv6cp:4; // IPV6CP state
1438 uint8_t ccp:4; // CCP state
1439 } ppp;
1440 uint16_t mru; // maximum receive unit
1441 in_addr_t ip; // IP of session set by RADIUS response (host byte order).
1442 int ip_pool_index; // index to IP pool
1443 uint32_t unique_id; // unique session id
1444 uint32_t magic; // ppp magic number
1445 uint32_t pin, pout; // packet counts
1446 uint32_t cin, cout; // byte counts
1447 uint32_t cin_wrap, cout_wrap; // byte counter wrap count (RADIUS accounting giagawords)
1448 uint32_t cin_delta, cout_delta; // byte count changes (for dump_session())
1449 uint16_t throttle_in; // upstream throttle rate (kbps)
1450 uint16_t throttle_out; // downstream throttle rate
1451 uint8_t filter_in; // input filter index (to ip_filters[N-1]; 0 if none)
1452 uint8_t filter_out; // output filter index
1453 uint16_t snoop_port; // Interception destination port
1454 in_addr_t snoop_ip; // Interception destination IP
1455 clockt opened; // when started
1456 clockt die; // being closed, when to finally free
1457 uint32_t session_timeout; // Maximum session time in seconds
1458 uint32_t idle_timeout; // Maximum idle time in seconds
1459 time_t last_packet; // Last packet from the user (used for idle timeouts)
1460 time_t last_data; // Last data packet to/from the user (used for idle timeouts)
1461 in_addr_t dns1, dns2; // DNS servers
1462 routet route[MAXROUTE]; // static routes
1463 uint16_t tbf_in; // filter bucket for throttling in from the user.
1464 uint16_t tbf_out; // filter bucket for throttling out to the user.
1465 int random_vector_length;
1466 uint8_t random_vector[MAXTEL];
1467 char user[MAXUSER]; // user (needed in session for radius stop messages)
1468 char called[MAXTEL]; // called number
1469 char calling[MAXTEL]; // calling number
1470 uint32_t tx_connect_speed;
1471 uint32_t rx_connect_speed;
1472 clockt timeout; // Session timeout
1473 uint32_t mrru; // Multilink Max-Receive-Reconstructed-Unit
1474 epdist epdis; // Multilink Endpoint Discriminator
1475 bundleidt bundle; // Multilink Bundle Identifier
1476 uint8_t mssf; // Multilink Short Sequence Number Header Format
1477 uint8_t walled_garden; // is this session gardened?
1478 uint8_t classlen; // class (needed for radius accounting messages)
1479 char class[MAXCLASS];
1480 uint8_t ipv6prefixlen; // IPv6 route prefix length
1481 struct in6_addr ipv6route; // Static IPv6 route
1482 sessionidt forwardtosession; // LNS id_session to forward
1483 uint8_t src_hwaddr[ETH_ALEN]; // MAC addr source (for pppoe sessions 6 bytes)
1484 char reserved[4]; // Space to expand structure without changing HB_VERSION
1485 };
1486
1487 struct oldsessionV8 {
1488 sessionidt next; // next session in linked list
1489 sessionidt far; // far end session ID
1490 tunnelidt tunnel; // near end tunnel ID
1491 uint8_t flags; // session flags: see SESSION_*
1492 struct {
1493 uint8_t phase; // PPP phase
1494 uint8_t lcp:4; // LCP state
1495 uint8_t ipcp:4; // IPCP state
1496 uint8_t ipv6cp:4; // IPV6CP state
1497 uint8_t ccp:4; // CCP state
1498 } ppp;
1499 uint16_t mru; // maximum receive unit
1500 in_addr_t ip; // IP of session set by RADIUS response (host byte order).
1501 int ip_pool_index; // index to IP pool
1502 uint32_t unique_id; // unique session id
1503 uint32_t magic; // ppp magic number
1504 uint32_t pin, pout; // packet counts
1505 uint32_t cin, cout; // byte counts
1506 uint32_t cin_wrap, cout_wrap; // byte counter wrap count (RADIUS accounting giagawords)
1507 uint32_t cin_delta, cout_delta; // byte count changes (for dump_session())
1508 uint16_t throttle_in; // upstream throttle rate (kbps)
1509 uint16_t throttle_out; // downstream throttle rate
1510 uint8_t filter_in; // input filter index (to ip_filters[N-1]; 0 if none)
1511 uint8_t filter_out; // output filter index
1512 uint16_t snoop_port; // Interception destination port
1513 in_addr_t snoop_ip; // Interception destination IP
1514 clockt opened; // when started
1515 clockt die; // being closed, when to finally free
1516 uint32_t session_timeout; // Maximum session time in seconds
1517 uint32_t idle_timeout; // Maximum idle time in seconds
1518 time_t last_packet; // Last packet from the user (used for idle timeouts)
1519 time_t last_data; // Last data packet to/from the user (used for idle timeouts)
1520 in_addr_t dns1, dns2; // DNS servers
1521 routet route[MAXROUTE]; // static routes
1522 uint16_t tbf_in; // filter bucket for throttling in from the user.
1523 uint16_t tbf_out; // filter bucket for throttling out to the user.
1524 int random_vector_length;
1525 uint8_t random_vector[MAXTEL];
1526 char user[MAXUSER]; // user (needed in session for radius stop messages)
1527 char called[MAXTEL]; // called number
1528 char calling[MAXTEL]; // calling number
1529 uint32_t tx_connect_speed;
1530 uint32_t rx_connect_speed;
1531 clockt timeout; // Session timeout
1532 uint32_t mrru; // Multilink Max-Receive-Reconstructed-Unit
1533 epdist epdis; // Multilink Endpoint Discriminator
1534 bundleidt bundle; // Multilink Bundle Identifier
1535 uint8_t mssf; // Multilink Short Sequence Number Header Format
1536 uint8_t walled_garden; // is this session gardened?
1537 uint8_t classlen; // class (needed for radius accounting messages)
1538 char class[MAXCLASS];
1539 uint8_t ipv6prefixlen; // IPv6 route prefix length
1540 struct in6_addr ipv6route; // Static IPv6 route
1541 sessionidt forwardtosession; // LNS id_session to forward
1542 uint8_t src_hwaddr[ETH_ALEN]; // MAC addr source (for pppoe sessions 6 bytes)
1543 uint32_t dhcpv6_prefix_iaid; // prefix iaid requested by client
1544 uint32_t dhcpv6_iana_iaid; // iaid of iana requested by client
1545 struct in6_addr ipv6address; // Framed Ipv6 address
1546 struct dhcp6_opt_clientid dhcpv6_client_id; // Size max (headers + DUID)
1547 char reserved[4]; // Space to expand structure without changing HB_VERSION
1548 };
1549
1550 static uint8_t *convert_session(struct oldsession *old)
1551 {
1552 static sessiont new;
1553 int i;
1554
1555 memset(&new, 0, sizeof(new));
1556
1557 new.next = old->next;
1558 new.far = old->far;
1559 new.tunnel = old->tunnel;
1560 new.flags = old->flags;
1561 new.ppp.phase = old->ppp.phase;
1562 new.ppp.lcp = old->ppp.lcp;
1563 new.ppp.ipcp = old->ppp.ipcp;
1564 new.ppp.ipv6cp = old->ppp.ipv6cp;
1565 new.ppp.ccp = old->ppp.ccp;
1566 new.ip = old->ip;
1567 new.ip_pool_index = old->ip_pool_index;
1568 new.unique_id = old->unique_id;
1569 new.magic = old->magic;
1570 new.pin = old->pin;
1571 new.pout = old->pout;
1572 new.cin = old->cin;
1573 new.cout = old->cout;
1574 new.cin_wrap = old->cin_wrap;
1575 new.cout_wrap = old->cout_wrap;
1576 new.cin_delta = old->cin_delta;
1577 new.cout_delta = old->cout_delta;
1578 new.throttle_in = old->throttle_in;
1579 new.throttle_out = old->throttle_out;
1580 new.filter_in = old->filter_in;
1581 new.filter_out = old->filter_out;
1582 new.mru = old->mru;
1583 new.opened = old->opened;
1584 new.die = old->die;
1585 new.session_timeout = old->session_timeout;
1586 new.idle_timeout = old->idle_timeout;
1587 new.last_packet = old->last_packet;
1588 new.last_data = old->last_data;
1589 new.dns1 = old->dns1;
1590 new.dns2 = old->dns2;
1591 new.tbf_in = old->tbf_in;
1592 new.tbf_out = old->tbf_out;
1593 new.random_vector_length = old->random_vector_length;
1594 new.tx_connect_speed = old->tx_connect_speed;
1595 new.rx_connect_speed = old->rx_connect_speed;
1596 new.timeout = old->timeout;
1597 new.mrru = old->mrru;
1598 new.mssf = old->mssf;
1599 new.epdis = old->epdis;
1600 new.bundle = old->bundle;
1601 new.snoop_ip = old->snoop_ip;
1602 new.snoop_port = old->snoop_port;
1603 new.walled_garden = old->walled_garden;
1604 new.route6[0].ipv6prefixlen = old->ipv6prefixlen;
1605 new.route6[0].ipv6route = old->ipv6route;
1606
1607 memcpy(new.random_vector, old->random_vector, sizeof(new.random_vector));
1608 memcpy(new.user, old->user, sizeof(new.user));
1609 memcpy(new.called, old->called, sizeof(new.called));
1610 memcpy(new.calling, old->calling, sizeof(new.calling));
1611
1612 for (i = 0; i < MAXROUTE; i++)
1613 memcpy(&new.route[i], &old->route[i], sizeof(new.route[i]));
1614
1615 return (uint8_t *) &new;
1616 }
1617
1618 static uint8_t *convert_sessionV7(struct oldsessionV7 *old)
1619 {
1620 static sessiont new;
1621 int i;
1622
1623 memset(&new, 0, sizeof(new));
1624
1625 new.next = old->next;
1626 new.far = old->far;
1627 new.tunnel = old->tunnel;
1628 new.flags = old->flags;
1629 new.ppp.phase = old->ppp.phase;
1630 new.ppp.lcp = old->ppp.lcp;
1631 new.ppp.ipcp = old->ppp.ipcp;
1632 new.ppp.ipv6cp = old->ppp.ipv6cp;
1633 new.ppp.ccp = old->ppp.ccp;
1634 new.mru = old->mru;
1635 new.ip = old->ip;
1636 new.ip_pool_index = old->ip_pool_index;
1637 new.unique_id = old->unique_id;
1638 new.magic = old->magic;
1639 new.pin = old->pin;
1640 new.pout = old->pout;
1641 new.cin = old->cin;
1642 new.cout = old->cout;
1643 new.cin_wrap = old->cin_wrap;
1644 new.cout_wrap = old->cout_wrap;
1645 new.cin_delta = old->cin_delta;
1646 new.cout_delta = old->cout_delta;
1647 new.throttle_in = old->throttle_in;
1648 new.throttle_out = old->throttle_out;
1649 new.filter_in = old->filter_in;
1650 new.filter_out = old->filter_out;
1651 new.snoop_port = old->snoop_port;
1652 new.snoop_ip = old->snoop_ip;
1653 new.opened = old->opened;
1654 new.die = old->die;
1655 new.session_timeout = old->session_timeout;
1656 new.idle_timeout = old->idle_timeout;
1657 new.last_packet = old->last_packet;
1658 new.last_data = old->last_data;
1659 new.dns1 = old->dns1;
1660 new.dns2 = old->dns2;
1661 for (i = 0; i < MAXROUTE; i++)
1662 memcpy(&new.route[i], &old->route[i], sizeof(new.route[i]));
1663 new.tbf_in = old->tbf_in;
1664 new.tbf_out = old->tbf_out;
1665 new.random_vector_length = old->random_vector_length;
1666 memcpy(new.random_vector, old->random_vector, sizeof(new.random_vector));
1667 memcpy(new.user, old->user, sizeof(new.user));
1668 memcpy(new.called, old->called, sizeof(new.called));
1669 memcpy(new.calling, old->calling, sizeof(new.calling));
1670 new.tx_connect_speed = old->tx_connect_speed;
1671 new.rx_connect_speed = old->rx_connect_speed;
1672 new.timeout = old->timeout;
1673 new.mrru = old->mrru;
1674 new.epdis = old->epdis;
1675 new.bundle = old->bundle;
1676 new.mssf = old->mssf;
1677 new.walled_garden = old->walled_garden;
1678 new.classlen = old->classlen;
1679 memcpy(new.class, old->class, sizeof(new.class));
1680 new.route6[0].ipv6prefixlen = old->ipv6prefixlen;
1681 new.route6[0].ipv6route = old->ipv6route;
1682
1683 new.forwardtosession = old->forwardtosession;
1684 memcpy(new.src_hwaddr, old->src_hwaddr, sizeof(new.src_hwaddr));
1685
1686 return (uint8_t *) &new;
1687 }
1688
1689 static uint8_t *convert_sessionV8(struct oldsessionV8 *old)
1690 {
1691 static sessiont new;
1692 int i;
1693
1694 memset(&new, 0, sizeof(new));
1695
1696 new.next = old->next;
1697 new.far = old->far;
1698 new.tunnel = old->tunnel;
1699 new.flags = old->flags;
1700 new.ppp.phase = old->ppp.phase;
1701 new.ppp.lcp = old->ppp.lcp;
1702 new.ppp.ipcp = old->ppp.ipcp;
1703 new.ppp.ipv6cp = old->ppp.ipv6cp;
1704 new.ppp.ccp = old->ppp.ccp;
1705 new.mru = old->mru;
1706 new.ip = old->ip;
1707 new.ip_pool_index = old->ip_pool_index;
1708 new.unique_id = old->unique_id;
1709 new.magic = old->magic;
1710 new.pin = old->pin;
1711 new.pout = old->pout;
1712 new.cin = old->cin;
1713 new.cout = old->cout;
1714 new.cin_wrap = old->cin_wrap;
1715 new.cout_wrap = old->cout_wrap;
1716 new.cin_delta = old->cin_delta;
1717 new.cout_delta = old->cout_delta;
1718 new.throttle_in = old->throttle_in;
1719 new.throttle_out = old->throttle_out;
1720 new.filter_in = old->filter_in;
1721 new.filter_out = old->filter_out;
1722 new.snoop_port = old->snoop_port;
1723 new.snoop_ip = old->snoop_ip;
1724 new.opened = old->opened;
1725 new.die = old->die;
1726 new.session_timeout = old->session_timeout;
1727 new.idle_timeout = old->idle_timeout;
1728 new.last_packet = old->last_packet;
1729 new.last_data = old->last_data;
1730 new.dns1 = old->dns1;
1731 new.dns2 = old->dns2;
1732 for (i = 0; i < MAXROUTE; i++)
1733 memcpy(&new.route[i], &old->route[i], sizeof(new.route[i]));
1734 new.tbf_in = old->tbf_in;
1735 new.tbf_out = old->tbf_out;
1736 new.random_vector_length = old->random_vector_length;
1737 memcpy(new.random_vector, old->random_vector, sizeof(new.random_vector));
1738 memcpy(new.user, old->user, sizeof(new.user));
1739 memcpy(new.called, old->called, sizeof(new.called));
1740 memcpy(new.calling, old->calling, sizeof(new.calling));
1741 new.tx_connect_speed = old->tx_connect_speed;
1742 new.rx_connect_speed = old->rx_connect_speed;
1743 new.timeout = old->timeout;
1744 new.mrru = old->mrru;
1745 new.epdis = old->epdis;
1746 new.bundle = old->bundle;
1747 new.mssf = old->mssf;
1748 new.walled_garden = old->walled_garden;
1749 new.classlen = old->classlen;
1750 memcpy(new.class, old->class, sizeof(new.class));
1751 new.route6[0].ipv6prefixlen = old->ipv6prefixlen;
1752 new.route6[0].ipv6route = old->ipv6route;
1753
1754 new.forwardtosession = old->forwardtosession;
1755 memcpy(new.src_hwaddr, old->src_hwaddr, sizeof(new.src_hwaddr));
1756 new.dhcpv6_prefix_iaid = old->dhcpv6_prefix_iaid;
1757 new.dhcpv6_iana_iaid = old->dhcpv6_iana_iaid;
1758 new.ipv6address = old->ipv6address;
1759 new.dhcpv6_client_id = old->dhcpv6_client_id;
1760
1761 return (uint8_t *) &new;
1762 }
1763
1764 //
1765 // Process a heartbeat..
1766 //
1767 // v6: added RADIUS class attribute, re-ordered session structure
1768 // v7: added tunnelt attribute at the end of struct (tunnelt size change)
1769 static int cluster_process_heartbeat(uint8_t *data, int size, int more, uint8_t *p, in_addr_t addr)
1770 {
1771 heartt *h;
1772 int s = size - (p-data);
1773 int i, type;
1774 int hb_ver = more;
1775
1776 #if HB_VERSION != 9
1777 # error "need to update cluster_process_heartbeat()"
1778 #endif
1779
1780 // we handle versions 5 through 8
1781 if (hb_ver < 5 || hb_ver > HB_VERSION) {
1782 LOG(0, 0, 0, "Received a heartbeat version that I don't support (%d)!\n", hb_ver);
1783 return -1; // Ignore it??
1784 }
1785
1786 if (size > sizeof(past_hearts[0].data)) {
1787 LOG(0, 0, 0, "Received an oversize heartbeat from %s (%d)!\n", fmtaddr(addr, 0), size);
1788 return -1;
1789 }
1790
1791 if (s < sizeof(*h))
1792 goto shortpacket;
1793
1794 h = (heartt *) p;
1795 p += sizeof(*h);
1796 s -= sizeof(*h);
1797
1798 if (h->clusterid != config->bind_address)
1799 return -1; // It's not part of our cluster.
1800
1801 if (config->cluster_iam_master) { // Sanity...
1802 // Note that this MUST match the election process above!
1803
1804 LOG(0, 0, 0, "I just got a heartbeat from master %s, but _I_ am the master!\n", fmtaddr(addr, 0));
1805 if (!h->basetime) {
1806 LOG(0, 0, 0, "Heartbeat with zero basetime! Ignoring\n");
1807 return -1; // Skip it.
1808 }
1809
1810 if (h->table_version > config->cluster_table_version) {
1811 LOG(0, 0, 0, "They've seen more state changes (%" PRIu64 " vs my %" PRIu64 ") so I'm gone!\n",
1812 h->table_version, config->cluster_table_version);
1813
1814 kill(0, SIGTERM);
1815 exit(1);
1816 }
1817
1818 if (h->table_version < config->cluster_table_version)
1819 return -1;
1820
1821 if (basetime > h->basetime) {
1822 LOG(0, 0, 0, "They're an older master than me so I'm gone!\n");
1823 kill(0, SIGTERM);
1824 exit(1);
1825 }
1826
1827 if (basetime < h->basetime)
1828 return -1;
1829
1830 if (my_address < addr) { // Tie breaker.
1831 LOG(0, 0, 0, "They're a higher IP address than me, so I'm gone!\n");
1832 kill(0, SIGTERM);
1833 exit(1);
1834 }
1835
1836 //
1837 // Send it a unicast heartbeat to see give it a chance to die.
1838 // NOTE: It's actually safe to do seq-number - 1 without checking
1839 // for wrap around.
1840 //
1841 cluster_catchup_slave(config->cluster_seq_number - 1, addr);
1842
1843 return -1; // Skip it.
1844 }
1845
1846 //
1847 // Try and guard against a stray master appearing.
1848 //
1849 // Ignore heartbeats received from another master before the
1850 // timeout (less a smidgen) for the old master has elapsed.
1851 //
1852 // Note that after a clean failover, the cluster_master_address
1853 // is cleared, so this doesn't run.
1854 //
1855 if (config->cluster_master_address && addr != config->cluster_master_address) {
1856 LOG(0, 0, 0, "Ignoring stray heartbeat from %s, current master %s has not yet timed out (last heartbeat %.1f seconds ago).\n",
1857 fmtaddr(addr, 0), fmtaddr(config->cluster_master_address, 1),
1858 0.1 * (TIME - config->cluster_last_hb));
1859 return -1; // ignore
1860 }
1861
1862 if (config->cluster_seq_number == -1) // Don't have one. Just align to the master...
1863 config->cluster_seq_number = h->seq;
1864
1865 config->cluster_last_hb = TIME; // Reset to ensure that we don't become master!!
1866 config->cluster_last_hb_ver = hb_ver; // remember what cluster version the master is using
1867
1868 if (config->cluster_seq_number != h->seq) { // Out of sequence heartbeat!
1869 static int lastseen_seq = 0;
1870 static time_t lastseen_time = 0;
1871
1872 // limit to once per second for a particular seq#
1873 int ask = (config->cluster_seq_number != lastseen_seq || time_now != lastseen_time);
1874
1875 LOG(1, 0, 0, "HB: Got seq# %d but was expecting %d. %s.\n",
1876 h->seq, config->cluster_seq_number,
1877 ask ? "Asking for resend" : "Ignoring");
1878
1879 if (ask)
1880 {
1881 lastseen_seq = config->cluster_seq_number;
1882 lastseen_time = time_now;
1883 peer_send_message(addr, C_LASTSEEN, config->cluster_seq_number, NULL, 0);
1884 }
1885
1886 config->cluster_last_hb = TIME; // Reset to ensure that we don't become master!!
1887
1888 // Just drop the packet. The master will resend it as part of the catchup.
1889
1890 return 0;
1891 }
1892 // Save the packet in our buffer.
1893 // This is needed in case we become the master.
1894 config->cluster_seq_number = (h->seq+1)%HB_MAX_SEQ;
1895 i = h->seq % HB_HISTORY_SIZE;
1896 past_hearts[i].seq = h->seq;
1897 past_hearts[i].size = size;
1898 memcpy(&past_hearts[i].data, data, size); // Save it.
1899
1900
1901 // Check that we don't have too many undefined sessions, and
1902 // that the free session pointer is correct.
1903 cluster_check_sessions(h->highsession, h->freesession, h->highbundle, h->hightunnel);
1904
1905 if (h->interval != config->cluster_hb_interval)
1906 {
1907 LOG(2, 0, 0, "Master set ping/heartbeat interval to %u (was %u)\n",
1908 h->interval, config->cluster_hb_interval);
1909
1910 config->cluster_hb_interval = h->interval;
1911 }
1912
1913 if (h->timeout != config->cluster_hb_timeout)
1914 {
1915 LOG(2, 0, 0, "Master set heartbeat timeout to %u (was %u)\n",
1916 h->timeout, config->cluster_hb_timeout);
1917
1918 config->cluster_hb_timeout = h->timeout;
1919 }
1920
1921 // Ok. process the packet...
1922 while ( s > 0) {
1923
1924 type = *((uint32_t *) p);
1925 p += sizeof(uint32_t);
1926 s -= sizeof(uint32_t);
1927
1928 more = *((uint32_t *) p);
1929 p += sizeof(uint32_t);
1930 s -= sizeof(uint32_t);
1931
1932 switch (type) {
1933 case C_CSESSION: { // Compressed session structure.
1934 uint8_t c[ sizeof(sessiont) + 2];
1935 int size;
1936 uint8_t *orig_p = p;
1937
1938 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c) );
1939 s -= (p - orig_p);
1940
1941 // session struct changed with v5
1942 if (hb_ver < 6)
1943 {
1944 if (size != sizeof(struct oldsession)) {
1945 LOG(0, 0, 0, "DANGER: Received a v%d CSESSION that didn't decompress correctly!\n", hb_ver);
1946 // Now what? Should exit! No-longer up to date!
1947 break;
1948 }
1949 cluster_recv_session(more, convert_session((struct oldsession *) c));
1950 break;
1951 }
1952
1953 if (size != sizeof(sessiont)) { // Ouch! Very very bad!
1954 if ((hb_ver < HB_VERSION) && (size < sizeof(sessiont)))
1955 {
1956 if ((hb_ver == 7) && (size == sizeof(struct oldsessionV7)))
1957 cluster_recv_session(more, convert_sessionV7((struct oldsessionV7 *) c));
1958 else if (size == sizeof(struct oldsessionV8))
1959 cluster_recv_session(more, convert_sessionV8((struct oldsessionV8 *) c));
1960 else
1961 LOG(0, 0, 0, "DANGER: Received a CSESSION version=%d that didn't decompress correctly!\n", hb_ver);
1962 break;
1963 }
1964 else
1965 {
1966 LOG(0, 0, 0, "DANGER: Received a CSESSION that didn't decompress correctly!\n");
1967 // Now what? Should exit! No-longer up to date!
1968 break;
1969 }
1970 }
1971
1972 cluster_recv_session(more, c);
1973 break;
1974 }
1975 case C_SESSION:
1976 if (hb_ver < 6)
1977 {
1978 if (s < sizeof(struct oldsession))
1979 goto shortpacket;
1980
1981 cluster_recv_session(more, convert_session((struct oldsession *) p));
1982
1983 p += sizeof(struct oldsession);
1984 s -= sizeof(struct oldsession);
1985 break;
1986 }
1987
1988 if ( s < sizeof(session[more]))
1989 goto shortpacket;
1990
1991 cluster_recv_session(more, p);
1992
1993 p += sizeof(session[more]);
1994 s -= sizeof(session[more]);
1995 break;
1996
1997 case C_CTUNNEL: { // Compressed tunnel structure.
1998 uint8_t c[ sizeof(tunnelt) + 2];
1999 int size;
2000 uint8_t *orig_p = p;
2001
2002 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c));
2003 s -= (p - orig_p);
2004
2005 if ( ((hb_ver >= HB_VERSION) && (size != sizeof(tunnelt))) ||
2006 ((hb_ver < HB_VERSION) && (size > sizeof(tunnelt))) )
2007 { // Ouch! Very very bad!
2008 LOG(0, 0, 0, "DANGER: Received a CTUNNEL that didn't decompress correctly!\n");
2009 // Now what? Should exit! No-longer up to date!
2010 break;
2011 }
2012
2013 cluster_recv_tunnel(more, c);
2014 break;
2015
2016 }
2017 case C_TUNNEL:
2018 if ( s < sizeof(tunnel[more]))
2019 goto shortpacket;
2020
2021 cluster_recv_tunnel(more, p);
2022
2023 p += sizeof(tunnel[more]);
2024 s -= sizeof(tunnel[more]);
2025 break;
2026
2027 case C_CBUNDLE: { // Compressed bundle structure.
2028 uint8_t c[ sizeof(bundlet) + 2];
2029 int size;
2030 uint8_t *orig_p = p;
2031
2032 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c));
2033 s -= (p - orig_p);
2034
2035 if (size != sizeof(bundlet) ) { // Ouch! Very very bad!
2036 LOG(0, 0, 0, "DANGER: Received a CBUNDLE that didn't decompress correctly!\n");
2037 // Now what? Should exit! No-longer up to date!
2038 break;
2039 }
2040
2041 cluster_recv_bundle(more, c);
2042 break;
2043
2044 }
2045 case C_BUNDLE:
2046 if ( s < sizeof(bundle[more]))
2047 goto shortpacket;
2048
2049 cluster_recv_bundle(more, p);
2050
2051 p += sizeof(bundle[more]);
2052 s -= sizeof(bundle[more]);
2053 break;
2054 default:
2055 LOG(0, 0, 0, "DANGER: I received a heartbeat element where I didn't understand the type! (%d)\n", type);
2056 return -1; // can't process any more of the packet!!
2057 }
2058 }
2059
2060 if (config->cluster_master_address != addr)
2061 {
2062 LOG(0, 0, 0, "My master just changed from %s to %s!\n",
2063 fmtaddr(config->cluster_master_address, 0), fmtaddr(addr, 1));
2064
2065 config->cluster_master_address = addr;
2066 }
2067
2068 config->cluster_last_hb = TIME; // Successfully received a heartbeat!
2069 config->cluster_table_version = h->table_version;
2070 return 0;
2071
2072 shortpacket:
2073 LOG(0, 0, 0, "I got an incomplete heartbeat packet! This means I'm probably out of sync!!\n");
2074 return -1;
2075 }
2076
2077 //
2078 // We got a packet on the cluster port!
2079 // Handle pings, lastseens, and heartbeats!
2080 //
2081 int processcluster(uint8_t *data, int size, in_addr_t addr)
2082 {
2083 int type, more;
2084 uint8_t *p = data;
2085 int s = size;
2086
2087 if (addr == my_address)
2088 return -1; // Ignore it. Something looped back the multicast!
2089
2090 LOG(5, 0, 0, "Process cluster: %d bytes from %s\n", size, fmtaddr(addr, 0));
2091
2092 if (s <= 0) // Any data there??
2093 return -1;
2094
2095 if (s < 8)
2096 goto shortpacket;
2097
2098 type = *((uint32_t *) p);
2099 p += sizeof(uint32_t);
2100 s -= sizeof(uint32_t);
2101
2102 more = *((uint32_t *) p);
2103 p += sizeof(uint32_t);
2104 s -= sizeof(uint32_t);
2105
2106 switch (type)
2107 {
2108 case C_PING: // Update the peers table.
2109 return cluster_add_peer(addr, more, (pingt *) p, s);
2110
2111 case C_MASTER: // Our master is wrong
2112 return cluster_set_master(addr, more);
2113
2114 case C_LASTSEEN: // Catch up a slave (slave missed a packet).
2115 return cluster_catchup_slave(more, addr);
2116
2117 case C_FORWARD: // Forwarded control packet. pass off to processudp.
2118 case C_FORWARD_DAE: // Forwarded DAE packet. pass off to processdae.
2119 if (!config->cluster_iam_master)
2120 {
2121 LOG(0, 0, 0, "I'm not the master, but I got a C_FORWARD%s from %s?\n",
2122 type == C_FORWARD_DAE ? "_DAE" : "", fmtaddr(addr, 0));
2123
2124 return -1;
2125 }
2126 else
2127 {
2128 struct sockaddr_in a;
2129 uint16_t indexudp;
2130 a.sin_addr.s_addr = more;
2131
2132 a.sin_port = (*(int *) p) & 0xFFFF;
2133 indexudp = ((*(int *) p) >> 16) & 0xFFFF;
2134 s -= sizeof(int);
2135 p += sizeof(int);
2136
2137 LOG(4, 0, 0, "Got a forwarded %spacket... (%s:%d)\n",
2138 type == C_FORWARD_DAE ? "DAE " : "", fmtaddr(more, 0), a.sin_port);
2139
2140 STAT(recv_forward);
2141 if (type == C_FORWARD_DAE)
2142 {
2143 struct in_addr local;
2144 local.s_addr = config->bind_address ? config->bind_address : my_address;
2145 processdae(p, s, &a, sizeof(a), &local);
2146 }
2147 else
2148 processudp(p, s, &a, indexudp);
2149
2150 return 0;
2151 }
2152 case C_PPPOE_FORWARD:
2153 if (!config->cluster_iam_master)
2154 {
2155 LOG(0, 0, 0, "I'm not the master, but I got a C_PPPOE_FORWARD from %s?\n", fmtaddr(addr, 0));
2156 return -1;
2157 }
2158 else
2159 {
2160 pppoe_process_forward(p, s, addr);
2161 return 0;
2162 }
2163
2164 case C_MPPP_FORWARD:
2165 // Receive a MPPP packet from a slave.
2166 if (!config->cluster_iam_master) {
2167 LOG(0, 0, 0, "I'm not the master, but I got a C_MPPP_FORWARD from %s?\n", fmtaddr(addr, 0));
2168 return -1;
2169 }
2170
2171 processipout(p, s);
2172 return 0;
2173
2174 case C_THROTTLE: { // Receive a forwarded packet from a slave.
2175 if (!config->cluster_iam_master) {
2176 LOG(0, 0, 0, "I'm not the master, but I got a C_THROTTLE from %s?\n", fmtaddr(addr, 0));
2177 return -1;
2178 }
2179
2180 tbf_queue_packet(more, p, s); // The TBF id tells wether it goes in or out.
2181 return 0;
2182 }
2183 case C_GARDEN:
2184 // Receive a walled garden packet from a slave.
2185 if (!config->cluster_iam_master) {
2186 LOG(0, 0, 0, "I'm not the master, but I got a C_GARDEN from %s?\n", fmtaddr(addr, 0));
2187 return -1;
2188 }
2189
2190 tun_write(p, s);
2191 return 0;
2192
2193 case C_BYTES:
2194 if (!config->cluster_iam_master) {
2195 LOG(0, 0, 0, "I'm not the master, but I got a C_BYTES from %s?\n", fmtaddr(addr, 0));
2196 return -1;
2197 }
2198
2199 return cluster_handle_bytes(p, s);
2200
2201 case C_KILL: // The master asked us to die!? (usually because we're too out of date).
2202 if (config->cluster_iam_master) {
2203 LOG(0, 0, 0, "_I_ am master, but I received a C_KILL from %s! (Seq# %d)\n", fmtaddr(addr, 0), more);
2204 return -1;
2205 }
2206 if (more != config->cluster_seq_number) {
2207 LOG(0, 0, 0, "The master asked us to die but the seq number didn't match!?\n");
2208 return -1;
2209 }
2210
2211 if (addr != config->cluster_master_address) {
2212 LOG(0, 0, 0, "Received a C_KILL from %s which doesn't match config->cluster_master_address (%s)\n",
2213 fmtaddr(addr, 0), fmtaddr(config->cluster_master_address, 1));
2214 // We can only warn about it. The master might really have switched!
2215 }
2216
2217 LOG(0, 0, 0, "Received a valid C_KILL: I'm going to die now.\n");
2218 kill(0, SIGTERM);
2219 exit(0); // Lets be paranoid;
2220 return -1; // Just signalling the compiler.
2221
2222 case C_HEARTBEAT:
2223 LOG(4, 0, 0, "Got a heartbeat from %s\n", fmtaddr(addr, 0));
2224 return cluster_process_heartbeat(data, size, more, p, addr);
2225
2226 default:
2227 LOG(0, 0, 0, "Strange type packet received on cluster socket (%d)\n", type);
2228 return -1;
2229 }
2230 return 0;
2231
2232 shortpacket:
2233 LOG(0, 0, 0, "I got a _short_ cluster heartbeat packet! This means I'm probably out of sync!!\n");
2234 return -1;
2235 }
2236
2237 //====================================================================================================
2238
2239 int cmd_show_cluster(struct cli_def *cli, const char *command, char **argv, int argc)
2240 {
2241 int i;
2242
2243 if (CLI_HELP_REQUESTED)
2244 return CLI_HELP_NO_ARGS;
2245
2246 cli_print(cli, "Cluster status : %s", config->cluster_iam_master ? "Master" : "Slave" );
2247 cli_print(cli, "My address : %s", fmtaddr(my_address, 0));
2248 cli_print(cli, "VIP address : %s", fmtaddr(config->bind_address, 0));
2249 cli_print(cli, "Multicast address: %s", fmtaddr(config->cluster_address, 0));
2250 cli_print(cli, "UDP port : %u", config->cluster_port);
2251 cli_print(cli, "Multicast i'face : %s", config->cluster_interface);
2252
2253 if (!config->cluster_iam_master) {
2254 cli_print(cli, "My master : %s (last heartbeat %.1f seconds old)",
2255 config->cluster_master_address
2256 ? fmtaddr(config->cluster_master_address, 0)
2257 : "Not defined",
2258 0.1 * (TIME - config->cluster_last_hb));
2259 cli_print(cli, "Uptodate : %s", config->cluster_iam_uptodate ? "Yes" : "No");
2260 cli_print(cli, "Table version # : %" PRIu64, config->cluster_table_version);
2261 cli_print(cli, "Next sequence number expected: %d", config->cluster_seq_number);
2262 cli_print(cli, "%d sessions undefined of %d", config->cluster_undefined_sessions, config->cluster_highest_sessionid);
2263 cli_print(cli, "%d bundles undefined of %d", config->cluster_undefined_bundles, config->cluster_highest_bundleid);
2264 cli_print(cli, "%d tunnels undefined of %d", config->cluster_undefined_tunnels, config->cluster_highest_tunnelid);
2265 } else {
2266 cli_print(cli, "Table version # : %" PRIu64, config->cluster_table_version);
2267 cli_print(cli, "Next heartbeat # : %d", config->cluster_seq_number);
2268 cli_print(cli, "Highest session : %d", config->cluster_highest_sessionid);
2269 cli_print(cli, "Highest bundle : %d", config->cluster_highest_bundleid);
2270 cli_print(cli, "Highest tunnel : %d", config->cluster_highest_tunnelid);
2271 cli_print(cli, "%d changes queued for sending", config->cluster_num_changes);
2272 }
2273 cli_print(cli, "%d peers.", num_peers);
2274
2275 if (num_peers)
2276 cli_print(cli, "%20s %10s %8s", "Address", "Basetime", "Age");
2277 for (i = 0; i < num_peers; ++i) {
2278 cli_print(cli, "%20s %10u %8d", fmtaddr(peers[i].peer, 0),
2279 peers[i].basetime, TIME - peers[i].timestamp);
2280 }
2281 return CLI_OK;
2282 }
2283
2284 //
2285 // Simple run-length-encoding compression.
2286 // Format is
2287 // 1 byte < 128 = count of non-zero bytes following. // Not legal to be zero.
2288 // n non-zero bytes;
2289 // or
2290 // 1 byte > 128 = (count - 128) run of zero bytes. //
2291 // repeat.
2292 // count == 0 indicates end of compressed stream.
2293 //
2294 // Compress from 'src' into 'dst'. return number of bytes
2295 // used from 'dst'.
2296 // Updates *src_p to indicate 1 past last bytes used.
2297 //
2298 // We could get an extra byte in the zero runs by storing (count-1)
2299 // but I'm playing it safe.
2300 //
2301 // Worst case is a 50% expansion in space required (trying to
2302 // compress { 0x00, 0x01 } * N )
2303 static int rle_compress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize)
2304 {
2305 int count;
2306 int orig_dsize = dsize;
2307 uint8_t *x, *src;
2308 src = *src_p;
2309
2310 while (ssize > 0 && dsize > 2) {
2311 count = 0;
2312 x = dst++; --dsize; // Reserve space for count byte..
2313
2314 if (*src) { // Copy a run of non-zero bytes.
2315 while (*src && count < 127 && ssize > 0 && dsize > 1) { // Count number of non-zero bytes.
2316 *dst++ = *src++;
2317 --dsize; --ssize;
2318 ++count;
2319 }
2320 *x = count; // Store number of non-zero bytes. Guarenteed to be non-zero!
2321
2322 } else { // Compress a run of zero bytes.
2323 while (*src == 0 && count < 127 && ssize > 0) {
2324 ++src;
2325 --ssize;
2326 ++count;
2327 }
2328 *x = count | 0x80 ;
2329 }
2330 }
2331
2332 *dst++ = 0x0; // Add Stop byte.
2333 --dsize;
2334
2335 *src_p = src;
2336 return (orig_dsize - dsize);
2337 }
2338
2339 //
2340 // Decompress the buffer into **p.
2341 // 'psize' is the size of the decompression buffer available.
2342 //
2343 // Returns the number of bytes decompressed.
2344 //
2345 // Decompresses from '*src_p' into 'dst'.
2346 // Return the number of dst bytes used.
2347 // Updates the 'src_p' pointer to point to the
2348 // first un-used byte.
2349 static int rle_decompress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize)
2350 {
2351 int count;
2352 int orig_dsize = dsize;
2353 uint8_t *src = *src_p;
2354
2355 while (ssize >0 && dsize > 0) { // While there's more to decompress, and there's room in the decompress buffer...
2356 count = *src++; --ssize; // get the count byte from the source.
2357 if (count == 0x0) // End marker reached? If so, finish.
2358 break;
2359
2360 if (count & 0x80) { // Decompress a run of zeros
2361 for (count &= 0x7f ; count > 0 && dsize > 0; --count) {
2362 *dst++ = 0x0;
2363 --dsize;
2364 }
2365 } else { // Copy run of non-zero bytes.
2366 for ( ; count > 0 && ssize && dsize; --count) { // Copy non-zero bytes across.
2367 *dst++ = *src++;
2368 --ssize; --dsize;
2369 }
2370 }
2371 }
2372 *src_p = src;
2373 return (orig_dsize - dsize);
2374 }