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