forked from dyninc/OpenBFDD
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Session.cpp
1553 lines (1306 loc) · 50.1 KB
/
Session.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************************************************
* Copyright (c) 2010-2013, Dynamic Network Services, Inc.
* Jake Montgomery ([email protected]) & Tom Daly ([email protected])
* Distributed under the FreeBSD License - see LICENSE
***************************************************************/
#include "common.h"
#include "Session.h"
#include "utils.h"
#include "Beacon.h"
#include "Scheduler.h"
#include <errno.h>
#include <sys/socket.h>
#include <string.h>
using namespace std;
namespace openbfdd
{
#ifdef TEST_DROP_FINAL
#warning TEST_DROP_FINAL defined ... testing only!
static int gDropFinalPercent = 60;
#else
static int gDropFinalPercent = 0;
#endif
static const size_t MaxUptimeCount = 4; // number of states to keep track of for logging.
uint32_t Session::m_nextId = 1;
Session::InitialParams::InitialParams() :
detectMulti(3),
desiredMinTx(bfd::BaseMinTxInterval),
requiredMinRx(1000000),
controlPlaneIndependent(false),
adminUpPollWorkaround(true)
{
}
// Note that the inclusion of the Beacon pointer is bad design and sheer
// laziness. This should really be an event sink or callback.
Session::Session(Scheduler &scheduler, Beacon *beacon, uint32_t descriminator, const InitialParams ¶ms) :
m_beacon(beacon),
m_scheduler(&scheduler),
m_remoteAddr(),
m_remoteSourcePort(0),
m_localAddr(),
m_sendPort(0),
m_isActive(false),
m_sessionState(bfd::State::Down),
m_remoteSessionState(bfd::State::Down),
m_localDiscr(descriminator),
m_remoteDiscr(0),
m_localDiag(bfd::Diag::None),
m_desiredMinTxInterval(bfd::BaseMinTxInterval), // Since we start "down" this must be 1s see v10/6.8.3
m_requiredMinRxInterval(params.requiredMinRx),
m_remoteMinRxInterval(1),
m_demandMode(false), // We get to choose this.
m_remoteDemandMode(false),
m_detectMult(params.detectMulti),
m_authType(bfd::AuthType::None), // ??
m_rcvAuthSeq(0),
m_xmitAuthSeq(rand() % UINT32_MAX),
m_authSeqKnown(false),
m_pollState(PollState::None),
m_pollReceived(false),
m_remoteDetectMult(0),
m_remoteDesiredMinTxInterval(0),
m_remoteDiag(bfd::Diag::None),
m_destroyAfterTimeouts(3),
m_remoteDestroyAfterTimeouts(3),
m_timeoutStatus(TimeoutStatus::None),
m_isSuspended(false),
m_immediateControlPacket(false),
m_controlPlaneIndependent(params.controlPlaneIndependent),
m_adminUpPollWorkaround(params.adminUpPollWorkaround),
m_forcedState(false),
m_wantsPollForNewDesiredMinTxInterval(false),
_useDesiredMinTxInterval(bfd::BaseMinTxInterval), // Since we start "down" this must be 1s see v10/6.8.3
m_defaultDesiredMinTxInterval(params.desiredMinTx), // this will not take effect until we are up ... see m_useDesiredMinTxInterva
m_wantsPollForNewRequiredMinRxInterval(false),
_useRequiredMinRxInterval(m_requiredMinRxInterval),
m_receiveTimeoutTimer(this),
m_transmitNextTimer(this)
{
LogAssert(m_scheduler->IsMainThread());
if (m_nextId == 0)
{
// This is unlikely, since we can handle 4 billion sessions.
gLog.LogError("Maximum session count exceeded, refusing new sessions.");
}
else
m_id = m_nextId;
// It may be more efficient to wait until we need these?
char name[32];
snprintf(name, sizeof(name), "<Rcv %u>", m_id);
m_receiveTimeoutTimer = m_scheduler->MakeTimer(name);
snprintf(name, sizeof(name), "<Tx %u>", m_id);
m_transmitNextTimer = m_scheduler->MakeTimer(name);
m_receiveTimeoutTimer->SetCallback(handleRecieveTimeoutTimerCallback, this);
m_receiveTimeoutTimer->SetPriority(Timer::Priority::Low);
m_transmitNextTimer->SetCallback(handletTransmitNextTimerCallback, this);
m_transmitNextTimer->SetPriority(Timer::Priority::Hi);
logSessionTransition();
// Update this only at the end, in case an exception is thrown.
m_nextId++;
}
Session::~Session()
{
LogAssert(m_scheduler->IsMainThread());
}
void Session::deleteTimer(Timer *timer)
{
LogAssert(m_scheduler->IsMainThread());
if (m_scheduler && timer)
{
gLog.Message(Log::Temp, "Free timer %p", timer);
m_scheduler->FreeTimer(timer);
}
}
bool Session::StartPassiveSession(const SockAddr &remoteAddr, const IpAddr &localAddr)
{
LogAssert(m_scheduler->IsMainThread());
// this should only be called once.
LogAssert(!m_remoteAddr.IsValid());
LogAssert(!m_localAddr.IsValid());
if (!LogVerify(remoteAddr.HasPort()))
return false;
if (!LogVerify(!localAddr.IsAny()))
return false;
m_remoteAddr = IpAddr(remoteAddr);
m_remoteSourcePort = remoteAddr.Port();
m_localAddr = localAddr;
m_isActive = false;
return true;
}
bool Session::StartActiveSession(const IpAddr &remoteAddr, const IpAddr &localAddr)
{
LogAssert(m_scheduler->IsMainThread());
// this should only be called once.
if (!LogVerify(!m_remoteAddr.IsValid()))
return false;
if (!LogVerify(!m_localAddr.IsValid()))
return false;
// Any is not valid send address
if (!LogVerify(!localAddr.IsAny()))
return false;
m_remoteAddr = remoteAddr;
m_remoteSourcePort = 0;
m_localAddr = localAddr;
m_isActive = true;
// Start the timers now, and begin sending connection packets.
// We set m_immediateControlPacket because this is a new connection, and there
// is no point in waiting.
m_immediateControlPacket = true;
scheduleTransmit();
return true;
}
bool Session::UpgradeToActiveSession()
{
LogAssert(m_scheduler->IsMainThread());
// Must already have a passive session.
if (!LogVerify(m_remoteAddr.IsValid()))
return false;
if (!LogVerify(m_localAddr.IsValid()))
return false;
if (!LogVerify(!IsActiveSession()))
return false;
m_isActive = true;
// Start the timers now, and begin sending connection packets
scheduleTransmit();
return true;
}
const IpAddr& Session::GetRemoteAddress()
{
LogAssert(m_scheduler->IsMainThread());
return m_remoteAddr;
}
const IpAddr& Session::GetLocalAddress()
{
LogAssert(m_scheduler->IsMainThread());
return m_localAddr;
}
bool Session::IsActiveSession()
{
LogAssert(m_scheduler->IsMainThread());
return m_isActive;
}
// static
bool Session::InitialProcessControlPacket(const uint8_t *data, size_t dataLength, BfdPacket &outPacket)
{
BfdPacketHeader &header = outPacket.header;
if (dataLength < bfd::BasePacketSize)
{
gLog.Optional(Log::Discard, "Discard packet: too small %zu", dataLength);
return false;
}
memcpy(&outPacket, data, min(dataLength, sizeof(outPacket)));
// the early stuff can be checked without worrying about byte order, since they
// are parsed as bytes.
if (header.GetVersion() != 0 && header.GetVersion() != 1)
{
gLog.Optional(Log::Discard, "Discard packet: bad version %hhu", header.GetVersion());
return false;
}
if (header.GetAuth())
{
if (header.length < bfd::BasePacketSize + bfd::AuthHeaderSize)
{
gLog.Optional(Log::Discard, "Discard packet: length too small to include auth %hhu", header.length);
return false;
}
}
else if (header.length < bfd::BasePacketSize)
{
gLog.Optional(Log::Discard, "Discard packet: length too small %hhu", header.length);
return false;
}
else if (header.length > dataLength)
{
gLog.Optional(Log::Discard, "Discard packet: length larger than data %hhu", header.length);
return false;
}
if (header.detectMult == 0)
{
gLog.Optional(Log::Discard, "Discard packet: detectMult is 0.");
return false;
}
if (header.GetMultipoint())
{
gLog.Optional(Log::Discard, "Discard packet: Multipoint bit is set.");
return false;
}
// Can check for 0 without byte order concerns.
if (header.myDisc == 0)
{
gLog.Optional(Log::Discard, "Discard packet: Source Discriminator is 0.");
return false;
}
// Can check for 0 without byte order concerns.
if (header.yourDisc == 0 && header.GetState() != bfd::State::Down && header.GetState() != bfd::State::AdminDown)
{
gLog.Optional(Log::Discard, "Discard packet: No destination discriminator and state is %s.", bfd::StateName(header.GetState()));
return false;
}
// Now we need to worry about byte order
header.myDisc = ntohl(header.myDisc);
header.yourDisc = ntohl(header.yourDisc);
header.txDesiredMinInt = ntohl(header.txDesiredMinInt);
header.rxRequiredMinInt = ntohl(header.rxRequiredMinInt);
header.rxRequiredMinEchoInt = ntohl(header.rxRequiredMinEchoInt);
// packet is good as far as we can tell without a session.
return true;
}
bool Session::ProcessControlPacket(const BfdPacket &packet, in_port_t port)
{
// Assumes that the first few checks have been done.
const BfdPacketHeader &header = packet.header;
uint32_t olduseDesiredMinTxInterval = getUseDesiredMinTxInterval();
uint32_t oldRemoteMinRxInterval = m_remoteMinRxInterval;
LogAssert(m_scheduler->IsMainThread());
logPacketContents(packet, false, true, m_remoteAddr, port, m_localAddr, 0);
if (gDropFinalPercent != 0)
{
// For testing only
if (header.GetFinal() && rand() % 100 < gDropFinalPercent)
{
gLog.Optional(Log::Discard, "Discard packet: TESTING final bit set.");
return false;
}
}
if (header.yourDisc != 0 && header.yourDisc != m_localDiscr)
{
gLog.Optional(Log::Discard, "Discard packet: Source Discriminator is does not match our discriminator.");
return false;
}
if (header.GetAuth())
{
if (packet.auth.GetAuthType() == bfd::AuthType::None)
{
gLog.Optional(Log::Discard, "Discard packet: Auth bit set but type is None.");
return false;
}
// We need to do authentication
gLog.LogWarn("Authentication requested, but we do not handle it currently.");
gLog.Optional(Log::Discard, "Discard packet: Auth bit set and we do not handle it.");
return false;
}
else
{
if (m_authType != bfd::AuthType::None)
{
gLog.Optional(Log::Discard, "Discard packet: Auth bit clear, but session is using authentication.");
return false;
}
}
if (header.GetDemand())
{
{
gLog.Optional(Log::Error, "Discard packet: We do not support demand mode for remote host.");
return false;
}
}
//
// looks like packet can not be discarded after this point
//
m_remoteDesiredMinTxInterval = header.txDesiredMinInt;
m_remoteDetectMult = header.detectMult;
m_remoteDiscr = header.myDisc;
m_remoteSessionState = header.GetState();
m_remoteDemandMode = header.GetDemand();
m_remoteMinRxInterval = header.rxRequiredMinInt;
m_remoteDiag = header.GetDiag();
if (header.rxRequiredMinEchoInt == 0)
{
// We do not handle echo anyway, but if we did, then we would stop.
}
if (header.GetFinal())
{
// Poll sequence, if any, must stop
if (m_pollState != PollState::Polling)
gLog.Optional(Log::Packet, "Unmatched Final bit in packet. ");
else
transitionPollState(PollState::Completed);
}
else
{
// Any poll sequence is now completely finished without ambiguity. (Assuming we
// are in the Competed state now.)
transitionPollState(PollState::None);
}
// Note, the spec has us checking header.GetState(), but that will always
// (currently) be the same as m_remoteSessionState.
LogAssert(m_remoteSessionState == header.GetState());
if (bfd::State::AdminDown == m_remoteSessionState)
setSessionState(bfd::State::Down, bfd::Diag::NeighborSessionDown, SetValueFlags::PreventTxReschedule);
else
{
if (m_sessionState == bfd::State::Down)
{
if (m_remoteSessionState == bfd::State::Down)
setSessionState(bfd::State::Init, bfd::Diag::None, SetValueFlags::PreventTxReschedule);
else if (m_remoteSessionState == bfd::State::Init)
setSessionState(bfd::State::Up, bfd::Diag::None, SetValueFlags::PreventTxReschedule);
}
else if (m_sessionState == bfd::State::Init)
{
if (m_remoteSessionState == bfd::State::Init
|| m_remoteSessionState == bfd::State::Up)
setSessionState(bfd::State::Up, bfd::Diag::None, SetValueFlags::PreventTxReschedule);
}
else if (m_sessionState == bfd::State::Up)
{
if (m_remoteSessionState == bfd::State::Down)
setSessionState(bfd::State::Down, bfd::Diag::NeighborSessionDown, SetValueFlags::PreventTxReschedule);
}
}
// TODO if we wanted to go into demand mode, this is where it would happen
if (isRemoteDemandModeActive())
{
// Cease periodic control packets.
LogVerifyFalse("We do not currently support demand mode");
m_transmitNextTimer->Stop();
}
else if (m_transmitNextTimer->IsStopped())
{
// Start the timer.
scheduleTransmit();
}
if (header.GetPoll())
{
// If poll was received than send a final response asap, "without respect to
// the transmission timer" (v10/6.8.7)
m_pollReceived = true;
sendControlPacket();
}
// If we are active, then we may not yet have a source port
if (m_remoteSourcePort == 0 && m_isActive)
m_remoteSourcePort = port;
else if (m_remoteSourcePort != port)
{
m_remoteSourcePort = port;
gLog.Optional(Log::Session, "Source port has changed for session %u.", m_id);
}
// If we were timing out, we no longer are.
m_timeoutStatus = TimeoutStatus::None;
// Certain changes my require a packet reschedule.
if (m_immediateControlPacket
|| olduseDesiredMinTxInterval != getUseDesiredMinTxInterval()
|| oldRemoteMinRxInterval > m_remoteMinRxInterval // v10/6.8.3p6
|| (oldRemoteMinRxInterval == 0 && oldRemoteMinRxInterval != m_remoteMinRxInterval) // basically the same as above.
)
{
scheduleTransmit();
}
// Packet received ... update Detection time timer
scheduleRecieveTimeout();
return true;
}
/**
* Gets the time between receiving remote control packets that should be
* considered a "timeout".
*
* Returns 0 if we do not expect any packets. (Timeout disabled.)
*
*/
uint64_t Session::getDetectionTimeout()
{
if (getUseRequiredMinRxInterval() == 0)
return 0;
return m_remoteDetectMult * uint64_t(max(getUseRequiredMinRxInterval(), m_remoteDesiredMinTxInterval));
}
/**
* Schedule the next received timeout based on the current settings.
*
*/
void Session::scheduleRecieveTimeout()
{
// Reset received timer (if any) using UpdateMicroTimer()
if (!LogVerify(!m_demandMode))
{
// We currently never set demand mode
return;
}
uint64_t timeout = getDetectionTimeout();
if (timeout == 0)
m_receiveTimeoutTimer->Stop();
else
m_receiveTimeoutTimer->SetMicroTimer(timeout);
}
/**
* Change the received timeout based on the current settings.
*/
void Session::reScheduleRecieveTimeout()
{
// Reset received timer (if any) using UpdateMicroTimer()
if (!LogVerify(!m_demandMode))
{
// We currently never set demand mode
return;
}
uint64_t timeout = getDetectionTimeout();
if (timeout == 0)
m_receiveTimeoutTimer->Stop();
else
m_receiveTimeoutTimer->UpdateMicroTimer(timeout);
}
bool Session::isRemoteDemandModeActive()
{
return (m_remoteDemandMode && m_sessionState == bfd::State::Up && m_remoteSessionState == bfd::State::Up);
}
/**
* Use this to change m_sessionState. Handles the timing of control packets.
*
* @note This may change the MinTXInterval.
*
*
* Set the SetValueFlags::PreventTxReschedule flag is in flags to prevent this
* function from calling scheduleTransmit(). Use only if caller will call
* scheduleTransmit(), or sendControlPacket().
*
* Set the SetValueFlags::TryPoll flag is in flags to start a poll sequence if
* the sate is changed. This is an 'optional' poll sequence, and will be ignored
* if there is already one underway. The poll sequence may be "ambiguous" (see
* transitionPollState)
*
*
* @param newState
* @param diag [in] - The new local diag.
* @param flags [in] - See description above.
*/
void Session::setSessionState(bfd::State::Value newState, bfd::Diag::Value diag, SetValueFlags::Flag flags /*SetValueFlags::None*/)
{
if (m_forcedState)
{
LogOptional(Log::SessionDetail, "(id=%u) Session held at %s no transition to %s", m_id, bfd::StateName(m_sessionState), bfd::StateName(newState));
return;
}
m_localDiag = diag;
if (m_sessionState != newState)
{
LogOptional(Log::Session, "(id=%u) Session transition from %s to %s", m_id, bfd::StateName(m_sessionState), bfd::StateName(newState));
m_sessionState = newState;
logSessionTransition();
if (newState == bfd::State::Up)
{
// Since we are up, we can change to our real DesiredMinTxInterval
if (m_desiredMinTxInterval != m_defaultDesiredMinTxInterval)
setDesiredMinTxInterval(m_defaultDesiredMinTxInterval, (flags & SetValueFlags::PreventTxReschedule));
}
else
{
// According to v10/6.8.3 when state is not up we must have
// m_desiredMinTxInterval at least 1000000
if (m_desiredMinTxInterval < bfd::BaseMinTxInterval)
setDesiredMinTxInterval(bfd::BaseMinTxInterval, (flags & SetValueFlags::PreventTxReschedule));
// If we were waiting for a RequiredMinRxInterval change to finish polling, that
// is now moot.
if (getUseRequiredMinRxInterval() != m_requiredMinRxInterval)
{
// This is Ok here only since we know we are not up.
gLog.Optional(Log::Session, "(id=%u) RequiredMinRxInterval now using new value %u due to session down.", m_id, m_requiredMinRxInterval);
setUseRequiredMinRxInterval(m_requiredMinRxInterval);
reScheduleRecieveTimeout();
}
}
if (SetValueFlags::TryPoll == (flags & SetValueFlags::TryPoll))
transitionPollState(PollState::Requested, true /*allowAmbiguous*/);
// Change in control packets should cause an immediate send (per v10/6.8.7)
m_immediateControlPacket = true;
if ((flags & SetValueFlags::PreventTxReschedule) != SetValueFlags::PreventTxReschedule)
scheduleTransmit(); // schedule immediate transmit.
}
}
/**
* Logs a transition to the current state.
* Stores the transition information for stats.
*/
void Session::logSessionTransition()
{
UptimeInfo *last = NULL;
TimeSpec now(TimeSpec::MonoNow());
// We only log state change when we are fully up.
// The state machine does not allow up->init transition, so we must have been
// down (and we still count this as down).
if (m_sessionState == bfd::State::Init)
return;
// Check if we even need to log the state transition
if (!m_uptimeList.empty())
{
last = &m_uptimeList.front();
// only log when state changes.
if (last->state == m_sessionState)
{
if (m_forcedState && !last->forced)
last->forced = m_forcedState;
return;
}
// If we go Down->AdminDown, then just call it that.
if (last->state == bfd::State::Down && m_sessionState == bfd::State::AdminDown)
{
last->state = bfd::State::AdminDown;
last->forced = m_forcedState;
return;
}
}
GetMonolithicTime(now);
if (last)
last->endTime = now;
// log the new state
UptimeInfo uptime;
uptime.state = m_sessionState;
uptime.startTime = now;
uptime.forced = false; // currently not using this.
try
{
m_uptimeList.push_front(uptime);
}
catch (std::exception)
{
// TODO - could mark the whole thing as "invalid"?
m_uptimeList.clear();
}
if (m_uptimeList.size() > MaxUptimeCount)
m_uptimeList.pop_back();
}
/**
* Called to attempt to transition poll state. Enforces linear transitions.
*
* @param nextState
* @param allowAmbiguous - If true, then we can start a new poll sequence even if
* the previous one just ended. The poll sequence will be
* "ambiguous" as described in v10/6/8/3p9. This should be
* used only if the caller does not need to take any
* action when the poll completes.
*
* @return - false if the transition was not valid.
*/
bool Session::transitionPollState(PollState::Value nextState, bool allowAmbiguous /*false*/)
{
// This is used to track polling. In particular, we can not start two separate
// polls too close together or they become ambiguous as described at the end of
// v10/6.8.3. Currently we require a non-F response in between to disambiguate
// poll. We could also add a timing element as described in that section, if
// needed.
if (nextState == PollState::None)
{
if (m_pollState == PollState::None)
return true;
if (m_pollState == PollState::Completed)
{
// Poll sequence is now unambiguously finished. We can now start a new one if we
// want.
m_pollState = PollState::None;
if (m_wantsPollForNewDesiredMinTxInterval
|| m_wantsPollForNewRequiredMinRxInterval
)
return transitionPollState(PollState::Requested);
return true;
}
return false;
}
else if (nextState == PollState::Requested)
{
if (m_pollState == PollState::Requested || m_pollState == PollState::None)
{
m_pollState = PollState::Requested;
// If either of these were true, then we can set them to false now, since they
// will automatically take effect at the end of this poll sequence.
m_wantsPollForNewDesiredMinTxInterval = false;
m_wantsPollForNewRequiredMinRxInterval = false;
// If we are not transmitting (perhaps m_remoteMinRxInterval == 0) then we need
// to now to make polling happen. Note that this will still wait until the
// "next" transmit, even though that might not be required in all cases.
if (m_transmitNextTimer->IsStopped())
scheduleTransmit();
return true;
}
if (m_pollState == PollState::Completed && allowAmbiguous)
{
m_pollState = PollState::None;
return transitionPollState(PollState::Requested);
}
return false;
}
else if (nextState == PollState::Polling)
{
if (m_pollState == PollState::Requested || m_pollState == PollState::None)
{
m_pollState = PollState::Polling;
return true;
}
return false;
}
else if (nextState == PollState::Completed)
{
if (m_pollState == PollState::Polling)
{
m_pollState = PollState::Completed;
// Handle any changes that need to be made after polling.
// we can use the m_desiredMinTxInterval once the poll has completed, unless we
// want another poll for that purpose.
if (!m_wantsPollForNewDesiredMinTxInterval)
setUseDesiredMinTxInterval(m_desiredMinTxInterval);
// we can use the m_requiredMinRxInterval once the poll has completed, unless we
// want another poll for that purpose.
if (!m_wantsPollForNewRequiredMinRxInterval && getUseRequiredMinRxInterval() != m_requiredMinRxInterval)
{
setUseRequiredMinRxInterval(m_requiredMinRxInterval);
reScheduleRecieveTimeout();
}
// If we are only sending packets as part of a poll then we can stop now.
if (!m_transmitNextTimer->IsStopped() && getBaseTransmitTime() == 0)
scheduleTransmit();
return true;
}
return false;
}
LogVerify(false);
return false;
}
/**
* Schedules the next packet transmission based on current state.
* Poll response packets are not scheduled, and so are not handled here.
*/
void Session::scheduleTransmit()
{
uint64_t transmitInterval = 0;
// Poll packet responses are handled immediately, so this routine should not be
// involved.
LogAssert(!m_pollReceived);
if (m_immediateControlPacket)
{
// On certain changes we need to send an immediate packet
m_transmitNextTimer->SetMicroTimer(0);
return;
}
if (!m_isActive && m_remoteDiscr == 0)
{
m_transmitNextTimer->Stop();
return; // Passive session.
}
// We recalculate the transmit interval every time, which may mean a little
// extra "churning" on the timer.
transmitInterval = getBaseTransmitTime();
if (transmitInterval == 0)
{
bool sendPoll = (m_pollState == PollState::Requested || m_pollState == PollState::Polling);
// If we are not polling, then no packets get sent.
if (!sendPoll)
{
m_transmitNextTimer->Stop();
return;
}
else
{
// We are polling, but we have demand mode (not supported anyway) or
// m_remoteMinRxInterval of 0 (not handled properly by JUNOS 8.5)
// So we just keep transmitting until we get a poll response. The timing is not
// spelled out in the spec. TODO: still verifying that this is a reasonable
// approach.
transmitInterval = getUseDesiredMinTxInterval();
}
}
// Apply jitter
transmitInterval = uint64_t(transmitInterval * (0.75 + 0.25 * double(rand()) / RAND_MAX));
// Limits on jitter
if (m_detectMult == 1)
{
if (transmitInterval > uint64_t(0.90 * transmitInterval))
transmitInterval = uint64_t(0.90 * transmitInterval);
}
m_transmitNextTimer->UpdateMicroTimer(transmitInterval);
}
/**
*
* Gets the base time for transmitting periodic control packets.
*
* @return uint32_t - 0 if no packets are being sent.
*/
uint32_t Session::getBaseTransmitTime()
{
if (!m_isActive && m_remoteDiscr == 0)
return 0; // Passive session.
if (m_remoteMinRxInterval == 0)
return 0; // no periodic
// Note, we do not handle this anyway.
if (isRemoteDemandModeActive())
return 0; // no periodic
return max(getUseDesiredMinTxInterval(), m_remoteMinRxInterval);
}
/**
* Sends a control packet. Does not update timers.
* @note Must be called from main thread.
*
*/
void Session::sendControlPacket()
{
BfdPacket packet;
BfdPacketHeader &header = packet.header;
bool poll;
if (!ensureSendSocket())
return;
poll = (!m_pollReceived && (m_pollState == PollState::Requested || m_pollState == PollState::Polling));
packet = BfdPacket();
header.SetVersion(bfd::Version);
header.length = sizeof(header);
header.SetDiag(m_localDiag);
header.SetState(m_sessionState);
header.SetPoll(poll);
header.SetFinal(m_pollReceived);
header.SetControlPlaneIndependent(m_controlPlaneIndependent);
// The next few are always false, so we could skip setting them. Included for
// completeness.
header.SetAuth(false); // never for now.
header.SetDemand(false); // never for now.
header.SetMultipoint(false), // never
header.detectMult = m_detectMult;
header.myDisc = htonl(m_localDiscr);
header.yourDisc = htonl(m_remoteDiscr);
header.txDesiredMinInt = htonl(m_desiredMinTxInterval);
header.rxRequiredMinInt = htonl(m_requiredMinRxInterval);
header.rxRequiredMinEchoInt = htonl(0); // no echo allowed for this system.
// Since we have sent a poll response, we are done unless we get another.
m_pollReceived = false;
// Since we are sending the packet, we have fulfilled m_immediateControlPacket
m_immediateControlPacket = false;
send(packet);
if (poll)
transitionPollState(PollState::Polling);
}
/**
* Sends the given packet.
*
* @note Must be called from main thread.
*
* @param packet
*/
void Session::send(const BfdPacket &packet)
{
if (!ensureSendSocket())
return;
if (m_isSuspended)
{
gLog.Optional(Log::Packet, "Not sending packet for suspended session %u.", m_id);
return;
}
logPacketContents(packet, true, false, m_remoteAddr, 0, m_localAddr, m_sendPort);
if (m_sendSocket.SendTo(&packet, packet.header.length,
SockAddr(m_remoteAddr, bfd::ListenPort),
MSG_NOSIGNAL))
gLog.Optional(Log::Packet, "Sent control packet for session %u.", m_id);
}
/**
* Attempts to connect the m_sendSocket send socket, if there is not one
* already.
*
* @return bool - false if the socket could not be opened.
*/
bool Session::ensureSendSocket()
{
uint16_t startPort;
Socket sendSocket;
SockAddr sendAddr;
if (!m_sendSocket.empty())
return true;
if (!LogVerify(m_localAddr.IsValid()))
return false;
if (!LogVerify(!m_localAddr.IsAny()))
return false;
char tmp[255];
sendSocket.SetLogName(FormatStr(tmp, sizeof(tmp), "Session %d sock", m_id));
// NotE that all sockets will log errors, so we do not have to.
if (!sendSocket.OpenUDP(m_localAddr.Type()))
return false;
if (!sendSocket.SetTTLOrHops(bfd::TTLValue))
return false;
/* Find an available port in the proper range */
if (m_sendPort != 0)
startPort = m_sendPort;
else
startPort = bfd::MinSourcePort + rand() % (bfd::MaxSourcePort - bfd::MinSourcePort);
sendAddr = SockAddr(m_localAddr, startPort);
// We need the socket to be quiet so we do not get warnings for each port tried.
RaiiObjCallVar<bool, Socket, bool, &Socket::SetQuiet> m_socketQuiet(&sendSocket);
m_socketQuiet = sendSocket.SetQuiet(true);
while (!sendSocket.Bind(sendAddr))
{
switch (sendSocket.GetLastError())
{
default:
gLog.LogError("Unable to open socket for session %" PRIu32 " %s : (%d) %s",
m_id, sendAddr.ToString(false),
sendSocket.GetLastError(), SystemErrorToString(sendSocket.GetLastError()));
return false;
break;
case EAGAIN:
case EADDRINUSE:
// Fall through and keep looking
break;
}
if (sendAddr.Port() == bfd::MaxSourcePort)
sendAddr.SetPort(bfd::MinSourcePort);
else
sendAddr.SetPort(sendAddr.Port() + 1);
if (sendAddr.Port() == startPort)
{
gLog.LogError("Cant find valid send port.");
return false;