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