basicauth.[ch]: refactor to make basicauth_string() reusable

This commit is contained in:
rofl0r 2018-02-23 20:16:39 +00:00 committed by rofl0r
parent 81ea4feb2e
commit 4d9891e59e
2 changed files with 30 additions and 15 deletions

View File

@ -26,35 +26,46 @@
#include "conf.h"
#include "base64.h"
/*
* Create basic-auth token in buf.
* Returns strlen of token on success,
* -1 if user/pass missing
* 0 if user/pass too long
*/
ssize_t basicauth_string(const char *user, const char *pass,
char *buf, size_t bufsize)
{
char tmp[256+2];
int l;
if (!user || !pass) return -1;
l = snprintf(tmp, sizeof tmp, "%s:%s", user, pass);
if (l < 0 || l >= (ssize_t) sizeof tmp) return 0;
if (bufsize < (BASE64ENC_BYTES((unsigned)l) + 1)) return 0;
base64enc(buf, tmp, l);
return BASE64ENC_BYTES(l);
}
/*
* Add entry to the basicauth list
*/
void basicauth_add (vector_t authlist,
const char *user, const char *pass)
{
char tmp[256+2];
char b[BASE64ENC_BYTES((sizeof tmp)-1) + 1];
int l;
size_t bl;
char b[BASE64ENC_BYTES((256+2)-1) + 1];
ssize_t ret;
if (user == NULL || pass == NULL) {
ret = basicauth_string(user, pass, b, sizeof b);
if (ret == -1) {
log_message (LOG_WARNING,
"Illegal basicauth rule: missing user or pass");
return;
}
l = snprintf(tmp, sizeof tmp, "%s:%s", user, pass);
if(l >= (ssize_t) sizeof tmp) {
} else if (ret == 0) {
log_message (LOG_WARNING,
"User / pass in basicauth rule too long");
"User / pass in basicauth rule too long");
return;
}
base64enc(b, tmp, l);
bl = BASE64ENC_BYTES(l) + 1;
if (vector_append(authlist, b, bl) == -ENOMEM) {
if (vector_append(authlist, b, ret + 1) == -ENOMEM) {
log_message (LOG_ERR,
"Unable to allocate memory in basicauth_add()");
return;

View File

@ -21,8 +21,12 @@
#ifndef TINYPROXY_BASICAUTH_H
#define TINYPROXY_BASICAUTH_H
#include <stddef.h>
#include "vector.h"
extern ssize_t basicauth_string(const char *user, const char *pass,
char *buf, size_t bufsize);
extern void basicauth_add (vector_t authlist,
const char *user, const char *pass);