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