Update changelog
[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 struct oldsessionV7 {
1542 sessionidt next; // next session in linked list
1543 sessionidt far; // far end session ID
1544 tunnelidt tunnel; // near end tunnel ID
1545 uint8_t flags; // session flags: see SESSION_*
1546 struct {
1547 uint8_t phase; // PPP phase
1548 uint8_t lcp:4; // LCP state
1549 uint8_t ipcp:4; // IPCP state
1550 uint8_t ipv6cp:4; // IPV6CP state
1551 uint8_t ccp:4; // CCP state
1552 } ppp;
1553 uint16_t mru; // maximum receive unit
1554 in_addr_t ip; // IP of session set by RADIUS response (host byte order).
1555 int ip_pool_index; // index to IP pool
1556 uint32_t unique_id; // unique session id
1557 uint32_t magic; // ppp magic number
1558 uint32_t pin, pout; // packet counts
1559 uint32_t cin, cout; // byte counts
1560 uint32_t cin_wrap, cout_wrap; // byte counter wrap count (RADIUS accounting giagawords)
1561 uint32_t cin_delta, cout_delta; // byte count changes (for dump_session())
1562 uint16_t throttle_in; // upstream throttle rate (kbps)
1563 uint16_t throttle_out; // downstream throttle rate
1564 uint8_t filter_in; // input filter index (to ip_filters[N-1]; 0 if none)
1565 uint8_t filter_out; // output filter index
1566 uint16_t snoop_port; // Interception destination port
1567 in_addr_t snoop_ip; // Interception destination IP
1568 clockt opened; // when started
1569 clockt die; // being closed, when to finally free
1570 uint32_t session_timeout; // Maximum session time in seconds
1571 uint32_t idle_timeout; // Maximum idle time in seconds
1572 time_t last_packet; // Last packet from the user (used for idle timeouts)
1573 time_t last_data; // Last data packet to/from the user (used for idle timeouts)
1574 in_addr_t dns1, dns2; // DNS servers
1575 routet route[MAXROUTE]; // static routes
1576 uint16_t tbf_in; // filter bucket for throttling in from the user.
1577 uint16_t tbf_out; // filter bucket for throttling out to the user.
1578 int random_vector_length;
1579 uint8_t random_vector[MAXTEL];
1580 char user[MAXUSER]; // user (needed in session for radius stop messages)
1581 char called[MAXTEL]; // called number
1582 char calling[MAXTEL]; // calling number
1583 uint32_t tx_connect_speed;
1584 uint32_t rx_connect_speed;
1585 clockt timeout; // Session timeout
1586 uint32_t mrru; // Multilink Max-Receive-Reconstructed-Unit
1587 epdist epdis; // Multilink Endpoint Discriminator
1588 bundleidt bundle; // Multilink Bundle Identifier
1589 uint8_t mssf; // Multilink Short Sequence Number Header Format
1590 uint8_t walled_garden; // is this session gardened?
1591 uint8_t classlen; // class (needed for radius accounting messages)
1592 char class[MAXCLASS];
1593 uint8_t ipv6prefixlen; // IPv6 route prefix length
1594 struct in6_addr ipv6route; // Static IPv6 route
1595 sessionidt forwardtosession; // LNS id_session to forward
1596 uint8_t src_hwaddr[ETH_ALEN]; // MAC addr source (for pppoe sessions 6 bytes)
1597 char reserved[4]; // Space to expand structure without changing HB_VERSION
1598 };
1599
1600 struct oldsessionV8 {
1601 sessionidt next; // next session in linked list
1602 sessionidt far; // far end session ID
1603 tunnelidt tunnel; // near end tunnel ID
1604 uint8_t flags; // session flags: see SESSION_*
1605 struct {
1606 uint8_t phase; // PPP phase
1607 uint8_t lcp:4; // LCP state
1608 uint8_t ipcp:4; // IPCP state
1609 uint8_t ipv6cp:4; // IPV6CP state
1610 uint8_t ccp:4; // CCP state
1611 } ppp;
1612 uint16_t mru; // maximum receive unit
1613 in_addr_t ip; // IP of session set by RADIUS response (host byte order).
1614 int ip_pool_index; // index to IP pool
1615 uint32_t unique_id; // unique session id
1616 uint32_t magic; // ppp magic number
1617 uint32_t pin, pout; // packet counts
1618 uint32_t cin, cout; // byte counts
1619 uint32_t cin_wrap, cout_wrap; // byte counter wrap count (RADIUS accounting giagawords)
1620 uint32_t cin_delta, cout_delta; // byte count changes (for dump_session())
1621 uint16_t throttle_in; // upstream throttle rate (kbps)
1622 uint16_t throttle_out; // downstream throttle rate
1623 uint8_t filter_in; // input filter index (to ip_filters[N-1]; 0 if none)
1624 uint8_t filter_out; // output filter index
1625 uint16_t snoop_port; // Interception destination port
1626 in_addr_t snoop_ip; // Interception destination IP
1627 clockt opened; // when started
1628 clockt die; // being closed, when to finally free
1629 uint32_t session_timeout; // Maximum session time in seconds
1630 uint32_t idle_timeout; // Maximum idle time in seconds
1631 time_t last_packet; // Last packet from the user (used for idle timeouts)
1632 time_t last_data; // Last data packet to/from the user (used for idle timeouts)
1633 in_addr_t dns1, dns2; // DNS servers
1634 routet route[MAXROUTE]; // static routes
1635 uint16_t tbf_in; // filter bucket for throttling in from the user.
1636 uint16_t tbf_out; // filter bucket for throttling out to the user.
1637 int random_vector_length;
1638 uint8_t random_vector[MAXTEL];
1639 char user[MAXUSER]; // user (needed in session for radius stop messages)
1640 char called[MAXTEL]; // called number
1641 char calling[MAXTEL]; // calling number
1642 uint32_t tx_connect_speed;
1643 uint32_t rx_connect_speed;
1644 clockt timeout; // Session timeout
1645 uint32_t mrru; // Multilink Max-Receive-Reconstructed-Unit
1646 epdist epdis; // Multilink Endpoint Discriminator
1647 bundleidt bundle; // Multilink Bundle Identifier
1648 uint8_t mssf; // Multilink Short Sequence Number Header Format
1649 uint8_t walled_garden; // is this session gardened?
1650 uint8_t classlen; // class (needed for radius accounting messages)
1651 char class[MAXCLASS];
1652 uint8_t ipv6prefixlen; // IPv6 route prefix length
1653 struct in6_addr ipv6route; // Static IPv6 route
1654 sessionidt forwardtosession; // LNS id_session to forward
1655 uint8_t src_hwaddr[ETH_ALEN]; // MAC addr source (for pppoe sessions 6 bytes)
1656 uint32_t dhcpv6_prefix_iaid; // prefix iaid requested by client
1657 uint32_t dhcpv6_iana_iaid; // iaid of iana requested by client
1658 struct in6_addr ipv6address; // Framed Ipv6 address
1659 struct dhcp6_opt_clientid dhcpv6_client_id; // Size max (headers + DUID)
1660 char reserved[4]; // Space to expand structure without changing HB_VERSION
1661 };
1662
1663 static uint8_t *convert_session(struct oldsession *old)
1664 {
1665 static sessiont new;
1666 int i;
1667
1668 memset(&new, 0, sizeof(new));
1669
1670 new.next = old->next;
1671 new.far = old->far;
1672 new.tunnel = old->tunnel;
1673 new.flags = old->flags;
1674 new.ppp.phase = old->ppp.phase;
1675 new.ppp.lcp = old->ppp.lcp;
1676 new.ppp.ipcp = old->ppp.ipcp;
1677 new.ppp.ipv6cp = old->ppp.ipv6cp;
1678 new.ppp.ccp = old->ppp.ccp;
1679 new.ip = old->ip;
1680 new.ip_pool_index = old->ip_pool_index;
1681 new.unique_id = old->unique_id;
1682 new.magic = old->magic;
1683 new.pin = old->pin;
1684 new.pout = old->pout;
1685 new.cin = old->cin;
1686 new.cout = old->cout;
1687 new.cin_wrap = old->cin_wrap;
1688 new.cout_wrap = old->cout_wrap;
1689 new.cin_delta = old->cin_delta;
1690 new.cout_delta = old->cout_delta;
1691 new.throttle_in = old->throttle_in;
1692 new.throttle_out = old->throttle_out;
1693 new.filter_in = old->filter_in;
1694 new.filter_out = old->filter_out;
1695 new.mru = old->mru;
1696 new.opened = old->opened;
1697 new.die = old->die;
1698 new.session_timeout = old->session_timeout;
1699 new.idle_timeout = old->idle_timeout;
1700 new.last_packet = old->last_packet;
1701 new.last_data = old->last_data;
1702 new.dns1 = old->dns1;
1703 new.dns2 = old->dns2;
1704 new.tbf_in = old->tbf_in;
1705 new.tbf_out = old->tbf_out;
1706 new.random_vector_length = old->random_vector_length;
1707 new.tx_connect_speed = old->tx_connect_speed;
1708 new.rx_connect_speed = old->rx_connect_speed;
1709 new.timeout = old->timeout;
1710 new.mrru = old->mrru;
1711 new.mssf = old->mssf;
1712 new.epdis = old->epdis;
1713 new.bundle = old->bundle;
1714 new.snoop_ip = old->snoop_ip;
1715 new.snoop_port = old->snoop_port;
1716 new.walled_garden = old->walled_garden;
1717 new.route6[0].ipv6prefixlen = old->ipv6prefixlen;
1718 new.route6[0].ipv6route = old->ipv6route;
1719
1720 memcpy(new.random_vector, old->random_vector, sizeof(new.random_vector));
1721 memcpy(new.user, old->user, sizeof(new.user));
1722 memcpy(new.called, old->called, sizeof(new.called));
1723 memcpy(new.calling, old->calling, sizeof(new.calling));
1724
1725 for (i = 0; i < MAXROUTE; i++)
1726 memcpy(&new.route[i], &old->route[i], sizeof(new.route[i]));
1727
1728 return (uint8_t *) &new;
1729 }
1730
1731 static uint8_t *convert_sessionV7(struct oldsessionV7 *old)
1732 {
1733 static sessiont new;
1734 int i;
1735
1736 memset(&new, 0, sizeof(new));
1737
1738 new.next = old->next;
1739 new.far = old->far;
1740 new.tunnel = old->tunnel;
1741 new.flags = old->flags;
1742 new.ppp.phase = old->ppp.phase;
1743 new.ppp.lcp = old->ppp.lcp;
1744 new.ppp.ipcp = old->ppp.ipcp;
1745 new.ppp.ipv6cp = old->ppp.ipv6cp;
1746 new.ppp.ccp = old->ppp.ccp;
1747 new.mru = old->mru;
1748 new.ip = old->ip;
1749 new.ip_pool_index = old->ip_pool_index;
1750 new.unique_id = old->unique_id;
1751 new.magic = old->magic;
1752 new.pin = old->pin;
1753 new.pout = old->pout;
1754 new.cin = old->cin;
1755 new.cout = old->cout;
1756 new.cin_wrap = old->cin_wrap;
1757 new.cout_wrap = old->cout_wrap;
1758 new.cin_delta = old->cin_delta;
1759 new.cout_delta = old->cout_delta;
1760 new.throttle_in = old->throttle_in;
1761 new.throttle_out = old->throttle_out;
1762 new.filter_in = old->filter_in;
1763 new.filter_out = old->filter_out;
1764 new.snoop_port = old->snoop_port;
1765 new.snoop_ip = old->snoop_ip;
1766 new.opened = old->opened;
1767 new.die = old->die;
1768 new.session_timeout = old->session_timeout;
1769 new.idle_timeout = old->idle_timeout;
1770 new.last_packet = old->last_packet;
1771 new.last_data = old->last_data;
1772 new.dns1 = old->dns1;
1773 new.dns2 = old->dns2;
1774 for (i = 0; i < MAXROUTE; i++)
1775 memcpy(&new.route[i], &old->route[i], sizeof(new.route[i]));
1776 new.tbf_in = old->tbf_in;
1777 new.tbf_out = old->tbf_out;
1778 new.random_vector_length = old->random_vector_length;
1779 memcpy(new.random_vector, old->random_vector, sizeof(new.random_vector));
1780 memcpy(new.user, old->user, sizeof(new.user));
1781 memcpy(new.called, old->called, sizeof(new.called));
1782 memcpy(new.calling, old->calling, sizeof(new.calling));
1783 new.tx_connect_speed = old->tx_connect_speed;
1784 new.rx_connect_speed = old->rx_connect_speed;
1785 new.timeout = old->timeout;
1786 new.mrru = old->mrru;
1787 new.epdis = old->epdis;
1788 new.bundle = old->bundle;
1789 new.mssf = old->mssf;
1790 new.walled_garden = old->walled_garden;
1791 new.classlen = old->classlen;
1792 memcpy(new.class, old->class, sizeof(new.class));
1793 new.route6[0].ipv6prefixlen = old->ipv6prefixlen;
1794 new.route6[0].ipv6route = old->ipv6route;
1795
1796 new.forwardtosession = old->forwardtosession;
1797 memcpy(new.src_hwaddr, old->src_hwaddr, sizeof(new.src_hwaddr));
1798
1799 return (uint8_t *) &new;
1800 }
1801
1802 static uint8_t *convert_sessionV8(struct oldsessionV8 *old)
1803 {
1804 static sessiont new;
1805 int i;
1806
1807 memset(&new, 0, sizeof(new));
1808
1809 new.next = old->next;
1810 new.far = old->far;
1811 new.tunnel = old->tunnel;
1812 new.flags = old->flags;
1813 new.ppp.phase = old->ppp.phase;
1814 new.ppp.lcp = old->ppp.lcp;
1815 new.ppp.ipcp = old->ppp.ipcp;
1816 new.ppp.ipv6cp = old->ppp.ipv6cp;
1817 new.ppp.ccp = old->ppp.ccp;
1818 new.mru = old->mru;
1819 new.ip = old->ip;
1820 new.ip_pool_index = old->ip_pool_index;
1821 new.unique_id = old->unique_id;
1822 new.magic = old->magic;
1823 new.pin = old->pin;
1824 new.pout = old->pout;
1825 new.cin = old->cin;
1826 new.cout = old->cout;
1827 new.cin_wrap = old->cin_wrap;
1828 new.cout_wrap = old->cout_wrap;
1829 new.cin_delta = old->cin_delta;
1830 new.cout_delta = old->cout_delta;
1831 new.throttle_in = old->throttle_in;
1832 new.throttle_out = old->throttle_out;
1833 new.filter_in = old->filter_in;
1834 new.filter_out = old->filter_out;
1835 new.snoop_port = old->snoop_port;
1836 new.snoop_ip = old->snoop_ip;
1837 new.opened = old->opened;
1838 new.die = old->die;
1839 new.session_timeout = old->session_timeout;
1840 new.idle_timeout = old->idle_timeout;
1841 new.last_packet = old->last_packet;
1842 new.last_data = old->last_data;
1843 new.dns1 = old->dns1;
1844 new.dns2 = old->dns2;
1845 for (i = 0; i < MAXROUTE; i++)
1846 memcpy(&new.route[i], &old->route[i], sizeof(new.route[i]));
1847 new.tbf_in = old->tbf_in;
1848 new.tbf_out = old->tbf_out;
1849 new.random_vector_length = old->random_vector_length;
1850 memcpy(new.random_vector, old->random_vector, sizeof(new.random_vector));
1851 memcpy(new.user, old->user, sizeof(new.user));
1852 memcpy(new.called, old->called, sizeof(new.called));
1853 memcpy(new.calling, old->calling, sizeof(new.calling));
1854 new.tx_connect_speed = old->tx_connect_speed;
1855 new.rx_connect_speed = old->rx_connect_speed;
1856 new.timeout = old->timeout;
1857 new.mrru = old->mrru;
1858 new.epdis = old->epdis;
1859 new.bundle = old->bundle;
1860 new.mssf = old->mssf;
1861 new.walled_garden = old->walled_garden;
1862 new.classlen = old->classlen;
1863 memcpy(new.class, old->class, sizeof(new.class));
1864 new.route6[0].ipv6prefixlen = old->ipv6prefixlen;
1865 new.route6[0].ipv6route = old->ipv6route;
1866
1867 new.forwardtosession = old->forwardtosession;
1868 memcpy(new.src_hwaddr, old->src_hwaddr, sizeof(new.src_hwaddr));
1869 new.dhcpv6_prefix_iaid = old->dhcpv6_prefix_iaid;
1870 new.dhcpv6_iana_iaid = old->dhcpv6_iana_iaid;
1871 new.ipv6address = old->ipv6address;
1872 new.dhcpv6_client_id = old->dhcpv6_client_id;
1873
1874 return (uint8_t *) &new;
1875 }
1876
1877 //
1878 // Process a heartbeat..
1879 //
1880 // v6: added RADIUS class attribute, re-ordered session structure
1881 // v7: added tunnelt attribute at the end of struct (tunnelt size change)
1882 static int cluster_process_heartbeat(uint8_t *data, int size, int more, uint8_t *p, in_addr_t addr)
1883 {
1884 heartt *h;
1885 int s = size - (p-data);
1886 int i, type;
1887 int hb_ver = more;
1888
1889 #if HB_VERSION != 9
1890 # error "need to update cluster_process_heartbeat()"
1891 #endif
1892
1893 // we handle versions 5 through 8
1894 if (hb_ver < 5 || hb_ver > HB_VERSION) {
1895 LOG(0, 0, 0, "Received a heartbeat version that I don't support (%d)!\n", hb_ver);
1896 return -1; // Ignore it??
1897 }
1898
1899 if (size > sizeof(past_hearts[0].data)) {
1900 LOG(0, 0, 0, "Received an oversize heartbeat from %s (%d)!\n", fmtaddr(addr, 0), size);
1901 return -1;
1902 }
1903
1904 if (s < sizeof(*h))
1905 goto shortpacket;
1906
1907 h = (heartt *) p;
1908 p += sizeof(*h);
1909 s -= sizeof(*h);
1910
1911 if (h->clusterid != config->bind_address)
1912 return -1; // It's not part of our cluster.
1913
1914 if (config->cluster_iam_master) { // Sanity...
1915 // Note that this MUST match the election process above!
1916
1917 LOG(0, 0, 0, "I just got a heartbeat from master %s, but _I_ am the master!\n", fmtaddr(addr, 0));
1918 if (!h->basetime) {
1919 LOG(0, 0, 0, "Heartbeat with zero basetime! Ignoring\n");
1920 return -1; // Skip it.
1921 }
1922
1923 if (h->table_version > config->cluster_table_version) {
1924 LOG(0, 0, 0, "They've seen more state changes (%" PRIu64 " vs my %" PRIu64 ") so I'm gone!\n",
1925 h->table_version, config->cluster_table_version);
1926
1927 kill(0, SIGTERM);
1928 exit(1);
1929 }
1930
1931 if (h->table_version < config->cluster_table_version)
1932 return -1;
1933
1934 if (basetime > h->basetime) {
1935 LOG(0, 0, 0, "They're an older master than me so I'm gone!\n");
1936 kill(0, SIGTERM);
1937 exit(1);
1938 }
1939
1940 if (basetime < h->basetime)
1941 return -1;
1942
1943 if (my_address < addr) { // Tie breaker.
1944 LOG(0, 0, 0, "They're a higher IP address than me, so I'm gone!\n");
1945 kill(0, SIGTERM);
1946 exit(1);
1947 }
1948
1949 //
1950 // Send it a unicast heartbeat to see give it a chance to die.
1951 // NOTE: It's actually safe to do seq-number - 1 without checking
1952 // for wrap around.
1953 //
1954 cluster_catchup_slave(config->cluster_seq_number - 1, addr);
1955
1956 return -1; // Skip it.
1957 }
1958
1959 //
1960 // Try and guard against a stray master appearing.
1961 //
1962 // Ignore heartbeats received from another master before the
1963 // timeout (less a smidgen) for the old master has elapsed.
1964 //
1965 // Note that after a clean failover, the cluster_master_address
1966 // is cleared, so this doesn't run.
1967 //
1968 if (config->cluster_master_address && addr != config->cluster_master_address) {
1969 LOG(0, 0, 0, "Ignoring stray heartbeat from %s, current master %s has not yet timed out (last heartbeat %.1f seconds ago).\n",
1970 fmtaddr(addr, 0), fmtaddr(config->cluster_master_address, 1),
1971 0.1 * (TIME - config->cluster_last_hb));
1972 return -1; // ignore
1973 }
1974
1975 if (config->cluster_seq_number == -1) // Don't have one. Just align to the master...
1976 config->cluster_seq_number = h->seq;
1977
1978 config->cluster_last_hb = TIME; // Reset to ensure that we don't become master!!
1979 config->cluster_last_hb_ver = hb_ver; // remember what cluster version the master is using
1980
1981 if (config->cluster_seq_number != h->seq) { // Out of sequence heartbeat!
1982 static int lastseen_seq = 0;
1983 static time_t lastseen_time = 0;
1984
1985 // limit to once per second for a particular seq#
1986 int ask = (config->cluster_seq_number != lastseen_seq || time_now != lastseen_time);
1987
1988 LOG(1, 0, 0, "HB: Got seq# %d but was expecting %d. %s.\n",
1989 h->seq, config->cluster_seq_number,
1990 ask ? "Asking for resend" : "Ignoring");
1991
1992 if (ask)
1993 {
1994 lastseen_seq = config->cluster_seq_number;
1995 lastseen_time = time_now;
1996 peer_send_message(addr, C_LASTSEEN, config->cluster_seq_number, NULL, 0);
1997 }
1998
1999 config->cluster_last_hb = TIME; // Reset to ensure that we don't become master!!
2000
2001 // Just drop the packet. The master will resend it as part of the catchup.
2002
2003 return 0;
2004 }
2005 // Save the packet in our buffer.
2006 // This is needed in case we become the master.
2007 config->cluster_seq_number = (h->seq+1)%HB_MAX_SEQ;
2008 i = h->seq % HB_HISTORY_SIZE;
2009 past_hearts[i].seq = h->seq;
2010 past_hearts[i].size = size;
2011 memcpy(&past_hearts[i].data, data, size); // Save it.
2012
2013
2014 // Check that we don't have too many undefined sessions, and
2015 // that the free session pointer is correct.
2016 gnextgrpid = h->nextgrpid;
2017 cluster_check_sessions(h->highsession, h->freesession, h->highbundle, h->hightunnel, h->highgroupe);
2018
2019 if (h->interval != config->cluster_hb_interval)
2020 {
2021 LOG(2, 0, 0, "Master set ping/heartbeat interval to %u (was %u)\n",
2022 h->interval, config->cluster_hb_interval);
2023
2024 config->cluster_hb_interval = h->interval;
2025 }
2026
2027 if (h->timeout != config->cluster_hb_timeout)
2028 {
2029 LOG(2, 0, 0, "Master set heartbeat timeout to %u (was %u)\n",
2030 h->timeout, config->cluster_hb_timeout);
2031
2032 config->cluster_hb_timeout = h->timeout;
2033 }
2034
2035 // Ok. process the packet...
2036 while ( s > 0) {
2037
2038 type = *((uint32_t *) p);
2039 p += sizeof(uint32_t);
2040 s -= sizeof(uint32_t);
2041
2042 more = *((uint32_t *) p);
2043 p += sizeof(uint32_t);
2044 s -= sizeof(uint32_t);
2045
2046 switch (type) {
2047 case C_CSESSION: { // Compressed session structure.
2048 uint8_t c[ sizeof(sessiont) + 2];
2049 int size;
2050 uint8_t *orig_p = p;
2051
2052 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c) );
2053 s -= (p - orig_p);
2054
2055 // session struct changed with v5
2056 if (hb_ver < 6)
2057 {
2058 if (size != sizeof(struct oldsession)) {
2059 LOG(0, 0, 0, "DANGER: Received a v%d CSESSION that didn't decompress correctly!\n", hb_ver);
2060 // Now what? Should exit! No-longer up to date!
2061 break;
2062 }
2063 cluster_recv_session(more, convert_session((struct oldsession *) c));
2064 break;
2065 }
2066
2067 if (size != sizeof(sessiont)) { // Ouch! Very very bad!
2068 if ((hb_ver < HB_VERSION) && (size < sizeof(sessiont)))
2069 {
2070 if ((hb_ver == 7) && (size == sizeof(struct oldsessionV7)))
2071 cluster_recv_session(more, convert_sessionV7((struct oldsessionV7 *) c));
2072 else if (size == sizeof(struct oldsessionV8))
2073 cluster_recv_session(more, convert_sessionV8((struct oldsessionV8 *) c));
2074 else
2075 LOG(0, 0, 0, "DANGER: Received a CSESSION version=%d that didn't decompress correctly!\n", hb_ver);
2076 break;
2077 }
2078 else
2079 {
2080 LOG(0, 0, 0, "DANGER: Received a CSESSION that didn't decompress correctly!\n");
2081 // Now what? Should exit! No-longer up to date!
2082 break;
2083 }
2084 }
2085
2086 cluster_recv_session(more, c);
2087 break;
2088 }
2089 case C_SESSION:
2090 if (hb_ver < 6)
2091 {
2092 if (s < sizeof(struct oldsession))
2093 goto shortpacket;
2094
2095 cluster_recv_session(more, convert_session((struct oldsession *) p));
2096
2097 p += sizeof(struct oldsession);
2098 s -= sizeof(struct oldsession);
2099 break;
2100 }
2101
2102 if ( s < sizeof(session[more]))
2103 goto shortpacket;
2104
2105 cluster_recv_session(more, p);
2106
2107 p += sizeof(session[more]);
2108 s -= sizeof(session[more]);
2109 break;
2110
2111 case C_CTUNNEL: { // Compressed tunnel structure.
2112 uint8_t c[ sizeof(tunnelt) + 2];
2113 int size;
2114 uint8_t *orig_p = p;
2115
2116 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c));
2117 s -= (p - orig_p);
2118
2119 if ( ((hb_ver >= HB_VERSION) && (size != sizeof(tunnelt))) ||
2120 ((hb_ver < HB_VERSION) && (size > sizeof(tunnelt))) )
2121 { // Ouch! Very very bad!
2122 LOG(0, 0, 0, "DANGER: Received a CTUNNEL that didn't decompress correctly!\n");
2123 // Now what? Should exit! No-longer up to date!
2124 break;
2125 }
2126
2127 cluster_recv_tunnel(more, c);
2128 break;
2129
2130 }
2131 case C_TUNNEL:
2132 if ( s < sizeof(tunnel[more]))
2133 goto shortpacket;
2134
2135 cluster_recv_tunnel(more, p);
2136
2137 p += sizeof(tunnel[more]);
2138 s -= sizeof(tunnel[more]);
2139 break;
2140
2141 case C_CBUNDLE: { // Compressed bundle structure.
2142 uint8_t c[ sizeof(bundlet) + 2];
2143 int size;
2144 uint8_t *orig_p = p;
2145
2146 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c));
2147 s -= (p - orig_p);
2148
2149 if (size != sizeof(bundlet) ) { // Ouch! Very very bad!
2150 LOG(0, 0, 0, "DANGER: Received a CBUNDLE that didn't decompress correctly!\n");
2151 // Now what? Should exit! No-longer up to date!
2152 break;
2153 }
2154
2155 cluster_recv_bundle(more, c);
2156 break;
2157
2158 }
2159 case C_BUNDLE:
2160 if ( s < sizeof(bundle[more]))
2161 goto shortpacket;
2162
2163 cluster_recv_bundle(more, p);
2164
2165 p += sizeof(bundle[more]);
2166 s -= sizeof(bundle[more]);
2167 break;
2168
2169 case C_CGROUPE:
2170 { // Compressed Groupe structure.
2171 uint8_t c[ sizeof(groupsesst) + 2];
2172 int size;
2173 uint8_t *orig_p = p;
2174
2175 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c));
2176 s -= (p - orig_p);
2177
2178 if (size != sizeof(groupsesst) )
2179 { // Ouch! Very very bad!
2180 LOG(0, 0, 0, "DANGER: Received a C_CGROUPE that didn't decompress correctly!\n");
2181 // Now what? Should exit! No-longer up to date!
2182 break;
2183 }
2184
2185 cluster_recv_groupe(more, c);
2186 break;
2187 }
2188 case C_GROUPE:
2189 if ( s < sizeof(grpsession[more]))
2190 goto shortpacket;
2191
2192 cluster_recv_groupe(more, p);
2193
2194 p += sizeof(grpsession[more]);
2195 s -= sizeof(grpsession[more]);
2196 break;
2197
2198 default:
2199 LOG(0, 0, 0, "DANGER: I received a heartbeat element where I didn't understand the type! (%d)\n", type);
2200 return -1; // can't process any more of the packet!!
2201 }
2202 }
2203
2204 if (config->cluster_master_address != addr)
2205 {
2206 LOG(0, 0, 0, "My master just changed from %s to %s!\n",
2207 fmtaddr(config->cluster_master_address, 0), fmtaddr(addr, 1));
2208
2209 config->cluster_master_address = addr;
2210 }
2211
2212 config->cluster_last_hb = TIME; // Successfully received a heartbeat!
2213 config->cluster_table_version = h->table_version;
2214 return 0;
2215
2216 shortpacket:
2217 LOG(0, 0, 0, "I got an incomplete heartbeat packet! This means I'm probably out of sync!!\n");
2218 return -1;
2219 }
2220
2221 //
2222 // We got a packet on the cluster port!
2223 // Handle pings, lastseens, and heartbeats!
2224 //
2225 int processcluster(uint8_t *data, int size, in_addr_t addr)
2226 {
2227 int type, more;
2228 uint8_t *p = data;
2229 int s = size;
2230
2231 if (addr == my_address)
2232 return -1; // Ignore it. Something looped back the multicast!
2233
2234 LOG(5, 0, 0, "Process cluster: %d bytes from %s\n", size, fmtaddr(addr, 0));
2235
2236 if (s <= 0) // Any data there??
2237 return -1;
2238
2239 if (s < 8)
2240 goto shortpacket;
2241
2242 type = *((uint32_t *) p);
2243 p += sizeof(uint32_t);
2244 s -= sizeof(uint32_t);
2245
2246 more = *((uint32_t *) p);
2247 p += sizeof(uint32_t);
2248 s -= sizeof(uint32_t);
2249
2250 switch (type)
2251 {
2252 case C_PING: // Update the peers table.
2253 return cluster_add_peer(addr, more, (pingt *) p, s);
2254
2255 case C_MASTER: // Our master is wrong
2256 return cluster_set_master(addr, more);
2257
2258 case C_LASTSEEN: // Catch up a slave (slave missed a packet).
2259 return cluster_catchup_slave(more, addr);
2260
2261 case C_FORWARD: // Forwarded control packet. pass off to processudp.
2262 case C_FORWARD_DAE: // Forwarded DAE packet. pass off to processdae.
2263 if (!config->cluster_iam_master)
2264 {
2265 LOG(0, 0, 0, "I'm not the master, but I got a C_FORWARD%s from %s?\n",
2266 type == C_FORWARD_DAE ? "_DAE" : "", fmtaddr(addr, 0));
2267
2268 return -1;
2269 }
2270 else
2271 {
2272 struct sockaddr_in a;
2273 uint16_t indexudp;
2274 a.sin_addr.s_addr = more;
2275
2276 a.sin_port = (*(int *) p) & 0xFFFF;
2277 indexudp = ((*(int *) p) >> 16) & 0xFFFF;
2278 s -= sizeof(int);
2279 p += sizeof(int);
2280
2281 LOG(4, 0, 0, "Got a forwarded %spacket... (%s:%d)\n",
2282 type == C_FORWARD_DAE ? "DAE " : "", fmtaddr(more, 0), a.sin_port);
2283
2284 STAT(recv_forward);
2285 if (type == C_FORWARD_DAE)
2286 {
2287 struct in_addr local;
2288 local.s_addr = config->bind_address ? config->bind_address : my_address;
2289 processdae(p, s, &a, sizeof(a), &local);
2290 }
2291 else
2292 processudp(p, s, &a, indexudp);
2293
2294 return 0;
2295 }
2296 case C_PPPOE_FORWARD:
2297 if (!config->cluster_iam_master)
2298 {
2299 LOG(0, 0, 0, "I'm not the master, but I got a C_PPPOE_FORWARD from %s?\n", fmtaddr(addr, 0));
2300 return -1;
2301 }
2302 else
2303 {
2304 pppoe_process_forward(p, s, addr);
2305 return 0;
2306 }
2307
2308 case C_MPPP_FORWARD:
2309 // Receive a MPPP packet from a slave.
2310 if (!config->cluster_iam_master) {
2311 LOG(0, 0, 0, "I'm not the master, but I got a C_MPPP_FORWARD from %s?\n", fmtaddr(addr, 0));
2312 return -1;
2313 }
2314
2315 processipout(p, s);
2316 return 0;
2317
2318 case C_THROTTLE: { // Receive a forwarded packet from a slave.
2319 if (!config->cluster_iam_master) {
2320 LOG(0, 0, 0, "I'm not the master, but I got a C_THROTTLE from %s?\n", fmtaddr(addr, 0));
2321 return -1;
2322 }
2323
2324 tbf_queue_packet(more, p, s); // The TBF id tells wether it goes in or out.
2325 return 0;
2326 }
2327 case C_GARDEN:
2328 // Receive a walled garden packet from a slave.
2329 if (!config->cluster_iam_master) {
2330 LOG(0, 0, 0, "I'm not the master, but I got a C_GARDEN from %s?\n", fmtaddr(addr, 0));
2331 return -1;
2332 }
2333
2334 tun_write(p, s);
2335 return 0;
2336
2337 case C_BYTES:
2338 if (!config->cluster_iam_master) {
2339 LOG(0, 0, 0, "I'm not the master, but I got a C_BYTES from %s?\n", fmtaddr(addr, 0));
2340 return -1;
2341 }
2342
2343 return cluster_handle_bytes(p, s);
2344
2345 case C_KILL: // The master asked us to die!? (usually because we're too out of date).
2346 if (config->cluster_iam_master) {
2347 LOG(0, 0, 0, "_I_ am master, but I received a C_KILL from %s! (Seq# %d)\n", fmtaddr(addr, 0), more);
2348 return -1;
2349 }
2350 if (more != config->cluster_seq_number) {
2351 LOG(0, 0, 0, "The master asked us to die but the seq number didn't match!?\n");
2352 return -1;
2353 }
2354
2355 if (addr != config->cluster_master_address) {
2356 LOG(0, 0, 0, "Received a C_KILL from %s which doesn't match config->cluster_master_address (%s)\n",
2357 fmtaddr(addr, 0), fmtaddr(config->cluster_master_address, 1));
2358 // We can only warn about it. The master might really have switched!
2359 }
2360
2361 LOG(0, 0, 0, "Received a valid C_KILL: I'm going to die now.\n");
2362 kill(0, SIGTERM);
2363 exit(0); // Lets be paranoid;
2364 return -1; // Just signalling the compiler.
2365
2366 case C_HEARTBEAT:
2367 LOG(4, 0, 0, "Got a heartbeat from %s\n", fmtaddr(addr, 0));
2368 return cluster_process_heartbeat(data, size, more, p, addr);
2369
2370 default:
2371 LOG(0, 0, 0, "Strange type packet received on cluster socket (%d)\n", type);
2372 return -1;
2373 }
2374 return 0;
2375
2376 shortpacket:
2377 LOG(0, 0, 0, "I got a _short_ cluster heartbeat packet! This means I'm probably out of sync!!\n");
2378 return -1;
2379 }
2380
2381 //====================================================================================================
2382
2383 int cmd_show_cluster(struct cli_def *cli, const char *command, char **argv, int argc)
2384 {
2385 int i;
2386
2387 if (CLI_HELP_REQUESTED)
2388 return CLI_HELP_NO_ARGS;
2389
2390 cli_print(cli, "Cluster status : %s", config->cluster_iam_master ? "Master" : "Slave" );
2391 cli_print(cli, "My address : %s", fmtaddr(my_address, 0));
2392 cli_print(cli, "VIP address : %s", fmtaddr(config->bind_address, 0));
2393 cli_print(cli, "Multicast address: %s", fmtaddr(config->cluster_address, 0));
2394 cli_print(cli, "Multicast i'face : %s", config->cluster_interface);
2395
2396 if (!config->cluster_iam_master) {
2397 cli_print(cli, "My master : %s (last heartbeat %.1f seconds old)",
2398 config->cluster_master_address
2399 ? fmtaddr(config->cluster_master_address, 0)
2400 : "Not defined",
2401 0.1 * (TIME - config->cluster_last_hb));
2402 cli_print(cli, "Uptodate : %s", config->cluster_iam_uptodate ? "Yes" : "No");
2403 cli_print(cli, "Table version # : %" PRIu64, config->cluster_table_version);
2404 cli_print(cli, "Next sequence number expected: %d", config->cluster_seq_number);
2405 cli_print(cli, "%d sessions undefined of %d", config->cluster_undefined_sessions, config->cluster_highest_sessionid);
2406 cli_print(cli, "%d bundles undefined of %d", config->cluster_undefined_bundles, config->cluster_highest_bundleid);
2407 cli_print(cli, "%d groupes undefined of %d", config->cluster_undefined_groupes, config->cluster_highest_groupeid);
2408 cli_print(cli, "%d tunnels undefined of %d", config->cluster_undefined_tunnels, config->cluster_highest_tunnelid);
2409 } else {
2410 cli_print(cli, "Table version # : %" PRIu64, config->cluster_table_version);
2411 cli_print(cli, "Next heartbeat # : %d", config->cluster_seq_number);
2412 cli_print(cli, "Highest session : %d", config->cluster_highest_sessionid);
2413 cli_print(cli, "Highest bundle : %d", config->cluster_highest_bundleid);
2414 cli_print(cli, "Highest groupe : %d", config->cluster_highest_groupeid);
2415 cli_print(cli, "Highest tunnel : %d", config->cluster_highest_tunnelid);
2416 cli_print(cli, "%d changes queued for sending", config->cluster_num_changes);
2417 }
2418 cli_print(cli, "%d peers.", num_peers);
2419
2420 if (num_peers)
2421 cli_print(cli, "%20s %10s %8s", "Address", "Basetime", "Age");
2422 for (i = 0; i < num_peers; ++i) {
2423 cli_print(cli, "%20s %10u %8d", fmtaddr(peers[i].peer, 0),
2424 peers[i].basetime, TIME - peers[i].timestamp);
2425 }
2426 return CLI_OK;
2427 }
2428
2429 //
2430 // Simple run-length-encoding compression.
2431 // Format is
2432 // 1 byte < 128 = count of non-zero bytes following. // Not legal to be zero.
2433 // n non-zero bytes;
2434 // or
2435 // 1 byte > 128 = (count - 128) run of zero bytes. //
2436 // repeat.
2437 // count == 0 indicates end of compressed stream.
2438 //
2439 // Compress from 'src' into 'dst'. return number of bytes
2440 // used from 'dst'.
2441 // Updates *src_p to indicate 1 past last bytes used.
2442 //
2443 // We could get an extra byte in the zero runs by storing (count-1)
2444 // but I'm playing it safe.
2445 //
2446 // Worst case is a 50% expansion in space required (trying to
2447 // compress { 0x00, 0x01 } * N )
2448 static int rle_compress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize)
2449 {
2450 int count;
2451 int orig_dsize = dsize;
2452 uint8_t *x, *src;
2453 src = *src_p;
2454
2455 while (ssize > 0 && dsize > 2) {
2456 count = 0;
2457 x = dst++; --dsize; // Reserve space for count byte..
2458
2459 if (*src) { // Copy a run of non-zero bytes.
2460 while (*src && count < 127 && ssize > 0 && dsize > 1) { // Count number of non-zero bytes.
2461 *dst++ = *src++;
2462 --dsize; --ssize;
2463 ++count;
2464 }
2465 *x = count; // Store number of non-zero bytes. Guarenteed to be non-zero!
2466
2467 } else { // Compress a run of zero bytes.
2468 while (*src == 0 && count < 127 && ssize > 0) {
2469 ++src;
2470 --ssize;
2471 ++count;
2472 }
2473 *x = count | 0x80 ;
2474 }
2475 }
2476
2477 *dst++ = 0x0; // Add Stop byte.
2478 --dsize;
2479
2480 *src_p = src;
2481 return (orig_dsize - dsize);
2482 }
2483
2484 //
2485 // Decompress the buffer into **p.
2486 // 'psize' is the size of the decompression buffer available.
2487 //
2488 // Returns the number of bytes decompressed.
2489 //
2490 // Decompresses from '*src_p' into 'dst'.
2491 // Return the number of dst bytes used.
2492 // Updates the 'src_p' pointer to point to the
2493 // first un-used byte.
2494 static int rle_decompress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize)
2495 {
2496 int count;
2497 int orig_dsize = dsize;
2498 uint8_t *src = *src_p;
2499
2500 while (ssize >0 && dsize > 0) { // While there's more to decompress, and there's room in the decompress buffer...
2501 count = *src++; --ssize; // get the count byte from the source.
2502 if (count == 0x0) // End marker reached? If so, finish.
2503 break;
2504
2505 if (count & 0x80) { // Decompress a run of zeros
2506 for (count &= 0x7f ; count > 0 && dsize > 0; --count) {
2507 *dst++ = 0x0;
2508 --dsize;
2509 }
2510 } else { // Copy run of non-zero bytes.
2511 for ( ; count > 0 && ssize && dsize; --count) { // Copy non-zero bytes across.
2512 *dst++ = *src++;
2513 --ssize; --dsize;
2514 }
2515 }
2516 }
2517 *src_p = src;
2518 return (orig_dsize - dsize);
2519 }