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