typedef void SPLAYFREE(Value &);
typedef SplayIterator<V> iterator;
typedef const SplayConstIterator<V> const_iterator;
- Splay():head(NULL), elements (0) {}
+ Splay():head(nullptr), elements (0) {}
template <class FindValue> Value const *find (FindValue const &, int( * compare)(FindValue const &a, Value const &b)) const;
SQUIDCEXTERN int splayLastResult;
template<class V>
-SplayNode<V>::SplayNode (Value const &someData) : data(someData), left(NULL), right (NULL) {}
+SplayNode<V>::SplayNode (Value const &someData) : data(someData), left(nullptr), right (nullptr) {}
template<class V>
void
if (splayLastResult == 0) { /* found it */
SplayNode<V> *newTop;
- if (result->left == NULL) {
+ if (result->left == nullptr) {
newTop = result->right;
} else {
newTop = result->left->splay(dataToRemove, compare);
/* temporary */
newTop->right = result->right;
- result->right = NULL;
+ result->right = nullptr;
}
delete result;
if (splayLastResult < 0) {
newNode->left = newTop->left;
newNode->right = newTop;
- newTop->left = NULL;
+ newTop->left = nullptr;
return newNode;
} else if (splayLastResult > 0) {
newNode->right = newTop->right;
newNode->left = newTop;
- newTop->right = NULL;
+ newTop->right = nullptr;
return newNode;
} else {
/* duplicate entry */
SplayNode<V> *l;
SplayNode<V> *r;
SplayNode<V> *y;
- N.left = N.right = NULL;
+ N.left = N.right = nullptr;
l = r = &N;
SplayNode<V> *top = const_cast<SplayNode<V> *>(this);
splayLastResult = compare(dataToFind, top->data);
if (splayLastResult < 0) {
- if (top->left == NULL)
+ if (top->left == nullptr)
break;
if ((splayLastResult = compare(dataToFind, top->left->data)) < 0) {
y->right = top;
top = y;
- if (top->left == NULL)
+ if (top->left == nullptr)
break;
}
r = top;
top = top->left;
} else if (splayLastResult > 0) {
- if (top->right == NULL)
+ if (top->right == nullptr)
break;
if ((splayLastResult = compare(dataToFind, top->right->data)) > 0) {
y->left = top;
top = y;
- if (top->right == NULL)
+ if (top->right == nullptr)
break;
}
typename Splay<V>::Value const *
Splay<V>::find (FindValue const &value, int( * compare)(FindValue const &a, Value const &b)) const
{
- if (head == NULL)
- return NULL;
+ if (head == nullptr)
+ return nullptr;
head = head->splay(value, compare);
if (splayLastResult != 0)
- return NULL;
+ return nullptr;
return &head->data;
}
void
Splay<V>::insert(Value const &value, SPLAYCMP *compare)
{
- if (find(value, compare) != NULL) // ignore duplicates
+ if (find(value, compare) != nullptr) // ignore duplicates
return;
- if (head == NULL)
+ if (head == nullptr)
head = new SplayNode<V>(value);
else
head = head->insert(value, compare);
Splay<V>::remove(Value const &value, SPLAYCMP *compare)
{
// also catches the head==NULL case
- if (find(value, compare) == NULL)
+ if (find(value, compare) == nullptr)
return;
head = head->remove(value, compare);
if (head)
return head->start();
- return NULL;
+ return nullptr;
}
template <class V>
if (head)
return head->finish();
- return NULL;
+ return nullptr;
}
template <class V>
if (head)
head->destroy(free_func);
- head = NULL;
+ head = nullptr;
elements = 0;
}
const SplayConstIterator<V>
Splay<V>::end() const
{
- return const_iterator(NULL);
+ return const_iterator(nullptr);
}
// XXX: This does not seem to iterate the whole thing in some cases.
void
SplayConstIterator<V>::addLeftPath(SplayNode<V> *aNode)
{
- if (aNode == NULL)
+ if (aNode == nullptr)
return;
do {
toVisit.push(aNode);
aNode = aNode->left;
- } while (aNode != NULL);
+ } while (aNode != nullptr);
}
template <class V>
hid->buckets = (hash_link **)xcalloc(hid->size, sizeof(hash_link *));
hid->cmp = cmp_func;
hid->hash = hash_func;
- hid->next = NULL;
+ hid->next = nullptr;
hid->current_slot = 0;
return hid;
}
hash_lookup(hash_table * hid, const void *k)
{
int b;
- assert(k != NULL);
+ assert(k != nullptr);
b = hid->hash(k, hid->size);
- for (hash_link *walker = hid->buckets[b]; walker != NULL; walker = walker->next) {
+ for (hash_link *walker = hid->buckets[b]; walker != nullptr; walker = walker->next) {
if ((hid->cmp) (k, walker->key) == 0) {
return (walker);
}
assert(walker != walker->next);
}
- return NULL;
+ return nullptr;
}
static void
hash_next_bucket(hash_table * hid)
{
- while (hid->next == NULL && ++hid->current_slot < hid->size)
+ while (hid->next == nullptr && ++hid->current_slot < hid->size)
hid->next = hid->buckets[hid->current_slot];
}
void
hash_first(hash_table * hid)
{
- assert(NULL == hid->next);
+ assert(nullptr == hid->next);
hid->current_slot = 0;
hid->next = hid->buckets[hid->current_slot];
- if (NULL == hid->next)
+ if (nullptr == hid->next)
hash_next_bucket(hid);
}
hash_next(hash_table * hid)
{
hash_link *p = hid->next;
- if (NULL == p)
- return NULL;
+ if (nullptr == p)
+ return nullptr;
hid->next = p->next;
- if (NULL == hid->next)
+ if (nullptr == hid->next)
hash_next_bucket(hid);
return p;
}
void
hash_last(hash_table * hid)
{
- assert(hid != NULL);
- hid->next = NULL;
+ assert(hid != nullptr);
+ hid->next = nullptr;
hid->current_slot = 0;
}
void
hash_remove_link(hash_table * hid, hash_link * hl)
{
- assert(hl != NULL);
+ assert(hl != nullptr);
int i = hid->hash(hl->key, hid->size);
for (hash_link **P = &hid->buckets[i]; *P; P = &(*P)->next) {
if (*P != hl)
*P = hl->next;
if (hid->next == hl) {
hid->next = hl->next;
- if (NULL == hid->next)
+ if (nullptr == hid->next)
hash_next_bucket(hid);
}
--hid->count;
hash_get_bucket(hash_table * hid, unsigned int bucket)
{
if (bucket >= hid->size)
- return NULL;
+ return nullptr;
return (hid->buckets[bucket]);
}
void
hashFreeMemory(hash_table * hid)
{
- if (hid == NULL)
+ if (hid == nullptr)
return;
if (hid->buckets)
xfree(hid->buckets);
#include <unistd.h>
#endif
-Trie::Trie(TrieCharTransform *aTransform) : head(0), transform(aTransform)
+Trie::Trie(TrieCharTransform *aTransform) : head(nullptr), transform(aTransform)
{}
Trie::~Trie()
{
public:
- Trie(TrieCharTransform *aTransform = 0);
+ Trie(TrieCharTransform *aTransform = nullptr);
~Trie();
Trie (Trie const &);
Trie &operator= (Trie const &);
if (head)
return head->find (aString, theLength, transform, false);
- return NULL;
+ return nullptr;
}
void *
if (head)
return head->find (aString, theLength, transform, true);
- return NULL;
+ return nullptr;
}
#endif /* LIBTRIE_SQUID_H */
#include <unistd.h>
#endif
-TrieNode::TrieNode() : _privateData(NULL)
+TrieNode::TrieNode() : _privateData(nullptr)
{
for (int i = 0; i < 256; ++i)
- internal[i] = NULL;
+ internal[i] = nullptr;
}
TrieNode::~TrieNode()
if (prefix)
return _privateData;
- return NULL;
+ return nullptr;
} else {
/* terminal node */
return _privateData;
lstring rv;
char *d;
- rv.str = NULL;
+ rv.str = nullptr;
rv.l = -1;
int16_t l = le16toh(str->len);
void
ntlm_make_nonce(char *nonce)
{
- static std::mt19937 mt(time(0));
+ static std::mt19937 mt(time(nullptr));
static xuniform_int_distribution<uint8_t> dist;
for (int i = 0; i < NTLM_NONCE_LEN; ++i)
memset(ch, 0, sizeof(ntlm_challenge)); /* reset */
memcpy(ch->hdr.signature, "NTLMSSP", 8); /* set the signature */
ch->hdr.type = htole32(NTLM_CHALLENGE); /* this is a challenge */
- if (domain != NULL) {
+ if (domain != nullptr) {
// silently truncate the domain if it exceeds 2^16-1 bytes.
// NTLM packets normally expect 2^8 bytes of domain.
const uint16_t dlen = strlen(domain) & 0xFFFF;
}
if (0) { //temporary hack to keep the linker happy
- uc(NULL);
- lc(NULL);
- hex_dump(NULL,0);
+ uc(nullptr);
+ lc(nullptr);
+ hex_dump(nullptr,0);
}
}
void BodyProducer::stopProducingFor(RefCount<BodyPipe> &p, bool atEof)
{
debugs(91,7, this << " will not produce for " << p << "; atEof: " << atEof);
- assert(p != NULL); // be strict: the caller state may depend on this
+ assert(p != nullptr); // be strict: the caller state may depend on this
p->clearProducer(atEof);
- p = NULL;
+ p = nullptr;
}
/* BodyConsumer */
void BodyConsumer::stopConsumingFrom(RefCount<BodyPipe> &p)
{
debugs(91,7, this << " will not consume from " << p);
- assert(p != NULL); // be strict: the caller state may depend on this
+ assert(p != nullptr); // be strict: the caller state may depend on this
p->clearConsumer();
- p = NULL;
+ p = nullptr;
}
/* BodyPipe */
BodyPipe::BodyPipe(Producer *aProducer): theBodySize(-1),
- theProducer(aProducer), theConsumer(0),
+ theProducer(aProducer), theConsumer(nullptr),
thePutSize(0), theGetSize(0),
mustAutoConsume(false), abortedConsumption(false), isCheckedOut(false)
{
{
public:
/* RegisteredRunner API */
- CollapsedForwardingRr(): owner(NULL) {}
+ CollapsedForwardingRr(): owner(nullptr) {}
virtual ~CollapsedForwardingRr();
protected:
void
CommCommonCbParams::print(std::ostream &os) const
{
- if (conn != NULL)
+ if (conn != nullptr)
os << conn;
else
os << "FD " << fd;
/* CommIoCbParams */
CommIoCbParams::CommIoCbParams(void *aData): CommCommonCbParams(aData),
- buf(NULL), size(0)
+ buf(nullptr), size(0)
{
}
bool ConfigParser::StrictMode = true;
std::stack<ConfigParser::CfgFile *> ConfigParser::CfgFiles;
ConfigParser::TokenType ConfigParser::LastTokenType = ConfigParser::SimpleToken;
-const char *ConfigParser::CfgLine = NULL;
-const char *ConfigParser::CfgPos = NULL;
+const char *ConfigParser::CfgLine = nullptr;
+const char *ConfigParser::CfgPos = nullptr;
std::queue<char *> ConfigParser::CfgLineTokens_;
bool ConfigParser::AllowMacros_ = false;
bool ConfigParser::ParseQuotedOrToEol_ = false;
return ConfigParser::NextToken();
static int fromFile = 0;
- static FILE *wordFile = NULL;
+ static FILE *wordFile = nullptr;
char *t;
static char buf[CONFIG_LINE_LIMIT];
ConfigParser::TokenType tokenType;
t = ConfigParser::NextElement(tokenType);
if (!t) {
- return NULL;
+ return nullptr;
} else if (*t == '\"' || *t == '\'') {
/* quote found, start reading from file */
debugs(3, 8,"Quoted token found : " << t);
*t = '\0';
- if ((wordFile = fopen(fn, "r")) == NULL) {
+ if ((wordFile = fopen(fn, "r")) == nullptr) {
debugs(3, DBG_CRITICAL, "ERROR: Can not open file " << fn << " for reading");
- return NULL;
+ return nullptr;
}
#if _SQUID_WINDOWS_
}
/* fromFile */
- if (fgets(buf, sizeof(buf), wordFile) == NULL) {
+ if (fgets(buf, sizeof(buf), wordFile) == nullptr) {
/* stop reading from file */
fclose(wordFile);
- wordFile = NULL;
+ wordFile = nullptr;
fromFile = 0;
- return NULL;
+ return nullptr;
} else {
char *t2, *t3;
t = buf;
char *
ConfigParser::UnQuote(const char *token, const char **next)
{
- const char *errorStr = NULL;
- const char *errorPos = NULL;
+ const char *errorStr = nullptr;
+ const char *errorPos = nullptr;
char quoteChar = *token;
assert(quoteChar == '"' || quoteChar == '\'');
LOCAL_ARRAY(char, UnQuoted, CONFIG_LINE_LIMIT);
ConfigParser::TokenParse(const char * &nextToken, ConfigParser::TokenType &type)
{
if (!nextToken || *nextToken == '\0')
- return NULL;
+ return nullptr;
type = ConfigParser::SimpleToken;
nextToken += strspn(nextToken, w_space);
if (*nextToken == '#')
- return NULL;
+ return nullptr;
if (ConfigParser::RecognizeQuotedValues && (*nextToken == '"' || *nextToken == '\'')) {
type = ConfigParser::QuotedToken;
} else
type = ConfigParser::SimpleToken;
- char *token = NULL;
+ char *token = nullptr;
if (nextToken - tokenStart) {
if (ConfigParser::StrictMode && type == ConfigParser::SimpleToken) {
bool tokenIsNumber = true;
char *
ConfigParser::NextToken()
{
- char *token = NULL;
+ char *token = nullptr;
do {
- while (token == NULL && !CfgFiles.empty()) {
+ while (token == nullptr && !CfgFiles.empty()) {
ConfigParser::CfgFile *wordfile = CfgFiles.top();
token = wordfile->parse(LastTokenType);
if (!token) {
if (LastTokenType != ConfigParser::QuotedToken) {
debugs(3, DBG_CRITICAL, "FATAL: Quoted filename missing: " << token);
self_destruct();
- return NULL;
+ return nullptr;
}
// The next token in current cfg file line must be a ")"
if (LastTokenType != ConfigParser::SimpleToken || strcmp(end, ")") != 0) {
debugs(3, DBG_CRITICAL, "FATAL: missing ')' after " << token << "(\"" << path << "\"");
self_destruct();
- return NULL;
+ return nullptr;
}
if (CfgFiles.size() > 16) {
debugs(3, DBG_CRITICAL, "FATAL: can't open %s for reading parameters: includes are nested too deeply (>16)!\n" << path);
self_destruct();
- return NULL;
+ return nullptr;
}
ConfigParser::CfgFile *wordfile = new ConfigParser::CfgFile();
debugs(3, DBG_CRITICAL, "FATAL: Error opening config file: " << token);
delete wordfile;
self_destruct();
- return NULL;
+ return nullptr;
}
CfgFiles.push(wordfile);
- token = NULL;
+ token = nullptr;
}
- } while (token == NULL && !CfgFiles.empty());
+ } while (token == nullptr && !CfgFiles.empty());
return token;
}
bool
ConfigParser::NextKvPair(char * &key, char * &value)
{
- key = value = NULL;
+ key = value = nullptr;
ParseKvPair_ = true;
KvPairState_ = ConfigParser::atParseKey;
- if ((key = NextToken()) != NULL) {
+ if ((key = NextToken()) != nullptr) {
KvPairState_ = ConfigParser::atParseValue;
value = NextQuotedToken();
}
bool
ConfigParser::CfgFile::startParse(char *path)
{
- assert(wordFile == NULL);
+ assert(wordFile == nullptr);
debugs(3, 3, "Parsing from " << path);
- if ((wordFile = fopen(path, "r")) == NULL) {
+ if ((wordFile = fopen(path, "r")) == nullptr) {
debugs(3, DBG_CRITICAL, "WARNING: file :" << path << " not found");
return false;
}
ConfigParser::CfgFile::getFileLine()
{
// Else get the next line
- if (fgets(parseBuffer, CONFIG_LINE_LIMIT, wordFile) == NULL) {
+ if (fgets(parseBuffer, CONFIG_LINE_LIMIT, wordFile) == nullptr) {
/* stop reading from file */
fclose(wordFile);
- wordFile = NULL;
+ wordFile = nullptr;
parseBuffer[0] = '\0';
return false;
}
ConfigParser::CfgFile::parse(ConfigParser::TokenType &type)
{
if (!wordFile)
- return NULL;
+ return nullptr;
if (!*parseBuffer)
- return NULL;
+ return nullptr;
char *token;
while (!(token = nextElement(type))) {
if (!getFileLine())
- return NULL;
+ return nullptr;
}
return token;
}
class CfgFile
{
public:
- CfgFile(): wordFile(NULL), parsePos(NULL), lineNo(0) { parseBuffer[0] = '\0';}
+ CfgFile(): wordFile(nullptr), parsePos(nullptr), lineNo(0) { parseBuffer[0] = '\0';}
~CfgFile();
/// True if the configuration file is open
- bool isOpen() {return wordFile != NULL;}
+ bool isOpen() {return wordFile != nullptr;}
/**
* Open the file given by 'path' and initializes the CfgFile object
* Unquotes the token, which must be quoted.
* \param next if it is not NULL, it is set after the end of token.
*/
- static char *UnQuote(const char *token, const char **next = NULL);
+ static char *UnQuote(const char *token, const char **next = nullptr);
/**
* Does the real tokens parsing job: Ignore comments, unquote an
#include <algorithm>
-static CpuAffinitySet *TheCpuAffinitySet = NULL;
+static CpuAffinitySet *TheCpuAffinitySet = nullptr;
void
CpuAffinityInit()
if (TheCpuAffinitySet) {
TheCpuAffinitySet->undo();
delete TheCpuAffinitySet;
- TheCpuAffinitySet = NULL;
+ TheCpuAffinitySet = nullptr;
}
CpuAffinityInit();
}
core = theCores[i];
}
}
- CpuAffinitySet *cpuAffinitySet = NULL;
+ CpuAffinitySet *cpuAffinitySet = nullptr;
if (core > 0) {
cpuAffinitySet = new CpuAffinitySet;
cpu_set_t cpuSet;
#include "HttpRequest.h"
#include "SquidConfig.h"
-DelayId::DelayId () : pool_ (0), compositeId(NULL), markedAsNoDelay(false)
+DelayId::DelayId () : pool_ (0), compositeId(nullptr), markedAsNoDelay(false)
{}
DelayId::DelayId (unsigned short aPool) :
- pool_ (aPool), compositeId (NULL), markedAsNoDelay (false)
+ pool_ (aPool), compositeId (nullptr), markedAsNoDelay (false)
{
debugs(77, 3, "DelayId::DelayId: Pool " << aPool << "u");
}
continue;
}
- ACLFilledChecklist ch(DelayPools::delay_data[pool].access, r, NULL);
+ ACLFilledChecklist ch(DelayPools::delay_data[pool].access, r, nullptr);
clientAclChecklistFill(ch, http);
if (!ch.reply && reply) {
ch.reply = reply;
/* limited */
int nbytes = max(minimum, maximum);
- if (compositeId != NULL)
+ if (compositeId != nullptr)
nbytes = compositeId->bytesWanted(minimum, nbytes);
return nbytes;
assert ((unsigned short)(pool() - 1) != 0xFFFF);
- if (compositeId != NULL)
+ if (compositeId != nullptr)
compositeId->bytesIn(qty);
}
void
DelayId::delayRead(const AsyncCall::Pointer &aRead)
{
- assert (compositeId != NULL);
+ assert (compositeId != nullptr);
compositeId->delayRead(aRead);
}
#include "DelayPool.h"
#include "Store.h"
-DelayPool::DelayPool() : pool (NULL), access (NULL)
+DelayPool::DelayPool() : pool (nullptr), access (nullptr)
{
pool = CommonPool::Factory(0, theComposite_);
}
void
DelayPool::parse()
{
- assert(theComposite() != NULL);
+ assert(theComposite() != nullptr);
theComposite()->parse();
}
void
DelayPool::dump(StoreEntry *entry, unsigned int i) const
{
- if (theComposite() == NULL)
+ if (theComposite() == nullptr)
return;
storeAppendPrintf(entry, "delay_class %d %s\n", i + 1, pool->theClassTypeLabel());
DelayPool::freeData()
{
delete pool;
- pool = NULL;
+ pool = nullptr;
}
// TODO: create DelayIdComposite.cc
}
// parse the first digits into restore_bps
- const char *p = NULL;
+ const char *p = nullptr;
if (!StringToInt(token, restore_bps, &p, 10) || *p != '/') {
debugs(77, DBG_CRITICAL, "ERROR: invalid delay rate '" << token << "'. Expecting restore/max or 'none'.");
self_destruct();
p++; // increment past the '/'
// parse the rest into max_bytes
- if (!StringToInt64(p, max_bytes, NULL, 10)) {
+ if (!StringToInt64(p, max_bytes, nullptr, 10)) {
debugs(77, DBG_CRITICAL, "ERROR: restore rate in '" << token << "' is not a number.");
self_destruct();
}
DelayUserCmp(DelayUserBucket::Pointer const &left, DelayUserBucket::Pointer const &right)
{
/* Verify for re-currance of Bug 2127. either of these missing will crash strcasecmp() */
- assert(left->authUser->username() != NULL);
- assert(right->authUser->username() != NULL);
+ assert(left->authUser->username() != nullptr);
+ assert(right->authUser->username() != nullptr);
/* for rate limiting, case insensitive */
return strcasecmp(left->authUser->username(), right->authUser->username());
DelayUserBucket::~DelayUserBucket()
{
- authUser = NULL;
+ authUser = nullptr;
debugs(77, 3, "DelayUserBucket::~DelayUserBucket");
}
#include "globals.h" /* for Squid_MaxFD */
// pre-allocates descriptor store and index for Squid_MaxFD descriptors
-DescriptorSet::DescriptorSet(): descriptors_(NULL), index_(NULL),
+DescriptorSet::DescriptorSet(): descriptors_(nullptr), index_(nullptr),
capacity_(0), size_(0)
{
// we allocate once and never realloc, at least for now
qe->aq_e_type = AQ_ENTRY_READ;
- qe->aq_e_free = NULL;
+ qe->aq_e_free = nullptr;
qe->aq_e_buf = request->buf;
fd = -1;
closed = true;
- assert (ioRequestor != NULL);
+ assert (ioRequestor != nullptr);
ioRequestor->closeCompleted();
}
AIODiskIOStrategy::newFile (char const *path)
{
if (shedLoad()) {
- return NULL;
+ return nullptr;
}
return new AIODiskFile (path, this);
ConfigOption *
AIODiskIOStrategy::getOptionTree() const
{
- return NULL;
+ return nullptr;
}
/*
ReadRequest::Pointer result = readRequest;
- readRequest = NULL;
+ readRequest = nullptr;
ioRequestor->readCompleted(buf, rlen, errflag, result);
}
debugs(79, 3, "FD " << fd << ", len " << len);
WriteRequest::Pointer result = writeRequest;
- writeRequest = NULL;
+ writeRequest = nullptr;
if (errflag) {
debugs(79, DBG_CRITICAL, "storeUfsWriteDone: got failure (" << errflag << ")");
DiskdAction::dump(StoreEntry* entry)
{
debugs(79, 5, MYNAME);
- Must(entry != NULL);
+ Must(entry != nullptr);
storeAppendPrintf(entry, "sent_count: %.0f\n", data.sent_count);
storeAppendPrintf(entry, "recv_count: %.0f\n", data.recv_count);
storeAppendPrintf(entry, "max_away: %.0f\n", data.max_away);
DiskdFile::open(int flags, mode_t, RefCount<IORequestor> callback)
{
debugs(79, 3, "DiskdFile::open: " << this << " opening for " << callback.getRaw());
- assert(ioRequestor.getRaw() == NULL);
+ assert(ioRequestor.getRaw() == nullptr);
ioRequestor = callback;
assert(callback.getRaw());
mode = flags;
strlen(buf) + 1,
mode,
shm_offset,
- NULL);
+ nullptr);
if (x < 0) {
ioCompleted();
errorOccured = true;
// IO->shm.put (shm_offset);
ioRequestor->ioCompletedNotification();
- ioRequestor = NULL;
+ ioRequestor = nullptr;
}
++diskd_stats.open.ops;
DiskdFile::create(int flags, mode_t, RefCount<IORequestor> callback)
{
debugs(79, 3, "DiskdFile::create: " << this << " creating for " << callback.getRaw());
- assert (ioRequestor.getRaw() == NULL);
+ assert (ioRequestor.getRaw() == nullptr);
ioRequestor = callback;
assert (callback.getRaw());
mode = flags;
strlen(buf) + 1,
mode,
shm_offset,
- NULL);
+ nullptr);
if (x < 0) {
int xerrno = errno;
// IO->shm.put (shm_offset);
debugs(79, DBG_IMPORTANT, "storeDiskdSend CREATE: " << xstrerr(xerrno));
notifyClient();
- ioRequestor = NULL;
+ ioRequestor = nullptr;
return;
}
void
DiskdFile::read(ReadRequest *aRead)
{
- assert (ioRequestor.getRaw() != NULL);
+ assert (ioRequestor.getRaw() != nullptr);
ssize_t shm_offset;
char *rbuf = (char *)IO->shm.get(&shm_offset);
assert(rbuf);
// IO->shm.put (shm_offset);
debugs(79, DBG_IMPORTANT, "storeDiskdSend READ: " << xstrerr(xerrno));
notifyClient();
- ioRequestor = NULL;
+ ioRequestor = nullptr;
return;
}
0,
0,
-1,
- NULL);
+ nullptr);
if (x < 0) {
int xerrno = errno;
errorOccured = true;
debugs(79, DBG_IMPORTANT, "storeDiskdSend CLOSE: " << xstrerr(xerrno));
notifyClient();
- ioRequestor = NULL;
+ ioRequestor = nullptr;
return;
}
debugs(79, DBG_IMPORTANT, "storeDiskdSend WRITE: " << xstrerr(xerrno));
// IO->shm.put (shm_offset);
notifyClient();
- ioRequestor = NULL;
+ ioRequestor = nullptr;
return;
}
if (canNotifyClient())
ioRequestor->closeCompleted();
- ioRequestor = NULL;
+ ioRequestor = nullptr;
}
void
ReadRequest::Pointer readRequest = dynamic_cast<ReadRequest *>(M->requestor);
/* remove the free protection */
- if (readRequest != NULL) {
+ if (readRequest != nullptr) {
const uint32_t lcount = readRequest->unlock();
if (lcount == 0)
debugs(79, DBG_IMPORTANT, "ERROR: invariant check failed: readRequest reference count is 0");
++diskd_stats.read.fail;
ioCompleted();
errorOccured = true;
- ioRequestor->readCompleted(NULL, -1, DISK_ERROR, readRequest);
+ ioRequestor->readCompleted(nullptr, -1, DISK_ERROR, readRequest);
return;
}
WriteRequest::Pointer writeRequest = dynamic_cast<WriteRequest *>(M->requestor);
/* remove the free protection */
- if (writeRequest != NULL) {
+ if (writeRequest != nullptr) {
const uint32_t lcount = writeRequest->unlock();
if (lcount == 0)
debugs(79, DBG_IMPORTANT, "ERROR: invariant check failed: writeRequest reference count is 0");
{
if (shedLoad()) {
openFailed();
- return NULL;
+ return nullptr;
}
return new DiskdFile (path, this);
x = send(_MQD_UNLINK,
0,
- (StoreIOState::Pointer )NULL,
+ (StoreIOState::Pointer )nullptr,
0,
0,
shm_offset);
args[1] = skey1;
args[2] = skey2;
args[3] = skey3;
- args[4] = NULL;
+ args[4] = nullptr;
localhost.setLocalhost();
pid = ipcCreate(IPC_STREAM,
Config.Program.diskd,
SharedMemory::get(ssize_t * shm_offset)
{
- char *aBuf = NULL;
+ char *aBuf = nullptr;
int i;
for (i = 0; i < nbufs; ++i) {
fatal("shmget failed");
}
- buf = (char *)shmat(id, NULL, 0);
+ buf = (char *)shmat(id, nullptr, 0);
if (buf == (void *) -1) {
int xerrno = errno;
struct timeval delay = {0, 1};
while (away > magic2) {
- select(0, NULL, NULL, NULL, &delay);
+ select(0, nullptr, nullptr, nullptr, &delay);
Store::Root().callback();
if (delay.tv_usec < 1000000)
off_t offset;
};
-static hash_table *hash = NULL;
+static hash_table *hash = nullptr;
static pid_t mypid;
static char *shmbuf;
static int DebugLevel = 0;
file_state *fs;
fs = (file_state *) hash_lookup(hash, &r->id);
- if (NULL == fs) {
+ if (nullptr == fs) {
errno = EBADF;
DEBUG(1) {
fprintf(stderr, "%d CLOSE id %d: ", (int) mypid, r->id);
file_state *fs;
fs = (file_state *) hash_lookup(hash, &r->id);
- if (NULL == fs) {
+ if (nullptr == fs) {
errno = EBADF;
DEBUG(1) {
fprintf(stderr, "%d READ id %d: ", (int) mypid, r->id);
file_state *fs;
fs = (file_state *) hash_lookup(hash, &r->id);
- if (NULL == fs) {
+ if (nullptr == fs) {
errno = EBADF;
DEBUG(1) {
fprintf(stderr, "%d WRITE id %d: ", (int) mypid, r->id);
static void
msg_handle(diomsg * r, int rl, diomsg * s)
{
- char *buf = NULL;
+ char *buf = nullptr;
s->mtype = r->mtype;
s->id = r->id;
s->seq_no = r->seq_no; /* optional, debugging */
char rbuf[512];
struct sigaction sa;
- setbuf(stdout, NULL);
- setbuf(stderr, NULL);
+ setbuf(stdout, nullptr);
+ setbuf(stderr, nullptr);
mypid = getpid();
assert(4 == argc);
key = atoi(argv[1]);
exit(EXIT_FAILURE);
}
- shmbuf = (char *)shmat(shmid, NULL, 0);
+ shmbuf = (char *)shmat(shmid, nullptr, 0);
if (shmbuf == (void *) -1) {
perror("shmat");
memset(&sa, '\0', sizeof(sa));
sa.sa_handler = alarm_handler;
sa.sa_flags = SA_RESTART;
- sigaction(SIGALRM, &sa, NULL);
+ sigaction(SIGALRM, &sa, nullptr);
for (;;) {
alarm(1);
fprintf(stderr, "%d diskd exiting\n", (int) mypid);
}
- if (msgctl(rmsgid, IPC_RMID, 0) < 0)
+ if (msgctl(rmsgid, IPC_RMID, nullptr) < 0)
perror("msgctl IPC_RMID");
- if (msgctl(smsgid, IPC_RMID, 0) < 0)
+ if (msgctl(smsgid, IPC_RMID, nullptr) < 0)
perror("msgctl IPC_RMID");
if (shmdt(shmbuf) < 0)
perror("shmdt");
- if (shmctl(shmid, IPC_RMID, 0) < 0)
+ if (shmctl(shmid, IPC_RMID, nullptr) < 0)
perror("shmctl IPC_RMID");
return EXIT_SUCCESS;
#include "DiskIO/Mmapped/MmappedDiskIOModule.h"
#endif
-std::vector<DiskIOModule*> *DiskIOModule::_Modules = NULL;
+std::vector<DiskIOModule*> *DiskIOModule::_Modules = nullptr;
//DiskIOModule() : initialised (false) {}
if (strcasecmp(type, (*i)->type()) == 0)
return *i;
- return NULL;
+ return nullptr;
}
DiskIOModule *
/** Best IO options are in order: */
DiskIOModule * result;
result = Find("DiskThreads");
- if (NULL == result)
+ if (nullptr == result)
result = Find("DiskDaemon");
- if (NULL == result)
+ if (nullptr == result)
result = Find("AIO");
- if (NULL == result)
+ if (nullptr == result)
result = Find("Blocking");
return result;
}
virtual void statfs(StoreEntry &) const {}
/** module specific options */
- virtual ConfigOption *getOptionTree() const {return NULL;}
+ virtual ConfigOption *getOptionTree() const {return nullptr;}
};
/* Because we need the DiskFile definition for newFile. */
fd_open(DoneFD, FD_PIPE, "async-io completion event: threads");
commSetNonBlocking(DoneReadFD);
commSetNonBlocking(DoneFD);
- Comm::SetSelect(DoneReadFD, COMM_SELECT_READ, NULLFDHandler, NULL, 0);
+ Comm::SetSelect(DoneReadFD, COMM_SELECT_READ, NULLFDHandler, nullptr, 0);
Initialized = true;
}
CommIO::NULLFDHandler(int fd, void *)
{
FlushPipe();
- Comm::SetSelect(fd, COMM_SELECT_READ, NULLFDHandler, NULL, 0);
+ Comm::SetSelect(fd, COMM_SELECT_READ, NULLFDHandler, nullptr, 0);
}
void
{
MEMPROXY_CLASS(squidaio_ctrl_t);
public:
- squidaio_ctrl_t() : done_handler(NULL), free_func(NULL) {}
+ squidaio_ctrl_t() : done_handler(nullptr), free_func(nullptr) {}
squidaio_ctrl_t *next = nullptr;
int fd = 0;
if (!ioInProgress()) {
doClose();
- assert (ioRequestor != NULL);
+ assert (ioRequestor != nullptr);
ioRequestor->closeCompleted();
return;
} else {
++squidaio_counts.check_callback;
for (;;) {
- if ((resultp = squidaio_poll_done()) == NULL)
+ if ((resultp = squidaio_poll_done()) == nullptr)
break;
ctrlp = (squidaio_ctrl_t *) resultp->data;
break;
}
- if (ctrlp == NULL)
+ if (ctrlp == nullptr)
continue; /* XXX Should not happen */
dlinkDelete(&ctrlp->node, &used_list);
if (ctrlp->done_handler) {
AIOCB *done_callback = ctrlp->done_handler;
void *cbdata;
- ctrlp->done_handler = NULL;
+ ctrlp->done_handler = nullptr;
if (cbdataReferenceValidDone(ctrlp->done_handler_data, &cbdata)) {
retval = 1; /* Return that we've actually done some work */
DiskThreadsIOStrategy::newFile (char const *path)
{
if (shedLoad()) {
- return NULL;
+ return nullptr;
}
return new DiskThreadsDiskFile(path);
DiskThreadsIOStrategy::unlinkFile(char const *path)
{
++statCounter.syscalls.disk.unlinks;
- aioUnlink(path, NULL, NULL);
+ aioUnlink(path, nullptr, nullptr);
}
static void squidaio_debug(squidaio_request_t *);
static void squidaio_poll_queues(void);
-static squidaio_thread_t *threads = NULL;
+static squidaio_thread_t *threads = nullptr;
static int squidaio_initialised = 0;
#define AIO_LARGE_BUFS 16384
#define AIO_TINY_BUFS AIO_LARGE_BUFS >> 3
#define AIO_MICRO_BUFS 128
-static MemAllocator *squidaio_large_bufs = NULL; /* 16K */
-static MemAllocator *squidaio_medium_bufs = NULL; /* 8K */
-static MemAllocator *squidaio_small_bufs = NULL; /* 4K */
-static MemAllocator *squidaio_tiny_bufs = NULL; /* 2K */
-static MemAllocator *squidaio_micro_bufs = NULL; /* 128K */
+static MemAllocator *squidaio_large_bufs = nullptr; /* 16K */
+static MemAllocator *squidaio_medium_bufs = nullptr; /* 8K */
+static MemAllocator *squidaio_small_bufs = nullptr; /* 4K */
+static MemAllocator *squidaio_tiny_bufs = nullptr; /* 2K */
+static MemAllocator *squidaio_micro_bufs = nullptr; /* 128K */
static int request_queue_len = 0;
-static MemAllocator *squidaio_request_pool = NULL;
-static MemAllocator *squidaio_thread_pool = NULL;
+static MemAllocator *squidaio_request_pool = nullptr;
+static MemAllocator *squidaio_thread_pool = nullptr;
static squidaio_request_queue_t request_queue;
static struct {
request_queue2 = {
- NULL, &request_queue2.head
+ nullptr, &request_queue2.head
};
static squidaio_request_queue_t done_queue;
done_requests = {
- NULL, &done_requests.head
+ nullptr, &done_requests.head
};
static pthread_attr_t globattr;
#if HAVE_SCHED_H
return squidaio_large_bufs;
}
- return NULL;
+ return nullptr;
}
void *
void *p;
MemAllocator *pool;
- if ((pool = squidaio_get_pool(size)) != NULL) {
+ if ((pool = squidaio_get_pool(size)) != nullptr) {
p = pool->alloc();
} else
p = xmalloc(size);
{
MemAllocator *pool;
- if ((pool = squidaio_get_pool(size)) != NULL) {
+ if ((pool = squidaio_get_pool(size)) != nullptr) {
pool->freeOne(p);
} else
xfree(p);
MemAllocator *pool;
int len = strlen(str) + 1;
- if ((pool = squidaio_get_pool(len)) != NULL) {
+ if ((pool = squidaio_get_pool(len)) != nullptr) {
pool->freeOne(str);
} else
xfree(str);
pthread_attr_setstacksize(&globattr, 256 * 1024);
/* Initialize request queue */
- if (pthread_mutex_init(&(request_queue.mutex), NULL))
+ if (pthread_mutex_init(&(request_queue.mutex), nullptr))
fatal("Failed to create mutex");
- if (pthread_cond_init(&(request_queue.cond), NULL))
+ if (pthread_cond_init(&(request_queue.cond), nullptr))
fatal("Failed to create condition variable");
- request_queue.head = NULL;
+ request_queue.head = nullptr;
request_queue.tailp = &request_queue.head;
request_queue.blocked = 0;
/* Initialize done queue */
- if (pthread_mutex_init(&(done_queue.mutex), NULL))
+ if (pthread_mutex_init(&(done_queue.mutex), nullptr))
fatal("Failed to create mutex");
- if (pthread_cond_init(&(done_queue.cond), NULL))
+ if (pthread_cond_init(&(done_queue.cond), nullptr))
fatal("Failed to create condition variable");
- done_queue.head = NULL;
+ done_queue.head = nullptr;
done_queue.tailp = &done_queue.head;
for (i = 0; i < NUMTHREADS; ++i) {
threadp = (squidaio_thread_t *)squidaio_thread_pool->alloc();
threadp->status = _THREAD_STARTING;
- threadp->current_req = NULL;
+ threadp->current_req = nullptr;
threadp->requests = 0;
threadp->next = threads;
threads = threadp;
sigaddset(&newSig, SIGTERM);
sigaddset(&newSig, SIGINT);
sigaddset(&newSig, SIGALRM);
- pthread_sigmask(SIG_BLOCK, &newSig, NULL);
+ pthread_sigmask(SIG_BLOCK, &newSig, nullptr);
while (1) {
- threadp->current_req = request = NULL;
- request = NULL;
+ threadp->current_req = request = nullptr;
+ request = nullptr;
/* Get a request to process */
threadp->status = _THREAD_WAITING;
pthread_mutex_lock(&request_queue.mutex);
/* process the request */
threadp->status = _THREAD_BUSY;
- request->next = NULL;
+ request->next = nullptr;
threadp->current_req = request;
++ threadp->requests;
} /* while forever */
- return NULL;
+ return nullptr;
} /* squidaio_thread_loop */
static void
request_queue_len += 1;
request->resultp->_data = request;
/* Play some tricks with the request_queue2 queue */
- request->next = NULL;
+ request->next = nullptr;
if (pthread_mutex_trylock(&request_queue.mutex) == 0) {
if (request_queue2.head) {
if (request_queue2.head) {
/* Clear queue of blocked requests */
- request_queue2.head = NULL;
+ request_queue2.head = nullptr;
request_queue2.tailp = &request_queue2.head;
}
} else {
break;
}
- if (resultp != NULL && !cancelled) {
+ if (resultp != nullptr && !cancelled) {
resultp->aio_return = requestp->ret;
resultp->aio_errno = requestp->err;
}
if (request && request->resultp == resultp) {
debugs(43, 9, "squidaio_cancel: " << request << " type=" << request->request_type << " result=" << request->resultp);
request->cancelled = 1;
- request->resultp = NULL;
- resultp->_data = NULL;
+ request->resultp = nullptr;
+ resultp->_data = nullptr;
resultp->result_type = _AIO_OP_NONE;
return 0;
}
request_queue.tailp = request_queue2.tailp;
pthread_cond_signal(&request_queue.cond);
pthread_mutex_unlock(&request_queue.mutex);
- request_queue2.head = NULL;
+ request_queue2.head = nullptr;
request_queue2.tailp = &request_queue2.head;
}
if (done_queue.head && pthread_mutex_trylock(&done_queue.mutex) == 0) {
struct squidaio_request_t *requests = done_queue.head;
- done_queue.head = NULL;
+ done_queue.head = nullptr;
done_queue.tailp = &done_queue.head;
pthread_mutex_unlock(&done_queue.mutex);
*done_requests.tailp = requests;
AIO_REPOLL:
request = done_requests.head;
- if (request == NULL && !polled) {
+ if (request == nullptr && !polled) {
CommIO::ResetNotifications();
squidaio_poll_queues();
polled = 1;
}
if (!request) {
- return NULL;
+ return nullptr;
}
debugs(43, 9, "squidaio_poll_done: " << request << " type=" << request->request_type << " result=" << request->resultp);
aioCancel(fd);
ctrlp = new squidaio_ctrl_t;
ctrlp->fd = fd;
- ctrlp->done_handler = NULL;
- ctrlp->done_handler_data = NULL;
+ ctrlp->done_handler = nullptr;
+ ctrlp->done_handler_data = nullptr;
ctrlp->operation = _AIO_CLOSE;
ctrlp->result.data = ctrlp;
squidaio_close(fd, &ctrlp->result);
if (ctrlp->done_handler) {
AIOCB *callback = ctrlp->done_handler;
void *cbdata;
- ctrlp->done_handler = NULL;
+ ctrlp->done_handler = nullptr;
debugs(32, DBG_IMPORTANT, "this be aioCancel. Danger ahead!");
if (cbdataReferenceValidDone(ctrlp->done_handler_data, &cbdata))
- callback(fd, cbdata, NULL, -2, -2);
+ callback(fd, cbdata, nullptr, -2, -2);
/* free data if requested to aioWrite() */
if (ctrlp->free_func)
void
IpcIoFile::close()
{
- assert(ioRequestor != NULL);
+ assert(ioRequestor != nullptr);
if (IamDiskProcess())
DiskerClose(SBuf(dbName.termedBuf()));
debugs(79,3, "(disker" << diskId << ", " << readRequest->len << ", " <<
readRequest->offset << ")");
- assert(ioRequestor != NULL);
+ assert(ioRequestor != nullptr);
assert(readRequest->offset >= 0);
Must(!error_);
debugs(79,3, "(disker" << diskId << ", " << writeRequest->len << ", " <<
writeRequest->offset << ")");
- assert(ioRequestor != NULL);
+ assert(ioRequestor != nullptr);
assert(writeRequest->len > 0); // TODO: work around mmap failures on zero-len?
assert(writeRequest->offset >= 0);
Must(!error_);
if (ipcIo.page)
Ipc::Mem::PutPage(ipcIo.page);
- pending->completeIo(NULL);
+ pending->completeIo(nullptr);
delete pending;
} catch (const TextException &e) {
debugs(47, DBG_IMPORTANT, "ERROR: " << dbName << " exception: " << e.what());
- pending->completeIo(NULL);
+ pending->completeIo(nullptr);
delete pending;
}
}
for (IpcIoFileList::iterator i = WaitingForOpen.begin();
i != WaitingForOpen.end(); ++i) {
if (*i == ipcIoFile) {
- (*i)->openCompleted(NULL);
+ (*i)->openCompleted(nullptr);
WaitingForOpen.erase(i);
break;
}
{
Must(requestId != 0);
- RequestMap *map = NULL;
+ RequestMap *map = nullptr;
RequestMap::iterator i = requestMap1.find(requestId);
if (i != requestMap1.end())
}
if (!map) // not found in both maps
- return NULL;
+ return nullptr;
IpcIoPendingRequest *pending = i->second;
map->erase(i);
file->writeCompleted(writeRequest, response);
else {
Must(!response); // only timeouts are handled here
- file->openCompleted(NULL);
+ file->openCompleted(nullptr);
}
}
{
public:
/* RegisteredRunner API */
- IpcIoRr(): owner(NULL) {}
+ IpcIoRr(): owner(nullptr) {}
virtual ~IpcIoRr();
virtual void claimMemoryNeeds();
{
debugs(79, 3, this << " closing for " << ioRequestor);
doClose();
- assert(ioRequestor != NULL);
+ assert(ioRequestor != nullptr);
ioRequestor->closeCompleted();
}
aRequest->offset << ")");
assert(fd >= 0);
- assert(ioRequestor != NULL);
+ assert(ioRequestor != nullptr);
assert(aRequest->len > 0); // TODO: work around mmap failures on zero-len?
assert(aRequest->offset >= 0);
assert(!error_); // TODO: propagate instead?
aRequest->offset << ")");
assert(fd >= 0);
- assert(ioRequestor != NULL);
+ assert(ioRequestor != nullptr);
assert(aRequest->len > 0); // TODO: work around mmap failures on zero-len?
assert(aRequest->offset >= 0);
assert(!error_); // TODO: propagate instead?
Mmapping::Mmapping(int aFd, size_t aLength, int aProt, int aFlags, off_t anOffset):
fd(aFd), length(aLength), prot(aProt), flags(aFlags), offset(anOffset),
- delta(-1), buf(NULL)
+ delta(-1), buf(nullptr)
{
}
static const int pageSize = getpagesize();
delta = offset % pageSize;
- buf = mmap(NULL, length + delta, prot, flags, fd, offset - delta);
+ buf = mmap(nullptr, length + delta, prot, flags, fd, offset - delta);
if (buf == MAP_FAILED) {
const int errNo = errno;
debugs(79,3, "error FD " << fd << "mmap(" << length << '+' <<
delta << ", " << offset << '-' << delta << "): " << xstrerr(errNo));
- buf = NULL;
- return NULL;
+ buf = nullptr;
+ return nullptr;
}
return static_cast<char*>(buf) + delta;
" munmap(" << buf << ", " << length << '+' << delta << "): " <<
"): " << xstrerr(errNo));
}
- buf = NULL;
+ buf = nullptr;
return !error;
}
{
int len;
assert(etag && str);
- etag->str = NULL;
+ etag->str = nullptr;
etag->weak = !strncmp(str, "W/", 2);
if (etag->weak)
if (len >= 2 && str[0] == '"' && str[len - 1] == '"')
etag->str = str;
- return etag->str != NULL;
+ return etag->str != nullptr;
}
bool
#include "fatal.h"
#include "time/Engine.h"
-EventLoop *EventLoop::Running = NULL;
+EventLoop *EventLoop::Running = nullptr;
-EventLoop::EventLoop() : errcount(0), last_loop(false), timeService(NULL),
- primaryEngine(NULL),
+EventLoop::EventLoop() : errcount(0), last_loop(false), timeService(nullptr),
+ primaryEngine(nullptr),
loop_delay(EVENT_LOOP_TIMEOUT),
error(false),
runOnceResult(false)
while (!runOnce());
- Running = NULL;
+ Running = nullptr;
}
bool
runOnceResult = false;
} while (sawActivity);
- if (waitingEngine != NULL)
+ if (waitingEngine != nullptr)
checkEngine(waitingEngine, true);
- if (timeService != NULL)
+ if (timeService != nullptr)
timeService->tick();
// dispatch calls scheduled by waitingEngine and timeService
ExternalACLEntry::ExternalACLEntry() :
notes()
{
- lru.next = lru.prev = NULL;
+ lru.next = lru.prev = nullptr;
result = ACCESS_DENIED;
date = 0;
- def = NULL;
+ def = nullptr;
}
ExternalACLEntry::~ExternalACLEntry()
debugs(17, 3, "because " << reason << "; " << serverConn);
assert(Comm::IsConnOpen(serverConn));
comm_remove_close_handler(serverConn->fd, closeHandler);
- closeHandler = NULL;
+ closeHandler = nullptr;
fwdPconnPool->noteUses(fd_table[serverConn->fd].pconn.uses);
serverConn->close();
}
entry(e),
request(r),
al(alp),
- err(NULL),
+ err(nullptr),
clientConn(client),
start_t(squid_curtime),
n_tries(0),
assert(err);
updateAleWithFinalError();
errorAppendEntry(entry, err);
- err = NULL;
+ err = nullptr;
#if USE_OPENSSL
if (request->flags.sslPeek && request->clientConnectionManager.valid()) {
CallJobHere1(17, 4, request->clientConnectionManager, ConnStateData,
entry->unlock("FwdState");
- entry = NULL;
+ entry = nullptr;
cancelStep("~FwdState");
* Intentionally replace the src_addr automatically selected by the checklist code
* we do NOT want the indirect client address to be tested here.
*/
- ACLFilledChecklist ch(Config.accessList.miss, request, NULL);
+ ACLFilledChecklist ch(Config.accessList.miss, request, nullptr);
ch.al = al;
ch.src_addr = request->client_addr;
ch.syncAle(request, nullptr);
FwdState::fwdStart(const Comm::ConnectionPointer &clientConn, StoreEntry *entry, HttpRequest *request)
{
// Hides AccessLogEntry.h from code that does not supply ALE anyway.
- Start(clientConn, entry, request, NULL);
+ Start(clientConn, entry, request, nullptr);
}
/// subtracts time_t values, returning zero if smaller exceeds the larger value
assert(serverConnection() == conn);
assert(Comm::IsConnOpen(conn));
comm_remove_close_handler(conn->fd, closeHandler);
- closeHandler = NULL;
- serverConn = NULL;
+ closeHandler = nullptr;
+ serverConn = nullptr;
destinationReceipt = nullptr;
}
// Optimize: A compliant proxy may retry PUTs, but Squid lacks the [rather
// complicated] code required to protect the PUT request body from being
// nibbled during the first try. Thus, Squid cannot retry some PUTs today.
- if (request->body_pipe != NULL)
+ if (request->body_pipe != nullptr)
return false;
// RFC2616 9.1 Safe and Idempotent Methods
request->hier.stopPeerClock(false);
- if (self != NULL && !err && shutting_down && entry->isEmpty()) {
+ if (self != nullptr && !err && shutting_down && entry->isEmpty()) {
const auto anErr = new ErrorState(ERR_SHUTTING_DOWN, Http::scServiceUnavailable, request, al);
errorAppendEntry(entry, anErr);
}
void
FwdState::doneWithRetries()
{
- if (request && request->body_pipe != NULL)
+ if (request && request->body_pipe != nullptr)
request->body_pipe->expectNoConsumption();
}
return; // anything will do.
}
- ACLFilledChecklist ch(NULL, request, NULL);
- ch.dst_peer_name = conn->getPeer() ? conn->getPeer()->name : NULL;
+ ACLFilledChecklist ch(nullptr, request, nullptr);
+ ch.dst_peer_name = conn->getPeer() ? conn->getPeer()->name : nullptr;
ch.dst_addr = conn->remote;
// TODO use the connection details in ACL.
if (!Ip::Qos::TheConfig.tosToServer)
return 0;
- ACLFilledChecklist ch(NULL, request, NULL);
+ ACLFilledChecklist ch(nullptr, request, nullptr);
ch.dst_peer_name = conn.getPeer() ? conn.getPeer()->name : nullptr;
ch.dst_addr = conn.remote;
return aclMapTOS(Ip::Qos::TheConfig.tosToServer, &ch);
if (!Ip::Qos::TheConfig.nfmarkToServer)
return 0;
- ACLFilledChecklist ch(NULL, request, NULL);
+ ACLFilledChecklist ch(nullptr, request, nullptr);
ch.dst_peer_name = conn.getPeer() ? conn.getPeer()->name : nullptr;
ch.dst_addr = conn.remote;
const auto mc = aclFindNfMarkConfig(Ip::Qos::TheConfig.nfmarkToServer, &ch);
{
const char *item;
const char *p; /* '=' parameter */
- const char *pos = NULL;
+ const char *pos = nullptr;
int ilen;
int nlen;
HttpHdrRangeSpec spec;
if (!spec.parseInit(field, flen))
- return NULL;
+ return nullptr;
return new HttpHdrRangeSpec(spec);
}
if (!r->parseInit(range_spec)) {
delete r;
- r = NULL;
+ r = nullptr;
}
return r;
HttpHdrRange::parseInit(const String * range_spec)
{
const char *item;
- const char *pos = NULL;
+ const char *pos = nullptr;
int ilen;
assert(range_spec);
++ParsedCount;
if (pos != end)
return *pos;
- return NULL;
+ return nullptr;
}
void
if (!sc->parse(&str)) {
delete sc;
- sc = NULL;
+ sc = nullptr;
}
return sc;
HttpHdrSc * sc=this;
const char *item;
const char *p; /* '=' parameter */
- const char *pos = NULL;
- const char *target = NULL; /* ;foo */
- const char *temp = NULL; /* temp buffer */
+ const char *pos = nullptr;
+ const char *target = nullptr; /* ;foo */
+ const char *temp = nullptr; /* temp buffer */
http_hdr_sc_type type;
int ilen, vlen;
int initiallen;
temp = xstrndup (item, initiallen + 1);
if (!((target = strrchr (temp, ';')) && !strchr (target, '"') && *(target + 1) != '\0'))
- target = NULL;
+ target = nullptr;
else
++target;
return &sct;
}
- return NULL;
+ return nullptr;
}
HttpHdrScTarget *
HttpHdrSc::getMergedTarget(const char *ourtarget)
{
HttpHdrScTarget *sctus = findTarget(ourtarget);
- HttpHdrScTarget *sctgeneric = findTarget(NULL);
+ HttpHdrScTarget *sctgeneric = findTarget(nullptr);
/* W3C Edge Architecture Specification 1.0 section 3
*
* XXX: the if statements below will *merge* the no-store and max-age settings.
*/
if (sctgeneric || sctus) {
- HttpHdrScTarget *sctusable = new HttpHdrScTarget(NULL);
+ HttpHdrScTarget *sctusable = new HttpHdrScTarget(nullptr);
if (sctgeneric)
sctusable->mergeWith(sctgeneric);
return sctusable;
}
- return NULL;
+ return nullptr;
}
/* header accounting */
// NP: keep in sync with enum http_hdr_owner_type
static std::array<HttpHeaderStat, hoEnd> HttpHeaderStats = {
- HttpHeaderStat(/*hoNone*/ "all", NULL),
+ HttpHeaderStat(/*hoNone*/ "all", nullptr),
#if USE_HTCP
HttpHeaderStat(/*hoHtcpReply*/ "HTCP reply", &ReplyHeadersMask),
#endif
if (Config.onoff.relaxed_header_parser) {
char *p = (char *) this_line; /* XXX Warning! This destroys original header content and violates specifications somewhat */
- while ((p = (char *)memchr(p, '\r', field_end - p)) != NULL) {
+ while ((p = (char *)memchr(p, '\r', field_end - p)) != nullptr) {
*p = ' ';
++p;
}
return static_cast<HttpHeaderEntry*>(entries[*pos]);
}
- return NULL;
+ return nullptr;
}
/*
/* check mask first */
if (!CBIT_TEST(mask, id))
- return NULL;
+ return nullptr;
/* looks like we must have it, do linear search */
for (auto e : entries) {
/* check mask first */
if (!CBIT_TEST(mask, id))
- return NULL;
+ return nullptr;
for (auto e = entries.rbegin(); e != entries.rend(); ++e) {
if (*e && (*e)->id == id)
HttpHeaderEntry *e;
assert(pos >= HttpHeaderInitPos && pos < static_cast<ssize_t>(entries.size()));
e = static_cast<HttpHeaderEntry*>(entries[pos]);
- entries[pos] = NULL;
+ entries[pos] = nullptr;
/* decrement header length, allow for ": " and crlf */
len -= e->name.length() + 2 + e->value.size() + 2;
assert(len >= 0);
return e->value.termedBuf();
}
- return NULL;
+ return nullptr;
}
/* unusual */
return e->value.termedBuf();
}
- return NULL;
+ return nullptr;
}
HttpHdrCc *
HttpHeader::getCc() const
{
if (!CBIT_TEST(mask, Http::HdrType::CACHE_CONTROL))
- return NULL;
+ return nullptr;
String s;
getList(Http::HdrType::CACHE_CONTROL, &s);
if (!cc->parse(s)) {
delete cc;
- cc = NULL;
+ cc = nullptr;
}
++ HttpHeaderStats[owner].ccParsedCount;
HttpHdrRange *
HttpHeader::getRange() const
{
- HttpHdrRange *r = NULL;
+ HttpHdrRange *r = nullptr;
HttpHeaderEntry *e;
/* some clients will send "Request-Range" _and_ *matching* "Range"
* who knows, some clients might send Request-Range only;
HttpHeader::getSc() const
{
if (!CBIT_TEST(mask, Http::HdrType::SURROGATE_CONTROL))
- return NULL;
+ return nullptr;
String s;
HttpHdrContRange *
HttpHeader::getContRange() const
{
- HttpHdrContRange *cr = NULL;
+ HttpHdrContRange *cr = nullptr;
HttpHeaderEntry *e;
if ((e = findEntry(Http::HdrType::CONTENT_RANGE))) {
ETag
HttpHeader::getETag(Http::HdrType id) const
{
- ETag etag = {NULL, -1};
+ ETag etag = {nullptr, -1};
HttpHeaderEntry *e;
assert(Http::HeaderLookupTable.lookup(id).type == Http::HdrFieldType::ftETag); /* must be of an appropriate type */
/* try as an ETag */
if (etagParseInit(&tot.tag, str)) {
- tot.valid = tot.tag.str != NULL;
+ tot.valid = tot.tag.str != nullptr;
tot.time = -1;
} else {
/* or maybe it is time? */
tot.time = Time::ParseRfc1123(str);
tot.valid = tot.time >= 0;
- tot.tag.str = NULL;
+ tot.tag.str = nullptr;
}
}
/* do we have a valid field name within this field? */
if (!name_len || name_end > field_end)
- return NULL;
+ return nullptr;
if (name_len > 65534) {
/* String must be LESS THAN 64K and it adds a terminating NULL */
// TODO: update this to show proper name_len in Raw markup, but not print all that
debugs(55, 2, "ignoring huge header field (" << Raw("field_start", field_start, 100) << "...)");
- return NULL;
+ return nullptr;
}
/*
if (!name_len) {
debugs(55, 2, "found header with only whitespace for name");
- return NULL;
+ return nullptr;
}
}
if (field_end - value_start > 65534) {
/* String must be LESS THAN 64K and it adds a terminating NULL */
debugs(55, 2, "WARNING: found '" << theName << "' header of " << (field_end - value_start) << " bytes");
- return NULL;
+ return nullptr;
}
/* set field value */
/* tmp variable used to pass stat info to dumpers */
extern const HttpHeaderStat *dump_stat; /* argh! */
-const HttpHeaderStat *dump_stat = NULL;
+const HttpHeaderStat *dump_stat = nullptr;
static void
httpHeaderFieldStatDumper(StoreEntry * sentry, int, double val, double, int count)
"id", "#flds", "count", "%total");
hs->hdrUCountDistr.dump(e, httpHeaderFldsPerHdrDumper);
storeAppendPrintf(e, "\n");
- dump_stat = NULL;
+ dump_stat = nullptr;
}
void
HttpHeader::hasListMember(Http::HdrType id, const char *member, const char separator) const
{
int result = 0;
- const char *pos = NULL;
+ const char *pos = nullptr;
const char *item;
int ilen;
int mlen = strlen(member);
HttpHeader::hasByNameListMember(const char *name, const char *member, const char separator) const
{
int result = 0;
- const char *pos = NULL;
+ const char *pos = nullptr;
const char *item;
int ilen;
int mlen = strlen(member);
bool getByIdIfPresent(Http::HdrType id, String *result) const;
/// returns true iff a [possibly empty] named field is there
/// when returning true, also sets the `value` parameter (if it is not nil)
- bool hasNamed(const SBuf &s, String *value = 0) const;
+ bool hasNamed(const SBuf &s, String *value = nullptr) const;
/// \deprecated use SBuf method instead.
- bool hasNamed(const char *name, unsigned int namelen, String *value = 0) const;
+ bool hasNamed(const char *name, unsigned int namelen, String *value = nullptr) const;
/// searches for the first matching key=value pair within the name-identified field
/// \returns the value of the found pair or an empty string
SBuf getByNameListMember(const char *name, const char *member, const char separator) const;
int has(Http::HdrType id) const;
/// Appends "this cache" information to VIA header field.
/// Takes the initial VIA value from "from" parameter, if provided.
- void addVia(const AnyP::ProtocolVersion &ver, const HttpHeader *from = 0);
+ void addVia(const AnyP::ProtocolVersion &ver, const HttpHeader *from = nullptr);
void putInt(Http::HdrType id, int number);
void putInt64(Http::HdrType id, int64_t number);
void putTime(Http::HdrType id, time_t htime);
{
public:
HttpHeaderStat() :
- label(NULL),
- owner_mask(NULL),
+ label(nullptr),
+ owner_mask(nullptr),
parsedCount(0),
ccParsedCount(0),
scParsedCount(0),
return 1;
}
- ACLFilledChecklist checklist(hm->access_list, request, NULL);
+ ACLFilledChecklist checklist(hm->access_list, request, nullptr);
checklist.al = al;
if (al && al->reply) {
/* aclCheckFast returns true for allow. */
debugs(66, 7, "checklist for mangler is positive. Mangle");
retval = 1;
- } else if (NULL == hm->replacement) {
+ } else if (nullptr == hm->replacement) {
/* It was denied, and we don't have any replacement */
debugs(66, 7, "checklist denied, we have no replacement. Pass");
// XXX: We said "Pass", but the caller will delete on zero retval.
void header_mangler_dump_access(StoreEntry * entry, const char *option,
const headerMangler &m, const char *name)
{
- if (m.access_list != NULL) {
+ if (m.access_list != nullptr) {
storeAppendPrintf(entry, "%s ", option);
dump_acl_access(entry, name, m.access_list);
}
if (all.access_list)
return &all;
- return NULL;
+ return nullptr;
}
void
httpHdrAdd(HttpHeader *heads, HttpRequest *request, const AccessLogEntryPointer &al, HeaderWithAclList &headersAdd)
{
- ACLFilledChecklist checklist(NULL, request, NULL);
+ ACLFilledChecklist checklist(nullptr, request, nullptr);
checklist.al = al;
if (al && al->reply) {
for (HeaderWithAclList::const_iterator hwa = headersAdd.begin(); hwa != headersAdd.end(); ++hwa) {
if (!hwa->aclList || checklist.fastCheck(hwa->aclList).allowed()) {
- const char *fieldValue = NULL;
+ const char *fieldValue = nullptr;
MemBuf mb;
if (hwa->quoted) {
- if (al != NULL) {
+ if (al != nullptr) {
mb.init();
hwa->valueFormat->assemble(mb, al, 0);
fieldValue = mb.content();
class HeaderWithAcl
{
public:
- HeaderWithAcl() : aclList(NULL), valueFormat(NULL), fieldId(Http::HdrType::BAD_HDR), quoted(false) {}
+ HeaderWithAcl() : aclList(nullptr), valueFormat(nullptr), fieldId(Http::HdrType::BAD_HDR), quoted(false) {}
/// HTTP header field name
std::string fieldName;
{
// we used to assert that the pipe is NULL, but now the message only
// points to a pipe that is owned and initiated by another object.
- body_pipe = NULL;
+ body_pipe = nullptr;
body.clear();
hdrCacheClean();
rv->content_type = content_type;
/* rv->content_range */
/* rv->keep_alive */
- rv->sline.set(Http::ProtocolVersion(), Http::scNotModified, NULL);
+ rv->sline.set(Http::ProtocolVersion(), Http::scNotModified, nullptr);
for (t = 0; ImsEntries[t] != Http::HdrType::OTHER; ++t) {
if ((e = header.findEntry(ImsEntries[t])))
HttpReply::redirect(Http::StatusCode status, const char *loc)
{
HttpHeader *hdr;
- sline.set(Http::ProtocolVersion(), status, NULL);
+ sline.set(Http::ProtocolVersion(), status, nullptr);
hdr = &header;
hdr->putStr(Http::HdrType::SERVER, APP_FULLNAME);
hdr->putTime(Http::HdrType::DATE, squid_curtime);
if (cache_control) {
delete cache_control;
- cache_control = NULL;
+ cache_control = nullptr;
}
if (surrogate_control) {
delete surrogate_control;
- surrogate_control = NULL;
+ surrogate_control = nullptr;
}
if (content_range) {
delete content_range;
- content_range = NULL;
+ content_range = nullptr;
}
}
if (!Config.ReplyBodySize)
return;
- ACLFilledChecklist ch(NULL, &request, NULL);
+ ACLFilledChecklist ch(nullptr, &request, nullptr);
// XXX: cont-cast becomes irrelevant when checklist is HttpReply::Pointer
ch.reply = const_cast<HttpReply *>(this);
HTTPMSGLOCK(ch.reply);
String HttpReply::removeStaleWarningValues(const String &value)
{
String newValue;
- const char *item = 0;
+ const char *item = nullptr;
int len = 0;
- const char *pos = 0;
+ const char *pos = nullptr;
while (strListGetItem(&value, ',', &item, &len, &pos)) {
bool keep = true;
// Does warning-value have warn-date (which contains quoted date)?
method = Http::METHOD_NONE;
url.clear();
#if USE_AUTH
- auth_user_request = NULL;
+ auth_user_request = nullptr;
#endif
flags = RequestFlags();
- range = NULL;
+ range = nullptr;
ims = -1;
imslen = 0;
lastmod = -1;
client_addr.setEmpty();
my_addr.setEmpty();
- body_pipe = NULL;
+ body_pipe = nullptr;
// hier
dnsWait = -1;
error.clear();
- peer_login = NULL; // not allocated/deallocated by this class
- peer_domain = NULL; // not allocated/deallocated by this class
- peer_host = NULL;
+ peer_login = nullptr; // not allocated/deallocated by this class
+ peer_domain = nullptr; // not allocated/deallocated by this class
+ peer_host = nullptr;
vary_headers = SBuf();
myportname = null_string;
tag = null_string;
indirect_client_addr.setEmpty();
#endif /* FOLLOW_X_FORWARDED_FOR */
#if USE_ADAPTATION
- adaptHistory_ = NULL;
+ adaptHistory_ = nullptr;
#endif
#if ICAP_CLIENT
- icapHistory_ = NULL;
+ icapHistory_ = nullptr;
#endif
rangeOffsetLimit = -2; //a value of -2 means not checked yet
forcedBodyContinuation = false;
{
// we used to assert that the pipe is NULL, but now the request only
// points to a pipe that is owned and initiated by another object.
- body_pipe = NULL;
+ body_pipe = nullptr;
#if USE_AUTH
- auth_user_request = NULL;
+ auth_user_request = nullptr;
#endif
vary_headers.clear();
url.clear();
if (cache_control) {
delete cache_control;
- cache_control = NULL;
+ cache_control = nullptr;
}
if (range) {
delete range;
- range = NULL;
+ range = nullptr;
}
myportname.clean();
etag.clean();
#if USE_ADAPTATION
- adaptHistory_ = NULL;
+ adaptHistory_ = nullptr;
#endif
#if ICAP_CLIENT
- icapHistory_ = NULL;
+ icapHistory_ = nullptr;
#endif
}
bool
HttpRequest::bodyNibbled() const
{
- return body_pipe != NULL && body_pipe->consumedSize() > 0;
+ return body_pipe != nullptr && body_pipe->consumedSize() > 0;
}
void
rangeOffsetLimit = 0; // default value for rangeOffsetLimit
- ACLFilledChecklist ch(NULL, this, NULL);
+ ACLFilledChecklist ch(nullptr, this, nullptr);
ch.src_addr = client_addr;
ch.my_addr = my_addr;
if (range) {
debugs(73, 3, static_cast<void*>(range) << " for " << reason);
delete range;
- range = NULL;
+ range = nullptr;
}
// Some callers also reset isRanged but it may not be safe for all callers:
// isRanged is used to determine whether a weak ETag comparison is allowed,
{
if (clientConnectionManager.valid() && clientConnectionManager->pinning.pinned)
return clientConnectionManager.get();
- return NULL;
+ return nullptr;
}
const SBuf
// Note: We must use preprocessor instead of C ifs because if dlopen()
// is seen by the static linker, the linker will complain.
-LoadableModule::LoadableModule(const String &aName): theName(aName), theHandle(0)
+LoadableModule::LoadableModule(const String &aName): theName(aName), theHandle(nullptr)
{
// Initialise preloaded symbol lookup table.
LTDL_SET_PRELOADED_SYMBOLS();
bool
LoadableModule::loaded() const
{
- return theHandle != 0;
+ return theHandle != nullptr;
}
void
if (!closeModule())
throw TexcHere(errorMsg());
- theHandle = 0;
+ theHandle = nullptr;
}
void *
MemBuf::init(mb_size_t szInit, mb_size_t szMax)
{
assert(szInit > 0 && szMax > 0);
- buf = NULL;
+ buf = nullptr;
size = 0;
max_capacity = szMax;
capacity = 0;
assert(!stolen); /* not frozen */
memFreeBuf(capacity, buf);
- buf = NULL;
+ buf = nullptr;
size = capacity = max_capacity = 0;
}
}
public:
MemBuf():
- buf(NULL),
+ buf(nullptr),
size(0),
max_capacity(0),
capacity(0),
#endif
-RemovalPolicy * mem_policy = NULL;
+RemovalPolicy * mem_policy = nullptr;
size_t
MemObject::inUseCount()
if (!shutting_down) { // Store::Root() is FATALly missing during shutdown
assert(xitTable.index < 0);
assert(memCache.index < 0);
- assert(swapout.sio == NULL);
+ assert(swapout.sio == nullptr);
}
data_hdr.freeContent();
void
MemObject::reset()
{
- assert(swapout.sio == NULL);
+ assert(swapout.sio == nullptr);
data_hdr.freeContent();
inmem_lo = 0;
/* Should we check for clients? */
* yet.
*/
- if (swapout.sio.getRaw() == NULL)
+ if (swapout.sio.getRaw() == nullptr)
return 0;
int64_t nwritten = swapout.sio->offset();
/* MemStore */
-MemStore::MemStore(): map(NULL), lastWritingSlice(-1)
+MemStore::MemStore(): map(nullptr), lastWritingSlice(-1)
{
}
MemStore::get(const cache_key *key)
{
if (!map)
- return NULL;
+ return nullptr;
sfileno index;
const Ipc::StoreMapAnchor *const slot = map->openForReading(key, index);
if (!slot)
- return NULL;
+ return nullptr;
// create a brand new store entry and initialize it with stored info
StoreEntry *e = new StoreEntry();
debugs(20, 3, "failed for " << *e);
map->freeEntry(index); // do not let others into the same trap
destroyStoreEntry(static_cast<hash_link *>(e));
- return NULL;
+ return nullptr;
}
void
return slotId;
}
assert(waitingFor.slot == &slot && waitingFor.page == &page);
- waitingFor.slot = NULL;
- waitingFor.page = NULL;
+ waitingFor.slot = nullptr;
+ waitingFor.page = nullptr;
debugs(47, 3, "cannot get a slice; entries: " << map->entryCount());
throw TexcHere("ran out of mem-cache slots");
} else {
*waitingFor.slot = slotId;
*waitingFor.page = pageId;
- waitingFor.slot = NULL;
- waitingFor.page = NULL;
+ waitingFor.slot = nullptr;
+ waitingFor.page = nullptr;
pageId = Ipc::Mem::PageId();
}
}
{
public:
/* RegisteredRunner API */
- MemStoreRr(): spaceOwner(NULL), mapOwner(NULL), extrasOwner(NULL) {}
+ MemStoreRr(): spaceOwner(nullptr), mapOwner(nullptr), extrasOwner(nullptr) {}
virtual void finalizeConfig();
virtual void claimMemoryNeeds();
virtual void useConfig();
class SlotAndPage
{
public:
- SlotAndPage(): slot(NULL), page(NULL) {}
+ SlotAndPage(): slot(nullptr), page(nullptr) {}
bool operator !() const { return !slot && !page; }
Ipc::Mem::PageId *slot; ///< local slot variable, waiting to be filled
Ipc::Mem::PageId *page; ///< local page variable, waiting to be filled
{
auto it = std::find_if(pools.begin(), pools.end(),
[&name](const MessageDelayPool::Pointer p) { return p->poolName == name; });
- return it == pools.end() ? 0 : *it;
+ return it == pools.end() ? nullptr : *it;
}
void
MessageDelayPool::MessageDelayPool(const SBuf &name, int64_t bucketSpeed, int64_t bucketSize,
int64_t aggregateSpeed, int64_t aggregateSize, uint16_t initialBucketPercent):
- access(0),
+ access(nullptr),
poolName(name),
individualRestore(bucketSpeed),
individualMaximum(bucketSize),
double
xatof(const char *token)
{
- char *end = NULL;
+ char *end = nullptr;
double ret = strtod(token, &end);
if (ret == 0 && end == token) {
int64_t
xatoll(const char *token, int base, char eov)
{
- char *end = NULL;
+ char *end = nullptr;
int64_t ret = strtoll(token, &end, base);
if (end == token) {
StringToInt(const char *s, int &result, const char **p, int base)
{
if (s) {
- char *ptr = 0;
+ char *ptr = nullptr;
const int h = (int) strtol(s, &ptr, base);
if (ptr != s && ptr) {
StringToInt64(const char *s, int64_t &result, const char **p, int base)
{
if (s) {
- char *ptr = 0;
+ char *ptr = nullptr;
const int64_t h = (int64_t) strtoll(s, &ptr, base);
if (ptr != s && ptr) {
char *tmp;
unsigned short port;
- host = NULL;
+ host = nullptr;
port = 0;
if (*token == '[') {
port = 0;
}
- if (NULL == host)
+ if (nullptr == host)
ipa->setAnyAddr();
else if (ipa->GetHostByName(host)) /* do not use ipcache. Accept either FQDN or IPA. */
(void) 0;
if (!validPeer()) {
debugs(48, 3, "peer gone");
- if (params.conn != NULL)
+ if (params.conn != nullptr)
params.conn->close();
return;
}
return;
}
- Must(params.conn != NULL);
+ Must(params.conn != nullptr);
// Handle TLS peers.
if (peer->secure.encryptTransport) {
{
Must(validPeer());
Must(Comm::IsConnOpen(conn));
- peer->standby.pool->push(conn, NULL /* domain */);
+ peer->standby.pool->push(conn, nullptr /* domain */);
// push() will trigger a checkpoint()
}
if (!validPeer()) {
debugs(48, 3, "peer gone");
- if (answer.conn != NULL)
+ if (answer.conn != nullptr)
answer.conn->close();
return;
}
// rule. Otherwise, creates an implicit/default refresh_pattern rule.
explicit RefreshPattern(RegexPointer aRegex):
min(0), pct(0.20), max(REFRESH_DEFAULT_MAX),
- next(NULL),
+ next(nullptr),
max_stale(0),
regex_(std::move(aRegex))
{
{
public:
- RemovalPolicySettings() : type(NULL), args(NULL) {};
+ RemovalPolicySettings() : type(nullptr), args(nullptr) {};
char *type;
wordlist *args;
{
public:
- RemovalPolicyNode() : data(NULL) {}
+ RemovalPolicyNode() : data(nullptr) {}
void *data;
};
void allocBuffer(size_type sz);
void setBuffer(char *buf, size_type sz);
- bool defined() const {return buf_!=NULL;}
+ bool defined() const {return buf_!=nullptr;}
bool undefined() const {return !defined();}
/* never reference these directly! */
}
StatHist::StatHist(const StatHist &src) :
- bins(NULL),
+ bins(nullptr),
capacity_(src.capacity_),
min_(src.min_),
max_(src.max_),
val_in(src.val_in),
val_out(src.val_out)
{
- if (src.bins!=NULL) {
+ if (src.bins!=nullptr) {
bins = static_cast<bins_type *>(xcalloc(src.capacity_, sizeof(bins_type)));
memcpy(bins,src.bins,capacity_*sizeof(*bins));
}
void
StatHist::count(double v)
{
- if (bins==NULL) //do not count before initialization or after destruction
+ if (bins==nullptr) //do not count before initialization or after destruction
return;
const unsigned int bin = findBin(v);
++bins[bin];
Must(min_ == B.min_);
Must(max_ == B.max_);
- if (B.bins == NULL) { // B was not yet initializted
+ if (B.bins == nullptr) { // B was not yet initializted
return *this;
}
- if (bins == NULL) { // this histogram was not yet initialized
+ if (bins == nullptr) { // this histogram was not yet initialized
*this = B;
return *this;
}
public:
struct Callback {
- Callback ():callback_handler(NULL), callback_data(NULL) {}
+ Callback ():callback_handler(nullptr), callback_data(nullptr) {}
Callback (STCB *, void *);
#include "squid.h"
#include "StoreFileSystem.h"
-std::vector<StoreFileSystem*> *StoreFileSystem::_FileSystems = NULL;
+std::vector<StoreFileSystem*> *StoreFileSystem::_FileSystems = nullptr;
void
StoreFileSystem::RegisterAllFsWithCacheManager(void)
{
public:
- StoreIOBuffer():length(0), offset (0), data (NULL) {flags.error = 0;}
+ StoreIOBuffer():length(0), offset (0), data (nullptr) {flags.error = 0;}
StoreIOBuffer(size_t aLength, int64_t anOffset, char *someData) :
length (aLength), offset (anOffset), data (someData) {
StoreIOState::StoreIOState(StoreIOState::STFNCB *cbFile, StoreIOState::STIOCB *cbIo, void *data) :
swap_dirn(-1),
swap_filen(-1),
- e(NULL),
+ e(nullptr),
mode(O_BINARY),
offset_(0),
file_callback(cbFile),
callback(cbIo),
callback_data(cbdataReference(data))
{
- read.callback = NULL;
- read.callback_data = NULL;
+ read.callback = nullptr;
+ read.callback_data = nullptr;
flags.closing = false;
}
StoreMeta::Factory (char type, size_t len, void const *value)
{
if (!validType(type))
- return NULL;
+ return nullptr;
StoreMeta *result;
default:
debugs(20, DBG_CRITICAL, "ERROR: Attempt to create unknown concrete StoreMeta");
- return NULL;
+ return nullptr;
}
if (!result->validLength(len)) {
delete result;
- return NULL;
+ return nullptr;
}
result->length = len;
{
StoreMeta *node;
- while ((node = *head) != NULL) {
+ while ((node = *head) != nullptr) {
*head = node->next;
xfree(node->value);
delete node;
StoreMeta **
StoreMeta::Add(StoreMeta **tail, StoreMeta *aNode)
{
- assert (*tail == NULL);
+ assert (*tail == nullptr);
*tail = aNode;
return &aNode->next; /* return new tail pointer */
}
position(1 + sizeof(int)),
type('\0'),
length(0),
- tail(NULL)
+ tail(nullptr)
{
- assert(aBuffer != NULL);
+ assert(aBuffer != nullptr);
}
void
StoreMeta *
StoreMetaUnpacker::createStoreMeta ()
{
- tlv *TLV = NULL;
+ tlv *TLV = nullptr;
tail = &TLV;
- assert(hdr_len != NULL);
+ assert(hdr_len != nullptr);
checkBuffer();
int
strListIsMember(const String * list, const SBuf &m, char del)
{
- const char *pos = NULL;
+ const char *pos = nullptr;
const char *item;
int ilen = 0;
buf_[len] = '\0';
}
-String::String(String const &old) : size_(0), len_(0), buf_(NULL)
+String::String(String const &old) : size_(0), len_(0), buf_(nullptr)
{
if (old.size() > 0)
allocAndFill(old.rawBuf(), old.size());
size_ = 0;
- buf_ = NULL;
+ buf_ = nullptr;
}
String::~String()
setBuffer(old.buf_, old.size_);
len_ = old.len_;
old.size_ = 0;
- old.buf_ = NULL;
+ old.buf_ = nullptr;
old.len_ = 0;
}
int
stringHasWhitespace(const char *s)
{
- return strpbrk(s, w_space) != NULL;
+ return strpbrk(s, w_space) != nullptr;
}
/* TODO: move onto String */
char *
strwordtok(char *buf, char **t)
{
- unsigned char *word = NULL;
+ unsigned char *word = nullptr;
unsigned char *p = (unsigned char *) buf;
unsigned char *d;
unsigned char ch;
String::pos(char const *aString) const
{
if (undefined())
- return NULL;
+ return nullptr;
return strstr(termedBuf(), aString);
}
String::pos(char const ch) const
{
if (undefined())
- return NULL;
+ return nullptr;
return strchr(termedBuf(), ch);
}
String::rpos(char const ch) const
{
if (undefined())
- return NULL;
+ return nullptr;
return strrchr(termedBuf(), (ch));
}
{
const char *c;
c=pos(ch);
- if (c==NULL)
+ if (c==nullptr)
return npos;
return c-rawBuf();
}
{
const char *c;
c=pos(aString);
- if (c==NULL)
+ if (c==nullptr)
return npos;
return c-rawBuf();
}
{
const char *c;
c=rpos(ch);
- if (c==NULL)
+ if (c==nullptr)
return npos;
return c-rawBuf();
}
/// shared memory segment path to use for Transients map
static const SBuf MapLabel("transients_map");
-Transients::Transients(): map(NULL), locals(NULL)
+Transients::Transients(): map(nullptr), locals(nullptr)
{
}
map->cleaner = this;
map->disableHitValidation(); // Transients lacks slices to validate
- locals = new Locals(entryLimit, 0);
+ locals = new Locals(entryLimit, nullptr);
}
void
Transients::get(const cache_key *key)
{
if (!map)
- return NULL;
+ return nullptr;
sfileno index;
const Ipc::StoreMapAnchor *anchor = map->openForReading(key, index);
if (!anchor)
- return NULL;
+ return nullptr;
// If we already have a local entry, the store_table should have found it.
// Since it did not, the local entry key must have changed from public to
Transients::findCollapsed(const sfileno index)
{
if (!map)
- return NULL;
+ return nullptr;
if (StoreEntry *oldE = locals->at(index)) {
debugs(20, 5, "found " << *oldE << " at " << index << " in " << MapLabel);
}
debugs(20, 3, "no entry at " << index << " in " << MapLabel);
- return NULL;
+ return nullptr;
}
void
#include <algorithm>
#include <map>
-const char *AclMatchedName = NULL;
+const char *AclMatchedName = nullptr;
namespace Acl {
debugs(28, 9, "ACL::FindByName found no match");
- return NULL;
+ return nullptr;
}
ACL::ACL() :
ACL::ParseAclLine(ConfigParser &parser, ACL ** head)
{
/* we're already using strtok() to grok the line */
- char *t = NULL;
- ACL *A = NULL;
+ char *t = nullptr;
+ ACL *A = nullptr;
LOCAL_ARRAY(char, aclname, ACL_NAME_SZ);
int new_acl = 0;
/* snarf the ACL name */
- if ((t = ConfigParser::NextToken()) == NULL) {
+ if ((t = ConfigParser::NextToken()) == nullptr) {
debugs(28, DBG_CRITICAL, "ERROR: aclParseAclLine: missing ACL name.");
parser.destruct();
return;
/* snarf the ACL type */
const char *theType;
- if ((theType = ConfigParser::NextToken()) == NULL) {
+ if ((theType = ConfigParser::NextToken()) == nullptr) {
debugs(28, DBG_CRITICAL, "ERROR: aclParseAclLine: missing ACL type.");
parser.destruct();
return;
// Is this ACL going to work?
if (strcmp(theType, "myip") == 0) {
AnyP::PortCfgPointer p = HttpPortList;
- while (p != NULL) {
+ while (p != nullptr) {
// Bug 3239: not reliable when there is interception traffic coming
if (p->flags.natIntercept)
debugs(28, DBG_CRITICAL, "WARNING: 'myip' ACL is not reliable for interception proxies. Please use 'myportname' instead.");
theType = "localip";
} else if (strcmp(theType, "myport") == 0) {
AnyP::PortCfgPointer p = HttpPortList;
- while (p != NULL) {
+ while (p != nullptr) {
// Bug 3239: not reliable when there is interception traffic coming
// Bug 3239: myport - not reliable (yet) when there is interception traffic coming
if (p->flags.natIntercept)
theType = "client_connection_mark";
}
- if ((A = FindByName(aclname)) == NULL) {
+ if ((A = FindByName(aclname)) == nullptr) {
debugs(28, 3, "aclParseAclLine: Creating ACL '" << aclname << "'");
A = Acl::Make(theType);
A->context(aclname, config_input_line);
/*
* Clear AclMatchedName from our temporary hack
*/
- AclMatchedName = NULL; /* ugly */
+ AclMatchedName = nullptr; /* ugly */
if (!new_acl)
return;
{
debugs(28, 3, "freeing ACL " << name);
safe_free(cfgline);
- AclMatchedName = NULL; // in case it was pointing to our name
+ AclMatchedName = nullptr; // in case it was pointing to our name
}
void
CBDATA_CLASS(AclSizeLimit);
public:
- AclSizeLimit() : next(NULL), aclList(NULL), size(0) {}
+ AclSizeLimit() : next(nullptr), aclList(nullptr), size(0) {}
~AclSizeLimit();
AclSizeLimit *next;
ACLAdaptationServiceStrategy::match (ACLData<MatchType> * &data, ACLFilledChecklist *checklist)
{
HttpRequest::Pointer request = checklist->request;
- if (request == NULL)
+ if (request == nullptr)
return 0;
Adaptation::History::Pointer ah = request->adaptHistory();
- if (ah == NULL)
+ if (ah == nullptr)
return 0;
Adaptation::History::AdaptationServices::iterator it;
while (char *t = ConfigParser::strtokFile()) {
if (
#if USE_ECAP
- Adaptation::Ecap::TheConfig.findServiceConfig(t) == NULL &&
+ Adaptation::Ecap::TheConfig.findServiceConfig(t) == nullptr &&
#endif
#if ICAP_CLIENT
- Adaptation::Icap::TheConfig.findServiceConfig(t) == NULL &&
+ Adaptation::Icap::TheConfig.findServiceConfig(t) == nullptr &&
#endif
- Adaptation::FindGroup(t) == NULL) {
+ Adaptation::FindGroup(t) == nullptr) {
debugs(28, DBG_CRITICAL, "FATAL: Adaptation service/group " << t << " in adaptation_service acl is not defined");
self_destruct();
}
CBDATA_CLASS(Address);
public:
- Address() : next(NULL), aclList(NULL) {}
+ Address() : next(nullptr), aclList(nullptr) {}
~Address();
Acl::Address *next;
void
Acl::AllOf::parse()
{
- Acl::InnerNode *whole = NULL;
- ACL *oldNode = empty() ? NULL : nodes.front();
+ Acl::InnerNode *whole = nullptr;
+ ACL *oldNode = empty() ? nullptr : nodes.front();
// optimization: this logic reduces subtree hight (number of tree levels)
if (Acl::OrNode *oldWhole = dynamic_cast<Acl::OrNode*>(oldNode)) {
if (sscanf(t, "%[0-9a-fA-F:]", buf) != 1) {
debugs(28, DBG_CRITICAL, "ERROR: aclParseArpData: Bad ethernet address: '" << t << "'");
delete q;
- return NULL;
+ return nullptr;
}
if (!q->decode(buf)) {
debugs(28, DBG_CRITICAL, "" << cfg_filename << " line " << config_lineno << ": " << config_input_line);
debugs(28, DBG_CRITICAL, "ERROR: aclParseArpData: Ignoring invalid ARP acl entry: cannot parse '" << buf << "'");
delete q;
- return NULL;
+ return nullptr;
}
return q;
struct squid_radix_node *rn;
as_info *e;
m_ADDR m_addr;
- CbDataList<int> *a = NULL;
- CbDataList<int> *b = NULL;
+ CbDataList<int> *a = nullptr;
+ CbDataList<int> *b = nullptr;
debugs(53, 3, "asnMatchIp: Called for " << addr );
- if (AS_tree_head == NULL)
+ if (AS_tree_head == nullptr)
return 0;
if (addr.isNoAddr())
rn = squid_rn_match(&m_addr, AS_tree_head);
- if (rn == NULL) {
+ if (rn == nullptr) {
debugs(53, 3, "asnMatchIp: Address not in as db.");
return 0;
}
{
squid_rn_walktree(AS_tree_head, destroyRadixNode, AS_tree_head);
- destroyRadixNode((struct squid_radix_node *) 0, (void *) AS_tree_head);
+ destroyRadixNode((struct squid_radix_node *) nullptr, (void *) AS_tree_head);
}
static void
asnAddNet(char *as_string, int as_number)
{
struct squid_radix_node *rn;
- CbDataList<int> **Tail = NULL;
- CbDataList<int> *q = NULL;
- as_info *asinfo = NULL;
+ CbDataList<int> **Tail = nullptr;
+ CbDataList<int> *q = nullptr;
+ as_info *asinfo = nullptr;
Ip::Address mask;
Ip::Address addr;
t = strchr(as_string, '/');
- if (t == NULL) {
+ if (t == nullptr) {
debugs(53, 3, "asnAddNet: failed, invalid response from whois server.");
return 0;
}
// generate Netbits Format Mask
mask.setNoAddr();
- mask.applyMask(bitl, (t!=NULL?AF_INET:AF_INET6) );
+ mask.applyMask(bitl, (t!=nullptr?AF_INET:AF_INET6) );
debugs(53, 3, "asnAddNet: called for " << addr << "/" << mask );
rn = squid_rn_lookup(&e->e_addr, &e->e_mask, AS_tree_head);
- if (rn != NULL) {
+ if (rn != nullptr) {
asinfo = ((rtentry_t *) rn)->e_info;
if (asinfo->as_number->find(as_number)) {
asinfo->as_number = q;
squid_rn_addroute(&e->e_addr, &e->e_mask, AS_tree_head, e->e_nodes);
rn = squid_rn_match(&e->e_addr, AS_tree_head);
- assert(rn != NULL);
+ assert(rn != nullptr);
e->e_info = asinfo;
}
- if (rn == 0) { /* assert might expand to nothing */
+ if (rn == nullptr) { /* assert might expand to nothing */
xfree(asinfo);
delete q;
xfree(e);
rtentry_t *e = (rtentry_t *) rn;
rn = squid_rn_delete(rn->rn_key, rn->rn_mask, rnh);
- if (rn == 0)
+ if (rn == nullptr)
debugs(53, 3, "destroyRadixNode: internal screwup");
destroyRadixNodeInfo(e->e_info);
static void
destroyRadixNodeInfo(as_info * e_info)
{
- CbDataList<int> *prev = NULL;
+ CbDataList<int> *prev = nullptr;
CbDataList<int> *data = e_info->as_number;
while (data) {
CbDataList<int> *ldata = data;
- while (ldata != NULL) {
+ while (ldata != nullptr) {
SBuf s;
s.Printf("%d", ldata->element);
sl.push_back(s);
bool
ACLASN::empty () const
{
- return data == NULL;
+ return data == nullptr;
}
void
{
CbDataList<int> **curlist = &data;
CbDataList<int> **Tail;
- CbDataList<int> *q = NULL;
- char *t = NULL;
+ CbDataList<int> *q = nullptr;
+ char *t = nullptr;
for (Tail = curlist; *Tail; Tail = &((*Tail)->next));
while ((t = ConfigParser::strtokFile())) {
#include "debug/Stream.h"
#include "wordlist.h"
-ACLCertificateData::ACLCertificateData(Ssl::GETX509ATTRIBUTE *sslStrategy, const char *attrs, bool optionalAttr) : validAttributesStr(attrs), attributeIsOptional(optionalAttr), attribute (NULL), values (), sslAttributeCall (sslStrategy)
+ACLCertificateData::ACLCertificateData(Ssl::GETX509ATTRIBUTE *sslStrategy, const char *attrs, bool optionalAttr) : validAttributesStr(attrs), attributeIsOptional(optionalAttr), attribute (nullptr), values (), sslAttributeCall (sslStrategy)
{
if (attrs) {
size_t current = 0;
char const *value = sslAttributeCall(cert, attribute);
debugs(28, 6, (attribute ? attribute : "value") << "=" << value);
- if (value == NULL)
+ if (value == nullptr)
return 0;
return values.match(value);
occupied_ = true;
asyncLoopDepth_ = 0;
- AclMatchedName = NULL;
+ AclMatchedName = nullptr;
finished_ = false;
}
debugs(28, 3, "ACLChecklist::checkCallback: " << this << " answer=" << answer);
callback_ = callback;
- callback = NULL;
+ callback = nullptr;
if (cbdataReferenceValidDone(callback_data, &cbdata_))
callback_(answer, cbdata_);
}
ACLChecklist::ACLChecklist() :
- accessList (NULL),
- callback (NULL),
- callback_data (NULL),
+ accessList (nullptr),
+ callback (nullptr),
+ callback_data (nullptr),
asyncCaller_(false),
occupied_(false),
finished_(false),
/** The ACL List should NEVER be NULL when calling this method.
* Always caller should check for NULL and handle appropriate to its needs first.
* We cannot select a sensible default for all callers here. */
- if (accessList == NULL) {
+ if (accessList == nullptr) {
debugs(28, DBG_CRITICAL, "SECURITY ERROR: ACL " << this << " checked with nothing to match against!!");
checkCallback(ACCESS_DUNNO);
return;
debugs(28, 5, "aclCheckFast: list: " << accessList);
const Acl::Tree *acl = cbdataReference(accessList);
- if (acl != NULL && cbdataReferenceValid(acl)) {
+ if (acl != nullptr && cbdataReferenceValid(acl)) {
matchAndFinish(); // calls markFinished() on success
// if finished (on a match or in exceptional cases), stop
class Breadcrumb
{
public:
- Breadcrumb(): parent(NULL) {}
+ Breadcrumb(): parent(nullptr) {}
Breadcrumb(const Acl::InnerNode *aParent, Acl::Nodes::const_iterator aPos): parent(aParent), position(aPos) {}
bool operator ==(const Breadcrumb &b) const { return parent == b.parent && (!parent || position == b.position); }
bool operator !=(const Breadcrumb &b) const { return !this->operator ==(b); }
- void clear() { parent = NULL; }
+ void clear() { parent = nullptr; }
const Acl::InnerNode *parent; ///< intermediate node in the ACL tree
Acl::Nodes::const_iterator position; ///< child position inside parent
};
int
ACLDestinationDomainStrategy::match (ACLData<MatchType> * &data, ACLFilledChecklist *checklist)
{
- assert(checklist != NULL && checklist->request != NULL);
+ assert(checklist != nullptr && checklist->request != nullptr);
if (data->match(checklist->request->url.host())) {
return 1;
bool
ACLDomainData::match(char const *host)
{
- if (host == NULL)
+ if (host == nullptr)
return 0;
debugs(28, 3, "aclMatchDomainList: checking '" << host << "'");
debugs(28, 3, "aclMatchDomainList: '" << host << "' " << (result ? "found" : "NOT found"));
- return (result != NULL);
+ return (result != nullptr);
}
struct AclDomainDataDumpVisitor {
if (sscanf(t, "%[0-9a-fA-F:]", buf) != 1) {
debugs(28, DBG_CRITICAL, "ERROR: aclParseEuiData: Bad EUI-64 address: '" << t << "'");
delete q;
- return NULL;
+ return nullptr;
}
if (!q->decode(buf)) {
debugs(28, DBG_CRITICAL, "" << cfg_filename << " line " << config_lineno << ": " << config_input_line);
debugs(28, DBG_CRITICAL, "ERROR: aclParseEuiData: Ignoring invalid EUI-64 acl entry: cannot parse '" << buf << "'");
delete q;
- return NULL;
+ return nullptr;
}
return q;
CBDATA_CLASS_INIT(ACLFilledChecklist);
ACLFilledChecklist::ACLFilledChecklist() :
- dst_rdns(NULL),
- request (NULL),
- reply (NULL),
+ dst_rdns(nullptr),
+ request (nullptr),
+ reply (nullptr),
#if USE_AUTH
- auth_user_request (NULL),
+ auth_user_request (nullptr),
#endif
#if SQUID_SNMP
- snmp_community(NULL),
+ snmp_community(nullptr),
#endif
#if USE_OPENSSL
- sslErrors(NULL),
+ sslErrors(nullptr),
#endif
requestErrorType(ERR_MAX),
- conn_(NULL),
+ conn_(nullptr),
fd_(-1),
destinationDomainChecked_(false),
sourceDomainChecked_(false)
* checkCallback() will delete the list (i.e., self).
*/
ACLFilledChecklist::ACLFilledChecklist(const acl_access *A, HttpRequest *http_request, const char *ident):
- dst_rdns(NULL),
- request(NULL),
- reply(NULL),
+ dst_rdns(nullptr),
+ request(nullptr),
+ reply(nullptr),
#if USE_AUTH
- auth_user_request(NULL),
+ auth_user_request(nullptr),
#endif
#if SQUID_SNMP
- snmp_community(NULL),
+ snmp_community(nullptr),
#endif
#if USE_OPENSSL
- sslErrors(NULL),
+ sslErrors(nullptr),
#endif
requestErrorType(ERR_MAX),
- conn_(NULL),
+ conn_(nullptr),
fd_(-1),
destinationDomainChecked_(false),
sourceDomainChecked_(false)
void markSourceDomainChecked();
// ACLChecklist API
- virtual bool hasRequest() const { return request != NULL; }
- virtual bool hasReply() const { return reply != NULL; }
- virtual bool hasAle() const { return al != NULL; }
+ virtual bool hasRequest() const { return request != nullptr; }
+ virtual bool hasReply() const { return reply != nullptr; }
+ virtual bool hasAle() const { return al != nullptr; }
virtual void syncAle(HttpRequest *adaptedRequest, const char *logUri) const;
virtual void verifyAle() const;
return ERR_NONE;
}
- AclDenyInfoList *A = NULL;
+ AclDenyInfoList *A = nullptr;
debugs(28, 8, "got called for " << name);
void
aclParseDenyInfoLine(AclDenyInfoList ** head)
{
- char *t = NULL;
+ char *t = nullptr;
AclDenyInfoList *B;
AclDenyInfoList **T;
/* first expect a page name */
- if ((t = ConfigParser::NextToken()) == NULL) {
+ if ((t = ConfigParser::NextToken()) == nullptr) {
debugs(28, DBG_CRITICAL, "aclParseDenyInfoLine: " << cfg_filename << " line " << config_lineno << ": " << config_input_line);
debugs(28, DBG_CRITICAL, "ERROR: aclParseDenyInfoLine: missing 'error page' parameter.");
return;
void
aclDestroyAcls(ACL ** head)
{
- *head = NULL; // Config.aclList
+ *head = nullptr; // Config.aclList
if (AclSet *acls = RegisteredAcls) {
debugs(28, 8, "deleting all " << acls->size() << " ACLs");
while (!acls->empty()) {
debugs(28, 8, "aclDestroyAclList: invoked");
assert(list);
delete *list;
- *list = NULL;
+ *list = nullptr;
}
void
if (*list)
debugs(28, 3, "destroying: " << *list << ' ' << (*list)->name);
delete *list;
- *list = NULL;
+ *list = nullptr;
}
/* maex@space.net (06.09.1996)
void
aclDestroyDenyInfoList(AclDenyInfoList ** list)
{
- AclDenyInfoList *a = NULL;
- AclDenyInfoList *a_next = NULL;
+ AclDenyInfoList *a = nullptr;
+ AclDenyInfoList *a_next = nullptr;
debugs(28, 8, "aclDestroyDenyInfoList: invoked");
delete a;
}
- *list = NULL;
+ *list = nullptr;
}
void
ACLHierCodeData::parse()
{
- char *t = NULL;
+ char *t = nullptr;
while ((t = ConfigParser::strtokFile())) {
for (hier_code iter = HIER_NONE; iter <= HIER_MAX; ++iter) {
bool
ACLHTTPHeaderData::match(HttpHeader* hdr)
{
- if (hdr == NULL)
+ if (hdr == nullptr)
return false;
debugs(28, 3, "aclHeaderData::match: checking '" << hdrName << "'");
return ret;
}
-ACLHTTPStatus::ACLHTTPStatus (char const *theClass) : data(NULL), class_ (theClass)
+ACLHTTPStatus::ACLHTTPStatus (char const *theClass) : data(nullptr), class_ (theClass)
{}
ACLHTTPStatus::~ACLHTTPStatus()
const acl_httpstatus_data * const * result = (*dataptr)->find(&X, aclHTTPStatusCompare);
debugs(28, 3, "aclMatchHTTPStatus: '" << status << "' " << (result ? "found" : "NOT found"));
- return (result != NULL);
+ return (result != nullptr);
}
static int
void
Acl::InnerNode::add(ACL *node)
{
- assert(node != NULL);
+ assert(node != nullptr);
nodes.push_back(node);
aclRegister(node);
}
debugs(28, 3, "looking for ACL " << t);
ACL *a = ACL::FindByName(t);
- if (a == NULL) {
+ if (a == nullptr) {
debugs(28, DBG_CRITICAL, "ERROR: ACL not found: " << t);
self_destruct();
return count; // not reached
acl_ip_data::toStr(char *buf, int len) const
{
char *b1 = buf;
- char *b2 = NULL;
- char *b3 = NULL;
+ char *b2 = nullptr;
+ char *b3 = nullptr;
int rlen = 0;
addr1.toStr(b1, len - rlen );
LOCAL_ARRAY(char, addr1, 256);
LOCAL_ARRAY(char, addr2, 256);
LOCAL_ARRAY(char, mask, 256);
- acl_ip_data *r = NULL;
- acl_ip_data **Q = NULL;
+ acl_ip_data *r = nullptr;
+ acl_ip_data **Q = nullptr;
Ip::Address temp;
char c;
unsigned int changed;
*/
debugs(28, 5, "aclIpParseIpData: Lookup Host/IP " << addr1);
- struct addrinfo *hp = NULL, *x = NULL;
+ struct addrinfo *hp = nullptr, *x = nullptr;
struct addrinfo hints;
- Ip::Address *prev_addr = NULL;
+ Ip::Address *prev_addr = nullptr;
memset(&hints, 0, sizeof(struct addrinfo));
- int errcode = getaddrinfo(addr1,NULL,&hints,&hp);
- if (hp == NULL) {
+ int errcode = getaddrinfo(addr1,nullptr,&hints,&hp);
+ if (hp == nullptr) {
delete q;
if (strcmp(addr1, "::1") == 0) {
debugs(28, DBG_IMPORTANT, "aclIpParseIpData: IPv6 has not been enabled in host DNS resolver.");
" : (" << errcode << ") " << gai_strerror(errcode) );
self_destruct();
}
- return NULL;
+ return nullptr;
}
Q = &q;
- for (x = hp; x != NULL;) {
- if ((r = *Q) == NULL)
+ for (x = hp; x != nullptr;) {
+ if ((r = *Q) == nullptr)
r = *Q = new acl_ip_data;
/* getaddrinfo given a host has a nasty tendency to return duplicate addr's */
if ( prev_addr && r->addr1 == *prev_addr) {
debugs(28, 3, "aclIpParseIpData: Duplicate host/IP: '" << r->addr1 << "' dropped.");
delete r;
- *Q = NULL;
+ *Q = nullptr;
continue;
} else
prev_addr = &r->addr1;
freeaddrinfo(hp);
- if (*Q != NULL) {
+ if (*Q != nullptr) {
debugs(28, DBG_CRITICAL, "ERROR: aclIpParseIpData: Bad host/IP: '" << t << "'");
self_destruct();
- return NULL;
+ return nullptr;
}
return q;
if ( iptype == AF_INET6 && !Ip::EnableIpv6) {
debugs(28, DBG_IMPORTANT, "aclIpParseIpData: IPv6 has not been enabled.");
delete q;
- return NULL;
+ return nullptr;
}
/* Decode addr1 */
debugs(28, DBG_CRITICAL, "ERROR: aclIpParseIpData: unknown first address in '" << t << "'");
delete q;
self_destruct();
- return NULL;
+ return nullptr;
}
/* Decode addr2 */
debugs(28, DBG_CRITICAL, "ERROR: aclIpParseIpData: unknown second address in '" << t << "'");
delete q;
self_destruct();
- return NULL;
+ return nullptr;
}
/* Decode mask (NULL or empty means a exact host mask) */
debugs(28, DBG_CRITICAL, "ERROR: aclParseIpData: unknown netmask '" << mask << "' in '" << t << "'");
delete q;
self_destruct();
- return NULL;
+ return nullptr;
}
changed = 0;
void
ACLIP::parse()
{
- if (data == NULL)
+ if (data == nullptr)
data = new IPSplay();
while (char *t = ConfigParser::strtokFile()) {
acl_ip_data *q = acl_ip_data::FactoryParse(t);
- while (q != NULL) {
+ while (q != nullptr) {
/* pop each result off the list and add it to the data tree individually */
acl_ip_data *next_node = q->next;
- q->next = NULL;
+ q->next = nullptr;
if (!data->find(q,acl_ip_data::NetworkCompare))
data->insert(q, acl_ip_data::NetworkCompare);
q = next_node;
const acl_ip_data * const * result = data->find(&ClientAddress, aclIpAddrNetworkCompare);
debugs(28, 3, "aclIpMatchIp: '" << clientip << "' " << (result ? "found" : "NOT found"));
- return (result != NULL);
+ return (result != nullptr);
}
-acl_ip_data::acl_ip_data() :addr1(), addr2(), mask(), next (NULL) {}
+acl_ip_data::acl_ip_data() :addr1(), addr2(), mask(), next (nullptr) {}
acl_ip_data::acl_ip_data(Ip::Address const &anAddress1, Ip::Address const &anAddress2, Ip::Address const &aMask, acl_ip_data *aNext) : addr1(anAddress1), addr2(anAddress2), mask(aMask), next(aNext) {}
void *operator new(size_t);
void operator delete(void *);
- ACLIP() : data(NULL) {}
+ ACLIP() : data(nullptr) {}
~ACLIP();
typedef Splay<acl_ip_data *> IPSplay;
int
ACLMyPortNameStrategy::match(ACLData<MatchType> * &data, ACLFilledChecklist *checklist)
{
- if (checklist->conn() != NULL && checklist->conn()->port != NULL)
+ if (checklist->conn() != nullptr && checklist->conn()->port != nullptr)
return data->match(checklist->conn()->port->name);
- if (checklist->request != NULL)
+ if (checklist->request != nullptr)
return data->match(checklist->request->myportname.termedBuf());
return 0;
}
return 1;
#if USE_ADAPTATION
const Adaptation::History::Pointer ah = request->adaptLogHistory();
- if (ah != NULL && ah->metaHeaders != NULL && matchNotes(data, ah->metaHeaders.getRaw()))
+ if (ah != nullptr && ah->metaHeaders != nullptr && matchNotes(data, ah->metaHeaders.getRaw()))
return 1;
#endif
}
ACLNoteData::parse()
{
char* t = ConfigParser::strtokFile();
- assert (t != NULL);
+ assert (t != nullptr);
name = t;
values->parse();
}
debugs(28, 5, "aclParseRandomData: " << t);
// seed random generator ...
- srand(time(NULL));
+ srand(time(nullptr));
if (sscanf(t, "%[0-9]:%[0-9]", bufa, bufb) == 2) {
int a = xatoi(bufa);
{
char const *theHeader = checklist->reply->header.getStr(header);
- if (NULL == theHeader)
+ if (nullptr == theHeader)
return 0;
return data->match(theHeader);
{
char const *theHeader = checklist->reply->header.getStr(Http::HdrType::CONTENT_TYPE);
- if (NULL == theHeader)
+ if (nullptr == theHeader)
theHeader = "";
return data->match(theHeader);
{
char const *theHeader = checklist->request->header.getStr(header);
- if (NULL == theHeader)
+ if (nullptr == theHeader)
return 0;
return data->match(theHeader);
{
char const *theHeader = checklist->request->header.getStr(Http::HdrType::CONTENT_TYPE);
- if (NULL == theHeader)
+ if (nullptr == theHeader)
theHeader = "";
return data->match(theHeader);
bool
ACLServerNameData::match(const char *host)
{
- if (host == NULL)
+ if (host == nullptr)
return 0;
debugs(28, 3, "checking '" << host << "'");
debugs(28, 3, "'" << host << "' " << (result ? "found" : "NOT found"));
- return (result != NULL);
+ return (result != nullptr);
}
int
ACLServerNameStrategy::match (ACLData<MatchType> * &data, ACLFilledChecklist *checklist)
{
- assert(checklist != NULL && checklist->request != NULL);
+ assert(checklist != nullptr && checklist->request != nullptr);
const char *serverName = nullptr;
SBuf clientSniKeeper; // because c_str() is not constant
int
ACLSourceDomainStrategy::match (ACLData<MatchType> * &data, ACLFilledChecklist *checklist)
{
- const char *fqdn = NULL;
+ const char *fqdn = nullptr;
fqdn = fqdncache_gethostbyaddr(checklist->src_addr, FQDN_LOOKUP_IF_MISS);
if (fqdn) {
int
ACLTagStrategy::match (ACLData<MatchType> * &data, ACLFilledChecklist *checklist)
{
- if (checklist->request != NULL)
+ if (checklist->request != nullptr)
return data->match (checklist->request->tag.termedBuf());
return 0;
}
#define ACL_ALLWEEK 0x7F
#define ACL_WEEKDAYS 0x3E
-ACLTimeData::ACLTimeData () : weekbits (0), start (0), stop (0), next (NULL) {}
+ACLTimeData::ACLTimeData () : weekbits (0), start (0), stop (0), next (nullptr) {}
ACLTimeData::~ACLTimeData()
{
SBufList sl;
const ACLTimeData *t = this;
- while (t != NULL) {
+ while (t != nullptr) {
SBuf s;
s.Printf("%c%c%c%c%c%c%c %02d:%02d-%02d:%02d",
t->weekbits & ACL_SUNDAY ? 'S' : '-',
long parsed_weekbits = 0;
for (Tail = &next; *Tail; Tail = &((*Tail)->next));
- ACLTimeData *q = NULL;
+ ACLTimeData *q = nullptr;
int h1, m1, h2, m2;
{
debugs(28, 7, "user is " << user << ", case_insensitive is " << flags.case_insensitive);
- if (user == NULL || strcmp(user, "-") == 0)
+ if (user == nullptr || strcmp(user, "-") == 0)
return 0;
if (flags.required) {
debugs(28, 2, "parsing user list");
flags.case_insensitive = bool(CaseInsensitive_);
- char *t = NULL;
+ char *t = nullptr;
if ((t = ConfigParser::strtokFile())) {
SBuf s(t);
debugs(28, 5, "first token is " << s);
/* Globals */
-static const char *basedn = NULL;
-static const char *searchfilter = NULL;
-static const char *userbasedn = NULL;
-static const char *userdnattr = NULL;
-static const char *usersearchfilter = NULL;
-static const char *binddn = NULL;
-static const char *bindpasswd = NULL;
+static const char *basedn = nullptr;
+static const char *searchfilter = nullptr;
+static const char *userbasedn = nullptr;
+static const char *userdnattr = nullptr;
+static const char *usersearchfilter = nullptr;
+static const char *binddn = nullptr;
+static const char *bindpasswd = nullptr;
static int searchscope = LDAP_SCOPE_SUBTREE;
static int persistent = 0;
static int noreferrals = 0;
main(int argc, char **argv)
{
char buf[HELPER_INPUT_BUFFER];
- char *user, *group, *extension_dn = NULL;
- char *ldapServer = NULL;
- LDAP *ld = NULL;
+ char *user, *group, *extension_dn = nullptr;
+ char *ldapServer = nullptr;
+ LDAP *ld = nullptr;
int tryagain = 0, rc;
int port = LDAP_PORT;
int use_extension_dn = 0;
int strip_nt_domain = 0;
int strip_kerberos_realm = 0;
- setbuf(stdout, NULL);
+ setbuf(stdout, nullptr);
while (argc > 1 && argv[1][0] == '-') {
const char *value = "";
}
#endif
- while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL) {
+ while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != nullptr) {
int found = 0;
if (!strchr(buf, '\n')) {
/* too large message received.. skip and deny */
fprintf(stderr, "%s: ERROR: Input Too large: %s\n", argv[0], buf);
while (fgets(buf, sizeof(buf), stdin)) {
fprintf(stderr, "%s: ERROR: Input Too large..: %s\n", argv[0], buf);
- if (strchr(buf, '\n') != NULL)
+ if (strchr(buf, '\n') != nullptr)
break;
}
SEND_BH(HLP_MSG("Input too large"));
}
if (strip_kerberos_realm) {
char *u = strchr(user, '@');
- if (u != NULL) {
+ if (u != nullptr) {
*u = '\0';
}
}
if (use_extension_dn) {
- extension_dn = strtok(NULL, " \n");
+ extension_dn = strtok(nullptr, " \n");
if (!extension_dn) {
debug("%s: Invalid request: Extension DN configured, but none sent.\n", argv[0]);
SEND_BH(HLP_MSG("Invalid Request. Extension DN required"));
rfc1738_unescape(extension_dn);
}
const char *broken = nullptr;
- while (!found && user && (group = strtok(NULL, " \n")) != NULL) {
+ while (!found && user && (group = strtok(nullptr, " \n")) != nullptr) {
rfc1738_unescape(group);
recover:
- if (ld == NULL) {
+ if (ld == nullptr) {
#if HAS_URI_SUPPORT
- if (strstr(ldapServer, "://") != NULL) {
+ if (strstr(ldapServer, "://") != nullptr) {
rc = ldap_initialize(&ld, ldapServer);
if (rc != LDAP_SUCCESS) {
broken = HLP_MSG("Unable to connect to LDAP server");
}
} else
#endif
- if ((ld = ldap_init(ldapServer, port)) == NULL) {
+ if ((ld = ldap_init(ldapServer, port)) == nullptr) {
broken = HLP_MSG("Unable to connect to LDAP server");
fprintf(stderr, "ERROR: %s:%s port:%d\n", broken, ldapServer, port);
break;
broken = HLP_MSG("Could not set LDAP_OPT_PROTOCOL_VERSION");
fprintf(stderr, "ERROR: %s %d\n", broken, version);
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
break;
}
if (use_tls) {
if (version != LDAP_VERSION3) {
fprintf(stderr, "FATAL: TLS requires LDAP version 3\n");
exit(EXIT_FAILURE);
- } else if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS) {
+ } else if (ldap_start_tls_s(ld, nullptr, nullptr) != LDAP_SUCCESS) {
broken = HLP_MSG("Could not Activate TLS connection");
fprintf(stderr, "ERROR: %s\n", broken);
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
break;
}
#else
broken = HLP_MSG("could not bind");
fprintf(stderr, PROGRAM_NAME ": WARNING: %s to binddn '%s'\n", broken, ldap_err2string(rc));
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
break;
}
}
if (tryagain) {
tryagain = 0;
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
goto recover;
}
broken = HLP_MSG("LDAP search error");
SEND_ERR("");
}
- if (ld != NULL) {
+ if (ld != nullptr) {
if (!persistent || (squid_ldap_errno(ld) != LDAP_SUCCESS && squid_ldap_errno(ld) != LDAP_INVALID_CREDENTIALS)) {
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
} else {
tryagain = 1;
}
searchLDAPGroup(LDAP * ld, const char *group, const char *member, const char *extension_dn)
{
std::string filter;
- LDAPMessage *res = NULL;
+ LDAPMessage *res = nullptr;
int rc;
- char *searchattr[] = {(char *) LDAP_NO_ATTRS, NULL};
+ char *searchattr[] = {(char *) LDAP_NO_ATTRS, nullptr};
const std::string searchbase = build_searchbase(extension_dn, basedn);
if (!build_filter(filter, searchfilter, member, group)) {
const char *current_userdn = userbasedn ? userbasedn : basedn;
if (usersearchfilter) {
- LDAPMessage *res = NULL;
+ LDAPMessage *res = nullptr;
LDAPMessage *entry;
int rc;
char *userdn;
- char *searchattr[] = {(char *) LDAP_NO_ATTRS, NULL};
+ char *searchattr[] = {(char *) LDAP_NO_ATTRS, nullptr};
const std::string searchbase = build_searchbase(extension_dn, current_userdn);
std::string filter(usersearchfilter);
const std::string escaped_login = ldap_escape_value(login);
readSecret(const char *filename)
{
char buf[BUFSIZ];
- char *e = 0;
+ char *e = nullptr;
FILE *f;
if (!(f = fopen(filename, "r"))) {
extern "C" void SigTrap(int);
/* Global variables */
-const char *search_attrib[] = { "cn", "uid", "networkAddress", "groupMembership", NULL };
+const char *search_attrib[] = { "cn", "uid", "networkAddress", "groupMembership", nullptr };
static edui_conf_t edui_conf;
static edui_ldap_t edui_ldap;
time_t edui_now;
else
xstrncpy(prog, edui_conf.program, sizeof(prog));
- if (msg == NULL) {
+ if (msg == nullptr) {
/* FAIL */
debug("local_printfx() FAILURE, no data.\n");
return;
static int
StringSplit(char *In_Str, char chr, char *Out_Str, size_t Out_Sz)
{
- if ((In_Str == NULL) || (Out_Str == NULL))
+ if ((In_Str == nullptr) || (Out_Str == nullptr))
return (-1);
size_t In_Len = strlen(In_Str) + 1;
BinarySplit(void *In_Obj, size_t In_Sz, char chr, void *Out_Obj, size_t Out_Sz)
{
// check tolerances
- if ((In_Obj == NULL) || (Out_Obj == NULL))
+ if ((In_Obj == nullptr) || (Out_Obj == nullptr))
return (-1);
char *in = static_cast<char*>(In_Obj);
static void
InitLDAP(edui_ldap_t *l)
{
- if (l == NULL) return;
+ if (l == nullptr) return;
- l->lp = NULL;
- if (l->lm != NULL)
+ l->lp = nullptr;
+ if (l->lm != nullptr)
ldap_msgfree(l->lm);
- if (l->val != NULL)
+ if (l->val != nullptr)
ldap_value_free_len(l->val);
- l->lm = NULL;
- l->val = NULL;
+ l->lm = nullptr;
+ l->val = nullptr;
*(l->basedn) = '\0';
*(l->host) = '\0';
*(l->dn) = '\0';
static int
OpenLDAP(edui_ldap_t *l, char *h, unsigned int p)
{
- if ((l == NULL) || (h == NULL)) return LDAP_ERR_NULL;
+ if ((l == nullptr) || (h == nullptr)) return LDAP_ERR_NULL;
if (!(l->status & LDAP_INIT_S)) return LDAP_ERR_INIT; /* Not initialized, or might be in use */
if (l->status & LDAP_OPEN_S) return LDAP_ERR_OPEN; /* Already open */
if (l->status & LDAP_BIND_S) return LDAP_ERR_BIND; /* Already bound */
#else
l->lp = ldap_open(l->host, l->port);
#endif
- if (l->lp == NULL) {
+ if (l->lp == nullptr) {
l->err = LDAP_CONNECT_ERROR;
return LDAP_ERR_CONNECT; /* Unable to connect */
} else {
CloseLDAP(edui_ldap_t *l)
{
int s;
- if (l == NULL) return LDAP_ERR_NULL;
- if (l->lp == NULL) return LDAP_ERR_NULL;
+ if (l == nullptr) return LDAP_ERR_NULL;
+ if (l->lp == nullptr) return LDAP_ERR_NULL;
if (!(l->status & LDAP_INIT_S)) return LDAP_ERR_INIT; /* Connection not initialized */
if (!(l->status & LDAP_OPEN_S)) return LDAP_ERR_OPEN; /* Connection not open */
- if (l->lm != NULL) {
+ if (l->lm != nullptr) {
ldap_msgfree(l->lm);
- l->lm = NULL;
+ l->lm = nullptr;
}
- if (l->val != NULL) {
+ if (l->val != nullptr) {
ldap_value_free_len(l->val);
- l->val = NULL;
+ l->val = nullptr;
}
/* okay, so it's open, close it - No need to check other criteria */
SetVerLDAP(edui_ldap_t *l, int v)
{
int x;
- if (l == NULL) return LDAP_ERR_NULL;
+ if (l == nullptr) return LDAP_ERR_NULL;
if ((v > 3) || (v < 1)) return LDAP_ERR_PARAM;
- if (l->lp == NULL) return LDAP_ERR_POINTER;
+ if (l->lp == nullptr) return LDAP_ERR_POINTER;
if (!(l->status & LDAP_INIT_S)) return LDAP_ERR_INIT; /* Not initialized */
if (!(l->status & LDAP_OPEN_S)) return LDAP_ERR_OPEN; /* Not open */
if (l->status & LDAP_BIND_S) return LDAP_ERR_BIND; /* Already bound */
BindLDAP(edui_ldap_t *l, char *dn, char *pw, unsigned int t)
{
int s;
- if (l == NULL) return LDAP_ERR_NULL;
+ if (l == nullptr) return LDAP_ERR_NULL;
if (!(l->status & LDAP_INIT_S)) return LDAP_ERR_INIT; /* Not initialized */
if (!(l->status & LDAP_OPEN_S)) return LDAP_ERR_OPEN; /* Not open */
if (l->status & LDAP_BIND_S) return LDAP_ERR_BIND; /* Already bound */
- if (l->lp == NULL) return LDAP_ERR_POINTER; /* Error */
+ if (l->lp == nullptr) return LDAP_ERR_POINTER; /* Error */
/* Copy details - dn and pw CAN be NULL for anonymous and/or TLS */
- if (dn != NULL) {
+ if (dn != nullptr) {
if (strlen(dn) >= sizeof(l->dn))
return LDAP_ERR_OOB; /* DN too large */
- if ((l->basedn[0] != '\0') && (strstr(dn, l->basedn) == NULL)) {
+ if ((l->basedn[0] != '\0') && (strstr(dn, l->basedn) == nullptr)) {
/* We got a basedn, but it's not part of dn */
const int x = snprintf(l->dn, sizeof(l->dn)-1, "%s,%s", dn, l->basedn);
if (x < 0 || static_cast<size_t>(x) >= sizeof(l->dn))
} else
xstrncpy(l->dn, dn, sizeof(l->dn));
}
- if (pw != NULL)
+ if (pw != nullptr)
xstrncpy(l->passwd, pw, sizeof(l->passwd));
/* Type */
/* Bind */
#if defined(LDAP_AUTH_TLS) && defined(NETSCAPE_SSL) && HAVE_LDAP_START_TLS_S
if (l->type == LDAP_AUTH_TLS)
- s = ldap_start_tls_s(l->lp, NULL, NULL);
+ s = ldap_start_tls_s(l->lp, nullptr, nullptr);
else
#endif
s = ldap_bind_s(l->lp, l->dn, l->passwd, l->type);
ConvertIP(edui_ldap_t *l, char *ip)
{
void *y, *z;
- if (l == NULL) return LDAP_ERR_NULL;
- if (ip == NULL) return LDAP_ERR_PARAM;
+ if (l == nullptr) return LDAP_ERR_NULL;
+ if (ip == nullptr) return LDAP_ERR_PARAM;
if (!(l->status & LDAP_INIT_S)) return LDAP_ERR_INIT; /* Not initialized */
if (!(l->status & LDAP_OPEN_S)) return LDAP_ERR_OPEN; /* Not open */
if (!(l->status & LDAP_BIND_S)) return LDAP_ERR_BIND; /* Not bound */
y = memchr((void *)ip, ':', EDUI_MAXLEN);
z = memchr((void *)ip, '.', EDUI_MAXLEN);
- if ((y != NULL) && (z != NULL)) {
- y = NULL;
- z = NULL;
+ if ((y != nullptr) && (z != nullptr)) {
+ y = nullptr;
+ z = nullptr;
return LDAP_ERR_INVALID;
}
- if ((y != NULL) && (edui_conf.mode & EDUI_MODE_IPV4)) {
+ if ((y != nullptr) && (edui_conf.mode & EDUI_MODE_IPV4)) {
/* IPv4 Mode forced */
return LDAP_ERR_INVALID;
- } else if (y != NULL) {
+ } else if (y != nullptr) {
/* Set IPv6 mode */
if (l->status & LDAP_IPV4_S)
l->status &= ~(LDAP_IPV4_S);
if (!(l->status & LDAP_IPV6_S))
l->status |= (LDAP_IPV6_S);
- y = NULL;
+ y = nullptr;
}
- if ((z != NULL) && (edui_conf.mode & EDUI_MODE_IPV6)) {
+ if ((z != nullptr) && (edui_conf.mode & EDUI_MODE_IPV6)) {
/* IPv6 Mode forced */
return LDAP_ERR_INVALID;
- } else if (z != NULL) {
+ } else if (z != nullptr) {
/* Set IPv4 mode */
if (l->status & LDAP_IPV6_S)
l->status &= ~(LDAP_IPV6_S);
if (!(l->status & LDAP_IPV4_S))
l->status |= (LDAP_IPV4_S);
- z = NULL;
+ z = nullptr;
}
size_t s = LDAP_ERR_INVALID;
static int
ResetLDAP(edui_ldap_t *l)
{
- if (l == NULL) return LDAP_ERR_NULL;
+ if (l == nullptr) return LDAP_ERR_NULL;
if (!(l->status & LDAP_INIT_S)) return LDAP_ERR_INIT; /* Not initialized */
if (!(l->status & LDAP_OPEN_S)) return LDAP_ERR_OPEN; /* Not open */
if (!(l->status & LDAP_BIND_S)) return LDAP_ERR_BIND; /* Not bound */
l->status &= ~(LDAP_IPV4_S);
if (l->status & LDAP_IPV6_S)
l->status &= ~(LDAP_IPV6_S);
- if (l->lm != NULL) {
+ if (l->lm != nullptr) {
ldap_msgfree(l->lm);
- l->lm = NULL;
+ l->lm = nullptr;
}
- if (l->val != NULL) {
+ if (l->val != nullptr) {
ldap_value_free_len(l->val);
- l->val = NULL;
+ l->val = nullptr;
}
memset(l->search_ip, '\0', sizeof(l->search_ip));
*(l->search_filter) = '\0';
size_t i, j, s;
int swi;
char bufa[EDUI_MAXLEN], bufb[EDUI_MAXLEN], bufc[EDUI_MAXLEN], bufd[EDUI_MAXLEN], bufg[EDUI_MAXLEN];
- if (l == NULL) return LDAP_ERR_NULL;
+ if (l == nullptr) return LDAP_ERR_NULL;
if (!(l->status & LDAP_INIT_S)) return LDAP_ERR_INIT; /* Not initialized */
if (!(l->status & LDAP_OPEN_S)) return LDAP_ERR_OPEN; /* Not open */
if (!(l->status & LDAP_BIND_S)) return LDAP_ERR_BIND; /* Not Bound */
++swi;
}
}
- if (group == NULL) {
+ if (group == nullptr) {
/* No groupMembership= to add, yay! */
/* networkAddress */
if (l->status & LDAP_IPV4_S) {
} else {
/* Needs groupMembership= to add... */
/* groupMembership -- NOTE: Squid *MUST* provide "cn=" from squid.conf */
- if ((l->basedn[0] != '\0') && (strstr(group, l->basedn) == NULL)) {
+ if ((l->basedn[0] != '\0') && (strstr(group, l->basedn) == nullptr)) {
const int ln = snprintf(bufg, sizeof(bufg), ",%s", l->basedn);
if (ln < 0 || static_cast<size_t>(ln) >= sizeof(bufd))
return LDAP_ERR_OOB;
{
int s;
char ft[EDUI_MAXLEN];
- if (l == NULL) return LDAP_ERR_NULL;
- if ((scope < 0) || (filter == NULL)) return LDAP_ERR_PARAM; /* If attrs is NULL, then all attrs will return */
- if (l->lp == NULL) return LDAP_ERR_POINTER;
+ if (l == nullptr) return LDAP_ERR_NULL;
+ if ((scope < 0) || (filter == nullptr)) return LDAP_ERR_PARAM; /* If attrs is NULL, then all attrs will return */
+ if (l->lp == nullptr) return LDAP_ERR_POINTER;
if (!(l->status & LDAP_INIT_S)) return LDAP_ERR_INIT; /* Not initialized */
if (!(l->status & LDAP_OPEN_S)) return LDAP_ERR_OPEN; /* Not open */
if (!(l->status & LDAP_BIND_S)) return LDAP_ERR_BIND; /* Not bound */
if (l->status & LDAP_SEARCH_S) return LDAP_ERR_SEARCHED; /* Already searching */
if (l->basedn[0] == '\0') return LDAP_ERR_DATA; /* We require a basedn */
- if (l->lm != NULL)
+ if (l->lm != nullptr)
ldap_msgfree(l->lm); /* Make sure l->lm is empty */
xstrncpy(ft, filter, sizeof(ft));
char bufa[EDUI_MAXLEN];
char bufb[EDUI_MAXLEN];
LDAPMessage *ent;
- if (l == NULL) return LDAP_ERR_NULL;
- if (l->lp == NULL) return LDAP_ERR_POINTER;
+ if (l == nullptr) return LDAP_ERR_NULL;
+ if (l->lp == nullptr) return LDAP_ERR_POINTER;
if (!(l->status & LDAP_INIT_S)) return LDAP_ERR_INIT; /* Not initialized */
if (!(l->status & LDAP_OPEN_S)) return LDAP_ERR_OPEN; /* Not open */
if (!(l->status & LDAP_BIND_S)) return LDAP_ERR_BIND; /* Not bound */
debug("l->num_ent: %d\n", l->num_ent);
return LDAP_ERR_DATA; /* No entries found */
}
- if (l->val != NULL)
+ if (l->val != nullptr)
ldap_value_free_len(l->val); /* Clear data before populating */
l->num_val = 0;
if (l->status & LDAP_VAL_S)
xstrncpy(edui_conf.attrib, "cn", sizeof(edui_conf.attrib)); /* Make sure edui_conf.attrib is set */
/* Sift through entries */
- struct berval **ber = NULL;
- for (ent = ldap_first_entry(l->lp, l->lm); ent != NULL; ent = ldap_next_entry(l->lp, ent)) {
+ struct berval **ber = nullptr;
+ for (ent = ldap_first_entry(l->lp, l->lm); ent != nullptr; ent = ldap_next_entry(l->lp, ent)) {
l->val = ldap_get_values_len(l->lp, ent, "networkAddress");
ber = ldap_get_values_len(l->lp, ent, edui_conf.attrib); /* edui_conf.attrib is the <userid> mapping */
- if (l->val != NULL) {
+ if (l->val != nullptr) {
x = ldap_count_values_len(l->val); /* We got x values ... */
l->num_val = x;
if (x > 0) {
/* Using bv_len of min() breaks the result by 2 chars */
}
ldap_value_free_len(l->val);
- l->val = NULL;
+ l->val = nullptr;
ldap_value_free_len(ber);
- ber = NULL;
+ ber = nullptr;
l->num_val = 0;
l->err = LDAP_SUCCESS;
l->status &= ~(LDAP_SEARCH_S);
/* Using bv_len of min() breaks the result by 2 chars */
}
ldap_value_free_len(l->val);
- l->val = NULL;
+ l->val = nullptr;
ldap_value_free_len(ber);
- ber = NULL;
+ ber = nullptr;
l->num_val = 0;
l->err = LDAP_SUCCESS;
l->status &= ~(LDAP_SEARCH_S);
/* Using bv_len of min() breaks the result by 2 chars */
}
ldap_value_free_len(l->val);
- l->val = NULL;
+ l->val = nullptr;
ldap_value_free_len(ber);
- ber = NULL;
+ ber = nullptr;
l->num_val = 0;
l->err = LDAP_SUCCESS;
l->status &= ~(LDAP_SEARCH_S);
/* Others are unsupported */
// }
}
- if (ber != NULL) {
+ if (ber != nullptr) {
ldap_value_free_len(ber);
- ber = NULL;
+ ber = nullptr;
}
}
ldap_value_free_len(l->val);
- l->val = NULL;
+ l->val = nullptr;
}
- if (ber != NULL) {
+ if (ber != nullptr) {
ldap_value_free_len(ber);
- ber = NULL;
+ ber = nullptr;
}
/* Attr not found, continue */
}
/* No entries found using given attr */
- if (l->val != NULL) {
+ if (l->val != nullptr) {
ldap_value_free_len(l->val);
- l->val = NULL;
+ l->val = nullptr;
}
- if (l->lm != NULL) {
+ if (l->lm != nullptr) {
ldap_msgfree(l->lm);
- l->lm = NULL;
+ l->lm = nullptr;
}
l->num_ent = 0;
l->num_val = 0;
static int
MainSafe(int argc, char **argv)
{
- char bufa[EDUI_MAXLEN], bufb[EDUI_MAXLEN], *p = NULL;
+ char bufa[EDUI_MAXLEN], bufb[EDUI_MAXLEN], *p = nullptr;
char bufc[EDUI_MAXLEN];
char sfmod[EDUI_MAXLEN];
int x;
break;
case 'v':
++i; /* Set LDAP version */
- if (argv[i] != NULL) {
+ if (argv[i] != nullptr) {
edui_conf.ver = atoi(argv[i]);
if (edui_conf.ver < 1)
edui_conf.ver = 1;
break;
case 't':
++i; /* Set Persistent timeout */
- if (argv[i] != NULL) {
+ if (argv[i] != nullptr) {
edui_conf.persist_timeout = atoi(argv[i]);
if (edui_conf.persist_timeout < 0)
edui_conf.persist_timeout = 0;
break;
case 'b':
++i; /* Set Base DN */
- if (argv[i] != NULL)
+ if (argv[i] != nullptr)
xstrncpy(edui_conf.basedn, argv[i], sizeof(edui_conf.basedn));
else {
local_printfx("No parameters given for 'b'.\n");
break;
case 'H':
++i; /* Set Hostname */
- if (argv[i] != NULL)
+ if (argv[i] != nullptr)
xstrncpy(edui_conf.host, argv[i], sizeof(edui_conf.host));
else {
local_printfx("No parameters given for 'H'.\n");
break;
case 'p':
++i; /* Set port */
- if (argv[i] != NULL)
+ if (argv[i] != nullptr)
edui_conf.port = atoi(argv[i]);
else {
local_printfx("No parameters given for 'p'.\n");
break;
case 'D':
++i; /* Set Bind DN */
- if (argv[i] != NULL)
+ if (argv[i] != nullptr)
xstrncpy(edui_conf.dn, argv[i], sizeof(edui_conf.dn));
else {
local_printfx("No parameters given for 'D'.\n");
break;
case 'W':
++i; /* Set Bind PWD */
- if (argv[i] != NULL)
+ if (argv[i] != nullptr)
xstrncpy(edui_conf.passwd, argv[i], sizeof(edui_conf.passwd));
else {
local_printfx("No parameters given for 'W'.\n");
break;
case 'F':
++i; /* Set Search Filter */
- if (argv[i] != NULL)
+ if (argv[i] != nullptr)
xstrncpy(edui_conf.search_filter, argv[i], sizeof(edui_conf.search_filter));
else {
local_printfx("No parameters given for 'F'.\n");
break;
case 's':
++i; /* Set Scope Level */
- if (argv[i] != NULL) {
+ if (argv[i] != nullptr) {
if (!strncmp(argv[i], "base", 4))
edui_conf.scope = 0;
else if (!strncmp(argv[i], "one", 4))
break;
case 'u':
++i; /* Set Search Attribute */
- if (argv[i] != NULL) {
+ if (argv[i] != nullptr) {
xstrncpy(edui_conf.attrib, argv[i], sizeof(edui_conf.attrib));
} else {
local_printfx("No parameters given for 'u'.\n");
/* Trap the following signals */
sigemptyset(&sv.sa_mask);
sv.sa_handler = SigTrap;
- sigaction(SIGTERM, &sv, NULL);
+ sigaction(SIGTERM, &sv, nullptr);
sv.sa_handler = SigTrap;
- sigaction(SIGHUP, &sv, NULL);
+ sigaction(SIGHUP, &sv, nullptr);
sv.sa_handler = SigTrap;
- sigaction(SIGABRT, &sv, NULL);
+ sigaction(SIGABRT, &sv, nullptr);
sv.sa_handler = SigTrap;
- sigaction(SIGINT, &sv, NULL);
+ sigaction(SIGINT, &sv, nullptr);
sv.sa_handler = SigTrap;
- sigaction(SIGSEGV, &sv, NULL);
+ sigaction(SIGSEGV, &sv, nullptr);
DisplayConf();
/* Done with arguments */
time(&edui_now);
t = edui_now;
/* Main loop -- Waits for stdin input before action */
- while (fgets(bufa, sizeof(bufa), stdin) != NULL) {
+ while (fgets(bufa, sizeof(bufa), stdin) != nullptr) {
if (edui_conf.mode & EDUI_MODE_KILL)
break;
time(&edui_now);
* BINARY DEBUGGING */
/* Check for CRLF */
p = strchr(bufa, '\n');
- if (p != NULL)
+ if (p != nullptr)
*p = '\0';
p = strchr(bufa, '\r');
- if (p != NULL)
+ if (p != nullptr)
*p = '\0';
p = strchr(bufa, ' ');
/* No space given, but group string is required --> ERR */
- if ((edui_conf.mode & EDUI_MODE_GROUP) && (p == NULL)) {
+ if ((edui_conf.mode & EDUI_MODE_GROUP) && (p == nullptr)) {
debug("while() -> Search group is missing. (required)\n");
local_printfx("BH message=\"(Search Group Required)\"\n");
continue;
}
edui_ldap.err = -1;
/* If we got a group string, split it */
- if (p != NULL) {
+ if (p != nullptr) {
/* Split string */
debug("StringSplit(%s, ' ', %s, %" PRIuSIZE ")\n", bufa, bufb, sizeof(bufb));
i = StringSplit(bufa, ' ', bufb, sizeof(bufb));
} else {
debug("ConvertIP(-, %s) -> Result[%d]: %s\n", bufa, x, edui_ldap.search_ip);
/* Do search */
- x = SearchFilterLDAP(&edui_ldap, NULL);
+ x = SearchFilterLDAP(&edui_ldap, nullptr);
if (x < 0) {
debug("SearchFilterLDAP() -> %s\n", ErrLDAP(x));
local_printfx("BH message=\"(SearchFilterLDAP: %s)\"\n", ErrLDAP(x));
load_dict(FILE * FH) {
struct ip_user_dict *current_entry; /* the structure used to
store data */
- struct ip_user_dict *first_entry = NULL; /* the head of the
+ struct ip_user_dict *first_entry = nullptr; /* the head of the
linked list */
char line[DICT_BUFFER_SIZE]; /* the buffer for the lines read
from the dict file */
current_entry = first_entry;
unsigned int lineCount = 0;
- while (fgets(line, sizeof(line), FH) != NULL) {
+ while (fgets(line, sizeof(line), FH) != nullptr) {
++lineCount;
if (line[0] == '#') {
continue;
}
char *cp; // a char pointer used to parse each line.
- if ((cp = strchr (line, '\n')) != NULL) {
+ if ((cp = strchr (line, '\n')) != nullptr) {
/* chop \n characters */
*cp = '\0';
}
- if (strtok(line, "\t ") != NULL) {
+ if (strtok(line, "\t ") != nullptr) {
// NP: line begins with IP/mask. Skipped to the end of it with this strtok()
/* get the username */
char *username;
- if ((username = strtok(NULL, "\t ")) == NULL) {
+ if ((username = strtok(nullptr, "\t ")) == nullptr) {
debug("Missing username on line %u of dictionary file\n", lineCount);
continue;
}
/* look for a netmask */
- if ((cp = strtok (line, "/")) != NULL) {
+ if ((cp = strtok (line, "/")) != nullptr) {
/* store the ip address in a temporary buffer */
tmpbuf = cp;
- cp = strtok (NULL, "/");
- if (cp != NULL) {
+ cp = strtok (nullptr, "/");
+ if (cp != nullptr) {
/* if we have a slash in the lhs, we have a netmask */
current_entry->netmask = (inet_addr(cp));
current_entry->address =
/* Move the pointer to the first entry of the linked list. */
struct ip_user_dict *current_entry = first_entry;
- while (current_entry->username != NULL) {
+ while (current_entry->username != nullptr) {
debug("user: %s\naddr: %lu\nmask: %lu\n\n",
current_entry->username, current_entry->address,
current_entry->netmask);
netmask) == current_entry->address) {
/* If the username contains an @ we assume it?s a group and
call the corresponding function */
- if ((strchr (current_entry->username, '@')) == NULL) {
+ if ((strchr (current_entry->username, '@')) == nullptr) {
if ((match_user (current_entry->username, username)) == 1)
return 1;
} else {
so we rip it off by incrementing
* the pointer by one */
- if ((g = getgrnam(dict_group)) == NULL) {
+ if ((g = getgrnam(dict_group)) == nullptr) {
debug("Group does not exist '%s'\n", dict_group);
return 0;
} else {
- while (*(g->gr_mem) != NULL) {
+ while (*(g->gr_mem) != nullptr) {
if (strcmp(*((g->gr_mem)++), username) == 0) {
return 1;
}
int
main (int argc, char *argv[])
{
- char *filename = NULL;
+ char *filename = nullptr;
char *program_name = argv[0];
char *cp;
char *username, *address;
struct ip_user_dict *current_entry;
int ch;
- setvbuf (stdout, NULL, _IOLBF, 0);
+ setvbuf (stdout, nullptr, _IOLBF, 0);
while ((ch = getopt(argc, argv, "df:h")) != -1) {
switch (ch) {
case 'f':
exit(EXIT_FAILURE);
}
}
- if (filename == NULL) {
+ if (filename == nullptr) {
fprintf(stderr, "%s: FATAL: No Filename configured.", program_name);
usage(program_name);
exit(EXIT_FAILURE);
current_entry = load_dict(FH);
while (fgets(line, HELPER_INPUT_BUFFER, stdin)) {
- if ((cp = strchr (line, '\n')) == NULL) {
+ if ((cp = strchr (line, '\n')) == nullptr) {
/* too large message received.. skip and deny */
fprintf(stderr, "%s: ERROR: Input Too Large: %s\n", program_name, line);
while (fgets(line, sizeof(line), stdin)) {
fprintf(stderr, "%s: ERROR: Input Too Large..: %s\n", program_name, line);
- if (strchr(line, '\n') != NULL)
+ if (strchr(line, '\n') != nullptr)
break;
}
SEND_BH(HLP_MSG("Input Too Large."));
}
*cp = '\0';
address = strtok(line, " \t");
- username = strtok(NULL, " \t");
+ username = strtok(nullptr, " \t");
if (!address || !username) {
debug("%s: unable to read tokens\n", program_name);
SEND_BH(HLP_MSG("Invalid Input."));
void
init_args(struct main_args *margs)
{
- margs->nlist = NULL;
- margs->glist = NULL;
- margs->llist = NULL;
- margs->ulist = NULL;
- margs->tlist = NULL;
- margs->luser = NULL;
- margs->lpass = NULL;
- margs->lbind = NULL;
- margs->lurl = NULL;
- margs->ssl = NULL;
+ margs->nlist = nullptr;
+ margs->glist = nullptr;
+ margs->llist = nullptr;
+ margs->ulist = nullptr;
+ margs->tlist = nullptr;
+ margs->luser = nullptr;
+ margs->lpass = nullptr;
+ margs->lbind = nullptr;
+ margs->lurl = nullptr;
+ margs->ssl = nullptr;
margs->rc_allow = 0;
margs->AD = 0;
margs->mdepth = 5;
margs->nokerberos = 0;
- margs->ddomain = NULL;
- margs->groups = NULL;
- margs->ndoms = NULL;
- margs->lservs = NULL;
- margs->principal = NULL;
+ margs->ddomain = nullptr;
+ margs->groups = nullptr;
+ margs->ndoms = nullptr;
+ margs->lservs = nullptr;
+ margs->principal = nullptr;
}
void clean_gd(struct gdstruct *gdsp);
void
clean_gd(struct gdstruct *gdsp)
{
- struct gdstruct *p = NULL, *pp = NULL;
+ struct gdstruct *p = nullptr, *pp = nullptr;
p = gdsp;
while (p) {
void
clean_nd(struct ndstruct *ndsp)
{
- struct ndstruct *p = NULL, *pp = NULL;
+ struct ndstruct *p = nullptr, *pp = nullptr;
p = ndsp;
while (p) {
void
clean_ls(struct lsstruct *lssp)
{
- struct lsstruct *p = NULL, *pp = NULL;
+ struct lsstruct *p = nullptr, *pp = nullptr;
p = lssp;
while (p) {
safe_free(margs->ddomain);
if (margs->groups) {
clean_gd(margs->groups);
- margs->groups = NULL;
+ margs->groups = nullptr;
}
if (margs->ndoms) {
clean_nd(margs->ndoms);
- margs->ndoms = NULL;
+ margs->ndoms = nullptr;
}
if (margs->lservs) {
clean_ls(margs->lservs);
- margs->lservs = NULL;
+ margs->lservs = nullptr;
}
safe_free(margs->principal);
}
{
char buf[6400];
char *user, *domain, *group;
- char *up=NULL, *dp=NULL, *np=NULL;
- char *nuser, *nuser8 = NULL, *netbios;
+ char *up=nullptr, *dp=nullptr, *np=nullptr;
+ char *nuser, *nuser8 = nullptr, *netbios;
int opt;
struct main_args margs;
#if HAVE_KRB5
krb5_error_code code = 0;
- kparam.context = NULL;
+ kparam.context = nullptr;
#endif
- setbuf(stdout, NULL);
- setbuf(stdin, NULL);
+ setbuf(stdout, nullptr);
+ setbuf(stdin, nullptr);
init_args(&margs);
debug((char *) "%s| %s: INFO: Starting version %s\n", LogTime(), PROGRAM, KERBEROS_LDAP_GROUP_VERSION);
int gopt = 0;
if (create_gd(&margs)) {
- if ( margs.glist != NULL ) {
+ if ( margs.glist != nullptr ) {
debug((char *) "%s| %s: FATAL: Error in group list: %s\n", LogTime(), PROGRAM, margs.glist ? margs.glist : "NULL");
SEND_BH("");
clean_args(&margs);
code = krb5_init_context(&kparam.context);
for (int i=0; i<MAX_DOMAINS; i++) {
- kparam.mem_ccache[i]=NULL;
- kparam.cc[i]=NULL;
+ kparam.mem_ccache[i]=nullptr;
+ kparam.cc[i]=nullptr;
kparam.ncache=0;
}
if (code) {
while (1) {
char *c;
- if (fgets(buf, sizeof(buf) - 1, stdin) == NULL) {
+ if (fgets(buf, sizeof(buf) - 1, stdin) == nullptr) {
if (ferror(stdin)) {
debug((char *) "%s| %s: FATAL: fgets() failed! dying..... errno=%d (%s)\n", LogTime(), PROGRAM, ferror(stdin),
strerror(ferror(stdin)));
exit(EXIT_SUCCESS);
}
if (gopt) {
- if ((group = strtok(NULL, " \n")) != NULL) {
+ if ((group = strtok(nullptr, " \n")) != nullptr) {
debug((char *) "%s| %s: INFO: Read group list %s from stdin\n", LogTime(), PROGRAM, group);
rfc1738_unescape(group);
if (margs.groups) {
clean_gd(margs.groups);
- margs.groups = NULL;
+ margs.groups = nullptr;
}
margs.glist = xstrdup(group);
if (create_gd(&margs)) {
int
main(int argc, char *const argv[])
{
- setbuf(stdout, NULL);
- setbuf(stdin, NULL);
+ setbuf(stdout, nullptr);
+ setbuf(stdin, nullptr);
char buf[6400];
while (1) {
- if (fgets(buf, sizeof(buf) - 1, stdin) == NULL) {
+ if (fgets(buf, sizeof(buf) - 1, stdin) == nullptr) {
}
fprintf(stdout, "ERR\n");
fprintf(stderr, "LDAP group authorisation not supported\n");
init_gd(void) {
struct gdstruct *gdsp;
gdsp = (struct gdstruct *) xmalloc(sizeof(struct gdstruct));
- gdsp->group = NULL;
- gdsp->domain = NULL;
- gdsp->next = NULL;
+ gdsp->group = nullptr;
+ gdsp->domain = nullptr;
+ gdsp->next = nullptr;
return gdsp;
}
src = margs->glist;
if (!src)
- return NULL;
+ return nullptr;
for (n = 0; n < strlen(src); ++n)
if ((unsigned char) src[n] > 127)
++c;
char *up = (flag ? margs->ulist : margs->tlist);
if (!up)
- return NULL;
+ return nullptr;
char *upd = strrchr(up, '@');
size_t a = (upd ? (size_t)(upd - up) : strlen(up) );
else {
debug((char *) "%s| %s: WARNING: Invalid Hex value %c\n", LogTime(), PROGRAM, ival);
xfree(ul);
- return NULL;
+ return nullptr;
}
if (n == a - 1) {
debug((char *) "%s| %s: WARNING: Invalid Hex UTF-8 string %s\n", LogTime(), PROGRAM, up);
xfree(ul);
- return NULL;
+ return nullptr;
}
++n;
ival = up[n];
else {
debug((char *) "%s| %s: WARNING: Invalid Hex value %c\n", LogTime(), PROGRAM, ival);
xfree(ul);
- return NULL;
+ return nullptr;
}
if (iUTF2) {
ul[nl + 1] = '\0';
debug((char *) "%s| %s: WARNING: Invalid UTF-8 sequence for Unicode %s\n", LogTime(), PROGRAM, ul);
xfree(ul);
- return NULL;
+ return nullptr;
}
} else if (iUTF3) {
if (iUTF3 == 0xE0 && ichar > 0x9F && ichar < 0xC0) {
ul[nl + 1] = '\0';
debug((char *) "%s| %s: WARNING: Invalid UTF-8 sequence for Unicode %s\n", LogTime(), PROGRAM, ul);
xfree(ul);
- return NULL;
+ return nullptr;
}
} else if (iUTF4) {
if (iUTF4 == 0xF0 && ichar > 0x8F && ichar < 0xC0) {
ul[nl + 1] = '\0';
debug((char *) "%s| %s: WARNING: Invalid UTF-8 sequence for Unicode %s\n", LogTime(), PROGRAM, ul);
xfree(ul);
- return NULL;
+ return nullptr;
}
} else if (ichar < 0x80) {
/* UTF1 */
ul[nl + 1] = '\0';
debug((char *) "%s| %s: WARNING: Invalid UTF-8 sequence for Unicode %s\n", LogTime(), PROGRAM, ul);
xfree(ul);
- return NULL;
+ return nullptr;
}
++n;
}
debug((char *) "%s| %s: INFO: iUTF2: %d iUTF3: %d iUTF4: %d\n", LogTime(), PROGRAM, iUTF2, iUTF3, iUTF4);
debug((char *) "%s| %s: WARNING: Invalid UTF-8 sequence for Unicode %s\n", LogTime(), PROGRAM, ul);
xfree(ul);
- return NULL;
+ return nullptr;
}
if (flag && upd)
ul = strcat(ul, upd);
{
char *gp, *dp;
char *p;
- struct gdstruct *gdsp = NULL, *gdspn = NULL;
+ struct gdstruct *gdsp = nullptr, *gdspn = nullptr;
/*
* Group list format:
*
// NP: will point to the start of a temporary assembly buffer used by 'p' and 'gp'
// for catenation of the hp1, hp2, and up buffer contents from above.
// necessary for xfree() because both p and gp move over the assembly area
- char *gpbuf = NULL;
+ char *gpbuf = nullptr;
// release the allocated UTF decoding buffers
#define cleanup() { \
}
gp = p;
debug((char *) "%s| %s: INFO: Group list %s\n", LogTime(), PROGRAM, p ? p : "NULL");
- dp = NULL;
+ dp = nullptr;
if (!p) {
debug((char *) "%s| %s: ERROR: No groups defined.\n", LogTime(), PROGRAM);
++p;
if (dp) { /* end of domain name */
gdsp->domain = xstrdup(dp);
- dp = NULL;
+ dp = nullptr;
} else { /* end of group name and no domain name */
gdsp = init_gd();
gdsp->group = xstrdup(gp);
debug((char *) "%s| %s: INFO: Group %s Domain %s\n", LogTime(), PROGRAM, gdsp->group, gdsp->domain ? gdsp->domain : "NULL");
margs->groups = gdsp;
- gdsp = NULL; // prevent the cleanup() deallocating it.
+ gdsp = nullptr; // prevent the cleanup() deallocating it.
cleanup();
return (0);
}
krb5_create_cache(char *domain, char *service_principal_name)
{
- krb5_keytab keytab = NULL;
+ krb5_keytab keytab = nullptr;
krb5_keytab_entry entry;
krb5_kt_cursor cursor;
krb5_cc_cursor ccursor;
- krb5_creds *creds = NULL;
- krb5_principal *principal_list = NULL;
- krb5_principal principal = NULL;
+ krb5_creds *creds = nullptr;
+ krb5_principal *principal_list = nullptr;
+ krb5_principal principal = nullptr;
char *service;
- char *keytab_name = NULL, *principal_name = NULL, *mem_cache = NULL;
+ char *keytab_name = nullptr, *principal_name = nullptr, *mem_cache = nullptr;
char buf[KT_PATH_MAX], *p;
size_t j,nprinc = 0;
int retval = 0;
if (code) {
if (principal)
krb5_free_principal(kparam.context, principal);
- principal = NULL;
+ principal = nullptr;
k5_debug("No default principal found in ccache", code);
} else {
/*
if (code) {
k5_error("Error while destroying ccache", code);
}
- assert(creds != NULL);
+ assert(creds != nullptr);
krb5_free_creds(kparam.context, creds);
- creds = NULL;
+ creds = nullptr;
safe_free(principal_name);
debug((char *) "%s| %s: DEBUG: Reset credential cache to %s\n", LogTime(), PROGRAM, mem_cache);
code = krb5_cc_resolve(kparam.context, mem_cache, &kparam.cc[ccindex]);
debug((char *) "%s| %s: DEBUG: credential will soon expire %d\n", LogTime(), PROGRAM, (int)(creds->times.endtime - now));
if (principal)
krb5_free_principal(kparam.context, principal);
- principal = NULL;
+ principal = nullptr;
code = krb5_cc_destroy(kparam.context, kparam.cc[ccindex]);
if (code) {
k5_error("Error while destroying ccache", code);
}
- assert(creds != NULL);
+ assert(creds != nullptr);
krb5_free_creds(kparam.context, creds);
- creds = NULL;
+ creds = nullptr;
safe_free(principal_name);
debug((char *) "%s| %s: DEBUG: Reset credential cache to %s\n", LogTime(), PROGRAM, mem_cache);
code = krb5_cc_resolve(kparam.context, mem_cache, &kparam.cc[ccindex]);
}
break;
}
- assert(creds != NULL);
+ assert(creds != nullptr);
krb5_free_creds(kparam.context, creds);
creds = static_cast<krb5_creds *>(xcalloc(1, sizeof(*creds)));
safe_free(principal_name);
}
if (creds)
krb5_free_creds(kparam.context, creds);
- creds = NULL;
+ creds = nullptr;
code2 = krb5_cc_end_seq_get(kparam.context, kparam.cc[ccindex], &ccursor);
if (code2) {
k5_error("Error while ending ccache scan", code2);
* get credentials
*/
#if HAVE_GET_INIT_CREDS_KEYTAB
- code = krb5_get_init_creds_keytab(kparam.context, creds, principal, keytab, 0, NULL, NULL);
+ code = krb5_get_init_creds_keytab(kparam.context, creds, principal, keytab, 0, nullptr, nullptr);
#else
service = (char *) xmalloc(strlen("krbtgt") + 2 * strlen(domain) + 3);
snprintf(service, strlen("krbtgt") + 2 * strlen(domain) + 3, "krbtgt/%s@%s", domain, domain);
krb5_free_principal(kparam.context, principal);
if (creds)
krb5_free_creds(kparam.context, creds);
- creds = NULL;
+ creds = nullptr;
found = 0;
continue;
}
krb5_free_principal(kparam.context, principal);
if (creds)
krb5_free_creds(kparam.context, creds);
- creds = NULL;
+ creds = nullptr;
found = 0;
continue;
}
safe_free(principal_name);
if (creds)
krb5_free_creds(kparam.context, creds);
- creds = NULL;
+ creds = nullptr;
found = 0;
continue;
}
debug((char *) "%s| %s: DEBUG: Try to get principal of trusted domain.\n", LogTime(), PROGRAM);
for (i = 0; i < nprinc; ++i) {
- krb5_creds *tgt_creds = NULL;
+ krb5_creds *tgt_creds = nullptr;
creds = (krb5_creds *) xmalloc(sizeof(*creds));
memset(creds, 0, sizeof(*creds));
/*
debug((char *) "%s| %s: DEBUG: Keytab entry has principal: %s\n", LogTime(), PROGRAM, principal_name);
#if HAVE_GET_INIT_CREDS_KEYTAB
- code = krb5_get_init_creds_keytab(kparam.context, creds, principal_list[i], keytab, 0, NULL, NULL);
+ code = krb5_get_init_creds_keytab(kparam.context, creds, principal_list[i], keytab, 0, nullptr, nullptr);
#else
service = (char *) xmalloc(strlen("krbtgt") + 2 * strlen(domain) + 3);
snprintf(service, strlen("krbtgt") + 2 * strlen(domain) + 3, "krbtgt/%s@%s", domain, domain);
debug((char *) "%s| %s: DEBUG: Found trusted principal name: %s\n", LogTime(), PROGRAM, principal_name);
if (tgt_creds)
krb5_free_creds(kparam.context, tgt_creds);
- tgt_creds = NULL;
+ tgt_creds = nullptr;
break;
}
safe_free(principal_name);
if (tgt_creds)
krb5_free_creds(kparam.context, tgt_creds);
- tgt_creds = NULL;
+ tgt_creds = nullptr;
if (creds)
krb5_free_creds(kparam.context, creds);
- creds = NULL;
+ creds = nullptr;
}
if (creds)
krb5_free_creds(kparam.context, creds);
- creds = NULL;
+ creds = nullptr;
}
} else {
debug((char *) "%s| %s: DEBUG: Got principal from ccache\n", LogTime(), PROGRAM);
cred.bv_val = cp->pw;
cred.bv_len = strlen(cp->pw);
}
- return ldap_sasl_bind_s(ld, cp->dn, LDAP_SASL_SIMPLE, &cred, NULL, NULL,
- NULL);
+ return ldap_sasl_bind_s(ld, cp->dn, LDAP_SASL_SIMPLE, &cred, nullptr, nullptr,
+ nullptr);
}
#endif
char *
convert_domain_to_bind_path(char *domain)
{
- char *dp, *bindp = NULL, *bp = NULL;
+ char *dp, *bindp = nullptr, *bp = nullptr;
size_t i = 0;
if (!domain)
- return NULL;
+ return nullptr;
for (dp = domain; *dp; ++dp) {
if (*dp == '.')
check_AD(struct main_args *margs, LDAP * ld)
{
LDAPMessage *res;
- char **attr_value = NULL;
+ char **attr_value = nullptr;
struct timeval searchtime;
size_t max_attr = 0;
int rc = 0;
"%s| %s: DEBUG: Search ldap server with bind path \"\" and filter: %s\n",
LogTime(), PROGRAM, FILTER_SCHEMA);
rc = ldap_search_ext_s(ld, (char *) "", LDAP_SCOPE_BASE,
- (char *) FILTER_SCHEMA, NULL, 0, NULL, NULL, &searchtime, 0, &res);
+ (char *) FILTER_SCHEMA, nullptr, 0, nullptr, nullptr, &searchtime, 0, &res);
if (rc == LDAP_SUCCESS)
max_attr = get_attributes(ld, res, ATTRIBUTE_SCHEMA, &attr_value);
"%s| %s: DEBUG: Search ldap server with bind path %s and filter: %s\n",
LogTime(), PROGRAM, attr_value[0], FILTER_SAM);
rc = ldap_search_ext_s(ld, attr_value[0], LDAP_SCOPE_SUBTREE,
- (char *) FILTER_SAM, NULL, 0, NULL, NULL, &searchtime, 0, &res);
+ (char *) FILTER_SAM, nullptr, 0, nullptr, nullptr, &searchtime, 0, &res);
debug((char *) "%s| %s: DEBUG: Found %d ldap entr%s\n", LogTime(),
PROGRAM, ldap_count_entries(ld, res), ldap_count_entries(ld,
res) > 1 || ldap_count_entries(ld, res) == 0 ? "ies" : "y");
search_group_tree(struct main_args *margs, LDAP * ld, char *bindp,
char *ldap_group, char *group, int depth)
{
- LDAPMessage *res = NULL;
- char **attr_value = NULL;
+ LDAPMessage *res = nullptr;
+ char **attr_value = nullptr;
size_t max_attr = 0;
- char *filter = NULL;
- char *search_exp = NULL;
+ char *filter = nullptr;
+ char *search_exp = nullptr;
size_t se_len = 0;
int rc = 0, retval = 0;
int ldepth;
- char *ldap_filter_esc = NULL;
+ char *ldap_filter_esc = nullptr;
struct timeval searchtime;
#define FILTER_GROUP_AD "(&(%s)(objectclass=group))"
debug((char *)
"%s| %s: DEBUG: Search ldap server with bind path %s and filter : %s\n",
LogTime(), PROGRAM, bindp, search_exp);
- rc = ldap_search_ext_s(ld, bindp, LDAP_SCOPE_SUBTREE, search_exp, NULL, 0,
- NULL, NULL, &searchtime, 0, &res);
+ rc = ldap_search_ext_s(ld, bindp, LDAP_SCOPE_SUBTREE, search_exp, nullptr, 0,
+ nullptr, nullptr, &searchtime, 0, &res);
xfree(search_exp);
if (rc != LDAP_SUCCESS) {
retval = 0;
ldepth = depth + 1;
for (size_t j = 0; j < max_attr; ++j) {
- char *av = NULL;
+ char *av = nullptr;
/* Compare first CN= value assuming it is the same as the group name itself */
av = attr_value[j];
if (!strncasecmp("CN=", av, 3)) {
- char *avp = NULL;
+ char *avp = nullptr;
av += 3;
if ((avp = strchr(av, ','))) {
*avp = '\0';
if (search_group_tree(margs, ld, bindp, av, group, ldepth)) {
retval = 1;
if (!strncasecmp("CN=", av, 3)) {
- char *avp = NULL;
+ char *avp = nullptr;
av += 3;
if ((avp = strchr(av, ','))) {
*avp = '\0';
#if HAVE_OPENLDAP
if (!margs->rc_allow) {
- char *ssl_cacertfile = NULL;
- char *ssl_cacertdir = NULL;
+ char *ssl_cacertfile = nullptr;
+ char *ssl_cacertdir = nullptr;
debug((char *)
"%s| %s: DEBUG: Enable server certificate check for ldap server.\n",
LogTime(), PROGRAM);
val = LDAP_OPT_X_TLS_DEMAND;
- rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &val);
+ rc = ldap_set_option(nullptr, LDAP_OPT_X_TLS_REQUIRE_CERT, &val);
if (rc != LDAP_SUCCESS) {
error((char *)
"%s| %s: ERROR: Error while setting LDAP_OPT_X_TLS_REQUIRE_CERT DEMAND for ldap server: %s\n",
debug((char *)
"%s| %s: DEBUG: Set certificate file for ldap server to %s. (Changeable through setting environment variable TLS_CACERTFILE)\n",
LogTime(), PROGRAM, ssl_cacertfile);
- rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE,
+ rc = ldap_set_option(nullptr, LDAP_OPT_X_TLS_CACERTFILE,
ssl_cacertfile);
xfree(ssl_cacertfile);
if (rc != LDAP_OPT_SUCCESS) {
debug((char *)
"%s| %s: DEBUG: Set certificate database path for ldap server to %s. (Changeable through setting environment variable TLS_CACERTDIR)\n",
LogTime(), PROGRAM, ssl_cacertdir);
- rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTDIR,
+ rc = ldap_set_option(nullptr, LDAP_OPT_X_TLS_CACERTDIR,
ssl_cacertdir);
xfree(ssl_cacertdir);
if (rc != LDAP_OPT_SUCCESS) {
"%s| %s: DEBUG: Disable server certificate check for ldap server.\n",
LogTime(), PROGRAM);
val = LDAP_OPT_X_TLS_ALLOW;
- rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &val);
+ rc = ldap_set_option(nullptr, LDAP_OPT_X_TLS_REQUIRE_CERT, &val);
if (rc != LDAP_SUCCESS) {
error((char *)
"%s| %s: ERROR: Error while setting LDAP_OPT_X_TLS_REQUIRE_CERT ALLOW for ldap server: %s\n",
switch (ldap_msgtype(msg)) {
case LDAP_RES_SEARCH_ENTRY: {
- BerElement *b = NULL;
+ BerElement *b = nullptr;
for (char *attr = ldap_first_attribute(ld, msg, &b); attr;
attr = ldap_next_attribute(ld, msg, b)) {
if (strcasecmp(attr, attribute) == 0) {
struct berval **values;
if ((values =
- ldap_get_values_len(ld, msg, attr)) != NULL) {
- for (int il = 0; values[il] != NULL; ++il) {
+ ldap_get_values_len(ld, msg, attr)) != nullptr) {
+ for (int il = 0; values[il] != nullptr; ++il) {
attr_value =
(char **) xrealloc(attr_value,
switch (ldap_msgtype(msg)) {
case LDAP_RES_SEARCH_ENTRY: {
- BerElement *b = NULL;
+ BerElement *b = nullptr;
for (char *attr = ldap_first_attribute(ld, msg, &b); attr;
attr = ldap_next_attribute(ld, msg, b)) {
if (strcasecmp(attr, attribute) == 0) {
struct berval **values;
if ((values =
- ldap_get_values_len(ld, msg, attr)) != NULL) {
- for (int il = 0; values[il] != NULL; ++il) {
+ ldap_get_values_len(ld, msg, attr)) != nullptr) {
+ for (int il = 0; values[il] != nullptr; ++il) {
attr_value =
(char **) xrealloc(attr_value,
{
LDAP *ld;
#if HAVE_OPENLDAP
- LDAPURLDesc *url = NULL;
- char *ldapuri = NULL;
+ LDAPURLDesc *url = nullptr;
+ char *ldapuri = nullptr;
#endif
int rc = 0;
error((char *)
"%s| %s: ERROR: Error while initialising connection to ldap server: %s\n",
LogTime(), PROGRAM, ldap_err2string(rc));
- ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
- return NULL;
+ ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
+ return nullptr;
}
#else
ld = ldap_init(host, port);
error((char *)
"%s| %s: ERROR: Error while setting default options for ldap server: %s\n",
LogTime(), PROGRAM, ldap_err2string(rc));
- ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
- return NULL;
+ ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
+ return nullptr;
}
if (ssl) {
/*
error((char *)
"%s| %s: ERROR: Error while setting SSL default options for ldap server: %s\n",
LogTime(), PROGRAM, ldap_err2string(rc));
- ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
- return NULL;
+ ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
+ return nullptr;
}
#if HAVE_OPENLDAP
/*
* Use tls if possible
*/
- rc = ldap_start_tls_s(ld, NULL, NULL);
+ rc = ldap_start_tls_s(ld, nullptr, nullptr);
if (rc != LDAP_SUCCESS) {
debug((char *)
"%s| %s: WARNING: Error while setting start_tls for ldap server: %s\n",
LogTime(), PROGRAM, ldap_err2string(rc));
- ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
+ ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
url = (LDAPURLDesc *) xmalloc(sizeof(*url));
memset(url, 0, sizeof(*url));
#if HAVE_LDAP_URL_LUD_SCHEME
error((char *)
"%s| %s: ERROR: Error while initialising connection to ldap server: %s\n",
LogTime(), PROGRAM, ldap_err2string(rc));
- ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
- return NULL;
+ ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
+ return nullptr;
}
rc = ldap_set_defaults(ld);
if (rc != LDAP_SUCCESS) {
error((char *)
"%s| %s: ERROR: Error while setting default options for ldap server: %s\n",
LogTime(), PROGRAM, ldap_err2string(rc));
- ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
- return NULL;
+ ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
+ return nullptr;
}
}
#elif HAVE_LDAPSSL_CLIENT_INIT
int
get_memberof(struct main_args *margs, char *user, char *domain, char *group)
{
- LDAP *ld = NULL;
+ LDAP *ld = nullptr;
LDAPMessage *res;
#if !HAVE_SUN_LDAP_SDK
int ldap_debug = 0;
#endif
- struct ldap_creds *lcreds = NULL;
- char *bindp = NULL;
- char *filter = NULL;
+ struct ldap_creds *lcreds = nullptr;
+ char *bindp = nullptr;
+ char *filter = nullptr;
char *search_exp;
size_t se_len = 0;
struct timeval searchtime;
int rc = 0, kc = 1;
int retval;
- char **attr_value = NULL;
+ char **attr_value = nullptr;
size_t max_attr = 0;
- struct hstruct *hlist = NULL;
+ struct hstruct *hlist = nullptr;
size_t nhosts = 0;
- char *ldap_filter_esc = NULL;
+ char *ldap_filter_esc = nullptr;
searchtime.tv_sec = SEARCH_TIMEOUT;
searchtime.tv_usec = 0;
// ldap_debug = 127 /* LDAP_DEBUG_TRACE */ ;
// ldap_debug = -1 /* LDAP_DEBUG_ANY */ ;
ldap_debug = 0;
- (void) ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &ldap_debug);
+ (void) ldap_set_option(nullptr, LDAP_OPT_DEBUG_LEVEL, &ldap_debug);
#endif
debug((char *) "%s| %s: DEBUG: Initialise ldap connection\n", LogTime(),
PROGRAM);
error((char *)
"%s| %s: ERROR: Error while binding to ldap server with SASL/GSSAPI: %s\n",
LogTime(), PROGRAM, ldap_err2string(rc));
- ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
+ ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
continue;
}
lcreds = (struct ldap_creds *) xmalloc(sizeof(struct ldap_creds));
- lcreds->dn = NULL;
- lcreds->pw = margs->ssl ? xstrdup(margs->ssl) : NULL;
+ lcreds->dn = nullptr;
+ lcreds->pw = margs->ssl ? xstrdup(margs->ssl) : nullptr;
ldap_set_rebind_proc(ld, ldap_sasl_rebind, (char *) lcreds);
- if (ld != NULL) {
+ if (ld != nullptr) {
debug((char *)
"%s| %s: DEBUG: %s initialised %sconnection to ldap server %s:%d\n",
LogTime(), PROGRAM, ld ? "Successfully" : "Failed to",
#endif
}
nhosts = free_hostname_list(&hlist, nhosts);
- if (ld == NULL) {
+ if (ld == nullptr) {
debug((char *)
"%s| %s: DEBUG: Error during initialisation of ldap connection: %s\n",
LogTime(), PROGRAM, strerror(errno));
char *hostname;
char *host;
int port;
- char *ssl = NULL;
+ char *ssl = nullptr;
char *p;
/*
* If username does not contain a domain and a url was given then try it
"%s| %s: DEBUG: Bind to ldap server with Username/Password\n",
LogTime(), PROGRAM);
rc = ldap_sasl_bind_s(ld, margs->luser, LDAP_SASL_SIMPLE, &cred,
- NULL, NULL, NULL);
+ nullptr, nullptr, nullptr);
if (rc != LDAP_SUCCESS) {
error((char *)
"%s| %s: ERROR: Error while binding to ldap server with Username/Password: %s\n",
LogTime(), PROGRAM, ldap_err2string(rc));
- ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
+ ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
continue;
}
lcreds = (struct ldap_creds *) xmalloc(sizeof(struct ldap_creds));
bindp = convert_domain_to_bind_path(domain);
}
}
- if (ld == NULL) {
+ if (ld == nullptr) {
debug((char *)
"%s| %s: DEBUG: Error during initialisation of ldap connection: %s\n",
LogTime(), PROGRAM, strerror(errno));
error((char *)
"%s| %s: ERROR: Error determining ldap server type: %s\n",
LogTime(), PROGRAM, ldap_err2string(rc));
- ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
+ ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
retval = 0;
goto cleanup;
}
debug((char *)
"%s| %s: DEBUG: Search ldap server with bind path %s and filter : %s\n",
LogTime(), PROGRAM, bindp, search_exp);
- rc = ldap_search_ext_s(ld, bindp, LDAP_SCOPE_SUBTREE, search_exp, NULL, 0,
- NULL, NULL, &searchtime, 0, &res);
+ rc = ldap_search_ext_s(ld, bindp, LDAP_SCOPE_SUBTREE, search_exp, nullptr, 0,
+ nullptr, nullptr, &searchtime, 0, &res);
xfree(search_exp);
if (rc != LDAP_SUCCESS) {
error((char *) "%s| %s: ERROR: Error searching ldap server: %s\n",
LogTime(), PROGRAM, ldap_err2string(rc));
- ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
+ ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
retval = 0;
goto cleanup;
}
*/
retval = 0;
for (size_t k = 0; k < max_attr; ++k) {
- char *av = NULL;
+ char *av = nullptr;
/* Compare first CN= value assuming it is the same as the group name itself */
av = attr_value[k];
if (!strncasecmp("CN=", av, 3)) {
- char *avp = NULL;
+ char *avp = nullptr;
av += 3;
if ((avp = strchr(av, ','))) {
*avp = '\0';
LogTime(), PROGRAM);
}
for (size_t j = 0; j < max_attr; ++j) {
- char *av = NULL;
+ char *av = nullptr;
av = attr_value[j];
if (search_group_tree(margs, ld, bindp, av, group, 1)) {
retval = 1;
if (!strncasecmp("CN=", av, 3)) {
- char *avp = NULL;
+ char *avp = nullptr;
av += 3;
if ((avp = strchr(av, ','))) {
*avp = '\0';
ldap_msgfree(res);
} else if (ldap_count_entries(ld, res) == 0 && margs->AD) {
ldap_msgfree(res);
- ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
+ ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
retval = 0;
goto cleanup;
} else {
debug((char *)
"%s| %s: DEBUG: Search ldap server with bind path %s and filter: %s\n",
LogTime(), PROGRAM, bindp, search_exp);
- rc = ldap_search_ext_s(ld, bindp, LDAP_SCOPE_SUBTREE, search_exp, NULL,
- 0, NULL, NULL, &searchtime, 0, &res);
+ rc = ldap_search_ext_s(ld, bindp, LDAP_SCOPE_SUBTREE, search_exp, nullptr,
+ 0, nullptr, nullptr, &searchtime, 0, &res);
xfree(search_exp);
debug((char *) "%s| %s: DEBUG: Found %d ldap entr%s\n", LogTime(),
}
if (max_attr == 1) {
- char **attr_value_2 = NULL;
+ char **attr_value_2 = nullptr;
size_t max_attr_2 = 0;
if (margs->AD) {
- char **attr_value_3 = NULL;
- int *attr_len_3 = NULL;
+ char **attr_value_3 = nullptr;
+ int *attr_len_3 = nullptr;
size_t max_attr_3 = 0;
uint32_t gid = atoi(attr_value[0]);
LogTime(), PROGRAM, len);
rc = 1;
} else {
- char *se = NULL;
+ char *se = nullptr;
attr_value_3[0][len - 1] = ((gid >> 24) & 0xff);
attr_value_3[0][len - 2] = ((gid >> 16) & 0xff);
attr_value_3[0][len - 3] = ((gid >> 8) & 0xff);
"%s| %s: DEBUG: Search ldap server with bind path %s and filter: %s\n",
LogTime(), PROGRAM, bindp, search_exp);
rc = ldap_search_ext_s(ld, bindp, LDAP_SCOPE_SUBTREE,
- search_exp, NULL, 0, NULL, NULL, &searchtime, 0,
+ search_exp, nullptr, 0, nullptr, nullptr, &searchtime, 0,
&res);
xfree(search_exp);
"%s| %s: DEBUG: Search ldap server with bind path %s and filter: %s\n",
LogTime(), PROGRAM, bindp, search_exp);
rc = ldap_search_ext_s(ld, bindp, LDAP_SCOPE_SUBTREE,
- search_exp, NULL, 0, NULL, NULL, &searchtime, 0, &res);
+ search_exp, nullptr, 0, nullptr, nullptr, &searchtime, 0, &res);
xfree(search_exp);
}
/* Compare first CN= value assuming it is the same as the group name itself */
char *av = attr_value_2[0];
if (!strncasecmp("CN=", av, 3)) {
- char *avp = NULL;
+ char *avp = nullptr;
av += 3;
if ((avp = strchr(av, ','))) {
*avp = '\0';
LogTime(), PROGRAM);
}
for (size_t j = 0; j < max_attr_2; ++j) {
- char *av = NULL;
+ char *av = nullptr;
av = attr_value_2[j];
if (search_group_tree(margs, ld, bindp, av, group, 1)) {
retval = 1;
if (!strncasecmp("CN=", av, 3)) {
- char *avp = NULL;
+ char *avp = nullptr;
av += 3;
if ((avp = strchr(av, ','))) {
*avp = '\0';
safe_free(attr_value);
}
}
- rc = ldap_unbind_ext(ld, NULL, NULL);
- ld = NULL;
+ rc = ldap_unbind_ext(ld, nullptr, nullptr);
+ ld = nullptr;
if (rc != LDAP_SUCCESS) {
error((char *) "%s| %s: ERROR: Error unbind ldap server: %s\n",
LogTime(), PROGRAM, ldap_err2string(rc));
struct timeval now;
static char buf[128];
- gettimeofday(&now, NULL);
+ gettimeofday(&now, nullptr);
if (now.tv_sec != last_t) {
struct tm *tm;
time_t tmp = now.tv_sec;
init_ls(void) {
struct lsstruct *lssp;
lssp = (struct lsstruct *) xmalloc(sizeof(struct lsstruct));
- lssp->lserver = NULL;
- lssp->domain = NULL;
- lssp->next = NULL;
+ lssp->lserver = nullptr;
+ lssp->domain = nullptr;
+ lssp->next = nullptr;
return lssp;
}
{
char *np, *dp;
char *p;
- struct lsstruct *lssp = NULL, *lsspn = NULL;
+ struct lsstruct *lssp = nullptr, *lsspn = nullptr;
/*
* netbios list format:
*
p = margs->llist;
np = margs->llist;
debug((char *) "%s| %s: DEBUG: ldap server list %s\n", LogTime(), PROGRAM, margs->llist ? margs->llist : "NULL");
- dp = NULL;
+ dp = nullptr;
if (!p) {
debug((char *) "%s| %s: DEBUG: No ldap servers defined.\n", LogTime(), PROGRAM);
++p;
if (dp) { /* end of domain name */
lssp->domain = xstrdup(dp);
- dp = NULL;
+ dp = nullptr;
} else { /* end of group name and no domain name */
lssp = init_ls();
lssp->lserver = xstrdup(np);
init_nd(void) {
struct ndstruct *ndsp;
ndsp = (struct ndstruct *) xmalloc(sizeof(struct ndstruct));
- ndsp->netbios = NULL;
- ndsp->domain = NULL;
- ndsp->next = NULL;
+ ndsp->netbios = nullptr;
+ ndsp->domain = nullptr;
+ ndsp->next = nullptr;
return ndsp;
}
{
char *np, *dp;
char *p;
- struct ndstruct *ndsp = NULL, *ndspn = NULL;
+ struct ndstruct *ndsp = nullptr, *ndspn = nullptr;
/*
* netbios list format:
*
p = margs->nlist;
np = margs->nlist;
debug((char *) "%s| %s: DEBUG: Netbios list %s\n", LogTime(), PROGRAM, margs->nlist ? margs->nlist : "NULL");
- dp = NULL;
+ dp = nullptr;
if (!p) {
debug((char *) "%s| %s: DEBUG: No netbios names defined.\n", LogTime(), PROGRAM);
++p;
if (dp) { /* end of domain name */
ndsp->domain = xstrdup(dp);
- dp = NULL;
+ dp = nullptr;
} else { /* end of group name and no domain name */
ndsp = init_nd();
ndsp->netbios = xstrdup(np);
nd = nd->next;
}
- return NULL;
+ return nullptr;
}
#endif
size_t
free_hostname_list(struct hstruct **hlist, size_t nhosts)
{
- struct hstruct *hp = NULL;
+ struct hstruct *hp = nullptr;
size_t i;
hp = *hlist;
size_t
get_hostname_list(struct hstruct **hlist, size_t nhosts, char *name)
{
- struct addrinfo *hres = NULL, *hres_list;
+ struct addrinfo *hres = nullptr, *hres_list;
int rc, count;
- struct hstruct *hp = NULL;
+ struct hstruct *hp = nullptr;
if (!name)
return (nhosts);
hp = *hlist;
- rc = getaddrinfo((const char *) name, NULL, NULL, &hres);
+ rc = getaddrinfo((const char *) name, nullptr, nullptr, &hres);
if (rc != 0) {
error((char *) "%s| %s: ERROR: Error while resolving hostname with getaddrinfo: %s\n", LogTime(), PROGRAM, gai_strerror(rc));
return (nhosts);
* char host[sysconf(_SC_HOST_NAME_MAX)];
*/
char host[1024];
- rc = getnameinfo(hres_list->ai_addr, hres_list->ai_addrlen, host, sizeof(host), NULL, 0, 0);
+ rc = getnameinfo(hres_list->ai_addr, hres_list->ai_addrlen, host, sizeof(host), nullptr, 0, 0);
if (rc != 0) {
error((char *) "%s| %s: ERROR: Error while resolving ip address with getnameinfo: %s\n", LogTime(), PROGRAM, gai_strerror(rc));
freeaddrinfo(hres);
* char name[sysconf(_SC_HOST_NAME_MAX)];
*/
char name[1024];
- char *service = NULL;
- struct hstruct *hp = NULL;
- struct lsstruct *ls = NULL;
+ char *service = nullptr;
+ struct hstruct *hp = nullptr;
+ struct lsstruct *ls = nullptr;
size_t nhosts = 0;
int size;
int len, olen;
size_t i, j, k;
- u_char *buffer = NULL;
+ u_char *buffer = nullptr;
u_char *p;
ls = margs->lservs;
defaults = (lutilSASLdefaults *) xmalloc(sizeof(lutilSASLdefaults));
- if (defaults == NULL)
- return NULL;
+ if (defaults == nullptr)
+ return nullptr;
- defaults->mech = mech ? xstrdup(mech) : NULL;
- defaults->realm = realm ? xstrdup(realm) : NULL;
- defaults->authcid = authcid ? xstrdup(authcid) : NULL;
- defaults->passwd = passwd ? xstrdup(passwd) : NULL;
- defaults->authzid = authzid ? xstrdup(authzid) : NULL;
+ defaults->mech = mech ? xstrdup(mech) : nullptr;
+ defaults->realm = realm ? xstrdup(realm) : nullptr;
+ defaults->authcid = authcid ? xstrdup(authcid) : nullptr;
+ defaults->passwd = passwd ? xstrdup(passwd) : nullptr;
+ defaults->authzid = authzid ? xstrdup(authzid) : nullptr;
- if (defaults->mech == NULL) {
+ if (defaults->mech == nullptr) {
ldap_get_option(ld, LDAP_OPT_X_SASL_MECH, &defaults->mech);
}
- if (defaults->realm == NULL) {
+ if (defaults->realm == nullptr) {
ldap_get_option(ld, LDAP_OPT_X_SASL_REALM, &defaults->realm);
}
- if (defaults->authcid == NULL) {
+ if (defaults->authcid == nullptr) {
ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHCID, &defaults->authcid);
}
- if (defaults->authzid == NULL) {
+ if (defaults->authzid == nullptr) {
ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHZID, &defaults->authzid);
}
- defaults->resps = NULL;
+ defaults->resps = nullptr;
defaults->nresps = 0;
return defaults;
}
if (dflt && !*dflt)
- dflt = NULL;
+ dflt = nullptr;
/* input must be empty */
interact->result = (dflt && *dflt) ? dflt : "";
{
sasl_interact_t *interact = (sasl_interact_t *) in;
- if (ld == NULL)
+ if (ld == nullptr)
return LDAP_PARAM_ERROR;
while (interact->id != SASL_CB_LIST_END) {
#else
unsigned sasl_flags = LDAP_SASL_QUIET;
#endif
- char *sasl_realm = NULL;
- char *sasl_authc_id = NULL;
- char *sasl_authz_id = NULL;
+ char *sasl_realm = nullptr;
+ char *sasl_authc_id = nullptr;
+ char *sasl_authz_id = nullptr;
char *sasl_mech = (char *) "GSSAPI";
/*
* Force encryption
/* sasl_secprops = (char *)"maxssf=0"; */
/* sasl_secprops = (char *)"maxssf=56"; */
- if (sasl_secprops != NULL) {
+ if (sasl_secprops != nullptr) {
rc = ldap_set_option(ld, LDAP_OPT_X_SASL_SECPROPS,
(void *) sasl_secprops);
if (rc != LDAP_SUCCESS) {
sasl_authz_id);
rc = ldap_sasl_interactive_bind_s(ld, binddn,
- sasl_mech, NULL, NULL,
+ sasl_mech, nullptr, nullptr,
sasl_flags, lutil_sasl_interact, defaults);
lutil_sasl_freedefs(defaults);
static int session_ttl = 3600;
static int fixed_timeout = 0;
-char *db_path = NULL;
+char *db_path = nullptr;
const char *program_name;
#if USE_BERKLEYDB
-DB *db = NULL;
-DB_ENV *db_env = NULL;
+DB *db = nullptr;
+DB_ENV *db_env = nullptr;
typedef DBT DB_ENTRY;
#elif USE_TRIVIALDB
#if USE_BERKLEYDB
if (db_env) {
- if (db->open(db, NULL, "session", NULL, DB_BTREE, DB_CREATE, 0666)) {
+ if (db->open(db, nullptr, "session", nullptr, DB_BTREE, DB_CREATE, 0666)) {
fprintf(stderr, "FATAL: %s: Failed to open db file '%s' in dir '%s'\n",
program_name, "session", db_path);
db_env->close(db_env, 0);
exit(EXIT_FAILURE);
}
} else {
- db_create(&db, NULL, 0);
- if (db->open(db, NULL, db_path, NULL, DB_BTREE, DB_CREATE, 0666)) {
+ db_create(&db, nullptr, 0);
+ if (db->open(db, nullptr, db_path, nullptr, DB_BTREE, DB_CREATE, 0666)) {
db = nullptr;
}
}
return 0;
}
copyValue(×tamp, &data, sizeof(timestamp));
- if (timestamp + session_ttl >= time(NULL))
+ if (timestamp + session_ttl >= time(nullptr))
return 1;
}
return 0;
{
DB_ENTRY key = {};
DB_ENTRY data = {};
- time_t now = time(0);
+ time_t now = time(nullptr);
#if USE_BERKLEYDB
key.data = static_cast<decltype(key.data)>(details);
key.size = len;
data.data = &now;
data.size = sizeof(now);
- db->put(db, NULL, &key, &data, 0);
+ db->put(db, nullptr, &key, &data, 0);
#elif USE_TRIVIALDB
key.dptr = reinterpret_cast<decltype(key.dptr)>(details);
key.dsize = len;
fixed_timeout = 1;
/* [[fallthrough]] */
case 't':
- session_ttl = strtol(optarg, NULL, 0);
+ session_ttl = strtol(optarg, nullptr, 0);
break;
case 'b':
db_path = xstrdup(optarg);
}
}
- setbuf(stdout, NULL);
+ setbuf(stdout, nullptr);
init_db();
while (fgets(request, HELPER_INPUT_BUFFER, stdin)) {
int action = 0;
const char *channel_id = strtok(request, " ");
- char *detail = strtok(NULL, "\n");
- if (detail == NULL) {
+ char *detail = strtok(nullptr, "\n");
+ if (detail == nullptr) {
// Only 1 parameter supplied. We are expecting at least 2 (including the channel ID)
fprintf(stderr, "FATAL: %s is concurrent and requires the concurrency option to be specified.\n", program_name);
shutdown_db();
struct passwd *p;
struct group *g;
- if ((p = getpwnam(username)) == NULL) {
+ if ((p = getpwnam(username)) == nullptr) {
/* Returns an error if user does not exist in the /etc/passwd */
fprintf(stderr, "ERROR: User does not exist '%s'\n", username);
return 0;
} else {
/* Verify if the this is the primary user group */
- if ((g = getgrgid(p->pw_gid)) != NULL) {
+ if ((g = getgrgid(p->pw_gid)) != nullptr) {
if ((strcmp(groupname, g->gr_name)) == 0)
return 1;
}
*/
struct group *g;
- if ((g = getgrnam(groupname)) == NULL) {
+ if ((g = getgrnam(groupname)) == nullptr) {
fprintf(stderr, "ERROR: Group does not exist '%s'\n", groupname);
return 0;
} else {
- while (*(g->gr_mem) != NULL) {
+ while (*(g->gr_mem) != nullptr) {
if (strcmp(*((g->gr_mem)++), username) == 0) {
return 1;
}
{
char *user, *suser, *p;
char buf[HELPER_INPUT_BUFFER];
- char **grents = NULL;
+ char **grents = nullptr;
int check_pw = 0, ch, ngroups = 0, i, j = 0, strip_dm = 0, strip_rm = 0;
/* make standard output line buffered */
- setvbuf(stdout, NULL, _IOLBF, 0);
+ setvbuf(stdout, nullptr, _IOLBF, 0);
/* get user options */
while ((ch = getopt(argc, argv, "dsrpg:")) != -1) {
}
while (fgets(buf, HELPER_INPUT_BUFFER, stdin)) {
j = 0;
- if ((p = strchr(buf, '\n')) == NULL) {
+ if ((p = strchr(buf, '\n')) == nullptr) {
/* too large message received.. skip and deny */
fprintf(stderr, "ERROR: %s: Too large: %s\n", argv[0], buf);
while (fgets(buf, sizeof(buf), stdin)) {
fprintf(stderr, "ERROR: %s: Too large..: %s\n", argv[0], buf);
- if (strchr(buf, '\n') != NULL)
+ if (strchr(buf, '\n') != nullptr)
break;
}
SEND_BH(HLP_MSG("Username Input too large."));
continue;
}
*p = '\0';
- if ((p = strtok(buf, " ")) == NULL) {
+ if ((p = strtok(buf, " ")) == nullptr) {
SEND_BH(HLP_MSG("No username given."));
continue;
} else {
if (suser) *suser = '\0';
}
/* check groups supplied by Squid */
- while ((p = strtok(NULL, " ")) != NULL) {
+ while ((p = strtok(nullptr, " ")) != nullptr) {
rfc1738_unescape(p);
if (check_pw == 1)
j += validate_user_pw(user, p);
Adaptation::Initiator *initiator):
AsyncJob("AccessCheck"), filter(aFilter),
theInitiator(initiator),
- acl_checklist(NULL)
+ acl_checklist(nullptr)
{
#if ICAP_CLIENT
Adaptation::Icap::History::Pointer h = filter.request->icapHistory();
- if (h != NULL)
+ if (h != nullptr)
h->start("ACL");
#endif
{
#if ICAP_CLIENT
Adaptation::Icap::History::Pointer h = filter.request->icapHistory();
- if (h != NULL)
+ if (h != nullptr)
h->stop("ACL");
#endif
}
}
debugs(93, 4, "NO candidates left");
- callBack(NULL);
+ callBack(nullptr);
Must(done());
}
if (answer.allowed()) { // the rule matched
ServiceGroupPointer g = topGroup();
- if (g != NULL) { // the corresponding group found
+ if (g != nullptr) { // the corresponding group found
callBack(g);
Must(done());
return;
int Adaptation::AccessRule::LastId = 0;
-Adaptation::AccessRule::AccessRule(const String &aGroupId): id(++LastId), groupId(aGroupId), acl(NULL)
+Adaptation::AccessRule::AccessRule(const String &aGroupId): id(++LastId), groupId(aGroupId), acl(nullptr)
{
}
if (!group()) { // no explicit group
debugs(93,7, "no service group: " << groupId);
// try to add a one-service group
- if (FindService(groupId) != NULL) {
+ if (FindService(groupId) != nullptr) {
ServiceGroupPointer g = new SingleService(groupId);
g->finalize(); // explicit groups were finalized before rules
AllGroups().push_back(g);
return *i;
}
- return NULL;
+ return nullptr;
}
Adaptation::AccessRule *
return *i;
}
- return NULL;
+ return nullptr;
}
#include <algorithm>
bool Adaptation::Config::Enabled = false;
-char *Adaptation::Config::masterx_shared_name = NULL;
+char *Adaptation::Config::masterx_shared_name = nullptr;
int Adaptation::Config::service_iteration_limit = 16;
int Adaptation::Config::send_client_ip = false;
int Adaptation::Config::send_username = false;
if ((*cfg)->key == service)
return *cfg;
}
- return NULL;
+ return nullptr;
}
void
const ServiceConfigs &configs = serviceConfigs;
for (VISCI i = configs.begin(); i != configs.end(); ++i) {
const ServiceConfigPointer cfg = *i;
- if (FindService(cfg->key) != NULL) {
+ if (FindService(cfg->key) != nullptr) {
debugs(93, DBG_CRITICAL, "ERROR: Duplicate adaptation service name: " <<
cfg->key);
continue; // TODO: make fatal
}
ServicePointer s = createService(cfg);
- if (s != NULL) {
+ if (s != nullptr) {
AllServices().push_back(s);
++created;
}
void
Adaptation::Config::ParseServiceGroup(ServiceGroupPointer g)
{
- assert(g != NULL);
+ assert(g != nullptr);
g->parse();
AllGroups().push_back(g);
}
AsyncCallT<AnswerDialer>::fire();
}
virtual ~AnswerCall() {
- if (!fired && dialer.arg1.message != NULL && dialer.arg1.message->body_pipe != NULL)
+ if (!fired && dialer.arg1.message != nullptr && dialer.arg1.message->body_pipe != nullptr)
dialer.arg1.message->body_pipe->expectNoConsumption();
}
theMsg(aMsg),
theCause(aCause),
al(alp),
- theLauncher(0),
+ theLauncher(nullptr),
iterations(0),
adapted(false)
{
- if (theCause != NULL)
+ if (theCause != nullptr)
HTTPMSGLOCK(theCause);
- if (theMsg != NULL)
+ if (theMsg != nullptr)
HTTPMSGLOCK(theMsg);
}
}
ServicePointer service = thePlan.current();
- Must(service != NULL);
+ Must(service != nullptr);
debugs(93,5, "using adaptation service: " << service->cfg().key);
if (Adaptation::Config::needHistory) {
if (HttpRequest *cause = dynamic_cast<HttpRequest*>(theMsg)) {
// definitely sent request, now use it as the cause
theCause = cause; // moving the lock
- theMsg = 0;
+ theMsg = nullptr;
debugs(93,3, "in request satisfaction mode");
}
}
debugs(85,5, "flags: " << srcIntact << canIgnore << adapted);
if (srcIntact) {
- if (thePlan.replacement(filter()) != NULL) {
+ if (thePlan.replacement(filter()) != nullptr) {
debugs(93,3, "trying a replacement service");
step();
return;
// the method may differ from theGroup->method due to request satisfaction
Method method = methodNone;
// temporary variables, no locking needed
- HttpRequest *req = NULL;
- HttpReply *rep = NULL;
+ HttpRequest *req = nullptr;
+ HttpReply *rep = nullptr;
if (HttpRequest *r = dynamic_cast<HttpRequest*>(theMsg)) {
method = methodReqmod;
req = r;
- rep = NULL;
+ rep = nullptr;
} else if (HttpReply *theReply = dynamic_cast<HttpReply*>(theMsg)) {
method = methodRespmod;
req = theCause;
#include "BodyPipe.h"
#include "http/Message.h"
-Adaptation::Message::Message(): header(NULL)
+Adaptation::Message::Message(): header(nullptr)
{
}
-Adaptation::Message::Message(Header *aHeader): header(NULL)
+Adaptation::Message::Message(Header *aHeader): header(nullptr)
{
set(aHeader);
}
Adaptation::Message::clear()
{
HTTPMSGUNLOCK(header);
- body_pipe = NULL;
+ body_pipe = nullptr;
}
void
Must(!dest.body_pipe); // can relax if needed, but need !body_pipe->used()
Must(src.header); // or there is nothing to shortcircuit
- if (src.header->body_pipe != NULL) {
+ if (src.header->body_pipe != nullptr) {
// check that it would not be too late to shortcircuit the pipe
Must(!src.header->body_pipe->consumedSize());
src.header->body_pipe->clearConsumer(); // if any
Adaptation::Service::Service(const ServiceConfigPointer &aConfig): theConfig(aConfig)
{
- Must(theConfig != NULL);
+ Must(theConfig != nullptr);
debugs(93,3, "creating adaptation service " << cfg().key);
}
if ((*i)->cfg().key == key)
return *i;
}
- return NULL;
+ return nullptr;
}
void Adaptation::DetachServices()
int len = 0;
if (*s == '[') {
const char *t;
- if ((t = strchr(s, ']')) == NULL)
+ if ((t = strchr(s, ']')) == nullptr)
return false;
++s;
len = t - s;
- if ((e = strchr(t, ':')) != NULL) {
+ if ((e = strchr(t, ':')) != nullptr) {
have_port = true;
- } else if ((e = strchr(t, '/')) != NULL) {
+ } else if ((e = strchr(t, '/')) != nullptr) {
have_port = false;
} else {
return false;
}
} else {
- if ((e = strchr(s, ':')) != NULL) {
+ if ((e = strchr(s, ':')) != nullptr) {
have_port = true;
- } else if ((e = strchr(s, '/')) != NULL) {
+ } else if ((e = strchr(s, '/')) != nullptr) {
have_port = false;
} else {
return false;
if (have_port) {
++s;
- if ((e = strchr(s, '/')) != NULL) {
+ if ((e = strchr(s, '/')) != nullptr) {
char *t;
const unsigned long p = strtoul(s, &t, 0);
bool
Adaptation::ServiceConfig::grokLong(long &var, const char *name, const char *value)
{
- char *bad = NULL;
+ char *bad = nullptr;
const long p = strtol(value, &bad, 0);
if (p < 0 || bad == value) {
debugs(3, DBG_CRITICAL, "ERROR: " << cfg_filename << ':' <<
{
id = ConfigParser::NextToken();
- wordlist *names = NULL;
+ wordlist *names = nullptr;
ConfigParser::ParseWordList(&names);
for (wordlist *i = names; i; i = i->next)
services.push_back(i->key);
// TODO: quit on all errors
const String &serviceId = services[pos];
ServicePointer service = at(pos);
- if (service != NULL) {
+ if (service != nullptr) {
if (method == methodNone) {
// optimization: cache values that should be the same
method = service->cfg().method;
for (Pos p = checkedPos + 1; has(p); ++p) {
ServicePointer s = at(p);
- if (s != NULL && s->cfg().key == checkedService->cfg().key)
+ if (s != nullptr && s->cfg().key == checkedService->cfg().key)
finalizeMsg("duplicate service name", s->cfg().key, false);
- else if (s != NULL && s->cfg().uri == checkedService->cfg().uri)
+ else if (s != nullptr && s->cfg().uri == checkedService->cfg().uri)
finalizeMsg("duplicate service URI", s->cfg().uri, false);
}
}
// walk the list of services and split it into two parts:
// services that are applicable now and future services
bool doingCurrent = true;
- const char *item = NULL;
+ const char *item = nullptr;
int ilen = 0;
- const char *pos = NULL;
+ const char *pos = nullptr;
while (strListGetItem(&ids, ',', &item, &ilen, &pos)) {
String id;
id.assign(item, ilen);
return *i;
}
- return NULL;
+ return nullptr;
}
Adaptation::Ecap::BodyRep::tie(const BodyPipe::Pointer &aBody)
{
Must(!theBody);
- Must(aBody != NULL);
+ Must(aBody != nullptr);
theBody = aBody;
}
/* MessageRep */
Adaptation::Ecap::MessageRep::MessageRep(Http::Message *rawHeader):
- theMessage(rawHeader), theFirstLineRep(NULL),
- theHeaderRep(NULL), theBodyRep(NULL)
+ theMessage(rawHeader), theFirstLineRep(nullptr),
+ theHeaderRep(nullptr), theBodyRep(nullptr)
{
Must(theMessage.header); // we do not want to represent a missing message
theHeaderRep = new HeaderRep(*theMessage.header);
- if (theMessage.body_pipe != NULL)
+ if (theMessage.body_pipe != nullptr)
theBodyRep = new BodyRep(theMessage.body_pipe);
}
Adaptation::Ecap::MessageRep::clone() const
{
Http::Message *hdr = theMessage.header->clone();
- hdr->body_pipe = NULL; // if any; TODO: remove pipe cloning from ::clone?
+ hdr->body_pipe = nullptr; // if any; TODO: remove pipe cloning from ::clone?
libecap::shared_ptr<libecap::Message> res(new MessageRep(hdr));
// restore indication of a body if needed, but not the pipe
- if (theMessage.header->body_pipe != NULL)
+ if (theMessage.header->body_pipe != nullptr)
res->addBody();
return res;
{
Must(!theBodyRep);
Must(!theMessage.body_pipe); // set in tieBody()
- theBodyRep = new BodyRep(NULL);
+ theBodyRep = new BodyRep(nullptr);
}
void
Adaptation::Ecap::MessageRep::tieBody(Adaptation::Ecap::XactionRep *x)
{
- Must(theBodyRep != NULL); // addBody must be called first
+ Must(theBodyRep != nullptr); // addBody must be called first
Must(!theMessage.header->body_pipe);
Must(!theMessage.body_pipe);
theMessage.header->body_pipe = new BodyPipe(x);
// register now because (a) we need EventLoop::Running and (b) we do not
// want to add more main loop overheads unless an async service is used.
- static AsyncEngine *TheEngine = NULL;
+ static AsyncEngine *TheEngine = nullptr;
if (AsyncServices.size() && !TheEngine && EventLoop::Running) {
TheEngine = new Engine;
EventLoop::Running->registerEngine(TheEngine);
AsyncJob("Adaptation::Ecap::XactionRep"),
Adaptation::Initiate("Adaptation::Ecap::XactionRep"),
theService(aService),
- theVirginRep(virginHeader), theCauseRep(NULL),
+ theVirginRep(virginHeader), theCauseRep(nullptr),
makingVb(opUndecided), proxyingAb(opUndecided),
adaptHistoryId(-1),
vbProductionFinished(false),
Adaptation::Service &
Adaptation::Ecap::XactionRep::service()
{
- Must(theService != NULL);
+ Must(theService != nullptr);
return *theService;
}
const HttpRequest *request = dynamic_cast<const HttpRequest*>(theCauseRep ?
theCauseRep->raw().header : theVirginRep.raw().header);
Must(request);
- if (request->auth_user_request != NULL) {
+ if (request->auth_user_request != nullptr) {
if (char const *name = request->auth_user_request->username())
return libecap::Area::FromTempBuffer(name, strlen(name));
else if (request->extacl_user.size() > 0)
Must(request);
if (sharedName.known()) { // must check to avoid empty names matching unset cfg
Adaptation::History::Pointer ah = request->adaptHistory(false);
- if (ah != NULL) {
+ if (ah != nullptr) {
String name, value;
if (ah->getXxRecord(name, value))
return libecap::Area::FromTempBuffer(value.rawBuf(), value.size());
HttpReply *reply = dynamic_cast<HttpReply*>(theVirginRep.raw().header);
Adaptation::History::Pointer ah = request->adaptLogHistory();
- if (ah != NULL) {
+ if (ah != nullptr) {
// retrying=false because ecap never retries transactions
adaptHistoryId = ah->recordXactStart(service().cfg().key, current_time, false);
SBuf matched;
for (auto h: Adaptation::Config::metaHeaders) {
if (h->match(request, reply, al, matched)) {
- if (ah->metaHeaders == NULL)
+ if (ah->metaHeaders == nullptr)
ah->metaHeaders = new NotePairs();
if (!ah->metaHeaders->hasPair(h->key(), matched))
ah->metaHeaders->add(h->key(), matched);
if (theAnswerRep) {
BodyPipe::Pointer body_pipe = answer().body_pipe;
- if (body_pipe != NULL) {
+ if (body_pipe != nullptr) {
Must(body_pipe->stillProducing(this));
stopProducingFor(body_pipe, false);
}
}
BodyPipe::Pointer &body_pipe = theVirginRep.raw().body_pipe;
- if (body_pipe != NULL && body_pipe->stillConsuming(this))
+ if (body_pipe != nullptr && body_pipe->stillConsuming(this))
stopConsumingFrom(body_pipe);
terminateMaster();
theCauseRep->raw().header : theVirginRep.raw().header);
Must(request);
Adaptation::History::Pointer ah = request->adaptLogHistory();
- if (ah != NULL && adaptHistoryId >= 0)
+ if (ah != nullptr && adaptHistoryId >= 0)
ah->recordXactFinish(adaptHistoryId);
Adaptation::Initiate::swanSong();
const libecap::Message &
Adaptation::Ecap::XactionRep::cause()
{
- Must(theCauseRep != NULL);
+ Must(theCauseRep != nullptr);
return *theCauseRep;
}
// we reset raw().body_pipe when we are done, so use this one for checking
const BodyPipePointer &permPipe = theVirginRep.raw().header->body_pipe;
- if (permPipe != NULL)
+ if (permPipe != nullptr)
permPipe->enableAutoConsumption();
forgetVb(reason);
// we reset raw().body_pipe when we are done, so use this one for checking
const BodyPipePointer &permPipe = theVirginRep.raw().header->body_pipe;
- if (permPipe != NULL) {
+ if (permPipe != nullptr) {
// if libecap consumed, we cannot preserve
Must(!permPipe->consumedSize());
}
debugs(93,9, "forget vb " << reason << "; status:" << status());
BodyPipePointer &p = theVirginRep.raw().body_pipe;
- if (p != NULL && p->stillConsuming(this))
+ if (p != nullptr && p->stillConsuming(this))
stopConsumingFrom(p);
if (makingVb == opUndecided)
MessageRep *rep = dynamic_cast<MessageRep*>(theAnswerRep.get());
Must(rep);
rep->tieBody(this); // sets us as a producer
- Must(msg->body_pipe != NULL); // check tieBody
+ Must(msg->body_pipe != nullptr); // check tieBody
updateHistory(msg);
sendAnswer(Answer::Forward(msg));
sinkVb("blockVirgin");
- updateHistory(NULL);
+ updateHistory(nullptr);
sendAnswer(Answer::Block(service().cfg().key));
Must(done());
}
// update the cross-transactional database if needed
if (const char *xxNameStr = Adaptation::Config::masterx_shared_name) {
Adaptation::History::Pointer ah = request->adaptHistory(true);
- if (ah != NULL) {
+ if (ah != nullptr) {
libecap::Name xxName(xxNameStr); // TODO: optimize?
if (const libecap::Area val = theMaster->option(xxName))
ah->updateXxRecord(xxNameStr, val.toString().c_str());
if (service().cfg().routing) {
if (const libecap::Area services = theMaster->option(libecap::metaNextServices)) {
Adaptation::History::Pointer ah = request->adaptHistory(true);
- if (ah != NULL)
+ if (ah != nullptr)
ah->updateNextServices(services.toString().c_str());
}
} // TODO: else warn (occasionally!) if we got libecap::metaNextServices
// If we already have stored headers from a previous adaptation transaction
// related to the same master transction, they will be replaced.
Adaptation::History::Pointer ah = request->adaptLogHistory();
- if (ah != NULL) {
+ if (ah != nullptr) {
HttpHeader meta(hoReply);
OptionsExtractor extractor(meta);
theMaster->visitEachOption(extractor);
{
Must(makingVb == opUndecided);
BodyPipePointer &p = theVirginRep.raw().body_pipe;
- Must(p != NULL);
+ Must(p != nullptr);
Must(p->setConsumerIfNotLate(this)); // to deliver vb, we must receive vb
makingVb = opOn;
}
Must(makingVb == opOn); // cannot make more if done proxying
// we cannot guarantee more vb, but we can check that there is a chance
const BodyPipePointer &p = theVirginRep.raw().body_pipe;
- Must(p != NULL && p->stillConsuming(this)); // we are plugged in
+ Must(p != nullptr && p->stillConsuming(this)); // we are plugged in
Must(!p->productionEnded() && p->mayNeedMoreData()); // and may get more
}
// We may not be makingVb yet. It should be OK, but see vbContentShift().
const BodyPipePointer &p = theVirginRep.raw().body_pipe;
- Must(p != NULL);
+ Must(p != nullptr);
// TODO: make MemBuf use size_t?
const size_t haveSize = static_cast<size_t>(p->buf().contentSize());
// until the adapter registers as a consumer
BodyPipePointer &p = theVirginRep.raw().body_pipe;
- Must(p != NULL);
+ Must(p != nullptr);
const size_t size = static_cast<size_t>(n); // XXX: check for overflow
const size_t haveSize = static_cast<size_t>(p->buf().contentSize()); // TODO: make MemBuf use size_t?
p->consume(min(size, haveSize));
default_options_ttl(0),
preview_enable(0), preview_size(0), allow206_enable(0),
connect_timeout_raw(0), io_timeout_raw(0), reuse_connections(0),
- client_username_header(NULL), client_username_encode(0), repeat(NULL),
+ client_username_header(nullptr), client_username_encode(0), repeat(nullptr),
repeat_limit(0)
{
}
// TODO: s/Header/Message/i ?
typedef Http::Message Header;
- InOut(): header(0), cause(0) {}
+ InOut(): header(nullptr), cause(nullptr) {}
~InOut() {
HTTPMSGUNLOCK(cause);
Adaptation::ServicePointer &aService):
AsyncJob(aTypeName),
Adaptation::Initiate(aTypeName),
- theService(aService), theXaction(0), theLaunches(0)
+ theService(aService), theXaction(nullptr), theLaunches(0)
{
}
AsyncJob("Adaptation::Icap::ModXact"),
Adaptation::Icap::Xaction("Adaptation::Icap::ModXact", aService),
virginConsumed(0),
- bodyParser(NULL),
+ bodyParser(nullptr),
canStartBypass(false), // too early
protectGroupBypass(true),
replyHttpHeaderSize(-1),
// reserve an adaptation history slot (attempts are known at this time)
Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
- if (ah != NULL)
+ if (ah != nullptr)
adaptHistoryId = ah->recordXactStart(service().cfg().key, icap_tr_start, attempts > 1);
estimateVirginBody(); // before virgin disappears!
{
debugs(93, 5, "checking whether to write more" << status());
- if (writer != NULL) // already writing something
+ if (writer != nullptr) // already writing something
return;
switch (state.writing) {
debugs(93, 8, "will write Preview body from " <<
virgin.body_pipe << status());
Must(state.writing == State::writingPreview);
- Must(virgin.body_pipe != NULL);
+ Must(virgin.body_pipe != nullptr);
const size_t sizeMax = (size_t)virgin.body_pipe->buf().contentSize();
const size_t size = min(preview.debt(), sizeMax);
void Adaptation::Icap::ModXact::writeSomeBody(const char *label, size_t size)
{
Must(!writer && state.writing < state.writingAlmostDone);
- Must(virgin.body_pipe != NULL);
+ Must(virgin.body_pipe != nullptr);
debugs(93, 8, "will write up to " << size << " bytes of " <<
label);
if (state.writing == State::writingReallyDone)
return;
- if (writer != NULL) {
+ if (writer != nullptr) {
if (nicely) {
debugs(93, 7, "will wait for the last write" << status());
state.writing = State::writingAlmostDone; // may already be set
void Adaptation::Icap::ModXact::readMore()
{
- if (reader != NULL || doneReading()) {
+ if (reader != nullptr || doneReading()) {
debugs(93,3, "returning from readMore because reader or doneReading()");
return;
}
// do not fill readBuf if we have no space to store the result
- if (adapted.body_pipe != NULL &&
+ if (adapted.body_pipe != nullptr &&
!adapted.body_pipe->buf().hasPotentialSpace()) {
debugs(93,3, "not reading because ICAP reply pipe is full");
return;
void Adaptation::Icap::ModXact::echoMore()
{
Must(state.sending == State::sendingVirgin);
- Must(adapted.body_pipe != NULL);
+ Must(adapted.body_pipe != nullptr);
Must(virginBodySending.active());
const size_t sizeMax = virginContentSize(virginBodySending);
if (state.sending != State::sendingUndecided) {
debugs(93, 7, "will no longer send" << status());
- if (adapted.body_pipe != NULL) {
+ if (adapted.body_pipe != nullptr) {
virginBodySending.disable();
// we may leave debts if we were echoing and the virgin
// body_pipe got exhausted before we echoed all planned bytes
// update the cross-transactional database if needed (all status codes!)
if (const char *xxName = Adaptation::Config::masterx_shared_name) {
Adaptation::History::Pointer ah = request->adaptHistory(true);
- if (ah != NULL) { // TODO: reorder checks to avoid creating history
+ if (ah != nullptr) { // TODO: reorder checks to avoid creating history
const String val = icapReply->header.getByName(xxName);
if (val.size() > 0) // XXX: HttpHeader lacks empty value detection
ah->updateXxRecord(xxName, val);
String services;
if (icapReply->header.getList(Http::HdrType::X_NEXT_SERVICES, &services)) {
Adaptation::History::Pointer ah = request->adaptHistory(true);
- if (ah != NULL)
+ if (ah != nullptr)
ah->updateNextServices(services);
}
} // TODO: else warn (occasionally!) if we got Http::HdrType::X_NEXT_SERVICES
// request, old headers will be replaced with the new one.
Adaptation::History::Pointer ah = request->adaptLogHistory();
- if (ah != NULL)
+ if (ah != nullptr)
ah->recordMeta(&icapReply->header);
// handle100Continue() manages state.writing on its own.
adapted.header);
// setup adapted body pipe if needed
- if (oldHead->body_pipe != NULL) {
+ if (oldHead->body_pipe != nullptr) {
debugs(93, 7, "will echo virgin body from " <<
oldHead->body_pipe);
if (!virginBodySending.active())
void Adaptation::Icap::ModXact::prepPartialBodyEchoing(uint64_t pos)
{
Must(virginBodySending.active());
- Must(virgin.header->body_pipe != NULL);
+ Must(virgin.header->body_pipe != nullptr);
setOutcome(xoPartEcho);
// update adaptation history if start was called and we reserved a slot
Adaptation::History::Pointer ah = virginRequest().adaptLogHistory();
- if (ah != NULL && adaptHistoryId >= 0)
+ if (ah != nullptr && adaptHistoryId >= 0)
ah->recordXactFinish(adaptHistoryId);
Adaptation::Icap::Xaction::swanSong();
}
Adaptation::Icap::History::Pointer h = virgin_request_->icapHistory();
- Must(h != NULL); // ICAPXaction::maybeLog calls only if there is a log
+ Must(h != nullptr); // ICAPXaction::maybeLog calls only if there is a log
al.icp.opcode = ICP_INVALID;
al.url = h->log_uri.termedBuf();
const Adaptation::Icap::ServiceRep &s = service();
virgin_msg = virgin_request_;
assert(virgin_msg != virgin.cause);
al.http.clientRequestSz.header = virgin_msg->hdr_sz;
- if (virgin_msg->body_pipe != NULL)
+ if (virgin_msg->body_pipe != nullptr)
al.http.clientRequestSz.payloadData = virgin_msg->body_pipe->producedSize();
// leave al.icap.bodyBytesRead negative if no body
// share the cross-transactional database records if needed
if (Adaptation::Config::masterx_shared_name) {
Adaptation::History::Pointer ah = request->adaptHistory(false);
- if (ah != NULL) {
+ if (ah != nullptr) {
String name, value;
if (ah->getXxRecord(name, value)) {
buf.appendf(SQUIDSTRINGPH ": " SQUIDSTRINGPH "\r\n", SQUIDSTRINGPRINT(name), SQUIDSTRINGPRINT(value));
buf.append(matched.rawContent(), matched.length());
buf.append("\r\n", 2);
Adaptation::History::Pointer ah = request->adaptHistory(false);
- if (ah != NULL) {
- if (ah->metaHeaders == NULL)
+ if (ah != nullptr) {
+ if (ah->metaHeaders == nullptr)
ah->metaHeaders = new NotePairs;
if (!ah->metaHeaders->hasPair(h->key(), matched))
ah->metaHeaders->add(h->key(), matched);
struct base64_encode_ctx ctx;
base64_encode_init(&ctx);
- const char *value = NULL;
- if (request->auth_user_request != NULL) {
+ const char *value = nullptr;
+ if (request->auth_user_request != nullptr) {
value = request->auth_user_request->username();
} else if (request->extacl_user.size() > 0) {
value = request->extacl_user.termedBuf();
if (state.serviceWaiting)
buf.append("U", 1);
- if (virgin.body_pipe != NULL)
+ if (virgin.body_pipe != nullptr)
buf.append("R", 1);
if (haveConnection() && !doneReading())
virginBodyWriting.plan();
// sign up as a body consumer
- Must(msg->body_pipe != NULL);
+ Must(msg->body_pipe != nullptr);
Must(msg->body_pipe == virgin.body_pipe);
Must(virgin.body_pipe->setConsumerIfNotLate(this));
Must(TheBackupLimit <= static_cast<size_t>(msg->body_pipe->buf().max_capacity));
} else {
debugs(93, 6, "does not expect virgin body");
- Must(msg->body_pipe == NULL);
+ Must(msg->body_pipe == nullptr);
checkConsuming();
}
}
bool Adaptation::Icap::ModXact::fillVirginHttpHeader(MemBuf &mb) const
{
- if (virgin.header == NULL)
+ if (virgin.header == nullptr)
return false;
virgin.header->firstLineBuf(mb);
{
Adaptation::Icap::ServiceRep::Pointer s =
dynamic_cast<Adaptation::Icap::ServiceRep*>(theService.getRaw());
- Must(s != NULL);
+ Must(s != nullptr);
return new Adaptation::Icap::ModXact(virgin.header, virgin.cause, al, s);
}
// r should never be NULL but we play safe; TODO: add Should()
if (r) {
Adaptation::Icap::History::Pointer h = r->icapHistory();
- if (h != NULL) {
+ if (h != nullptr) {
if (doStart)
h->start("ICAPModXactLauncher");
else
void Adaptation::Icap::OptXact::handleCommRead(size_t)
{
if (parseResponse()) {
- Must(icapReply != NULL);
+ Must(icapReply != nullptr);
// We read everything if there is no response body. If there is a body,
// we cannot parse it because we do not support any opt-body-types, so
// we leave readAll false which forces connection closure.
// al.cache.caddr = 0;
al.icap.reqMethod = Adaptation::methodOptions;
- if (icapReply != NULL && al.icap.bytesRead > icapReply->hdr_sz)
+ if (icapReply != nullptr && al.icap.bytesRead > icapReply->hdr_sz)
al.icap.bodyBytesRead = al.icap.bytesRead - icapReply->hdr_sz;
Adaptation::Icap::Xaction::finalizeLogInfo();
{
Adaptation::Icap::ServiceRep::Pointer s =
dynamic_cast<Adaptation::Icap::ServiceRep*>(theService.getRaw());
- Must(s != NULL);
+ Must(s != nullptr);
return new Adaptation::Icap::OptXact(s);
}
void Adaptation::Icap::Options::configure(const HttpReply *reply)
{
- error = NULL; // reset initial "unconfigured" value (or an old error?)
+ error = nullptr; // reset initial "unconfigured" value (or an old error?)
const HttpHeader *h = &reply->header;
/* Adaptation::Icap::Options::TransferList */
-Adaptation::Icap::Options::TransferList::TransferList(): extensions(NULL), name(NULL),
+Adaptation::Icap::Options::TransferList::TransferList(): extensions(nullptr), name(nullptr),
kind(xferNone)
{
};
foundStar = false;
const char *item;
- const char *pos = NULL;
+ const char *pos = nullptr;
int ilen;
while (strListGetItem(&buf, ',', &item, &ilen, &pos)) {
if (ilen == 1 && *item == '*')
Adaptation::Icap::ServiceRep::ServiceRep(const ServiceConfigPointer &svcCfg):
AsyncJob("Adaptation::Icap::ServiceRep"), Adaptation::Service(svcCfg),
- theOptions(NULL), theOptionsFetcher(0), theLastUpdate(0),
+ theOptions(nullptr), theOptionsFetcher(nullptr), theLastUpdate(0),
theBusyConns(0),
theAllWaiters(0),
connOverloadReported(false),
- theIdleConns(NULL),
- isSuspended(0), notifying(false),
+ theIdleConns(nullptr),
+ isSuspended(nullptr), notifying(false),
updateScheduled(false),
wasAnnouncedUp(true), // do not announce an "up" service at startup
isDetached(false)
{
setMaxConnections();
- theIdleConns = new IdleConnList("ICAP Service", NULL);
+ theIdleConns = new IdleConnList("ICAP Service", nullptr);
}
Adaptation::Icap::ServiceRep::~ServiceRep()
Client i = theNotificationWaiters.front();
theNotificationWaiters.pop_front();
ScheduleCallHere(i.callback);
- i.callback = NULL;
+ i.callback = nullptr;
--freed;
}
}
// note: we must notify even if we are invalidated
- Pointer us = NULL;
+ Pointer us = nullptr;
while (!theClients.empty()) {
Client i = theClients.back();
theClients.pop_back();
ScheduleCallHere(i.callback);
- i.callback = 0;
+ i.callback = nullptr;
}
notifying = false;
void Adaptation::Icap::ServiceRep::callWhenAvailable(AsyncCall::Pointer &cb, bool priority)
{
debugs(93,8, "ICAPServiceRep::callWhenAvailable");
- Must(cb!=NULL);
+ Must(cb!=nullptr);
Must(up());
Must(!theIdleConns->count()); // or we should not be waiting
void Adaptation::Icap::ServiceRep::callWhenReady(AsyncCall::Pointer &cb)
{
- Must(cb!=NULL);
+ Must(cb!=nullptr);
debugs(93,5, "Adaptation::Icap::Service is asked to call " << *cb <<
" when ready " << status());
delete theOptions;
theOptions = newOptions;
theSessionFailures.clear();
- isSuspended = 0;
+ isSuspended = nullptr;
theLastUpdate = squid_curtime;
checkOptions();
void Adaptation::Icap::ServiceRep::checkOptions()
{
- if (theOptions == NULL)
+ if (theOptions == nullptr)
return;
if (!theOptions->valid()) {
if (answer.kind == Answer::akError) {
debugs(93,3, "failed to fetch options " << status());
- handleNewOptions(0);
+ handleNewOptions(nullptr);
return;
}
debugs(93,5, "is interpreting new options " << status());
- Adaptation::Icap::Options *newOptions = NULL;
+ Adaptation::Icap::Options *newOptions = nullptr;
if (const HttpReply *r = dynamic_cast<const HttpReply*>(msg)) {
newOptions = new Adaptation::Icap::Options;
newOptions->configure(r);
clearAdaptation(theOptionsFetcher);
debugs(93,2, "ICAP probably failed to fetch options (" << e.what() <<
")" << status());
- handleNewOptions(0);
+ handleNewOptions(nullptr);
}
void Adaptation::Icap::ServiceRep::handleNewOptions(Adaptation::Icap::Options *newOptions)
Adaptation::Icap::Xaction::Xaction(const char *aTypeName, Adaptation::Icap::ServiceRep::Pointer &aService):
AsyncJob(aTypeName),
Adaptation::Initiate(aTypeName),
- icapRequest(NULL),
- icapReply(NULL),
+ icapRequest(nullptr),
+ icapReply(nullptr),
attempts(0),
theService(aService),
commEof(false),
Adaptation::Icap::ServiceRep &
Adaptation::Icap::Xaction::service()
{
- Must(theService != NULL);
+ Must(theService != nullptr);
return *theService;
}
Adaptation::Icap::ServiceRep &s = service();
- if (ia == NULL) {
+ if (ia == nullptr) {
debugs(44, DBG_IMPORTANT, "ERROR: ICAP: Unknown service host: " << s.cfg().host);
#if WHEN_IPCACHE_NBGETHOSTBYNAME_USES_ASYNC_CALLS
{
if (haveConnection()) {
- if (closer != NULL) {
+ if (closer != nullptr) {
comm_remove_close_handler(connection->fd, closer);
- closer = NULL;
+ closer = nullptr;
}
commUnsetConnTimeout(connection);
Adaptation::Icap::ServiceRep &s = service();
s.putConnection(connection, reuseConnection, reset, status());
- writer = NULL;
- reader = NULL;
- connection = NULL;
+ writer = nullptr;
+ reader = nullptr;
+ connection = nullptr;
}
}
void Adaptation::Icap::Xaction::noteCommWrote(const CommIoCbParams &io)
{
- Must(writer != NULL);
- writer = NULL;
+ Must(writer != nullptr);
+ writer = nullptr;
if (ignoreLastWrite) {
// a hack due to comm inability to cancel a pending write
connection->noteClosure();
connection = nullptr;
}
- closer = NULL;
+ closer = nullptr;
static const auto d = MakeNamedErrorDetail("ICAP_XACT_CLOSE");
detailError(d);
{
Must(haveConnection());
- if (reader != NULL || writer != NULL) {
+ if (reader != nullptr || writer != nullptr) {
// restart the timeout before each I/O
// XXX: why does Config.Timeout lacks a write timeout?
// TODO: service bypass status may differ from that of a transaction
// comm module read a portion of the ICAP response for us
void Adaptation::Icap::Xaction::noteCommRead(const CommIoCbParams &io)
{
- Must(reader != NULL);
- reader = NULL;
+ Must(reader != nullptr);
+ reader = nullptr;
Must(io.flag == Comm::OK);
void Adaptation::Icap::Xaction::cancelRead()
{
- if (reader != NULL) {
+ if (reader != nullptr) {
Must(haveConnection());
Comm::ReadCancel(connection->fd, reader);
- reader = NULL;
+ reader = nullptr;
}
}
bool Adaptation::Icap::Xaction::haveConnection() const
{
- return connection != NULL && connection->isOpen();
+ return connection != nullptr && connection->isOpen();
}
// initiator aborted
al.icap.request = icapRequest;
HTTPMSGLOCK(al.icap.request);
- if (icapReply != NULL) {
+ if (icapReply != nullptr) {
al.icap.reply = icapReply.getRaw();
HTTPMSGLOCK(al.icap.reply);
al.icap.resStatus = icapReply->sline.status();
if (haveConnection()) {
buf.appendf("FD %d", connection->fd);
- if (writer != NULL)
+ if (writer != nullptr)
buf.append("w", 1);
- if (reader != NULL)
+ if (reader != nullptr)
buf.append("r", 1);
buf.append(";", 1);
if (haveConnection() && commEof)
buf.appendf("Comm(%d)", connection->fd);
- if (stopReason != NULL)
+ if (stopReason != nullptr)
buf.append("Stopped", 7);
}
for (log = Config.Log.icaplogs; log; log = log->next) {
if (log->logfile) {
logfileClose(log->logfile);
- log->logfile = NULL;
+ log->logfile = nullptr;
}
}
}
void icapLogLog(AccessLogEntry::Pointer &al)
{
if (IcapLogfileStatus == LOG_ENABLE) {
- ACLFilledChecklist checklist(NULL, al->adapted_request, NULL);
+ ACLFilledChecklist checklist(nullptr, al->adapted_request, nullptr);
if (al->reply) {
checklist.reply = al->reply.getRaw();
HTTPMSGLOCK(checklist.reply);
next(),
s(),
transport(AnyP::PROTO_HTTP,1,1), // "Squid is an HTTP proxy", etc.
- name(NULL),
- defaultsite(NULL),
+ name(nullptr),
+ defaultsite(nullptr),
flags(),
allow_direct(false),
vhost(false),
{
if (Comm::IsConnOpen(listenConn)) {
listenConn->close();
- listenConn = NULL;
+ listenConn = nullptr;
}
safe_free(name);
LOCAL_ARRAY(char, login, MAX_URL);
LOCAL_ARRAY(char, foundHost, MAX_URL);
LOCAL_ARRAY(char, urlpath, MAX_URL);
- char *t = NULL;
- char *q = NULL;
+ char *t = nullptr;
+ char *q = nullptr;
int foundPort;
int l;
int i;
/* Is there any login information? (we should eventually parse it above) */
t = strrchr(foundHost, '@');
- if (t != NULL) {
+ if (t != nullptr) {
strncpy((char *) login, (char *) foundHost, sizeof(login)-1);
login[sizeof(login)-1] = '\0';
t = strrchr(login, '@');
/* RFC 2732 states IPv6 "SHOULD" be bracketed. allowing for times when its not. */
/* RFC 3986 'update' simply modifies this to an "is" with no emphasis at all! */
/* therefore we MUST accept the case where they are not bracketed at all. */
- t = NULL;
+ t = nullptr;
}
}
HttpRequest *request = checklist->request;
Http::HdrType headertype;
- if (NULL == request) {
+ if (nullptr == request) {
fatal ("requiresRequest SHOULD have been true for this ACL!!");
return ACCESS_DENIED;
} else if (request->flags.sslBumped) {
debugs(28, 5, "SslBumped request: It is an encapsulated request do not authenticate");
- checklist->auth_user_request = checklist->conn() != NULL ? checklist->conn()->getAuth() : request->auth_user_request;
- if (checklist->auth_user_request != NULL)
+ checklist->auth_user_request = checklist->conn() != nullptr ? checklist->conn()->getAuth() : request->auth_user_request;
+ if (checklist->auth_user_request != nullptr)
return ACCESS_ALLOWED;
else
return ACCESS_DENIED;
case ACCESS_ALLOWED:
// check for a match
ti = match(checklist->auth_user_request, checklist->src_addr);
- checklist->auth_user_request = NULL;
+ checklist->auth_user_request = nullptr;
return ti;
case ACCESS_DENIED:
debugs(28, 3, "checking password via authenticator");
/* make sure someone created auth_user_request for us */
- assert(checklist->auth_user_request != NULL);
+ assert(checklist->auth_user_request != nullptr);
assert(checklist->auth_user_request->valid());
checklist->auth_user_request->start(checklist->request, checklist->al, LookupDone, checklist);
}
{
ACLFilledChecklist *checklist = Filled(static_cast<ACLChecklist*>(data));
- if (checklist->auth_user_request == NULL || !checklist->auth_user_request->valid() || checklist->conn() == NULL) {
+ if (checklist->auth_user_request == nullptr || !checklist->auth_user_request->valid() || checklist->conn() == nullptr) {
/* credentials could not be checked either way
* restart the whole process */
/* OR the connection was closed, there's no way to continue */
- checklist->auth_user_request = NULL;
+ checklist->auth_user_request = nullptr;
- if (checklist->conn() != NULL) {
- checklist->conn()->setAuth(NULL, "proxy_auth ACL failure");
+ if (checklist->conn() != nullptr) {
+ checklist->conn()->setAuth(nullptr, "proxy_auth ACL failure");
}
}
ACLProxyAuth::matchForCache(ACLChecklist *cl)
{
ACLFilledChecklist *checklist = Filled(cl);
- assert (checklist->auth_user_request != NULL);
+ assert (checklist->auth_user_request != nullptr);
return data->match(checklist->auth_user_request->username());
}
}
/* check to see if we have matched the user-acl before */
int result = cacheMatchAcl(&checklist->auth_user_request->user()->proxy_match_cache, checklist);
- checklist->auth_user_request = NULL;
+ checklist->auth_user_request = nullptr;
return result;
}
public:
QueueNode(Auth::UserRequest *aRequest, AUTHCB *aHandler, void *aData) :
- next(NULL),
+ next(nullptr),
auth_user_request(aRequest),
handler(aHandler),
data(cbdataReference(aData)) {}
cbdataReferenceDone(data);
while (next) {
QueueNode *tmp = next->next;
- next->next = NULL;
+ next->next = nullptr;
delete next;
next = tmp;
};
#include "auth/SchemeConfig.h"
#include "globals.h"
-std::vector<Auth::Scheme::Pointer> *Auth::Scheme::_Schemes = NULL;
+std::vector<Auth::Scheme::Pointer> *Auth::Scheme::_Schemes = nullptr;
void
Auth::Scheme::AddScheme(Auth::Scheme::Pointer instance)
return *i;
}
- return Auth::Scheme::Pointer(NULL);
+ return Auth::Scheme::Pointer(nullptr);
}
std::vector<Auth::Scheme::Pointer> &
Auth::UserRequest::Pointer
Auth::SchemeConfig::CreateAuthUser(const char *proxy_auth, AccessLogEntry::Pointer &al)
{
- assert(proxy_auth != NULL);
+ assert(proxy_auth != nullptr);
debugs(29, 9, "header = '" << proxy_auth << "'");
Auth::SchemeConfig *config = Find(proxy_auth);
- if (config == NULL || !config->active()) {
+ if (config == nullptr || !config->active()) {
debugs(29, (shutting_down?3:DBG_IMPORTANT), (shutting_down?"":"WARNING: ") <<
"Unsupported or unconfigured/inactive proxy-auth scheme, '" << proxy_auth << "'");
- return NULL;
+ return nullptr;
}
static MemBuf rmb;
rmb.reset();
return scheme;
}
- return NULL;
+ return nullptr;
}
Auth::SchemeConfig *
keyExtras = nlf;
- if (char *t = strtok(NULL, w_space)) {
+ if (char *t = strtok(nullptr, w_space)) {
debugs(29, DBG_CRITICAL, "FATAL: Unexpected argument '" << t << "' after request_format specification");
self_destruct();
}
wordlist *list = authenticateProgram;
storeAppendPrintf(entry, "%s %s", name, schemeType);
- while (list != NULL) {
+ while (list != nullptr) {
storeAppendPrintf(entry, " %s", list->key);
list = list->next;
}
Auth::SchemeConfig::done()
{
delete keyExtras;
- keyExtras = NULL;
+ keyExtras = nullptr;
keyExtrasLine.clean();
}
handler(h) {}
~StateData() {
- auth_user_request = NULL;
+ auth_user_request = nullptr;
cbdataReferenceDone(data);
}
username_(nullptr),
requestRealm_(aRequestRealm)
{
- proxy_match_cache.head = proxy_match_cache.tail = NULL;
- ip_list.head = ip_list.tail = NULL;
+ proxy_match_cache.head = proxy_match_cache.tail = nullptr;
+ ip_list.head = ip_list.tail = nullptr;
debugs(29, 5, "Initialised auth_user '" << this << "'.");
}
/* absorb the list of IP address sources (for max_user_ip controls) */
AuthUserIP *new_ipdata;
- while (from->ip_list.head != NULL) {
+ while (from->ip_list.head != nullptr) {
new_ipdata = static_cast<AuthUserIP *>(from->ip_list.head->data);
/* If this IP has expired - ignore the expensive merge actions. */
assert(!username_);
username_ = xstrdup(aString);
// NP: param #2 is working around a c_str() data-copy performance regression
- userKey_ = BuildUserKey(username_, (!requestRealm_.isEmpty() ? requestRealm_.c_str() : NULL));
+ userKey_ = BuildUserKey(username_, (!requestRealm_.isEmpty() ? requestRealm_.c_str() : nullptr));
} else {
safe_free(username_);
userKey_.clear();
char const *
Auth::UserRequest::username() const
{
- if (user() != NULL)
+ if (user() != nullptr)
return user()->username();
else
- return NULL;
+ return nullptr;
}
/**** PUBLIC FUNCTIONS (ALL GENERIC!) ****/
{
debugs(29, 9, "Validating Auth::UserRequest '" << this << "'.");
- if (user() == NULL) {
+ if (user() == nullptr) {
debugs(29, 4, "No associated Auth::User data");
return false;
}
}
Auth::UserRequest::UserRequest():
- _auth_user(NULL),
- message(NULL),
+ _auth_user(nullptr),
+ message(nullptr),
lastReply(AUTH_ACL_CANNOT_AUTHENTICATE)
{
debugs(29, 5, "initialised request " << this);
assert(LockCount()==0);
debugs(29, 5, "freeing request " << this);
- if (user() != NULL) {
+ if (user() != nullptr) {
/* release our references to the user credentials */
- user(NULL);
+ user(nullptr);
}
safe_free(message);
char const *
Auth::UserRequest::denyMessage(char const * const default_message) const
{
- if (getDenyMessage() == NULL)
+ if (getDenyMessage() == nullptr)
return default_message;
return getDenyMessage();
void
authenticateAuthUserRequestClearIp(Auth::UserRequest::Pointer auth_user_request)
{
- if (auth_user_request != NULL)
+ if (auth_user_request != nullptr)
auth_user_request->user()->clearIp();
}
int
authenticateAuthUserRequestIPCount(Auth::UserRequest::Pointer auth_user_request)
{
- assert(auth_user_request != NULL);
- assert(auth_user_request->user() != NULL);
+ assert(auth_user_request != nullptr);
+ assert(auth_user_request->user() != nullptr);
return auth_user_request->user()->ipcount;
}
int
authenticateUserAuthenticated(Auth::UserRequest::Pointer auth_user_request)
{
- if (auth_user_request == NULL || !auth_user_request->valid())
+ if (auth_user_request == nullptr || !auth_user_request->valid())
return 0;
return auth_user_request->authenticated();
Auth::Direction
Auth::UserRequest::direction()
{
- if (user() == NULL)
+ if (user() == nullptr)
return Auth::CRED_ERROR; // No credentials. Should this be a CHALLENGE instead?
if (authenticateUserAuthenticated(this))
Auth::UserRequest::connLastHeader()
{
fatal("Auth::UserRequest::connLastHeader should always be overridden by conn based auth schemes");
- return NULL;
+ return nullptr;
}
/*
static void
authenticateAuthenticateUser(Auth::UserRequest::Pointer auth_user_request, HttpRequest * request, ConnStateData * conn, Http::HdrType type)
{
- assert(auth_user_request.getRaw() != NULL);
+ assert(auth_user_request.getRaw() != nullptr);
auth_user_request->authenticate(request, conn, type);
}
{
Auth::UserRequest::Pointer res;
- if (auth_user_request != NULL)
+ if (auth_user_request != nullptr)
res = auth_user_request;
- else if (request != NULL && request->auth_user_request != NULL)
+ else if (request != nullptr && request->auth_user_request != nullptr)
res = request->auth_user_request;
- else if (conn != NULL)
+ else if (conn != nullptr)
res = conn->getAuth();
// attach the credential notes from helper to the transaction
- if (request != NULL && res != NULL && res->user() != NULL) {
+ if (request != nullptr && res != nullptr && res->user() != nullptr) {
// XXX: we have no access to the transaction / AccessLogEntry so can't SyncNotes().
// workaround by using anything already set in HttpRequest
// OR use new and rely on a later Sync copying these to AccessLogEntry
*/
/* a) can we find other credentials to use? and b) are they logged in already? */
- if (proxy_auth == NULL && !authenticateUserAuthenticated(authTryGetUser(*auth_user_request,conn,request))) {
+ if (proxy_auth == nullptr && !authenticateUserAuthenticated(authTryGetUser(*auth_user_request,conn,request))) {
/* no header or authentication failed/got corrupted - restart */
debugs(29, 4, "No Proxy-Auth header and no working alternative. Requesting auth header.");
/* something wrong with the AUTH credentials. Force a new attempt */
/* connection auth we must reset on auth errors */
- if (conn != NULL) {
- conn->setAuth(NULL, "HTTP request missing credentials");
+ if (conn != nullptr) {
+ conn->setAuth(nullptr, "HTTP request missing credentials");
}
- *auth_user_request = NULL;
+ *auth_user_request = nullptr;
return AUTH_ACL_CHALLENGE;
}
* No check for function required in the if: its compulsory for conn based
* auth modules
*/
- if (proxy_auth && conn != NULL && conn->getAuth() != NULL &&
+ if (proxy_auth && conn != nullptr && conn->getAuth() != nullptr &&
authenticateUserAuthenticated(conn->getAuth()) &&
- conn->getAuth()->connLastHeader() != NULL &&
+ conn->getAuth()->connLastHeader() != nullptr &&
strcmp(proxy_auth, conn->getAuth()->connLastHeader())) {
debugs(29, 2, "WARNING: DUPLICATE AUTH - authentication header on already authenticated connection!. AU " <<
conn->getAuth() << ", Current user '" <<
/* This should _only_ ever occur on the first pass through
* authenticateAuthenticate
*/
- assert(*auth_user_request == NULL);
- conn->setAuth(NULL, "changed credentials token");
+ assert(*auth_user_request == nullptr);
+ conn->setAuth(nullptr, "changed credentials token");
}
/* we have a proxy auth header and as far as we know this connection has
* not had bungled connection oriented authentication happen on it. */
debugs(29, 9, "header " << (proxy_auth ? proxy_auth : "-") << ".");
- if (*auth_user_request == NULL) {
- if (conn != NULL) {
+ if (*auth_user_request == nullptr) {
+ if (conn != nullptr) {
debugs(29, 9, "This is a new checklist test on:" << conn->clientConnection);
}
- if (proxy_auth && request->auth_user_request == NULL && conn != NULL && conn->getAuth() != NULL) {
+ if (proxy_auth && request->auth_user_request == nullptr && conn != nullptr && conn->getAuth() != nullptr) {
Auth::SchemeConfig * scheme = Auth::SchemeConfig::Find(proxy_auth);
- if (conn->getAuth()->user() == NULL || conn->getAuth()->user()->config != scheme) {
+ if (conn->getAuth()->user() == nullptr || conn->getAuth()->user()->config != scheme) {
debugs(29, DBG_IMPORTANT, "WARNING: Unexpected change of authentication scheme from '" <<
- (conn->getAuth()->user()!=NULL?conn->getAuth()->user()->config->type():"[no user]") <<
+ (conn->getAuth()->user()!=nullptr?conn->getAuth()->user()->config->type():"[no user]") <<
"' to '" << proxy_auth << "' (client " <<
src_addr << ")");
- conn->setAuth(NULL, "changed auth scheme");
+ conn->setAuth(nullptr, "changed auth scheme");
}
}
- if (request->auth_user_request == NULL && (conn == NULL || conn->getAuth() == NULL)) {
+ if (request->auth_user_request == nullptr && (conn == nullptr || conn->getAuth() == nullptr)) {
/* beginning of a new request check */
debugs(29, 4, "No connection authentication type");
*auth_user_request = Auth::SchemeConfig::CreateAuthUser(proxy_auth, al);
- if (*auth_user_request == NULL)
+ if (*auth_user_request == nullptr)
return AUTH_ACL_CHALLENGE;
else if (!(*auth_user_request)->valid()) {
/* the decode might have left a username for logging, or a message to
request->auth_user_request = *auth_user_request;
}
- *auth_user_request = NULL;
+ *auth_user_request = nullptr;
return AUTH_ACL_CHALLENGE;
}
- } else if (request->auth_user_request != NULL) {
+ } else if (request->auth_user_request != nullptr) {
*auth_user_request = request->auth_user_request;
} else {
- assert (conn != NULL);
- if (conn->getAuth() != NULL) {
+ assert (conn != nullptr);
+ if (conn->getAuth() != nullptr) {
*auth_user_request = conn->getAuth();
} else {
/* failed connection based authentication */
debugs(29, 4, "Auth user request " << *auth_user_request << " conn-auth missing and failed to authenticate.");
- *auth_user_request = NULL;
+ *auth_user_request = nullptr;
return AUTH_ACL_CHALLENGE;
}
}
case Auth::CRED_CHALLENGE:
- if (request->auth_user_request == NULL) {
+ if (request->auth_user_request == nullptr) {
request->auth_user_request = *auth_user_request;
}
*auth_user_request = nullptr;
case Auth::CRED_ERROR:
/* this ACL check is finished. */
- *auth_user_request = NULL;
+ *auth_user_request = nullptr;
return AUTH_ACL_CHALLENGE;
case Auth::CRED_LOOKUP:
}
}
- *auth_user_request = NULL;
+ *auth_user_request = nullptr;
return AUTH_ACL_CHALLENGE;
}
// otherwise fallthrough to acceptance.
/* copy username to request for logging on client-side */
/* the credentials are correct at this point */
- if (request->auth_user_request == NULL) {
+ if (request->auth_user_request == nullptr) {
request->auth_user_request = *auth_user_request;
authenticateAuthUserRequestSetIp(*auth_user_request, src_addr);
}
// If we have already been called, return the cached value
Auth::UserRequest::Pointer t = authTryGetUser(*aUR, conn, request);
- if (t != NULL && t->lastReply != AUTH_ACL_CANNOT_AUTHENTICATE && t->lastReply != AUTH_ACL_HELPER) {
- if (*aUR == NULL)
+ if (t != nullptr && t->lastReply != AUTH_ACL_CANNOT_AUTHENTICATE && t->lastReply != AUTH_ACL_HELPER) {
+ if (*aUR == nullptr)
*aUR = t;
- if (request->auth_user_request == NULL && t->lastReply == AUTH_AUTHENTICATED) {
+ if (request->auth_user_request == nullptr && t->lastReply == AUTH_AUTHENTICATED) {
request->auth_user_request = t;
}
return t->lastReply;
// auth process may have changed the UserRequest we are dealing with
t = authTryGetUser(*aUR, conn, request);
- if (t != NULL && result != AUTH_ACL_CANNOT_AUTHENTICATE && result != AUTH_ACL_HELPER)
+ if (t != nullptr && result != AUTH_ACL_CANNOT_AUTHENTICATE && result != AUTH_ACL_HELPER)
t->lastReply = result;
return result;
schemesConfig(HttpRequest *request, HttpReply *rep)
{
if (!Auth::TheConfig.schemeLists.empty() && Auth::TheConfig.schemeAccess) {
- ACLFilledChecklist ch(NULL, request, NULL);
+ ACLFilledChecklist ch(nullptr, request, nullptr);
ch.reply = rep;
HTTPMSGLOCK(ch.reply);
const auto answer = ch.fastCheck(Auth::TheConfig.schemeAccess);
/* this is a authenticate-needed response */
{
- if (auth_user_request != NULL && auth_user_request->direction() == Auth::CRED_CHALLENGE)
+ if (auth_user_request != nullptr && auth_user_request->direction() == Auth::CRED_CHALLENGE)
/* add the scheme specific challenge header to the response */
auth_user_request->user()->config->fixHeader(auth_user_request, rep, type, request);
else {
Auth::ConfigVector &configs = schemesConfig(request, rep);
for (auto *scheme : configs) {
if (scheme->active()) {
- if (auth_user_request != NULL && auth_user_request->scheme()->type() == scheme->type())
+ if (auth_user_request != nullptr && auth_user_request->scheme()->type() == scheme->type())
scheme->fixHeader(auth_user_request, rep, type, request);
else
- scheme->fixHeader(NULL, rep, type, request);
+ scheme->fixHeader(nullptr, rep, type, request);
} else
debugs(29, 4, "Configured scheme " << scheme->type() << " not Active");
}
* allow protocol specific headers to be _added_ to the existing
* response - currently Digest or Negotiate auth
*/
- if (auth_user_request != NULL) {
+ if (auth_user_request != nullptr) {
auth_user_request->addAuthenticationInfoHeader(rep, accelerated);
if (auth_user_request->lastReply != AUTH_AUTHENTICATED)
auth_user_request->lastReply = AUTH_ACL_CANNOT_AUTHENTICATE;
debugs(29, 5, "Assembled line to send :" << mb.content());
return mb.content();
}
- return NULL;
+ return nullptr;
}
void
*/
void start(HttpRequest *request, AccessLogEntry::Pointer &al, AUTHCB *handler, void *data);
- char const * denyMessage(char const * const default_message = NULL) const;
+ char const * denyMessage(char const * const default_message = nullptr) const;
/** Possibly overridable in future */
void setDenyMessage(char const *);
/* Basic Scheme */
static AUTHSSTATS authenticateBasicStats;
-helper *basicauthenticators = NULL;
+helper *basicauthenticators = nullptr;
static int authbasic_initialised = 0;
bool
Auth::Basic::Config::configured() const
{
- if ((authenticateProgram != NULL) && (authenticateChildren.n_max != 0) && !realm.isEmpty()) {
+ if ((authenticateProgram != nullptr) && (authenticateChildren.n_max != 0) && !realm.isEmpty()) {
debugs(29, 9, "returning configured");
return true;
}
}
delete basicauthenticators;
- basicauthenticators = NULL;
+ basicauthenticators = nullptr;
if (authenticateProgram)
wordlistDestroy(&authenticateProgram);
Auth::User::Pointer lb;
/* permitted because local_basic is purely local function scope. */
- Auth::Basic::User *local_basic = NULL;
+ Auth::Basic::User *local_basic = nullptr;
char *separator = strchr(cleartext, ':');
Tolower(cleartext);
local_basic->username(cleartext);
- if (local_basic->passwd == NULL) {
+ if (local_basic->passwd == nullptr) {
debugs(29, 4, "no password in proxy authorization header '" << proxy_auth << "'");
auth_user_request->setDenyMessage("no password was present in the HTTP [proxy-]authorization header. This is most likely a browser bug");
} else {
lb->addToNameCache();
auth_user = lb;
- assert(auth_user != NULL);
+ assert(auth_user != nullptr);
} else {
/* replace the current cached password with the new one */
Auth::Basic::User *basic_auth = dynamic_cast<Auth::Basic::User *>(auth_user.getRaw());
if (authenticateProgram) {
authbasic_initialised = 1;
- if (basicauthenticators == NULL)
+ if (basicauthenticators == nullptr)
basicauthenticators = new helper("basicauthenticator");
basicauthenticators->cmdline = authenticateProgram;
/* Global options */
static const char *basedn;
-static const char *searchfilter = NULL;
-static const char *binddn = NULL;
-static const char *bindpasswd = NULL;
+static const char *searchfilter = nullptr;
+static const char *binddn = nullptr;
+static const char *bindpasswd = nullptr;
static const char *userattr = "uid";
-static const char *passwdattr = NULL;
+static const char *passwdattr = nullptr;
static int searchscope = LDAP_SCOPE_SUBTREE;
static int persistent = 0;
static int bind_once = 0;
static LDAP *
open_ldap_connection(const char *ldapServer, int port)
{
- LDAP *ld = NULL;
+ LDAP *ld = nullptr;
#if HAS_URI_SUPPORT
- if (strstr(ldapServer, "://") != NULL) {
+ if (strstr(ldapServer, "://") != nullptr) {
int rc = ldap_initialize(&ld, ldapServer);
if (rc != LDAP_SUCCESS) {
fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer);
}
} else
#endif
- if ((ld = ldap_init(ldapServer, port)) == NULL) {
+ if ((ld = ldap_init(ldapServer, port)) == nullptr) {
fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n",
ldapServer, port);
exit(EXIT_FAILURE);
if (version != LDAP_VERSION3) {
fprintf(stderr, "TLS requires LDAP version 3\n");
exit(EXIT_FAILURE);
- } else if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS) {
+ } else if (ldap_start_tls_s(ld, nullptr, nullptr) != LDAP_SUCCESS) {
fprintf(stderr, "Could not Activate TLS connection\n");
exit(EXIT_FAILURE);
}
{
char buf[1024];
char *user, *passwd;
- char *ldapServer = NULL;
- LDAP *ld = NULL;
+ char *ldapServer = nullptr;
+ LDAP *ld = nullptr;
int tryagain;
int port = LDAP_PORT;
- setbuf(stdout, NULL);
+ setbuf(stdout, nullptr);
while (argc > 1 && argv[1][0] == '-') {
const char *value = "";
}
#endif
- while (fgets(buf, sizeof(buf), stdin) != NULL) {
+ while (fgets(buf, sizeof(buf), stdin) != nullptr) {
user = strtok(buf, " \r\n");
- passwd = strtok(NULL, "\r\n");
+ passwd = strtok(nullptr, "\r\n");
if (!user) {
SEND_ERR(HLP_MSG("Missing username"));
SEND_ERR(HLP_MSG("Invalid username"));
continue;
}
- tryagain = (ld != NULL);
+ tryagain = (ld != nullptr);
recover:
- if (ld == NULL && persistent)
+ if (ld == nullptr && persistent)
ld = open_ldap_connection(ldapServer, port);
if (checkLDAP(ld, user, passwd, ldapServer, port) != 0) {
const auto e = squid_ldap_errno(ld);
if (tryagain && e != LDAP_INVALID_CREDENTIALS) {
tryagain = 0;
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
goto recover;
}
if (LDAP_SECURITY_ERROR(e))
}
if (ld && (squid_ldap_errno(ld) != LDAP_SUCCESS && squid_ldap_errno(ld) != LDAP_INVALID_CREDENTIALS)) {
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
}
}
if (ld)
{
char dn[1024];
int ret = 0;
- LDAP *bind_ld = NULL;
+ LDAP *bind_ld = nullptr;
if (!*password) {
/* LDAP can't bind with a blank password. Seen as "anonymous"
if (searchfilter) {
char filter[16384];
char escaped_login[1024];
- LDAPMessage *res = NULL;
+ LDAPMessage *res = nullptr;
LDAPMessage *entry;
- char *searchattr[] = {(char *)LDAP_NO_ATTRS, NULL};
+ char *searchattr[] = {(char *)LDAP_NO_ATTRS, nullptr};
char *userdn;
int rc;
LDAP *search_ld = persistent_ld;
if (ret == 0 && (!binddn || !bind_once || passwdattr)) {
/* Reuse the search connection for comparing the user password attribute */
bind_ld = search_ld;
- search_ld = NULL;
+ search_ld = nullptr;
}
search_done:
if (res) {
ldap_msgfree(res);
- res = NULL;
+ res = nullptr;
}
if (search_ld && search_ld != persistent_ld) {
ldap_unbind(search_ld);
- search_ld = NULL;
+ search_ld = nullptr;
}
if (ret != 0)
return ret;
ret = 1;
if (bind_ld != persistent_ld) {
ldap_unbind(bind_ld);
- bind_ld = NULL;
+ bind_ld = nullptr;
}
return ret;
}
readSecret(const char *filename)
{
char buf[BUFSIZ];
- char *e = NULL;
+ char *e = nullptr;
FILE *f;
- char *passwd = NULL;
+ char *passwd = nullptr;
if (!(f = fopen(filename, "r"))) {
fprintf(stderr, PROGRAM_NAME " ERROR: Can not read secret file %s\n", filename);
}
unsigned int lineCount = 0;
buf[HELPER_INPUT_BUFFER-1] = '\0';
- while (fgets(buf, sizeof(buf)-1, f) != NULL) {
+ while (fgets(buf, sizeof(buf)-1, f) != nullptr) {
++lineCount;
if ((buf[0] == '#') || (buf[0] == ' ') || (buf[0] == '\t') ||
(buf[0] == '\n'))
continue;
user = strtok(buf, ":\n\r");
- if (user == NULL) {
+ if (user == nullptr) {
fprintf(stderr, "ERROR: Missing user name at %s line %d\n", passwdfile, lineCount);
continue;
}
- passwd = strtok(NULL, ":\n\r");
+ passwd = strtok(nullptr, ":\n\r");
if ((strlen(user) > 0) && passwd) {
usermap[user] = passwd;
}
time_t change_time = -1;
char buf[HELPER_INPUT_BUFFER];
char *user, *passwd, *p;
- setbuf(stdout, NULL);
+ setbuf(stdout, nullptr);
if (argc != 2) {
fprintf(stderr, "Usage: ncsa_auth <passwordfile>\n");
exit(EXIT_FAILURE);
fprintf(stderr, "FATAL: cannot stat %s\n", argv[1]);
exit(EXIT_FAILURE);
}
- while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL) {
- if ((p = strchr(buf, '\n')) != NULL)
+ while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != nullptr) {
+ if ((p = strchr(buf, '\n')) != nullptr)
*p = '\0'; /* strip \n */
if (stat(argv[1], &sb) == 0) {
if (sb.st_mtime != change_time) {
change_time = sb.st_mtime;
}
}
- if ((user = strtok(buf, " ")) == NULL) {
+ if ((user = strtok(buf, " ")) == nullptr) {
SEND_ERR("");
continue;
}
- if ((passwd = strtok(NULL, "")) == NULL) {
+ if ((passwd = strtok(nullptr, "")) == nullptr) {
SEND_ERR("");
continue;
}
std::string stored_pass = userpassIterator->second;
const char *salted = stored_pass.c_str(); // locally stored version contains salt etc.
- char *crypted = NULL;
+ char *crypted = nullptr;
#if HAVE_CRYPT
size_t passwordLength = strlen(passwd);
// Bug 3831: given algorithms more secure than DES crypt() does not truncate, so we can ignore the bug 3107 length checks below
char *user, *passwd, *p;
char *nispasswd;
- setbuf(stdout, NULL);
+ setbuf(stdout, nullptr);
if (argc != 3) {
fprintf(stderr, "Usage: basic_nis_auth <domainname> <nis map for password>\n");
nisdomain = argv[1];
nismap = argv[2];
- while (fgets(buf, 256, stdin) != NULL) {
- if ((p = strchr(buf, '\n')) != NULL)
+ while (fgets(buf, 256, stdin) != nullptr) {
+ if ((p = strchr(buf, '\n')) != nullptr)
*p = '\0'; /* strip \n */
- if ((user = strtok(buf, " ")) == NULL) {
+ if ((user = strtok(buf, " ")) == nullptr) {
printf("ERR\n");
continue;
}
- if ((passwd = strtok(NULL, "")) == NULL) {
+ if ((passwd = strtok(nullptr, "")) == nullptr) {
printf("ERR\n");
continue;
}
}
#if HAVE_CRYPT
- char *crypted = NULL;
+ char *crypted = nullptr;
if ((crypted = crypt(passwd, nispasswd)) && strcmp(nispasswd, crypted) == 0) {
/* All ok !, thanks... */
printf("OK\n");
char *
get_nis_password(char *user, char *nisdomain, char *nismap)
{
- static char *val = NULL;
- char *password = NULL;
+ static char *val = nullptr;
+ char *password = nullptr;
int vallen, res;
#ifdef DEBUG
/* Free last entry */
if (val) {
free(val);
- val = NULL;
+ val = nullptr;
}
/* Get NIS entry */
case NO_YPERR:
/* username = */
(void) strtok(val, ":");
- password = strtok(NULL, ",:");
+ password = strtok(nullptr, ",:");
return password;
case YPERR_YPBIND:
syslog(LOG_ERR, "Squid Authentication through ypbind failure: can't communicate with ypbind");
- return NULL;
+ return nullptr;
case YPERR_KEY: /* No such key in map */
- return NULL;
+ return nullptr;
default:
- return NULL;
+ return nullptr;
}
}
time_since(const struct timeval *when)
{
struct timeval now;
- gettimeofday(&now, NULL);
+ gettimeofday(&now, nullptr);
return timeval_diff(when, &now);
}
static void
random_vector(char *aVector)
{
- static std::mt19937 mt(time(0));
+ static std::mt19937 mt(time(nullptr));
static xuniform_int_distribution<uint8_t> dist;
for (int i = 0; i < AUTH_VECTOR_LEN; ++i)
char line[MAXLINE];
int srv = 0, crt = 0;
- if ((cf = fopen(cfname, "r")) == NULL) {
+ if ((cf = fopen(cfname, "r")) == nullptr) {
perror(cfname);
return -1;
}
- while (fgets(line, MAXLINE, cf) != NULL) {
+ while (fgets(line, MAXLINE, cf) != nullptr) {
if (!memcmp(line, "server", 6))
srv = sscanf(line, "server %s", server);
if (!memcmp(line, "secret", 6))
++src;
tmp[1] = *src;
++src;
- *dst = strtol(tmp, NULL, 16);
+ *dst = strtol(tmp, nullptr, 16);
++dst;
} else {
*dst = *src;
/*
* Send the request we've built.
*/
- gettimeofday(&sent, NULL);
+ gettimeofday(&sent, nullptr);
if (send(socket_fd, (char *) auth, total_length, 0) < 0) {
int xerrno = errno;
// EAGAIN is expected at high traffic, just retry
}
FD_ZERO(&readfds);
FD_SET(socket_fd, &readfds);
- if (select(socket_fd + 1, &readfds, NULL, NULL, &tv) == 0) /* Select timeout */
+ if (select(socket_fd + 1, &readfds, nullptr, nullptr, &tv) == 0) /* Select timeout */
break;
salen = sizeof(saremote);
len = recvfrom(socket_fd, recv_buffer, sizeof(i_recv_buffer),
char passwd[MAXPASS];
char *ptr;
char buf[HELPER_INPUT_BUFFER];
- const char *cfname = NULL;
+ const char *cfname = nullptr;
int err = 0;
socklen_t salen;
int c;
}
}
/* make standard output line buffered */
- if (setvbuf(stdout, NULL, _IOLBF, 0) != 0)
+ if (setvbuf(stdout, nullptr, _IOLBF, 0) != 0)
exit(EXIT_FAILURE);
if (cfname) {
* Open a connection to the server.
*/
svp = getservbyname(svc_name, "udp");
- if (svp != NULL)
+ if (svp != nullptr)
svc_port = ntohs((unsigned short) svp->s_port);
else
svc_port = atoi(svc_name);
}
#endif
nas_ipaddr = ntohl(salocal.sin_addr.s_addr);
- while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL) {
+ while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != nullptr) {
char *end;
/* protect me form to long lines */
- if ((end = strchr(buf, '\n')) == NULL) {
+ if ((end = strchr(buf, '\n')) == nullptr) {
err = 1;
continue;
}
ptr = buf;
while (isspace(*ptr))
++ptr;
- if ((end = strchr(ptr, ' ')) == NULL) {
+ if ((end = strchr(ptr, ' ')) == nullptr) {
SEND_ERR("No password");
continue;
}
if (good_ipaddr(host) == 0) {
return(ipstr2long(host));
- } else if ((hp = gethostbyname(host)) == (struct hostent *)NULL) {
+ } else if ((hp = gethostbyname(host)) == (struct hostent *)nullptr) {
return((uint32_t)0);
}
return(ntohl(*(uint32_t *)hp->h_addr));
#endif
int rc;
- sasl_conn_t *conn = NULL;
+ sasl_conn_t *conn = nullptr;
/* make standard output line buffered */
- setvbuf(stdout, NULL, _IOLBF, 0);
+ setvbuf(stdout, nullptr, _IOLBF, 0);
- rc = sasl_server_init( NULL, APP_NAME_SASL );
+ rc = sasl_server_init( nullptr, APP_NAME_SASL );
if ( rc != SASL_OK ) {
- fprintf(stderr, "FATAL: %d %s\n", rc, sasl_errstring(rc, NULL, NULL ));
+ fprintf(stderr, "FATAL: %d %s\n", rc, sasl_errstring(rc, nullptr, nullptr ));
exit(EXIT_FAILURE);
}
#if SASL_VERSION_MAJOR < 2
rc = sasl_server_new( APP_NAME_SASL, NULL, NULL, NULL, 0, &conn );
#else
- rc = sasl_server_new( APP_NAME_SASL, NULL, NULL, NULL, NULL, NULL, 0, &conn );
+ rc = sasl_server_new( APP_NAME_SASL, nullptr, nullptr, nullptr, nullptr, nullptr, 0, &conn );
#endif
if ( rc != SASL_OK ) {
- fprintf(stderr, "FATAL: %d %s\n", rc, sasl_errstring(rc, NULL, NULL ));
+ fprintf(stderr, "FATAL: %d %s\n", rc, sasl_errstring(rc, nullptr, nullptr ));
exit(EXIT_FAILURE);
}
struct SMBDOMAIN *next; /* linked list */
};
-struct SMBDOMAIN *firstdom = NULL;
-struct SMBDOMAIN *lastdom = NULL;
+struct SMBDOMAIN *firstdom = nullptr;
+struct SMBDOMAIN *lastdom = nullptr;
/*
* escape the backslash character, since it has a special meaning
const char *shcmd;
/* make standard output line buffered */
- if (setvbuf(stdout, NULL, _IOLBF, 0) != 0)
+ if (setvbuf(stdout, nullptr, _IOLBF, 0) != 0)
exit(EXIT_FAILURE);
/* parse command line arguments */
dom->nmbcast = NMB_BROADCAST;
dom->authshare = (char *)"NETLOGON";
dom->authfile = "proxyauth";
- dom->next = NULL;
+ dom->next = nullptr;
/* append to linked list */
- if (lastdom != NULL)
+ if (lastdom != nullptr)
lastdom->next = dom;
else
firstdom = dom;
continue;
}
if (strcmp(argv[i], "-w") == 0) {
- if (lastdom != NULL)
+ if (lastdom != nullptr)
lastdom->sname = argv[++i];
continue;
}
if (strcmp(argv[i], "-P") == 0) {
- if (lastdom != NULL)
+ if (lastdom != nullptr)
lastdom->passthrough = argv[++i];
continue;
}
if (strcmp(argv[i], "-B") == 0) {
- if (lastdom != NULL) {
+ if (lastdom != nullptr) {
lastdom->nmbaddr = argv[++i];
lastdom->nmbcast = NMB_BROADCAST;
}
continue;
}
if (strcmp(argv[i], "-U") == 0) {
- if (lastdom != NULL) {
+ if (lastdom != nullptr) {
lastdom->nmbaddr = argv[++i];
lastdom->nmbcast = NMB_UNICAST;
}
continue;
}
if (strcmp(argv[i], "-S") == 0) {
- if (lastdom != NULL) {
- if ((lastdom->authshare = xstrdup(argv[++i])) == NULL)
+ if (lastdom != nullptr) {
+ if ((lastdom->authshare = xstrdup(argv[++i])) == nullptr)
exit(EXIT_FAILURE);
/* convert backslashes to forward slashes */
if (*lastdom->authshare == '/')
++lastdom->authshare;
- if ((s = strchr(lastdom->authshare, '/')) != NULL) {
+ if ((s = strchr(lastdom->authshare, '/')) != nullptr) {
*s = '\0';
lastdom->authfile = s + 1;
}
shcmd = debug_enabled ? HELPERSCRIPT : HELPERSCRIPT " > /dev/null 2>&1";
- while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL) {
+ while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != nullptr) {
- if ((s = strchr(buf, '\n')) == NULL)
+ if ((s = strchr(buf, '\n')) == nullptr)
continue;
*s = '\0';
- if ((s = strchr(buf, ' ')) == NULL) {
+ if ((s = strchr(buf, ' ')) == nullptr) {
SEND_ERR("");
continue;
}
user = buf;
pass = s + 1;
- domname = NULL;
+ domname = nullptr;
rfc1738_unescape(user);
rfc1738_unescape(pass);
- if ((s = strchr(user, '\\')) != NULL) {
+ if ((s = strchr(user, '\\')) != nullptr) {
*s = '\0';
domname = user;
user = s + 1;
}
/* match domname with linked list */
- if (domname != NULL && strlen(domname) > 0) {
- for (dom = firstdom; dom != NULL; dom = dom->next)
+ if (domname != nullptr && strlen(domname) > 0) {
+ for (dom = firstdom; dom != nullptr; dom = dom->next)
if (strcasecmp(dom->sname, domname) == 0)
break;
} else
dom = firstdom;
- if (dom == NULL) {
+ if (dom == nullptr) {
SEND_ERR("");
continue;
}
- if ((p = popen(shcmd, "w")) == NULL) {
+ if ((p = popen(shcmd, "w")) == nullptr) {
SEND_ERR("");
continue;
}
#include "debug/Stream.h"
#include "helper.h"
-Auth::Scheme::Pointer Auth::Basic::Scheme::_instance = NULL;
+Auth::Scheme::Pointer Auth::Basic::Scheme::_instance = nullptr;
Auth::Scheme::Pointer
Auth::Basic::Scheme::GetInstance()
{
- if (_instance == NULL) {
+ if (_instance == nullptr) {
_instance = new Auth::Basic::Scheme();
AddScheme(_instance);
}
void
Auth::Basic::Scheme::shutdownCleanup()
{
- if (_instance == NULL)
+ if (_instance == nullptr)
return;
- _instance = NULL;
+ _instance = nullptr;
debugs(29, Critical(12), "Shutdown: Basic authentication.");
}
Auth::Basic::User::User(Auth::SchemeConfig *aConfig, const char *aRequestRealm) :
Auth::User(aConfig, aRequestRealm),
- passwd(NULL),
- queue(NULL),
- currentRequest(NULL)
+ passwd(nullptr),
+ queue(nullptr),
+ currentRequest(nullptr)
{}
Auth::Basic::User::~User()
bool
Auth::Basic::User::valid() const
{
- if (username() == NULL)
+ if (username() == nullptr)
return false;
- if (passwd == NULL)
+ if (passwd == nullptr)
return false;
return true;
}
credentials(Auth::Unchecked);
xfree(passwd);
passwd = from->passwd;
- from->passwd = NULL;
+ from->passwd = nullptr;
}
if (credentials() == Auth::Failed) {
Auth::Basic::User const *basic_auth = dynamic_cast<Auth::Basic::User const *>(user().getRaw());
if (basic_auth)
return basic_auth->passwd;
- return NULL;
+ return nullptr;
}
/* log a basic user in
void
Auth::Basic::UserRequest::authenticate(HttpRequest *, ConnStateData *, Http::HdrType)
{
- assert(user() != NULL);
+ assert(user() != nullptr);
/* if the password is not ok, do an identity */
if (!user() || user()->credentials() != Auth::Ok)
{
assert(user()->auth_type == Auth::AUTH_BASIC);
Auth::Basic::User *basic_auth = dynamic_cast<Auth::Basic::User *>(user().getRaw());
- assert(basic_auth != NULL);
+ assert(basic_auth != nullptr);
debugs(29, 9, "'" << basic_auth->username() << ":" << basic_auth->passwd << "'");
- if (static_cast<Auth::Basic::Config*>(Auth::SchemeConfig::Find("basic"))->authenticateProgram == NULL) {
+ if (static_cast<Auth::Basic::Config*>(Auth::SchemeConfig::Find("basic"))->authenticateProgram == nullptr) {
debugs(29, DBG_CRITICAL, "ERROR: No Basic authentication program configured.");
handler(data);
return;
void *cbdata;
debugs(29, 5, "reply=" << reply);
- assert(r->auth_user_request != NULL);
+ assert(r->auth_user_request != nullptr);
assert(r->auth_user_request->user()->auth_type == Auth::AUTH_BASIC);
// add new helper kv-pair notes to the credentials object
* and do not pass the pointer itself anywhere */
Auth::Basic::User *basic_auth = dynamic_cast<Auth::Basic::User *>(r->auth_user_request->user().getRaw());
- assert(basic_auth != NULL);
+ assert(basic_auth != nullptr);
if (reply.result == Helper::Okay)
basic_auth->credentials(Auth::Ok);
basic_auth->queue->handler(cbdata);
Auth::QueueNode *tmpnode = basic_auth->queue->next;
- basic_auth->queue->next = NULL;
+ basic_auth->queue->next = nullptr;
delete basic_auth->queue;
basic_auth->queue = tmpnode;
{
struct passwd *pwd;
pwd = getpwnam(user);
- if (pwd == NULL) {
+ if (pwd == nullptr) {
return 0; /* User does not exist */
} else {
char *crypted = crypt(passwd, pwd->pw_passwd);
{
struct spwd *pwd;
pwd = getspnam(user);
- if (pwd == NULL) {
+ if (pwd == nullptr) {
return passwd_auth(user, passwd); /* Fall back to passwd_auth */
} else {
char *crypted = crypt(passwd, pwd->sp_pwdp);
char buf[HELPER_INPUT_BUFFER];
char *user, *passwd, *p;
- setbuf(stdout, NULL);
- while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL) {
+ setbuf(stdout, nullptr);
+ while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != nullptr) {
- if ((p = strchr(buf, '\n')) != NULL)
+ if ((p = strchr(buf, '\n')) != nullptr)
*p = '\0'; /* strip \n */
- if ((user = strtok(buf, " ")) == NULL) {
+ if ((user = strtok(buf, " ")) == nullptr) {
SEND_ERR("No Username");
continue;
}
- if ((passwd = strtok(NULL, "")) == NULL) {
+ if ((passwd = strtok(nullptr, "")) == nullptr) {
SEND_ERR("No Password");
continue;
}
static AUTHSSTATS authenticateDigestStats;
-helper *digestauthenticators = NULL;
+helper *digestauthenticators = nullptr;
static hash_table *digest_nonce_cache;
static int authdigest_initialised = 0;
-static MemAllocator *digest_nonce_pool = NULL;
+static MemAllocator *digest_nonce_pool = nullptr;
enum http_digest_attr_type {
DIGEST_USERNAME,
if (!digest_nonce_cache) {
digest_nonce_cache = hash_create((HASHCMP *) strcmp, 7921, hash_string);
assert(digest_nonce_cache);
- eventAdd("Digest nonce cache maintenance", authenticateDigestNonceCacheCleanup, NULL, static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->nonceGCInterval, 1);
+ eventAdd("Digest nonce cache maintenance", authenticateDigestNonceCacheCleanup, nullptr, static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->nonceGCInterval, 1);
}
}
debugs(29, 3, "Finished cleaning the nonce cache.");
if (static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->active())
- eventAdd("Digest nonce cache maintenance", authenticateDigestNonceCacheCleanup, NULL, static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->nonceGCInterval, 1);
+ eventAdd("Digest nonce cache maintenance", authenticateDigestNonceCacheCleanup, nullptr, static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->nonceGCInterval, 1);
}
static void
authDigestNonceLink(digest_nonce_h * nonce)
{
- assert(nonce != NULL);
+ assert(nonce != nullptr);
++nonce->references;
assert(nonce->references != 0); // no overflows
debugs(29, 9, "nonce '" << nonce << "' now at '" << nonce->references << "'.");
void
authDigestNonceUnlink(digest_nonce_h * nonce)
{
- assert(nonce != NULL);
+ assert(nonce != nullptr);
if (nonce->references > 0) {
-- nonce->references;
authenticateDigestNonceNonceHex(const digest_nonce_h * nonce)
{
if (!nonce)
- return NULL;
+ return nullptr;
return (char const *) nonce->key;
}
static digest_nonce_h *
authenticateDigestNonceFindNonce(const char *noncehex)
{
- digest_nonce_h *nonce = NULL;
+ digest_nonce_h *nonce = nullptr;
- if (noncehex == NULL)
- return NULL;
+ if (noncehex == nullptr)
+ return nullptr;
debugs(29, 9, "looking for noncehex '" << noncehex << "' in the nonce cache.");
nonce = static_cast < digest_nonce_h * >(hash_lookup(digest_nonce_cache, noncehex));
- if ((nonce == NULL) || (strcmp(authenticateDigestNonceNonceHex(nonce), noncehex)))
- return NULL;
+ if ((nonce == nullptr) || (strcmp(authenticateDigestNonceNonceHex(nonce), noncehex)))
+ return nullptr;
debugs(29, 9, "Found nonce '" << nonce << "'");
if (!nonce)
return 0;
- intnc = strtol(nc, NULL, 16);
+ intnc = strtol(nc, nullptr, 16);
/* has it already been invalidated ? */
if (!nonce->flags.valid) {
bool
Auth::Digest::Config::configured() const
{
- if ((authenticateProgram != NULL) &&
+ if ((authenticateProgram != nullptr) &&
(authenticateChildren.n_max != 0) &&
!realm.isEmpty() && (noncemaxduration > -1))
return true;
return;
bool stale = false;
- digest_nonce_h *nonce = NULL;
+ digest_nonce_h *nonce = nullptr;
/* on a 407 or 401 we always use a new nonce */
- if (auth_user_request != NULL) {
+ if (auth_user_request != nullptr) {
Auth::Digest::User *digest_user = dynamic_cast<Auth::Digest::User *>(auth_user_request->user().getRaw());
if (digest_user) {
authenticateDigestNonceSetup();
authdigest_initialised = 1;
- if (digestauthenticators == NULL)
+ if (digestauthenticators == nullptr)
digestauthenticators = new helper("digestauthenticator");
digestauthenticators->cmdline = authenticateProgram;
return;
delete digestauthenticators;
- digestauthenticators = NULL;
+ digestauthenticators = nullptr;
if (authenticateProgram)
wordlistDestroy(&authenticateProgram);
dlinkDelete(tmplink, &digest_user->nonces);
authDigestNonceUnlink(static_cast < digest_nonce_h * >(tmplink->data));
delete tmplink;
- link = NULL;
+ link = nullptr;
}
}
/* this reference to user was not locked because freeeing the user frees
* the nonce too.
*/
- nonce->user = NULL;
+ nonce->user = nullptr;
}
/* authDigesteserLinkNonce: add a nonce to a given user's struct */
authDigestNonceLink(nonce);
/* ping this nonce to this auth user */
- assert((nonce->user == NULL) || (nonce->user == user));
+ assert((nonce->user == nullptr) || (nonce->user == user));
/* we don't lock this reference because removing the user removes the
* hash too. Of course if that changes we're stuffed so read the code huh?
static Auth::UserRequest::Pointer
authDigestLogUsername(char *username, Auth::UserRequest::Pointer auth_user_request, const char *requestRealm)
{
- assert(auth_user_request != NULL);
+ assert(auth_user_request != nullptr);
/* log the username */
debugs(29, 9, "Creating new user for logging '" << (username?username:"[no username]") << "'");
{
const char *item;
const char *p;
- const char *pos = NULL;
- char *username = NULL;
+ const char *pos = nullptr;
+ char *username = nullptr;
digest_nonce_h *nonce;
int ilen;
/* check that we're not being hacked / the username hasn't changed */
if (nonce && nonce->user && strcmp(username, nonce->user->username())) {
debugs(29, 2, "Username for the nonce does not equal the username for the request");
- nonce = NULL;
+ nonce = nullptr;
}
if (!nonce) {
}
/*link the request and the user */
- assert(digest_request != NULL);
+ assert(digest_request != nullptr);
digest_request->user(digest_user);
debugs(29, 9, "username = '" << digest_user->username() << "'\nrealm = '" <<
{
char *p;
requestData->parsed = 0;
- if ((p = strchr(buf, '\n')) != NULL)
+ if ((p = strchr(buf, '\n')) != nullptr)
*p = '\0'; /* strip \n */
- p = NULL;
+ p = nullptr;
requestData->channelId = strtoll(buf, &p, 10);
if (*p != ' ') // not a channel-ID
requestData->channelId = -1;
else
buf = ++p;
- if ((requestData->user = strtok(buf, "\"")) == NULL)
+ if ((requestData->user = strtok(buf, "\"")) == nullptr)
return;
- if ((requestData->realm = strtok(NULL, "\"")) == NULL)
+ if ((requestData->realm = strtok(nullptr, "\"")) == nullptr)
return;
- if ((requestData->realm = strtok(NULL, "\"")) == NULL)
+ if ((requestData->realm = strtok(nullptr, "\"")) == nullptr)
return;
requestData->parsed = -1;
}
main(int argc, char **argv)
{
char buf[HELPER_INPUT_BUFFER];
- setbuf(stdout, NULL);
+ setbuf(stdout, nullptr);
ProcessArguments(argc, argv);
- while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL)
+ while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != nullptr)
DoOneRequest(buf);
return EXIT_SUCCESS;
}
/* Globals */
-static LDAP *ld = NULL;
-static const char *passattr = NULL;
-static char *ldapServer = NULL;
-static const char *userbasedn = NULL;
-static const char *userdnattr = NULL;
-static const char *usersearchfilter = NULL;
-static const char *binddn = NULL;
-static const char *bindpasswd = NULL;
+static LDAP *ld = nullptr;
+static const char *passattr = nullptr;
+static char *ldapServer = nullptr;
+static const char *userbasedn = nullptr;
+static const char *userdnattr = nullptr;
+static const char *usersearchfilter = nullptr;
+static const char *binddn = nullptr;
+static const char *bindpasswd = nullptr;
static const char *delimiter = ":";
static const char *frealm = "";
static int encrpass = 0;
static char *
getpassword(char *login, char *realm)
{
- LDAPMessage *res = NULL;
+ LDAPMessage *res = nullptr;
LDAPMessage *entry;
- char **values = NULL;
- char **value = NULL;
- char *password = NULL;
+ char **values = nullptr;
+ char **value = nullptr;
+ char *password = nullptr;
int retry = 0;
char filter[8192];
char searchbase[8192];
retrysrch:
debug("user filter '%s', searchbase '%s'\n", filter, searchbase);
- rc = ldap_search_s(ld, searchbase, searchscope, filter, NULL, 0, &res);
+ rc = ldap_search_s(ld, searchbase, searchscope, filter, nullptr, 0, &res);
if (rc != LDAP_SUCCESS) {
if (noreferrals && rc == LDAP_PARTIAL_RESULTS) {
/* Everything is fine. This is expected when referrals
if (!retry) {
++retry;
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
ldapconnect();
goto retrysrch;
}
- return NULL;
+ return nullptr;
}
}
retrydnattr:
debug("searchbase '%s'\n", userbasedn);
- rc = ldap_search_s(ld, userbasedn, searchscope, filter, NULL, 0, &res);
+ rc = ldap_search_s(ld, userbasedn, searchscope, filter, nullptr, 0, &res);
}
if (rc == LDAP_SUCCESS) {
entry = ldap_first_entry(ld, res);
values = ldap_get_values(ld, entry, passattr);
else {
ldap_msgfree(res);
- return NULL;
+ return nullptr;
}
if (!values) {
debug("No attribute value found\n");
ldap_msgfree(res);
- return NULL;
+ return nullptr;
}
value = values;
while (*value) {
if (encrpass && *delimiter ) {
const char *t = strtok(*value, delimiter);
if (t && strcmp(t, realm) == 0) {
- password = strtok(NULL, delimiter);
+ password = strtok(nullptr, delimiter);
break;
}
} else {
if (!retry) {
++retry;
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
ldapconnect();
goto retrydnattr;
}
- return NULL;
+ return nullptr;
}
}
- return NULL;
+ return nullptr;
}
static void
}
#endif
- if (ld == NULL) {
+ if (ld == nullptr) {
#if HAS_URI_SUPPORT
- if (strstr(ldapServer, "://") != NULL) {
+ if (strstr(ldapServer, "://") != nullptr) {
rc = ldap_initialize(&ld, ldapServer);
if (rc != LDAP_SUCCESS) {
fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer);
}
} else
#endif
- if ((ld = ldap_init(ldapServer, port)) == NULL) {
+ if ((ld = ldap_init(ldapServer, port)) == nullptr) {
fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", ldapServer, port);
}
if (connect_timeout)
fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
version);
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
}
if (use_tls) {
#ifdef LDAP_OPT_X_TLS
if (version != LDAP_VERSION3) {
fprintf(stderr, "TLS requires LDAP version 3\n");
exit(EXIT_FAILURE);
- } else if (ldap_start_tls_s(ld, NULL, NULL) != LDAP_SUCCESS) {
+ } else if (ldap_start_tls_s(ld, nullptr, nullptr) != LDAP_SUCCESS) {
fprintf(stderr, "Could not Activate TLS connection\n");
exit(EXIT_FAILURE);
}
if (rc != LDAP_SUCCESS) {
fprintf(stderr, PROGRAM_NAME " WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc));
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
}
}
debug("Connected OK\n");
int
LDAPArguments(int argc, char **argv)
{
- setbuf(stdout, NULL);
+ setbuf(stdout, nullptr);
while (argc > 1 && argv[1][0] == '-') {
const char *value = "";
readSecret(const char *filename)
{
char buf[BUFSIZ];
- char *e = 0;
+ char *e = nullptr;
FILE *f;
if (!(f = fopen(filename, "r"))) {
void
LDAPHHA1(RequestData * requestData)
{
- char *password = NULL;
+ char *password = nullptr;
ldapconnect();
// use the -l delimiter to find realm, or
if (lookup)
password = getpassword(requestData->user, requestData->realm);
- if (password != NULL) {
+ if (password != nullptr) {
if (encrpass)
xstrncpy(requestData->HHA1, password, sizeof(requestData->HHA1));
else {
HASH HA1;
- DigestCalcHA1("md5", requestData->user, requestData->realm, password, NULL, NULL, HA1, requestData->HHA1);
+ DigestCalcHA1("md5", requestData->user, requestData->realm, password, nullptr, nullptr, HA1, requestData->HHA1);
}
free(password);
} else {
#include "globals.h"
#include "helper.h"
-Auth::Scheme::Pointer Auth::Digest::Scheme::_instance = NULL;
+Auth::Scheme::Pointer Auth::Digest::Scheme::_instance = nullptr;
Auth::Scheme::Pointer
Auth::Digest::Scheme::GetInstance()
{
- if (_instance == NULL) {
+ if (_instance == nullptr) {
_instance = new Auth::Digest::Scheme();
AddScheme(_instance);
}
void
Auth::Digest::Scheme::shutdownCleanup()
{
- if (_instance == NULL)
+ if (_instance == nullptr)
return;
authenticateDigestNonceShutdown();
- _instance = NULL;
+ _instance = nullptr;
debugs(29, Critical(59), "Shutdown: Digest authentication.");
}
digest_nonce_h *
Auth::Digest::User::currentNonce()
{
- digest_nonce_h *nonce = NULL;
+ digest_nonce_h *nonce = nullptr;
dlink_node *link = nonces.tail;
if (link) {
nonce = static_cast<digest_nonce_h *>(link->data);
if (authDigestNonceIsStale(nonce))
- nonce = NULL;
+ nonce = nullptr;
}
return nonce;
}
#include "MemBuf.h"
Auth::Digest::UserRequest::UserRequest() :
- noncehex(NULL),
- cnonce(NULL),
- realm(NULL),
- pszPass(NULL),
- algorithm(NULL),
- pszMethod(NULL),
- qop(NULL),
- uri(NULL),
- response(NULL),
- nonce(NULL)
+ noncehex(nullptr),
+ cnonce(nullptr),
+ realm(nullptr),
+ pszPass(nullptr),
+ algorithm(nullptr),
+ pszMethod(nullptr),
+ qop(nullptr),
+ uri(nullptr),
+ response(nullptr),
+ nonce(nullptr)
{
memset(nc, 0, sizeof(nc));
memset(&flags, 0, sizeof(flags));
int
Auth::Digest::UserRequest::authenticated() const
{
- if (user() != NULL && user()->credentials() == Auth::Ok)
+ if (user() != nullptr && user()->credentials() == Auth::Ok)
return 1;
return 0;
HASHHEX Response;
/* if the check has corrupted the user, just return */
- if (user() == NULL || user()->credentials() == Auth::Failed) {
+ if (user() == nullptr || user()->credentials() == Auth::Failed) {
return;
}
Auth::User::Pointer auth_user = user();
Auth::Digest::User *digest_user = dynamic_cast<Auth::Digest::User*>(auth_user.getRaw());
- assert(digest_user != NULL);
+ assert(digest_user != nullptr);
Auth::Digest::UserRequest *digest_request = this;
return;
}
- if (digest_request->nonce == NULL) {
+ if (digest_request->nonce == nullptr) {
/* this isn't a nonce we issued */
auth_user->credentials(Auth::Failed);
return;
}
- DigestCalcHA1(digest_request->algorithm, NULL, NULL, NULL,
+ DigestCalcHA1(digest_request->algorithm, nullptr, nullptr, nullptr,
authenticateDigestNonceNonceHex(digest_request->nonce),
digest_request->cnonce,
digest_user->HA1, SESSIONKEY);
{
char buf[8192];
- assert(user() != NULL && user()->auth_type == Auth::AUTH_DIGEST);
+ assert(user() != nullptr && user()->auth_type == Auth::AUTH_DIGEST);
debugs(29, 9, "'\"" << user()->username() << "\":\"" << realm << "\"'");
- if (static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->authenticateProgram == NULL) {
+ if (static_cast<Auth::Digest::Config*>(Auth::SchemeConfig::Find("digest"))->authenticateProgram == nullptr) {
debugs(29, DBG_CRITICAL, "ERROR: No Digest authentication program configured.");
handler(data);
return;
Auth::StateData *replyData = static_cast<Auth::StateData *>(data);
debugs(29, 9, "reply=" << reply);
- assert(replyData->auth_user_request != NULL);
+ assert(replyData->auth_user_request != nullptr);
Auth::UserRequest::Pointer auth_user_request = replyData->auth_user_request;
// add new helper kv-pair notes to the credentials object
/* allow this because the digest_request pointer is purely local */
Auth::Digest::User *digest_user = dynamic_cast<Auth::Digest::User *>(auth_user_request->user().getRaw());
- assert(digest_user != NULL);
+ assert(digest_user != nullptr);
CvtBin(reply.other().content(), digest_user->HA1);
digest_user->HA1created = 1;
case Helper::Okay: {
/* allow this because the digest_request pointer is purely local */
Auth::Digest::User *digest_user = dynamic_cast<Auth::Digest::User *>(auth_user_request->user().getRaw());
- assert(digest_user != NULL);
+ assert(digest_user != nullptr);
if (const char *ha1Note = reply.notes.findFirst("ha1")) {
CvtBin(ha1Note, digest_user->HA1);
break;
}
- void *cbdata = NULL;
+ void *cbdata = nullptr;
if (cbdataReferenceValidDone(replyData->data, &cbdata))
replyData->handler(cbdata);
{
char *p;
requestData->parsed = 0;
- if ((p = strchr(buf, '\n')) != NULL)
+ if ((p = strchr(buf, '\n')) != nullptr)
*p = '\0'; /* strip \n */
- p = NULL;
+ p = nullptr;
requestData->channelId = strtoll(buf, &p, 10);
if (*p != ' ') // not a channel-ID
requestData->channelId = -1;
else
buf = ++p;
- if ((requestData->user = strtok(buf, "\"")) == NULL)
+ if ((requestData->user = strtok(buf, "\"")) == nullptr)
return;
- if ((requestData->realm = strtok(NULL, "\"")) == NULL)
+ if ((requestData->realm = strtok(nullptr, "\"")) == nullptr)
return;
- if ((requestData->realm = strtok(NULL, "\"")) == NULL)
+ if ((requestData->realm = strtok(nullptr, "\"")) == nullptr)
return;
requestData->parsed = -1;
}
main(int argc, char **argv)
{
char buf[HELPER_INPUT_BUFFER];
- setbuf(stdout, NULL);
+ setbuf(stdout, nullptr);
ProcessArguments(argc, argv);
- while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL)
+ while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != nullptr)
DoOneRequest(buf);
return EXIT_SUCCESS;
}
const char *password2)
{
int err = 0, rc=0;
- BerElement *requestBer = NULL;
+ BerElement *requestBer = nullptr;
- const char * utf8ObjPtr = NULL;
+ const char * utf8ObjPtr = nullptr;
int utf8ObjSize = 0;
- const char * utf8PwdPtr = NULL;
+ const char * utf8PwdPtr = nullptr;
int utf8PwdSize = 0;
- const char * utf8Pwd2Ptr = NULL;
+ const char * utf8Pwd2Ptr = nullptr;
int utf8Pwd2Size = 0;
/* Convert objectDN and tag strings from Unicode to UTF-8 */
utf8ObjSize = strlen(objectDN)+1;
utf8ObjPtr = objectDN;
- if (password != NULL) {
+ if (password != nullptr) {
utf8PwdSize = strlen(password)+1;
utf8PwdPtr = password;
}
- if (password2 != NULL) {
+ if (password2 != nullptr) {
utf8Pwd2Size = strlen(password2)+1;
utf8Pwd2Ptr = password2;
}
/* Allocate a BerElement for the request parameters. */
- if ((requestBer = ber_alloc()) == NULL) {
+ if ((requestBer = ber_alloc()) == nullptr) {
err = LDAP_ENCODING_ERROR;
ber_free(requestBer, 1);
return err;
}
- if (password != NULL && password2 != NULL) {
+ if (password != nullptr && password2 != nullptr) {
/* BER encode the NMAS Version, the objectDN, and the password */
rc = ber_printf(requestBer, "{iooo}", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize, utf8PwdPtr, utf8PwdSize, utf8Pwd2Ptr, utf8Pwd2Size);
- } else if (password != NULL) {
+ } else if (password != nullptr) {
/* BER encode the NMAS Version, the objectDN, and the password */
rc = ber_printf(requestBer, "{ioo}", NMAS_LDAP_EXT_VERSION, utf8ObjPtr, utf8ObjSize, utf8PwdPtr, utf8PwdSize);
} else {
{
unsigned int elemCnt = methodIDLen / sizeof(unsigned int);
- char *utf8ObjPtr=NULL;
+ char *utf8ObjPtr=nullptr;
int utf8ObjSize = 0;
- char *utf8TagPtr = NULL;
+ char *utf8TagPtr = nullptr;
int utf8TagSize = 0;
utf8ObjPtr = objectDN;
void *retData )
{
int err = 0;
- BerElement *replyBer = NULL;
- char *retOctStr = NULL;
+ BerElement *replyBer = nullptr;
+ char *retOctStr = nullptr;
size_t retOctStrLen = 0;
- if ((replyBer = ber_init(replyBV)) == NULL) {
+ if ((replyBer = ber_init(replyBV)) == nullptr) {
err = LDAP_OPERATIONS_ERROR;
} else if (retData) {
retOctStrLen = *retDataLen + 1;
ber_free(replyBer, 1);
}
- if (retOctStr != NULL) {
+ if (retOctStr != nullptr) {
memset(retOctStr, 0, retOctStrLen);
free(retOctStr);
}
void *data )
{
int err = 0;
- struct berval *requestBV = NULL;
- char *replyOID = NULL;
- struct berval *replyBV = NULL;
+ struct berval *requestBV = nullptr;
+ char *replyOID = nullptr;
+ struct berval *replyBV = nullptr;
int serverVersion = 0;
/* Validate unicode parameters. */
- if ((strlen(objectDN) == 0) || ld == NULL) {
+ if ((strlen(objectDN) == 0) || ld == nullptr) {
return LDAP_NO_SUCH_ATTRIBUTE;
}
- err = berEncodeLoginData(&requestBV, objectDN, methodIDLen, methodID, tag, 0, NULL);
+ err = berEncodeLoginData(&requestBV, objectDN, methodIDLen, methodID, tag, 0, nullptr);
if (err) {
;
} else if (!err && (err = ldap_extended_operation_s(ld, NMASLDAP_GET_LOGIN_CONFIG_REQUEST,
- requestBV, NULL, NULL, &replyOID, &replyBV))) {
+ requestBV, nullptr, nullptr, &replyOID, &replyBV))) {
/* Call the ldap_extended_operation (synchronously) */
;
} else if (!replyOID) {
unsigned int methodID = 0;
unsigned int methodIDLen = sizeof(methodID);
char tag[] = {'P','A','S','S','W','O','R','D',' ','H','A','S','H',0};
- char *pwdBuf=NULL;
+ char *pwdBuf=nullptr;
size_t pwdBufLen, bufferLen;
bufferLen = pwdBufLen = pwdLen+2;
pwdBuf = (char*)SMB_MALLOC_ARRAY(char, pwdBufLen); /* digest and null */
- if (pwdBuf == NULL) {
+ if (pwdBuf == nullptr) {
return LDAP_NO_MEMORY;
}
}
}
- if (pwdBuf != NULL) {
+ if (pwdBuf != nullptr) {
Mem::ZeroSensitiveMemory(pwdBuf, bufferLen);
free(pwdBuf);
}
{
int err = 0;
- struct berval *requestBV = NULL;
- char *replyOID = NULL;
- struct berval *replyBV = NULL;
+ struct berval *requestBV = nullptr;
+ char *replyOID = nullptr;
+ struct berval *replyBV = nullptr;
int serverVersion;
char *pwdBuf;
size_t pwdBufLen, bufferLen;
/* Validate char parameters. */
- if (objectDN == NULL || (strlen(objectDN) == 0) || pwdSize == NULL || ld == NULL) {
+ if (objectDN == nullptr || (strlen(objectDN) == 0) || pwdSize == nullptr || ld == nullptr) {
return LDAP_NO_SUCH_ATTRIBUTE;
}
bufferLen = pwdBufLen = *pwdSize;
pwdBuf = (char*)SMB_MALLOC_ARRAY(char, pwdBufLen+2);
- if (pwdBuf == NULL) {
+ if (pwdBuf == nullptr) {
return LDAP_NO_MEMORY;
}
- err = berEncodePasswordData(&requestBV, objectDN, NULL, NULL);
+ err = berEncodePasswordData(&requestBV, objectDN, nullptr, nullptr);
if (err) {
;
- } else if ((err = ldap_extended_operation_s(ld, NMASLDAP_GET_PASSWORD_REQUEST, requestBV, NULL, NULL, &replyOID, &replyBV))) {
+ } else if ((err = ldap_extended_operation_s(ld, NMASLDAP_GET_PASSWORD_REQUEST, requestBV, nullptr, nullptr, &replyOID, &replyBV))) {
; /* Call the ldap_extended_operation (synchronously) */
} else if (!replyOID) {
/* Make sure there is a return OID */
err = LDAP_OPERATIONS_ERROR;
} else if (!err && pwdBufLen != 0) {
- if (*pwdSize >= pwdBufLen+1 && pwd != NULL) {
+ if (*pwdSize >= pwdBufLen+1 && pwd != nullptr) {
memcpy(pwd, pwdBuf, pwdBufLen);
pwd[pwdBufLen] = 0; /* add null termination */
}
ber_bvfree(requestBV);
}
- if (pwdBuf != NULL) {
+ if (pwdBuf != nullptr) {
Mem::ZeroSensitiveMemory(pwdBuf, bufferLen);
free(pwdBuf);
}
/* Globals */
-static LDAP *ld = NULL;
-static const char *passattr = NULL;
-static char *ldapServer = NULL;
-static const char *userbasedn = NULL;
-static const char *userdnattr = NULL;
-static const char *usersearchfilter = NULL;
-static const char *binddn = NULL;
-static const char *bindpasswd = NULL;
+static LDAP *ld = nullptr;
+static const char *passattr = nullptr;
+static char *ldapServer = nullptr;
+static const char *userbasedn = nullptr;
+static const char *userdnattr = nullptr;
+static const char *usersearchfilter = nullptr;
+static const char *binddn = nullptr;
+static const char *bindpasswd = nullptr;
static const char *delimiter = ":";
static int encrpass = 0;
static int searchscope = LDAP_SCOPE_SUBTREE;
static char *
getpassword(char *login, char *realm)
{
- LDAPMessage *res = NULL;
+ LDAPMessage *res = nullptr;
LDAPMessage *entry;
- char **values = NULL;
- char **value = NULL;
- char *password = NULL;
+ char **values = nullptr;
+ char **value = nullptr;
+ char *password = nullptr;
int retry = 0;
char filter[8192];
*filter = '\0';
char searchbase[8192];
*searchbase = '\0';
- char *universal_password = NULL;
+ char *universal_password = nullptr;
size_t universal_password_len = 256;
int nmas_res = 0;
int rc = -1;
retrysrch:
debug("user filter '%s', searchbase '%s'\n", filter, searchbase);
- rc = ldap_search_s(ld, searchbase, searchscope, filter, NULL, 0, &res);
+ rc = ldap_search_s(ld, searchbase, searchscope, filter, nullptr, 0, &res);
if (rc != LDAP_SUCCESS) {
if (noreferrals && rc == LDAP_PARTIAL_RESULTS) {
/* Everything is fine. This is expected when referrals
if (!retry) {
++retry;
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
ldapconnect();
goto retrysrch;
}
- return NULL;
+ return nullptr;
}
}
retrydnattr:
debug("searchbase '%s'\n", searchbase);
- rc = ldap_search_s(ld, searchbase, searchscope, NULL, NULL, 0, &res);
+ rc = ldap_search_s(ld, searchbase, searchscope, nullptr, nullptr, 0, &res);
}
if (rc == LDAP_SUCCESS) {
entry = ldap_first_entry(ld, res);
}
} else {
ldap_msgfree(res);
- return NULL;
+ return nullptr;
}
if (!values) {
debug("No attribute value found\n");
if (edir_universal_passwd)
free(universal_password);
ldap_msgfree(res);
- return NULL;
+ return nullptr;
}
value = values;
while (*value) {
if (encrpass) {
const char *t = strtok(*value, delimiter);
if (t && strcmp(t, realm) == 0) {
- password = strtok(NULL, delimiter);
+ password = strtok(nullptr, delimiter);
break;
}
} else {
if (!retry) {
++retry;
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
ldapconnect();
goto retrydnattr;
}
- return NULL;
+ return nullptr;
}
}
- return NULL;
+ return nullptr;
}
static void
}
#endif
- if (ld == NULL) {
+ if (ld == nullptr) {
#if HAS_URI_SUPPORT
- if (strstr(ldapServer, "://") != NULL) {
+ if (strstr(ldapServer, "://") != nullptr) {
rc = ldap_initialize(&ld, ldapServer);
if (rc != LDAP_SUCCESS) {
fprintf(stderr, "\nUnable to connect to LDAPURI:%s\n", ldapServer);
}
} else
#endif
- if ((ld = ldap_init(ldapServer, port)) == NULL) {
+ if ((ld = ldap_init(ldapServer, port)) == nullptr) {
fprintf(stderr, "\nUnable to connect to LDAP server:%s port:%d\n", ldapServer, port);
}
if (connect_timeout)
fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
version);
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
}
if (use_tls) {
#ifdef LDAP_OPT_X_TLS
- if ((version == LDAP_VERSION3) && (ldap_start_tls_s(ld, NULL, NULL) == LDAP_SUCCESS)) {
+ if ((version == LDAP_VERSION3) && (ldap_start_tls_s(ld, nullptr, nullptr) == LDAP_SUCCESS)) {
fprintf(stderr, "Could not Activate TLS connection\n");
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
}
#else
fprintf(stderr, "TLS not supported with your LDAP library\n");
if (rc != LDAP_SUCCESS) {
fprintf(stderr, PROGRAM_NAME " WARNING, could not bind to binddn '%s'\n", ldap_err2string(rc));
ldap_unbind(ld);
- ld = NULL;
+ ld = nullptr;
}
}
debug("Connected OK\n");
int
LDAPArguments(int argc, char **argv)
{
- setbuf(stdout, NULL);
+ setbuf(stdout, nullptr);
while (argc > 1 && argv[1][0] == '-') {
const char *value = "";
if (!ldapServer)
ldapServer = (char *) "localhost";
- if (!userbasedn || !((passattr != NULL) || (edir_universal_passwd && usersearchfilter && version == LDAP_VERSION3 && use_tls))) {
+ if (!userbasedn || !((passattr != nullptr) || (edir_universal_passwd && usersearchfilter && version == LDAP_VERSION3 && use_tls))) {
fprintf(stderr, "Usage: " PROGRAM_NAME " -b basedn -f filter [options] ldap_server_name\n\n");
fprintf(stderr, "\t-A password attribute(REQUIRED)\t\tUser attribute that contains the password\n");
fprintf(stderr, "\t-l password realm delimiter(REQUIRED)\tCharater(s) that divides the password attribute\n\t\t\t\t\t\tin realm and password tokens, default ':' realm:password\n");
readSecret(const char *filename)
{
char buf[BUFSIZ];
- char *e = 0;
+ char *e = nullptr;
FILE *f;
if (!(f = fopen(filename, "r"))) {
char *password;
ldapconnect();
password = getpassword(requestData->user, requestData->realm);
- if (password != NULL) {
+ if (password != nullptr) {
if (encrpass)
xstrncpy(requestData->HHA1, password, sizeof(requestData->HHA1));
else {
HASH HA1;
- DigestCalcHA1("md5", requestData->user, requestData->realm, password, NULL, NULL, HA1, requestData->HHA1);
+ DigestCalcHA1("md5", requestData->user, requestData->realm, password, nullptr, nullptr, HA1, requestData->HHA1);
}
free(password);
} else {
{
char *p;
requestData->parsed = 0;
- if ((p = strchr(buf, '\n')) != NULL)
+ if ((p = strchr(buf, '\n')) != nullptr)
*p = '\0'; /* strip \n */
- p = NULL;
+ p = nullptr;
requestData->channelId = strtoll(buf, &p, 10);
if (*p != ' ') // not a channel-ID
requestData->channelId = -1;
else
buf = ++p;
- if ((requestData->user = strtok(buf, "\"")) == NULL)
+ if ((requestData->user = strtok(buf, "\"")) == nullptr)
return;
- if ((requestData->realm = strtok(NULL, "\"")) == NULL)
+ if ((requestData->realm = strtok(nullptr, "\"")) == nullptr)
return;
- if ((requestData->realm = strtok(NULL, "\"")) == NULL)
+ if ((requestData->realm = strtok(nullptr, "\"")) == nullptr)
return;
requestData->parsed = -1;
}
main(int argc, char **argv)
{
char buf[HELPER_INPUT_BUFFER];
- setbuf(stdout, NULL);
+ setbuf(stdout, nullptr);
ProcessArguments(argc, argv);
- while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL)
+ while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != nullptr)
DoOneRequest(buf);
return EXIT_SUCCESS;
}
#include "squid.h"
#include "auth/digest/file/text_backend.h"
-static hash_table *hash = NULL;
+static hash_table *hash = nullptr;
static HASHFREE my_free;
-static char *passwdfile = NULL;
+static char *passwdfile = nullptr;
static int ha1mode = 0;
static time_t change_time = 0;
user_data *u;
char *user;
char *passwd;
- char *ha1 = NULL;
+ char *ha1 = nullptr;
char *realm;
- if (hash != NULL) {
+ if (hash != nullptr) {
hashFreeItems(hash, my_free);
}
/* initial setup */
hash = hash_create((HASHCMP *) strcmp, 7921, hash_string);
- if (NULL == hash) {
+ if (nullptr == hash) {
fprintf(stderr, "digest_file_auth: cannot create hash table\n");
exit(EXIT_FAILURE);
}
exit(EXIT_FAILURE);
}
unsigned int lineCount = 0;
- while (fgets(buf, sizeof(buf), f) != NULL) {
+ while (fgets(buf, sizeof(buf), f) != nullptr) {
++lineCount;
if ((buf[0] == '#') || (buf[0] == ' ') || (buf[0] == '\t') ||
(buf[0] == '\n'))
fprintf(stderr, "digest_file_auth: missing user name at line %u in '%s'\n", lineCount, passwordFile);
continue;
}
- realm = strtok(NULL, ":\n");
- passwd = strtok(NULL, ":\n");
+ realm = strtok(nullptr, ":\n");
+ passwd = strtok(nullptr, ":\n");
if (!passwd) {
passwd = realm;
- realm = NULL;
+ realm = nullptr;
}
if ((strlen(user) > 0) && passwd) {
if (strncmp(passwd, "{HHA1}", 6) == 0) {
ha1 = passwd + 6;
- passwd = NULL;
+ passwd = nullptr;
} else if (isHa1Mode) {
ha1 = passwd;
- passwd = NULL;
+ passwd = nullptr;
}
if (ha1 && strlen(ha1) != 32) {
/* We cannot accept plaintext passwords when using HA1 encoding,
}
}
if (!hash)
- return NULL;
+ return nullptr;
len = snprintf(buf, sizeof(buf), "%s:%s", requestData->user, requestData->realm);
if (len >= static_cast<int>(sizeof(buf)))
- return NULL;
+ return nullptr;
u = (user_data*)hash_lookup(hash, buf);
if (u)
return u;
xstrncpy(requestData->HHA1, u->ha1, sizeof(requestData->HHA1));
} else {
HASH HA1;
- DigestCalcHA1("md5", requestData->user, requestData->realm, u->passwd, NULL, NULL, HA1, requestData->HHA1);
+ DigestCalcHA1("md5", requestData->user, requestData->realm, u->passwd, nullptr, nullptr, HA1, requestData->HHA1);
}
}
static AUTHSSTATS authenticateNegotiateStats;
-statefulhelper *negotiateauthenticators = NULL;
+statefulhelper *negotiateauthenticators = nullptr;
static int authnegotiate_initialised = 0;
-static hash_table *proxy_auth_cache = NULL;
+static hash_table *proxy_auth_cache = nullptr;
void
Auth::Negotiate::Config::rotateHelpers()
return;
delete negotiateauthenticators;
- negotiateauthenticators = NULL;
+ negotiateauthenticators = nullptr;
if (authenticateProgram)
wordlistDestroy(&authenticateProgram);
authnegotiate_initialised = 1;
- if (negotiateauthenticators == NULL)
+ if (negotiateauthenticators == nullptr)
negotiateauthenticators = new statefulhelper("negotiateauthenticator");
if (!proxy_auth_cache)
return;
/* New request, no user details */
- if (auth_user_request == NULL) {
+ if (auth_user_request == nullptr) {
debugs(29, 9, "Sending type:" << reqType << " header: 'Negotiate'");
httpHeaderPutStrf(&rep->header, reqType, "Negotiate");
}
} else {
Auth::Negotiate::UserRequest *negotiate_request = dynamic_cast<Auth::Negotiate::UserRequest *>(auth_user_request.getRaw());
- assert(negotiate_request != NULL);
+ assert(negotiate_request != nullptr);
switch (negotiate_request->user()->credentials()) {
{
Auth::Negotiate::User *newUser = new Auth::Negotiate::User(Auth::SchemeConfig::Find("negotiate"), aRequestRealm);
Auth::UserRequest *auth_user_request = new Auth::Negotiate::UserRequest();
- assert(auth_user_request->user() == NULL);
+ assert(auth_user_request->user() == nullptr);
auth_user_request->user(newUser);
auth_user_request->user()->auth_type = Auth::AUTH_NEGOTIATE;
#include "debug/Stream.h"
#include "helper.h"
-Auth::Scheme::Pointer Auth::Negotiate::Scheme::_instance = NULL;
+Auth::Scheme::Pointer Auth::Negotiate::Scheme::_instance = nullptr;
Auth::Scheme::Pointer
Auth::Negotiate::Scheme::GetInstance()
{
- if (_instance == NULL) {
+ if (_instance == nullptr) {
_instance = new Auth::Negotiate::Scheme();
AddScheme(_instance);
}
void
Auth::Negotiate::Scheme::shutdownCleanup()
{
- if (_instance == NULL)
+ if (_instance == nullptr)
return;
- _instance = NULL;
+ _instance = nullptr;
debugs(29, Critical(60), "Shutdown: Negotiate authentication.");
}
if (request) {
HTTPMSGUNLOCK(request);
- request = NULL;
+ request = nullptr;
}
}
const char *
Auth::Negotiate::UserRequest::connLastHeader()
{
- return NULL;
+ return nullptr;
}
int
Auth::Negotiate::UserRequest::authenticated() const
{
- if (user() != NULL && user()->credentials() == Auth::Ok) {
+ if (user() != nullptr && user()->credentials() == Auth::Ok) {
debugs(29, 9, "user authenticated.");
return 1;
}
assert(data);
assert(handler);
- assert(user() != NULL);
+ assert(user() != nullptr);
assert(user()->auth_type == Auth::AUTH_NEGOTIATE);
- if (static_cast<Auth::Negotiate::Config*>(Auth::SchemeConfig::Find("negotiate"))->authenticateProgram == NULL) {
+ if (static_cast<Auth::Negotiate::Config*>(Auth::SchemeConfig::Find("negotiate"))->authenticateProgram == nullptr) {
debugs(29, DBG_CRITICAL, "ERROR: No Negotiate authentication program configured.");
handler(data);
return;
/* Check that we are in the client side, where we can generate
* auth challenges */
- if (conn == NULL || !cbdataReferenceValid(conn)) {
+ if (conn == nullptr || !cbdataReferenceValid(conn)) {
user()->credentials(Auth::Failed);
debugs(29, DBG_IMPORTANT, "WARNING: Negotiate Authentication attempt to perform authentication without a connection!");
return;
user()->credentials(Auth::Pending);
safe_free(client_blob);
client_blob=xstrdup(blob);
- assert(conn->getAuth() == NULL);
+ assert(conn->getAuth() == nullptr);
conn->setAuth(this, "new Negotiate handshake request");
request = aRequest;
HTTPMSGLOCK(request);
}
Auth::UserRequest::Pointer auth_user_request = r->auth_user_request;
- assert(auth_user_request != NULL);
+ assert(auth_user_request != nullptr);
// add new helper kv-pair notes to the credentials object
// so that any transaction using those credentials can access them
auth_user_request->user()->notes.remove("token");
Auth::Negotiate::UserRequest *lm_request = dynamic_cast<Auth::Negotiate::UserRequest *>(auth_user_request.getRaw());
- assert(lm_request != NULL);
+ assert(lm_request != nullptr);
assert(lm_request->waiting);
lm_request->waiting = 0;
safe_free(lm_request->client_blob);
- assert(auth_user_request->user() != NULL);
+ assert(auth_user_request->user() != nullptr);
assert(auth_user_request->user()->auth_type == Auth::AUTH_NEGOTIATE);
if (!lm_request->reservationId)
case Helper::Okay: {
const char *userNote = reply.notes.findFirst("user");
const char *tokenNote = reply.notes.findFirst("token");
- if (userNote == NULL || tokenNote == NULL) {
+ if (userNote == nullptr || tokenNote == nullptr) {
// XXX: handle a success with no username better
/* protocol error */
fatalf("authenticateNegotiateHandleReply: *** Unsupported helper response ***, '%s'\n", reply.other().content());
if (lm_request->request) {
HTTPMSGUNLOCK(lm_request->request);
- lm_request->request = NULL;
+ lm_request->request = nullptr;
}
r->handler(r->data);
delete r;
static time_t last_t = 0;
static char buf[128];
- gettimeofday(&now, NULL);
+ gettimeofday(&now, nullptr);
if (now.tv_sec != last_t) {
struct tm *tm;
tm = localtime((time_t *) & now.tv_sec);
struct _krb5_kt_list *next;
krb5_keytab_entry *entry;
} *krb5_kt_list;
-krb5_kt_list ktlist = NULL;
+krb5_kt_list ktlist = nullptr;
krb5_keytab memory_keytab;
* char hostname[sysconf(_SC_HOST_NAME_MAX)];
*/
char hostname[1024];
- struct addrinfo *hres = NULL, *hres_list;
+ struct addrinfo *hres = nullptr, *hres_list;
int rc, count;
rc = gethostname(hostname, sizeof(hostname)-1);
debug((char *) "%s| %s: ERROR: resolving hostname '%s' failed\n", LogTime(), PROGRAM, hostname);
fprintf(stderr, "%s| %s: ERROR: resolving hostname '%s' failed\n",
LogTime(), PROGRAM, hostname);
- return NULL;
+ return nullptr;
}
- rc = getaddrinfo(hostname, NULL, NULL, &hres);
- if (rc != 0 || hres == NULL ) {
+ rc = getaddrinfo(hostname, nullptr, nullptr, &hres);
+ if (rc != 0 || hres == nullptr ) {
debug((char *) "%s| %s: ERROR: resolving hostname with getaddrinfo: %s failed\n",
LogTime(), PROGRAM, gai_strerror(rc));
fprintf(stderr,
"%s| %s: ERROR: resolving hostname with getaddrinfo: %s failed\n",
LogTime(), PROGRAM, gai_strerror(rc));
- return NULL;
+ return nullptr;
}
hres_list = hres;
count = 0;
hres_list = hres_list->ai_next;
}
rc = getnameinfo(hres->ai_addr, hres->ai_addrlen, hostname,
- sizeof(hostname), NULL, 0, 0);
+ sizeof(hostname), nullptr, 0, 0);
if (rc != 0) {
debug((char *) "%s| %s: ERROR: resolving ip address with getnameinfo: %s failed\n",
LogTime(), PROGRAM, gai_strerror(rc));
"%s| %s: ERROR: resolving ip address with getnameinfo: %s failed\n",
LogTime(), PROGRAM, gai_strerror(rc));
freeaddrinfo(hres);
- return NULL;
+ return nullptr;
}
freeaddrinfo(hres);
hostname[sizeof(hostname)-1] = '\0';
*/
krb5_error_code krb5_read_keytab(krb5_context context, char *name, krb5_kt_list *list)
{
- krb5_kt_list lp = NULL, tail = NULL, back = NULL;
+ krb5_kt_list lp = nullptr, tail = nullptr, back = nullptr;
krb5_keytab kt;
krb5_keytab_entry *entry;
krb5_kt_cursor cursor;
}
if (!tail)
tail = lp;
- lp->next = NULL;
+ lp->next = nullptr;
lp->entry = entry;
}
xfree(entry);
retval = 0;
else {
krb5_free_kt_list(context, tail);
- tail = NULL;
+ tail = nullptr;
if (back)
- back->next = NULL;
+ back->next = nullptr;
}
}
if (!*list)
{
char buf[MAX_AUTHTOKEN_LEN];
char *c, *p;
- char *user = NULL;
- char *rfc_user = NULL;
+ char *user = nullptr;
+ char *rfc_user = nullptr;
#if HAVE_PAC_SUPPORT
char ad_groups[MAX_PAC_GROUP_SIZE];
- char *ag=NULL;
+ char *ag=nullptr;
krb5_pac pac;
#if USE_HEIMDAL_KRB5
gss_buffer_desc data_set = GSS_C_EMPTY_BUFFER;
gss_buffer_desc type_id = GSS_C_EMPTY_BUFFER;
#endif
#endif
- krb5_context context = NULL;
+ krb5_context context = nullptr;
krb5_error_code ret;
long length = 0;
static int err = 0;
int opt, log = 0, norealm = 0;
OM_uint32 ret_flags = 0, spnego_flag = 0;
- char *service_name = (char *) "HTTP", *host_name = NULL;
- char *token = NULL;
- char *service_principal = NULL;
- char *keytab_name = NULL;
- char *keytab_name_env = NULL;
+ char *service_name = (char *) "HTTP", *host_name = nullptr;
+ char *token = nullptr;
+ char *service_principal = nullptr;
+ char *keytab_name = nullptr;
+ char *keytab_name_env = nullptr;
char default_keytab[MAXPATHLEN] = {};
#if HAVE_KRB5_MEMORY_KEYTAB
- char *memory_keytab_name = NULL;
- char *memory_keytab_name_env = NULL;
+ char *memory_keytab_name = nullptr;
+ char *memory_keytab_name_env = nullptr;
#endif
- char *rcache_type = NULL;
- char *rcache_type_env = NULL;
- char *rcache_dir = NULL;
- char *rcache_dir_env = NULL;
+ char *rcache_type = nullptr;
+ char *rcache_type_env = nullptr;
+ char *rcache_dir = nullptr;
+ char *rcache_dir_env = nullptr;
OM_uint32 major_status, minor_status;
gss_ctx_id_t gss_context = GSS_C_NO_CONTEXT;
gss_name_t client_name = GSS_C_NO_NAME;
gss_buffer_desc service = GSS_C_EMPTY_BUFFER;
gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
- const unsigned char *kerberosToken = NULL;
- const unsigned char *spnegoToken = NULL;
+ const unsigned char *kerberosToken = nullptr;
+ const unsigned char *spnegoToken = nullptr;
size_t spnegoTokenLength = 0;
- setbuf(stdout, NULL);
- setbuf(stdin, NULL);
+ setbuf(stdout, nullptr);
+ setbuf(stdin, nullptr);
while (-1 != (opt = getopt(argc, argv, "dirs:k:c:t:"))) {
switch (opt) {
gsskrb5_register_acceptor_identity(keytab_name);
#endif
while (1) {
- if (fgets(buf, sizeof(buf) - 1, stdin) == NULL) {
+ if (fgets(buf, sizeof(buf) - 1, stdin) == nullptr) {
if (ferror(stdin)) {
debug((char *) "%s| %s: FATAL: fgets() failed! dying..... errno=%d (%s)\n",
LogTime(), PROGRAM, ferror(stdin),
if (client_name)
gss_release_name(&minor_status, &client_name);
if (gss_context != GSS_C_NO_CONTEXT)
- gss_delete_sec_context(&minor_status, &gss_context, NULL);
+ gss_delete_sec_context(&minor_status, &gss_context, nullptr);
if (kerberosToken) {
/* Allocated by parseNegTokenInit, but no matching free function exists.. */
if (!spnego_flag)
}
if (!strncmp(buf, "YR", 2)) {
if (gss_context != GSS_C_NO_CONTEXT)
- gss_delete_sec_context(&minor_status, &gss_context, NULL);
+ gss_delete_sec_context(&minor_status, &gss_context, nullptr);
gss_context = GSS_C_NO_CONTEXT;
}
if (strlen(buf) <= 3) {
major_status =
gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
- GSS_C_NO_OID_SET, GSS_C_ACCEPT, &server_creds, NULL, NULL);
+ GSS_C_NO_OID_SET, GSS_C_ACCEPT, &server_creds, nullptr, nullptr);
if (check_gss_err(major_status, minor_status, "gss_acquire_cred()", log, 1))
goto cleanup;
server_creds,
&input_token,
GSS_C_NO_CHANNEL_BINDINGS,
- &client_name, NULL, &output_token, &ret_flags, NULL, NULL);
+ &client_name, nullptr, &output_token, &ret_flags, nullptr, nullptr);
if (output_token.length) {
spnegoToken = (const unsigned char *) output_token.value;
spnegoTokenLength = output_token.length;
token = (char *) xmalloc((size_t)base64_encode_len(spnegoTokenLength));
- if (token == NULL) {
+ if (token == nullptr) {
debug((char *) "%s| %s: ERROR: Not enough memory\n", LogTime(), PROGRAM);
fprintf(stdout, "BH Not enough memory\n");
goto cleanup;
gss_release_buffer(&minor_status, &output_token);
major_status =
gss_display_name(&minor_status, client_name, &output_token,
- NULL);
+ nullptr);
if (check_gss_err(major_status, minor_status, "gss_display_name()", log, 1))
goto cleanup;
user = (char *) xmalloc(output_token.length + 1);
- if (user == NULL) {
+ if (user == nullptr) {
debug((char *) "%s| %s: ERROR: Not enough memory\n", LogTime(), PROGRAM);
fprintf(stdout, "BH Not enough memory\n");
goto cleanup;
}
memcpy(user, output_token.value, output_token.length);
user[output_token.length] = '\0';
- if (norealm && (p = strchr(user, '@')) != NULL) {
+ if (norealm && (p = strchr(user, '@')) != nullptr) {
*p = '\0';
}
gss_release_buffer(&minor_status, &output_token);
major_status =
gss_display_name(&minor_status, client_name, &output_token,
- NULL);
+ nullptr);
if (check_gss_err(major_status, minor_status, "gss_display_name()", log, 1))
goto cleanup;
* Return dummy token AA. May need an extra return tag then AF
*/
user = (char *) xmalloc(output_token.length + 1);
- if (user == NULL) {
+ if (user == nullptr) {
debug((char *) "%s| %s: ERROR: Not enough memory\n", LogTime(), PROGRAM);
fprintf(stdout, "BH Not enough memory\n");
goto cleanup;
}
memcpy(user, output_token.value, output_token.length);
user[output_token.length] = '\0';
- if (norealm && (p = strchr(user, '@')) != NULL) {
+ if (norealm && (p = strchr(user, '@')) != nullptr) {
*p = '\0';
}
rfc_user = rfc1738_escape(user);
static time_t last_t = 0;
static char buf[128];
- gettimeofday(&now, NULL);
+ gettimeofday(&now, nullptr);
if (now.tv_sec != last_t) {
tm = localtime((const time_t *) &now.tv_sec);
strftime(buf, 127, "%Y/%m/%d %H:%M:%S", tm);
gss_buffer_desc service = GSS_C_EMPTY_BUFFER;
gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
- char *token = NULL;
+ char *token = nullptr;
- setbuf(stdout, NULL);
- setbuf(stdin, NULL);
+ setbuf(stdout, nullptr);
+ setbuf(stdin, nullptr);
if (!proxy) {
fprintf(stderr, "%s| %s: Error: No proxy server name\n", LogTime(),
PROGRAM);
- return NULL;
+ return nullptr;
}
service.value = xmalloc(strlen("HTTP") + strlen(proxy) + 2);
snprintf((char *) service.value, strlen("HTTP") + strlen(proxy) + 2, "%s@%s", "HTTP", proxy);
0,
0,
GSS_C_NO_CHANNEL_BINDINGS,
- &input_token, NULL, &output_token, NULL, NULL);
+ &input_token, nullptr, &output_token, nullptr, nullptr);
if (!check_gss_err(major_status, minor_status, "gss_init_sec_context()") && output_token.length) {
token = (char *) xcalloc(base64_encode_len(output_token.length), 1);
}
}
- gss_delete_sec_context(&minor_status, &gss_context, NULL);
+ gss_delete_sec_context(&minor_status, &gss_context, nullptr);
gss_release_buffer(&minor_status, &service);
gss_release_buffer(&minor_status, &input_token);
gss_release_buffer(&minor_status, &output_token);
{
if (dst) {
if (strlen(dst)>MAX_PAC_GROUP_SIZE)
- return NULL;
+ return nullptr;
else
return strcpy(src,dst);
} else
{
if (dst) {
if (strlen(src)+strlen(dst)+1>MAX_PAC_GROUP_SIZE)
- return NULL;
+ return nullptr;
else
return strcat(src,dst);
} else
if ( ngroup != GroupCount) {
debug((char *) "%s| %s: ERROR: Group encoding error => GroupCount: %d Array size: %d\n",
LogTime(), PROGRAM, GroupCount, ngroup);
- return NULL;
+ return nullptr;
}
debug((char *) "%s| %s: INFO: Found %d rids\n", LogTime(), PROGRAM, GroupCount);
if (!ad_groups) {
debug((char *) "%s| %s: ERR: No space to store groups\n",
LogTime(), PROGRAM);
- return NULL;
+ return nullptr;
}
if (DomainLogonId!= 0) {
if (nauth > maxGidCount) {
debug((char *) "%s| %s: ERROR: Too many groups ! count > %d : %s\n",
LogTime(), PROGRAM, maxGidCount, ad_groups);
- return NULL;
+ return nullptr;
}
size_t length = 1+1+6+nauth*4;
if ( ngroup != SidCount) {
debug((char *) "%s| %s: ERROR: Group encoding error => SidCount: %d Array size: %d\n",
LogTime(), PROGRAM, SidCount, ngroup);
- return NULL;
+ return nullptr;
}
debug((char *) "%s| %s: INFO: Found %d ExtraSIDs\n", LogTime(), PROGRAM, SidCount);
debug((char *) "%s| %s: ERROR: Too many extra groups ! count > %d : %s\n",
LogTime(), PROGRAM, maxGidCount, ad_groups);
xfree(pa);
- return NULL;
+ return nullptr;
}
size_t length = 1+1+6+nauth*4;
LogTime(), PROGRAM);
xfree(pa);
xfree(ag);
- return NULL;
+ return nullptr;
} else {
if (!pstrcat(ad_groups," group=")) {
debug((char *) "%s| %s: WARN: Too many groups ! size > %d : %s\n",
uint32_t ResourceGroupCount=0;
uint32_t ResourceGroupIds=0;
*/
- char **Rids=NULL;
+ char **Rids=nullptr;
int l=0;
if (!ad_groups) {
debug((char *) "%s| %s: ERR: No space to store groups\n",
LogTime(), PROGRAM);
- return NULL;
+ return nullptr;
}
ad_data = (krb5_data *)xcalloc(1,sizeof(krb5_data));
if (checkustr(&LogonDomainName)<0)
goto k5clean;
ad_groups = getdomaingids(ad_groups,LogonDomainId,Rids,GroupCount);
- if ((ad_groups = getextrasids(ad_groups,ExtraSids,SidCount))==NULL)
+ if ((ad_groups = getextrasids(ad_groups,ExtraSids,SidCount))==nullptr)
goto k5clean;
debug((char *) "%s| %s: INFO: Read %d of %d bytes \n", LogTime(), PROGRAM, bpos, (int)ad_data->length);
xfree(Rids);
}
krb5_free_data(context, ad_data);
- return NULL;
+ return nullptr;
}
#endif
static time_t last_t = 0;
static char buf[128];
- gettimeofday(&now, NULL);
+ gettimeofday(&now, nullptr);
if (now.tv_sec != last_t) {
time_t *tmp = (time_t *) & now.tv_sec;
struct tm *tm = localtime(tmp);
char buff[MAX_AUTHTOKEN_LEN+2];
char *c;
size_t length;
- uint8_t *token = NULL;
+ uint8_t *token = nullptr;
while (1) {
- if (fgets(buf, sizeof(buf) - 1, stdin) == NULL) {
+ if (fgets(buf, sizeof(buf) - 1, stdin) == nullptr) {
xfree(token);
if (ferror(stdin)) {
if (debug_enabled)
LogTime(), PROGRAM, (int) *((unsigned char *) token +
sizeof ntlmProtocol));
fprintf(FDNIN, "%s\n",buf);
- if (fgets(tbuff, sizeof(tbuff) - 1, FDNOUT) == NULL) {
+ if (fgets(tbuff, sizeof(tbuff) - 1, FDNOUT) == nullptr) {
xfree(token);
if (ferror(FDNOUT)) {
fprintf(stderr,
LogTime(), PROGRAM);
fprintf(FDKIN, "%s\n",buf);
- if (fgets(buff, sizeof(buff) - 1, FDKOUT) == NULL) {
+ if (fgets(buff, sizeof(buff) - 1, FDKOUT) == nullptr) {
xfree(token);
if (ferror(FDKOUT)) {
fprintf(stderr,
int pnin[2];
int pnout[2];
- setbuf(stdout, NULL);
- setbuf(stdin, NULL);
+ setbuf(stdout, nullptr);
+ setbuf(stdin, nullptr);
if (argc ==1 || !strncasecmp(argv[1],"-h",2)) {
usage();
fprintf(stderr, "%s| %s: Starting version %s\n", LogTime(), PROGRAM,
VERSION);
- if ((nargs = (char **)xmalloc((nend-nstart+1)*sizeof(char *))) == NULL) {
+ if ((nargs = (char **)xmalloc((nend-nstart+1)*sizeof(char *))) == nullptr) {
fprintf(stderr, "%s| %s: Error allocating memory for ntlm helper\n", LogTime(), PROGRAM);
exit(EXIT_FAILURE);
}
memcpy(nargs,argv+nstart+1,(nend-nstart)*sizeof(char *));
- nargs[nend-nstart]=NULL;
+ nargs[nend-nstart]=nullptr;
if (debug_enabled) {
fprintf(stderr, "%s| %s: NTLM command: ", LogTime(), PROGRAM);
for (int i=0; i<nend-nstart; ++i)
fprintf(stderr, "%s ", nargs[i]);
fprintf(stderr, "\n");
}
- if ((kargs = (char **)xmalloc((kend-kstart+1)*sizeof(char *))) == NULL) {
+ if ((kargs = (char **)xmalloc((kend-kstart+1)*sizeof(char *))) == nullptr) {
fprintf(stderr, "%s| %s: Error allocating memory for kerberos helper\n", LogTime(), PROGRAM);
exit(EXIT_FAILURE);
}
memcpy(kargs,argv+kstart+1,(kend-kstart)*sizeof(char *));
- kargs[kend-kstart]=NULL;
+ kargs[kend-kstart]=nullptr;
if (debug_enabled) {
fprintf(stderr, "%s| %s: Kerberos command: ", LogTime(), PROGRAM);
for (int i=0; i<kend-kstart; ++i)
dup2(pkout[1],STDOUT_FILENO);
close(pkout[1]);
- setbuf(stdin, NULL);
- setbuf(stdout, NULL);
+ setbuf(stdin, nullptr);
+ setbuf(stdout, nullptr);
execv(kargs[0], kargs);
fprintf(stderr, "%s| %s: Failed execv for %s: %s\n", LogTime(), PROGRAM, kargs[0], strerror(errno));
dup2(pnout[1],STDOUT_FILENO);
close(pnout[1]);
- setbuf(stdin, NULL);
- setbuf(stdout, NULL);
+ setbuf(stdin, nullptr);
+ setbuf(stdout, nullptr);
execv(nargs[0], nargs);
fprintf(stderr, "%s| %s: Failed execv for %s: %s\n", LogTime(), PROGRAM, nargs[0], strerror(errno));
exit(EXIT_FAILURE);
}
- setbuf(FDKIN, NULL);
- setbuf(FDKOUT, NULL);
- setbuf(FDNIN, NULL);
- setbuf(FDNOUT, NULL);
+ setbuf(FDKIN, nullptr);
+ setbuf(FDKOUT, nullptr);
+ setbuf(FDNIN, nullptr);
+ setbuf(FDNOUT, nullptr);
int result = processingLoop(FDKIN, FDKOUT, FDNIN, FDNOUT);
closeFds(FDKIN, FDKOUT, FDNIN, FDNOUT);
/* NTLM Scheme */
static AUTHSSTATS authenticateNTLMStats;
-statefulhelper *ntlmauthenticators = NULL;
+statefulhelper *ntlmauthenticators = nullptr;
static int authntlm_initialised = 0;
-static hash_table *proxy_auth_cache = NULL;
+static hash_table *proxy_auth_cache = nullptr;
void
Auth::Ntlm::Config::rotateHelpers()
return;
delete ntlmauthenticators;
- ntlmauthenticators = NULL;
+ ntlmauthenticators = nullptr;
if (authenticateProgram)
wordlistDestroy(&authenticateProgram);
authntlm_initialised = 1;
- if (ntlmauthenticators == NULL)
+ if (ntlmauthenticators == nullptr)
ntlmauthenticators = new statefulhelper("ntlmauthenticator");
if (!proxy_auth_cache)
bool
Auth::Ntlm::Config::configured() const
{
- if ((authenticateProgram != NULL) && (authenticateChildren.n_max != 0)) {
+ if ((authenticateProgram != nullptr) && (authenticateChildren.n_max != 0)) {
debugs(29, 9, "returning configured");
return true;
}
return;
/* New request, no user details */
- if (auth_user_request == NULL) {
+ if (auth_user_request == nullptr) {
debugs(29, 9, "Sending type:" << hdrType << " header: 'NTLM'");
httpHeaderPutStrf(&rep->header, hdrType, "NTLM");
}
} else {
Auth::Ntlm::UserRequest *ntlm_request = dynamic_cast<Auth::Ntlm::UserRequest *>(auth_user_request.getRaw());
- assert(ntlm_request != NULL);
+ assert(ntlm_request != nullptr);
switch (ntlm_request->user()->credentials()) {
{
Auth::Ntlm::User *newUser = new Auth::Ntlm::User(Auth::SchemeConfig::Find("ntlm"), aRequestRealm);
Auth::UserRequest::Pointer auth_user_request = new Auth::Ntlm::UserRequest();
- assert(auth_user_request->user() == NULL);
+ assert(auth_user_request->user() == nullptr);
auth_user_request->user(newUser);
auth_user_request->user()->auth_type = Auth::AUTH_NTLM;
if (request) {
HTTPMSGUNLOCK(request);
- request = NULL;
+ request = nullptr;
}
}
const char *
Auth::Ntlm::UserRequest::connLastHeader()
{
- return NULL;
+ return nullptr;
}
int
Auth::Ntlm::UserRequest::authenticated() const
{
- if (user() != NULL && user()->credentials() == Auth::Ok) {
+ if (user() != nullptr && user()->credentials() == Auth::Ok) {
debugs(29, 9, "user authenticated.");
return 1;
}
assert(data);
assert(handler);
- if (static_cast<Auth::Ntlm::Config*>(Auth::SchemeConfig::Find("ntlm"))->authenticateProgram == NULL) {
+ if (static_cast<Auth::Ntlm::Config*>(Auth::SchemeConfig::Find("ntlm"))->authenticateProgram == nullptr) {
debugs(29, DBG_CRITICAL, "ERROR: NTLM Start: no NTLM program configured.");
handler(data);
return;
/* Check that we are in the client side, where we can generate
* auth challenges */
- if (conn == NULL || !cbdataReferenceValid(conn)) {
+ if (conn == nullptr || !cbdataReferenceValid(conn)) {
user()->credentials(Auth::Failed);
debugs(29, DBG_IMPORTANT, "WARNING: NTLM Authentication attempt to perform authentication without a connection!");
return;
user()->credentials(Auth::Pending);
safe_free(client_blob);
client_blob=xstrdup(blob);
- assert(conn->getAuth() == NULL);
+ assert(conn->getAuth() == nullptr);
conn->setAuth(this, "new NTLM handshake request");
request = aRequest;
HTTPMSGLOCK(request);
}
Auth::UserRequest::Pointer auth_user_request = r->auth_user_request;
- assert(auth_user_request != NULL);
+ assert(auth_user_request != nullptr);
// add new helper kv-pair notes to the credentials object
// so that any transaction using those credentials can access them
auth_user_request->user()->notes.remove("token");
Auth::Ntlm::UserRequest *lm_request = dynamic_cast<Auth::Ntlm::UserRequest *>(auth_user_request.getRaw());
- assert(lm_request != NULL);
+ assert(lm_request != nullptr);
assert(lm_request->waiting);
lm_request->waiting = 0;
safe_free(lm_request->client_blob);
- assert(auth_user_request->user() != NULL);
+ assert(auth_user_request->user() != nullptr);
assert(auth_user_request->user()->auth_type == Auth::AUTH_NTLM);
if (!lm_request->reservationId)
if (lm_request->request) {
HTTPMSGUNLOCK(lm_request->request);
- lm_request->request = NULL;
+ lm_request->request = nullptr;
}
r->handler(r->data);
delete r;
* -v enable verbose NTLM packet debugging.
* -l if specified, changes behavior on failures to last-ditch.
*/
-char *my_program_name = NULL;
+char *my_program_name = nullptr;
static void
usage(void)
char helper_command[3];
int len;
- setbuf(stdout, NULL);
- setbuf(stderr, NULL);
+ setbuf(stdout, nullptr);
+ setbuf(stderr, nullptr);
my_program_name = argv[0];
debug("%s " VERSION " " SQUID_BUILD_INFO " starting up...\n", my_program_name);
- while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL) {
+ while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != nullptr) {
user[0] = '\0'; /*no user code */
domain[0] = '\0'; /*no domain code */
- if ((p = strchr(buf, '\n')) != NULL)
+ if ((p = strchr(buf, '\n')) != nullptr)
*p = '\0'; /* strip \n */
buflen = strlen(buf); /* keep this so we only scan the buffer for \0 once per loop */
ntlmhdr *packet;
decodedLen = dstLen;
packet = (ntlmhdr*)decodedBuf;
} else {
- packet = NULL;
+ packet = nullptr;
decodedLen = 0;
}
ntlm_make_nonce(nonce);
if (buflen > 3 && packet) {
ntlm_negotiate *nego = (ntlm_negotiate *)packet;
- ntlm_make_challenge(&chal, authenticate_ntlm_domain, NULL, nonce, NTLM_NONCE_LEN, nego->flags);
+ ntlm_make_challenge(&chal, authenticate_ntlm_domain, nullptr, nonce, NTLM_NONCE_LEN, nego->flags);
} else {
- ntlm_make_challenge(&chal, authenticate_ntlm_domain, NULL, nonce, NTLM_NONCE_LEN, NTLM_NEGOTIATE_ASCII);
+ ntlm_make_challenge(&chal, authenticate_ntlm_domain, nullptr, nonce, NTLM_NONCE_LEN, NTLM_NEGOTIATE_ASCII);
}
// TODO: find out what this context means, and why only the fake auth helper contains it.
chal.context_high = htole32(0x003a<<16);
void
AsyncCall::dequeue(AsyncCall::Pointer &head, AsyncCall::Pointer &prev)
{
- if (prev != NULL)
+ if (prev != nullptr)
prev->setNext(Next());
else
head = Next();
- setNext(NULL);
+ setNext(nullptr);
}
bool
// can be called from canFire() for debugging; always returns false
bool cancel(const char *reason);
- bool canceled() { return isCanceled != NULL; }
+ bool canceled() { return isCanceled != nullptr; }
virtual CallDialer *getDialer() = 0;
#include "base/AsyncCallQueue.h"
#include "debug/Stream.h"
-AsyncCallQueue *AsyncCallQueue::TheInstance = 0;
+AsyncCallQueue *AsyncCallQueue::TheInstance = nullptr;
// Fire all scheduled calls; returns true if at least one call was fired.
// The calls may be added while the current call is in progress.
}
AsyncJob::AsyncJob(const char *aTypeName) :
- stopReason(NULL), typeName(aTypeName), inCall(NULL)
+ stopReason(nullptr), typeName(aTypeName), inCall(nullptr)
{
debugs(93,5, "AsyncJob constructed, this=" << this <<
" type=" << typeName << " [" << id << ']');
{
Must(aReason);
stopReason = aReason;
- if (inCall != NULL) {
+ if (inCall != nullptr) {
// if we are in-call, then the call wrapper will delete us
debugs(93, 4, typeName << " will NOT delete in-call job, reason: " << stopReason);
return;
return;
}
- Must(inCall != NULL); // otherwise nobody will delete us if we are done()
+ Must(inCall != nullptr); // otherwise nobody will delete us if we are done()
Must(aReason);
if (!stopReason) {
stopReason = aReason;
bool AsyncJob::done() const
{
// stopReason, set in mustStop(), overwrites all other conditions
- return stopReason != NULL || doneAll();
+ return stopReason != nullptr || doneAll();
}
bool AsyncJob::doneAll() const
bool AsyncJob::canBeCalled(AsyncCall &call) const
{
- if (inCall != NULL) {
+ if (inCall != nullptr) {
// This may happen when we have bugs or some module is not calling
// us asynchronously (comm used to do that).
debugs(93, 5, inCall << " is in progress; " <<
debugs(inCall->debugSection, inCall->debugLevel,
typeName << " status out:" << status());
- inCall = NULL;
+ inCall = nullptr;
}
// returns a temporary string depicting transaction status, for debugging
buf.reset();
buf.append(" [", 2);
- if (stopReason != NULL) {
+ if (stopReason != nullptr) {
buf.appendf("Stopped, reason:%s", stopReason);
}
buf.appendf(" %s%u]", id.prefix(), id.value);
return entry->element;
}
bool end() {
- return next_entry == NULL;
+ return next_entry == nullptr;
}
private:
/** \endcond */
template <class C>
-CbDataList<C>::CbDataList(C const &value) : next(NULL), element (value)
+CbDataList<C>::CbDataList(C const &value) : next(nullptr), element (value)
{}
template <class C>
bool
CbDataList<C>::find (C const &toFind) const
{
- CbDataList<C> const *node = NULL;
+ CbDataList<C> const *node = nullptr;
for (node = this; node; node = node->next)
if (node->element == toFind)
}
template <class C>
-CbDataListContainer<C>::CbDataListContainer() : head (NULL)
+CbDataListContainer<C>::CbDataListContainer() : head (nullptr)
{}
template <class C>
CbDataList<C> *node = new CbDataList<C> (element);
if (head) {
- CbDataList<C> *tempNode = NULL;
+ CbDataList<C> *tempNode = nullptr;
for (tempNode = head; tempNode->next; tempNode = tempNode->next);
tempNode->next = node;
bool
CbDataListContainer<C>::empty() const
{
- return head == NULL;
+ return head == nullptr;
}
#endif /* SQUID_CBDATALIST_H */
Cbc *operator ->() const; ///< a valid Cbc pointer or exception
// no bool operator because set() != valid()
- bool set() const { return cbc != NULL; } ///< was set but may be invalid
+ bool set() const { return cbc != nullptr; } ///< was set but may be invalid
Cbc *valid() const { return get(); } ///< was set and is valid
bool operator !() const { return !valid(); } ///< invalid or was not set
bool operator ==(const CbcPointer<Cbc> &o) const { return lock == o.lock; }
/// support converting a child cbc pointer into a parent cbc pointer
template <typename Other>
- CbcPointer(const CbcPointer<Other> &o): cbc(o.raw()), lock(NULL) {
+ CbcPointer(const CbcPointer<Other> &o): cbc(o.raw()), lock(nullptr) {
if (o.valid())
lock = cbdataReference(o->toCbdata());
}
// inlined methods
template<class Cbc>
-CbcPointer<Cbc>::CbcPointer(): cbc(NULL), lock(NULL)
+CbcPointer<Cbc>::CbcPointer(): cbc(nullptr), lock(nullptr)
{
}
template<class Cbc>
-CbcPointer<Cbc>::CbcPointer(Cbc *aCbc): cbc(aCbc), lock(NULL)
+CbcPointer<Cbc>::CbcPointer(Cbc *aCbc): cbc(aCbc), lock(nullptr)
{
if (cbc)
lock = cbdataReference(cbc->toCbdata());
}
template<class Cbc>
-CbcPointer<Cbc>::CbcPointer(const CbcPointer &d): cbc(d.cbc), lock(NULL)
+CbcPointer<Cbc>::CbcPointer(const CbcPointer &d): cbc(d.cbc), lock(nullptr)
{
if (d.lock && cbdataReferenceValid(d.lock))
lock = cbdataReference(d.lock);
debugs(45, 3, "cbc=" << (void*)cbc << ", lock=" << (void*)lock);
#endif
cbdataReferenceDone(lock); // lock may be nil before and will be nil after
- cbc = NULL;
+ cbc = nullptr;
}
template<class Cbc>
Cbc *
CbcPointer<Cbc>::get() const
{
- return (lock && cbdataReferenceValid(lock)) ? cbc : NULL;
+ return (lock && cbdataReferenceValid(lock)) ? cbc : nullptr;
}
template<class Cbc>
const char *full = __FILE__;
// Disable heuristic if it does not work.
- if (strstr(full, tail) == 0)
+ if (strstr(full, tail) == nullptr)
return 0;
return strlen(full) - strlen(tail);
UnitFileNameHashCacher(const char *fileName, FileNameHasher hasher)
{
static SourceLocationId cachedHash = 0;
- static const char *hashedFilename = 0;
+ static const char *hashedFilename = nullptr;
// Each file #included in a translation unit has its own __FILE__ value.
// Keep the cache fresh (and the result correct).
if (hashedFilename != fileName) { // cheap pointer comparison
public:
/* create a stream for writing text etc into theBuffer */
// See http://www.codecomments.com/archive292-2005-2-396222.html
- explicit PackableStream(Packable &p) : std::ostream(0), theBuffer(p) {
+ explicit PackableStream(Packable &p) : std::ostream(nullptr), theBuffer(p) {
rdbuf(&theBuffer); // set the buffer to now-initialized theBuffer
clear(); //clear badbit set by calling init(0)
}
{
public:
- RefCount () : p_ (NULL) {}
+ RefCount () : p_ (nullptr) {}
RefCount (C const *p) : p_(p) { reference (*this); }
}
RefCount (RefCount &&p) : p_(std::move(p.p_)) {
- p.p_=NULL;
+ p.p_=nullptr;
}
/// Base::Pointer = Derived::Pointer
RefCount& operator = (RefCount&& p) {
if (this != &p) {
dereference(p.p_);
- p.p_ = NULL;
+ p.p_ = nullptr;
}
return *this;
}
}
private:
- void dereference(C const *newP = NULL) {
+ void dereference(C const *newP = nullptr) {
/* Setting p_ first is important:
* we may be freed ourselves as a result of
* delete p_;
template <class C>
inline std::ostream &operator <<(std::ostream &os, const RefCount<C> &p)
{
- if (p != NULL)
+ if (p != nullptr)
return os << p.getRaw() << '*' << p->LockCount();
else
return os << "NULL";
/// whether this is an "any single character" regex (".")
bool isDot() const { return pattern.length() == 1 && pattern[0] == '.'; }
- bool match(const char *str) const {return regexec(®ex,str,0,NULL,0)==0;}
+ bool match(const char *str) const {return regexec(®ex,str,0,nullptr,0)==0;}
/// Attempts to reproduce this regex (context-sensitive) configuration.
/// If the previous regex is nil, may not report default flags.
/// a collection of unique runners, in no particular order
typedef std::set<RegisteredRunner*> Runners;
/// all known runners
-static Runners *TheRunners = NULL;
+static Runners *TheRunners = nullptr;
/// used to avoid re-creating deleted TheRunners after shutdown finished.
static bool RunnersGone = false;
{
public:
/// Must be passed an object. nil pointers are not permitted.
- explicit CallSubscription(const RefCount<Call_> &aCall) : call(aCall) { assert(aCall != NULL); }
+ explicit CallSubscription(const RefCount<Call_> &aCall) : call(aCall) { assert(aCall != nullptr); }
virtual AsyncCall::Pointer callback() const
{
const AsyncCall::Pointer cb = new Call_(*call);
parseManyConfigFiles(char* files, int depth)
{
int error_count = 0;
- char* saveptr = NULL;
+ char* saveptr = nullptr;
#if HAVE_GLOB
char *path;
glob_t globbuf;
int i;
memset(&globbuf, 0, sizeof(globbuf));
- for (path = strwordtok(files, &saveptr); path; path = strwordtok(NULL, &saveptr)) {
- if (glob(path, globbuf.gl_pathc ? GLOB_APPEND : 0, NULL, &globbuf) != 0) {
+ for (path = strwordtok(files, &saveptr); path; path = strwordtok(nullptr, &saveptr)) {
+ if (glob(path, globbuf.gl_pathc ? GLOB_APPEND : 0, nullptr, &globbuf) != 0) {
int xerrno = errno;
fatalf("Unable to find configuration file: %s: %s", path, xstrerr(xerrno));
}
static void
ReplaceSubstr(char*& str, int& len, unsigned substrIdx, unsigned substrLen, const char* newSubstr)
{
- assert(str != NULL);
- assert(newSubstr != NULL);
+ assert(str != nullptr);
+ assert(newSubstr != nullptr);
unsigned newSubstrLen = strlen(newSubstr);
if (newSubstrLen > substrLen)
static void
SubstituteMacro(char*& line, int& len, const char* macroName, const char* substStr)
{
- assert(line != NULL);
- assert(macroName != NULL);
- assert(substStr != NULL);
+ assert(line != nullptr);
+ assert(macroName != nullptr);
+ assert(substStr != nullptr);
unsigned macroNameLen = strlen(macroName);
while (const char* macroPos = strstr(line, macroName)) // we would replace all occurrences
ReplaceSubstr(line, len, macroPos - line, macroNameLen, substStr);
static void
trim_trailing_ws(char* str)
{
- assert(str != NULL);
+ assert(str != nullptr);
unsigned i = strlen(str);
while ((i > 0) && xisspace(str[i - 1]))
--i;
static const char*
FindStatement(const char* line, const char* statement)
{
- assert(line != NULL);
- assert(statement != NULL);
+ assert(line != nullptr);
+ assert(statement != nullptr);
const char* str = skip_ws(line);
unsigned len = strlen(statement);
return skip_ws(str);
}
- return NULL;
+ return nullptr;
}
static bool
StrToInt(const char* str, long& number)
{
- assert(str != NULL);
+ assert(str != nullptr);
char* end;
number = strtol(str, &end, 0);
static bool
EvalBoolExpr(const char* expr)
{
- assert(expr != NULL);
+ assert(expr != nullptr);
if (strcmp(expr, "true") == 0) {
return true;
} else if (strcmp(expr, "false") == 0) {
static int
parseOneConfigFile(const char *file_name, unsigned int depth)
{
- FILE *fp = NULL;
+ FILE *fp = nullptr;
const char *orig_cfg_filename = cfg_filename;
const int orig_config_lineno = config_lineno;
- char *token = NULL;
- char *tmp_line = NULL;
+ char *token = nullptr;
+ char *tmp_line = nullptr;
int tmp_line_len = 0;
int err_count = 0;
int is_pipe = 0;
if (*Config.appendDomain != '.')
fatal("append_domain must begin with a '.'");
- if (Config.errHtmlText == NULL)
+ if (Config.errHtmlText == nullptr)
Config.errHtmlText = xstrdup(null_string);
#if !HAVE_SETRLIMIT || !defined(RLIMIT_NOFILE)
Config2.onoff.enable_purge = (ACLMethodData::ThePurgeCount > 0);
if (geteuid() == 0) {
- if (NULL != Config.effectiveUser) {
+ if (nullptr != Config.effectiveUser) {
struct passwd *pwd = getpwnam(Config.effectiveUser);
- if (NULL == pwd) {
+ if (nullptr == pwd) {
/*
* Andres Kroonmaa <andre@online.ee>:
* Some getpwnam() implementations (Solaris?) require
Config2.effectiveGroupID = getegid();
}
- if (NULL != Config.effectiveGroup) {
+ if (nullptr != Config.effectiveGroup) {
struct group *grp = getgrnam(Config.effectiveGroup);
- if (NULL == grp) {
+ if (nullptr == grp) {
fatalf("getgrnam failed to find groupid for effective group '%s'",
Config.effectiveGroup);
return;
#endif
}
- for (CachePeer *p = Config.peers; p != NULL; p = p->next) {
+ for (CachePeer *p = Config.peers; p != nullptr; p = p->next) {
// default value for ssldomain= is the peer host/IP
if (p->secure.sslDomain.isEmpty())
}
}
- for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
+ for (AnyP::PortCfgPointer s = HttpPortList; s != nullptr; s = s->next) {
if (!s->secure.encryptTransport)
continue;
debugs(3, DBG_IMPORTANT, "Initializing " << AnyP::UriScheme(s->transport.protocol) << "_port " << s->s << " TLS contexts");
return;
}
- if ((token = ConfigParser::NextToken()) == NULL) {
+ if ((token = ConfigParser::NextToken()) == nullptr) {
self_destruct();
return;
}
if (0.0 == d)
(void) 0;
- else if ((token = ConfigParser::NextToken()) == NULL)
+ else if ((token = ConfigParser::NextToken()) == nullptr)
debugs(3, DBG_CRITICAL, "WARNING: No units on '" <<
config_input_line << "', assuming " <<
d << " " << units );
return;
}
- if ((token = ConfigParser::NextToken()) == NULL) {
+ if ((token = ConfigParser::NextToken()) == nullptr) {
self_destruct();
return;
}
if (0.0 == d)
(void) 0;
- else if ((token = ConfigParser::NextToken()) == NULL)
+ else if ((token = ConfigParser::NextToken()) == nullptr)
debugs(3, DBG_CRITICAL, "WARNING: No units on '" <<
config_input_line << "', assuming " <<
d << " " << units );
return;
}
- if ((token = ConfigParser::NextToken()) == NULL) {
+ if ((token = ConfigParser::NextToken()) == nullptr) {
self_destruct();
return;
}
if (0.0 == d)
(void) 0;
- else if ((token = ConfigParser::NextToken()) == NULL)
+ else if ((token = ConfigParser::NextToken()) == nullptr)
debugs(3, DBG_CRITICAL, "WARNING: No units on '" <<
config_input_line << "', assuming " <<
d << " " << units );
static void
dump_acl(StoreEntry * entry, const char *name, ACL * ae)
{
- while (ae != NULL) {
+ while (ae != nullptr) {
debugs(3, 3, "dump_acl: " << name << " " << ae->name);
storeAppendPrintf(entry, "%s %s %s ",
name,
free_acl_address(Acl::Address ** head)
{
delete *head;
- *head = NULL;
+ *head = nullptr;
}
static void
return;
}
- if (!xstrtoui(token, NULL, &tos, 0, std::numeric_limits<tos_t>::max())) {
+ if (!xstrtoui(token, nullptr, &tos, 0, std::numeric_limits<tos_t>::max())) {
self_destruct();
return;
}
free_acl_tos(acl_tos ** head)
{
delete *head;
- *head = NULL;
+ *head = nullptr;
}
#if SO_MARK && USE_LIBCAP
free_acl_nfmark(acl_nfmark ** head)
{
delete *head;
- *head = NULL;
+ *head = nullptr;
}
#endif /* SO_MARK */
free_acl_b_size_t(AclSizeLimit ** head)
{
delete *head;
- *head = NULL;
+ *head = nullptr;
}
#if USE_DELAY_POOLS
static void
parse_http_header_access(HeaderManglers **pm)
{
- char *t = NULL;
+ char *t = nullptr;
- if ((t = ConfigParser::NextToken()) == NULL) {
+ if ((t = ConfigParser::NextToken()) == nullptr) {
debugs(3, DBG_CRITICAL, "" << cfg_filename << " line " << config_lineno << ": " << config_input_line);
debugs(3, DBG_CRITICAL, "ERROR: parse_http_header_access: missing header name.");
return;
// we delete the entire http_header_* mangler configuration at once
if (const HeaderManglers *manglers = *pm) {
delete manglers;
- *pm = NULL;
+ *pm = nullptr;
}
}
static void
parse_http_header_replace(HeaderManglers **pm)
{
- char *t = NULL;
+ char *t = nullptr;
- if ((t = ConfigParser::NextToken()) == NULL) {
+ if ((t = ConfigParser::NextToken()) == nullptr) {
debugs(3, DBG_CRITICAL, "" << cfg_filename << " line " << config_lineno << ": " << config_input_line);
debugs(3, DBG_CRITICAL, "ERROR: parse_http_header_replace: missing header name.");
return;
static int
check_null_string(char *s)
{
- return s == NULL;
+ return s == nullptr;
}
#if USE_AUTH
/* find a configuration for the scheme in the currently parsed configs... */
Auth::SchemeConfig *schemeCfg = Auth::SchemeConfig::Find(type_str);
- if (schemeCfg == NULL) {
+ if (schemeCfg == nullptr) {
/* Create a configuration based on the scheme info */
Auth::Scheme::Pointer theScheme = Auth::Scheme::Find(type_str);
- if (theScheme == NULL) {
+ if (theScheme == nullptr) {
debugs(3, DBG_CRITICAL, "ERROR: Failure while parsing Config File: Unknown authentication scheme '" << type_str << "'.");
self_destruct();
return;
config->push_back(theScheme->createConfig());
schemeCfg = Auth::SchemeConfig::Find(type_str);
- if (schemeCfg == NULL) {
+ if (schemeCfg == nullptr) {
debugs(3, DBG_CRITICAL, "Parsing Config File: Corruption configuring authentication scheme '" << type_str << "'.");
self_destruct();
return;
NeighborTypeDomainList *t;
LOCAL_ARRAY(char, xname, 128);
- while (p != NULL) {
+ while (p != nullptr) {
storeAppendPrintf(entry, "%s %s %s %d %d name=%s",
name,
p->host,
static unsigned short
GetService(const char *proto)
{
- struct servent *port = NULL;
+ struct servent *port = nullptr;
/** Parses a port number or service name from the squid.conf */
char *token = ConfigParser::NextToken();
- if (token == NULL) {
+ if (token == nullptr) {
self_destruct();
return 0; /* NEVER REACHED */
}
/** Returns either the service port number from /etc/services */
if ( !isUnsignedNumeric(token, strlen(token)) )
port = getservbyname(token, proto);
- if (port != NULL) {
+ if (port != nullptr) {
return ntohs((unsigned short)port->s_port);
}
/** Or a numeric translation of the config text. */
p->index = ++Config.npeers;
- while (*head != NULL)
+ while (*head != nullptr)
head = &(*head)->next;
*head = p;
free_peer(CachePeer ** P)
{
delete *P;
- *P = NULL;
+ *P = nullptr;
Config.npeers = 0;
}
static void
dump_denyinfo(StoreEntry * entry, const char *name, AclDenyInfoList * var)
{
- while (var != NULL) {
+ while (var != nullptr) {
storeAppendPrintf(entry, "%s %s", name, var->err_page_name);
for (const auto &aclName: var->acl_list)
static void
dump_refreshpattern(StoreEntry * entry, const char *name, RefreshPattern * head)
{
- while (head != NULL) {
+ while (head != nullptr) {
PackableStream os(*entry);
os << name << ' ';
head->printHead(os);
max = (time_t) (i * 60); /* convert minutes to seconds */
/* Options */
- while ((token = ConfigParser::NextToken()) != NULL) {
+ while ((token = ConfigParser::NextToken()) != nullptr) {
if (!strcmp(token, "refresh-ims")) {
refresh_ims = 1;
} else if (!strcmp(token, "store-stale")) {
t->flags.ignore_private = true;
#endif
- t->next = NULL;
+ t->next = nullptr;
while (*head)
head = &(*head)->next;
static void
dump_string(StoreEntry * entry, const char *name, char *var)
{
- if (var != NULL)
+ if (var != nullptr)
storeAppendPrintf(entry, "%s %s\n", name, var);
}
static void
dump_wordlist(StoreEntry * entry, const char *name, wordlist * list)
{
- while (list != NULL) {
+ while (list != nullptr) {
storeAppendPrintf(entry, "%s %s\n", name, list->key);
list = list->next;
}
static int
check_null_acl_access(acl_access * a)
{
- return a == NULL;
+ return a == nullptr;
}
#define free_wordlist wordlistDestroy
delete *settings;
- *settings = NULL;
+ *settings = nullptr;
}
static void
free_IpAddress_list(Ip::Address_list ** head)
{
if (*head) delete *head;
- *head = NULL;
+ *head = nullptr;
}
#if CURRENTLY_UNUSED
static void
parsePortSpecification(const AnyP::PortCfgPointer &s, char *token)
{
- char *host = NULL;
+ char *host = nullptr;
unsigned short port = 0;
- char *t = NULL;
- char *junk = NULL;
+ char *t = nullptr;
+ char *junk = nullptr;
s->disable_pmtu_discovery = DISABLE_PMTU_OFF;
s->name = xstrdup(token);
return;
}
- if (port == 0 && host != NULL) {
+ if (port == 0 && host != nullptr) {
debugs(3, DBG_CRITICAL, "FATAL: " << portType << "_port: Port cannot be 0: " << token);
self_destruct();
return;
}
- if (NULL == host) {
+ if (nullptr == host) {
s->s.setAnyAddr();
s->s.port(port);
if (!Ip::EnableIpv6)
s->transport = parsePortProtocol(SBuf("HTTP"));
parsePortSpecification(s, portspec);
// we may need to merge better if the above returns a list with clones
- assert(s->next == NULL);
+ assert(s->next == nullptr);
s->next = HttpPortList;
HttpPortList = s;
}
s->next = s->ipV4clone();
}
- while (*head != NULL)
+ while (*head != nullptr)
head = &((*head)->next);
*head = s;
static void
dump_PortCfg(StoreEntry * e, const char *n, const AnyP::PortCfgPointer &s)
{
- for (AnyP::PortCfgPointer p = s; p != NULL; p = p->next) {
+ for (AnyP::PortCfgPointer p = s; p != nullptr; p = p->next) {
dump_generic_port(e, n, p);
storeAppendPrintf(e, "\n");
}
struct stat sb;
char pathbuf[BUFSIZ];
- assert(path != NULL);
+ assert(path != nullptr);
if (Config.chroot_dir && (geteuid() == 0)) {
snprintf(pathbuf, BUFSIZ, "%s/%s", Config.chroot_dir, path);
static int
check_null_access_log(CustomLog *customlog_definitions)
{
- return customlog_definitions == NULL;
+ return customlog_definitions == nullptr;
}
static void
free_CpuAffinityMap(CpuAffinityMap **const cpuAffinityMap)
{
delete *cpuAffinityMap;
- *cpuAffinityMap = NULL;
+ *cpuAffinityMap = nullptr;
}
#if USE_ADAPTATION
char *token;
cfg->service_failure_limit = GetInteger();
- if ((token = ConfigParser::NextToken()) == NULL)
+ if ((token = ConfigParser::NextToken()) == nullptr)
return;
if (strcmp(token,"in") != 0) {
}
*s = '\0';
} else
- param = NULL;
+ param = nullptr;
std::unique_ptr<sslproxy_cert_adapt> ca(new sslproxy_cert_adapt);
if (strcmp(al, Ssl::CertAdaptAlgorithmStr[Ssl::algSetValidAfter]) == 0) {
static void parse_sslproxy_ssl_bump(acl_access **ssl_bump)
{
typedef const char *BumpCfgStyle;
- BumpCfgStyle bcsNone = NULL;
+ BumpCfgStyle bcsNone = nullptr;
BumpCfgStyle bcsNew = "new client/server-first/none";
BumpCfgStyle bcsOld = "deprecated allow/deny";
static BumpCfgStyle bumpCfgStyleLast = bcsNone;
BumpCfgStyle bumpCfgStyleNow = bcsNone;
char *bm;
- if ((bm = ConfigParser::NextToken()) == NULL) {
+ if ((bm = ConfigParser::NextToken()) == nullptr) {
self_destruct();
return;
}
// if this is the first rule processed
- if (*ssl_bump == NULL) {
+ if (*ssl_bump == nullptr) {
bumpCfgStyleLast = bcsNone;
sslBumpCfgRr::lastDeprecatedRule = Ssl::bumpEnd;
}
if (!*headers) {
*headers = new HeaderWithAclList;
}
- if ((fn = ConfigParser::NextToken()) == NULL) {
+ if ((fn = ConfigParser::NextToken()) == nullptr) {
self_destruct();
return;
}
if (hwa->valueFormat) {
delete hwa->valueFormat;
- hwa->valueFormat = NULL;
+ hwa->valueFormat = nullptr;
}
}
delete *header;
- *header = NULL;
+ *header = nullptr;
}
static void parse_note(Notes *notes)
// 2) if this line is "ftp_epsv on|off" and already exist rules of "ftp_epsv allow|deny ..."
// then abort
if ((!ftpEpsvIsDeprecatedRule && FtpEspvDeprecated) ||
- (ftpEpsvIsDeprecatedRule && !FtpEspvDeprecated && *ftp_epsv != NULL)) {
+ (ftpEpsvIsDeprecatedRule && !FtpEspvDeprecated && *ftp_epsv != nullptr)) {
debugs(3, DBG_CRITICAL, "FATAL: do not mix \"ftp_epsv on|off\" cfg lines with \"ftp_epsv allow|deny ...\" cfg lines. Update your ftp_epsv rules.");
self_destruct();
return;
parse_on_unsupported_protocol(acl_access **access)
{
char *tm;
- if ((tm = ConfigParser::NextToken()) == NULL) {
+ if ((tm = ConfigParser::NextToken()) == nullptr) {
self_destruct();
return;
}
void
CacheManager::registerProfile(const Mgr::ActionProfile::Pointer &profile)
{
- Must(profile != NULL);
+ Must(profile != nullptr);
if (!CacheManager::findAction(profile->name)) {
menu_.push_back(profile);
debugs(16, 3, "registered profile: " << *profile);
Mgr::ActionProfile::Pointer
CacheManager::findAction(char const * action) const
{
- Must(action != NULL);
+ Must(action != nullptr);
Menu::const_iterator a;
debugs(16, 5, "CacheManager::findAction: looking for action " << action);
cmd->profile = findAction(actionName);
cmd->params.actionName = actionName;
- Must(cmd->profile != NULL);
+ Must(cmd->profile != nullptr);
return cmd->profile->creator->create(cmd);
}
Mgr::Command::Pointer cmd = new Mgr::Command;
cmd->params = params;
cmd->profile = findAction(params.actionName.termedBuf());
- Must(cmd->profile != NULL);
+ Must(cmd->profile != nullptr);
return cmd->profile->creator->create(cmd);
}
int
CacheManager::CheckPassword(const Mgr::Command &cmd)
{
- assert(cmd.profile != NULL);
+ assert(cmd.profile != nullptr);
const char *action = cmd.profile->name;
char *pwd = PasswdGet(Config.passwd_list, action);
debugs(16, 4, "CacheManager::CheckPassword for action " << action);
- if (pwd == NULL)
+ if (pwd == nullptr)
return cmd.profile->isPwReq;
if (strcmp(pwd, "disable") == 0)
}
Mgr::Action::Pointer action = cmd->profile->creator->create(cmd);
- Must(action != NULL);
+ Must(action != nullptr);
action->run(entry, true);
}
const char *
CacheManager::ActionProtection(const Mgr::ActionProfile::Pointer &profile)
{
- assert(profile != NULL);
+ assert(profile != nullptr);
const char *pwd = PasswdGet(Config.passwd_list, profile->name);
if (!pwd)
a = a->next;
}
- return NULL;
+ return nullptr;
}
CacheManager*
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
static int n_carp_peers = 0;
-static CachePeer **carp_peers = NULL;
+static CachePeer **carp_peers = nullptr;
static OBJH carpCachemgr;
static int
HttpRequest *request = ps->request;
int k;
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
CachePeer *tp;
unsigned int user_hash = 0;
unsigned int combined_hash;
double high_score = 0;
if (n_carp_peers == 0)
- return NULL;
+ return nullptr;
/* calculate hash key */
debugs(39, 2, "carpSelectParent: Calculating hash for " << request->effectiveRequestUri());
locks(0),
type(CBDATA_UNKNOWN),
#if USE_CBDATA_DEBUG
- file(NULL),
+ file(nullptr),
line(0),
#endif
cookie(0),
- data(NULL)
+ data(nullptr)
{}
~cbdata();
struct CBDataIndex {
MemAllocator *pool;
}
-*cbdata_index = NULL;
+*cbdata_index = nullptr;
int cbdata_types = 0;
if (c->locks) {
debugs(45, 9, p << " has " << c->locks << " locks, not freeing");
- return NULL;
+ return nullptr;
}
cbdataRealFree(c, file, line);
- return NULL;
+ return nullptr;
}
void
cbdataInternalLock(const void *p)
#endif
{
- if (p == NULL)
+ if (p == nullptr)
return;
auto *c = cbdata::FromUserData(p);
cbdataInternalUnlock(const void *p)
#endif
{
- if (p == NULL)
+ if (p == nullptr)
return;
auto *c = cbdata::FromUserData(p);
c->check(__LINE__);
- assert(c != NULL);
+ assert(c != nullptr);
assert(c->locks > 0);
int
cbdataReferenceValid(const void *p)
{
- if (p == NULL)
+ if (p == nullptr)
return 1; /* A NULL pointer cannot become invalid */
debugs(45, 9, p);
{
void *p = (void *) *pp;
int valid = cbdataReferenceValid(p);
- *pp = NULL;
+ *pp = nullptr;
#if USE_CBDATA_DEBUG
cbdataInternalUnlockDbg(p, file, line);
*tp = p;
return 1;
} else {
- *tp = NULL;
+ *tp = nullptr;
return 0;
}
}
TypeList types;
enum State state;
int rc = 0;
- char *ptr = NULL;
+ char *ptr = nullptr;
char buff[MAX_LINE];
std::ifstream fp;
std::stack<std::string> IFDEFS;
if (!type || type[0] == '#')
continue;
Type t(type);
- while ((dep = strtok(NULL, WS)) != NULL) {
+ while ((dep = strtok(nullptr, WS)) != nullptr) {
t.depend.push_front(dep);
}
types.push_front(t);
*t = '\0';
if (strncmp(buff, "IF ", 3) == 0) {
- if ((ptr = strtok(buff + 3, WS)) == NULL) {
+ if ((ptr = strtok(buff + 3, WS)) == nullptr) {
errorMsg(input_filename, linenum, "Missing IF parameter");
exit(EXIT_FAILURE);
}
} else if (!strncmp(buff, "NAME:", 5)) {
char *name, *aliasname;
- if ((name = strtok(buff + 5, WS)) == NULL) {
+ if ((name = strtok(buff + 5, WS)) == nullptr) {
errorMsg(input_filename, linenum, buff);
exit(EXIT_FAILURE);
}
entries.emplace_back(name);
- while ((aliasname = strtok(NULL, WS)) != NULL)
+ while ((aliasname = strtok(nullptr, WS)) != nullptr)
entries.back().alias.push_front(aliasname);
state = s1;
curr.defaults.docs.push_back(ptr);
} else if (!strncmp(buff, "LOC:", 4)) {
- if ((ptr = strtok(buff + 4, WS)) == NULL) {
+ if ((ptr = strtok(buff + 4, WS)) == nullptr) {
errorMsg(input_filename, linenum, buff);
exit(EXIT_FAILURE);
}
curr.loc = ptr;
} else if (!strncmp(buff, "TYPE:", 5)) {
- if ((ptr = strtok(buff + 5, WS)) == NULL) {
+ if ((ptr = strtok(buff + 5, WS)) == nullptr) {
errorMsg(input_filename, linenum, buff);
exit(EXIT_FAILURE);
}
checkDepend(curr.name, ptr, types, entries);
curr.type = ptr;
} else if (!strncmp(buff, "IFDEF:", 6)) {
- if ((ptr = strtok(buff + 6, WS)) == NULL) {
+ if ((ptr = strtok(buff + 6, WS)) == nullptr) {
errorMsg(input_filename, linenum, buff);
exit(EXIT_FAILURE);
}
CBDATA_CLASS_INIT(clientStreamNode);
clientStreamNode::clientStreamNode(CSR * aReadfunc, CSCB * aCallback, CSD * aDetach, CSS * aStatus, ClientStreamData aData) :
- head(NULL),
+ head(nullptr),
readfunc(aReadfunc),
callback(aCallback),
detach(aDetach),
debugs(87, 3, "Freeing clientStreamNode " << this);
removeFromStream();
- data = NULL;
+ data = nullptr;
}
/**
ClientStreamData readdata, CSCB * callback, CSD * cdetach, ClientStreamData callbackdata,
StoreIOBuffer tailBuffer)
{
- clientStreamNode *temp = new clientStreamNode(func, NULL, rdetach, readstatus, readdata);
+ clientStreamNode *temp = new clientStreamNode(func, nullptr, rdetach, readstatus, readdata);
dlinkAdd(cbdataReference(temp), &temp->node, list);
temp->head = list;
- clientStreamInsertHead(list, NULL, callback, cdetach, NULL, callbackdata);
+ clientStreamInsertHead(list, nullptr, callback, cdetach, nullptr, callbackdata);
temp = (clientStreamNode *)list->tail->data;
temp->readBuffer = tailBuffer;
}
CSD * detach, CSS * status, ClientStreamData data)
{
/* test preconditions */
- assert(list != NULL);
+ assert(list != nullptr);
assert(list->head);
clientStreamNode *temp = new clientStreamNode(func, callback, detach, status, data);
temp->head = list;
{
clientStreamNode *temp = thisObject;
- assert(thisObject->node.next == NULL);
+ assert(thisObject->node.next == nullptr);
debugs(87, 3, "clientStreamDetach: Detaching node " << thisObject);
/* And clean up thisObject node */
/* ESI TODO: push refcount class through to head */
- clientStreamNode *prev = NULL;
+ clientStreamNode *prev = nullptr;
if (thisObject->prev())
prev = cbdataReference(thisObject->prev());
{
dlink_list *list;
- assert(thisObject != NULL);
- assert(http != NULL);
+ assert(thisObject != nullptr);
+ assert(http != nullptr);
list = thisObject->head;
debugs(87, 3, "clientStreamAbort: Aborting stream with tail " << list->tail);
if (head)
dlinkDelete(&node, head);
- head = NULL;
+ head = nullptr;
}
clientStreamNode *
if (node.prev)
return (clientStreamNode *)node.prev->data;
else
- return NULL;
+ return nullptr;
}
clientStreamNode *
if (node.next)
return (clientStreamNode *)node.next->data;
else
- return NULL;
+ return nullptr;
}
#include "snmp_core.h"
#endif
-static hash_table *client_table = NULL;
+static hash_table *client_table = nullptr;
static ClientInfo *clientdbAdd(const Ip::Address &addr);
static FREE clientdbFreeItem;
if ((statCounter.client_http.clients > max_clients) && !cleanup_running && cleanup_scheduled < 2) {
++cleanup_scheduled;
- eventAdd("client_db garbage collector", clientdbScheduledGC, NULL, 90, 0);
+ eventAdd("client_db garbage collector", clientdbScheduledGC, nullptr, 90, 0);
}
return c;
ClientInfo *c;
if (!Config.onoff.client_db)
- return NULL;
+ return nullptr;
addr.toStr(key,MAX_IPSTRLEN);
c = (ClientInfo *) hash_lookup(client_table, key);
- if (c==NULL) {
+ if (c==nullptr) {
debugs(77, DBG_IMPORTANT,"Client db does not contain information for given IP address "<<(const char*)key);
- return NULL;
+ return nullptr;
}
return c;
}
c = (ClientInfo *) hash_lookup(client_table, key);
- if (c == NULL)
+ if (c == nullptr)
c = clientdbAdd(addr);
- if (c == NULL)
+ if (c == nullptr)
debug_trap("clientdbUpdate: Failed to add entry");
if (p == AnyP::PROTO_HTTP) {
c = (ClientInfo *) hash_lookup(client_table, key);
- if (c == NULL) {
+ if (c == nullptr) {
c = clientdbAdd(addr);
}
- if (c == NULL)
+ if (c == nullptr)
debug_trap("clientdbUpdate: Failed to add entry");
c->n_established += delta;
c = (ClientInfo *) hash_lookup(client_table, key);
- if (c == NULL)
+ if (c == nullptr)
return 0;
/*
#if USE_DELAY_POOLS
if (CommQuotaQueue *q = quotaQueue) {
- q->clientInfo = NULL;
+ q->clientInfo = nullptr;
delete q; // invalidates cbdata, cancelling any pending kicks
}
#endif
{
hashFreeItems(client_table, clientdbFreeItem);
hashFreeMemory(client_table);
- client_table = NULL;
+ client_table = nullptr;
}
static void
link_next = hash_get_bucket(client_table, bucket++);
- while (link_next != NULL) {
+ while (link_next != nullptr) {
ClientInfo *c = (ClientInfo *)link_next;
int age = squid_curtime - c->last_seen;
link_next = link_next->next;
}
if (bucket < CLIENT_DB_HASH_SIZE)
- eventAdd("client_db garbage collector", clientdbGC, NULL, 0.15, 0);
+ eventAdd("client_db garbage collector", clientdbGC, nullptr, 0.15, 0);
else {
bucket = 0;
cleanup_running = 0;
if (!cleanup_scheduled) {
cleanup_scheduled = 1;
- eventAdd("client_db garbage collector", clientdbScheduledGC, NULL, 6 * 3600, 0);
+ eventAdd("client_db garbage collector", clientdbScheduledGC, nullptr, 6 * 3600, 0);
}
debugs(49, 2, "clientdbGC: Removed " << cleanup_removed << " entries");
max_clients = statCounter.client_http.clients;
cleanup_running = 1;
cleanup_removed = 0;
- clientdbGC(NULL);
+ clientdbGC(nullptr);
}
#if SQUID_SNMP
snmp_meshCtblFn(variable_list * Var, snint * ErrP)
{
char key[MAX_IPSTRLEN];
- ClientInfo *c = NULL;
+ ClientInfo *c = nullptr;
Ip::Address keyIp;
*ErrP = SNMP_ERR_NOERROR;
oid2addr(&(Var->name[12]), keyIp, 16);
} else {
*ErrP = SNMP_ERR_NOSUCHNAME;
- return NULL;
+ return nullptr;
}
keyIp.toStr(key, sizeof(key));
debugs(49, 5, "[" << key << "] requested!");
c = (ClientInfo *) hash_lookup(client_table, key);
- if (c == NULL) {
+ if (c == nullptr) {
debugs(49, 5, "not found.");
*ErrP = SNMP_ERR_NOSUCHNAME;
- return NULL;
+ return nullptr;
}
- variable_list *Answer = NULL;
+ variable_list *Answer = nullptr;
int aggr = 0;
switch (Var->name[LEN_SQ_NET + 2]) {
prepareLogWithRequestDetails(HttpRequest *request, const AccessLogEntryPointer &aLogEntry)
{
assert(request);
- assert(aLogEntry != NULL);
+ assert(aLogEntry != nullptr);
if (Config.onoff.log_mime_hdrs) {
MemBuf mb;
#if USE_ADAPTATION
const Adaptation::History::Pointer ah = request->adaptLogHistory();
- if (ah != NULL) {
+ if (ah != nullptr) {
mb.reset();
ah->lastMeta.packInto(&mb);
aLogEntry->adapt.last_meta = xstrdup(mb.buf);
#if ICAP_CLIENT
const Adaptation::Icap::History::Pointer ih = request->icapHistory();
- if (ih != NULL)
+ if (ih != nullptr)
ih->processingTime(aLogEntry->icap.processingTime);
#endif
al->syncNotes(request);
}
- ACLFilledChecklist checklist(NULL, request, NULL);
+ ACLFilledChecklist checklist(nullptr, request, nullptr);
if (al->reply) {
checklist.reply = al->reply.getRaw();
HTTPMSGLOCK(checklist.reply);
bool updatePerformanceCounters = true;
if (Config.accessList.stats_collection) {
- ACLFilledChecklist statsCheck(Config.accessList.stats_collection, request, NULL);
+ ACLFilledChecklist statsCheck(Config.accessList.stats_collection, request, nullptr);
statsCheck.al = al;
if (al->reply) {
statsCheck.reply = al->reply.getRaw();
if (request)
updateCounters();
- if (getConn() != NULL && getConn()->clientConnection != NULL)
+ if (getConn() != nullptr && getConn()->clientConnection != nullptr)
clientdbUpdate(getConn()->clientConnection->remote, loggingTags(), AnyP::PROTO_HTTP, out.size);
}
}
httpRequestFree(void *data)
{
ClientHttpRequest *http = (ClientHttpRequest *)data;
- assert(http != NULL);
+ assert(http != nullptr);
delete http;
}
void
ConnStateData::setAuth(const Auth::UserRequest::Pointer &aur, const char *by)
{
- if (auth_ == NULL) {
- if (aur != NULL) {
+ if (auth_ == nullptr) {
+ if (aur != nullptr) {
debugs(33, 2, "Adding connection-auth to " << clientConnection << " from " << by);
auth_ = aur;
}
*/
// clobbered with nul-pointer
- if (aur == NULL) {
+ if (aur == nullptr) {
debugs(33, 2, "WARNING: Graceful closure on " << clientConnection << " due to connection-auth erase from " << by);
auth_->releaseAuthServer();
- auth_ = NULL;
+ auth_ = nullptr;
// XXX: need to test whether the connection re-auth challenge is sent. If not, how to trigger it from here.
// NP: the current situation seems to fix challenge loops in Safari without visible issues in others.
// we stop receiving more traffic but can leave the Job running to terminate after the error or challenge is delivered.
if (aur != auth_) {
debugs(33, 2, "ERROR: Closing " << clientConnection << " due to change of connection-auth from " << by);
auth_->releaseAuthServer();
- auth_ = NULL;
+ auth_ = nullptr;
// this is a fatal type of problem.
// Close the connection immediately with TCP RST to abort all traffic flow
comm_reset_close(clientConnection);
#if USE_AUTH
// NP: do this bit after closing the connections to avoid side effects from unwanted TCP RST
- setAuth(NULL, "ConnStateData::SwanSong cleanup");
+ setAuth(nullptr, "ConnStateData::SwanSong cleanup");
#endif
flags.swanSang = true;
if (!flags.swanSang)
debugs(33, DBG_IMPORTANT, "ERROR: Squid BUG: ConnStateData was not destroyed properly; " << clientConnection);
- if (bodyPipe != NULL)
+ if (bodyPipe != nullptr)
stopProducingFor(bodyPipe, false);
delete bodyParser; // TODO: pool
return;
/* Test preconditions */
- assert(node != NULL);
+ assert(node != nullptr);
/* TODO: handle this rather than asserting
* - it should only ever happen if we cause an abort and
* the callback chain loops back to here, so we can simply return.
* However, that itself shouldn't happen, so it stays as an assert for now.
*/
assert(cbdataReferenceValid(node));
- assert(node->node.next == NULL);
+ assert(node->node.next == nullptr);
Http::StreamPointer context = dynamic_cast<Http::Stream *>(node->data.getRaw());
- assert(context != NULL);
+ assert(context != nullptr);
/* TODO: check offset is what we asked for */
clientSocketDetach(clientStreamNode * node, ClientHttpRequest * http)
{
/* Test preconditions */
- assert(node != NULL);
+ assert(node != nullptr);
/* TODO: handle this rather than asserting
* - it should only ever happen if we cause an abort and
* the callback chain loops back to here, so we can simply return.
*/
assert(cbdataReferenceValid(node));
/* Set null by ContextFree */
- assert(node->node.next == NULL);
+ assert(node->node.next == nullptr);
/* this is the assert discussed above */
- assert(NULL == dynamic_cast<Http::Stream *>(node->data.getRaw()));
+ assert(nullptr == dynamic_cast<Http::Stream *>(node->data.getRaw()));
/* We are only called when the client socket shutsdown.
* Tell the prev pipeline member we're finished
*/
const char *
findTrailingHTTPVersion(const char *uriAndHTTPVersion, const char *end)
{
- if (NULL == end) {
+ if (nullptr == end) {
end = uriAndHTTPVersion + strcspn(uriAndHTTPVersion, "\r\n");
assert(end);
}
}
}
- return NULL;
+ return nullptr;
}
static char *
if (hp->needsMoreData()) {
debugs(33, 5, "Incomplete request, waiting for end of request line");
- return NULL;
+ return nullptr;
}
if (!parsedOk) {
"\n----------");
/* deny CONNECT via accelerated ports */
- if (hp->method() == Http::METHOD_CONNECT && port != NULL && port->flags.accelSurrogate) {
+ if (hp->method() == Http::METHOD_CONNECT && port != nullptr && port->flags.accelSurrogate) {
debugs(33, DBG_IMPORTANT, "WARNING: CONNECT method received on " << transferProtocol << " Accelerator port " << port->s.port());
debugs(33, DBG_IMPORTANT, "WARNING: for request: " << hp->method() << " " << hp->requestUri() << " " << hp->messageProtocol());
hp->parseStatusCode = Http::scMethodNotAllowed;
} else if (internalCheck(hp->requestUri())) { // NP: only matches relative-URI
/* internal URL mode */
/* prepend our name & port */
- http->uri = xstrdup(internalLocalUri(NULL, hp->requestUri()));
+ http->uri = xstrdup(internalLocalUri(nullptr, hp->requestUri()));
// We just re-wrote the URL. Must replace the Host: header.
// But have not parsed there yet!! flag for local-only handling.
http->flags.internal = true;
clientAclChecklistFill(check, http);
allowDomainMismatch = check.fastCheck().allowed();
delete check.sslErrors;
- check.sslErrors = NULL;
+ check.sslErrors = nullptr;
}
if (!allowDomainMismatch) {
const auto request = http ? http->request : nullptr;
if (context)
context->finished(); // Will remove from pipeline queue
- Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, NULL, NULL, 0);
+ Comm::SetSelect(clientConnection->fd, COMM_SELECT_READ, nullptr, nullptr, 0);
return initiateTunneledRequest(request, "unknown-protocol", preservedClientData);
}
debugs(33, 3, "denied; send error: " << requestError);
* to here because calling comm_reset_close() causes http to
* be freed before accessing.
*/
- if (request != NULL && request->flags.resetTcp && Comm::IsConnOpen(conn->clientConnection)) {
+ if (request != nullptr && request->flags.resetTcp && Comm::IsConnOpen(conn->clientConnection)) {
debugs(33, 3, "Sending TCP RST on " << conn->clientConnection);
conn->flags.readMore = false;
comm_reset_close(conn->clientConnection);
((request->flags.sslBumped || conn->port->transport.protocol == AnyP::PROTO_HTTPS) ? Http::Message::srcHttps : Http::Message::srcHttp);
#if USE_AUTH
if (request->flags.sslBumped) {
- if (conn->getAuth() != NULL)
+ if (conn->getAuth() != nullptr)
request->auth_user_request = conn->getAuth();
}
#endif
ConnStateData::handleReadData()
{
// if we are reading a body, stuff data into the body pipe
- if (bodyPipe != NULL)
+ if (bodyPipe != nullptr)
return handleRequestBodyData();
return true;
}
bool
ConnStateData::handleRequestBodyData()
{
- assert(bodyPipe != NULL);
+ assert(bodyPipe != nullptr);
if (bodyParser) { // chunked encoding
if (const err_type error = handleChunkedRequestBody()) {
if (!bodyPipe->mayNeedMoreData()) {
// BodyPipe will clear us automagically when we produced everything
- bodyPipe = NULL;
+ bodyPipe = nullptr;
}
}
ConnStateData::noteBodyConsumerAborted(BodyPipe::Pointer )
{
// request reader may get stuck waiting for space if nobody consumes body
- if (bodyPipe != NULL)
+ if (bodyPipe != nullptr)
bodyPipe->enableAutoConsumption();
// kids extend
#if USE_IDENT
if (Ident::TheConfig.identLookup) {
- ACLFilledChecklist identChecklist(Ident::TheConfig.identLookup, NULL, NULL);
+ ACLFilledChecklist identChecklist(Ident::TheConfig.identLookup, nullptr, nullptr);
fillChecklist(identChecklist);
if (identChecklist.fastCheck().allowed())
Ident::Start(clientConnection, clientIdentDone, this);
clientdbEstablished(clientConnection->remote, 1);
#if USE_DELAY_POOLS
- fd_table[clientConnection->fd].clientInfo = NULL;
+ fd_table[clientConnection->fd].clientInfo = nullptr;
if (!Config.onoff.client_db)
return; // client delay pools require client_db
const auto &pools = ClientDelayPools::Instance()->pools;
if (pools.size()) {
- ACLFilledChecklist ch(NULL, NULL, NULL);
+ ACLFilledChecklist ch(nullptr, nullptr, nullptr);
fillChecklist(ch);
// TODO: we check early to limit error response bandwidth but we
// should recheck when we can honor delay_pool_uses_indirect
CodeContext::Reset(connectAle);
// TODO: Use these request/ALE when waiting for new bumped transactions.
- ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(Config.accessList.ssl_bump, request, NULL);
+ ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(Config.accessList.ssl_bump, request, nullptr);
fillChecklist(*acl_checklist);
// Build a local AccessLogEntry to allow requiresAle() acls work
acl_checklist->al = connectAle;
ACLFilledChecklist checklist(nullptr, sslServerBump->request.getRaw());
fillChecklist(checklist);
- for (sslproxy_cert_adapt *ca = Config.ssl_client.cert_adapt; ca != NULL; ca = ca->next) {
+ for (sslproxy_cert_adapt *ca = Config.ssl_client.cert_adapt; ca != nullptr; ca = ca->next) {
// If the algorithm already set, then ignore it.
if ((ca->alg == Ssl::algSetCommonName && certProperties.setCommonName) ||
(ca->alg == Ssl::algSetValidAfter && certProperties.setValidAfter) ||
}
certProperties.signAlgorithm = Ssl::algSignEnd;
- for (sslproxy_cert_sign *sg = Config.ssl_client.cert_sign; sg != NULL; sg = sg->next) {
+ for (sslproxy_cert_sign *sg = Config.ssl_client.cert_sign; sg != nullptr; sg = sg->next) {
if (sg->aclList && checklist.fastCheck(sg->aclList).allowed()) {
certProperties.signAlgorithm = (Ssl::CertSignAlgorithm)sg->alg;
break;
debugs(83, 5, "Peek and splice at step2 done. Start forwarding the request!!! ");
sslServerBump->step = XactionStep::tlsBump3;
- FwdState::Start(clientConnection, sslServerBump->entry, sslServerBump->request.getRaw(), http ? http->al : NULL);
+ FwdState::Start(clientConnection, sslServerBump->entry, sslServerBump->request.getRaw(), http ? http->al : nullptr);
}
/// process a problematic Security::Accept() result on the SslBump code path
void
ConnStateData::httpsPeeked(PinnedIdleContext pic)
{
- Must(sslServerBump != NULL);
+ Must(sslServerBump != nullptr);
Must(sslServerBump->request == pic.request);
Must(pipeline.empty() || pipeline.front()->http == nullptr || pipeline.front()->http->request == pic.request.getRaw());
static void
clientHttpConnectionsOpen(void)
{
- for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
+ for (AnyP::PortCfgPointer s = HttpPortList; s != nullptr; s = s->next) {
const SBuf &scheme = AnyP::UriScheme(s->transport.protocol).image();
if (MAXTCPLISTENPORTS == NHttpSockets) {
static void
clientListenerConnectionOpened(AnyP::PortCfgPointer &s, const Ipc::FdNoteId portTypeNote, const Subscription::Pointer &sub)
{
- Must(s != NULL);
+ Must(s != nullptr);
if (!OpenedHttpSocket(s->listenConn, portTypeNote))
return;
void
clientConnectionsClose()
{
- for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
- if (s->listenConn != NULL) {
+ for (AnyP::PortCfgPointer s = HttpPortList; s != nullptr; s = s->next) {
+ if (s->listenConn != nullptr) {
debugs(1, Important(14), "Closing HTTP(S) port " << s->listenConn->local);
s->listenConn->close();
- s->listenConn = NULL;
+ s->listenConn = nullptr;
}
}
bool
ConnStateData::transparent() const
{
- return clientConnection != NULL && (clientConnection->flags & (COMM_TRANSPARENT|COMM_INTERCEPTION));
+ return clientConnection != nullptr && (clientConnection->flags & (COMM_TRANSPARENT|COMM_INTERCEPTION));
}
BodyPipe::Pointer
void
ConnStateData::expectNoForwarding()
{
- if (bodyPipe != NULL) {
+ if (bodyPipe != nullptr) {
debugs(33, 4, "no consumer for virgin body " << bodyPipe->status());
bodyPipe->expectNoConsumption();
}
void
ConnStateData::startDechunkingRequest()
{
- Must(bodyPipe != NULL);
+ Must(bodyPipe != nullptr);
debugs(33, 5, "start dechunking" << bodyPipe->status());
assert(!bodyParser);
bodyParser = new Http1::TeChunkedParser;
{
debugs(33, 5, "finish dechunking: " << withSuccess);
- if (bodyPipe != NULL) {
+ if (bodyPipe != nullptr) {
debugs(33, 7, "dechunked tail: " << bodyPipe->status());
BodyPipe::Pointer myPipe = bodyPipe;
stopProducingFor(bodyPipe, withSuccess); // sets bodyPipe->bodySize()
if (withSuccess) {
Must(myPipe->bodySizeKnown());
Http::StreamPointer context = pipeline.front();
- if (context != NULL && context->http && context->http->request)
+ if (context != nullptr && context->http && context->http->request)
context->http->request->setContentLength(myPipe->bodySize());
}
}
delete bodyParser;
- bodyParser = NULL;
+ bodyParser = nullptr;
}
// XXX: this is an HTTP/1-only operation
// FwdState might repin a failed connection sooner than this close
// callback is called for the failed connection.
assert(pinning.serverConnection == io.conn);
- pinning.closeHandler = NULL; // Comm unregisters handlers before calling
+ pinning.closeHandler = nullptr; // Comm unregisters handlers before calling
const bool sawZeroReply = pinning.zeroReply; // reset when unpinning
pinning.serverConnection->noteClosure();
unpinConnection(false);
- if (sawZeroReply && clientConnection != NULL) {
+ if (sawZeroReply && clientConnection != nullptr) {
debugs(33, 3, "Closing client connection on pinned zero reply.");
clientConnection->close();
}
debugs(33, 3, pinning.serverConnection);
- Must(pinning.serverConnection != NULL);
+ Must(pinning.serverConnection != nullptr);
const char *pinnedHost = "[unknown]";
pinning.host = xstrdup(request.url.host());
void
ConnStateData::startPinnedConnectionMonitoring()
{
- if (pinning.readHandler != NULL)
+ if (pinning.readHandler != nullptr)
return; // already monitoring
typedef CommCbMemFunT<ConnStateData, CommIoCbParams> Dialer;
void
ConnStateData::stopPinnedConnectionMonitoring()
{
- if (pinning.readHandler != NULL) {
+ if (pinning.readHandler != nullptr) {
Comm::ReadCancel(pinning.serverConnection->fd, pinning.readHandler);
- pinning.readHandler = NULL;
+ pinning.readHandler = nullptr;
}
}
void
ConnStateData::clientPinnedConnectionRead(const CommIoCbParams &io)
{
- pinning.readHandler = NULL; // Comm unregisters handlers before calling
+ pinning.readHandler = nullptr; // Comm unregisters handlers before calling
if (io.flag == Comm::ERR_CLOSING)
return; // close handler will clean up
// If we are still sending data to the client, do not close now. When we are done sending,
// ConnStateData::kick() checks pinning.serverConnection and will close.
// However, if we are idle, then we must close to inform the idle client and minimize races.
- if (clientIsIdle && clientConnection != NULL)
+ if (clientIsIdle && clientConnection != nullptr)
clientConnection->close();
}
cbdataReferenceDone(pinning.peer);
if (Comm::IsConnOpen(pinning.serverConnection)) {
- if (pinning.closeHandler != NULL) {
+ if (pinning.closeHandler != nullptr) {
comm_remove_close_handler(pinning.serverConnection->fd, pinning.closeHandler);
- pinning.closeHandler = NULL;
+ pinning.closeHandler = nullptr;
}
stopPinnedConnectionMonitoring();
// close the server side socket if requested
if (andClose)
pinning.serverConnection->close();
- pinning.serverConnection = NULL;
+ pinning.serverConnection = nullptr;
}
safe_free(pinning.host);
NotePairs::Pointer theNotes;
};
-const char *findTrailingHTTPVersion(const char *uriAndHTTPVersion, const char *end = NULL);
+const char *findTrailingHTTPVersion(const char *uriAndHTTPVersion, const char *end = nullptr);
int varyEvaluateMatch(StoreEntry * entry, HttpRequest * req);
purgeStatus(Http::scNone),
http(cbdataReference(clientContext)),
headers_sz(0),
- sc(NULL),
+ sc(nullptr),
old_reqsize(0),
reqsize(0),
reqofs(0),
- ourNode(NULL),
- reply(NULL),
- old_entry(NULL),
- old_sc(NULL),
+ ourNode(nullptr),
+ reply(nullptr),
+ old_entry(nullptr),
+ old_sc(nullptr),
old_lastmod(-1),
deleting(false),
collapsedRevalidation(crNone)
http->request->ignoreRange("responding with a Squid-generated error");
createStoreEntry(method, RequestFlags());
- assert(errstate->callback_data == NULL);
+ assert(errstate->callback_data == nullptr);
errorAppendEntry(http->storeEntry(), errstate);
/* Now the caller reads to get this */
}
StoreEntry *e;
store_client *sc_tmp = *scp;
- if ((e = *ep) != NULL) {
- *ep = NULL;
+ if ((e = *ep) != nullptr) {
+ *ep = nullptr;
storeUnregister(sc_tmp, e, this);
- *scp = NULL;
+ *scp = nullptr;
e->unlock("clientReplyContext::removeStoreReference");
}
}
void
clientReplyContext::saveState()
{
- assert(old_sc == NULL);
+ assert(old_sc == nullptr);
debugs(88, 3, "clientReplyContext::saveState: saving store context");
old_entry = http->storeEntry();
old_sc = sc;
old_reqsize = reqsize;
tempBuffer.offset = reqofs;
/* Prevent accessing the now saved entries */
- http->storeEntry(NULL);
- sc = NULL;
+ http->storeEntry(nullptr);
+ sc = nullptr;
reqsize = 0;
reqofs = 0;
}
void
clientReplyContext::restoreState()
{
- assert(old_sc != NULL);
+ assert(old_sc != nullptr);
debugs(88, 3, "clientReplyContext::restoreState: Restoring store context");
removeClientStoreReference(&sc, http);
http->storeEntry(old_entry);
http->request->lastmod = old_lastmod;
http->request->etag = old_etag;
/* Prevent accessed the old saved entries */
- old_entry = NULL;
- old_sc = NULL;
+ old_entry = nullptr;
+ old_sc = nullptr;
old_lastmod = -1;
old_etag.clean();
old_reqsize = 0;
http->request->lastmod = lastmod;
if (!http->request->header.has(Http::HdrType::IF_NONE_MATCH)) {
- ETag etag = {NULL, -1}; // TODO: make that a default ETag constructor
+ ETag etag = {nullptr, -1}; // TODO: make that a default ETag constructor
if (old_entry->hasEtag(etag) && !etag.weak)
http->request->etag = etag.str;
}
* A refcounted pointer so that FwdState stays around as long as
* this clientReplyContext does
*/
- Comm::ConnectionPointer conn = http->getConn() != NULL ? http->getConn()->clientConnection : NULL;
+ Comm::ConnectionPointer conn = http->getConn() != nullptr ? http->getConn()->clientConnection : nullptr;
FwdState::Start(conn, http->storeEntry(), http->request, http->al);
}
/* Register with storage manager to receive updates when data comes in. */
debugs(88, 3, http->storeEntry()->url() << ", " << (long unsigned) result.length << " bytes");
- if (http->storeEntry() == NULL)
+ if (http->storeEntry() == nullptr)
return;
if (result.flags.error && !EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED))
debugs(88, 3, "clientCacheHit: " << http->uri << ", " << result.length << " bytes");
- if (http->storeEntry() == NULL) {
+ if (http->storeEntry() == nullptr) {
debugs(88, 3, "clientCacheHit: request aborted");
return;
} else if (result.flags.error) {
* to requery the cache.
*/
removeClientStoreReference(&sc, http);
- e = NULL;
+ e = nullptr;
/* Note: varyEvalyateMatch updates the request with vary information
* so we only get here once. (it also takes care of cancelling loops)
*/
if (r->method == Http::METHOD_PURGE) {
debugs(88, 5, "PURGE gets a HIT");
removeClientStoreReference(&sc, http);
- e = NULL;
+ e = nullptr;
purgeRequest();
return;
}
{
char *url = http->uri;
HttpRequest *r = http->request;
- ErrorState *err = NULL;
+ ErrorState *err = nullptr;
debugs(88, 4, r->method << ' ' << url);
/**
{
debugs(88, 4, http->request->method << ' ' << http->uri);
http->al->http.code = Http::scGatewayTimeout;
- ErrorState *err = clientBuildError(ERR_ONLY_IF_CACHED_MISS, Http::scGatewayTimeout, NULL,
+ ErrorState *err = clientBuildError(ERR_ONLY_IF_CACHED_MISS, Http::scGatewayTimeout, nullptr,
http->getConn(), http->request, http->al);
removeClientStoreReference(&sc, http);
startError(err);
if (!Config2.onoff.enable_purge) {
http->updateLoggingTags(LOG_TCP_DENIED);
- ErrorState *err = clientBuildError(ERR_ACCESS_DENIED, Http::scForbidden, NULL,
+ ErrorState *err = clientBuildError(ERR_ACCESS_DENIED, Http::scForbidden, nullptr,
http->getConn(), http->request, http->al);
startError(err);
return;
triggerInitialStoreRead();
const HttpReplyPointer rep(new HttpReply);
- rep->setHeaders(purgeStatus, NULL, NULL, 0, 0, -1);
+ rep->setHeaders(purgeStatus, nullptr, nullptr, 0, 0, -1);
http->storeEntry()->replaceHttpReply(rep);
http->storeEntry()->complete();
}
http->storeEntry()->releaseRequest();
http->storeEntry()->buffer();
const HttpReplyPointer rep(new HttpReply);
- rep->setHeaders(Http::scOkay, NULL, "text/plain", http->request->prefixLen(), 0, squid_curtime);
+ rep->setHeaders(Http::scOkay, nullptr, "text/plain", http->request->prefixLen(), 0, squid_curtime);
http->storeEntry()->replaceHttpReply(rep);
http->request->swapOut(http->storeEntry());
http->storeEntry()->complete();
{
StoreEntry *entry = http->storeEntry();
- if (entry == NULL)
+ if (entry == nullptr)
return 0;
/*
* Now, handle STORE_PENDING objects
*/
MemObject *mem = http->storeEntry()->mem_obj;
- assert(mem != NULL);
- assert(http->request != NULL);
+ assert(mem != nullptr);
+ assert(http->request != nullptr);
/* mem->reply was wrong because it uses the UPSTREAM header length!!! */
if (headers_sz == 0)
int done;
/* Here because lower nodes don't need it */
- if (http->storeEntry() == NULL) {
+ if (http->storeEntry() == nullptr) {
debugs(88, 5, "clientReplyStatus: no storeEntry");
return STREAM_FAILED; /* yuck, but what can we do? */
}
* responses
*/
Auth::UserRequest::AddReplyAuthHeader(reply, request->auth_user_request, request, 0, 1);
- } else if (request->auth_user_request != NULL)
+ } else if (request->auth_user_request != nullptr)
Auth::UserRequest::AddReplyAuthHeader(reply, request->auth_user_request, request, http->flags.accel, 0);
#endif
void
clientReplyContext::cloneReply()
{
- assert(reply == NULL);
+ assert(reply == nullptr);
reply = http->storeEntry()->mem().freshestReply().clone();
HTTPMSGLOCK(reply);
// Ideally, ClientHttpRequest::storeEntry() should lock/unlock, but it is
// used so inconsistently that simply adding locking there leads to bugs.
e->lock("clientReplyContext::forgetHit");
- http->storeEntry(NULL);
+ http->storeEntry(nullptr);
e->unlock("clientReplyContext::forgetHit"); // may delete e
}
clientGetMoreData(clientStreamNode * aNode, ClientHttpRequest * http)
{
/* Test preconditions */
- assert(aNode != NULL);
+ assert(aNode != nullptr);
assert(cbdataReferenceValid(aNode));
- assert(aNode->node.prev == NULL);
- assert(aNode->node.next != NULL);
+ assert(aNode->node.prev == nullptr);
+ assert(aNode->node.next != nullptr);
clientReplyContext *context = dynamic_cast<clientReplyContext *>(aNode->data.getRaw());
assert (context);
assert(context->http == http);
clientReplyContext::doGetMoreData()
{
/* We still have to do store logic processing - vary, cache hit etc */
- if (http->storeEntry() != NULL) {
+ if (http->storeEntry() != nullptr) {
/* someone found the object in the cache for us */
StoreIOBuffer localTempBuffer;
flags.complete = 1;
http->request->flags.streamError = true;
localTempBuffer.flags.error = result.flags.error;
- clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, NULL,
+ clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, nullptr,
localTempBuffer);
}
if (localTempBuffer.length)
localTempBuffer.data = source;
- clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, NULL,
+ clientStreamCallback((clientStreamNode*)http->client_stream.head->data, http, nullptr,
localTempBuffer);
}
clientReplyContext::sendBodyTooLargeError()
{
http->updateLoggingTags(LOG_TCP_DENIED_REPLY);
- ErrorState *err = clientBuildError(ERR_TOO_BIG, Http::scForbidden, NULL,
+ ErrorState *err = clientBuildError(ERR_TOO_BIG, Http::scForbidden, nullptr,
http->getConn(), http->request, http->al);
removeClientStoreReference(&(sc), http);
HTTPMSGUNLOCK(reply);
if (page_id == ERR_NONE)
page_id = ERR_ACCESS_DENIED;
- err = clientBuildError(page_id, Http::scForbidden, NULL,
+ err = clientBuildError(page_id, Http::scForbidden, nullptr,
http->getConn(), http->request, http->al);
removeClientStoreReference(&sc, http);
esiEnableProcessing(reply)) {
debugs(88, 2, "Enabling ESI processing for " << http->uri);
clientStreamInsertHead(&http->client_stream, esiStreamRead,
- esiProcessStream, esiStreamDetach, esiStreamStatus, NULL);
+ esiProcessStream, esiStreamDetach, esiStreamStatus, nullptr);
}
#endif
if (next()->readBuffer.offset > body_size) {
/* Can't use any of the body we received. send nothing */
localTempBuffer.length = 0;
- localTempBuffer.data = NULL;
+ localTempBuffer.data = nullptr;
} else {
localTempBuffer.length = body_size - next()->readBuffer.offset;
localTempBuffer.data = body_buf + next()->readBuffer.offset;
assert(reqofs <= HTTP_REQBUF_SZ || flags.headersSent);
- assert(http->request != NULL);
+ assert(http->request != nullptr);
/* ESI TODO: remove this assert once everything is stable */
assert(http->client_stream.head->data
void
clientReplyContext::createStoreEntry(const HttpRequestMethod& m, RequestFlags reqFlags)
{
- assert(http != NULL);
+ assert(http != nullptr);
/*
* For erroneous requests, we might not have a h->request,
* so make a fake one.
*/
- if (http->request == NULL) {
+ if (http->request == nullptr) {
const auto connManager = http->getConn();
const auto mx = MasterXaction::MakePortful(connManager ? connManager->port : nullptr);
// XXX: These fake URI parameters shadow the real (or error:...) URI.
al->updateError(aConn->bareError);
#if USE_OPENSSL
- if (aConn->clientConnection != NULL && aConn->clientConnection->isOpen()) {
+ if (aConn->clientConnection != nullptr && aConn->clientConnection->isOpen()) {
if (auto ssl = fd_table[aConn->clientConnection->fd].ssl.get())
al->cache.sslClientCert.resetWithoutLocking(SSL_get_peer_certificate(ssl));
}
logRequest();
- loggingEntry(NULL);
+ loggingEntry(nullptr);
if (request)
checkFailureRatio(request->error.category, al->hier.code);
#if USE_ADAPTATION
announceInitiatorAbort(virginHeadSource);
- if (adaptedBodySource != NULL)
+ if (adaptedBodySource != nullptr)
stopConsumingFrom(adaptedBodySource);
#endif
char *tailbuf, size_t taillen, const MasterXaction::Pointer &mx)
{
size_t url_sz;
- ClientHttpRequest *http = new ClientHttpRequest(NULL);
+ ClientHttpRequest *http = new ClientHttpRequest(nullptr);
HttpRequest *request;
StoreIOBuffer tempBuffer;
- if (http->al != NULL)
+ if (http->al != nullptr)
http->al->cache.start_time = current_time;
/* this is only used to adjust the connection offset in client_side.c */
http->req_sz = 0;
if (cbdataReferenceValid(http_))
return true;
- http = NULL;
+ http = nullptr;
cbdataReferenceDone(http_);
nullptr,
http->getConn(),
http->request,
- NULL,
+ nullptr,
#if USE_AUTH
- http->getConn() != NULL && http->getConn()->getAuth() != NULL ?
+ http->getConn() != nullptr && http->getConn()->getAuth() != nullptr ?
http->getConn()->getAuth() : http->request->auth_user_request);
#else
NULL);
}
// Locate if there is a port attached, strip ready for IP lookup
- char *portStr = NULL;
+ char *portStr = nullptr;
char *hostB = xstrdup(host);
host = hostB;
if (host[0] == '[') {
// IPv6 literal.
portStr = strchr(hostB, ']');
if (portStr && *(++portStr) != ':') {
- portStr = NULL;
+ portStr = nullptr;
}
} else {
// Domain or IPv4 literal with port
if (portStr) {
*portStr = '\0'; // strip the ':'
if (*(++portStr) != '\0') {
- char *end = NULL;
+ char *end = nullptr;
int64_t ret = strtoll(portStr, &end, 10);
if (end == portStr || *end != '\0' || ret < 1 || ret > 0xFFFF) {
// invalid port details. Replace the ':'
*(--portStr) = ':';
- portStr = NULL;
+ portStr = nullptr;
} else
port = (ret & 0xFFFF);
}
void
ClientRequestContext::clientAccessCheckDone(const Acl::Answer &answer)
{
- acl_checklist = NULL;
+ acl_checklist = nullptr;
err_type page_id;
Http::StatusCode status;
debugs(85, 2, "The request " << http->request->method << ' ' <<
#if USE_AUTH
char const *proxy_auth_msg = "<null>";
- if (http->getConn() != NULL && http->getConn()->getAuth() != NULL)
+ if (http->getConn() != nullptr && http->getConn()->getAuth() != nullptr)
proxy_auth_msg = http->getConn()->getAuth()->denyMessage("<null>");
- else if (http->request->auth_user_request != NULL)
+ else if (http->request->auth_user_request != nullptr)
proxy_auth_msg = http->request->auth_user_request->denyMessage("<null>");
#endif
#if USE_AUTH
error->auth_user_request =
- http->getConn() != NULL && http->getConn()->getAuth() != NULL ?
+ http->getConn() != nullptr && http->getConn()->getAuth() != nullptr ?
http->getConn()->getAuth() : http->request->auth_user_request;
#endif
#if ICAP_CLIENT
Adaptation::Icap::History::Pointer ih = request->icapHistory();
- if (ih != NULL) {
- if (getConn() != NULL && getConn()->clientConnection != NULL) {
+ if (ih != nullptr) {
+ if (getConn() != nullptr && getConn()->clientConnection != nullptr) {
ih->rfc931 = getConn()->clientConnection->rfc931;
#if USE_OPENSSL
if (getConn()->clientConnection->isOpen()) {
{
ClientRequestContext *context = (ClientRequestContext *)data;
ClientHttpRequest *http = context->http;
- context->acl_checklist = NULL;
+ context->acl_checklist = nullptr;
if (answer.allowed())
redirectStart(http, clientRedirectDoneWrapper, context);
{
ClientRequestContext *context = static_cast<ClientRequestContext *>(data);
ClientHttpRequest *http = context->http;
- context->acl_checklist = NULL;
+ context->acl_checklist = nullptr;
if (answer.allowed())
storeIdStart(http, clientStoreIdDoneWrapper, context);
const char *statusNote = reply.notes.findFirst("status");
const char *urlNote = reply.notes.findFirst("url");
- if (urlNote != NULL) {
+ if (urlNote != nullptr) {
// HTTP protocol redirect to be done.
// TODO: change default redirect status for appropriate requests
// HTTP/1.1 client contacting reverse-proxy should get 307 (Http::scTemporaryRedirect)
// HTTP/1.1 client being diverted by forward-proxy should get 303 (Http::scSeeOther)
Http::StatusCode status = Http::scFound;
- if (statusNote != NULL) {
+ if (statusNote != nullptr) {
const char * result = statusNote;
status = static_cast<Http::StatusCode>(atoi(result));
}
urlNote = reply.notes.findFirst("rewrite-url");
// prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
- if (urlNote != NULL && strcmp(urlNote, http->uri)) {
+ if (urlNote != nullptr && strcmp(urlNote, http->uri)) {
AnyP::Uri tmpUrl;
if (tmpUrl.parse(old_request->method, SBuf(urlNote))) {
HttpRequest *new_request = old_request->clone();
new_request->flags.redirected = true;
// unlink bodypipe from the old request. Not needed there any longer.
- if (old_request->body_pipe != NULL) {
- old_request->body_pipe = NULL;
+ if (old_request->body_pipe != nullptr) {
+ old_request->body_pipe = nullptr;
debugs(61,2, "URL-rewriter diverts body_pipe " << new_request->body_pipe <<
" from request " << old_request << " to " << new_request);
}
/* XXX PIPELINE: This is inaccurate during pipelining */
- if (http->getConn() != NULL && Comm::IsConnOpen(http->getConn()->clientConnection))
+ if (http->getConn() != nullptr && Comm::IsConnOpen(http->getConn()->clientConnection))
fd_note(http->getConn()->clientConnection->fd, http->uri);
assert(http->uri);
const char *urlNote = reply.notes.findFirst("store-id");
// prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.
- if (urlNote != NULL && strcmp(urlNote, http->uri) ) {
+ if (urlNote != nullptr && strcmp(urlNote, http->uri) ) {
// Debug section required for some very specific cases.
debugs(85, 9, "Setting storeID with: " << urlNote );
http->request->store_id = urlNote;
void
ClientRequestContext::checkNoCacheDone(const Acl::Answer &answer)
{
- acl_checklist = NULL;
+ acl_checklist = nullptr;
if (answer.denied()) {
http->request->flags.noCache = true; // do not read reply from cache
http->request->flags.cachable = false; // do not store reply into cache
#if USE_AUTH
// Preserve authentication info for the ssl-bumped request
- if (request->auth_user_request != NULL)
+ if (request->auth_user_request != nullptr)
getConn()->setAuth(request->auth_user_request, "SSL-bumped CONNECT");
#endif
calloutContext->adaptation_acl_check_done = true;
if (Adaptation::AccessCheck::Start(
Adaptation::methodReqmod, Adaptation::pointPreCache,
- request, NULL, calloutContext->http->al, this))
+ request, nullptr, calloutContext->http->al, this))
return; // will call callback
}
#endif
// set final error but delay sending until we bump
Ssl::ServerBump *srvBump = new Ssl::ServerBump(this, e, Ssl::bumpClientFirst);
errorAppendEntry(e, calloutContext->error);
- calloutContext->error = NULL;
+ calloutContext->error = nullptr;
getConn()->setServerBump(srvBump);
e->unlock("ClientHttpRequest::doCallouts+sslBumpNeeded");
} else
assert (repContext);
repContext->setReplyToStoreEntry(e, "immediate SslBump error");
errorAppendEntry(e, calloutContext->error);
- calloutContext->error = NULL;
+ calloutContext->error = nullptr;
if (calloutContext->readNextRequest && getConn())
getConn()->flags.readMore = true; // resume any pipeline reads.
node = (clientStreamNode *)client_stream.tail->data;
cbdataReferenceDone(calloutContext->http);
delete calloutContext;
- calloutContext = NULL;
+ calloutContext = nullptr;
#if HEADERS_LOG
headersLog(0, 1, request->method, request);
#if ICAP_CLIENT
Adaptation::Icap::History::Pointer ih = request->icapHistory();
- if (ih != NULL)
+ if (ih != nullptr)
ih->logType = loggingTags();
#endif
}
assert(!virginHeadSource);
assert(!adaptedBodySource);
virginHeadSource = initiateAdaptation(
- new Adaptation::Iterator(request, NULL, al, g));
+ new Adaptation::Iterator(request, nullptr, al, g));
// we could try to guess whether we can bypass this adaptation
// initiation failure, but it should not really happen
debugs(85,3, "REQMOD reply is HTTP reply");
// subscribe to receive reply body
- if (new_rep->body_pipe != NULL) {
+ if (new_rep->body_pipe != nullptr) {
adaptedBodySource = new_rep->body_pipe;
int consumer_ok = adaptedBodySource->setConsumerIfNotLate(this);
assert(consumer_ok);
AclMatchedName = answer.ruleId.termedBuf();
assert(calloutContext);
calloutContext->clientAccessCheckDone(ACCESS_DENIED);
- AclMatchedName = NULL;
+ AclMatchedName = nullptr;
}
void
ClientHttpRequest::noteMoreBodyDataAvailable(BodyPipe::Pointer)
{
assert(request_satisfaction_mode);
- assert(adaptedBodySource != NULL);
+ assert(adaptedBodySource != nullptr);
if (size_t contentSize = adaptedBodySource->buf().contentSize()) {
const size_t spaceAvailable = storeEntry()->bytesWanted(Range<size_t>(0,contentSize));
receivedWholeAdaptedReply = true;
// should we end request satisfaction now?
- if (adaptedBodySource != NULL && adaptedBodySource->exhausted())
+ if (adaptedBodySource != nullptr && adaptedBodySource->exhausted())
endRequestSatisfaction();
}
debugs(85,3, "handleAdaptationFailure(" << bypassable << ")");
const bool usedStore = storeEntry() && !storeEntry()->isEmpty();
- const bool usedPipe = request->body_pipe != NULL &&
+ const bool usedPipe = request->body_pipe != nullptr &&
request->body_pipe->consumedSize() > 0;
if (bypassable && !usedStore && !usedPipe) {
nullptr, c, request, al);
#if USE_AUTH
calloutContext->error->auth_user_request =
- c != NULL && c->getAuth() != NULL ? c->getAuth() : request->auth_user_request;
+ c != nullptr && c->getAuth() != nullptr ? c->getAuth() : request->auth_user_request;
#endif
calloutContext->error->detailError(errDetail);
calloutContext->readNextRequest = true;
- if (c != NULL)
+ if (c != nullptr)
c->expectNoForwarding();
}
//else if(calloutContext == NULL) is it possible?
HTTPMSGUNLOCK(theVirginReply);
HTTPMSGUNLOCK(theFinalReply);
- if (responseBodyBuffer != NULL) {
+ if (responseBodyBuffer != nullptr) {
delete responseBodyBuffer;
- responseBodyBuffer = NULL;
+ responseBodyBuffer = nullptr;
}
}
Client::swanSong()
{
// get rid of our piping obligations
- if (requestBodySource != NULL)
+ if (requestBodySource != nullptr)
stopConsumingFrom(requestBodySource);
#if USE_ADAPTATION
completed = true;
originalRequest()->hier.stopPeerClock(true);
- if (requestBodySource != NULL)
+ if (requestBodySource != nullptr)
stopConsumingFrom(requestBodySource);
- if (responseBodyBuffer != NULL)
+ if (responseBodyBuffer != nullptr)
return;
serverComplete2();
debugs(11,5, "serverComplete2 " << this);
#if USE_ADAPTATION
- if (virginBodyDestination != NULL)
+ if (virginBodyDestination != nullptr)
stopProducingFor(virginBodyDestination, true);
if (!doneWithAdaptation())
Client::completeForwarding()
{
debugs(11,5, "completing forwarding for " << fwd);
- assert(fwd != NULL);
+ assert(fwd != nullptr);
doneWithFwd = "completeForwarding()";
fwd->complete();
}
bool Client::startRequestBodyFlow()
{
HttpRequestPointer r(originalRequest());
- assert(r->body_pipe != NULL);
+ assert(r->body_pipe != nullptr);
requestBodySource = r->body_pipe;
if (requestBodySource->setConsumerIfNotLate(this)) {
debugs(11,3, "expecting request body from " <<
debugs(11,3, "aborting on partially consumed request body: " <<
requestBodySource->status());
- requestBodySource = NULL;
+ requestBodySource = nullptr;
return false;
}
Client::doneSendingRequestBody()
{
debugs(9,3, "done sending request body");
- assert(requestBodySource != NULL);
+ assert(requestBodySource != nullptr);
stopConsumingFrom(requestBodySource);
// kids extend this
void
Client::handleRequestBodyProducerAborted()
{
- if (requestSender != NULL)
+ if (requestSender != nullptr)
debugs(9,3, "fyi: request body aborted while we were sending");
fwd->dontRetry(true); // the problem is not with the server
debugs(11, 5, "sentRequestBody: FD " << io.fd << ": size " << io.size << ": errflag " << io.flag << ".");
debugs(32,3, "sentRequestBody called");
- requestSender = NULL;
+ requestSender = nullptr;
if (io.size > 0) {
fd_bytes(io.fd, io.size, FD_WRITE);
void
Client::sendMoreRequestBody()
{
- assert(requestBodySource != NULL);
+ assert(requestBodySource != nullptr);
assert(!requestSender);
const Comm::ConnectionPointer conn = dataConnection();
Comm::Write(conn, &buf, requestSender);
} else {
debugs(9,3, "will wait for more request body bytes or eof");
- requestSender = NULL;
+ requestSender = nullptr;
}
}
Client::getMoreRequestBody(MemBuf &buf)
{
// default implementation does not encode request body content
- Must(requestBodySource != NULL);
+ Must(requestBodySource != nullptr);
return requestBodySource->getMoreData(buf);
}
{
debugs(11,5, "cleaning ICAP; ACL: " << adaptationAccessCheckPending);
- if (virginBodyDestination != NULL)
+ if (virginBodyDestination != nullptr)
stopProducingFor(virginBodyDestination, false);
announceInitiatorAbort(adaptedHeadSource);
- if (adaptedBodySource != NULL)
+ if (adaptedBodySource != nullptr)
stopConsumingFrom(adaptedBodySource);
if (!adaptationAccessCheckPending) // we cannot cancel a pending callback
if (responseBodyBuffer) {
if (putSize == responseBodyBuffer->contentSize()) {
delete responseBodyBuffer;
- responseBodyBuffer = NULL;
+ responseBodyBuffer = nullptr;
} else {
responseBodyBuffer->consume(putSize);
}
Client::noteMoreBodySpaceAvailable(BodyPipe::Pointer)
{
if (responseBodyBuffer) {
- addVirginReplyBody(NULL, 0); // kick the buffered fragment alive again
+ addVirginReplyBody(nullptr, 0); // kick the buffered fragment alive again
if (completed && !responseBodyBuffer) {
serverComplete2();
return;
// return. Tell the ICAP side that it is on its own.
HttpReply *rep = dynamic_cast<HttpReply*>(msg);
assert(rep);
- if (rep->body_pipe != NULL)
+ if (rep->body_pipe != nullptr)
rep->body_pipe->expectNoConsumption();
return;
setFinalReply(rep);
assert(!adaptedBodySource);
- if (rep->body_pipe != NULL) {
+ if (rep->body_pipe != nullptr) {
// subscribe to receive adapted body
adaptedBodySource = rep->body_pipe;
// assume that ICAP does not auto-consume on failures
handleMoreAdaptedBodyAvailable();
- if (adaptedBodySource != NULL && adaptedBodySource->exhausted())
+ if (adaptedBodySource != nullptr && adaptedBodySource->exhausted())
endAdaptedBodyConsumption();
}
receivedWholeAdaptedReply = true;
// end consumption if we consumed everything
- if (adaptedBodySource != NULL && adaptedBodySource->exhausted())
+ if (adaptedBodySource != nullptr && adaptedBodySource->exhausted())
endAdaptedBodyConsumption();
// else resumeBodyStorage() will eventually consume the rest
}
return 0; // Stop reading if already overflowed waiting for ICAP to catch up
}
- if (virginBodyDestination != NULL) {
+ if (virginBodyDestination != nullptr) {
/*
* BodyPipe buffer has a finite size limit. We
* should not read more data from the network than will fit
return 0; // Stop reading if already overflowed waiting for ICAP to catch up
}
- if (virginBodyDestination != NULL) {
+ if (virginBodyDestination != nullptr) {
/*
* BodyPipe buffer has a finite size limit. We
* should not read more data from the network than will fit
const AsyncCall::Pointer &aCloser)
{
assert(!Comm::IsConnOpen(conn));
- assert(closer == NULL);
+ assert(closer == nullptr);
assert(Comm::IsConnOpen(newConn));
- assert(aCloser != NULL);
+ assert(aCloser != nullptr);
conn = newConn;
conn->leaveOrphanage();
void
Ftp::Channel::clear()
{
- conn = NULL;
- closer = NULL;
+ conn = nullptr;
+ closer = nullptr;
}
/* Ftp::CtrlChannel */
Ftp::CtrlChannel::CtrlChannel():
- buf(NULL),
+ buf(nullptr),
size(0),
offset(0),
- message(NULL),
- last_command(NULL),
- last_reply(NULL),
+ message(nullptr),
+ last_command(nullptr),
+ last_reply(nullptr),
replycode(0)
{
buf = static_cast<char*>(memAllocBuf(4096, &size));
/* Ftp::DataChannel */
Ftp::DataChannel::DataChannel():
- readBuf(NULL),
- host(NULL),
+ readBuf(nullptr),
+ host(nullptr),
port(0),
read_pending(false)
{
ctrl(),
data(),
state(BEGIN),
- old_request(NULL),
- old_reply(NULL),
+ old_request(nullptr),
+ old_reply(nullptr),
shortenReadTimeout(false)
{
++statCounter.server.all.requests;
safe_free(old_request);
safe_free(old_reply);
- fwd = NULL; // refcounted
+ fwd = nullptr; // refcounted
}
void
void
Ftp::Client::initReadBuf()
{
- if (data.readBuf == NULL) {
+ if (data.readBuf == nullptr) {
data.readBuf = new MemBuf;
data.readBuf->init(4096, SQUID_TCP_SO_RCVBUF);
}
ftperr->xerrno = xerrno;
ftperr->ftp.server_msg = ctrl.message;
- ctrl.message = NULL;
+ ctrl.message = nullptr;
if (old_request)
command = old_request;
buf = ctrl.last_reply + strcspn(ctrl.last_reply, "0123456789");
const char *forceIp = Config.Ftp.sanitycheck ?
- fd_table[ctrl.conn->fd].ipaddr : NULL;
+ fd_table[ctrl.conn->fd].ipaddr : nullptr;
if (!Ftp::ParseIpPort(buf, forceIp, srvAddr)) {
debugs(9, DBG_IMPORTANT, "Unsafe PASV reply from " <<
ctrl.conn->remote << ": " << ctrl.last_reply);
*/
debugs(9, 5, "scanning: " << ctrl.last_reply);
buf = ctrl.last_reply;
- while (buf != NULL && *buf != '\0' && *buf != '\n' && *buf != '(')
+ while (buf != nullptr && *buf != '\0' && *buf != '\n' && *buf != '(')
++buf;
- if (buf != NULL && *buf == '\n')
+ if (buf != nullptr && *buf == '\n')
++buf;
- if (buf == NULL || *buf == '\0') {
+ if (buf == nullptr || *buf == '\0') {
/* handle broken server (RFC 2428 says MUST specify supported protocols in 522) */
debugs(9, DBG_IMPORTANT, "ERROR: Broken FTP Server at " << ctrl.conn->remote << ". 522 error missing protocol negotiation hints");
return sendPassive();
default: {
bool doEpsv = true;
if (Config.accessList.ftp_epsv) {
- ACLFilledChecklist checklist(Config.accessList.ftp_epsv, fwd->request, NULL);
+ ACLFilledChecklist checklist(Config.accessList.ftp_epsv, fwd->request, nullptr);
doEpsv = checklist.fastCheck().allowed();
}
if (!doEpsv) {
if (ctrl.message)
wordlistDestroy(&ctrl.message);
- ctrl.message = NULL; //No message to return to client.
+ ctrl.message = nullptr; //No message to return to client.
ctrl.offset = 0; //reset readed response, to make room read the next response
writeCommand(mb.content());
debugs(9, 4, status());
if (data.conn)
data.conn->noteClosure();
- if (data.listenConn != NULL) {
+ if (data.listenConn != nullptr) {
data.listenConn->close();
- data.listenConn = NULL;
+ data.listenConn = nullptr;
}
data.clear();
}
typedef CommCbMemFunT<Client, CommIoCbParams> Dialer;
AsyncCall::Pointer call = JobCallback(9, 5, Dialer, this,
Ftp::Client::writeCommandCallback);
- Comm::Write(ctrl.conn, ctrl.last_command, strlen(ctrl.last_command), call, NULL);
+ Comm::Write(ctrl.conn, ctrl.last_command, strlen(ctrl.last_command), call, nullptr);
scheduleReadControlReply(0);
}
Ftp::Client::abortAll(const char *reason)
{
debugs(9, 3, "aborting transaction for " << reason <<
- "; FD " << (ctrl.conn!=NULL?ctrl.conn->fd:-1) << ", Data FD " << (data.conn!=NULL?data.conn->fd:-1) << ", this " << this);
+ "; FD " << (ctrl.conn!=nullptr?ctrl.conn->fd:-1) << ", Data FD " << (data.conn!=nullptr?data.conn->fd:-1) << ", this " << this);
mustStop(reason);
}
char *end;
int usable;
int complete = 0;
- wordlist *head = NULL;
+ wordlist *head = nullptr;
wordlist *list;
wordlist **tail = &head;
size_t linelen;
ftpReadTransferDone, /* READING_DATA (RETR,LIST,NLST) */
ftpWriteTransferDone, /* WRITING_DATA (STOR) */
ftpReadMkdir, /* SENT_MKDIR */
- NULL, /* SENT_FEAT */
- NULL, /* SENT_PWD */
- NULL, /* SENT_CDUP*/
- NULL, /* SENT_DATA_REQUEST */
- NULL /* SENT_COMMAND */
+ nullptr, /* SENT_FEAT */
+ nullptr, /* SENT_PWD */
+ nullptr, /* SENT_CDUP*/
+ nullptr, /* SENT_DATA_REQUEST */
+ nullptr /* SENT_COMMAND */
};
/// handler called by Comm when FTP data channel is closed unexpectedly
AsyncJob("FtpStateData"),
Ftp::Client(fwdState),
password_url(0),
- reply_hdr(NULL),
+ reply_hdr(nullptr),
reply_hdr_state(0),
conn_att(0),
login_att(0),
mdtm(-1),
theSize(-1),
- pathcomps(NULL),
- filepath(NULL),
- dirpath(NULL),
+ pathcomps(nullptr),
+ filepath(nullptr),
+ dirpath(nullptr),
restart_offset(0),
- proxy_host(NULL),
+ proxy_host(nullptr),
list_width(0),
- old_filepath(NULL),
+ old_filepath(nullptr),
typecode('\0')
{
debugs(9, 3, entry->url());
if (reply_hdr) {
memFree(reply_hdr, MEM_8K_BUF);
- reply_hdr = NULL;
+ reply_hdr = nullptr;
}
if (pathcomps)
static ftpListParts *
ftpListParseParts(const char *buf, struct Ftp::GatewayFlags flags)
{
- ftpListParts *p = NULL;
- char *t = NULL;
+ ftpListParts *p = nullptr;
+ char *t = nullptr;
struct FtpLineToken {
char *token = nullptr; ///< token image copied from the received line
size_t pos = 0; ///< token offset on the received line
int i;
int n_tokens;
static char tbuf[128];
- char *xbuf = NULL;
+ char *xbuf = nullptr;
static int scan_ftp_initialized = 0;
static regex_t scan_ftp_integer;
static regex_t scan_ftp_time;
regcomp(&scan_ftp_dostime, "^[0123456789]+:[0123456789]+[AP]M$", REG_EXTENDED | REG_NOSUB | REG_ICASE);
}
- if (buf == NULL)
- return NULL;
+ if (buf == nullptr)
+ return nullptr;
if (*buf == '\0')
- return NULL;
+ return nullptr;
p = (ftpListParts *)xcalloc(1, sizeof(ftpListParts));
return p;
}
- for (t = strtok(xbuf, w_space); t && n_tokens < MAX_TOKENS; t = strtok(NULL, w_space)) {
+ for (t = strtok(xbuf, w_space); t && n_tokens < MAX_TOKENS; t = strtok(nullptr, w_space)) {
tokens[n_tokens].token = xstrdup(t);
tokens[n_tokens].pos = t - xbuf;
++n_tokens;
if (!is_month(month))
continue;
- if (regexec(&scan_ftp_integer, size, 0, NULL, 0) != 0)
+ if (regexec(&scan_ftp_integer, size, 0, nullptr, 0) != 0)
continue;
- if (regexec(&scan_ftp_integer, day, 0, NULL, 0) != 0)
+ if (regexec(&scan_ftp_integer, day, 0, nullptr, 0) != 0)
continue;
- if (regexec(&scan_ftp_time, year, 0, NULL, 0) != 0) /* Yr | hh:mm */
+ if (regexec(&scan_ftp_time, year, 0, nullptr, 0) != 0) /* Yr | hh:mm */
continue;
const auto *copyFrom = buf + tokens[i].pos;
// TODO: replace isTypeA and isTypeB with a regex.
if (isTypeA || isTypeB) {
p->type = *tokens[0].token;
- p->size = strtoll(size, NULL, 10);
+ p->size = strtoll(size, nullptr, 10);
const auto finalDateSize = snprintf(tbuf, sizeof(tbuf), "%s %2s %5s", month, day, year);
assert(finalDateSize >= 0);
p->date = xstrdup(tbuf);
/* try it as a DOS listing, 04-05-70 09:33PM ... */
if (n_tokens > 3 &&
- regexec(&scan_ftp_dosdate, tokens[0].token, 0, NULL, 0) == 0 &&
- regexec(&scan_ftp_dostime, tokens[1].token, 0, NULL, 0) == 0) {
+ regexec(&scan_ftp_dosdate, tokens[0].token, 0, nullptr, 0) == 0 &&
+ regexec(&scan_ftp_dostime, tokens[1].token, 0, nullptr, 0) == 0) {
if (!strcasecmp(tokens[2].token, "<dir>")) {
p->type = 'd';
} else {
p->type = '-';
- p->size = strtoll(tokens[2].token, NULL, 10);
+ p->size = strtoll(tokens[2].token, nullptr, 10);
}
snprintf(tbuf, sizeof(tbuf), "%s %s", tokens[0].token, tokens[1].token);
Ftp::Gateway::handleControlReply()
{
Ftp::Client::handleControlReply();
- if (ctrl.message == NULL)
+ if (ctrl.message == nullptr)
return; // didn't get complete reply yet
/* Copy the message except for the last line to cwd_message to be
ftpSendUser(ftpState);
} else if (code == 120) {
- if (NULL != ftpState->ctrl.message)
+ if (nullptr != ftpState->ctrl.message)
debugs(9, DBG_IMPORTANT, "FTP server is busy: " << ftpState->ctrl.message->key);
return;
void
Ftp::Gateway::loginFailed()
{
- ErrorState *err = NULL;
+ ErrorState *err = nullptr;
if ((state == SENT_USER || state == SENT_PASS) && ctrl.replycode >= 400) {
if (ctrl.replycode == 421 || ctrl.replycode == 426) {
if (!ftpState || !ftpState->haveControlChannel("ftpSendUser"))
return;
- if (ftpState->proxy_host != NULL)
+ if (ftpState->proxy_host != nullptr)
snprintf(cbuf, CTRL_BUFLEN, "USER %s@%s\r\n", ftpState->user, ftpState->request->url.host());
else
snprintf(cbuf, CTRL_BUFLEN, "USER %s\r\n", ftpState->user);
safe_free(ftpState->dirpath);
ftpState->dirpath = ftpState->filepath;
- ftpState->filepath = NULL;
+ ftpState->filepath = nullptr;
/* Done? */
- if (ftpState->pathcomps == NULL) {
+ if (ftpState->pathcomps == nullptr) {
debugs(9, 3, "the final component was a directory");
ftpListDir(ftpState);
return;
ftpState->filepath = wordlistChopHead(& ftpState->pathcomps);
/* Check if we are to CWD or RETR */
- if (ftpState->pathcomps != NULL || ftpState->flags.isdir) {
+ if (ftpState->pathcomps != nullptr || ftpState->flags.isdir) {
ftpSendCwd(ftpState);
} else {
debugs(9, 3, "final component is probably a file");
static void
ftpSendCwd(Ftp::Gateway * ftpState)
{
- char *path = NULL;
+ char *path = nullptr;
/* check the server control channel is still available */
if (!ftpState || !ftpState->haveControlChannel("ftpSendCwd"))
ftpState->cwd_message.append('\n');
ftpState->cwd_message.append(w->key);
}
- ftpState->ctrl.message = NULL;
+ ftpState->ctrl.message = nullptr;
/* Continue to traverse the path */
ftpTraverseDirectory(ftpState);
static void
ftpSendMkdir(Ftp::Gateway * ftpState)
{
- char *path = NULL;
+ char *path = nullptr;
/* check the server control channel is still available */
if (!ftpState || !ftpState->haveControlChannel("ftpSendMkdir"))
* is useless on ASCII transfers */
if (ftpState->flags.binary) {
- assert(ftpState->filepath != NULL);
+ assert(ftpState->filepath != nullptr);
assert(*ftpState->filepath != '\0');
snprintf(cbuf, CTRL_BUFLEN, "SIZE %s\r\n", ftpState->filepath);
ftpState->writeCommand(cbuf);
if (code == 213) {
ftpState->unhack();
- ftpState->theSize = strtoll(ftpState->ctrl.last_reply, NULL, 10);
+ ftpState->theSize = strtoll(ftpState->ctrl.last_reply, nullptr, 10);
if (ftpState->theSize == 0) {
debugs(9, 2, "SIZE reported " <<
{
Ip::Address srvAddr; // unused
if (ftpState->handleEpsvReply(srvAddr)) {
- if (ftpState->ctrl.message == NULL)
+ if (ftpState->ctrl.message == nullptr)
return; // didn't get complete reply yet
ftpState->connectDataChannel();
ftpOpenListenSocket(Ftp::Gateway * ftpState, int fallback)
{
/// Close old data channels, if any. We may open a new one below.
- if (ftpState->data.conn != NULL) {
+ if (ftpState->data.conn != nullptr) {
if ((ftpState->data.conn->flags & COMM_REUSEADDR))
// NP: in fact it points to the control channel. just clear it.
ftpState->data.clear();
ftpOpenListenSocket(ftpState, 0);
if (!Comm::IsConnOpen(ftpState->data.listenConn)) {
- if ( ftpState->data.listenConn != NULL && !ftpState->data.listenConn->local.isIPv4() ) {
+ if ( ftpState->data.listenConn != nullptr && !ftpState->data.listenConn->local.isIPv4() ) {
/* non-IPv4 CANNOT send PORT command. */
/* we got here by attempting and failing an EPRT */
/* using the same reply code should simulate a PORT failure */
// pull out the internal IP address bytes to send in PORT command...
// source them from the listen_conn->local
- struct addrinfo *AI = NULL;
+ struct addrinfo *AI = nullptr;
ftpState->data.listenConn->local.getAddrInfo(AI, AF_INET);
unsigned char *addrptr = (unsigned char *) &((struct sockaddr_in*)AI->ai_addr)->sin_addr;
unsigned char *portptr = (unsigned char *) &((struct sockaddr_in*)AI->ai_addr)->sin_port;
if (io.flag != Comm::OK) {
data.listenConn->close();
- data.listenConn = NULL;
+ data.listenConn = nullptr;
debugs(9, DBG_IMPORTANT, "FTP AcceptDataConnection: " << io.conn << ": " << xstrerr(io.xerrno));
// TODO: need to send error message on control channel
ftpFail(this);
if (EBIT_TEST(entry->flags, ENTRY_ABORTED)) {
abortAll("entry aborted when accepting data conn");
data.listenConn->close();
- data.listenConn = NULL;
+ data.listenConn = nullptr;
io.conn->close();
return;
}
/* data listening conn is no longer even open. abort. */
if (!Comm::IsConnOpen(data.listenConn)) {
- data.listenConn = NULL; // ensure that it's cleared and not just closed.
+ data.listenConn = nullptr; // ensure that it's cleared and not just closed.
return;
}
"data-peer= " << fd_table[data.conn->fd].ipaddr);
assert(haveControlChannel("ftpAcceptDataConnection"));
- assert(ctrl.message == NULL);
+ assert(ctrl.message == nullptr);
// Ctrl channel operations will determine what happens to this data connection
}
debugs(9, 3, MYNAME);
- if (ftpState->filepath != NULL) {
+ if (ftpState->filepath != nullptr) {
/* Plain file upload */
snprintf(cbuf, CTRL_BUFLEN, "STOR %s\r\n", ftpState->filepath);
ftpState->writeCommand(cbuf);
debugs(9, 3, MYNAME);
- assert(ftpState->filepath != NULL);
+ assert(ftpState->filepath != nullptr);
snprintf(cbuf, CTRL_BUFLEN, "RETR %s\r\n", ftpState->filepath);
ftpState->writeCommand(cbuf);
ftpState->state = Ftp::Client::SENT_RETR;
ferr.ftp.listing = &listing;
ferr.ftp.cwd_msg = xstrdup(cwd_message.size()? cwd_message.termedBuf() : "");
ferr.ftp.server_msg = ctrl.message;
- ctrl.message = NULL;
+ ctrl.message = nullptr;
entry->replaceHttpReply(ferr.BuildHttpReply());
entry->flush();
entry->unlock("Ftp::Gateway");
{
debugs(9, 3, MYNAME);
- if (old_request != NULL) {
+ if (old_request != nullptr) {
safe_free(old_request);
safe_free(old_reply);
}
debugs(9, 3, MYNAME);
- if (old_request == NULL) {
+ if (old_request == nullptr) {
old_request = ctrl.last_command;
- ctrl.last_command = NULL;
+ ctrl.last_command = nullptr;
old_reply = ctrl.last_reply;
- ctrl.last_reply = NULL;
+ ctrl.last_reply = nullptr;
- if (pathcomps == NULL && filepath != NULL)
+ if (pathcomps == nullptr && filepath != nullptr)
old_filepath = xstrdup(filepath);
}
auto t = urlPath.rfind('/');
SBuf filename = urlPath.substr(t != SBuf::npos ? t : 0);
- const char *mime_type = NULL;
- const char *mime_enc = NULL;
+ const char *mime_type = nullptr;
+ const char *mime_enc = nullptr;
if (flags.isdir) {
mime_type = "text/html";
void
Ftp::Gateway::completeForwarding()
{
- if (fwd == NULL || flags.completed_forwarding) {
+ if (fwd == nullptr || flags.completed_forwarding) {
debugs(9, 3, "avoid double-complete on FD " <<
(ctrl.conn ? ctrl.conn->fd : -1) << ", Data FD " << data.conn->fd <<
", this " << this << ", fwd " << fwd);
void startDataUpload();
bool startDirTracking();
void stopDirTracking();
- bool weAreTrackingDir() const {return savedReply.message != NULL;}
+ bool weAreTrackingDir() const {return savedReply.message != nullptr;}
typedef void (Relay::*PreliminaryCb)();
void forwardPreliminaryReply(const PreliminaryCb cb);
&Ftp::Relay::readGreeting, // BEGIN
&Ftp::Relay::readUserOrPassReply, // SENT_USER
&Ftp::Relay::readUserOrPassReply, // SENT_PASS
- NULL,/* &Ftp::Relay::readReply */ // SENT_TYPE
- NULL,/* &Ftp::Relay::readReply */ // SENT_MDTM
- NULL,/* &Ftp::Relay::readReply */ // SENT_SIZE
- NULL, // SENT_EPRT
- NULL, // SENT_PORT
+ nullptr,/* &Ftp::Relay::readReply */ // SENT_TYPE
+ nullptr,/* &Ftp::Relay::readReply */ // SENT_MDTM
+ nullptr,/* &Ftp::Relay::readReply */ // SENT_SIZE
+ nullptr, // SENT_EPRT
+ nullptr, // SENT_PORT
&Ftp::Relay::readEpsvReply, // SENT_EPSV_ALL
&Ftp::Relay::readEpsvReply, // SENT_EPSV_1
&Ftp::Relay::readEpsvReply, // SENT_EPSV_2
&Ftp::Relay::readPasvReply, // SENT_PASV
&Ftp::Relay::readCwdOrCdupReply, // SENT_CWD
- NULL,/* &Ftp::Relay::readDataReply, */ // SENT_LIST
- NULL,/* &Ftp::Relay::readDataReply, */ // SENT_NLST
- NULL,/* &Ftp::Relay::readReply */ // SENT_REST
- NULL,/* &Ftp::Relay::readDataReply */ // SENT_RETR
- NULL,/* &Ftp::Relay::readReply */ // SENT_STOR
- NULL,/* &Ftp::Relay::readReply */ // SENT_QUIT
+ nullptr,/* &Ftp::Relay::readDataReply, */ // SENT_LIST
+ nullptr,/* &Ftp::Relay::readDataReply, */ // SENT_NLST
+ nullptr,/* &Ftp::Relay::readReply */ // SENT_REST
+ nullptr,/* &Ftp::Relay::readDataReply */ // SENT_RETR
+ nullptr,/* &Ftp::Relay::readReply */ // SENT_STOR
+ nullptr,/* &Ftp::Relay::readReply */ // SENT_QUIT
&Ftp::Relay::readTransferDoneReply, // READING_DATA
&Ftp::Relay::readReply, // WRITING_DATA
- NULL,/* &Ftp::Relay::readReply */ // SENT_MKDIR
+ nullptr,/* &Ftp::Relay::readReply */ // SENT_MKDIR
&Ftp::Relay::readFeatReply, // SENT_FEAT
- NULL,/* &Ftp::Relay::readPwdReply */ // SENT_PWD
+ nullptr,/* &Ftp::Relay::readPwdReply */ // SENT_PWD
&Ftp::Relay::readCwdOrCdupReply, // SENT_CDUP
&Ftp::Relay::readDataReply,// SENT_DATA_REQUEST
&Ftp::Relay::readReply, // SENT_COMMAND
- NULL
+ nullptr
};
Ftp::Relay::Relay(FwdState *const fwdState):
AsyncJob("Ftp::Relay"),
Ftp::Client(fwdState),
- thePreliminaryCb(NULL),
+ thePreliminaryCb(nullptr),
forwardingCompleted(false),
originWaitInProgress(false)
{
- savedReply.message = NULL;
- savedReply.lastCommand = NULL;
- savedReply.lastReply = NULL;
+ savedReply.message = nullptr;
+ savedReply.lastCommand = nullptr;
+ savedReply.lastReply = nullptr;
savedReply.replyCode = 0;
// Prevent the future response from becoming public and being shared/cached
#endif
- if (data.readBuf != NULL && data.readBuf->hasContent()) {
+ if (data.readBuf != nullptr && data.readBuf->hasContent()) {
const mb_size_t csize = data.readBuf->contentSize();
debugs(9, 5, "writing " << csize << " bytes to the reply");
addVirginReplyBody(data.readBuf->content(), csize);
}
Ftp::Client::handleControlReply();
- if (ctrl.message == NULL)
+ if (ctrl.message == nullptr)
return; // didn't get complete reply yet
assert(state < END);
- assert(this->SM_FUNCS[state] != NULL);
+ assert(this->SM_FUNCS[state] != nullptr);
(this->*SM_FUNCS[state])();
}
debugs(9, 5, "forwarding preliminary reply to client");
// we must prevent concurrent ConnStateData::sendControlMsg() calls
- Must(thePreliminaryCb == NULL);
+ Must(thePreliminaryCb == nullptr);
thePreliminaryCb = cb;
const HttpReply::Pointer reply = createHttpReply(Http::scContinue);
{
debugs(9, 5, "proceeding after preliminary reply to client");
- Must(thePreliminaryCb != NULL);
+ Must(thePreliminaryCb != nullptr);
const PreliminaryCb cb = thePreliminaryCb;
- thePreliminaryCb = NULL;
+ thePreliminaryCb = nullptr;
(this->*cb)();
}
start();
break;
case 120:
- if (NULL != ctrl.message)
+ if (nullptr != ctrl.message)
debugs(9, DBG_IMPORTANT, "FTP server is busy: " << ctrl.message->key);
forwardPreliminaryReply(&Ftp::Relay::scheduleReadControlReply);
break;
return; // ignore preliminary replies
if (handleEpsvReply(updateMaster().clientDataAddr)) {
- if (ctrl.message == NULL)
+ if (ctrl.message == nullptr)
return; // didn't get complete reply yet
forwardReply();
savedReply.lastReply = ctrl.last_reply;
savedReply.replyCode = ctrl.replycode;
- ctrl.last_command = NULL;
- ctrl.last_reply = NULL;
- ctrl.message = NULL;
+ ctrl.last_command = nullptr;
+ ctrl.last_reply = nullptr;
+ ctrl.message = nullptr;
ctrl.offset = 0;
writeCommand("PWD\r\n");
return true;
ctrl.last_reply = savedReply.lastReply;
ctrl.replycode = savedReply.replyCode;
- savedReply.message = NULL;
- savedReply.lastReply = NULL;
- savedReply.lastCommand = NULL;
+ savedReply.message = nullptr;
+ savedReply.lastReply = nullptr;
+ savedReply.lastCommand = nullptr;
}
void
Ftp::Relay::abortOnData(const char *reason)
{
debugs(9, 3, "aborting transaction for " << reason <<
- "; FD " << (ctrl.conn != NULL ? ctrl.conn->fd : -1) << ", Data FD " << (data.conn != NULL ? data.conn->fd : -1) << ", this " << this);
+ "; FD " << (ctrl.conn != nullptr ? ctrl.conn->fd : -1) << ", Data FD " << (data.conn != nullptr ? data.conn->fd : -1) << ", this " << this);
// this method is only called to handle data connection problems
// the control connection should keep going
#if USE_ADAPTATION
- if (adaptedBodySource != NULL)
+ if (adaptedBodySource != nullptr)
stopConsumingFrom(adaptedBodySource);
#endif
/* STATIC */
-static DescriptorSet *TheHalfClosed = NULL; /// the set of half-closed FDs
+static DescriptorSet *TheHalfClosed = nullptr; /// the set of half-closed FDs
static bool WillCheckHalfClosed = false; /// true if check is scheduled
static EVH commHalfClosedCheck;
static void commPlanHalfClosedCheck();
{
++ statCounter.syscalls.sock.recvfroms;
debugs(5,8, "comm_udp_recvfrom: FD " << fd << " from " << from);
- struct addrinfo *AI = NULL;
+ struct addrinfo *AI = nullptr;
Ip::Address::InitAddr(AI);
int x = recvfrom(fd, buf, len, flags, AI->ai_addr, &AI->ai_addrlen);
from = *AI;
bool
comm_has_incomplete_write(int fd)
{
- assert(isOpen(fd) && COMMIO_FD_WRITECB(fd) != NULL);
+ assert(isOpen(fd) && COMMIO_FD_WRITECB(fd) != nullptr);
return COMMIO_FD_WRITECB(fd)->active();
}
comm_local_port(int fd)
{
Ip::Address temp;
- struct addrinfo *addr = NULL;
+ struct addrinfo *addr = nullptr;
fde *F = &fd_table[fd];
/* If the fd is closed already, just return */
const char *note)
{
int new_socket;
- struct addrinfo *AI = NULL;
+ struct addrinfo *AI = nullptr;
/* Create socket for accepting new connections. */
++ statCounter.syscalls.sock.sockets;
fde *F = &fd_table[fd];
assert(F->flags.open);
- F->timeoutHandler = NULL;
+ F->timeoutHandler = nullptr;
F->timeout = 0;
}
assert(F->flags.open);
if (timeout < 0) {
- F->timeoutHandler = NULL;
+ F->timeoutHandler = nullptr;
F->timeout = 0;
} else {
- if (callback != NULL) {
+ if (callback != nullptr) {
typedef CommTimeoutCbParams Params;
Params ¶ms = GetCommParams<Params>(callback);
params.conn = conn;
int x = 0;
int err = 0;
socklen_t errlen;
- struct addrinfo *AI = NULL;
+ struct addrinfo *AI = nullptr;
assert(address.port() != 0);
fde *F = &fd_table[fd];
debugs(5, 5, "commCallCloseHandlers: FD " << fd);
- while (F->closeHandler != NULL) {
+ while (F->closeHandler != nullptr) {
AsyncCall::Pointer call = F->closeHandler;
F->closeHandler = call->Next();
- call->setNext(NULL);
+ call->setNext(nullptr);
// If call is not canceled schedule it for execution else ignore it
if (!call->canceled()) {
debugs(5, 5, "commCallCloseHandlers: ch->handler=" << call);
// notify read/write handlers after canceling select reservations, if any
if (COMMIO_FD_WRITECB(fd)->active()) {
- Comm::SetSelect(fd, COMM_SELECT_WRITE, NULL, NULL, 0);
+ Comm::SetSelect(fd, COMM_SELECT_WRITE, nullptr, nullptr, 0);
COMMIO_FD_WRITECB(fd)->finish(Comm::ERR_CLOSING, errno);
}
if (COMMIO_FD_READCB(fd)->active()) {
- Comm::SetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
+ Comm::SetSelect(fd, COMM_SELECT_READ, nullptr, nullptr, 0);
COMMIO_FD_READCB(fd)->finish(Comm::ERR_CLOSING, errno);
}
comm_empty_os_read_buffers(fd);
AsyncCall::Pointer completeCall=commCbCall(5,4, "comm_close_complete",
- FdeCbPtrFun(comm_close_complete, NULL));
+ FdeCbPtrFun(comm_close_complete, nullptr));
FdeCbParams &completeParams = GetCommParams<FdeCbParams>(completeCall);
completeParams.fd = fd;
// must use async call to wait for all callbacks
debugs(50, 3, "comm_udp_sendto: Attempt to send UDP packet to " << to_addr <<
" using FD " << fd << " using Port " << comm_local_port(fd) );
- struct addrinfo *AI = NULL;
+ struct addrinfo *AI = nullptr;
to_addr.getAddrInfo(AI, fd_table[fd].sock_family);
int x = sendto(fd, buf, len, 0, AI->ai_addr, AI->ai_addrlen);
int xerrno = errno;
debugs(5, 5, "comm_remove_close_handler: FD " << fd << ", handler=" <<
handler << ", data=" << data);
- AsyncCall::Pointer p, prev = NULL;
- for (p = fd_table[fd].closeHandler; p != NULL; prev = p, p = p->Next()) {
+ AsyncCall::Pointer p, prev = nullptr;
+ for (p = fd_table[fd].closeHandler; p != nullptr; prev = p, p = p->Next()) {
typedef CommCbFunPtrCallT<CommCloseCbPtrFun> Call;
const Call *call = dynamic_cast<const Call*>(p.getRaw());
if (!call) // method callbacks have their own comm_remove_close_handler
}
// comm_close removes all close handlers so our handler may be gone
- if (p != NULL) {
+ if (p != nullptr) {
p->dequeue(fd_table[fd].closeHandler, prev);
p->cancel("comm_remove_close_handler");
}
debugs(5, 5, "comm_remove_close_handler: FD " << fd << ", AsyncCall=" << call);
// comm_close removes all close handlers so our handler may be gone
- AsyncCall::Pointer p, prev = NULL;
- for (p = fd_table[fd].closeHandler; p != NULL && p != call; prev = p, p = p->Next());
+ AsyncCall::Pointer p, prev = nullptr;
+ for (p = fd_table[fd].closeHandler; p != nullptr && p != call; prev = p, p = p->Next());
- if (p != NULL)
+ if (p != nullptr)
p->dequeue(fd_table[fd].closeHandler, prev);
call->cancel("comm_remove_close_handler");
}
comm_exit(void)
{
delete TheHalfClosed;
- TheHalfClosed = NULL;
+ TheHalfClosed = nullptr;
Comm::CallbackTableDestruct();
}
commCloseAllSockets(void)
{
int fd;
- fde *F = NULL;
+ fde *F = nullptr;
for (fd = 0; fd <= Biggest_FD; ++fd) {
F = &fd_table[fd];
if (F->flags.ipc) /* don't close inter-process sockets */
continue;
- if (F->timeoutHandler != NULL) {
+ if (F->timeoutHandler != nullptr) {
AsyncCall::Pointer callback = F->timeoutHandler;
- F->timeoutHandler = NULL;
+ F->timeoutHandler = nullptr;
debugs(5, 5, "commCloseAllSockets: FD " << fd << ": Calling timeout handler");
ScheduleCallHere(callback);
} else {
checkTimeouts(void)
{
int fd;
- fde *F = NULL;
+ fde *F = nullptr;
AsyncCall::Pointer callback;
for (fd = 0; fd <= Biggest_FD; ++fd) {
// We have an active write callback and we are timed out
CodeContext::Reset(F->codeContext);
debugs(5, 5, "checkTimeouts: FD " << fd << " auto write timeout");
- Comm::SetSelect(fd, COMM_SELECT_WRITE, NULL, NULL, 0);
+ Comm::SetSelect(fd, COMM_SELECT_WRITE, nullptr, nullptr, 0);
COMMIO_FD_WRITECB(fd)->finish(Comm::COMM_ERROR, ETIMEDOUT);
CodeContext::Reset();
continue;
CodeContext::Reset(F->codeContext);
debugs(5, 5, "checkTimeouts: FD " << fd << " Expired");
- if (F->timeoutHandler != NULL) {
+ if (F->timeoutHandler != nullptr) {
debugs(5, 5, "checkTimeouts: FD " << fd << ": Call timeout handler");
callback = F->timeoutHandler;
- F->timeoutHandler = NULL;
+ F->timeoutHandler = nullptr;
ScheduleCallHere(callback);
} else {
debugs(5, 5, "checkTimeouts: FD " << fd << ": Forcing comm_close()");
commPlanHalfClosedCheck()
{
if (!WillCheckHalfClosed && !TheHalfClosed->empty()) {
- eventAdd("commHalfClosedCheck", &commHalfClosedCheck, NULL, 1.0, 1);
+ eventAdd("commHalfClosedCheck", &commHalfClosedCheck, nullptr, 1.0, 1);
WillCheckHalfClosed = true;
}
}
// cancel the read if one was scheduled
AsyncCall::Pointer reader = fd_table[fd].halfClosedReader;
- if (reader != NULL)
+ if (reader != nullptr)
Comm::ReadCancel(fd, reader);
- fd_table[fd].halfClosedReader = NULL;
+ fd_table[fd].halfClosedReader = nullptr;
TheHalfClosed->del(fd);
}
{
// there cannot be more data coming in on half-closed connections
assert(size == 0);
- assert(conn != NULL);
+ assert(conn != nullptr);
assert(commHasHalfClosedMonitor(conn->fd)); // or we would have canceled the read
- fd_table[conn->fd].halfClosedReader = NULL; // done reading, for now
+ fd_table[conn->fd].halfClosedReader = nullptr; // done reading, for now
// nothing to do if fd is being closed
if (flag == Comm::ERR_CLOSING)
AI.ai_protocol = proto;
AI.ai_addrlen = SUN_LEN(addr);
AI.ai_addr = (sockaddr*)addr;
- AI.ai_canonname = NULL;
- AI.ai_next = NULL;
+ AI.ai_canonname = nullptr;
+ AI.ai_next = nullptr;
debugs(50, 3, "Attempt open socket for: " << addr->sun_path);
Comm::ConnOpener::ConnOpener(const Comm::ConnectionPointer &c, const AsyncCall::Pointer &handler, time_t ctimeout) :
AsyncJob("Comm::ConnOpener"),
- host_(NULL),
+ host_(nullptr),
temporaryFd_(-1),
conn_(c),
callback_(handler),
Comm::ConnOpener::doneAll() const
{
// is the conn_ to be opened still waiting?
- if (conn_ == NULL) {
+ if (conn_ == nullptr) {
return AsyncJob::doneAll();
}
// is the callback still to be called?
- if (callback_ == NULL || callback_->canceled()) {
+ if (callback_ == nullptr || callback_->canceled()) {
return AsyncJob::doneAll();
}
void
Comm::ConnOpener::swanSong()
{
- if (callback_ != NULL) {
+ if (callback_ != nullptr) {
// inform the still-waiting caller we are dying
sendAnswer(Comm::ERR_CONNECT, 0, "Comm::ConnOpener::swanSong");
}
Comm::ConnOpener::setHost(const char * new_host)
{
// unset and erase if already set.
- if (host_ != NULL)
+ if (host_ != nullptr)
safe_free(host_);
// set the new one if given.
- if (new_host != NULL)
+ if (new_host != nullptr)
host_ = xstrdup(new_host);
}
Comm::ConnOpener::sendAnswer(Comm::Flag errFlag, int xerrno, const char *why)
{
// only mark the address good/bad AFTER connect is finished.
- if (host_ != NULL) {
+ if (host_ != nullptr) {
if (xerrno == 0) // XXX: should not we use errFlag instead?
ipcacheMarkGoodAddr(host_, conn_->remote);
else {
}
}
- if (callback_ != NULL) {
+ if (callback_ != nullptr) {
// avoid scheduling cancelled callbacks, assuming they are common
// enough to make this extra check an optimization
if (callback_->canceled()) {
params.xerrno = xerrno;
ScheduleCallHere(callback_);
}
- callback_ = NULL;
+ callback_ = nullptr;
}
// The job will stop without this call because nil callback_ makes
*/
delete static_cast<Pointer*>(f.write_data);
- f.write_data = NULL;
- f.write_handler = NULL;
+ f.write_data = nullptr;
+ f.write_handler = nullptr;
}
// Comm::DoSelect does not do this when calling and resetting write_handler
// (because it expects more writes to come?). We could mimic that
// optimization by resetting Comm "Select" state only when the FD is
// actually closed.
- Comm::SetSelect(temporaryFd_, COMM_SELECT_WRITE, NULL, NULL, 0);
+ Comm::SetSelect(temporaryFd_, COMM_SELECT_WRITE, nullptr, nullptr, 0);
- if (calls_.timeout_ != NULL) {
+ if (calls_.timeout_ != nullptr) {
calls_.timeout_->cancel("Comm::ConnOpener::cleanFd");
- calls_.timeout_ = NULL;
+ calls_.timeout_ = nullptr;
}
// Comm checkTimeouts() and commCloseAllSockets() do not clear .timeout
// when calling timeoutHandler (XXX fix them), so we clear unconditionally.
- f.timeoutHandler = NULL;
+ f.timeoutHandler = nullptr;
f.timeout = 0;
- if (calls_.earlyAbort_ != NULL) {
+ if (calls_.earlyAbort_ != nullptr) {
comm_remove_close_handler(temporaryFd_, calls_.earlyAbort_);
- calls_.earlyAbort_ = NULL;
+ calls_.earlyAbort_ = nullptr;
}
}
void
Comm::ConnOpener::keepFd()
{
- Must(conn_ != NULL);
+ Must(conn_ != nullptr);
Must(temporaryFd_ >= 0);
cleanFd();
void
Comm::ConnOpener::start()
{
- Must(conn_ != NULL);
+ Must(conn_ != nullptr);
/* outbound sockets have no need to be protocol agnostic. */
if (!(Ip::EnableIpv6&IPV6_SPECIAL_V4MAPPING) && conn_->remote.isIPv4()) {
assert(conn_);
// our initiators signal abort by cancelling their callbacks
- if (callback_ == NULL || callback_->canceled())
+ if (callback_ == nullptr || callback_->canceled())
return false;
temporaryFd_ = comm_openex(SOCK_STREAM, IPPROTO_TCP, conn_->local, conn_->flags, host_);
void
Comm::ConnOpener::doConnect()
{
- Must(conn_ != NULL);
+ Must(conn_ != nullptr);
Must(temporaryFd_ >= 0);
++ totalTries_;
void
Comm::ConnOpener::lookupLocalAddress()
{
- struct addrinfo *addr = NULL;
+ struct addrinfo *addr = nullptr;
Ip::Address::InitAddr(addr);
if (getsockname(conn_->fd, addr->ai_addr, &(addr->ai_addrlen)) != 0) {
Comm::ConnOpener::earlyAbort(const CommCloseCbParams &io)
{
debugs(5, 3, io.conn);
- calls_.earlyAbort_ = NULL;
+ calls_.earlyAbort_ = nullptr;
// NP: is closing or shutdown better?
sendAnswer(Comm::ERR_CLOSING, io.xerrno, "Comm::ConnOpener::earlyAbort");
}
Comm::ConnOpener::timeout(const CommTimeoutCbParams &)
{
debugs(5, 5, conn_ << ": * - ERR took too long to receive response.");
- calls_.timeout_ = NULL;
+ calls_.timeout_ = nullptr;
sendAnswer(Comm::TIMEOUT, ETIMEDOUT, "Comm::ConnOpener::timeout");
}
bool
Comm::IsConnOpen(const Comm::ConnectionPointer &conn)
{
- return conn != NULL && conn->isOpen();
+ return conn != nullptr && conn->isOpen();
}
Comm::Connection::Connection() :
if (cbdataReferenceValid(peer_))
return peer_;
- return NULL;
+ return nullptr;
}
void
inline std::ostream &
operator << (std::ostream &os, const Comm::ConnectionPointer &conn)
{
- if (conn != NULL)
+ if (conn != nullptr)
os << *conn;
return os;
}
{
// release any Comm::Connections being held.
for (int pos = 0; pos < Squid_MaxFD; ++pos) {
- iocb_table[pos].readcb.conn = NULL;
- iocb_table[pos].writecb.conn = NULL;
+ iocb_table[pos].readcb.conn = nullptr;
+ iocb_table[pos].writecb.conn = nullptr;
}
safe_free(iocb_table);
}
{
assert(!active());
assert(type == t);
- assert(cb != NULL);
+ assert(cb != nullptr);
callback = cb;
buf = b;
return;
callback->cancel(reason);
- callback = NULL;
+ callback = nullptr;
reset();
}
void
Comm::IoCallback::reset()
{
- conn = NULL;
+ conn = nullptr;
if (freefunc) {
freefunc(buf);
- buf = NULL;
- freefunc = NULL;
+ buf = nullptr;
+ freefunc = nullptr;
}
xerrno = 0;
/* free data */
if (freefunc && buf) {
freefunc(buf);
- buf = NULL;
- freefunc = NULL;
+ buf = nullptr;
+ freefunc = nullptr;
}
- if (callback != NULL) {
+ if (callback != nullptr) {
typedef CommIoCbParams Params;
Params ¶ms = GetCommParams<Params>(callback);
- if (conn != NULL) params.fd = conn->fd; // for legacy write handlers...
+ if (conn != nullptr) params.fd = conn->fd; // for legacy write handlers...
params.conn = conn;
params.buf = buf;
params.size = offset;
params.flag = code;
params.xerrno = xerrn;
ScheduleCallHere(callback);
- callback = NULL;
+ callback = nullptr;
}
/* Reset for next round. */
unsigned int quotaQueueReserv; ///< reservation ID from CommQuotaQueue
#endif
- bool active() const { return callback != NULL; }
+ bool active() const { return callback != nullptr; }
void setCallback(iocb_type type, AsyncCall::Pointer &cb, char *buf, FREE *func, int sz);
/// called when fd needs to write but may need to wait in line for its quota
// TODO: add EPOLLPRI??
if (cevents->events & (EPOLLIN|EPOLLHUP|EPOLLERR) || F->flags.read_pending) {
- if ((hdl = F->read_handler) != NULL) {
+ if ((hdl = F->read_handler) != nullptr) {
debugs(5, DEBUG_EPOLL ? 0 : 8, "Calling read handler on FD " << fd);
- F->read_handler = NULL;
+ F->read_handler = nullptr;
hdl(fd, F->read_data);
++ statCounter.select_fds;
} else {
debugs(5, DEBUG_EPOLL ? 0 : 8, "no read handler for FD " << fd);
// remove interest since no handler exist for this event.
- SetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
+ SetSelect(fd, COMM_SELECT_READ, nullptr, nullptr, 0);
}
}
if (cevents->events & (EPOLLOUT|EPOLLHUP|EPOLLERR)) {
- if ((hdl = F->write_handler) != NULL) {
+ if ((hdl = F->write_handler) != nullptr) {
debugs(5, DEBUG_EPOLL ? 0 : 8, "Calling write handler on FD " << fd);
- F->write_handler = NULL;
+ F->write_handler = nullptr;
hdl(fd, F->write_data);
++ statCounter.select_fds;
} else {
debugs(5, DEBUG_EPOLL ? 0 : 8, "no write handler for FD " << fd);
// remove interest since no handler exist for this event.
- SetSelect(fd, COMM_SELECT_WRITE, NULL, NULL, 0);
+ SetSelect(fd, COMM_SELECT_WRITE, nullptr, nullptr, 0);
}
}
}
static int
fdIsUdpListen(int fd)
{
- if (icpIncomingConn != NULL && icpIncomingConn->fd == fd)
+ if (icpIncomingConn != nullptr && icpIncomingConn->fd == fd)
return 1;
- if (icpOutgoingConn != NULL && icpOutgoingConn->fd == fd)
+ if (icpOutgoingConn != nullptr && icpOutgoingConn->fd == fd)
return 1;
return 0;
static int
fdIsTcpListen(int fd)
{
- for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
- if (s->listenConn != NULL && s->listenConn->fd == fd)
+ for (AnyP::PortCfgPointer s = HttpPortList; s != nullptr; s = s->next) {
+ if (s->listenConn != nullptr && s->listenConn->fd == fd)
return 1;
}
{
int i;
int fd;
- PF *hdl = NULL;
+ PF *hdl = nullptr;
int npfds;
struct pollfd pfds[3 + MAXTCPLISTENPORTS];
if (revents & (POLLRDNORM | POLLIN | POLLHUP | POLLERR)) {
if ((hdl = fd_table[fd].read_handler)) {
- fd_table[fd].read_handler = NULL;
+ fd_table[fd].read_handler = nullptr;
hdl(fd, fd_table[fd].read_data);
} else if (pfds[i].events & POLLRDNORM)
debugs(5, DBG_IMPORTANT, "comm_poll_incoming: FD " << fd << " NULL read handler");
if (revents & (POLLWRNORM | POLLOUT | POLLHUP | POLLERR)) {
if ((hdl = fd_table[fd].write_handler)) {
- fd_table[fd].write_handler = NULL;
+ fd_table[fd].write_handler = nullptr;
hdl(fd, fd_table[fd].write_data);
} else if (pfds[i].events & POLLWRNORM)
debugs(5, DBG_IMPORTANT, "comm_poll_incoming: FD " << fd << " NULL write_handler");
{
struct pollfd pfds[SQUID_MAXFD];
- PF *hdl = NULL;
+ PF *hdl = nullptr;
int fd;
int maxfd;
unsigned long nfds;
debugs(5, 6, "comm_poll: FD " << fd << " ready for reading");
if ((hdl = F->read_handler)) {
- F->read_handler = NULL;
+ F->read_handler = nullptr;
hdl(fd, F->read_data);
++ statCounter.select_fds;
debugs(5, 6, "comm_poll: FD " << fd << " ready for writing");
if ((hdl = F->write_handler)) {
- F->write_handler = NULL;
+ F->write_handler = nullptr;
hdl(fd, F->write_data);
++ statCounter.select_fds;
debugs(5, DBG_CRITICAL, "tmout:" << F->timeoutHandler << "read:" <<
F->read_handler << " write:" << F->write_handler);
- for (ch = F->closeHandler; ch != NULL; ch = ch->Next())
+ for (ch = F->closeHandler; ch != nullptr; ch = ch->Next())
debugs(5, DBG_CRITICAL, " close handler: " << ch);
- if (F->closeHandler != NULL) {
+ if (F->closeHandler != nullptr) {
commCallCloseHandlers(fd);
- } else if (F->timeoutHandler != NULL) {
+ } else if (F->timeoutHandler != nullptr) {
debugs(5, DBG_CRITICAL, "comm_poll: Calling Timeout Handler");
ScheduleCallHere(F->timeoutHandler);
}
- F->closeHandler = NULL;
- F->timeoutHandler = NULL;
- F->read_handler = NULL;
- F->write_handler = NULL;
+ F->closeHandler = nullptr;
+ F->timeoutHandler = nullptr;
+ F->read_handler = nullptr;
+ F->write_handler = nullptr;
if (F->flags.open)
fd_close(fd);
static int
fdIsUdpListener(int fd)
{
- if (icpIncomingConn != NULL && fd == icpIncomingConn->fd)
+ if (icpIncomingConn != nullptr && fd == icpIncomingConn->fd)
return 1;
- if (icpOutgoingConn != NULL && fd == icpOutgoingConn->fd)
+ if (icpOutgoingConn != nullptr && fd == icpOutgoingConn->fd)
return 1;
return 0;
static int
fdIsTcpListener(int fd)
{
- for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
- if (s->listenConn != NULL && s->listenConn->fd == fd)
+ for (AnyP::PortCfgPointer s = HttpPortList; s != nullptr; s = s->next) {
+ if (s->listenConn != nullptr && s->listenConn->fd == fd)
return 1;
}
int i;
int fd;
int maxfd = 0;
- PF *hdl = NULL;
+ PF *hdl = nullptr;
fd_set read_mask;
fd_set write_mask;
FD_ZERO(&read_mask);
++ statCounter.syscalls.selects;
- if (select(maxfd, &read_mask, &write_mask, NULL, &zero_tv) < 1)
+ if (select(maxfd, &read_mask, &write_mask, nullptr, &zero_tv) < 1)
return incoming_sockets_accepted;
for (i = 0; i < nfds; ++i) {
fd = fds[i];
if (FD_ISSET(fd, &read_mask)) {
- if ((hdl = fd_table[fd].read_handler) != NULL) {
- fd_table[fd].read_handler = NULL;
- commUpdateReadBits(fd, NULL);
+ if ((hdl = fd_table[fd].read_handler) != nullptr) {
+ fd_table[fd].read_handler = nullptr;
+ commUpdateReadBits(fd, nullptr);
hdl(fd, fd_table[fd].read_data);
} else {
debugs(5, DBG_IMPORTANT, "comm_select_incoming: FD " << fd << " NULL read handler");
}
if (FD_ISSET(fd, &write_mask)) {
- if ((hdl = fd_table[fd].write_handler) != NULL) {
- fd_table[fd].write_handler = NULL;
- commUpdateWriteBits(fd, NULL);
+ if ((hdl = fd_table[fd].write_handler) != nullptr) {
+ fd_table[fd].write_handler = nullptr;
+ commUpdateWriteBits(fd, nullptr);
hdl(fd, fd_table[fd].write_data);
} else {
debugs(5, DBG_IMPORTANT, "comm_select_incoming: FD " << fd << " NULL write handler");
// XXX: only poll sockets that won't be deferred. But how do we identify them?
- for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
+ for (AnyP::PortCfgPointer s = HttpPortList; s != nullptr; s = s->next) {
if (Comm::IsConnOpen(s->listenConn)) {
fds[nfds] = s->listenConn->fd;
++nfds;
fd_set pendingfds;
fd_set writefds;
- PF *hdl = NULL;
+ PF *hdl = nullptr;
int fd;
int maxfd;
int num;
poll_time.tv_sec = msec / 1000;
poll_time.tv_usec = (msec % 1000) * 1000;
++ statCounter.syscalls.selects;
- num = select(maxfd, &readfds, &writefds, NULL, &poll_time);
+ num = select(maxfd, &readfds, &writefds, nullptr, &poll_time);
int xerrno = errno;
++ statCounter.select_loops;
F = &fd_table[fd];
debugs(5, 6, "comm_select: FD " << fd << " ready for reading");
- if (NULL == (hdl = F->read_handler))
+ if (nullptr == (hdl = F->read_handler))
(void) 0;
else {
- F->read_handler = NULL;
- commUpdateReadBits(fd, NULL);
+ F->read_handler = nullptr;
+ commUpdateReadBits(fd, nullptr);
hdl(fd, F->read_data);
++ statCounter.select_fds;
debugs(5, 6, "comm_select: FD " << fd << " ready for writing");
if ((hdl = F->write_handler)) {
- F->write_handler = NULL;
- commUpdateWriteBits(fd, NULL);
+ F->write_handler = nullptr;
+ commUpdateWriteBits(fd, nullptr);
hdl(fd, F->write_data);
++ statCounter.select_fds;
fd_set write_x;
struct timeval tv;
- AsyncCall::Pointer ch = NULL;
- fde *F = NULL;
+ AsyncCall::Pointer ch = nullptr;
+ fde *F = nullptr;
struct stat sb;
debugs(5, DBG_CRITICAL, "examine_select: Examining open file descriptors...");
debugs(5, DBG_CRITICAL, "FD " << fd << " is a " << fdTypeStr[F->type] << " called '" << F->desc << "'");
debugs(5, DBG_CRITICAL, "tmout:" << F->timeoutHandler << " read:" << F->read_handler << " write:" << F->write_handler);
- for (ch = F->closeHandler; ch != NULL; ch = ch->Next())
+ for (ch = F->closeHandler; ch != nullptr; ch = ch->Next())
debugs(5, DBG_CRITICAL, " close handler: " << ch);
- if (F->closeHandler != NULL) {
+ if (F->closeHandler != nullptr) {
commCallCloseHandlers(fd);
- } else if (F->timeoutHandler != NULL) {
+ } else if (F->timeoutHandler != nullptr) {
debugs(5, DBG_CRITICAL, "examine_select: Calling Timeout Handler");
ScheduleCallHere(F->timeoutHandler);
}
- F->closeHandler = NULL;
- F->timeoutHandler = NULL;
- F->read_handler = NULL;
- F->write_handler = NULL;
+ F->closeHandler = nullptr;
+ F->timeoutHandler = nullptr;
+ F->read_handler = nullptr;
+ F->write_handler = nullptr;
FD_CLR(fd, readfds);
FD_CLR(fd, writefds);
}
bool
Comm::MonitorsRead(int fd)
{
- assert(isOpen(fd) && COMMIO_FD_READCB(fd) != NULL);
+ assert(isOpen(fd) && COMMIO_FD_READCB(fd) != nullptr);
// Being active is usually the same as monitoring because we always
// start monitoring the FD when we configure Comm::IoCallback for I/O
// and we usually configure Comm::IoCallback for I/O when we starting
{
// TODO: move comm_read_base() internals into here
// when comm_read() char* API is no longer needed
- comm_read_base(conn, NULL, 0, callback);
+ comm_read_base(conn, nullptr, 0, callback);
}
/**
// Active/passive conflicts are OK and simply cancel passive monitoring.
if (ccb->active()) {
// if the assertion below fails, we have an active comm_read conflict
- assert(fd_table[conn->fd].halfClosedReader != NULL);
+ assert(fd_table[conn->fd].halfClosedReader != nullptr);
commStopHalfClosedMonitor(conn->fd);
assert(!ccb->active());
}
ccb->conn = conn;
/* Queue the read */
- ccb->setCallback(Comm::IOCB_READ, callback, (char *)buf, NULL, size);
+ ccb->setCallback(Comm::IOCB_READ, callback, (char *)buf, nullptr, size);
Comm::SetSelect(conn->fd, COMM_SELECT_READ, Comm::HandleRead, ccb, 0);
}
cb->cancel("old comm_read_cancel");
/* And the IO event */
- Comm::SetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
+ Comm::SetSelect(fd, COMM_SELECT_READ, nullptr, nullptr, 0);
}
void
cb->cancel("comm_read_cancel");
/* And the IO event */
- Comm::SetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
+ Comm::SetSelect(fd, COMM_SELECT_READ, nullptr, nullptr, 0);
}
time_t
void comm_read_base(const Comm::ConnectionPointer &conn, char *buf, int len, AsyncCall::Pointer &callback);
inline void comm_read(const Comm::ConnectionPointer &conn, char *buf, int len, AsyncCall::Pointer &callback)
{
- assert(buf != NULL);
+ assert(buf != nullptr);
comm_read_base(conn, buf, len, callback);
}
void comm_read_cancel(int fd, IOCB *callback, void *data);
Comm::TcpAcceptor::unsubscribe(const char *reason)
{
debugs(5, 5, status() << " AsyncCall Subscription " << theCallSub << " removed: " << reason);
- theCallSub = NULL;
+ theCallSub = nullptr;
}
void
}
// stop when handlers are gone
- if (theCallSub == NULL) {
+ if (theCallSub == nullptr) {
return AsyncJob::doneAll();
}
debugs(5,5, MYNAME);
unsubscribe("swanSong");
if (IsConnOpen(conn)) {
- if (closer_ != NULL)
+ if (closer_ != nullptr)
comm_remove_close_handler(conn->fd, closer_);
conn->close();
}
- conn = NULL;
+ conn = nullptr;
AcceptLimiter::Instance().removeDead(this);
AsyncJob::swanSong();
}
const char *
Comm::TcpAcceptor::status() const
{
- if (conn == NULL)
+ if (conn == nullptr)
return "[nil connection]";
static char ipbuf[MAX_IPSTRLEN] = {'\0'};
void
Comm::TcpAcceptor::handleClosure(const CommCloseCbParams &)
{
- closer_ = NULL;
+ closer_ = nullptr;
if (conn) {
conn->noteClosure();
conn = nullptr;
return;
}
- if (theCallSub != NULL) {
+ if (theCallSub != nullptr) {
AsyncCall::Pointer call = theCallSub->callback();
CommAcceptCbParams ¶ms = GetCommParams<CommAcceptCbParams>(call);
params.port = listenPort_;
{
++statCounter.syscalls.sock.accepts;
int sock;
- struct addrinfo *gai = NULL;
+ struct addrinfo *gai = nullptr;
Ip::Address::InitAddr(gai);
errcode = 0; // reset local errno copy.
int len = 0;
int nleft;
- assert(state->conn != NULL);
+ assert(state->conn != nullptr);
assert(state->conn->fd == fd);
debugs(5, 5, state->conn << ": off " <<
#include <functional>
#include <memory>
-char *Debug::debugOptions = NULL;
+char *Debug::debugOptions = nullptr;
int Debug::override_X = 0;
bool Debug::log_syslog = false;
int Debug::Levels[MAX_DEBUG_SECTIONS];
-char *Debug::cache_log = NULL;
+char *Debug::cache_log = nullptr;
int Debug::rotateNumber = -1;
/// a counter related to the number of debugs() calls
},
#endif
{
- NULL, 0
+ nullptr, 0
}
};
void
Debug::parseOptions(char const *options)
{
- char *p = NULL;
- char *s = NULL;
+ char *p = nullptr;
+ char *s = nullptr;
if (override_X) {
debugs(0, 9, "command-line -X overrides: " << options);
if (options) {
p = xstrdup(options);
- for (s = strtok(p, w_space); s; s = strtok(NULL, w_space))
+ for (s = strtok(p, w_space); s; s = strtok(nullptr, w_space))
debugArg(s);
xfree(p);
default:
fatal ("unknown delay pool class");
- return NULL;
+ return nullptr;
};
return result;
theAggregate->kickReads();
}
-DelayPool *DelayPools::delay_data = NULL;
+DelayPool *DelayPools::delay_data = nullptr;
time_t DelayPools::LastUpdate = 0;
unsigned short DelayPools::pools_ (0);
DelayPools::delay_data = new DelayPool[pools()];
- eventAdd("DelayPools::Update", DelayPools::Update, NULL, 1.0, 1);
+ eventAdd("DelayPools::Update", DelayPools::Update, nullptr, 1.0, 1);
}
void
if (!pools() && toUpdate.empty())
return;
- eventAdd("DelayPools::Update", Update, NULL, 1.0, 1);
+ eventAdd("DelayPools::Update", Update, nullptr, 1.0, 1);
int incr = squid_curtime - LastUpdate;
dlinkAdd(void *data, dlink_node * m, dlink_list * list)
{
m->data = data;
- m->prev = NULL;
+ m->prev = nullptr;
m->next = list->head;
if (list->head)
list->head = m;
- if (list->tail == NULL)
+ if (list->tail == nullptr)
list->tail = m;
}
dlinkAddTail(void *data, dlink_node * m, dlink_list * list)
{
m->data = data;
- m->next = NULL;
+ m->next = nullptr;
m->prev = list->tail;
if (list->tail)
list->tail = m;
- if (list->head == NULL)
+ if (list->head == nullptr)
list->head = m;
}
if (m == list->tail)
list->tail = m->prev;
- m->next = m->prev = NULL;
+ m->next = m->prev = nullptr;
}
/*
* NOTE: use of strtok here makes names like foo....com valid.
*/
- for (t = strtok(copy, "."); t; t = strtok(NULL, "."))
+ for (t = strtok(copy, "."); t; t = strtok(nullptr, "."))
off += rfc1035LabelPack(buf + off, sz - off, t);
xfree(copy);
- off += rfc1035LabelPack(buf + off, sz - off, NULL);
+ off += rfc1035LabelPack(buf + off, sz - off, nullptr);
assert(off <= sz);
return off;
}
unsigned int i;
unsigned short rdlength;
unsigned int rdata_off;
- if (rfc1035NameUnpack(buf, sz, off, NULL, RR->name, RFC1035_MAXHOSTNAMESZ, 0)) {
+ if (rfc1035NameUnpack(buf, sz, off, nullptr, RR->name, RFC1035_MAXHOSTNAMESZ, 0)) {
RFC1035_UNPACK_DEBUG;
memset(RR, '\0', sizeof(*RR));
return 1;
void
rfc1035RRDestroy(rfc1035_rr ** rr, int n)
{
- if (*rr == NULL) {
+ if (*rr == nullptr) {
return;
}
xfree((*rr)[n].rdata);
}
xfree(*rr);
- *rr = NULL;
+ *rr = nullptr;
}
/*
rfc1035QueryUnpack(const char *buf, size_t sz, unsigned int *off, rfc1035_query * query)
{
unsigned short s;
- if (rfc1035NameUnpack(buf, sz, off, NULL, query->name, RFC1035_MAXHOSTNAMESZ, 0)) {
+ if (rfc1035NameUnpack(buf, sz, off, nullptr, query->name, RFC1035_MAXHOSTNAMESZ, 0)) {
RFC1035_UNPACK_DEBUG;
memset(query, '\0', sizeof(*query));
return 1;
if ((*msg)->answer)
rfc1035RRDestroy(&(*msg)->answer, (*msg)->ancount);
xfree(*msg);
- *msg = NULL;
+ *msg = nullptr;
}
/*
unsigned int off = 0;
unsigned int i, j;
unsigned int nr = 0;
- rfc1035_message *msg = NULL;
- rfc1035_rr *recs = NULL;
- rfc1035_query *querys = NULL;
+ rfc1035_message *msg = nullptr;
+ rfc1035_rr *recs = nullptr;
+ rfc1035_query *querys = nullptr;
msg = (rfc1035_message*)xcalloc(1, sizeof(*msg));
if (rfc1035HeaderUnpack(buf + off, sz - off, &off, msg)) {
RFC1035_UNPACK_DEBUG;
* didn't actually get any.
*/
rfc1035MessageDestroy(&msg);
- *answer = NULL;
+ *answer = nullptr;
return -rfc1035_unpack_error;
}
return nr;
opt.type = RFC1035_TYPE_OPT;
opt._class = min(edns_sz, (ssize_t)SQUID_UDP_SO_RCVBUF-1);
opt.ttl = 0; // relevant?
- opt.rdata = NULL;
+ opt.rdata = nullptr;
opt.rdlength = 0;
return rfc1035RRPack(buf, sz, &opt);
};
static std::vector<ns> nameservers;
-static sp *searchpath = NULL;
+static sp *searchpath = nullptr;
static int nns_mdns_count = 0;
static int npc = 0;
static int npc_alloc = 0;
static int ndots = 1;
static dlink_list lru_list;
static int event_queued = 0;
-static hash_table *idns_lookup_hash = NULL;
+static hash_table *idns_lookup_hash = nullptr;
/*
* Notes on EDNS:
}
char buf[RESOLV_BUFSZ];
- const char *t = NULL;
+ const char *t = nullptr;
while (fgets(buf, RESOLV_BUFSZ, fp)) {
t = strtok(buf, w_space);
- if (NULL == t) {
+ if (nullptr == t) {
continue;
} else if (strcmp(t, "nameserver") == 0) {
- t = strtok(NULL, w_space);
+ t = strtok(nullptr, w_space);
- if (NULL == t)
+ if (nullptr == t)
continue;
debugs(78, DBG_IMPORTANT, "Adding nameserver " << t << " from " << _PATH_RESCONF);
result = true;
} else if (strcmp(t, "domain") == 0) {
idnsFreeSearchpath();
- t = strtok(NULL, w_space);
+ t = strtok(nullptr, w_space);
- if (NULL == t)
+ if (nullptr == t)
continue;
debugs(78, DBG_IMPORTANT, "Adding domain " << t << " from " << _PATH_RESCONF);
idnsAddPathComponent(t);
} else if (strcmp(t, "search") == 0) {
idnsFreeSearchpath();
- while (NULL != t) {
- t = strtok(NULL, w_space);
+ while (nullptr != t) {
+ t = strtok(nullptr, w_space);
- if (NULL == t)
+ if (nullptr == t)
continue;
debugs(78, DBG_IMPORTANT, "Adding domain " << t << " from " << _PATH_RESCONF);
idnsAddPathComponent(t);
}
} else if (strcmp(t, "options") == 0) {
- while (NULL != t) {
- t = strtok(NULL, w_space);
+ while (nullptr != t) {
+ t = strtok(nullptr, w_space);
- if (NULL == t)
+ if (nullptr == t)
continue;
if (strncmp(t, "ndots:", 6) == 0) {
if (event_queued)
return;
- if (NULL == lru_list.tail)
+ if (nullptr == lru_list.tail)
return;
const double when = min(Config.Timeout.idns_query, Config.Timeout.idns_retransmit)/1000.0;
- eventAdd("idnsCheckQueue", idnsCheckQueue, NULL, when, 1);
+ eventAdd("idnsCheckQueue", idnsCheckQueue, nullptr, when, 1);
event_queued = 1;
}
delete queue;
delete msg;
if (ns < nameservers.size()) // XXX: idnsShutdownAndFreeState may have freed nameservers[]
- nameservers[ns].vc = NULL;
+ nameservers[ns].vc = nullptr;
}
static void
{
assert(nsv < nameservers.size());
nsvc *vc = new nsvc(nsv);
- assert(vc->conn == NULL); // MUST be NULL from the construction process!
+ assert(vc->conn == nullptr); // MUST be NULL from the construction process!
nameservers[nsv].vc = vc;
Comm::ConnectionPointer conn = new Comm::Connection();
idnsSendQueryVC(idns_query * q, size_t nsn)
{
assert(nsn < nameservers.size());
- if (nameservers[nsn].vc == NULL)
+ if (nameservers[nsn].vc == nullptr)
idnsInitVC(nsn);
nsvc *vc = nameservers[nsn].vc;
return;
}
- assert(q->lru.next == NULL);
+ assert(q->lru.next == nullptr);
- assert(q->lru.prev == NULL);
+ assert(q->lru.prev == nullptr);
int x = -1, y = -1;
size_t nsn;
return q;
}
- return NULL;
+ return nullptr;
}
static unsigned short
static void
idnsGrokReply(const char *buf, size_t sz, int /*from_ns*/)
{
- rfc1035_message *message = NULL;
+ rfc1035_message *message = nullptr;
int n = rfc1035MessageUnpack(buf, sz, &message);
- if (message == NULL) {
+ if (message == nullptr) {
debugs(78, DBG_IMPORTANT, "ERROR: idnsGrokReply: Malformed DNS response");
return;
}
idns_query *q = idnsFindQuery(message->id);
- if (q == NULL) {
+ if (q == nullptr) {
debugs(78, 3, "idnsGrokReply: Late response");
rfc1035MessageDestroy(&message);
return;
// things simple. NXDOMAIN is authoritative for the label, not
// the record type.
if (q->rcode == 3 && !q->master && q->do_searchpath && q->attempt < MAX_ATTEMPT) {
- assert(NULL == message->answer);
+ assert(nullptr == message->answer);
strcpy(q->name, q->orig);
debugs(78, 3, "idnsGrokReply: Query result: NXDOMAIN - " << q->name );
while (idns_query *slave = q->slave) {
dlinkDelete(&slave->lru, &lru_list);
q->slave = slave->slave;
- slave->slave = NULL;
+ slave->slave = nullptr;
delete slave;
}
q->ancount = n;
if (n >= 0)
- idnsCallback(q, NULL);
+ idnsCallback(q, nullptr);
else
idnsCallback(q, rfc1035ErrorMessage(q->rcode));
// Always keep reading. This stops (or at least makes harder) several
// attacks on the DNS client.
- Comm::SetSelect(fd, COMM_SELECT_READ, idnsRead, NULL, 0);
+ Comm::SetSelect(fd, COMM_SELECT_READ, idnsRead, nullptr, 0);
/* BUG (UNRESOLVED)
* two code lines after returning from comm_udprecvfrom()
idnsCheckQueue(void *)
{
dlink_node *n;
- dlink_node *p = NULL;
+ dlink_node *p = nullptr;
idns_query *q;
event_queued = 0;
if (DnsSocketB >= 0) {
comm_local_port(DnsSocketB);
debugs(78, Important(16), "DNS IPv6 socket created at " << addrV6 << ", FD " << DnsSocketB);
- Comm::SetSelect(DnsSocketB, COMM_SELECT_READ, idnsRead, NULL, 0);
+ Comm::SetSelect(DnsSocketB, COMM_SELECT_READ, idnsRead, nullptr, 0);
}
if (DnsSocketA >= 0) {
comm_local_port(DnsSocketA);
debugs(78, Important(64), "DNS IPv4 socket created at " << addrV4 << ", FD " << DnsSocketA);
- Comm::SetSelect(DnsSocketA, COMM_SELECT_READ, idnsRead, NULL, 0);
+ Comm::SetSelect(DnsSocketA, COMM_SELECT_READ, idnsRead, nullptr, 0);
}
}
snmp_netDnsFn(variable_list * Var, snint * ErrP)
{
int n = 0;
- variable_list *Answer = NULL;
+ variable_list *Answer = nullptr;
MemBuf tmp;
debugs(49, 5, "snmp_netDnsFn: Processing request: " << snmpDebugOid(Var->name, Var->name_length, tmp));
*ErrP = SNMP_ERR_NOERROR;
static const int error_hard_text_count = sizeof(error_hard_text) / sizeof(*error_hard_text);
/// \ingroup ErrorPageInternal
-static char **error_text = NULL;
+static char **error_text = nullptr;
/// \ingroup ErrorPageInternal
static int error_page_count = 0;
if (error_hard_text[i].type == type)
return error_hard_text[i].text;
- return NULL;
+ return nullptr;
}
TemplateFile::TemplateFile(const char *name, const err_type code): silent(false), wasLoaded(false), templateName(name), templateCode(code)
void
errorAppendEntry(StoreEntry * entry, ErrorState * err)
{
- assert(entry->mem_obj != NULL);
+ assert(entry->mem_obj != nullptr);
assert (entry->isEmpty());
debugs(4, 4, "storing " << err << " in " << *entry);
ErrorState::compileLegacyCode(Build &build)
{
static MemBuf mb;
- const char *p = NULL; /* takes priority over mb if set */
+ const char *p = nullptr; /* takes priority over mb if set */
int do_quote = 1;
int no_urlescape = 0; /* if true then item is NOT to be further URL-encoded */
char ntoabuf[MAX_IPSTRLEN];
case 'R':
if (building_deny_info_url) {
- if (request != NULL) {
+ if (request != nullptr) {
const SBuf &tmp = request->url.path();
mb.append(tmp.rawContent(), tmp.length());
no_urlescape = 1;
status = Http::scTemporaryRedirect;
}
- rep->setHeaders(status, NULL, "text/html;charset=utf-8", 0, 0, -1);
+ rep->setHeaders(status, nullptr, "text/html;charset=utf-8", 0, 0, -1);
if (request) {
auto location = compile(urlTemplate, true, true);
httpHeaderPutStrf(&rep->header, Http::HdrType::X_SQUID_ERROR, "%d %s", httpStatus, "Access Denied");
} else {
const auto body = buildBody();
- rep->setHeaders(httpStatus, NULL, "text/html;charset=utf-8", body.length(), 0, -1);
+ rep->setHeaders(httpStatus, nullptr, "text/html;charset=utf-8", body.length(), 0, -1);
/*
* include some information for downstream caches. Implicit
* replaceable content. This isn't quite sufficient. xerrno is not
delete value;
}
-ESIAssign::ESIAssign (ESIAssign const &old) : parent (NULL), varState (NULL), name (old.name), value (old.value ? new ESIVariableExpression (*old.value): NULL), variable (NULL), unevaluatedVariable(old.unevaluatedVariable)
+ESIAssign::ESIAssign (ESIAssign const &old) : parent (nullptr), varState (nullptr), name (old.name), value (old.value ? new ESIVariableExpression (*old.value): nullptr), variable (nullptr), unevaluatedVariable(old.unevaluatedVariable)
{}
-ESIAssign::ESIAssign (esiTreeParentPtr aParent, int attrcount, char const **attr, ESIContext *aContext) : parent (aParent), varState (NULL), name(), value (NULL), variable (NULL), unevaluatedVariable()
+ESIAssign::ESIAssign (esiTreeParentPtr aParent, int attrcount, char const **attr, ESIContext *aContext) : parent (aParent), varState (nullptr), name(), value (nullptr), variable (nullptr), unevaluatedVariable()
{
/* TODO: grab content IFF no value was specified */
assert (aContext);
if (variable.getRaw())
variable->process (false);
- variable = NULL;
+ variable = nullptr;
if (unevaluatedVariable.size()) {
varState->feedData(unevaluatedVariable.rawBuf(), unevaluatedVariable.size());
varState->addVariable (name.rawBuf(), name.size(), value);
- value = NULL;
+ value = nullptr;
debugs(86, 5, "ESIAssign: Processed " << this);
cbdataReferenceDone (varState);
if (parent.getRaw())
- parent = NULL;
+ parent = nullptr;
}
bool
http->storeEntry()->cachedESITree = treeToCache;
- treeToCache = NULL;
+ treeToCache = nullptr;
}
bool
public:
typedef RefCount<ESIContext> Pointer;
ESIContext() :
- thisNode(NULL),
- http(NULL),
+ thisNode(nullptr),
+ http(nullptr),
errorpage(ERR_NONE),
errorstatus(Http::scNone),
- errormessage(NULL),
- rep(NULL),
+ errormessage(nullptr),
+ rep(nullptr),
outbound_offset(0),
readpos(0),
pos(0),
- varState(NULL),
+ varState(nullptr),
cachedASTInUse(false),
reading_(true),
processing(false) {
/* when esi processing completes */
void provideData(ESISegment::Pointer, ESIElement *source);
- void fail (ESIElement *source, char const*anError = NULL);
+ void fail (ESIElement *source, char const*anError = nullptr);
void startRead();
void finishRead();
bool reading() const;
void render(ESISegment::Pointer);
bool addElement (ESIElement::Pointer);
- void fail(ESIElement *, char const * = NULL);
+ void fail(ESIElement *, char const * = nullptr);
esiProcessResult_t process (int dovars);
void provideData (ESISegment::Pointer data, ESIElement * source);
Pointer makeCacheable() const;
void render(ESISegment::Pointer);
bool addElement (ESIElement::Pointer);
- void fail(ESIElement *, char const * = NULL);
+ void fail(ESIElement *, char const * = nullptr);
esiProcessResult_t process (int dovars);
void provideData (ESISegment::Pointer data, ESIElement *source);
return reading_;
}
-ESIStreamContext::ESIStreamContext() : finished(false), include (NULL), localbuffer (new ESISegment), buffer (NULL)
+ESIStreamContext::ESIStreamContext() : finished(false), include (nullptr), localbuffer (new ESISegment), buffer (nullptr)
{}
/* Local functions */
outbound = theData;
outboundtail = outbound;
} else {
- assert (outboundtail->next.getRaw() == NULL);
+ assert (outboundtail->next.getRaw() == nullptr);
outboundtail->next = theData;
}
{
clientStreamNode *next;
/* Test preconditions */
- assert (thisNode != NULL);
+ assert (thisNode != nullptr);
assert (cbdataReferenceValid (thisNode));
/* we are not in the chain until ESI is detected on a data callback */
- assert (thisNode->node.prev != NULL);
- assert (thisNode->node.next != NULL);
+ assert (thisNode->node.prev != nullptr);
+ assert (thisNode->node.next != nullptr);
ESIContext::Pointer context = dynamic_cast<ESIContext *>(thisNode->data.getRaw());
- assert (context.getRaw() != NULL);
+ assert (context.getRaw() != nullptr);
if (context->flags.passthrough) {
/* passthru mode - read into supplied buffers */
assert (!context->outbound.getRaw());
/* We've finished processing, and there is no more data buffered */
debugs(86, 5, "Telling recipient EOF on READ");
- clientStreamCallback (thisNode, http, NULL, tempBuffer);
+ clientStreamCallback (thisNode, http, nullptr, tempBuffer);
return;
}
esiStreamStatus (clientStreamNode *thisNode, ClientHttpRequest *http)
{
/* Test preconditions */
- assert (thisNode != NULL);
+ assert (thisNode != nullptr);
assert (cbdataReferenceValid (thisNode));
/* we are not in the chain until ESI is detected on a data callback */
- assert (thisNode->node.prev != NULL);
- assert (thisNode->node.next != NULL);
+ assert (thisNode->node.prev != nullptr);
+ assert (thisNode->node.next != nullptr);
ESIContext::Pointer context = dynamic_cast<ESIContext *>(thisNode->data.getRaw());
- assert (context.getRaw() != NULL);
+ assert (context.getRaw() != nullptr);
if (context->flags.passthrough)
return clientStreamStatus (thisNode, http);
assert (pos == next->readBuffer.offset);
/* We must send data or a reply */
- assert (len != 0 || rep != NULL);
+ assert (len != 0 || rep != nullptr);
if (len) {
memcpy(next->readBuffer.data, &outbound->buf[outbound_offset], len);
pos += len;
if (!outbound.getRaw())
- outboundtail = NULL;
+ outboundtail = nullptr;
trimBlanks();
}
debugs(86, 5, "ESIContext::send: this=" << this << " Client no longer wants data ");
/* Deal with re-entrancy */
HttpReplyPointer temprep = rep;
- rep = NULL; /* freed downstream */
+ rep = nullptr; /* freed downstream */
if (temprep && varState)
varState->buildVary(temprep.getRaw());
if (tree.getRaw())
tree->finish();
- tree = NULL;
+ tree = nullptr;
}
/* Detach event from a client Stream */
{
/* if we have pending callbacks, tell them we're done. */
/* test preconditions */
- assert (thisNode != NULL);
+ assert (thisNode != nullptr);
assert (cbdataReferenceValid (thisNode));
ESIContext::Pointer context = dynamic_cast<ESIContext *>(thisNode->data.getRaw());
- assert (context.getRaw() != NULL);
+ assert (context.getRaw() != nullptr);
/* detach from the stream */
clientStreamDetach (thisNode,http);
/* if we have pending callbacks (from subincludes), tell them we're done. */
- context->thisNode = NULL;
+ context->thisNode = nullptr;
context->flags.detached = 1;
context->finishChildren();
/* HACK for parser stack not being emptied */
- context->parserState.stack[0] = NULL;
+ context->parserState.stack[0] = nullptr;
/* allow refcount logic to trigger */
- context->cbdataLocker = NULL;
+ context->cbdataLocker = nullptr;
}
/* Process incoming data for ESI tags */
esiProcessStream (clientStreamNode *thisNode, ClientHttpRequest *http, HttpReply *rep, StoreIOBuffer receivedData)
{
/* test preconditions */
- assert (thisNode != NULL);
+ assert (thisNode != nullptr);
/* ESI TODO: handle thisNode rather than asserting - it should only ever
* happen if we cause an abort and the callback chain
* loops back to here, so we can simply return. However, that itself
* if data is NULL thisNode is the first entrance. If rep is also NULL,
* something is wrong.
* */
- assert (thisNode->data.getRaw() != NULL || rep);
- assert (thisNode->node.next != NULL);
+ assert (thisNode->data.getRaw() != nullptr || rep);
+ assert (thisNode->node.next != nullptr);
if (!thisNode->data.getRaw())
/* setup ESI context from reply headers */
ESIContext::Pointer context = dynamic_cast<ESIContext *>(thisNode->data.getRaw());
- assert (context.getRaw() != NULL);
+ assert (context.getRaw() != nullptr);
context->finishRead();
}
/* EOF / Read error / aborted entry */
- if (rep == NULL && receivedData.data == NULL && receivedData.length == 0 && !context->flags.finishedtemplate) {
+ if (rep == nullptr && receivedData.data == nullptr && receivedData.length == 0 && !context->flags.finishedtemplate) {
/* TODO: get stream status to test the entry for aborts */
/* else flush the esi processor */
debugs(86, 5, "esiProcess: " << context.getRaw() << " Finished reading upstream data");
case ESIElement::ESI_ELEMENT_ASSIGN:
/* pop of the stack */
- parserState.stack[--parserState.stackdepth] = NULL;
+ parserState.stack[--parserState.stackdepth] = nullptr;
break;
}
} /* End of end handler */
assert (buffered.getRaw());
debugs (86,9,"ESIContext::parseOneBuffer: " << buffered->len << " bytes");
- bool lastBlock = buffered->next.getRaw() == NULL && flags.finishedtemplate ? true : false;
+ bool lastBlock = buffered->next.getRaw() == nullptr && flags.finishedtemplate ? true : false;
if (! parserState.theParser->parse(buffered->buf, buffered->len, lastBlock)) {
setError();
}
/* Tel the read code to allocate a new buffer */
- incoming = NULL;
+ incoming = nullptr;
parserState.parsing = 0;
}
void
ESIContext::ParserState::freeResources()
{
- theParser = NULL;
+ theParser = nullptr;
inited_ = false;
}
ESIContext::ParserState::popAll()
{
while (stackdepth)
- stack[--stackdepth] = NULL;
+ stack[--stackdepth] = nullptr;
}
void
ESISegmentFreeList (outbound);
ESISegmentFreeList (outboundtail);
delete varState;
- varState=NULL;
+ varState=nullptr;
/* don't touch incoming, it's a pointer into buffered anyway */
}
// XXX: with the in-direction on remote IP. does the http->getConn()->clientConnection exist?
const auto err = clientBuildError(errorpage, errorstatus, nullptr, http->getConn(), http->request, http->al);
err->err_msg = errormessage;
- errormessage = NULL;
+ errormessage = nullptr;
rep = err->BuildHttpReply();
// XXX: Leaking err!
assert (rep->body.hasContent());
esiComment::makeCacheable() const
{
debugs(86, 5, "esiComment::makeCacheable: returning NULL");
- return NULL;
+ return nullptr;
}
ESIElement::Pointer
esiComment::makeUsable(esiTreeParentPtr, ESIVarState &) const
{
fatal ("esiComment::Usable: unreachable code!\n");
- return NULL;
+ return nullptr;
}
/* esiLiteral */
{
debugs(86, 9, "esiLiteral::render: Rendering " << this);
/* append the entire chain */
- assert (output->next.getRaw() == NULL);
+ assert (output->next.getRaw() == nullptr);
output->next = buffer;
- buffer = NULL;
+ buffer = nullptr;
}
esiProcessResult_t
}
esiLiteral::esiLiteral(esiLiteral const &old) : buffer (old.buffer->cloneList()),
- varState (NULL)
+ varState (nullptr)
{
flags.donevars = 0;
}
esiRemove::makeCacheable() const
{
debugs(86, 5, "esiRemove::makeCacheable: Returning NULL");
- return NULL;
+ return nullptr;
}
ESIElement::Pointer
esiRemove::makeUsable(esiTreeParentPtr, ESIVarState &) const
{
fatal ("esiRemove::Usable: unreachable code!\n");
- return NULL;
+ return nullptr;
}
/* esiTry */
esiTry::esiTry(esiTreeParentPtr aParent) :
parent(aParent),
- exceptbuffer(NULL)
+ exceptbuffer(nullptr)
{
memset(&flags, 0, sizeof(flags));
}
if (flags.attemptfailed) {
if (flags.exceptok) {
parent->provideData (exceptbuffer, this);
- exceptbuffer = NULL;
- } else if (flags.exceptfailed || except.getRaw() == NULL) {
+ exceptbuffer = nullptr;
+ } else if (flags.exceptfailed || except.getRaw() == nullptr) {
parent->fail (this, "esi:try - except claused failed, or no except clause found");
}
}
parent->provideData (data, this);
} else if (source == except) {
flags.exceptok = 1;
- assert (exceptbuffer == NULL);
+ assert (exceptbuffer == nullptr);
ESISegment::ListTransfer (data, exceptbuffer);
notifyParent();
}
esiTry::esiTry(esiTry const &)
{
- attempt = NULL;
- except = NULL;
+ attempt = nullptr;
+ except = nullptr;
flags.attemptok = 0;
flags.exceptok = 0;
flags.attemptfailed = 0;
flags.exceptfailed = 0;
- parent = NULL;
- exceptbuffer = NULL;
+ parent = nullptr;
+ exceptbuffer = nullptr;
}
ESIElement::Pointer
void
esiTry::finish()
{
- parent = NULL;
+ parent = nullptr;
if (attempt.getRaw())
attempt->finish();
- attempt = NULL;
+ attempt = nullptr;
if (except.getRaw())
except->finish();
- except = NULL;
+ except = nullptr;
}
/* esiChoose */
esiChoose::render(ESISegment::Pointer output)
{
/* append all processed elements, and trim processed and rendered elements */
- assert (output->next == NULL);
+ assert (output->next == nullptr);
assert (elements.size() || otherwise.getRaw());
debugs(86, 5, "esiChooseRender: rendering");
if (otherwise.getRaw())
otherwise->finish();
- otherwise = NULL;
+ otherwise = nullptr;
int pos = 0;
for (auto &element : elements) {
if (otherwise.getRaw())
otherwise->finish();
- otherwise = NULL;
+ otherwise = nullptr;
- parent = NULL;
+ parent = nullptr;
return ESI_PROCESS_FAILED;
}
if (otherwise.getRaw())
otherwise->finish();
- otherwise = NULL;
+ otherwise = nullptr;
parent->fail(this, anError);
- parent = NULL;
+ parent = nullptr;
}
void
parent->provideData (data, this);
}
-esiChoose::esiChoose(esiChoose const &old) : chosenelement(-1), otherwise (NULL), parent (NULL)
+esiChoose::esiChoose(esiChoose const &old) : chosenelement(-1), otherwise (nullptr), parent (nullptr)
{
for (size_t counter = 0; counter < old.elements.size(); ++counter) {
ESIElement::Pointer newElement = old.elements[counter]->makeCacheable();
esiWhen::esiWhen(esiTreeParentPtr aParent, int attrcount, const char **attr,ESIVarState *aVar) :
esiSequence(aParent),
testValue(false),
- unevaluatedExpression(NULL),
- varState(NULL)
+ unevaluatedExpression(nullptr),
+ varState(nullptr)
{
- char const *expression = NULL;
+ char const *expression = nullptr;
for (int loopCounter = 0; loopCounter < attrcount && attr[loopCounter]; loopCounter += 2) {
if (!strcmp(attr[loopCounter],"test")) {
/* evaluate test */
debugs(86, 5, "esiWhen::esiWhen: Evaluating '" << attr[loopCounter+1] << "'");
/* TODO: warn the user instead of asserting */
- assert (expression == NULL);
+ assert (expression == nullptr);
expression = attr[loopCounter+1];
} else {
/* ignore mistyped attributes.
esiWhen::esiWhen(esiWhen const &old) :
esiSequence(old),
testValue(false),
- unevaluatedExpression(NULL),
- varState(NULL)
+ unevaluatedExpression(nullptr),
+ varState(nullptr)
{
if (old.unevaluatedExpression)
unevaluatedExpression = xstrdup(old.unevaluatedExpression);
ESIExpatParser::ESIExpatParser(ESIParserClient *aClient) : theClient (aClient)
{
/* TODO: grab the document encoding from the headers */
- p = XML_ParserCreateNS(NULL,'|');
+ p = XML_ParserCreateNS(nullptr,'|');
XML_SetUserData (myParser(), static_cast<void *>(this));
XML_SetElementHandler(myParser(), Start, End);
XML_SetDefaultHandler(myParser(), Default);
ESIExpatParser::~ESIExpatParser()
{
XML_ParserFree (myParser());
- p = NULL;
+ p = nullptr;
}
void
if (s->valuetype == ESI_EXPR_LITERAL
&& s->valuestored == ESI_LITERAL_STRING) {
safe_free(s->value.string);
- s->value.string = NULL;
+ s->value.string = nullptr;
}
}
char const *origs = s;
/* trim whitespace */
s = trim(s);
- rv.eval = NULL; /* A literal */
+ rv.eval = nullptr; /* A literal */
rv.valuetype = ESI_EXPR_INVALID;
rv.valuestored = ESI_LITERAL_INVALID;
rv.precedence = 1; /* A literal */
esiBufferRecipient (clientStreamNode *node, ClientHttpRequest *http, HttpReply *rep, StoreIOBuffer receivedData)
{
/* Test preconditions */
- assert (node != NULL);
+ assert (node != nullptr);
/* ESI TODO: handle thisNode rather than asserting
* - it should only ever happen if we cause an
* abort and the callback chain loops back to
* itself shouldn't happen, so it stays as an
* assert for now. */
assert (cbdataReferenceValid (node));
- assert (node->node.next == NULL);
- assert (http->getConn() == NULL);
+ assert (node->node.next == nullptr);
+ assert (http->getConn() == nullptr);
ESIStreamContext::Pointer esiStream = dynamic_cast<ESIStreamContext *>(node->data.getRaw());
- assert (esiStream.getRaw() != NULL);
+ assert (esiStream.getRaw() != nullptr);
/* If segments become more flexible, ignore thisNode */
assert (receivedData.length <= sizeof(esiStream->localbuffer->buf));
assert (!esiStream->finished);
/* trivial case */
if (http->out.offset != 0) {
- assert(rep == NULL);
+ assert(rep == nullptr);
} else {
if (rep) {
if (rep->sline.status() != Http::scOkay) {
- rep = NULL;
+ rep = nullptr;
esiStream->include->includeFail (esiStream);
esiStream->finished = 1;
httpRequestFree (http);
headersLog(0, 0, http->request->method, rep);
#endif
- rep = NULL;
+ rep = nullptr;
}
}
esiStream->localbuffer->len = receivedData.length;
} else {
- assert (esiStream->buffer.getRaw() != NULL);
+ assert (esiStream->buffer.getRaw() != nullptr);
esiStream->buffer->len = receivedData.length;
}
}
/* EOF / Read error / aborted entry */
- if (rep == NULL && receivedData.data == NULL && receivedData.length == 0) {
+ if (rep == nullptr && receivedData.data == nullptr && receivedData.length == 0) {
/* TODO: get stream status to test the entry for aborts */
debugs(86, 5, "Finished reading upstream data in subrequest");
esiStream->include->subRequestDone (esiStream, true);
ESIStreamContext::freeResources()
{
debugs(86, 5, "Freeing stream context resources.");
- buffer = NULL;
- localbuffer = NULL;
- include = NULL;
+ buffer = nullptr;
+ localbuffer = nullptr;
+ include = nullptr;
}
ESIStreamContext *
void
ESIInclude::finish()
{
- parent = NULL;
+ parent = nullptr;
}
ESIElement::Pointer
}
ESIInclude::ESIInclude(ESIInclude const &old) :
- varState(NULL),
- srcurl(NULL),
- alturl(NULL),
- parent(NULL),
+ varState(nullptr),
+ srcurl(nullptr),
+ alturl(nullptr),
+ parent(nullptr),
started(false),
sent(false)
{
}
ESIInclude::ESIInclude(esiTreeParentPtr aParent, int attrcount, char const **attr, ESIContext *aContext) :
- varState(NULL),
- srcurl(NULL),
- alturl(NULL),
+ varState(nullptr),
+ srcurl(nullptr),
+ alturl(nullptr),
parent(aParent),
started(false),
sent(false)
debugs(86, 5, "ESIIncludeNew: Requesting source '" << attr[i+1] << "'");
/* TODO: don't assert on thisNode, ignore the duplicate */
- assert (src.getRaw() == NULL);
+ assert (src.getRaw() == nullptr);
src = ESIStreamContextNew (this);
- assert (src.getRaw() != NULL);
+ assert (src.getRaw() != nullptr);
srcurl = xstrdup(attr[i+1]);
} else if (!strcmp(attr[i],"alt")) {
/* Start a secondary request for thisNode url */
*/
debugs(86, 5, "ESIIncludeNew: Requesting alternate '" << attr[i+1] << "'");
- assert (alt.getRaw() == NULL); /* TODO: fix? */
+ assert (alt.getRaw() == nullptr); /* TODO: fix? */
alt = ESIStreamContextNew (this);
- assert (alt.getRaw() != NULL);
+ assert (alt.getRaw() != nullptr);
alturl = xstrdup(attr[i+1]);
} else if (!strcmp(attr[i],"onerror")) {
if (!strcmp(attr[i+1], "continue")) {
Start (src, srcurl, varState);
Start (alt, alturl, varState);
} else {
- alt = NULL;
+ alt = nullptr;
debugs(86, DBG_IMPORTANT, "ESIIncludeNew: esi:include with no src attributes");
/* Render the content */
if (srccontent.getRaw()) {
myout = srccontent;
- srccontent = NULL;
+ srccontent = nullptr;
} else if (altcontent.getRaw()) {
myout = altcontent;
- altcontent = NULL;
+ altcontent = nullptr;
} else
fatal ("ESIIncludeRender called with no content, and no failure!\n");
- assert (output->next == NULL);
+ assert (output->next == nullptr);
output->next = myout;
}
}
- src = NULL;
+ src = nullptr;
} else if (stream == alt) {
debugs(86, 3, "ESIInclude::subRequestDone: " << alturl);
}
}
- alt = NULL;
+ alt = nullptr;
} else {
fatal ("ESIIncludeSubRequestDone: non-owned stream found!\n");
}
* Its probably due to parent being set to null - by a call to
* 'this.finish' while the subrequest is still not completed.
*/
- if (parent.getRaw() == NULL) {
+ if (parent.getRaw() == nullptr) {
debugs(86, DBG_CRITICAL, "ERROR: Squid Bug #951: ESIInclude::subRequestDone: Sub request completed "
"after finish() called and parent unlinked. Unable to "
"continue handling the request, and may be memory leaking. "
parent->provideData (srccontent.getRaw() ? srccontent:altcontent,this);
if (srccontent.getRaw())
- srccontent = NULL;
+ srccontent = nullptr;
else
- altcontent = NULL;
+ altcontent = nullptr;
} else if (flags.onerrorcontinue) {
/* render nothing but inform of completion */
// the global document that will store the resolved entity
// definitions
-static htmlDocPtr entity_doc = NULL;
+static htmlDocPtr entity_doc = nullptr;
EsiParserDefinition(ESILibxml2Parser);
int count=0;
xmlChar **tmp = (xmlChar **)atts;
- while (tmp && *tmp != NULL) {
+ while (tmp && *tmp != nullptr) {
++count;
++tmp;
}
{
xmlEntityPtr res = xmlGetDocEntity(entity_doc, name);
- if (res == NULL) {
+ if (res == nullptr) {
const htmlEntityDesc *ent = htmlEntityLookup(name);
- if (ent != NULL) {
+ if (ent != nullptr) {
char tmp[32];
snprintf(tmp, 32, "&#%d;", ent->value);
- res = xmlAddDocEntity(entity_doc, (const xmlChar *)name, XML_INTERNAL_GENERAL_ENTITY, NULL, NULL, (const xmlChar *)tmp);
+ res = xmlAddDocEntity(entity_doc, (const xmlChar *)name, XML_INTERNAL_GENERAL_ENTITY, nullptr, nullptr, (const xmlChar *)tmp);
}
}
sax.getEntity = esi_getEntitySAXFunc;
/* TODO: grab the document encoding from the headers */
- parser = xmlCreatePushParserCtxt(&sax, static_cast<void *>(this), NULL, 0, NULL);
+ parser = xmlCreatePushParserCtxt(&sax, static_cast<void *>(this), nullptr, 0, nullptr);
- if (entity_doc == NULL)
- entity_doc = htmlNewDoc(NULL, NULL);
+ if (entity_doc == nullptr)
+ entity_doc = htmlNewDoc(nullptr, nullptr);
}
ESILibxml2Parser::~ESILibxml2Parser()
{
xmlFreeParserCtxt(parser);
- parser = NULL;
+ parser = nullptr;
}
bool
{
xmlErrorPtr error = xmlGetLastError();
- if (error == NULL)
- return NULL;
+ if (error == nullptr)
+ return nullptr;
return error->message;
}
#include "esi/Parser.h"
#include "fatal.h"
-char *ESIParser::Type = NULL;
-ESIParser::Register *ESIParser::Parser = NULL;
+char *ESIParser::Type = nullptr;
+ESIParser::Register *ESIParser::Parser = nullptr;
std::list<ESIParser::Register *> &
ESIParser::GetRegistry()
while (head.getRaw()) {
ESISegment::Pointer temp = head;
head = head->next;
- temp->next = NULL;
+ temp->next = nullptr;
}
}
void
ESISegment::adsorbList (ESISegment::Pointer from)
{
- assert (next.getRaw() == NULL);
- assert (from.getRaw() != NULL);
+ assert (next.getRaw() == nullptr);
+ assert (from.getRaw() != nullptr);
/* prevent worst case */
assert (!(len == 0 && from->len == space() ));
Pointer copyFrom = from;
{
if (!to.getRaw()) {
to = from;
- from = NULL;
+ from = nullptr;
return;
}
ESISegment::Pointer temp = to->tail();
temp->adsorbList (from);
- from = NULL;
+ from = nullptr;
}
size_t
void
ESISegment::listAppend (char const *s, size_t length)
{
- assert (next.getRaw() == NULL);
+ assert (next.getRaw() == nullptr);
ESISegment::Pointer output = this;
/* copy the string to output */
size_t pos=0;
while (pos < length) {
if (output->space() == 0) {
- assert (output->next.getRaw() == NULL);
+ assert (output->next.getRaw() == nullptr);
output->next = new ESISegment;
output = output->next;
}
ESISegment::cloneList () const
{
ESISegment::Pointer result = new ESISegment (*this);
- result->next = next.getRaw() ? next->cloneList() : NULL;
+ result->next = next.getRaw() ? next->cloneList() : nullptr;
return result;
}
return result.getRaw();
}
-ESISegment::ESISegment(ESISegment const &old) : len (0), next(NULL)
+ESISegment::ESISegment(ESISegment const &old) : len (0), next(nullptr)
{
append (old.buf, old.len);
}
static void ListAppend (Pointer &, char const *, size_t);
static void ListTransfer (Pointer &from, Pointer &to);
- ESISegment() : len(0), next(NULL) {*buf = 0;}
+ ESISegment() : len(0), next(nullptr) {*buf = 0;}
ESISegment(ESISegment const &);
~ESISegment() {}
/* append all processed elements, and trim processed
* and rendered elements
*/
- assert (output->next == NULL);
+ assert (output->next == nullptr);
debugs (86,5, "esiSequenceRender: rendering " << processedcount << " elements");
for (size_t i = 0; i < processedcount; ++i) {
// prune completed elements
elements.erase(elements.begin(), elements.begin() + processedcount);
processedcount = 0;
- assert (output->next == NULL);
+ assert (output->next == nullptr);
}
void
{
debugs(86, 5, "esiSequence::finish: " << this << " is finished");
FinishAllElements(elements);
- parent = NULL;
+ parent = nullptr;
}
void
if (processingResult == ESI_PROCESS_FAILED) {
FinishAllElements(elements);
failed = true;
- parent = NULL;
+ parent = nullptr;
processing = false;
return processingResult;
}
/* Depends on full parsing before processing */
if (processedcount == elements.size())
- parent = NULL;
+ parent = nullptr;
debugs(86, 5, "esiSequence::process: " << this << " completed");
debugs(86, 5, "esiSequence::fail: " << this << " has failed.");
parent->fail (this, anError);
FinishAllElements(elements);
- parent = NULL;
+ parent = nullptr;
}
esiSequence::esiSequence(esiSequence const &old) :
processedcount(0),
- parent(NULL),
+ parent(nullptr),
mayFail_(old.mayFail_),
failed(old.failed),
provideIncrementalData(old.provideIncrementalData),
if (elements.size() == 0) {
debugs(86, 5, "esiSequence::makeCacheable: No elements in sequence " << this << ", returning NULL");
- return NULL;
+ return nullptr;
}
esiSequence * resultS = new esiSequence (*this);
if (elements.size() == 0) {
debugs(86, 5, "esiSequence::makeUsable: No elements in sequence " << this << ", returning NULL");
- return NULL;
+ return nullptr;
}
esiSequence * resultS = new esiSequence (*this);
void provideData (ESISegment::Pointer, ESIElement*);
bool mayFail () const;
void wontFail();
- void fail(ESIElement *, char const *anError = NULL);
+ void fail(ESIElement *, char const *anError = nullptr);
void makeCachableElements(esiSequence const &old);
Pointer makeCacheable() const;
void makeUsableElements(esiSequence const &old, ESIVarState &);
{
doIt();
ESISegment::Pointer rv = output;
- output = NULL;
+ output = nullptr;
debugs(86, 6, "ESIVarStateExtractList: Extracted list");
return rv;
}
ESIVarState::~ESIVarState()
{
// freeResources
- input = NULL;
+ input = nullptr;
ESISegmentFreeList(output);
hdr.clean();
return xstrndup(t, len + 1);
}
-ESIVariableQuery::ESIVariableQuery(char const *uri) : query (NULL), query_sz (0), query_elements (0), query_string (NULL)
+ESIVariableQuery::ESIVariableQuery(char const *uri) : query (nullptr), query_sz (0), query_elements (0), query_string (nullptr)
{
/* Count off the query elements */
char const *query_start = strchr (uri, '?');
}
ESIVarState::ESIVarState(HttpHeader const *aHeader, char const *uri) :
- output(NULL),
+ output(nullptr),
hdr(hoReply)
{
memset(&flags, 0, sizeof(flags));
void
ESIVariableCookie::eval (ESIVarState &state, char const *subref, char const *found_default) const
{
- const char *s = NULL;
+ const char *s = nullptr;
state.cookieUsed();
if (state.header().has(Http::HdrType::COOKIE)) {
void
ESIVariableHost::eval (ESIVarState &state, char const *subref, char const *found_default) const
{
- const char *s = NULL;
+ const char *s = nullptr;
state.hostUsed();
if (!subref && state.header().has(Http::HdrType::HOST)) {
void
ESIVariableLanguage::eval (ESIVarState &state, char const *subref, char const *found_default) const
{
- char const *s = NULL;
+ char const *s = nullptr;
state.languageUsed();
if (state.header().has(Http::HdrType::ACCEPT_LANGUAGE)) {
void
ESIVariableQuery::eval (ESIVarState &state, char const *subref, char const *found_default) const
{
- char const *s = NULL;
+ char const *s = nullptr;
if (!subref)
s = queryString();
void
ESIVariableReferer::eval (ESIVarState &state, char const *subref, char const *found_default) const
{
- const char *s = NULL;
+ const char *s = nullptr;
state.refererUsed();
if (!subref && state.header().has(Http::HdrType::REFERER))
void
ESIVariableUserAgent::eval (ESIVarState &state, char const *subref, char const *found_default) const
{
- char const *s = NULL;
+ char const *s = nullptr;
state.useragentUsed();
if (state.header().has(Http::HdrType::USER_AGENT)) {
if (*symbol == '(')
return new ESIFunction(aProcessor);
- return NULL;
+ return nullptr;
}
class ESIVariableProcessor
#define LOOKFORSTART 0
ESIVariableProcessor::ESIVariableProcessor(char *aString, ESISegment::Pointer &aSegment, Trie &aTrie, ESIVarState *aState) :
string(aString), output (aSegment), variables(aTrie), varState (aState),
- state(LOOKFORSTART), pos(0), var_pos(0), done_pos(0), found_subref (NULL),
- found_default (NULL), currentFunction(NULL)
+ state(LOOKFORSTART), pos(0), var_pos(0), done_pos(0), found_subref (nullptr),
+ found_default (nullptr), currentFunction(nullptr)
{
len = strlen (string);
vartype = varState->GetVar("",0);
void
ESIVariableProcessor::doIt()
{
- assert (output == NULL);
+ assert (output == nullptr);
while (pos < len) {
/* skipping pre-variables */
/* The list of event processes */
static OBJH eventDump;
-static const char *last_event_ran = NULL;
+static const char *last_event_ran = nullptr;
// This AsyncCall dialer can be configured to check that the event cbdata is
// valid before calling the event handler
when(evWhen),
weight(aWeight),
cbdata(haveArg),
- next(NULL)
+ next(nullptr)
{
}
EventScheduler EventScheduler::_instance;
-EventScheduler::EventScheduler(): tasks(NULL)
+EventScheduler::EventScheduler(): tasks(nullptr)
{}
EventScheduler::~EventScheduler()
ev_entry **E;
ev_entry *event;
- for (E = &tasks; (event = *E) != NULL; E = &(*E)->next) {
+ for (E = &tasks; (event = *E) != nullptr; E = &(*E)->next) {
if (event->func != func)
continue;
* to NULL. We need to break here or else we'll get a NULL
* pointer dereference in the last clause of the for loop.
*/
- if (NULL == *E)
+ if (nullptr == *E)
break;
}
delete event;
}
- tasks = NULL;
+ tasks = nullptr;
}
void
ev_entry *event;
- for (event = tasks; event != NULL; event = event->next) {
+ for (event = tasks; event != nullptr; event = event->next) {
if (event->func == func && event->arg == arg)
return true;
}
CBDATA_CLASS_INIT(external_acl);
external_acl::external_acl() :
- next(NULL),
+ next(nullptr),
ttl(DEFAULT_EXTERNAL_ACL_TTL),
negative_ttl(-1),
grace(1),
- name(NULL),
+ name(nullptr),
format("external_acl_type"),
- cmdline(NULL),
+ cmdline(nullptr),
children(DEFAULT_EXTERNAL_ACL_CHILDREN),
- theHelper(NULL),
- cache(NULL),
+ theHelper(nullptr),
+ cache(nullptr),
cache_size(256*1024),
cache_entries(0),
#if USE_AUTH
if (theHelper) {
helperShutdown(theHelper);
delete theHelper;
- theHelper = NULL;
+ theHelper = nullptr;
}
while (lru_list.tail) {
while (next) {
external_acl *node = next;
next = node->next;
- node->next = NULL; // prevent recursion
+ node->next = nullptr; // prevent recursion
delete node;
}
}
if (node->quote == Format::LOG_QUOTE_SHELL)
storeAppendPrintf(sentry, " protocol=2.5");
- node->format.dump(sentry, NULL, false);
+ node->format.dump(sentry, nullptr, false);
for (word = node->cmdline; word; word = word->next)
storeAppendPrintf(sentry, " %s", word->key);
free_externalAclHelper(external_acl ** list)
{
delete *list;
- *list = NULL;
+ *list = nullptr;
}
static external_acl *
return node;
}
- return NULL;
+ return nullptr;
}
void
external_acl::add(const ExternalACLEntryPointer &anEntry)
{
trimCache();
- assert(anEntry != NULL);
- assert (anEntry->def == NULL);
+ assert(anEntry != nullptr);
+ assert (anEntry->def == nullptr);
anEntry->def = this;
ExternalACLEntry *e = const_cast<ExternalACLEntry *>(anEntry.getRaw()); // XXX: make hash a std::map of Pointer.
hash_join(cache, e);
CBDATA_CLASS(external_acl_data);
public:
- explicit external_acl_data(external_acl *aDef) : def(cbdataReference(aDef)), name(NULL), arguments(NULL) {}
+ explicit external_acl_data(external_acl *aDef) : def(cbdataReference(aDef)), name(nullptr), arguments(nullptr) {}
~external_acl_data();
external_acl *def;
external_acl_message = "MISSING REQUIRED INFORMATION";
- if (entry != NULL) {
+ if (entry != nullptr) {
if (entry->def == acl->def) {
/* Ours, use it.. if the key matches */
const char *key = makeExternalAclKey(ch, acl);
if (strcmp(key, (char*)entry->key) != 0) {
debugs(82, 9, "entry key='" << (char *)entry->key << "', our key='" << key << "' do not match. Discarded.");
// too bad. need a new lookup.
- entry = ch->extacl_entry = NULL;
+ entry = ch->extacl_entry = nullptr;
}
} else {
/* Not ours.. get rid of it */
debugs(82, 9, "entry " << entry << " not valid or not ours. Discarded.");
- if (entry != NULL) {
+ if (entry != nullptr) {
debugs(82, 9, "entry def=" << entry->def << ", our def=" << acl->def);
const char *key = makeExternalAclKey(ch, acl); // may be nil
debugs(82, 9, "entry key='" << (char *)entry->key << "', our key='" << key << "'");
}
- entry = ch->extacl_entry = NULL;
+ entry = ch->extacl_entry = nullptr;
}
}
entry = static_cast<ExternalACLEntry *>(hash_lookup(acl->def->cache, key));
const ExternalACLEntryPointer staleEntry = entry;
- if (entry != NULL && external_acl_entry_expired(acl->def, entry))
- entry = NULL;
+ if (entry != nullptr && external_acl_entry_expired(acl->def, entry))
+ entry = nullptr;
- if (entry != NULL && external_acl_grace_expired(acl->def, entry)) {
+ if (entry != nullptr && external_acl_grace_expired(acl->def, entry)) {
// refresh in the background
ExternalACLLookup::Start(ch, acl, true);
debugs(82, 4, "no need to wait for the refresh of '" <<
// if we fail to go async, we still return NULL and the caller
// will detect the failure in ACLExternal::match().
(void)ch->goAsync(IdentLookup::Instance());
- return NULL;
+ return nullptr;
}
}
#endif
entry = static_cast<ExternalACLEntry *>(hash_lookup(def->cache, key));
debugs(82, 2, "external_acl_cache_add: Adding '" << key << "' = " << data.result);
- if (entry != NULL) {
+ if (entry != nullptr) {
debugs(82, 3, "updating existing entry");
entry->update(data);
external_acl_cache_touch(def, entry);
static void
external_acl_cache_delete(external_acl * def, const ExternalACLEntryPointer &entry)
{
- assert(entry != NULL);
+ assert(entry != nullptr);
assert(def->cache_size > 0 && entry->def == def);
ExternalACLEntry *e = const_cast<ExternalACLEntry *>(entry.getRaw()); // XXX: make hash a std::map of Pointer.
hash_remove_link(def->cache, e);
public:
externalAclState(external_acl* aDef, const char *aKey) :
- callback(NULL),
- callback_data(NULL),
+ callback(nullptr),
+ callback_data(nullptr),
key(xstrdup(aKey)),
def(cbdataReference(aDef)),
- queue(NULL)
+ queue(nullptr)
{}
~externalAclState();
entryData.notes.append(&reply.notes);
const char *label = reply.notes.findFirst("tag");
- if (label != NULL && *label != '\0')
+ if (label != nullptr && *label != '\0')
entryData.tag = label;
label = reply.notes.findFirst("message");
- if (label != NULL && *label != '\0')
+ if (label != nullptr && *label != '\0')
entryData.message = label;
label = reply.notes.findFirst("log");
- if (label != NULL && *label != '\0')
+ if (label != nullptr && *label != '\0')
entryData.log = label;
#if USE_AUTH
label = reply.notes.findFirst("user");
- if (label != NULL && *label != '\0')
+ if (label != nullptr && *label != '\0')
entryData.user = label;
label = reply.notes.findFirst("password");
- if (label != NULL && *label != '\0')
+ if (label != nullptr && *label != '\0')
entryData.password = label;
#endif
state->callback(cbdata, entry);
next = state->queue;
- state->queue = NULL;
+ state->queue = nullptr;
delete state;
/* Check for a pending lookup to hook into */
// only possible if we are caching results.
- externalAclState *oldstate = NULL;
+ externalAclState *oldstate = nullptr;
if (def->cache_size > 0) {
for (dlink_node *node = def->queue.head; node; node = node->next) {
externalAclState *oldstatetmp = static_cast<externalAclState *>(node->data);
checklist->resumeNonBlockingCheck(ExternalACLLookup::Instance());
}
-ACLExternal::ACLExternal(char const *theClass) : data(NULL), class_(xstrdup(theClass))
+ACLExternal::ACLExternal(char const *theClass) : data(nullptr), class_(xstrdup(theClass))
{}
char const *
void
fatal_dump(const char *message)
{
- failure_notify = NULL;
+ failure_notify = nullptr;
releaseServerSockets();
if (message)
assert(F->flags.open);
if (F->type == FD_FILE) {
- assert(F->read_handler == NULL);
- assert(F->write_handler == NULL);
+ assert(F->read_handler == nullptr);
+ assert(F->write_handler == nullptr);
}
debugs(51, 3, "fd_close FD " << fd << " " << F->desc);
const SBuf Format::Dash("-");
Format::Format::Format(const char *n) :
- format(NULL),
- next(NULL)
+ format(nullptr),
+ next(nullptr)
{
name = xstrdup(n);
}
// unlink the next entry for deletion
Format *temp = next;
next = temp->next;
- temp->next = NULL;
+ temp->next = nullptr;
delete temp;
}
storeAppendPrintf(entry, "%s", t->data.string);
else {
char argbuf[256];
- char *arg = NULL;
+ char *arg = nullptr;
ByteCode_t type = t->type;
switch (type) {
static_assert(sizeof(quotedOut) > 0, "quotedOut has zero length");
quotedOut[0] = '\0';
- char *newout = NULL;
+ char *newout = nullptr;
int newfree = 0;
switch (fmt->quote) {
char *
Format::QuoteUrlEncodeUsername(const char *name)
{
- if (NULL == name)
- return NULL;
+ if (nullptr == name)
+ return nullptr;
if (name[0] == '\0')
- return NULL;
+ return nullptr;
return QuoteMimeBlob(name);
}
char *buf;
char *buf_cursor;
- if (header == NULL) {
+ if (header == nullptr) {
buf = static_cast<char *>(xcalloc(1, 1));
*buf = '\0';
return buf;
TokenTableEntry("%", LFT_PERCENT),
- TokenTableEntry(NULL, LFT_NONE) /* this must be last */
+ TokenTableEntry(nullptr, LFT_NONE) /* this must be last */
};
/// 2-char tokens
TokenTableEntry("ea", LFT_EXT_LOG),
TokenTableEntry("sn", LFT_SEQUENCE_NUMBER),
- TokenTableEntry(NULL, LFT_NONE) /* this must be last */
+ TokenTableEntry(nullptr, LFT_NONE) /* this must be last */
};
/// Miscellaneous >2 byte tokens
TokenTableEntry("USER_CERTCHAIN", LFT_EXT_ACL_USER_CERTCHAIN_RAW),
TokenTableEntry("USER_CERT", LFT_EXT_ACL_USER_CERT_RAW),
#endif
- TokenTableEntry(NULL, LFT_NONE) /* this must be last */
+ TokenTableEntry(nullptr, LFT_NONE) /* this must be last */
};
static TokenTableEntry TokenTableProxyProtocol[] = {
TokenTableEntry("all_trs", LFT_ADAPTATION_ALL_XACT_TIMES),
TokenTableEntry("sum_trs", LFT_ADAPTATION_SUM_XACT_TIMES),
TokenTableEntry("<last_h", LFT_ADAPTATION_LAST_HEADER),
- TokenTableEntry(NULL, LFT_NONE) /* this must be last */
+ TokenTableEntry(nullptr, LFT_NONE) /* this must be last */
};
#endif
TokenTableEntry("to", LFT_ICAP_OUTCOME),
TokenTableEntry("Hs", LFT_ICAP_STATUS_CODE),
- TokenTableEntry(NULL, LFT_NONE) /* this must be last */
+ TokenTableEntry(nullptr, LFT_NONE) /* this must be last */
};
#endif
TokenTableEntry("<received_hello_version", LFT_TLS_SERVER_RECEIVED_HELLO_VERSION),
TokenTableEntry(">received_supported_version", LFT_TLS_CLIENT_SUPPORTED_VERSION),
TokenTableEntry("<received_supported_version", LFT_TLS_SERVER_SUPPORTED_VERSION),
- TokenTableEntry(NULL, LFT_NONE)
+ TokenTableEntry(nullptr, LFT_NONE)
};
#endif
} // namespace Format
const char *
Format::Token::scanForToken(TokenTableEntry const table[], const char *cur)
{
- for (TokenTableEntry const *lte = table; lte->configTag != NULL; ++lte) {
+ for (TokenTableEntry const *lte = table; lte->configTag != nullptr; ++lte) {
debugs(46, 8, "compare tokens '" << lte->configTag << "' with '" << cur << "'");
if (strncmp(lte->configTag, cur, strlen(lte->configTag)) == 0) {
type = lte->tokenType;
}
Format::Token::Token() : type(LFT_NONE),
- label(NULL),
+ label(nullptr),
widthMin(-1),
widthMax(-1),
quote(LOG_QUOTE_NONE),
space(false),
zero(false),
divisor(1),
- next(NULL)
+ next(nullptr)
{
- data.string = NULL;
- data.header.header = NULL;
- data.header.element = NULL;
+ data.string = nullptr;
+ data.header.header = nullptr;
+ data.header.element = nullptr;
data.header.separator = ',';
data.headerId = ProxyProtocol::Two::htUnknown;
}
Format::Token::~Token()
{
- label = NULL; // drop reference to global static.
+ label = nullptr; // drop reference to global static.
safe_free(data.string);
while (next) {
Token *tokens = next;
next = next->next;
- tokens->next = NULL;
+ tokens->next = nullptr;
delete tokens;
}
}
class TokenTableEntry
{
public:
- TokenTableEntry() : configTag(NULL), tokenType(LFT_NONE), options(0) {}
+ TokenTableEntry() : configTag(nullptr), tokenType(LFT_NONE), options(0) {}
TokenTableEntry(const char *aTag, const ByteCode_t &aType) : configTag(aTag), tokenType(aType), options(0) {}
// nothing to destruct configTag is pointer to global const string
~TokenTableEntry() {}
static void fqdncacheAddEntry(fqdncache_entry * f);
/// \ingroup FQDNCacheInternal
-static hash_table *fqdn_table = NULL;
+static hash_table *fqdn_table = nullptr;
/// \ingroup FQDNCacheInternal
static long fqdncache_low = 180;
{
hash_link *e;
static fqdncache_entry *f;
- f = NULL;
+ f = nullptr;
if (fqdn_table) {
- if ((e = (hash_link *)hash_lookup(fqdn_table, name)) != NULL)
+ if ((e = (hash_link *)hash_lookup(fqdn_table, name)) != nullptr)
f = (fqdncache_entry *) e;
}
fqdncache_purgelru(void *)
{
dlink_node *m;
- dlink_node *prev = NULL;
+ dlink_node *prev = nullptr;
fqdncache_entry *f;
int removed = 0;
- eventAdd("fqdncache_purgelru", fqdncache_purgelru, NULL, 10.0, 1);
+ eventAdd("fqdncache_purgelru", fqdncache_purgelru, nullptr, 10.0, 1);
for (m = lru_list.tail; m; m = prev) {
if (fqdncacheCount() < fqdncache_low)
purge_entries_fromhosts(void)
{
dlink_node *m = lru_list.head;
- fqdncache_entry *i = NULL;
+ fqdncache_entry *i = nullptr;
fqdncache_entry *t;
while (m) {
- if (i != NULL) { /* need to delay deletion */
+ if (i != nullptr) { /* need to delay deletion */
fqdncacheRelease(i); /* we just override locks */
- i = NULL;
+ i = nullptr;
}
t = (fqdncache_entry *)m->data;
m = m->next;
}
- if (i != NULL)
+ if (i != nullptr)
fqdncacheRelease(i);
}
{
hash_link *e = (hash_link *)hash_lookup(fqdn_table, f->hash.key);
- if (NULL != e) {
+ if (nullptr != e) {
/* avoid collision */
fqdncache_entry *q = (fqdncache_entry *) e;
fqdncacheRelease(q);
callback = f->handler;
- f->handler = NULL;
+ f->handler = nullptr;
if (cbdataReferenceValidDone(f->handlerData, &cbdata)) {
const Dns::LookupDetails details(f->error_message, wait);
- callback(f->name_count ? f->names[0] : NULL, details, cbdata);
+ callback(f->name_count ? f->names[0] : nullptr, details, cbdata);
}
fqdncacheUnlockEntry(f);
void
fqdncache_nbgethostbyaddr(const Ip::Address &addr, FQDNH * handler, void *handlerData)
{
- fqdncache_entry *f = NULL;
+ fqdncache_entry *f = nullptr;
char name[MAX_IPSTRLEN];
generic_cbdata *c;
addr.toStr(name,MAX_IPSTRLEN);
debugs(35, 4, "fqdncache_nbgethostbyaddr: Invalid name!");
const Dns::LookupDetails details("Invalid hostname", -1); // error, no lookup
if (handler)
- handler(NULL, details, handlerData);
+ handler(nullptr, details, handlerData);
return;
}
f = fqdncache_get(name);
- if (NULL == f) {
+ if (nullptr == f) {
/* miss */
(void) 0;
} else if (fqdncacheExpiredEntry(f)) {
/* hit, but expired -- bummer */
fqdncacheRelease(f);
- f = NULL;
+ f = nullptr;
} else {
/* hit */
debugs(35, 4, "fqdncache_nbgethostbyaddr: HIT for '" << name << "'");
fqdncache_gethostbyaddr(const Ip::Address &addr, int flags)
{
char name[MAX_IPSTRLEN];
- fqdncache_entry *f = NULL;
+ fqdncache_entry *f = nullptr;
if (addr.isAnyAddr() || addr.isNoAddr()) {
debugs(35, 7, "nothing to lookup: " << addr);
- return NULL;
+ return nullptr;
}
addr.toStr(name,MAX_IPSTRLEN);
++ FqdncacheStats.requests;
f = fqdncache_get(name);
- if (NULL == f) {
+ if (nullptr == f) {
(void) 0;
} else if (fqdncacheExpiredEntry(f)) {
fqdncacheRelease(f);
- f = NULL;
+ f = nullptr;
} else if (f->flags.negcached) {
debugs(35, 5, "negative HIT: " << addr);
++ FqdncacheStats.negative_hits;
// ignore f->error_message: the caller just checks FQDN cache presence
- return NULL;
+ return nullptr;
} else {
debugs(35, 5, "HIT: " << addr);
++ FqdncacheStats.hits;
++ FqdncacheStats.misses;
if (flags & FQDN_LOOKUP_IF_MISS) {
- fqdncache_nbgethostbyaddr(addr, NULL, NULL);
+ fqdncache_nbgethostbyaddr(addr, nullptr, nullptr);
}
- return NULL;
+ return nullptr;
}
/**
void
fqdnStats(StoreEntry * sentry)
{
- fqdncache_entry *f = NULL;
+ fqdncache_entry *f = nullptr;
int k;
int ttl;
- if (fqdn_table == NULL)
+ if (fqdn_table == nullptr)
return;
storeAppendPrintf(sentry, "FQDN Cache Statistics:\n");
{
hashFreeItems(fqdn_table, fqdncacheFreeEntry);
hashFreeMemory(fqdn_table);
- fqdn_table = NULL;
+ fqdn_table = nullptr;
}
/**
}
fce->name_count = j;
- fce->names[j] = NULL; /* it's safe */
+ fce->names[j] = nullptr; /* it's safe */
fce->flags.fromhosts = true;
fqdncacheAddEntry(fce);
fqdncacheLockEntry(fce);
variable_list *
snmp_netFqdnFn(variable_list * Var, snint * ErrP)
{
- variable_list *Answer = NULL;
+ variable_list *Answer = nullptr;
MemBuf tmp;
debugs(49, 5, "snmp_netFqdnFn: Processing request:" << snmpDebugOid(Var->name, Var->name_length, tmp));
*ErrP = SNMP_ERR_NOERROR;
#if HAVE_FS_ROCK
#include "fs/rock/RockStoreFileSystem.h"
-static Rock::StoreFileSystem *RockInstance = NULL;
+static Rock::StoreFileSystem *RockInstance = nullptr;
#endif
void Fs::Init()
*/
/* Unused variable: */
-Fs::Ufs::StoreFSufs<Fs::Ufs::UFSSwapDir> *DiskdInstance_foo = NULL;
+Fs::Ufs::StoreFSufs<Fs::Ufs::UFSSwapDir> *DiskdInstance_foo = nullptr;
StoreIOState::STIOCB *cbIo,
void *data) :
StoreIOState(cbFile, cbIo, data),
- readableAnchor_(NULL),
- writeableAnchor_(NULL),
+ readableAnchor_(nullptr),
+ writeableAnchor_(nullptr),
splicingPoint(-1),
staleSplicingPointNext(-1),
dir(aDir),
if (callback_data)
cbdataReferenceDone(callback_data);
- theFile = NULL;
+ theFile = nullptr;
e->unlock("rock I/O");
}
Rock::IoState::file(const RefCount<DiskFile> &aFile)
{
assert(!theFile);
- assert(aFile != NULL);
+ assert(aFile != nullptr);
theFile = aFile;
}
{
debugs(79, 7, swap_filen << " reads from " << coreOff);
- assert(theFile != NULL);
+ assert(theFile != nullptr);
assert(coreOff >= 0);
// if we are dealing with the first read or
sidCurrent = currentReadableSlice().next;
}
- assert(read.callback == NULL);
- assert(read.callback_data == NULL);
+ assert(read.callback == nullptr);
+ assert(read.callback_data == nullptr);
read.callback = cb;
read.callback_data = cbdataReference(data);
staleSplicingPointNext = currentReadableSlice().next;
StoreIOState::STRCB *callb = read.callback;
assert(callb);
- read.callback = NULL;
+ read.callback = nullptr;
void *cbdata;
if (cbdataReferenceValidDone(read.callback_data, &cbdata))
callb(cbdata, buf, rlen, this);
// buffer incoming data in slot buffer and write overflowing or final slots
// quit when no data left or we stopped writing on reentrant error
- while (size > 0 && theFile != NULL) {
+ while (size > 0 && theFile != nullptr) {
const size_t processed = writeToBuffer(buf, size);
buf += processed;
size -= processed;
void
Rock::IoState::writeToDisk()
{
- assert(theFile != NULL);
+ assert(theFile != nullptr);
assert(theBuf.size >= sizeof(DbCellHeader));
assert((sidFirst < 0) == (sidCurrent < 0));
{
public:
StoreIOStateCb(StoreIOState::STIOCB *cb, void *data, int err, const Rock::IoState::Pointer &anSio):
- callback(NULL),
- callback_data(NULL),
+ callback(nullptr),
+ callback_data(nullptr),
errflag(err),
sio(anSio) {
}
StoreIOStateCb(const StoreIOStateCb &cb):
- callback(NULL),
- callback_data(NULL),
+ callback(nullptr),
+ callback_data(nullptr),
errflag(cb.errflag),
sio(cb.sio) {
Rock::IoState::callBack(int errflag)
{
debugs(79,3, "errflag=" << errflag);
- theFile = NULL;
+ theFile = nullptr;
AsyncCall::Pointer call = asyncCall(79,3, "SomeIoStateCloseCb",
StoreIOStateCb(callback, callback_data, errflag, this));
ScheduleCallHere(call);
- callback = NULL;
+ callback = nullptr;
cbdataReferenceDone(callback_data);
}
virtual void close(int how);
/// whether we are still waiting for the I/O results (i.e., not closed)
- bool stillWaiting() const { return theFile != NULL; }
+ bool stillWaiting() const { return theFile != nullptr; }
/// forwards read data (or an error) to the reader that initiated this I/O
void handleReadCompletion(Rock::ReadRequest &request, const int rlen, const int errFlag);
const int64_t Rock::SwapDir::HeaderSize = 16*1024;
Rock::SwapDir::SwapDir(): ::SwapDir("rock"),
- slotSize(HeaderSize), filePath(NULL), map(NULL), io(NULL),
- waitingForPage(NULL)
+ slotSize(HeaderSize), filePath(nullptr), map(nullptr), io(nullptr),
+ waitingForPage(nullptr)
{
}
Rock::SwapDir::get(const cache_key *key)
{
if (!map || !theFile || !theFile->canRead())
- return NULL;
+ return nullptr;
sfileno filen;
const Ipc::StoreMapAnchor *const slot = map->openForReading(key, filen);
if (!slot)
- return NULL;
+ return nullptr;
// create a brand new store entry and initialize it with stored basics
StoreEntry *e = new StoreEntry();
// but it is difficult to know whether THIS worker is reading or writing e,
// especially since we may switch from writing to reading. This code relies
// on Rock::IoState::writeableAnchor_ being set when we locked for writing.
- if (e.mem_obj && e.mem_obj->swapout.sio != NULL &&
+ if (e.mem_obj && e.mem_obj->swapout.sio != nullptr &&
dynamic_cast<IoState&>(*e.mem_obj->swapout.sio).writeableAnchor_) {
map->abortWriting(e.swap_filen);
e.detachFromDisk();
- dynamic_cast<IoState&>(*e.mem_obj->swapout.sio).writeableAnchor_ = NULL;
+ dynamic_cast<IoState&>(*e.mem_obj->swapout.sio).writeableAnchor_ = nullptr;
Store::Root().stopSharing(e); // broadcasts after the change
} else {
map->closeForReading(e.swap_filen);
}
// TODO: handle time units and detect parsing errors better
- const int64_t parsedValue = strtoll(value, NULL, 10);
+ const int64_t parsedValue = strtoll(value, nullptr, 10);
if (parsedValue < 0) {
debugs(3, DBG_CRITICAL, "FATAL: cache_dir " << path << ' ' << option << " must not be negative but is: " << parsedValue);
self_destruct();
}
// TODO: handle time units and detect parsing errors better
- const int64_t parsedValue = strtoll(value, NULL, 10);
+ const int64_t parsedValue = strtoll(value, nullptr, 10);
if (parsedValue < 0) {
debugs(3, DBG_CRITICAL, "FATAL: cache_dir " << path << ' ' << option << " must not be negative but is: " << parsedValue);
self_destruct();
}
// TODO: handle size units and detect parsing errors better
- const uint64_t newSize = strtoll(value, NULL, 10);
+ const uint64_t newSize = strtoll(value, nullptr, 10);
if (newSize <= 0) {
debugs(3, DBG_CRITICAL, "FATAL: cache_dir " << path << ' ' << option << " must be positive; got: " << newSize);
self_destruct();
{
if (!theFile || theFile->error()) {
debugs(47,4, theFile);
- return NULL;
+ return nullptr;
}
sfileno filen;
map->openForWriting(reinterpret_cast<const cache_key *>(e.key), filen);
if (!slot) {
debugs(47, 5, "map->add failed");
- return NULL;
+ return nullptr;
}
assert(filen >= 0);
return slotId;
}
assert(waitingForPage == &pageId);
- waitingForPage = NULL;
+ waitingForPage = nullptr;
// This may happen when the number of available db slots is close to the
// number of concurrent requests reading or writing those slots, which may
pageId.number = sliceId+1;
if (waitingForPage) {
*waitingForPage = pageId;
- waitingForPage = NULL;
+ waitingForPage = nullptr;
} else {
freeSlots->push(pageId);
}
{
if (!theFile || theFile->error()) {
debugs(47,4, theFile);
- return NULL;
+ return nullptr;
}
if (!e.hasDisk()) {
debugs(47,4, e);
- return NULL;
+ return nullptr;
}
// Do not start I/O transaction if there are less than 10% free pages left.
if (needsDiskStrand() &&
Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage)) {
debugs(47, 5, "too few shared pages for IPC I/O left");
- return NULL;
+ return nullptr;
}
// The are two ways an entry can get swap_filen: our get() locked it for
// locked entry is safe, but no support for reading the entry we swap out.
const Ipc::StoreMapAnchor *slot = map->peekAtReader(e.swap_filen);
if (!slot)
- return NULL; // we were writing after all
+ return nullptr; // we were writing after all
Rock::SwapDir::Pointer self(this);
IoState *sio = new IoState(self, &e, cbFile, cbIo, data);
void
Rock::SwapDir::closeCompleted()
{
- theFile = NULL;
+ theFile = nullptr;
}
void
Rock::WriteRequest *request = dynamic_cast<Rock::WriteRequest*>(r.getRaw());
assert(request);
- assert(request->sio != NULL);
+ assert(request->sio != nullptr);
IoState &sio = *request->sio;
// quit if somebody called IoState::close() while we were waiting
map->switchWritingToReading(sio.swap_filen);
// sio.e keeps the (now read) lock on the anchor
}
- sio.writeableAnchor_ = NULL;
+ sio.writeableAnchor_ = nullptr;
sio.finishedWriting(DISK_OK);
}
}
bool
Rock::SwapDir::full() const
{
- return freeSlots != NULL && !freeSlots->size();
+ return freeSlots != nullptr && !freeSlots->size();
}
// storeSwapOutFileClosed calls this nethod on DISK_NO_SPACE_LEFT,
Fs::Ufs::RebuildState::RebuildState(RefCount<UFSSwapDir> aSwapDir) :
sd(aSwapDir),
n_read(0),
- LogParser(NULL),
+ LogParser(nullptr),
curlvl1(0),
curlvl2(0),
in_dir(0),
done(0),
fn(0),
- entry(NULL),
- td(NULL),
+ entry(nullptr),
+ td(nullptr),
fromLog(true),
_done(false),
- cbdata(NULL)
+ cbdata(nullptr)
{
/*
if (fp && !zeroLengthLog)
LogParser = Fs::Ufs::UFSSwapLogParser::GetUFSSwapLogParser(fp);
- if (LogParser == NULL ) {
+ if (LogParser == nullptr ) {
fromLog = false;
- if (fp != NULL)
+ if (fp != nullptr)
fclose(fp);
} else {
debugs(47, DBG_IMPORTANT, "Done reading " << sd->path << " swaplog (" << n_read << " entries)");
LogParser->Close();
delete LogParser;
- LogParser = NULL;
+ LogParser = nullptr;
_done = true;
return;
}
entry = readdir(td); /* skip . and .. */
entry = readdir(td);
- if (entry == NULL && errno == ENOENT)
+ if (entry == nullptr && errno == ENOENT)
debugs(47, DBG_IMPORTANT, "WARNING: directory does not exist!");
debugs(47, 3, "Directory " << fullpath);
}
}
- if (td != NULL && (entry = readdir(td)) != NULL) {
+ if (td != nullptr && (entry = readdir(td)) != nullptr) {
++in_dir;
if (sscanf(entry->d_name, "%x", &fn) != 1) {
continue;
}
- if (td != NULL)
+ if (td != nullptr)
closedir(td);
- td = NULL;
+ td = nullptr;
in_dir = 0;
#include "fs/ufs/UFSSwapDir.h"
/* Unused variable: */
-Fs::Ufs::StoreFSufs<Fs::Ufs::UFSSwapDir> *UfsInstance_foo = NULL;
+Fs::Ufs::StoreFSufs<Fs::Ufs::UFSSwapDir> *UfsInstance_foo = nullptr;
};
template <class C>
-StoreFSufs<C>::StoreFSufs(char const *defaultModuleName, char const *aLabel) : IO(NULL), moduleName(defaultModuleName), label(aLabel)
+StoreFSufs<C>::StoreFSufs(char const *defaultModuleName, char const *aLabel) : IO(nullptr), moduleName(defaultModuleName), label(aLabel)
{
FsAdd(*this);
}
Fs::Ufs::StoreSearchUFS::StoreSearchUFS(RefCount<UFSSwapDir> aSwapDir) :
sd(aSwapDir),
walker(sd->repl->WalkInit(sd->repl)),
- cbdata(NULL),
- current(NULL),
+ cbdata(nullptr),
+ current(nullptr),
_done(false)
{}
Fs::Ufs::StoreSearchUFS::~StoreSearchUFS()
{
walker->Done(walker);
- walker = NULL;
+ walker = nullptr;
}
void
if (walker)
current = const_cast<StoreEntry *>(walker->Next(walker));
- if (current == NULL)
+ if (current == nullptr)
_done = true;
- return current != NULL;
+ return current != nullptr;
}
bool
void
Fs::Ufs::UFSStoreState::read_(char *buf, size_t size, off_t aOffset, STRCB * aCallback, void *aCallbackData)
{
- assert(read.callback == NULL);
- assert(read.callback_data == NULL);
+ assert(read.callback == nullptr);
+ assert(read.callback_data == nullptr);
assert(!reading);
assert(!closing);
assert (aCallback);
assert(callback_);
- read.callback = NULL;
+ read.callback = nullptr;
void *cbdata;
callback_(cbdata, read_buf, len, this);
}
- if (flags.try_closing || (theFile != NULL && theFile->error()) )
+ if (flags.try_closing || (theFile != nullptr && theFile->error()) )
tryClosing();
}
*/
freePending();
STIOCB *theCallback = callback;
- callback = NULL;
+ callback = nullptr;
void *cbdata;
* us that the file has been closed. This must be the last line,
* as theFile may be the only object holding us in memory.
*/
- theFile = NULL; // refcounted
+ theFile = nullptr; // refcounted
}
/* ============= THE REAL UFS CODE ================ */
Fs::Ufs::UFSStoreState::UFSStoreState(SwapDir * SD, StoreEntry * anEntry, STIOCB * cbIo, void *data) :
- StoreIOState(NULL, cbIo, data),
+ StoreIOState(nullptr, cbIo, data),
opening(false),
creating(false),
closing(false),
reading(false),
writing(false),
- read_buf(NULL)
+ read_buf(nullptr)
{
// StoreIOState inherited members
swap_filen = anEntry->swap_filen;
assert (state);
- char *path = ((UFSSwapDir *)SD)->fullPath(e->swap_filen, NULL);
+ char *path = ((UFSSwapDir *)SD)->fullPath(e->swap_filen, nullptr);
DiskFile::Pointer myFile = newFile (path);
- if (myFile.getRaw() == NULL)
- return NULL;
+ if (myFile.getRaw() == nullptr)
+ return nullptr;
state->theFile = myFile;
myFile->open (sio->mode, 0644, state);
if (myFile->error())
- return NULL;
+ return nullptr;
return sio;
}
assert (state);
- char *path = ((UFSSwapDir *)SD)->fullPath(filn, NULL);
+ char *path = ((UFSSwapDir *)SD)->fullPath(filn, nullptr);
DiskFile::Pointer myFile = newFile (path);
- if (myFile.getRaw() == NULL) {
+ if (myFile.getRaw() == nullptr) {
((UFSSwapDir *)SD)->mapBitReset (filn);
- return NULL;
+ return nullptr;
}
state->theFile = myFile;
if (myFile->error()) {
((UFSSwapDir *)SD)->mapBitReset (filn);
- return NULL;
+ return nullptr;
}
/* now insert into the replacement policy */
#endif
int Fs::Ufs::UFSSwapDir::NumberOfUFSDirs = 0;
-int *Fs::Ufs::UFSSwapDir::UFSDirToGlobalDirMapping = NULL;
+int *Fs::Ufs::UFSSwapDir::UFSDirToGlobalDirMapping = nullptr;
class UFSCleanLog : public SwapDir::CleanLog
{
const StoreEntry *
UFSCleanLog::nextEntry()
{
- const StoreEntry *entry = NULL;
+ const StoreEntry *entry = nullptr;
if (walker)
entry = walker->Next(walker);
file_close(fd);
fd = -1;
unlink(newLog.c_str());
- sd->cleanLog = NULL;
+ sd->cleanLog = nullptr;
delete this;
return;
}
{
ConfigOption *parentResult = SwapDir::getOptionTree();
- if (currentIOOptions == NULL)
+ if (currentIOOptions == nullptr)
currentIOOptions = new ConfigOptionVector();
currentIOOptions->options.push_back(parentResult);
ConfigOption* result = currentIOOptions;
- currentIOOptions = NULL;
+ currentIOOptions = nullptr;
return result;
}
{
debugs(47, 3, "Initialising UFS SwapDir engine.");
/* Parsing must be finished by now - force to NULL, don't delete */
- currentIOOptions = NULL;
+ currentIOOptions = nullptr;
static int started_clean_event = 0;
static const char *errmsg =
"\tFailed to verify one of the swap directories, Check cache.log\n"
rebuild();
if (!started_clean_event) {
- eventAdd("UFS storeDirClean", CleanEvent, NULL, 15.0, 1);
+ eventAdd("UFS storeDirClean", CleanEvent, nullptr, 15.0, 1);
started_clean_event = 1;
}
Fs::Ufs::UFSSwapDir::UFSSwapDir(char const *aType, const char *anIOType) :
SwapDir(aType),
- IO(NULL),
- fsdata(NULL),
+ IO(nullptr),
+ fsdata(nullptr),
map(new FileMap()),
suggest(0),
l1(16),
Fs::Ufs::UFSSwapDir::dumpEntry(StoreEntry &e) const
{
debugs(47, DBG_CRITICAL, "FILENO "<< std::setfill('0') << std::hex << std::uppercase << std::setw(8) << e.swap_filen);
- debugs(47, DBG_CRITICAL, "PATH " << fullPath(e.swap_filen, NULL) );
+ debugs(47, DBG_CRITICAL, "PATH " << fullPath(e.swap_filen, nullptr) );
e.dump(0);
}
struct stat sb;
- if (::stat(fullPath(e.swap_filen, NULL), &sb) < 0) {
+ if (::stat(fullPath(e.swap_filen, nullptr), &sb) < 0) {
debugs(47, DBG_CRITICAL, "WARNING: Missing swap file");
dumpEntry(e);
return true;
uint16_t newFlags,
int)
{
- StoreEntry *e = NULL;
+ StoreEntry *e = nullptr;
debugs(47, 5, storeKeyText(key) <<
", fileno="<< std::setfill('0') << std::hex << std::uppercase << std::setw(8) << file_number);
/* if you call this you'd better be sure file_number is not
if (::stat(swaplog_path.c_str(), &log_sb) < 0) {
debugs(47, DBG_IMPORTANT, "Cache Dir #" << index << ": No log file");
- return NULL;
+ return nullptr;
}
*zero_flag = log_sb.st_size == 0 ? 1 : 0;
memset(buf.space(), 0, header.gapSize());
buf.appended(header.gapSize());
file_write(swaplog_fd, -1, buf.content(), buf.contentSize(),
- NULL, NULL, buf.freeFunc());
+ nullptr, nullptr, buf.freeFunc());
}
/* open a read-only stream of the old log */
struct stat sb;
#endif
- cleanLog = NULL;
+ cleanLog = nullptr;
state->cur = logFile();
state->newLog = logFile(".clean");
state->fd = file_open(state->newLog.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY);
UFSCleanLog *state = (UFSCleanLog *)cleanLog;
int fd;
- if (NULL == state)
+ if (nullptr == state)
return;
if (state->fd < 0)
delete state;
- cleanLog = NULL;
+ cleanLog = nullptr;
}
/// safely cleans a few unused files if possible
if (!NumberOfUFSDirs)
return 0; // probably in the middle of reconfiguration
- if (NULL == UFSDirToGlobalDirMapping) {
+ if (nullptr == UFSDirToGlobalDirMapping) {
SwapDir *sd;
/*
* Initialize the little array that translates UFS cache_dir
Fs::Ufs::UFSSwapDir::CleanEvent(void *)
{
const int n = HandleCleanEvent();
- eventAdd("storeDirClean", CleanEvent, NULL,
+ eventAdd("storeDirClean", CleanEvent, nullptr,
15.0 * exp(-0.25 * n), 1);
}
Fs::Ufs::UFSSwapDir::IsUFSDir(SwapDir * sd)
{
UFSSwapDir *mySD = dynamic_cast<UFSSwapDir *>(sd);
- return (mySD != 0) ;
+ return (mySD != nullptr) ;
}
/*
{
debugs(79, 3, "unlinking fileno " << std::setfill('0') <<
std::hex << std::uppercase << std::setw(8) << f << " '" <<
- fullPath(f,NULL) << "'");
+ fullPath(f,nullptr) << "'");
/* commonUfsDirMapBitReset(this, f); */
- IO->unlinkFile(fullPath(f,NULL));
+ IO->unlinkFile(fullPath(f,nullptr));
}
bool
-1,
s,
sizeof(StoreSwapLogData),
- NULL,
- NULL,
+ nullptr,
+ nullptr,
FreeObject);
}
int
Fs::Ufs::UFSSwapDir::DirClean(int swap_index)
{
- DIR *dir_pointer = NULL;
+ DIR *dir_pointer = nullptr;
int files[20];
int swapfileno;
int fn; /* same as swapfileno, but with dirn bits set */
}
dirent_t *de;
- while ((de = readdir(dir_pointer)) != NULL && k < 20) {
+ while ((de = readdir(dir_pointer)) != nullptr && k < 20) {
if (sscanf(de->d_name, "%X", &swapfileno) != 1)
continue;
assert(fp);
if (fread(&header, sizeof(StoreSwapLogHeader), 1, fp) != 1)
- return NULL;
+ return nullptr;
if (header.op != SWAP_LOG_VERSION) {
debugs(47, DBG_IMPORTANT, "Old swap file detected...");
if (header.version == 1) {
if (fseek(fp, header.record_size, SEEK_SET) != 0)
- return NULL;
+ return nullptr;
debugs(47, DBG_IMPORTANT, "ERROR: Rejecting swap file v1 to avoid cache " <<
"index corruption. Forcing a full cache index rebuild. " <<
"See Squid bug #3441.");
- return NULL;
+ return nullptr;
}
if (header.version >= 2) {
if (!header.sane()) {
debugs(47, DBG_IMPORTANT, "ERROR: Corrupted v" << header.version <<
" swap file header.");
- return NULL;
+ return nullptr;
}
if (fseek(fp, header.record_size, SEEK_SET) != 0)
- return NULL;
+ return nullptr;
if (header.version == 2)
return new UFSSwapLogParser_v2(fp);
// TODO: v3: write to disk in network-order bytes for the larger fields?
debugs(47, DBG_IMPORTANT, "ERROR: Unknown swap file version: " << header.version);
- return NULL;
+ return nullptr;
}
int
void Close() {
if (log) {
fclose(log);
- log = NULL;
+ log = nullptr;
}
}
};
assert(F->flags.open);
if ((read_callback = F->read_handler)) {
- F->read_handler = NULL;
+ F->read_handler = nullptr;
read_callback(-1, F->read_data);
}
* Assert there is no write callback. Otherwise we might be
* leaking write state data by closing the descriptor
*/
- assert(F->write_handler == NULL);
+ assert(F->write_handler == nullptr);
close(fd);
* XXX This currently ignores any seeks (file_offset)
*/
- if (fdd->write_q != NULL && fdd->write_q->next != NULL) {
+ if (fdd->write_q != nullptr && fdd->write_q->next != nullptr) {
int len = 0;
- for (dwrite_q *q = fdd->write_q; q != NULL; q = q->next)
+ for (dwrite_q *q = fdd->write_q; q != nullptr; q = q->next)
len += q->len - q->buf_offset;
dwrite_q *wq = (dwrite_q *)memAllocate(MEM_DWRITE_Q);
wq->buf_offset = 0;
- wq->next = NULL;
+ wq->next = nullptr;
wq->free_func = cxx_xfree;
- while (fdd->write_q != NULL) {
+ while (fdd->write_q != nullptr) {
dwrite_q *q = fdd->write_q;
len = q->len - q->buf_offset;
int status = DISK_OK;
bool do_close;
- if (NULL == q)
+ if (nullptr == q)
return;
debugs(6, 3, "diskHandleWrite: FD " << fd);
F->flags.write_daemon = false;
- assert(fdd->write_q != NULL);
+ assert(fdd->write_q != nullptr);
assert(fdd->write_q->len > fdd->write_q->buf_offset);
* a fatal message.
*/
- if (fdd->wrt_handle == NULL)
+ if (fdd->wrt_handle == nullptr)
fatal("Write failure -- check your disk space and cache.log");
/*
if (q) {
memFree(q, MEM_DWRITE_Q);
- q = NULL;
+ q = nullptr;
}
} while ((q = fdd->write_q));
}
len = 0;
}
- if (q != NULL) {
+ if (q != nullptr) {
/* q might become NULL from write failure above */
q->buf_offset += len;
if (q) {
memFree(q, MEM_DWRITE_Q);
- q = NULL;
+ q = nullptr;
}
}
}
- if (fdd->write_q == NULL) {
+ if (fdd->write_q == nullptr) {
/* no more data */
- fdd->write_q_tail = NULL;
+ fdd->write_q_tail = nullptr;
} else {
/* another block is queued */
diskCombineWrites(fdd);
- Comm::SetSelect(fd, COMM_SELECT_WRITE, diskHandleWrite, NULL, 0);
+ Comm::SetSelect(fd, COMM_SELECT_WRITE, diskHandleWrite, nullptr, 0);
F->flags.write_daemon = true;
}
if (fdd->wrt_handle) {
DWCB *callback = fdd->wrt_handle;
void *cbdata;
- fdd->wrt_handle = NULL;
+ fdd->wrt_handle = nullptr;
if (cbdataReferenceValidDone(fdd->wrt_handle_data, &cbdata)) {
callback(fd, status, len, cbdata);
void *handle_data,
FREE * free_func)
{
- dwrite_q *wq = NULL;
+ dwrite_q *wq = nullptr;
fde *F = &fd_table[fd];
assert(fd >= 0);
assert(F->flags.open);
wq->buf = (char *)ptr_to_buf;
wq->len = len;
wq->buf_offset = 0;
- wq->next = NULL;
+ wq->next = nullptr;
wq->free_func = free_func;
if (!F->disk.wrt_handle_data) {
}
/* add to queue */
- if (F->disk.write_q == NULL) {
+ if (F->disk.write_q == nullptr) {
/* empty queue */
F->disk.write_q = F->disk.write_q_tail = wq;
} else {
}
if (!F->flags.write_daemon) {
- diskHandleWrite(fd, NULL);
+ diskHandleWrite(fd, nullptr);
}
}
overflowed(false),
cso_recno(0),
len(0),
- buf(NULL),
+ buf(nullptr),
fwd(aFwd)
{
*request = 0;
gopherMimeCreate(GopherStateData * gopherState)
{
StoreEntry *entry = gopherState->entry;
- const char *mime_type = NULL;
- const char *mime_enc = NULL;
+ const char *mime_type = nullptr;
+ const char *mime_enc = nullptr;
switch (gopherState->type_id) {
/* parse to see type */
gopher_request_parse(req,
&type_id,
- NULL);
+ nullptr);
switch (type_id) {
StoreEntry *e = gopherState->entry;
if (!gopherState->HTML_header_added) {
- gopherHTMLHeader(e, "Server Return Nothing", NULL);
+ gopherHTMLHeader(e, "Server Return Nothing", nullptr);
storeAppendPrintf(e, "<P>The Gopher query resulted in a blank response</P>");
} else if (gopherState->HTML_pre) {
storeAppendPrintf(e, "</PRE>\n");
gopherToHTML(GopherStateData * gopherState, char *inbuf, int len)
{
char *pos = inbuf;
- char *lpos = NULL;
- char *tline = NULL;
+ char *lpos = nullptr;
+ char *tline = nullptr;
LOCAL_ARRAY(char, line, TEMP_BUF_SIZE);
- char *name = NULL;
- char *selector = NULL;
- char *host = NULL;
- char *port = NULL;
- char *escaped_selector = NULL;
+ char *name = nullptr;
+ char *selector = nullptr;
+ char *host = nullptr;
+ char *port = nullptr;
+ char *escaped_selector = nullptr;
char gtype;
- StoreEntry *entry = NULL;
+ StoreEntry *entry = nullptr;
memset(line, '\0', TEMP_BUF_SIZE);
if (!gopherState->HTML_header_added) {
if (gopherState->conversion == GopherStateData::HTML_CSO_RESULT)
- gopherHTMLHeader(entry, "CSO Search Result", NULL);
+ gopherHTMLHeader(entry, "CSO Search Result", nullptr);
else
- gopherHTMLHeader(entry, "Gopher Menu", NULL);
+ gopherHTMLHeader(entry, "Gopher Menu", nullptr);
outbuf.append ("<PRE>");
char *s_code, *s_recno, *result;
s_code = strtok(line + 1, ":\n");
- s_recno = strtok(NULL, ":\n");
- result = strtok(NULL, "\n");
+ s_recno = strtok(nullptr, ":\n");
+ result = strtok(nullptr, "\n");
if (!result)
break;
char *s_code, *result;
s_code = strtok(line, ":");
- result = strtok(NULL, "\n");
+ result = strtok(nullptr, "\n");
if (!result)
break;
comm_add_close_handler(fwd->serverConnection()->fd, gopherStateFree, gopherState);
if (((gopherState->type_id == GOPHER_INDEX) || (gopherState->type_id == GOPHER_CSO))
- && (strchr(gopherState->request, '?') == NULL)) {
+ && (strchr(gopherState->request, '?') == nullptr)) {
/* Index URL without query word */
/* We have to generate search page back to client. No need for connection */
gopherMimeCreate(gopherState);
}
}
- gopherToHTML(gopherState, (char *) NULL, 0);
+ gopherToHTML(gopherState, (char *) nullptr, 0);
fwd->markStoredReplyAsWhole("gopher instant internal request satisfaction");
fwd->complete();
return;
{
if (rbuf) {
memFreeBuf(rbuf_sz, rbuf);
- rbuf = NULL;
+ rbuf = nullptr;
}
}
if (writebuf) {
writebuf->clean();
delete writebuf;
- writebuf = NULL;
+ writebuf = nullptr;
}
if (Comm::IsConnOpen(writePipe))
void * hIpc;
wordlist *w;
- if (hlp->cmdline == NULL)
+ if (hlp->cmdline == nullptr)
return;
progname = hlp->cmdline->key;
++nargs;
}
- args[nargs] = NULL;
+ args[nargs] = nullptr;
++nargs;
assert(nargs <= HELPER_MAX_ARGS);
srv->wqueue = new MemBuf;
srv->roffset = 0;
srv->nextRequestId = 0;
- srv->replyXaction = NULL;
+ srv->replyXaction = nullptr;
srv->ignoreToEom = false;
srv->parent = cbdataReference(hlp);
dlinkAddTail(srv, &srv->link, &hlp->servers);
char fd_note_buf[FD_DESC_SZ];
int nargs = 0;
- if (hlp->cmdline == NULL)
+ if (hlp->cmdline == nullptr)
return;
if (hlp->childs.concurrency)
++nargs;
}
- args[nargs] = NULL;
+ args[nargs] = nullptr;
++nargs;
assert(nargs <= HELPER_MAX_ARGS);
for (dlink_node *link = servers.head; link; link = link->next) {
HelperServerBase *srv = static_cast<HelperServerBase *>(link->data);
assert(srv);
- Helper::Xaction *xaction = srv->requests.empty() ? NULL : srv->requests.front();
+ Helper::Xaction *xaction = srv->requests.empty() ? nullptr : srv->requests.front();
double tt = 0.001 * (xaction ? tvSubMsec(xaction->request.dispatch_time, current_time) : tvSubMsec(srv->dispatch_time, srv->answer_time));
p->appendf("%7u\t%7d\t%7d\t%11" PRIu64 "\t%11" PRIu64 "\t%11" PRIu64 "\t%c%c%c%c%c%c\t%7.3f\t%7d\t%s\n",
srv->index.value,
if (!srv->ignoreToEom && !srv->replyXaction) {
int i = 0;
if (hlp->childs.concurrency) {
- char *e = NULL;
+ char *e = nullptr;
i = strtol(msg, &e, 10);
// Do we need to check for e == msg? Means wrong response from helper.
// Will be dropped as "unexpected reply on channel 0"
if (eom && srv->ignoreToEom)
srv->ignoreToEom = false;
} else
- assert(skip == 0 && eom == NULL);
+ assert(skip == 0 && eom == nullptr);
}
if (needsMore) {
static void
helperStatefulHandleRead(const Comm::ConnectionPointer &conn, char *, size_t len, Comm::Flag flag, int, void *data)
{
- char *t = NULL;
+ char *t = nullptr;
helper_stateful_server *srv = (helper_stateful_server *)data;
statefulhelper *hlp = srv->parent;
assert(cbdataReferenceValid(data));
Helper::Xaction *r = srv->requests.front();
debugs(84, DBG_DATA, Raw("accumulated", srv->rbuf, srv->roffset));
- if (r == NULL) {
+ if (r == nullptr) {
/* someone spoke without being spoken to */
debugs(84, DBG_IMPORTANT, "ERROR: helperStatefulHandleRead: unexpected read from " <<
hlp->id_name << " #" << srv->index << ", " << (int)len <<
{
dlink_node *n;
helper_server *srv;
- helper_server *selected = NULL;
+ helper_server *selected = nullptr;
debugs(84, 5, "GetFirstAvailable: Running servers " << hlp->childs.n_running);
if (hlp->childs.n_running == 0)
- return NULL;
+ return nullptr;
/* Find "least" loaded helper (approx) */
- for (n = hlp->servers.head; n != NULL; n = n->next) {
+ for (n = hlp->servers.head; n != nullptr; n = n->next) {
srv = (helper_server *)n->data;
if (selected && selected->stats.pending <= srv->stats.pending)
if (!selected) {
debugs(84, 5, "GetFirstAvailable: None available.");
- return NULL;
+ return nullptr;
}
if (selected->stats.pending >= (hlp->childs.concurrency ? hlp->childs.concurrency : 1)) {
debugs(84, 3, "GetFirstAvailable: Least-loaded helper is fully loaded!");
- return NULL;
+ return nullptr;
}
debugs(84, 5, "GetFirstAvailable: returning srv-" << selected->index);
StatefulGetFirstAvailable(statefulhelper * hlp)
{
dlink_node *n;
- helper_stateful_server *srv = NULL;
+ helper_stateful_server *srv = nullptr;
helper_stateful_server *oldestReservedServer = nullptr;
debugs(84, 5, "StatefulGetFirstAvailable: Running servers " << hlp->childs.n_running);
if (hlp->childs.n_running == 0)
- return NULL;
+ return nullptr;
- for (n = hlp->servers.head; n != NULL; n = n->next) {
+ for (n = hlp->servers.head; n != nullptr; n = n->next) {
srv = (helper_stateful_server *)n->data;
if (srv->stats.pending)
srv->writebuf->clean();
delete srv->writebuf;
- srv->writebuf = NULL;
+ srv->writebuf = nullptr;
srv->flags.writing = false;
if (flag != Comm::OK) {
srv->flags.writing = true;
AsyncCall::Pointer call = commCbCall(5,5, "helperDispatchWriteDone",
CommIoCbPtrFun(helperDispatchWriteDone, srv));
- Comm::Write(srv->writePipe, srv->writebuf->content(), srv->writebuf->contentSize(), call, NULL);
+ Comm::Write(srv->writePipe, srv->writebuf->content(), srv->writebuf->contentSize(), call, nullptr);
}
}
srv->wqueue->append(r->request.buf, strlen(r->request.buf));
if (!srv->flags.writing) {
- assert(NULL == srv->writebuf);
+ assert(nullptr == srv->writebuf);
srv->writebuf = srv->wqueue;
srv->wqueue = new MemBuf;
srv->flags.writing = true;
AsyncCall::Pointer call = commCbCall(5,5, "helperDispatchWriteDone",
CommIoCbPtrFun(helperDispatchWriteDone, srv));
- Comm::Write(srv->writePipe, srv->writebuf->content(), srv->writebuf->contentSize(), call, NULL);
+ Comm::Write(srv->writePipe, srv->writebuf->content(), srv->writebuf->contentSize(), call, nullptr);
}
debugs(84, 5, "helperDispatch: Request sent to " << hlp->id_name << " #" << srv->index << ", " << strlen(r->request.buf) << " bytes");
srv->dispatch_time = current_time;
AsyncCall::Pointer call = commCbCall(5,5, "helperStatefulDispatchWriteDone",
CommIoCbPtrFun(helperStatefulDispatchWriteDone, hlp));
- Comm::Write(srv->writePipe, r->request.buf, strlen(r->request.buf), call, NULL);
+ Comm::Write(srv->writePipe, r->request.buf, strlen(r->request.buf), call, nullptr);
debugs(84, 5, "helperStatefulDispatch: Request sent to " <<
hlp->id_name << " #" << srv->index << ", " <<
(int) strlen(r->request.buf) << " bytes");
public:
/// \param name admin-visible helper category (with this process lifetime)
inline helper(const char *name) :
- cmdline(NULL),
+ cmdline(nullptr),
id_name(name),
ipc_type(0),
droppedRequests(0),
void submitRequest(Helper::Xaction *r);
/// Dump some stats about the helper state to a Packable object
- void packStatsInto(Packable *p, const char *label = NULL) const;
+ void packStatsInto(Packable *p, const char *label = nullptr) const;
/// whether the helper will be in "overloaded" state after one more request
/// already overloaded helpers return true
bool willOverload() const;
result = Helper::TT;
p+=3;
// followed by an auth token
- char *w1 = strwordtok(NULL, &p);
- if (w1 != NULL) {
+ char *w1 = strwordtok(nullptr, &p);
+ if (w1 != nullptr) {
const char *authToken = w1;
notes.add("token",authToken);
} else {
// followed by:
// an optional auth token and user field
// or, an optional username field
- char *w1 = strwordtok(NULL, &p);
- char *w2 = strwordtok(NULL, &p);
- if (w2 != NULL) {
+ char *w1 = strwordtok(nullptr, &p);
+ char *w2 = strwordtok(nullptr, &p);
+ if (w2 != nullptr) {
// Negotiate "token user"
const char *authToken = w1;
notes.add("token",authToken);
const char *user = w2;
notes.add("user",user);
- } else if (w1 != NULL) {
+ } else if (w1 != nullptr) {
// NTLM "user"
const char *user = w1;
notes.add("user",user);
// the value may be a quoted string or a token
const bool urlDecode = (*p != '"'); // check before moving p.
- char *v = strwordtok(NULL, &p);
- if (v != NULL && urlDecode && (p-v) > 2) // 1-octet %-escaped requires 3 bytes
+ char *v = strwordtok(nullptr, &p);
+ if (v != nullptr && urlDecode && (p-v) > 2) // 1-octet %-escaped requires 3 bytes
rfc1738_unescape(v);
notes.add(key, v ? v : ""); // value can be empty, but must not be NULL
public:
Request(HLPCB *c, void *d, const char *b) :
- buf(b ? xstrdup(b) : NULL),
+ buf(b ? xstrdup(b) : nullptr),
callback(c),
data(cbdataReference(d)),
- placeholder(b == NULL),
+ placeholder(b == nullptr),
Id(0),
retries(0)
{
static void htcpIncomingConnectionOpened(const Comm::ConnectionPointer &conn, int errNo);
static uint32_t msg_id_counter = 0;
-static Comm::ConnectionPointer htcpOutgoingConn = NULL;
-static Comm::ConnectionPointer htcpIncomingConn = NULL;
+static Comm::ConnectionPointer htcpOutgoingConn = nullptr;
+static Comm::ConnectionPointer htcpIncomingConn = nullptr;
#define N_QUERIED_KEYS 8192
static uint32_t queried_id[N_QUERIED_KEYS];
static cache_key queried_keys[N_QUERIED_KEYS][SQUID_MD5_DIGEST_LENGTH];
if (l > sz) {
debugs(31, 3, "htcpUnpackDetail: failed to unpack RESP_HDRS");
delete d;
- return NULL;
+ return nullptr;
}
/* Set RESP-HDRS */
if (l > sz) {
debugs(31, 3, "htcpUnpackDetail: failed to unpack ENTITY_HDRS");
delete d;
- return NULL;
+ return nullptr;
}
/* Add terminating null to RESP-HDRS */
if (l > sz) {
debugs(31, 3, "htcpUnpackDetail: failed to unpack CACHE_HDRS");
delete d;
- return NULL;
+ return nullptr;
}
/* Add terminating null to ENTITY-HDRS */
htcpHandleTstResponse(htcpDataHeader * hdr, char *buf, int sz, Ip::Address &from)
{
HtcpReplyData htcpReply;
- cache_key *key = NULL;
+ cache_key *key = nullptr;
Ip::Address *peer;
- htcpDetail *d = NULL;
+ htcpDetail *d = nullptr;
char *t;
if (queried_id[hdr->msg_id % N_QUERIED_KEYS] != hdr->msg_id) {
debugs(31, 3, "htcpHandleTstResponse: HIT");
d = htcpUnpackDetail(buf, sz);
- if (d == NULL) {
+ if (d == nullptr) {
debugs(31, 3, "htcpHandleTstResponse: bad DETAIL");
return;
}
htcpTstReply(dhdr, e, this, from); /* hit */
htcpLogHtcp(from, dhdr->opcode, LOG_UDP_HIT, uri, al);
} else {
- htcpTstReply(dhdr, NULL, NULL, from); /* cache miss */
+ htcpTstReply(dhdr, nullptr, nullptr, from); /* cache miss */
htcpLogHtcp(from, dhdr->opcode, LOG_UDP_MISS, uri, al);
}
}
htcpHandleMsg(buf, len, from);
- Comm::SetSelect(fd, COMM_SELECT_READ, htcpRecv, NULL, 0);
+ Comm::SetSelect(fd, COMM_SELECT_READ, htcpRecv, nullptr, 0);
}
/*
if (!Comm::IsConnOpen(htcpOutgoingConn))
fatal("Cannot open Outgoing HTCP Socket");
- Comm::SetSelect(htcpOutgoingConn->fd, COMM_SELECT_READ, htcpRecv, NULL, 0);
+ Comm::SetSelect(htcpOutgoingConn->fd, COMM_SELECT_READ, htcpRecv, nullptr, 0);
debugs(31, DBG_IMPORTANT, "Sending HTCP messages from " << htcpOutgoingConn->local);
}
if (!Comm::IsConnOpen(conn))
fatal("Cannot open HTCP Socket");
- Comm::SetSelect(conn->fd, COMM_SELECT_READ, htcpRecv, NULL, 0);
+ Comm::SetSelect(conn->fd, COMM_SELECT_READ, htcpRecv, nullptr, 0);
debugs(31, DBG_CRITICAL, "Accepting HTCP messages on " << conn->local);
stuff.S.method = sb.c_str();
stuff.S.uri = (char *) e->url();
stuff.S.version = vbuf;
- HttpStateData::httpBuildRequestHeader(req, e, NULL, &hdr, flags);
+ HttpStateData::httpBuildRequestHeader(req, e, nullptr, &hdr, flags);
MemBuf mb;
mb.init();
hdr.packInto(&mb);
stuff.S.uri = uri.c_str();
stuff.S.version = vbuf;
if (reason != HTCP_CLR_INVALIDATION) {
- HttpStateData::httpBuildRequestHeader(req, e, NULL, &hdr, flags);
+ HttpStateData::httpBuildRequestHeader(req, e, nullptr, &hdr, flags);
mb.init();
hdr.packInto(&mb);
hdr.clean();
stuff.S.req_hdrs = mb.buf;
} else {
- stuff.S.req_hdrs = NULL;
+ stuff.S.req_hdrs = nullptr;
}
pktlen = htcpBuildPacket(pkt, sizeof(pkt), &stuff);
if (reason != HTCP_CLR_INVALIDATION) {
* function from executing repeatedly. When we are really ready to
* exit or restart, main will comm_close the 'out' descriptor.
*/
- htcpIncomingConn = NULL;
+ htcpIncomingConn = nullptr;
/*
* Normally we only write to the outgoing HTCP socket, but
*/
assert(Comm::IsConnOpen(htcpOutgoingConn));
- Comm::SetSelect(htcpOutgoingConn->fd, COMM_SELECT_READ, NULL, NULL, 0);
+ Comm::SetSelect(htcpOutgoingConn->fd, COMM_SELECT_READ, nullptr, nullptr, 0);
}
void
{
htcpSocketShutdown();
- if (htcpOutgoingConn != NULL) {
+ if (htcpOutgoingConn != nullptr) {
debugs(12, DBG_IMPORTANT, "Stop sending HTCP from " << htcpOutgoingConn->local);
- htcpOutgoingConn = NULL;
+ htcpOutgoingConn = nullptr;
}
}
assert(logcode != LOG_TAG_NONE);
al->cache.code.update(logcode);
- accessLogLog(al, NULL);
+ accessLogLog(al, nullptr);
}
debugs(11,5, "HttpStateData " << this << " created");
serverConnection = fwd->serverConnection();
- if (fwd->serverConnection() != NULL)
+ if (fwd->serverConnection() != nullptr)
_peer = cbdataReference(fwd->serverConnection()->getPeer()); /* might be NULL */
flags.peering = _peer;
StoreEntry *pe = findPreviouslyCachedEntry(e);
- if (pe != NULL) {
+ if (pe != nullptr) {
assert(e != pe);
#if USE_HTCP
neighborsHtcpClear(e, e->mem_obj->request.getRaw(), e->mem_obj->method, HTCP_CLR_INVALIDATION);
else
pe = storeGetPublic(e->mem_obj->storeId(), Http::METHOD_HEAD);
- if (pe != NULL) {
+ if (pe != nullptr) {
assert(e != pe);
#if USE_HTCP
neighborsHtcpClear(e, e->mem_obj->request.getRaw(), HttpRequestMethod(Http::METHOD_HEAD), HTCP_CLR_INVALIDATION);
const char *v;
#if USE_HTTP_VIOLATIONS
- const RefreshPattern *R = NULL;
+ const RefreshPattern *R = nullptr;
/* This strange looking define first looks up the refresh pattern
* and then checks if the specified flag is set. The main purpose
/* Attempt to parse the first line; this will define where the protocol, status, reason-phrase and header begin */
{
- if (hp == NULL)
+ if (hp == nullptr)
hp = new Http1::ResponseParser;
bool parsedOk = hp->parse(inBuf);
}
// done with Parser, now process using the HttpReply
- hp = NULL;
+ hp = nullptr;
newrep->sources |= request->url.getScheme() == AnyP::PROTO_HTTPS ? Http::Message::srcHttps : Http::Message::srcHttp;
flags.do_next_read = false;
comm_remove_close_handler(serverConnection->fd, closeHandler);
- closeHandler = NULL;
+ closeHandler = nullptr;
Ip::Address client_addr; // XXX: Remove as unused. Why was it added?
if (request->flags.spoofClientIp)
if (Comm::IsConnOpen(serverConnection)) {
fwd->unregister(serverConnection);
comm_remove_close_handler(serverConnection->fd, closeHandler);
- closeHandler = NULL;
+ closeHandler = nullptr;
serverConnection->close();
}
}
if (request->extacl_user.size())
username = request->extacl_user.termedBuf();
#if USE_AUTH
- else if (request->auth_user_request != NULL)
+ else if (request->auth_user_request != nullptr)
username = request->auth_user_request->username();
#endif
/* Kerberos login to peer */
#if HAVE_AUTH_MODULE_NEGOTIATE && HAVE_KRB5 && HAVE_GSSAPI
if (strncmp(request->peer_login, "NEGOTIATE",strlen("NEGOTIATE")) == 0) {
- char *Token=NULL;
- char *PrincipalName=NULL,*p;
+ char *Token=nullptr;
+ char *PrincipalName=nullptr,*p;
int negotiate_flags = 0;
- if ((p=strchr(request->peer_login,':')) != NULL ) {
+ if ((p=strchr(request->peer_login,':')) != nullptr ) {
PrincipalName=++p;
}
if (request->flags.auth_no_keytab) {
LOCAL_ARRAY(char, bbuf, BBUF_SZ);
LOCAL_ARRAY(char, ntoabuf, MAX_IPSTRLEN);
const HttpHeader *hdr_in = &request->header;
- const HttpHeaderEntry *e = NULL;
+ const HttpHeaderEntry *e = nullptr;
HttpHeaderPos pos = HttpHeaderInitPos;
assert (hdr_out->owner == hoRequest);
int64_t roffLimit = request->getRangeOffsetLimit();
- if (NULL == request->range || !request->flags.cachable
+ if (nullptr == request->range || !request->flags.cachable
|| request->range->offsetLimitExceeded(roffLimit) || request->flags.connectionAuth)
result = false;
if (!Comm::IsConnOpen(serverConnection)) {
debugs(11,3, "cannot send request to closing " << serverConnection);
- assert(closeHandler != NULL);
+ assert(closeHandler != nullptr);
return false;
}
flags.do_next_read = true;
maybeReadVirginBody();
- if (request->body_pipe != NULL) {
+ if (request->body_pipe != nullptr) {
if (!startRequestBodyFlow()) // register to receive body data
return false;
typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
else if (flags.tunneling)
// tunneled non pinned bumped requests must not keepalive
flags.keepalive = !request->flags.sslBumped;
- else if (_peer == NULL)
+ else if (_peer == nullptr)
flags.keepalive = true;
else if (_peer->stats.n_keepalives_sent < 10)
flags.keepalive = true;
}
mb.init();
- request->peer_host=_peer?_peer->host:NULL;
+ request->peer_host=_peer?_peer->host:nullptr;
buildRequestPrefix(&mb);
debugs(11, 2, "HTTP Server " << serverConnection);
MemBuf raw;
- Must(requestBodySource != NULL);
+ Must(requestBodySource != nullptr);
if (!requestBodySource->getMoreData(raw))
return false; // no request body bytes to chunk yet
if (!Comm::IsConnOpen(serverConnection)) {
debugs(11, 3, "ignoring broken POST for closed " << serverConnection);
- assert(closeHandler != NULL);
+ assert(closeHandler != nullptr);
return true; // prevent caller from proceeding as if nothing happened
}
typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
requestSender = JobCallback(11,5,
Dialer, this, HttpStateData::wroteLast);
- Comm::Write(serverConnection, "\r\n", 2, requestSender, NULL);
+ Comm::Write(serverConnection, "\r\n", 2, requestSender, nullptr);
return true;
#else
return false;
typedef CommCbMemFunT<HttpStateData, CommIoCbParams> Dialer;
requestSender = JobCallback(11,5, Dialer, this, HttpStateData::wroteLast);
- Comm::Write(serverConnection, "0\r\n\r\n", 5, requestSender, NULL);
+ Comm::Write(serverConnection, "0\r\n\r\n", 5, requestSender, nullptr);
return true;
}
return;
}
- assert(requestBodySource != NULL);
+ assert(requestBodySource != nullptr);
if (requestBodySource->buf().hasContent()) {
// XXX: why does not this trigger a debug message on every request?
Http::Message::hdrCacheInit()
{
content_length = header.getInt64(Http::HdrType::CONTENT_LENGTH);
- assert(NULL == cache_control);
+ assert(nullptr == cache_control);
cache_control = header.getCc();
}
return &HttpHeaderDefinitionsTable[key];
}
}
- return 0;
+ return nullptr;
}
#line 114 "RegisteredHeadersHash.gperf"
theMethod = Http::METHOD_NONE;
theImage.clear();
- if (begin == NULL)
+ if (begin == nullptr)
return;
char const *end = begin + strcspn(begin, w_space);
void
Http::StatusLine::init()
{
- set(Http::ProtocolVersion(), Http::scNone, NULL);
+ set(Http::ProtocolVersion(), Http::scNone, nullptr);
}
void
Http::StatusLine::clean()
{
- set(Http::ProtocolVersion(), Http::scInternalServerError, NULL);
+ set(Http::ProtocolVersion(), Http::scInternalServerError, nullptr);
}
/* set values */
/// set this status-line to the given values
/// when reason is NULL the default message text for this StatusCode will be used
/// when reason is not NULL, it must not point to a dynamically allocated value
- void set(const AnyP::ProtocolVersion &newVersion, Http::StatusCode newStatus, const char *newReason = NULL);
+ void set(const AnyP::ProtocolVersion &newVersion, Http::StatusCode newStatus, const char *newReason = nullptr);
/// reset the reason phrase to its default status code-derived value
void resetReason() { reason_ = nullptr; }
Http::One::Parser::clear()
{
parsingStage_ = HTTP_PARSE_NONE;
- buf_ = NULL;
+ buf_ = nullptr;
msgProtocol_ = AnyP::ProtocolVersion();
mimeHeaderBlock_.clear();
}
Http::One::Parser::getHostHeaderField()
{
if (!headerBlockSize())
- return NULL;
+ return nullptr;
LOCAL_ARRAY(char, header, GET_HDR_SZ);
const char *name = "Host";
return header;
}
- return NULL;
+ return nullptr;
}
int
parsingStage_ = Http1::HTTP_PARSE_NONE;
buf_.clear();
theChunkSize = theLeftBodySize = 0;
- theOut = NULL;
+ theOut = nullptr;
// XXX: We do not reset customExtensionValueParser here. Based on the
// clear() API description, we must, but it makes little sense and could
// break method callers if they appear because some of them may forget to
* -d enable debugging.
* -h interface help.
*/
-char *my_program_name = NULL;
+char *my_program_name = nullptr;
static void
usage(void)
char buf[HELPER_INPUT_BUFFER];
int buflen = 0;
- setbuf(stdout, NULL);
- setbuf(stderr, NULL);
+ setbuf(stdout, nullptr);
+ setbuf(stderr, nullptr);
my_program_name = argv[0];
debug("%s " VERSION " " SQUID_BUILD_INFO " starting up...\n", my_program_name);
- while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != NULL) {
+ while (fgets(buf, HELPER_INPUT_BUFFER, stdin) != nullptr) {
char *p;
- if ((p = strchr(buf, '\n')) != NULL) {
+ if ((p = strchr(buf, '\n')) != nullptr) {
*p = '\0'; /* strip \n */
buflen = p - buf; /* length is known already */
} else
debug("Got %d bytes '%s' from Squid\n", buflen, buf);
- p = NULL;
+ p = nullptr;
int64_t channelId = strtoll(buf, &p, 10);
if (*p != ' ') {
/* send 'no-change' result back to Squid in non-concurrent format */
* Content longer than MAX_PAYLOAD will be truncated.
\param len Length of the payload in bytes if any is to be sent or 0.
*/
- virtual void SendEcho(Ip::Address &to, int opcode, const char *payload=NULL, int len=0) =0;
+ virtual void SendEcho(Ip::Address &to, int opcode, const char *payload=nullptr, int len=0) =0;
/// Handle ICMP responses.
virtual void Recv(void) =0;
int x;
LOCAL_ARRAY(char, pkt, MAX_PKT4_SZ);
- struct icmphdr *icmp = NULL;
+ struct icmphdr *icmp = nullptr;
icmpEchoData *echo;
size_t icmp_pktsize = sizeof(struct icmphdr);
- struct addrinfo *S = NULL;
+ struct addrinfo *S = nullptr;
static_assert(sizeof(*icmp) + sizeof(*echo) <= sizeof(pkt), "our custom ICMPv4 Echo payload fits the packet buffer");
debugs(42, DBG_IMPORTANT, MYNAME << "ERROR: sending to ICMP packet to " << to << ": " << xstrerr(xerrno));
}
- Log(to, ' ', NULL, 0, 0);
+ Log(to, ' ', nullptr, 0, 0);
Ip::Address::FreeAddr(S);
}
Icmp4::Recv(void)
{
int n;
- struct addrinfo *from = NULL;
+ struct addrinfo *from = nullptr;
int iphdrlen = sizeof(iphdr);
- struct iphdr *ip = NULL;
- struct icmphdr *icmp = NULL;
- static char *pkt = NULL;
+ struct iphdr *ip = nullptr;
+ struct icmphdr *icmp = nullptr;
+ static char *pkt = nullptr;
struct timeval now;
icmpEchoData *echo;
static pingerReplyData preply;
return;
}
- if (pkt == NULL)
+ if (pkt == nullptr)
pkt = (char *)xmalloc(MAX_PKT4_SZ);
Ip::Address::InitAddr(from);
#else
- gettimeofday(&now, NULL);
+ gettimeofday(&now, nullptr);
#endif
{
int x;
LOCAL_ARRAY(char, pkt, MAX_PKT6_SZ);
- struct icmp6_hdr *icmp = NULL;
- icmpEchoData *echo = NULL;
- struct addrinfo *S = NULL;
+ struct icmp6_hdr *icmp = nullptr;
+ icmpEchoData *echo = nullptr;
+ struct addrinfo *S = nullptr;
size_t icmp6_pktsize = 0;
static_assert(sizeof(*icmp) + sizeof(*echo) <= sizeof(pkt), "our custom ICMPv6 Echo payload fits the packet buffer");
}
debugs(42,9, "x=" << x);
- Log(to, 0, NULL, 0, 0);
+ Log(to, 0, nullptr, 0, 0);
Ip::Address::FreeAddr(S);
}
Icmp6::Recv(void)
{
int n;
- struct addrinfo *from = NULL;
+ struct addrinfo *from = nullptr;
// struct ip6_hdr *ip = NULL;
- static char *pkt = NULL;
- struct icmp6_hdr *icmp6header = NULL;
- icmpEchoData *echo = NULL;
+ static char *pkt = nullptr;
+ struct icmp6_hdr *icmp6header = nullptr;
+ icmpEchoData *echo = nullptr;
struct timeval now;
static pingerReplyData preply;
return;
}
- if (pkt == NULL) {
+ if (pkt == nullptr) {
pkt = (char *)xmalloc(MAX_PKT6_SZ);
}
#else
- gettimeofday(&now, NULL);
+ gettimeofday(&now, nullptr);
#endif
pingerReplyData preply;
static Ip::Address F;
- Comm::SetSelect(icmp_sock, COMM_SELECT_READ, icmpSquidRecv, NULL, 0);
+ Comm::SetSelect(icmp_sock, COMM_SELECT_READ, icmpSquidRecv, nullptr, 0);
n = comm_udp_recv(icmp_sock,
(char *) &preply,
sizeof(pingerReplyData),
}
args[0] = "(pinger)";
- args[1] = NULL;
+ args[1] = nullptr;
localhost.setLocalhost();
/*
fd_note(icmp_sock, "pinger");
- Comm::SetSelect(icmp_sock, COMM_SELECT_READ, icmpSquidRecv, NULL, 0);
+ Comm::SetSelect(icmp_sock, COMM_SELECT_READ, icmpSquidRecv, nullptr, 0);
commUnsetFdTimeout(icmp_sock);
void DomainPing(Ip::Address &to, const char *domain);
#if USE_ICMP
- virtual void SendEcho(Ip::Address &to, int opcode, const char* payload=NULL, int len=0);
+ virtual void SendEcho(Ip::Address &to, int opcode, const char* payload=nullptr, int len=0);
virtual void Recv(void);
#endif
};
CBDATA_CLASS_INIT(netdbExchangeState);
-static hash_table *addr_table = NULL;
-static hash_table *host_table = NULL;
+static hash_table *addr_table = nullptr;
+static hash_table *host_table = nullptr;
Ip::Address networkFromInaddr(const Ip::Address &a);
static void netdbRelease(netdbEntry * n);
* gets freed during a reconfigure. We want this database to
* remain persisitent, so _net_db_peer->peername points into this
* linked list */
-static wordlist *peer_names = NULL;
+static wordlist *peer_names = nullptr;
static void
netdbHashInsert(netdbEntry * n, Ip::Address &addr)
{
networkFromInaddr(addr).toStr(n->network, MAX_IPSTRLEN);
n->key = n->network;
- assert(hash_lookup(addr_table, n->network) == NULL);
+ assert(hash_lookup(addr_table, n->network) == nullptr);
hash_join(addr_table, n);
}
{
hash_link *hptr = (hash_link *)hash_lookup(addr_table, key);
- if (hptr == NULL) {
+ if (hptr == nullptr) {
debug_trap("netdbHashDelete: key not found");
return;
}
netdbHostInsert(netdbEntry * n, const char *hostname)
{
net_db_name *x = new net_db_name(hostname, n);
- assert(hash_lookup(host_table, hostname) == NULL);
+ assert(hash_lookup(host_table, hostname) == nullptr);
hash_join(host_table, x);
}
static void
netdbHostDelete(const net_db_name * x)
{
- assert(x != NULL);
- assert(x->net_db_entry != NULL);
+ assert(x != nullptr);
+ assert(x->net_db_entry != nullptr);
netdbEntry *n = x->net_db_entry;
-- n->link_count;
netdbLookupHost(const char *key)
{
net_db_name *x = (net_db_name *) hash_lookup(host_table, key);
- return x ? x->net_db_entry : NULL;
+ return x ? x->net_db_entry : nullptr;
}
static void
netdbHostDelete(x);
}
- n->hosts = NULL;
+ n->hosts = nullptr;
safe_free(n->peers);
- n->peers = NULL;
+ n->peers = nullptr;
n->n_peers = 0;
n->n_peers_alloc = 0;
if (netdbEntry::UseCount() > Config.Netdb.high)
netdbPurgeLRU();
- if ((n = netdbLookupAddr(addr)) == NULL) {
+ if ((n = netdbLookupAddr(addr)) == nullptr) {
n = new netdbEntry;
netdbHashInsert(n, addr);
}
netdbSendPing(const ipcache_addrs *ia, const Dns::LookupDetails &, void *data)
{
Ip::Address addr;
- char *hostname = NULL;
+ char *hostname = nullptr;
static_cast<generic_cbdata *>(data)->unwrap(&hostname);
netdbEntry *n;
netdbEntry *na;
net_db_name *x;
net_db_name **X;
- if (ia == NULL) {
+ if (ia == nullptr) {
xfree(hostname);
return;
}
addr = ia->current();
- if ((n = netdbLookupHost(hostname)) == NULL) {
+ if ((n = netdbLookupHost(hostname)) == nullptr) {
n = netdbAdd(addr);
netdbHostInsert(n, hostname);
} else if ((na = netdbLookupAddr(addr)) != n) {
*hostname moved from 'network n' to 'network na'!
*/
- if (na == NULL)
+ if (na == nullptr)
na = netdbAdd(addr);
debugs(38, 3, "netdbSendPing: " << hostname << " moved from " << n->network << " to " << na->network);
x = (net_db_name *) hash_lookup(host_table, hostname);
- if (x == NULL) {
+ if (x == nullptr) {
debugs(38, DBG_IMPORTANT, "ERROR: Squid BUG: net_db_name list bug: " << hostname << " not found");
xfree(hostname);
return;
return p;
}
- return NULL;
+ return nullptr;
}
static net_db_peer *
debugs(38, DBG_IMPORTANT, "NETDB state saved; " <<
count << " entries, " <<
tvSubMsec(start, current_time) << " msec" );
- eventAddIsh("netdbSaveState", netdbSaveState, NULL, 3600.0, 1);
+ eventAddIsh("netdbSaveState", netdbSaveState, nullptr, 3600.0, 1);
}
static void
q = strtok(t, w_space);
t = s + 1;
- if (NULL == q)
+ if (nullptr == q)
continue;
if (! (addr = q) )
continue;
- if (netdbLookupAddr(addr) != NULL) /* no dups! */
+ if (netdbLookupAddr(addr) != nullptr) /* no dups! */
continue;
- if ((q = strtok(NULL, w_space)) == NULL)
+ if ((q = strtok(nullptr, w_space)) == nullptr)
continue;
N.pings_sent = atoi(q);
- if ((q = strtok(NULL, w_space)) == NULL)
+ if ((q = strtok(nullptr, w_space)) == nullptr)
continue;
N.pings_recv = atoi(q);
N.pings_recv = 1;
- if ((q = strtok(NULL, w_space)) == NULL)
+ if ((q = strtok(nullptr, w_space)) == nullptr)
continue;
N.hops = atof(q);
- if ((q = strtok(NULL, w_space)) == NULL)
+ if ((q = strtok(nullptr, w_space)) == nullptr)
continue;
N.rtt = atof(q);
- if ((q = strtok(NULL, w_space)) == NULL)
+ if ((q = strtok(nullptr, w_space)) == nullptr)
continue;
N.next_ping_time = (time_t) atoi(q);
- if ((q = strtok(NULL, w_space)) == NULL)
+ if ((q = strtok(nullptr, w_space)) == nullptr)
continue;
N.last_use_time = (time_t) atoi(q);
netdbHashInsert(n, addr);
- while ((q = strtok(NULL, w_space)) != NULL) {
- if (netdbLookupHost(q) != NULL) /* no dups! */
+ while ((q = strtok(nullptr, w_space)) != nullptr) {
+ if (netdbLookupHost(q) != nullptr) /* no dups! */
continue;
netdbHostInsert(n, q);
host_table = hash_create((HASHCMP *) strcmp, n, hash_string);
- eventAddIsh("netdbSaveState", netdbSaveState, NULL, 3600.0, 1);
+ eventAddIsh("netdbSaveState", netdbSaveState, nullptr, 3600.0, 1);
netdbReloadState();
#if USE_ICMP
netdbEntry *n;
- if ((n = netdbLookupHost(hostname)) != NULL)
+ if ((n = netdbLookupHost(hostname)) != nullptr)
if (n->next_ping_time > squid_curtime)
return;
int N;
debugs(38, 3, "netdbHandlePingReply: from " << from);
- if ((n = netdbLookupAddr(from)) == NULL)
+ if ((n = netdbLookupAddr(from)) == nullptr)
return;
N = ++n->pings_recv;
#if USE_ICMP
hashFreeItems(addr_table, netdbFreeNetdbEntry);
hashFreeMemory(addr_table);
- addr_table = NULL;
+ addr_table = nullptr;
hashFreeItems(host_table, netdbFreeNameEntry);
hashFreeMemory(host_table);
- host_table = NULL;
+ host_table = nullptr;
wordlistDestroy(&peer_names);
- peer_names = NULL;
+ peer_names = nullptr;
#endif
}
#if USE_ICMP
netdbEntry *n = netdbLookupHost(host);
- if (n == NULL)
+ if (n == nullptr)
return;
*samp = n->pings_recv;
debugs(38, 3, url.host() << ", " << ihops << " hops, " << irtt << " rtt");
n = netdbLookupHost(url.host());
- if (n == NULL) {
+ if (n == nullptr) {
debugs(38, 3, "host " << url.host() << " not found");
return;
}
- if ((p = netdbPeerByName(n, e->host)) == NULL)
+ if ((p = netdbPeerByName(n, e->host)) == nullptr)
p = netdbPeerAdd(n, e);
p->rtt = rtt;
n = netdbLookupAddr(addr);
- if (n == NULL)
+ if (n == nullptr)
n = netdbAdd(addr);
- assert(NULL != n);
+ assert(nullptr != n);
- if ((p = netdbPeerByName(n, e->host)) == NULL)
+ if ((p = netdbPeerByName(n, e->host)) == nullptr)
p = netdbPeerAdd(n, e);
p->rtt = rtt;
#if USE_ICMP
netdbEntry *n = netdbLookupAddr(addr);
- if (n == NULL)
+ if (n == nullptr)
return;
debugs(38, 3, "netdbDeleteAddrNetwork: " << n->network);
struct in_addr line_addr;
s->buffer();
- reply->setHeaders(Http::scOkay, "OK", NULL, -1, squid_curtime, -2);
+ reply->setHeaders(Http::scOkay, "OK", nullptr, -1, squid_curtime, -2);
s->replaceHttpReply(reply);
rec_sz = 0;
rec_sz += 1 + sizeof(struct in_addr);
netdbExchangeState *ex = new netdbExchangeState(p, req);
ex->e = storeCreateEntry(uri, uri, RequestFlags(), Http::METHOD_GET);
- assert(NULL != ex->e);
+ assert(nullptr != ex->e);
StoreIOBuffer tempBuffer;
tempBuffer.length = ex->buf_sz;
assert(ps);
HttpRequest *request = ps->request;
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
netdbEntry *n;
const ipcache_addrs *ia;
net_db_peer *h;
int i;
n = netdbLookupHost(request->url.host());
- if (NULL == n) {
+ if (nullptr == n) {
/* try IP addr */
ia = ipcache_gethostbyname(request->url.host(), 0);
- if (NULL != ia)
+ if (nullptr != ia)
n = netdbLookupAddr(ia->current());
}
- if (NULL == n)
- return NULL;
+ if (nullptr == n)
+ return nullptr;
if (0 == n->n_peers)
- return NULL;
+ return nullptr;
n->last_use_time = squid_curtime;
p = peerFindByName(h->peername);
- if (NULL == p) /* not found */
+ if (nullptr == p) /* not found */
continue;
if (neighborType(p, request->url) != PEER_PARENT)
#else
(void)ps;
#endif
- return NULL;
+ return nullptr;
}
}
FD_SET(squid_link, &R);
- x = select(max_fd+1, &R, NULL, NULL, &tv);
+ x = select(max_fd+1, &R, nullptr, nullptr, &tv);
getCurrentTime();
if (x < 0) {
* IcpQueueHead is global so comm_incoming() knows whether or not
* to call icpUdpSendQueue.
*/
-static DelayedUdpSend *IcpQueueHead = NULL;
+static DelayedUdpSend *IcpQueueHead = nullptr;
/// \ingroup ServerProtocolICPInternal2
-static DelayedUdpSend *IcpQueueTail = NULL;
+static DelayedUdpSend *IcpQueueTail = nullptr;
/// \ingroup ServerProtocolICPInternal2
-Comm::ConnectionPointer icpIncomingConn = NULL;
+Comm::ConnectionPointer icpIncomingConn = nullptr;
/// \ingroup ServerProtocolICPInternal2
-Comm::ConnectionPointer icpOutgoingConn = NULL;
+Comm::ConnectionPointer icpOutgoingConn = nullptr;
/* icp_common_t */
icp_common_t::icp_common_t() :
header(aHeader),
request(aRequest),
fd(-1),
- url(NULL)
+ url(nullptr)
{
HTTPMSGLOCK(request);
}
al->cache.code.update(logcode);
}
clientdbUpdate(caddr, al->cache.code, AnyP::PROTO_ICP, len);
- accessLogLog(al, NULL);
+ accessLogLog(al, nullptr);
}
/// \ingroup ServerProtocolICPInternal2
{
DelayedUdpSend *q;
- while ((q = IcpQueueHead) != NULL) {
+ while ((q = IcpQueueHead) != nullptr) {
int delay = tvSubUsec(q->queue_time, current_time);
/* increment delay to prevent looping */
const int x = icpUdpSend(fd, q->address, q->msg, ++delay, q->ale);
int reqnum,
int pad)
{
- char *buf = NULL;
- icp_common_t *headerp = NULL;
- char *urloffset = NULL;
+ char *buf = nullptr;
+ icp_common_t *headerp = nullptr;
+ char *urloffset = nullptr;
int buf_len;
buf_len = sizeof(icp_common_t) + strlen(url) + 1;
queue->queue_time = current_time;
queue->ale = al;
- if (IcpQueueHead == NULL) {
+ if (IcpQueueHead == nullptr) {
IcpQueueHead = queue;
IcpQueueTail = queue;
} else if (IcpQueueTail == IcpQueueHead) {
IcpQueueTail = queue;
}
- Comm::SetSelect(fd, COMM_SELECT_WRITE, icpUdpSendQueue, NULL, 0);
+ Comm::SetSelect(fd, COMM_SELECT_WRITE, icpUdpSendQueue, nullptr, 0);
++statCounter.icp.replies_queued;
} else {
/* don't queue it */
if (!Config.accessList.icp)
return false;
- ACLFilledChecklist checklist(Config.accessList.icp, icp_request, NULL);
+ ACLFilledChecklist checklist(Config.accessList.icp, icp_request, nullptr);
checklist.src_addr = from;
checklist.my_addr.setNoAddr();
return checklist.fastCheck().allowed();
if (strpbrk(url, w_space)) {
url = rfc1738_escape(url);
icpCreateAndSend(ICP_ERR, 0, rfc1738_escape(url), reqnum, 0, fd, from, nullptr);
- return NULL;
+ return nullptr;
}
const auto mx = MasterXaction::MakePortless<XactionInitiator::initIcp>();
int len;
int icp_version;
int max = INCOMING_UDP_MAX;
- Comm::SetSelect(sock, COMM_SELECT_READ, icpHandleUdp, NULL, 0);
+ Comm::SetSelect(sock, COMM_SELECT_READ, icpHandleUdp, nullptr, 0);
while (max) {
--max;
debugs(12, DBG_CRITICAL, "Sending ICP messages from " << icpOutgoingConn->local);
- Comm::SetSelect(icpOutgoingConn->fd, COMM_SELECT_READ, icpHandleUdp, NULL, 0);
+ Comm::SetSelect(icpOutgoingConn->fd, COMM_SELECT_READ, icpHandleUdp, nullptr, 0);
fd_note(icpOutgoingConn->fd, "Outgoing ICP socket");
}
}
if (!Comm::IsConnOpen(conn))
fatal("Cannot open ICP Port");
- Comm::SetSelect(conn->fd, COMM_SELECT_READ, icpHandleUdp, NULL, 0);
+ Comm::SetSelect(conn->fd, COMM_SELECT_READ, icpHandleUdp, nullptr, 0);
for (const wordlist *s = Config.mcast_group_list; s; s = s->next)
- ipcache_nbgethostbyname(s->key, mcastJoinGroups, NULL); // XXX: pass the conn for mcastJoinGroups usage.
+ ipcache_nbgethostbyname(s->key, mcastJoinGroups, nullptr); // XXX: pass the conn for mcastJoinGroups usage.
debugs(12, DBG_IMPORTANT, "Accepting ICP messages on " << conn->local);
* in and out sockets may be sharing one same FD.
* This prevents this function from executing repeatedly.
*/
- icpIncomingConn = NULL;
+ icpIncomingConn = nullptr;
/**
* Normally we only write to the outgoing ICP socket, but
*/
assert(Comm::IsConnOpen(icpOutgoingConn));
- Comm::SetSelect(icpOutgoingConn->fd, COMM_SELECT_READ, NULL, NULL, 0);
+ Comm::SetSelect(icpOutgoingConn->fd, COMM_SELECT_READ, nullptr, nullptr, 0);
}
void
{
icpConnectionShutdown();
- if (icpOutgoingConn != NULL) {
+ if (icpOutgoingConn != nullptr) {
debugs(12, DBG_IMPORTANT, "Stop sending ICP from " << icpOutgoingConn->local);
- icpOutgoingConn = NULL;
+ icpOutgoingConn = nullptr;
}
}
ACLFilledChecklist *checklist = Filled(cl);
if (checklist->rfc931[0]) {
return data->match(checklist->rfc931);
- } else if (checklist->conn() != NULL && checklist->conn()->clientConnection != NULL && checklist->conn()->clientConnection->rfc931[0]) {
+ } else if (checklist->conn() != nullptr && checklist->conn()->clientConnection != nullptr && checklist->conn()->clientConnection->rfc931[0]) {
return data->match(checklist->conn()->clientConnection->rfc931);
- } else if (checklist->conn() != NULL && Comm::IsConnOpen(checklist->conn()->clientConnection)) {
+ } else if (checklist->conn() != nullptr && Comm::IsConnOpen(checklist->conn()->clientConnection)) {
if (checklist->goAsync(IdentLookup::Instance())) {
debugs(28, 3, "switching to ident lookup state");
return -1;
* Cache the ident result in the connection, to avoid redoing ident lookup
* over and over on persistent connections
*/
- if (checklist->conn() != NULL && checklist->conn()->clientConnection != NULL && !checklist->conn()->clientConnection->rfc931[0])
+ if (checklist->conn() != nullptr && checklist->conn()->clientConnection != nullptr && !checklist->conn()->clientConnection->rfc931[0])
xstrncpy(checklist->conn()->clientConnection->rfc931, checklist->rfc931, USER_IDENT_SZ);
checklist->resumeNonBlockingCheck(IdentLookup::Instance());
static CLCB Close;
static CTCB Timeout;
static CNCB ConnectDone;
-static hash_table *ident_hash = NULL;
+static hash_table *ident_hash = nullptr;
static void ClientAdd(IdentStateData * state, IDCB * callback, void *callback_data);
} // namespace Ident
void
Ident::IdentStateData::swanSong()
{
- if (clients != NULL)
- notify(NULL);
+ if (clients != nullptr)
+ notify(nullptr);
}
Ident::IdentStateData::~IdentStateData() {
break;
}
- if (c == NULL) {
+ if (c == nullptr) {
state->deleteThis("client(s) aborted");
return;
}
Ident::ReadReply(const Comm::ConnectionPointer &conn, char *buf, size_t len, Comm::Flag flag, int, void *data)
{
IdentStateData *state = (IdentStateData *)data;
- char *ident = NULL;
- char *t = NULL;
+ char *ident = nullptr;
+ char *t = nullptr;
assert(buf == state->buf);
assert(conn->fd == state->conn->fd);
if ((ident = strrchr(buf, ':'))) {
while (xisspace(*++ident));
if (ident && *ident == '\0')
- ident = NULL;
+ ident = nullptr;
state->notify(ident);
}
}
hashPrime(Squid_MaxFD / 8),
hash4);
}
- if ((state = (IdentStateData *)hash_lookup(ident_hash, key)) != NULL) {
+ if ((state = (IdentStateData *)hash_lookup(ident_hash, key)) != nullptr) {
ClientAdd(state, callback, data);
return;
}
Ip::Address::applyMask(const unsigned int cidrMask, int mtype)
{
uint8_t clearbits = 0;
- uint8_t* p = NULL;
+ uint8_t* p = nullptr;
// validation and short-cuts.
if (cidrMask > 128)
}
int err = 0;
- struct addrinfo *res = NULL;
- if ( (err = getaddrinfo(s, NULL, &want, &res)) != 0) {
+ struct addrinfo *res = nullptr;
+ if ( (err = getaddrinfo(s, nullptr, &want, &res)) != 0) {
debugs(14,3, "Given Non-IP '" << s << "': " << gai_strerror(err) );
/* free the memory getaddrinfo() dynamically allocated. */
if (res)
break;
maybeIpv4 = maybeIpv4->ai_next;
}
- if (maybeIpv4 != NULL)
+ if (maybeIpv4 != nullptr)
res = maybeIpv4;
// else IPv6-only host, let the caller deal with first-IP anyway.
}
Ip::Address::operator =(const struct hostent &s)
{
- struct in_addr* ipv4 = NULL;
+ struct in_addr* ipv4 = nullptr;
- struct in6_addr* ipv6 = NULL;
+ struct in6_addr* ipv6 = nullptr;
//struct hostent {
// char *h_name; /* official name of host */
Ip::Address::operator =(const struct addrinfo &s)
{
- struct sockaddr_in* ipv4 = NULL;
+ struct sockaddr_in* ipv4 = nullptr;
- struct sockaddr_in6* ipv6 = NULL;
+ struct sockaddr_in6* ipv6 = nullptr;
//struct addrinfo {
// int ai_flags; /* input flags */
default:
// attempt to handle partially initialised addrinfo.
// such as those where data only comes from getsockopt()
- if (s.ai_addr != NULL) {
+ if (s.ai_addr != nullptr) {
if (s.ai_addrlen == sizeof(struct sockaddr_in6)) {
operator=(*((struct sockaddr_in6*)s.ai_addr));
return true;
void
Ip::Address::getAddrInfo(struct addrinfo *&dst, int force) const
{
- if (dst == NULL) {
+ if (dst == nullptr) {
dst = new addrinfo;
}
void
Ip::Address::InitAddr(struct addrinfo *&ai)
{
- if (ai == NULL) {
+ if (ai == nullptr) {
ai = new addrinfo;
memset(ai,0,sizeof(struct addrinfo));
}
void
Ip::Address::FreeAddr(struct addrinfo *&ai)
{
- if (ai == NULL) return;
+ if (ai == nullptr) return;
if (ai->ai_addr) delete ai->ai_addr;
- ai->ai_addr = NULL;
+ ai->ai_addr = nullptr;
ai->ai_addrlen = 0;
// NP: name fields are NOT allocated at present.
delete ai;
- ai = NULL;
+ ai = nullptr;
}
int
Ip::Address::toStr(char* buf, const unsigned int blen, int force) const
{
// Ensure we have a buffer.
- if (buf == NULL) {
- return NULL;
+ if (buf == nullptr) {
+ return nullptr;
}
/* some external code may have blindly memset a parent. */
// Ensure we have a buffer.
- if (buf == NULL) {
- return NULL;
+ if (buf == nullptr) {
+ return nullptr;
}
p += toHostStr(p, blen);
void
Ip::Address::getSockAddr(struct sockaddr_storage &addr, const int family) const
{
- struct sockaddr_in *sin = NULL;
+ struct sockaddr_in *sin = nullptr;
if ( family == AF_INET && !isIPv4()) {
// TODO INET6: caller using the wrong socket type!
class Address_list
{
public:
- Address_list() { next = NULL; };
- ~Address_list() { if (next) delete next; next = NULL; };
+ Address_list() { next = nullptr; };
+ ~Address_list() { if (next) delete next; next = nullptr; };
Address s;
Address_list *next;
preserveMissTosMask(0xFF), markLocalHit(0), markSiblingHit(0),
markParentHit(0), markMiss(0), markMissMask(0),
preserveMissMark(false), preserveMissMarkMask(0xFFFFFFFF),
- tosToServer(NULL), tosToClient(NULL), nfmarkToServer(NULL),
- nfmarkToClient(NULL)
+ tosToServer(nullptr), tosToClient(nullptr), nfmarkToServer(nullptr),
+ nfmarkToClient(nullptr)
{
}
if (strncmp(token, "local-hit=",10) == 0) {
if (mark) {
- if (!xstrtoui(&token[10], NULL, &markLocalHit, 0, std::numeric_limits<nfmark_t>::max())) {
+ if (!xstrtoui(&token[10], nullptr, &markLocalHit, 0, std::numeric_limits<nfmark_t>::max())) {
debugs(3, DBG_CRITICAL, "ERROR: Bad mark local-hit value " << &token[10]);
self_destruct();
}
} else {
unsigned int v = 0;
- if (!xstrtoui(&token[10], NULL, &v, 0, std::numeric_limits<tos_t>::max())) {
+ if (!xstrtoui(&token[10], nullptr, &v, 0, std::numeric_limits<tos_t>::max())) {
debugs(3, DBG_CRITICAL, "ERROR: Bad TOS local-hit value " << &token[10]);
self_destruct();
}
} else if (strncmp(token, "sibling-hit=",12) == 0) {
if (mark) {
- if (!xstrtoui(&token[12], NULL, &markSiblingHit, 0, std::numeric_limits<nfmark_t>::max())) {
+ if (!xstrtoui(&token[12], nullptr, &markSiblingHit, 0, std::numeric_limits<nfmark_t>::max())) {
debugs(3, DBG_CRITICAL, "ERROR: Bad mark sibling-hit value " << &token[12]);
self_destruct();
}
} else {
unsigned int v = 0;
- if (!xstrtoui(&token[12], NULL, &v, 0, std::numeric_limits<tos_t>::max())) {
+ if (!xstrtoui(&token[12], nullptr, &v, 0, std::numeric_limits<tos_t>::max())) {
debugs(3, DBG_CRITICAL, "ERROR: Bad TOS sibling-hit value " << &token[12]);
self_destruct();
}
} else if (strncmp(token, "parent-hit=",11) == 0) {
if (mark) {
- if (!xstrtoui(&token[11], NULL, &markParentHit, 0, std::numeric_limits<nfmark_t>::max())) {
+ if (!xstrtoui(&token[11], nullptr, &markParentHit, 0, std::numeric_limits<nfmark_t>::max())) {
debugs(3, DBG_CRITICAL, "ERROR: Bad mark parent-hit value " << &token[11]);
self_destruct();
}
} else {
unsigned int v = 0;
- if (!xstrtoui(&token[11], NULL, &v, 0, std::numeric_limits<tos_t>::max())) {
+ if (!xstrtoui(&token[11], nullptr, &v, 0, std::numeric_limits<tos_t>::max())) {
debugs(3, DBG_CRITICAL, "ERROR: Bad TOS parent-hit value " << &token[11]);
self_destruct();
}
self_destruct();
}
if (*end == '/') {
- if (!xstrtoui(end + 1, NULL, &markMissMask, 0, std::numeric_limits<nfmark_t>::max())) {
+ if (!xstrtoui(end + 1, nullptr, &markMissMask, 0, std::numeric_limits<nfmark_t>::max())) {
debugs(3, DBG_CRITICAL, "ERROR: Bad mark miss mask value " << (end + 1) << ". Using 0xFFFFFFFF instead.");
markMissMask = 0xFFFFFFFF;
}
}
tosMiss = (tos_t)v;
if (*end == '/') {
- if (!xstrtoui(end + 1, NULL, &v, 0, std::numeric_limits<tos_t>::max())) {
+ if (!xstrtoui(end + 1, nullptr, &v, 0, std::numeric_limits<tos_t>::max())) {
debugs(3, DBG_CRITICAL, "ERROR: Bad TOS miss mask value " << (end + 1) << ". Using 0xFF instead.");
tosMissMask = 0xFF;
} else
} else if (strncmp(token, "miss-mask=",10) == 0) {
if (mark && preserveMissMark) {
- if (!xstrtoui(&token[10], NULL, &preserveMissMarkMask, 0, std::numeric_limits<nfmark_t>::max())) {
+ if (!xstrtoui(&token[10], nullptr, &preserveMissMarkMask, 0, std::numeric_limits<nfmark_t>::max())) {
debugs(3, DBG_CRITICAL, "ERROR: Bad mark miss-mark value " << &token[10]);
self_destruct();
}
} else if (preserveMissTos) {
unsigned int v = 0;
- if (!xstrtoui(&token[10], NULL, &v, 0, std::numeric_limits<tos_t>::max())) {
+ if (!xstrtoui(&token[10], nullptr, &v, 0, std::numeric_limits<tos_t>::max())) {
debugs(3, DBG_CRITICAL, "ERROR: Bad TOS miss-mark value " << &token[10]);
self_destruct();
}
CBDATA_CLASS(acl_tos);
public:
- acl_tos() : next(NULL), aclList(NULL), tos(0) {}
+ acl_tos() : next(nullptr), aclList(nullptr), tos(0) {}
~acl_tos();
acl_tos *next;
CBDATA_CLASS(acl_nfmark);
public:
- acl_nfmark() : next(NULL), aclList(NULL) {}
+ acl_nfmark() : next(nullptr), aclList(nullptr) {}
~acl_nfmark();
acl_nfmark *next;
pid_t pid;
Ip::Address ChS;
Ip::Address PaS;
- struct addrinfo *AI = NULL;
+ struct addrinfo *AI = nullptr;
int crfd = -1;
int prfd = -1;
int cwfd = -1;
*wfd = -1;
if (hIpc)
- *hIpc = NULL;
+ *hIpc = nullptr;
// NP: no wrapping around d and c usage since we *want* code expansion
#define IPC_CHECK_FAIL(f,d,c) \
struct timeval sl;
sl.tv_sec = Config.sleep_after_fork / 1000000;
sl.tv_usec = Config.sleep_after_fork % 1000000;
- select(0, NULL, NULL, NULL, &sl);
+ select(0, nullptr, nullptr, nullptr, &sl);
}
return pid;
if (type == IPC_TCP_SOCKET) {
debugs(54, 3, "ipcCreate: calling accept on FD " << crfd);
- if ((fd = accept(crfd, NULL, NULL)) < 0) {
+ if ((fd = accept(crfd, nullptr, nullptr)) < 0) {
xerrno = errno;
debugs(54, DBG_CRITICAL, "ipcCreate: FD " << crfd << " accept: " << xstrerr(xerrno));
_exit(1);
#include <cerrno>
CBDATA_NAMESPACED_CLASS_INIT(Ipc, Coordinator);
-Ipc::Coordinator* Ipc::Coordinator::TheInstance = NULL;
+Ipc::Coordinator* Ipc::Coordinator::TheInstance = nullptr;
Ipc::Coordinator::Coordinator():
Port(Ipc::Port::CoordinatorAddr())
if (iter->kidId == kidId)
return &(*iter);
}
- return NULL;
+ return nullptr;
}
void Ipc::Coordinator::registerStrand(const StrandCoord& strand)
Ipc::Coordinator::handleSearchRequest(const Ipc::StrandSearchRequest &request)
{
// do we know of a strand with the given search tag?
- const StrandCoord *strand = NULL;
+ const StrandCoord *strand = nullptr;
typedef StrandCoords::const_iterator SCCI;
for (SCCI i = strands_.begin(); !strand && i != strands_.end(); ++i) {
if (i->tag == request.tag)
Ipc::Forwarder::RequestTimedOut(void* param)
{
debugs(54, 3, MYNAME);
- Must(param != NULL);
+ Must(param != nullptr);
Forwarder* fwdr = static_cast<Forwarder*>(param);
// use async call to enable job call protection that time events lack
RequestsMap::iterator request = TheRequestsMap.find(requestId);
if (request != TheRequestsMap.end()) {
call = request->second;
- Must(call != NULL);
+ Must(call != nullptr);
TheRequestsMap.erase(request);
}
return call;
Must(requestId != 0);
AsyncCall::Pointer call = DequeueRequest(requestId);
- if (call != NULL)
+ if (call != nullptr)
ScheduleCallHere(call);
}
Must(request->requestId == 0);
AsyncCall::Pointer callback = asyncCall(54, 5, "Mgr::Inquirer::handleRemoteAck",
- HandleAckDialer(this, &Inquirer::handleRemoteAck, NULL));
+ HandleAckDialer(this, &Inquirer::handleRemoteAck, nullptr));
if (++LastRequestId == 0) // don't use zero value as request->requestId
++LastRequestId;
request->requestId = LastRequestId;
RequestsMap::iterator request = TheRequestsMap.find(requestId);
if (request != TheRequestsMap.end()) {
call = request->second;
- Must(call != NULL);
+ Must(call != nullptr);
TheRequestsMap.erase(request);
}
return call;
{
Must(response.requestId != 0);
AsyncCall::Pointer call = DequeueRequest(response.requestId);
- if (call != NULL) {
+ if (call != nullptr) {
HandleAckDialer* dialer = dynamic_cast<HandleAckDialer*>(call->getDialer());
Must(dialer);
dialer->arg1 = response.clone();
Ipc::Inquirer::RequestTimedOut(void* param)
{
debugs(54, 3, MYNAME);
- Must(param != NULL);
+ Must(param != nullptr);
Inquirer* cmi = static_cast<Inquirer*>(param);
// use async call to enable job call protection that time events lack
CallBack(cmi->codeContext, [&cmi] {
if (storage[i].getPid() == pid)
return &storage[i];
}
- return NULL;
+ return nullptr;
}
/// returns the kid by index, useful for kids iteration
#include "tools.h"
Ipc::MemMap::MemMap(const char *const aPath) :
- cleaner(NULL),
+ cleaner(nullptr),
path(aPath),
shared(shm_old(Shared)(aPath))
{
return slot;
}
- return NULL;
+ return nullptr;
}
Ipc::MemMap::Slot *
lock.unlockExclusive();
debugs(54, 5, "cannot open existing entry " << fileno <<
" for writing " << path);
- return NULL;
+ return nullptr;
}
// free if the entry was used, keeping the entry locked
debugs(54, 5, "failed to open slot at " << fileno <<
" for writing in map [" << path << ']');
- return NULL;
+ return nullptr;
}
void
if (s.reading())
return &s; // immediate access by lock holder so no locking
if (s.writing())
- return NULL; // cannot read the slot when it is being written
+ return nullptr; // cannot read the slot when it is being written
assert(false); // must be locked for reading or writing
- return NULL;
+ return nullptr;
}
void
}
debugs(54, 5, "failed to open slot for key " << storeKeyText(key)
<< " for reading in map [" << path << ']');
- return NULL;
+ return nullptr;
}
const Ipc::MemMap::Slot *
if (!s.lock.lockShared()) {
debugs(54, 5, "failed to lock slot at " << fileno << " for "
"reading in map [" << path << ']');
- return NULL;
+ return nullptr;
}
if (s.empty()) {
s.lock.unlockShared();
debugs(54, 7, "empty slot at " << fileno << " for "
"reading in map [" << path << ']');
- return NULL;
+ return nullptr;
}
if (s.waitingToBeFreed) {
s.lock.unlockShared();
debugs(54, 7, "dirty slot at " << fileno << " for "
"reading in map [" << path << ']');
- return NULL;
+ return nullptr;
}
debugs(54, 5, "opened slot at " << fileno << " for reading in"
static int Items2Bytes(const unsigned int maxItemSize, const int size);
/// returns true iff the value was set; [un]blocks the reader as needed
- template<class Value> bool pop(Value &value, QueueReader *const reader = NULL);
+ template<class Value> bool pop(Value &value, QueueReader *const reader = nullptr);
/// returns true iff the caller must notify the reader of the pushed item
- template<class Value> bool push(const Value &value, QueueReader *const reader = NULL);
+ template<class Value> bool push(const Value &value, QueueReader *const reader = nullptr);
/// returns true iff the value was set; the value may be stale!
template<class Value> bool peek(Value &value) const;
TheSharedListenRequestMap.erase(pori);
StartListeningCb *cbd = dynamic_cast<StartListeningCb*>(por.callback->getDialer());
- assert(cbd && cbd->conn != NULL);
- Must(cbd && cbd->conn != NULL);
+ assert(cbd && cbd->conn != nullptr);
+ Must(cbd && cbd->conn != nullptr);
cbd->conn->fd = response.fd;
if (Comm::IsConnOpen(cbd->conn)) {
cbd->conn->local = p.addr;
cbd->conn->flags = p.flags;
// XXX: leave the comm AI stuff to comm_import_opened()?
- struct addrinfo *AI = NULL;
+ struct addrinfo *AI = nullptr;
p.addr.getAddrInfo(AI);
AI->ai_socktype = p.sock_type;
AI->ai_protocol = p.proto;
#include <cerrno>
-Ipc::StartListeningCb::StartListeningCb(): conn(NULL), errNo(0)
+Ipc::StartListeningCb::StartListeningCb(): conn(nullptr), errNo(0)
{
}
return owner;
}
-Ipc::StoreMap::StoreMap(const SBuf &aPath): cleaner(NULL), path(aPath),
+Ipc::StoreMap::StoreMap(const SBuf &aPath): cleaner(nullptr), path(aPath),
fileNos(shm_old(FileNos)(StoreMapFileNosId(path).c_str())),
anchors(shm_old(Anchors)(StoreMapAnchorsId(path).c_str())),
slices(shm_old(Slices)(StoreMapSlicesId(path).c_str())),
return anchor;
}
- return NULL;
+ return nullptr;
}
Ipc::StoreMap::Anchor *
lock.unlockExclusive();
debugs(54, 5, "cannot open existing entry " << fileno <<
" for writing " << path);
- return NULL;
+ return nullptr;
}
// free if the entry was used, keeping the entry locked
debugs(54, 5, "cannot open busy entry " << fileno <<
" for writing " << path);
- return NULL;
+ return nullptr;
}
void
fileno = idx;
return anchor; // locked for reading
}
- return NULL;
+ return nullptr;
}
const Ipc::StoreMap::Anchor *
if (!s.lock.lockShared()) {
debugs(54, 5, "cannot open busy entry " << fileno <<
" for reading " << path);
- return NULL;
+ return nullptr;
}
if (s.empty()) {
s.lock.unlockShared();
debugs(54, 7, "cannot open empty entry " << fileno <<
" for reading " << path);
- return NULL;
+ return nullptr;
}
if (s.waitingToBeFreed) {
s.lock.unlockShared();
debugs(54, 7, "cannot open marked entry " << fileno <<
" for reading " << path);
- return NULL;
+ return nullptr;
}
if (!s.sameKey(key)) {
debugs(54, 5, '[' << this << ']');
if (Comm::IsConnOpen(conn_))
conn_->close();
- conn_ = NULL;
+ conn_ = nullptr;
}
void Ipc::UdsOp::setOptions(int newOptions)
if (!Comm::IsConnOpen(conn_)) {
if (options & COMM_DOBIND)
unlink(address.sun_path);
- if (conn_ == NULL)
+ if (conn_ == nullptr)
conn_ = new Comm::Connection;
conn_->fd = comm_open_uds(SOCK_DGRAM, 0, &address, options);
Must(Comm::IsConnOpen(conn_));
typedef CommCbMemFunT<UdsSender, CommIoCbParams> Dialer;
AsyncCall::Pointer writeHandler = JobCallback(54, 5,
Dialer, this, UdsSender::wrote);
- Comm::Write(conn(), message.raw(), message.size(), writeHandler, NULL);
+ Comm::Write(conn(), message.raw(), message.size(), writeHandler, nullptr);
writing = true;
}
socklen_t len = sizeof(addr);
if (getsockname(conn->fd, reinterpret_cast<sockaddr*>(&addr), &len) == 0) {
conn->remote = addr;
- struct addrinfo* addr_info = NULL;
+ struct addrinfo* addr_info = nullptr;
conn->remote.getAddrInfo(addr_info);
addr_info->ai_socktype = socktype;
addr_info->ai_protocol = protocol;
// safer than bool which would enable silent casts to int
typedef const uint32_t PageId::*SaferBool;
- operator SaferBool() const { return set() ? &PageId::number : NULL; }
+ operator SaferBool() const { return set() ? &PageId::number : nullptr; }
/// The ID of a PagePool (and/or PageStack) this page belongs to.
/// Positive values are (ab)used to detect in-use pages. See set().
// TODO: make pool id more unique so it does not conflict with other Squids?
static const char *PagePoolId = "squid-page-pool";
-static Ipc::Mem::PagePool *ThePagePool = 0;
+static Ipc::Mem::PagePool *ThePagePool = nullptr;
static int TheLimits[Ipc::Mem::PageId::maxPurpose+1];
// TODO: make configurable to avoid waste when mem-cached objects are small/big
{
public:
/* RegisteredRunner API */
- SharedMemPagesRr(): owner(NULL) {}
+ SharedMemPagesRr(): owner(nullptr) {}
virtual void useConfig();
virtual void create();
virtual void open();
SharedMemPagesRr::~SharedMemPagesRr()
{
delete ThePagePool;
- ThePagePool = NULL;
+ ThePagePool = nullptr;
delete owner;
}
typedef RefCount< Object<Class> > Base;
public:
- explicit Pointer(Object<Class> *const anObject = NULL): Base(anObject) {}
+ explicit Pointer(Object<Class> *const anObject = nullptr): Base(anObject) {}
Class *operator ->() const { return Base::operator ->()->theObject; }
Class &operator *() const { return *Base::operator *().theObject; }
template <class Class>
Owner<Class>::Owner(const char *const id, const off_t sharedSize):
- theSegment(id), theObject(NULL)
+ theSegment(id), theObject(nullptr)
{
theSegment.create(sharedSize);
Must(theSegment.mem());
#if HAVE_SHM
Ipc::Mem::Segment::Segment(const char *const id):
- theFD(-1), theName(GenerateName(id)), theMem(NULL),
+ theFD(-1), theName(GenerateName(id)), theMem(nullptr),
theSize(0), theReserved(0), doUnlink(false)
{
}
assert(theSize == static_cast<off_t>(static_cast<size_t>(theSize)));
void *const p =
- mmap(NULL, theSize, PROT_READ | PROT_WRITE, MAP_SHARED, theFD, 0);
+ mmap(nullptr, theSize, PROT_READ | PROT_WRITE, MAP_SHARED, theFD, 0);
if (p == MAP_FAILED) {
int xerrno = errno;
debugs(54, 5, "mmap " << theName << ": " << xstrerr(xerrno));
fatalf("Ipc::Mem::Segment::detach failed to munmap(%s): %s\n",
theName.termedBuf(), xstrerr(xerrno));
}
- theMem = 0;
+ theMem = nullptr;
}
/// Lock the segment into RAM, ensuring that the OS has enough RAM for it [now]
static void ipcache_nbgethostbyname_(const char *name, IpCacheLookupForwarder handler);
/// \ingroup IPCacheInternal
-static hash_table *ip_table = NULL;
+static hash_table *ip_table = nullptr;
/// \ingroup IPCacheInternal
static long ipcache_low = 180;
static ipcache_entry *
ipcache_get(const char *name)
{
- if (ip_table != NULL)
+ if (ip_table != nullptr)
return (ipcache_entry *) hash_lookup(ip_table, name);
else
- return NULL;
+ return nullptr;
}
/// \ingroup IPCacheInternal
ipcache_purgelru(void *)
{
dlink_node *m;
- dlink_node *prev = NULL;
+ dlink_node *prev = nullptr;
ipcache_entry *i;
int removed = 0;
- eventAdd("ipcache_purgelru", ipcache_purgelru, NULL, 10.0, 1);
+ eventAdd("ipcache_purgelru", ipcache_purgelru, nullptr, 10.0, 1);
for (m = lru_list.tail; m; m = prev) {
if (ipcacheCount() < ipcache_low)
purge_entries_fromhosts(void)
{
dlink_node *m = lru_list.head;
- ipcache_entry *i = NULL, *t;
+ ipcache_entry *i = nullptr, *t;
while (m) {
- if (i != NULL) { /* need to delay deletion */
+ if (i != nullptr) { /* need to delay deletion */
ipcacheRelease(i); /* we just override locks */
- i = NULL;
+ i = nullptr;
}
t = (ipcache_entry*)m->data;
m = m->next;
}
- if (i != NULL)
+ if (i != nullptr)
ipcacheRelease(i);
}
{
hash_link *e = (hash_link *)hash_lookup(ip_table, i->hash.key);
- if (NULL != e) {
+ if (nullptr != e) {
/* avoid collision */
ipcache_entry *q = (ipcache_entry *) e;
ipcacheRelease(q);
static void
ipcache_nbgethostbyname_(const char *name, IpCacheLookupForwarder handler)
{
- ipcache_entry *i = NULL;
- const ipcache_addrs *addrs = NULL;
+ ipcache_entry *i = nullptr;
+ const ipcache_addrs *addrs = nullptr;
++IpcacheStats.requests;
- if (name == NULL || name[0] == '\0') {
+ if (name == nullptr || name[0] == '\0') {
debugs(14, 4, "ipcache_nbgethostbyname: Invalid name!");
++IpcacheStats.invalid;
const Dns::LookupDetails details("Invalid hostname", -1); // error, no lookup
i = ipcache_get(name);
- if (NULL == i) {
+ if (nullptr == i) {
/* miss */
(void) 0;
} else if (ipcacheExpiredEntry(i)) {
/* hit, but expired -- bummer */
ipcacheRelease(i);
- i = NULL;
+ i = nullptr;
} else {
/* hit */
debugs(14, 4, "ipcache_nbgethostbyname: HIT for '" << name << "'");
const ipcache_addrs *
ipcache_gethostbyname(const char *name, int flags)
{
- ipcache_entry *i = NULL;
+ ipcache_entry *i = nullptr;
assert(name);
debugs(14, 3, "ipcache_gethostbyname: '" << name << "', flags=" << std::hex << flags);
++IpcacheStats.requests;
i = ipcache_get(name);
- if (NULL == i) {
+ if (nullptr == i) {
(void) 0;
} else if (ipcacheExpiredEntry(i)) {
ipcacheRelease(i);
- i = NULL;
+ i = nullptr;
} else if (i->flags.negcached) {
++IpcacheStats.negative_hits;
// ignore i->error_message: the caller just checks IP cache presence
- return NULL;
+ return nullptr;
} else {
++IpcacheStats.hits;
i->lastref = squid_curtime;
++IpcacheStats.misses;
if (flags & IP_LOOKUP_IF_MISS)
- ipcache_nbgethostbyname(name, NULL, NULL);
+ ipcache_nbgethostbyname(name, nullptr, nullptr);
- return NULL;
+ return nullptr;
}
/// \ingroup IPCacheInternal
stat_ipcache_get(StoreEntry * sentry)
{
dlink_node *m;
- assert(ip_table != NULL);
+ assert(ip_table != nullptr);
storeAppendPrintf(sentry, "IP Cache Statistics:\n");
storeAppendPrintf(sentry, "IPcache Entries Cached: %d\n",
ipcacheCount());
{
ipcache_entry *i;
- if ((i = ipcache_get(name)) == NULL)
+ if ((i = ipcache_get(name)) == nullptr)
return;
i->expires = squid_curtime;
{
ipcache_entry *i;
- if ((i = ipcache_get(name)) == NULL)
+ if ((i = ipcache_get(name)) == nullptr)
return;
if (i->flags.negcached)
{
hashFreeItems(ip_table, ipcacheFreeEntry);
hashFreeMemory(ip_table);
- ip_table = NULL;
+ ip_table = nullptr;
}
/**
variable_list *
snmp_netIpFn(variable_list * Var, snint * ErrP)
{
- variable_list *Answer = NULL;
+ variable_list *Answer = nullptr;
MemBuf tmp;
debugs(49, 5, "snmp_netIpFn: Processing request:" << snmpDebugOid(Var->name, Var->name_length, tmp));
*ErrP = SNMP_ERR_NOERROR;
default:
*ErrP = SNMP_ERR_NOSUCHNAME;
snmp_var_free(Answer);
- return (NULL);
+ return (nullptr);
}
return Answer;
Logfile::Logfile(const char *aPath) :
sequence_number(0),
- data(NULL),
- f_linestart(NULL),
- f_linewrite(NULL),
- f_lineend(NULL),
- f_flush(NULL),
- f_rotate(NULL),
- f_close(NULL)
+ data(nullptr),
+ f_linestart(nullptr),
+ f_linewrite(nullptr),
+ f_lineend(nullptr),
+ f_flush(nullptr),
+ f_rotate(nullptr),
+ f_close(nullptr)
{
xstrncpy(path, aPath, sizeof(path));
flags.fatal = 0;
debugs(50, DBG_IMPORTANT, "ERROR: logfileOpen: " << path << ": could not open!");
lf->f_close(lf);
delete lf;
- return NULL;
+ return nullptr;
}
- assert(lf->data != NULL);
+ assert(lf->data != nullptr);
if (fatal_flag)
lf->flags.fatal = 1;
Log::Format::HttpdCombined(const AccessLogEntry::Pointer &al, Logfile * logfile)
{
const char *user_ident = ::Format::QuoteUrlEncodeUsername(al->getClientIdent());
- const char *user_auth = NULL;
- const char *referer = NULL;
- const char *agent = NULL;
+ const char *user_auth = nullptr;
+ const char *referer = nullptr;
+ const char *agent = nullptr;
if (al->request) {
#if USE_AUTH
- if (al->request->auth_user_request != NULL)
+ if (al->request->auth_user_request != nullptr)
user_auth = ::Format::QuoteUrlEncodeUsername(al->request->auth_user_request->username());
#endif
referer = al->request->header.getStr(Http::HdrType::REFERER);
void
Log::Format::HttpdCommon(const AccessLogEntry::Pointer &al, Logfile * logfile)
{
- const char *user_auth = NULL;
+ const char *user_auth = nullptr;
#if USE_AUTH
- if (al->request && al->request->auth_user_request != NULL)
+ if (al->request && al->request->auth_user_request != nullptr)
user_auth = ::Format::QuoteUrlEncodeUsername(al->request->auth_user_request->username());
#endif
const char *user_ident = ::Format::QuoteUrlEncodeUsername(al->getClientIdent());
void
Log::Format::SquidIcap(const AccessLogEntry::Pointer &al, Logfile * logfile)
{
- const char *user = NULL;
+ const char *user = nullptr;
char tmp[MAX_IPSTRLEN], clientbuf[MAX_IPSTRLEN];
const auto client = al->getLogClientFqdn(clientbuf, sizeof(clientbuf));
#if USE_AUTH
- if (al->request != NULL && al->request->auth_user_request != NULL)
+ if (al->request != nullptr && al->request->auth_user_request != nullptr)
user = ::Format::QuoteUrlEncodeUsername(al->request->auth_user_request->username());
#endif
{
char hierHost[MAX_IPSTRLEN];
- const char *user = NULL;
+ const char *user = nullptr;
#if USE_AUTH
- if (al->request && al->request->auth_user_request != NULL)
+ if (al->request && al->request->auth_user_request != nullptr)
user = ::Format::QuoteUrlEncodeUsername(al->request->auth_user_request->username());
#endif
user ? user : dash_str,
al->hier.ping.timedout ? "TIMEOUT_" : "",
hier_code_str[al->hier.code],
- al->hier.tcpServer != NULL ? al->hier.tcpServer->remote.toStr(hierHost, sizeof(hierHost)) : "-",
+ al->hier.tcpServer != nullptr ? al->hier.tcpServer->remote.toStr(hierHost, sizeof(hierHost)) : "-",
al->http.content_type,
(Config.onoff.log_mime_hdrs?"":"\n"));
void
Log::Format::SquidReferer(const AccessLogEntry::Pointer &al, Logfile *logfile)
{
- const char *referer = NULL;
+ const char *referer = nullptr;
if (al->request)
referer = al->request->header.getStr(Http::HdrType::REFERER);
void
Log::Format::SquidUserAgent(const AccessLogEntry::Pointer &al, Logfile * logfile)
{
- const char *agent = NULL;
+ const char *agent = nullptr;
if (al->request)
agent = al->request->header.getStr(Http::HdrType::USER_AGENT);
debugs(50, 5, "logfileNewBuffer: " << lf->path << ": new buffer");
b = static_cast<logfile_buffer_t*>(xcalloc(1, sizeof(logfile_buffer_t)));
- assert(b != NULL);
+ assert(b != nullptr);
b->buf = static_cast<char*>(xcalloc(1, LOGFILE_BUFSZ));
- assert(b->buf != NULL);
+ assert(b->buf != nullptr);
b->size = LOGFILE_BUFSZ;
b->written_len = 0;
b->len = 0;
logfileFreeBuffer(Logfile * lf, logfile_buffer_t * b)
{
l_daemon_t *ll = (l_daemon_t *) lf->data;
- assert(b != NULL);
+ assert(b != nullptr);
dlinkDelete(&b->node, &ll->bufs);
-- ll->nbufs;
xfree(b->buf);
return;
logfile_buffer_t *b = static_cast<logfile_buffer_t*>(ll->bufs.head->data);
- assert(b != NULL);
+ assert(b != nullptr);
ll->flush_pending = 0;
int ret = FD_WRITE_METHOD(ll->wfd, b->buf + b->written_len, b->len - b->written_len);
if (b->written_len == b->len) {
/* written the whole buffer! */
logfileFreeBuffer(lf, b);
- b = NULL;
+ b = nullptr;
}
/* Is there more to write? */
if (!ll->bufs.head)
logfileQueueWrite(Logfile * lf)
{
l_daemon_t *ll = (l_daemon_t *) lf->data;
- if (ll->flush_pending || ll->bufs.head == NULL) {
+ if (ll->flush_pending || ll->bufs.head == nullptr) {
return;
}
ll->flush_pending = 1;
int s;
/* Is there a buffer? If not, create one */
- if (ll->bufs.head == NULL) {
+ if (ll->bufs.head == nullptr) {
logfileNewBuffer(lf);
}
debugs(50, 3, "logfile_mod_daemon_append: " << lf->path << ": appending " << len << " bytes");
Ip::Address localhost;
args[0] = "(logfile-daemon)";
args[1] = path;
- args[2] = NULL;
+ args[2] = nullptr;
localhost.setLocalhost();
- ll->pid = ipcCreate(IPC_STREAM, Log::TheConfig.logfile_daemon, args, "logfile-daemon", localhost, &ll->rfd, &ll->wfd, NULL);
+ ll->pid = ipcCreate(IPC_STREAM, Log::TheConfig.logfile_daemon, args, "logfile-daemon", localhost, &ll->rfd, &ll->wfd, nullptr);
if (ll->pid < 0)
fatal("Couldn't start logfile helper");
}
kill(ll->pid, SIGTERM);
eventDelete(logfileFlushEvent, lf);
xfree(ll);
- lf->data = NULL;
+ lf->data = nullptr;
cbdataInternalUnlock(lf); // WTF??
}
return;
ll->eol = 1;
/* Kick a write off if the head buffer is -full- */
- if (ll->bufs.head != NULL) {
+ if (ll->bufs.head != nullptr) {
b = static_cast<logfile_buffer_t*>(ll->bufs.head->data);
- if (b->node.next != NULL || !Config.onoff.buffered_logs)
+ if (b->node.next != nullptr || !Config.onoff.buffered_logs)
logfileQueueWrite(lf);
}
}
debugs(50, DBG_IMPORTANT, "ERROR: Logfile Daemon: Could not set the pipe blocking for flush! You are now missing some log entries.");
return;
}
- while (ll->bufs.head != NULL) {
+ while (ll->bufs.head != nullptr) {
logfileHandleWrite(ll->wfd, lf);
}
if (commSetNonBlocking(ll->wfd)) {
xfree(ll->buf);
xfree(lf->data);
- lf->data = NULL;
+ lf->data = nullptr;
}
/*
#ifdef LOG_DEBUG
{syslog_symbol(LOG_DEBUG)},
#endif
- {NULL, 0}
+ {nullptr, 0}
};
syslog_symbol_t *p;
- for (p = symbols; p->name != NULL; ++p)
+ for (p = symbols; p->name != nullptr; ++p)
if (!strcmp(s, p->name) || !strcasecmp(s, p->name + 4))
return p->value;
logfile_mod_syslog_close(Logfile *lf)
{
xfree(lf->data);
- lf->data = NULL;
+ lf->data = nullptr;
}
/*
xfree(ll->buf);
xfree(lf->data);
- lf->data = NULL;
+ lf->data = nullptr;
}
/*
quitOnEmpty(false),
reconnectScheduled(false),
writeScheduled(false),
- conn(NULL),
+ conn(nullptr),
remote(them),
connectFailures(0),
drops(0)
Log::TcpLogger::endGracefully()
{
// job call protection must end our job if we are done logging current bufs
- assert(inCall != NULL);
+ assert(inCall != nullptr);
quitOnEmpty = true;
flush();
}
void Log::TcpLogger::writeIfPossible()
{
debugs(MY_DEBUG_SECTION, 7, "guards: " << (!writeScheduled) <<
- (bufferedSize > 0) << (conn != NULL) <<
- (conn != NULL && !fd_table[conn->fd].closing()) << " buffered: " <<
+ (bufferedSize > 0) << (conn != nullptr) <<
+ (conn != nullptr && !fd_table[conn->fd].closing()) << " buffered: " <<
bufferedSize << '/' << buffers.size());
// XXX: Squid shutdown sequence starts closing our connection before
// calling LogfileClose, leading to loss of log records during shutdown.
- if (!writeScheduled && bufferedSize > 0 && conn != NULL &&
+ if (!writeScheduled && bufferedSize > 0 && conn != nullptr &&
!fd_table[conn->fd].closing()) {
debugs(MY_DEBUG_SECTION, 5, "writing first buffer");
typedef CommCbMemFunT<TcpLogger, CommIoCbParams> WriteDialer;
AsyncCall::Pointer callback = JobCallback(MY_DEBUG_SECTION, 5, WriteDialer, this, Log::TcpLogger::writeDone);
const MemBlob::Pointer &buffer = buffers.front();
- Comm::Write(conn, buffer->mem, buffer->size, callback, NULL);
+ Comm::Write(conn, buffer->mem, buffer->size, callback, nullptr);
writeScheduled = true;
}
}
void
Log::TcpLogger::handleClosure(const CommCloseCbParams &)
{
- assert(inCall != NULL);
- closer = NULL;
+ assert(inCall != nullptr);
+ closer = nullptr;
if (conn) {
conn->noteClosure();
conn = nullptr;
void
Log::TcpLogger::disconnect()
{
- if (conn != NULL) {
- if (closer != NULL) {
+ if (conn != nullptr) {
+ if (closer != nullptr) {
comm_remove_close_handler(conn->fd, closer);
- closer = NULL;
+ closer = nullptr;
}
conn->close();
- conn = NULL;
+ conn = nullptr;
}
}
{
if (Pointer *pptr = static_cast<Pointer*>(lf->data))
return pptr->get(); // may be nil
- return NULL;
+ return nullptr;
}
void
ScheduleCallHere(call);
}
delete static_cast<Pointer*>(lf->data);
- lf->data = NULL;
+ lf->data = nullptr;
}
/*
for (log = Config.Log.accesslogs; log; log = log->next) {
if (log->logfile) {
logfileClose(log->logfile);
- log->logfile = NULL;
+ log->logfile = nullptr;
}
}
n_choices(0),
n_ichoices(0),
peer_reply_status(Http::scNone),
- tcpServer(NULL),
+ tcpServer(nullptr),
bodyBytesRead(-1)
{
memset(host, '\0', SQUIDHOSTNAMELEN);
clearPeerNotes();
tcpServer = server;
- if (tcpServer == NULL) {
+ if (tcpServer == nullptr) {
code = HIER_NONE;
xstrncpy(host, requestedHost, sizeof(host));
} else {
LogfileStatus = LOG_ENABLE;
#if USE_ADAPTATION
- for (Format::Token * curr_token = (log->logFormat?log->logFormat->format:NULL); curr_token; curr_token = curr_token->next) {
+ for (Format::Token * curr_token = (log->logFormat?log->logFormat->format:nullptr); curr_token; curr_token = curr_token->next) {
if (curr_token->type == Format::LFT_ADAPTATION_SUM_XACT_TIMES ||
curr_token->type == Format::LFT_ADAPTATION_ALL_XACT_TIMES ||
curr_token->type == Format::LFT_ADAPTATION_LAST_HEADER ||
exit(EXIT_FAILURE);
}
fp = fopen(argv[1], "a");
- if (fp == NULL) {
+ if (fp == nullptr) {
perror("fopen");
exit(EXIT_FAILURE);
}
- setbuf(stdout, NULL);
+ setbuf(stdout, nullptr);
/* XXX stderr should not be closed, but in order to support squid must be
* able to collect and manage modules' stderr first.
*/
fclose(fp);
rotate(argv[1], rotate_count);
fp = fopen(argv[1], "a");
- if (fp == NULL) {
+ if (fp == nullptr) {
perror("fopen");
exit(EXIT_FAILURE);
}
fclose(fp);
rotate(argv[1], rotate_count);
fp = fopen(argv[1], "a");
- if (fp == NULL) {
+ if (fp == nullptr) {
perror("fopen");
exit(EXIT_FAILURE);
}
}
}
fclose(fp);
- fp = NULL;
+ fp = nullptr;
return EXIT_SUCCESS;
}
#endif
static int opt_signal_service = FALSE;
-static char *opt_syslog_facility = NULL;
+static char *opt_syslog_facility = nullptr;
static int icpPortNumOverride = 1; /* Want to detect "-u 0" */
static int configured_once = 0;
#if MALLOC_DBG
Auth::Scheme::FreeAll();
#endif
- eventAdd("SquidTerminate", &StopEventLoop, NULL, 0, 1, false);
+ eventAdd("SquidTerminate", &StopEventLoop, nullptr, 0, 1, false);
}
void doShutdown(time_t wait);
// long options
static struct option squidOptions[] = {
- {"foreground", no_argument, 0, optForeground},
- {"kid", required_argument, 0, optKid},
- {"help", no_argument, 0, 'h'},
- {"version", no_argument, 0, 'v'},
- {0, 0, 0, 0}
+ {"foreground", no_argument, nullptr, optForeground},
+ {"kid", required_argument, nullptr, optKid},
+ {"help", no_argument, nullptr, 'h'},
+ {"version", no_argument, nullptr, 'v'},
+ {nullptr, 0, nullptr, 0}
};
// handle a command line parameter
#endif
Security::CloseLogs();
- eventAdd("mainReconfigureFinish", &mainReconfigureFinish, NULL, 0, 1,
+ eventAdd("mainReconfigureFinish", &mainReconfigureFinish, nullptr, 0, 1,
false);
}
#endif
if (Config.onoff.announce) {
- if (!eventFind(start_announce, NULL))
- eventAdd("start_announce", start_announce, NULL, 3600.0, 1);
+ if (!eventFind(start_announce, nullptr))
+ eventAdd("start_announce", start_announce, nullptr, 3600.0, 1);
} else {
- if (eventFind(start_announce, NULL))
- eventDelete(start_announce, NULL);
+ if (eventFind(start_announce, nullptr))
+ eventDelete(start_announce, nullptr);
}
reconfiguring = 0;
if ((cpid = fork()) == 0) {
/* child */
- execl(script, squid_start_script, (char *)NULL);
+ execl(script, squid_start_script, (char *)nullptr);
_exit(-1);
} else {
do {
void checkHighWater() {
if (hwater_level < level) {
hwater_level = level;
- hwater_stamp = squid_curtime ? squid_curtime : time(NULL);
+ hwater_stamp = squid_curtime ? squid_curtime : time(nullptr);
}
}
void
memPoolIterateDone(MemPoolIterator ** iter)
{
- assert(iter != NULL);
- Iterator.pool = NULL;
- *iter = NULL;
+ assert(iter != nullptr);
+ Iterator.pool = nullptr;
+ *iter = nullptr;
}
MemImplementingAllocator *
memPoolIterateNext(MemPoolIterator * iter)
{
MemImplementingAllocator *pool;
- assert(iter != NULL);
+ assert(iter != nullptr);
pool = iter->pool;
if (!pool)
- return NULL;
+ return nullptr;
iter->pool = pool->next;
return pool;
void
MemImplementingAllocator::freeOne(void *obj)
{
- assert(obj != NULL);
+ assert(obj != nullptr);
(void) VALGRIND_CHECK_MEM_IS_ADDRESSABLE(obj, obj_size);
deallocate(obj, MemPools::GetInstance().mem_idle_limit == 0);
++free_calls;
}
MemImplementingAllocator::MemImplementingAllocator(char const *aLabel, size_t aSize) : MemAllocator(aLabel),
- next(NULL),
+ next(nullptr),
alloc_calls(0),
free_calls(0),
saved_calls(0),
MemImplementingAllocator *last_pool;
- assert(aLabel != NULL && aSize);
+ assert(aLabel != nullptr && aSize);
/* Append as Last */
for (last_pool = MemPools::GetInstance().pools; last_pool && last_pool->next;)
last_pool = last_pool->next;
MemImplementingAllocator *find_pool, *prev_pool;
/* Abort if the associated pool doesn't exist */
- assert(MemPools::GetInstance().pools != NULL );
+ assert(MemPools::GetInstance().pools != nullptr );
/* Pool clean, remove it from List and free */
- for (find_pool = MemPools::GetInstance().pools, prev_pool = NULL; (find_pool && this != find_pool); find_pool = find_pool->next)
+ for (find_pool = MemPools::GetInstance().pools, prev_pool = nullptr; (find_pool && this != find_pool); find_pool = find_pool->next)
prev_pool = find_pool;
/* make sure that we found the pool to destroy */
- assert(find_pool != NULL);
+ assert(find_pool != nullptr);
if (prev_pool)
prev_pool->next = next;
* free the first chunk.
*/
inuse_count = 0;
- next = NULL;
+ next = nullptr;
pool = aPool;
if (pool->doZero)
MemPoolChunked::MemPoolChunked(const char *aLabel, size_t aSize) :
MemImplementingAllocator(aLabel, aSize), chunk_size(0),
- chunk_capacity(0), chunkCount(0), freeCache(0), nextFreeChunk(0),
- Chunks(0), allChunks(Splay<MemChunk *>())
+ chunk_capacity(0), chunkCount(0), freeCache(nullptr), nextFreeChunk(nullptr),
+ Chunks(nullptr), allChunks(Splay<MemChunk *>())
{
setChunkSize(MEM_CHUNK_SIZE);
Free = (void **)freeCache;
(void) VALGRIND_MAKE_MEM_DEFINED(Free, obj_size);
freeCache = *Free;
- *Free = NULL;
+ *Free = nullptr;
return Free;
}
/* then try perchunk freelist chain */
- if (nextFreeChunk == NULL) {
+ if (nextFreeChunk == nullptr) {
/* no chunk with frees, so create new one */
-- saved_calls; // compensate for the ++ above
createChunk();
Free = (void **)chunk->freeList;
chunk->freeList = *Free;
- *Free = NULL;
+ *Free = nullptr;
++chunk->inuse_count;
chunk->lastref = squid_curtime;
- if (chunk->freeList == NULL) {
+ if (chunk->freeList == nullptr) {
/* last free in this chunk, so remove us from perchunk freelist chain */
nextFreeChunk = chunk->nextFreeChunk;
}
newChunk = new MemChunk(this);
chunk = Chunks;
- if (chunk == NULL) { /* first chunk in pool */
+ if (chunk == nullptr) { /* first chunk in pool */
Chunks = newChunk;
return;
}
assert(meter.inuse.currentLevel() == 0);
chunk = Chunks;
- while ( (fchunk = chunk) != NULL) {
+ while ( (fchunk = chunk) != nullptr) {
chunk = chunk->next;
delete fchunk;
}
* any given Free belongs to, and stuff it into that Chunk's freelist
*/
- while ((Free = freeCache) != NULL) {
- MemChunk *chunk = NULL;
+ while ((Free = freeCache) != nullptr) {
+ MemChunk *chunk = nullptr;
chunk = const_cast<MemChunk *>(*allChunks.find(Free, memCompObjChunks));
assert(splayLastResult == 0);
assert(chunk->inuse_count > 0);
/* Recreate nextFreeChunk list from scratch */
chunk = Chunks;
- while ((freechunk = chunk->next) != NULL) {
+ while ((freechunk = chunk->next) != nullptr) {
age = squid_curtime - freechunk->lastref;
- freechunk->nextFreeChunk = NULL;
+ freechunk->nextFreeChunk = nullptr;
if (freechunk->inuse_count == 0)
if (age >= maxage) {
chunk->next = freechunk->next;
delete freechunk;
- freechunk = NULL;
+ freechunk = nullptr;
}
- if (chunk->next == NULL)
+ if (chunk->next == nullptr)
break;
chunk = chunk->next;
}
chunk = Chunks;
nextFreeChunk = chunk;
- chunk->nextFreeChunk = NULL;
+ chunk->nextFreeChunk = nullptr;
while (chunk->next) {
- chunk->next->nextFreeChunk = NULL;
+ chunk->next->nextFreeChunk = nullptr;
if (chunk->next->inuse_count < chunk_capacity) {
listTail = nextFreeChunk;
while (listTail->nextFreeChunk) {
void *
MemPoolMalloc::allocate()
{
- void *obj = NULL;
+ void *obj = nullptr;
if (!freelist.empty()) {
obj = freelist.top();
freelist.pop();
{
assert(name && size);
- if (GetPool(type) != NULL)
+ if (GetPool(type) != nullptr)
return;
GetPool(type) = memPoolCreate(name, size);
void
memFreeBuf(size_t size, void *buf)
{
- mem_type type = memFindBufSizeType(size, NULL);
+ mem_type type = memFindBufSizeType(size, nullptr);
if (type != MEM_NONE)
memFree(buf, type);
Mem::CleanIdlePools(void *)
{
MemPools::GetInstance().clean(static_cast<time_t>(clean_interval));
- eventAdd("memPoolCleanIdlePools", CleanIdlePools, NULL, clean_interval, 1);
+ eventAdd("memPoolCleanIdlePools", CleanIdlePools, nullptr, clean_interval, 1);
}
void
xfree(sortme);
- mp_stats.pool = NULL;
+ mp_stats.pool = nullptr;
mp_stats.label = "Total";
mp_stats.meter = mp_total.TheMeter;
mp_stats.obj_size = 1;
static ptrdiff_t
makeMemNodeDataOffset()
{
- mem_node *p = 0L;
+ mem_node *p = nullptr;
return ptrdiff_t(&p->data);
}
Mgr::Action::Action(const Command::Pointer &aCmd): cmd(aCmd)
{
- Must(cmd != NULL);
- Must(cmd->profile != NULL);
+ Must(cmd != nullptr);
+ Must(cmd->profile != nullptr);
}
Mgr::Action::~Action()
const Mgr::Command &
Mgr::Action::command() const
{
- Must(cmd != NULL);
+ Must(cmd != nullptr);
return *cmd;
}
if (writeHttpHeader) {
HttpReply *rep = new HttpReply;
- rep->setHeaders(Http::scOkay, NULL, contentType(), -1, squid_curtime, squid_curtime);
+ rep->setHeaders(Http::scOkay, nullptr, contentType(), -1, squid_curtime, squid_curtime);
// Allow cachemgr and other XHR scripts access to our version string
const ActionParams ¶ms = command().params;
if (params.httpOrigin.size() > 0) {
Mgr::ActionWriter::start()
{
debugs(16, 5, MYNAME);
- Must(action != NULL);
+ Must(action != nullptr);
StoreToCommWriter::start();
action->fillEntry(entry, false);
Mgr::MenuAction::dump(StoreEntry* entry)
{
debugs(16, 5, MYNAME);
- Must(entry != NULL);
+ Must(entry != nullptr);
typedef CacheManager::Menu::const_iterator Iterator;
const CacheManager::Menu& menu = CacheManager::GetInstance()->menu();
std::ostream &
operator <<(std::ostream &os, const Mgr::Command &cmd)
{
- if (cmd.profile != NULL)
+ if (cmd.profile != nullptr)
return os << *cmd.profile;
return os << "undef";
}
Mgr::CountersAction::dump(StoreEntry* entry)
{
debugs(16, 5, MYNAME);
- Must(entry != NULL);
+ Must(entry != nullptr);
DumpCountersStats(data, entry);
}
{
debugs(16, 5, MYNAME);
Must(requestId != 0);
- Must(action != NULL);
+ Must(action != nullptr);
StoreToCommWriter::start();
action->run(entry, false);
{
debugs(16, 5, conn);
Must(Comm::IsConnOpen(conn));
- Must(httpRequest != NULL);
- Must(entry != NULL);
+ Must(httpRequest != nullptr);
+ Must(entry != nullptr);
HTTPMSGLOCK(httpRequest);
entry->lock("Mgr::Forwarder");
Mgr::Forwarder::swanSong()
{
if (Comm::IsConnOpen(conn)) {
- if (closer != NULL) {
+ if (closer != nullptr) {
comm_remove_close_handler(conn->fd, closer);
- closer = NULL;
+ closer = nullptr;
}
conn->close();
}
- conn = NULL;
+ conn = nullptr;
Ipc::Forwarder::swanSong();
}
void
Mgr::Forwarder::handleException(const std::exception &e)
{
- if (entry != NULL && httpRequest != NULL && Comm::IsConnOpen(conn))
+ if (entry != nullptr && httpRequest != nullptr && Comm::IsConnOpen(conn))
sendError(new ErrorState(ERR_INVALID_RESP, Http::scInternalServerError, httpRequest, ale));
Ipc::Forwarder::handleException(e);
}
Mgr::Forwarder::sendError(ErrorState *error)
{
debugs(16, 3, MYNAME);
- Must(error != NULL);
- Must(entry != NULL);
- Must(httpRequest != NULL);
+ Must(error != nullptr);
+ Must(entry != nullptr);
+ Must(httpRequest != nullptr);
entry->buffer();
entry->replaceHttpReply(error->BuildHttpReply());
Mgr::FunAction::FunAction(const Command::Pointer &aCmd, OBJH* aHandler):
Action(aCmd), handler(aHandler)
{
- Must(handler != NULL);
+ Must(handler != nullptr);
debugs(16, 5, MYNAME);
}
Mgr::FunAction::dump(StoreEntry* entry)
{
debugs(16, 5, MYNAME);
- Must(entry != NULL);
+ Must(entry != nullptr);
if (UsingSmp())
storeAppendPrintf(entry, "by kid%d {\n", KidIdentifier);
handler(entry);
Mgr::InfoAction::dump(StoreEntry* entry)
{
debugs(16, 5, MYNAME);
- Must(entry != NULL);
+ Must(entry != nullptr);
#if XMALLOC_STATISTICS
if (UsingSmp())
void
Mgr::Inquirer::removeCloseHandler()
{
- if (closer != NULL) {
+ if (closer != nullptr) {
comm_remove_close_handler(conn->fd, closer);
- closer = NULL;
+ closer = nullptr;
}
}
debugs(16, 5, MYNAME);
Ipc::Inquirer::start();
Must(Comm::IsConnOpen(conn));
- Must(aggrAction != NULL);
+ Must(aggrAction != nullptr);
std::unique_ptr<MemBuf> replyBuf;
if (strands.empty()) {
replyBuf.reset(reply->pack());
} else {
std::unique_ptr<HttpReply> reply(new HttpReply);
- reply->setHeaders(Http::scOkay, NULL, "text/plain", -1, squid_curtime, squid_curtime);
+ reply->setHeaders(Http::scOkay, nullptr, "text/plain", -1, squid_curtime, squid_curtime);
reply->header.putStr(Http::HdrType::CONNECTION, "close"); // until we chunk response
replyBuf.reset(reply->pack());
}
Mgr::Inquirer::noteWroteHeader(const CommIoCbParams& params)
{
debugs(16, 5, MYNAME);
- writer = NULL;
+ writer = nullptr;
Must(params.flag == Comm::OK);
Must(params.conn.getRaw() == conn.getRaw());
Must(params.size != 0);
if (!strands.empty() && aggrAction->aggregatable()) {
removeCloseHandler();
AsyncJob::Start(new ActionWriter(aggrAction, conn));
- conn = NULL; // should not close because we passed it to ActionWriter
+ conn = nullptr; // should not close because we passed it to ActionWriter
}
}
QueryParam::Pointer processesParam = aParams.get("processes");
QueryParam::Pointer workersParam = aParams.get("workers");
- if (processesParam == NULL || workersParam == NULL) {
- if (processesParam != NULL) {
+ if (processesParam == nullptr || workersParam == nullptr) {
+ if (processesParam != nullptr) {
IntParam* param = dynamic_cast<IntParam*>(processesParam.getRaw());
- if (param != NULL && param->type == QueryParam::ptInt) {
+ if (param != nullptr && param->type == QueryParam::ptInt) {
const std::vector<int>& processes = param->value();
for (Ipc::StrandCoords::const_iterator iter = aStrands.begin();
iter != aStrands.end(); ++iter) {
sc.push_back(*iter);
}
}
- } else if (workersParam != NULL) {
+ } else if (workersParam != nullptr) {
IntParam* param = dynamic_cast<IntParam*>(workersParam.getRaw());
- if (param != NULL && param->type == QueryParam::ptInt) {
+ if (param != nullptr && param->type == QueryParam::ptInt) {
const std::vector<int>& workers = param->value();
for (int i = 0; i < (int)aStrands.size(); ++i) {
if (std::find(workers.begin(), workers.end(), i + 1) != workers.end())
Mgr::IntervalAction::dump(StoreEntry* entry)
{
debugs(16, 5, MYNAME);
- Must(entry != NULL);
+ Must(entry != nullptr);
DumpAvgStat(data, entry);
}
Mgr::IoAction::dump(StoreEntry* entry)
{
debugs(16, 5, MYNAME);
- Must(entry != NULL);
+ Must(entry != nullptr);
DumpIoStats(data, entry);
}
{
Must(name.size() != 0);
Params::const_iterator pos = find(name);
- return (pos == params.end() ? NULL : pos->second);
+ return (pos == params.end() ? nullptr : pos->second);
}
void
for (Params::const_iterator iter = params.begin(); iter != params.end(); ++iter) {
Must(iter->first.size() != 0);
msg.putString(iter->first);
- Must(iter->second != NULL);
+ Must(iter->second != nullptr);
iter->second->pack(msg);
}
}
throw TexcHere("unknown parameter type");
break;
}
- return NULL;
+ return nullptr;
}
bool
Mgr::Response::hasAction() const
{
- return action != NULL;
+ return action != nullptr;
}
const Mgr::Action&
Mgr::ServiceTimesAction::dump(StoreEntry* entry)
{
debugs(16, 5, MYNAME);
- Must(entry != NULL);
+ Must(entry != nullptr);
DumpServiceTimesStats(data, entry);
}
Mgr::StoreIoAction::dump(StoreEntry* entry)
{
debugs(16, 5, MYNAME);
- Must(entry != NULL);
+ Must(entry != nullptr);
storeAppendPrintf(entry, "Store IO Interface Stats\n");
storeAppendPrintf(entry, "create.calls %.0f\n", data.create_calls);
storeAppendPrintf(entry, "create.select_fail %.0f\n", data.create_select_fail);
Mgr::StoreToCommWriter::StoreToCommWriter(const Comm::ConnectionPointer &conn, StoreEntry* anEntry):
AsyncJob("Mgr::StoreToCommWriter"),
- clientConnection(conn), entry(anEntry), sc(NULL), writeOffset(0), closer(NULL)
+ clientConnection(conn), entry(anEntry), sc(nullptr), writeOffset(0), closer(nullptr)
{
debugs(16, 6, clientConnection);
closer = asyncCall(16, 5, "Mgr::StoreToCommWriter::noteCommClosed",
Mgr::StoreToCommWriter::close()
{
if (Comm::IsConnOpen(clientConnection)) {
- if (closer != NULL) {
+ if (closer != nullptr) {
comm_remove_close_handler(clientConnection->fd, closer);
- closer = NULL;
+ closer = nullptr;
}
clientConnection->close();
}
{
debugs(16, 6, MYNAME);
Must(Comm::IsConnOpen(clientConnection));
- Must(entry != NULL);
+ Must(entry != nullptr);
AsyncCall::Pointer call = asyncCall(16, 4, "StoreToCommWriter::Abort", cbdataDialer(&StoreToCommWriter::HandleStoreAbort, this));
entry->registerAbortCallback(call);
sc = storeClientListAdd(entry, this);
- Must(sc != NULL);
+ Must(sc != nullptr);
// initiate the receive-from-store, write-to-comm sequence
scheduleStoreCopy();
Mgr::StoreToCommWriter::scheduleStoreCopy()
{
debugs(16, 6, MYNAME);
- Must(entry != NULL);
- Must(sc != NULL);
+ Must(entry != nullptr);
+ Must(sc != nullptr);
StoreIOBuffer readBuf(sizeof(buffer), writeOffset, buffer);
storeClientCopy(sc, entry, readBuf, &NoteStoreCopied, this);
}
void
Mgr::StoreToCommWriter::NoteStoreCopied(void* data, StoreIOBuffer ioBuf)
{
- Must(data != NULL);
+ Must(data != nullptr);
// make sync Store call async to get async call protections and features
StoreToCommWriter* writer = static_cast<StoreToCommWriter*>(data);
typedef UnaryMemFunT<StoreToCommWriter, StoreIOBuffer> MyDialer;
{
debugs(16, 6, MYNAME);
Must(Comm::IsConnOpen(clientConnection));
- Must(ioBuf.data != NULL);
+ Must(ioBuf.data != nullptr);
// write filled buffer
typedef CommCbMemFunT<StoreToCommWriter, CommIoCbParams> MyDialer;
AsyncCall::Pointer writer =
asyncCall(16, 5, "Mgr::StoreToCommWriter::noteCommWrote",
MyDialer(this, &StoreToCommWriter::noteCommWrote));
- Comm::Write(clientConnection, ioBuf.data, ioBuf.length, writer, NULL);
+ Comm::Write(clientConnection, ioBuf.data, ioBuf.length, writer, nullptr);
}
void
{
debugs(16, 6, MYNAME);
Must(params.flag == Comm::OK);
- Must(clientConnection != NULL && params.fd == clientConnection->fd);
+ Must(clientConnection != nullptr && params.fd == clientConnection->fd);
Must(params.size != 0);
writeOffset += params.size;
if (!doneAll())
Mgr::StoreToCommWriter::swanSong()
{
debugs(16, 6, MYNAME);
- if (entry != NULL) {
- if (sc != NULL) {
+ if (entry != nullptr) {
+ if (sc != nullptr) {
storeUnregister(sc, entry, this);
- sc = NULL;
+ sc = nullptr;
}
entry->unregisterAbortCallback("StoreToCommWriter done");
entry->unlock("Mgr::StoreToCommWriter::swanSong");
- entry = NULL;
+ entry = nullptr;
}
close();
}
MimeEntry *next;
};
-static MimeEntry *MimeTable = NULL;
+static MimeEntry *MimeTable = nullptr;
static MimeEntry **MimeTableTail = &MimeTable;
static MimeEntry *
char *name = xstrdup(fn);
do {
- t = NULL;
+ t = nullptr;
for (m = MimeTable; m; m = m->next) {
- if (regexec(&m->compiled_pattern, name, 0, 0, 0) == 0)
+ if (regexec(&m->compiled_pattern, name, 0, nullptr, 0) == 0)
break;
}
if (!skip_encodings)
(void) 0;
- else if (m == NULL)
+ else if (m == nullptr)
(void) 0;
else if (strcmp(m->content_type, dash_str))
(void) 0;
*t = '\0';
} else {
/* What? A encoding without a extension? */
- m = NULL;
+ m = nullptr;
}
}
} while (t);
{
MimeEntry *m = mimeGetEntry(fn, 1);
- if (m == NULL)
- return NULL;
+ if (m == nullptr)
+ return nullptr;
if (!strcmp(m->content_type, dash_str))
- return NULL;
+ return nullptr;
return m->content_type;
}
{
MimeEntry *m = mimeGetEntry(fn, 0);
- if (m == NULL)
- return NULL;
+ if (m == nullptr)
+ return nullptr;
if (!strcmp(m->content_encoding, dash_str))
- return NULL;
+ return nullptr;
return m->content_encoding;
}
mimeGetViewOption(const char *fn)
{
MimeEntry *m = mimeGetEntry(fn, 0);
- return m != 0 ? m->view_option : false;
+ return m != nullptr ? m->view_option : false;
}
/* Initializes/reloads the mime table
MimeEntry *m;
int re_flags = REG_EXTENDED | REG_NOSUB | REG_ICASE;
- if (filename == NULL)
+ if (filename == nullptr)
return;
- if ((fp = fopen(filename, "r")) == NULL) {
+ if ((fp = fopen(filename, "r")) == nullptr) {
int xerrno = errno;
debugs(25, DBG_IMPORTANT, "mimeInit: " << filename << ": " << xstrerr(xerrno));
return;
xstrncpy(chopbuf, buf, BUFSIZ);
- if ((pattern = strtok(chopbuf, w_space)) == NULL) {
+ if ((pattern = strtok(chopbuf, w_space)) == nullptr) {
debugs(25, DBG_IMPORTANT, "ERROR: mimeInit: parse failure: '" << buf << "'");
continue;
}
- if ((type = strtok(NULL, w_space)) == NULL) {
+ if ((type = strtok(nullptr, w_space)) == nullptr) {
debugs(25, DBG_IMPORTANT, "ERROR: mimeInit: parse failure: '" << buf << "'");
continue;
}
- if ((icon = strtok(NULL, w_space)) == NULL) {
+ if ((icon = strtok(nullptr, w_space)) == nullptr) {
debugs(25, DBG_IMPORTANT, "ERROR: mimeInit: parse failure: '" << buf << "'");
continue;
}
- if ((encoding = strtok(NULL, w_space)) == NULL) {
+ if ((encoding = strtok(nullptr, w_space)) == nullptr) {
debugs(25, DBG_IMPORTANT, "ERROR: mimeInit: parse failure: '" << buf << "'");
continue;
}
- if ((mode = strtok(NULL, w_space)) == NULL) {
+ if ((mode = strtok(nullptr, w_space)) == nullptr) {
debugs(25, DBG_IMPORTANT, "ERROR: mimeInit: parse failure: '" << buf << "'");
continue;
}
download_option = 0;
view_option = 0;
- while ((option = strtok(NULL, w_space)) != NULL) {
+ while ((option = strtok(nullptr, w_space)) != nullptr) {
if (!strcmp(option, "+download"))
download_option = 1;
else if (!strcmp(option, "+view"))
fclose(fp);
- for (m = MimeTable; m != NULL; m = m->next)
+ for (m = MimeTable; m != nullptr; m = m->next)
m->theIcon.load();
debugs(25, Important(28), "Finished loading MIME types and icons.");
}
{
const char *type = mimeGetContentType(icon_.c_str());
- if (type == NULL)
+ if (type == nullptr)
fatal("Unknown icon format while reading mime.conf\n");
if (const auto e = storeGetPublic(url_, Http::METHOD_GET)) {
HttpReplyPointer reply(new HttpReply);
if (status == Http::scNoContent)
- reply->setHeaders(status, NULL, NULL, 0, -1, -1);
+ reply->setHeaders(status, nullptr, nullptr, 0, -1, -1);
else
- reply->setHeaders(status, NULL, mimeGetContentType(icon_.c_str()), sb.st_size, sb.st_mtime, -1);
+ reply->setHeaders(status, nullptr, mimeGetContentType(icon_.c_str()), sb.st_size, sb.st_mtime, -1);
reply->cache_control = new HttpHdrCc();
reply->cache_control->maxAge(86400);
reply->header.putCc(reply->cache_control);
content_encoding(xstrdup(aContentEncoding)),
view_option(optionViewEnable),
download_option(optionDownloadEnable),
- theIcon(anIconName), next(NULL)
+ theIcon(anIconName), next(nullptr)
{
if (!strcasecmp(aTransferMode, "ascii"))
transfer_mode = 'A';
#ifdef IP_MULTICAST_TTL
struct ip_mreq mr;
- if (ia == NULL) {
+ if (ia == nullptr) {
debugs(7, DBG_CRITICAL, "ERROR: comm_join_mcast_groups: Unknown host");
return;
}
static unsigned short echo_port;
static int NLateReplies = 0;
-static CachePeer *first_ping = NULL;
+static CachePeer *first_ping = nullptr;
const char *
neighborTypeStr(const CachePeer * p)
{
int j;
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
debugs(15, 3, "whichPeer: from " << from);
for (p = Config.peers; p; p = p->next) {
}
}
- return NULL;
+ return nullptr;
}
peer_t
neighborType(const CachePeer * p, const AnyP::Uri &url)
{
- const NeighborTypeDomainList *d = NULL;
+ const NeighborTypeDomainList *d = nullptr;
for (d = p->typelist; d; d = d->next) {
if (0 == matchDomainName(url.host(), d->domain))
{
assert(ps);
HttpRequest *request = ps->request;
- assert(request != NULL);
+ assert(request != nullptr);
if (neighborType(p, request->url) == PEER_SIBLING) {
#if PEER_MULTICAST_SIBLINGS
if (p->options.originserver && request->method == Http::METHOD_CONNECT && request->url.port() != p->http_port)
return false;
- if (p->access == NULL)
+ if (p->access == nullptr)
return true;
- ACLFilledChecklist checklist(p->access, request, NULL);
+ ACLFilledChecklist checklist(p->access, request, nullptr);
checklist.al = ps->al;
if (ps->al && ps->al->reply) {
checklist.reply = ps->al->reply.getRaw();
int
neighborsCount(PeerSelector *ps)
{
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
int count = 0;
for (p = Config.peers; p; p = p->next)
assert(ps);
HttpRequest *request = ps->request;
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
for (p = Config.peers; p; p = p->next) {
if (!neighborUp(p))
HttpRequest *request = ps->request;
CachePeer *p;
- CachePeer *q = NULL;
+ CachePeer *q = nullptr;
for (p = Config.peers; p; p = p->next) {
if (!p->options.roundrobin)
HttpRequest *request = ps->request;
CachePeer *p;
- CachePeer *q = NULL;
+ CachePeer *q = nullptr;
int weighted_rtt;
for (p = Config.peers; p; p = p->next) {
{
static bool event_added = false;
if (!event_added) {
- peerClearRRLoop(NULL);
+ peerClearRRLoop(nullptr);
event_added=true;
}
}
void
peerClearRR()
{
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
for (p = Config.peers; p; p = p->next) {
p->rr_count = 1;
}
assert(ps);
HttpRequest *request = ps->request;
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
for (p = Config.peers; p; p = p->next) {
if (neighborType(p, request->url) != PEER_PARENT)
}
debugs(15, 3, "getDefaultParent: returning NULL");
- return NULL;
+ return nullptr;
}
CachePeer *
static void
neighborRemove(CachePeer * target)
{
- CachePeer *p = NULL;
- CachePeer **P = NULL;
+ CachePeer *p = nullptr;
+ CachePeer **P = nullptr;
p = Config.peers;
P = &Config.peers;
if (p) {
*P = p->next;
- p->next = NULL;
+ p->next = nullptr;
delete p;
--Config.npeers;
}
void
neighbors_init(void)
{
- struct servent *sep = NULL;
+ struct servent *sep = nullptr;
const char *me = getMyHostname();
- CachePeer *thisPeer = NULL;
- CachePeer *next = NULL;
+ CachePeer *thisPeer = nullptr;
+ CachePeer *next = nullptr;
neighborsRegisterWithCacheManager();
if (0 != strcmp(thisPeer->host, me))
continue;
- for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
+ for (AnyP::PortCfgPointer s = HttpPortList; s != nullptr; s = s->next) {
if (thisPeer->http_port != s->s.port())
continue;
{
const char *url = entry->url();
MemObject *mem = entry->mem_obj;
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
int i;
int reqnum = 0;
int flags;
int sibling_timeout = 0, sibling_exprep = 0;
int mcast_timeout = 0, mcast_exprep = 0;
- if (Config.peers == NULL)
+ if (Config.peers == nullptr)
return 0;
assert(!entry->hasDisk());
reqnum = icpSetCacheKey((const cache_key *)entry->key);
for (i = 0, p = first_ping; i++ < Config.npeers; p = p->next) {
- if (p == NULL)
+ if (p == nullptr)
p = Config.peers;
debugs(15, 5, "neighborsUdpPing: Peer " << p->host);
p->stats.probe_start = squid_curtime;
}
- if ((first_ping = first_ping->next) == NULL)
+ if ((first_ping = first_ping->next) == nullptr)
first_ping = Config.peers;
/*
#if USE_CACHE_DIGESTS
assert(ps);
HttpRequest *request = ps->request;
- const cache_key *key = request ? storeKeyPublicByRequest(request) : NULL;
+ const cache_key *key = request ? storeKeyPublicByRequest(request) : nullptr;
assert(p);
assert(request);
debugs(15, 5, "peerDigestLookup: peer " << p->host);
CachePeer *
neighborsDigestSelect(PeerSelector *ps)
{
- CachePeer *best_p = NULL;
+ CachePeer *best_p = nullptr;
#if USE_CACHE_DIGESTS
assert(ps);
HttpRequest *request = ps->request;
int i;
if (!request->flags.hierarchical)
- return NULL;
+ return nullptr;
storeKeyPublicByRequest(request);
static void
neighborCountIgnored(CachePeer * p)
{
- if (p == NULL)
+ if (p == nullptr)
return;
++ p->stats.ignored_replies;
++NLateReplies;
}
-static CachePeer *non_peers = NULL;
+static CachePeer *non_peers = nullptr;
static void
neighborIgnoreNonPeer(const Ip::Address &from, icp_opcode opcode)
break;
}
- if (np == NULL) {
+ if (np == nullptr) {
np = new CachePeer;
np->in_addr = from;
np->icp.port = from.port();
static int
ignoreMulticastReply(CachePeer * p, PeerSelector * ps)
{
- if (p == NULL)
+ if (p == nullptr)
return 0;
if (!p->options.mcast_responder)
void
neighborsUdpAck(const cache_key * key, icp_common_t * header, const Ip::Address &from)
{
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
StoreEntry *entry;
- MemObject *mem = NULL;
+ MemObject *mem = nullptr;
peer_t ntype = PEER_NONE;
icp_opcode opcode = (icp_opcode) header->opcode;
neighborUpdateRtt(p, mem);
/* Does the entry exist? */
- if (NULL == entry) {
+ if (nullptr == entry) {
debugs(12, 3, "neighborsUdpAck: Cache key '" << storeKeyText(key) << "' not found");
neighborCountIgnored(p);
return;
return;
}
- if (mem == NULL) {
+ if (mem == nullptr) {
debugs(15, 2, "Ignoring " << opcode_d << " for missing mem_obj: " << storeKeyText(key));
neighborCountIgnored(p);
return;
if (ignoreMulticastReply(p, mem->ircb_data)) {
neighborCountIgnored(p);
} else if (opcode == ICP_MISS) {
- if (p == NULL) {
+ if (p == nullptr) {
neighborIgnoreNonPeer(from, opcode);
} else {
mem->ping_reply_callback(p, ntype, AnyP::PROTO_ICP, header, mem->ircb_data);
}
} else if (opcode == ICP_HIT) {
- if (p == NULL) {
+ if (p == nullptr) {
neighborIgnoreNonPeer(from, opcode);
} else {
header->opcode = ICP_HIT;
mem->ping_reply_callback(p, ntype, AnyP::PROTO_ICP, header, mem->ircb_data);
}
} else if (opcode == ICP_DECHO) {
- if (p == NULL) {
+ if (p == nullptr) {
neighborIgnoreNonPeer(from, opcode);
} else if (ntype == PEER_SIBLING) {
debug_trap("neighborsUdpAck: Found non-ICP cache as SIBLING\n");
debugs(15, DBG_IMPORTANT, "Unsolicited SECHO from " << from);
}
} else if (opcode == ICP_DENIED) {
- if (p == NULL) {
+ if (p == nullptr) {
neighborIgnoreNonPeer(from, opcode);
} else if (p->stats.pings_acked > 100) {
if (100 * p->icp.counts[ICP_DENIED] / p->stats.pings_acked > 95) {
debugs(15, DBG_CRITICAL, "95%% of replies from '" << p->host << "' are UDP_DENIED");
debugs(15, DBG_CRITICAL, "Disabling '" << p->host << "', please check your configuration.");
neighborRemove(p);
- p = NULL;
+ p = nullptr;
} else {
neighborCountIgnored(p);
}
CachePeer *
peerFindByName(const char *name)
{
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
for (p = Config.peers; p; p = p->next) {
if (!strcasecmp(name, p->name))
CachePeer *
peerFindByNameAndPort(const char *name, unsigned short port)
{
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
for (p = Config.peers; p; p = p->next) {
if (strcasecmp(name, p->name))
p->n_addresses = 0;
- if (ia == NULL) {
+ if (ia == nullptr) {
debugs(0, DBG_CRITICAL, "WARNING: DNS lookup for '" << p->host << "' failed!");
return;
}
static void
peerRefreshDNS(void *data)
{
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
- if (eventFind(peerRefreshDNS, NULL))
- eventDelete(peerRefreshDNS, NULL);
+ if (eventFind(peerRefreshDNS, nullptr))
+ eventDelete(peerRefreshDNS, nullptr);
if (!data && 0 == stat5minClientRequests()) {
/* no recent client traffic, wait a bit */
- eventAddIsh("peerRefreshDNS", peerRefreshDNS, NULL, 180.0, 1);
+ eventAddIsh("peerRefreshDNS", peerRefreshDNS, nullptr, 180.0, 1);
return;
}
ipcache_nbgethostbyname(p->host, peerDNSConfigure, p);
/* Reconfigure the peers every hour */
- eventAddIsh("peerRefreshDNS", peerRefreshDNS, NULL, 3600.0, 1);
+ eventAddIsh("peerRefreshDNS", peerRefreshDNS, nullptr, 3600.0, 1);
}
static void
conn->remote = p->addresses[i];
conn->remote.port(p->http_port);
conn->setPeer(p);
- getOutgoingAddress(NULL, conn);
+ getOutgoingAddress(nullptr, conn);
++ p->testing_now;
char ntoabuf[MAX_IPSTRLEN];
int i;
- if (peers == NULL)
+ if (peers == nullptr)
storeAppendPrintf(sentry, "There are no neighbors installed.\n");
for (CachePeer *e = peers; e; e = e->next) {
- assert(e->host != NULL);
+ assert(e->host != nullptr);
storeAppendPrintf(sentry, "\n%-11.11s: %s\n",
neighborTypeStr(e),
e->name);
neighborsHtcpReply(const cache_key * key, HtcpReplyData * htcp, const Ip::Address &from)
{
StoreEntry *e = Store::Root().findCallbackXXX(key);
- MemObject *mem = NULL;
+ MemObject *mem = nullptr;
CachePeer *p;
peer_t ntype = PEER_NONE;
debugs(15, 6, "neighborsHtcpReply: " <<
(htcp->hit ? "HIT" : "MISS") << " " <<
storeKeyText(key) );
- if (NULL != e)
+ if (nullptr != e)
mem = e->mem_obj;
if ((p = whichPeer(from)))
neighborAliveHtcp(p, mem, htcp);
/* Does the entry exist? */
- if (NULL == e) {
+ if (nullptr == e) {
debugs(12, 3, "neighyborsHtcpReply: Cache key '" << storeKeyText(key) << "' not found");
neighborCountIgnored(p);
return;
return;
}
- if (mem == NULL) {
+ if (mem == nullptr) {
debugs(15, 2, "Ignoring reply for missing mem_obj: " << storeKeyText(key));
neighborCountIgnored(p);
return;
#define PCONN_FDS_SZ 8 /* pconn set size, increase for better memcache hit rate */
//TODO: re-attach to MemPools. WAS: static MemAllocator *pconn_fds_pool = NULL;
-PconnModule * PconnModule::instance = NULL;
+PconnModule * PconnModule::instance = nullptr;
CBDATA_CLASS_INIT(IdleConnList);
/* ========== IdleConnList ============================================ */
{
//Initialize hash_link members
key = xstrdup(aKey);
- next = NULL;
+ next = nullptr;
theList_ = new Comm::ConnectionPointer[capacity_];
parent_->unlinkList(this);
if (size_) {
- parent_ = NULL; // prevent reentrant notifications and deletions
+ parent_ = nullptr; // prevent reentrant notifications and deletions
closeN(size_);
}
// shuffle the remaining entries to fill the new gap.
for (; index < size_ - 1; ++index)
theList_[index] = theList_[index + 1];
- theList_[--size_] = NULL;
+ theList_[--size_] = nullptr;
if (parent_) {
parent_->noteConnectionRemoved();
debugs(48, 2, "Closing all entries.");
while (size_ > 0) {
const Comm::ConnectionPointer conn = theList_[--size_];
- theList_[size_] = NULL;
+ theList_[size_] = nullptr;
clearHandlers(conn);
conn->close();
if (parent_)
// ensure the first N entries are closed
for (index = 0; index < n; ++index) {
const Comm::ConnectionPointer conn = theList_[index];
- theList_[index] = NULL;
+ theList_[index] = nullptr;
clearHandlers(conn);
conn->close();
if (parent_)
}
// ensure the last N entries are unset
while (index < ((size_t)size_)) {
- theList_[index] = NULL;
+ theList_[index] = nullptr;
++index;
}
size_ -= n;
// our connection timeout handler is scheduled to run already. unsafe for now.
// TODO: cancel the pending timeout callback and allow re-use of the conn.
- if (fd_table[theList_[i]->fd].timeoutHandler == NULL)
+ if (fd_table[theList_[i]->fd].timeoutHandler == nullptr)
continue;
// finally, a match. pop and return it.
// our connection timeout handler is scheduled to run already. unsafe for now.
// TODO: cancel the pending timeout callback and allow re-use of the conn.
- if (fd_table[theList_[i]->fd].timeoutHandler == NULL)
+ if (fd_table[theList_[i]->fd].timeoutHandler == nullptr)
continue;
// finally, a match. pop and return it.
/* ========== PconnPool PUBLIC FUNCTIONS ============================================ */
PconnPool::PconnPool(const char *aDescr, const CbcPointer<PeerPoolMgr> &aMgr):
- table(NULL), descr(aDescr),
+ table(nullptr), descr(aDescr),
mgr(aMgr),
theCount(0)
{
PconnModule::GetInstance()->remove(this);
hashFreeItems(table, &DeleteIdleConnList);
hashFreeMemory(table);
- descr = NULL;
+ descr = nullptr;
}
void
const char *aKey = key(conn, domain);
IdleConnList *list = (IdleConnList *) hash_lookup(table, aKey);
- if (list == NULL) {
+ if (list == nullptr) {
list = new IdleConnList(aKey, this);
debugs(48, 3, "new IdleConnList for {" << hashKeyStr(list) << "}" );
hash_join(table, list);
const char * aKey = key(dest, domain);
IdleConnList *list = (IdleConnList *)hash_lookup(table, aKey);
- if (list == NULL) {
+ if (list == nullptr) {
debugs(48, 3, "lookup for key {" << aKey << "} failed.");
// failure notifications resume standby conn creation after fdUsageHigh
notifyManager("pop lookup failure");
PconnModule *
PconnModule::GetInstance()
{
- if (instance == NULL)
+ if (instance == nullptr)
instance = new PconnModule;
return instance;
DigestFetchState::DigestFetchState(PeerDigest *aPd, HttpRequest *req) :
pd(cbdataReference(aPd)),
- entry(NULL),
- old_entry(NULL),
- sc(NULL),
- old_sc(NULL),
+ entry(nullptr),
+ old_entry(nullptr),
+ sc(nullptr),
+ old_sc(nullptr),
request(req),
offset(0),
mask_offset(0),
storeUnregister(sc, entry, this);
entry->unlock("DigestFetchState destructed");
- entry = NULL;
+ entry = nullptr;
HTTPMSGUNLOCK(request);
- assert(pd == NULL);
+ assert(pd == nullptr);
}
/* allocate new peer digest, call Init, and lock everything */
{
CachePeer *p = pd->peer;
StoreEntry *e, *old_e;
- char *url = NULL;
+ char *url = nullptr;
HttpRequest *req;
StoreIOBuffer tempBuffer;
- pd->req_result = NULL;
+ pd->req_result = nullptr;
pd->flags.requested = true;
/* compute future request components */
fetch->entry = fetch->old_entry;
- fetch->old_entry = NULL;
+ fetch->old_entry = nullptr;
/* preserve request -- we need its size to update counters */
/* requestUnlink(r); */
storeUnregister(fetch->old_sc, fetch->old_entry, fetch);
fetch->old_entry->releaseRequest();
fetch->old_entry->unlock("peerDigestFetchReply 200");
- fetch->old_entry = NULL;
+ fetch->old_entry = nullptr;
}
} else {
/* some kind of a bug */
if (peerDigestSetCBlock(pd, buf)) {
/* XXX: soon we will have variable header size */
/* switch to CD buffer and fetch digest guts */
- buf = NULL;
+ buf = nullptr;
assert(pd->cd->mask);
fetch->state = DIGEST_READ_MASK;
return StoreDigestCBlockSize;
/* NOTE! buf points to the middle of pd->cd->mask! */
- if (peerDigestFetchedEnough(fetch, NULL, size, "peerDigestSwapInMask"))
+ if (peerDigestFetchedEnough(fetch, nullptr, size, "peerDigestSwapInMask"))
return -1;
fetch->mask_offset += size;
debugs(72, 2, "peerDigestSwapInMask: Done! Got " <<
fetch->mask_offset << ", expected " << pd->cd->mask_size);
assert(fetch->mask_offset == pd->cd->mask_size);
- assert(peerDigestFetchedEnough(fetch, NULL, 0, "peerDigestSwapInMask"));
+ assert(peerDigestFetchedEnough(fetch, nullptr, 0, "peerDigestSwapInMask"));
return -1; /* XXX! */
}
static const SBuf hostUnknown("<unknown>"); // peer host (if any)
SBuf host = hostUnknown;
- PeerDigest *pd = NULL;
- const char *reason = NULL; /* reason for completion */
- const char *no_bug = NULL; /* successful completion if set */
+ PeerDigest *pd = nullptr;
+ const char *reason = nullptr; /* reason for completion */
+ const char *no_bug = nullptr; /* successful completion if set */
const int pdcb_valid = cbdataReferenceValid(fetch->pd);
const int pcb_valid = cbdataReferenceValid(fetch->pd->peer);
assert(pdcb_valid && pcb_valid);
}
- return reason != NULL;
+ return reason != nullptr;
}
/* call this when all callback data is valid and fetch must be stopped but
storeUnregister(fetch->old_sc, fetch->old_entry, fetch);
fetch->old_entry->releaseRequest();
fetch->old_entry->unlock("peerDigestFetchFinish old");
- fetch->old_entry = NULL;
+ fetch->old_entry = nullptr;
}
/* update global stats */
krb5_context context;
krb5_ccache cc;
} kparam = {
- NULL, NULL
+ nullptr, nullptr
};
/*
if (kparam.context) {
if (kparam.cc)
krb5_cc_destroy(kparam.context, kparam.cc);
- kparam.cc = NULL;
+ kparam.cc = nullptr;
krb5_free_context(kparam.context);
- kparam.context = NULL;
+ kparam.context = nullptr;
}
}
#define MAX_RENEW_TIME "365d"
#define DEFAULT_SKEW (krb5_deltat) 600
- static char *keytab_filename = NULL, *principal_name = NULL;
- static krb5_keytab keytab = 0;
+ static char *keytab_filename = nullptr, *principal_name = nullptr;
+ static krb5_keytab keytab = nullptr;
static krb5_keytab_entry entry;
static krb5_kt_cursor cursor;
- static krb5_creds *creds = NULL;
+ static krb5_creds *creds = nullptr;
#if USE_HEIMDAL_KRB5 && !HAVE_KRB5_GET_RENEWED_CREDS
static krb5_creds creds2;
#endif
- static krb5_principal principal = NULL;
+ static krb5_principal principal = nullptr;
static krb5_deltat skew;
#if HAVE_KRB5_GET_INIT_CREDS_OPT_ALLOC
* Check if credentials need to be renewed
*/
if (creds &&
- (creds->times.endtime - time(0) > skew) &&
- (creds->times.renew_till - time(0) > 2 * skew)) {
- if (creds->times.endtime - time(0) < 2 * skew) {
+ (creds->times.endtime - time(nullptr) > skew) &&
+ (creds->times.renew_till - time(nullptr) > 2 * skew)) {
+ if (creds->times.endtime - time(nullptr) < 2 * skew) {
#if HAVE_KRB5_GET_RENEWED_CREDS
/* renew ticket */
code =
krb5_get_renewed_creds(kparam.context, creds, principal,
- kparam.cc, NULL);
+ kparam.cc, nullptr);
#else
/* renew ticket */
flags.i = 0;
if (code) {
if (code == KRB5KRB_AP_ERR_TKT_EXPIRED) {
krb5_free_creds(kparam.context, creds);
- creds = NULL;
+ creds = nullptr;
/* this can happen because of clock skew */
goto restart;
}
return (1);
}
code =
- profile_get_integer(profile, "libdefaults", "clockskew", 0,
+ profile_get_integer(profile, "libdefaults", "clockskew", nullptr,
5 * 60, &skew);
if (profile)
profile_release(profile);
krb5_get_init_creds_opt_set_renew_life(options, rlife);
code =
krb5_get_init_creds_keytab(kparam.context, creds, principal,
- keytab, 0, NULL, options);
+ keytab, 0, nullptr, options);
#if HAVE_KRB5_GET_INIT_CREDS_FREE_CONTEXT
krb5_get_init_creds_opt_free(kparam.context, options);
#else
gss_buffer_desc service = GSS_C_EMPTY_BUFFER;
gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
- char *token = NULL;
+ char *token = nullptr;
- setbuf(stdout, NULL);
- setbuf(stdin, NULL);
+ setbuf(stdout, nullptr);
+ setbuf(stdin, nullptr);
if (!proxy) {
debugs(11, 5, "Error : No proxy server name");
- return NULL;
+ return nullptr;
}
if (!(flags & PEER_PROXY_NEGOTIATE_NOKEYTAB)) {
"Creating credential cache for " << principal_name);
else
debugs(11, 5, "Creating credential cache");
- rc = krb5_create_cache(NULL, principal_name);
+ rc = krb5_create_cache(nullptr, principal_name);
if (rc) {
debugs(11, 5, "Error : Failed to create Kerberos cache");
krb5_cleanup();
- return NULL;
+ return nullptr;
}
}
0,
0,
GSS_C_NO_CHANNEL_BINDINGS,
- &input_token, NULL, &output_token, NULL, NULL);
+ &input_token, nullptr, &output_token, nullptr, nullptr);
if (check_gss_err(major_status, minor_status, "gss_init_sec_context()"))
goto cleanup;
}
cleanup:
- gss_delete_sec_context(&minor_status, &gss_context, NULL);
+ gss_delete_sec_context(&minor_status, &gss_context, nullptr);
gss_release_buffer(&minor_status, &service);
gss_release_buffer(&minor_status, &input_token);
gss_release_buffer(&minor_status, &output_token);
if (entry) {
assert(entry->ping_status != PING_WAITING);
entry->unlock("peerSelect");
- entry = NULL;
+ entry = nullptr;
}
delete lastError;
debugs(44, 3, "Unknown host: " << (fs->_peer.valid() ? fs->_peer->host : request->url.host()));
// discard any previous error.
delete lastError;
- lastError = NULL;
+ lastError = nullptr;
if (fs->code == HIER_DIRECT) {
lastError = new ErrorState(ERR_DNS_FAIL, Http::scServiceUnavailable, request, al);
lastError->dnsError = details.error;
p = whichPeer(closest_parent_miss);
- if (p == NULL)
+ if (p == nullptr)
return 0;
debugs(44, 3, "closest_parent_miss RTT = " << ping.p_rtt << " msec");
if (always_direct == ACCESS_DUNNO) {
debugs(44, 3, "direct = " << DirectStr[direct] << " (always_direct to be checked)");
/** check always_direct; */
- ACLFilledChecklist *ch = new ACLFilledChecklist(Config.accessList.AlwaysDirect, request, NULL);
+ ACLFilledChecklist *ch = new ACLFilledChecklist(Config.accessList.AlwaysDirect, request, nullptr);
ch->al = al;
acl_checklist = ch;
acl_checklist->syncAle(request, nullptr);
} else if (never_direct == ACCESS_DUNNO) {
debugs(44, 3, "direct = " << DirectStr[direct] << " (never_direct to be checked)");
/** check never_direct; */
- ACLFilledChecklist *ch = new ACLFilledChecklist(Config.accessList.NeverDirect, request, NULL);
+ ACLFilledChecklist *ch = new ACLFilledChecklist(Config.accessList.NeverDirect, request, nullptr);
ch->al = al;
acl_checklist = ch;
acl_checklist->syncAle(request, nullptr);
if (!entry || entry->ping_status == PING_NONE)
selectPinned();
- if (entry == NULL) {
+ if (entry == nullptr) {
(void) 0;
} else if (entry->ping_status == PING_NONE) {
selectSomeNeighbor();
void
PeerSelector::selectSomeNeighborReplies()
{
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
hier_code code = HIER_NONE;
assert(entry->ping_status == PING_WAITING);
assert(direct != DIRECT_YES);
PeerSelector::PeerSelector(PeerSelectionInitiator *initiator):
request(nullptr),
- entry (NULL),
+ entry (nullptr),
always_direct(Config.accessList.AlwaysDirect?ACCESS_DUNNO:ACCESS_DENIED),
never_direct(Config.accessList.NeverDirect?ACCESS_DUNNO:ACCESS_DENIED),
direct(DIRECT_UNKNOWN),
- lastError(NULL),
- servers (NULL),
+ lastError(nullptr),
+ servers (nullptr),
first_parent_miss(),
closest_parent_miss(),
- hit(NULL),
+ hit(nullptr),
hit_type(PEER_NONE),
- acl_checklist (NULL),
+ acl_checklist (nullptr),
initiator_(initiator)
{
; // no local defaults.
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
static int n_sourcehash_peers = 0;
-static CachePeer **sourcehash_peers = NULL;
+static CachePeer **sourcehash_peers = nullptr;
static OBJH peerSourceHashCachemgr;
static void peerSourceHashRegisterWithCacheManager(void);
{
int k;
const char *c;
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
CachePeer *tp;
unsigned int user_hash = 0;
unsigned int combined_hash;
double score;
double high_score = 0;
- const char *key = NULL;
+ const char *key = nullptr;
char ntoabuf[MAX_IPSTRLEN];
if (n_sourcehash_peers == 0)
- return NULL;
+ return nullptr;
assert(ps);
HttpRequest *request = ps->request;
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
static int n_userhash_peers = 0;
-static CachePeer **userhash_peers = NULL;
+static CachePeer **userhash_peers = nullptr;
static OBJH peerUserHashCachemgr;
static void peerUserHashRegisterWithCacheManager(void);
{
int k;
const char *c;
- CachePeer *p = NULL;
+ CachePeer *p = nullptr;
CachePeer *tp;
unsigned int user_hash = 0;
unsigned int combined_hash;
double score;
double high_score = 0;
- const char *key = NULL;
+ const char *key = nullptr;
if (n_userhash_peers == 0)
- return NULL;
+ return nullptr;
assert(ps);
HttpRequest *request = ps->request;
- if (request->auth_user_request != NULL)
+ if (request->auth_user_request != nullptr)
key = request->auth_user_request->username();
if (!key)
- return NULL;
+ return nullptr;
/* calculate hash key */
debugs(39, 2, "peerUserHashSelectParent: Calculating hash for " << key);
static HLPCB redirectHandleReply;
static HLPCB storeIdHandleReply;
-static helper *redirectors = NULL;
-static helper *storeIds = NULL;
+static helper *redirectors = nullptr;
+static helper *storeIds = nullptr;
static OBJH redirectStats;
static OBJH storeIdStats;
static int redirectorBypassed = 0;
static int storeIdBypassed = 0;
-static Format::Format *redirectorExtrasFmt = NULL;
-static Format::Format *storeIdExtrasFmt = NULL;
+static Format::Format *redirectorExtrasFmt = nullptr;
+static Format::Format *storeIdExtrasFmt = nullptr;
CBDATA_CLASS_INIT(RedirectStateData);
RedirectStateData::RedirectStateData(const char *url) :
- data(NULL),
+ data(nullptr),
orig_url(url),
- handler(NULL)
+ handler(nullptr)
{
}
static void
redirectStats(StoreEntry * sentry)
{
- if (redirectors == NULL) {
+ if (redirectors == nullptr) {
storeAppendPrintf(sentry, "No redirectors defined\n");
return;
}
static void
storeIdStats(StoreEntry * sentry)
{
- if (storeIds == NULL) {
+ if (storeIds == nullptr) {
storeAppendPrintf(sentry, "No StoreId helpers defined\n");
return;
}
nullptr,
http->getConn(),
http->request,
- NULL,
+ nullptr,
#if USE_AUTH
- http->getConn() != NULL && http->getConn()->getAuth() != NULL ?
+ http->getConn() != nullptr && http->getConn()->getAuth() != nullptr ?
http->getConn()->getAuth() : http->request->auth_user_request);
#else
NULL);
if (Config.Program.redirect) {
- if (redirectors == NULL)
+ if (redirectors == nullptr)
redirectors = new helper("redirector");
redirectors->cmdline = Config.Program.redirect;
if (Config.Program.store_id) {
- if (storeIds == NULL)
+ if (storeIds == nullptr)
storeIds = new helper("store_id");
storeIds->cmdline = Config.Program.store_id;
return;
delete redirectors;
- redirectors = NULL;
+ redirectors = nullptr;
delete storeIds;
- storeIds = NULL;
+ storeIds = nullptr;
delete redirectorExtrasFmt;
- redirectorExtrasFmt = NULL;
+ redirectorExtrasFmt = nullptr;
delete storeIdExtrasFmt;
- storeIdExtrasFmt = NULL;
+ storeIdExtrasFmt = nullptr;
}
void
*/
// XXX: performance regression. c_str() reallocates
const RefreshPattern *R = (uri != nilUri) ? refreshLimits(uri.c_str()) : refreshFirstDotRule();
- if (NULL == R)
+ if (nullptr == R)
R = &DefaultRefresh;
debugs(22, 3, "Matched '" << *R << '\'');
#endif
// Check the Cache-Control client request header
- if (NULL != cc) {
+ if (nullptr != cc) {
// max-age directive
int maxAge = -1;
* avoid objects which expire almost immediately, and which can't
* be refreshed.
*/
- int reason = refreshCheck(entry, NULL, Config.minimum_expiry_time);
+ int reason = refreshCheck(entry, nullptr, Config.minimum_expiry_time);
++ refreshCounts[rcStore].total;
++ refreshCounts[rcStore].status[reason];
/* We should know entry's modification time to do a refresh */
return false;
- if (entry->mem_obj == NULL)
+ if (entry->mem_obj == nullptr)
/* no mem_obj? */
return true;
heap_delete(h->theHeap, hnode);
- node->data = NULL;
+ node->data = nullptr;
h->count -= 1;
}
StoreEntry *entry;
if (heap_walk->current >= heap_nodes(h->theHeap))
- return NULL; /* done */
+ return nullptr; /* done */
entry = (StoreEntry *) heap_peep(h->theHeap, heap_walk->current++);
try_again:
if (heap_empty(h->theHeap))
- return NULL; /* done */
+ return nullptr; /* done */
age = heap_peepminkey(h->theHeap);
}
heap_walker->min_age = age;
- h->setPolicyNode(entry, NULL);
+ h->setPolicyNode(entry, nullptr);
return entry;
}
policy->Remove = heap_remove;
- policy->Referenced = NULL;
+ policy->Referenced = nullptr;
policy->Dereferenced = heap_referenced;
dlink_node node;
};
-static MemAllocator *lru_node_pool = NULL;
+static MemAllocator *lru_node_pool = nullptr;
static int nr_lru_policies = 0;
static void
* but not be in the LRU list, so check for that case rather
* than suffer a NULL pointer access.
*/
- if (NULL == lru_node->node.data)
+ if (nullptr == lru_node->node.data)
return;
assert(lru_node->node.data == entry);
- node->data = NULL;
+ node->data = nullptr;
dlinkDelete(&lru_node->node, &lru->list);
LruNode *lru_node = lru_walk->current;
if (!lru_node)
- return NULL;
+ return nullptr;
lru_walk->current = (LruNode *) lru_node->node.next;
lru_node = lru_walker->current;
if (!lru_node || walker->scanned >= walker->max_scan)
- return NULL;
+ return nullptr;
walker->scanned += 1;
if (lru_walker->current == lru_walker->start) {
/* Last node found */
- lru_walker->current = NULL;
+ lru_walker->current = nullptr;
}
entry = (StoreEntry *) lru_node->node.data;
lru_node_pool->freeOne(lru_node);
lru->count -= 1;
- lru->setPolicyNode(entry, NULL);
+ lru->setPolicyNode(entry, nullptr);
return entry;
}
/* MemBlob */
MemBlob::MemBlob(const MemBlob::size_type reserveSize) :
- mem(NULL), capacity(0), size(0) // will be set by memAlloc
+ mem(nullptr), capacity(0), size(0) // will be set by memAlloc
{
debugs(MEMBLOB_DEBUGSECTION,9, "constructed, this="
<< static_cast<void*>(this) << " id=" << id
}
MemBlob::MemBlob(const char *buffer, const MemBlob::size_type bufSize) :
- mem(NULL), capacity(0), size(0) // will be set by memAlloc
+ mem(nullptr), capacity(0), size(0) // will be set by memAlloc
{
debugs(MEMBLOB_DEBUGSECTION,9, "constructed, this="
<< static_cast<void*>(this) << " id=" << id
SBuf::append(const char * S, size_type Ssize)
{
const Locker blobKeeper(this, S);
- if (S == NULL)
+ if (S == nullptr)
return *this;
if (Ssize == SBuf::npos)
Ssize = strlen(S);
// with (v)appendf() the fmt or an arg might be a dangerous char*
const Locker blobKeeper(this, buf());
- Must(fmt != NULL);
+ Must(fmt != nullptr);
int sz = 0;
//reserve twice the format-string size, it's a likely heuristic
size_type requiredSpaceEstimate = strlen(fmt)*2;
++stats.trim;
if (atEnd) {
const char *p = bufEnd()-1;
- while (!isEmpty() && memchr(toRemove.buf(), *p, toRemove.length()) != NULL) {
+ while (!isEmpty() && memchr(toRemove.buf(), *p, toRemove.length()) != nullptr) {
//current end-of-buf is in the searched set
--len_;
--p;
}
if (atBeginning) {
const char *p = buf();
- while (!isEmpty() && memchr(toRemove.buf(), *p, toRemove.length()) != NULL) {
+ while (!isEmpty() && memchr(toRemove.buf(), *p, toRemove.length()) != nullptr) {
--len_;
++off_;
++p;
const void *i = memchr(buf()+startPos, (int)c, (size_type)length()-startPos);
- if (i == NULL)
+ if (i == nullptr)
return npos;
return (static_cast<const char *>(i)-buf());
debugs(24, 8, " begin=" << (void *) start <<
", lastPossible=" << (void*) lastPossible );
tmp = static_cast<char *>(memchr(start, needleBegin, lastPossible-start));
- if (tmp == NULL) {
+ if (tmp == nullptr) {
debugs(24, 8, "First byte not found");
return npos;
}
const void *i = memrchr(buf(), (int)c, (size_type)endPos);
- if (i == NULL)
+ if (i == nullptr)
return npos;
return (static_cast<const char *>(i)-buf());
store_ = std::move(S.store_);
off_ = S.off_;
len_ = S.len_;
- S.store_ = NULL; //RefCount supports NULL, and S is about to be destructed
+ S.store_ = nullptr; //RefCount supports NULL, and S is about to be destructed
S.off_ = 0;
S.len_ = 0;
}
/// Details a server-side certificate verification failure.
/// If `broken` is nil, then the broken certificate is the peer certificate.
- ErrorDetail(ErrorCode err_no, const CertPointer &peer, const CertPointer &broken, const char *aReason = NULL);
+ ErrorDetail(ErrorCode err_no, const CertPointer &peer, const CertPointer &broken, const char *aReason = nullptr);
#if USE_OPENSSL
/// Details (or starts detailing) a non-validation failure.
}
#endif
- noteNegotiationDone(NULL);
+ noteNegotiationDone(nullptr);
return true;
}
void
Security::PeerConnector::sslCrtvdHandleReply(Ssl::CertValidationResponse::Pointer validationResponse)
{
- Must(validationResponse != NULL);
+ Must(validationResponse != nullptr);
Must(Comm::IsConnOpen(serverConnection()));
ErrorDetail::Pointer errDetails;
validatorFailed = true;
if (!errDetails && !validatorFailed) {
- noteNegotiationDone(NULL);
+ noteNegotiationDone(nullptr);
if (callback)
sendSuccess();
return;
}
- ErrorState *anErr = NULL;
+ ErrorState *anErr = nullptr;
if (validatorFailed) {
anErr = new ErrorState(ERR_GATEWAY_FAILURE, Http::scInternalServerError, request.getRaw(), al);
} else {
{
Must(Comm::IsConnOpen(serverConnection()));
- ACLFilledChecklist *check = NULL;
+ ACLFilledChecklist *check = nullptr;
Security::SessionPointer session(fd_table[serverConnection()->fd].ssl);
if (acl_access *acl = ::Config.ssl_client.cert_error) {
debugs(83, 5, "confirming SSL error " << i->error_no);
const auto &brokenCert = i->cert;
Security::CertPointer peerCert(SSL_get_peer_certificate(session.get()));
- const char *aReason = i->error_reason.empty() ? NULL : i->error_reason.c_str();
+ const char *aReason = i->error_reason.empty() ? nullptr : i->error_reason.c_str();
errDetails = new ErrorDetail(i->error_no, peerCert, brokenCert, aReason);
}
if (check) {
delete check->sslErrors;
- check->sslErrors = NULL;
+ check->sslErrors = nullptr;
}
}
AsyncCall::Pointer cb = callback;
// Do this now so that if we throw below, swanSong() assert that we _tried_
// to call back holds.
- callback = NULL; // this should make done() true
+ callback = nullptr; // this should make done() true
ScheduleCallHere(cb);
}
// TODO: redesign AsyncJob::status() API to avoid this
// id and stop reason reporting duplication.
buf.append(" [", 2);
- if (stopReason != NULL) {
+ if (stopReason != nullptr) {
buf.append("Stopped, reason:", 16);
buf.appendf("%s",stopReason);
}
// be able to accept collection of certificates.
// TODO: support collection of certificates
const unsigned char *raw = (const unsigned char*)obj.rawContent();
- if (X509 *cert = d2i_X509(NULL, &raw, obj.length())) {
+ if (X509 *cert = d2i_X509(nullptr, &raw, obj.length())) {
debugs(81, 5, "Retrieved certificate: " << *cert);
if (!downloadedCerts)
"", 0
},
{
- NULL, 0
+ nullptr, 0
}
};
#endif /* USE_OPENSSL */
return;
}
- while (X509_CRL *crl = PEM_read_bio_X509_CRL(in,NULL,NULL,NULL)) {
+ while (X509_CRL *crl = PEM_read_bio_X509_CRL(in,nullptr,nullptr,nullptr)) {
parsedCrl.emplace_back(Security::CrlPointer(crl));
}
BIO_free(in);
#if USE_OPENSSL
DH *dhp = nullptr;
if (FILE *in = fopen(dhParamsFile.c_str(), "r")) {
- dhp = PEM_read_DHparams(in, NULL, NULL, NULL);
+ dhp = PEM_read_DHparams(in, nullptr, nullptr, nullptr);
fclose(in);
}
{
row = (char **)OPENSSL_malloc(sizeof(char *) * (width + 1));
for (size_t i = 0; i < width + 1; ++i)
- row[i] = NULL;
+ row[i] = nullptr;
}
Ssl::CertificateDb::Row::Row(char **aRow, size_t aWidth): width(aWidth)
return;
void *max;
- if ((max = (void *)row[width]) != NULL) {
+ if ((max = (void *)row[width]) != nullptr) {
// It is an openSSL allocated row. The TXT_DB_read function stores the
// index and row items one one memory segment. The row[width] points
// to the end of buffer. We have to check for items in the array which
// are not stored in this segment. These items should released.
for (size_t i = 0; i < width + 1; ++i) {
- if (((row[i] < (char *)row) || (row[i] > max)) && (row[i] != NULL))
+ if (((row[i] < (char *)row) || (row[i] > max)) && (row[i] != nullptr))
OPENSSL_free(row[i]);
}
} else {
void Ssl::CertificateDb::Row::reset()
{
- row = NULL;
+ row = nullptr;
}
void Ssl::CertificateDb::Row::setValue(size_t cell, char const * value)
row[cell] = static_cast<char *>(OPENSSL_malloc(sizeof(char) * (strlen(value) + 1)));
memcpy(row[cell], value, sizeof(char) * (strlen(value) + 1));
} else
- row[cell] = NULL;
+ row[cell] = nullptr;
}
char ** Ssl::CertificateDb::Row::getRow()
const Columns db_indexes[]= {cnlSerial, cnlKey};
for (unsigned int i = 0; i < countof(db_indexes); ++i) {
- void *data = NULL;
+ void *data = nullptr;
#if SQUID_SSLTXTDB_PSTRINGDATA
if (LHASH_OF(OPENSSL_STRING) *fieldIndex = db->index[db_indexes[i]])
data = lh_OPENSSL_STRING_delete(fieldIndex, rrow);
Row row;
ASN1_INTEGER * ai = X509_get_serialNumber(cert.get());
std::string serial_string;
- Ssl::BIGNUM_Pointer serial(ASN1_INTEGER_to_BN(ai, NULL));
+ Ssl::BIGNUM_Pointer serial(ASN1_INTEGER_to_BN(ai, nullptr));
{
const UniqueCString hex_bn(BN_bn2hex(serial.get()));
serial_string = std::string(hex_bn.get());
char ** rrow = TXT_DB_get_by_index(db.get(), cnlSerial, row.getRow());
// We are creating certificates with unique serial numbers. If the serial
// number is found in the database, the same certificate is already stored.
- if (rrow != NULL) {
+ if (rrow != nullptr) {
// TODO: check if the stored row is valid.
return true;
}
row.setValue(cnlKey, key.c_str());
char **rrow = TXT_DB_get_by_index(db.get(), cnlKey, row.getRow());
- if (rrow == NULL)
+ if (rrow == nullptr)
return false;
if (!sslDateIsInTheFuture(rrow[cnlExp_date]))
corrupt = true;
// Create indexes in db.
- if (!corrupt && !TXT_DB_create_index(temp_db.get(), cnlSerial, NULL, LHASH_HASH_FN(index_serial_hash), LHASH_COMP_FN(index_serial_cmp)))
+ if (!corrupt && !TXT_DB_create_index(temp_db.get(), cnlSerial, nullptr, LHASH_HASH_FN(index_serial_hash), LHASH_COMP_FN(index_serial_cmp)))
corrupt = true;
- if (!corrupt && !TXT_DB_create_index(temp_db.get(), cnlKey, NULL, LHASH_HASH_FN(index_name_hash), LHASH_COMP_FN(index_name_cmp)))
+ if (!corrupt && !TXT_DB_create_index(temp_db.get(), cnlKey, nullptr, LHASH_HASH_FN(index_name_hash), LHASH_COMP_FN(index_name_cmp)))
corrupt = true;
if (corrupt)
cert = Ssl::ReadCertificate(bio);
- if (!Ssl::ReadPrivateKey(bio, pkey, NULL))
+ if (!Ssl::ReadPrivateKey(bio, pkey, nullptr))
return false;
orig = Ssl::ReadOptionalCertificate(bio);
Ssl::CrtdMessage::ParseResult parse_result = Ssl::CrtdMessage::INCOMPLETE;
while (parse_result == Ssl::CrtdMessage::INCOMPLETE) {
- if (fgets(request, HELPER_INPUT_BUFFER, stdin) == NULL)
+ if (fgets(request, HELPER_INPUT_BUFFER, stdin) == nullptr)
exit(EXIT_FAILURE);
size_t gcount = strlen(request);
parse_result = request_message.parse(request, gcount);
if (!Comm::IsConnOpen(icpOutgoingConn))
return;
- ipcache_nbgethostbyname(Config.Announce.host, send_announce, NULL);
+ ipcache_nbgethostbyname(Config.Announce.host, send_announce, nullptr);
- eventAdd("send_announce", start_announce, NULL, (double) Config.Announce.period, 1);
+ eventAdd("send_announce", start_announce, nullptr, (double) Config.Announce.period, 1);
}
static void
LOCAL_ARRAY(char, sndbuf, BUFSIZ);
char *host = Config.Announce.host;
- char *file = NULL;
+ char *file = nullptr;
unsigned short port = Config.Announce.port;
int l;
int n;
int fd;
- if (ia == NULL) {
+ if (ia == nullptr) {
debugs(27, DBG_IMPORTANT, "ERROR: send_announce: Unknown host '" << host << "'");
return;
}
sndbuf[0] = '\0';
snprintf(tbuf, 256, "cache_version SQUID/%s\n", version_string);
strcat(sndbuf, tbuf);
- assert(HttpPortList != NULL);
+ assert(HttpPortList != nullptr);
snprintf(tbuf, 256, "Running on %s %d %d\n",
getMyHostname(),
getMyPort(),
strcat(sndbuf, tbuf);
l = strlen(sndbuf);
- if ((file = Config.Announce.file) != NULL) {
+ if ((file = Config.Announce.file) != nullptr) {
fd = file_open(file, O_RDONLY | O_TEXT);
if (fd > -1 && (n = FD_READ_METHOD(fd, sndbuf + l, BUFSIZ - l - 1)) > 0) {
char buf[MAX_IPSTRLEN];
clientConnection->local.toUrl(buf, MAX_IPSTRLEN);
host = buf;
- calcUri(NULL);
+ calcUri(nullptr);
debugs(33, 5, "FTP transparent URL: " << uri);
}
void
Ftp::Server::maybeReadUploadData()
{
- if (reader != NULL)
+ if (reader != nullptr)
return;
const size_t availSpace = sizeof(uploadBuf) - uploadAvailSize;
Must(context != nullptr);
ClientHttpRequest *const http = context->http;
- assert(http != NULL);
+ assert(http != nullptr);
HttpRequest *const request = http->request;
Must(http->storeEntry() || request);
const bool mayForward = !http->storeEntry() && handleRequest(request);
- if (http->storeEntry() != NULL) {
+ if (http->storeEntry() != nullptr) {
debugs(33, 4, "got an immediate response");
clientSetKeepaliveFlag(http);
context->pullData();
} else if (mayForward) {
debugs(33, 4, "forwarding request to server side");
- assert(http->storeEntry() == NULL);
+ assert(http->storeEntry() == nullptr);
clientProcessRequest(this, Http1::RequestParserPointer(), context.getRaw());
} else {
debugs(33, 4, "will resume processing later");
Ftp::Server::readUploadData(const CommIoCbParams &io)
{
debugs(33, 5, io.conn << " size " << io.size);
- Must(reader != NULL);
- reader = NULL;
+ Must(reader != nullptr);
+ reader = nullptr;
assert(Comm::IsConnOpen(dataConn));
assert(io.conn->fd == dataConn->fd);
- if (io.flag == Comm::OK && bodyPipe != NULL) {
+ if (io.flag == Comm::OK && bodyPipe != nullptr) {
if (io.size > 0) {
statCounter.client_http.kbytes_in += io.size;
void
Ftp::Server::shovelUploadData()
{
- assert(bodyPipe != NULL);
+ assert(bodyPipe != nullptr);
debugs(33, 5, "handling FTP request data for " << clientConnection);
const size_t putSize = bodyPipe->putMoreData(uploadBuf,
void
Ftp::StartListening()
{
- for (AnyP::PortCfgPointer s = FtpPortList; s != NULL; s = s->next) {
+ for (AnyP::PortCfgPointer s = FtpPortList; s != nullptr; s = s->next) {
if (MAXTCPLISTENPORTS == NHttpSockets) {
debugs(1, DBG_IMPORTANT, "Ignoring ftp_port lines exceeding the" <<
" limit of " << MAXTCPLISTENPORTS << " ports.");
typedef CommCbFunPtrCallT<CommAcceptCbPtrFun> AcceptCall;
RefCount<AcceptCall> subCall = commCbCall(5, 5, "Ftp::Server::AcceptCtrlConnection",
CommAcceptCbPtrFun(Ftp::Server::AcceptCtrlConnection,
- CommAcceptCbParams(NULL)));
+ CommAcceptCbParams(nullptr)));
clientStartListeningOn(s, subCall, Ipc::fdnFtpSocket);
}
}
void
Ftp::StopListening()
{
- for (AnyP::PortCfgPointer s = FtpPortList; s != NULL; s = s->next) {
- if (s->listenConn != NULL) {
+ for (AnyP::PortCfgPointer s = FtpPortList; s != nullptr; s = s->next) {
+ if (s->listenConn != nullptr) {
debugs(1, DBG_IMPORTANT, "Closing FTP port " << s->listenConn->local);
s->listenConn->close();
- s->listenConn = NULL;
+ s->listenConn = nullptr;
}
}
}
Http::StreamPointer context = pipeline.front();
Must(context != nullptr);
ClientHttpRequest *const http = context->http;
- Must(http != NULL);
+ Must(http != nullptr);
HttpRequest *const request = http->request;
- Must(request != NULL);
+ Must(request != nullptr);
// make FTP peer connection exclusive to our request
pinBusyConnection(conn, request);
}
dataConn->leaveOrphanage();
uploadAvailSize = 0;
debugs(33, 7, "ready for data");
- if (onDataAcceptCall != NULL) {
+ if (onDataAcceptCall != nullptr) {
AsyncCall::Pointer call = onDataAcceptCall;
- onDataAcceptCall = NULL;
+ onDataAcceptCall = nullptr;
// If we got an upload request, start reading data from the client.
if (master->serverState == fssHandleUploadRequest)
maybeReadUploadData();
void
Ftp::Server::closeDataConnection()
{
- if (listener != NULL) {
+ if (listener != nullptr) {
listener->cancel("no longer needed");
- listener = NULL;
+ listener = nullptr;
}
if (Comm::IsConnOpen(dataListenConn)) {
*dataListenConn);
dataListenConn->close();
}
- dataListenConn = NULL;
+ dataListenConn = nullptr;
- if (reader != NULL) {
+ if (reader != nullptr) {
// Comm::ReadCancel can deal with negative FDs
Comm::ReadCancel(dataConn->fd, reader);
- reader = NULL;
+ reader = nullptr;
}
if (Comm::IsConnOpen(dataConn)) {
*dataConn);
dataConn->close();
}
- dataConn = NULL;
+ dataConn = nullptr;
}
/// Writes FTP [error] response before we fully parsed the FTP request and
debugs(33, 7, code << ' ' << msg);
assert(99 < code && code < 1000);
- const bool sendDetails = reply != NULL &&
+ const bool sendDetails = reply != nullptr &&
reply->header.has(Http::HdrType::FTP_STATUS) && reply->header.has(Http::HdrType::FTP_REASON);
MemBuf mb;
static_cast<SBuf::size_type>(Config.maxRequestHeaderSize));
if (cmd.length() > tokenMax || params.length() > tokenMax) {
changeState(fssError, "huge req token");
- quitAfterError(NULL);
+ quitAfterError(nullptr);
return earlyError(EarlyErrorKind::HugeRequest);
}
// we need more data, but can we buffer more?
if (inBuf.length() >= Config.maxRequestHeaderSize) {
changeState(fssError, "huge req");
- quitAfterError(NULL);
+ quitAfterError(nullptr);
return earlyError(EarlyErrorKind::HugeRequest);
} else {
flags.readMore = true;
debugs(33, 5, "Waiting for more, up to " <<
(Config.maxRequestHeaderSize - inBuf.length()));
- return NULL;
+ return nullptr;
}
}
Http::METHOD_PUT : Http::METHOD_GET;
const SBuf *path = (params.length() && CommandHasPathParameter(cmd)) ?
- ¶ms : NULL;
+ ¶ms : nullptr;
calcUri(path);
const auto mx = MasterXaction::MakePortful(port);
mx->tcpClient = clientConnection;
assert(context != nullptr);
static ReplyHandler handlers[] = {
- NULL, // fssBegin
- NULL, // fssConnected
+ nullptr, // fssBegin
+ nullptr, // fssConnected
&Ftp::Server::handleFeatReply, // fssHandleFeat
&Ftp::Server::handlePasvReply, // fssHandlePasv
&Ftp::Server::handlePortReply, // fssHandlePort
&Ftp::Server::handleUploadReply, // fssHandleUploadRequest
&Ftp::Server::handleEprtReply,// fssHandleEprt
&Ftp::Server::handleEpsvReply,// fssHandleEpsv
- NULL, // fssHandleCwd
- NULL, // fssHandlePass
- NULL, // fssHandleCdup
+ nullptr, // fssHandleCwd
+ nullptr, // fssHandlePass
+ nullptr, // fssHandleCdup
&Ftp::Server::handleErrorReply // fssError
};
try {
void
Ftp::Server::handleDataReply(const HttpReply *reply, StoreIOBuffer data)
{
- if (reply != NULL && reply->sline.status() != Http::scOkay) {
+ if (reply != nullptr && reply->sline.status() != Http::scOkay) {
writeForwardedReply(reply);
if (Comm::IsConnOpen(dataConn)) {
debugs(33, 3, "closing " << dataConn << " on KO reply");
Must(reply);
if (waitingForOrigin) {
- Must(delayedReply == NULL);
+ Must(delayedReply == nullptr);
delayedReply = reply;
return;
}
#if USE_ADAPTATION
// XXX: Remove hard coded names. Use an error page template instead.
const Adaptation::History::Pointer ah = request->adaptHistory();
- if (ah != NULL) { // XXX: add adapt::<all_h but use lastMeta here
+ if (ah != nullptr) { // XXX: add adapt::<all_h but use lastMeta here
const String info = ah->allMeta.getByName("X-Response-Info");
const String desc = ah->allMeta.getByName("X-Response-Desc");
if (info.size())
void
Ftp::Server::writeForwardedReplyAndCall(const HttpReply *reply, AsyncCall::Pointer &call)
{
- assert(reply != NULL);
+ assert(reply != nullptr);
const HttpHeader &header = reply->header;
// without status, the caller must use the writeForwardedForeign() path
if (header.has(Http::HdrType::FTP_STATUS)) {
const char *reason = header.getStr(Http::HdrType::FTP_REASON);
mb.appendf("%i %s\r\n", header.getInt(Http::HdrType::FTP_STATUS),
- (reason ? reason : 0));
+ (reason ? reason : nullptr));
}
}
handlers["CDUP"] = &Ftp::Server::handleCdupRequest;
}
- RequestHandler handler = NULL;
+ RequestHandler handler = nullptr;
if (request->method == Http::METHOD_PUT)
handler = &Ftp::Server::handleUploadRequest;
else {
oldUri = uri;
master->workingDir.clear();
- calcUri(NULL);
+ calcUri(nullptr);
if (!master->clientReadGreeting) {
debugs(9, 3, "set URI to " << uri);
resetLogin("URI reset");
}
- return NULL; // no early errors
+ return nullptr; // no early errors
}
bool
bool
Ftp::Server::createDataConnection(Ip::Address cltAddr)
{
- assert(clientConnection != NULL);
+ assert(clientConnection != nullptr);
assert(!clientConnection->remote.isAnyAddr());
if (cltAddr != clientConnection->remote) {
}
Ip::Address cltAddr;
- if (!Ftp::ParseIpPort(params.termedBuf(), NULL, cltAddr)) {
+ if (!Ftp::ParseIpPort(params.termedBuf(), nullptr, cltAddr)) {
setReply(501, "Invalid parameter");
return false;
}
if (Config.accessList.forceRequestBodyContinuation) {
ClientHttpRequest *http = pipeline.front()->http;
HttpRequest *request = http->request;
- ACLFilledChecklist bodyContinuationCheck(Config.accessList.forceRequestBodyContinuation, request, NULL);
+ ACLFilledChecklist bodyContinuationCheck(Config.accessList.forceRequestBodyContinuation, request, nullptr);
bodyContinuationCheck.al = http->al;
bodyContinuationCheck.syncAle(request, http->log_uri);
if (bodyContinuationCheck.fastCheck().allowed()) {
Ftp::Server::setDataCommand()
{
ClientHttpRequest *const http = pipeline.front()->http;
- assert(http != NULL);
+ assert(http != nullptr);
HttpRequest *const request = http->request;
- assert(request != NULL);
+ assert(request != nullptr);
HttpHeader &header = request->header;
header.delById(Http::HdrType::FTP_COMMAND);
header.putStr(Http::HdrType::FTP_COMMAND, "PASV");
setReply(425, "Cannot open data connection.");
Http::StreamPointer context = pipeline.front();
Must(context->http);
- Must(context->http->storeEntry() != NULL);
+ Must(context->http->storeEntry() != nullptr);
// TODO: call closeDataConnection() to reset data conn processing?
} else {
// Finalize the details and start owning the supplied connection.
{
Http::StreamPointer context = pipeline.front();
ClientHttpRequest *const http = context->http;
- assert(http != NULL);
- assert(http->storeEntry() == NULL);
+ assert(http != nullptr);
+ assert(http->storeEntry() == nullptr);
HttpReply *const reply = Ftp::HttpReplyWrapper(code, msg, Http::scNoContent, 0);
clientStreamNode *const node = context->getClientReplyContext();
clientReplyContext *const repContext =
dynamic_cast<clientReplyContext *>(node->data.getRaw());
- assert(repContext != NULL);
+ assert(repContext != nullptr);
RequestFlags reqFlags;
reqFlags.cachable = false; // force releaseRequest() in storeCreateEntry()
void maybeReadUploadData();
void setReply(const int code, const char *msg);
- void writeCustomReply(const int code, const char *msg, const HttpReply *reply = NULL);
+ void writeCustomReply(const int code, const char *msg, const HttpReply *reply = nullptr);
void writeEarlyReply(const int code, const char *msg);
void writeErrorReply(const HttpReply *reply, const int status);
void writeForwardedForeign(const HttpReply *reply);
// setReplyToError() requires log_uri
http->setLogUriToRawUri(http->uri, parser_->method());
- const char * requestErrorBytes = NULL; //HttpParserHdrBuf(parser_);
+ const char * requestErrorBytes = nullptr; //HttpParserHdrBuf(parser_);
if (!tunnelOnError(ERR_UNSUP_HTTPVERSION)) {
setReplyError(context, request, ERR_UNSUP_HTTPVERSION, Http::scHttpVersionNotSupported, requestErrorBytes);
clientProcessRequestFinished(this, request);
debugs(33, 5, "Failed to parse request headers:\n" << parser_->mimeHeader());
// setReplyToError() requires log_uri
http->setLogUriToRawUri(http->uri, parser_->method());
- const char * requestErrorBytes = NULL; //HttpParserHdrBuf(parser_);
+ const char * requestErrorBytes = nullptr; //HttpParserHdrBuf(parser_);
if (!tunnelOnError(ERR_INVALID_REQ)) {
setReplyError(context, request, ERR_INVALID_REQ, Http::scBadRequest, requestErrorBytes);
clientProcessRequestFinished(this, request);
}
if (Config.accessList.forceRequestBodyContinuation) {
- ACLFilledChecklist bodyContinuationCheck(Config.accessList.forceRequestBodyContinuation, request.getRaw(), NULL);
+ ACLFilledChecklist bodyContinuationCheck(Config.accessList.forceRequestBodyContinuation, request.getRaw(), nullptr);
bodyContinuationCheck.al = http->al;
bodyContinuationCheck.syncAle(request.getRaw(), http->log_uri);
if (bodyContinuationCheck.fastCheck().allowed()) {
Http::StreamPointer context = pipeline.front();
Must(context != nullptr);
const ClientHttpRequest *http = context->http;
- Must(http != NULL);
+ Must(http != nullptr);
// After sending Transfer-Encoding: chunked (at least), always send
// the last-chunk if there was no error, ignoring responseFinishedOrFailed.
{
if (reading()) {
Comm::ReadCancel(clientConnection->fd, reader);
- reader = NULL;
+ reader = nullptr;
}
}
{
debugs(33,5, io.conn);
Must(reading());
- reader = NULL;
+ reader = nullptr;
/* Bail out quickly on Comm::ERR_CLOSING - close handlers will tidy up */
if (io.flag == Comm::ERR_CLOSING) {
virtual void afterClientRead() = 0;
/// whether Comm::Read() is scheduled
- bool reading() const {return reader != NULL;}
+ bool reading() const {return reader != nullptr;}
/// cancels Comm::Read() if it is scheduled
void stopReading();
virtual void afterClientWrite(size_t) {}
/// whether Comm::Write() is scheduled
- bool writing() const {return writer != NULL;}
+ bool writing() const {return writer != nullptr;}
// XXX: should be 'protected:' for child access only,
// but all sorts of code likes to play directly
Snmp::Forwarder::swanSong()
{
if (fd >= 0) {
- if (closer != NULL) {
+ if (closer != nullptr) {
comm_remove_close_handler(fd, closer);
- closer = NULL;
+ closer = nullptr;
}
fd = -1;
}
// snmpAgentResponse() can modify arg
Pdu tmp = pdu;
Snmp::Response response(requestId);
- snmp_pdu* response_pdu = NULL;
+ snmp_pdu* response_pdu = nullptr;
try {
response_pdu = snmpAgentResponse(&tmp);
- Must(response_pdu != NULL);
+ Must(response_pdu != nullptr);
response.pdu = static_cast<Pdu&>(*response_pdu);
snmp_free_pdu(response_pdu);
} catch (const std::exception& e) {
Snmp::Inquirer::cleanup()
{
if (Comm::IsConnOpen(conn)) {
- if (closer != NULL) {
+ if (closer != nullptr) {
comm_remove_close_handler(conn->fd, closer);
- closer = NULL;
+ closer = nullptr;
}
conn->close();
}
- conn = NULL;
+ conn = nullptr;
}
void
{
Must(varCount() == pdu.varCount());
++aggrCount;
- for (variable_list* p_aggr = variables, *p_var = pdu.variables; p_var != NULL;
+ for (variable_list* p_aggr = variables, *p_var = pdu.variables; p_var != nullptr;
p_aggr = p_aggr->next_variable, p_var = p_var->next_variable) {
- Must(p_aggr != NULL);
+ Must(p_aggr != nullptr);
Var& aggr = static_cast<Var&>(*p_aggr);
Var& var = static_cast<Var&>(*p_var);
if (aggr.isNull()) {
Snmp::Pdu::clearVars()
{
variable_list* var = variables;
- while (var != NULL) {
+ while (var != nullptr) {
variable_list* tmp = var;
var = var->next_variable;
snmp_var_free(tmp);
}
- variables = NULL;
+ variables = nullptr;
}
void
Snmp::Pdu::setVars(variable_list* vars)
{
clearVars();
- for (variable_list** p_var = &variables; vars != NULL;
+ for (variable_list** p_var = &variables; vars != nullptr;
vars = vars->next_variable, p_var = &(*p_var)->next_variable) {
*p_var = new Var(static_cast<Var&>(*vars));
}
void
Snmp::Pdu::clearSystemOid()
{
- if (enterprise != NULL) {
+ if (enterprise != nullptr) {
xfree(enterprise);
- enterprise = NULL;
+ enterprise = nullptr;
}
enterprise_length = 0;
}
msg.putPod(max_repetitions);
msg.putInt(enterprise_length);
if (enterprise_length > 0) {
- Must(enterprise != NULL);
+ Must(enterprise != nullptr);
msg.putFixed(enterprise, enterprise_length * sizeof(oid));
}
msg.putPod(agent_addr);
msg.putPod(specific_type);
msg.putPod(time);
msg.putInt(varCount());
- for (variable_list* var = variables; var != NULL; var = var->next_variable)
+ for (variable_list* var = variables; var != nullptr; var = var->next_variable)
static_cast<Var*>(var)->pack(msg);
}
Snmp::Pdu::varCount() const
{
int count = 0;
- for (variable_list* var = variables; var != NULL; var = var->next_variable)
+ for (variable_list* var = variables; var != nullptr; var = var->next_variable)
++count;
return count;
}
{
if (aggrCount < 2)
return;
- for (variable_list* p_aggr = variables; p_aggr != NULL; p_aggr = p_aggr->next_variable) {
+ for (variable_list* p_aggr = variables; p_aggr != nullptr; p_aggr = p_aggr->next_variable) {
Var& aggr = static_cast<Var&>(*p_aggr);
if (snmpAggrType(aggr.name, aggr.name_length) == atAverage) {
aggr /= aggrCount;
Snmp::Session::reset()
{
if (community_len > 0) {
- Must(community != NULL);
+ Must(community != nullptr);
xfree(community);
}
xfree(peername);
msg.putPod(Version);
msg.putInt(community_len);
if (community_len > 0) {
- Must(community != NULL);
+ Must(community != nullptr);
msg.putFixed(community, community_len);
}
msg.putPod(retries);
msg.putPod(timeout);
- int len = peername != NULL ? strlen(peername) : 0;
+ int len = peername != nullptr ? strlen(peername) : 0;
msg.putInt(len);
if (len > 0)
msg.putFixed(peername, len);
community_len = msg.getInt();
if (community_len > 0) {
community = static_cast<u_char*>(xmalloc(community_len + 1));
- Must(community != NULL);
+ Must(community != nullptr);
msg.getFixed(community, community_len);
community[community_len] = 0;
}
int len = msg.getInt();
if (len > 0) {
peername = static_cast<char*>(xmalloc(len + 1));
- Must(peername != NULL);
+ Must(peername != nullptr);
msg.getFixed(peername, len);
peername[len] = 0;
}
Snmp::Var::asInt() const
{
Must(type == SMI_INTEGER);
- Must(val.integer != NULL && val_len == sizeof(int));
+ Must(val.integer != nullptr && val_len == sizeof(int));
return *val.integer;
}
Snmp::Var::asGauge() const
{
Must(type == SMI_GAUGE32);
- Must(val.integer != NULL && val_len == 4);
+ Must(val.integer != nullptr && val_len == 4);
return *reinterpret_cast<unsigned int*>(val.integer);
}
Snmp::Var::asCounter() const
{
Must(type == SMI_COUNTER32);
- Must(val.integer != NULL && val_len == 4);
+ Must(val.integer != nullptr && val_len == 4);
return *reinterpret_cast<int*>(val.integer);
}
Snmp::Var::asCounter64() const
{
Must(type == SMI_COUNTER64);
- Must(val.integer != NULL && val_len == 8);
+ Must(val.integer != nullptr && val_len == 8);
return *reinterpret_cast<long long int*>(val.integer);
}
Snmp::Var::asTimeTicks() const
{
Must(type == SMI_TIMETICKS);
- Must(val.integer != NULL && val_len == sizeof(unsigned int));
+ Must(val.integer != nullptr && val_len == sizeof(unsigned int));
return *reinterpret_cast<unsigned int*>(val.integer);
}
Must(type == SMI_OBJID);
Must(val_len % sizeof(oid) == 0);
int length = val_len / sizeof(oid);
- Must(val.objid != NULL && length > 0);
+ Must(val.objid != nullptr && length > 0);
return Range<const oid*>(val.objid, val.objid + length);
}
Snmp::Var::asString() const
{
Must(type == SMI_STRING);
- Must(val.string != NULL && val_len > 0);
+ Must(val.string != nullptr && val_len > 0);
return Range<const u_char*>(val.string, val.string + val_len);
}
Snmp::Var::setValue(const void* value, int length, int aType)
{
clearValue();
- if (value != NULL) {
+ if (value != nullptr) {
Must(length > 0 && aType > 0);
val.string = static_cast<u_char*>(xmalloc(length));
memcpy(val.string, value, length);
{
msg.putInt(name_length);
if (name_length > 0) {
- Must(name != NULL);
+ Must(name != nullptr);
msg.putFixed(name, name_length * sizeof(oid));
}
msg.putPod(type);
msg.putPod(val_len);
if (val_len > 0) {
- Must(val.string != NULL);
+ Must(val.string != nullptr);
msg.putFixed(val.string, val_len);
}
}
variable_list *
snmp_sysFn(variable_list * Var, snint * ErrP)
{
- variable_list *Answer = NULL;
+ variable_list *Answer = nullptr;
MemBuf tmp;
debugs(49, 5, "snmp_sysFn: Processing request:" << snmpDebugOid(Var->name, Var->name_length, tmp));
*ErrP = SNMP_ERR_NOERROR;
variable_list *
snmp_confFn(variable_list * Var, snint * ErrP)
{
- variable_list *Answer = NULL;
- const char *cp = NULL;
+ variable_list *Answer = nullptr;
+ const char *cp = nullptr;
debugs(49, 5, "snmp_confFn: Processing request with magic " << Var->name[8] << "!");
*ErrP = SNMP_ERR_NOERROR;
variable_list *
snmp_meshPtblFn(variable_list * Var, snint * ErrP)
{
- variable_list *Answer = NULL;
+ variable_list *Answer = nullptr;
Ip::Address laddr;
- char *cp = NULL;
- CachePeer *p = NULL;
+ char *cp = nullptr;
+ CachePeer *p = nullptr;
int cnt = 0;
debugs(49, 5, "snmp_meshPtblFn: peer " << Var->name[LEN_SQ_MESH + 3] << " requested!");
*ErrP = SNMP_ERR_NOERROR;
u_int index = Var->name[LEN_SQ_MESH + 3] ;
- for (p = Config.peers; p != NULL; p = p->next, ++cnt) {
+ for (p = Config.peers; p != nullptr; p = p->next, ++cnt) {
if (p->index == index) {
laddr = p->in_addr ;
break;
}
}
- if (p == NULL) {
+ if (p == nullptr) {
*ErrP = SNMP_ERR_NOSUCHNAME;
- return NULL;
+ return nullptr;
}
switch (Var->name[LEN_SQ_MESH + 2]) {
variable_list *
snmp_prfSysFn(variable_list * Var, snint * ErrP)
{
- variable_list *Answer = NULL;
+ variable_list *Answer = nullptr;
static struct rusage rusage;
debugs(49, 5, "snmp_prfSysFn: Processing request with magic " << Var->name[LEN_SQ_PRF + 1] << "!");
variable_list *
snmp_prfProtoFn(variable_list * Var, snint * ErrP)
{
- variable_list *Answer = NULL;
- static StatCounters *f = NULL;
- static StatCounters *l = NULL;
+ variable_list *Answer = nullptr;
+ static StatCounters *f = nullptr;
+ static StatCounters *l = nullptr;
double x;
int minutes;
debugs(49, 5, "snmp_prfProtoFn: Processing request with magic " << Var->name[LEN_SQ_PRF] << "!");
default:
*ErrP = SNMP_ERR_NOSUCHNAME;
- return NULL;
+ return nullptr;
}
return snmp_var_new_integer(Var->name, Var->name_length,
}
*ErrP = SNMP_ERR_NOSUCHNAME;
- return NULL;
+ return nullptr;
}
* without having a "search" function. A search function should be written
* to make this and the other code much less evil.
*/
- mib_tree_head = snmpAddNode(snmpCreateOid(1, 1), 1, NULL, NULL, atNone, 0);
+ mib_tree_head = snmpAddNode(snmpCreateOid(1, 1), 1, nullptr, nullptr, atNone, 0);
assert(mib_tree_head);
debugs(49, 5, "snmpInit: root is " << mib_tree_head);
- snmpAddNodeStr("1", 3, NULL, NULL);
+ snmpAddNodeStr("1", 3, nullptr, nullptr);
- snmpAddNodeStr("1.3", 6, NULL, NULL);
+ snmpAddNodeStr("1.3", 6, nullptr, nullptr);
- snmpAddNodeStr("1.3.6", 1, NULL, NULL);
- snmpAddNodeStr("1.3.6.1", 4, NULL, NULL);
- snmpAddNodeStr("1.3.6.1.4", 1, NULL, NULL);
- snmpAddNodeStr("1.3.6.1.4.1", 3495, NULL, NULL);
- mib_tree_entry *m2 = snmpAddNodeStr("1.3.6.1.4.1.3495", 1, NULL, NULL);
+ snmpAddNodeStr("1.3.6", 1, nullptr, nullptr);
+ snmpAddNodeStr("1.3.6.1", 4, nullptr, nullptr);
+ snmpAddNodeStr("1.3.6.1.4", 1, nullptr, nullptr);
+ snmpAddNodeStr("1.3.6.1.4.1", 3495, nullptr, nullptr);
+ mib_tree_entry *m2 = snmpAddNodeStr("1.3.6.1.4.1.3495", 1, nullptr, nullptr);
- mib_tree_entry *n = snmpLookupNodeStr(NULL, "1.3.6.1.4.1.3495.1");
+ mib_tree_entry *n = snmpLookupNodeStr(nullptr, "1.3.6.1.4.1.3495.1");
assert(m2 == n);
/* SQ_SYS - 1.3.6.1.4.1.3495.1.1 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1", 1, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1", 1, nullptr, nullptr);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.1", SYSVMSIZ, snmp_sysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.1", SYSSTOR, snmp_sysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.1", SYS_UPTIME, snmp_sysFn, static_Inst, atMax);
/* SQ_CONF - 1.3.6.1.4.1.3495.1.2 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1", 2, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1", 2, nullptr, nullptr);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_ADMIN, snmp_confFn, static_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_VERSION, snmp_confFn, static_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_VERSION_ID, snmp_confFn, static_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_LOG_FAC, snmp_confFn, static_Inst);
/* SQ_CONF + CONF_STORAGE - 1.3.6.1.4.1.3495.1.5 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_STORAGE, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_STORAGE, nullptr, nullptr);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2.5", CONF_ST_MMAXSZ, snmp_confFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2.5", CONF_ST_SWMAXSZ, snmp_confFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2.5", CONF_ST_SWHIWM, snmp_confFn, static_Inst, atMin);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_UNIQNAME, snmp_confFn, static_Inst);
/* SQ_PRF - 1.3.6.1.4.1.3495.1.3 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1", 3, NULL, NULL); /* SQ_PRF */
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1", 3, nullptr, nullptr); /* SQ_PRF */
/* PERF_SYS - 1.3.6.1.4.1.3495.1.3.1 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.3", PERF_SYS, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.3", PERF_SYS, nullptr, nullptr);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_PF, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_NUMR, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_MEMUSAGE, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_CURMAX_FD, snmp_prfSysFn, static_Inst, atMax);
/* PERF_PROTO - 1.3.6.1.4.1.3495.1.3.2 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.3", PERF_PROTO, NULL, NULL);
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2", PERF_PROTOSTAT_AGGR, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.3", PERF_PROTO, nullptr, nullptr);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2", PERF_PROTOSTAT_AGGR, nullptr, nullptr);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_HTTP_REQ, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_HTTP_HITS, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_HTTP_ERRORS, snmp_prfProtoFn, static_Inst, atSum);
/* Note this is time-series rather than 'static' */
/* cacheMedianSvcTable */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2", PERF_PROTOSTAT_MEDIAN, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2", PERF_PROTOSTAT_MEDIAN, nullptr, nullptr);
/* cacheMedianSvcEntry */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2", 1, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2", 1, nullptr, nullptr);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_TIME, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_HTTP_ALL, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_HTTP_MISS, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_HTTP_NH, snmp_prfProtoFn, time_Inst, atAverage);
/* SQ_NET - 1.3.6.1.4.1.3495.1.4 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1", 4, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1", 4, nullptr, nullptr);
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.4", NET_IP_CACHE, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.4", NET_IP_CACHE, nullptr, nullptr);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_ENT, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_REQ, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_HITS, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_GHBN, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_LOC, snmp_netIpFn, static_Inst, atSum);
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.4", NET_FQDN_CACHE, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.4", NET_FQDN_CACHE, nullptr, nullptr);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_ENT, snmp_netFqdnFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_REQ, snmp_netFqdnFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_HITS, snmp_netFqdnFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_MISS, snmp_netFqdnFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_GHBN, snmp_netFqdnFn, static_Inst, atSum);
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.4", NET_DNS_CACHE, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.4", NET_DNS_CACHE, nullptr, nullptr);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.3", DNS_REQ, snmp_netDnsFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.3", DNS_REP, snmp_netDnsFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.3", DNS_SERVERS, snmp_netDnsFn, static_Inst, atSum);
/* SQ_MESH - 1.3.6.1.4.1.3495.1.5 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1", 5, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1", 5, nullptr, nullptr);
/* cachePeerTable - 1.3.6.1.4.1.3495.1.5.1 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.5", MESH_PTBL, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.5", MESH_PTBL, nullptr, nullptr);
/* CachePeerEntry (version 3) - 1.3.6.1.4.1.3495.1.5.1.3 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1", 3, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1", 3, nullptr, nullptr);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_INDEX, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_NAME, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_ADDR_TYPE, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_KEEPAL_R, snmp_meshPtblFn, peer_Inst);
/* cacheClientTable - 1.3.6.1.4.1.3495.1.5.2 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.5", MESH_CTBL, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.5", MESH_CTBL, nullptr, nullptr);
/* BUG 2811: we NEED to create a reliable index for the client DB and make version 3 of the table. */
/* for now we have version 2 table with OID capable of mixed IPv4 / IPv6 clients and upgraded address text format. */
/* cacheClientEntry - 1.3.6.1.4.1.3495.1.5.2.2 */
- snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2", 2, NULL, NULL);
+ snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2", 2, nullptr, nullptr);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_ADDR_TYPE, snmp_meshCtblFn, client_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_ADDR, snmp_meshCtblFn, client_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_HTREQ, snmp_meshCtblFn, client_Inst);
if (!Comm::IsConnOpen(conn))
fatalf("Cannot open SNMP %s Port",(conn->fd == snmpIncomingConn->fd?"receiving":"sending"));
- Comm::SetSelect(conn->fd, COMM_SELECT_READ, snmpHandleUdp, NULL, 0);
+ Comm::SetSelect(conn->fd, COMM_SELECT_READ, snmpHandleUdp, nullptr, 0);
if (conn->fd == snmpIncomingConn->fd)
debugs(1, DBG_IMPORTANT, "Accepting SNMP messages on " << snmpIncomingConn->local);
debugs(49, DBG_IMPORTANT, "Closing SNMP receiving port " << snmpIncomingConn->local);
snmpIncomingConn->close();
}
- snmpIncomingConn = NULL;
+ snmpIncomingConn = nullptr;
if (Comm::IsConnOpen(snmpOutgoingConn) && snmpIncomingConn != snmpOutgoingConn) {
// Perform OUT port closure so as not to step on IN port when sharing a conn.
debugs(49, DBG_IMPORTANT, "Closing SNMP sending port " << snmpOutgoingConn->local);
snmpOutgoingConn->close();
}
- snmpOutgoingConn = NULL;
+ snmpOutgoingConn = nullptr;
}
/*
debugs(49, 5, "snmpHandleUdp: Called.");
- Comm::SetSelect(sock, COMM_SELECT_READ, snmpHandleUdp, NULL, 0);
+ Comm::SetSelect(sock, COMM_SELECT_READ, snmpHandleUdp, nullptr, 0);
memset(buf, '\0', sizeof(buf));
/* Check if we have explicit permission to access SNMP data.
* default (set above) is to deny all */
if (Community) {
- ACLFilledChecklist checklist(Config.accessList.snmp, NULL, NULL);
+ ACLFilledChecklist checklist(Config.accessList.snmp, nullptr, nullptr);
checklist.src_addr = rq->from;
checklist.snmp_community = (char *) Community;
RespPDU = snmpAgentResponse(rq->PDU);
snmp_free_pdu(rq->PDU);
- if (RespPDU != NULL) {
+ if (RespPDU != nullptr) {
snmp_build(&rq->session, RespPDU, rq->outbuf, &rq->outlen);
comm_udp_sendto(rq->sock, rq->from, rq->outbuf, rq->outlen);
snmp_free_pdu(RespPDU);
struct snmp_pdu *
snmpAgentResponse(struct snmp_pdu *PDU) {
- struct snmp_pdu *Answer = NULL;
+ struct snmp_pdu *Answer = nullptr;
debugs(49, 5, "snmpAgentResponse: Called.");
for (VarPtr_ = PDU->variables; VarPtr_; VarPtr_ = VarPtr_->next_variable) {
variable_list *VarPtr = VarPtr_;
- variable_list *VarNew = NULL;
- oid *NextOidName = NULL;
+ variable_list *VarNew = nullptr;
+ oid *NextOidName = nullptr;
snint NextOidNameLen = 0;
++index;
else
ParseFn = snmpTreeGet(VarPtr->name, VarPtr->name_length);
- if (ParseFn == NULL) {
+ if (ParseFn == nullptr) {
Answer->errstat = SNMP_ERR_NOSUCHNAME;
debugs(49, 5, "snmpAgentResponse: No such oid. ");
} else {
snmp_var_free(VarPtr);
}
- if ((Answer->errstat != SNMP_ERR_NOERROR) || (VarNew == NULL)) {
+ if ((Answer->errstat != SNMP_ERR_NOERROR) || (VarNew == nullptr)) {
Answer->errindex = index;
debugs(49, 5, "snmpAgentResponse: error.");
if (VarNew)
snmp_var_free(VarNew);
- while ((VarPtr = Answer->variables) != NULL) {
+ while ((VarPtr = Answer->variables) != nullptr) {
Answer->variables = VarPtr->next_variable;
snmp_var_free(VarPtr);
}
/* Steal the original PDU list of variables for the error response */
Answer->variables = PDU->variables;
- PDU->variables = NULL;
+ PDU->variables = nullptr;
return (Answer);
}
static oid_ParseFn *
snmpTreeGet(oid * Current, snint CurrentLen)
{
- oid_ParseFn *Fn = NULL;
- mib_tree_entry *mibTreeEntry = NULL;
+ oid_ParseFn *Fn = nullptr;
+ mib_tree_entry *mibTreeEntry = nullptr;
int count = 0;
debugs(49, 5, "snmpTreeGet: Called");
if (Current[count] == mibTreeEntry->name[count]) {
++count;
- while (mibTreeEntry != NULL && count < CurrentLen) {
+ while (mibTreeEntry != nullptr && count < CurrentLen) {
mibTreeEntry = snmpTreeEntry(Current[count], count, mibTreeEntry);
- if (mibTreeEntry != NULL)
+ if (mibTreeEntry != nullptr)
type = mibTreeEntry->aggrType;
++count;
}
static oid_ParseFn *
snmpTreeNext(oid * Current, snint CurrentLen, oid ** Next, snint * NextLen)
{
- oid_ParseFn *Fn = NULL;
+ oid_ParseFn *Fn = nullptr;
int count = 0;
debugs(49, 5, "snmpTreeNext: Called");
}
debugs(49, 5, "snmpTreeNext: Recursed down to requested object");
} else {
- return NULL;
+ return nullptr;
}
if (mibTreeEntry == mib_tree_last)
if (!mibTreeEntry) {
mibTreeEntry = nextoid;
- nextoid = NULL;
+ nextoid = nullptr;
}
} else {
nextoid = mibTreeEntry;
- mibTreeEntry = NULL;
+ mibTreeEntry = nullptr;
}
}
}
debugs(49, 6, "snmpTreeNext: Next : " << snmpDebugOid(*Next, *NextLen, tmp));
return (Fn);
} else
- return NULL;
+ return nullptr;
}
static oid *
static_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn)
{
- oid *instance = NULL;
+ oid *instance = nullptr;
if (*len <= current->len) {
instance = (oid *)xmalloc(sizeof(*name) * (*len + 1));
memcpy(instance, name, sizeof(*name) * (*len));
static oid *
time_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn)
{
- oid *instance = NULL;
+ oid *instance = nullptr;
int identifier = 0, loop = 0;
int index[TIME_INDEX_LEN] = {TIME_INDEX};
static oid *
peer_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn)
{
- oid *instance = NULL;
+ oid *instance = nullptr;
CachePeer *peers = Config.peers;
- if (peers == NULL) {
+ if (peers == nullptr) {
debugs(49, 6, "snmp peer_Inst: No Peers.");
current = current->parent->parent->parent->leaves[1];
while ((current) && (!current->parsefunction))
static oid *
client_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn)
{
- oid *instance = NULL;
+ oid *instance = nullptr;
Ip::Address laddr;
Ip::Address *aux;
int size = 0;
int newshift = 0;
if (*len <= current->len) {
- aux = client_entry(NULL);
+ aux = client_entry(nullptr);
if (aux)
laddr = *aux;
else
static mib_tree_entry *
snmpTreeSiblingEntry(oid entry, snint len, mib_tree_entry * current)
{
- mib_tree_entry *next = NULL;
+ mib_tree_entry *next = nullptr;
int count = 0;
while ((!next) && (count < current->children)) {
if (count < current->children) {
next = current->leaves[count];
} else {
- next = NULL;
+ next = nullptr;
}
return (next);
static mib_tree_entry *
snmpTreeEntry(oid entry, snint len, mib_tree_entry * current)
{
- mib_tree_entry *next = NULL;
+ mib_tree_entry *next = nullptr;
int count = 0;
while ((!next) && current && (count < current->children)) {
e = mib_tree_head;
if (! snmpCreateOidFromStr(str, &name, &namelen))
- return NULL;
+ return nullptr;
/* I wish there were some kind of sensible existing tree traversal
* routine to use. I'll worry about that later */
{
char const *delim = ".";
- *name = NULL;
+ *name = nullptr;
*nl = 0;
const char *s = str;
/* Find base node */
b = snmpLookupNodeStr(mib_tree_head, base_str);
if (! b)
- return NULL;
+ return nullptr;
debugs(49, 5, "snmpAddNodeStr: " << base_str << ": -> " << b);
/* Create OID string for new entry */
snprintf(s, 1024, "%s.%d", base_str, o);
if (! snmpCreateOidFromStr(s, &n, &nl))
- return NULL;
+ return nullptr;
/* Create a node */
m = snmpAddNode(n, nl, parsefunction, instancefunction, aggrType, 0);
{
va_list args;
int loop;
- mib_tree_entry *entry = NULL;
+ mib_tree_entry *entry = nullptr;
va_start(args, children);
MemBuf tmp;
entry->parsefunction = parsefunction;
entry->instancefunction = instancefunction;
entry->children = children;
- entry->leaves = NULL;
+ entry->leaves = nullptr;
entry->aggrType = aggrType;
if (children > 0) {
addr2oid(Ip::Address &addr, oid * Dest)
{
u_int i ;
- u_char *cp = NULL;
+ u_char *cp = nullptr;
struct in_addr i4addr;
struct in6_addr i6addr;
oid code = addr.isIPv6()? INETADDRESSTYPE_IPV6 : INETADDRESSTYPE_IPV4 ;
Ssl::Config::Config():
#if USE_SSL_CRTD
- ssl_crtd(NULL),
+ ssl_crtd(nullptr),
#endif
- ssl_crt_validator(NULL)
+ ssl_crt_validator(nullptr)
{
ssl_crt_validator_Children.concurrency = 1;
}
"X509_V_ERR_OCSP_VERIFY_NEEDED",
"X509_V_ERR_OCSP_VERIFY_FAILED",
"X509_V_ERR_OCSP_CERT_UNKNOWN",
- NULL
+ nullptr
};
struct SslErrorAlias {
{"certUntrusted", certUntrusted},
{"ssl::certSelfSigned", certSelfSigned},
{"certSelfSigned", certSelfSigned},
- {NULL, NULL}
+ {nullptr, nullptr}
};
// Use std::map to optimize search.
}
if (xisdigit(*name)) {
- const long int value = strtol(name, NULL, 0);
+ const long int value = strtol(name, nullptr, 0);
if ((SQUID_TLS_ERR_OFFSET < value && value < SQUID_TLS_ERR_END) || // custom
(value >= 0)) { // an official error, including SSL_ERROR_NONE
errors.emplace(value);
bool
Ssl::ErrorIsOptional(const char *name)
{
- for (int i = 0; OptionalSslErrors[i] != NULL; ++i) {
+ for (int i = 0; OptionalSslErrors[i] != nullptr; ++i) {
if (strcmp(name, OptionalSslErrors[i]) == 0)
return true;
}
return it->second.descr.termedBuf();
}
- return NULL;
+ return nullptr;
}
const char *
return it->second.detail.termedBuf();
}
- return NULL;
+ return nullptr;
}
-Ssl::ErrorDetailsManager *Ssl::ErrorDetailsManager::TheDetailsManager = NULL;
+Ssl::ErrorDetailsManager *Ssl::ErrorDetailsManager::TheDetailsManager = nullptr;
Ssl::ErrorDetailsManager &Ssl::ErrorDetailsManager::GetInstance()
{
void Ssl::ErrorDetailsManager::Shutdown()
{
delete TheDetailsManager;
- TheDetailsManager = NULL;
+ TheDetailsManager = nullptr;
}
Ssl::ErrorDetailsManager::ErrorDetailsManager()
return it->second;
}
- return NULL;
+ return nullptr;
}
void Ssl::ErrorDetailsManager::cacheDetails(ErrorDetailsList::Pointer &errorDetails)
{
#if USE_ERR_LOCALES
String hdr;
- if (request != NULL && request->header.getList(Http::HdrType::ACCEPT_LANGUAGE, &hdr)) {
- ErrorDetailsList::Pointer errDetails = NULL;
+ if (request != nullptr && request->header.getList(Http::HdrType::ACCEPT_LANGUAGE, &hdr)) {
+ ErrorDetailsList::Pointer errDetails = nullptr;
//Try to retrieve from cache
size_t pos = 0;
char lang[256];
}
}
- if (errDetails != NULL && errDetails->getRecord(value, entry))
+ if (errDetails != nullptr && errDetails->getRecord(value, entry))
return true;
}
#else
ACLFilledChecklist *acl_checklist = new ACLFilledChecklist(
::Config.accessList.ssl_bump,
- request.getRaw(), NULL);
+ request.getRaw(), nullptr);
acl_checklist->al = al;
acl_checklist->banAction(Acl::Answer(ACCESS_ALLOWED, Ssl::bumpNone));
acl_checklist->banAction(Acl::Answer(ACCESS_ALLOWED, Ssl::bumpPeek));
if (ConnStateData *csd = request->clientConnectionManager.valid()) {
- SBuf *hostName = NULL;
+ SBuf *hostName = nullptr;
//Enable Status_request TLS extension, required to bump some clients
SSL_set_tlsext_status_type(serverSession.get(), TLSEXT_STATUSTYPE_ocsp);
Ssl::ServerBump::sslErrors() const
{
if (!serverSession)
- return NULL;
+ return nullptr;
const Security::CertErrors *errs = static_cast<const Security::CertErrors*>(SSL_get_ex_data(serverSession.get(), ssl_ex_index_ssl_errors));
return errs;
BIO_meth_set_write(SquidMethods, squid_bio_write);
BIO_meth_set_read(SquidMethods, squid_bio_read);
BIO_meth_set_puts(SquidMethods, squid_bio_puts);
- BIO_meth_set_gets(SquidMethods, NULL);
+ BIO_meth_set_gets(SquidMethods, nullptr);
BIO_meth_set_ctrl(SquidMethods, squid_bio_ctrl);
BIO_meth_set_create(SquidMethods, squid_bio_create);
BIO_meth_set_destroy(SquidMethods, squid_bio_destroy);
BIO_int_ctrl(bio, BIO_C_SET_FD, type, fd);
return bio;
}
- return NULL;
+ return nullptr;
}
void
// No need to set more, openSSL initialize BIO memory to zero.
#endif
- BIO_set_data(bi, NULL);
+ BIO_set_data(bi, nullptr);
return 1;
}
squid_bio_destroy(BIO *table)
{
delete static_cast<Ssl::Bio*>(BIO_get_data(table));
- BIO_set_data(table, NULL);
+ BIO_set_data(table, nullptr);
return 1;
}
const char *e = label + len -1;
while (e != label && xisdigit(*e)) --e;
if (e != label) ++e;
- return strtol(e, 0, 10);
+ return strtol(e, nullptr, 10);
}
bool
certs.push_back(ci);
const char *b = strstr(value, "-----END CERTIFICATE-----");
- if (b == NULL) {
+ if (b == nullptr) {
throw TextException(ToSBuf("Missing END CERTIFICATE boundary: ", value), Here());
}
b += strlen("-----END CERTIFICATE-----");
if (ci->name.compare(name) == 0)
return ci->cert.get();
}
- return NULL;
+ return nullptr;
}
uint64_t
std::map<Ip::Address, LocalContextStorage *>::iterator i = storage.find(address);
if (i == storage.end())
- return NULL;
+ return nullptr;
else
return i->second;
}
std::string temp_body(body.c_str(), body.length());
char * buffer = const_cast<char *>(temp_body.c_str());
char * token = strtok(buffer, "\r\n");
- while (token != NULL) {
+ while (token != nullptr) {
std::string current_string(token);
size_t equal_pos = current_string.find('=');
if (equal_pos == std::string::npos) {
std::string value(current_string.c_str() + equal_pos + 1);
map.insert(std::make_pair(param, value));
}
- token = strtok(NULL, "\r\n");
+ token = strtok(nullptr, "\r\n");
}
}
Security::PrivateKeyPointer pkey(EVP_PKEY_new());
if (!pkey)
- return NULL;
+ return nullptr;
BIGNUM_Pointer bn(BN_new());
if (!bn)
- return NULL;
+ return nullptr;
if (!BN_set_word(bn.get(), RSA_F4))
- return NULL;
+ return nullptr;
Ssl::RSA_Pointer rsa(RSA_new());
if (!rsa)
- return NULL;
+ return nullptr;
int num = 2048; // Maybe use 4096 RSA keys, or better make it configurable?
- if (!RSA_generate_key_ex(rsa.get(), num, bn.get(), NULL))
- return NULL;
+ if (!RSA_generate_key_ex(rsa.get(), num, bn.get(), nullptr))
+ return nullptr;
if (!EVP_PKEY_assign_RSA(pkey.get(), (rsa.get())))
- return NULL;
+ return nullptr;
rsa.release();
return pkey.release();
if (!PEM_write_bio_X509 (bio.get(), cert.get()))
return false;
- if (!PEM_write_bio_PrivateKey(bio.get(), pkey.get(), NULL, NULL, 0, NULL, NULL))
+ if (!PEM_write_bio_PrivateKey(bio.get(), pkey.get(), nullptr, nullptr, 0, nullptr, nullptr))
return false;
- char *ptr = NULL;
+ char *ptr = nullptr;
long len = BIO_get_mem_data(bio.get(), &ptr);
if (!ptr)
return false;
if (!PEM_write_bio_X509 (bio.get(), cert.get()))
return false;
- char *ptr = NULL;
+ char *ptr = nullptr;
long len = BIO_get_mem_data(bio.get(), &ptr);
if (!ptr)
return false;
return false;
}
- EVP_PKEY * pkeyPtr = NULL;
- pkey.resetWithoutLocking(PEM_read_bio_PrivateKey(bio.get(), &pkeyPtr, 0, 0));
+ EVP_PKEY * pkeyPtr = nullptr;
+ pkey.resetWithoutLocking(PEM_read_bio_PrivateKey(bio.get(), &pkeyPtr, nullptr, nullptr));
if (!pkey)
return false;
"signTrusted",
"signUntrusted",
"signSelf",
- NULL
+ nullptr
};
const char *Ssl::CertAdaptAlgorithmStr[] = {
"setValidAfter",
"setValidBefore",
"setCommonName",
- NULL
+ nullptr
};
Ssl::CertificateProperties::CertificateProperties():
setValidBefore(false),
setCommonName(false),
signAlgorithm(Ssl::algSignEnd),
- signHash(NULL)
+ signHash(nullptr)
{}
static void
certKey.append(certSignAlgorithm(properties.signAlgorithm));
}
- if (properties.signHash != NULL) {
+ if (properties.signHash != nullptr) {
certKey.append("+SignHash=", 10);
certKey.append(EVP_MD_name(properties.signHash));
}
if (!method)
return false;
- unsigned char *ext_der = NULL;
+ unsigned char *ext_der = nullptr;
int ext_len = ASN1_item_i2d((ASN1_VALUE *)theAuthKeyId.get(), &ext_der, ASN1_ITEM_ptr(method->it));
Ssl::ASN1_OCTET_STRING_Pointer extOct(ASN1_OCTET_STRING_new());
extOct.get()->data = ext_der;
extOct.get()->length = ext_len;
- Ssl::X509_EXTENSION_Pointer extAuthKeyId(X509_EXTENSION_create_by_NID(NULL, NID_authority_key_identifier, 0, extOct.get()));
+ Ssl::X509_EXTENSION_Pointer extAuthKeyId(X509_EXTENSION_create_by_NID(nullptr, NID_authority_key_identifier, 0, extOct.get()));
if (!extAuthKeyId.get())
return false;
// that the more stringent requirements are met.
const int p = X509_get_ext_by_NID(cert.get(), NID_key_usage, -1);
- if ((ext = X509_get_ext(cert.get(), p)) != NULL) {
+ if ((ext = X509_get_ext(cert.get(), p)) != nullptr) {
ASN1_BIT_STRING *keyusage = (ASN1_BIT_STRING *)X509V3_EXT_d2i(ext);
ASN1_BIT_STRING_set_bit(keyusage, KeyEncipherment, 1);
//Build the ASN1_OCTET_STRING
const X509V3_EXT_METHOD *method = X509V3_EXT_get(ext);
assert(method && method->it);
- unsigned char *ext_der = NULL;
+ unsigned char *ext_der = nullptr;
int ext_len = ASN1_item_i2d((ASN1_VALUE *)keyusage,
&ext_der,
(const ASN1_ITEM *)ASN1_ITEM_ptr(method->it));
if (res <= 0 || res >= static_cast<int>(sizeof(dnsName)))
return false;
- X509_EXTENSION *ext = X509V3_EXT_conf_nid(NULL, NULL, NID_subject_alt_name, dnsName);
+ X509_EXTENSION *ext = X509V3_EXT_conf_nid(nullptr, nullptr, NID_subject_alt_name, dnsName);
if (!ext)
return false;
// fields from caCert.
// Currently there is not any way in openssl tollkit to compare two ASN1_TIME
// objects.
- ASN1_TIME *aTime = NULL;
+ ASN1_TIME *aTime = nullptr;
if (!properties.setValidBefore && properties.mimicCert.get())
aTime = X509_getm_notBefore(properties.mimicCert.get());
if (!aTime && properties.signWithX509.get())
} else if (!X509_gmtime_adj(X509_getm_notBefore(cert.get()), (-2)*24*60*60))
return false;
- aTime = NULL;
+ aTime = nullptr;
if (!properties.setValidAfter && properties.mimicCert.get())
aTime = X509_getm_notAfter(properties.mimicCert.get());
if (!aTime && properties.signWithX509.get())
assert(n == 20); //for sha1 n is 20 (for md5 n is 16)
- BIGNUM *serial = NULL;
- serial = BN_bin2bn(md, n, NULL);
+ BIGNUM *serial = nullptr;
+ serial = BN_bin2bn(md, n, nullptr);
// if the serial is "0" set it to '1'
if (BN_is_zero(serial) == true)
unsigned char md[EVP_MAX_MD_SIZE];
if (!X509_digest(cert.get(),EVP_sha1(),md,&n))
- return NULL;
+ return nullptr;
return createCertSerial(md, n);
}
unsigned char md[EVP_MAX_MD_SIZE];
if (!X509_pubkey_digest(cert.get(),EVP_sha1(),md,&n))
- return NULL;
+ return nullptr;
return createCertSerial(md, n);
}
Ssl::ReadPrivateKey(Ssl::BIO_Pointer &bio, Security::PrivateKeyPointer &pkey, pem_password_cb *passwd_callback)
{
assert(bio);
- if (EVP_PKEY *akey = PEM_read_bio_PrivateKey(bio.get(), NULL, passwd_callback, NULL)) {
+ if (EVP_PKEY *akey = PEM_read_bio_PrivateKey(bio.get(), nullptr, passwd_callback, nullptr)) {
pkey.resetWithoutLocking(akey);
return true;
}
{
if (!pkey || !bio)
return false;
- if (!PEM_write_bio_PrivateKey(bio.get(), pkey.get(), NULL, NULL, 0, NULL, NULL))
+ if (!PEM_write_bio_PrivateKey(bio.get(), pkey.get(), nullptr, nullptr, 0, nullptr, nullptr))
return false;
return true;
}
// Compare subjectAltName extension
STACK_OF(GENERAL_NAME) * cert1_altnames;
- cert1_altnames = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
+ cert1_altnames = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr);
STACK_OF(GENERAL_NAME) * cert2_altnames;
- cert2_altnames = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(cert2, NID_subject_alt_name, NULL, NULL);
+ cert2_altnames = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(cert2, NID_subject_alt_name, nullptr, nullptr);
bool match = true;
if (cert1_altnames) {
int numalts = sk_GENERAL_NAME_num(cert1_altnames);
static char name[1024] = ""; // stores common name (CN)
if (!x509)
- return NULL;
+ return nullptr;
// TODO: What if the entry is a UTF8String? See X509_NAME_get_index_by_NID(3ssl).
const int nameLen = X509_NAME_get_text_by_NID(
if (nameLen > 0)
return name;
- return NULL;
+ return nullptr;
}
const char *Ssl::CommonHostName(X509 *x509)
return false;
int cert1Len;
- unsigned char *cert1Asn = NULL;
+ unsigned char *cert1Asn = nullptr;
cert1Len = ASN1_item_i2d((ASN1_VALUE *)cert1.get(), &cert1Asn, ASN1_ITEM_rptr(X509));
int cert2Len;
- unsigned char *cert2Asn = NULL;
+ unsigned char *cert2Asn = nullptr;
cert2Len = ASN1_item_i2d((ASN1_VALUE *)cert2.get(), &cert2Asn, ASN1_ITEM_rptr(X509));
if (cert1Len != cert2Len)
if (sg >=0 && sg < Ssl::algSignEnd)
return Ssl::CertSignAlgorithmStr[sg];
- return NULL;
+ return nullptr;
}
/**
*/
inline CertSignAlgorithm certSignAlgorithmId(const char *sg)
{
- for (int i = 0; i < algSignEnd && Ssl::CertSignAlgorithmStr[i] != NULL; i++)
+ for (int i = 0; i < algSignEnd && Ssl::CertSignAlgorithmStr[i] != nullptr; i++)
if (strcmp(Ssl::CertSignAlgorithmStr[i], sg) == 0)
return (CertSignAlgorithm)i;
if (alg >=0 && alg < Ssl::algSetEnd)
return Ssl::CertAdaptAlgorithmStr[alg];
- return NULL;
+ return nullptr;
}
/**
void Ssl::Helper::Init()
{
- assert(ssl_crtd == NULL);
+ assert(ssl_crtd == nullptr);
// we need to start ssl_crtd only if some port(s) need to bump SSL *and* generate certificates
// TODO: generate host certificates for SNI enabled accel ports
bool found = false;
- for (AnyP::PortCfgPointer s = HttpPortList; !found && s != NULL; s = s->next)
+ for (AnyP::PortCfgPointer s = HttpPortList; !found && s != nullptr; s = s->next)
found = s->flags.tunnelSslBumping && s->secure.generateHostCertificates;
if (!found)
return;
// The crtd messages may contain the eol ('\n') character. We are
// going to use the '\1' char as the end-of-message mark.
ssl_crtd->eom = '\1';
- assert(ssl_crtd->cmdline == NULL);
+ assert(ssl_crtd->cmdline == nullptr);
{
char *tmp = xstrdup(Ssl::TheConfig.ssl_crtd);
char *tmp_begin = tmp;
- char *token = NULL;
- while ((token = strwordtok(NULL, &tmp))) {
+ char *token = nullptr;
+ while ((token = strwordtok(nullptr, &tmp))) {
wordlistAdd(&ssl_crtd->cmdline, token);
}
safe_free(tmp_begin);
helperShutdown(ssl_crtd);
wordlistDestroy(&ssl_crtd->cmdline);
delete ssl_crtd;
- ssl_crtd = NULL;
+ ssl_crtd = nullptr;
}
void
if (!Ssl::TheConfig.ssl_crt_validator)
return;
- assert(ssl_crt_validator == NULL);
+ assert(ssl_crt_validator == nullptr);
// we need to start ssl_crtd only if some port(s) need to bump SSL
bool found = false;
- for (AnyP::PortCfgPointer s = HttpPortList; !found && s != NULL; s = s->next)
+ for (AnyP::PortCfgPointer s = HttpPortList; !found && s != nullptr; s = s->next)
found = s->flags.tunnelSslBumping;
if (!found)
return;
// The crtd messages may contain the eol ('\n') character. We are
// going to use the '\1' char as the end-of-message mark.
ssl_crt_validator->eom = '\1';
- assert(ssl_crt_validator->cmdline == NULL);
+ assert(ssl_crt_validator->cmdline == nullptr);
/* defaults */
int ttl = 3600; // 1 hour
// TODO: Do this during parseConfigFile() for proper parsing, error handling
char *tmp = xstrdup(Ssl::TheConfig.ssl_crt_validator);
char *tmp_begin = tmp;
- char * token = NULL;
+ char * token = nullptr;
bool parseParams = true;
- while ((token = strwordtok(NULL, &tmp))) {
+ while ((token = strwordtok(nullptr, &tmp))) {
if (parseParams) {
if (strcmp(token, "ttl=infinity") == 0) {
ttl = std::numeric_limits<CacheType::Ttl>::max();
helperOpenServers(ssl_crt_validator);
//WARNING: initializing static member in an object initialization method
- assert(HelperCache == NULL);
+ assert(HelperCache == nullptr);
HelperCache = new CacheType(cache, ttl);
}
helperShutdown(ssl_crt_validator);
wordlistDestroy(&ssl_crt_validator->cmdline);
delete ssl_crt_validator;
- ssl_crt_validator = NULL;
+ ssl_crt_validator = nullptr;
// CertValidationHelper::HelperCache is a static member, it is not good policy to
// reset it here. Will work because the current Ssl::CertValidationHelper is
// always the same static object.
delete HelperCache;
- HelperCache = NULL;
+ HelperCache = nullptr;
}
void
static Ssl::CertsIndexedList SquidUntrustedCerts;
-const EVP_MD *Ssl::DefaultSignHash = NULL;
+const EVP_MD *Ssl::DefaultSignHash = nullptr;
std::vector<const char *> Ssl::BumpModeStr = {
"none",
}
STACK_OF(GENERAL_NAME) * altnames;
- altnames = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(peer_cert, NID_subject_alt_name, NULL, NULL);
+ altnames = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(peer_cert, NID_subject_alt_name, nullptr, nullptr);
if (altnames) {
int numalts = sk_GENERAL_NAME_num(altnames);
if (!SSL_set_ex_data(ssl, ssl_ex_index_ssl_errors, (void *)errs)) {
debugs(83, 2, "Failed to set ssl error_no in ssl_verify_cb: Certificate " << *peer_cert);
delete errs;
- errs = NULL;
+ errs = nullptr;
}
} else // remember another error number
errs->push_back_unique(Security::CertError(error_no, broken_cert, depth));
if (!Ssl::DefaultSignHash)
fatalf("Sign hash '%s' is not supported\n", defName);
- ssl_ex_index_server = SSL_get_ex_new_index(0, (void *) "server", NULL, NULL, ssl_free_SBuf);
- ssl_ctx_ex_index_dont_verify_domain = SSL_CTX_get_ex_new_index(0, (void *) "dont_verify_domain", NULL, NULL, NULL);
- ssl_ex_index_cert_error_check = SSL_get_ex_new_index(0, (void *) "cert_error_check", NULL, &ssl_dupAclChecklist, &ssl_freeAclChecklist);
- ssl_ex_index_ssl_error_detail = SSL_get_ex_new_index(0, (void *) "ssl_error_detail", NULL, NULL, &ssl_free_ErrorDetail);
- ssl_ex_index_ssl_peeked_cert = SSL_get_ex_new_index(0, (void *) "ssl_peeked_cert", NULL, NULL, &ssl_free_X509);
- ssl_ex_index_ssl_errors = SSL_get_ex_new_index(0, (void *) "ssl_errors", NULL, NULL, &ssl_free_SslErrors);
- ssl_ex_index_ssl_cert_chain = SSL_get_ex_new_index(0, (void *) "ssl_cert_chain", NULL, NULL, &ssl_free_CertChain);
- ssl_ex_index_ssl_validation_counter = SSL_get_ex_new_index(0, (void *) "ssl_validation_counter", NULL, NULL, &ssl_free_int);
+ ssl_ex_index_server = SSL_get_ex_new_index(0, (void *) "server", nullptr, nullptr, ssl_free_SBuf);
+ ssl_ctx_ex_index_dont_verify_domain = SSL_CTX_get_ex_new_index(0, (void *) "dont_verify_domain", nullptr, nullptr, nullptr);
+ ssl_ex_index_cert_error_check = SSL_get_ex_new_index(0, (void *) "cert_error_check", nullptr, &ssl_dupAclChecklist, &ssl_freeAclChecklist);
+ ssl_ex_index_ssl_error_detail = SSL_get_ex_new_index(0, (void *) "ssl_error_detail", nullptr, nullptr, &ssl_free_ErrorDetail);
+ ssl_ex_index_ssl_peeked_cert = SSL_get_ex_new_index(0, (void *) "ssl_peeked_cert", nullptr, nullptr, &ssl_free_X509);
+ ssl_ex_index_ssl_errors = SSL_get_ex_new_index(0, (void *) "ssl_errors", nullptr, nullptr, &ssl_free_SslErrors);
+ ssl_ex_index_ssl_cert_chain = SSL_get_ex_new_index(0, (void *) "ssl_cert_chain", nullptr, nullptr, &ssl_free_CertChain);
+ ssl_ex_index_ssl_validation_counter = SSL_get_ex_new_index(0, (void *) "ssl_validation_counter", nullptr, nullptr, &ssl_free_int);
ssl_ex_index_verify_callback_parameters = SSL_get_ex_new_index(0, (void *) "verify_callback_parameters", nullptr, nullptr, &ssl_free_VerifyCallbackParameters);
}
const char *ret;
if (!cert)
- return NULL;
+ return nullptr;
name = X509_get_subject_name(cert);
{
static char buf[1024];
if (!cert)
- return NULL;
+ return nullptr;
unsigned int n;
unsigned char md[EVP_MAX_MD_SIZE];
if (!X509_digest(cert, EVP_sha1(), md, &n))
- return NULL;
+ return nullptr;
assert(3 * n + 1 < sizeof(buf));
const char *ret;
if (!cert)
- return NULL;
+ return nullptr;
name = X509_get_issuer_name(cert);
const char *sslGetUserAttribute(SSL *ssl, const char *attribute_name)
{
if (!ssl)
- return NULL;
+ return nullptr;
X509 *cert = SSL_get_peer_certificate(ssl);
const char *sslGetCAAttribute(SSL *ssl, const char *attribute_name)
{
if (!ssl)
- return NULL;
+ return nullptr;
X509 *cert = SSL_get_peer_certificate(ssl);
AUTHORITY_INFO_ACCESS *info;
if (!cert)
return nullptr;
- info = static_cast<AUTHORITY_INFO_ACCESS *>(X509_get_ext_d2i(cert, NID_info_access, NULL, NULL));
+ info = static_cast<AUTHORITY_INFO_ACCESS *>(X509_get_ext_d2i(cert, NID_info_access, nullptr, nullptr));
if (!info)
return nullptr;
{
const auto name = Security::IssuerName(*cert);
if (name.isEmpty())
- return NULL;
+ return nullptr;
const auto ret = list.equal_range(name);
for (Ssl::CertsIndexedList::iterator it = ret.first; it != ret.second; ++it) {
return issuer;
}
}
- return NULL;
+ return nullptr;
}
/// slowly find the issuer certificate of a given cert using linear search
void
Ssl::useSquidUntrusted(SSL_CTX *sslContext)
{
- SSL_CTX_set_cert_verify_callback(sslContext, untrustedToStoreCtx_cb, NULL);
+ SSL_CTX_set_cert_verify_callback(sslContext, untrustedToStoreCtx_cb, nullptr);
}
bool
bio_sbuf_create(BIO* bio)
{
BIO_set_init(bio, 0);
- BIO_set_data(bio, NULL);
+ BIO_set_data(bio, nullptr);
return 1;
}
*/
inline const char *bumpMode(int bm)
{
- return (0 <= bm && bm < Ssl::bumpEnd) ? Ssl::BumpModeStr.at(bm) : NULL;
+ return (0 <= bm && bm < Ssl::bumpEnd) ? Ssl::BumpModeStr.at(bm) : nullptr;
}
/// certificates indexed by issuer name
mb->appendf("\t%d locks, %d clients, %d refs\n", (int) e->locks(), storePendingNClients(e), (int) e->refcount);
mb->appendf("\tSwap Dir %d, File %#08X\n", e->swap_dirn, e->swap_filen);
- if (mem != NULL)
+ if (mem != nullptr)
mem->stat (mb);
mb->append("\n", 1);
static void
stat_objects_get(StoreEntry * sentry)
{
- statObjectsStart(sentry, NULL);
+ statObjectsStart(sentry, nullptr);
}
static int
static int
statObjectsOpenfdFilter(const StoreEntry * e)
{
- if (e->mem_obj == NULL)
+ if (e->mem_obj == nullptr)
return 0;
- if (e->mem_obj->swapout.sio == NULL)
+ if (e->mem_obj->swapout.sio == nullptr)
return 0;
return 1;
statCountersInit(&statCounter);
- eventAdd("statAvgTick", statAvgTick, NULL, (double) COUNT_INTERVAL, 1);
+ eventAdd("statAvgTick", statAvgTick, nullptr, (double) COUNT_INTERVAL, 1);
- ClientActiveRequests.head = NULL;
+ ClientActiveRequests.head = nullptr;
- ClientActiveRequests.tail = NULL;
+ ClientActiveRequests.tail = nullptr;
statRegisterWithCacheManager();
}
statAvgTick(void *)
{
struct rusage rusage;
- eventAdd("statAvgTick", statAvgTick, NULL, (double) COUNT_INTERVAL, 1);
+ eventAdd("statAvgTick", statAvgTick, nullptr, (double) COUNT_INTERVAL, 1);
squid_getrusage(&rusage);
statCounter.page_faults = rusage_pagefaults(&rusage);
statCounter.cputime = rusage_cputime(&rusage);
statCountersHistograms(StoreEntry * sentry)
{
storeAppendPrintf(sentry, "client_http.allSvcTime histogram:\n");
- statCounter.client_http.allSvcTime.dump(sentry, NULL);
+ statCounter.client_http.allSvcTime.dump(sentry, nullptr);
storeAppendPrintf(sentry, "client_http.missSvcTime histogram:\n");
- statCounter.client_http.missSvcTime.dump(sentry, NULL);
+ statCounter.client_http.missSvcTime.dump(sentry, nullptr);
storeAppendPrintf(sentry, "client_http.nearMissSvcTime histogram:\n");
- statCounter.client_http.nearMissSvcTime.dump(sentry, NULL);
+ statCounter.client_http.nearMissSvcTime.dump(sentry, nullptr);
storeAppendPrintf(sentry, "client_http.nearHitSvcTime histogram:\n");
- statCounter.client_http.nearHitSvcTime.dump(sentry, NULL);
+ statCounter.client_http.nearHitSvcTime.dump(sentry, nullptr);
storeAppendPrintf(sentry, "client_http.hitSvcTime histogram:\n");
- statCounter.client_http.hitSvcTime.dump(sentry, NULL);
+ statCounter.client_http.hitSvcTime.dump(sentry, nullptr);
storeAppendPrintf(sentry, "icp.querySvcTime histogram:\n");
- statCounter.icp.querySvcTime.dump(sentry, NULL);
+ statCounter.icp.querySvcTime.dump(sentry, nullptr);
storeAppendPrintf(sentry, "icp.replySvcTime histogram:\n");
- statCounter.icp.replySvcTime.dump(sentry, NULL);
+ statCounter.icp.replySvcTime.dump(sentry, nullptr);
storeAppendPrintf(sentry, "dns.svc_time histogram:\n");
- statCounter.dns.svcTime.dump(sentry, NULL);
+ statCounter.dns.svcTime.dump(sentry, nullptr);
storeAppendPrintf(sentry, "select_fds_hist histogram:\n");
- statCounter.select_fds_hist.dump(sentry, NULL);
+ statCounter.select_fds_hist.dump(sentry, nullptr);
}
static void
char buf[MAX_IPSTRLEN];
for (i = ClientActiveRequests.head; i; i = i->next) {
- const char *p = NULL;
+ const char *p = nullptr;
http = static_cast<ClientHttpRequest *>(i->data);
assert(http);
ConnStateData * conn = http->getConn();
storeAppendPrintf(s, "Connection: %p\n", conn);
- if (conn != NULL) {
+ if (conn != nullptr) {
const int fd = conn->clientConnection->fd;
storeAppendPrintf(s, "\tFD %d, read %" PRId64 ", wrote %" PRId64 "\n", fd,
fd_table[fd].bytes_read, fd_table[fd].bytes_written);
(int) http->al->cache.start_time.tv_usec,
tvSubDsec(http->al->cache.start_time, current_time));
#if USE_AUTH
- if (http->request->auth_user_request != NULL)
+ if (http->request->auth_user_request != nullptr)
p = http->request->auth_user_request->username();
else
#endif
p = http->request->extacl_user.termedBuf();
}
- if (!p && conn != NULL && conn->clientConnection->rfc931[0])
+ if (!p && conn != nullptr && conn->clientConnection->rfc931[0])
p = conn->clientConnection->rfc931;
#if USE_OPENSSL
- if (!p && conn != NULL && Comm::IsConnOpen(conn->clientConnection))
+ if (!p && conn != nullptr && Comm::IsConnOpen(conn->clientConnection))
p = sslGetUserEmail(fd_table[conn->clientConnection->fd].ssl.get());
#endif
if (result)
return *result;
- return NULL;
+ return nullptr;
}
size_t
return nodes.start()->data;
}
- mem_node *candidate = NULL;
+ mem_node *candidate = nullptr;
/* case 2: location fits within an extant node */
if (offset > 0) {
if (result)
return result->data;
- return NULL;
+ return nullptr;
}
const Splay<mem_node *> &
REMOVALPOLICYCREATE *create;
};
-static storerepl_entry_t *storerepl_list = NULL;
+static storerepl_entry_t *storerepl_list = nullptr;
/*
* local function prototypes
* local variables
*/
static std::stack<StoreEntry*> LateReleaseStack;
-MemAllocator *StoreEntry::pool = NULL;
+MemAllocator *StoreEntry::pool = nullptr;
void
Store::Stats(StoreEntry * output)
size_t
StoreEntry::bytesWanted (Range<size_t> const aRange, bool ignoreDelayPools) const
{
- if (mem_obj == NULL)
+ if (mem_obj == nullptr)
return aRange.end;
#if URL_CHECKSUM_DEBUG
}
StoreEntry::StoreEntry() :
- mem_obj(NULL),
+ mem_obj(nullptr),
timestamp(-1),
lastref(-1),
expires(-1),
void
StoreEntry::kickProducer()
{
- if (deferredProducer != NULL) {
+ if (deferredProducer != nullptr) {
ScheduleCallHere(deferredProducer);
- deferredProducer = NULL;
+ deferredProducer = nullptr;
}
}
#endif
if (auto memObj = mem_obj) {
setMemStatus(NOT_IN_MEMORY);
- mem_obj = NULL;
+ mem_obj = nullptr;
delete memObj;
}
}
{
debugs(20, 3, "destroyStoreEntry: destroying " << data);
StoreEntry *e = static_cast<StoreEntry *>(static_cast<hash_link *>(data));
- assert(e != NULL);
+ assert(e != nullptr);
// Store::Root() is FATALly missing during shutdown
if (e->hasDisk() && !shutting_down)
e->hashDelete();
- assert(e->key == NULL);
+ assert(e->key == nullptr);
delete e;
}
if (key) { // some test cases do not create keys and do not hashInsert()
hash_remove_link(store_table, this);
storeKeyFree((const cache_key *)key);
- key = NULL;
+ key = nullptr;
}
}
{
StoreEntry *e = storeGetPublicByRequestMethod(req, req->method, keyScope);
- if (e == NULL && req->method == Http::METHOD_HEAD)
+ if (e == nullptr && req->method == Http::METHOD_HEAD)
/* We can generate a HEAD reply from a cached GET object */
e = storeGetPublicByRequestMethod(req, Http::METHOD_GET, keyScope);
mem_obj->id = getKeyCounter();
const cache_key *newkey = storeKeyPrivate();
- assert(hash_lookup(store_table, newkey) == NULL);
+ assert(hash_lookup(store_table, newkey) == nullptr);
EBIT_SET(flags, KEY_PRIVATE);
shareableWhenPrivate = shareable;
hashInsert(newkey);
StoreEntry *
storeCreatePureEntry(const char *url, const char *log_url, const HttpRequestMethod& method)
{
- StoreEntry *e = NULL;
+ StoreEntry *e = nullptr;
debugs(20, 3, "storeCreateEntry: '" << url << "'");
e = new StoreEntry();
void
StoreEntry::write (StoreIOBuffer writeBuffer)
{
- assert(mem_obj != NULL);
+ assert(mem_obj != nullptr);
/* This assert will change when we teach the store to update */
assert(store_status == STORE_PENDING);
void
StoreEntry::append(char const *buf, int len)
{
- assert(mem_obj != NULL);
+ assert(mem_obj != nullptr);
assert(len >= 0);
assert(store_status == STORE_PENDING);
{
++statCounter.aborted_requests;
assert(store_status == STORE_PENDING);
- assert(mem_obj != NULL);
+ assert(mem_obj != nullptr);
debugs(20, 6, "storeAbort: " << getMD5Text());
lock("StoreEntry::abort"); /* lock while aborting */
Store::Root().maintain();
/* Reregister a maintain event .. */
- eventAdd("MaintainSwapSpace", Maintain, NULL, 1.0, 1);
+ eventAdd("MaintainSwapSpace", Maintain, nullptr, 1.0, 1);
}
static int n = 0;
if (Store::Controller::store_dirs_rebuilding) {
- eventAdd("storeLateRelease", storeLateRelease, NULL, 1.0, 1);
+ eventAdd("storeLateRelease", storeLateRelease, nullptr, 1.0, 1);
return;
}
++n;
}
- eventAdd("storeLateRelease", storeLateRelease, NULL, 0.0, 1);
+ eventAdd("storeLateRelease", storeLateRelease, nullptr, 0.0, 1);
}
/// whether the base response has all the body bytes we expect
StoreEntry::validLength() const
{
int64_t diff;
- assert(mem_obj != NULL);
+ assert(mem_obj != nullptr);
const auto reply = &mem_obj->baseReply();
debugs(20, 3, "storeEntryValidLength: Checking '" << getMD5Text() << "'");
debugs(20, 5, "storeEntryValidLength: object_len = " <<
mem_policy = createRemovalPolicy(Config.memPolicy);
storeDigestInit();
storeLogOpen();
- eventAdd("storeLateRelease", storeLateRelease, NULL, 1.0, 1);
+ eventAdd("storeLateRelease", storeLateRelease, nullptr, 1.0, 1);
Store::Root().init();
storeRebuildStart();
if (!checkCachable())
return 0;
- if (mem_obj == NULL)
+ if (mem_obj == nullptr)
return 0;
if (mem_obj->data_hdr.size() == 0)
#if USE_CACHE_DIGESTS
delete store_digest;
#endif
- store_digest = NULL;
+ store_digest = nullptr;
}
int
return;
}
- assert(mem_obj != NULL);
+ assert(mem_obj != nullptr);
if (new_status == IN_MEMORY) {
assert(mem_obj->inmem_lo == 0);
const char *
StoreEntry::url() const
{
- if (mem_obj == NULL)
+ if (mem_obj == nullptr)
return "[null_mem_obj]";
else
return mem_obj->storeId();
debugs(20, DBG_IMPORTANT, "ERROR: Be sure to have set cache_replacement_policy");
debugs(20, DBG_IMPORTANT, "ERROR: and memory_replacement_policy in squid.conf!");
fatalf("ERROR: Unknown policy %s\n", settings->type);
- return NULL; /* NOTREACHED */
+ return nullptr; /* NOTREACHED */
}
void
}
bool matched = false;
- const char *pos = NULL;
+ const char *pos = nullptr;
const char *item;
int ilen;
while (!matched && strListGetItem(&reqETags, ',', &item, &ilen, &pos)) {
swapDir(new Disks),
sharedMemStore(nullptr),
localMemStore(false),
- transients(NULL)
+ transients(nullptr)
{
assert(!store_table);
}
// fall through
}
}
- return NULL;
+ return nullptr;
}
/// indexes and adds SMP-tracking for an ephemeral peek() result
Store::Disk::Disk(char const *aType): theType(aType),
max_size(0), min_objsize(-1), max_objsize (-1),
- path(NULL), index(-1), disker(-1),
- repl(NULL), removals(0), scanned(0),
- cleanLog(NULL)
+ path(nullptr), index(-1), disker(-1),
+ repl(nullptr), removals(0), scanned(0),
+ cleanLog(nullptr)
{
fs.blksize = 1024;
}
ConfigOption *newOption = getOptionTree();
- while ((name = ConfigParser::NextToken()) != NULL) {
+ while ((name = ConfigParser::NextToken()) != nullptr) {
value = strchr(name, '=');
if (value) {
return false;
}
- int64_t size = strtoll(value, NULL, 10);
+ int64_t size = strtoll(value, nullptr, 10);
if (isaReconfig && *val != size) {
if (allowOptionReconfigure(option)) {
StoreEntry *
Store::Disk::get(const cache_key *)
{
- return NULL;
+ return nullptr;
}
int
storeDirWriteCleanLogs(int reopen)
{
- const StoreEntry *e = NULL;
+ const StoreEntry *e = nullptr;
int n = 0;
struct timeval start;
while (!isDone() && !entries.size())
copyBucket();
- return currentItem() != NULL;
+ return currentItem() != nullptr;
}
bool
Store::LocalSearch::currentItem()
{
if (!entries.size())
- return NULL;
+ return nullptr;
return entries.back();
}
/* probably need to lock the store entries...
* we copy them all to prevent races on the links. */
assert (!entries.size());
- hash_link *link_ptr = NULL;
- hash_link *link_next = NULL;
+ hash_link *link_ptr = nullptr;
+ hash_link *link_next = nullptr;
link_next = hash_get_bucket(store_table, bucket);
- while (NULL != (link_ptr = link_next)) {
+ while (nullptr != (link_ptr = link_next)) {
link_next = link_ptr->next;
StoreEntry *e = (StoreEntry *) link_ptr;
cmp_offset = result.offset + result.length;
STCB *temphandler = _callback.callback_handler;
void *cbdata = _callback.callback_data;
- _callback = Callback(NULL, NULL);
- copyInto.data = NULL;
+ _callback = Callback(nullptr, nullptr);
+ copyInto.data = nullptr;
if (cbdataReferenceValid(cbdata))
temphandler(cbdata, result);
STCB * callback,
void *data)
{
- assert (sc != NULL);
+ assert (sc != nullptr);
sc->copy(e, copyInto,callback,data);
}
* if needed.
*/
- if (STORE_DISK_CLIENT == getType() && swapin_sio == NULL) {
+ if (STORE_DISK_CLIENT == getType() && swapin_sio == nullptr) {
if (!startSwapin())
return; // failure
}
/* Don't set store_io_pending here */
storeSwapInStart(this);
- if (swapin_sio == NULL) {
+ if (swapin_sio == nullptr) {
fail();
flags.store_copying = false;
return false;
/* What the client wants is not in memory. Schedule a disk read */
if (getType() == STORE_DISK_CLIENT) {
// we should have called startSwapin() already
- assert(swapin_sio != NULL);
+ assert(swapin_sio != nullptr);
} else if (!swapin_sio && !startSwapin()) {
debugs(90, 3, "bailing after swapin start failure for " << *entry);
assert(!flags.store_copying);
(void)data;
#endif
- if (mem == NULL)
+ if (mem == nullptr)
return 0;
debugs(90, 3, "storeUnregister: called for '" << e->getMD5Text() << "'");
- if (sc == NULL) {
+ if (sc == nullptr) {
debugs(90, 3, "storeUnregister: No matching client for '" << e->getMD5Text() << "'");
return 0;
}
if (e->store_status == STORE_OK && !swapoutFinished)
e->swapOut();
- if (sc->swapin_sio != NULL) {
+ if (sc->swapin_sio != nullptr) {
storeClose(sc->swapin_sio, StoreIOState::readerDone);
- sc->swapin_sio = NULL;
+ sc->swapin_sio = nullptr;
++statCounter.swap.ins;
}
swapOut();
int i = 0;
store_client *sc;
- dlink_node *nx = NULL;
+ dlink_node *nx = nullptr;
dlink_node *node;
debugs(90, 3, mem_obj->nclients << " clients; " << *this << ' ' << getMD5Text());
storePendingNClients(const StoreEntry * e)
{
MemObject *mem = e->mem_obj;
- int npend = NULL == mem ? 0 : mem->nclients;
+ int npend = nullptr == mem ? 0 : mem->nclients;
debugs(90, 3, "storePendingNClients: returning " << npend);
return npend;
}
#if USE_CACHE_DIGESTS
if (!Config.onoff.digest_generation) {
- store_digest = NULL;
+ store_digest = nullptr;
debugs(71, 3, "Local cache digest generation disabled");
return;
}
#if USE_CACHE_DIGESTS
if (Config.onoff.digest_generation) {
- storeDigestRebuildStart(NULL);
- storeDigestRewriteStart(NULL);
+ storeDigestRebuildStart(nullptr);
+ storeDigestRewriteStart(nullptr);
}
#endif
sd_stats = StoreDigestStats();
- eventAdd("storeDigestRebuildStep", storeDigestRebuildStep, NULL, 0.0, 1);
+ eventAdd("storeDigestRebuildStep", storeDigestRebuildStep, nullptr, 0.0, 1);
}
/* finishes swap out sequence for the digest; schedules next rebuild */
sd_state.rebuild_lock = 0;
++sd_state.rebuild_count;
debugs(71, 2, "storeDigestRebuildFinish: done.");
- eventAdd("storeDigestRebuildStart", storeDigestRebuildStart, NULL, (double)
+ eventAdd("storeDigestRebuildStart", storeDigestRebuildStart, nullptr, (double)
Config.digest.rebuild_period, 1);
/* resume pending Rewrite if any */
if (sd_state.theSearch->isDone())
storeDigestRebuildFinish();
else
- eventAdd("storeDigestRebuildStep", storeDigestRebuildStep, NULL, 0.0, 1);
+ eventAdd("storeDigestRebuildStep", storeDigestRebuildStep, nullptr, 0.0, 1);
}
/* starts swap out sequence for the digest */
" (" << std::showpos << (int) (e->expires - squid_curtime) << ")");
/* is this the write order? @?@ */
e->mem_obj->unlinkRequest();
- sd_state.rewrite_lock = NULL;
+ sd_state.rewrite_lock = nullptr;
++sd_state.rewrite_count;
- eventAdd("storeDigestRewriteStart", storeDigestRewriteStart, NULL, (double)
+ eventAdd("storeDigestRewriteStart", storeDigestRewriteStart, nullptr, (double)
Config.digest.rewrite_period, 1);
/* resume pending Rebuild if any */
if (!sd) {
debugs(20, 2, "storeCreate: no swapdirs for " << *e);
++store_io_stats.create.select_fail;
- return NULL;
+ return nullptr;
}
/* Now that we have a fs to use, call its storeCreate function */
StoreIOState::Pointer sio = sd->createStoreIO(*e, file_callback, close_callback, callback_data);
- if (sio == NULL)
+ if (sio == nullptr)
++store_io_stats.create.create_fail;
else
++store_io_stats.create.success;
t[0] = *(buf + (j++));
t[1] = *(buf + (j++));
t[2] = '\0';
- *(digest + i) = (unsigned char) strtol(t, NULL, 16);
+ *(digest + i) = (unsigned char) strtol(t, nullptr, 16);
}
return digest;
static int storeLogTagsCounts[STORE_LOG_SWAPOUTFAIL+1];
static OBJH storeLogTagsHist;
-static Logfile *storelog = NULL;
+static Logfile *storelog = nullptr;
static String str_unknown;
if (str_unknown.size()==0)
str_unknown="unknown"; //hack. Delay initialization as string doesn't support global variables..
- if (NULL == storelog)
+ if (nullptr == storelog)
return;
++storeLogTagsCounts[tag];
- if (mem != NULL) {
+ if (mem != nullptr) {
reply = &mem->freshestReply();
/*
* XXX Ok, where should we print the dir number here?
void
storeLogRotate(void)
{
- if (NULL == storelog)
+ if (nullptr == storelog)
return;
logfileRotate(storelog, Config.Log.rotateNumber);
void
storeLogClose(void)
{
- if (NULL == storelog)
+ if (nullptr == storelog)
return;
logfileClose(storelog);
- storelog = NULL;
+ storelog = nullptr;
}
static void
{
storeLogRegisterWithCacheManager();
- if (Config.Log.store == NULL || strcmp(Config.Log.store, "none") == 0) {
+ if (Config.Log.store == nullptr || strcmp(Config.Log.store, "none") == 0) {
debugs(20, Important(42), "Store logging disabled");
return;
}
int scanned;
} store_rebuild_progress;
-static store_rebuild_progress *RebuildProgress = NULL;
+static store_rebuild_progress *RebuildProgress = nullptr;
void
StoreRebuildData::updateStartTime(const timeval &dirStartTime)
static int validated = 0;
static int seen = 0;
- if (currentSearch == NULL || currentSearch->isDone())
+ if (currentSearch == nullptr || currentSearch->isDone())
currentSearch = Store::Root().search();
size_t statCount = 500;
if (store_digest)
storeDigestNoteStoreReady();
- currentSearch = NULL;
+ currentSearch = nullptr;
} else
- eventAdd("storeCleanup", storeCleanup, NULL, 0.0, 1);
+ eventAdd("storeCleanup", storeCleanup, nullptr, 0.0, 1);
}
/* meta data recreated from disk image in swap directory */
((double) counts.objcount / (dt > 0.0 ? dt : 1.0)) << " objects/sec).");
debugs(20, Important(56), "Beginning Validation Procedure");
- eventAdd("storeCleanup", storeCleanup, NULL, 0.0, 1);
+ eventAdd("storeCleanup", storeCleanup, nullptr, 0.0, 1);
xfree(RebuildProgress);
- RebuildProgress = NULL;
+ RebuildProgress = nullptr;
}
/*
if (sd_index >= Config.cacheSwap.n_configured)
return;
- if (NULL == RebuildProgress)
+ if (nullptr == RebuildProgress)
return;
RebuildProgress[sd_index].total = total;
InitStoreEntry visitor(&tmpe, key);
for_each(*tlv_list, visitor);
storeSwapTLVFree(tlv_list);
- tlv_list = NULL;
+ tlv_list = nullptr;
if (storeKeyNull(key)) {
debugs(47, DBG_IMPORTANT, "WARNING: Ignoring keyless cache entry");
return;
}
- assert(e->mem_obj != NULL);
+ assert(e->mem_obj != nullptr);
sc->swapin_sio = storeOpen(e, storeSwapInFileNotify, storeSwapInFileClosed, sc);
}
{
store_client *sc = (store_client *)data;
debugs(20, 3, "storeSwapInFileClosed: sio=" << sc->swapin_sio.getRaw() << ", errflag=" << errflag);
- sc->swapin_sio = NULL;
+ sc->swapin_sio = nullptr;
if (sc->_callback.pending()) {
assert (errflag <= 0);
{
tlv *t;
- while ((t = n) != NULL) {
+ while ((t = n) != nullptr) {
n = t->next;
xfree(t->value);
delete t;
tlv *
storeSwapMetaBuild(const StoreEntry *e)
{
- tlv *TLV = NULL; /* we'll return this */
+ tlv *TLV = nullptr; /* we'll return this */
tlv **T = &TLV;
- assert(e->mem_obj != NULL);
+ assert(e->mem_obj != nullptr);
const int64_t objsize = e->mem_obj->expectedReplySize();
// e->mem_obj->request may be nil in this context
if (!t) {
storeSwapTLVFree(TLV);
- return NULL;
+ return nullptr;
}
T = StoreMeta::Add(T, t);
if (!t) {
storeSwapTLVFree(TLV);
- return NULL;
+ return nullptr;
}
// XXX: do TLV without the c_str() termination. check readers first though
if (!t) {
storeSwapTLVFree(TLV);
- return NULL;
+ return nullptr;
}
if (objsize >= 0) {
if (!t) {
storeSwapTLVFree(TLV);
- return NULL;
+ return nullptr;
}
}
if (!t) {
storeSwapTLVFree(TLV);
- return NULL;
+ return nullptr;
}
StoreMeta::Add (T, t);
tlv *t;
int j = 0;
char *buf;
- assert(length != NULL);
+ assert(length != nullptr);
++buflen; /* STORE_META_OK */
buflen += sizeof(int); /* size of header to follow */
generic_cbdata *c = new generic_cbdata(e);
sio = storeCreate(e, storeSwapOutFileNotify, storeSwapOutFileClosed, c);
- if (sio == NULL) {
+ if (sio == nullptr) {
assert(!e->hasDisk());
e->swap_status = SWAPOUT_NONE;
e->swapOutDecision(MemObject::SwapOut::swImpossible);
debugs(20, 7, "storeSwapOut: mem->endOffset() = " << mem_obj->endOffset());
debugs(20, 7, "storeSwapOut: swapout.queue_offset = " << mem_obj->swapout.queue_offset);
- if (mem_obj->swapout.sio != NULL)
+ if (mem_obj->swapout.sio != nullptr)
debugs(20, 7, "storeSwapOut: storeOffset() = " << mem_obj->swapout.sio->offset() );
int64_t const lowest_offset = mem_obj->lowestMemReaderOffset();
/* Ok, we have stuff to swap out. Is there a swapout.sio open? */
if (!hasDisk()) {
- assert(mem_obj->swapout.sio == NULL);
+ assert(mem_obj->swapout.sio == nullptr);
assert(mem_obj->inmem_lo == 0);
storeSwapOutStart(this); // sets SwapOut::swImpossible on failures
}
- if (mem_obj->swapout.sio == NULL)
+ if (mem_obj->swapout.sio == nullptr)
return;
if (!doPages(this))
void
StoreEntry::swapOutFileClose(int how)
{
- assert(mem_obj != NULL);
+ assert(mem_obj != nullptr);
debugs(20, 3, "storeSwapOutFileClose: " << getMD5Text() << " how=" << how);
debugs(20, 3, "storeSwapOutFileClose: sio = " << mem_obj->swapout.sio.getRaw());
- if (mem_obj->swapout.sio == NULL)
+ if (mem_obj->swapout.sio == nullptr)
return;
storeClose(mem_obj->swapout.sio, how);
Store::Root().transientsCompleteWriting(*e);
debugs(20, 3, "storeSwapOutFileClosed: " << __FILE__ << ":" << __LINE__);
- mem->swapout.sio = NULL;
+ mem->swapout.sio = nullptr;
e->unlock("storeSwapOutFileClosed");
}
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklomnpqrstuvwxyz";
- static std::mt19937 mt(time(0));
+ static std::mt19937 mt(time(nullptr));
// sizeof() counts the terminating zero at the end of characters
// and the distribution is an 'inclusive' value range, so -2
StoreIOState::Pointer
TestSwapDir::createStoreIO(StoreEntry &, StoreIOState::STFNCB *, StoreIOState::STIOCB *, void *)
{
- return NULL;
+ return nullptr;
}
StoreIOState::Pointer
TestSwapDir::openStoreIO(StoreEntry &, StoreIOState::STFNCB *, StoreIOState::STIOCB *, void *)
{
- return NULL;
+ return nullptr;
}
void
#define STUB_API "stub_DelayId.cc"
#include "tests/STUB.h"
-DelayId::DelayId(): pool_(0), compositeId(NULL), markedAsNoDelay(false) {}
+DelayId::DelayId(): pool_(0), compositeId(nullptr), markedAsNoDelay(false) {}
DelayId::~DelayId() {}
void DelayId::delayRead(const AsyncCallPointer &) STUB_NOP
#define STUB_API "EventLoop.cc"
#include "tests/STUB.h"
-EventLoop *EventLoop::Running = NULL;
+EventLoop *EventLoop::Running = nullptr;
-EventLoop::EventLoop(): errcount(0), last_loop(false), timeService(NULL),
- primaryEngine(NULL), loop_delay(0), error(false), runOnceResult(false)
+EventLoop::EventLoop(): errcount(0), last_loop(false), timeService(nullptr),
+ primaryEngine(nullptr), loop_delay(0), error(false), runOnceResult(false)
STUB_NOP
void EventLoop::registerEngine(AsyncEngine *) STUB
bool HttpReply::expectingBody(const HttpRequestMethod&, int64_t&) const STUB_RETVAL(false)
bool HttpReply::parseFirstLine(const char *, const char *) STUB_RETVAL(false)
void HttpReply::hdrCacheInit() STUB
-HttpReply * HttpReply::clone() const STUB_RETVAL(NULL)
+HttpReply * HttpReply::clone() const STUB_RETVAL(nullptr)
bool HttpReply::inheritProperties(const Http::Message *) STUB_RETVAL(false)
HttpReply::Pointer HttpReply::recreateOnNotModified(const HttpReply &) const STUB_RETVAL(nullptr)
int64_t HttpReply::bodySize(const HttpRequestMethod&) const STUB_RETVAL(0)
HttpRequest::~HttpRequest() STUB
void HttpRequest::reset() STUB
void HttpRequest::initHTTP(const HttpRequestMethod &, AnyP::ProtocolType, const char *, const char *) STUB
-HttpRequest * HttpRequest::clone() const STUB_RETVAL(NULL)
+HttpRequest * HttpRequest::clone() const STUB_RETVAL(nullptr)
bool HttpRequest::maybeCacheable() STUB_RETVAL(false)
bool HttpRequest::conditional() const STUB_RETVAL(false)
bool HttpRequest::canHandle1xx() const STUB_RETVAL(false)
void HttpRequest::httpRequestPack(void *, Packable *) STUB
HttpRequest * HttpRequest::FromUrl(const SBuf &, const MasterXaction::Pointer &, const HttpRequestMethod &) STUB_RETVAL(nullptr)
HttpRequest * HttpRequest::FromUrlXXX(const char *, const MasterXaction::Pointer &, const HttpRequestMethod &) STUB_RETVAL(nullptr)
-ConnStateData *HttpRequest::pinnedConnection() STUB_RETVAL(NULL)
+ConnStateData *HttpRequest::pinnedConnection() STUB_RETVAL(nullptr)
const SBuf HttpRequest::storeId() STUB_RETVAL(SBuf("."))
void HttpRequest::ignoreRange(const char *) STUB
int64_t HttpRequest::getRangeOffsetLimit() STUB_RETVAL(0)
void MemBuf::clean() STUB
void MemBuf::reset() STUB
int MemBuf::isNull() const STUB_RETVAL(1)
-FREE *MemBuf::freeFunc() STUB_RETVAL(NULL)
+FREE *MemBuf::freeFunc() STUB_RETVAL(nullptr)
void MemBuf::append(const char *, int) STUB
void MemBuf::vappendf(const char *, va_list) STUB
#define STUB_API "MemObject.cc"
#include "tests/STUB.h"
-RemovalPolicy * mem_policy = NULL;
+RemovalPolicy * mem_policy = nullptr;
int64_t
MemObject::endOffset() const
memset(&start_ping, 0, sizeof(start_ping));
} // NOP instead of elided due to Store
-const char *MemObject::storeId() const STUB_RETVAL(NULL)
-const char *MemObject::logUri() const STUB_RETVAL(NULL)
+const char *MemObject::storeId() const STUB_RETVAL(nullptr)
+const char *MemObject::logUri() const STUB_RETVAL(nullptr)
void MemObject::setUris(char const *, char const *, const HttpRequestMethod &) STUB
void MemObject::reset() STUB
void MemObject::delayRead(const AsyncCallPointer &) STUB
void MemStore::init() STUB
void MemStore::getStats(StoreInfoStats&) const STUB
void MemStore::stat(StoreEntry &) const STUB
-StoreEntry *MemStore::get(const cache_key *) STUB_RETVAL(NULL)
+StoreEntry *MemStore::get(const cache_key *) STUB_RETVAL(nullptr)
uint64_t MemStore::maxSize() const STUB_RETVAL(0)
uint64_t MemStore::minSize() const STUB_RETVAL(0)
uint64_t MemStore::currentSize() const STUB_RETVAL(0)
SBuf SBuf::consume(size_type) STUB_RETVAL(*this)
const SBufStats& SBuf::GetStats() STUB_RETVAL(SBuf::stats)
SBuf::size_type SBuf::copy(char *, size_type) const STUB_RETVAL(0)
-const char* SBuf::rawContent() const STUB_RETVAL(NULL)
-char *SBuf::rawAppendStart(size_type) STUB_RETVAL(NULL)
+const char* SBuf::rawContent() const STUB_RETVAL(nullptr)
+char *SBuf::rawAppendStart(size_type) STUB_RETVAL(nullptr)
void SBuf::rawAppendFinish(const char *, size_type) STUB
const char* SBuf::c_str() STUB_RETVAL("")
void SBuf::reserveCapacity(size_type) STUB
bool StoreMeta::validType(char) STUB_RETVAL(false)
bool StoreMeta::validLength(int) const STUB_RETVAL(false)
-StoreMeta * StoreMeta::Factory (char, size_t, void const *) STUB_RETVAL(NULL)
+StoreMeta * StoreMeta::Factory (char, size_t, void const *) STUB_RETVAL(nullptr)
void StoreMeta::FreeList(StoreMeta **) STUB
-StoreMeta ** StoreMeta::Add(StoreMeta **, StoreMeta *) STUB_RETVAL(NULL)
+StoreMeta ** StoreMeta::Add(StoreMeta **, StoreMeta *) STUB_RETVAL(nullptr)
bool StoreMeta::checkConsistency(StoreEntry *) const STUB_RETVAL(false)
void Mgr::RegisterAction(char const*, char const*, OBJH, int, int) {}
void Mgr::RegisterAction(char const *, char const *, Mgr::ClassActionCreationHandler *, int, int) {}
-Mgr::Action::Pointer CacheManager::createRequestedAction(const Mgr::ActionParams &) STUB_RETVAL(NULL)
+Mgr::Action::Pointer CacheManager::createRequestedAction(const Mgr::ActionParams &) STUB_RETVAL(nullptr)
bool ConnStateData::serveDelayedError(Http::Stream *) STUB_RETVAL(false)
#endif
-const char *findTrailingHTTPVersion(const char *, const char *) STUB_RETVAL(NULL)
+const char *findTrailingHTTPVersion(const char *, const char *) STUB_RETVAL(nullptr)
int varyEvaluateMatch(StoreEntry *, HttpRequest *) STUB_RETVAL(0)
void clientOpenListenSockets(void) STUB
void httpRequestFree(void *) STUB
#include "tests/STUB.h"
char *Debug::debugOptions;
-char *Debug::cache_log= NULL;
+char *Debug::cache_log= nullptr;
int Debug::rotateNumber = 0;
int Debug::Levels[MAX_DEBUG_SECTIONS];
int Debug::override_X = 0;
bool EventScheduler::find(EVH *, void *) STUB_RETVAL(false)
void EventScheduler::schedule(const char *, EVH *, void *, double, int, bool) STUB
int EventScheduler::checkEvents(int) STUB_RETVAL(-1)
-EventScheduler *EventScheduler::GetInstance() STUB_RETVAL(NULL)
+EventScheduler *EventScheduler::GetInstance() STUB_RETVAL(nullptr)
void ExternalACLLookup::Start(ACLChecklist *, external_acl_data *, bool) STUB
void externalAclInit(void) STUB_NOP
void externalAclShutdown(void) STUB_NOP
-ExternalACLLookup * ExternalACLLookup::Instance() STUB_RETVAL(NULL)
+ExternalACLLookup * ExternalACLLookup::Instance() STUB_RETVAL(nullptr)
void ExternalACLLookup::checkForAsync(ACLChecklist *) const STUB
void ExternalACLLookup::LookupDone(void *, const ExternalACLEntryPointer &) STUB
#define STUB_API "fd.cc"
#include "tests/STUB.h"
-fde *fde::Table = NULL;
+fde *fde::Table = nullptr;
int fdNFree(void) STUB_RETVAL(-1)
void fd_open(int, unsigned int, const char *) STUB
void foo_stub_ipc_forwarder();
void foo_stub_ipc_forwarder()
{
- Ipc::Forwarder foo(NULL,1.0);
+ Ipc::Forwarder foo(nullptr,1.0);
}
namespace Auth
{
Auth::UserRequest::Pointer SchemeConfig::CreateAuthUser(const char *, AccessLogEntry::Pointer &) STUB_RETVAL(nullptr)
-Auth::SchemeConfig * SchemeConfig::Find(const char *) STUB_RETVAL(NULL)
+Auth::SchemeConfig * SchemeConfig::Find(const char *) STUB_RETVAL(nullptr)
void SchemeConfig::registerWithCacheManager(void) STUB_NOP
Auth::ConfigVector TheConfig;
}
#include "auth/Scheme.h"
#include <vector>
-std::vector<Auth::Scheme::Pointer> *Auth::Scheme::_Schemes = NULL;
+std::vector<Auth::Scheme::Pointer> *Auth::Scheme::_Schemes = nullptr;
void Auth::Scheme::AddScheme(Auth::Scheme::Pointer) STUB
-Auth::Scheme::Pointer Auth::Scheme::Find(const char *) STUB_RETVAL(NULL)
+Auth::Scheme::Pointer Auth::Scheme::Find(const char *) STUB_RETVAL(nullptr)
std::vector<Auth::Scheme::Pointer> & Auth::Scheme::GetSchemes() STUB_RETVAL(*_Schemes);
void Auth::Scheme::FreeAll() STUB
AuthAclState Auth::UserRequest::authenticate(Auth::UserRequest::Pointer *, Http::HdrType, HttpRequest *, ConnStateData *, Ip::Address &, AccessLogEntry::Pointer &) STUB_RETVAL(AUTH_AUTHENTICATED)
AuthAclState Auth::UserRequest::tryToAuthenticateAndSetAuthUser(Auth::UserRequest::Pointer *, Http::HdrType, HttpRequest *, ConnStateData *, Ip::Address &, AccessLogEntry::Pointer &) STUB_RETVAL(AUTH_AUTHENTICATED)
void Auth::UserRequest::AddReplyAuthHeader(HttpReply *, Auth::UserRequest::Pointer, HttpRequest *, int, int) STUB
-Auth::Scheme::Pointer Auth::UserRequest::scheme() const STUB_RETVAL(NULL)
+Auth::Scheme::Pointer Auth::UserRequest::scheme() const STUB_RETVAL(nullptr)
#include "AuthReg.h"
void Auth::Init() STUB_NOP
#include "auth/AclMaxUserIp.h"
ACLMaxUserIP::ACLMaxUserIP (char const *) STUB
-char const * ACLMaxUserIP::typeString() const STUB_RETVAL(NULL)
+char const * ACLMaxUserIP::typeString() const STUB_RETVAL(nullptr)
bool ACLMaxUserIP::empty () const STUB_RETVAL(false)
bool ACLMaxUserIP::valid () const STUB_RETVAL(false)
void ACLMaxUserIP::parse() STUB
#include "auth/AclProxyAuth.h"
ACLProxyAuth::~ACLProxyAuth() STUB
ACLProxyAuth::ACLProxyAuth(ACLData<char const *> *, char const *) STUB
-char const * ACLProxyAuth::typeString() const STUB_RETVAL(NULL)
+char const * ACLProxyAuth::typeString() const STUB_RETVAL(nullptr)
void ACLProxyAuth::parse() STUB
int ACLProxyAuth::match(ACLChecklist *) STUB_RETVAL(0)
SBufList ACLProxyAuth::dump() const STUB_RETVAL(SBufList())
bool ACLProxyAuth::empty () const STUB_RETVAL(false)
bool ACLProxyAuth::valid () const STUB_RETVAL(false)
-ProxyAuthLookup * ProxyAuthLookup::Instance() STUB_RETVAL(NULL)
+ProxyAuthLookup * ProxyAuthLookup::Instance() STUB_RETVAL(nullptr)
void ProxyAuthLookup::checkForAsync(ACLChecklist *) const STUB
void ProxyAuthLookup::LookupDone(void *) STUB
int ACLProxyAuth::matchForCache(ACLChecklist *) STUB_RETVAL(0)
Comm::ConnectionPointer Comm::Connection::cloneProfile() const STUB_RETVAL(nullptr)
void Comm::Connection::close() STUB
void Comm::Connection::noteClosure() STUB
-CachePeer * Comm::Connection::getPeer() const STUB_RETVAL(NULL)
+CachePeer * Comm::Connection::getPeer() const STUB_RETVAL(nullptr)
void Comm::Connection::setPeer(CachePeer *) STUB
ScopedId Comm::Connection::codeContextGist() const STUB_RETVAL(id.detach())
std::ostream &Comm::Connection::detailCodeContext(std::ostream &os) const STUB_RETVAL(os)
Comm::ConnOpener::ConnOpener(const Comm::ConnectionPointer &, const AsyncCall::Pointer &, time_t) : AsyncJob("STUB Comm::ConnOpener") STUB
Comm::ConnOpener::~ConnOpener() STUB
void Comm::ConnOpener::setHost(const char *) STUB
- const char * Comm::ConnOpener::getHost() const STUB_RETVAL(NULL)
+ const char * Comm::ConnOpener::getHost() const STUB_RETVAL(nullptr)
#include "comm/forward.h"
bool Comm::IsConnOpen(const Comm::ConnectionPointer &) STUB_RETVAL(false)
void Comm::IoCallback::selectOrQueueWrite() STUB
void Comm::IoCallback::cancel(const char *) STUB
void Comm::IoCallback::finish(Comm::Flag, int) STUB
- Comm::CbEntry *Comm::iocb_table = NULL;
+ Comm::CbEntry *Comm::iocb_table = nullptr;
void Comm::CallbackTableInit() STUB
void Comm::CallbackTableDestruct() STUB
void DiskIOModule::SetupAllModules() STUB
void DiskIOModule::ModuleAdd(DiskIOModule &) STUB
void DiskIOModule::FreeAllModules() STUB
-DiskIOModule *DiskIOModule::Find(char const *) STUB_RETVAL(NULL)
-DiskIOModule *DiskIOModule::FindDefault() STUB_RETVAL(NULL)
+DiskIOModule *DiskIOModule::Find(char const *) STUB_RETVAL(nullptr)
+DiskIOModule *DiskIOModule::FindDefault() STUB_RETVAL(nullptr)
std::vector<DiskIOModule*> const &DiskIOModule::Modules() STUB_RETSTATREF(std::vector<DiskIOModule*>)
DiskIOModule::DiskIOModule() {STUB}
DiskIOModule::DiskIOModule(DiskIOModule const &) {STUB}
#include "eui/Eui48.h"
#if USE_SQUID_EUI
-const unsigned char *Eui::Eui48::get(void) STUB_RETVAL(NULL)
+const unsigned char *Eui::Eui48::get(void) STUB_RETVAL(nullptr)
bool Eui::Eui48::decode(const char *) STUB_RETVAL(false)
bool Eui::Eui48::encode(char *, const int) const STUB_RETVAL(false)
bool Eui::Eui48::lookup(const Ip::Address &) STUB_RETVAL(false)
#include "eui/Eui64.h"
#if USE_SQUID_EUI
-const unsigned char *Eui::Eui64::get(void) STUB_RETVAL(NULL)
+const unsigned char *Eui::Eui64::get(void) STUB_RETVAL(nullptr)
bool Eui::Eui64::decode(const char *) STUB_RETVAL(false)
bool Eui::Eui64::encode(char *, const int) const STUB_RETVAL(false)
bool Eui::Eui64::lookup(const Ip::Address &) STUB_RETVAL(false)
void Mgr::Action::respond(const Request &) STUB
void Mgr::Action::sendResponse(const Ipc::RequestId) STUB
bool Mgr::Action::atomic() const STUB_RETVAL(false)
-const char * Mgr::Action::name() const STUB_RETVAL(NULL)
+const char * Mgr::Action::name() const STUB_RETVAL(nullptr)
static Mgr::Command static_Command;
const Mgr::Command & Mgr::Action::command() const STUB_RETVAL(static_Command)
-StoreEntry * Mgr::Action::createStoreEntry() const STUB_RETVAL(NULL)
+StoreEntry * Mgr::Action::createStoreEntry() const STUB_RETVAL(nullptr)
static Mgr::Action::Pointer dummyAction;
#include "mgr/ActionParams.h"
void Mgr::QueryParams::Parse(Parser::Tokenizer &, QueryParams &) STUB
//private:
//Params::const_iterator Mgr::QueryParams::find(const String&) const STUB_RETVAL(new Mgr::Params::const_iterator(*this))
-Mgr::QueryParam::Pointer Mgr::QueryParams::CreateParam(QueryParam::Type) STUB_RETVAL(Mgr::QueryParam::Pointer(NULL))
+Mgr::QueryParam::Pointer Mgr::QueryParams::CreateParam(QueryParam::Type) STUB_RETVAL(Mgr::QueryParam::Pointer(nullptr))
#include "mgr/Registration.h"
//void Mgr::RegisterAction(char const *, char const *, OBJH *, int, int);
//Mgr::Response::Response(const Ipc::TypedMsgHdr&) STUB
void Mgr::Response::pack(Ipc::TypedMsgHdr&) const STUB
static Ipc::Response::Pointer ipr_static;
-Ipc::Response::Pointer Mgr::Response::clone() const STUB_RETVAL(Ipc::Response::Pointer(NULL))
+Ipc::Response::Pointer Mgr::Response::clone() const STUB_RETVAL(Ipc::Response::Pointer(nullptr))
bool Mgr::Response::hasAction() const STUB_RETVAL(false)
//static Mgr::Action mgraction_static;
//const Mgr::Action& Mgr::Response::getAction() const STUB_RETVAL(mgraction_static)
#include "ssl/Config.h"
Ssl::Config::Config():
#if USE_SSL_CRTD
- ssl_crtd(NULL),
+ ssl_crtd(nullptr),
#endif
- ssl_crt_validator(NULL)
+ ssl_crt_validator(nullptr)
{
ssl_crt_validator_Children.concurrency = 1;
STUB_NOP
void PconnPool::dumpHist(StoreEntry *) const STUB
void PconnPool::dumpHash(StoreEntry *) const STUB
void PconnPool::unlinkList(IdleConnList *) STUB
-PconnModule * PconnModule::GetInstance() STUB_RETVAL(NULL)
+PconnModule * PconnModule::GetInstance() STUB_RETVAL(nullptr)
void PconnModule::DumpWrapper(StoreEntry *) STUB
PconnModule::PconnModule() STUB
void PconnModule::registerWithCacheManager(void) STUB
#include "tests/STUB.h"
class StoreEntry;
-const char *storeEntryFlags(const StoreEntry *) STUB_RETVAL(NULL)
+const char *storeEntryFlags(const StoreEntry *) STUB_RETVAL(nullptr)
void sigusr2_handle(int) STUB
void debug_trap(const char *) STUB
void sig_child(int) STUB
-const char * getMyHostname(void) STUB_RETVAL(NULL)
-const char * uniqueHostname(void) STUB_RETVAL(NULL)
+const char * getMyHostname(void) STUB_RETVAL(nullptr)
+const char * uniqueHostname(void) STUB_RETVAL(nullptr)
void leave_suid(void) STUB_NOP
void enter_suid(void) STUB
void no_suid(void) STUB
char * line = xstrdup("test max_user_ip -s 1");
/* seed the parser */
ConfigParser::SetCfgLine(line);
- ACL *anACL = NULL;
+ ACL *anACL = nullptr;
ConfigParser LegacyParser;
ACL::ParseAclLine(LegacyParser, &anACL);
ACLMaxUserIP *maxUserIpACL = dynamic_cast<ACLMaxUserIP *>(anACL);
testCacheManager::testRegister()
{
CacheManager *manager=CacheManager::GetInstance();
- CPPUNIT_ASSERT(manager != NULL);
+ CPPUNIT_ASSERT(manager != nullptr);
manager->registerProfile("sample", "my sample", &dummy_action, false, false);
Mgr::Action::Pointer action = manager->createNamedAction("sample");
- CPPUNIT_ASSERT(action != NULL);
+ CPPUNIT_ASSERT(action != nullptr);
const Mgr::ActionProfile::Pointer profile = action->command().profile;
- CPPUNIT_ASSERT(profile != NULL);
- CPPUNIT_ASSERT(profile->creator != NULL);
+ CPPUNIT_ASSERT(profile != nullptr);
+ CPPUNIT_ASSERT(profile->creator != nullptr);
CPPUNIT_ASSERT_EQUAL(false, profile->isPwReq);
CPPUNIT_ASSERT_EQUAL(false, profile->isAtomic);
CPPUNIT_ASSERT_EQUAL(String("sample"), String(action->name()));
DiskIOModule * module = DiskIOModule::FindDefault();
#if USE_DISKIO
/* enabled. we expect at least ONE */
- CPPUNIT_ASSERT(module != NULL);
+ CPPUNIT_ASSERT(module != nullptr);
#else
/* disabled. we don't expect ANY */
CPPUNIT_ASSERT(module == NULL);
testEvent::testSingleton()
{
EventScheduler *scheduler = dynamic_cast<EventScheduler *>(EventScheduler::GetInstance());
- CPPUNIT_ASSERT(NULL != scheduler);
+ CPPUNIT_ASSERT(nullptr != scheduler);
}
// if parsing was successful, check easily visible field outputs
if (parsed) {
CPPUNIT_ASSERT_EQUAL(expect.method, output.method_);
- if (expect.uri != NULL)
+ if (expect.uri != nullptr)
CPPUNIT_ASSERT_EQUAL(0, output.uri_.cmp(expect.uri));
CPPUNIT_ASSERT_EQUAL(expect.version, output.msgProtocol_);
}
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(Http::METHOD_POST),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scBadRequest,
.suffixSz = input.length(),
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
output.clear();
.status = Http::scNone,
.suffixSz = 0,
.method = HttpRequestMethod(),
- .uri = NULL,
+ .uri = nullptr,
.version = AnyP::ProtocolVersion()
};
testHttpRequest::testIPv6HostColonBug()
{
unsigned short expected_port;
- HttpRequest *aRequest = NULL;
+ HttpRequest *aRequest = nullptr;
/* valid IPv6 address without port */
SBuf url("http://[2000:800::45]/foo");
/* parse an empty string -> Http::METHOD_NONE */
HttpRequestMethod a;
- a.HttpRequestMethodXXX(NULL);
+ a.HttpRequestMethodXXX(nullptr);
CPPUNIT_ASSERT(a == Http::METHOD_NONE);
/* parsing a literal should work */
CPPUNIT_ASSERT_EQUAL(SBuf("QWERTY"), c.image());
// parsing error should not leave stale results
- b.HttpRequestMethodXXX(NULL);
+ b.HttpRequestMethodXXX(nullptr);
CPPUNIT_ASSERT(b == Http::METHOD_NONE);
CPPUNIT_ASSERT_EQUAL(SBuf("NONE"), b.image());
}
buf[tmpval]=htons(1+tmpval);
// NULL data
- CPPUNIT_ASSERT_EQUAL((int)htons(0xffff), icmp.testChecksum(NULL,0));
+ CPPUNIT_ASSERT_EQUAL((int)htons(0xffff), icmp.testChecksum(nullptr,0));
// NULL data with length!!
- CPPUNIT_ASSERT_EQUAL((int)htons(0xffff), icmp.testChecksum(NULL,1));
+ CPPUNIT_ASSERT_EQUAL((int)htons(0xffff), icmp.testChecksum(nullptr,1));
// data with 0 length
CPPUNIT_ASSERT_EQUAL((int)htons(0xffff), icmp.testChecksum(buf,0));
void
testIpAddress::testHostentConstructor()
{
- struct hostent *hp = NULL;
+ struct hostent *hp = nullptr;
struct in_addr outval;
struct in_addr expectval;
expectval.s_addr = htonl(0xC0A8640C);
hp = gethostbyname("192.168.100.12");
- CPPUNIT_ASSERT( hp != NULL /* gethostbyname failure.*/ );
+ CPPUNIT_ASSERT( hp != nullptr /* gethostbyname failure.*/ );
Ip::Address anIPA(*hp);
CPPUNIT_ASSERT_EQUAL( 80, anIPA.cidr() );
/* BUG Check: test values by display. */
- CPPUNIT_ASSERT( anIPA.toStr(buf,MAX_IPSTRLEN) != NULL );
+ CPPUNIT_ASSERT( anIPA.toStr(buf,MAX_IPSTRLEN) != nullptr );
CPPUNIT_ASSERT( memcmp("ffff:ffff:ffff:ffff:ffff::", buf, 26) == 0 );
/* Test Network Bitmask from Ip::Address */
testIpAddress::testAddrInfo()
{
struct addrinfo *expect;
- struct addrinfo *ipval = NULL;
+ struct addrinfo *ipval = nullptr;
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
Ip::Address anIP = "127.0.0.1";
/* assert this just to check that getaddrinfo is working properly */
- CPPUNIT_ASSERT( getaddrinfo("127.0.0.1", NULL, &hints, &expect ) == 0 );
+ CPPUNIT_ASSERT( getaddrinfo("127.0.0.1", nullptr, &hints, &expect ) == 0 );
anIP.getAddrInfo(ipval);
/* Setup a buffer with the known-content packet */
const char *buf = "\x76\xb1\x81\x80\x00\x01\x00\x01\x00\x02\x00\x02\x03\x77\x77\x77\x07\x67\x61\x6d\x65\x64\x65\x76\x03\x6e\x65\x74\x00\x00\x01\x00\x01\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xef\x00\x04\xd8\xb9\x60\xea\xc0\x10\x00\x02\x00\x01\x00\x00\x00\xef\x00\x0f\x03\x6e\x73\x32\x05\x7a\x77\x61\x76\x65\x03\x63\x6f\x6d\x00\xc0\x10\x00\x02\x00\x01\x00\x00\x00\xef\x00\x06\x03\x6e\x73\x31\xc0\x41\xc0\x3d\x00\x01\x00\x01\x00\x00\x29\x6b\x00\x04\xd8\xea\xee\x4a\xc0\x58\x00\x01\x00\x01\x00\x00\x29\x6b\x00\x04\xd8\xea\xee\x4b";
size_t len = 126;
- rfc1035_message *msg = NULL;
+ rfc1035_message *msg = nullptr;
int res = 0;
unsigned int off = 0;
/* cleanup */
delete msg;
- msg = NULL;
+ msg = nullptr;
}
void testRFC1035::testParseAPacket()
/* Setup a buffer with the known-content packet */
const char *buf = "\x76\xb1\x81\x80\x00\x01\x00\x01\x00\x02\x00\x02\x03\x77\x77\x77\x07\x67\x61\x6d\x65\x64\x65\x76\x03\x6e\x65\x74\x00\x00\x01\x00\x01\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\xef\x00\x04\xd8\xb9\x60\xea\xc0\x10\x00\x02\x00\x01\x00\x00\x00\xef\x00\x0f\x03\x6e\x73\x32\x05\x7a\x77\x61\x76\x65\x03\x63\x6f\x6d\x00\xc0\x10\x00\x02\x00\x01\x00\x00\x00\xef\x00\x06\x03\x6e\x73\x31\xc0\x41\xc0\x3d\x00\x01\x00\x01\x00\x00\x29\x6b\x00\x04\xd8\xea\xee\x4a\xc0\x58\x00\x01\x00\x01\x00\x00\x29\x6b\x00\x04\xd8\xea\xee\x4b";
size_t len = 126;
- rfc1035_message *msg = NULL;
+ rfc1035_message *msg = nullptr;
int res = 0;
/* Test the MessageUnpack function itself */
res = rfc1035MessageUnpack(buf, len, &msg);
CPPUNIT_ASSERT_EQUAL(1, res);
- CPPUNIT_ASSERT(msg != NULL);
+ CPPUNIT_ASSERT(msg != nullptr);
/* cleanup */
rfc1035MessageDestroy(&msg);
- CPPUNIT_ASSERT(msg == NULL);
+ CPPUNIT_ASSERT(msg == nullptr);
}
void testRFC1035::testBugPacketEndingOnCompressionPtr()
/* Setup a buffer with the known-to-fail packet */
const char *buf = "\xec\x7b\x81\x80\x00\x01\x00\x01\x00\x00\x00\x00\x05\x62\x75\x72\x73\x74\x02\x74\x65\x06\x74\x61\x63\x6f\x64\x61\x03\x6e\x65\x74\x00\x00\x1c\x00\x01\xc0\x0c\x00\x05\x00\x01\x00\x00\x19\xe5\x00\x0a\x02\x74\x65\x04\x67\x73\x6c\x62\xc0\x15";
size_t len = 59;
- rfc1035_message *msg = NULL;
+ rfc1035_message *msg = nullptr;
int res = 0;
unsigned int off = 0;
printf("\n Header : OK");
/* cleanup */
delete msg;
- msg = NULL;
+ msg = nullptr;
// TODO explicitly test RR and Name unpack functions for this packet.
res = rfc1035MessageUnpack(buf, len, &msg);
CPPUNIT_ASSERT_EQUAL(1, res);
- CPPUNIT_ASSERT(msg != NULL);
+ CPPUNIT_ASSERT(msg != nullptr);
rfc1035MessageDestroy(&msg);
}
/* Setup a buffer with the known-to-fail headers-only packet */
const char *buf = "\xab\xcd\x81\x80\x00\x01\x00\x05\x00\x04\x00\x04";
size_t len = 12;
- rfc1035_message *msg = NULL;
+ rfc1035_message *msg = nullptr;
int res = 0;
unsigned int off = 0;
CPPUNIT_ASSERT(0 == res);
/* cleanup */
delete msg;
- msg = NULL;
+ msg = nullptr;
/* Test the MessageUnpack function itself */
res = rfc1035MessageUnpack(buf, len, &msg);
CPPUNIT_ASSERT(0 == memcmp("The DNS reply message is corrupt or could not be safely parsed.", rfc1035ErrorMessage(res), 63));
CPPUNIT_ASSERT(res < 0);
- CPPUNIT_ASSERT(msg == NULL);
+ CPPUNIT_ASSERT(msg == nullptr);
}
// use current directory for shared segments (on path-based OSes)
Ipc::Mem::Segment::BasePath = getcwd(cwd,MAXPATHLEN);
- if (Ipc::Mem::Segment::BasePath == NULL)
+ if (Ipc::Mem::Segment::BasePath == nullptr)
Ipc::Mem::Segment::BasePath = ".";
Store::Init();
Store::FreeMemory();
- store = NULL;
+ store = nullptr;
free_cachedir(&Config.cacheSwap);
rr->finishShutdown(); // deletes rr
- rr = NULL;
+ rr = nullptr;
// TODO: do this once, or each time.
// safe_free(Config.replPolicy->type);
Config.replPolicy = new RemovalPolicySettings;
Config.replPolicy->type = xstrdup("lru");
- Config.replPolicy->args = NULL;
+ Config.replPolicy->args = nullptr;
/* garh garh */
storeReplAdd("lru", createRemovalPolicy_lru);
// try to get and release all entries
for (int i = 0; i < 6; ++i) {
StoreEntry *const pe = getEntry(i);
- CPPUNIT_ASSERT(pe != NULL);
+ CPPUNIT_ASSERT(pe != nullptr);
pe->release(); // destroys pe
StoreEntry *const pe2 = getEntry(i);
- CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(NULL), pe2);
+ CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(nullptr), pe2);
}
}
CPPUNIT_TEST_SUITE_END();
public:
- testRock() : rr(NULL) {}
+ testRock() : rr(nullptr) {}
virtual void setUp();
virtual void tearDown();
// TEST: copy-construct NULL string (implicit destructor non-crash test)
{
- SBuf s1(NULL);
+ SBuf s1(nullptr);
CPPUNIT_ASSERT_EQUAL(0U,s1.length());
CPPUNIT_ASSERT_EQUAL(SBuf(""),s1);
CPPUNIT_ASSERT_EQUAL(empty_sbuf,s1);
bool
InspectingStatHist::operator ==(const InspectingStatHist & src)
{
- assert(bins != NULL && src.bins != NULL); // TODO: remove after initializing bins at construction time
+ assert(bins != nullptr && src.bins != nullptr); // TODO: remove after initializing bins at construction time
if (capacity_ != src.capacity_ ||
min_!=src.min_ ||
max_!=src.max_ ||
StoreEntry*
TestStore::get(const cache_key*)
{
- return NULL;
+ return nullptr;
}
void
StoreSearch *
TestStore::search()
{
- return NULL;
+ return nullptr;
}
void
{
Store::Init();
StoreEntry *logEntry = new StoreEntry;
- logEntry->createMemObject("dummy_storeId", NULL, HttpRequestMethod());
+ logEntry->createMemObject("dummy_storeId", nullptr, HttpRequestMethod());
logEntry->store_status = STORE_PENDING;
TestSwapDirPointer aStore (new TestSwapDir);
TestSwapDirPointer aStore2 (new TestSwapDir);
{
commonInit();
StoreEntry *logEntry = new StoreEntry;
- logEntry->createMemObject("dummy_storeId", NULL, HttpRequestMethod());
+ logEntry->createMemObject("dummy_storeId", nullptr, HttpRequestMethod());
logEntry->store_status = STORE_PENDING;
Store::Init();
TestSwapDirPointer aStore (new TestSwapDir);
addSwapDir(aStore);
addSwapDir(aStore2);
Store::Root().init();
- StoreEntry * entry1 = addedEntry(aStore.getRaw(), "name", NULL, NULL);
- StoreEntry * entry2 = addedEntry(aStore2.getRaw(), "name2", NULL, NULL);
+ StoreEntry * entry1 = addedEntry(aStore.getRaw(), "name", nullptr, nullptr);
+ StoreEntry * entry2 = addedEntry(aStore2.getRaw(), "name2", nullptr, nullptr);
StoreSearchPointer search = Store::Root().search(); /* search for everything in the store */
/* nothing should be immediately available */
CPPUNIT_ASSERT_EQUAL(false, search->error());
CPPUNIT_ASSERT_EQUAL(false, search->isDone());
- CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(NULL), search->currentItem());
+ CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(nullptr), search->currentItem());
/* trigger a callback */
cbcalled = false;
- search->next(searchCallback, NULL);
+ search->next(searchCallback, nullptr);
CPPUNIT_ASSERT_EQUAL(true, cbcalled);
/* we should have access to a entry now, that matches the entry we had before */
/* trigger another callback */
cbcalled = false;
- search->next(searchCallback, NULL);
+ search->next(searchCallback, nullptr);
CPPUNIT_ASSERT_EQUAL(true, cbcalled);
/* we should have access to a entry now, that matches the entry we had before */
/* trigger another callback */
cbcalled = false;
- search->next(searchCallback, NULL);
+ search->next(searchCallback, nullptr);
CPPUNIT_ASSERT_EQUAL(true, cbcalled);
/* now we should have no error, we should have finished and have no current item */
CPPUNIT_ASSERT_EQUAL(false, search->error());
CPPUNIT_ASSERT_EQUAL(true, search->isDone());
- CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(NULL), search->currentItem());
+ CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(nullptr), search->currentItem());
//CPPUNIT_ASSERT_EQUAL(false, search->next());
Store::FreeMemory();
testStoreHashIndex::testStats()
{
StoreEntry *logEntry = new StoreEntry;
- logEntry->createMemObject("dummy_storeId", NULL, HttpRequestMethod());
+ logEntry->createMemObject("dummy_storeId", nullptr, HttpRequestMethod());
logEntry->store_status = STORE_PENDING;
Store::Init();
TestSwapDirPointer aStore (new TestSwapDir);
testStoreHashIndex::testMaxSize()
{
StoreEntry *logEntry = new StoreEntry;
- logEntry->createMemObject("dummy_storeId", NULL, HttpRequestMethod());
+ logEntry->createMemObject("dummy_storeId", nullptr, HttpRequestMethod());
logEntry->store_status = STORE_PENDING;
Store::Init();
TestSwapDirPointer aStore (new TestSwapDir);
addSwapDir(aStore);
addSwapDir(aStore2);
Store::Root().init();
- StoreEntry * entry1 = addedEntry(aStore.getRaw(), "name", NULL, NULL);
- StoreEntry * entry2 = addedEntry(aStore2.getRaw(), "name2", NULL, NULL);
+ StoreEntry * entry1 = addedEntry(aStore.getRaw(), "name", nullptr, nullptr);
+ StoreEntry * entry2 = addedEntry(aStore2.getRaw(), "name2", nullptr, nullptr);
StoreSearchPointer search = Store::Root().search(); /* search for everything in the store */
/* nothing should be immediately available */
CPPUNIT_ASSERT_EQUAL(false, search->error());
CPPUNIT_ASSERT_EQUAL(false, search->isDone());
- CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(NULL), search->currentItem());
+ CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(nullptr), search->currentItem());
/* trigger a callback */
cbcalled = false;
- search->next(searchCallback, NULL);
+ search->next(searchCallback, nullptr);
CPPUNIT_ASSERT_EQUAL(true, cbcalled);
/* we should have access to a entry now, that matches the entry we had before */
/* trigger another callback */
cbcalled = false;
- search->next(searchCallback, NULL);
+ search->next(searchCallback, nullptr);
CPPUNIT_ASSERT_EQUAL(true, cbcalled);
/* we should have access to a entry now, that matches the entry we had before */
/* trigger another callback */
cbcalled = false;
- search->next(searchCallback, NULL);
+ search->next(searchCallback, nullptr);
CPPUNIT_ASSERT_EQUAL(true, cbcalled);
/* now we should have no error, we should have finished and have no current item */
CPPUNIT_ASSERT_EQUAL(false, search->error());
CPPUNIT_ASSERT_EQUAL(true, search->isDone());
- CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(NULL), search->currentItem());
+ CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(nullptr), search->currentItem());
//CPPUNIT_ASSERT_EQUAL(false, search->next());
Store::FreeMemory();
String left, right;
/* two default strings are equal */
CPPUNIT_ASSERT(!left.cmp(right));
- CPPUNIT_ASSERT(!left.cmp(NULL));
- CPPUNIT_ASSERT(!left.cmp(NULL, 1));
+ CPPUNIT_ASSERT(!left.cmp(nullptr));
+ CPPUNIT_ASSERT(!left.cmp(nullptr, 1));
}
void
String right;
/* an empty string ("") is equal to a default string */
CPPUNIT_ASSERT(!left.cmp(right));
- CPPUNIT_ASSERT(!left.cmp(NULL));
- CPPUNIT_ASSERT(!left.cmp(NULL, 1));
+ CPPUNIT_ASSERT(!left.cmp(nullptr));
+ CPPUNIT_ASSERT(!left.cmp(nullptr, 1));
/* reverse the order to catch corners */
CPPUNIT_ASSERT(!right.cmp(left));
CPPUNIT_ASSERT(!right.cmp(""));
String right;
/* empty string sorts before everything */
CPPUNIT_ASSERT(left.cmp(right) > 0);
- CPPUNIT_ASSERT(left.cmp(NULL) > 0);
- CPPUNIT_ASSERT(left.cmp(NULL, 1) > 0);
+ CPPUNIT_ASSERT(left.cmp(nullptr) > 0);
+ CPPUNIT_ASSERT(left.cmp(nullptr, 1) > 0);
/* reverse for symmetry tests */
CPPUNIT_ASSERT(right.cmp(left) < 0);
CPPUNIT_ASSERT(right.cmp("foo") < 0);
CPPUNIT_ASSERT_EQUAL(aScheme, aUrl.getScheme());
auto *urlPointer = new AnyP::Uri;
- CPPUNIT_ASSERT(urlPointer != NULL);
+ CPPUNIT_ASSERT(urlPointer != nullptr);
delete urlPointer;
}
CPPUNIT_ASSERT_EQUAL(false, search->error());
CPPUNIT_ASSERT_EQUAL(false, search->isDone());
- CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(NULL), search->currentItem());
+ CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(nullptr), search->currentItem());
/* trigger a callback */
cbcalled = false;
- search->next(searchCallback, NULL);
+ search->next(searchCallback, nullptr);
CPPUNIT_ASSERT_EQUAL(true, cbcalled);
/* we should have access to a entry now, that matches the entry we had before */
//CPPUNIT_ASSERT_EQUAL(false, search->next());
CPPUNIT_ASSERT_EQUAL(false, search->error());
CPPUNIT_ASSERT_EQUAL(false, search->isDone());
- CPPUNIT_ASSERT(search->currentItem() != NULL);
+ CPPUNIT_ASSERT(search->currentItem() != nullptr);
/* trigger another callback */
cbcalled = false;
- search->next(searchCallback, NULL);
+ search->next(searchCallback, nullptr);
CPPUNIT_ASSERT_EQUAL(true, cbcalled);
/* now we should have no error, we should have finished and have no current item */
//CPPUNIT_ASSERT_EQUAL(false, search->next());
CPPUNIT_ASSERT_EQUAL(false, search->error());
CPPUNIT_ASSERT_EQUAL(true, search->isDone());
- CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(NULL), search->currentItem());
+ CPPUNIT_ASSERT_EQUAL(static_cast<StoreEntry *>(nullptr), search->currentItem());
Store::FreeMemory();
aStore->parse(0, path);
safe_free(path);
safe_free(config_line);
- CPPUNIT_ASSERT(aStore->IO->io != NULL);
+ CPPUNIT_ASSERT(aStore->IO->io != nullptr);
Store::FreeMemory();
free_cachedir(&Config.cacheSwap);
gettimeofday(¤t_time);
#else
- gettimeofday(¤t_time, NULL);
+ gettimeofday(¤t_time, nullptr);
#endif
current_dtime = (double) current_time.tv_sec +
memset(&tm, 0, sizeof(tm));
if (!day || !month || !year || !aTime || (zone && strcmp(zone, "GMT")))
- return NULL;
+ return nullptr;
tm.tm_mday = atoi(day);
tm.tm_mon = make_month(month);
if (tm.tm_mon < 0)
- return NULL;
+ return nullptr;
tm.tm_year = atoi(year);
if (strlen(year) == 4)
tm.tm_year -= 1900;
tm.tm_hour = make_num(aTime);
t = strchr(aTime, ':');
if (!t)
- return NULL;
+ return nullptr;
t++;
tm.tm_min = atoi(t);
t = strchr(t, ':');
if (t)
tm.tm_sec = atoi(t + 1);
- return tmSaneValues(&tm) ? &tm : NULL;
+ return tmSaneValues(&tm) ? &tm : nullptr;
}
static struct tm *
struct tm *tm;
static char tmp[64];
char *t;
- char *wday = NULL;
- char *day = NULL;
- char *month = NULL;
- char *year = NULL;
- char *timestr = NULL;
- char *zone = NULL;
+ char *wday = nullptr;
+ char *day = nullptr;
+ char *month = nullptr;
+ char *year = nullptr;
+ char *timestr = nullptr;
+ char *zone = nullptr;
xstrncpy(tmp, str, 64);
- for (t = strtok(tmp, ", "); t; t = strtok(NULL, ", ")) {
+ for (t = strtok(tmp, ", "); t; t = strtok(nullptr, ", ")) {
if (xisdigit(*t)) {
if (!day) {
day = t;
month = t;
t = strchr(t, '-');
if (!t)
- return NULL;
+ return nullptr;
*t++ = '\0';
year = t;
}
else if (!year)
year = t;
else
- return NULL;
+ return nullptr;
} else if (!wday)
wday = t;
else if (!month)
else if (!zone)
zone = t;
else
- return NULL;
+ return nullptr;
}
tm = parse_date_elements(day, month, year, timestr, zone);
{
struct tm *tm;
time_t t;
- if (NULL == str)
+ if (nullptr == str)
return -1;
tm = parse_date(str);
if (!tm)
static void
mail_warranty(void)
{
- FILE *fp = NULL;
+ FILE *fp = nullptr;
static char command[256];
/*
#if HAVE_MKSTEMP
char filename[] = "/tmp/squid-XXXXXX";
int tfd = mkstemp(filename);
- if (tfd < 0 || (fp = fdopen(tfd, "w")) == NULL) {
+ if (tfd < 0 || (fp = fdopen(tfd, "w")) == nullptr) {
umask(prev_umask);
return;
}
{
LOCAL_ARRAY(char, host, SQUIDHOSTNAMELEN + 1);
static int present = 0;
- struct addrinfo *AI = NULL;
+ struct addrinfo *AI = nullptr;
Ip::Address sa;
- if (Config.visibleHostname != NULL)
+ if (Config.visibleHostname != nullptr)
return Config.visibleHostname;
if (present)
host[0] = '\0';
- if (HttpPortList != NULL && sa.isAnyAddr())
+ if (HttpPortList != nullptr && sa.isAnyAddr())
sa = HttpPortList->s;
/*
sa.getAddrInfo(AI);
/* we are looking for a name. */
- if (getnameinfo(AI->ai_addr, AI->ai_addrlen, host, SQUIDHOSTNAMELEN, NULL, 0, NI_NAMEREQD ) == 0) {
+ if (getnameinfo(AI->ai_addr, AI->ai_addrlen, host, SQUIDHOSTNAMELEN, nullptr, 0, NI_NAMEREQD ) == 0) {
/* DNS lookup successful */
/* use the official name from DNS lookup */
debugs(50, 4, "getMyHostname: resolved " << sa << " to '" << host << "'");
memset(&hints, 0, sizeof(addrinfo));
hints.ai_flags = AI_CANONNAME;
- if (getaddrinfo(host, NULL, NULL, &AI) == 0) {
+ if (getaddrinfo(host, nullptr, nullptr, &AI) == 0) {
/* DNS lookup successful */
/* use the official name from DNS lookup */
debugs(50, 6, "getMyHostname: '" << host << "' has DNS resolution.");
return;
/* Started as a root, check suid option */
- if (Config.effectiveUser == NULL)
+ if (Config.effectiveUser == nullptr)
return;
debugs(21, 3, "leave_suid: PID " << getpid() << " giving up root, becoming '" << Config.effectiveUser << "'");
sa.sa_flags = flags;
sigemptyset(&sa.sa_mask);
- if (sigaction(sig, &sa, NULL) < 0) {
+ if (sigaction(sig, &sa, nullptr) < 0) {
int xerrno = errno;
debugs(50, DBG_CRITICAL, "sigaction: sig=" << sig << " func=" << func << ": " << xstrerr(xerrno));
}
nt = strpbrk(lt, w_space);
- if (nt == NULL) /* empty line */
+ if (nt == nullptr) /* empty line */
continue;
*nt = '\0'; /* null-terminate the address */
SBufList hosts;
while ((nt = strpbrk(lt, w_space))) {
- char *host = NULL;
+ char *host = nullptr;
if (nt == lt) { /* multiple spaces */
debugs(1, 5, "etc_hosts: multiple spaces, skipping");
getMyPort(void)
{
AnyP::PortCfgPointer p;
- if ((p = HttpPortList) != NULL) {
+ if ((p = HttpPortList) != nullptr) {
// skip any special interception ports
- while (p != NULL && p->flags.isIntercepted())
+ while (p != nullptr && p->flags.isIntercepted())
p = p->next;
- if (p != NULL)
+ if (p != nullptr)
return p->s.port();
}
- if ((p = FtpPortList) != NULL) {
+ if ((p = FtpPortList) != nullptr) {
// skip any special interception ports
- while (p != NULL && p->flags.isIntercepted())
+ while (p != nullptr && p->flags.isIntercepted())
p = p->next;
- if (p != NULL)
+ if (p != nullptr)
return p->s.port();
}
AccessLogEntryPointer al;
const char * getHost() const {
- return (server.conn != NULL && server.conn->getPeer() ? server.conn->getPeer()->host : request->url.host());
+ return (server.conn != nullptr && server.conn->getPeer() ? server.conn->getPeer()->host : request->url.host());
};
/// store the given to-server connection; prohibit retries and do not look
if (http.valid() && http->getConn() && http->getConn()->serverBump() && http->getConn()->serverBump()->at(XactionStep::tlsBump2, XactionStep::tlsBump3))
return false;
#endif
- return !(request != NULL &&
+ return !(request != nullptr &&
(request->flags.interceptTproxy || request->flags.intercepted));
}
{
public:
- Connection() : len (0), buf ((char *)xmalloc(SQUID_TCP_SO_RCVBUF)), size_ptr(NULL), delayedLoops(0),
+ Connection() : len (0), buf ((char *)xmalloc(SQUID_TCP_SO_RCVBUF)), size_ptr(nullptr), delayedLoops(0),
dirty(false),
- readPending(NULL), readPendingFunc(NULL) {}
+ readPending(nullptr), readPendingFunc(nullptr) {}
~Connection();
debugs(26, 3, "Schedule Write");
AsyncCall::Pointer call = commCbCall(5,5, "TunnelBlindCopyWriteHandler",
CommIoCbPtrFun(completion, this));
- to.write(from.buf, len, call, NULL);
+ to.write(from.buf, len, call, nullptr);
}
/* Writes data from the client buffer to the server side */
{
TunnelStateData *tunnelState = (TunnelStateData *)data;
assert (cbdataReferenceValid (tunnelState));
- tunnelState->server.writer = NULL;
+ tunnelState->server.writer = nullptr;
tunnelState->writeServerDone(buf, len, flag, xerrno);
}
{
TunnelStateData *tunnelState = (TunnelStateData *)data;
assert (cbdataReferenceValid (tunnelState));
- tunnelState->client.writer = NULL;
+ tunnelState->client.writer = nullptr;
tunnelState->writeClientDone(buf, len, flag, xerrno);
}
TunnelStateData *tunnel = static_cast<TunnelStateData*>(data);
const auto savedContext = CodeContext::Current();
CodeContext::Reset(tunnel->codeContext);
- tunnel->client.readPending = NULL;
+ tunnel->client.readPending = nullptr;
static uint64_t counter=0;
debugs(26, 7, "Client read(2) delayed " << ++counter << " times");
tunnel->copyRead(tunnel->client, TunnelStateData::ReadClient);
TunnelStateData *tunnel = static_cast<TunnelStateData*>(data);
const auto savedContext = CodeContext::Current();
CodeContext::Reset(tunnel->codeContext);
- tunnel->server.readPending = NULL;
+ tunnel->server.readPending = nullptr;
static uint64_t counter=0;
debugs(26, 7, "Server read(2) delayed " << ++counter << " times");
tunnel->copyRead(tunnel->server, TunnelStateData::ReadServer);
{
TunnelStateData *tunnelState = (TunnelStateData *)data;
debugs(26, 3, conn << ", flag=" << flag);
- tunnelState->client.writer = NULL;
+ tunnelState->client.writer = nullptr;
if (flag != Comm::OK) {
*tunnelState->status_ptr = Http::scInternalServerError;
{
TunnelStateData *tunnelState = (TunnelStateData *)data;
debugs(26, 3, "FD " << fd);
- assert(tunnelState != NULL);
+ assert(tunnelState != nullptr);
/* temporary lock to save our own feets (comm_close -> tunnelClientClosed -> Free) */
CbcPointer<TunnelStateData> safetyLock(tunnelState);
{
debugs(26, 3, MYNAME);
/* Create state structure. */
- TunnelStateData *tunnelState = NULL;
- ErrorState *err = NULL;
+ TunnelStateData *tunnelState = nullptr;
+ ErrorState *err = nullptr;
HttpRequest *request = http->request;
char *url = http->uri;
* Check if this host is allowed to fetch MISSES from us (miss_access)
* default is to allow.
*/
- ACLFilledChecklist ch(Config.accessList.miss, request, NULL);
+ ACLFilledChecklist ch(Config.accessList.miss, request, nullptr);
ch.al = http->al;
ch.src_addr = request->client_addr;
ch.my_addr = request->my_addr;
Ip::Address localhost;
args[0] = "(unlinkd)";
- args[1] = NULL;
+ args[1] = nullptr;
localhost.setLocalhost();
pid = ipcCreate(
urnFindMinRtt(url_entry * urls, const HttpRequestMethod &, int *rtt_ret)
{
int min_rtt = 0;
- url_entry *u = NULL;
- url_entry *min_u = NULL;
+ url_entry *u = nullptr;
+ url_entry *min_u = nullptr;
int i;
int urlcnt = 0;
debugs(52, 3, "urnFindMinRtt");
- assert(urls != NULL);
+ assert(urls != nullptr);
- for (i = 0; NULL != urls[i].url; ++i)
+ for (i = 0; nullptr != urls[i].url; ++i)
++urlcnt;
debugs(53, 3, "urnFindMinRtt: Counted " << i << " URLs");
entry->lock("UrnState::start");
setUriResFromRequest(r);
- if (urlres_r == NULL)
+ if (urlres_r == nullptr)
return;
auto urlEntry = storeGetPublic(urlres, Http::METHOD_GET);
UrnState *urnState = static_cast<UrnState *>(data);
StoreEntry *e = urnState->entry;
StoreEntry *urlres_e = urnState->urlres_e;
- char *s = NULL;
+ char *s = nullptr;
size_t k;
HttpReply *rep;
url_entry *urls;
debugs(53, 3, "urnFindMinRtt: Counted " << i << " URLs");
- min_u = urnFindMinRtt(urls, urnState->request->method, NULL);
+ min_u = urnFindMinRtt(urls, urnState->request->method, nullptr);
qsort(urls, urlcnt, sizeof(*urls), url_entry_sort);
e->buffer();
SBuf body;
"</ADDRESS>\n",
APP_FULLNAME, getMyHostname());
rep = new HttpReply;
- rep->setHeaders(Http::scFound, NULL, "text/html", mb->length(), 0, squid_curtime);
+ rep->setHeaders(Http::scFound, nullptr, "text/html", mb->length(), 0, squid_curtime);
if (min_u) {
rep->header.putStr(Http::HdrType::LOCATION, min_u->url);
debugs(52, 3, "urnParseReply");
list = (url_entry *)xcalloc(n + 1, sizeof(*list));
- for (token = strtok(buf, crlf); token; token = strtok(NULL, crlf)) {
+ for (token = strtok(buf, crlf); token; token = strtok(nullptr, crlf)) {
debugs(52, 3, "urnParseReply: got '" << token << "'");
if (i == n) {
number_caches = 0;
if (!Config.Wccp.router.isAnyAddr())
- if (!eventFind(wccpHereIam, NULL))
- eventAdd("wccpHereIam", wccpHereIam, NULL, 5.0, 1);
+ if (!eventFind(wccpHereIam, nullptr))
+ eventAdd("wccpHereIam", wccpHereIam, nullptr, 5.0, 1);
}
void
if (theWccpConnection < 0)
fatal("Cannot open WCCP Port");
- Comm::SetSelect(theWccpConnection, COMM_SELECT_READ, wccpHandleUdp, NULL, 0);
+ Comm::SetSelect(theWccpConnection, COMM_SELECT_READ, wccpHandleUdp, nullptr, 0);
debugs(80, DBG_IMPORTANT, "Accepting WCCPv1 messages on " << Config.Wccp.address << ", FD " << theWccpConnection << ".");
debugs(80, 6, "wccpHandleUdp: Called.");
- Comm::SetSelect(sock, COMM_SELECT_READ, wccpHandleUdp, NULL, 0);
+ Comm::SetSelect(sock, COMM_SELECT_READ, wccpHandleUdp, nullptr, 0);
memset(&wccp_i_see_you, '\0', sizeof(wccp_i_see_you));
interval = 2.0;
}
- if (!eventFind(wccpHereIam, NULL))
- eventAdd("wccpHereIam", wccpHereIam, NULL, interval, 1);
+ if (!eventFind(wccpHereIam, nullptr))
+ eventAdd("wccpHereIam", wccpHereIam, nullptr, interval, 1);
}
static void
uint32_t wccp2_security_type;
};
-static struct wccp2_service_list_t *wccp2_service_list_head = NULL;
+static struct wccp2_service_list_t *wccp2_service_list_head = nullptr;
int empty_portlist[WCCP2_NUMPORTS] = {0, 0, 0, 0, 0, 0, 0, 0};
p = wccp2_service_list_head;
- while (p != NULL) {
+ while (p != nullptr) {
if (p->info.service == service && p->info.service_id == service_id) {
return p;
}
p = p->next;
}
- return NULL;
+ return nullptr;
}
/*
service_list_ptr = wccp2_service_list_head;
- while (service_list_ptr != NULL) {
+ while (service_list_ptr != nullptr) {
/* Set up our list pointers */
router_list_ptr = &service_list_ptr->router_list_head;
/* update the pointer */
router_list_ptr = router_list_ptr->next;
- router_list_ptr->next = NULL;
+ router_list_ptr->next = nullptr;
/* no need to copy memory - we've just set the values directly in the packet above */
/* Add the event if everything initialised correctly */
debugs(80,3,"wccp2Init: scheduled 'HERE_I_AM' message to " << wccp2_numrouters << "routers.");
if (wccp2_numrouters) {
- if (!eventFind(wccp2HereIam, NULL)) {
- eventAdd("wccp2HereIam", wccp2HereIam, NULL, 1, 1);
+ if (!eventFind(wccp2HereIam, nullptr)) {
+ eventAdd("wccp2HereIam", wccp2HereIam, nullptr, 1, 1);
} else
debugs(80,3,"wccp2Init: skip duplicate 'HERE_I_AM'.");
}
}
#endif
- Comm::SetSelect(theWccp2Connection, COMM_SELECT_READ, wccp2HandleUdp, NULL, 0);
+ Comm::SetSelect(theWccp2Connection, COMM_SELECT_READ, wccp2HandleUdp, nullptr, 0);
debugs(80, DBG_IMPORTANT, "Accepting WCCPv2 messages on port " << WCCP_PORT << ", FD " << theWccp2Connection << ".");
debugs(80, DBG_IMPORTANT, "Initialising all WCCPv2 lists");
service_list_ptr = wccp2_service_list_head;
- while (service_list_ptr != NULL) {
- for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != NULL; router_list_ptr = router_list_ptr->next) {
+ while (service_list_ptr != nullptr) {
+ for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != nullptr; router_list_ptr = router_list_ptr->next) {
router_len = sizeof(router);
memset(&router, '\0', router_len);
router.sin_family = AF_INET;
/* free all stored router state */
service_list_ptr = wccp2_service_list_head;
- while (service_list_ptr != NULL) {
- for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr != NULL; router_list_ptr = router_list_next) {
+ while (service_list_ptr != nullptr) {
+ for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr != nullptr; router_list_ptr = router_list_next) {
for (cache_list_ptr = &router_list_ptr->cache_list_head; cache_list_ptr; cache_list_ptr = cache_list_ptr_next) {
cache_list_ptr_next = cache_list_ptr->next;
service_list_ptr = service_list_ptr_next;
}
- wccp2_service_list_head = NULL;
- eventDelete(wccp2HereIam, NULL);
- eventDelete(wccp2AssignBuckets, NULL);
- eventDelete(wccp2HereIam, NULL);
+ wccp2_service_list_head = nullptr;
+ eventDelete(wccp2HereIam, nullptr);
+ eventDelete(wccp2AssignBuckets, nullptr);
+ eventDelete(wccp2HereIam, nullptr);
wccp2_connected = 0;
}
/* These structs form the parts of the packet */
- struct wccp2_security_none_t *security_info = NULL;
+ struct wccp2_security_none_t *security_info = nullptr;
- struct wccp2_service_info_t *service_info = NULL;
+ struct wccp2_service_info_t *service_info = nullptr;
- struct router_identity_info_t *router_identity_info = NULL;
+ struct router_identity_info_t *router_identity_info = nullptr;
- struct router_view_t *router_view_header = NULL;
+ struct router_view_t *router_view_header = nullptr;
- struct wccp2_cache_mask_identity_info_t *cache_mask_identity = NULL;
+ struct wccp2_cache_mask_identity_info_t *cache_mask_identity = nullptr;
- struct cache_mask_info_t *cache_mask_info = NULL;
+ struct cache_mask_info_t *cache_mask_info = nullptr;
- struct wccp2_cache_identity_info_t *cache_identity = NULL;
+ struct wccp2_cache_identity_info_t *cache_identity = nullptr;
- struct wccp2_capability_info_header_t *router_capability_header = NULL;
+ struct wccp2_capability_info_header_t *router_capability_header = nullptr;
char *router_capability_data_start = nullptr;
struct wccp2_capability_element_t *router_capability_element;
debugs(80, 6, "wccp2HandleUdp: Called.");
- Comm::SetSelect(sock, COMM_SELECT_READ, wccp2HandleUdp, NULL, 0);
+ Comm::SetSelect(sock, COMM_SELECT_READ, wccp2HandleUdp, nullptr, 0);
// TODO: drop conversion boundary
Ip::Address from_tmp;
/* Check that the service in the packet is configured on this router */
service_list_ptr = wccp2_service_list_head;
- while (service_list_ptr != NULL) {
+ while (service_list_ptr != nullptr) {
if (service_info->service_id == service_list_ptr->service_info->service_id) {
break;
}
service_list_ptr = service_list_ptr->next;
}
- if (service_list_ptr == NULL) {
+ if (service_list_ptr == nullptr) {
debugs(80, DBG_IMPORTANT, "ERROR: WCCPv2 Unknown service received from router (" << service_info->service_id << ")");
return;
}
}
/* Check that the router address is configured on this router */
- for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != NULL; router_list_ptr = router_list_ptr->next) {
+ for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != nullptr; router_list_ptr = router_list_ptr->next) {
if (router_list_ptr->router_sendto_address.s_addr == from.sin_addr.s_addr)
break;
}
}
/* TODO: check return/forwarding methods */
- if (router_capability_header == NULL) {
+ if (router_capability_header == nullptr) {
if ((Config.Wccp2.return_method != WCCP2_PACKET_RETURN_METHOD_GRE) || (Config.Wccp2.forwarding_method != WCCP2_FORWARDING_METHOD_GRE)) {
debugs(80, DBG_IMPORTANT, "ERROR: wccp2HandleUdp: fatal error - A WCCP router does not support the forwarding method specified, only GRE supported");
wccp2ConnectionClose();
cache_list_ptr = cache_list_ptr->next;
- cache_list_ptr->next = NULL;
+ cache_list_ptr->next = nullptr;
debugs (80, 5, "checking cache list: (" << std::hex << cache_address.s_addr << ":" << router_list_ptr->local_ip.s_addr << ")");
cache_list_ptr->next = (wccp2_cache_list_t*) xcalloc(1, sizeof(struct wccp2_cache_list_t));
cache_list_ptr = cache_list_ptr->next;
- cache_list_ptr->next = NULL;
+ cache_list_ptr->next = nullptr;
service_list_ptr->lowest_ip = 1;
found = true;
if (ntohl(router_view_header->change_number) != router_list_ptr->member_change) {
debugs(80, 4, "Change detected - queueing up new assignment");
router_list_ptr->member_change = ntohl(router_view_header->change_number);
- eventDelete(wccp2AssignBuckets, NULL);
- eventAdd("wccp2AssignBuckets", wccp2AssignBuckets, NULL, 15.0, 1);
+ eventDelete(wccp2AssignBuckets, nullptr);
+ eventAdd("wccp2AssignBuckets", wccp2AssignBuckets, nullptr, 15.0, 1);
} else {
debugs(80, 5, "Change not detected (" << ntohl(router_view_header->change_number) << " = " << router_list_ptr->member_change << ")");
}
} else {
- eventDelete(wccp2AssignBuckets, NULL);
+ eventDelete(wccp2AssignBuckets, nullptr);
debugs(80, 5, "I am not the lowest ip cache - not assigning buckets");
}
/* Wait if store dirs are rebuilding */
if (StoreController::store_dirs_rebuilding && Config.Wccp2.rebuildwait) {
- eventAdd("wccp2HereIam", wccp2HereIam, NULL, 1.0, 1);
+ eventAdd("wccp2HereIam", wccp2HereIam, nullptr, 1.0, 1);
return;
}
/* for each router on each service send a packet */
service_list_ptr = wccp2_service_list_head;
- while (service_list_ptr != NULL) {
+ while (service_list_ptr != nullptr) {
debugs(80, 5, "wccp2HereIam: sending to service id " << service_list_ptr->info.service_id);
- for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != NULL; router_list_ptr = router_list_ptr->next) {
+ for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != nullptr; router_list_ptr = router_list_ptr->next) {
router = router_list_ptr->router_sendto_address;
/* Set the cache id (ip) */
service_list_ptr = service_list_ptr->next;
}
- eventAdd("wccp2HereIam", wccp2HereIam, NULL, 10.0, 1);
+ eventAdd("wccp2HereIam", wccp2HereIam, nullptr, 10.0, 1);
}
static void
struct wccp2_message_header_t *main_header;
- struct wccp2_security_md5_t *security = NULL;
+ struct wccp2_security_md5_t *security = nullptr;
/* service from service struct */
struct wccp2_item_header_t *assignment_header;
- struct wccp2_item_header_t *alt_assignment_type_header = NULL;
+ struct wccp2_item_header_t *alt_assignment_type_header = nullptr;
struct assignment_key_t *assignment_key;
/* number of routers */
debugs(80, 2, "Running wccp2AssignBuckets");
service_list_ptr = wccp2_service_list_head;
- while (service_list_ptr != NULL) {
+ while (service_list_ptr != nullptr) {
/* If we're not the lowest, we don't need to worry */
if (service_list_ptr->lowest_ip == 0) {
offset += sizeof(service_list_ptr->num_routers);
- for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != NULL; router_list_ptr = router_list_ptr->next) {
+ for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != nullptr; router_list_ptr = router_list_ptr->next) {
/* Add routers */
saved_offset = offset;
- for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != NULL; router_list_ptr = router_list_ptr->next) {
+ for (router_list_ptr = &service_list_ptr->router_list_head; router_list_ptr->next != nullptr; router_list_ptr = router_list_ptr->next) {
unsigned long *weight = (unsigned long *)xcalloc(sizeof(*weight), ntohl(router_list_ptr->num_caches));
unsigned long total_weight = 0;
int num_caches = ntohl(router_list_ptr->num_caches);
char *t;
/* Snarf the method */
- if ((t = ConfigParser::NextToken()) == NULL) {
+ if ((t = ConfigParser::NextToken()) == nullptr) {
debugs(80, DBG_CRITICAL, "ERROR: wccp2_*_method: missing setting.");
self_destruct();
return;
char *t;
/* Snarf the method */
- if ((t = ConfigParser::NextToken()) == NULL) {
+ if ((t = ConfigParser::NextToken()) == nullptr) {
debugs(80, DBG_CRITICAL, "ERROR: wccp2_assignment_method: missing setting.");
self_destruct();
return;
}
/* Snarf the type */
- if ((t = ConfigParser::NextToken()) == NULL) {
+ if ((t = ConfigParser::NextToken()) == nullptr) {
debugs(80, DBG_CRITICAL, "ERROR: wccp2ParseServiceInfo: missing service info type (standard|dynamic)");
self_destruct();
return;
memset(wccp_password, 0, sizeof(wccp_password));
/* Handle password, if any */
- if ((t = ConfigParser::NextToken()) != NULL) {
+ if ((t = ConfigParser::NextToken()) != nullptr) {
if (strncmp(t, "password=", 9) == 0) {
security_type = WCCP2_MD5_SECURITY;
xstrncpy(wccp_password, t + 9, sizeof(wccp_password));
struct wccp2_service_list_t *srv;
srv = wccp2_service_list_head;
- while (srv != NULL) {
+ while (srv != nullptr) {
debugs(80, 3, "dump_wccp2_service: id " << srv->info.service_id << ", type " << srv->info.service);
storeAppendPrintf(e, "%s %s %d", label,
(srv->info.service == WCCP2_SERVICE_DYNAMIC) ? "dynamic" : "standard",
/* Next: find the (hopefully!) existing service */
srv = wccp2_get_service_by_id(WCCP2_SERVICE_DYNAMIC, service_id);
- if (srv == NULL) {
+ if (srv == nullptr) {
fatalf("parse_wccp2_service_info: unknown dynamic service id %d: you need to define it using wccp2_service (and make sure you wish to configure it as a dynamic service.)\n", service_id);
}
/* Next: loop until we don't have any more tokens */
- while ((t = ConfigParser::NextToken()) != NULL) {
+ while ((t = ConfigParser::NextToken()) != nullptr) {
if (strncmp(t, "flags=", 6) == 0) {
/* XXX eww, string pointer math */
flags = parse_wccp2_service_flags(t + 6);
int flags;
srv = wccp2_service_list_head;
- while (srv != NULL) {
+ while (srv != nullptr) {
debugs(80, 3, "dump_wccp2_service_info: id " << srv->info.service_id << " (type " << srv->info.service << ")");
/* We don't need to spit out information for standard services */
AsyncCall::Pointer writeCall = commCbCall(5,5, "whoisWriteComplete",
CommIoCbPtrFun(whoisWriteComplete, p));
- Comm::Write(fwd->serverConnection(), buf, strlen(buf), writeCall, NULL);
+ Comm::Write(fwd->serverConnection(), buf, strlen(buf), writeCall, nullptr);
AsyncCall::Pointer readCall = commCbCall(5,4, "whoisReadReply",
CommIoCbPtrFun(whoisReadReply, p));
comm_read(fwd->serverConnection(), p->buf, BUFSIZ, readCall);
void
wordlistCat(const wordlist * w, MemBuf * mb)
{
- while (NULL != w) {
+ while (nullptr != w) {
mb->appendf("%s\n", w->key);
w = w->next;
}
ToSBufList(wordlist *wl)
{
SBufList rv;
- while (wl != NULL) {
+ while (wl != nullptr) {
rv.push_back(SBuf(wl->key));
wl = wl->next;
}
assert (aHeader.lowestOffset() == 0);
assert (aHeader.write (StoreIOBuffer()));
assert (aHeader.lowestOffset() == 0);
- assert (aHeader.write (StoreIOBuffer(0, 1, (char *)NULL)));
+ assert (aHeader.write (StoreIOBuffer(0, 1, (char *)nullptr)));
assert (aHeader.lowestOffset() == 0);
char * sampleData = xstrdup ("A");
assert (aHeader.write (StoreIOBuffer(1, 100, sampleData)));
{
/* test void * splay containers */
- splayNode *top = NULL;
+ splayNode *top = nullptr;
for (int i = 0; i < 100; ++i) {
intnode *I = (intnode *)xcalloc(sizeof(intnode), 1);
}
SplayCheck::BeginWalk();
- top->walk(SplayCheck::WalkVoid, NULL);
+ top->walk(SplayCheck::WalkVoid, nullptr);
SplayCheck::BeginWalk();
- top->walk(SplayCheck::WalkVoid, NULL);
+ top->walk(SplayCheck::WalkVoid, nullptr);
top->destroy(destintvoid);
}
}
SplayCheck::BeginWalk();
- safeTop->walk(SplayCheck::WalkNode, NULL);
+ safeTop->walk(SplayCheck::WalkNode, nullptr);
safeTop->destroy(destint);
}
}
SplayCheck::BeginWalk();
- safeTop->walk(SplayCheck::WalkNodeRef, NULL);
+ safeTop->walk(SplayCheck::WalkNodeRef, nullptr);
safeTop->destroy(destintref);
}
intnode I;
I.i = 1;
/* check we don't segfault on NULL splay calls */
- SplayCheck::WalkNodeRef(I, NULL);
+ SplayCheck::WalkNodeRef(I, nullptr);
I.i = 0;
SplayCheck::ExpectedFail = true;
- SplayCheck::WalkNodeRef(I, NULL);
+ SplayCheck::WalkNodeRef(I, nullptr);
}
{
/* check for begin() */
Splay<intnode> *safeTop = new Splay<intnode>();
- if (safeTop->start() != NULL)
+ if (safeTop->start() != nullptr)
exit(EXIT_FAILURE);
- if (safeTop->finish() != NULL)
+ if (safeTop->finish() != nullptr)
exit(EXIT_FAILURE);
for (int i = 0; i < 100; ++i) {
{
Splay<intnode *> aSplay;
- if (aSplay.start() != NULL)
+ if (aSplay.start() != nullptr)
exit(EXIT_FAILURE);
if (aSplay.size() != 0)
aSplay.insert (new intnode(5), compareint);
- if (aSplay.start() == NULL)
+ if (aSplay.start() == nullptr)
exit(EXIT_FAILURE);
if (aSplay.size() != 1)
aSplay.destroy(destint);
- if (aSplay.start() != NULL)
+ if (aSplay.start() != nullptr)
exit(EXIT_FAILURE);
if (aSplay.size() != 0)
dlinkAdd(void *data, dlink_node * m, dlink_list * list)
{
m->data = data;
- m->prev = NULL;
+ m->prev = nullptr;
m->next = list->head;
if (list->head)
list->head = m;
- if (list->tail == NULL)
+ if (list->tail == nullptr)
list->tail = m;
}
dlinkAddTail(void *data, dlink_node * m, dlink_list * list)
{
m->data = data;
- m->next = NULL;
+ m->next = nullptr;
m->prev = list->tail;
if (list->tail)
list->tail = m;
- if (list->head == NULL)
+ if (list->head == nullptr)
list->head = m;
}
if (m == list->tail)
list->tail = m->prev;
- m->next = m->prev = NULL;
+ m->next = m->prev = nullptr;
}
*/
static const time_t passwd_ttl = 60 * 60 * 3; /* in sec */
static const char *script_name = "/cgi-bin/cachemgr.cgi";
-static const char *progname = NULL;
+static const char *progname = nullptr;
static time_t now;
/*
*str = p + 1;
*p = '\0';
} else
- *str = NULL;
+ *str = nullptr;
/* trim */
len = strlen(tok);
fp = fopen("cachemgr.conf", "r");
- if (fp == NULL)
+ if (fp == nullptr)
fp = fopen(DEFAULT_CACHEMGR_CONFIG, "r");
- if (fp == NULL)
+ if (fp == nullptr)
printf("X-Error: message=\"Unable to open config %s\"", DEFAULT_CACHEMGR_CONFIG);
printf("Content-Type: text/html\r\n\r\n");
printf("<TABLE BORDER=\"0\" CELLPADDING=\"10\" CELLSPACING=\"1\">\n");
- if (fp != NULL) {
+ if (fp != nullptr) {
int servers = 0;
char config_line[BUFSIZ];
if (config_line[0] == '\0')
continue;
- if ((server = strtok(config_line, " \t")) == NULL)
+ if ((server = strtok(config_line, " \t")) == nullptr)
continue;
if (strchr(server, '*') || strchr(server, '[') || strchr(server, '?')) {
continue;
}
- comment = strtok(NULL, "");
+ comment = strtok(nullptr, "");
if (comment)
while (*comment == ' ' || *comment == '\t')
const char *sp = strchr(sline, ' ');
if (statusStr)
- *statusStr = NULL;
+ *statusStr = nullptr;
if (strncasecmp(sline, "HTTP/", 5) || !sp)
return -1;
} istate = isStatusLine;
int parse_menu = 0;
const char *action = req->action;
- const char *statusStr = NULL;
+ const char *statusStr = nullptr;
int status = -1;
if (0 == strlen(req->action))
else if (0 == strcasecmp(req->action, "menu"))
parse_menu = 1;
- if (fp == NULL) {
+ if (fp == nullptr) {
#if _SQUID_WINDOWS_
perror(tmpfile);
xfree(tmpfile);
{
char ipbuf[MAX_IPSTRLEN];
- struct addrinfo *AI = NULL;
+ struct addrinfo *AI = nullptr;
Ip::Address S;
int s;
int l;
static char buf[2 * 1024];
- if (req == NULL) {
+ if (req == nullptr) {
auth_html(CACHEMGR_HOSTNAME, CACHE_HTTP_PORT, "");
return 1;
}
- if (req->hostname == NULL) {
+ if (req->hostname == nullptr) {
req->hostname = xstrdup(CACHEMGR_HOSTNAME);
}
req->port = CACHE_HTTP_PORT;
}
- if (req->action == NULL) {
+ if (req->action == nullptr) {
req->action = xstrdup("");
}
char *s;
cachemgr_request *req;
- now = time(NULL);
+ now = time(nullptr);
#if _SQUID_WINDOWS_
Win32SockInit();
else
progname = xstrdup(argv[0]);
- if ((s = getenv("SCRIPT_NAME")) != NULL)
+ if ((s = getenv("SCRIPT_NAME")) != nullptr)
script_name = xstrdup(s);
char **args = argv;
{
char *s;
- if ((s = getenv("REQUEST_METHOD")) == NULL)
- return NULL;
+ if ((s = getenv("REQUEST_METHOD")) == nullptr)
+ return nullptr;
if (0 != strcasecmp(s, "POST"))
- return NULL;
+ return nullptr;
- if ((s = getenv("CONTENT_LENGTH")) == NULL)
- return NULL;
+ if ((s = getenv("CONTENT_LENGTH")) == nullptr)
+ return nullptr;
if (*s == '-') // negative length content huh?
- return NULL;
+ return nullptr;
uint64_t len;
char *endptr = s+ strlen(s);
if ((len = strtoll(s, &endptr, 10)) <= 0)
- return NULL;
+ return nullptr;
// limit the input to something reasonable.
// 4KB should be enough for the GET/POST data length, but may be extended.
size_t readLen = fread(buf, 1, bufLen, stdin);
if (readLen == 0) {
xfree(buf);
- return NULL;
+ return nullptr;
}
buf[readLen] = '\0';
len -= readLen;
{
char *s;
- if ((s = getenv("QUERY_STRING")) == NULL)
- return NULL;
+ if ((s = getenv("QUERY_STRING")) == nullptr)
+ return nullptr;
return xstrdup(s);
}
cachemgr_request *req;
char *s;
- char *t = NULL;
+ char *t = nullptr;
char *q;
- if ((buf = read_post_request()) != NULL)
+ if ((buf = read_post_request()) != nullptr)
(void) 0;
- else if ((buf = read_get_request()) != NULL)
+ else if ((buf = read_get_request()) != nullptr)
(void) 0;
else
- return NULL;
+ return nullptr;
#if _SQUID_WINDOWS_
#endif
{
xfree(buf);
- return NULL;
+ return nullptr;
}
req = (cachemgr_request *)xcalloc(1, sizeof(cachemgr_request));
- for (s = strtok(buf, "&"); s != NULL; s = strtok(NULL, "&")) {
+ for (s = strtok(buf, "&"); s != nullptr; s = strtok(nullptr, "&")) {
safe_free(t);
t = xstrdup(s);
- if ((q = strchr(t, '=')) == NULL)
+ if ((q = strchr(t, '=')) == nullptr)
continue;
*q = '\0';
char *p;
req->hostname = strtok(req->server, ":");
- if ((p = strtok(NULL, ":")))
+ if ((p = strtok(nullptr, ":")))
req->port = atoi(p);
}
debug("cmgr: length ok\n");
/* parse ( a lot of memory leaks, but that is cachemgr style :) */
- if ((host_name = strtok(buf, "|")) == NULL) {
+ if ((host_name = strtok(buf, "|")) == nullptr) {
xfree(buf);
return;
}
debug("cmgr: decoded host: '%s'\n", host_name);
- if ((time_str = strtok(NULL, "|")) == NULL) {
+ if ((time_str = strtok(nullptr, "|")) == nullptr) {
xfree(buf);
return;
}
debug("cmgr: decoded time: '%s' (now: %d)\n", time_str, (int) now);
char *user_name;
- if ((user_name = strtok(NULL, "|")) == NULL) {
+ if ((user_name = strtok(nullptr, "|")) == nullptr) {
xfree(buf);
return;
}
debug("cmgr: decoded uname: '%s'\n", user_name);
char *passwd;
- if ((passwd = strtok(NULL, "|")) == NULL) {
+ if ((passwd = strtok(nullptr, "|")) == nullptr) {
xfree(buf);
return;
}
check_target_acl(const char *hostname, int port)
{
char config_line[BUFSIZ];
- FILE *fp = NULL;
+ FILE *fp = nullptr;
int ret = 0;
fp = fopen("cachemgr.conf", "r");
- if (fp == NULL)
+ if (fp == nullptr)
fp = fopen(DEFAULT_CACHEMGR_CONFIG, "r");
- if (fp == NULL) {
+ if (fp == nullptr) {
#ifdef CACHEMGR_HOSTNAME_DEFINED
// TODO: simplify and maybe get rid of CACHEMGR_HOSTNAME altogether
if (strcmp(hostname, CACHEMGR_HOSTNAME) == 0 && port == CACHE_HTTP_PORT)
}
while (fgets(config_line, BUFSIZ, fp)) {
- char *token = NULL;
+ char *token = nullptr;
strtok(config_line, " \r\n\t");
if (config_line[0] == '#')
if (config_line[0] == '\0')
continue;
- if ((token = strtok(config_line, ":")) == NULL)
+ if ((token = strtok(config_line, ":")) == nullptr)
continue;
#if HAVE_FNMATCH_H
#endif
- if ((token = strtok(NULL, ":")) != NULL) {
+ if ((token = strtok(nullptr, ":")) != nullptr) {
int i;
if (strcmp(token, "*") == 0)
(int)subs[offset].rm_so,
(int)subs[offset].rm_eo,
line+subs[offset].rm_so );
- cd.size = strtoul( line+subs[offset].rm_so, 0, 10 );
+ cd.size = strtoul( line+subs[offset].rm_so, nullptr, 10 );
++offset;
// extract 1st level directories
(int)subs[offset].rm_so,
(int)subs[offset].rm_eo,
line+subs[offset].rm_so );
- cd.level[0] = strtoul( line+subs[offset].rm_so, 0, 10 );
+ cd.level[0] = strtoul( line+subs[offset].rm_so, nullptr, 10 );
++offset;
// extract 2nd level directories
(int)subs[offset].rm_so,
(int)subs[offset].rm_eo,
line+subs[offset].rm_so );
- cd.level[1] = strtoul( line+subs[offset].rm_so, 0, 10 );
+ cd.level[1] = strtoul( line+subs[offset].rm_so, nullptr, 10 );
++offset;
cachedir.push_back( cd );
int
readConfigFile( CacheDirVector& cachedir,
const char* fn,
- FILE* debug = 0 );
+ FILE* debug = nullptr );
// purpose: read squid.conf file and extract cache_dir entries
// paramtr: cachedir (OUT): vector with an entry for each cache_dir found
// fn (IN): file name of squid.conf to use
if ( (peer ? getpeername( fd, (SA*) &socket, &len ) :
getsockname( fd, (SA*) &socket, &len )) == -1 )
- return NULL;
+ return nullptr;
else
return my_sock_ntoa( socket, buffer );
}
// dst (OUT): the internet address in network byteorder.
// returns: -1 in case of error, see h_errno; 0 otherwise.
{
- if ( host == 0 ) return -1;
+ if ( host == nullptr ) return -1;
unsigned long int h = inet_addr(host);
if ( h == 0xFFFFFFFF && strncmp(host,"255.255.255.255",15) != 0 ) {
// symbolic host
struct hostent* dns = gethostbyname(host);
- if ( dns == NULL ) return -1;
+ if ( dns == nullptr ) return -1;
else memcpy( &dst.s_addr, dns->h_addr, dns->h_length );
} else {
// numeric host
// dst (OUT): port number in network byteorder.
// returns: -1 in case of error, see errno; 0 otherwise.
{
- int p = strtoul(port,0,0);
+ int p = strtoul(port,nullptr,0);
if ( p == 0 ) {
// symbolic port
struct servent* proto = getservbyname( port, "tcp" );
- if ( proto == NULL ) return -1;
+ if ( proto == nullptr ) return -1;
else dst = proto->s_port;
} else {
// numeric port
// find hostname part after the scheme (okok, not counting port, etc.)
const char* ptr = strstr( url, "://" );
- if ( ptr == 0 || strlen(ptr) < 4 ) return false;
+ if ( ptr == nullptr || strlen(ptr) < 4 ) return false;
// create filename to store contents into
// NP: magic extra 5 bytes for the component delimiter and termination octets
char *filename = new char[ strlen(ptr) + strlen(copydir) + strlen(index) +5 ];
- assert( filename != 0 );
+ assert( filename != nullptr );
strcpy( filename, copydir );
strcat( filename, "/" );
char* here = filename + strlen(filename);
strcat( filename, ptr+3 );
// handle server root (e.g. "http://www.focus.de" )
- if ( strchr( ptr+3, '/' ) == 0 ) strcat( filename, "/" );
+ if ( strchr( ptr+3, '/' ) == nullptr ) strcat( filename, "/" );
// handle directories (e.g. "http://www.focus.de/A/" )
if ( filename[strlen(filename)-1] == '/' ) strcat( filename, index );
}
// create source mmap to copy from (mmap complete file)
- caddr_t src = (caddr_t) mmap( 0, filesize, PROT_READ,
+ caddr_t src = (caddr_t) mmap( nullptr, filesize, PROT_READ,
MAP_FILE | MAP_SHARED, input, 0 );
if ( src == (caddr_t) -1 ) {
perror( "mmap input" );
}
// create destination mmap to copy into (mmap data portion)
- caddr_t dst = (caddr_t) mmap( 0, filesize-metasize, PROT_READ | PROT_WRITE,
+ caddr_t dst = (caddr_t) mmap( nullptr, filesize-metasize, PROT_READ | PROT_WRITE,
MAP_FILE | MAP_SHARED, out, 0 );
if ( dst == (caddr_t) -1 ) {
perror( "mmap output" );
#endif // DEFAULTPORT
volatile sig_atomic_t term_flag = 0; // 'terminate' is a gcc 2.8.x internal...
-char* linebuffer = 0;
+char* linebuffer = nullptr;
size_t buffersize = 128*1024;
-static char* copydir = 0;
+static char* copydir = nullptr;
static uint32_t debugFlag = 0;
static unsigned purgeMode = 0;
static bool iamalive = false;
static bool verbose = false;
static bool envelope = false;
static bool no_fork = false;
-static const char* programname = 0;
+static const char* programname = nullptr;
// ----------------------------------------------------------------------
};
REList::REList( const char* what, bool doCase )
- :next(0),data(xstrdup(what))
+ :next(nullptr),data(xstrdup(what))
{
int result = regcomp( &rexp, what,
REG_EXTENDED | REG_NOSUB | (doCase ? 0 : REG_ICASE) );
bool
REList::match( const char* check ) const
{
- int result = regexec( &rexp, check, 0, 0, 0 );
+ int result = regexec( &rexp, check, 0, nullptr, 0 );
if ( result != 0 && result != REG_NOMATCH ) {
char buffer[256];
regerror( result, &rexp, buffer, 256 );
// first run: determine size
unsigned size = strlen(start)+1;
va_start( ap, start );
- while ( (s=va_arg(ap,const char*)) != NULL )
+ while ( (s=va_arg(ap,const char*)) != nullptr )
size += strlen(s);
va_end(ap);
// allocate
char* result = new char[size];
- if ( result == 0 ) {
+ if ( result == nullptr ) {
perror( "string memory allocation" );
exit(EXIT_FAILURE);
}
// second run: copy content
strcpy( result, start );
va_start( ap, start );
- while ( (s=va_arg(ap,const char*)) != NULL ) strcat( result, s );
+ while ( (s=va_arg(ap,const char*)) != nullptr ) strcat( result, s );
va_end(ap);
return result;
{
static const char hexdigit[] = "0123456789ABCDEF";
char md5[34];
- const SquidTLV* findings = 0;
+ const SquidTLV* findings = nullptr;
if ( meta && (findings = meta->search( STORE_META_KEY_MD5 )) ) {
unsigned char* s = (unsigned char*) findings->data;
}
buffer[bufsize-1] = '\0';
close(sockfd);
- int64_t s = strtol(buffer+8,0,10);
+ int64_t s = strtol(buffer+8,nullptr,10);
if (s > 0 && s < 1000)
status = s;
else {
const SquidTLV* urlmeta = meta.search( STORE_META_URL );
if ( urlmeta ) {
// found URL in meta data. Try to process the URL
- if ( list == 0 )
+ if ( list == nullptr )
flag = action( fd, datastart, fn, (char*) urlmeta->data, meta );
else {
REList* head = (REList*) list; // YUCK!
- while ( head != 0 ) {
+ while ( head != nullptr ) {
if ( head->match( (char*) urlmeta->data ) ) break;
head = head->next;
}
- if ( head != 0 )
+ if ( head != nullptr )
flag = action( fd, datastart, fn, (char*) urlmeta->data, meta );
else flag = true;
}
// weird file, TODO: stat() it!
struct stat st;
long size = ( fstat(fd,&st) == -1 ? -1 : st.st_size );
- if ( ::verbose ) flag = ( log_extended( fn, -1, size, 0 ) >= 0 );
+ if ( ::verbose ) flag = ( log_extended( fn, -1, size, nullptr ) >= 0 );
else flag = ( log_output( fn, -1, size, "strange file" ) >= 0 );
if ( (::purgeMode & 0x04) ) {
fprintf( stderr, "# [2] %s\n", directory );
DIR* dir = opendir( directory );
- if ( dir == NULL ) {
+ if ( dir == nullptr ) {
fprintf( stderr, "unable to open directory \"%s\": %s\n",
directory, strerror(errno) );
return false;
fprintf( stderr, "# [%d] %s\n", (level ? 1 : 0), dirname );
DIR* dir = opendir( dirname );
- if ( dir == NULL ) {
+ if ( dir == nullptr ) {
fprintf( stderr, "unable to open directory \"%s\": %s\n",
dirname, strerror(errno) );
return false;
// -1 if not a port
{
// if there is a period in there, it must be a valid hostname
- if ( strchr( arg, '.' ) != 0 ) return -1;
+ if ( strchr( arg, '.' ) != nullptr ) return -1;
// if it is just a number between 0 and 65535, it must be a port
- char* errstr = 0;
+ char* errstr = nullptr;
unsigned long result = strtoul( arg, &errstr, 0 );
if ( result < 65536 && errstr != arg ) return htons(result);
FILE* rfile;
// program basename
- if ( (ptr = strrchr(argv[0],'/')) == NULL )
+ if ( (ptr = strrchr(argv[0],'/')) == nullptr )
ptr=argv[0];
else
++ptr;
::programname = ptr;
// extract commandline parameters
- REList* tail = head = 0;
+ REList* tail = head = nullptr;
opterr = 0;
while ( (option = getopt( argc, argv, "ac:C:d:E:e:F:f:Hnp:P:sv" )) != -1 ) {
switch ( option ) {
fprintf( stderr, "%c expects a mask parameter. Debug disabled.\n", option );
::debugFlag = 0;
} else
- ::debugFlag = (strtoul(optarg, NULL, 0) & 0xFFFFFFFF);
+ ::debugFlag = (strtoul(optarg, nullptr, 0) & 0xFFFFFFFF);
break;
case 'E':
fprintf( stderr, "%c requires a regex pattern argument!\n", option );
exit(EXIT_FAILURE);
}
- if ( head == 0 )
+ if ( head == nullptr )
tail = head = new REList( optarg, option=='E' );
else {
tail->next = new REList( optarg, option=='E' );
fprintf( stderr, "%c requires a filename argument!\n", option );
exit(EXIT_FAILURE);
}
- if ( (rfile = fopen( optarg, "r" )) != NULL ) {
+ if ( (rfile = fopen( optarg, "r" )) != nullptr ) {
unsigned long lineno = 0;
#define LINESIZE 512
char line[LINESIZE];
- while ( fgets( line, LINESIZE, rfile ) != NULL ) {
+ while ( fgets( line, LINESIZE, rfile ) != nullptr ) {
++lineno;
int len = strlen(line)-1;
if ( len+2 >= LINESIZE ) {
}
// insert into list of expressions
- if ( head == 0 ) tail = head = new REList(line,option=='F');
+ if ( head == nullptr ) tail = head = new REList(line,option=='F');
else {
tail->next = new REList(line,option=='F');
tail = tail->next;
exit(EXIT_FAILURE);
}
colon = strchr( optarg, ':' );
- if ( colon == 0 ) {
+ if ( colon == nullptr ) {
// no colon, only look at host
// fix: see if somebody just put in there a port (no periods)
fprintf( stderr, "%c requires a mode argument!\n", option );
exit(EXIT_FAILURE);
}
- ::purgeMode = ( strtol( optarg, 0, 0 ) & 0x07 );
+ ::purgeMode = ( strtol( optarg, nullptr, 0 ) & 0x07 );
break;
case 's':
showme=1;
// adjust
if ( ! isatty(fileno(stdout)) || (::debugFlag & 0x01) ) ::iamalive = false;
- if ( head == 0 ) {
+ if ( head == nullptr ) {
fputs( "There was no regular expression defined. If you intend\n", stderr );
fputs( "to match all possible URLs, use \"-e .\" instead.\n", stderr );
exit(EXIT_FAILURE);
}
// postcondition: head != 0
- assert( head != 0 );
+ assert( head != nullptr );
// make sure that the copy out directory is there and accessible
if ( copyDirPath && *copyDirPath )
printf( "# Regular expression: " );
unsigned count(0);
- for ( tail = head; tail != NULL; tail = tail->next ) {
+ for ( tail = head; tail != nullptr; tail = tail->next ) {
if ( count++ )
printf( "#%22u", count );
#if defined(LINUX) && putc==_IO_putc
static
int
-makelinebuffered( FILE* fp, const char* fn = 0 )
+makelinebuffered( FILE* fp, const char* fn = nullptr )
// purpose: make the given FILE line buffered
// paramtr: fp (IO): file pointer which to put into line buffer mode
// fn (IN): name of file to print in case of error
// returns: 0 is ok, -1 to indicate an error
// warning: error messages will already be printed
{
- if ( setvbuf( fp, 0, _IOLBF, 0 ) == 0 ) {
+ if ( setvbuf( fp, nullptr, _IOLBF, 0 ) == 0 ) {
// ok
return 0;
} else {
main( int argc, char* argv[] )
{
// setup variables
- REList* list = 0;
+ REList* list = nullptr;
char* conffile = xstrdup(DEFAULT_CONFIG_FILE);
serverPort = htons(DEFAULTPORT);
if ( convertHostname(DEFAULTHOST,serverHost) == -1 ) {
// setup line buffer
::linebuffer = new char[ ::buffersize ];
- assert( ::linebuffer != 0 );
+ assert( ::linebuffer != nullptr );
// parse commandline
puts( "### Use at your own risk! No guarantees whatsoever. You were warned. ###");
// try to read squid.conf file to determine all cache_dir locations
CacheDirVector cdv(0);
- if ( readConfigFile( cdv, conffile, debugFlag ? stderr : 0 ) > 0 ) {
+ if ( readConfigFile( cdv, conffile, debugFlag ? stderr : nullptr ) > 0 ) {
// there are some valid cache_dir entries.
// unless forking was forbidden by cmdline option,
// for a process for each cache_dir entry to remove files.
#include "squid-tlv.hh"
SquidTLV::SquidTLV( SquidMetaType _type, size_t _size, void* _data )
- :next(0),size(_size)
+ :next(nullptr),size(_size)
{
type = _type;
data = (char*) _data;
SquidMetaList::SquidMetaList()
{
- head = tail = 0;
+ head = tail = nullptr;
}
SquidMetaList::~SquidMetaList()
SquidMetaList::append( SquidMetaType type, size_t size, void* data )
{
SquidTLV* temp = new SquidTLV( type, size, data );
- if ( head == 0 ) head = tail = temp;
+ if ( head == nullptr ) head = tail = temp;
else {
tail->next = temp;
tail = temp;
struct SquidTLV {
// create a shallow reference pointing into the "buffer" variable
// do not copy --> saves times, saves memory.
- SquidTLV( SquidMetaType _type, size_t _size = 0, void* _data = 0 );
+ SquidTLV( SquidMetaType _type, size_t _size = 0, void* _data = nullptr );
~SquidTLV() {}
SquidTLV* next;
if (Ping::Config.enable) {
#if HAVE_SIGACTION
struct sigaction sa, osa;
- if (sigaction(SIGINT, NULL, &osa) == 0 && osa.sa_handler == SIG_DFL) {
+ if (sigaction(SIGINT, nullptr, &osa) == 0 && osa.sa_handler == SIG_DFL) {
sa.sa_handler = catchSignal;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
- (void) sigaction(SIGINT, &sa, NULL);
+ (void) sigaction(SIGINT, &sa, nullptr);
}
#else
void (*osig) (int);
#if GETTIMEOFDAY_NO_TZP
(void)gettimeofday(&tv1);
#else
- (void)gettimeofday(&tv1, NULL);
+ (void)gettimeofday(&tv1, nullptr);
#endif
}
#if GETTIMEOFDAY_NO_TZP
(void)gettimeofday(&tv2);
#else
- (void)gettimeofday(&tv2, NULL);
+ (void)gettimeofday(&tv2, nullptr);
#endif
elapsed_msec = tvSubMsec(tv1, tv2);
tvs.tv_sec = msec_left / 1000;
tvs.tv_usec = (msec_left % 1000) * 1000;
- select(0, NULL, NULL, NULL, &tvs);
+ select(0, nullptr, nullptr, nullptr, &tvs);
}
}
// options for controlling squidclient ping mode
static struct option pingOptions[] = {
- {"count", no_argument, 0, 'g'},
- {"interval", no_argument, 0, 'I'},
- {0, 0, 0, 0}
+ {"count", no_argument, nullptr, 'g'},
+ {"interval", no_argument, nullptr, 'I'},
+ {nullptr, 0, nullptr, 0}
};
int saved_opterr = opterr;
// options for controlling squidclient transport connection
static struct option longOptions[] = {
- {"anonymous-tls",no_argument, 0, '\1'},
- {"https", no_argument, 0, '\3'},
- {"trusted-ca", required_argument, 0, 'A'},
- {"cert", required_argument, 0, 'C'},
- {"host", required_argument, 0, 'h'},
- {"local", required_argument, 0, 'l'},
- {"port", required_argument, 0, 'p'},
- {"params", required_argument, 0, 'P'},
- {0, 0, 0, 0}
+ {"anonymous-tls",no_argument, nullptr, '\1'},
+ {"https", no_argument, nullptr, '\3'},
+ {"trusted-ca", required_argument, nullptr, 'A'},
+ {"cert", required_argument, nullptr, 'C'},
+ {"host", required_argument, nullptr, 'h'},
+ {"local", required_argument, nullptr, 'l'},
+ {"port", required_argument, nullptr, 'p'},
+ {"params", required_argument, nullptr, 'P'},
+ {nullptr, 0, nullptr, 0}
};
int saved_opterr = opterr;
static int
client_comm_bind(int sock, const Ip::Address &addr)
{
- static struct addrinfo *AI = NULL;
+ static struct addrinfo *AI = nullptr;
addr.getAddrInfo(AI);
int res = bind(sock, AI->ai_addr, AI->ai_addrlen);
Ip::Address::FreeAddr(AI);
static void
resolveDestination(Ip::Address &iaddr)
{
- struct addrinfo *AI = NULL;
+ struct addrinfo *AI = nullptr;
debugVerbose(2, "Transport detected: IPv4" <<
((Ip::EnableIpv6 & IPV6_SPECIAL_V4MAPPING) ? "-mapped " : "") <<
static int
client_comm_connect(int sock, const Ip::Address &addr)
{
- static struct addrinfo *AI = NULL;
+ static struct addrinfo *AI = nullptr;
addr.getAddrInfo(AI);
int res = connect(sock, AI->ai_addr, AI->ai_addrlen);
Ip::Address::FreeAddr(AI);
public:
TheConfig() :
ioTimeout(120),
- localHost(NULL),
+ localHost(nullptr),
port(CACHE_HTTP_PORT),
tlsEnabled(false),
tlsAnonymous(false) {
gss_buffer_desc service = GSS_C_EMPTY_BUFFER;
gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
- char *token = NULL;
+ char *token = nullptr;
- setbuf(stdout, NULL);
- setbuf(stdin, NULL);
+ setbuf(stdout, nullptr);
+ setbuf(stdin, nullptr);
if (!server) {
std::cerr << "ERROR: GSSAPI: No server name" << std::endl;
0,
GSS_C_NO_CHANNEL_BINDINGS,
&input_token,
- NULL,
+ nullptr,
&output_token,
- NULL,
- NULL);
+ nullptr,
+ nullptr);
if (!check_gss_err(major_status, minor_status, "gss_init_sec_context()") && output_token.length) {
token = new char[base64_encode_len(output_token.length)];
token[5] = '\0';
}
- gss_delete_sec_context(&minor_status, &gss_context, NULL);
+ gss_delete_sec_context(&minor_status, &gss_context, nullptr);
gss_release_buffer(&minor_status, &service);
gss_release_buffer(&minor_status, &input_token);
gss_release_buffer(&minor_status, &output_token);
Parameters scParams;
static int put_fd;
-static char *put_file = NULL;
+static char *put_file = nullptr;
static struct stat sb;
int total_bytes = 0;
time_t ims = 0;
int max_forwards = -1;
- const char *host = NULL;
+ const char *host = nullptr;
const char *version = "1.0";
- const char *useragent = NULL;
+ const char *useragent = nullptr;
/* set the defaults */
to_stdout = true;
// options for controlling squidclient
static struct option basicOptions[] = {
/* These are the generic options for squidclient itself */
- {"help", no_argument, 0, '?'},
- {"verbose", no_argument, 0, 'v'},
- {"quiet", no_argument, 0, 's'},
- {"host", required_argument, 0, 'h'},
- {"local", required_argument, 0, 'l'},
- {"port", required_argument, 0, 'p'},
- {"ping", no_argument, 0, '\1'},
- {"https", no_argument, 0, '\3'},
- {0, 0, 0, 0}
+ {"help", no_argument, nullptr, '?'},
+ {"verbose", no_argument, nullptr, 'v'},
+ {"quiet", no_argument, nullptr, 's'},
+ {"host", required_argument, nullptr, 'h'},
+ {"local", required_argument, nullptr, 'l'},
+ {"port", required_argument, nullptr, 'p'},
+ {"ping", no_argument, nullptr, '\1'},
+ {"https", no_argument, nullptr, '\3'},
+ {nullptr, 0, nullptr, 0}
};
int c;
/* Build the HTTP request */
if (strncmp(url, "mgr:", 4) == 0) {
char *t = xstrdup(url + 4);
- const char *at = NULL;
+ const char *at = nullptr;
if (!strrchr(t, '@')) { // ignore any -w password if @ is explicit already.
at = ProxyAuthorization.password;
}
sa.sa_flags = SA_RESTART;
sigemptyset(&sa.sa_mask);
- if (sigaction(SIGPIPE, &sa, NULL) < 0) {
+ if (sigaction(SIGPIPE, &sa, nullptr) < 0) {
std::cerr << "ERROR: Cannot set PIPE signal." << std::endl;
exit(EXIT_FAILURE);
}