merge from multibind
[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 #include <linux/rtnetlink.h>
20
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(CLUSTERPORT);
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(CLUSTERPORT);
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(CLUSTERPORT);
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 session[i].coutgrp_delta += sess_local[i].cout;
715
716 session[i].pin += sess_local[i].pin;
717 session[i].pout += sess_local[i].pout;
718
719 sess_local[i].cin = sess_local[i].cout = 0;
720 sess_local[i].pin = sess_local[i].pout = 0;
721
722 sess_local[i].radius = 0; // Reset authentication as the radius blocks aren't up to date.
723
724 if (session[i].unique_id >= high_unique_id) // This is different to the index into the session table!!!
725 high_unique_id = session[i].unique_id+1;
726
727 session[i].tbf_in = session[i].tbf_out = 0; // Remove stale pointers from old master.
728 throttle_session(i, session[i].throttle_in, session[i].throttle_out);
729
730 config->cluster_highest_sessionid = i;
731 }
732
733 session[last_free].next = 0; // End of chain.
734 last_id = high_unique_id; // Keep track of the highest used session ID.
735
736 become_master();
737
738 rebuild_address_pool();
739
740 // If we're not the very first master, this is a big issue!
741 if (count > 0)
742 LOG(0, 0, 0, "Warning: Fixed %d uninitialized sessions in becoming master!\n", count);
743
744 config->cluster_undefined_sessions = 0;
745 config->cluster_undefined_bundles = 0;
746 config->cluster_undefined_tunnels = 0;
747 config->cluster_iam_uptodate = 1; // assume all peers are up-to-date
748
749 // FIXME. We need to fix up the tunnel control message
750 // queue here! There's a number of other variables we
751 // should also update.
752 }
753
754
755 //
756 // Check that our session table is validly matching what the
757 // master has in mind.
758 //
759 // In particular, if we have too many sessions marked 'undefined'
760 // we fix it up here, and we ensure that the 'first free session'
761 // pointer is valid.
762 //
763 static void cluster_check_sessions(int highsession, int freesession_ptr, int highbundle, int hightunnel)
764 {
765 int i;
766
767 sessionfree = freesession_ptr; // Keep the freesession ptr valid.
768
769 if (config->cluster_iam_uptodate)
770 return;
771
772 if (highsession > config->cluster_undefined_sessions && highbundle > config->cluster_undefined_bundles && hightunnel > config->cluster_undefined_tunnels)
773 return;
774
775 // Clear out defined sessions, counting the number of
776 // undefs remaining.
777 config->cluster_undefined_sessions = 0;
778 for (i = 1 ; i < MAXSESSION; ++i) {
779 if (i > highsession) {
780 if (session[i].tunnel == T_UNDEF) session[i].tunnel = T_FREE; // Defined.
781 continue;
782 }
783
784 if (session[i].tunnel == T_UNDEF)
785 ++config->cluster_undefined_sessions;
786 }
787
788 // Clear out defined bundles, counting the number of
789 // undefs remaining.
790 config->cluster_undefined_bundles = 0;
791 for (i = 1 ; i < MAXBUNDLE; ++i) {
792 if (i > highbundle) {
793 if (bundle[i].state == BUNDLEUNDEF) bundle[i].state = BUNDLEFREE; // Defined.
794 continue;
795 }
796
797 if (bundle[i].state == BUNDLEUNDEF)
798 ++config->cluster_undefined_bundles;
799 }
800
801 // Clear out defined tunnels, counting the number of
802 // undefs remaining.
803 config->cluster_undefined_tunnels = 0;
804 for (i = 1 ; i < MAXTUNNEL; ++i) {
805 if (i > hightunnel) {
806 if (tunnel[i].state == TUNNELUNDEF) tunnel[i].state = TUNNELFREE; // Defined.
807 continue;
808 }
809
810 if (tunnel[i].state == TUNNELUNDEF)
811 ++config->cluster_undefined_tunnels;
812 }
813
814
815 if (config->cluster_undefined_sessions || config->cluster_undefined_tunnels || config->cluster_undefined_bundles) {
816 LOG(2, 0, 0, "Cleared undefined sessions/bundles/tunnels. %d sess (high %d), %d bund (high %d), %d tunn (high %d)\n",
817 config->cluster_undefined_sessions, highsession, config->cluster_undefined_bundles, highbundle, config->cluster_undefined_tunnels, hightunnel);
818 return;
819 }
820
821 // Are we up to date?
822
823 if (!config->cluster_iam_uptodate)
824 cluster_uptodate();
825 }
826
827 static int hb_add_type(uint8_t **p, int type, int id)
828 {
829 switch (type) {
830 case C_CSESSION: { // Compressed C_SESSION.
831 uint8_t c[sizeof(sessiont) * 2]; // Bigger than worst case.
832 uint8_t *d = (uint8_t *) &session[id];
833 uint8_t *orig = d;
834 int size;
835
836 size = rle_compress( &d, sizeof(sessiont), c, sizeof(c) );
837
838 // Did we compress the full structure, and is the size actually
839 // reduced??
840 if ( (d - orig) == sizeof(sessiont) && size < sizeof(sessiont) ) {
841 add_type(p, C_CSESSION, id, c, size);
842 break;
843 }
844 // Failed to compress : Fall through.
845 }
846 case C_SESSION:
847 add_type(p, C_SESSION, id, (uint8_t *) &session[id], sizeof(sessiont));
848 break;
849
850 case C_CBUNDLE: { // Compressed C_BUNDLE
851 uint8_t c[sizeof(bundlet) * 2]; // Bigger than worst case.
852 uint8_t *d = (uint8_t *) &bundle[id];
853 uint8_t *orig = d;
854 int size;
855
856 size = rle_compress( &d, sizeof(bundlet), c, sizeof(c) );
857
858 // Did we compress the full structure, and is the size actually
859 // reduced??
860 if ( (d - orig) == sizeof(bundlet) && size < sizeof(bundlet) ) {
861 add_type(p, C_CBUNDLE, id, c, size);
862 break;
863 }
864 // Failed to compress : Fall through.
865 }
866
867 case C_BUNDLE:
868 add_type(p, C_BUNDLE, id, (uint8_t *) &bundle[id], sizeof(bundlet));
869 break;
870
871 case C_CTUNNEL: { // Compressed C_TUNNEL
872 uint8_t c[sizeof(tunnelt) * 2]; // Bigger than worst case.
873 uint8_t *d = (uint8_t *) &tunnel[id];
874 uint8_t *orig = d;
875 int size;
876
877 size = rle_compress( &d, sizeof(tunnelt), c, sizeof(c) );
878
879 // Did we compress the full structure, and is the size actually
880 // reduced??
881 if ( (d - orig) == sizeof(tunnelt) && size < sizeof(tunnelt) ) {
882 add_type(p, C_CTUNNEL, id, c, size);
883 break;
884 }
885 // Failed to compress : Fall through.
886 }
887 case C_TUNNEL:
888 add_type(p, C_TUNNEL, id, (uint8_t *) &tunnel[id], sizeof(tunnelt));
889 break;
890 default:
891 LOG(0, 0, 0, "Found an invalid type in heart queue! (%d)\n", type);
892 kill(0, SIGTERM);
893 exit(1);
894 }
895 return 0;
896 }
897
898 //
899 // Send a heartbeat, incidently sending out any queued changes..
900 //
901 void cluster_heartbeat()
902 {
903 int i, count = 0, tcount = 0, bcount = 0;
904 uint8_t buff[MAX_HEART_SIZE + sizeof(heartt) + sizeof(int) ];
905 heartt h;
906 uint8_t *p = buff;
907
908 if (!config->cluster_iam_master) // Only the master does this.
909 return;
910
911 config->cluster_table_version += config->cluster_num_changes;
912
913 // Fill out the heartbeat header.
914 memset(&h, 0, sizeof(h));
915
916 h.version = HB_VERSION;
917 h.seq = config->cluster_seq_number;
918 h.basetime = basetime;
919 h.clusterid = config->bind_address; // Will this do??
920 h.basetime = basetime;
921 h.highsession = config->cluster_highest_sessionid;
922 h.freesession = sessionfree;
923 h.hightunnel = config->cluster_highest_tunnelid;
924 h.highbundle = config->cluster_highest_bundleid;
925 h.size_sess = sizeof(sessiont); // Just in case.
926 h.size_bund = sizeof(bundlet);
927 h.size_tunn = sizeof(tunnelt);
928 h.interval = config->cluster_hb_interval;
929 h.timeout = config->cluster_hb_timeout;
930 h.table_version = config->cluster_table_version;
931
932 add_type(&p, C_HEARTBEAT, HB_VERSION, (uint8_t *) &h, sizeof(h));
933
934 for (i = 0; i < config->cluster_num_changes; ++i) {
935 hb_add_type(&p, cluster_changes[i].type, cluster_changes[i].id);
936 }
937
938 if (p > (buff + sizeof(buff))) { // Did we somehow manage to overun the buffer?
939 LOG(0, 0, 0, "FATAL: Overran the heartbeat buffer! This is fatal. Exiting. (size %d)\n", (int) (p - buff));
940 kill(0, SIGTERM);
941 exit(1);
942 }
943
944 //
945 // Fill out the packet with sessions from the session table...
946 // (not forgetting to leave space so we can get some tunnels in too )
947 while ( (p + sizeof(uint32_t) * 2 + sizeof(sessiont) * 2 ) < (buff + MAX_HEART_SIZE) ) {
948
949 if (!walk_session_number) // session #0 isn't valid.
950 ++walk_session_number;
951
952 if (count >= config->cluster_highest_sessionid) // If we're a small cluster, don't go wild.
953 break;
954
955 hb_add_type(&p, C_CSESSION, walk_session_number);
956 walk_session_number = (1+walk_session_number)%(config->cluster_highest_sessionid+1); // +1 avoids divide by zero.
957
958 ++count; // Count the number of extra sessions we're sending.
959 }
960
961 //
962 // Fill out the packet with tunnels from the tunnel table...
963 // This effectively means we walk the tunnel table more quickly
964 // than the session table. This is good because stuffing up a
965 // tunnel is a much bigger deal than stuffing up a session.
966 //
967 while ( (p + sizeof(uint32_t) * 2 + sizeof(tunnelt) ) < (buff + MAX_HEART_SIZE) ) {
968
969 if (!walk_tunnel_number) // tunnel #0 isn't valid.
970 ++walk_tunnel_number;
971
972 if (tcount >= config->cluster_highest_tunnelid)
973 break;
974
975 hb_add_type(&p, C_CTUNNEL, walk_tunnel_number);
976 walk_tunnel_number = (1+walk_tunnel_number)%(config->cluster_highest_tunnelid+1); // +1 avoids divide by zero.
977
978 ++tcount;
979 }
980
981 //
982 // Fill out the packet with bundles from the bundle table...
983 while ( (p + sizeof(uint32_t) * 2 + sizeof(bundlet) ) < (buff + MAX_HEART_SIZE) ) {
984
985 if (!walk_bundle_number) // bundle #0 isn't valid.
986 ++walk_bundle_number;
987
988 if (bcount >= config->cluster_highest_bundleid)
989 break;
990
991 hb_add_type(&p, C_CBUNDLE, walk_bundle_number);
992 walk_bundle_number = (1+walk_bundle_number)%(config->cluster_highest_bundleid+1); // +1 avoids divide by zero.
993 ++bcount;
994 }
995
996 //
997 // Did we do something wrong?
998 if (p > (buff + sizeof(buff))) { // Did we somehow manage to overun the buffer?
999 LOG(0, 0, 0, "Overran the heartbeat buffer now! This is fatal. Exiting. (size %d)\n", (int) (p - buff));
1000 kill(0, SIGTERM);
1001 exit(1);
1002 }
1003
1004 LOG(4, 0, 0, "Sending v%d heartbeat #%d, change #%" PRIu64 " with %d changes "
1005 "(%d x-sess, %d x-bundles, %d x-tunnels, %d highsess, %d highbund, %d hightun, size %d)\n",
1006 HB_VERSION, h.seq, h.table_version, config->cluster_num_changes,
1007 count, bcount, tcount, config->cluster_highest_sessionid, config->cluster_highest_bundleid,
1008 config->cluster_highest_tunnelid, (int) (p - buff));
1009
1010 config->cluster_num_changes = 0;
1011
1012 send_heartbeat(h.seq, buff, (p-buff) ); // Send out the heartbeat to the cluster, keeping a copy of it.
1013
1014 config->cluster_seq_number = (config->cluster_seq_number+1)%HB_MAX_SEQ; // Next seq number to use.
1015 }
1016
1017 //
1018 // A structure of type 'type' has changed; Add it to the queue to send.
1019 //
1020 static int type_changed(int type, int id)
1021 {
1022 int i;
1023
1024 for (i = 0 ; i < config->cluster_num_changes ; ++i)
1025 {
1026 if ( cluster_changes[i].id == id && cluster_changes[i].type == type)
1027 {
1028 // Already marked for change, remove it
1029 --config->cluster_num_changes;
1030 memmove(&cluster_changes[i],
1031 &cluster_changes[i+1],
1032 (config->cluster_num_changes - i) * sizeof(cluster_changes[i]));
1033 break;
1034 }
1035 }
1036
1037 cluster_changes[config->cluster_num_changes].type = type;
1038 cluster_changes[config->cluster_num_changes].id = id;
1039 ++config->cluster_num_changes;
1040
1041 if (config->cluster_num_changes > MAX_CHANGES)
1042 cluster_heartbeat(); // flush now
1043
1044 return 1;
1045 }
1046
1047 // A particular session has been changed!
1048 int cluster_send_session(int sid)
1049 {
1050 if (!config->cluster_iam_master) {
1051 LOG(0, sid, 0, "I'm not a master, but I just tried to change a session!\n");
1052 return -1;
1053 }
1054
1055 if (forked) {
1056 LOG(0, sid, 0, "cluster_send_session called from child process!\n");
1057 return -1;
1058 }
1059
1060 return type_changed(C_CSESSION, sid);
1061 }
1062
1063 // A particular bundle has been changed!
1064 int cluster_send_bundle(int bid)
1065 {
1066 if (!config->cluster_iam_master) {
1067 LOG(0, 0, bid, "I'm not a master, but I just tried to change a bundle!\n");
1068 return -1;
1069 }
1070
1071 return type_changed(C_CBUNDLE, bid);
1072 }
1073
1074 // A particular tunnel has been changed!
1075 int cluster_send_tunnel(int tid)
1076 {
1077 if (!config->cluster_iam_master) {
1078 LOG(0, 0, tid, "I'm not a master, but I just tried to change a tunnel!\n");
1079 return -1;
1080 }
1081
1082 return type_changed(C_CTUNNEL, tid);
1083 }
1084
1085
1086 //
1087 // We're a master, and a slave has just told us that it's
1088 // missed a packet. We'll resend it every packet since
1089 // the last one it's seen.
1090 //
1091 static int cluster_catchup_slave(int seq, in_addr_t slave)
1092 {
1093 int s;
1094 int diff;
1095
1096 LOG(1, 0, 0, "Slave %s sent LASTSEEN with seq %d\n", fmtaddr(slave, 0), seq);
1097 if (!config->cluster_iam_master) {
1098 LOG(1, 0, 0, "Got LASTSEEN but I'm not a master! Redirecting it to %s.\n",
1099 fmtaddr(config->cluster_master_address, 0));
1100
1101 peer_send_message(slave, C_MASTER, config->cluster_master_address, NULL, 0);
1102 return 0;
1103 }
1104
1105 diff = config->cluster_seq_number - seq; // How many packet do we need to send?
1106 if (diff < 0)
1107 diff += HB_MAX_SEQ;
1108
1109 if (diff >= HB_HISTORY_SIZE) { // Ouch. We don't have the packet to send it!
1110 LOG(0, 0, 0, "A slave asked for message %d when our seq number is %d. Killing it.\n",
1111 seq, config->cluster_seq_number);
1112 return peer_send_message(slave, C_KILL, seq, NULL, 0);// Kill the slave. Nothing else to do.
1113 }
1114
1115 LOG(1, 0, 0, "Sending %d catchup packets to slave %s\n", diff, fmtaddr(slave, 0) );
1116
1117 // Now resend every packet that it missed, in order.
1118 while (seq != config->cluster_seq_number) {
1119 s = seq % HB_HISTORY_SIZE;
1120 if (seq != past_hearts[s].seq) {
1121 LOG(0, 0, 0, "Tried to re-send heartbeat for %s but %d doesn't match %d! (%d,%d)\n",
1122 fmtaddr(slave, 0), seq, past_hearts[s].seq, s, config->cluster_seq_number);
1123 return -1; // What to do here!?
1124 }
1125 peer_send_data(slave, past_hearts[s].data, past_hearts[s].size);
1126 seq = (seq+1)%HB_MAX_SEQ; // Increment to next seq number.
1127 }
1128 return 0; // All good!
1129 }
1130
1131 //
1132 // We've heard from another peer! Add it to the list
1133 // that we select from at election time.
1134 //
1135 static int cluster_add_peer(in_addr_t peer, time_t basetime, pingt *pp, int size)
1136 {
1137 int i;
1138 in_addr_t clusterid;
1139 pingt p;
1140
1141 // Allow for backward compatability.
1142 // Just the ping packet into a new structure to allow
1143 // for the possibility that we might have received
1144 // more or fewer elements than we were expecting.
1145 if (size > sizeof(p))
1146 size = sizeof(p);
1147
1148 memset( (void *) &p, 0, sizeof(p) );
1149 memcpy( (void *) &p, (void *) pp, size);
1150
1151 clusterid = p.addr;
1152 if (clusterid != config->bind_address)
1153 {
1154 // Is this for us?
1155 LOG(4, 0, 0, "Skipping ping from %s (different cluster)\n", fmtaddr(peer, 0));
1156 return 0;
1157 }
1158
1159 for (i = 0; i < num_peers ; ++i)
1160 {
1161 if (peers[i].peer != peer)
1162 continue;
1163
1164 // This peer already exists. Just update the timestamp.
1165 peers[i].basetime = basetime;
1166 peers[i].timestamp = TIME;
1167 peers[i].uptodate = !p.undef;
1168 break;
1169 }
1170
1171 // Is this the master shutting down??
1172 if (peer == config->cluster_master_address) {
1173 LOG(3, 0, 0, "Master %s %s\n", fmtaddr(config->cluster_master_address, 0),
1174 basetime ? "has restarted!" : "shutting down...");
1175
1176 config->cluster_master_address = 0;
1177 config->cluster_last_hb = 0; // Force an election.
1178 cluster_check_master();
1179 }
1180
1181 if (i >= num_peers)
1182 {
1183 LOG(4, 0, 0, "Adding %s as a peer\n", fmtaddr(peer, 0));
1184
1185 // Not found. Is there a stale slot to re-use?
1186 for (i = 0; i < num_peers ; ++i)
1187 {
1188 if (!peers[i].basetime) // Shutdown
1189 break;
1190
1191 if ((peers[i].timestamp + config->cluster_hb_timeout * 10) < TIME) // Stale.
1192 break;
1193 }
1194
1195 if (i >= CLUSTER_MAX_SIZE)
1196 {
1197 // Too many peers!!
1198 LOG(0, 0, 0, "Tried to add %s as a peer, but I already have %d of them!\n", fmtaddr(peer, 0), i);
1199 return -1;
1200 }
1201
1202 peers[i].peer = peer;
1203 peers[i].basetime = basetime;
1204 peers[i].timestamp = TIME;
1205 peers[i].uptodate = !p.undef;
1206 if (i == num_peers)
1207 ++num_peers;
1208
1209 LOG(1, 0, 0, "Added %s as a new peer. Now %d peers\n", fmtaddr(peer, 0), num_peers);
1210 }
1211
1212 return 1;
1213 }
1214
1215 // A slave responds with C_MASTER when it gets a message which should have gone to a master.
1216 static int cluster_set_master(in_addr_t peer, in_addr_t master)
1217 {
1218 if (config->cluster_iam_master) // Sanity...
1219 return 0;
1220
1221 LOG(3, 0, 0, "Peer %s set the master to %s...\n", fmtaddr(peer, 0),
1222 fmtaddr(master, 1));
1223
1224 config->cluster_master_address = master;
1225 if (master)
1226 {
1227 // catchup with new master
1228 peer_send_message(master, C_LASTSEEN, config->cluster_seq_number, NULL, 0);
1229
1230 // delay next election
1231 config->cluster_last_hb = TIME;
1232 }
1233
1234 // run election (or reset "probed" if master was set)
1235 cluster_check_master();
1236 return 0;
1237 }
1238
1239 /* Handle the slave updating the byte counters for the master. */
1240 //
1241 // Note that we don't mark the session as dirty; We rely on
1242 // the slow table walk to propogate this back out to the slaves.
1243 //
1244 static int cluster_handle_bytes(uint8_t *data, int size)
1245 {
1246 bytest *b;
1247
1248 b = (bytest *) data;
1249
1250 LOG(3, 0, 0, "Got byte counter update (size %d)\n", size);
1251
1252 /* Loop around, adding the byte
1253 counts to each of the sessions. */
1254
1255 while (size >= sizeof(*b) ) {
1256 if (b->sid > MAXSESSION) {
1257 LOG(0, 0, 0, "Got C_BYTES with session #%d!\n", b->sid);
1258 return -1; /* Abort processing */
1259 }
1260
1261 session[b->sid].pin += b->pin;
1262 session[b->sid].pout += b->pout;
1263
1264 increment_counter(&session[b->sid].cin, &session[b->sid].cin_wrap, b->cin);
1265 increment_counter(&session[b->sid].cout, &session[b->sid].cout_wrap, b->cout);
1266
1267 session[b->sid].cin_delta += b->cin;
1268 session[b->sid].cout_delta += b->cout;
1269 session[b->sid].coutgrp_delta += b->cout;
1270
1271 if (b->cin)
1272 session[b->sid].last_packet = session[b->sid].last_data = time_now;
1273 else if (b->cout)
1274 session[b->sid].last_data = time_now;
1275
1276 size -= sizeof(*b);
1277 ++b;
1278 }
1279
1280 if (size != 0)
1281 LOG(0, 0, 0, "Got C_BYTES with %d bytes of trailing junk!\n", size);
1282
1283 return size;
1284 }
1285
1286 //
1287 // Handle receiving a session structure in a heartbeat packet.
1288 //
1289 static int cluster_recv_session(int more, uint8_t *p)
1290 {
1291 if (more >= MAXSESSION) {
1292 LOG(0, 0, 0, "DANGER: Received a heartbeat session id > MAXSESSION!\n");
1293 return -1;
1294 }
1295
1296 if (session[more].tunnel == T_UNDEF) {
1297 if (config->cluster_iam_uptodate) { // Sanity.
1298 LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined session!\n");
1299 } else {
1300 --config->cluster_undefined_sessions;
1301 }
1302 }
1303
1304 load_session(more, (sessiont *) p); // Copy session into session table..
1305
1306 LOG(5, more, 0, "Received session update (%d undef)\n", config->cluster_undefined_sessions);
1307
1308 if (!config->cluster_iam_uptodate)
1309 cluster_uptodate(); // Check to see if we're up to date.
1310
1311 return 0;
1312 }
1313
1314 static int cluster_recv_bundle(int more, uint8_t *p)
1315 {
1316 if (more >= MAXBUNDLE) {
1317 LOG(0, 0, 0, "DANGER: Received a bundle id > MAXBUNDLE!\n");
1318 return -1;
1319 }
1320
1321 if (bundle[more].state == BUNDLEUNDEF) {
1322 if (config->cluster_iam_uptodate) { // Sanity.
1323 LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined bundle!\n");
1324 } else {
1325 --config->cluster_undefined_bundles;
1326 }
1327 }
1328
1329 memcpy(&bundle[more], p, sizeof(bundle[more]) );
1330
1331 LOG(5, 0, more, "Received bundle update\n");
1332
1333 if (!config->cluster_iam_uptodate)
1334 cluster_uptodate(); // Check to see if we're up to date.
1335
1336 return 0;
1337 }
1338
1339 static int cluster_recv_tunnel(int more, uint8_t *p)
1340 {
1341 if (more >= MAXTUNNEL) {
1342 LOG(0, 0, 0, "DANGER: Received a tunnel session id > MAXTUNNEL!\n");
1343 return -1;
1344 }
1345
1346 if (tunnel[more].state == TUNNELUNDEF) {
1347 if (config->cluster_iam_uptodate) { // Sanity.
1348 LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined tunnel!\n");
1349 } else {
1350 --config->cluster_undefined_tunnels;
1351 }
1352 }
1353
1354 memcpy(&tunnel[more], p, sizeof(tunnel[more]) );
1355
1356 //
1357 // Clear tunnel control messages. These are dynamically allocated.
1358 // If we get unlucky, this may cause the tunnel to drop!
1359 //
1360 tunnel[more].controls = tunnel[more].controle = NULL;
1361 tunnel[more].controlc = 0;
1362
1363 LOG(5, 0, more, "Received tunnel update\n");
1364
1365 if (!config->cluster_iam_uptodate)
1366 cluster_uptodate(); // Check to see if we're up to date.
1367
1368 return 0;
1369 }
1370
1371
1372 // pre v6 heartbeat session structure
1373 struct oldsession {
1374 sessionidt next;
1375 sessionidt far;
1376 tunnelidt tunnel;
1377 uint8_t flags;
1378 struct {
1379 uint8_t phase;
1380 uint8_t lcp:4;
1381 uint8_t ipcp:4;
1382 uint8_t ipv6cp:4;
1383 uint8_t ccp:4;
1384 } ppp;
1385 char reserved_1[2];
1386 in_addr_t ip;
1387 int ip_pool_index;
1388 uint32_t unique_id;
1389 char reserved_2[4];
1390 uint32_t magic;
1391 uint32_t pin, pout;
1392 uint32_t cin, cout;
1393 uint32_t cin_wrap, cout_wrap;
1394 uint32_t cin_delta, cout_delta;
1395 uint16_t throttle_in;
1396 uint16_t throttle_out;
1397 uint8_t filter_in;
1398 uint8_t filter_out;
1399 uint16_t mru;
1400 clockt opened;
1401 clockt die;
1402 uint32_t session_timeout;
1403 uint32_t idle_timeout;
1404 time_t last_packet;
1405 time_t last_data;
1406 in_addr_t dns1, dns2;
1407 routet route[MAXROUTE];
1408 uint16_t tbf_in;
1409 uint16_t tbf_out;
1410 int random_vector_length;
1411 uint8_t random_vector[MAXTEL];
1412 char user[MAXUSER];
1413 char called[MAXTEL];
1414 char calling[MAXTEL];
1415 uint32_t tx_connect_speed;
1416 uint32_t rx_connect_speed;
1417 clockt timeout;
1418 uint32_t mrru;
1419 uint8_t mssf;
1420 epdist epdis;
1421 bundleidt bundle;
1422 in_addr_t snoop_ip;
1423 uint16_t snoop_port;
1424 uint8_t walled_garden;
1425 uint8_t ipv6prefixlen;
1426 struct in6_addr ipv6route;
1427 char reserved_3[11];
1428 };
1429
1430 static uint8_t *convert_session(struct oldsession *old)
1431 {
1432 static sessiont new;
1433 int i;
1434
1435 memset(&new, 0, sizeof(new));
1436
1437 new.next = old->next;
1438 new.far = old->far;
1439 new.tunnel = old->tunnel;
1440 new.flags = old->flags;
1441 new.ppp.phase = old->ppp.phase;
1442 new.ppp.lcp = old->ppp.lcp;
1443 new.ppp.ipcp = old->ppp.ipcp;
1444 new.ppp.ipv6cp = old->ppp.ipv6cp;
1445 new.ppp.ccp = old->ppp.ccp;
1446 new.ip = old->ip;
1447 new.ip_pool_index = old->ip_pool_index;
1448 new.unique_id = old->unique_id;
1449 new.magic = old->magic;
1450 new.pin = old->pin;
1451 new.pout = old->pout;
1452 new.cin = old->cin;
1453 new.cout = old->cout;
1454 new.cin_wrap = old->cin_wrap;
1455 new.cout_wrap = old->cout_wrap;
1456 new.cin_delta = old->cin_delta;
1457 new.cout_delta = old->cout_delta;
1458 new.throttle_in = old->throttle_in;
1459 new.throttle_out = old->throttle_out;
1460 new.filter_in = old->filter_in;
1461 new.filter_out = old->filter_out;
1462 new.mru = old->mru;
1463 new.opened = old->opened;
1464 new.die = old->die;
1465 new.session_timeout = old->session_timeout;
1466 new.idle_timeout = old->idle_timeout;
1467 new.last_packet = old->last_packet;
1468 new.last_data = old->last_data;
1469 new.dns1 = old->dns1;
1470 new.dns2 = old->dns2;
1471 new.tbf_in = old->tbf_in;
1472 new.tbf_out = old->tbf_out;
1473 new.random_vector_length = old->random_vector_length;
1474 new.tx_connect_speed = old->tx_connect_speed;
1475 new.rx_connect_speed = old->rx_connect_speed;
1476 new.timeout = old->timeout;
1477 new.mrru = old->mrru;
1478 new.mssf = old->mssf;
1479 new.epdis = old->epdis;
1480 new.bundle = old->bundle;
1481 new.snoop_ip = old->snoop_ip;
1482 new.snoop_port = old->snoop_port;
1483 new.walled_garden = old->walled_garden;
1484 new.ipv6prefixlen = old->ipv6prefixlen;
1485 new.ipv6route = old->ipv6route;
1486
1487 memcpy(new.random_vector, old->random_vector, sizeof(new.random_vector));
1488 memcpy(new.user, old->user, sizeof(new.user));
1489 memcpy(new.called, old->called, sizeof(new.called));
1490 memcpy(new.calling, old->calling, sizeof(new.calling));
1491
1492 for (i = 0; i < MAXROUTE; i++)
1493 memcpy(&new.route[i], &old->route[i], sizeof(new.route[i]));
1494
1495 return (uint8_t *) &new;
1496 }
1497
1498 //
1499 // Process a heartbeat..
1500 //
1501 // v6: added RADIUS class attribute, re-ordered session structure
1502 // v7: added tunnelt attribute at the end of struct (tunnelt size change)
1503 static int cluster_process_heartbeat(uint8_t *data, int size, int more, uint8_t *p, in_addr_t addr)
1504 {
1505 heartt *h;
1506 int s = size - (p-data);
1507 int i, type;
1508 int hb_ver = more;
1509
1510 #if HB_VERSION != 7
1511 # error "need to update cluster_process_heartbeat()"
1512 #endif
1513
1514 // we handle versions 5 through 7
1515 if (hb_ver < 5 || hb_ver > HB_VERSION) {
1516 LOG(0, 0, 0, "Received a heartbeat version that I don't support (%d)!\n", hb_ver);
1517 return -1; // Ignore it??
1518 }
1519
1520 if (size > sizeof(past_hearts[0].data)) {
1521 LOG(0, 0, 0, "Received an oversize heartbeat from %s (%d)!\n", fmtaddr(addr, 0), size);
1522 return -1;
1523 }
1524
1525 if (s < sizeof(*h))
1526 goto shortpacket;
1527
1528 h = (heartt *) p;
1529 p += sizeof(*h);
1530 s -= sizeof(*h);
1531
1532 if (h->clusterid != config->bind_address)
1533 return -1; // It's not part of our cluster.
1534
1535 if (config->cluster_iam_master) { // Sanity...
1536 // Note that this MUST match the election process above!
1537
1538 LOG(0, 0, 0, "I just got a heartbeat from master %s, but _I_ am the master!\n", fmtaddr(addr, 0));
1539 if (!h->basetime) {
1540 LOG(0, 0, 0, "Heartbeat with zero basetime! Ignoring\n");
1541 return -1; // Skip it.
1542 }
1543
1544 if (h->table_version > config->cluster_table_version) {
1545 LOG(0, 0, 0, "They've seen more state changes (%" PRIu64 " vs my %" PRIu64 ") so I'm gone!\n",
1546 h->table_version, config->cluster_table_version);
1547
1548 kill(0, SIGTERM);
1549 exit(1);
1550 }
1551
1552 if (h->table_version < config->cluster_table_version)
1553 return -1;
1554
1555 if (basetime > h->basetime) {
1556 LOG(0, 0, 0, "They're an older master than me so I'm gone!\n");
1557 kill(0, SIGTERM);
1558 exit(1);
1559 }
1560
1561 if (basetime < h->basetime)
1562 return -1;
1563
1564 if (my_address < addr) { // Tie breaker.
1565 LOG(0, 0, 0, "They're a higher IP address than me, so I'm gone!\n");
1566 kill(0, SIGTERM);
1567 exit(1);
1568 }
1569
1570 //
1571 // Send it a unicast heartbeat to see give it a chance to die.
1572 // NOTE: It's actually safe to do seq-number - 1 without checking
1573 // for wrap around.
1574 //
1575 cluster_catchup_slave(config->cluster_seq_number - 1, addr);
1576
1577 return -1; // Skip it.
1578 }
1579
1580 //
1581 // Try and guard against a stray master appearing.
1582 //
1583 // Ignore heartbeats received from another master before the
1584 // timeout (less a smidgen) for the old master has elapsed.
1585 //
1586 // Note that after a clean failover, the cluster_master_address
1587 // is cleared, so this doesn't run.
1588 //
1589 if (config->cluster_master_address && addr != config->cluster_master_address) {
1590 LOG(0, 0, 0, "Ignoring stray heartbeat from %s, current master %s has not yet timed out (last heartbeat %.1f seconds ago).\n",
1591 fmtaddr(addr, 0), fmtaddr(config->cluster_master_address, 1),
1592 0.1 * (TIME - config->cluster_last_hb));
1593 return -1; // ignore
1594 }
1595
1596 if (config->cluster_seq_number == -1) // Don't have one. Just align to the master...
1597 config->cluster_seq_number = h->seq;
1598
1599 config->cluster_last_hb = TIME; // Reset to ensure that we don't become master!!
1600 config->cluster_last_hb_ver = hb_ver; // remember what cluster version the master is using
1601
1602 if (config->cluster_seq_number != h->seq) { // Out of sequence heartbeat!
1603 static int lastseen_seq = 0;
1604 static time_t lastseen_time = 0;
1605
1606 // limit to once per second for a particular seq#
1607 int ask = (config->cluster_seq_number != lastseen_seq || time_now != lastseen_time);
1608
1609 LOG(1, 0, 0, "HB: Got seq# %d but was expecting %d. %s.\n",
1610 h->seq, config->cluster_seq_number,
1611 ask ? "Asking for resend" : "Ignoring");
1612
1613 if (ask)
1614 {
1615 lastseen_seq = config->cluster_seq_number;
1616 lastseen_time = time_now;
1617 peer_send_message(addr, C_LASTSEEN, config->cluster_seq_number, NULL, 0);
1618 }
1619
1620 config->cluster_last_hb = TIME; // Reset to ensure that we don't become master!!
1621
1622 // Just drop the packet. The master will resend it as part of the catchup.
1623
1624 return 0;
1625 }
1626 // Save the packet in our buffer.
1627 // This is needed in case we become the master.
1628 config->cluster_seq_number = (h->seq+1)%HB_MAX_SEQ;
1629 i = h->seq % HB_HISTORY_SIZE;
1630 past_hearts[i].seq = h->seq;
1631 past_hearts[i].size = size;
1632 memcpy(&past_hearts[i].data, data, size); // Save it.
1633
1634
1635 // Check that we don't have too many undefined sessions, and
1636 // that the free session pointer is correct.
1637 cluster_check_sessions(h->highsession, h->freesession, h->highbundle, h->hightunnel);
1638
1639 if (h->interval != config->cluster_hb_interval)
1640 {
1641 LOG(2, 0, 0, "Master set ping/heartbeat interval to %u (was %u)\n",
1642 h->interval, config->cluster_hb_interval);
1643
1644 config->cluster_hb_interval = h->interval;
1645 }
1646
1647 if (h->timeout != config->cluster_hb_timeout)
1648 {
1649 LOG(2, 0, 0, "Master set heartbeat timeout to %u (was %u)\n",
1650 h->timeout, config->cluster_hb_timeout);
1651
1652 config->cluster_hb_timeout = h->timeout;
1653 }
1654
1655 // Ok. process the packet...
1656 while ( s > 0) {
1657
1658 type = *((uint32_t *) p);
1659 p += sizeof(uint32_t);
1660 s -= sizeof(uint32_t);
1661
1662 more = *((uint32_t *) p);
1663 p += sizeof(uint32_t);
1664 s -= sizeof(uint32_t);
1665
1666 switch (type) {
1667 case C_CSESSION: { // Compressed session structure.
1668 uint8_t c[ sizeof(sessiont) + 2];
1669 int size;
1670 uint8_t *orig_p = p;
1671
1672 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c) );
1673 s -= (p - orig_p);
1674
1675 // session struct changed with v5
1676 if (hb_ver < 6)
1677 {
1678 if (size != sizeof(struct oldsession)) {
1679 LOG(0, 0, 0, "DANGER: Received a v%d CSESSION that didn't decompress correctly!\n", hb_ver);
1680 // Now what? Should exit! No-longer up to date!
1681 break;
1682 }
1683 cluster_recv_session(more, convert_session((struct oldsession *) c));
1684 break;
1685 }
1686
1687 if (size != sizeof(sessiont) ) { // Ouch! Very very bad!
1688 LOG(0, 0, 0, "DANGER: Received a CSESSION that didn't decompress correctly!\n");
1689 // Now what? Should exit! No-longer up to date!
1690 break;
1691 }
1692
1693 cluster_recv_session(more, c);
1694 break;
1695 }
1696 case C_SESSION:
1697 if (hb_ver < 6)
1698 {
1699 if (s < sizeof(struct oldsession))
1700 goto shortpacket;
1701
1702 cluster_recv_session(more, convert_session((struct oldsession *) p));
1703
1704 p += sizeof(struct oldsession);
1705 s -= sizeof(struct oldsession);
1706 break;
1707 }
1708
1709 if ( s < sizeof(session[more]))
1710 goto shortpacket;
1711
1712 cluster_recv_session(more, p);
1713
1714 p += sizeof(session[more]);
1715 s -= sizeof(session[more]);
1716 break;
1717
1718 case C_CTUNNEL: { // Compressed tunnel structure.
1719 uint8_t c[ sizeof(tunnelt) + 2];
1720 int size;
1721 uint8_t *orig_p = p;
1722
1723 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c));
1724 s -= (p - orig_p);
1725
1726 if ( ((hb_ver >= HB_VERSION) && (size != sizeof(tunnelt))) ||
1727 ((hb_ver < HB_VERSION) && (size > sizeof(tunnelt))) )
1728 { // Ouch! Very very bad!
1729 LOG(0, 0, 0, "DANGER: Received a CTUNNEL that didn't decompress correctly!\n");
1730 // Now what? Should exit! No-longer up to date!
1731 break;
1732 }
1733
1734 cluster_recv_tunnel(more, c);
1735 break;
1736
1737 }
1738 case C_TUNNEL:
1739 if ( s < sizeof(tunnel[more]))
1740 goto shortpacket;
1741
1742 cluster_recv_tunnel(more, p);
1743
1744 p += sizeof(tunnel[more]);
1745 s -= sizeof(tunnel[more]);
1746 break;
1747
1748 case C_CBUNDLE: { // Compressed bundle structure.
1749 uint8_t c[ sizeof(bundlet) + 2];
1750 int size;
1751 uint8_t *orig_p = p;
1752
1753 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c));
1754 s -= (p - orig_p);
1755
1756 if (size != sizeof(bundlet) ) { // Ouch! Very very bad!
1757 LOG(0, 0, 0, "DANGER: Received a CBUNDLE that didn't decompress correctly!\n");
1758 // Now what? Should exit! No-longer up to date!
1759 break;
1760 }
1761
1762 cluster_recv_bundle(more, c);
1763 break;
1764
1765 }
1766 case C_BUNDLE:
1767 if ( s < sizeof(bundle[more]))
1768 goto shortpacket;
1769
1770 cluster_recv_bundle(more, p);
1771
1772 p += sizeof(bundle[more]);
1773 s -= sizeof(bundle[more]);
1774 break;
1775 default:
1776 LOG(0, 0, 0, "DANGER: I received a heartbeat element where I didn't understand the type! (%d)\n", type);
1777 return -1; // can't process any more of the packet!!
1778 }
1779 }
1780
1781 if (config->cluster_master_address != addr)
1782 {
1783 LOG(0, 0, 0, "My master just changed from %s to %s!\n",
1784 fmtaddr(config->cluster_master_address, 0), fmtaddr(addr, 1));
1785
1786 config->cluster_master_address = addr;
1787 }
1788
1789 config->cluster_last_hb = TIME; // Successfully received a heartbeat!
1790 config->cluster_table_version = h->table_version;
1791 return 0;
1792
1793 shortpacket:
1794 LOG(0, 0, 0, "I got an incomplete heartbeat packet! This means I'm probably out of sync!!\n");
1795 return -1;
1796 }
1797
1798 //
1799 // We got a packet on the cluster port!
1800 // Handle pings, lastseens, and heartbeats!
1801 //
1802 int processcluster(uint8_t *data, int size, in_addr_t addr)
1803 {
1804 int type, more;
1805 uint8_t *p = data;
1806 int s = size;
1807
1808 if (addr == my_address)
1809 return -1; // Ignore it. Something looped back the multicast!
1810
1811 LOG(5, 0, 0, "Process cluster: %d bytes from %s\n", size, fmtaddr(addr, 0));
1812
1813 if (s <= 0) // Any data there??
1814 return -1;
1815
1816 if (s < 8)
1817 goto shortpacket;
1818
1819 type = *((uint32_t *) p);
1820 p += sizeof(uint32_t);
1821 s -= sizeof(uint32_t);
1822
1823 more = *((uint32_t *) p);
1824 p += sizeof(uint32_t);
1825 s -= sizeof(uint32_t);
1826
1827 switch (type)
1828 {
1829 case C_PING: // Update the peers table.
1830 return cluster_add_peer(addr, more, (pingt *) p, s);
1831
1832 case C_MASTER: // Our master is wrong
1833 return cluster_set_master(addr, more);
1834
1835 case C_LASTSEEN: // Catch up a slave (slave missed a packet).
1836 return cluster_catchup_slave(more, addr);
1837
1838 case C_FORWARD: // Forwarded control packet. pass off to processudp.
1839 case C_FORWARD_DAE: // Forwarded DAE packet. pass off to processdae.
1840 if (!config->cluster_iam_master)
1841 {
1842 LOG(0, 0, 0, "I'm not the master, but I got a C_FORWARD%s from %s?\n",
1843 type == C_FORWARD_DAE ? "_DAE" : "", fmtaddr(addr, 0));
1844
1845 return -1;
1846 }
1847 else
1848 {
1849 struct sockaddr_in a;
1850 uint16_t indexudp;
1851 a.sin_addr.s_addr = more;
1852
1853 a.sin_port = (*(int *) p) & 0xFFFF;
1854 indexudp = ((*(int *) p) >> 16) & 0xFFFF;
1855 s -= sizeof(int);
1856 p += sizeof(int);
1857
1858 LOG(4, 0, 0, "Got a forwarded %spacket... (%s:%d)\n",
1859 type == C_FORWARD_DAE ? "DAE " : "", fmtaddr(more, 0), a.sin_port);
1860
1861 STAT(recv_forward);
1862 if (type == C_FORWARD_DAE)
1863 {
1864 struct in_addr local;
1865 local.s_addr = config->bind_address ? config->bind_address : my_address;
1866 processdae(p, s, &a, sizeof(a), &local);
1867 }
1868 else
1869 processudp(p, s, &a, indexudp);
1870
1871 return 0;
1872 }
1873 case C_PPPOE_FORWARD:
1874 if (!config->cluster_iam_master)
1875 {
1876 LOG(0, 0, 0, "I'm not the master, but I got a C_PPPOE_FORWARD from %s?\n", fmtaddr(addr, 0));
1877 return -1;
1878 }
1879 else
1880 {
1881 pppoe_process_forward(p, s, addr);
1882 return 0;
1883 }
1884
1885 case C_MPPP_FORWARD:
1886 // Receive a MPPP packet from a slave.
1887 if (!config->cluster_iam_master) {
1888 LOG(0, 0, 0, "I'm not the master, but I got a C_MPPP_FORWARD from %s?\n", fmtaddr(addr, 0));
1889 return -1;
1890 }
1891
1892 processipout(p, s);
1893 return 0;
1894
1895 case C_THROTTLE: { // Receive a forwarded packet from a slave.
1896 if (!config->cluster_iam_master) {
1897 LOG(0, 0, 0, "I'm not the master, but I got a C_THROTTLE from %s?\n", fmtaddr(addr, 0));
1898 return -1;
1899 }
1900
1901 tbf_queue_packet(more, p, s); // The TBF id tells wether it goes in or out.
1902 return 0;
1903 }
1904 case C_GARDEN:
1905 // Receive a walled garden packet from a slave.
1906 if (!config->cluster_iam_master) {
1907 LOG(0, 0, 0, "I'm not the master, but I got a C_GARDEN from %s?\n", fmtaddr(addr, 0));
1908 return -1;
1909 }
1910
1911 tun_write(p, s);
1912 return 0;
1913
1914 case C_BYTES:
1915 if (!config->cluster_iam_master) {
1916 LOG(0, 0, 0, "I'm not the master, but I got a C_BYTES from %s?\n", fmtaddr(addr, 0));
1917 return -1;
1918 }
1919
1920 return cluster_handle_bytes(p, s);
1921
1922 case C_KILL: // The master asked us to die!? (usually because we're too out of date).
1923 if (config->cluster_iam_master) {
1924 LOG(0, 0, 0, "_I_ am master, but I received a C_KILL from %s! (Seq# %d)\n", fmtaddr(addr, 0), more);
1925 return -1;
1926 }
1927 if (more != config->cluster_seq_number) {
1928 LOG(0, 0, 0, "The master asked us to die but the seq number didn't match!?\n");
1929 return -1;
1930 }
1931
1932 if (addr != config->cluster_master_address) {
1933 LOG(0, 0, 0, "Received a C_KILL from %s which doesn't match config->cluster_master_address (%s)\n",
1934 fmtaddr(addr, 0), fmtaddr(config->cluster_master_address, 1));
1935 // We can only warn about it. The master might really have switched!
1936 }
1937
1938 LOG(0, 0, 0, "Received a valid C_KILL: I'm going to die now.\n");
1939 kill(0, SIGTERM);
1940 exit(0); // Lets be paranoid;
1941 return -1; // Just signalling the compiler.
1942
1943 case C_HEARTBEAT:
1944 LOG(4, 0, 0, "Got a heartbeat from %s\n", fmtaddr(addr, 0));
1945 return cluster_process_heartbeat(data, size, more, p, addr);
1946
1947 default:
1948 LOG(0, 0, 0, "Strange type packet received on cluster socket (%d)\n", type);
1949 return -1;
1950 }
1951 return 0;
1952
1953 shortpacket:
1954 LOG(0, 0, 0, "I got a _short_ cluster heartbeat packet! This means I'm probably out of sync!!\n");
1955 return -1;
1956 }
1957
1958 //====================================================================================================
1959
1960 int cmd_show_cluster(struct cli_def *cli, char *command, char **argv, int argc)
1961 {
1962 int i;
1963
1964 if (CLI_HELP_REQUESTED)
1965 return CLI_HELP_NO_ARGS;
1966
1967 cli_print(cli, "Cluster status : %s", config->cluster_iam_master ? "Master" : "Slave" );
1968 cli_print(cli, "My address : %s", fmtaddr(my_address, 0));
1969 cli_print(cli, "VIP address : %s", fmtaddr(config->bind_address, 0));
1970 cli_print(cli, "Multicast address: %s", fmtaddr(config->cluster_address, 0));
1971 cli_print(cli, "Multicast i'face : %s", config->cluster_interface);
1972
1973 if (!config->cluster_iam_master) {
1974 cli_print(cli, "My master : %s (last heartbeat %.1f seconds old)",
1975 config->cluster_master_address
1976 ? fmtaddr(config->cluster_master_address, 0)
1977 : "Not defined",
1978 0.1 * (TIME - config->cluster_last_hb));
1979 cli_print(cli, "Uptodate : %s", config->cluster_iam_uptodate ? "Yes" : "No");
1980 cli_print(cli, "Table version # : %" PRIu64, config->cluster_table_version);
1981 cli_print(cli, "Next sequence number expected: %d", config->cluster_seq_number);
1982 cli_print(cli, "%d sessions undefined of %d", config->cluster_undefined_sessions, config->cluster_highest_sessionid);
1983 cli_print(cli, "%d bundles undefined of %d", config->cluster_undefined_bundles, config->cluster_highest_bundleid);
1984 cli_print(cli, "%d tunnels undefined of %d", config->cluster_undefined_tunnels, config->cluster_highest_tunnelid);
1985 } else {
1986 cli_print(cli, "Table version # : %" PRIu64, config->cluster_table_version);
1987 cli_print(cli, "Next heartbeat # : %d", config->cluster_seq_number);
1988 cli_print(cli, "Highest session : %d", config->cluster_highest_sessionid);
1989 cli_print(cli, "Highest bundle : %d", config->cluster_highest_bundleid);
1990 cli_print(cli, "Highest tunnel : %d", config->cluster_highest_tunnelid);
1991 cli_print(cli, "%d changes queued for sending", config->cluster_num_changes);
1992 }
1993 cli_print(cli, "%d peers.", num_peers);
1994
1995 if (num_peers)
1996 cli_print(cli, "%20s %10s %8s", "Address", "Basetime", "Age");
1997 for (i = 0; i < num_peers; ++i) {
1998 cli_print(cli, "%20s %10u %8d", fmtaddr(peers[i].peer, 0),
1999 peers[i].basetime, TIME - peers[i].timestamp);
2000 }
2001 return CLI_OK;
2002 }
2003
2004 //
2005 // Simple run-length-encoding compression.
2006 // Format is
2007 // 1 byte < 128 = count of non-zero bytes following. // Not legal to be zero.
2008 // n non-zero bytes;
2009 // or
2010 // 1 byte > 128 = (count - 128) run of zero bytes. //
2011 // repeat.
2012 // count == 0 indicates end of compressed stream.
2013 //
2014 // Compress from 'src' into 'dst'. return number of bytes
2015 // used from 'dst'.
2016 // Updates *src_p to indicate 1 past last bytes used.
2017 //
2018 // We could get an extra byte in the zero runs by storing (count-1)
2019 // but I'm playing it safe.
2020 //
2021 // Worst case is a 50% expansion in space required (trying to
2022 // compress { 0x00, 0x01 } * N )
2023 static int rle_compress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize)
2024 {
2025 int count;
2026 int orig_dsize = dsize;
2027 uint8_t *x, *src;
2028 src = *src_p;
2029
2030 while (ssize > 0 && dsize > 2) {
2031 count = 0;
2032 x = dst++; --dsize; // Reserve space for count byte..
2033
2034 if (*src) { // Copy a run of non-zero bytes.
2035 while (*src && count < 127 && ssize > 0 && dsize > 1) { // Count number of non-zero bytes.
2036 *dst++ = *src++;
2037 --dsize; --ssize;
2038 ++count;
2039 }
2040 *x = count; // Store number of non-zero bytes. Guarenteed to be non-zero!
2041
2042 } else { // Compress a run of zero bytes.
2043 while (*src == 0 && count < 127 && ssize > 0) {
2044 ++src;
2045 --ssize;
2046 ++count;
2047 }
2048 *x = count | 0x80 ;
2049 }
2050 }
2051
2052 *dst++ = 0x0; // Add Stop byte.
2053 --dsize;
2054
2055 *src_p = src;
2056 return (orig_dsize - dsize);
2057 }
2058
2059 //
2060 // Decompress the buffer into **p.
2061 // 'psize' is the size of the decompression buffer available.
2062 //
2063 // Returns the number of bytes decompressed.
2064 //
2065 // Decompresses from '*src_p' into 'dst'.
2066 // Return the number of dst bytes used.
2067 // Updates the 'src_p' pointer to point to the
2068 // first un-used byte.
2069 static int rle_decompress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize)
2070 {
2071 int count;
2072 int orig_dsize = dsize;
2073 uint8_t *src = *src_p;
2074
2075 while (ssize >0 && dsize > 0) { // While there's more to decompress, and there's room in the decompress buffer...
2076 count = *src++; --ssize; // get the count byte from the source.
2077 if (count == 0x0) // End marker reached? If so, finish.
2078 break;
2079
2080 if (count & 0x80) { // Decompress a run of zeros
2081 for (count &= 0x7f ; count > 0 && dsize > 0; --count) {
2082 *dst++ = 0x0;
2083 --dsize;
2084 }
2085 } else { // Copy run of non-zero bytes.
2086 for ( ; count > 0 && ssize && dsize; --count) { // Copy non-zero bytes across.
2087 *dst++ = *src++;
2088 --ssize; --dsize;
2089 }
2090 }
2091 }
2092 *src_p = src;
2093 return (orig_dsize - dsize);
2094 }