ServerUser: use QTime instead of std::chrono and ctime

The legacy implementation (with ctime), used when std::chrono is not available (C++ < 11), caused the client's messages to be permanently blocked until it reconnected.
More specifically, millisecondsBetween() always returned 0.

This commit replaces both implementations with a simpler one which makes use of QTime.
This commit is contained in:
Davide Beatrici 2019-05-25 21:33:53 +02:00
parent 4e83913974
commit da7baf5313
2 changed files with 9 additions and 39 deletions

View File

@ -112,32 +112,14 @@ int BandwidthRecord::bandwidth() const {
return static_cast<int>((sum * 1000000ULL) / elapsed);
}
#if __cplusplus > 199711LL
inline static
time_point now() {
return std::chrono::steady_clock::now();
inline static QTime now() {
return QTime::currentTime();
}
inline static
unsigned long millisecondsBetween(time_point start, time_point end) {
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
inline static int millisecondsBetween(const QTime &start, const QTime &end) {
return start.msecsTo(end);
}
#else
inline static
time_point now() {
return clock();
}
inline static
unsigned long millisecondsBetween(time_point start, time_point end) {
return 1000 * (end - start) / CLOCKS_PER_SEC;
}
#endif
// Rate limiting: burst up to 5, 1 message per sec limit over longer time
LeakyBucket::LeakyBucket(unsigned int tokensPerSec, unsigned int maxTokens) : tokensPerSec(tokensPerSec), maxTokens(maxTokens), currentTokens(0) {
lastUpdate = now();
@ -145,10 +127,10 @@ LeakyBucket::LeakyBucket(unsigned int tokensPerSec, unsigned int maxTokens) : to
bool LeakyBucket::ratelimit(int tokens) {
// First remove tokens we leaked over time
time_point tnow = now();
long ms = millisecondsBetween(lastUpdate, tnow);
const QTime tnow = now();
const long ms = millisecondsBetween(lastUpdate, tnow);
long drainTokens = (ms * tokensPerSec) / 1000;
const long drainTokens = (ms * tokensPerSec) / 1000;
// Prevent constant starvation due to too many updates
if (drainTokens > 0) {

View File

@ -7,6 +7,7 @@
#define MUMBLE_MURMUR_SERVERUSER_H_
#include <QtCore/QStringList>
#include <QtCore/QTime>
#ifdef Q_OS_UNIX
#include <sys/socket.h>
@ -14,13 +15,6 @@
#include <winsock2.h>
#endif
// <chrono> was introduced in C++11
#if __cplusplus > 199711LL
#include <chrono>
#else
#include <ctime>
#endif
#include "Connection.h"
#include "Timer.h"
#include "User.h"
@ -62,18 +56,12 @@ struct WhisperTarget {
class Server;
#if __cplusplus > 199711L
typedef std::chrono::time_point<std::chrono::steady_clock> time_point;
#else
typedef clock_t time_point;
#endif
// Simple algorithm for rate limiting
class LeakyBucket {
private:
unsigned int tokensPerSec, maxTokens;
long currentTokens;
time_point lastUpdate;
QTime lastUpdate;
public:
// Returns true if packets should be dropped