#include "util/proxy_protocol.h"
struct proxy_protocol_data {
void (*write_uint16)(void* buf, uint16_t data);
void (*write_uint32)(void* buf, uint32_t data);
};
struct proxy_protocol_data pp_data;
struct proxy_protocol_lookup_table {
int id;
const char *text;
};
static struct proxy_protocol_lookup_table pp_parse_errors_data[] = {
{ PP_PARSE_NOERROR, "no parse error" },
{ PP_PARSE_SIZE, "not enough space for header" },
{ PP_PARSE_WRONG_HEADERv2, "could not match PROXYv2 header" },
{ PP_PARSE_UNKNOWN_CMD, "unknown command" },
{ PP_PARSE_UNKNOWN_FAM_PROT, "unknown family and protocol" },
};
void
pp_init(void (*write_uint16)(void* buf, uint16_t data),
void (*write_uint32)(void* buf, uint32_t data)) {
pp_data.write_uint16 = write_uint16;
pp_data.write_uint32 = write_uint32;
}
const char*
pp_lookup_error(enum pp_parse_errors error) {
return pp_parse_errors_data[error].text;
}
size_t
pp2_write_to_buf(uint8_t* buf, size_t buflen,
#ifdef INET6
struct sockaddr_storage* src,
#else
struct sockaddr_in* src,
#endif
int stream)
{
int af;
size_t expected_size;
if(!src) return 0;
af = (int)((struct sockaddr_in*)src)->sin_family;
expected_size = PP2_HEADER_SIZE + (af==AF_INET?12:36);
if(buflen < expected_size) {
return 0;
}
memcpy(buf, PP2_SIG, PP2_SIG_LEN);
buf += PP2_SIG_LEN;
*buf = (PP2_VERSION << 4) | PP2_CMD_PROXY;
buf++;
switch(af) {
case AF_INET:
*buf = (PP2_AF_INET<<4) |
(stream?PP2_PROT_STREAM:PP2_PROT_DGRAM);
buf++;
(*pp_data.write_uint16)(buf, 12);
buf += 2;
memcpy(buf,
&((struct sockaddr_in*)src)->sin_addr.s_addr, 4);
buf += 4;
(*pp_data.write_uint32)(buf, 0);
buf += 4;
memcpy(buf,
&((struct sockaddr_in*)src)->sin_port, 2);
buf += 2;
(*pp_data.write_uint16)(buf, 12);
break;
#ifdef INET6
case AF_INET6:
*buf = (PP2_AF_INET6<<4) |
(stream?PP2_PROT_STREAM:PP2_PROT_DGRAM);
buf++;
(*pp_data.write_uint16)(buf, 36);
buf += 2;
memcpy(buf,
&((struct sockaddr_in6*)src)->sin6_addr, 16);
buf += 16;
memset(buf, 0, 16);
buf += 16;
memcpy(buf, &((struct sockaddr_in6*)src)->sin6_port, 2);
buf += 2;
(*pp_data.write_uint16)(buf, 0);
break;
#endif
case AF_UNIX:
default:
return 0;
}
return expected_size;
}
int
pp2_read_header(uint8_t* buf, size_t buflen)
{
size_t size;
struct pp2_header* header = (struct pp2_header*)buf;
if(buflen < PP2_HEADER_SIZE) {
return PP_PARSE_SIZE;
}
if(memcmp(header, PP2_SIG, PP2_SIG_LEN) != 0 ||
((header->ver_cmd & 0xF0)>>4) != PP2_VERSION) {
return PP_PARSE_WRONG_HEADERv2;
}
size = PP2_HEADER_SIZE + ntohs(header->len);
if(buflen < size) {
return PP_PARSE_SIZE;
}
if((header->ver_cmd & 0xF) != PP2_CMD_LOCAL &&
(header->ver_cmd & 0xF) != PP2_CMD_PROXY) {
return PP_PARSE_UNKNOWN_CMD;
}
if(header->fam_prot != PP2_UNSPEC_UNSPEC &&
header->fam_prot != PP2_INET_STREAM &&
header->fam_prot != PP2_INET_DGRAM &&
header->fam_prot != PP2_INET6_STREAM &&
header->fam_prot != PP2_INET6_DGRAM &&
header->fam_prot != PP2_UNIX_STREAM &&
header->fam_prot != PP2_UNIX_DGRAM) {
return PP_PARSE_UNKNOWN_FAM_PROT;
}
return PP_PARSE_NOERROR;
}