repo_id stringlengths 6 101 | size int64 367 5.14M | file_path stringlengths 2 269 | content stringlengths 367 5.14M |
|---|---|---|---|
281677160/openwrt-package | 9,884 | luci-app-ssr-plus/shadowsocksr-libev/src/libudns/udns_dn.c | /* udns_dn.c
domain names manipulation routines
Copyright (C) 2005 Michael Tokarev <mjt@corpit.ru>
This file is part of UDNS library, an async DNS stub resolver.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library, in file named COPYING.LGPL; if not,
write to the Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
*/
#include <string.h>
#include "udns.h"
unsigned dns_dnlen(dnscc_t *dn) {
register dnscc_t *d = dn;
while(*d)
d += 1 + *d;
return (unsigned)(d - dn) + 1;
}
unsigned dns_dnlabels(register dnscc_t *dn) {
register unsigned l = 0;
while(*dn)
++l, dn += 1 + *dn;
return l;
}
unsigned dns_dnequal(register dnscc_t *dn1, register dnscc_t *dn2) {
register unsigned c;
dnscc_t *dn = dn1;
for(;;) {
if ((c = *dn1++) != *dn2++)
return 0;
if (!c)
return (unsigned)(dn1 - dn);
while(c--) {
if (DNS_DNLC(*dn1) != DNS_DNLC(*dn2))
return 0;
++dn1; ++dn2;
}
}
}
unsigned
dns_dntodn(dnscc_t *sdn, dnsc_t *ddn, unsigned ddnsiz) {
unsigned sdnlen = dns_dnlen(sdn);
if (ddnsiz < sdnlen)
return 0;
memcpy(ddn, sdn, sdnlen);
return sdnlen;
}
int
dns_ptodn(const char *name, unsigned namelen,
dnsc_t *dn, unsigned dnsiz, int *isabs)
{
dnsc_t *dp; /* current position in dn (len byte first) */
dnsc_t *const de /* end of dn: last byte that can be filled up */
= dn + (dnsiz >= DNS_MAXDN ? DNS_MAXDN : dnsiz) - 1;
dnscc_t *np = (dnscc_t *)name;
dnscc_t *ne = np + (namelen ? namelen : strlen((char*)np));
dnsc_t *llab; /* start of last label (llab[-1] will be length) */
unsigned c; /* next input character, or length of last label */
if (!dnsiz)
return 0;
dp = llab = dn + 1;
while(np < ne) {
if (*np == '.') { /* label delimiter */
c = dp - llab; /* length of the label */
if (!c) { /* empty label */
if (np == (dnscc_t *)name && np + 1 == ne) {
/* special case for root dn, aka `.' */
++np;
break;
}
return -1; /* zero label */
}
if (c > DNS_MAXLABEL)
return -1; /* label too long */
llab[-1] = (dnsc_t)c; /* update len of last label */
llab = ++dp; /* start new label, llab[-1] will be len of it */
++np;
continue;
}
/* check whenever we may put out one more byte */
if (dp >= de) /* too long? */
return dnsiz >= DNS_MAXDN ? -1 : 0;
if (*np != '\\') { /* non-escape, simple case */
*dp++ = *np++;
continue;
}
/* handle \-style escape */
/* note that traditionally, domain names (gethostbyname etc)
* used decimal \dd notation, not octal \ooo (RFC1035), so
* we're following this tradition here.
*/
if (++np == ne)
return -1; /* bad escape */
else if (*np >= '0' && *np <= '9') { /* decimal number */
/* we allow not only exactly 3 digits as per RFC1035,
* but also 2 or 1, for better usability. */
c = *np++ - '0';
if (np < ne && *np >= '0' && *np <= '9') { /* 2digits */
c = c * 10 + *np++ - '0';
if (np < ne && *np >= '0' && *np <= '9') {
c = c * 10 + *np++ - '0';
if (c > 255)
return -1; /* bad escape */
}
}
}
else
c = *np++;
*dp++ = (dnsc_t)c; /* place next out byte */
}
if ((c = dp - llab) > DNS_MAXLABEL)
return -1; /* label too long */
if ((llab[-1] = (dnsc_t)c) != 0) {
*dp++ = 0;
if (isabs)
*isabs = 0;
}
else if (isabs)
*isabs = 1;
return dp - dn;
}
dnscc_t dns_inaddr_arpa_dn[14] = "\07in-addr\04arpa";
dnsc_t *
dns_a4todn_(const struct in_addr *addr, dnsc_t *dn, dnsc_t *dne) {
const unsigned char *s = ((const unsigned char *)addr) + 4;
while(s > (const unsigned char *)addr) {
unsigned n = *--s;
dnsc_t *p = dn + 1;
if (n > 99) {
if (p + 2 > dne) return 0;
*p++ = n / 100 + '0';
*p++ = (n % 100 / 10) + '0';
*p = n % 10 + '0';
}
else if (n > 9) {
if (p + 1 > dne) return 0;
*p++ = n / 10 + '0';
*p = n % 10 + '0';
}
else {
if (p > dne) return 0;
*p = n + '0';
}
*dn = p - dn;
dn = p + 1;
}
return dn;
}
int dns_a4todn(const struct in_addr *addr, dnscc_t *tdn,
dnsc_t *dn, unsigned dnsiz) {
dnsc_t *dne = dn + (dnsiz > DNS_MAXDN ? DNS_MAXDN : dnsiz);
dnsc_t *p;
unsigned l;
p = dns_a4todn_(addr, dn, dne);
if (!p) return 0;
if (!tdn)
tdn = dns_inaddr_arpa_dn;
l = dns_dnlen(tdn);
if (p + l > dne) return dnsiz >= DNS_MAXDN ? -1 : 0;
memcpy(p, tdn, l);
return (p + l) - dn;
}
int dns_a4ptodn(const struct in_addr *addr, const char *tname,
dnsc_t *dn, unsigned dnsiz) {
dnsc_t *p;
int r;
if (!tname)
return dns_a4todn(addr, NULL, dn, dnsiz);
p = dns_a4todn_(addr, dn, dn + dnsiz);
if (!p) return 0;
r = dns_sptodn(tname, p, dnsiz - (p - dn));
return r != 0 ? r : dnsiz >= DNS_MAXDN ? -1 : 0;
}
dnscc_t dns_ip6_arpa_dn[10] = "\03ip6\04arpa";
dnsc_t *
dns_a6todn_(const struct in6_addr *addr, dnsc_t *dn, dnsc_t *dne) {
const unsigned char *s = ((const unsigned char *)addr) + 16;
if (dn + 64 > dne) return 0;
while(s > (const unsigned char *)addr) {
unsigned n = *--s & 0x0f;
*dn++ = 1;
*dn++ = n > 9 ? n + 'a' - 10 : n + '0';
*dn++ = 1;
n = *s >> 4;
*dn++ = n > 9 ? n + 'a' - 10 : n + '0';
}
return dn;
}
int dns_a6todn(const struct in6_addr *addr, dnscc_t *tdn,
dnsc_t *dn, unsigned dnsiz) {
dnsc_t *dne = dn + (dnsiz > DNS_MAXDN ? DNS_MAXDN : dnsiz);
dnsc_t *p;
unsigned l;
p = dns_a6todn_(addr, dn, dne);
if (!p) return 0;
if (!tdn)
tdn = dns_ip6_arpa_dn;
l = dns_dnlen(tdn);
if (p + l > dne) return dnsiz >= DNS_MAXDN ? -1 : 0;
memcpy(p, tdn, l);
return (p + l) - dn;
}
int dns_a6ptodn(const struct in6_addr *addr, const char *tname,
dnsc_t *dn, unsigned dnsiz) {
dnsc_t *p;
int r;
if (!tname)
return dns_a6todn(addr, NULL, dn, dnsiz);
p = dns_a6todn_(addr, dn, dn + dnsiz);
if (!p) return 0;
r = dns_sptodn(tname, p, dnsiz - (p - dn));
return r != 0 ? r : dnsiz >= DNS_MAXDN ? -1 : 0;
}
/* return size of buffer required to convert the dn into asciiz string.
* Keep in sync with dns_dntop() below.
*/
unsigned dns_dntop_size(dnscc_t *dn) {
unsigned size = 0; /* the size reqd */
dnscc_t *le; /* label end */
while(*dn) {
/* *dn is the length of the next label, non-zero */
if (size)
++size; /* for the dot */
le = dn + *dn + 1;
++dn;
do {
switch(*dn) {
case '.':
case '\\':
/* Special modifiers in zone files. */
case '"':
case ';':
case '@':
case '$':
size += 2;
break;
default:
if (*dn <= 0x20 || *dn >= 0x7f)
/* \ddd decimal notation */
size += 4;
else
size += 1;
}
} while(++dn < le);
}
size += 1; /* zero byte at the end - string terminator */
return size > DNS_MAXNAME ? 0 : size;
}
/* Convert the dn into asciiz string.
* Keep in sync with dns_dntop_size() above.
*/
int dns_dntop(dnscc_t *dn, char *name, unsigned namesiz) {
char *np = name; /* current name ptr */
char *const ne = name + namesiz; /* end of name */
dnscc_t *le; /* label end */
while(*dn) {
/* *dn is the length of the next label, non-zero */
if (np != name) {
if (np >= ne) goto toolong;
*np++ = '.';
}
le = dn + *dn + 1;
++dn;
do {
switch(*dn) {
case '.':
case '\\':
/* Special modifiers in zone files. */
case '"':
case ';':
case '@':
case '$':
if (np + 2 > ne) goto toolong;
*np++ = '\\';
*np++ = *dn;
break;
default:
if (*dn <= 0x20 || *dn >= 0x7f) {
/* \ddd decimal notation */
if (np + 4 >= ne) goto toolong;
*np++ = '\\';
*np++ = '0' + (*dn / 100);
*np++ = '0' + ((*dn % 100) / 10);
*np++ = '0' + (*dn % 10);
}
else {
if (np >= ne) goto toolong;
*np++ = *dn;
}
}
} while(++dn < le);
}
if (np >= ne) goto toolong;
*np++ = '\0';
return np - name;
toolong:
return namesiz >= DNS_MAXNAME ? -1 : 0;
}
#if 0
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i;
int sz;
dnsc_t dn[DNS_MAXDN+10];
dnsc_t *dl, *dp;
int isabs;
sz = (argc > 1) ? atoi(argv[1]) : 0;
for(i = 2; i < argc; ++i) {
int r = dns_ptodn(argv[i], 0, dn, sz, &isabs);
printf("%s: ", argv[i]);
if (r < 0) printf("error\n");
else if (!r) printf("buffer too small\n");
else {
printf("len=%d dnlen=%d size=%d name:",
r, dns_dnlen(dn), dns_dntop_size(dn));
dl = dn;
while(*dl) {
printf(" %d=", *dl);
dp = dl + 1;
dl = dp + *dl;
while(dp < dl) {
if (*dp <= ' ' || *dp >= 0x7f)
printf("\\%03d", *dp);
else if (*dp == '.' || *dp == '\\')
printf("\\%c", *dp);
else
putchar(*dp);
++dp;
}
}
if (isabs) putchar('.');
putchar('\n');
}
}
return 0;
}
#endif /* TEST */
|
281677160/openwrt-package | 3,206 | luci-app-ssr-plus/shadowsocksr-libev/src/libudns/ex-rdns.c | /* ex-rdns.c
parallel rDNS resolver example - read IP addresses from stdin,
write domain names to stdout
Copyright (C) 2005 Michael Tokarev <mjt@corpit.ru>
This file is part of UDNS library, an async DNS stub resolver.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library, in file named COPYING.LGPL; if not,
write to the Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/poll.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include "udns.h"
static int curq;
static const char *n2ip(const unsigned char *c) {
static char b[sizeof("255.255.255.255")];
sprintf(b, "%u.%u.%u.%u", c[0], c[1], c[2], c[3]);
return b;
}
static void dnscb(struct dns_ctx *ctx, struct dns_rr_ptr *rr, void *data) {
const char *ip = n2ip((unsigned char *)&data);
int i;
--curq;
if (rr) {
printf("%s", ip);
for(i = 0; i < rr->dnsptr_nrr; ++i)
printf(" %s", rr->dnsptr_ptr[i]);
putchar('\n');
free(rr);
}
else
fprintf(stderr, "%s: %s\n", ip, dns_strerror(dns_status(ctx)));
}
int main(int argc, char **argv) {
int c;
time_t now;
int maxq = 10;
struct pollfd pfd;
char linebuf[1024];
char *eol;
int eof;
if (dns_init(NULL, 1) < 0) {
fprintf(stderr, "unable to initialize dns library\n");
return 1;
}
while((c = getopt(argc, argv, "m:r")) != EOF) switch(c) {
case 'm': maxq = atoi(optarg); break;
case 'r':
dns_set_opt(0, DNS_OPT_FLAGS,
dns_set_opt(0, DNS_OPT_FLAGS, -1) | DNS_NORD);
break;
default: return 1;
}
if (argc != optind) return 1;
pfd.fd = dns_sock(0);
pfd.events = POLLIN;
now = time(NULL);
c = optind;
eof = 0;
while(curq || !eof) {
if (!eof && curq < maxq) {
union { struct in_addr a; void *p; } pa;
if (!fgets(linebuf, sizeof(linebuf), stdin)) {
eof = 1;
continue;
}
eol = strchr(linebuf, '\n');
if (eol) *eol = '\0';
if (!linebuf[0]) continue;
if (dns_pton(AF_INET, linebuf, &pa.a) <= 0)
fprintf(stderr, "%s: invalid address\n", linebuf);
else if (dns_submit_a4ptr(0, &pa.a, dnscb, pa.p) == 0)
fprintf(stderr, "%s: unable to submit query: %s\n",
linebuf, dns_strerror(dns_status(0)));
else
++curq;
continue;
}
if (curq) {
c = dns_timeouts(0, -1, now);
c = poll(&pfd, 1, c < 0 ? -1 : c * 1000);
now = time(NULL);
if (c)
dns_ioevent(0, now);
}
}
return 0;
}
|
281677160/openwrt-package | 4,813 | luci-app-ssr-plus/shadowsocksr-libev/src/libudns/udns_rr_srv.c | /* udns_rr_srv.c
parse/query SRV IN (rfc2782) records
Copyright (C) 2005 Michael Tokarev <mjt@corpit.ru>
This file is part of UDNS library, an async DNS stub resolver.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library, in file named COPYING.LGPL; if not,
write to the Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
Copyright 2005 Thadeu Lima de Souza Cascardo <cascardo@minaslivre.org>
2005-09-11:
Changed MX parser file into a SRV parser file
*/
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include "udns.h"
int
dns_parse_srv(dnscc_t *qdn, dnscc_t *pkt, dnscc_t *cur, dnscc_t *end,
void **result) {
struct dns_rr_srv *ret;
struct dns_parse p;
struct dns_rr rr;
int r, l;
char *sp;
dnsc_t srv[DNS_MAXDN];
assert(dns_get16(cur+2) == DNS_C_IN && dns_get16(cur+0) == DNS_T_SRV);
/* first, validate the answer and count size of the result */
l = 0;
dns_initparse(&p, qdn, pkt, cur, end);
while((r = dns_nextrr(&p, &rr)) > 0) {
cur = rr.dnsrr_dptr + 6;
r = dns_getdn(pkt, &cur, end, srv, sizeof(srv));
if (r <= 0 || cur != rr.dnsrr_dend)
return DNS_E_PROTOCOL;
l += dns_dntop_size(srv);
}
if (r < 0)
return DNS_E_PROTOCOL;
if (!p.dnsp_nrr)
return DNS_E_NODATA;
/* next, allocate and set up result */
l += dns_stdrr_size(&p);
ret = malloc(sizeof(*ret) + sizeof(struct dns_srv) * p.dnsp_nrr + l);
if (!ret)
return DNS_E_NOMEM;
ret->dnssrv_nrr = p.dnsp_nrr;
ret->dnssrv_srv = (struct dns_srv *)(ret+1);
/* and 3rd, fill in result, finally */
sp = (char*)(ret->dnssrv_srv + p.dnsp_nrr);
for (dns_rewind(&p, qdn), r = 0; dns_nextrr(&p, &rr); ++r) {
ret->dnssrv_srv[r].name = sp;
cur = rr.dnsrr_dptr;
ret->dnssrv_srv[r].priority = dns_get16(cur);
ret->dnssrv_srv[r].weight = dns_get16(cur+2);
ret->dnssrv_srv[r].port = dns_get16(cur+4);
cur += 6;
dns_getdn(pkt, &cur, end, srv, sizeof(srv));
sp += dns_dntop(srv, sp, DNS_MAXNAME);
}
dns_stdrr_finish((struct dns_rr_null *)ret, sp, &p);
*result = ret;
return 0;
}
/* Add a single service or proto name prepending an undescore (_),
* according to rfc2782 rules.
* Return 0 or the label length.
* Routing assumes dn holds enouth space for a single DN label. */
static int add_sname(dnsc_t *dn, const char *sn) {
int l = dns_ptodn(sn, 0, dn + 1, DNS_MAXLABEL-1, NULL);
if (l <= 1 || l - 2 != dn[1])
/* Should we really check if sn is exactly one label? Do we care? */
return 0;
dn[0] = l - 1;
dn[1] = '_';
return l;
}
/* Construct a domain name for SRV query from the given name, service and proto.
* The code allows any combinations of srv and proto (both are non-NULL,
* both NULL, or either one is non-NULL). Whenever it makes any sense or not
* is left as an exercise to programmer.
* Return negative value on error (malformed query) or addition query flag(s).
*/
static int
build_srv_dn(dnsc_t *dn, const char *name, const char *srv, const char *proto)
{
int p = 0, l, isabs;
if (srv) {
l = add_sname(dn + p, srv);
if (!l)
return -1;
p += l;
}
if (proto) {
l = add_sname(dn + p, proto);
if (!l)
return -1;
p += l;
}
l = dns_ptodn(name, 0, dn + p, DNS_MAXDN - p, &isabs);
if (l < 0)
return -1;
return isabs ? DNS_NOSRCH : 0;
}
struct dns_query *
dns_submit_srv(struct dns_ctx *ctx,
const char *name, const char *srv, const char *proto,
int flags, dns_query_srv_fn *cbck, void *data) {
dnsc_t dn[DNS_MAXDN];
int r = build_srv_dn(dn, name, srv, proto);
if (r < 0) {
dns_setstatus (ctx, DNS_E_BADQUERY);
return NULL;
}
return
dns_submit_dn(ctx, dn, DNS_C_IN, DNS_T_SRV, flags | r,
dns_parse_srv, (dns_query_fn *)cbck, data);
}
struct dns_rr_srv *
dns_resolve_srv(struct dns_ctx *ctx,
const char *name, const char *srv, const char *proto, int flags)
{
dnsc_t dn[DNS_MAXDN];
int r = build_srv_dn(dn, name, srv, proto);
if (r < 0) {
dns_setstatus(ctx, DNS_E_BADQUERY);
return NULL;
}
return (struct dns_rr_srv *)
dns_resolve_dn(ctx, dn, DNS_C_IN, DNS_T_SRV, flags | r, dns_parse_srv);
}
|
281677160/openwrt-package | 6,895 | luci-app-ssr-plus/shadowsocksr-libev/src/libudns/udns_init.c | /* udns_init.c
resolver initialisation stuff
Copyright (C) 2006 Michael Tokarev <mjt@corpit.ru>
This file is part of UDNS library, an async DNS stub resolver.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library, in file named COPYING.LGPL; if not,
write to the Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#ifdef __MINGW32__
# include <winsock2.h> /* includes <windows.h> */
# include <iphlpapi.h> /* for dns server addresses etc */
#else
# include <sys/types.h>
# include <unistd.h>
# include <fcntl.h>
#endif /* !__MINGW32__ */
#include <stdlib.h>
#include <string.h>
#include "udns.h"
#define ISSPACE(x) (x == ' ' || x == '\t' || x == '\r' || x == '\n')
static const char space[] = " \t\r\n";
static void dns_set_serv_internal(struct dns_ctx *ctx, char *serv) {
dns_add_serv(ctx, NULL);
for(serv = strtok(serv, space); serv; serv = strtok(NULL, space))
dns_add_serv(ctx, serv);
}
static void dns_set_srch_internal(struct dns_ctx *ctx, char *srch) {
dns_add_srch(ctx, NULL);
for(srch = strtok(srch, space); srch; srch = strtok(NULL, space))
dns_add_srch(ctx, srch);
}
#ifdef __MINGW32__
#define NO_IPHLPAPI
#ifndef NO_IPHLPAPI
/* Apparently, some systems does not have proper headers for IPHLPAIP to work.
* The best is to upgrade headers, but here's another, ugly workaround for
* this: compile with -DNO_IPHLPAPI.
*/
typedef DWORD (WINAPI *GetAdaptersAddressesFunc)(
ULONG Family, DWORD Flags, PVOID Reserved,
PIP_ADAPTER_ADDRESSES pAdapterAddresses,
PULONG pOutBufLen);
static int dns_initns_iphlpapi(struct dns_ctx *ctx) {
HANDLE h_iphlpapi;
GetAdaptersAddressesFunc pfnGetAdAddrs;
PIP_ADAPTER_ADDRESSES pAddr, pAddrBuf;
PIP_ADAPTER_DNS_SERVER_ADDRESS pDnsAddr;
ULONG ulOutBufLen;
DWORD dwRetVal;
int ret = -1;
h_iphlpapi = LoadLibrary("iphlpapi.dll");
if (!h_iphlpapi)
return -1;
pfnGetAdAddrs = (GetAdaptersAddressesFunc)
GetProcAddress(h_iphlpapi, "GetAdaptersAddresses");
if (!pfnGetAdAddrs) goto freelib;
ulOutBufLen = 0;
dwRetVal = pfnGetAdAddrs(AF_UNSPEC, 0, NULL, NULL, &ulOutBufLen);
if (dwRetVal != ERROR_BUFFER_OVERFLOW) goto freelib;
pAddrBuf = malloc(ulOutBufLen);
if (!pAddrBuf) goto freelib;
dwRetVal = pfnGetAdAddrs(AF_UNSPEC, 0, NULL, pAddrBuf, &ulOutBufLen);
if (dwRetVal != ERROR_SUCCESS) goto freemem;
for (pAddr = pAddrBuf; pAddr; pAddr = pAddr->Next)
for (pDnsAddr = pAddr->FirstDnsServerAddress;
pDnsAddr;
pDnsAddr = pDnsAddr->Next)
dns_add_serv_s(ctx, pDnsAddr->Address.lpSockaddr);
ret = 0;
freemem:
free(pAddrBuf);
freelib:
FreeLibrary(h_iphlpapi);
return ret;
}
#else /* NO_IPHLPAPI */
#define dns_initns_iphlpapi(ctx) (-1)
#endif /* NO_IPHLPAPI */
static int dns_initns_registry(struct dns_ctx *ctx) {
LONG res;
HKEY hk;
DWORD type = REG_EXPAND_SZ | REG_SZ;
DWORD len;
char valBuf[1024];
#define REGKEY_WINNT "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"
#define REGKEY_WIN9x "SYSTEM\\CurrentControlSet\\Services\\VxD\\MSTCP"
res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGKEY_WINNT, 0, KEY_QUERY_VALUE, &hk);
if (res != ERROR_SUCCESS)
res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGKEY_WIN9x,
0, KEY_QUERY_VALUE, &hk);
if (res != ERROR_SUCCESS)
return -1;
len = sizeof(valBuf) - 1;
res = RegQueryValueEx(hk, "NameServer", NULL, &type, (BYTE*)valBuf, &len);
if (res != ERROR_SUCCESS || !len || !valBuf[0]) {
len = sizeof(valBuf) - 1;
res = RegQueryValueEx(hk, "DhcpNameServer", NULL, &type,
(BYTE*)valBuf, &len);
}
RegCloseKey(hk);
if (res != ERROR_SUCCESS || !len || !valBuf[0])
return -1;
valBuf[len] = '\0';
/* nameservers are stored as a whitespace-seperate list:
* "192.168.1.1 123.21.32.12" */
dns_set_serv_internal(ctx, valBuf);
return 0;
}
#else /* !__MINGW32__ */
static int dns_init_resolvconf(struct dns_ctx *ctx) {
char *v;
char buf[2049]; /* this buffer is used to hold /etc/resolv.conf */
int has_srch = 0;
/* read resolv.conf... */
{ int fd = open("/etc/resolv.conf", O_RDONLY);
if (fd >= 0) {
int l = read(fd, buf, sizeof(buf) - 1);
close(fd);
buf[l < 0 ? 0 : l] = '\0';
}
else
buf[0] = '\0';
}
if (buf[0]) { /* ...and parse it */
char *line, *nextline;
line = buf;
do {
nextline = strchr(line, '\n');
if (nextline) *nextline++ = '\0';
v = line;
while(*v && !ISSPACE(*v)) ++v;
if (!*v) continue;
*v++ = '\0';
while(ISSPACE(*v)) ++v;
if (!*v) continue;
if (strcmp(line, "domain") == 0) {
dns_set_srch_internal(ctx, strtok(v, space));
has_srch = 1;
}
else if (strcmp(line, "search") == 0) {
dns_set_srch_internal(ctx, v);
has_srch = 1;
}
else if (strcmp(line, "nameserver") == 0)
dns_add_serv(ctx, strtok(v, space));
else if (strcmp(line, "options") == 0)
dns_set_opts(ctx, v);
} while((line = nextline) != NULL);
}
buf[sizeof(buf)-1] = '\0';
/* get list of nameservers from env. vars. */
if ((v = getenv("NSCACHEIP")) != NULL ||
(v = getenv("NAMESERVERS")) != NULL) {
strncpy(buf, v, sizeof(buf) - 1);
dns_set_serv_internal(ctx, buf);
}
/* if $LOCALDOMAIN is set, use it for search list */
if ((v = getenv("LOCALDOMAIN")) != NULL) {
strncpy(buf, v, sizeof(buf) - 1);
dns_set_srch_internal(ctx, buf);
has_srch = 1;
}
if ((v = getenv("RES_OPTIONS")) != NULL)
dns_set_opts(ctx, v);
/* if still no search list, use local domain name */
if (has_srch &&
gethostname(buf, sizeof(buf) - 1) == 0 &&
(v = strchr(buf, '.')) != NULL &&
*++v != '\0')
dns_add_srch(ctx, v);
return 0;
}
#endif /* !__MINGW32__ */
int dns_init(struct dns_ctx *ctx, int do_open) {
if (!ctx)
ctx = &dns_defctx;
dns_reset(ctx);
#ifdef __MINGW32__
if (dns_initns_iphlpapi(ctx) != 0)
dns_initns_registry(ctx);
/*XXX __MINGW32__: probably good to get default domain and search list too...
* And options. Something is in registry. */
/*XXX __MINGW32__: maybe environment variables are also useful? */
#else
dns_init_resolvconf(ctx);
#endif
return do_open ? dns_open(ctx) : 0;
}
|
281677160/openwrt-package | 5,210 | luci-app-ssr-plus/shadowsocksr-libev/src/libudns/udns_bl.c | /* udns_bl.c
DNSBL stuff
Copyright (C) 2005 Michael Tokarev <mjt@corpit.ru>
This file is part of UDNS library, an async DNS stub resolver.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library, in file named COPYING.LGPL; if not,
write to the Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
*/
#include "udns.h"
#ifndef NULL
# define NULL 0
#endif
struct dns_query *
dns_submit_a4dnsbl(struct dns_ctx *ctx,
const struct in_addr *addr, const char *dnsbl,
dns_query_a4_fn *cbck, void *data) {
dnsc_t dn[DNS_MAXDN];
if (dns_a4ptodn(addr, dnsbl, dn, sizeof(dn)) <= 0) {
dns_setstatus(ctx, DNS_E_BADQUERY);
return NULL;
}
return
dns_submit_dn(ctx, dn, DNS_C_IN, DNS_T_A, DNS_NOSRCH,
dns_parse_a4, (dns_query_fn*)cbck, data);
}
struct dns_query *
dns_submit_a4dnsbl_txt(struct dns_ctx *ctx,
const struct in_addr *addr, const char *dnsbl,
dns_query_txt_fn *cbck, void *data) {
dnsc_t dn[DNS_MAXDN];
if (dns_a4ptodn(addr, dnsbl, dn, sizeof(dn)) <= 0) {
dns_setstatus(ctx, DNS_E_BADQUERY);
return NULL;
}
return
dns_submit_dn(ctx, dn, DNS_C_IN, DNS_T_TXT, DNS_NOSRCH,
dns_parse_txt, (dns_query_fn*)cbck, data);
}
struct dns_rr_a4 *
dns_resolve_a4dnsbl(struct dns_ctx *ctx,
const struct in_addr *addr, const char *dnsbl) {
return (struct dns_rr_a4 *)
dns_resolve(ctx, dns_submit_a4dnsbl(ctx, addr, dnsbl, 0, 0));
}
struct dns_rr_txt *
dns_resolve_a4dnsbl_txt(struct dns_ctx *ctx,
const struct in_addr *addr, const char *dnsbl) {
return (struct dns_rr_txt *)
dns_resolve(ctx, dns_submit_a4dnsbl_txt(ctx, addr, dnsbl, 0, 0));
}
struct dns_query *
dns_submit_a6dnsbl(struct dns_ctx *ctx,
const struct in6_addr *addr, const char *dnsbl,
dns_query_a4_fn *cbck, void *data) {
dnsc_t dn[DNS_MAXDN];
if (dns_a6ptodn(addr, dnsbl, dn, sizeof(dn)) <= 0) {
dns_setstatus(ctx, DNS_E_BADQUERY);
return NULL;
}
return
dns_submit_dn(ctx, dn, DNS_C_IN, DNS_T_A, DNS_NOSRCH,
dns_parse_a4, (dns_query_fn*)cbck, data);
}
struct dns_query *
dns_submit_a6dnsbl_txt(struct dns_ctx *ctx,
const struct in6_addr *addr, const char *dnsbl,
dns_query_txt_fn *cbck, void *data) {
dnsc_t dn[DNS_MAXDN];
if (dns_a6ptodn(addr, dnsbl, dn, sizeof(dn)) <= 0) {
dns_setstatus(ctx, DNS_E_BADQUERY);
return NULL;
}
return
dns_submit_dn(ctx, dn, DNS_C_IN, DNS_T_TXT, DNS_NOSRCH,
dns_parse_txt, (dns_query_fn*)cbck, data);
}
struct dns_rr_a4 *
dns_resolve_a6dnsbl(struct dns_ctx *ctx,
const struct in6_addr *addr, const char *dnsbl) {
return (struct dns_rr_a4 *)
dns_resolve(ctx, dns_submit_a6dnsbl(ctx, addr, dnsbl, 0, 0));
}
struct dns_rr_txt *
dns_resolve_a6dnsbl_txt(struct dns_ctx *ctx,
const struct in6_addr *addr, const char *dnsbl) {
return (struct dns_rr_txt *)
dns_resolve(ctx, dns_submit_a6dnsbl_txt(ctx, addr, dnsbl, 0, 0));
}
static int
dns_rhsbltodn(const char *name, const char *rhsbl, dnsc_t dn[DNS_MAXDN])
{
int l = dns_sptodn(name, dn, DNS_MAXDN);
if (l <= 0) return 0;
l = dns_sptodn(rhsbl, dn+l-1, DNS_MAXDN-l+1);
if (l <= 0) return 0;
return 1;
}
struct dns_query *
dns_submit_rhsbl(struct dns_ctx *ctx, const char *name, const char *rhsbl,
dns_query_a4_fn *cbck, void *data) {
dnsc_t dn[DNS_MAXDN];
if (!dns_rhsbltodn(name, rhsbl, dn)) {
dns_setstatus(ctx, DNS_E_BADQUERY);
return NULL;
}
return
dns_submit_dn(ctx, dn, DNS_C_IN, DNS_T_A, DNS_NOSRCH,
dns_parse_a4, (dns_query_fn*)cbck, data);
}
struct dns_query *
dns_submit_rhsbl_txt(struct dns_ctx *ctx, const char *name, const char *rhsbl,
dns_query_txt_fn *cbck, void *data) {
dnsc_t dn[DNS_MAXDN];
if (!dns_rhsbltodn(name, rhsbl, dn)) {
dns_setstatus(ctx, DNS_E_BADQUERY);
return NULL;
}
return
dns_submit_dn(ctx, dn, DNS_C_IN, DNS_T_TXT, DNS_NOSRCH,
dns_parse_txt, (dns_query_fn*)cbck, data);
}
struct dns_rr_a4 *
dns_resolve_rhsbl(struct dns_ctx *ctx, const char *name, const char *rhsbl) {
return (struct dns_rr_a4*)
dns_resolve(ctx, dns_submit_rhsbl(ctx, name, rhsbl, 0, 0));
}
struct dns_rr_txt *
dns_resolve_rhsbl_txt(struct dns_ctx *ctx, const char *name, const char *rhsbl)
{
return (struct dns_rr_txt*)
dns_resolve(ctx, dns_submit_rhsbl_txt(ctx, name, rhsbl, 0, 0));
}
|
281677160/openwrt-package | 21,549 | luci-app-ssr-plus/shadowsocksr-libev/src/libudns/dnsget.c | /* dnsget.c
simple host/dig-like application using UDNS library
Copyright (C) 2005 Michael Tokarev <mjt@corpit.ru>
This file is part of UDNS library, an async DNS stub resolver.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library, in file named COPYING.LGPL; if not,
write to the Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#ifdef __MINGW32__
#include <windows.h>
#include <winsock2.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <unistd.h>
#endif
#include <time.h>
#include <stdarg.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "udns.h"
#ifndef HAVE_GETOPT
# include "getopt.c"
#endif
#ifndef AF_INET6
# define AF_INET6 10
#endif
static char *progname;
static int verbose = 1;
static int errors;
static int notfound;
/* verbosity level:
* <0 - bare result
* 0 - bare result and error messages
* 1 - readable result
* 2 - received packet contents and `trying ...' stuff
* 3 - sent and received packet contents
*/
static void die(int errnum, const char *fmt, ...) {
va_list ap;
fprintf(stderr, "%s: ", progname);
va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap);
if (errnum) fprintf(stderr, ": %s\n", strerror(errnum));
else putc('\n', stderr);
fflush(stderr);
exit(1);
}
static const char *dns_xntop(int af, const void *src) {
static char buf[6*5+4*4];
return dns_ntop(af, src, buf, sizeof(buf));
}
struct query {
const char *name; /* original query string */
unsigned char *dn; /* the DN being looked up */
enum dns_type qtyp; /* type of the query */
};
static void query_free(struct query *q) {
free(q->dn);
free(q);
}
static struct query *
query_new(const char *name, const unsigned char *dn, enum dns_type qtyp) {
struct query *q = malloc(sizeof(*q));
unsigned l = dns_dnlen(dn);
unsigned char *cdn = malloc(l);
if (!q || !cdn) die(0, "out of memory");
memcpy(cdn, dn, l);
q->name = name;
q->dn = cdn;
q->qtyp = qtyp;
return q;
}
static enum dns_class qcls = DNS_C_IN;
static void
dnserror(struct query *q, int errnum) {
if (verbose >= 0)
fprintf(stderr, "%s: unable to lookup %s record for %s: %s\n", progname,
dns_typename(q->qtyp), dns_dntosp(q->dn), dns_strerror(errnum));
if (errnum == DNS_E_NXDOMAIN || errnum == DNS_E_NODATA)
++notfound;
else
++errors;
query_free(q);
}
static const unsigned char *
printtxt(const unsigned char *c) {
unsigned n = *c++;
const unsigned char *e = c + n;
if (verbose > 0) while(c < e) {
if (*c < ' ' || *c >= 127) printf("\\%03u", *c);
else if (*c == '\\' || *c == '"') printf("\\%c", *c);
else putchar(*c);
++c;
}
else
fwrite(c, n, 1, stdout);
return e;
}
static void
printhex(const unsigned char *c, const unsigned char *e) {
while(c < e)
printf("%02x", *c++);
}
static unsigned char to_b64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static void
printb64(const unsigned char *c, const unsigned char *e) {
while(c < e) {
putchar(to_b64[c[0] >> 2]);
if (c+1 < e) {
putchar(to_b64[(c[0] & 0x3) << 4 | c[1] >> 4]);
if (c+2 < e) {
putchar(to_b64[(c[1] & 0xf) << 2 | c[2] >> 6]);
putchar(to_b64[c[2] & 0x3f]);
}
else {
putchar(to_b64[(c[1] & 0xf) << 2]);
putchar('=');
break;
}
}
else {
putchar(to_b64[(c[0] & 0x3) << 4]);
putchar('=');
putchar('=');
break;
}
c += 3;
}
}
static void
printdate(time_t time) {
struct tm *tm = gmtime(&time);
printf("%04d%02d%02d%02d%02d%02d",
tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
}
static void
printrr(const struct dns_parse *p, struct dns_rr *rr) {
const unsigned char *pkt = p->dnsp_pkt;
const unsigned char *end = p->dnsp_end;
const unsigned char *dptr = rr->dnsrr_dptr;
const unsigned char *dend = rr->dnsrr_dend;
unsigned char *dn = rr->dnsrr_dn;
const unsigned char *c;
unsigned n;
if (verbose > 0) {
if (verbose > 1) {
if (!p->dnsp_rrl && !rr->dnsrr_dn[0] && rr->dnsrr_typ == DNS_T_OPT) {
printf(";EDNS%d OPT record (UDPsize: %d, ERcode: %d, Flags: 0x%02x): %d bytes\n",
(rr->dnsrr_ttl>>16) & 0xff, /* version */
rr->dnsrr_cls, /* udp size */
(rr->dnsrr_ttl>>24) & 0xff, /* extended rcode */
rr->dnsrr_ttl & 0xffff, /* flags */
rr->dnsrr_dsz);
return;
}
n = printf("%s.", dns_dntosp(rr->dnsrr_dn));
printf("%s%u\t%s\t%s\t",
n > 15 ? "\t" : n > 7 ? "\t\t" : "\t\t\t",
rr->dnsrr_ttl,
dns_classname(rr->dnsrr_cls),
dns_typename(rr->dnsrr_typ));
}
else
printf("%s. %s ", dns_dntosp(rr->dnsrr_dn), dns_typename(rr->dnsrr_typ));
}
switch(rr->dnsrr_typ) {
case DNS_T_CNAME:
case DNS_T_PTR:
case DNS_T_NS:
case DNS_T_MB:
case DNS_T_MD:
case DNS_T_MF:
case DNS_T_MG:
case DNS_T_MR:
if (dns_getdn(pkt, &dptr, end, dn, DNS_MAXDN) <= 0) goto xperr;
printf("%s.", dns_dntosp(dn));
break;
case DNS_T_A:
if (rr->dnsrr_dsz != 4) goto xperr;
printf("%d.%d.%d.%d", dptr[0], dptr[1], dptr[2], dptr[3]);
break;
case DNS_T_AAAA:
if (rr->dnsrr_dsz != 16) goto xperr;
printf("%s", dns_xntop(AF_INET6, dptr));
break;
case DNS_T_MX:
c = dptr + 2;
if (dns_getdn(pkt, &c, end, dn, DNS_MAXDN) <= 0 || c != dend) goto xperr;
printf("%d %s.", dns_get16(dptr), dns_dntosp(dn));
break;
case DNS_T_TXT:
/* first verify it */
for(c = dptr; c < dend; c += n) {
n = *c++;
if (c + n > dend) goto xperr;
}
c = dptr; n = 0;
while (c < dend) {
if (verbose > 0) printf(n++ ? "\" \"":"\"");
c = printtxt(c);
}
if (verbose > 0) putchar('"');
break;
case DNS_T_HINFO: /* CPU, OS */
c = dptr;
n = *c++; if ((c += n) >= dend) goto xperr;
n = *c++; if ((c += n) != dend) goto xperr;
c = dptr;
if (verbose > 0) putchar('"');
c = printtxt(c);
if (verbose > 0) printf("\" \""); else putchar(' ');
printtxt(c);
if (verbose > 0) putchar('"');
break;
case DNS_T_WKS:
c = dptr;
if (dptr + 4 + 2 >= end) goto xperr;
printf("%s %d", dns_xntop(AF_INET, dptr), dptr[4]);
c = dptr + 5;
for (n = 0; c < dend; ++c, n += 8) {
if (*c) {
unsigned b;
for (b = 0; b < 8; ++b)
if (*c & (1 << (7-b))) printf(" %d", n + b);
}
}
break;
case DNS_T_SRV: /* prio weight port targetDN */
c = dptr;
c += 2 + 2 + 2;
if (dns_getdn(pkt, &c, end, dn, DNS_MAXDN) <= 0 || c != dend) goto xperr;
c = dptr;
printf("%d %d %d %s.",
dns_get16(c+0), dns_get16(c+2), dns_get16(c+4),
dns_dntosp(dn));
break;
case DNS_T_NAPTR: /* order pref flags serv regexp repl */
c = dptr;
c += 4; /* order, pref */
for (n = 0; n < 3; ++n)
if (c >= dend) goto xperr;
else c += *c + 1;
if (dns_getdn(pkt, &c, end, dn, DNS_MAXDN) <= 0 || c != dend) goto xperr;
c = dptr;
printf("%u %u", dns_get16(c+0), dns_get16(c+2));
c += 4;
for(n = 0; n < 3; ++n) {
putchar(' ');
if (verbose > 0) putchar('"');
c = printtxt(c);
if (verbose > 0) putchar('"');
}
printf(" %s.", dns_dntosp(dn));
break;
case DNS_T_KEY:
case DNS_T_DNSKEY:
/* flags(2) proto(1) algo(1) pubkey */
case DNS_T_DS:
case DNS_T_DLV:
/* ktag(2) proto(1) algo(1) pubkey */
c = dptr;
if (c + 2 + 1 + 1 > dend) goto xperr;
printf("%d %d %d", dns_get16(c), c[2], c[3]);
c += 2 + 1 + 1;
if (c < dend) {
putchar(' ');
printb64(c, dend);
}
break;
case DNS_T_SIG:
case DNS_T_RRSIG:
/* type(2) algo(1) labels(1) ottl(4) sexp(4) sinc(4) tag(2) sdn sig */
c = dptr;
c += 2 + 1 + 1 + 4 + 4 + 4 + 2;
if (dns_getdn(pkt, &c, end, dn, DNS_MAXDN) <= 0) goto xperr;
printf("%s %u %u %u ",
dns_typename(dns_get16(dptr)), dptr[2], dptr[3], dns_get32(dptr+4));
printdate(dns_get32(dptr+8));
putchar(' ');
printdate(dns_get32(dptr+12));
printf(" %d %s. ", dns_get16(dptr+10), dns_dntosp(dn));
printb64(c, dend);
break;
case DNS_T_SSHFP: /* algo(1), fp type(1), fp... */
if (dend < dptr + 3) goto xperr;
printf("%u %u ", dptr[0], dptr[1]); /* algo, fp type */
printhex(dptr + 2, dend);
break;
#if 0 /* unused RR types? */
case DNS_T_NSEC: /* nextDN bitmaps */
c = dptr;
if (dns_getdn(pkt, &c, end, dn, DNS_MAXDN) <= 0) goto xperr;
printf("%s.", dns_dntosp(dn));
unfinished.
break;
#endif
case DNS_T_SOA:
c = dptr;
if (dns_getdn(pkt, &c, end, dn, DNS_MAXDN) <= 0 ||
dns_getdn(pkt, &c, end, dn, DNS_MAXDN) <= 0 ||
c + 4*5 != dend)
goto xperr;
dns_getdn(pkt, &dptr, end, dn, DNS_MAXDN);
printf("%s. ", dns_dntosp(dn));
dns_getdn(pkt, &dptr, end, dn, DNS_MAXDN);
printf("%s. ", dns_dntosp(dn));
printf("%u %u %u %u %u",
dns_get32(dptr), dns_get32(dptr+4), dns_get32(dptr+8),
dns_get32(dptr+12), dns_get32(dptr+16));
break;
case DNS_T_MINFO:
c = dptr;
if (dns_getdn(pkt, &c, end, dn, DNS_MAXDN) <= 0 ||
dns_getdn(pkt, &c, end, dn, DNS_MAXDN) <= 0 ||
c != dend)
goto xperr;
dns_getdn(pkt, &dptr, end, dn, DNS_MAXDN);
printf("%s. ", dns_dntosp(dn));
dns_getdn(pkt, &dptr, end, dn, DNS_MAXDN);
printf("%s.", dns_dntosp(dn));
break;
case DNS_T_NULL:
default:
printhex(dptr, dend);
break;
}
putchar('\n');
return;
xperr:
printf("<parse error>\n");
++errors;
}
static int
printsection(struct dns_parse *p, int nrr, const char *sname) {
struct dns_rr rr;
int r;
if (!nrr) return 0;
if (verbose > 1) printf("\n;; %s section (%d):\n", sname, nrr);
p->dnsp_rrl = nrr;
while((r = dns_nextrr(p, &rr)) > 0)
printrr(p, &rr);
if (r < 0) printf("<<ERROR>>\n");
return r;
}
/* dbgcb will only be called if verbose > 1 */
static void
dbgcb(int code, const struct sockaddr *sa, unsigned slen,
const unsigned char *pkt, int r,
const struct dns_query *unused_q, void *unused_data) {
struct dns_parse p;
const unsigned char *cur, *end;
int numqd;
if (code > 0) {
printf(";; trying %s.\n", dns_dntosp(dns_payload(pkt)));
printf(";; sending %d bytes query to ", r);
}
else
printf(";; received %d bytes response from ", r);
if (sa->sa_family == AF_INET && slen >= sizeof(struct sockaddr_in))
printf("%s port %d\n",
dns_xntop(AF_INET, &((struct sockaddr_in*)sa)->sin_addr),
htons(((struct sockaddr_in*)sa)->sin_port));
#ifdef HAVE_IPv6
else if (sa->sa_family == AF_INET6 && slen >= sizeof(struct sockaddr_in6))
printf("%s port %d\n",
dns_xntop(AF_INET6, &((struct sockaddr_in6*)sa)->sin6_addr),
htons(((struct sockaddr_in6*)sa)->sin6_port));
#endif
else
printf("<<unknown socket type %d>>\n", sa->sa_family);
if (code > 0 && verbose < 3) {
putchar('\n');
return;
}
if (code == -2) printf(";; reply from unexpected source\n");
if (code == -5) printf(";; reply to a query we didn't sent (or old)\n");
if (r < DNS_HSIZE) {
printf(";; short packet (%d bytes)\n", r);
return;
}
if (dns_opcode(pkt) != 0)
printf(";; unexpected opcode %d\n", dns_opcode(pkt));
if (dns_tc(pkt) != 0)
printf(";; warning: TC bit set, probably incomplete reply\n");
printf(";; ->>HEADER<<- opcode: ");
switch(dns_opcode(pkt)) {
case 0: printf("QUERY"); break;
case 1: printf("IQUERY"); break;
case 2: printf("STATUS"); break;
default: printf("UNKNOWN(%u)", dns_opcode(pkt)); break;
}
printf(", status: %s, id: %d, size: %d\n;; flags:",
dns_rcodename(dns_rcode(pkt)), dns_qid(pkt), r);
if (dns_qr(pkt)) printf(" qr");
if (dns_aa(pkt)) printf(" aa");
if (dns_tc(pkt)) printf(" tc");
if (dns_rd(pkt)) printf(" rd");
if (dns_ra(pkt)) printf(" ra");
/* if (dns_z(pkt)) printf(" z"); only one reserved bit left */
if (dns_ad(pkt)) printf(" ad");
if (dns_cd(pkt)) printf(" cd");
numqd = dns_numqd(pkt);
printf("; QUERY: %d, ANSWER: %d, AUTHORITY: %d, ADDITIONAL: %d\n",
numqd, dns_numan(pkt), dns_numns(pkt), dns_numar(pkt));
if (numqd != 1)
printf(";; unexpected number of entries in QUERY section: %d\n",
numqd);
printf("\n;; QUERY SECTION (%d):\n", numqd);
cur = dns_payload(pkt);
end = pkt + r;
while(numqd--) {
if (dns_getdn(pkt, &cur, end, p.dnsp_dnbuf, DNS_MAXDN) <= 0 ||
cur + 4 > end) {
printf("; invalid query section\n");
return;
}
r = printf(";%s.", dns_dntosp(p.dnsp_dnbuf));
printf("%s%s\t%s\n",
r > 23 ? "\t" : r > 15 ? "\t\t" : r > 7 ? "\t\t\t" : "\t\t\t\t",
dns_classname(dns_get16(cur+2)), dns_typename(dns_get16(cur)));
cur += 4;
}
p.dnsp_pkt = pkt;
p.dnsp_cur = p.dnsp_ans = cur;
p.dnsp_end = end;
p.dnsp_qdn = NULL;
p.dnsp_qcls = p.dnsp_qtyp = 0;
p.dnsp_ttl = 0xffffffffu;
p.dnsp_nrr = 0;
r = printsection(&p, dns_numan(pkt), "ANSWER");
if (r == 0)
r = printsection(&p, dns_numns(pkt), "AUTHORITY");
if (r == 0)
r = printsection(&p, dns_numar(pkt), "ADDITIONAL");
putchar('\n');
}
static void dnscb(struct dns_ctx *ctx, void *result, void *data) {
int r = dns_status(ctx);
struct query *q = data;
struct dns_parse p;
struct dns_rr rr;
unsigned nrr;
unsigned char dn[DNS_MAXDN];
const unsigned char *pkt, *cur, *end;
if (!result) {
dnserror(q, r);
return;
}
pkt = result; end = pkt + r; cur = dns_payload(pkt);
dns_getdn(pkt, &cur, end, dn, sizeof(dn));
dns_initparse(&p, NULL, pkt, cur, end);
p.dnsp_qcls = p.dnsp_qtyp = 0;
nrr = 0;
while((r = dns_nextrr(&p, &rr)) > 0) {
if (!dns_dnequal(dn, rr.dnsrr_dn)) continue;
if ((qcls == DNS_C_ANY || qcls == rr.dnsrr_cls) &&
(q->qtyp == DNS_T_ANY || q->qtyp == rr.dnsrr_typ))
++nrr;
else if (rr.dnsrr_typ == DNS_T_CNAME && !nrr) {
if (dns_getdn(pkt, &rr.dnsrr_dptr, end,
p.dnsp_dnbuf, sizeof(p.dnsp_dnbuf)) <= 0 ||
rr.dnsrr_dptr != rr.dnsrr_dend) {
r = DNS_E_PROTOCOL;
break;
}
else {
if (verbose == 1) {
printf("%s.", dns_dntosp(dn));
printf(" CNAME %s.\n", dns_dntosp(p.dnsp_dnbuf));
}
dns_dntodn(p.dnsp_dnbuf, dn, sizeof(dn));
}
}
}
if (!r && !nrr)
r = DNS_E_NODATA;
if (r < 0) {
dnserror(q, r);
free(result);
return;
}
if (verbose < 2) { /* else it is already printed by dbgfn */
dns_rewind(&p, NULL);
p.dnsp_qtyp = q->qtyp == DNS_T_ANY ? 0 : q->qtyp;
p.dnsp_qcls = qcls == DNS_C_ANY ? 0 : qcls;
while(dns_nextrr(&p, &rr))
printrr(&p, &rr);
}
free(result);
query_free(q);
}
int main(int argc, char **argv) {
int i;
int fd;
fd_set fds;
struct timeval tv;
time_t now;
char *ns[DNS_MAXSERV];
int nns = 0;
struct query *q;
enum dns_type qtyp = 0;
struct dns_ctx *nctx = NULL;
int flags = 0;
if (!(progname = strrchr(argv[0], '/'))) progname = argv[0];
else argv[0] = ++progname;
if (argc <= 1)
die(0, "try `%s -h' for help", progname);
if (dns_init(NULL, 0) < 0 || !(nctx = dns_new(NULL)))
die(errno, "unable to initialize dns library");
/* we keep two dns contexts: one may be needed to resolve
* nameservers if given as names, using default options.
*/
while((i = getopt(argc, argv, "vqt:c:an:o:f:h")) != EOF) switch(i) {
case 'v': ++verbose; break;
case 'q': --verbose; break;
case 't':
if (optarg[0] == '*' && !optarg[1])
i = DNS_T_ANY;
else if ((i = dns_findtypename(optarg)) <= 0)
die(0, "unrecognized query type `%s'", optarg);
qtyp = i;
break;
case 'c':
if (optarg[0] == '*' && !optarg[1])
i = DNS_C_ANY;
else if ((i = dns_findclassname(optarg)) < 0)
die(0, "unrecognized query class `%s'", optarg);
qcls = i;
break;
case 'a':
qtyp = DNS_T_ANY;
++verbose;
break;
case 'n':
if (nns >= DNS_MAXSERV)
die(0, "too many nameservers, %d max", DNS_MAXSERV);
ns[nns++] = optarg;
break;
case 'o':
case 'f': {
char *opt;
const char *const delim = " \t,;";
for(opt = strtok(optarg, delim); opt != NULL; opt = strtok(NULL, delim)) {
if (dns_set_opts(NULL, optarg) == 0)
;
else if (strcmp(opt, "aa") == 0) flags |= DNS_AAONLY;
else if (strcmp(optarg, "nord") == 0) flags |= DNS_NORD;
else if (strcmp(optarg, "dnssec") == 0) flags |= DNS_SET_DO;
else if (strcmp(optarg, "do") == 0) flags |= DNS_SET_DO;
else if (strcmp(optarg, "cd") == 0) flags |= DNS_SET_CD;
else
die(0, "invalid option: `%s'", opt);
}
break;
}
case 'h':
printf(
"%s: simple DNS query tool (using udns version %s)\n"
"Usage: %s [options] domain-name...\n"
"where options are:\n"
" -h - print this help and exit\n"
" -v - be more verbose\n"
" -q - be less verbose\n"
" -t type - set query type (A, AAA, PTR etc)\n"
" -c class - set query class (IN (default), CH, HS, *)\n"
" -a - equivalent to -t ANY -v\n"
" -n ns - use given nameserver(s) instead of default\n"
" (may be specified multiple times)\n"
" -o opt,opt,... (comma- or space-separated list,\n"
" may be specified more than once):\n"
" set resovler options (the same as setting $RES_OPTIONS):\n"
" timeout:sec - initial query timeout\n"
" attempts:num - number of attempt to resovle a query\n"
" ndots:num - if name has more than num dots, lookup it before search\n"
" port:num - port number for queries instead of default 53\n"
" udpbuf:num - size of UDP buffer (use EDNS0 if >512)\n"
" or query flags:\n"
" aa,nord,dnssec,do,cd - set query flag (auth-only, no recursion,\n"
" enable DNSSEC (DNSSEC Ok), check disabled)\n"
, progname, dns_version(), progname);
return 0;
default:
die(0, "try `%s -h' for help", progname);
}
argc -= optind; argv += optind;
if (!argc)
die(0, "no name(s) to query specified");
if (nns) {
/* if nameservers given as names, resolve them.
* We only allow IPv4 nameservers as names for now.
* Ok, it is easy enouth to try both AAAA and A,
* but the question is what to do by default.
*/
struct sockaddr_in sin;
int j, r = 0, opened = 0;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(dns_set_opt(NULL, DNS_OPT_PORT, -1));
dns_add_serv(NULL, NULL);
for(i = 0; i < nns; ++i) {
if (dns_pton(AF_INET, ns[i], &sin.sin_addr) <= 0) {
struct dns_rr_a4 *rr;
if (!opened) {
if (dns_open(nctx) < 0)
die(errno, "unable to initialize dns context");
opened = 1;
}
rr = dns_resolve_a4(nctx, ns[i], 0);
if (!rr)
die(0, "unable to resolve nameserver %s: %s",
ns[i], dns_strerror(dns_status(nctx)));
for(j = 0; j < rr->dnsa4_nrr; ++j) {
sin.sin_addr = rr->dnsa4_addr[j];
if ((r = dns_add_serv_s(NULL, (struct sockaddr *)&sin)) < 0)
break;
}
free(rr);
}
else
r = dns_add_serv_s(NULL, (struct sockaddr *)&sin);
if (r < 0)
die(errno, "unable to add nameserver %s",
dns_xntop(AF_INET, &sin.sin_addr));
}
}
dns_free(nctx);
fd = dns_open(NULL);
if (fd < 0)
die(errno, "unable to initialize dns context");
if (verbose > 1)
dns_set_dbgfn(NULL, dbgcb);
if (flags)
dns_set_opt(NULL, DNS_OPT_FLAGS, flags);
for (i = 0; i < argc; ++i) {
char *name = argv[i];
union {
struct in_addr addr;
struct in6_addr addr6;
} a;
unsigned char dn[DNS_MAXDN];
enum dns_type l_qtyp = 0;
int abs;
if (dns_pton(AF_INET, name, &a.addr) > 0) {
dns_a4todn(&a.addr, 0, dn, sizeof(dn));
l_qtyp = DNS_T_PTR;
abs = 1;
}
#ifdef HAVE_IPv6
else if (dns_pton(AF_INET6, name, &a.addr6) > 0) {
dns_a6todn(&a.addr6, 0, dn, sizeof(dn));
l_qtyp = DNS_T_PTR;
abs = 1;
}
#endif
else if (!dns_ptodn(name, strlen(name), dn, sizeof(dn), &abs))
die(0, "invalid name `%s'\n", name);
else
l_qtyp = DNS_T_A;
if (qtyp) l_qtyp = qtyp;
q = query_new(name, dn, l_qtyp);
if (abs) abs = DNS_NOSRCH;
if (!dns_submit_dn(NULL, dn, qcls, l_qtyp, abs, 0, dnscb, q))
dnserror(q, dns_status(NULL));
}
FD_ZERO(&fds);
now = 0;
while((i = dns_timeouts(NULL, -1, now)) > 0) {
FD_SET(fd, &fds);
tv.tv_sec = i;
tv.tv_usec = 0;
i = select(fd+1, &fds, 0, 0, &tv);
now = time(NULL);
if (i > 0) dns_ioevent(NULL, now);
}
return errors ? 1 : notfound ? 100 : 0;
}
|
281677160/openwrt-package | 7,962 | luci-app-ssr-plus/shadowsocksr-libev/src/doc/shadowsocks-libev.asciidoc | shadowsocks-libev(8)
====================
NAME
----
shadowsocks-libev - a lightweight and secure socks5 proxy
SYNOPSIS
--------
*ss-local*|*ss-redir*|*ss-server*|*ss-tunnel*|*ss-manager*
[-s <server_host>] [-p <server_port>] [-l <local_port>] [-k <password>]
[-m <encrypt_method>] [-f <pid_file>] [-t <timeout>] [-c <config_file>]
DESCRIPTION
-----------
*Shadowsocks-libev* is a lightweight and secure socks5 proxy.
It is a port of the original shadowsocks created by clowwindy.
*Shadowsocks-libev* is written in pure C and takes advantage of *libev*
to achieve both high performance and low resource consumption.
*Shadowsocks-libev* consists of five components. One is `ss-server`(1)
that runs on a remote server to provide secured tunnel service.
`ss-local`(1) and `ss-redir`(1) are clients on your local machines to proxy
traffic(TCP/UDP or both).
`ss-tunnel`(1) is a tool for local port forwarding.
While `ss-local`(1) works as a standard socks5 proxy, `ss-redir`(1) works
as a transparent proxy and requires netfilter's NAT module. For more
information, check out the 'EXAMPLE' section.
`ss-manager`(1) is a controller for multi-user management and traffic
statistics, using UNIX domain socket to talk with `ss-server`(1).
Also, it provides a UNIX domain socket or IP based API for other software.
About the details of this API, please refer to the 'PROTOCOL' section.
OPTIONS
-------
-s <server_host>::
Set the server's hostname or IP.
-l <local_port>::
Set the local port number.
+
Not available in server nor manager mode.
-k <password>::
Set the password. The server and the client should use the same password.
-m <encrypt_method>::
Set the cipher.
+
*Shadowsocks-libev* accepts 21 different ciphers:
+
table, rc4, rc4-md5, aes-128-cfb, aes-192-cfb, aes-256-cfb,
aes-128-ctr, aes-192-ctr, aes-256-ctr, bf-cfb,
camellia-128-cfb, camellia-192-cfb, camellia-256-cfb, cast5-cfb, des-cfb,
idea-cfb, rc2-cfb, seed-cfb, salsa20, chacha20 and chacha20-ietf.
+
The default cipher is 'rc4-md5'.
+
If built with PolarSSL or custom OpenSSL libraries, some of
these ciphers may not work.
-a <user_name>::
Run as a specific user.
-f <pid_file>::
Start shadowsocks as a daemon with specific pid file.
-t <timeout>::
Set the socket timeout in seconds. The default value is 60.
-c <config_file>::
Use a configuration file.
-n <number>::
Specify max number of open files.
+
Not available in manager mode.
+
Only available on Linux.
-i <interface>::
Send traffic through specific network interface.
+
For example, there are three interfaces in your device, which is
lo (127.0.0.1), eth0 (192.168.0.1) and eth1 (192.168.0.2).
Meanwhile, you configure *shadowsocks-libev* to listen on 0.0.0.0:8388
and bind to eth1. That results the traffic go out through eth1,
but not lo nor eth0. This option is useful to control traffic in
multi-interface environment.
+
Not available in redir mode.
-b <local_address>::
Specify local address to bind.
+
Not available in server nor manager mode.
-u::
Enable UDP relay.
+
TPROXY is required in redir mode. You may need root permission.
-U::
Enable UDP relay and disable TCP relay.
+
Not available in local mode.
-A::
Enable onetime authentication.
-L <addr:port>::
Specify destination server address and port for local port forwarding.
+
Only available in tunnel mode.
-d <addr>::
Setup name servers for internal DNS resolver (libudns).
The default server is fetched from /etc/resolv.conf.
+
Only available in server and manager mode.
--fast-open::
Enable TCP fast open.
+
Not available in redir nor tunnel mode, with Linux kernel > 3.7.0.
--acl <acl_config>::
Enable ACL (Access Control List) and specify config file.
+
Not available in redir nor tunnel mode.
--manager-address <path_to_unix_domain>::
Specify UNIX domain socket address.
+
Only available in server and manager mode.
--executable <path_to_server_executable>::
Specify the executable path of `ss-server`.
+
Only available in manager mode.
-v::
Enable verbose mode.
-h|--help::
Print help message.
CONFIG FILE
-----------
The config file is written in JSON and easy to edit.
The config file equivalent of command line options is listed as example below.
[frame="topbot",options="header"]
|==========================================================================
| Command line | JSON
| -s some.server.net | "server": "some.server.net"
| -s some.server.net -p 1234 (client) | "server": "some.server.net:1234"
| -p 1234 -k "PasSworD" (server) | "port_password": {"1234":"PasSworD"}
| -p 1234 | "server_port": "1234"
| -b 0.0.0.0 | "local_address": "0.0.0.0"
| -l 4321 | "local_port": "4321"
| -k "PasSworD" | "password": "PasSworD"
| -m "aes-256-cfb" | "method": "aes-256-cfb"
| -t 60 | "timeout": 60
| -a nobody | "user": "nobody"
| --fast-open | "fast_open": true
| -6 | "ipv6_first": true
| -A | "auth": true
| -n "/etc/nofile" | "nofile": "/etc/nofile"
| -d "8.8.8.8" | "nameserver": "8.8.8.8"
| -L "somedns.net:53" | "tunnel_address": "somedns.net:53"
| -u | "mode": "tcp_and_udp"
| -U | "mode": "udp_only"
| no "-u" nor "-U" options (default) | "mode": "tcp_only"
|============================================================================
EXAMPLE
-------
`ss-redir` requires netfilter's NAT function. Here is an example:
....
# Create new chain
root@Wrt:~# iptables -t nat -N SHADOWSOCKS
root@Wrt:~# iptables -t mangle -N SHADOWSOCKS
# Ignore your shadowsocks server's addresses
# It's very IMPORTANT, just be careful.
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 123.123.123.123 -j RETURN
# Ignore LANs and any other addresses you'd like to bypass the proxy
# See Wikipedia and RFC5735 for full list of reserved networks.
# See ashi009/bestroutetb for a highly optimized CHN route list.
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 0.0.0.0/8 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 10.0.0.0/8 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 127.0.0.0/8 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 169.254.0.0/16 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 172.16.0.0/12 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 192.168.0.0/16 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 224.0.0.0/4 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 240.0.0.0/4 -j RETURN
# Anything else should be redirected to shadowsocks's local port
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -p tcp -j REDIRECT --to-ports 12345
# Add any UDP rules
root@Wrt:~# ip rule add fwmark 0x01/0x01 table 100
root@Wrt:~# ip route add local 0.0.0.0/0 dev lo table 100
root@Wrt:~# iptables -t mangle -A SHADOWSOCKS -p udp --dport 53 -j TPROXY --on-port 12345 --tproxy-mark 0x01/0x01
# Apply the rules
root@Wrt:~# iptables -t nat -A PREROUTING -p tcp -j SHADOWSOCKS
root@Wrt:~# iptables -t mangle -A PREROUTING -j SHADOWSOCKS
# Start the shadowsocks-redir
root@Wrt:~# ss-redir -u -c /etc/config/shadowsocks.json -f /var/run/shadowsocks.pid
....
PROTOCOL
--------
`ss-manager`(1) provides several APIs through UDP protocol::
Send UDP commands in the following format to the manager-address provided to ss-manager(1): ::::
command: [JSON data]
To add a port: ::::
add: {"server_port": 8001, "password":"7cd308cc059"}
To remove a port: ::::
remove: {"server_port": 8001}
To receive a pong: ::::
ping
Then `ss-manager`(1) will send back the traffic statistics: ::::
stat: {"8001":11370}
SEE ALSO
--------
`ss-local`(1),
`ss-server`(1),
`ss-tunnel`(1),
`ss-redir`(1),
`ss-manager`(1),
`iptables`(8),
/etc/shadowsocks-libev/config.json
|
281677160/openwrt-package | 2,061 | luci-app-ssr-plus/shadowsocksr-libev/src/doc/ss-nat.asciidoc | ss-nat(1)
=========
NAME
----
ss-nat - helper script to setup NAT rules for transparent proxy
SYNOPSIS
--------
*ss-nat*
[-ouUfh]
[-s <server_ip>] [-S <server_ip>] [-l <local_port>]
[-L <local_port>] [-i <ip_list_file>] [-a <lan_ips>]
[-b <wan_ips>] [-w <wan_ips>] [-e <extra_options>]
DESCRIPTION
-----------
*Shadowsocks-libev* is a lightweight and secure socks5 proxy.
It is a port of the original shadowsocks created by clowwindy.
*Shadowsocks-libev* is written in pure C and takes advantage of libev to
achieve both high performance and low resource consumption.
`ss-nat`(1) sets up NAT rules for `ss-redir`(1) to provide traffic redirection.
It requires netfilter's NAT module and `iptables`(8).
For more information, check out `shadowsocks-libev`(8) and the following
'EXAMPLE' section.
OPTIONS
-------
-s <server_ip>::
IP address of shadowsocks remote server
-l <local_port>::
Port number of shadowsocks local server
-S <server_ip>::
IP address of shadowsocks remote UDP server
-L <local_port>::
Port number of shadowsocks local UDP server
-i <ip_list_file>::
a file whose content is bypassed ip list
-a <lan_ips>::
LAN IP of access control, need a prefix to define access control mode
-b <wan_ips>::
WAN IP of will be bypassed
-w <wan_ips>::
WAN IP of will be forwarded
-e <extra_options>::
Extra options for iptables
-o::
Apply the rules to the OUTPUT chain
-u::
Enable udprelay mode, TPROXY is required
-U::
Enable udprelay mode, using different IP and ports for TCP and UDP
-f::
Flush the rules
-h::
Show this help message and exit
EXAMPLE
-------
`ss-nat` requires `iptables`(8). Here is an example:
....
# Enable NAT rules for shadowsocks,
# with both TCP and UDP redirection enabled,
# and applied for both PREROUTING and OUTPUT chains
root@Wrt:~# ss-nat -s 192.168.1.100 -l 1080 -u -o
# Disable and flush all NAT rules for shadowsocks
root@Wrt:~# ss-nat -f
....
SEE ALSO
--------
`ss-local`(1),
`ss-server`(1),
`ss-tunnel`(1),
`ss-manager`(1),
`shadowsocks-libev`(8),
`iptables`(8),
/etc/shadowsocks-libev/config.json
|
281677160/openwrt-package | 3,354 | luci-app-ssr-plus/shadowsocksr-libev/src/doc/ss-local.asciidoc | ss-local(1)
===========
NAME
----
ss-local - shadowsocks client as socks5 proxy, libev port
SYNOPSIS
--------
*ss-local*
[-Auv6] [-h|--help]
[-s <server_host>] [-p <server_port>] [-l <local_port>]
[-k <password>] [-m <encrypt_method>] [-f <pid_file>]
[-t <timeout>] [-c <config_file>] [-i <interface>]
[-a <user_name>] [-b <local_address] [-n <nofile>]
[--fast-open] [--acl <acl_config>] [--mtu <MTU>]
DESCRIPTION
-----------
*Shadowsocks-libev* is a lightweight and secure socks5 proxy.
It is a port of the original shadowsocks created by clowwindy.
*Shadowsocks-libev* is written in pure C and takes advantage of libev to
achieve both high performance and low resource consumption.
*Shadowsocks-libev* consists of five components. `ss-local`(1) works as a standard
socks5 proxy on local machines to proxy TCP traffic.
For more information, check out `shadowsocks-libev`(8).
OPTIONS
-------
-s <server_host>::
Set the server's hostname or IP.
-p <server_port>::
Set the server's port number.
-l <local_port>::
Set the local port number.
-k <password>::
Set the password. The server and the client should use the same password.
-m <encrypt_method>::
Set the cipher.
+
*Shadowsocks-libev* accepts 21 different ciphers:
+
table, rc4, rc4-md5, aes-128-cfb, aes-192-cfb, aes-256-cfb,
aes-128-ctr, aes-192-ctr, aes-256-ctr, bf-cfb,
camellia-128-cfb, camellia-192-cfb, camellia-256-cfb, cast5-cfb, des-cfb,
idea-cfb, rc2-cfb, seed-cfb, salsa20, chacha20 and chacha20-ietf.
+
The default cipher is 'rc4-md5'.
+
If built with PolarSSL or custom OpenSSL libraries, some of
these ciphers may not work.
-a <user_name>::
Run as a specific user.
-f <pid_file>::
Start shadowsocks as a daemon with specific pid file.
-t <timeout>::
Set the socket timeout in seconds. The default value is 60.
-c <config_file>::
Use a configuration file.
+
Refer to `shadowsocks-libev`(8) 'CONFIG FILE' section for more details.
-n <number>::
Specify max number of open files.
+
Only available on Linux.
-i <interface>::
Send traffic through specific network interface.
+
For example, there are three interfaces in your device,
which is lo (127.0.0.1), eth0 (192.168.0.1) and eth1 (192.168.0.2).
Meanwhile, you configure `ss-local` to listen on 0.0.0.0:8388 and bind to eth1.
That results the traffic go out through eth1, but not lo nor eth0.
This option is useful to control traffic in multi-interface environment.
-b <local_address>::
Specify local address to bind.
-u::
Enable UDP relay.
-U::
Enable UDP relay and disable TCP relay.
-A::
Enable onetime authentication.
-6::
Resovle hostname to IPv6 address first.
--fast-open::
Enable TCP fast open.
+
Only available with Linux kernel > 3.7.0.
--acl <acl_config>::
Enable ACL (Access Control List) and specify config file.
--mtu <MTU>::
Specify the MTU of your network interface.
--mptcp::
Enable Multipath TCP.
+
Only available with MPTCP enabled Linux kernel.
-v::
Enable verbose mode.
-h|--help::
Print help message.
EXAMPLE
-------
`ss-local`(1) can be started from command line and run in foreground.
Here is an example:
....
# Start ss-local with given parameters
ss-local -s example.com -p 12345 -l 1080 -k foobar -m aes-256-cfb
....
SEE ALSO
--------
`ss-server`(1),
`ss-tunnel`(1),
`ss-redir`(1),
`ss-manager`(1),
`shadowsocks-libev`(8),
`iptables`(8),
/etc/shadowsocks-libev/config.json
|
281677160/openwrt-package | 4,146 | luci-app-ssr-plus/shadowsocksr-libev/src/doc/ss-server.asciidoc | ss-server(1)
============
NAME
----
ss-server - shadowsocks server, libev port
SYNOPSIS
--------
*ss-server*
[-AuUv] [-h|--help]
[-s <server_host>] [-p <server_port>] [-l <local_port>]
[-k <password>] [-m <encrypt_method>] [-f <pid_file>]
[-t <timeout>] [-c <config_file>] [-i <interface>]
[-a <user_name>] [-d <addr>] [-n <nofile>]
[-b <local_address] [--fast-open] [--mptcp]
[--firewall] [--acl <acl_config>] [--mtu <MTU>]
[--manager-address <path_to_unix_domain>]
DESCRIPTION
-----------
*Shadowsocks-libev* is a lightweight and secure socks5 proxy.
It is a port of the original shadowsocks created by clowwindy.
*Shadowsocks-libev* is written in pure C and takes advantage of libev to
achieve both high performance and low resource consumption.
*Shadowsocks-libev* consists of five components.
`ss-server`(1) runs on a remote server to provide secured tunnel service.
For more information, check out `shadowsocks-libev`(8).
OPTIONS
-------
-s <server_host>::
Set the server's hostname or IP.
-p <server_port>::
Set the server's port number.
-k <password>::
Set the password. The server and the client should use the same password.
-m <encrypt_method>::
Set the cipher.
+
*Shadowsocks-libev* accepts 21 different ciphers:
+
table, rc4, rc4-md5, aes-128-cfb, aes-192-cfb, aes-256-cfb,
aes-128-ctr, aes-192-ctr, aes-256-ctr, bf-cfb,
camellia-128-cfb, camellia-192-cfb, camellia-256-cfb, cast5-cfb, des-cfb,
idea-cfb, rc2-cfb, seed-cfb, salsa20, chacha20 and chacha20-ietf.
+
The default cipher is 'rc4-md5'.
+
If built with PolarSSL or custom OpenSSL libraries, some of
these ciphers may not work.
-a <user_name>::
Run as a specific user.
-f <pid_file>::
Start shadowsocks as a daemon with specific pid file.
-t <timeout>::
Set the socket timeout in seconds. The default value is 60.
-c <config_file>::
Use a configuration file.
+
Refer to `shadowsocks-libev`(8) 'CONFIG FILE' section for more details.
-n <number>::
Specify max number of open files.
+
Only available on Linux.
-i <interface>::
Send traffic through specific network interface.
+
For example, there are three interfaces in your device,
which is lo (127.0.0.1), eth0 (192.168.0.1) and eth1 (192.168.0.2).
Meanwhile, you configure `ss-server` to listen on 0.0.0.0:8388 and bind to eth1.
That results the traffic go out through eth1, but not lo nor eth0.
This option is useful to control traffic in multi-interface environment.
-b <local_address>::
Specify local address to bind.
-u::
Enable UDP relay.
-U::
Enable UDP relay and disable TCP relay.
-A::
Enable onetime authentication.
-6::
Resovle hostname to IPv6 address first.
-d <addr>::
Setup name servers for internal DNS resolver (libudns).
The default server is fetched from '/etc/resolv.conf'.
--fast-open::
Enable TCP fast open.
+
Only available with Linux kernel > 3.7.0.
--mptcp::
Enable Multipath TCP.
+
Only available with MPTCP enabled Linux kernel.
--firewall::
Setup firewall rules for auto blocking.
--acl <acl_config>::
Enable ACL (Access Control List) and specify config file.
--manager-address <path_to_unix_domain>::
Specify UNIX domain socket address for the communication between ss-manager(1) and ss-server(1).
+
Only available in server and manager mode.
--mtu <MTU>::
Specify the MTU of your network interface.
--mptcp::
Enable Multipath TCP.
+
Only available with MPTCP enabled Linux kernel.
-v::
Enable verbose mode.
-h|--help::
Print help message.
EXAMPLE
-------
It is recommended to use a config file when starting `ss-server`(1).
The config file is written in JSON and is easy to edit.
Check out the 'SEE ALSO' section for the default path of config file.
....
# Start the ss-server
ss-server -c /etc/shadowsocks-libev/config.json
....
INCOMPATIBILITY
---------------
The config file of `shadowsocks-libev`(8) is slightly different from original
shadowsocks.
In order to listen to both IPv4/IPv6 address, use the following grammar in
your config json file:
....
{
"server":["::0","0.0.0.0"],
...
}
....
SEE ALSO
--------
`ss-local`(1),
`ss-tunnel`(1),
`ss-redir`(1),
`ss-manager`(1),
`shadowsocks-libev`(8),
`iptables`(8),
/etc/shadowsocks-libev/config.json
|
281677160/openwrt-package | 4,351 | luci-app-ssr-plus/shadowsocksr-libev/src/doc/ss-redir.asciidoc | ss-redir(1)
===========
NAME
----
ss-redir - shadowsocks client as transparent proxy, libev port
SYNOPSIS
--------
*ss-redir*
[-AuUv6] [-h|--help]
[-s <server_host>] [-p <server_port>] [-l <local_port>]
[-k <password>] [-m <encrypt_method>] [-f <pid_file>]
[-t <timeout>] [-c <config_file>] [-b <local_address>]
[-a <user_name>] [-n <nofile>] [--mtu <MTU>]
DESCRIPTION
-----------
*Shadowsocks-libev* is a lightweight and secure socks5 proxy.
It is a port of the original shadowsocks created by clowwindy.
*Shadowsocks-libev* is written in pure C and takes advantage of libev to
achieve both high performance and low resource consumption.
*Shadowsocks-libev* consists of five components.
`ss-redir`(1) works as a transparent proxy on local machines to proxy TCP
traffic and requires netfilter's NAT module.
For more information, check out `shadowsocks-libev`(8) and the following
'EXAMPLE' section.
OPTIONS
-------
-s <server_host>::
Set the server's hostname or IP.
-p <server_port>::
Set the server's port number.
-l <local_port>::
Set the local port number.
-k <password>::
Set the password. The server and the client should use the same
password.
-m <encrypt_method>::
Set the cipher.
+
*Shadowsocks-libev* accepts 21 different ciphers:
+
table, rc4, rc4-md5, aes-128-cfb, aes-192-cfb, aes-256-cfb,
aes-128-ctr, aes-192-ctr, aes-256-ctr, bf-cfb,
camellia-128-cfb, camellia-192-cfb, camellia-256-cfb, cast5-cfb, des-cfb,
idea-cfb, rc2-cfb, seed-cfb, salsa20, chacha20 and chacha20-ietf.
+
The default cipher is 'rc4-md5'.
+
If built with PolarSSL or custom OpenSSL libraries, some of
these ciphers may not work.
-a <user_name>::
Run as a specific user.
-f <pid_file>::
Start shadowsocks as a daemon with specific pid file.
-t <timeout>::
Set the socket timeout in seconds. The default value is 60.
-c <config_file>::
Use a configuration file.
+
Refer to `shadowsocks-libev`(8) 'CONFIG FILE' section for more details.
-n <number>::
Specify max number of open files.
+
Only available on Linux.
-b <local_address>::
Specify local address to bind.
-u::
Enable UDP relay.
+
TPROXY is required in redir mode. You may need root permission.
-U::
Enable UDP relay and disable TCP relay.
-A::
Enable onetime authentication.
-6::
Resovle hostname to IPv6 address first.
--mtu <MTU>::
Specify the MTU of your network interface.
--mptcp::
Enable Multipath TCP.
+
Only available with MPTCP enabled Linux kernel.
-v::
Enable verbose mode.
-h|--help::
Print help message.
EXAMPLE
-------
ss-redir requires netfilter's NAT function. Here is an example:
....
# Create new chain
root@Wrt:~# iptables -t nat -N SHADOWSOCKS
# Ignore your shadowsocks server's addresses
# It's very IMPORTANT, just be careful.
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 123.123.123.123 -j RETURN
# Ignore LANs and any other addresses you'd like to bypass the proxy
# See Wikipedia and RFC5735 for full list of reserved networks.
# See ashi009/bestroutetb for a highly optimized CHN route list.
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 0.0.0.0/8 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 10.0.0.0/8 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 127.0.0.0/8 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 169.254.0.0/16 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 172.16.0.0/12 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 192.168.0.0/16 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 224.0.0.0/4 -j RETURN
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -d 240.0.0.0/4 -j RETURN
# Anything else should be redirected to shadowsocks's local port
root@Wrt:~# iptables -t nat -A SHADOWSOCKS -p tcp -j REDIRECT --to-ports 12345
# Add any UDP rules
root@Wrt:~# ip rule add fwmark 0x01/0x01 table 100
root@Wrt:~# ip route add local 0.0.0.0/0 dev lo table 100
root@Wrt:~# iptables -t mangle -A SHADOWSOCKS -p udp --dport 53 -j TPROXY --on-port 12345 --tproxy-mark 0x01/0x01
# Apply the rules
root@Wrt:~# iptables -t nat -A PREROUTING -p tcp -j SHADOWSOCKS
root@Wrt:~# iptables -t mangle -A PREROUTING -j SHADOWSOCKS
# Start the shadowsocks-redir
root@Wrt:~# ss-redir -u -c /etc/config/shadowsocks.json -f /var/run/shadowsocks.pid
....
SEE ALSO
--------
`ss-local`(1),
`ss-server`(1),
`ss-tunnel`(1),
`ss-manager`(1),
`shadowsocks-libev`(8),
`iptables`(8),
/etc/shadowsocks-libev/config.json
|
281677160/openwrt-package | 4,408 | luci-app-ssr-plus/shadowsocksr-libev/src/doc/ss-manager.asciidoc | ss-manager(1)
=============
NAME
----
ss-manager - ss-server controller for multi-user management and traffic statistics
SYNOPSIS
--------
*ss-manager*
[-AuUv] [-h|--help]
[-s <server_host>] [-p <server_port>] [-l <local_port>]
[-k <password>] [-m <encrypt_method>] [-f <pid_file>]
[-t <timeout>] [-c <config_file>] [-i <interface>]
[-b <local_addr>] [-a <user_name>]
[--manager-address <path_to_unix_domain>]
[--executable <path_to_server_executable>]
DESCRIPTION
-----------
*Shadowsocks-libev* is a lightweight and secure socks5 proxy.
It is a port of the original shadowsocks created by clowwindy.
*Shadowsocks-libev* is written in pure C and takes advantage of libev to
achieve both high performance and low resource consumption.
*Shadowsocks-libev* consists of five components.
`ss-manager`(1) is a controller for multi-user management and
traffic statistics, using UNIX domain socket to talk with `ss-server`(1).
Also, it provides a UNIX domain socket or IP based API for other software.
About the details of this API, please refer to the following 'PROTOCOL'
section.
OPTIONS
-------
-s <server_host>::
Set the server's hostname or IP.
-k <password>::
Set the password. The server and the client should use the same password.
-m <encrypt_method>::
Set the cipher.
+
*Shadowsocks-libev* accepts 21 different ciphers:
+
table, rc4, rc4-md5, aes-128-cfb, aes-192-cfb, aes-256-cfb,
aes-128-ctr, aes-192-ctr, aes-256-ctr, bf-cfb,
camellia-128-cfb, camellia-192-cfb, camellia-256-cfb, cast5-cfb, des-cfb,
idea-cfb, rc2-cfb, seed-cfb, salsa20, chacha20 and chacha20-ietf.
+
The default cipher is 'rc4-md5'.
+
If built with PolarSSL or custom OpenSSL libraries, some of
these ciphers may not work.
-a <user_name>::
Run as a specific user.
-f <pid_file>::
Start shadowsocks as a daemon with specific pid file.
-t <timeout>::
Set the socket timeout in seconds. The default value is 60.
-c <config_file>::
Use a configuration file.
-i <interface>::
Send traffic through specific network interface.
+
For example, there are three interfaces in your device,
which is lo (127.0.0.1), eth0 (192.168.0.1) and eth1 (192.168.0.2).
Meanwhile, you configure `ss-local` to listen on 0.0.0.0:8388 and bind to eth1.
That results the traffic go out through eth1, but not lo nor eth0.
This option is useful to control traffic in multi-interface environment.
-u::
Enable UDP relay.
-U::
Enable UDP relay and disable TCP relay.
-A::
Enable onetime authentication.
-d <addr>::
Setup name servers for internal DNS resolver (libudns).
The default server is fetched from `/etc/resolv.conf`.
--fast-open::
Enable TCP fast open.
+
Only available with Linux kernel > 3.7.0.
--acl <acl_config>::
Enable ACL (Access Control List) and specify config file.
--manager-address <path_to_unix_domain>::
Specify UNIX domain socket address for the communication between ss-manager(1) and ss-server(1).
+
Only available in server and manager mode.
--executable <path_to_server_executable>::
Specify the executable path of ss-server.
+
Only available in manager mode.
-v::
Enable verbose mode.
-h|--help::
Print help message.
PROTOCOL
--------
`ss-manager`(1) provides several APIs through UDP protocol:
Send UDP commands in the following format to the manager-address provided to ss-manager(1): ::::
command: [JSON data]
To add a port: ::::
add: {"server_port": 8001, "password":"7cd308cc059"}
To remove a port: ::::
remove: {"server_port": 8001}
To receive a pong: ::::
ping
Then `ss-manager`(1) will send back the traffic statistics: ::::
stat: {"8001":11370}
EXAMPLE
-------
To use `ss-manager`(1), First start it and specify necessary information.
Then communicate with `ss-manager`(1) through UNIX Domain Socket using UDP
protocol:
....
# Start the manager. Arguments for ss-server will be passed to generated
# ss-server process(es) respectively.
ss-manager --manager-address /tmp/manager.sock --executable $(which ss-server) -s example.com -m aes-256-cfb -c /path/to/config.json
# Connect to the socket. Using netcat-openbsd as an example.
# You should use scripts or other programs for further management.
nc -Uu /tmp/manager.sock
....
After that, you may communicate with `ss-manager`(1) as described above in the
'PROTOCOL' section.
SEE ALSO
--------
`ss-local`(1),
`ss-server`(1),
`ss-tunnel`(1),
`ss-redir`(1),
`shadowsocks-libev`(8),
`iptables`(8),
/etc/shadowsocks-libev/config.json
|
281677160/openwrt-package | 3,124 | luci-app-ssr-plus/shadowsocksr-libev/src/doc/ss-tunnel.asciidoc | ss-tunnel(1)
============
NAME
----
ss-tunnel - shadowsocks tools for local port forwarding, libev port
SYNOPSIS
--------
*ss-tunnel*
[-AuUv6] [-h|--help]
[-s <server_host>] [-p <server_port>] [-l <local_port>]
[-k <password>] [-m <encrypt_method>] [-f <pid_file>]
[-t <timeout>] [-c <config_file>] [-i <interface>]
[-b <local_addr>] [-a <user_name>] [-n <nofile>]
[-L addr:port] [--mtu <MTU>]
DESCRIPTION
-----------
*Shadowsocks-libev* is a lightweight and secure socks5 proxy.
It is a port of the original shadowsocks created by clowwindy.
*Shadowsocks-libev* is written in pure C and takes advantage of libev to
achieve both high performance and low resource consumption.
*Shadowsocks-libev* consists of five components.
`ss-tunnel`(1) is a tool for local port forwarding.
See 'OPTIONS' section for special option needed by `ss-tunnel`(1).
For more information, check out `shadowsocks-libev`(8).
OPTIONS
-------
-s <server_host>::
Set the server's hostname or IP.
-p <server_port>::
Set the server's port number.
-l <local_port>::
Set the local port number.
-k <password>::
Set the password. The server and the client should use the same password.
-m <encrypt_method>::
Set the cipher.
+
*Shadowsocks-libev* accepts 21 different ciphers:
+
table, rc4, rc4-md5, aes-128-cfb, aes-192-cfb, aes-256-cfb,
aes-128-ctr, aes-192-ctr, aes-256-ctr, bf-cfb,
camellia-128-cfb, camellia-192-cfb, camellia-256-cfb, cast5-cfb, des-cfb,
idea-cfb, rc2-cfb, seed-cfb, salsa20, chacha20 and chacha20-ietf.
+
The default cipher is 'rc4-md5'.
+
If built with PolarSSL or custom OpenSSL libraries, some of
these ciphers may not work.
-a <user_name>::
Run as a specific user.
-f <pid_file>::
Start shadowsocks as a daemon with specific pid file.
-t <timeout>::
Set the socket timeout in seconds. The default value is 60.
-c <config_file>::
Use a configuration file.
+
Refer to `shadowsocks-libev`(8) 'CONFIG FILE' section for more details.
-n <number>::
Specify max number of open files.
+
Only available on Linux.
-i <interface>::
Send traffic through specific network interface.
+
For example, there are three interfaces in your device,
which is lo (127.0.0.1), eth0 (192.168.0.1) and eth1 (192.168.0.2).
Meanwhile, you configure `ss-tunnel` to listen on 0.0.0.0:8388 and bind to eth1.
That results the traffic go out through eth1, but not lo nor eth0.
This option is useful to control traffic in multi-interface environment.
-b <local_address>::
Specify local address to bind.
-u::
Enable UDP relay.
-U::
Enable UDP relay and disable TCP relay.
-A::
Enable onetime authentication.
-6::
Resovle hostname to IPv6 address first.
-L <addr:port>::
Specify destination server address and port for local port forwarding.
+
Only used and available in tunnel mode.
--mtu <MTU>::
Specify the MTU of your network interface.
--mptcp::
Enable Multipath TCP.
+
Only available with MPTCP enabled Linux kernel.
-v::
Enable verbose mode.
-h|--help::
Print help message.
SEE ALSO
--------
`ss-local`(1),
`ss-server`(1),
`ss-redir`(1),
`ss-manager`(1),
`shadowsocks-libev`(8),
`iptables`(8),
/etc/shadowsocks-libev/config.json
|
281677160/openwrt-package | 1,192 | luci-app-ssr-plus/shadowsocksr-libev/src/doc/manpage-base.xsl | <!-- manpage-base.xsl:
special formatting for manpages rendered from asciidoc+docbook -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<!-- these params silence some output from xmlto -->
<xsl:param name="man.output.quietly" select="1"/>
<xsl:param name="refentry.meta.get.quietly" select="1"/>
<!-- convert asciidoc callouts to man page format;
git.docbook.backslash and git.docbook.dot params
must be supplied by another XSL file or other means -->
<xsl:template match="co">
<xsl:value-of select="concat(
$git.docbook.backslash,'fB(',
substring-after(@id,'-'),')',
$git.docbook.backslash,'fR')"/>
</xsl:template>
<xsl:template match="calloutlist">
<xsl:value-of select="$git.docbook.dot"/>
<xsl:text>sp </xsl:text>
<xsl:apply-templates/>
<xsl:text> </xsl:text>
</xsl:template>
<xsl:template match="callout">
<xsl:value-of select="concat(
$git.docbook.backslash,'fB',
substring-after(@arearefs,'-'),
'. ',$git.docbook.backslash,'fR')"/>
<xsl:apply-templates/>
<xsl:value-of select="$git.docbook.dot"/>
<xsl:text>br </xsl:text>
</xsl:template>
</xsl:stylesheet>
|
281677160/openwrt-package | 4,040 | luci-app-ssr-plus/shadowsocksr-libev/src/debian/shadowsocks-libev.init | #!/bin/sh
### BEGIN INIT INFO
# Provides: shadowsocks-libev
# Required-Start: $network $local_fs $remote_fs
# Required-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: lightweight secured socks5 proxy
# Description: Shadowsocks-libev is a lightweight secured
# socks5 proxy for embedded devices and low end boxes.
### END INIT INFO
# Author: Max Lv <max.c.lv@gmail.com>
# PATH should only include /usr/ if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC=shadowsocks-libev # Introduce a short description here
NAME=shadowsocks-libev # Introduce the short server's name here
DAEMON=/usr/bin/ss-server # Introduce the server's location here
DAEMON_ARGS="" # Arguments to run the daemon with
PIDFILE=/var/run/$NAME/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
# Exit if the package is not installed
[ -x $DAEMON ] || exit 0
# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
[ "$START" = "yes" ] || exit 0
: ${USER:="root"}
: ${GROUP:="root"}
# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh
# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions
#
# Function that starts the daemon/service
#
do_start()
{
# Modify the file descriptor limit
ulimit -n ${MAXFD}
# Take care of pidfile permissions
mkdir /var/run/$NAME 2>/dev/null || true
chown "$USER:$GROUP" /var/run/$NAME
# Return
# 0 if daemon has been started
# 1 if daemon was already running
# 2 if daemon could not be started
start-stop-daemon --start --quiet --pidfile $PIDFILE --chuid root:$GROUP --exec $DAEMON --test > /dev/null \
|| return 1
start-stop-daemon --start --quiet --pidfile $PIDFILE --chuid root:$GROUP --exec $DAEMON -- \
-c "$CONFFILE" -a "$USER" -u -f $PIDFILE $DAEMON_ARGS \
|| return 2
}
#
# Function that stops the daemon/service
#
do_stop()
{
# Return
# 0 if daemon has been stopped
# 1 if daemon was already stopped
# 2 if daemon could not be stopped
# other if a failure occurred
start-stop-daemon --stop --quiet --retry=KILL/5 --pidfile $PIDFILE --exec $DAEMON
RETVAL="$?"
[ "$RETVAL" = 2 ] && return 2
# Wait for children to finish too if this is a daemon that forks
# and if the daemon is only ever run from this initscript.
# If the above conditions are not satisfied then add some other code
# that waits for the process to drop all resources that could be
# needed by services started subsequently. A last resort is to
# sleep for some time.
start-stop-daemon --stop --quiet --oknodo --retry=KILL/5 --exec $DAEMON
[ "$?" = 2 ] && return 2
# Many daemons don't delete their pidfiles when they exit.
rm -f $PIDFILE
return "$RETVAL"
}
case "$1" in
start)
[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC " "$NAME"
do_start
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
stop)
[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
do_stop
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
status)
status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
;;
restart|force-reload)
log_daemon_msg "Restarting $DESC" "$NAME"
do_stop
case "$?" in
0|1)
do_start
case "$?" in
0) log_end_msg 0 ;;
1) log_end_msg 1 ;; # Old process is still running
*) log_end_msg 1 ;; # Failed to start
esac
;;
*)
# Failed to stop
log_end_msg 1
;;
esac
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
exit 3
;;
esac
:
|
281677160/openwrt-package | 2,118 | luci-app-ssr-plus/shadowsocksr-libev/src/debian/control | Source: shadowsocks-libev
Section: net
Priority: extra
Maintainer: Max Lv <max.c.lv@gmail.com>
Build-Depends:
asciidoc,
autotools-dev,
debhelper (>= 9),
dh-systemd (>= 1.5),
gawk,
libpcre3-dev,
libssl-dev (>= 0.9.8),
mime-support,
pkg-config,
xmlto,
Standards-Version: 3.9.8
Homepage: https://www.shadowsocks.org
Vcs-Git: https://github.com/shadowsocks/shadowsocks-libev.git
Vcs-Browser: https://github.com/shadowsocks/shadowsocks-libev
Package: libshadowsocks-libev-dev
Architecture: any
Section: libdevel
Breaks:
shadowsocks-libev (<< 2.4.0),
Depends:
libshadowsocks-libev2 (= ${binary:Version}),
${misc:Depends},
Description: lightweight and secure socks5 proxy (development files)
Shadowsocks-libev is a lightweight and secure socks5 proxy for
embedded devices and low end boxes.
.
Shadowsocks-libev was inspired by Shadowsock (in Python). It's rewritten
in pure C and only depends on libev, mbedTLS and a few other tiny
libraries.
.
This package provides C header files for the libraries.
Package: libshadowsocks-libev2
Architecture: any
Multi-Arch: same
Section: libs
Replaces: libshadowsocks-libev1
Breaks:
libshadowsocks-libev1,
shadowsocks-libev (<< 2.4.0),
Pre-Depends:
${misc:Pre-Depends},
Depends:
${misc:Depends},
${shlibs:Depends},
Description: lightweight and secure socks5 proxy (shared library)
Shadowsocks-libev is a lightweight and secure socks5 proxy for
embedded devices and low end boxes.
.
Shadowsocks-libev was inspired by Shadowsock (in Python). It's rewritten
in pure C and only depends on libev, mbedTLS and a few other tiny
libraries.
.
This package provides shared libraries.
Package: shadowsocks-libev
Replaces:
shadowsocks (<< 1.5.3-2),
Breaks:
shadowsocks (<< 1.5.3-2),
Architecture: any
Depends:
apg,
${misc:Depends},
${shlibs:Depends},
Description: lightweight and secure socks5 proxy
Shadowsocks-libev is a lightweight and secure socks5 proxy for
embedded devices and low end boxes.
.
Shadowsocks-libev was inspired by Shadowsock (in Python). It's rewritten
in pure C and only depends on libev, mbedTLS and a few other tiny
libraries.
|
281677160/openwrt-package | 10,523 | luci-app-ssr-plus/shadowsocksr-libev/src/debian/changelog | shadowsocks-libev (2.5.6-1) unstable; urgency=medium
* Add outbound ACL for server.
* Refine log format.
-- Max Lv <max.c.lv@gmail.com> Tue, 01 Nov 2016 09:51:52 +0800
shadowsocks-libev (2.5.5-1) unstable; urgency=medium
* Refine attack detection.
-- Max Lv <max.c.lv@gmail.com> Tue, 11 Oct 2016 15:45:09 +0800
shadowsocks-libev (2.5.4-1) unstable; urgency=medium
* Fix a bug of auto blocking mechanism.
-- Max Lv <max.c.lv@gmail.com> Sun, 09 Oct 2016 19:36:37 +0800
shadowsocks-libev (2.5.3-1) unstable; urgency=medium
* Fix TCP Fast Open on macOS.
-- Max Lv <max.c.lv@gmail.com> Wed, 21 Sep 2016 19:31:57 +0800
shadowsocks-libev (2.5.2-1) unstable; urgency=medium
* Fix a bug of UDP relay mode of ss-local.
-- Max Lv <max.c.lv@gmail.com> Mon, 12 Sep 2016 12:54:33 +0800
shadowsocks-libev (2.5.1-1) unstable; urgency=medium
* Refine ACL feature with hostname support.
* Add HTTP/SNI parser for ss-local/ss-redir.
-- Max Lv <max.c.lv@gmail.com> Sat, 10 Sep 2016 17:06:49 +0800
shadowsocks-libev (2.5.0-1) unstable; urgency=medium
* Fix several bugs of the command line interface.
* Add aes-128/192/256-ctr ciphers.
* Add option MTU for UDP relay.
* Add MultiPath TCP support.
-- Max Lv <max.c.lv@gmail.com> Mon, 29 Aug 2016 13:07:51 +0800
shadowsocks-libev (2.4.8-1) unstable; urgency=low
* Update manual pages with asciidoc.
* Fix issues of bind_address option.
-- Max Lv <max.c.lv@gmail.com> Wed, 20 Jul 2016 09:25:50 +0800
shadowsocks-libev (2.4.7-1) unstable; urgency=low
* Add ss-nat, a helper script to set up NAT rules for ss-redir.
* Fix several issues for debian package.
-- Max Lv <max.c.lv@gmail.com> Wed, 1 Jun 2016 18:21:45 +0800
shadowsocks-libev (2.4.6-1) unstable; urgency=low
* Update manual pages.
-- Max Lv <max.c.lv@gmail.com> Thu, 21 Apr 2016 17:33:34 +0800
shadowsocks-libev (2.4.5-1) unstable; urgency=low
* Fix build issues on OpenWRT.
* Reduce the latency of redir mode.
-- Max Lv <max.c.lv@gmail.com> Mon, 01 Feb 2016 13:22:50 +0800
shadowsocks-libev (2.4.4-1) unstable; urgency=low
* Fix a potential memory leak.
* Fix some compiler related issues.
-- Max Lv <max.c.lv@gmail.com> Wed, 13 Jan 2016 11:50:12 +0800
shadowsocks-libev (2.4.3-1) unstable; urgency=high
* Refine the buffer allocation.
-- Max Lv <max.c.lv@gmail.com> Sat, 19 Dec 2015 12:30:21 +0900
shadowsocks-libev (2.4.1-1) unstable; urgency=high
* Fix a security bug.
-- Max Lv <max.c.lv@gmail.com> Thu, 29 Oct 2015 15:42:47 +0900
shadowsocks-libev (2.4.0-1) unstable; urgency=low
* Update the one-time authentication
-- Max Lv <max.c.lv@gmail.com> Thu, 24 Sep 2015 14:11:05 +0900
shadowsocks-libev (2.3.3-1) unstable; urgency=low
* Refine the onetime authentication of header.
* Enforce CRC16 on the payload.
-- Max Lv <max.c.lv@gmail.com> Fri, 18 Sep 2015 10:38:21 +0900
shadowsocks-libev (2.3.2-1) unstable; urgency=low
* Fix minor issues of build scripts.
-- Max Lv <max.c.lv@gmail.com> Sun, 13 Sep 2015 15:22:28 +0900
shadowsocks-libev (2.3.1-1) unstable; urgency=low
* Fix an issue of connection cache of UDP relay.
* Add support of onetime authentication for header verification.
-- Max Lv <max.c.lv@gmail.com> Fri, 04 Sep 2015 07:54:02 +0900
shadowsocks-libev (2.3.0-1) unstable; urgency=low
* Add manager mode to support multi-user and traffic stat.
* Fix a build issue on OS X El Capitan.
-- Max Lv <max.c.lv@gmail.com> Thu, 30 Jul 2015 17:30:43 +0900
shadowsocks-libev (2.2.3-1) unstable; urgency=high
* Fix the multiple UDP source port issue.
* Allow working in UDP only mode.
-- Max Lv <max.c.lv@gmail.com> Sat, 11 Jul 2015 08:31:02 +0900
shadowsocks-libev (2.2.2-1) unstable; urgency=low
* Fix the timer of UDP relay.
* Check name_len in the header.
-- Max Lv <max.c.lv@gmail.com> Mon, 15 Jun 2015 10:26:40 +0900
shadowsocks-libev (2.2.1-1) unstable; urgency=low
* Fix an issue of UDP relay.
-- Max Lv <max.c.lv@gmail.com> Sun, 10 May 2015 21:23:44 +0900
shadowsocks-libev (2.2.0-1) unstable; urgency=low
* Add TPROXY support in redir mode.
-- Max Lv <max.c.lv@gmail.com> Mon, 04 May 2015 02:44:17 -0300
shadowsocks-libev (2.1.4-1) unstable; urgency=low
* Fix a bug of server mode ACL.
-- Max Lv <max.c.lv@gmail.com> Sun, 08 Feb 2015 20:24:43 +0900
shadowsocks-libev (2.1.3-1) unstable; urgency=low
* Add ACL support to remote server.
-- Max Lv <max.c.lv@gmail.com> Sun, 08 Feb 2015 10:59:44 +0900
shadowsocks-libev (2.1.2-1) unstable; urgency=low
* Refine multiple port binding.
-- Max Lv <max.c.lv@gmail.com> Sat, 31 Jan 2015 18:56:25 +0900
shadowsocks-libev (2.1.1-1) unstable; urgency=low
* Fix a memory leak.
-- Max Lv <max.c.lv@gmail.com> Wed, 21 Jan 2015 21:40:58 +0900
shadowsocks-libev (2.1.0-1) unstable; urgency=low
* Fix a bug of tunnel mode.
-- Max Lv <max.c.lv@gmail.com> Mon, 19 Jan 2015 09:59:52 +0900
shadowsocks-libev (2.0.8-1) unstable; urgency=low
* Fix a bug of IPv6.
-- Max Lv <max.c.lv@gmail.com> Fri, 16 Jan 2015 10:58:12 +0900
shadowsocks-libev (2.0.7-1) unstable; urgency=low
* Fix some performance issue.
-- Max Lv <max.c.lv@gmail.com> Tue, 13 Jan 2015 13:17:58 +0900
shadowsocks-libev (2.0.6-1) unstable; urgency=high
* Fix a critical issue in redir mode.
-- Max Lv <max.c.lv@gmail.com> Mon, 12 Jan 2015 21:51:19 +0900
shadowsocks-libev (2.0.5-1) unstable; urgency=low
* Refine local, tunnel, and redir modes.
-- Max Lv <max.c.lv@gmail.com> Mon, 12 Jan 2015 12:39:05 +0800
shadowsocks-libev (2.0.4-1) unstable; urgency=low
* Fix building issues with MinGW32.
-- Max Lv <max.c.lv@gmail.com> Sun, 11 Jan 2015 13:33:31 +0900
shadowsocks-libev (2.0.3-1) unstable; urgency=high
* Fix some issues.
-- Max Lv <max.c.lv@gmail.com> Sat, 10 Jan 2015 16:27:54 +0800
shadowsocks-libev (2.0.2-1) unstable; urgency=low
* Fix issues with MinGW.
-- Max Lv <max.c.lv@gmail.com> Sat, 10 Jan 2015 15:17:10 +0800
shadowsocks-libev (2.0.1-1) unstable; urgency=low
* Implement a real asynchronous DNS resolver.
-- Max Lv <max.c.lv@gmail.com> Sat, 10 Jan 2015 10:04:28 +0800
shadowsocks-libev (1.6.4-1) unstable; urgency=low
* Update documents.
-- Max Lv <max.c.lv@gmail.com> Wed, 07 Jan 2015 21:48:58 +0900
shadowsocks-libev (1.6.3-1) unstable; urgency=low
* Refine ss-redir.
-- Max Lv <max.c.lv@gmail.com> Sun, 04 Jan 2015 19:23:52 +0900
shadowsocks-libev (1.6.2-1) unstable; urgency=low
* Fix some build issues.
-- Max Lv <max.c.lv@gmail.com> Tue, 30 Dec 2014 10:30:28 +0800
shadowsocks-libev (1.6.1-1) unstable; urgency=high
* Add salsa20 and chacha20 support.
-- Max Lv <max.c.lv@gmail.com> Sat, 13 Dec 2014 15:11:34 +0800
shadowsocks-libev (1.6.0-1) unstable; urgency=low
* Solve conflicts with other shadowsocks portings.
-- Max Lv <max.c.lv@gmail.com> Mon, 17 Nov 2014 14:10:21 +0800
shadowsocks-libev (1.5.3-2) unstable; urgency=low
* rename as shadowsocks-libev.
-- Symeon Huang <hzwhuang@gmail.com> Sat, 15 Nov 2014 14:55:28 +0000
shadowsocks (1.5.3-1) unstable; urgency=low
* Fix log on Win32.
-- Max Lv <max.c.lv@gmail.com> Fri, 14 Nov 2014 09:10:06 +0800
shadowsocks (1.5.2-1) unstable; urgency=low
* Handle SIGTERM and SIGKILL nicely.
-- Max Lv <max.c.lv@gmail.com> Tue, 12 Nov 2014 13:11:29 +0800
shadowsocks (1.5.1-1) unstable; urgency=low
* Fix a bug of tcp fast open.
-- Max Lv <max.c.lv@gmail.com> Sat, 08 Nov 2014 19:45:37 +0900
shadowsocks (1.5.0-1) unstable; urgency=low
* Support to build static or shared library.
* Supprot IPv6 NAT in redirect mode.
* Refine the cache size of UDPRelay.
-- Max Lv <max.c.lv@gmail.com> Fri, 07 Nov 2014 09:33:19 +0800
shadowsocks (1.4.8-1) unstable; urgency=low
* Fix a bug of tcp fast open.
-- Max Lv <max.c.lv@gmail.com> Wed, 08 Oct 2014 18:02:02 +0800
shadowsocks (1.4.7-1) unstable; urgency=low
* Add a new encryptor rc4-md5.
-- Max Lv <max.c.lv@gmail.com> Tue, 09 Sep 2014 07:50:10 +0800
shadowsocks (1.4.6-1) unstable; urgency=low
* Add ACL support.
-- Max Lv <max.c.lv@gmail.com> Sat, 03 May 2014 04:37:10 -0400
shadowsocks (1.4.5-1) unstable; urgency=high
* Fix the compatibility issue of udprelay.
* Enhance asyncns to reduce the latency.
* Add TCP_FASTOPEN support.
-- Max Lv <max.c.lv@gmail.com> Sun, 20 Apr 2014 08:12:45 +0800
shadowsocks (1.4.4-1) unstable; urgency=low
* Add CommonCrypto support for darwin.
* Fix some config related issues.
-- Max Lv <max.c.lv@gmail.com> Wed, 26 Mar 2014 13:29:03 +0800
shadowsocks (1.4.3-1) unstable; urgency=low
* Add tunnel mode with local port forwarding feature.
-- Max Lv <max.c.lv@gmail.com> Fri, 21 Feb 2014 11:52:13 +0900
shadowsocks (1.4.2-1) unstable; urgency=high
* Fix the UDP relay issues.
* Add syslog support.
-- Max Lv <max.c.lv@gmail.com> Sun, 05 Jan 2014 10:05:29 +0900
shadowsocks (1.4.1-1) unstable; urgency=low
* Add multi-port support.
* Add PolarSSL support by @linusyang.
-- Max Lv <max.c.lv@gmail.com> Tue, 12 Nov 2013 03:57:21 +0000
shadowsocks (1.4.0-1) unstable; urgency=low
* Add standard socks5 udp support.
-- Max Lv <max.c.lv@gmail.com> Sun, 08 Sep 2013 02:20:40 +0000
shadowsocks (1.3.3-1) unstable; urgency=high
* Provide more info in verbose mode.
-- Max Lv <max.c.lv@gmail.com> Fri, 21 Jun 2013 09:59:20 +0800
shadowsocks (1.3.2-1) unstable; urgency=high
* Fix some ciphers by @linusyang.
-- Max Lv <max.c.lv@gmail.com> Sun, 09 Jun 2013 09:52:31 +0000
shadowsocks (1.3.1-1) unstable; urgency=low
* Support more cihpers: camellia, idea, rc2 and seed.
-- Max Lv <max.c.lv@gmail.com> Tue, 04 Jun 2013 00:56:17 +0000
shadowsocks (1.3-1) unstable; urgency=low
* Able to bind connections to specific interface.
* Support more ciphers: aes-128-cfb, aes-192-cfb, aes-256-cfb, bf-cfb, cast5-cfb, des-cfb.
-- Max Lv <max.c.lv@gmail.com> Thu, 16 May 2013 10:51:15 +0800
shadowsocks (1.2-2) unstable; urgency=low
* Close timeouted TCP connections.
-- Max Lv <max.c.lv@gmail.com> Tue, 07 May 2013 14:10:33 +0800
shadowsocks (1.2-1) unstable; urgency=low
* Fix a high load issue.
-- Max Lv <max.c.lv@gmail.com> Thu, 18 Apr 2013 10:52:34 +0800
shadowsocks (1.1-1) unstable; urgency=low
* Fix a IPV6 resolve issue.
-- Max Lv <max.c.lv@gmail.com> Wed, 10 Apr 2013 12:11:36 +0800
shadowsocks (1.0-2) unstable; urgency=low
* Initial release.
-- Max Lv <max.c.lv@gmail.com> Sat, 06 Apr 2013 16:59:15 +0800
|
281677160/openwrt-package | 9,218 | luci-app-ssr-plus/shadowsocksr-libev/src/debian/copyright | Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: shadowsocks-libev
Upstream-Contact: Max Lv <max.c.lv@gmail.com>
Source: https://github.com/shadowsocks/shadowsocks-libev
Files: *
Copyright: 2013-2015, Clow Windy <clowwindy42@gmail.com>
2013-2016, Max Lv <max.c.lv@gmail.com>
2014, Linus Yang <linusyang@gmail.com>
License: GPL-3+
Files: debian/*
Copyright: 2013-2015, Max Lv <max.c.lv@gmail.com>
2015, Boyuan Yang <073plan@gmail.com>
2016, Roger Shimizu <rogershimizu@gmail.com>
License: GPL-3+
Files: libcork/* libipset/*
Copyright: 2011-2013, RedJack, LLC.
License: BSD-3-clause
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
.
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
.
Neither the name of RedJack Software, LLC nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Files: doc/*
Copyright: 2012-2016, Max Lv <max.c.lv@gmail.com>
License: GFDL-1.1+
Files: m4/ax_pthread.m4
Copyright: 2008 Steven G. Johnson <stevenj@alum.mit.edu>
2011 Daniel Richard G. <skunk@iSKUNK.ORG>
License: GPL-3+ with Autoconf exception
Files: m4/ax_tls.m4
Copyright: 2008 Alan Woodland <ajw05@aber.ac.uk>
2010 Diego Elio Petteno` <flameeyes@gmail.com>
License: GPL-3+ with Autoconf exception
Files: m4/pcre.m4
Copyright: 2015 Syrone Wong <wong.syrone@gmail.com>
License: Apache-2.0
Files: m4/stack-protector.m4
Copyright: 2007 Google Inc.
License: Apache-2.0
Files: src/json.c src/json.h
Copyright: 2012-2014, James McLaughlin et al.
License: BSD-2-clause
Files: src/http.c src/http.h src/protocol.h src/resolv.c src/resolv.h src/tls.c src/tls.h
Copyright: 2011-2014, Dustin Lundquist <dustin@null-ptr.net>
License: BSD-2-clause
Files: src/rule.c src/rule.h
Copyright: 2011-2012, Dustin Lundquist <dustin@null-ptr.net>
2011, Manuel Kasper <mk@neon1.net>
License: BSD-2-clause
Files: src/ss-nat
Copyright: 2015, OpenWrt-dist
2015, Jian Chang <aa65535@live.com>
License: GPL-3+
Files: src/uthash.h
Copyright: 2003-2013, Troy D. Hanson
License: BSD-1-clause
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
.
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
License: Apache-2.0
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
.
http://www.apache.org/licenses/LICENSE-2.0
.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
.
On Debian systems, the complete text of the Apache version 2.0 license
can be found in "/usr/share/common-licenses/Apache-2.0".
License: BSD-2-clause
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
.
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
License: GFDL-1.1+
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
.
A copy of the license is included in the section entitled
"GNU Free Documentation License".
License: GPL-3+
This package is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
.
On Debian systems, the complete text of the GNU General
Public License version 3 can be found in "/usr/share/common-licenses/GPL-3".
License: GPL-3+ with Autoconf exception
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
.
You should have received a copy of the GNU General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
.
As a special exception, the respective Autoconf Macro's copyright owner
gives unlimited permission to copy, distribute and modify the configure
scripts that are the output of Autoconf when processing the Macro. You
need not follow the terms of the GNU General Public License when using
or distributing such scripts, even though portions of the text of the
Macro appear in them. The GNU General Public License (GPL) does govern
all other use of the material that constitutes the Autoconf Macro.
.
This special exception to the GPL applies to versions of the Autoconf
Macro released by the Autoconf Archive. When you make and distribute a
modified version of the Autoconf Macro, you may extend this special
exception to the GPL to apply to your modified version as well.
|
281677160/openwrt-package | 1,371 | luci-app-ssr-plus/shadowsocksr-libev/src/rpm/genrpm.sh | #!/usr/bin/env bash
set -e
show_help()
{
echo -e "`basename $0` [option] [argument]"
echo
echo -e "Options:"
echo -e " -h show this help."
echo -e " -v with argument version (2.5.6 by default)."
echo -e " -f with argument format (tar.xz by default) used by git archive."
echo
echo -e "Examples:"
echo -e " to build base on version \`2.4.1' with format \`tar.xz', run:"
echo -e " `basename $0` -f tar.xz -v 2.4.1"
}
while getopts "hv:f:" opt
do
case ${opt} in
h)
show_help
exit 0
;;
v)
if [ "${OPTARG}" = v* ]; then
version=${OPTARG#"v"}
else
version=${OPTARG}
fi
;;
f)
format=${OPTARG}
;;
*)
exit 1
;;
esac
done
: ${version:=2.5.6}
: ${format:=tar.gz}
name="shadowsocks-libev"
spec_name="shadowsocks-libev.spec"
pushd `git rev-parse --show-toplevel`
git archive "v${version}" --format="${format}" --prefix="${name}-${version}/" -o rpm/SOURCES/"${name}-${version}.${format}"
pushd rpm
sed -e "s/^\(Version: \).*$/\1${version}/" \
-e "s/^\(Source0: \).*$/\1${name}-${version}.${format}/" \
SPECS/"${spec_name}".in > SPECS/"${spec_name}"
rpmbuild -bb SPECS/"${spec_name}" --define "%_topdir `pwd`"
|
281677160/openwrt-package | 2,252 | luci-app-ssr-plus/shadowsocksr-libev/src/src/tunnel.h | /*
* tunnel.h - Define tunnel's buffers and callbacks
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _TUNNEL_H
#define _TUNNEL_H
#include <ev.h>
#include "encrypt.h"
#include "obfs/obfs.h"
#include "jconf.h"
#include "common.h"
typedef struct listen_ctx {
ev_io io;
ss_addr_t tunnel_addr;
char *iface;
int remote_num;
int method;
int timeout;
int fd;
int mptcp;
struct sockaddr **remote_addr;
// SSR
char *protocol_name;
char *protocol_param;
char *obfs_name;
char *obfs_param;
void **list_protocol_global;
void **list_obfs_global;
} listen_ctx_t;
typedef struct server_ctx {
ev_io io;
int connected;
struct server *server;
} server_ctx_t;
typedef struct server {
int fd;
buffer_t *buf;
ssize_t buf_capacity;
struct enc_ctx *e_ctx;
struct enc_ctx *d_ctx;
struct server_ctx *recv_ctx;
struct server_ctx *send_ctx;
struct remote *remote;
ss_addr_t destaddr;
// SSR
obfs *protocol;
obfs *obfs;
obfs_class *protocol_plugin;
obfs_class *obfs_plugin;
} server_t;
typedef struct remote_ctx {
ev_io io;
ev_timer watcher;
int connected;
struct remote *remote;
} remote_ctx_t;
typedef struct remote {
int fd;
buffer_t *buf;
ssize_t buf_capacity;
struct remote_ctx *recv_ctx;
struct remote_ctx *send_ctx;
struct server *server;
uint32_t counter;
// SSR
int remote_index;
} remote_t;
#endif // _TUNNEL_H
|
281677160/openwrt-package | 3,819 | luci-app-ssr-plus/shadowsocksr-libev/src/src/android.c | /*
* android.c - Setup IPC for shadowsocks-android
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <locale.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/un.h>
#include <ancillary.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "netutils.h"
#include "utils.h"
extern char *prefix;
int
protect_socket(int fd)
{
int sock;
struct sockaddr_un addr;
if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
LOGE("[android] socket() failed: %s (socket fd = %d)\n", strerror(errno), sock);
return -1;
}
// Set timeout to 1s
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(struct timeval));
char path[257];
sprintf(path, "%s/protect_path", prefix);
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
LOGE("[android] connect() failed: %s (socket fd = %d), path: %s\n",
strerror(errno), sock, path);
close(sock);
return -1;
}
if (ancil_send_fd(sock, fd)) {
ERROR("[android] ancil_send_fd");
close(sock);
return -1;
}
char ret = 0;
if (recv(sock, &ret, 1, 0) == -1) {
ERROR("[android] recv");
close(sock);
return -1;
}
close(sock);
return ret;
}
int
send_traffic_stat(uint64_t tx, uint64_t rx)
{
int sock;
struct sockaddr_un addr;
if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
LOGE("[android] socket() failed: %s (socket fd = %d)\n", strerror(errno), sock);
return -1;
}
// Set timeout to 1s
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(struct timeval));
char path[257];
sprintf(path, "%s/stat_path", prefix);
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
LOGE("[android] connect() failed: %s (socket fd = %d), path: %s\n",
strerror(errno), sock, path);
close(sock);
return -1;
}
uint64_t stat[2] = { tx, rx };
if (send(sock, stat, sizeof(stat), 0) == -1) {
ERROR("[android] send");
close(sock);
return -1;
}
char ret = 0;
if (recv(sock, &ret, 1, 0) == -1) {
ERROR("[android] recv");
close(sock);
return -1;
}
close(sock);
return ret;
}
|
281677160/openwrt-package | 5,852 | luci-app-ssr-plus/shadowsocksr-libev/src/src/encrypt.h | /*
* encrypt.h - Define the enryptor's interface
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _ENCRYPT_H
#define _ENCRYPT_H
#ifndef __MINGW32__
#include <sys/socket.h>
#else
#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif
#endif
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#if defined(USE_CRYPTO_OPENSSL)
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <openssl/md5.h>
typedef EVP_CIPHER cipher_kt_t;
typedef EVP_CIPHER_CTX cipher_evp_t;
typedef EVP_MD digest_type_t;
#define MAX_KEY_LENGTH EVP_MAX_KEY_LENGTH
#define MAX_IV_LENGTH EVP_MAX_IV_LENGTH
#define MAX_MD_SIZE EVP_MAX_MD_SIZE
#elif defined(USE_CRYPTO_POLARSSL)
#include <polarssl/cipher.h>
#include <polarssl/md.h>
typedef cipher_info_t cipher_kt_t;
typedef cipher_context_t cipher_evp_t;
typedef md_info_t digest_type_t;
#define MAX_KEY_LENGTH 64
#define MAX_IV_LENGTH POLARSSL_MAX_IV_LENGTH
#define MAX_MD_SIZE POLARSSL_MD_MAX_SIZE
#elif defined(USE_CRYPTO_MBEDTLS)
#include <mbedtls/cipher.h>
#include <mbedtls/md.h>
typedef mbedtls_cipher_info_t cipher_kt_t;
typedef mbedtls_cipher_context_t cipher_evp_t;
typedef mbedtls_md_info_t digest_type_t;
#define MAX_KEY_LENGTH 64
#define MAX_IV_LENGTH MBEDTLS_MAX_IV_LENGTH
#define MAX_MD_SIZE MBEDTLS_MD_MAX_SIZE
/* we must have MBEDTLS_CIPHER_MODE_CFB defined */
#if !defined(MBEDTLS_CIPHER_MODE_CFB)
#error Cipher Feedback mode a.k.a CFB not supported by your mbed TLS.
#endif
#endif
#ifdef USE_CRYPTO_APPLECC
#include <CommonCrypto/CommonCrypto.h>
#define kCCAlgorithmInvalid UINT32_MAX
#define kCCContextValid 0
#define kCCContextInvalid -1
typedef struct {
CCCryptorRef cryptor;
int valid;
CCOperation encrypt;
CCAlgorithm cipher;
CCMode mode;
CCPadding padding;
uint8_t iv[MAX_IV_LENGTH];
uint8_t key[MAX_KEY_LENGTH];
size_t iv_len;
size_t key_len;
} cipher_cc_t;
#endif
typedef struct {
uint8_t *enc_table;
uint8_t *dec_table;
uint8_t enc_key[MAX_KEY_LENGTH];
int enc_key_len;
int enc_iv_len;
int enc_method;
struct cache *iv_cache;
} cipher_env_t;
typedef struct {
cipher_evp_t *evp;
#ifdef USE_CRYPTO_APPLECC
cipher_cc_t cc;
#endif
uint8_t iv[MAX_IV_LENGTH];
} cipher_ctx_t;
typedef struct {
cipher_kt_t *info;
size_t iv_len;
size_t key_len;
} cipher_t;
#ifdef HAVE_STDINT_H
#include <stdint.h>
#elif HAVE_INTTYPES_H
#include <inttypes.h>
#endif
#define SODIUM_BLOCK_SIZE 64
enum crpher_index {
NONE,
TABLE,
RC4,
RC4_MD5_6,
RC4_MD5,
AES_128_CFB,
AES_192_CFB,
AES_256_CFB,
AES_128_CTR,
AES_192_CTR,
AES_256_CTR,
BF_CFB,
CAMELLIA_128_CFB,
CAMELLIA_192_CFB,
CAMELLIA_256_CFB,
CAST5_CFB,
DES_CFB,
IDEA_CFB,
RC2_CFB,
SEED_CFB,
SALSA20,
CHACHA20,
CHACHA20IETF,
CIPHER_NUM,
};
#define ADDRTYPE_MASK 0xEF
#define MD5_BYTES 16U
#define SHA1_BYTES 20U
#define min(a, b) (((a) < (b)) ? (a) : (b))
#define max(a, b) (((a) > (b)) ? (a) : (b))
typedef struct buffer {
size_t idx;
size_t len;
size_t capacity;
char *array;
} buffer_t;
typedef struct chunk {
uint32_t idx;
uint32_t len;
uint32_t counter;
buffer_t *buf;
} chunk_t;
typedef struct enc_ctx {
uint8_t init;
uint64_t counter;
cipher_ctx_t evp;
} enc_ctx_t;
void bytes_to_key_with_size(const char *pass, size_t len, uint8_t *md, size_t md_size);
int rand_bytes(uint8_t *output, int len);
int ss_encrypt_all(cipher_env_t* env, buffer_t *plaintext, size_t capacity);
int ss_decrypt_all(cipher_env_t* env, buffer_t *ciphertext, size_t capacity);
int ss_encrypt(cipher_env_t* env, buffer_t *plaintext, enc_ctx_t *ctx, size_t capacity);
int ss_decrypt(cipher_env_t* env, buffer_t *ciphertext, enc_ctx_t *ctx, size_t capacity);
int enc_init(cipher_env_t *env, const char *pass, const char *method);
void enc_release(cipher_env_t *env);
void enc_ctx_init(cipher_env_t *env, enc_ctx_t *ctx, int enc);
void enc_ctx_release(cipher_env_t* env, enc_ctx_t *ctx);
int enc_get_iv_len(cipher_env_t* env);
uint8_t* enc_get_key(cipher_env_t* env);
int enc_get_key_len(cipher_env_t* env);
void cipher_context_release(cipher_env_t *env, cipher_ctx_t *ctx);
unsigned char *enc_md5(const unsigned char *d, size_t n, unsigned char *md);
int ss_md5_hmac_with_key(char *auth, char *msg, int msg_len, uint8_t *auth_key, int key_len);
int ss_md5_hash_func(char *auth, char *msg, int msg_len);
int ss_sha1_hmac_with_key(char *auth, char *msg, int msg_len, uint8_t *auth_key, int key_len);
int ss_sha1_hash_func(char *auth, char *msg, int msg_len);
int ss_aes_128_cbc(char *encrypt, char *out_data, char *key);
int ss_encrypt_buffer(cipher_env_t *env, enc_ctx_t *ctx, char *in, size_t in_size, char *out, size_t *out_size);
int ss_decrypt_buffer(cipher_env_t *env, enc_ctx_t *ctx, char *in, size_t in_size, char *out, size_t *out_size);
int balloc(buffer_t *ptr, size_t capacity);
int brealloc(buffer_t *ptr, size_t len, size_t capacity);
void bfree(buffer_t *ptr);
//extern cipher_env_t cipher_env;
#endif // _ENCRYPT_H
|
281677160/openwrt-package | 1,959 | luci-app-ssr-plus/shadowsocksr-libev/src/src/resolv.h | /*
* Copyright (c) 2014, Dustin Lundquist <dustin@null-ptr.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RESOLV_H
#define RESOLV_H
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdint.h>
#ifdef __MINGW32__
#include "win32.h"
#else
#include <sys/socket.h>
#endif
struct ResolvQuery;
int resolv_init(struct ev_loop *, char **, int, int);
struct ResolvQuery *resolv_query(const char *, void (*)(struct sockaddr *,
void *), void (*)(
void *), void *, uint16_t);
void resolv_cancel(struct ResolvQuery *);
void resolv_shutdown(struct ev_loop *);
#endif
|
281677160/openwrt-package | 2,129 | luci-app-ssr-plus/shadowsocksr-libev/src/src/server.h | /*
* server.h - Define shadowsocks server's buffers and callbacks
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _SERVER_H
#define _SERVER_H
#include <ev.h>
#include <time.h>
#include <libcork/ds.h>
#include "encrypt.h"
#include "jconf.h"
#include "resolv.h"
#include "common.h"
typedef struct listen_ctx {
ev_io io;
int fd;
int timeout;
int method;
char *iface;
struct ev_loop *loop;
} listen_ctx_t;
typedef struct server_ctx {
ev_io io;
ev_timer watcher;
int connected;
struct server *server;
} server_ctx_t;
typedef struct server {
int fd;
int stage;
buffer_t *buf;
ssize_t buf_capacity;
buffer_t *header_buf;
struct chunk *chunk;
struct enc_ctx *e_ctx;
struct enc_ctx *d_ctx;
struct server_ctx *recv_ctx;
struct server_ctx *send_ctx;
struct listen_ctx *listen_ctx;
struct remote *remote;
struct ResolvQuery *query;
struct cork_dllist_item entries;
} server_t;
typedef struct query {
server_t *server;
char hostname[257];
} query_t;
typedef struct remote_ctx {
ev_io io;
int connected;
struct remote *remote;
} remote_ctx_t;
typedef struct remote {
int fd;
buffer_t *buf;
ssize_t buf_capacity;
struct remote_ctx *recv_ctx;
struct remote_ctx *send_ctx;
struct server *server;
} remote_t;
#endif // _SERVER_H
|
281677160/openwrt-package | 2,771 | luci-app-ssr-plus/shadowsocksr-libev/src/src/win32.c | /*
* win32.c - Win32 port helpers
*
* Copyright (C) 2014, Linus Yang <linusyang@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "win32.h"
#include "utils.h"
#ifdef setsockopt
#undef setsockopt
#endif
void
winsock_init(void)
{
WORD wVersionRequested;
WSADATA wsaData;
int ret;
wVersionRequested = MAKEWORD(1, 1);
ret = WSAStartup(wVersionRequested, &wsaData);
if (ret != 0) {
FATAL("Could not initialize winsock");
}
if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) {
WSACleanup();
FATAL("Could not find a usable version of winsock");
}
}
void
winsock_cleanup(void)
{
WSACleanup();
}
void
ss_error(const char *s)
{
LPVOID *msg = NULL;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, WSAGetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&msg, 0, NULL);
if (msg != NULL) {
LOGE("%s: %s", s, (char *)msg);
LocalFree(msg);
}
}
int
setnonblocking(int fd)
{
u_long iMode = 1;
long int iResult;
iResult = ioctlsocket(fd, FIONBIO, &iMode);
if (iResult != NO_ERROR) {
LOGE("ioctlsocket failed with error: %ld\n", iResult);
}
return iResult;
}
size_t
strnlen(const char *s, size_t maxlen)
{
const char *end = memchr(s, 0, maxlen);
return end ? (size_t)(end - s) : maxlen;
}
const char *
inet_ntop(int af, const void *src, char *dst, socklen_t size)
{
struct sockaddr_storage ss;
unsigned long s = size;
ZeroMemory(&ss, sizeof(ss));
ss.ss_family = af;
switch (af) {
case AF_INET:
((struct sockaddr_in *)&ss)->sin_addr = *(struct in_addr *)src;
break;
case AF_INET6:
((struct sockaddr_in6 *)&ss)->sin6_addr = *(struct in6_addr *)src;
break;
default:
return NULL;
}
return (WSAAddressToString((struct sockaddr *)&ss, sizeof(ss), NULL, dst,
&s) == 0) ? dst : NULL;
}
|
281677160/openwrt-package | 1,505 | luci-app-ssr-plus/shadowsocksr-libev/src/src/tls.h | /*
* Copyright (c) 2011 and 2012, Dustin Lundquist <dustin@null-ptr.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TLS_H
#define TLS_H
#include "protocol.h"
const protocol_t *const tls_protocol;
#endif
|
281677160/openwrt-package | 4,677 | luci-app-ssr-plus/shadowsocksr-libev/src/src/http.c | /*
* Copyright (c) 2011 and 2012, Dustin Lundquist <dustin@null-ptr.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h> /* malloc() */
#include <string.h> /* strncpy() */
#include <strings.h> /* strncasecmp() */
#include <ctype.h> /* isblank() */
#include "http.h"
#include "protocol.h"
#define SERVER_NAME_LEN 256
static int parse_http_header(const char *, size_t, char **);
static int get_header(const char *, const char *, int, char **);
static int next_header(const char **, int *);
static const protocol_t http_protocol_st = {
.default_port = 80,
.parse_packet = &parse_http_header,
};
const protocol_t *const http_protocol = &http_protocol_st;
/*
* Parses a HTTP request for the Host: header
*
* Returns:
* >=0 - length of the hostname and updates *hostname
* caller is responsible for freeing *hostname
* -1 - Incomplete request
* -2 - No Host header included in this request
* -3 - Invalid hostname pointer
* -4 - malloc failure
* < -4 - Invalid HTTP request
*
*/
static int
parse_http_header(const char *data, size_t data_len, char **hostname)
{
int result, i;
if (hostname == NULL)
return -3;
if (data_len == 0)
return -1;
result = get_header("Host:", data, data_len, hostname);
if (result < 0)
return result;
/*
* if the user specifies the port in the request, it is included here.
* Host: example.com:80
* so we trim off port portion
*/
for (i = result - 1; i >= 0; i--)
if ((*hostname)[i] == ':') {
(*hostname)[i] = '\0';
result = i;
break;
}
return result;
}
static int
get_header(const char *header, const char *data, int data_len, char **value)
{
int len, header_len;
header_len = strlen(header);
/* loop through headers stopping at first blank line */
while ((len = next_header(&data, &data_len)) != 0)
if (len > header_len && strncasecmp(header, data, header_len) == 0) {
/* Eat leading whitespace */
while (header_len < len && isblank(data[header_len]))
header_len++;
*value = malloc(len - header_len + 1);
if (*value == NULL)
return -4;
strncpy(*value, data + header_len, len - header_len);
(*value)[len - header_len] = '\0';
return len - header_len;
}
/* If there is no data left after reading all the headers then we do not
* have a complete HTTP request, there must be a blank line */
if (data_len == 0)
return -1;
return -2;
}
static int
next_header(const char **data, int *len)
{
int header_len;
/* perhaps we can optimize this to reuse the value of header_len, rather
* than scanning twice.
* Walk our data stream until the end of the header */
while (*len > 2 && (*data)[0] != '\r' && (*data)[1] != '\n') {
(*len)--;
(*data)++;
}
/* advanced past the <CR><LF> pair */
*data += 2;
*len -= 2;
/* Find the length of the next header */
header_len = 0;
while (*len > header_len + 1
&& (*data)[header_len] != '\r'
&& (*data)[header_len + 1] != '\n')
header_len++;
return header_len;
}
|
281677160/openwrt-package | 1,487 | luci-app-ssr-plus/shadowsocksr-libev/src/src/acl.h | /*
* acl.h - Define the ACL interface
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _ACL_H
#define _ACL_H
#define BLACK_LIST 0
#define WHITE_LIST 1
#define MAX_TRIES 64
#define MALICIOUS 8
#define SUSPICIOUS 4
#define BAD 2
#define MALFORMED 1
int init_acl(const char *path);
void free_acl(void);
void clear_block_list(void);
int acl_match_host(const char *ip);
int acl_add_ip(const char *ip);
int acl_remove_ip(const char *ip);
int get_acl_mode(void);
void init_block_list(int firewall);
void free_block_list();
int check_block_list(char *addr);
int update_block_list(char *addr, int err_level);
int remove_from_block_list(char *addr);
int outbound_block_match_host(const char *host);
#endif // _ACL_H
|
281677160/openwrt-package | 1,574 | luci-app-ssr-plus/shadowsocksr-libev/src/src/protocol.h | /*
* Copyright (c) 2014, Dustin Lundquist <dustin@null-ptr.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PROTOCOL_H
#define PROTOCOL_H
typedef struct protocol {
const int default_port;
int(*const parse_packet)(const char *, size_t, char **);
} protocol_t;
#endif
|
281677160/openwrt-package | 44,272 | luci-app-ssr-plus/shadowsocksr-libev/src/src/udprelay.c | /*
* udprelay.c - Setup UDP relay for both client and server
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <locale.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#ifndef __MINGW32__
#include <arpa/inet.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H) && defined(__linux__)
#include <net/if.h>
#include <sys/ioctl.h>
#define SET_INTERFACE
#endif
#ifdef __MINGW32__
#include "win32.h"
#endif
#include <libcork/core.h>
#include <udns.h>
#include "utils.h"
#include "netutils.h"
#include "cache.h"
#include "udprelay.h"
#include "encrypt.h"
#ifdef MODULE_REMOTE
#define MAX_UDP_CONN_NUM 512
#else
#define MAX_UDP_CONN_NUM 256
#endif
#ifdef MODULE_REMOTE
#ifdef MODULE_
#error "MODULE_REMOTE and MODULE_LOCAL should not be both defined"
#endif
#endif
#ifndef EAGAIN
#define EAGAIN EWOULDBLOCK
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK EAGAIN
#endif
static void server_recv_cb(EV_P_ ev_io *w, int revents);
static void remote_recv_cb(EV_P_ ev_io *w, int revents);
static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents);
static char *hash_key(const int af, const struct sockaddr_storage *addr);
#ifdef MODULE_REMOTE
static void query_resolve_cb(struct sockaddr *addr, void *data);
#endif
static void close_and_free_remote(EV_P_ remote_ctx_t *ctx);
static remote_ctx_t *new_remote(int fd, server_ctx_t *server_ctx);
#ifdef ANDROID
extern int log_tx_rx;
extern uint64_t tx;
extern uint64_t rx;
extern int vpn;
#endif
extern int verbose;
#ifdef MODULE_REMOTE
extern uint64_t tx;
extern uint64_t rx;
#endif
static int packet_size = DEFAULT_PACKET_SIZE;
static int buf_size = DEFAULT_PACKET_SIZE * 2;
static int server_num = 0;
static server_ctx_t *server_ctx_list[MAX_REMOTE_NUM] = { NULL };
#ifndef __MINGW32__
static int
setnonblocking(int fd)
{
int flags;
if (-1 == (flags = fcntl(fd, F_GETFL, 0))) {
flags = 0;
}
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
#endif
#if defined(MODULE_REMOTE) && defined(SO_BROADCAST)
static int
set_broadcast(int socket_fd)
{
int opt = 1;
return setsockopt(socket_fd, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(opt));
}
#endif
#ifdef SO_NOSIGPIPE
static int
set_nosigpipe(int socket_fd)
{
int opt = 1;
return setsockopt(socket_fd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
}
#endif
#ifdef MODULE_REDIR
#ifndef IP_TRANSPARENT
#define IP_TRANSPARENT 19
#endif
#ifndef IP_RECVORIGDSTADDR
#ifdef IP_ORIGDSTADDR
# define IP_RECVORIGDSTADDR IP_ORIGDSTADDR
#else
# define IP_RECVORIGDSTADDR 20
# endif
#endif
#ifndef IPV6_RECVORIGDSTADDR
#ifdef IPV6_ORIGDSTADDR
#define IPV6_RECVORIGDSTADDR IPV6_ORIGDSTADDR
#else
#define IPV6_RECVORIGDSTADDR 74
#endif
#endif
static int
get_dstaddr(struct msghdr *msg, struct sockaddr_storage *dstaddr)
{
struct cmsghdr *cmsg;
for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
if (cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_RECVORIGDSTADDR) {
memcpy(dstaddr, CMSG_DATA(cmsg), sizeof(struct sockaddr_in));
dstaddr->ss_family = AF_INET;
return 0;
} else if (cmsg->cmsg_level == SOL_IPV6 && cmsg->cmsg_type == IPV6_RECVORIGDSTADDR) {
memcpy(dstaddr, CMSG_DATA(cmsg), sizeof(struct sockaddr_in6));
dstaddr->ss_family = AF_INET6;
return 0;
}
}
return 1;
}
#endif
#define HASH_KEY_LEN sizeof(struct sockaddr_storage) + sizeof(int)
static char *
hash_key(const int af, const struct sockaddr_storage *addr)
{
size_t addr_len = sizeof(struct sockaddr_storage);
static char key[HASH_KEY_LEN];
memset(key, 0, HASH_KEY_LEN);
memcpy(key, &af, sizeof(int));
memcpy(key + sizeof(int), (const uint8_t *)addr, addr_len);
return key;
}
#if defined(MODULE_REDIR) || defined(MODULE_REMOTE)
static int
construct_udprealy_header(const struct sockaddr_storage *in_addr,
char *addr_header)
{
int addr_header_len = 0;
if (in_addr->ss_family == AF_INET) {
struct sockaddr_in *addr = (struct sockaddr_in *)in_addr;
size_t addr_len = sizeof(struct in_addr);
addr_header[addr_header_len++] = 1;
memcpy(addr_header + addr_header_len, &addr->sin_addr, addr_len);
addr_header_len += addr_len;
memcpy(addr_header + addr_header_len, &addr->sin_port, 2);
addr_header_len += 2;
} else if (in_addr->ss_family == AF_INET6) {
struct sockaddr_in6 *addr = (struct sockaddr_in6 *)in_addr;
size_t addr_len = sizeof(struct in6_addr);
addr_header[addr_header_len++] = 4;
memcpy(addr_header + addr_header_len, &addr->sin6_addr, addr_len);
addr_header_len += addr_len;
memcpy(addr_header + addr_header_len, &addr->sin6_port, 2);
addr_header_len += 2;
} else {
return 0;
}
return addr_header_len;
}
#endif
static int
parse_udprealy_header(const char *buf, const size_t buf_len,
char *host, char *port, struct sockaddr_storage *storage)
{
const uint8_t atyp = *(uint8_t *)buf;
int offset = 1;
// get remote addr and port
if ((atyp & ADDRTYPE_MASK) == 1) {
// IP V4
size_t in_addr_len = sizeof(struct in_addr);
if (buf_len >= in_addr_len + 3) {
if (storage != NULL) {
struct sockaddr_in *addr = (struct sockaddr_in *)storage;
addr->sin_family = AF_INET;
addr->sin_addr = *(struct in_addr *)(buf + offset);
addr->sin_port = *(uint16_t *)(buf + offset + in_addr_len);
}
if (host != NULL) {
dns_ntop(AF_INET, (const void *)(buf + offset),
host, INET_ADDRSTRLEN);
}
offset += in_addr_len;
}
} else if ((atyp & ADDRTYPE_MASK) == 3) {
// Domain name
uint8_t name_len = *(uint8_t *)(buf + offset);
if (name_len + 4 <= buf_len) {
if (storage != NULL) {
char tmp[257] = { 0 };
struct cork_ip ip;
memcpy(tmp, buf + offset + 1, name_len);
if (cork_ip_init(&ip, tmp) != -1) {
if (ip.version == 4) {
struct sockaddr_in *addr = (struct sockaddr_in *)storage;
dns_pton(AF_INET, tmp, &(addr->sin_addr));
addr->sin_port = *(uint16_t *)(buf + offset + 1 + name_len);
addr->sin_family = AF_INET;
} else if (ip.version == 6) {
struct sockaddr_in6 *addr = (struct sockaddr_in6 *)storage;
dns_pton(AF_INET, tmp, &(addr->sin6_addr));
addr->sin6_port = *(uint16_t *)(buf + offset + 1 + name_len);
addr->sin6_family = AF_INET6;
}
}
}
if (host != NULL) {
memcpy(host, buf + offset + 1, name_len);
}
offset += 1 + name_len;
}
} else if ((atyp & ADDRTYPE_MASK) == 4) {
// IP V6
size_t in6_addr_len = sizeof(struct in6_addr);
if (buf_len >= in6_addr_len + 3) {
if (storage != NULL) {
struct sockaddr_in6 *addr = (struct sockaddr_in6 *)storage;
addr->sin6_family = AF_INET6;
addr->sin6_addr = *(struct in6_addr *)(buf + offset);
addr->sin6_port = *(uint16_t *)(buf + offset + in6_addr_len);
}
if (host != NULL) {
dns_ntop(AF_INET6, (const void *)(buf + offset),
host, INET6_ADDRSTRLEN);
}
offset += in6_addr_len;
}
}
if (offset == 1) {
LOGE("[udp] invalid header with addr type %d", atyp);
return 0;
}
if (port != NULL) {
sprintf(port, "%d", ntohs(*(uint16_t *)(buf + offset)));
}
offset += 2;
return offset;
}
static char *
get_addr_str(const struct sockaddr *sa)
{
static char s[SS_ADDRSTRLEN];
memset(s, 0, SS_ADDRSTRLEN);
char addr[INET6_ADDRSTRLEN] = { 0 };
char port[PORTSTRLEN] = { 0 };
uint16_t p;
switch (sa->sa_family) {
case AF_INET:
dns_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),
addr, INET_ADDRSTRLEN);
p = ntohs(((struct sockaddr_in *)sa)->sin_port);
sprintf(port, "%d", p);
break;
case AF_INET6:
dns_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
addr, INET6_ADDRSTRLEN);
p = ntohs(((struct sockaddr_in *)sa)->sin_port);
sprintf(port, "%d", p);
break;
default:
strncpy(s, "Unknown AF", SS_ADDRSTRLEN);
}
int addr_len = strlen(addr);
int port_len = strlen(port);
memcpy(s, addr, addr_len);
memcpy(s + addr_len + 1, port, port_len);
s[addr_len] = ':';
return s;
}
int
create_remote_socket(int ipv6)
{
int remote_sock;
if (ipv6) {
// Try to bind IPv6 first
struct sockaddr_in6 addr;
memset(&addr, 0, sizeof(struct sockaddr_in6));
addr.sin6_family = AF_INET6;
addr.sin6_addr = in6addr_any;
addr.sin6_port = 0;
remote_sock = socket(AF_INET6, SOCK_DGRAM, 0);
if (remote_sock == -1) {
ERROR("[udp] cannot create socket");
return -1;
}
if (bind(remote_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
FATAL("[udp] cannot bind remote");
return -1;
}
} else {
// Or else bind to IPv4
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = 0;
remote_sock = socket(AF_INET, SOCK_DGRAM, 0);
if (remote_sock == -1) {
ERROR("[udp] cannot create socket");
return -1;
}
if (bind(remote_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
FATAL("[udp] cannot bind remote");
return -1;
}
}
return remote_sock;
}
int
create_server_socket(const char *host, const char *port)
{
struct addrinfo hints;
struct addrinfo *result, *rp, *ipv4v6bindall;
int s, server_sock;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
hints.ai_socktype = SOCK_DGRAM; /* We want a UDP socket */
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; /* For wildcard IP address */
hints.ai_protocol = IPPROTO_UDP;
s = getaddrinfo(host, port, &hints, &result);
if (s != 0) {
LOGE("[udp] getaddrinfo: %s", gai_strerror(s));
return -1;
}
rp = result;
/*
* On Linux, with net.ipv6.bindv6only = 0 (the default), getaddrinfo(NULL) with
* AI_PASSIVE returns 0.0.0.0 and :: (in this order). AI_PASSIVE was meant to
* return a list of addresses to listen on, but it is impossible to listen on
* 0.0.0.0 and :: at the same time, if :: implies dualstack mode.
*/
if (!host) {
ipv4v6bindall = result;
/* Loop over all address infos found until a IPV6 address is found. */
while (ipv4v6bindall) {
if (ipv4v6bindall->ai_family == AF_INET6) {
rp = ipv4v6bindall; /* Take first IPV6 address available */
break;
}
ipv4v6bindall = ipv4v6bindall->ai_next; /* Get next address info, if any */
}
}
if (result == NULL) {
LOGE("[udp] cannot bind");
return -1;
}
for (/*rp = result*/; rp != NULL; rp = rp->ai_next) {
server_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (server_sock == -1) {
continue;
}
if (rp->ai_family == AF_INET6) {
int ipv6only = host ? 1 : 0;
setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6only, sizeof(ipv6only));
}
int opt = 1;
setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
set_nosigpipe(server_sock);
#endif
int err = set_reuseport(server_sock);
if (err == 0) {
LOGI("udp port reuse enabled");
}
#ifdef IP_TOS
// Set QoS flag
int tos = 46;
setsockopt(server_sock, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
#endif
#ifdef MODULE_REDIR
if (setsockopt(server_sock, SOL_IP, IP_TRANSPARENT, &opt, sizeof(opt))) {
ERROR("[udp] setsockopt IP_TRANSPARENT");
exit(EXIT_FAILURE);
}
if (rp->ai_family == AF_INET) {
if (setsockopt(server_sock, SOL_IP, IP_RECVORIGDSTADDR, &opt, sizeof(opt))) {
FATAL("[udp] setsockopt IP_RECVORIGDSTADDR");
}
} else if (rp->ai_family == AF_INET6) {
if (setsockopt(server_sock, SOL_IPV6, IPV6_RECVORIGDSTADDR, &opt, sizeof(opt))) {
FATAL("[udp] setsockopt IPV6_RECVORIGDSTADDR");
}
}
#endif
s = bind(server_sock, rp->ai_addr, rp->ai_addrlen);
if (s == 0) {
/* We managed to bind successfully! */
break;
} else {
ERROR("[udp] bind");
}
close(server_sock);
server_sock = -1;
}
freeaddrinfo(result);
return server_sock;
}
remote_ctx_t *
new_remote(int fd, server_ctx_t *server_ctx)
{
remote_ctx_t *ctx = ss_malloc(sizeof(remote_ctx_t));
memset(ctx, 0, sizeof(remote_ctx_t));
ctx->fd = fd;
ctx->server_ctx = server_ctx;
ev_io_init(&ctx->io, remote_recv_cb, fd, EV_READ);
ev_timer_init(&ctx->watcher, remote_timeout_cb, server_ctx->timeout,
server_ctx->timeout);
return ctx;
}
server_ctx_t *
new_server_ctx(int fd)
{
server_ctx_t *ctx = ss_malloc(sizeof(server_ctx_t));
memset(ctx, 0, sizeof(server_ctx_t));
ctx->fd = fd;
ev_io_init(&ctx->io, server_recv_cb, fd, EV_READ);
return ctx;
}
#ifdef MODULE_REMOTE
struct query_ctx *
new_query_ctx(char *buf, size_t len)
{
struct query_ctx *ctx = ss_malloc(sizeof(struct query_ctx));
memset(ctx, 0, sizeof(struct query_ctx));
ctx->buf = ss_malloc(sizeof(buffer_t));
balloc(ctx->buf, len);
memcpy(ctx->buf->array, buf, len);
ctx->buf->len = len;
return ctx;
}
void
close_and_free_query(EV_P_ struct query_ctx *ctx)
{
if (ctx != NULL) {
if (ctx->query != NULL) {
resolv_cancel(ctx->query);
ctx->query = NULL;
}
if (ctx->buf != NULL) {
bfree(ctx->buf);
ss_free(ctx->buf);
}
ss_free(ctx);
}
}
#endif
void
close_and_free_remote(EV_P_ remote_ctx_t *ctx)
{
if (ctx != NULL) {
ev_timer_stop(EV_A_ & ctx->watcher);
ev_io_stop(EV_A_ & ctx->io);
close(ctx->fd);
ss_free(ctx);
}
}
static void
remote_timeout_cb(EV_P_ ev_timer *watcher, int revents)
{
remote_ctx_t *remote_ctx
= cork_container_of(watcher, remote_ctx_t, watcher);
if (verbose) {
LOGI("[udp] connection timeout");
}
char *key = hash_key(remote_ctx->af, &remote_ctx->src_addr);
cache_remove(remote_ctx->server_ctx->conn_cache, key, HASH_KEY_LEN);
}
#ifdef MODULE_REMOTE
static void
query_resolve_cb(struct sockaddr *addr, void *data)
{
struct query_ctx *query_ctx = (struct query_ctx *)data;
struct ev_loop *loop = query_ctx->server_ctx->loop;
if (verbose) {
LOGI("[udp] udns resolved");
}
query_ctx->query = NULL;
if (addr == NULL) {
LOGE("[udp] udns returned an error");
} else {
remote_ctx_t *remote_ctx = query_ctx->remote_ctx;
int cache_hit = 0;
// Lookup in the conn cache
if (remote_ctx == NULL) {
char *key = hash_key(AF_UNSPEC, &query_ctx->src_addr);
cache_lookup(query_ctx->server_ctx->conn_cache, key, HASH_KEY_LEN, (void *)&remote_ctx);
}
if (remote_ctx == NULL) {
int remotefd = create_remote_socket(addr->sa_family == AF_INET6);
if (remotefd != -1) {
setnonblocking(remotefd);
#ifdef SO_BROADCAST
set_broadcast(remotefd);
#endif
#ifdef SO_NOSIGPIPE
set_nosigpipe(remotefd);
#endif
#ifdef IP_TOS
// Set QoS flag
int tos = 46;
setsockopt(remotefd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
#endif
#ifdef SET_INTERFACE
if (query_ctx->server_ctx->iface) {
if (setinterface(remotefd, query_ctx->server_ctx->iface) == -1)
ERROR("setinterface");
}
#endif
remote_ctx = new_remote(remotefd, query_ctx->server_ctx);
remote_ctx->src_addr = query_ctx->src_addr;
remote_ctx->server_ctx = query_ctx->server_ctx;
remote_ctx->addr_header_len = query_ctx->addr_header_len;
memcpy(remote_ctx->addr_header, query_ctx->addr_header,
query_ctx->addr_header_len);
} else {
ERROR("[udp] bind() error");
}
} else {
cache_hit = 1;
}
if (remote_ctx != NULL) {
memcpy(&remote_ctx->dst_addr, addr, sizeof(struct sockaddr_storage));
size_t addr_len = get_sockaddr_len(addr);
int s = sendto(remote_ctx->fd, query_ctx->buf->array, query_ctx->buf->len,
0, addr, addr_len);
if (s == -1) {
ERROR("[udp] sendto_remote");
if (!cache_hit) {
close_and_free_remote(EV_A_ remote_ctx);
}
} else {
if (!cache_hit) {
// Add to conn cache
char *key = hash_key(AF_UNSPEC, &remote_ctx->src_addr);
cache_insert(query_ctx->server_ctx->conn_cache, key, HASH_KEY_LEN, (void *)remote_ctx);
ev_io_start(EV_A_ & remote_ctx->io);
ev_timer_start(EV_A_ & remote_ctx->watcher);
}
}
}
}
// clean up
close_and_free_query(EV_A_ query_ctx);
}
#endif
static void
remote_recv_cb(EV_P_ ev_io *w, int revents)
{
ssize_t r;
remote_ctx_t *remote_ctx = (remote_ctx_t *)w;
server_ctx_t *server_ctx = remote_ctx->server_ctx;
// server has been closed
if (server_ctx == NULL) {
LOGE("[udp] invalid server");
close_and_free_remote(EV_A_ remote_ctx);
return;
}
struct sockaddr_storage src_addr;
socklen_t src_addr_len = sizeof(struct sockaddr_storage);
memset(&src_addr, 0, src_addr_len);
buffer_t *buf = ss_malloc(sizeof(buffer_t));
balloc(buf, buf_size);
// recv
r = recvfrom(remote_ctx->fd, buf->array, buf_size, 0, (struct sockaddr *)&src_addr, &src_addr_len);
if (r == -1) {
// error on recv
// simply drop that packet
ERROR("[udp] remote_recv_recvfrom");
goto CLEAN_UP;
} else if (r > packet_size) {
LOGE("[udp] remote_recv_recvfrom fragmentation");
goto CLEAN_UP;
}
buf->len = r;
#ifdef MODULE_LOCAL
int err = ss_decrypt_all(server_ctx->cipher_env, buf, buf_size);
if (err) {
// drop the packet silently
goto CLEAN_UP;
}
//SSR beg
if (server_ctx->protocol_plugin) {
obfs_class *protocol_plugin = server_ctx->protocol_plugin;
if (protocol_plugin->client_udp_post_decrypt) {
buf->len = protocol_plugin->client_udp_post_decrypt(server_ctx->protocol, &buf->array, buf->len, &buf->capacity);
if ((int)buf->len < 0) {
LOGE("client_udp_post_decrypt");
close_and_free_remote(EV_A_ remote_ctx);
return;
}
if ( buf->len == 0 )
return;
}
}
// SSR end
#ifdef MODULE_REDIR
struct sockaddr_storage dst_addr;
memset(&dst_addr, 0, sizeof(struct sockaddr_storage));
int len = parse_udprealy_header(buf->array, buf->len, NULL, NULL, &dst_addr);
if (dst_addr.ss_family != AF_INET && dst_addr.ss_family != AF_INET6) {
LOGI("[udp] ss-redir does not support domain name");
goto CLEAN_UP;
}
if (verbose) {
char src[SS_ADDRSTRLEN];
char dst[SS_ADDRSTRLEN];
strcpy(src, get_addr_str((struct sockaddr *)&src_addr));
strcpy(dst, get_addr_str((struct sockaddr *)&dst_addr));
LOGI("[udp] recv %s via %s", dst, src);
}
#else
int len = parse_udprealy_header(buf->array, buf->len, NULL, NULL, NULL);
#endif
if (len == 0) {
LOGI("[udp] error in parse header");
// error in parse header
goto CLEAN_UP;
}
// server may return using a different address type other than the type we
// have used during sending
#if defined(MODULE_TUNNEL) || defined(MODULE_REDIR)
// Construct packet
buf->len -= len;
memmove(buf->array, buf->array + len, buf->len);
#else
#ifdef ANDROID
if (r > 0 && log_tx_rx)
rx += r;
#endif
// Construct packet
if (server_ctx->tunnel_addr.host && server_ctx->tunnel_addr.port) {
buf->len -= len;
memmove(buf->array, buf->array + len, buf->len);
} else {
brealloc(buf, buf->len + 3, buf_size);
memmove(buf->array + 3, buf->array, buf->len);
memset(buf->array, 0, 3);
buf->len += 3;
}
#endif
#endif
#ifdef MODULE_REMOTE
rx += buf->len;
char addr_header_buf[512];
char *addr_header = remote_ctx->addr_header;
int addr_header_len = remote_ctx->addr_header_len;
if (remote_ctx->af == AF_INET || remote_ctx->af == AF_INET6) {
addr_header_len = construct_udprealy_header(&src_addr, addr_header_buf);
addr_header = addr_header_buf;
}
// Construct packet
brealloc(buf, buf->len + addr_header_len, buf_size);
memmove(buf->array + addr_header_len, buf->array, buf->len);
memcpy(buf->array, addr_header, addr_header_len);
buf->len += addr_header_len;
int err = ss_decrypt_all(server_ctx->cipher_env, buf, buf_size);
if (err) {
// drop the packet silently
goto CLEAN_UP;
}
#endif
if (buf->len > packet_size) {
LOGE("[udp] remote_recv_sendto fragmentation");
goto CLEAN_UP;
}
size_t remote_src_addr_len = get_sockaddr_len((struct sockaddr *)&remote_ctx->src_addr);
#ifdef MODULE_REDIR
size_t remote_dst_addr_len = get_sockaddr_len((struct sockaddr *)&dst_addr);
int src_fd = socket(remote_ctx->src_addr.ss_family, SOCK_DGRAM, 0);
if (src_fd < 0) {
ERROR("[udp] remote_recv_socket");
goto CLEAN_UP;
}
int opt = 1;
if (setsockopt(src_fd, SOL_IP, IP_TRANSPARENT, &opt, sizeof(opt))) {
ERROR("[udp] remote_recv_setsockopt");
close(src_fd);
goto CLEAN_UP;
}
if (setsockopt(src_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
ERROR("[udp] remote_recv_setsockopt");
close(src_fd);
goto CLEAN_UP;
}
#ifdef IP_TOS
// Set QoS flag
int tos = 46;
setsockopt(src_fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
#endif
if (bind(src_fd, (struct sockaddr *)&dst_addr, remote_dst_addr_len) != 0) {
ERROR("[udp] remote_recv_bind");
close(src_fd);
goto CLEAN_UP;
}
int s = sendto(src_fd, buf->array, buf->len, 0,
(struct sockaddr *)&remote_ctx->src_addr, remote_src_addr_len);
if (s == -1) {
ERROR("[udp] remote_recv_sendto");
close(src_fd);
goto CLEAN_UP;
}
close(src_fd);
#else
int s = sendto(server_ctx->fd, buf->array, buf->len, 0,
(struct sockaddr *)&remote_ctx->src_addr, remote_src_addr_len);
if (s == -1) {
ERROR("[udp] remote_recv_sendto");
goto CLEAN_UP;
}
#endif
// handle the UDP packet successfully,
// triger the timer
ev_timer_again(EV_A_ & remote_ctx->watcher);
CLEAN_UP:
bfree(buf);
ss_free(buf);
}
static void
server_recv_cb(EV_P_ ev_io *w, int revents)
{
server_ctx_t *server_ctx = (server_ctx_t *)w;
struct sockaddr_storage src_addr;
memset(&src_addr, 0, sizeof(struct sockaddr_storage));
buffer_t *buf = ss_malloc(sizeof(buffer_t));
balloc(buf, buf_size);
socklen_t src_addr_len = sizeof(struct sockaddr_storage);
unsigned int offset = 0;
#ifdef MODULE_REDIR
char control_buffer[64] = { 0 };
struct msghdr msg;
memset(&msg, 0, sizeof(struct msghdr));
struct iovec iov[1];
struct sockaddr_storage dst_addr;
memset(&dst_addr, 0, sizeof(struct sockaddr_storage));
msg.msg_name = &src_addr;
msg.msg_namelen = src_addr_len;
msg.msg_control = control_buffer;
msg.msg_controllen = sizeof(control_buffer);
iov[0].iov_base = buf->array;
iov[0].iov_len = buf_size;
msg.msg_iov = iov;
msg.msg_iovlen = 1;
buf->len = recvmsg(server_ctx->fd, &msg, 0);
if (buf->len == -1) {
ERROR("[udp] server_recvmsg");
goto CLEAN_UP;
} else if (buf->len > packet_size) {
ERROR("[udp] UDP server_recv_recvmsg fragmentation");
goto CLEAN_UP;
}
if (get_dstaddr(&msg, &dst_addr)) {
LOGE("[udp] unable to get dest addr");
goto CLEAN_UP;
}
src_addr_len = msg.msg_namelen;
#else
ssize_t r;
r = recvfrom(server_ctx->fd, buf->array, buf_size,
0, (struct sockaddr *)&src_addr, &src_addr_len);
if (r == -1) {
// error on recv
// simply drop that packet
ERROR("[udp] server_recv_recvfrom");
goto CLEAN_UP;
} else if (r > packet_size) {
ERROR("[udp] server_recv_recvfrom fragmentation");
goto CLEAN_UP;
}
buf->len = r;
#endif
#ifdef MODULE_REMOTE
tx += buf->len;
int err = ss_decrypt_all(server_ctx->cipher_env, buf, buf_size);
if (err) {
// drop the packet silently
goto CLEAN_UP;
}
#endif
/*
*
* SOCKS5 UDP Request
* +----+------+------+----------+----------+----------+
* |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
* +----+------+------+----------+----------+----------+
* | 2 | 1 | 1 | Variable | 2 | Variable |
* +----+------+------+----------+----------+----------+
*
* SOCKS5 UDP Response
* +----+------+------+----------+----------+----------+
* |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
* +----+------+------+----------+----------+----------+
* | 2 | 1 | 1 | Variable | 2 | Variable |
* +----+------+------+----------+----------+----------+
*
* shadowsocks UDP Request (before encrypted)
* +------+----------+----------+----------+
* | ATYP | DST.ADDR | DST.PORT | DATA |
* +------+----------+----------+----------+
* | 1 | Variable | 2 | Variable |
* +------+----------+----------+----------+
*
* shadowsocks UDP Response (before encrypted)
* +------+----------+----------+----------+
* | ATYP | DST.ADDR | DST.PORT | DATA |
* +------+----------+----------+----------+
* | 1 | Variable | 2 | Variable |
* +------+----------+----------+----------+
*
* shadowsocks UDP Request and Response (after encrypted)
* +-------+--------------+
* | IV | PAYLOAD |
* +-------+--------------+
* | Fixed | Variable |
* +-------+--------------+
*
*/
#ifdef MODULE_REDIR
if (verbose) {
char src[SS_ADDRSTRLEN];
char dst[SS_ADDRSTRLEN];
strcpy(src, get_addr_str((struct sockaddr *)&src_addr));
strcpy(dst, get_addr_str((struct sockaddr *)&dst_addr));
LOGI("[udp] redir to %s from %s", dst, src);
}
char addr_header[512] = { 0 };
int addr_header_len = construct_udprealy_header(&dst_addr, addr_header);
if (addr_header_len == 0) {
LOGE("[udp] failed to parse tproxy addr");
goto CLEAN_UP;
}
// reconstruct the buffer
brealloc(buf, buf->len + addr_header_len, buf_size);
memmove(buf->array + addr_header_len, buf->array, buf->len);
memcpy(buf->array, addr_header, addr_header_len);
buf->len += addr_header_len;
#else
char addr_header[512] = { 0 };
int addr_header_len = 0;
uint8_t frag = 0;
char host[257] = { 0 };
char port[65] = { 0 };
if (server_ctx->tunnel_addr.host && server_ctx->tunnel_addr.port) {
strncpy(host, server_ctx->tunnel_addr.host, 256);
strncpy(port, server_ctx->tunnel_addr.port, 64);
uint16_t port_num = (uint16_t)atoi(port);
uint16_t port_net_num = htons(port_num);
struct cork_ip ip;
if (cork_ip_init(&ip, host) != -1) {
if (ip.version == 4) {
// send as IPv4
struct in_addr host_addr;
memset(&host_addr, 0, sizeof(struct in_addr));
int host_len = sizeof(struct in_addr);
if (dns_pton(AF_INET, host, &host_addr) == -1) {
FATAL("IP parser error");
}
addr_header[addr_header_len++] = 1;
memcpy(addr_header + addr_header_len, &host_addr, host_len);
addr_header_len += host_len;
} else if (ip.version == 6) {
// send as IPv6
struct in6_addr host_addr;
memset(&host_addr, 0, sizeof(struct in6_addr));
int host_len = sizeof(struct in6_addr);
if (dns_pton(AF_INET6, host, &host_addr) == -1) {
FATAL("IP parser error");
}
addr_header[addr_header_len++] = 4;
memcpy(addr_header + addr_header_len, &host_addr, host_len);
addr_header_len += host_len;
} else {
FATAL("IP parser error");
}
} else {
// send as domain
int host_len = strlen(host);
addr_header[addr_header_len++] = 3;
addr_header[addr_header_len++] = host_len;
memcpy(addr_header + addr_header_len, host, host_len);
addr_header_len += host_len;
}
memcpy(addr_header + addr_header_len, &port_net_num, 2);
addr_header_len += 2;
// reconstruct the buffer
brealloc(buf, buf->len + addr_header_len, buf_size);
memmove(buf->array + addr_header_len, buf->array, buf->len);
memcpy(buf->array, addr_header, addr_header_len);
buf->len += addr_header_len;
} else {
frag = *(uint8_t *)(buf->array + 2);
offset += 3;
struct sockaddr_storage dst_addr;
memset(&dst_addr, 0, sizeof(struct sockaddr_storage));
addr_header_len = parse_udprealy_header(buf->array + offset, buf->len - offset,
host, port, &dst_addr);
if (addr_header_len == 0) {
// error in parse header
goto CLEAN_UP;
}
strncpy(addr_header, buf->array + offset, addr_header_len);
}
#endif
#ifdef MODULE_LOCAL
char *key = hash_key(server_ctx->remote_addr->sa_family, &src_addr);
#else
char *key = hash_key(dst_addr.ss_family, &src_addr);
#endif
struct cache *conn_cache = server_ctx->conn_cache;
remote_ctx_t *remote_ctx = NULL;
cache_lookup(conn_cache, key, HASH_KEY_LEN, (void *)&remote_ctx);
if (remote_ctx != NULL) {
if (sockaddr_cmp(&src_addr, &remote_ctx->src_addr, sizeof(src_addr))) {
remote_ctx = NULL;
}
}
// reset the timer
if (remote_ctx != NULL) {
ev_timer_again(EV_A_ & remote_ctx->watcher);
}
if (remote_ctx == NULL) {
if (verbose) {
#ifdef MODULE_REDIR
char src[SS_ADDRSTRLEN];
char dst[SS_ADDRSTRLEN];
strcpy(src, get_addr_str((struct sockaddr *)&src_addr));
strcpy(dst, get_addr_str((struct sockaddr *)&dst_addr));
LOGI("[udp] cache miss: %s <-> %s", dst, src);
#else
LOGI("[udp] cache miss: %s:%s <-> %s", host, port,
get_addr_str((struct sockaddr *)&src_addr));
#endif
}
} else {
if (verbose) {
#ifdef MODULE_REDIR
char src[SS_ADDRSTRLEN];
char dst[SS_ADDRSTRLEN];
strcpy(src, get_addr_str((struct sockaddr *)&src_addr));
strcpy(dst, get_addr_str((struct sockaddr *)&dst_addr));
LOGI("[udp] cache hit: %s <-> %s", dst, src);
#else
LOGI("[udp] cache hit: %s:%s <-> %s", host, port,
get_addr_str((struct sockaddr *)&src_addr));
#endif
}
}
#ifdef MODULE_LOCAL
#if !defined(MODULE_TUNNEL) && !defined(MODULE_REDIR)
if (frag) {
LOGE("[udp] drop a message since frag is not 0, but %d", frag);
goto CLEAN_UP;
}
#endif
const struct sockaddr *remote_addr = server_ctx->remote_addr;
const int remote_addr_len = server_ctx->remote_addr_len;
if (remote_ctx == NULL) {
// Bind to any port
int remotefd = create_remote_socket(remote_addr->sa_family == AF_INET6);
if (remotefd < 0) {
ERROR("[udp] udprelay bind() error");
goto CLEAN_UP;
}
setnonblocking(remotefd);
#ifdef SO_NOSIGPIPE
set_nosigpipe(remotefd);
#endif
#ifdef IP_TOS
// Set QoS flag
int tos = 46;
setsockopt(remotefd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
#endif
#ifdef SET_INTERFACE
if (server_ctx->iface) {
if (setinterface(remotefd, server_ctx->iface) == -1)
ERROR("setinterface");
}
#endif
#ifdef ANDROID
if (vpn) {
if (protect_socket(remotefd) == -1) {
ERROR("protect_socket");
close(remotefd);
goto CLEAN_UP;
}
}
#endif
// Init remote_ctx
remote_ctx = new_remote(remotefd, server_ctx);
remote_ctx->src_addr = src_addr;
remote_ctx->af = remote_addr->sa_family;
remote_ctx->addr_header_len = addr_header_len;
memcpy(remote_ctx->addr_header, addr_header, addr_header_len);
// Add to conn cache
cache_insert(conn_cache, key, HASH_KEY_LEN, (void *)remote_ctx);
// Start remote io
ev_io_start(EV_A_ & remote_ctx->io);
ev_timer_start(EV_A_ & remote_ctx->watcher);
}
if (offset > 0) {
buf->len -= offset;
memmove(buf->array, buf->array + offset, buf->len);
}
// SSR beg
if (server_ctx->protocol_plugin) {
obfs_class *protocol_plugin = server_ctx->protocol_plugin;
if (protocol_plugin->client_udp_pre_encrypt) {
buf->len = protocol_plugin->client_udp_pre_encrypt(server_ctx->protocol, &buf->array, buf->len, &buf->capacity);
}
}
//SSR end
int err = ss_encrypt_all(server_ctx->cipher_env, buf, buf->len);
if (err) {
// drop the packet silently
goto CLEAN_UP;
}
if (buf->len > packet_size) {
LOGE("[udp] server_recv_sendto fragmentation");
goto CLEAN_UP;
}
int s = sendto(remote_ctx->fd, buf->array, buf->len, 0, remote_addr, remote_addr_len);
if (s == -1) {
ERROR("[udp] server_recv_sendto");
}
#if !defined(MODULE_TUNNEL) && !defined(MODULE_REDIR)
#ifdef ANDROID
if (log_tx_rx)
tx += buf->len;
#endif
#endif
#else
int cache_hit = 0;
int need_query = 0;
if (buf->len - addr_header_len > packet_size) {
LOGE("[udp] server_recv_sendto fragmentation");
goto CLEAN_UP;
}
if (remote_ctx != NULL) {
cache_hit = 1;
// detect destination mismatch
if (remote_ctx->addr_header_len != addr_header_len
|| memcmp(addr_header, remote_ctx->addr_header, addr_header_len) != 0) {
if (dst_addr.ss_family != AF_INET && dst_addr.ss_family != AF_INET6) {
need_query = 1;
}
} else {
memcpy(&dst_addr, &remote_ctx->dst_addr, sizeof(struct sockaddr_storage));
}
} else {
if (dst_addr.ss_family == AF_INET || dst_addr.ss_family == AF_INET6) {
int remotefd = create_remote_socket(dst_addr.ss_family == AF_INET6);
if (remotefd != -1) {
setnonblocking(remotefd);
#ifdef SO_BROADCAST
set_broadcast(remotefd);
#endif
#ifdef SO_NOSIGPIPE
set_nosigpipe(remotefd);
#endif
#ifdef IP_TOS
// Set QoS flag
int tos = 46;
setsockopt(remotefd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
#endif
#ifdef SET_INTERFACE
if (server_ctx->iface) {
if (setinterface(remotefd, server_ctx->iface) == -1)
ERROR("setinterface");
}
#endif
remote_ctx = new_remote(remotefd, server_ctx);
remote_ctx->src_addr = src_addr;
remote_ctx->server_ctx = server_ctx;
remote_ctx->addr_header_len = addr_header_len;
memcpy(remote_ctx->addr_header, addr_header, addr_header_len);
memcpy(&remote_ctx->dst_addr, &dst_addr, sizeof(struct sockaddr_storage));
} else {
ERROR("[udp] bind() error");
goto CLEAN_UP;
}
}
}
if (remote_ctx != NULL && !need_query) {
size_t addr_len = get_sockaddr_len((struct sockaddr *)&dst_addr);
int s = sendto(remote_ctx->fd, buf->array + addr_header_len,
buf->len - addr_header_len, 0,
(struct sockaddr *)&dst_addr, addr_len);
if (s == -1) {
ERROR("[udp] sendto_remote");
if (!cache_hit) {
close_and_free_remote(EV_A_ remote_ctx);
}
} else {
if (!cache_hit) {
// Add to conn cache
remote_ctx->af = dst_addr.ss_family;
char *key = hash_key(remote_ctx->af, &remote_ctx->src_addr);
cache_insert(server_ctx->conn_cache, key, HASH_KEY_LEN, (void *)remote_ctx);
ev_io_start(EV_A_ & remote_ctx->io);
ev_timer_start(EV_A_ & remote_ctx->watcher);
}
}
} else {
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
struct query_ctx *query_ctx = new_query_ctx(buf->array + addr_header_len,
buf->len - addr_header_len);
query_ctx->server_ctx = server_ctx;
query_ctx->addr_header_len = addr_header_len;
query_ctx->src_addr = src_addr;
memcpy(query_ctx->addr_header, addr_header, addr_header_len);
if (need_query) {
query_ctx->remote_ctx = remote_ctx;
}
struct ResolvQuery *query = resolv_query(host, query_resolve_cb,
NULL, query_ctx, htons(atoi(port)));
if (query == NULL) {
ERROR("[udp] unable to create DNS query");
close_and_free_query(EV_A_ query_ctx);
goto CLEAN_UP;
}
query_ctx->query = query;
}
#endif
CLEAN_UP:
bfree(buf);
ss_free(buf);
}
void
free_cb(void *key, void *element)
{
remote_ctx_t *remote_ctx = (remote_ctx_t *)element;
if (verbose) {
LOGI("[udp] one connection freed");
}
close_and_free_remote(EV_DEFAULT, remote_ctx);
}
int
init_udprelay(const char *server_host, const char *server_port,
#ifdef MODULE_LOCAL
const struct sockaddr *remote_addr, const int remote_addr_len,
const ss_addr_t tunnel_addr,
#endif
int mtu, int timeout, const char *iface,
cipher_env_t* cipher_env, const char *protocol, const char *protocol_param)
{
// Initialize ev loop
struct ev_loop *loop = EV_DEFAULT;
// Initialize MTU
if (mtu > 0) {
packet_size = mtu - 1 - 28 - 2 - 64;
buf_size = packet_size * 2;
}
// Initialize cache
struct cache *conn_cache;
cache_create(&conn_cache, MAX_UDP_CONN_NUM, free_cb);
// ////////////////////////////////////////////////
// Setup server context
// Bind to port
int serverfd = create_server_socket(server_host, server_port);
if (serverfd < 0) {
FATAL("[udp] bind() error");
}
setnonblocking(serverfd);
server_ctx_t *server_ctx = new_server_ctx(serverfd);
server_ctx->cipher_env = cipher_env;
#ifdef MODULE_REMOTE
server_ctx->loop = loop;
#endif
server_ctx->timeout = max(timeout, MIN_UDP_TIMEOUT);
server_ctx->iface = iface;
server_ctx->conn_cache = conn_cache;
#ifdef MODULE_LOCAL
server_ctx->remote_addr = remote_addr;
server_ctx->remote_addr_len = remote_addr_len;
//SSR beg
server_ctx->protocol_plugin = new_obfs_class((char *)protocol);
if (server_ctx->protocol_plugin) {
server_ctx->protocol = server_ctx->protocol_plugin->new_obfs();
server_ctx->protocol_global = server_ctx->protocol_plugin->init_data();
}
server_info _server_info;
memset(&_server_info, 0, sizeof(server_info));
strcpy(_server_info.host, server_host);
_server_info.port = atoi(server_port);
_server_info.g_data = server_ctx->protocol_global;
_server_info.param = (char *)protocol_param;
_server_info.key = enc_get_key(cipher_env);
_server_info.key_len = enc_get_key_len(cipher_env);
if (server_ctx->protocol_plugin)
server_ctx->protocol_plugin->set_server_info(server_ctx->protocol, &_server_info);
//SSR end
server_ctx->tunnel_addr = tunnel_addr;
#endif
ev_io_start(loop, &server_ctx->io);
server_ctx_list[server_num++] = server_ctx;
return 0;
}
void
free_udprelay()
{
struct ev_loop *loop = EV_DEFAULT;
while (server_num-- > 0) {
server_ctx_t *server_ctx = server_ctx_list[server_num];
#ifdef MODULE_LOCAL
//SSR beg
if (server_ctx->protocol_plugin) {
server_ctx->protocol_plugin->dispose(server_ctx->protocol);
server_ctx->protocol = NULL;
free_obfs_class(server_ctx->protocol_plugin);
server_ctx->protocol_plugin = NULL;
}
//SSR end
#endif
ev_io_stop(loop, &server_ctx->io);
close(server_ctx->fd);
cache_delete(server_ctx->conn_cache, 0);
ss_free(server_ctx);
server_ctx_list[server_num] = NULL;
}
}
|
281677160/openwrt-package | 2,622 | luci-app-ssr-plus/shadowsocksr-libev/src/src/redir.h | /*
* redir.h - Define the redirector's buffers and callbacks
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _LOCAL_H
#define _LOCAL_H
#include <ev.h>
#include "encrypt.h"
#include "obfs/obfs.h"
#include "jconf.h"
#include "common.h"
typedef struct listen_ctx {
ev_io io;
struct cork_dllist_item entries; // for inactive profile list
struct cork_dllist connections_eden; // For connections just created but not attach to a server
// int remote_num;
int timeout;
int fd;
// int method;
int mptcp;
// struct sockaddr **remote_addr;
// // SSR
// char *protocol_name;
// char *protocol_param;
// char *obfs_name;
// char *obfs_param;
// void **list_protocol_global;
// void **list_obfs_global;
int server_num;
server_def_t servers[MAX_SERVER_NUM];
} listen_ctx_t;
typedef struct server_ctx {
ev_io io;
int connected;
struct server *server;
} server_ctx_t;
typedef struct remote_ctx {
ev_io io;
ev_timer watcher;
int connected;
struct remote *remote;
} remote_ctx_t;
typedef struct remote {
int fd;
buffer_t *buf;
struct remote_ctx *recv_ctx;
struct remote_ctx *send_ctx;
uint32_t counter;
struct server *server;
// // SSR
// int remote_index;
} remote_t;
typedef struct server {
int fd;
buffer_t *buf;
struct sockaddr_storage destaddr;
enc_ctx_t *e_ctx;
enc_ctx_t *d_ctx;
server_ctx_t *recv_ctx;
server_ctx_t *send_ctx;
listen_ctx_t *listener;
remote_t *remote;
char *hostname;
size_t hostname_len;
struct cork_dllist_item entries;
struct cork_dllist_item entries_all; // for all_connections
server_def_t *server_env;
// SSR
obfs *protocol;
obfs *obfs;
// obfs_class *protocol_plugin;
// obfs_class *obfs_plugin;
} server_t;
#endif // _LOCAL_H
|
281677160/openwrt-package | 2,778 | luci-app-ssr-plus/shadowsocksr-libev/src/src/common.h | /*
* common.h - Provide global definitions
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _COMMON_H
#define _COMMON_H
#define DEFAULT_CONF_PATH "/etc/shadowsocks-libev/config.json"
#ifndef SOL_TCP
#define SOL_TCP IPPROTO_TCP
#endif
#if defined(MODULE_TUNNEL) || defined(MODULE_REDIR)
#define MODULE_LOCAL
#endif
#include <libcork/ds.h>
#include "encrypt.h"
#include "obfs/obfs.h"
int init_udprelay(const char *server_host, const char *server_port,
#ifdef MODULE_LOCAL
const struct sockaddr *remote_addr, const int remote_addr_len,
const ss_addr_t tunnel_addr,
#endif
int mtu, int timeout, const char *iface,
cipher_env_t* cipher_env, const char *protocol, const char *protocol_param);
void free_udprelay(void);
typedef struct server_def {
char *hostname;
char *host;
int port;
int udp_port;
struct sockaddr_storage *addr; // resolved address
struct sockaddr_storage *addr_udp; // resolved address
int addr_len;
int addr_udp_len;
char *psw; // raw password
cipher_env_t cipher;
struct cork_dllist connections;
// SSR
char *protocol_name; // for logging use only?
char *obfs_name; // for logging use only?
char *protocol_param;
char *obfs_param;
obfs_class *protocol_plugin;
obfs_class *obfs_plugin;
void *protocol_global;
void *obfs_global;
int enable;
char *id;
char *group;
int udp_over_tcp;
} server_def_t;
#ifdef ANDROID
int protect_socket(int fd);
int send_traffic_stat(uint64_t tx, uint64_t rx);
#endif
#define STAGE_ERROR -1 /* Error detected */
#define STAGE_INIT 0 /* Initial stage */
#define STAGE_HANDSHAKE 1 /* Handshake with client */
#define STAGE_PARSE 2 /* Parse the header */
#define STAGE_RESOLVE 4 /* Resolve the hostname */
#define STAGE_STREAM 5 /* Stream between client and server */
#endif // _COMMON_H
|
281677160/openwrt-package | 1,898 | luci-app-ssr-plus/shadowsocksr-libev/src/src/ssrlink.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import traceback
import random
import getopt
import sys
import json
import base64
def to_bytes(s):
if bytes != str:
if type(s) == str:
return s.encode('utf-8')
return s
def to_str(s):
if bytes != str:
if type(s) == bytes:
return s.decode('utf-8')
return s
def b64decode(data):
if b':' in data:
return data
if len(data) % 4 == 2:
data += b'=='
elif len(data) % 4 == 3:
data += b'='
return base64.urlsafe_b64decode(data)
def fromlink(link):
if link[:6] == 'ssr://':
link = to_bytes(link[6:])
link = to_str(b64decode(link))
params_dict = {}
if '/' in link:
datas = link.split('/', 1)
link = datas[0]
param = datas[1]
pos = param.find('?')
if pos >= 0:
param = param[pos + 1:]
params = param.split('&')
for param in params:
part = param.split('=', 1)
if len(part) == 2:
if part[0] in ['obfsparam', 'protoparam']:
params_dict[part[0]] = to_str(b64decode(to_bytes(part[1])))
else:
params_dict[part[0]] = part[1]
datas = link.split(':')
if len(datas) == 6:
host = datas[0]
port = int(datas[1])
protocol = datas[2]
method = datas[3]
obfs = datas[4]
passwd = to_str(b64decode(to_bytes(datas[5])))
result = {}
result['server'] = host
result['server_port'] = port
result['local_address'] = '0.0.0.0'
result['local_port'] = 1080
result['password'] = passwd
result['protocol'] = protocol
result['method'] = method
result['obfs'] = obfs
result['timeout'] = 300
if 'obfsparam' in params_dict:
result['obfs_param'] = params_dict['obfsparam']
if 'protoparam' in params_dict:
result['protocol_param'] = params_dict['protoparam']
output = json.dumps(result, sort_keys=True, indent=4, separators=(',', ': '))
print(output)
def main():
link = sys.argv[1]
fromlink(link)
if __name__ == '__main__':
main()
|
281677160/openwrt-package | 3,519 | luci-app-ssr-plus/shadowsocksr-libev/src/src/rule.c | /*
* Copyright (c) 2011 and 2012, Dustin Lundquist <dustin@null-ptr.net>
* Copyright (c) 2011 Manuel Kasper <mk@neon1.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <string.h>
#ifdef __MINGW32__
extern void ss_error(const char *s);
#endif
#include "rule.h"
#include "utils.h"
static void free_rule(rule_t *);
rule_t *
new_rule()
{
rule_t *rule;
rule = calloc(1, sizeof(rule_t));
if (rule == NULL) {
ERROR("malloc");
return NULL;
}
return rule;
}
int
accept_rule_arg(rule_t *rule, const char *arg)
{
if (rule->pattern == NULL) {
rule->pattern = strdup(arg);
if (rule->pattern == NULL) {
ERROR("strdup failed");
return -1;
}
} else {
LOGE("Unexpected table rule argument: %s", arg);
return -1;
}
return 1;
}
void
add_rule(struct cork_dllist *rules, rule_t *rule)
{
cork_dllist_add(rules, &rule->entries);
}
int
init_rule(rule_t *rule)
{
if (rule->pattern_re == NULL) {
const char *reerr;
int reerroffset;
rule->pattern_re =
pcre_compile(rule->pattern, 0, &reerr, &reerroffset, NULL);
if (rule->pattern_re == NULL) {
LOGE("Regex compilation of \"%s\" failed: %s, offset %d",
rule->pattern, reerr, reerroffset);
return 0;
}
}
return 1;
}
rule_t *
lookup_rule(const struct cork_dllist *rules, const char *name, size_t name_len)
{
struct cork_dllist_item *curr, *next;
if (name == NULL) {
name = "";
name_len = 0;
}
cork_dllist_foreach_void(rules, curr, next) {
rule_t *rule = cork_container_of(curr, rule_t, entries);
if (pcre_exec(rule->pattern_re, NULL,
name, name_len, 0, 0, NULL, 0) >= 0)
return rule;
}
return NULL;
}
void
remove_rule(rule_t *rule)
{
cork_dllist_remove(&rule->entries);
free_rule(rule);
}
static void
free_rule(rule_t *rule)
{
if (rule == NULL)
return;
ss_free(rule->pattern);
if (rule->pattern_re != NULL)
pcre_free(rule->pattern_re);
ss_free(rule);
}
|
281677160/openwrt-package | 69,484 | luci-app-ssr-plus/shadowsocksr-libev/src/src/uthash.h | /*
Copyright (c) 2003-2016, Troy D. Hanson http://troydhanson.github.com/uthash/
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef UTHASH_H
#define UTHASH_H
#define UTHASH_VERSION 2.0.1
#include <string.h> /* memcmp,strlen */
#include <stddef.h> /* ptrdiff_t */
#include <stdlib.h> /* exit() */
/* These macros use decltype or the earlier __typeof GNU extension.
As decltype is only available in newer compilers (VS2010 or gcc 4.3+
when compiling c++ source) this code uses whatever method is needed
or, for VS2008 where neither is available, uses casting workarounds. */
#if defined(_MSC_VER) /* MS compiler */
#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */
#define DECLTYPE(x) (decltype(x))
#else /* VS2008 or older (or VS2010 in C mode) */
#define NO_DECLTYPE
#define DECLTYPE(x)
#endif
#elif defined(__BORLANDC__) || defined(__LCC__) || defined(__WATCOMC__)
#define NO_DECLTYPE
#define DECLTYPE(x)
#else /* GNU, Sun and other compilers */
#define DECLTYPE(x) (__typeof(x))
#endif
#ifdef NO_DECLTYPE
#define DECLTYPE_ASSIGN(dst,src) \
do { \
char **_da_dst = (char**)(&(dst)); \
*_da_dst = (char*)(src); \
} while (0)
#else
#define DECLTYPE_ASSIGN(dst,src) \
do { \
(dst) = DECLTYPE(dst)(src); \
} while (0)
#endif
/* a number of the hash function use uint32_t which isn't defined on Pre VS2010 */
#if defined(_WIN32)
#if defined(_MSC_VER) && _MSC_VER >= 1600
#include <stdint.h>
#elif defined(__WATCOMC__) || defined(__MINGW32__) || defined(__CYGWIN__)
#include <stdint.h>
#else
typedef unsigned int uint32_t;
typedef unsigned char uint8_t;
#endif
#elif defined(__GNUC__) && !defined(__VXWORKS__)
#include <stdint.h>
#else
typedef unsigned int uint32_t;
typedef unsigned char uint8_t;
#endif
#ifndef uthash_fatal
#define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */
#endif
#ifndef uthash_malloc
#define uthash_malloc(sz) malloc(sz) /* malloc fcn */
#endif
#ifndef uthash_free
#define uthash_free(ptr,sz) free(ptr) /* free fcn */
#endif
#ifndef uthash_strlen
#define uthash_strlen(s) strlen(s)
#endif
#ifndef uthash_memcmp
#define uthash_memcmp(a,b,n) memcmp(a,b,n)
#endif
#ifndef uthash_noexpand_fyi
#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */
#endif
#ifndef uthash_expand_fyi
#define uthash_expand_fyi(tbl) /* can be defined to log expands */
#endif
/* initial number of buckets */
#define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */
#define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */
#define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */
/* calculate the element whose hash handle address is hhp */
#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho)))
/* calculate the hash handle from element address elp */
#define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle *)(((char*)(elp)) + ((tbl)->hho)))
#define HASH_VALUE(keyptr,keylen,hashv) \
do { \
HASH_FCN(keyptr, keylen, hashv); \
} while (0)
#define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out) \
do { \
(out) = NULL; \
if (head) { \
unsigned _hf_bkt; \
HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \
if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) { \
HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \
} \
} \
} while (0)
#define HASH_FIND(hh,head,keyptr,keylen,out) \
do { \
unsigned _hf_hashv; \
HASH_VALUE(keyptr, keylen, _hf_hashv); \
HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \
} while (0)
#ifdef HASH_BLOOM
#define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM)
#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL)
#define HASH_BLOOM_MAKE(tbl) \
do { \
(tbl)->bloom_nbits = HASH_BLOOM; \
(tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \
if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \
memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \
(tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \
} while (0)
#define HASH_BLOOM_FREE(tbl) \
do { \
uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \
} while (0)
#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8U] |= (1U << ((idx)%8U)))
#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8U] & (1U << ((idx)%8U)))
#define HASH_BLOOM_ADD(tbl,hashv) \
HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1U)))
#define HASH_BLOOM_TEST(tbl,hashv) \
HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1U)))
#else
#define HASH_BLOOM_MAKE(tbl)
#define HASH_BLOOM_FREE(tbl)
#define HASH_BLOOM_ADD(tbl,hashv)
#define HASH_BLOOM_TEST(tbl,hashv) (1)
#define HASH_BLOOM_BYTELEN 0U
#endif
#define HASH_MAKE_TABLE(hh,head) \
do { \
(head)->hh.tbl = (UT_hash_table*)uthash_malloc( \
sizeof(UT_hash_table)); \
if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \
memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \
(head)->hh.tbl->tail = &((head)->hh); \
(head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \
(head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \
(head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \
(head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \
HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \
if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \
memset((head)->hh.tbl->buckets, 0, \
HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \
HASH_BLOOM_MAKE((head)->hh.tbl); \
(head)->hh.tbl->signature = HASH_SIGNATURE; \
} while (0)
#define HASH_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \
do { \
(replaced) = NULL; \
HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \
if (replaced) { \
HASH_DELETE(hh, head, replaced); \
} \
HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \
} while (0)
#define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \
do { \
(replaced) = NULL; \
HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \
if (replaced) { \
HASH_DELETE(hh, head, replaced); \
} \
HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \
} while (0)
#define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \
do { \
unsigned _hr_hashv; \
HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \
HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \
} while (0)
#define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn) \
do { \
unsigned _hr_hashv; \
HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \
HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \
} while (0)
#define HASH_APPEND_LIST(hh, head, add) \
do { \
(add)->hh.next = NULL; \
(add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \
(head)->hh.tbl->tail->next = (add); \
(head)->hh.tbl->tail = &((add)->hh); \
} while (0)
#define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \
do { \
unsigned _ha_bkt; \
(add)->hh.hashv = (hashval); \
(add)->hh.key = (char*) (keyptr); \
(add)->hh.keylen = (unsigned) (keylen_in); \
if (!(head)) { \
(add)->hh.next = NULL; \
(add)->hh.prev = NULL; \
(head) = (add); \
HASH_MAKE_TABLE(hh, head); \
} else { \
struct UT_hash_handle *_hs_iter = &(head)->hh; \
(add)->hh.tbl = (head)->hh.tbl; \
do { \
if (cmpfcn(DECLTYPE(head) ELMT_FROM_HH((head)->hh.tbl, _hs_iter), add) > 0) \
break; \
} while ((_hs_iter = _hs_iter->next)); \
if (_hs_iter) { \
(add)->hh.next = _hs_iter; \
if (((add)->hh.prev = _hs_iter->prev)) { \
HH_FROM_ELMT((head)->hh.tbl, _hs_iter->prev)->next = (add); \
} else { \
(head) = (add); \
} \
_hs_iter->prev = (add); \
} else { \
HASH_APPEND_LIST(hh, head, add); \
} \
} \
(head)->hh.tbl->num_items++; \
HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \
HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \
HASH_BLOOM_ADD((head)->hh.tbl, hashval); \
HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \
HASH_FSCK(hh, head); \
} while (0)
#define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn) \
do { \
unsigned _hs_hashv; \
HASH_VALUE(keyptr, keylen_in, _hs_hashv); \
HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \
} while (0)
#define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \
HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn)
#define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn) \
HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn)
#define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add) \
do { \
unsigned _ha_bkt; \
(add)->hh.hashv = (hashval); \
(add)->hh.key = (char*) (keyptr); \
(add)->hh.keylen = (unsigned) (keylen_in); \
if (!(head)) { \
(add)->hh.next = NULL; \
(add)->hh.prev = NULL; \
(head) = (add); \
HASH_MAKE_TABLE(hh, head); \
} else { \
(add)->hh.tbl = (head)->hh.tbl; \
HASH_APPEND_LIST(hh, head, add); \
} \
(head)->hh.tbl->num_items++; \
HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \
HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \
HASH_BLOOM_ADD((head)->hh.tbl, hashval); \
HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \
HASH_FSCK(hh, head); \
} while (0)
#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \
do { \
unsigned _ha_hashv; \
HASH_VALUE(keyptr, keylen_in, _ha_hashv); \
HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \
} while (0)
#define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add) \
HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add)
#define HASH_ADD(hh,head,fieldname,keylen_in,add) \
HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add)
#define HASH_TO_BKT(hashv,num_bkts,bkt) \
do { \
bkt = ((hashv) & ((num_bkts) - 1U)); \
} while (0)
/* delete "delptr" from the hash table.
* "the usual" patch-up process for the app-order doubly-linked-list.
* The use of _hd_hh_del below deserves special explanation.
* These used to be expressed using (delptr) but that led to a bug
* if someone used the same symbol for the head and deletee, like
* HASH_DELETE(hh,users,users);
* We want that to work, but by changing the head (users) below
* we were forfeiting our ability to further refer to the deletee (users)
* in the patch-up process. Solution: use scratch space to
* copy the deletee pointer, then the latter references are via that
* scratch pointer rather than through the repointed (users) symbol.
*/
#define HASH_DELETE(hh,head,delptr) \
do { \
struct UT_hash_handle *_hd_hh_del; \
if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \
uthash_free((head)->hh.tbl->buckets, \
(head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \
HASH_BLOOM_FREE((head)->hh.tbl); \
uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \
head = NULL; \
} else { \
unsigned _hd_bkt; \
_hd_hh_del = &((delptr)->hh); \
if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \
(head)->hh.tbl->tail = \
(UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \
(head)->hh.tbl->hho); \
} \
if ((delptr)->hh.prev != NULL) { \
((UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \
(head)->hh.tbl->hho))->next = (delptr)->hh.next; \
} else { \
DECLTYPE_ASSIGN(head,(delptr)->hh.next); \
} \
if (_hd_hh_del->next != NULL) { \
((UT_hash_handle*)((ptrdiff_t)_hd_hh_del->next + \
(head)->hh.tbl->hho))->prev = \
_hd_hh_del->prev; \
} \
HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \
HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \
(head)->hh.tbl->num_items--; \
} \
HASH_FSCK(hh,head); \
} while (0)
/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */
#define HASH_FIND_STR(head,findstr,out) \
HASH_FIND(hh,head,findstr,(unsigned)uthash_strlen(findstr),out)
#define HASH_ADD_STR(head,strfield,add) \
HASH_ADD(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add)
#define HASH_REPLACE_STR(head,strfield,add,replaced) \
HASH_REPLACE(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add,replaced)
#define HASH_FIND_INT(head,findint,out) \
HASH_FIND(hh,head,findint,sizeof(int),out)
#define HASH_ADD_INT(head,intfield,add) \
HASH_ADD(hh,head,intfield,sizeof(int),add)
#define HASH_REPLACE_INT(head,intfield,add,replaced) \
HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced)
#define HASH_FIND_PTR(head,findptr,out) \
HASH_FIND(hh,head,findptr,sizeof(void *),out)
#define HASH_ADD_PTR(head,ptrfield,add) \
HASH_ADD(hh,head,ptrfield,sizeof(void *),add)
#define HASH_REPLACE_PTR(head,ptrfield,add,replaced) \
HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced)
#define HASH_DEL(head,delptr) \
HASH_DELETE(hh,head,delptr)
/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined.
* This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined.
*/
#ifdef HASH_DEBUG
#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0)
#define HASH_FSCK(hh,head) \
do { \
struct UT_hash_handle *_thh; \
if (head) { \
unsigned _bkt_i; \
unsigned _count; \
char *_prev; \
_count = 0; \
for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \
unsigned _bkt_count = 0; \
_thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \
_prev = NULL; \
while (_thh) { \
if (_prev != (char*)(_thh->hh_prev)) { \
HASH_OOPS("invalid hh_prev %p, actual %p\n", \
_thh->hh_prev, _prev ); \
} \
_bkt_count++; \
_prev = (char*)(_thh); \
_thh = _thh->hh_next; \
} \
_count += _bkt_count; \
if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \
HASH_OOPS("invalid bucket count %u, actual %u\n", \
(head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \
} \
} \
if (_count != (head)->hh.tbl->num_items) { \
HASH_OOPS("invalid hh item count %u, actual %u\n", \
(head)->hh.tbl->num_items, _count ); \
} \
/* traverse hh in app order; check next/prev integrity, count */ \
_count = 0; \
_prev = NULL; \
_thh = &(head)->hh; \
while (_thh) { \
_count++; \
if (_prev !=(char*)(_thh->prev)) { \
HASH_OOPS("invalid prev %p, actual %p\n", \
_thh->prev, _prev ); \
} \
_prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \
_thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \
(head)->hh.tbl->hho) : NULL ); \
} \
if (_count != (head)->hh.tbl->num_items) { \
HASH_OOPS("invalid app item count %u, actual %u\n", \
(head)->hh.tbl->num_items, _count ); \
} \
} \
} while (0)
#else
#define HASH_FSCK(hh,head)
#endif
/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to
* the descriptor to which this macro is defined for tuning the hash function.
* The app can #include <unistd.h> to get the prototype for write(2). */
#ifdef HASH_EMIT_KEYS
#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \
do { \
unsigned _klen = fieldlen; \
write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \
write(HASH_EMIT_KEYS, keyptr, (unsigned long)fieldlen); \
} while (0)
#else
#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen)
#endif
/* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */
#ifdef HASH_FUNCTION
#define HASH_FCN HASH_FUNCTION
#else
#define HASH_FCN HASH_JEN
#endif
/* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */
#define HASH_BER(key,keylen,hashv) \
do { \
unsigned _hb_keylen=(unsigned)keylen; \
const unsigned char *_hb_key=(const unsigned char*)(key); \
(hashv) = 0; \
while (_hb_keylen-- != 0U) { \
(hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \
} \
} while (0)
/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at
* http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */
#define HASH_SAX(key,keylen,hashv) \
do { \
unsigned _sx_i; \
const unsigned char *_hs_key=(const unsigned char*)(key); \
hashv = 0; \
for(_sx_i=0; _sx_i < keylen; _sx_i++) { \
hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \
} \
} while (0)
/* FNV-1a variation */
#define HASH_FNV(key,keylen,hashv) \
do { \
unsigned _fn_i; \
const unsigned char *_hf_key=(const unsigned char*)(key); \
hashv = 2166136261U; \
for(_fn_i=0; _fn_i < keylen; _fn_i++) { \
hashv = hashv ^ _hf_key[_fn_i]; \
hashv = hashv * 16777619U; \
} \
} while (0)
#define HASH_OAT(key,keylen,hashv) \
do { \
unsigned _ho_i; \
const unsigned char *_ho_key=(const unsigned char*)(key); \
hashv = 0; \
for(_ho_i=0; _ho_i < keylen; _ho_i++) { \
hashv += _ho_key[_ho_i]; \
hashv += (hashv << 10); \
hashv ^= (hashv >> 6); \
} \
hashv += (hashv << 3); \
hashv ^= (hashv >> 11); \
hashv += (hashv << 15); \
} while (0)
#define HASH_JEN_MIX(a,b,c) \
do { \
a -= b; a -= c; a ^= ( c >> 13 ); \
b -= c; b -= a; b ^= ( a << 8 ); \
c -= a; c -= b; c ^= ( b >> 13 ); \
a -= b; a -= c; a ^= ( c >> 12 ); \
b -= c; b -= a; b ^= ( a << 16 ); \
c -= a; c -= b; c ^= ( b >> 5 ); \
a -= b; a -= c; a ^= ( c >> 3 ); \
b -= c; b -= a; b ^= ( a << 10 ); \
c -= a; c -= b; c ^= ( b >> 15 ); \
} while (0)
#define HASH_JEN(key,keylen,hashv) \
do { \
unsigned _hj_i,_hj_j,_hj_k; \
unsigned const char *_hj_key=(unsigned const char*)(key); \
hashv = 0xfeedbeefu; \
_hj_i = _hj_j = 0x9e3779b9u; \
_hj_k = (unsigned)(keylen); \
while (_hj_k >= 12U) { \
_hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \
+ ( (unsigned)_hj_key[2] << 16 ) \
+ ( (unsigned)_hj_key[3] << 24 ) ); \
_hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \
+ ( (unsigned)_hj_key[6] << 16 ) \
+ ( (unsigned)_hj_key[7] << 24 ) ); \
hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \
+ ( (unsigned)_hj_key[10] << 16 ) \
+ ( (unsigned)_hj_key[11] << 24 ) ); \
\
HASH_JEN_MIX(_hj_i, _hj_j, hashv); \
\
_hj_key += 12; \
_hj_k -= 12U; \
} \
hashv += (unsigned)(keylen); \
switch ( _hj_k ) { \
case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \
case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \
case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \
case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \
case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \
case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \
case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \
case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \
case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \
case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \
case 1: _hj_i += _hj_key[0]; \
} \
HASH_JEN_MIX(_hj_i, _hj_j, hashv); \
} while (0)
/* The Paul Hsieh hash function */
#undef get16bits
#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
|| defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
#define get16bits(d) (*((const uint16_t *) (d)))
#endif
#if !defined (get16bits)
#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \
+(uint32_t)(((const uint8_t *)(d))[0]) )
#endif
#define HASH_SFH(key,keylen,hashv) \
do { \
unsigned const char *_sfh_key=(unsigned const char*)(key); \
uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \
\
unsigned _sfh_rem = _sfh_len & 3U; \
_sfh_len >>= 2; \
hashv = 0xcafebabeu; \
\
/* Main loop */ \
for (;_sfh_len > 0U; _sfh_len--) { \
hashv += get16bits (_sfh_key); \
_sfh_tmp = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv; \
hashv = (hashv << 16) ^ _sfh_tmp; \
_sfh_key += 2U*sizeof (uint16_t); \
hashv += hashv >> 11; \
} \
\
/* Handle end cases */ \
switch (_sfh_rem) { \
case 3: hashv += get16bits (_sfh_key); \
hashv ^= hashv << 16; \
hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)]) << 18; \
hashv += hashv >> 11; \
break; \
case 2: hashv += get16bits (_sfh_key); \
hashv ^= hashv << 11; \
hashv += hashv >> 17; \
break; \
case 1: hashv += *_sfh_key; \
hashv ^= hashv << 10; \
hashv += hashv >> 1; \
} \
\
/* Force "avalanching" of final 127 bits */ \
hashv ^= hashv << 3; \
hashv += hashv >> 5; \
hashv ^= hashv << 4; \
hashv += hashv >> 17; \
hashv ^= hashv << 25; \
hashv += hashv >> 6; \
} while (0)
#ifdef HASH_USING_NO_STRICT_ALIASING
/* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads.
* For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error.
* MurmurHash uses the faster approach only on CPU's where we know it's safe.
*
* Note the preprocessor built-in defines can be emitted using:
*
* gcc -m64 -dM -E - < /dev/null (on gcc)
* cc -## a.c (where a.c is a simple test file) (Sun Studio)
*/
#if (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86))
#define MUR_GETBLOCK(p,i) p[i]
#else /* non intel */
#define MUR_PLUS0_ALIGNED(p) (((unsigned long)p & 3UL) == 0UL)
#define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 3UL) == 1UL)
#define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 3UL) == 2UL)
#define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 3UL) == 3UL)
#define WP(p) ((uint32_t*)((unsigned long)(p) & ~3UL))
#if (defined(__BIG_ENDIAN__) || defined(SPARC) || defined(__ppc__) || defined(__ppc64__))
#define MUR_THREE_ONE(p) ((((*WP(p))&0x00ffffff) << 8) | (((*(WP(p)+1))&0xff000000) >> 24))
#define MUR_TWO_TWO(p) ((((*WP(p))&0x0000ffff) <<16) | (((*(WP(p)+1))&0xffff0000) >> 16))
#define MUR_ONE_THREE(p) ((((*WP(p))&0x000000ff) <<24) | (((*(WP(p)+1))&0xffffff00) >> 8))
#else /* assume little endian non-intel */
#define MUR_THREE_ONE(p) ((((*WP(p))&0xffffff00) >> 8) | (((*(WP(p)+1))&0x000000ff) << 24))
#define MUR_TWO_TWO(p) ((((*WP(p))&0xffff0000) >>16) | (((*(WP(p)+1))&0x0000ffff) << 16))
#define MUR_ONE_THREE(p) ((((*WP(p))&0xff000000) >>24) | (((*(WP(p)+1))&0x00ffffff) << 8))
#endif
#define MUR_GETBLOCK(p,i) (MUR_PLUS0_ALIGNED(p) ? ((p)[i]) : \
(MUR_PLUS1_ALIGNED(p) ? MUR_THREE_ONE(p) : \
(MUR_PLUS2_ALIGNED(p) ? MUR_TWO_TWO(p) : \
MUR_ONE_THREE(p))))
#endif
#define MUR_ROTL32(x,r) (((x) << (r)) | ((x) >> (32 - (r))))
#define MUR_FMIX(_h) \
do { \
_h ^= _h >> 16; \
_h *= 0x85ebca6bu; \
_h ^= _h >> 13; \
_h *= 0xc2b2ae35u; \
_h ^= _h >> 16; \
} while (0)
#define HASH_MUR(key,keylen,hashv) \
do { \
const uint8_t *_mur_data = (const uint8_t*)(key); \
const int _mur_nblocks = (int)(keylen) / 4; \
uint32_t _mur_h1 = 0xf88D5353u; \
uint32_t _mur_c1 = 0xcc9e2d51u; \
uint32_t _mur_c2 = 0x1b873593u; \
uint32_t _mur_k1 = 0; \
const uint8_t *_mur_tail; \
const uint32_t *_mur_blocks = (const uint32_t*)(_mur_data+(_mur_nblocks*4)); \
int _mur_i; \
for(_mur_i = -_mur_nblocks; _mur_i!=0; _mur_i++) { \
_mur_k1 = MUR_GETBLOCK(_mur_blocks,_mur_i); \
_mur_k1 *= _mur_c1; \
_mur_k1 = MUR_ROTL32(_mur_k1,15); \
_mur_k1 *= _mur_c2; \
\
_mur_h1 ^= _mur_k1; \
_mur_h1 = MUR_ROTL32(_mur_h1,13); \
_mur_h1 = (_mur_h1*5U) + 0xe6546b64u; \
} \
_mur_tail = (const uint8_t*)(_mur_data + (_mur_nblocks*4)); \
_mur_k1=0; \
switch((keylen) & 3U) { \
case 3: _mur_k1 ^= (uint32_t)_mur_tail[2] << 16; /* FALLTHROUGH */ \
case 2: _mur_k1 ^= (uint32_t)_mur_tail[1] << 8; /* FALLTHROUGH */ \
case 1: _mur_k1 ^= (uint32_t)_mur_tail[0]; \
_mur_k1 *= _mur_c1; \
_mur_k1 = MUR_ROTL32(_mur_k1,15); \
_mur_k1 *= _mur_c2; \
_mur_h1 ^= _mur_k1; \
} \
_mur_h1 ^= (uint32_t)(keylen); \
MUR_FMIX(_mur_h1); \
hashv = _mur_h1; \
} while (0)
#endif /* HASH_USING_NO_STRICT_ALIASING */
/* iterate over items in a known bucket to find desired item */
#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out) \
do { \
if ((head).hh_head != NULL) { \
DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \
} else { \
(out) = NULL; \
} \
while ((out) != NULL) { \
if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \
if (uthash_memcmp((out)->hh.key, keyptr, keylen_in) == 0) { \
break; \
} \
} \
if ((out)->hh.hh_next != NULL) { \
DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (out)->hh.hh_next)); \
} else { \
(out) = NULL; \
} \
} \
} while (0)
/* add an item to a bucket */
#define HASH_ADD_TO_BKT(head,addhh) \
do { \
head.count++; \
(addhh)->hh_next = head.hh_head; \
(addhh)->hh_prev = NULL; \
if (head.hh_head != NULL) { (head).hh_head->hh_prev = (addhh); } \
(head).hh_head=addhh; \
if ((head.count >= ((head.expand_mult+1U) * HASH_BKT_CAPACITY_THRESH)) \
&& ((addhh)->tbl->noexpand != 1U)) { \
HASH_EXPAND_BUCKETS((addhh)->tbl); \
} \
} while (0)
/* remove an item from a given bucket */
#define HASH_DEL_IN_BKT(hh,head,hh_del) \
(head).count--; \
if ((head).hh_head == hh_del) { \
(head).hh_head = hh_del->hh_next; \
} \
if (hh_del->hh_prev) { \
hh_del->hh_prev->hh_next = hh_del->hh_next; \
} \
if (hh_del->hh_next) { \
hh_del->hh_next->hh_prev = hh_del->hh_prev; \
}
/* Bucket expansion has the effect of doubling the number of buckets
* and redistributing the items into the new buckets. Ideally the
* items will distribute more or less evenly into the new buckets
* (the extent to which this is true is a measure of the quality of
* the hash function as it applies to the key domain).
*
* With the items distributed into more buckets, the chain length
* (item count) in each bucket is reduced. Thus by expanding buckets
* the hash keeps a bound on the chain length. This bounded chain
* length is the essence of how a hash provides constant time lookup.
*
* The calculation of tbl->ideal_chain_maxlen below deserves some
* explanation. First, keep in mind that we're calculating the ideal
* maximum chain length based on the *new* (doubled) bucket count.
* In fractions this is just n/b (n=number of items,b=new num buckets).
* Since the ideal chain length is an integer, we want to calculate
* ceil(n/b). We don't depend on floating point arithmetic in this
* hash, so to calculate ceil(n/b) with integers we could write
*
* ceil(n/b) = (n/b) + ((n%b)?1:0)
*
* and in fact a previous version of this hash did just that.
* But now we have improved things a bit by recognizing that b is
* always a power of two. We keep its base 2 log handy (call it lb),
* so now we can write this with a bit shift and logical AND:
*
* ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0)
*
*/
#define HASH_EXPAND_BUCKETS(tbl) \
do { \
unsigned _he_bkt; \
unsigned _he_bkt_i; \
struct UT_hash_handle *_he_thh, *_he_hh_nxt; \
UT_hash_bucket *_he_new_buckets, *_he_newbkt; \
_he_new_buckets = (UT_hash_bucket*)uthash_malloc( \
2UL * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \
if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \
memset(_he_new_buckets, 0, \
2UL * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \
tbl->ideal_chain_maxlen = \
(tbl->num_items >> (tbl->log2_num_buckets+1U)) + \
(((tbl->num_items & ((tbl->num_buckets*2U)-1U)) != 0U) ? 1U : 0U); \
tbl->nonideal_items = 0; \
for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \
{ \
_he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \
while (_he_thh != NULL) { \
_he_hh_nxt = _he_thh->hh_next; \
HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2U, _he_bkt); \
_he_newbkt = &(_he_new_buckets[ _he_bkt ]); \
if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \
tbl->nonideal_items++; \
_he_newbkt->expand_mult = _he_newbkt->count / \
tbl->ideal_chain_maxlen; \
} \
_he_thh->hh_prev = NULL; \
_he_thh->hh_next = _he_newbkt->hh_head; \
if (_he_newbkt->hh_head != NULL) { _he_newbkt->hh_head->hh_prev = \
_he_thh; } \
_he_newbkt->hh_head = _he_thh; \
_he_thh = _he_hh_nxt; \
} \
} \
uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \
tbl->num_buckets *= 2U; \
tbl->log2_num_buckets++; \
tbl->buckets = _he_new_buckets; \
tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \
(tbl->ineff_expands+1U) : 0U; \
if (tbl->ineff_expands > 1U) { \
tbl->noexpand=1; \
uthash_noexpand_fyi(tbl); \
} \
uthash_expand_fyi(tbl); \
} while (0)
/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */
/* Note that HASH_SORT assumes the hash handle name to be hh.
* HASH_SRT was added to allow the hash handle name to be passed in. */
#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn)
#define HASH_SRT(hh,head,cmpfcn) \
do { \
unsigned _hs_i; \
unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \
struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \
if (head != NULL) { \
_hs_insize = 1; \
_hs_looping = 1; \
_hs_list = &((head)->hh); \
while (_hs_looping != 0U) { \
_hs_p = _hs_list; \
_hs_list = NULL; \
_hs_tail = NULL; \
_hs_nmerges = 0; \
while (_hs_p != NULL) { \
_hs_nmerges++; \
_hs_q = _hs_p; \
_hs_psize = 0; \
for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \
_hs_psize++; \
_hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \
((void*)((char*)(_hs_q->next) + \
(head)->hh.tbl->hho)) : NULL); \
if (! (_hs_q) ) { break; } \
} \
_hs_qsize = _hs_insize; \
while ((_hs_psize > 0U) || ((_hs_qsize > 0U) && (_hs_q != NULL))) {\
if (_hs_psize == 0U) { \
_hs_e = _hs_q; \
_hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \
((void*)((char*)(_hs_q->next) + \
(head)->hh.tbl->hho)) : NULL); \
_hs_qsize--; \
} else if ( (_hs_qsize == 0U) || (_hs_q == NULL) ) { \
_hs_e = _hs_p; \
if (_hs_p != NULL){ \
_hs_p = (UT_hash_handle*)((_hs_p->next != NULL) ? \
((void*)((char*)(_hs_p->next) + \
(head)->hh.tbl->hho)) : NULL); \
} \
_hs_psize--; \
} else if (( \
cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \
DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \
) <= 0) { \
_hs_e = _hs_p; \
if (_hs_p != NULL){ \
_hs_p = (UT_hash_handle*)((_hs_p->next != NULL) ? \
((void*)((char*)(_hs_p->next) + \
(head)->hh.tbl->hho)) : NULL); \
} \
_hs_psize--; \
} else { \
_hs_e = _hs_q; \
_hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \
((void*)((char*)(_hs_q->next) + \
(head)->hh.tbl->hho)) : NULL); \
_hs_qsize--; \
} \
if ( _hs_tail != NULL ) { \
_hs_tail->next = ((_hs_e != NULL) ? \
ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \
} else { \
_hs_list = _hs_e; \
} \
if (_hs_e != NULL) { \
_hs_e->prev = ((_hs_tail != NULL) ? \
ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \
} \
_hs_tail = _hs_e; \
} \
_hs_p = _hs_q; \
} \
if (_hs_tail != NULL){ \
_hs_tail->next = NULL; \
} \
if ( _hs_nmerges <= 1U ) { \
_hs_looping=0; \
(head)->hh.tbl->tail = _hs_tail; \
DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \
} \
_hs_insize *= 2U; \
} \
HASH_FSCK(hh,head); \
} \
} while (0)
/* This function selects items from one hash into another hash.
* The end result is that the selected items have dual presence
* in both hashes. There is no copy of the items made; rather
* they are added into the new hash through a secondary hash
* hash handle that must be present in the structure. */
#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \
do { \
unsigned _src_bkt, _dst_bkt; \
void *_last_elt=NULL, *_elt; \
UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \
ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \
if (src != NULL) { \
for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \
for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \
_src_hh != NULL; \
_src_hh = _src_hh->hh_next) { \
_elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \
if (cond(_elt)) { \
_dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \
_dst_hh->key = _src_hh->key; \
_dst_hh->keylen = _src_hh->keylen; \
_dst_hh->hashv = _src_hh->hashv; \
_dst_hh->prev = _last_elt; \
_dst_hh->next = NULL; \
if (_last_elt_hh != NULL) { _last_elt_hh->next = _elt; } \
if (dst == NULL) { \
DECLTYPE_ASSIGN(dst,_elt); \
HASH_MAKE_TABLE(hh_dst,dst); \
} else { \
_dst_hh->tbl = (dst)->hh_dst.tbl; \
} \
HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \
HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \
(dst)->hh_dst.tbl->num_items++; \
_last_elt = _elt; \
_last_elt_hh = _dst_hh; \
} \
} \
} \
} \
HASH_FSCK(hh_dst,dst); \
} while (0)
#define HASH_CLEAR(hh,head) \
do { \
if (head != NULL) { \
uthash_free((head)->hh.tbl->buckets, \
(head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \
HASH_BLOOM_FREE((head)->hh.tbl); \
uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \
(head)=NULL; \
} \
} while (0)
#define HASH_OVERHEAD(hh,head) \
((head != NULL) ? ( \
(size_t)(((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \
((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \
sizeof(UT_hash_table) + \
(HASH_BLOOM_BYTELEN))) : 0U)
#ifdef NO_DECLTYPE
#define HASH_ITER(hh,head,el,tmp) \
for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \
(el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL)))
#else
#define HASH_ITER(hh,head,el,tmp) \
for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \
(el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL)))
#endif
/* obtain a count of items in the hash */
#define HASH_COUNT(head) HASH_CNT(hh,head)
#define HASH_CNT(hh,head) ((head != NULL)?((head)->hh.tbl->num_items):0U)
typedef struct UT_hash_bucket {
struct UT_hash_handle *hh_head;
unsigned count;
/* expand_mult is normally set to 0. In this situation, the max chain length
* threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If
* the bucket's chain exceeds this length, bucket expansion is triggered).
* However, setting expand_mult to a non-zero value delays bucket expansion
* (that would be triggered by additions to this particular bucket)
* until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH.
* (The multiplier is simply expand_mult+1). The whole idea of this
* multiplier is to reduce bucket expansions, since they are expensive, in
* situations where we know that a particular bucket tends to be overused.
* It is better to let its chain length grow to a longer yet-still-bounded
* value, than to do an O(n) bucket expansion too often.
*/
unsigned expand_mult;
} UT_hash_bucket;
/* random signature used only to find hash tables in external analysis */
#define HASH_SIGNATURE 0xa0111fe1u
#define HASH_BLOOM_SIGNATURE 0xb12220f2u
typedef struct UT_hash_table {
UT_hash_bucket *buckets;
unsigned num_buckets, log2_num_buckets;
unsigned num_items;
struct UT_hash_handle *tail; /* tail hh in app order, for fast append */
ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */
/* in an ideal situation (all buckets used equally), no bucket would have
* more than ceil(#items/#buckets) items. that's the ideal chain length. */
unsigned ideal_chain_maxlen;
/* nonideal_items is the number of items in the hash whose chain position
* exceeds the ideal chain maxlen. these items pay the penalty for an uneven
* hash distribution; reaching them in a chain traversal takes >ideal steps */
unsigned nonideal_items;
/* ineffective expands occur when a bucket doubling was performed, but
* afterward, more than half the items in the hash had nonideal chain
* positions. If this happens on two consecutive expansions we inhibit any
* further expansion, as it's not helping; this happens when the hash
* function isn't a good fit for the key domain. When expansion is inhibited
* the hash will still work, albeit no longer in constant time. */
unsigned ineff_expands, noexpand;
uint32_t signature; /* used only to find hash tables in external analysis */
#ifdef HASH_BLOOM
uint32_t bloom_sig; /* used only to test bloom exists in external analysis */
uint8_t *bloom_bv;
uint8_t bloom_nbits;
#endif
} UT_hash_table;
typedef struct UT_hash_handle {
struct UT_hash_table *tbl;
void *prev; /* prev element in app order */
void *next; /* next element in app order */
struct UT_hash_handle *hh_prev; /* previous hh in bucket order */
struct UT_hash_handle *hh_next; /* next hh in bucket order */
void *key; /* ptr to enclosing struct's key */
unsigned keylen; /* enclosing struct's key len */
unsigned hashv; /* result of hash-fcn(key) */
} UT_hash_handle;
#endif /* UTHASH_H */
|
281677160/openwrt-package | 1,811 | luci-app-ssr-plus/shadowsocksr-libev/src/src/win32.h | /*
* win32.h - Win32 port helpers
*
* Copyright (C) 2014, Linus Yang <linusyang@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _WIN32_H
#define _WIN32_H
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#include <winsock2.h>
#include <ws2tcpip.h>
#ifdef EWOULDBLOCK
#undef EWOULDBLOCK
#endif
#ifdef errno
#undef errno
#endif
#ifdef ERROR
#undef ERROR
#endif
#ifndef AI_ALL
#define AI_ALL 0x00000100
#endif
#ifndef AI_ADDRCONFIG
#define AI_ADDRCONFIG 0x00000400
#endif
#ifndef AI_V4MAPPED
#define AI_V4MAPPED 0x00000800
#endif
#ifndef IPV6_V6ONLY
#define IPV6_V6ONLY 27 // Treat wildcard bind as AF_INET6-only.
#endif
#define EWOULDBLOCK WSAEWOULDBLOCK
#define errno WSAGetLastError()
#define close(fd) closesocket(fd)
#define ERROR(s) ss_error(s)
#define setsockopt(a, b, c, d, e) setsockopt(a, b, c, (char *)(d), e)
void winsock_init(void);
void winsock_cleanup(void);
void ss_error(const char *s);
size_t strnlen(const char *s, size_t maxlen);
int setnonblocking(int fd);
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
#endif
|
281677160/openwrt-package | 12,586 | luci-app-ssr-plus/shadowsocksr-libev/src/src/utils.c | /*
* utils.c - Misc utilities
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#ifndef __MINGW32__
#include <pwd.h>
#include <grp.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include "utils.h"
#ifdef HAVE_SETRLIMIT
#include <sys/time.h>
#include <sys/resource.h>
#endif
#define INT_DIGITS 19 /* enough for 64 bit integer */
#ifdef LIB_ONLY
FILE *logfile;
#endif
#ifdef HAS_SYSLOG
int use_syslog = 0;
#endif
#ifndef __MINGW32__
void
ERROR(const char *s)
{
char *msg = strerror(errno);
LOGE("%s: %s", s, msg);
}
#endif
int use_tty = 1;
char *
ss_itoa(int i)
{
/* Room for INT_DIGITS digits, - and '\0' */
static char buf[INT_DIGITS + 2];
char *p = buf + INT_DIGITS + 1; /* points to terminating '\0' */
if (i >= 0) {
do {
*--p = '0' + (i % 10);
i /= 10;
} while (i != 0);
return p;
} else { /* i < 0 */
do {
*--p = '0' - (i % 10);
i /= 10;
} while (i != 0);
*--p = '-';
}
return p;
}
int
ss_isnumeric(const char *s) {
if (!s || !*s)
return 0;
while (isdigit(*s))
++s;
return *s == '\0';
}
/*
* setuid() and setgid() for a specified user.
*/
int
run_as(const char *user)
{
#ifndef __MINGW32__
if (user[0]) {
/* Convert user to a long integer if it is a non-negative number.
* -1 means it is a user name. */
long uid = -1;
if (ss_isnumeric(user)) {
errno = 0;
char *endptr;
uid = strtol(user, &endptr, 10);
if (errno || endptr == user)
uid = -1;
}
#ifdef HAVE_GETPWNAM_R
struct passwd pwdbuf, *pwd;
memset(&pwdbuf, 0, sizeof(struct passwd));
size_t buflen;
int err;
for (buflen = 128;; buflen *= 2) {
char buf[buflen]; /* variable length array */
/* Note that we use getpwnam_r() instead of getpwnam(),
* which returns its result in a statically allocated buffer and
* cannot be considered thread safe. */
err = uid >= 0 ? getpwuid_r((uid_t)uid, &pwdbuf, buf, buflen, &pwd)
: getpwnam_r(user, &pwdbuf, buf, buflen, &pwd);
if (err == 0 && pwd) {
/* setgid first, because we may not be allowed to do it anymore after setuid */
if (setgid(pwd->pw_gid) != 0) {
LOGE(
"Could not change group id to that of run_as user '%s': %s",
pwd->pw_name, strerror(errno));
return 0;
}
if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
LOGE("Could not change supplementary groups for user '%s'.", pwd->pw_name);
return 0;
}
if (setuid(pwd->pw_uid) != 0) {
LOGE(
"Could not change user id to that of run_as user '%s': %s",
pwd->pw_name, strerror(errno));
return 0;
}
break;
} else if (err != ERANGE) {
if (err) {
LOGE("run_as user '%s' could not be found: %s", user,
strerror(err));
} else {
LOGE("run_as user '%s' could not be found.", user);
}
return 0;
} else if (buflen >= 16 * 1024) {
/* If getpwnam_r() seems defective, call it quits rather than
* keep on allocating ever larger buffers until we crash. */
LOGE(
"getpwnam_r() requires more than %u bytes of buffer space.",
(unsigned)buflen);
return 0;
}
/* Else try again with larger buffer. */
}
#else
/* No getpwnam_r() :-( We'll use getpwnam() and hope for the best. */
struct passwd *pwd;
if (!(pwd = uid >=0 ? getpwuid((uid_t)uid) : getpwnam(user))) {
LOGE("run_as user %s could not be found.", user);
return 0;
}
/* setgid first, because we may not allowed to do it anymore after setuid */
if (setgid(pwd->pw_gid) != 0) {
LOGE("Could not change group id to that of run_as user '%s': %s",
pwd->pw_name, strerror(errno));
return 0;
}
if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
LOGE("Could not change supplementary groups for user '%s'.", pwd->pw_name);
return 0;
}
if (setuid(pwd->pw_uid) != 0) {
LOGE("Could not change user id to that of run_as user '%s': %s",
pwd->pw_name, strerror(errno));
return 0;
}
#endif
}
#endif // __MINGW32__
return 1;
}
char *
ss_strndup(const char *s, size_t n)
{
size_t len = strlen(s);
char *ret;
if (len <= n) {
return strdup(s);
}
ret = ss_malloc(n + 1);
strncpy(ret, s, n);
ret[n] = '\0';
return ret;
}
char *
ss_strdup(const char *s) {
if (!s) {
return NULL;
}
return strdup(s);
}
void
FATAL(const char *msg)
{
LOGE("%s", msg);
exit(-1);
}
void *
ss_malloc(size_t size)
{
void *tmp = malloc(size);
if (tmp == NULL)
exit(EXIT_FAILURE);
return tmp;
}
void *
ss_realloc(void *ptr, size_t new_size)
{
void *new = realloc(ptr, new_size);
if (new == NULL) {
free(ptr);
ptr = NULL;
exit(EXIT_FAILURE);
}
return new;
}
void
usage()
{
printf("\n");
printf("shadowsocks-libev %s with %s\n\n", VERSION, USING_CRYPTO);
printf(
" maintained by Max Lv <max.c.lv@gmail.com> and Linus Yang <laokongzi@gmail.com>\n\n");
printf(" usage:\n\n");
#ifdef MODULE_LOCAL
printf(" ss-local\n");
#elif MODULE_REMOTE
printf(" ss-server\n");
#elif MODULE_TUNNEL
printf(" ss-tunnel\n");
#elif MODULE_REDIR
printf(" ss-redir\n");
#elif MODULE_MANAGER
printf(" ss-manager\n");
#endif
printf("\n");
printf(
" -s <server_host> Host name or IP address of your remote server.\n");
printf(
" -p <server_port> Port number of your remote server.\n");
printf(
" -l <local_port> Port number of your local server.\n");
printf(
" -k <password> Password of your remote server.\n");
printf(
" -m <encrypt_method> Encrypt method: table, rc4, rc4-md5,\n");
printf(
" aes-128-cfb, aes-192-cfb, aes-256-cfb,\n");
printf(
" aes-128-ctr, aes-192-ctr, aes-256-ctr,\n");
printf(
" bf-cfb, camellia-128-cfb, camellia-192-cfb,\n");
printf(
" camellia-256-cfb, cast5-cfb, des-cfb,\n");
printf(
" idea-cfb, rc2-cfb, seed-cfb, salsa20,\n");
printf(
" chacha20 and chacha20-ietf.\n");
printf(
" The default cipher is rc4-md5.\n");
printf("\n");
printf(
" [-a <user>] Run as another user.\n");
printf(
" [-f <pid_file>] The file path to store pid.\n");
printf(
" [-t <timeout>] Socket timeout in seconds.\n");
printf(
" [-c <config_file>] The path to config file.\n");
#ifdef HAVE_SETRLIMIT
printf(
" [-n <number>] Max number of open files.\n");
#endif
#ifndef MODULE_REDIR
printf(
" [-i <interface>] Network interface to bind.\n");
#endif
printf(
" [-b <local_address>] Local address to bind.\n");
printf("\n");
printf(
" [-u] Enable UDP relay.\n");
#ifdef MODULE_REDIR
printf(
" TPROXY is required in redir mode.\n");
#endif
printf(
" [-U] Enable UDP relay and disable TCP relay.\n");
#ifdef MODULE_REMOTE
printf(
" [-6] Resovle hostname to IPv6 address first.\n");
#endif
printf("\n");
#ifdef MODULE_TUNNEL
printf(
" [-L <addr>:<port>] Destination server address and port\n");
printf(
" for local port forwarding.\n");
#endif
#ifdef MODULE_REMOTE
printf(
" [-d <addr>] Name servers for internal DNS resolver.\n");
#endif
#if defined(MODULE_REMOTE) || defined(MODULE_LOCAL)
printf(
" [--fast-open] Enable TCP fast open.\n");
printf(
" with Linux kernel > 3.7.0.\n");
printf(
" [--acl <acl_file>] Path to ACL (Access Control List).\n");
#endif
#if defined(MODULE_REMOTE) || defined(MODULE_MANAGER)
printf(
" [--manager-address <addr>] UNIX domain socket address.\n");
#endif
#ifdef MODULE_MANAGER
printf(
" [--executable <path>] Path to the executable of ss-server.\n");
#endif
printf(
" [--mtu <MTU>] MTU of your network interface.\n");
#ifdef __linux__
printf(
" [--mptcp] Enable Multipath TCP on MPTCP Kernel.\n");
#ifdef MODULE_REMOTE
printf(
" [--firewall] Setup firewall rules for auto blocking.\n");
#endif
#endif
printf("\n");
printf(
" [-v] Verbose mode.\n");
printf(
" [-h, --help] Print this message.\n");
printf("\n");
}
void
daemonize(const char *path)
{
#ifndef __MINGW32__
/* Our process ID and Session ID */
pid_t pid, sid;
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then
* we can exit the parent process. */
if (pid > 0) {
FILE *file = fopen(path, "w");
if (file == NULL) {
FATAL("Invalid pid file\n");
}
fprintf(file, "%d", (int)pid);
fclose(file);
exit(EXIT_SUCCESS);
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Change the current working directory */
if ((chdir("/")) < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
#endif
}
#ifdef HAVE_SETRLIMIT
int
set_nofile(int nofile)
{
struct rlimit limit = { nofile, nofile }; /* set both soft and hard limit */
if (nofile <= 0) {
FATAL("nofile must be greater than 0\n");
}
if (setrlimit(RLIMIT_NOFILE, &limit) < 0) {
if (errno == EPERM) {
LOGE(
"insufficient permission to change NOFILE, not starting as root?");
return -1;
} else if (errno == EINVAL) {
LOGE("invalid nofile, decrease nofile and try again");
return -1;
} else {
LOGE("setrlimit failed: %s", strerror(errno));
return -1;
}
}
return 0;
}
#endif
|
281677160/openwrt-package | 1,527 | luci-app-ssr-plus/shadowsocksr-libev/src/src/http.h | /*
* Copyright (c) 2011 and 2012, Dustin Lundquist <dustin@null-ptr.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef HTTP_H
#define HTTP_H
#include <stdio.h>
#include "protocol.h"
const protocol_t *const http_protocol;
#endif
|
281677160/openwrt-package | 47,603 | luci-app-ssr-plus/shadowsocksr-libev/src/src/redir.c | /*
* redir.c - Provide a transparent TCP proxy through remote shadowsocks
* server
*
* Copyright (C) 2013 - 2015, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <sys/stat.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <locale.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <limits.h>
#include <linux/if.h>
#include <linux/netfilter_ipv4.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <udns.h>
#include <libcork/core.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "http.h"
#include "tls.h"
#include "netutils.h"
#include "utils.h"
#include "redir.h"
#include "common.h"
#ifndef EAGAIN
#define EAGAIN EWOULDBLOCK
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK EAGAIN
#endif
#ifndef BUF_SIZE
#define BUF_SIZE 2048
#endif
#ifndef IP6T_SO_ORIGINAL_DST
#define IP6T_SO_ORIGINAL_DST 80
#endif
#include "includeobfs.h" // I don't want to modify makefile
#include "jconf.h"
static void accept_cb(EV_P_ ev_io *w, int revents);
static void server_recv_cb(EV_P_ ev_io *w, int revents);
static void server_send_cb(EV_P_ ev_io *w, int revents);
static void remote_recv_cb(EV_P_ ev_io *w, int revents);
static void remote_send_cb(EV_P_ ev_io *w, int revents);
static remote_t *new_remote(int fd, int timeout);
static server_t *new_server(int fd, listen_ctx_t* profile);
static void free_remote(remote_t *remote);
static void close_and_free_remote(EV_P_ remote_t *remote);
static void free_server(server_t *server);
static void close_and_free_server(EV_P_ server_t *server);
int verbose = 0;
int keep_resolving = 1;
static int ipv6first = 0;
static int mode = TCP_ONLY;
#ifdef HAVE_SETRLIMIT
static int nofile = 0;
#endif
static struct cork_dllist inactive_profiles;
static listen_ctx_t *current_profile;
static struct cork_dllist all_connections;
int
getdestaddr(int fd, struct sockaddr_storage *destaddr)
{
socklen_t socklen = sizeof(*destaddr);
int error = 0;
error = getsockopt(fd, SOL_IPV6, IP6T_SO_ORIGINAL_DST, destaddr, &socklen);
if (error) { // Didn't find a proper way to detect IP version.
error = getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, destaddr, &socklen);
if (error) {
return -1;
}
}
return 0;
}
int
setnonblocking(int fd)
{
int flags;
if (-1 == (flags = fcntl(fd, F_GETFL, 0))) {
flags = 0;
}
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
int
create_and_bind(const char *addr, const char *port)
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int s, listen_sock;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */
s = getaddrinfo(addr, port, &hints, &result);
if (s != 0) {
LOGI("getaddrinfo: %s", gai_strerror(s));
return -1;
}
if (result == NULL) {
LOGE("Could not bind");
return -1;
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
listen_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (listen_sock == -1) {
continue;
}
int opt = 1;
setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(listen_sock, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
int err = set_reuseport(listen_sock);
if (err == 0) {
LOGI("tcp port reuse enabled");
}
s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen);
if (s == 0) {
/* We managed to bind successfully! */
break;
} else {
ERROR("bind");
}
close(listen_sock);
listen_sock = -1;
}
freeaddrinfo(result);
return listen_sock;
}
static void
server_recv_cb(EV_P_ ev_io *w, int revents)
{
server_ctx_t *server_recv_ctx = (server_ctx_t *)w;
server_t *server = server_recv_ctx->server;
remote_t *remote = server->remote;
server_def_t *server_env = server->server_env;
ssize_t r = recv(server->fd, remote->buf->array + remote->buf->len,
BUF_SIZE - remote->buf->len, 0);
if (r == 0) {
// connection closed
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else if (r == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data
// continue to wait for recv
return;
} else {
ERROR("server recv");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
remote->buf->len += r;
if (verbose) {
uint16_t port = 0;
char ipstr[INET6_ADDRSTRLEN];
memset(&ipstr, 0, INET6_ADDRSTRLEN);
if (AF_INET == server->destaddr.ss_family) {
struct sockaddr_in *sa = (struct sockaddr_in *)&(server->destaddr);
dns_ntop(AF_INET, &(sa->sin_addr), ipstr, INET_ADDRSTRLEN);
port = ntohs(sa->sin_port);
} else {
// TODO: The code below need to be test in IPv6 envirment, which I
// don't have.
struct sockaddr_in6 *sa = (struct sockaddr_in6 *)&(server->destaddr);
dns_ntop(AF_INET6, &(sa->sin6_addr), ipstr, INET6_ADDRSTRLEN);
port = ntohs(sa->sin6_port);
}
LOGI("redir to %s:%d, len=%zu, recv=%zd", ipstr, port, remote->buf->len, r);
}
if (!remote->send_ctx->connected) {
// SNI
int ret = 0;
uint16_t port = 0;
if (AF_INET6 == server->destaddr.ss_family) { // IPv6
port = ntohs(((struct sockaddr_in6 *)&(server->destaddr))->sin6_port);
} else { // IPv4
port = ntohs(((struct sockaddr_in *)&(server->destaddr))->sin_port);
}
if (port == http_protocol->default_port)
ret = http_protocol->parse_packet(remote->buf->array,
remote->buf->len, &server->hostname);
else if (port == tls_protocol->default_port)
ret = tls_protocol->parse_packet(remote->buf->array,
remote->buf->len, &server->hostname);
if (ret > 0) {
server->hostname_len = ret;
}
ev_io_stop(EV_A_ & server_recv_ctx->io);
ev_io_start(EV_A_ & remote->send_ctx->io);
return;
}
// SSR beg
if (server_env->protocol_plugin) {
obfs_class *protocol_plugin = server_env->protocol_plugin;
if (protocol_plugin->client_pre_encrypt) {
remote->buf->len = protocol_plugin->client_pre_encrypt(server->protocol, &remote->buf->array, remote->buf->len, &remote->buf->capacity);
}
}
int err = ss_encrypt(&server_env->cipher, remote->buf, server->e_ctx, BUF_SIZE);
if (err) {
LOGE("invalid password or cipher");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (server_env->obfs_plugin) {
obfs_class *obfs_plugin = server_env->obfs_plugin;
if (obfs_plugin->client_encode) {
remote->buf->len = obfs_plugin->client_encode(server->obfs, &remote->buf->array, remote->buf->len, &remote->buf->capacity);
}
}
// SSR end
if (!remote->send_ctx->connected) {
ev_io_stop(EV_A_ & server_recv_ctx->io);
ev_io_start(EV_A_ & remote->send_ctx->io);
return;
}
if (r > 0 && remote->buf->len == 0) { // SSR pause recv
remote->buf->idx = 0;
ev_io_stop(EV_A_ & server_recv_ctx->io);
return;
}
int s = send(remote->fd, remote->buf->array, remote->buf->len, 0);
if (s == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data, wait for send
remote->buf->idx = 0;
ev_io_stop(EV_A_ & server_recv_ctx->io);
ev_io_start(EV_A_ & remote->send_ctx->io);
return;
} else {
ERROR("send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
} else if (s < remote->buf->len) {
remote->buf->len -= s;
remote->buf->idx = s;
ev_io_stop(EV_A_ & server_recv_ctx->io);
ev_io_start(EV_A_ & remote->send_ctx->io);
return;
} else {
remote->buf->idx = 0;
remote->buf->len = 0;
}
}
static void
server_send_cb(EV_P_ ev_io *w, int revents)
{
server_ctx_t *server_send_ctx = (server_ctx_t *)w;
server_t *server = server_send_ctx->server;
remote_t *remote = server->remote;
if (server->buf->len == 0) {
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else {
// has data to send
ssize_t s = send(server->fd, server->buf->array + server->buf->idx,
server->buf->len, 0);
if (s == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
ERROR("send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
} else if (s < server->buf->len) {
// partly sent, move memory, wait for the next time to send
server->buf->len -= s;
server->buf->idx += s;
return;
} else {
// all sent out, wait for reading
server->buf->len = 0;
server->buf->idx = 0;
ev_io_stop(EV_A_ & server_send_ctx->io);
ev_io_start(EV_A_ & remote->recv_ctx->io);
}
}
}
static void
remote_timeout_cb(EV_P_ ev_timer *watcher, int revents)
{
remote_ctx_t *remote_ctx
= cork_container_of(watcher, remote_ctx_t, watcher);
remote_t *remote = remote_ctx->remote;
server_t *server = remote->server;
ev_timer_stop(EV_A_ watcher);
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
static void
remote_recv_cb(EV_P_ ev_io *w, int revents)
{
remote_ctx_t *remote_recv_ctx = (remote_ctx_t *)w;
remote_t *remote = remote_recv_ctx->remote;
server_t *server = remote->server;
server_def_t *server_env = server->server_env;
ev_timer_again(EV_A_ & remote->recv_ctx->watcher);
ssize_t r = recv(remote->fd, server->buf->array, BUF_SIZE, 0);
if (r == 0) {
// connection closed
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else if (r == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data
// continue to wait for recv
return;
} else {
ERROR("remote recv");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
server->buf->len = r;
// SSR beg
if (server_env->obfs_plugin) {
obfs_class *obfs_plugin = server_env->obfs_plugin;
if (obfs_plugin->client_decode) {
int needsendback;
server->buf->len = obfs_plugin->client_decode(server->obfs, &server->buf->array, server->buf->len, &server->buf->capacity, &needsendback);
if ((int)server->buf->len < 0) {
LOGE("client_decode");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (needsendback) {
obfs_class *obfs_plugin = server_env->obfs_plugin;
if (obfs_plugin->client_encode) {
remote->buf->len = obfs_plugin->client_encode(server->obfs, &remote->buf->array, 0, &remote->buf->capacity);
ssize_t s = send(remote->fd, remote->buf->array, remote->buf->len, 0);
if (s == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
ERROR("remote_send_cb_send");
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
} else if (s < (ssize_t)(remote->buf->len)) {
// partly sent, move memory, wait for the next time to send
remote->buf->len -= s;
remote->buf->idx += s;
return;
} else {
// all sent out, wait for reading
remote->buf->len = 0;
remote->buf->idx = 0;
ev_io_stop(EV_A_ & remote->send_ctx->io);
ev_io_start(EV_A_ & server->recv_ctx->io);
}
}
}
}
}
if ( server->buf->len == 0 )
return;
int err = ss_decrypt(&server_env->cipher, server->buf, server->d_ctx, BUF_SIZE);
if (err) {
LOGE("invalid password or cipher");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (server_env->protocol_plugin) {
obfs_class *protocol_plugin = server_env->protocol_plugin;
if (protocol_plugin->client_post_decrypt) {
server->buf->len = protocol_plugin->client_post_decrypt(server->protocol, &server->buf->array, server->buf->len, &server->buf->capacity);
if ((int)server->buf->len < 0) {
LOGE("client_post_decrypt");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if ( server->buf->len == 0 )
return;
}
}
// SSR end
int s = send(server->fd, server->buf->array, server->buf->len, 0);
if (s == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data, wait for send
server->buf->idx = 0;
ev_io_stop(EV_A_ & remote_recv_ctx->io);
ev_io_start(EV_A_ & server->send_ctx->io);
} else {
ERROR("send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
} else if (s < server->buf->len) {
server->buf->len -= s;
server->buf->idx = s;
ev_io_stop(EV_A_ & remote_recv_ctx->io);
ev_io_start(EV_A_ & server->send_ctx->io);
}
}
static void
remote_send_cb(EV_P_ ev_io *w, int revents)
{
remote_ctx_t *remote_send_ctx = (remote_ctx_t *)w;
remote_t *remote = remote_send_ctx->remote;
server_t *server = remote->server;
server_def_t *server_env = server->server_env;
if (!remote_send_ctx->connected) {
struct sockaddr_storage addr;
memset(&addr, 0, sizeof(struct sockaddr_storage));
socklen_t len = sizeof addr;
int r = getpeername(remote->fd, (struct sockaddr *)&addr, &len);
if (r == 0) {
remote_send_ctx->connected = 1;
ev_io_stop(EV_A_ & remote_send_ctx->io);
//ev_io_stop(EV_A_ & server->recv_ctx->io);
ev_timer_stop(EV_A_ & remote_send_ctx->watcher);
ev_timer_start(EV_A_ & remote->recv_ctx->watcher);
// send destaddr
buffer_t ss_addr_to_send;
buffer_t *abuf = &ss_addr_to_send;
balloc(abuf, BUF_SIZE);
if (server->hostname_len > 0
&& validate_hostname(server->hostname, server->hostname_len)) { // HTTP/SNI
uint16_t port;
if (AF_INET6 == server->destaddr.ss_family) { // IPv6
port = (((struct sockaddr_in6 *)&(server->destaddr))->sin6_port);
} else { // IPv4
port = (((struct sockaddr_in *)&(server->destaddr))->sin_port);
}
abuf->array[abuf->len++] = 3; // Type 3 is hostname
abuf->array[abuf->len++] = server->hostname_len;
memcpy(abuf->array + abuf->len, server->hostname, server->hostname_len);
abuf->len += server->hostname_len;
memcpy(abuf->array + abuf->len, &port, 2);
} else if (AF_INET6 == server->destaddr.ss_family) { // IPv6
abuf->array[abuf->len++] = 4; // Type 4 is IPv6 address
size_t in6_addr_len = sizeof(struct in6_addr);
memcpy(abuf->array + abuf->len,
&(((struct sockaddr_in6 *)&(server->destaddr))->sin6_addr),
in6_addr_len);
abuf->len += in6_addr_len;
memcpy(abuf->array + abuf->len,
&(((struct sockaddr_in6 *)&(server->destaddr))->sin6_port),
2);
} else { // IPv4
abuf->array[abuf->len++] = 1; // Type 1 is IPv4 address
size_t in_addr_len = sizeof(struct in_addr);
memcpy(abuf->array + abuf->len,
&((struct sockaddr_in *)&(server->destaddr))->sin_addr, in_addr_len);
abuf->len += in_addr_len;
memcpy(abuf->array + abuf->len,
&((struct sockaddr_in *)&(server->destaddr))->sin_port, 2);
}
abuf->len += 2;
if (remote->buf->len > 0) {
brealloc(remote->buf, remote->buf->len + abuf->len, BUF_SIZE);
memmove(remote->buf->array + abuf->len, remote->buf->array, remote->buf->len);
memcpy(remote->buf->array, abuf->array, abuf->len);
remote->buf->len += abuf->len;
} else {
brealloc(remote->buf, abuf->len, BUF_SIZE);
memcpy(remote->buf->array, abuf->array, abuf->len);
remote->buf->len = abuf->len;
}
bfree(abuf);
// SSR beg
server_info _server_info;
if (server_env->obfs_plugin) {
server_env->obfs_plugin->get_server_info(server->obfs, &_server_info);
_server_info.head_len = get_head_size(remote->buf->array, remote->buf->len, 30);
server_env->obfs_plugin->set_server_info(server->obfs, &_server_info);
}
if (server_env->protocol_plugin) {
obfs_class *protocol_plugin = server_env->protocol_plugin;
if (protocol_plugin->client_pre_encrypt) {
remote->buf->len = protocol_plugin->client_pre_encrypt(server->protocol, &remote->buf->array, remote->buf->len, &remote->buf->capacity);
}
}
int err = ss_encrypt(&server_env->cipher, remote->buf, server->e_ctx, BUF_SIZE);
if (err) {
LOGE("invalid password or cipher");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (server_env->obfs_plugin) {
obfs_class *obfs_plugin = server_env->obfs_plugin;
if (obfs_plugin->client_encode) {
remote->buf->len = obfs_plugin->client_encode(server->obfs, &remote->buf->array, remote->buf->len, &remote->buf->capacity);
}
}
// SSR end
ev_io_start(EV_A_ & remote->recv_ctx->io);
} else {
ERROR("getpeername");
// not connected
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
if (remote->buf->len == 0) {
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else {
// has data to send
ssize_t s = send(remote->fd, remote->buf->array + remote->buf->idx,
remote->buf->len, 0);
if (s == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
ERROR("send");
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
} else if (s < remote->buf->len) {
// partly sent, move memory, wait for the next time to send
remote->buf->len -= s;
remote->buf->idx += s;
return;
} else {
// all sent out, wait for reading
remote->buf->len = 0;
remote->buf->idx = 0;
ev_io_stop(EV_A_ & remote_send_ctx->io);
ev_io_start(EV_A_ & server->recv_ctx->io);
}
}
}
static remote_t *
new_remote(int fd, int timeout)
{
remote_t *remote = ss_malloc(sizeof(remote_t));
memset(remote, 0, sizeof(remote_t));
remote->buf = ss_malloc(sizeof(buffer_t));
remote->recv_ctx = ss_malloc(sizeof(remote_ctx_t));
remote->send_ctx = ss_malloc(sizeof(remote_ctx_t));
balloc(remote->buf, BUF_SIZE);
memset(remote->recv_ctx, 0, sizeof(remote_ctx_t));
memset(remote->send_ctx, 0, sizeof(remote_ctx_t));
remote->recv_ctx->connected = 0;
remote->send_ctx->connected = 0;
remote->fd = fd;
remote->recv_ctx->remote = remote;
remote->send_ctx->remote = remote;
ev_io_init(&remote->recv_ctx->io, remote_recv_cb, fd, EV_READ);
ev_io_init(&remote->send_ctx->io, remote_send_cb, fd, EV_WRITE);
ev_timer_init(&remote->send_ctx->watcher, remote_timeout_cb,
min(MAX_CONNECT_TIMEOUT, timeout), 0);
ev_timer_init(&remote->recv_ctx->watcher, remote_timeout_cb,
timeout, 0);
return remote;
}
static void
free_remote(remote_t *remote)
{
if (remote != NULL) {
if (remote->server != NULL) {
remote->server->remote = NULL;
}
if (remote->buf != NULL) {
bfree(remote->buf);
ss_free(remote->buf);
}
ss_free(remote->recv_ctx);
ss_free(remote->send_ctx);
ss_free(remote);
}
}
static void
close_and_free_remote(EV_P_ remote_t *remote)
{
if (remote != NULL) {
ev_timer_stop(EV_A_ & remote->send_ctx->watcher);
ev_timer_stop(EV_A_ & remote->recv_ctx->watcher);
ev_io_stop(EV_A_ & remote->send_ctx->io);
ev_io_stop(EV_A_ & remote->recv_ctx->io);
close(remote->fd);
free_remote(remote);
}
}
static server_t *
new_server(int fd, listen_ctx_t* profile) {
server_t *server = ss_malloc(sizeof(server_t));
memset(server, 0, sizeof(server_t));
server->listener = profile;
server->recv_ctx = ss_malloc(sizeof(server_ctx_t));
server->send_ctx = ss_malloc(sizeof(server_ctx_t));
server->buf = ss_malloc(sizeof(buffer_t));
balloc(server->buf, BUF_SIZE);
memset(server->recv_ctx, 0, sizeof(server_ctx_t));
memset(server->send_ctx, 0, sizeof(server_ctx_t));
server->recv_ctx->connected = 0;
server->send_ctx->connected = 0;
server->fd = fd;
server->recv_ctx->server = server;
server->send_ctx->server = server;
server->hostname = NULL;
server->hostname_len = 0;
ev_io_init(&server->recv_ctx->io, server_recv_cb, fd, EV_READ);
ev_io_init(&server->send_ctx->io, server_send_cb, fd, EV_WRITE);
cork_dllist_add(&profile->connections_eden, &server->entries);
cork_dllist_add(&all_connections, &server->entries_all);
return server;
}
static void
release_profile(listen_ctx_t *profile)
{
int i;
for(i = 0; i < profile->server_num; i++)
{
server_def_t *server_env = &profile->servers[i];
ss_free(server_env->host);
if(server_env->addr != server_env->addr_udp)
{
ss_free(server_env->addr_udp);
}
ss_free(server_env->addr);
ss_free(server_env->psw);
ss_free(server_env->protocol_name);
ss_free(server_env->obfs_name);
ss_free(server_env->protocol_param);
ss_free(server_env->obfs_param);
ss_free(server_env->protocol_global);
ss_free(server_env->obfs_global);
if(server_env->protocol_plugin){
free_obfs_class(server_env->protocol_plugin);
}
if(server_env->obfs_plugin){
free_obfs_class(server_env->obfs_plugin);
}
ss_free(server_env->id);
ss_free(server_env->group);
enc_release(&server_env->cipher);
}
ss_free(profile);
}
static void
check_and_free_profile(listen_ctx_t *profile)
{
int i;
if(profile == current_profile)
{
return;
}
// if this connection is created from an inactive profile, then we need to free the profile
// when the last connection of that profile is colsed
if(!cork_dllist_is_empty(&profile->connections_eden))
{
return;
}
for(i = 0; i < profile->server_num; i++)
{
if(!cork_dllist_is_empty(&profile->servers[i].connections))
{
return;
}
}
// No connections anymore
cork_dllist_remove(&profile->entries);
release_profile(profile);
}
static void
free_server(server_t *server)
{
if(server != NULL) {
listen_ctx_t *profile = server->listener;
server_def_t *server_env = server->server_env;
cork_dllist_remove(&server->entries);
cork_dllist_remove(&server->entries_all);
if (server->remote != NULL) {
server->remote->server = NULL;
}
if (server->buf != NULL) {
bfree(server->buf);
ss_free(server->buf);
}
if (server->hostname != NULL) {
ss_free(server->hostname);
}
// if (server != NULL) {
// if (server->remote != NULL) {
// server->remote->server = NULL;
// }
if (server_env) {
if (server->e_ctx != NULL) {
enc_ctx_release(&server_env->cipher, server->e_ctx);
ss_free(server->e_ctx);
}
if (server->d_ctx != NULL) {
enc_ctx_release(&server_env->cipher, server->d_ctx);
ss_free(server->d_ctx);
}
// if (server->buf != NULL) {
// bfree(server->buf);
// ss_free(server->buf);
// }
// SSR beg
if (server_env->obfs_plugin) {
server_env->obfs_plugin->dispose(server->obfs);
server->obfs = NULL;
// free_obfs_class(server->obfs_plugin);
// server->obfs_plugin = NULL;
}
if (server_env->protocol_plugin) {
server_env->protocol_plugin->dispose(server->protocol);
server->protocol = NULL;
// free_obfs_class(server->protocol_plugin);
// server->protocol_plugin = NULL;
}
// SSR end
}
ss_free(server->recv_ctx);
ss_free(server->send_ctx);
ss_free(server);
// after free server, we need to check the profile
check_and_free_profile(profile);
}
}
static void
close_and_free_server(EV_P_ server_t *server)
{
if (server != NULL) {
ev_io_stop(EV_A_ & server->send_ctx->io);
ev_io_stop(EV_A_ & server->recv_ctx->io);
close(server->fd);
free_server(server);
}
}
static void
accept_cb(EV_P_ ev_io *w, int revents)
{
listen_ctx_t *listener = (listen_ctx_t *)w;
struct sockaddr_storage destaddr;
memset(&destaddr, 0, sizeof(struct sockaddr_storage));
int err;
int serverfd = accept(listener->fd, NULL, NULL);
if (serverfd == -1) {
ERROR("accept");
return;
}
err = getdestaddr(serverfd, &destaddr);
if (err) {
ERROR("getdestaddr");
return;
}
setnonblocking(serverfd);
int opt = 1;
setsockopt(serverfd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(serverfd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
// pick a server
int index = rand() % listener->server_num;
server_def_t *server_env = &listener->servers[index];
struct sockaddr *remote_addr = (struct sockaddr *) server_env->addr;
int remotefd = socket(remote_addr->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (remotefd == -1) {
ERROR("socket");
return;
}
// Set flags
setsockopt(remotefd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(remotefd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
// Setup
int keepAlive = 1;
int keepIdle = 40;
int keepInterval = 20;
int keepCount = 5;
setsockopt(remotefd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepAlive, sizeof(keepAlive));
setsockopt(remotefd, SOL_TCP, TCP_KEEPIDLE, (void *)&keepIdle, sizeof(keepIdle));
setsockopt(remotefd, SOL_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval));
setsockopt(remotefd, SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount));
// Setup
setnonblocking(remotefd);
// Enable MPTCP
if (listener->mptcp == 1) {
int err = setsockopt(remotefd, SOL_TCP, MPTCP_ENABLED, &opt, sizeof(opt));
if (err == -1) {
ERROR("failed to enable multipath TCP");
}
}
server_t *server = new_server(serverfd, listener);
remote_t *remote = new_remote(remotefd, listener->timeout);
server->destaddr = destaddr;
server->server_env = server_env;
// expelled from eden
cork_dllist_remove(&server->entries);
cork_dllist_add(&server_env->connections, &server->entries);
int r = connect(remotefd, remote_addr, get_sockaddr_len(remote_addr));
if (r == -1 && errno != CONNECT_IN_PROGRESS) {
ERROR("connect");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
// init server cipher
if (server_env->cipher.enc_method > TABLE) {
server->e_ctx = ss_malloc(sizeof(struct enc_ctx));
server->d_ctx = ss_malloc(sizeof(struct enc_ctx));
enc_ctx_init(&server_env->cipher, server->e_ctx, 1);
enc_ctx_init(&server_env->cipher, server->d_ctx, 0);
} else {
server->e_ctx = NULL;
server->d_ctx = NULL;
}
// SSR beg
// remote->remote_index = index;
// server->obfs_plugin = new_obfs_class(listener->obfs_name);
// if (server->obfs_plugin) {
// server->obfs = server->obfs_plugin->new_obfs();
// }
// server->protocol_plugin = new_obfs_class(listener->protocol_name);
// if (server->protocol_plugin) {
// server->protocol = server->protocol_plugin->new_obfs();
// }
// if (listener->list_obfs_global[remote->remote_index] == NULL && server->obfs_plugin) {
// listener->list_obfs_global[remote->remote_index] = server->obfs_plugin->init_data();
// }
// if (listener->list_protocol_global[remote->remote_index] == NULL && server->protocol_plugin) {
// listener->list_protocol_global[remote->remote_index] = server->protocol_plugin->init_data();
// }
server_info _server_info;
memset(&_server_info, 0, sizeof(server_info));
strcpy(_server_info.host, server_env->host);
_server_info.port = server_env->port;
_server_info.param = server_env->obfs_param;
_server_info.g_data = server_env->obfs_global;
_server_info.head_len = (AF_INET6 == server->destaddr.ss_family ? 19 : 7);
_server_info.iv = server->e_ctx->evp.iv;
_server_info.iv_len = enc_get_iv_len(&server_env->cipher);
_server_info.key = enc_get_key(&server_env->cipher);
_server_info.key_len = enc_get_key_len(&server_env->cipher);
_server_info.tcp_mss = 1452;
_server_info.buffer_size = BUF_SIZE;
_server_info.cipher_env = &server_env->cipher;
if (server_env->obfs_plugin) {
server->obfs = server_env->obfs_plugin->new_obfs();
server_env->obfs_plugin->set_server_info(server->obfs, &_server_info);
}
_server_info.param = server_env->protocol_param;
_server_info.g_data = server_env->protocol_global;
if (server_env->protocol_plugin) {
server->protocol = server_env->protocol_plugin->new_obfs();
_server_info.overhead = server_env->protocol_plugin->get_overhead(server->protocol)
+ (server_env->obfs_plugin ? server_env->obfs_plugin->get_overhead(server->obfs) : 0);
server_env->protocol_plugin->set_server_info(server->protocol, &_server_info);
}
// SSR end
server->remote = remote;
remote->server = server;
if (verbose) {
int port = ((struct sockaddr_in*)&destaddr)->sin_port;
port = (uint16_t)(port >> 8 | port << 8);
LOGI("connect to %s:%d", inet_ntoa(((struct sockaddr_in*)&destaddr)->sin_addr), port);
}
// listen to remote connected event
ev_io_start(EV_A_ & remote->send_ctx->io);
ev_timer_start(EV_A_ & remote->send_ctx->watcher);
ev_io_start(EV_A_ & server->recv_ctx->io);
}
void
signal_cb(int dummy)
{
keep_resolving = 0;
exit(-1);
}
static void
init_obfs(server_def_t *serv, char *protocol, char *protocol_param, char *obfs, char *obfs_param)
{
serv->protocol_name = protocol;
serv->protocol_param = protocol_param;
serv->protocol_plugin = new_obfs_class(protocol);
serv->obfs_name = obfs;
serv->obfs_param = obfs_param;
serv->obfs_plugin = new_obfs_class(obfs);
if (serv->obfs_plugin) {
serv->obfs_global = serv->obfs_plugin->init_data();
}
if (serv->protocol_plugin) {
serv->protocol_global = serv->protocol_plugin->init_data();
}
}
int
main(int argc, char **argv)
{
srand(time(NULL));
int i, c;
int pid_flags = 0;
int mptcp = 0;
int mtu = 0;
char *user = NULL;
char *local_port = NULL;
char *local_addr = NULL;
char *password = NULL;
char *timeout = NULL;
char *protocol = NULL; // SSR
char *protocol_param = NULL; // SSR
char *method = NULL;
char *obfs = NULL; // SSR
char *obfs_param = NULL; // SSR
char *pid_path = NULL;
char *conf_path = NULL;
int use_new_profile = 0;
jconf_t *conf = NULL;
int remote_num = 0;
ss_addr_t remote_addr[MAX_REMOTE_NUM];
char *remote_port = NULL;
ss_addr_t tunnel_addr = { .host = NULL, .port = NULL };
int option_index = 0;
static struct option long_options[] = {
{ "mtu", required_argument, 0, 0 },
{ "mptcp", no_argument, 0, 0 },
{ "help", no_argument, 0, 0 },
{ 0, 0, 0, 0 }
};
opterr = 0;
USE_TTY();
while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:c:b:a:n:huUvA6"
"O:o:G:g:",
long_options, &option_index)) != -1) {
switch (c) {
case 0:
if (option_index == 0) {
mtu = atoi(optarg);
LOGI("set MTU to %d", mtu);
} else if (option_index == 1) {
mptcp = 1;
LOGI("enable multipath TCP");
} else if (option_index == 2) {
usage();
exit(EXIT_SUCCESS);
}
break;
case 's':
if (remote_num < MAX_REMOTE_NUM) {
remote_addr[remote_num].host = optarg;
remote_addr[remote_num++].port = NULL;
}
break;
case 'p':
remote_port = optarg;
break;
case 'l':
local_port = optarg;
break;
case 'k':
password = optarg;
break;
case 'f':
pid_flags = 1;
pid_path = optarg;
break;
case 't':
timeout = optarg;
break;
// SSR beg
case 'O':
protocol = optarg;
break;
case 'm':
method = optarg;
break;
case 'o':
obfs = optarg;
break;
case 'G':
protocol_param = optarg;
break;
case 'g':
obfs_param = optarg;
break;
// SSR end
case 'c':
conf_path = optarg;
break;
case 'b':
local_addr = optarg;
break;
case 'a':
user = optarg;
break;
#ifdef HAVE_SETRLIMIT
case 'n':
nofile = atoi(optarg);
break;
#endif
case 'u':
mode = TCP_AND_UDP;
break;
case 'U':
mode = UDP_ONLY;
break;
case 'v':
verbose = 1;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'A':
LOGI("The 'A' argument is deprecate! Ignored.");
break;
case '6':
ipv6first = 1;
break;
case '?':
// The option character is not recognized.
LOGE("Unrecognized option: %s", optarg);
opterr = 1;
break;
}
}
if (opterr) {
usage();
exit(EXIT_FAILURE);
}
if (argc == 1) {
if (conf_path == NULL) {
conf_path = DEFAULT_CONF_PATH;
}
}
if (conf_path != NULL) {
conf = read_jconf(conf_path);
if(conf->conf_ver != CONF_VER_LEGACY){
use_new_profile = 1;
} else {
if (remote_num == 0) {
remote_num = conf->server_legacy.remote_num;
for (i = 0; i < remote_num; i++)
remote_addr[i] = conf->server_legacy.remote_addr[i];
}
if (remote_port == NULL) {
remote_port = conf->server_legacy.remote_port;
}
if (local_addr == NULL) {
local_addr = conf->server_legacy.local_addr;
}
if (local_port == NULL) {
local_port = conf->server_legacy.local_port;
}
if (password == NULL) {
password = conf->server_legacy.password;
}
// SSR beg
if (protocol == NULL) {
protocol = conf->server_legacy.protocol;
LOGI("protocol %s", protocol);
}
if (protocol_param == NULL) {
protocol_param = conf->server_legacy.protocol_param;
LOGI("protocol_param %s", protocol_param);
}
if (method == NULL) {
method = conf->server_legacy.method;
LOGI("method %s", method);
}
if (obfs == NULL) {
obfs = conf->server_legacy.obfs;
LOGI("obfs %s", obfs);
}
if (obfs_param == NULL) {
obfs_param = conf->server_legacy.obfs_param;
LOGI("obfs_param %s", obfs_param);
}
// SSR end
}
if (timeout == NULL) {
timeout = conf->timeout;
}
if (user == NULL) {
user = conf->user;
}
if (mtu == 0) {
mtu = conf->mtu;
}
if (mptcp == 0) {
mptcp = conf->mptcp;
}
#ifdef HAVE_SETRLIMIT
if (nofile == 0) {
nofile = conf->nofile;
}
/*
* no need to check the return value here since we will show
* the user an error message if setrlimit(2) fails
*/
if (nofile > 1024) {
if (verbose) {
LOGI("setting NOFILE to %d", nofile);
}
set_nofile(nofile);
}
#endif
}
if (protocol && strcmp(protocol, "verify_sha1") == 0) {
LOGI("The verify_sha1 protocol is deprecate! Fallback to origin protocol.");
protocol = NULL;
}
if (remote_num == 0 || remote_port == NULL ||
local_port == NULL || password == NULL) {
usage();
exit(EXIT_FAILURE);
}
if (method == NULL) {
method = "rc4-md5";
}
if (timeout == NULL) {
timeout = "600";
}
#ifdef HAVE_SETRLIMIT
/*
* no need to check the return value here since we will show
* the user an error message if setrlimit(2) fails
*/
if (nofile > 1024) {
if (verbose) {
LOGI("setting NOFILE to %d", nofile);
}
set_nofile(nofile);
}
#endif
if (local_addr == NULL) {
local_addr = "127.0.0.1";
}
if (pid_flags) {
USE_SYSLOG(argv[0]);
daemonize(pid_path);
}
if (ipv6first) {
LOGI("resolving hostname to IPv6 address first");
}
// ignore SIGPIPE
signal(SIGPIPE, SIG_IGN);
signal(SIGABRT, SIG_IGN);
signal(SIGINT, signal_cb);
signal(SIGTERM, signal_cb);
// Setup profiles
listen_ctx_t *profile = (listen_ctx_t *)ss_malloc(sizeof(listen_ctx_t));
memset(profile, 0, sizeof(listen_ctx_t));
cork_dllist_init(&all_connections);
cork_dllist_init(&profile->connections_eden);
profile->timeout = atoi(timeout);
profile->mptcp = mptcp;
if(use_new_profile) {
char port[6];
ss_server_new_1_t *servers = &conf->server_new_1;
profile->server_num = servers->server_num;
for(i = 0; i < servers->server_num; i++){
server_def_t *serv = &profile->servers[i];
ss_server_t *serv_cfg = &servers->servers[i];
struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage));
char *host = serv_cfg->server;
snprintf(port, sizeof(port), "%d", serv_cfg->server_port);
if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) {
FATAL("failed to resolve the provided hostname");
}
serv->addr = serv->addr_udp = storage;
serv->addr_len = serv->addr_udp_len = get_sockaddr_len((struct sockaddr *) storage);
serv->port = serv->udp_port = serv_cfg->server_port;
// set udp port
if (serv_cfg->server_udp_port != 0 && serv_cfg->server_udp_port != serv_cfg->server_port) {
storage = ss_malloc(sizeof(struct sockaddr_storage));
snprintf(port, sizeof(port), "%d", serv_cfg->server_udp_port);
if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) {
FATAL("failed to resolve the provided hostname");
}
serv->addr_udp = storage;
serv->addr_udp_len = get_sockaddr_len((struct sockaddr *) storage);
serv->udp_port = serv_cfg->server_udp_port;
}
serv->host = ss_strdup(host);
// Setup keys
LOGI("initializing ciphers... %s", serv_cfg->method);
enc_init(&serv->cipher, serv_cfg->password, serv_cfg->method);
serv->psw = ss_strdup(serv_cfg->password);
if (serv_cfg->protocol && strcmp(serv_cfg->protocol, "verify_sha1") == 0) {
ss_free(serv_cfg->protocol);
}
cork_dllist_init(&serv->connections);
// init obfs
init_obfs(serv, ss_strdup(serv_cfg->protocol), ss_strdup(serv_cfg->protocol_param), ss_strdup(serv_cfg->obfs), ss_strdup(serv_cfg->obfs_param));
serv->enable = serv_cfg->enable;
serv->id = ss_strdup(serv_cfg->id);
serv->group = ss_strdup(serv_cfg->group);
serv->udp_over_tcp = serv_cfg->udp_over_tcp;
}
} else {
profile->server_num = remote_num;
for(i = 0; i < remote_num; i++) {
server_def_t *serv = &profile->servers[i];
char *host = remote_addr[i].host;
char *port = remote_addr[i].port == NULL ? remote_port :
remote_addr[i].port;
struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage));
if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) {
FATAL("failed to resolve the provided hostname");
}
serv->host = ss_strdup(host);
serv->addr = serv->addr_udp = storage;
serv->addr_len = serv->addr_udp_len = get_sockaddr_len((struct sockaddr *)storage);
serv->port = serv->udp_port = atoi(port);
// Setup keys
LOGI("initializing ciphers... %s", method);
enc_init(&serv->cipher, password, method);
serv->psw = ss_strdup(password);
cork_dllist_init(&serv->connections);
// init obfs
init_obfs(serv, ss_strdup(protocol), ss_strdup(protocol_param), ss_strdup(obfs), ss_strdup(obfs_param));
serv->enable = 1;
}
}
// Init profiles
cork_dllist_init(&inactive_profiles);
current_profile = profile;
struct ev_loop *loop = EV_DEFAULT;
listen_ctx_t *listen_ctx = current_profile;
if (mode != UDP_ONLY) {
// Setup socket
int listenfd;
listenfd = create_and_bind(local_addr, local_port);
if (listenfd == -1) {
FATAL("bind() error");
}
if (listen(listenfd, SOMAXCONN) == -1) {
FATAL("listen() error");
}
setnonblocking(listenfd);
listen_ctx->fd = listenfd;
ev_io_init(&listen_ctx->io, accept_cb, listenfd, EV_READ);
ev_io_start(loop, &listen_ctx->io);
}
// Setup UDP
if (mode != TCP_ONLY) {
LOGI("UDP relay enabled");
init_udprelay(local_addr, local_port, (struct sockaddr*)listen_ctx->servers[0].addr_udp,
listen_ctx->servers[0].addr_udp_len, tunnel_addr, mtu, listen_ctx->timeout, NULL, &listen_ctx->servers[0].cipher, listen_ctx->servers[0].protocol_name, listen_ctx->servers[0].protocol_param);
}
if (mode == UDP_ONLY) {
LOGI("TCP relay disabled");
}
LOGI("listening at %s:%s", local_addr, local_port);
// setuid
if (user != NULL && ! run_as(user)) {
FATAL("failed to switch user");
}
if (geteuid() == 0){
LOGI("running from root user");
}
ev_run(loop, 0);
// TODO: release?
return 0;
}
|
281677160/openwrt-package | 55,147 | luci-app-ssr-plus/shadowsocksr-libev/src/src/server.c | /*
* server.c - Provide shadowsocks service
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <locale.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <math.h>
#ifndef __MINGW32__
#include <netdb.h>
#include <errno.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <sys/un.h>
#endif
#include <libcork/core.h>
#include <udns.h>
#ifdef __MINGW32__
#include "win32.h"
#endif
#if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H) && defined(__linux__)
#include <net/if.h>
#include <sys/ioctl.h>
#define SET_INTERFACE
#endif
#include "netutils.h"
#include "utils.h"
#include "acl.h"
#include "server.h"
#ifndef EAGAIN
#define EAGAIN EWOULDBLOCK
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK EAGAIN
#endif
#ifndef BUF_SIZE
#define BUF_SIZE 2048
#endif
#ifndef SSMAXCONN
#define SSMAXCONN 1024
#endif
#ifndef UPDATE_INTERVAL
#define UPDATE_INTERVAL 30
#endif
static void signal_cb(EV_P_ ev_signal *w, int revents);
static void accept_cb(EV_P_ ev_io *w, int revents);
static void server_send_cb(EV_P_ ev_io *w, int revents);
static void server_recv_cb(EV_P_ ev_io *w, int revents);
static void remote_recv_cb(EV_P_ ev_io *w, int revents);
static void remote_send_cb(EV_P_ ev_io *w, int revents);
static void server_timeout_cb(EV_P_ ev_timer *watcher, int revents);
static void block_list_clear_cb(EV_P_ ev_timer *watcher, int revents);
static remote_t *new_remote(int fd);
static server_t *new_server(int fd, listen_ctx_t *listener);
static remote_t *connect_to_remote(EV_P_ struct addrinfo *res,
server_t *server);
static void free_remote(remote_t *remote);
static void close_and_free_remote(EV_P_ remote_t *remote);
static void free_server(server_t *server);
static void close_and_free_server(EV_P_ server_t *server);
static void server_resolve_cb(struct sockaddr *addr, void *data);
static void query_free_cb(void *data);
static int is_header_complete(const buffer_t *buf);
int verbose = 0;
static int acl = 0;
static int mode = TCP_ONLY;
static int ipv6first = 0;
static int fast_open = 0;
#ifdef HAVE_SETRLIMIT
static int nofile = 0;
#endif
static int remote_conn = 0;
static int server_conn = 0;
static char *bind_address = NULL;
static char *server_port = NULL;
static char *manager_address = NULL;
uint64_t tx = 0;
uint64_t rx = 0;
ev_timer stat_update_watcher;
ev_timer block_list_watcher;
static struct cork_dllist connections;
static void
stat_update_cb(EV_P_ ev_timer *watcher, int revents)
{
#ifndef __MINGW32__
struct sockaddr_un svaddr, claddr;
#endif
int sfd = -1;
size_t msgLen;
char resp[BUF_SIZE];
if (verbose) {
LOGI("update traffic stat: tx: %" PRIu64 " rx: %" PRIu64 "", tx, rx);
}
snprintf(resp, BUF_SIZE, "stat: {\"%s\":%" PRIu64 "}", server_port, tx + rx);
msgLen = strlen(resp) + 1;
ss_addr_t ip_addr = { .host = NULL, .port = NULL };
parse_addr(manager_address, &ip_addr);
if (ip_addr.host == NULL || ip_addr.port == NULL) {
#ifndef __MINGW32__
sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sfd == -1) {
ERROR("stat_socket");
return;
}
memset(&claddr, 0, sizeof(struct sockaddr_un));
claddr.sun_family = AF_UNIX;
snprintf(claddr.sun_path, sizeof(claddr.sun_path), "/tmp/shadowsocks.%s", server_port);
unlink(claddr.sun_path);
if (bind(sfd, (struct sockaddr *)&claddr, sizeof(struct sockaddr_un)) == -1) {
ERROR("stat_bind");
close(sfd);
return;
}
memset(&svaddr, 0, sizeof(struct sockaddr_un));
svaddr.sun_family = AF_UNIX;
strncpy(svaddr.sun_path, manager_address, sizeof(svaddr.sun_path) - 1);
if (sendto(sfd, resp, strlen(resp) + 1, 0, (struct sockaddr *)&svaddr,
sizeof(struct sockaddr_un)) != msgLen) {
ERROR("stat_sendto");
close(sfd);
return;
}
unlink(claddr.sun_path);
#else
ERROR("unsupported platform");
return;
#endif
} else {
struct sockaddr_storage storage;
memset(&storage, 0, sizeof(struct sockaddr_storage));
if (get_sockaddr(ip_addr.host, ip_addr.port, &storage, 0, ipv6first) == -1) {
ERROR("failed to parse the manager addr");
return;
}
sfd = socket(storage.ss_family, SOCK_DGRAM, 0);
if (sfd == -1) {
ERROR("stat_socket");
return;
}
size_t addr_len = get_sockaddr_len((struct sockaddr *)&storage);
if (sendto(sfd, resp, strlen(resp) + 1, 0, (struct sockaddr *)&storage,
addr_len) != msgLen) {
ERROR("stat_sendto");
close(sfd);
return;
}
}
close(sfd);
}
static void
free_connections(struct ev_loop *loop)
{
struct cork_dllist_item *curr, *next;
cork_dllist_foreach_void(&connections, curr, next) {
server_t *server = cork_container_of(curr, server_t, entries);
remote_t *remote = server->remote;
close_and_free_server(loop, server);
close_and_free_remote(loop, remote);
}
}
static int
is_header_complete(const buffer_t *buf)
{
size_t header_len = 0;
size_t buf_len = buf->len;
char atyp = buf->array[header_len];
// 1 byte for atyp
header_len++;
if ((atyp & ADDRTYPE_MASK) == 1) {
// IP V4
header_len += sizeof(struct in_addr);
} else if ((atyp & ADDRTYPE_MASK) == 3) {
// Domain name
// domain len + len of domain
if (buf_len < header_len + 1)
return 0;
uint8_t name_len = *(uint8_t *)(buf->array + header_len);
header_len += name_len + 1;
} else if ((atyp & ADDRTYPE_MASK) == 4) {
// IP V6
header_len += sizeof(struct in6_addr);
} else {
return -1;
}
// len of port
header_len += 2;
return buf_len >= header_len ? 1 : 0;
}
static char *
get_peer_name(int fd)
{
static char peer_name[INET6_ADDRSTRLEN] = { 0 };
struct sockaddr_storage addr;
socklen_t len = sizeof(struct sockaddr_storage);
memset(&addr, 0, len);
memset(peer_name, 0, INET6_ADDRSTRLEN);
int err = getpeername(fd, (struct sockaddr *)&addr, &len);
if (err == 0) {
if (addr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
dns_ntop(AF_INET, &s->sin_addr, peer_name, INET_ADDRSTRLEN);
} else if (addr.ss_family == AF_INET6) {
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
dns_ntop(AF_INET6, &s->sin6_addr, peer_name, INET6_ADDRSTRLEN);
}
} else {
return NULL;
}
return peer_name;
}
#ifdef __linux__
static void
set_linger(int fd)
{
struct linger so_linger;
memset(&so_linger, 0, sizeof(struct linger));
so_linger.l_onoff = 1;
so_linger.l_linger = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER, &so_linger, sizeof so_linger);
}
#endif
static void
reset_addr(int fd)
{
char *peer_name;
peer_name = get_peer_name(fd);
if (peer_name != NULL) {
remove_from_block_list(peer_name);
}
}
static void
report_addr(int fd, int err_level)
{
#ifdef __linux__
set_linger(fd);
#endif
char *peer_name;
peer_name = get_peer_name(fd);
if (peer_name != NULL) {
LOGE("failed to handshake with %s", peer_name);
update_block_list(peer_name, err_level);
}
}
int
setfastopen(int fd)
{
int s = 0;
#ifdef TCP_FASTOPEN
if (fast_open) {
#ifdef __APPLE__
int opt = 1;
#else
int opt = 5;
#endif
s = setsockopt(fd, IPPROTO_TCP, TCP_FASTOPEN, &opt, sizeof(opt));
if (s == -1) {
if (errno == EPROTONOSUPPORT || errno == ENOPROTOOPT) {
LOGE("fast open is not supported on this platform");
fast_open = 0;
} else {
ERROR("setsockopt");
}
}
}
#endif
return s;
}
#ifndef __MINGW32__
int
setnonblocking(int fd)
{
int flags;
if (-1 == (flags = fcntl(fd, F_GETFL, 0))) {
flags = 0;
}
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
#endif
int
create_and_bind(const char *host, const char *port, int mptcp)
{
struct addrinfo hints;
struct addrinfo *result, *rp, *ipv4v6bindall;
int s, listen_sock;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; /* For wildcard IP address */
hints.ai_protocol = IPPROTO_TCP;
for (int i = 1; i < 8; i++) {
s = getaddrinfo(host, port, &hints, &result);
if (s == 0) {
break;
} else {
sleep(pow(2, i));
LOGE("failed to resolve server name, wait %.0f seconds", pow(2, i));
}
}
if (s != 0) {
LOGE("getaddrinfo: %s", gai_strerror(s));
return -1;
}
rp = result;
/*
* On Linux, with net.ipv6.bindv6only = 0 (the default), getaddrinfo(NULL) with
* AI_PASSIVE returns 0.0.0.0 and :: (in this order). AI_PASSIVE was meant to
* return a list of addresses to listen on, but it is impossible to listen on
* 0.0.0.0 and :: at the same time, if :: implies dualstack mode.
*/
if (!host) {
ipv4v6bindall = result;
/* Loop over all address infos found until a IPV6 address is found. */
while (ipv4v6bindall) {
if (ipv4v6bindall->ai_family == AF_INET6) {
rp = ipv4v6bindall; /* Take first IPV6 address available */
break;
}
ipv4v6bindall = ipv4v6bindall->ai_next; /* Get next address info, if any */
}
}
for (/*rp = result*/; rp != NULL; rp = rp->ai_next) {
listen_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (listen_sock == -1) {
continue;
}
if (rp->ai_family == AF_INET6) {
int ipv6only = host ? 1 : 0;
setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6only, sizeof(ipv6only));
}
int opt = 1;
setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(listen_sock, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
int err = set_reuseport(listen_sock);
if (err == 0) {
LOGI("tcp port reuse enabled");
}
if (mptcp == 1) {
int err = setsockopt(listen_sock, SOL_TCP, MPTCP_ENABLED, &opt, sizeof(opt));
if (err == -1) {
ERROR("failed to enable multipath TCP");
}
}
s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen);
if (s == 0) {
/* We managed to bind successfully! */
break;
} else {
ERROR("bind");
}
close(listen_sock);
}
if (rp == NULL) {
LOGE("Could not bind");
return -1;
}
freeaddrinfo(result);
return listen_sock;
}
static remote_t *
connect_to_remote(EV_P_ struct addrinfo *res,
server_t *server)
{
int sockfd;
#ifdef SET_INTERFACE
const char *iface = server->listen_ctx->iface;
#endif
if (acl) {
char ipstr[INET6_ADDRSTRLEN];
memset(ipstr, 0, INET6_ADDRSTRLEN);
if (res->ai_addr->sa_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)res->ai_addr;
dns_ntop(AF_INET, &s->sin_addr, ipstr, INET_ADDRSTRLEN);
} else if (res->ai_addr->sa_family == AF_INET6) {
struct sockaddr_in6 *s = (struct sockaddr_in6 *)res->ai_addr;
dns_ntop(AF_INET6, &s->sin6_addr, ipstr, INET6_ADDRSTRLEN);
}
if (outbound_block_match_host(ipstr) == 1) {
if (verbose)
LOGI("outbound blocked %s", ipstr);
return NULL;
}
}
// initialize remote socks
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sockfd == -1) {
ERROR("socket");
close(sockfd);
return NULL;
}
int opt = 1;
setsockopt(sockfd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
// setup remote socks
if (setnonblocking(sockfd) == -1)
ERROR("setnonblocking");
if (bind_address != NULL)
if (bind_to_address(sockfd, bind_address) == -1) {
ERROR("bind_to_address");
close(sockfd);
return NULL;
}
#ifdef SET_INTERFACE
if (iface) {
if (setinterface(sockfd, iface) == -1) {
ERROR("setinterface");
close(sockfd);
return NULL;
}
}
#endif
remote_t *remote = new_remote(sockfd);
#ifdef TCP_FASTOPEN
if (fast_open) {
#ifdef __APPLE__
((struct sockaddr_in *)(res->ai_addr))->sin_len = sizeof(struct sockaddr_in);
sa_endpoints_t endpoints;
memset((char *)&endpoints, 0, sizeof(endpoints));
endpoints.sae_dstaddr = res->ai_addr;
endpoints.sae_dstaddrlen = res->ai_addrlen;
struct iovec iov;
iov.iov_base = server->buf->array + server->buf->idx;
iov.iov_len = server->buf->len;
size_t len;
int s = connectx(sockfd, &endpoints, SAE_ASSOCID_ANY, CONNECT_DATA_IDEMPOTENT,
&iov, 1, &len, NULL);
if (s == 0) {
s = len;
}
#else
ssize_t s = sendto(sockfd, server->buf->array + server->buf->idx,
server->buf->len, MSG_FASTOPEN, res->ai_addr,
res->ai_addrlen);
#endif
if (s == -1) {
if (errno == CONNECT_IN_PROGRESS || errno == EAGAIN
|| errno == EWOULDBLOCK) {
// The remote server doesn't support tfo or it's the first connection to the server.
// It will automatically fall back to conventional TCP.
} else if (errno == EOPNOTSUPP || errno == EPROTONOSUPPORT ||
errno == ENOPROTOOPT) {
// Disable fast open as it's not supported
fast_open = 0;
LOGE("fast open is not supported on this platform");
} else {
ERROR("sendto");
}
} else if (s <= server->buf->len) {
server->buf->idx += s;
server->buf->len -= s;
} else {
server->buf->idx = 0;
server->buf->len = 0;
}
}
#endif
if (!fast_open) {
int r = connect(sockfd, res->ai_addr, res->ai_addrlen);
if (r == -1 && errno != CONNECT_IN_PROGRESS) {
ERROR("connect");
close_and_free_remote(EV_A_ remote);
return NULL;
}
}
return remote;
}
static void
server_recv_cb(EV_P_ ev_io *w, int revents)
{
server_ctx_t *server_recv_ctx = (server_ctx_t *)w;
server_t *server = server_recv_ctx->server;
remote_t *remote = NULL;
int len = server->buf->len;
buffer_t *buf = server->buf;
if (server->stage > STAGE_PARSE) {
remote = server->remote;
buf = remote->buf;
len = 0;
ev_timer_again(EV_A_ & server->recv_ctx->watcher);
}
if (len > BUF_SIZE) {
ERROR("out of recv buffer");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
ssize_t r = recv(server->fd, buf->array + len, BUF_SIZE - len, 0);
if (r == 0) {
// connection closed
if (verbose) {
LOGI("server_recv close the connection");
}
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else if (r == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data
// continue to wait for recv
return;
} else {
ERROR("server recv");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
tx += r;
if (server->stage == STAGE_ERROR) {
server->buf->len = 0;
server->buf->idx = 0;
return;
}
// handle incomplete header part 1
if (server->stage == STAGE_INIT) {
buf->len += r;
if (buf->len <= enc_get_iv_len(&cipher_env) + 1) {
// wait for more
return;
}
} else {
buf->len = r;
}
int err = ss_decrypt(&cipher_env, buf, server->d_ctx, BUF_SIZE);
if (err) {
report_addr(server->fd, MALICIOUS);
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
// handle incomplete header part 2
if (server->stage == STAGE_INIT) {
int ret = is_header_complete(server->buf);
if (ret == 1) {
bfree(server->header_buf);
ss_free(server->header_buf);
server->stage = STAGE_PARSE;
} else if (ret == -1) {
server->stage = STAGE_ERROR;
report_addr(server->fd, MALFORMED);
server->buf->len = 0;
server->buf->idx = 0;
return;
} else {
server->stage = STAGE_HANDSHAKE;
}
}
if (server->stage == STAGE_HANDSHAKE) {
size_t header_len = server->header_buf->len;
brealloc(server->header_buf, server->buf->len + header_len, BUF_SIZE);
memcpy(server->header_buf->array + header_len,
server->buf->array, server->buf->len);
server->header_buf->len = server->buf->len + header_len;
int ret = is_header_complete(server->buf);
if (ret == 1) {
brealloc(server->buf, server->header_buf->len, BUF_SIZE);
memcpy(server->buf->array, server->header_buf->array, server->header_buf->len);
server->buf->len = server->header_buf->len;
bfree(server->header_buf);
ss_free(server->header_buf);
server->stage = STAGE_PARSE;
} else {
if (ret == -1)
server->stage = STAGE_ERROR;
server->buf->len = 0;
server->buf->idx = 0;
return;
}
}
// handshake and transmit data
if (server->stage == STAGE_STREAM) {
int s = send(remote->fd, remote->buf->array, remote->buf->len, 0);
if (s == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data, wait for send
remote->buf->idx = 0;
ev_io_stop(EV_A_ & server_recv_ctx->io);
ev_io_start(EV_A_ & remote->send_ctx->io);
} else {
ERROR("server_recv_send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
} else if (s < remote->buf->len) {
remote->buf->len -= s;
remote->buf->idx = s;
ev_io_stop(EV_A_ & server_recv_ctx->io);
ev_io_start(EV_A_ & remote->send_ctx->io);
}
return;
} else if (server->stage == STAGE_PARSE) {
/*
* Shadowsocks TCP Relay Header:
*
* +------+----------+----------+
* | ATYP | DST.ADDR | DST.PORT |
* +------+----------+----------+
* | 1 | Variable | 2 |
* +------+----------+----------+
*/
/*
* TCP Relay's payload
*
* +-------------+------+
* | DATA | ...
* +-------------+------+
* | Variable | ...
* +-------------+------+
*/
int offset = 0;
int need_query = 0;
char atyp = server->buf->array[offset++];
char host[257] = { 0 };
uint16_t port = 0;
struct addrinfo info;
struct sockaddr_storage storage;
memset(&info, 0, sizeof(struct addrinfo));
memset(&storage, 0, sizeof(struct sockaddr_storage));
// get remote addr and port
if ((atyp & ADDRTYPE_MASK) == 1) {
// IP V4
struct sockaddr_in *addr = (struct sockaddr_in *)&storage;
size_t in_addr_len = sizeof(struct in_addr);
addr->sin_family = AF_INET;
if (server->buf->len >= in_addr_len + 3) {
addr->sin_addr = *(struct in_addr *)(server->buf->array + offset);
dns_ntop(AF_INET, (const void *)(server->buf->array + offset),
host, INET_ADDRSTRLEN);
offset += in_addr_len;
} else {
LOGE("invalid header with addr type %d", atyp);
report_addr(server->fd, MALFORMED);
close_and_free_server(EV_A_ server);
return;
}
addr->sin_port = *(uint16_t *)(server->buf->array + offset);
info.ai_family = AF_INET;
info.ai_socktype = SOCK_STREAM;
info.ai_protocol = IPPROTO_TCP;
info.ai_addrlen = sizeof(struct sockaddr_in);
info.ai_addr = (struct sockaddr *)addr;
} else if ((atyp & ADDRTYPE_MASK) == 3) {
// Domain name
uint8_t name_len = *(uint8_t *)(server->buf->array + offset);
if (name_len + 4 <= server->buf->len) {
memcpy(host, server->buf->array + offset + 1, name_len);
offset += name_len + 1;
} else {
LOGE("invalid name length: %d", name_len);
report_addr(server->fd, MALFORMED);
close_and_free_server(EV_A_ server);
return;
}
if (acl && outbound_block_match_host(host) == 1) {
if (verbose)
LOGI("outbound blocked %s", host);
close_and_free_server(EV_A_ server);
return;
}
struct cork_ip ip;
if (cork_ip_init(&ip, host) != -1) {
info.ai_socktype = SOCK_STREAM;
info.ai_protocol = IPPROTO_TCP;
if (ip.version == 4) {
struct sockaddr_in *addr = (struct sockaddr_in *)&storage;
dns_pton(AF_INET, host, &(addr->sin_addr));
addr->sin_port = *(uint16_t *)(server->buf->array + offset);
addr->sin_family = AF_INET;
info.ai_family = AF_INET;
info.ai_addrlen = sizeof(struct sockaddr_in);
info.ai_addr = (struct sockaddr *)addr;
} else if (ip.version == 6) {
struct sockaddr_in6 *addr = (struct sockaddr_in6 *)&storage;
dns_pton(AF_INET6, host, &(addr->sin6_addr));
addr->sin6_port = *(uint16_t *)(server->buf->array + offset);
addr->sin6_family = AF_INET6;
info.ai_family = AF_INET6;
info.ai_addrlen = sizeof(struct sockaddr_in6);
info.ai_addr = (struct sockaddr *)addr;
}
} else {
if (!validate_hostname(host, name_len)) {
LOGE("invalid host name");
report_addr(server->fd, MALFORMED);
close_and_free_server(EV_A_ server);
return;
}
need_query = 1;
}
} else if ((atyp & ADDRTYPE_MASK) == 4) {
// IP V6
struct sockaddr_in6 *addr = (struct sockaddr_in6 *)&storage;
size_t in6_addr_len = sizeof(struct in6_addr);
addr->sin6_family = AF_INET6;
if (server->buf->len >= in6_addr_len + 3) {
addr->sin6_addr = *(struct in6_addr *)(server->buf->array + offset);
dns_ntop(AF_INET6, (const void *)(server->buf->array + offset),
host, INET6_ADDRSTRLEN);
offset += in6_addr_len;
} else {
LOGE("invalid header with addr type %d", atyp);
report_addr(server->fd, MALFORMED);
close_and_free_server(EV_A_ server);
return;
}
addr->sin6_port = *(uint16_t *)(server->buf->array + offset);
info.ai_family = AF_INET6;
info.ai_socktype = SOCK_STREAM;
info.ai_protocol = IPPROTO_TCP;
info.ai_addrlen = sizeof(struct sockaddr_in6);
info.ai_addr = (struct sockaddr *)addr;
}
if (offset == 1) {
LOGE("invalid header with addr type %d", atyp);
report_addr(server->fd, MALFORMED);
close_and_free_server(EV_A_ server);
return;
}
port = (*(uint16_t *)(server->buf->array + offset));
offset += 2;
if (server->buf->len < offset) {
report_addr(server->fd, MALFORMED);
close_and_free_server(EV_A_ server);
return;
} else {
server->buf->len -= offset;
memmove(server->buf->array, server->buf->array + offset, server->buf->len);
}
if (verbose) {
if ((atyp & ADDRTYPE_MASK) == 4)
LOGI("connect to [%s]:%d", host, ntohs(port));
else
LOGI("connect to %s:%d", host, ntohs(port));
}
if (!need_query) {
remote_t *remote = connect_to_remote(EV_A_ &info, server);
if (remote == NULL) {
LOGE("connect error");
close_and_free_server(EV_A_ server);
return;
} else {
server->remote = remote;
remote->server = server;
// XXX: should handle buffer carefully
if (server->buf->len > 0) {
memcpy(remote->buf->array, server->buf->array, server->buf->len);
remote->buf->len = server->buf->len;
remote->buf->idx = 0;
server->buf->len = 0;
server->buf->idx = 0;
}
// waiting on remote connected event
ev_io_stop(EV_A_ & server_recv_ctx->io);
ev_io_start(EV_A_ & remote->send_ctx->io);
}
} else {
query_t *query = ss_malloc(sizeof(query_t));
memset(query, 0, sizeof(query_t));
query->server = server;
snprintf(query->hostname, 256, "%s", host);
server->stage = STAGE_RESOLVE;
server->query = resolv_query(host, server_resolve_cb,
query_free_cb, query, port);
ev_io_stop(EV_A_ & server_recv_ctx->io);
}
return;
}
// should not reach here
FATAL("server context error");
}
static void
server_send_cb(EV_P_ ev_io *w, int revents)
{
server_ctx_t *server_send_ctx = (server_ctx_t *)w;
server_t *server = server_send_ctx->server;
remote_t *remote = server->remote;
if (remote == NULL) {
LOGE("invalid server");
close_and_free_server(EV_A_ server);
return;
}
if (server->buf->len == 0) {
// close and free
if (verbose) {
LOGI("server_send close the connection");
}
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else {
// has data to send
ssize_t s = send(server->fd, server->buf->array + server->buf->idx,
server->buf->len, 0);
if (s == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
ERROR("server_send_send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
} else if (s < server->buf->len) {
// partly sent, move memory, wait for the next time to send
server->buf->len -= s;
server->buf->idx += s;
return;
} else {
// all sent out, wait for reading
server->buf->len = 0;
server->buf->idx = 0;
ev_io_stop(EV_A_ & server_send_ctx->io);
if (remote != NULL) {
ev_io_start(EV_A_ & remote->recv_ctx->io);
return;
} else {
LOGE("invalid remote");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
}
}
static void
block_list_clear_cb(EV_P_ ev_timer *watcher, int revents)
{
clear_block_list();
}
static void
server_timeout_cb(EV_P_ ev_timer *watcher, int revents)
{
server_ctx_t *server_ctx
= cork_container_of(watcher, server_ctx_t, watcher);
server_t *server = server_ctx->server;
remote_t *remote = server->remote;
if (verbose) {
LOGI("TCP connection timeout");
}
if (server->stage < STAGE_PARSE) {
if (verbose) {
size_t len = server->stage ?
server->header_buf->len : server->buf->len;
#ifdef __MINGW32__
LOGI("incomplete header: %u", len);
#else
LOGI("incomplete header: %zu", len);
#endif
}
report_addr(server->fd, SUSPICIOUS);
}
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
static void
query_free_cb(void *data)
{
if (data != NULL) {
ss_free(data);
}
}
static void
server_resolve_cb(struct sockaddr *addr, void *data)
{
query_t *query = (query_t *)data;
server_t *server = query->server;
struct ev_loop *loop = server->listen_ctx->loop;
server->query = NULL;
if (addr == NULL) {
LOGE("unable to resolve %s", query->hostname);
close_and_free_server(EV_A_ server);
} else {
if (verbose) {
LOGI("successfully resolved %s", query->hostname);
}
struct addrinfo info;
memset(&info, 0, sizeof(struct addrinfo));
info.ai_socktype = SOCK_STREAM;
info.ai_protocol = IPPROTO_TCP;
info.ai_addr = addr;
if (addr->sa_family == AF_INET) {
info.ai_family = AF_INET;
info.ai_addrlen = sizeof(struct sockaddr_in);
} else if (addr->sa_family == AF_INET6) {
info.ai_family = AF_INET6;
info.ai_addrlen = sizeof(struct sockaddr_in6);
}
remote_t *remote = connect_to_remote(EV_A_ &info, server);
if (remote == NULL) {
close_and_free_server(EV_A_ server);
} else {
server->remote = remote;
remote->server = server;
// XXX: should handle buffer carefully
if (server->buf->len > 0) {
memcpy(remote->buf->array, server->buf->array + server->buf->idx,
server->buf->len);
remote->buf->len = server->buf->len;
remote->buf->idx = 0;
server->buf->len = 0;
server->buf->idx = 0;
}
// listen to remote connected event
ev_io_start(EV_A_ & remote->send_ctx->io);
}
}
}
static void
remote_recv_cb(EV_P_ ev_io *w, int revents)
{
remote_ctx_t *remote_recv_ctx = (remote_ctx_t *)w;
remote_t *remote = remote_recv_ctx->remote;
server_t *server = remote->server;
if (server == NULL) {
LOGE("invalid server");
close_and_free_remote(EV_A_ remote);
return;
}
ev_timer_again(EV_A_ & server->recv_ctx->watcher);
ssize_t r = recv(remote->fd, server->buf->array, BUF_SIZE, 0);
if (r == 0) {
// connection closed
if (verbose) {
LOGI("remote_recv close the connection");
}
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else if (r == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data
// continue to wait for recv
return;
} else {
ERROR("remote recv");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
rx += r;
server->buf->len = r;
int err = ss_encrypt(&cipher_env, server->buf, server->e_ctx, BUF_SIZE);
if (err) {
LOGE("invalid password or cipher");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
int s = send(server->fd, server->buf->array, server->buf->len, 0);
if (s == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data, wait for send
server->buf->idx = 0;
ev_io_stop(EV_A_ & remote_recv_ctx->io);
ev_io_start(EV_A_ & server->send_ctx->io);
} else {
ERROR("remote_recv_send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
} else if (s < server->buf->len) {
server->buf->len -= s;
server->buf->idx = s;
ev_io_stop(EV_A_ & remote_recv_ctx->io);
ev_io_start(EV_A_ & server->send_ctx->io);
}
// Disable TCP_NODELAY after the first response are sent
int opt = 0;
setsockopt(server->fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
setsockopt(remote->fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
}
static void
remote_send_cb(EV_P_ ev_io *w, int revents)
{
remote_ctx_t *remote_send_ctx = (remote_ctx_t *)w;
remote_t *remote = remote_send_ctx->remote;
server_t *server = remote->server;
if (server == NULL) {
LOGE("invalid server");
close_and_free_remote(EV_A_ remote);
return;
}
if (!remote_send_ctx->connected) {
struct sockaddr_storage addr;
socklen_t len = sizeof(struct sockaddr_storage);
memset(&addr, 0, len);
int r = getpeername(remote->fd, (struct sockaddr *)&addr, &len);
if (r == 0) {
if (verbose) {
LOGI("remote connected");
}
remote_send_ctx->connected = 1;
// Clear the state of this address in the block list
reset_addr(server->fd);
if (remote->buf->len == 0) {
server->stage = STAGE_STREAM;
ev_io_stop(EV_A_ & remote_send_ctx->io);
ev_io_start(EV_A_ & server->recv_ctx->io);
ev_io_start(EV_A_ & remote->recv_ctx->io);
return;
}
} else {
ERROR("getpeername");
// not connected
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
if (remote->buf->len == 0) {
// close and free
if (verbose) {
LOGI("remote_send close the connection");
}
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else {
// has data to send
ssize_t s = send(remote->fd, remote->buf->array + remote->buf->idx,
remote->buf->len, 0);
if (s == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
ERROR("remote_send_send");
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
} else if (s < remote->buf->len) {
// partly sent, move memory, wait for the next time to send
remote->buf->len -= s;
remote->buf->idx += s;
return;
} else {
// all sent out, wait for reading
remote->buf->len = 0;
remote->buf->idx = 0;
ev_io_stop(EV_A_ & remote_send_ctx->io);
if (server != NULL) {
ev_io_start(EV_A_ & server->recv_ctx->io);
if (server->stage != STAGE_STREAM) {
server->stage = STAGE_STREAM;
ev_io_start(EV_A_ & remote->recv_ctx->io);
}
} else {
LOGE("invalid server");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
}
}
}
static remote_t *
new_remote(int fd)
{
if (verbose) {
remote_conn++;
}
remote_t *remote = ss_malloc(sizeof(remote_t));
memset(remote, 0, sizeof(remote_t));
remote->recv_ctx = ss_malloc(sizeof(remote_ctx_t));
remote->send_ctx = ss_malloc(sizeof(remote_ctx_t));
remote->buf = ss_malloc(sizeof(buffer_t));
balloc(remote->buf, BUF_SIZE);
memset(remote->recv_ctx, 0, sizeof(remote_ctx_t));
memset(remote->send_ctx, 0, sizeof(remote_ctx_t));
remote->fd = fd;
remote->recv_ctx->remote = remote;
remote->recv_ctx->connected = 0;
remote->send_ctx->remote = remote;
remote->send_ctx->connected = 0;
remote->server = NULL;
ev_io_init(&remote->recv_ctx->io, remote_recv_cb, fd, EV_READ);
ev_io_init(&remote->send_ctx->io, remote_send_cb, fd, EV_WRITE);
return remote;
}
static void
free_remote(remote_t *remote)
{
if (remote->server != NULL) {
remote->server->remote = NULL;
}
if (remote->buf != NULL) {
bfree(remote->buf);
ss_free(remote->buf);
}
ss_free(remote->recv_ctx);
ss_free(remote->send_ctx);
ss_free(remote);
}
static void
close_and_free_remote(EV_P_ remote_t *remote)
{
if (remote != NULL) {
ev_io_stop(EV_A_ & remote->send_ctx->io);
ev_io_stop(EV_A_ & remote->recv_ctx->io);
close(remote->fd);
free_remote(remote);
if (verbose) {
remote_conn--;
LOGI("current remote connection: %d", remote_conn);
}
}
}
static server_t *
new_server(int fd, listen_ctx_t *listener)
{
if (verbose) {
server_conn++;
}
server_t *server;
server = ss_malloc(sizeof(server_t));
memset(server, 0, sizeof(server_t));
server->recv_ctx = ss_malloc(sizeof(server_ctx_t));
server->send_ctx = ss_malloc(sizeof(server_ctx_t));
server->buf = ss_malloc(sizeof(buffer_t));
server->header_buf = ss_malloc(sizeof(buffer_t));
memset(server->recv_ctx, 0, sizeof(server_ctx_t));
memset(server->send_ctx, 0, sizeof(server_ctx_t));
balloc(server->buf, BUF_SIZE);
balloc(server->header_buf, BUF_SIZE);
server->fd = fd;
server->recv_ctx->server = server;
server->recv_ctx->connected = 0;
server->send_ctx->server = server;
server->send_ctx->connected = 0;
server->stage = STAGE_INIT;
server->query = NULL;
server->listen_ctx = listener;
server->remote = NULL;
if (listener->method) {
server->e_ctx = ss_malloc(sizeof(enc_ctx_t));
server->d_ctx = ss_malloc(sizeof(enc_ctx_t));
enc_ctx_init(&cipher_env, server->e_ctx, 1);
enc_ctx_init(&cipher_env, server->d_ctx, 0);
} else {
server->e_ctx = NULL;
server->d_ctx = NULL;
}
int request_timeout = min(MAX_REQUEST_TIMEOUT, listener->timeout)
+ rand() % MAX_REQUEST_TIMEOUT;
ev_io_init(&server->recv_ctx->io, server_recv_cb, fd, EV_READ);
ev_io_init(&server->send_ctx->io, server_send_cb, fd, EV_WRITE);
ev_timer_init(&server->recv_ctx->watcher, server_timeout_cb,
request_timeout, listener->timeout);
server->chunk = ss_malloc(sizeof(chunk_t));
memset(server->chunk, 0, sizeof(chunk_t));
server->chunk->buf = ss_malloc(sizeof(buffer_t));
memset(server->chunk->buf, 0, sizeof(buffer_t));
cork_dllist_add(&connections, &server->entries);
return server;
}
static void
free_server(server_t *server)
{
cork_dllist_remove(&server->entries);
if (server->chunk != NULL) {
if (server->chunk->buf != NULL) {
bfree(server->chunk->buf);
ss_free(server->chunk->buf);
}
ss_free(server->chunk);
}
if (server->remote != NULL) {
server->remote->server = NULL;
}
if (server->e_ctx != NULL) {
enc_ctx_release(&cipher_env, server->e_ctx);
ss_free(server->e_ctx);
}
if (server->d_ctx != NULL) {
enc_ctx_release(&cipher_env, server->d_ctx);
ss_free(server->d_ctx);
}
if (server->buf != NULL) {
bfree(server->buf);
ss_free(server->buf);
}
if (server->header_buf != NULL) {
bfree(server->header_buf);
ss_free(server->header_buf);
}
ss_free(server->recv_ctx);
ss_free(server->send_ctx);
ss_free(server);
}
static void
close_and_free_server(EV_P_ server_t *server)
{
if (server != NULL) {
if (server->query != NULL) {
resolv_cancel(server->query);
server->query = NULL;
}
ev_io_stop(EV_A_ & server->send_ctx->io);
ev_io_stop(EV_A_ & server->recv_ctx->io);
ev_timer_stop(EV_A_ & server->recv_ctx->watcher);
close(server->fd);
free_server(server);
if (verbose) {
server_conn--;
LOGI("current server connection: %d", server_conn);
}
}
}
static void
signal_cb(EV_P_ ev_signal *w, int revents)
{
if (revents & EV_SIGNAL) {
switch (w->signum) {
case SIGINT:
case SIGTERM:
ev_unloop(EV_A_ EVUNLOOP_ALL);
}
}
}
static void
accept_cb(EV_P_ ev_io *w, int revents)
{
listen_ctx_t *listener = (listen_ctx_t *)w;
int serverfd = accept(listener->fd, NULL, NULL);
if (serverfd == -1) {
ERROR("accept");
return;
}
char *peer_name = get_peer_name(serverfd);
if (peer_name != NULL) {
int in_white_list = 0;
if (acl) {
if ((get_acl_mode() == BLACK_LIST && acl_match_host(peer_name) == 1)
|| (get_acl_mode() == WHITE_LIST && acl_match_host(peer_name) >= 0)) {
LOGE("Access denied from %s", peer_name);
close(serverfd);
return;
} else if (acl_match_host(peer_name) == -1) {
in_white_list = 1;
}
}
if (!in_white_list && check_block_list(peer_name)) {
LOGE("block all requests from %s", peer_name);
#ifdef __linux__
set_linger(serverfd);
#endif
close(serverfd);
return;
}
}
int opt = 1;
setsockopt(serverfd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(serverfd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
setnonblocking(serverfd);
if (verbose) {
LOGI("accept a connection");
}
server_t *server = new_server(serverfd, listener);
ev_io_start(EV_A_ & server->recv_ctx->io);
ev_timer_start(EV_A_ & server->recv_ctx->watcher);
}
int
main(int argc, char **argv)
{
int i, c;
int pid_flags = 0;
int mptcp = 0;
int firewall = 0;
int mtu = 0;
char *user = NULL;
char *password = NULL;
char *timeout = NULL;
char *method = NULL;
char *pid_path = NULL;
char *conf_path = NULL;
char *iface = NULL;
int server_num = 0;
const char *server_host[MAX_REMOTE_NUM];
char *nameservers[MAX_DNS_NUM + 1];
int nameserver_num = 0;
int option_index = 0;
static struct option long_options[] = {
{ "fast-open", no_argument, 0, 0 },
{ "acl", required_argument, 0, 0 },
{ "manager-address", required_argument, 0, 0 },
{ "mtu", required_argument, 0, 0 },
{ "help", no_argument, 0, 0 },
#ifdef __linux__
{ "mptcp", no_argument, 0, 0 },
{ "firewall", no_argument, 0, 0 },
#endif
{ 0, 0, 0, 0 }
};
opterr = 0;
USE_TTY();
while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:b:c:i:d:a:n:huUvA6",
long_options, &option_index)) != -1) {
switch (c) {
case 0:
if (option_index == 0) {
fast_open = 1;
} else if (option_index == 1) {
LOGI("initializing acl...");
acl = !init_acl(optarg);
} else if (option_index == 2) {
manager_address = optarg;
} else if (option_index == 3) {
mtu = atoi(optarg);
LOGI("set MTU to %d", mtu);
} else if (option_index == 4) {
usage();
exit(EXIT_SUCCESS);
} else if (option_index == 5) {
mptcp = 1;
LOGI("enable multipath TCP");
} else if (option_index == 6) {
firewall = 1;
LOGI("enable firewall rules");
}
break;
case 's':
if (server_num < MAX_REMOTE_NUM) {
server_host[server_num++] = optarg;
}
break;
case 'b':
bind_address = optarg;
break;
case 'p':
server_port = optarg;
break;
case 'k':
password = optarg;
break;
case 'f':
pid_flags = 1;
pid_path = optarg;
break;
case 't':
timeout = optarg;
break;
case 'm':
method = optarg;
break;
case 'c':
conf_path = optarg;
break;
case 'i':
iface = optarg;
break;
case 'd':
if (nameserver_num < MAX_DNS_NUM) {
nameservers[nameserver_num++] = optarg;
}
break;
case 'a':
user = optarg;
break;
#ifdef HAVE_SETRLIMIT
case 'n':
nofile = atoi(optarg);
break;
#endif
case 'u':
mode = TCP_AND_UDP;
break;
case 'U':
mode = UDP_ONLY;
break;
case 'v':
verbose = 1;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'A':
LOGI("The 'A' argument is deprecate! Ignored.");
break;
case '6':
ipv6first = 1;
break;
case '?':
// The option character is not recognized.
LOGE("Unrecognized option: %s", optarg);
opterr = 1;
break;
}
}
if (opterr) {
usage();
exit(EXIT_FAILURE);
}
if (argc == 1) {
if (conf_path == NULL) {
conf_path = DEFAULT_CONF_PATH;
}
}
if (conf_path != NULL) {
jconf_t *conf = read_jconf(conf_path);
if (server_num == 0) {
server_num = conf->remote_num;
for (i = 0; i < server_num; i++)
server_host[i] = conf->remote_addr[i].host;
}
if (server_port == NULL) {
server_port = conf->remote_port;
}
if (password == NULL) {
password = conf->password;
}
if (method == NULL) {
method = conf->method;
}
if (timeout == NULL) {
timeout = conf->timeout;
}
if (user == NULL) {
user = conf->user;
}
if (mode == TCP_ONLY) {
mode = conf->mode;
}
if (mtu == 0) {
mtu = conf->mtu;
}
if (mptcp == 0) {
mptcp = conf->mptcp;
}
#ifdef TCP_FASTOPEN
if (fast_open == 0) {
fast_open = conf->fast_open;
}
#endif
#ifdef HAVE_SETRLIMIT
if (nofile == 0) {
nofile = conf->nofile;
}
#endif
if (conf->nameserver != NULL) {
nameservers[nameserver_num++] = conf->nameserver;
}
if (ipv6first == 0) {
ipv6first = conf->ipv6_first;
}
}
if (server_num == 0) {
server_host[server_num++] = NULL;
}
if (server_num == 0 || server_port == NULL || password == NULL) {
usage();
exit(EXIT_FAILURE);
}
if (method == NULL) {
method = "rc4-md5";
}
if (timeout == NULL) {
timeout = "60";
}
#ifdef HAVE_SETRLIMIT
/*
* no need to check the return value here since we will show
* the user an error message if setrlimit(2) fails
*/
if (nofile > 1024) {
if (verbose) {
LOGI("setting NOFILE to %d", nofile);
}
set_nofile(nofile);
}
#endif
if (pid_flags) {
USE_SYSLOG(argv[0]);
daemonize(pid_path);
}
if (ipv6first) {
LOGI("resolving hostname to IPv6 address first");
}
if (fast_open == 1) {
#ifdef TCP_FASTOPEN
LOGI("using tcp fast open");
#else
LOGE("tcp fast open is not supported by this environment");
fast_open = 0;
#endif
}
if (mode != TCP_ONLY) {
LOGI("UDP relay enabled");
}
if (mode == UDP_ONLY) {
LOGI("TCP relay disabled");
}
#ifdef __MINGW32__
winsock_init();
#else
// ignore SIGPIPE
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
signal(SIGABRT, SIG_IGN);
#endif
struct ev_signal sigint_watcher;
struct ev_signal sigterm_watcher;
ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
ev_signal_start(EV_DEFAULT, &sigint_watcher);
ev_signal_start(EV_DEFAULT, &sigterm_watcher);
// setup keys
LOGI("initializing ciphers... %s", method);
int m = enc_init(&cipher_env, password, method);
// initialize ev loop
struct ev_loop *loop = EV_DEFAULT;
// setup udns
if (nameserver_num == 0) {
#ifdef __MINGW32__
nameservers[nameserver_num++] = "8.8.8.8";
resolv_init(loop, nameservers, nameserver_num, ipv6first);
#else
resolv_init(loop, NULL, 0, ipv6first);
#endif
} else {
resolv_init(loop, nameservers, nameserver_num, ipv6first);
}
for (int i = 0; i < nameserver_num; i++)
LOGI("using nameserver: %s", nameservers[i]);
// initialize listen context
listen_ctx_t listen_ctx_list[server_num];
// bind to each interface
while (server_num > 0) {
int index = --server_num;
const char *host = server_host[index];
if (mode != UDP_ONLY) {
// Bind to port
int listenfd;
listenfd = create_and_bind(host, server_port, mptcp);
if (listenfd == -1) {
FATAL("bind() error");
}
if (listen(listenfd, SSMAXCONN) == -1) {
FATAL("listen() error");
}
setfastopen(listenfd);
setnonblocking(listenfd);
listen_ctx_t *listen_ctx = &listen_ctx_list[index];
// Setup proxy context
listen_ctx->timeout = atoi(timeout);
listen_ctx->fd = listenfd;
listen_ctx->method = m;
listen_ctx->iface = iface;
listen_ctx->loop = loop;
ev_io_init(&listen_ctx->io, accept_cb, listenfd, EV_READ);
ev_io_start(loop, &listen_ctx->io);
}
// Setup UDP
if (mode != TCP_ONLY) {
init_udprelay(server_host[index], server_port, mtu,
atoi(timeout), iface, NULL, NULL);
}
if (host && strcmp(host, ":") > 0)
LOGI("listening at [%s]:%s", host, server_port);
else
LOGI("listening at %s:%s", host ? host : "*", server_port);
}
if (manager_address != NULL) {
ev_timer_init(&stat_update_watcher, stat_update_cb, UPDATE_INTERVAL, UPDATE_INTERVAL);
ev_timer_start(EV_DEFAULT, &stat_update_watcher);
}
ev_timer_init(&block_list_watcher, block_list_clear_cb, UPDATE_INTERVAL, UPDATE_INTERVAL);
ev_timer_start(EV_DEFAULT, &block_list_watcher);
// setuid
if (user != NULL && ! run_as(user)) {
FATAL("failed to switch user");
}
#ifndef __MINGW32__
if (geteuid() == 0){
LOGI("running from root user");
} else if (firewall) {
LOGE("firewall setup requires running from root user");
exit(-1);
}
#endif
// init block list
init_block_list(firewall);
// Init connections
cork_dllist_init(&connections);
// start ev loop
ev_run(loop, 0);
if (verbose) {
LOGI("closed gracefully");
}
// Free block list
free_block_list();
if (manager_address != NULL) {
ev_timer_stop(EV_DEFAULT, &stat_update_watcher);
}
ev_timer_stop(EV_DEFAULT, &block_list_watcher);
// Clean up
for (int i = 0; i <= server_num; i++) {
listen_ctx_t *listen_ctx = &listen_ctx_list[i];
if (mode != UDP_ONLY) {
ev_io_stop(loop, &listen_ctx->io);
close(listen_ctx->fd);
}
}
if (mode != UDP_ONLY) {
free_connections(loop);
}
if (mode != TCP_ONLY) {
free_udprelay();
}
resolv_shutdown(loop);
#ifdef __MINGW32__
winsock_cleanup();
#endif
ev_signal_stop(EV_DEFAULT, &sigint_watcher);
ev_signal_stop(EV_DEFAULT, &sigterm_watcher);
return 0;
}
|
281677160/openwrt-package | 1,414 | luci-app-ssr-plus/shadowsocksr-libev/src/src/socks5.h | /*
* socks5.h - Define SOCKS5's header
*
* Copyright (C) 2013, clowwindy <clowwindy42@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _SOCKS5_H
#define _SOCKS5_H
#define SVERSION 0x05
#define CONNECT 0x01
#define IPV4 0x01
#define DOMAIN 0x03
#define IPV6 0x04
#define CMD_NOT_SUPPORTED 0x07
#pragma pack(push)
#pragma pack(1)
struct method_select_request {
char ver;
char nmethods;
char methods[255];
};
struct method_select_response {
char ver;
char method;
};
struct socks5_request {
char ver;
char cmd;
char rsv;
char atyp;
};
struct socks5_response {
char ver;
char rep;
char rsv;
char atyp;
};
#pragma pack(pop)
#endif // _SOCKS5_H
|
281677160/openwrt-package | 1,489 | luci-app-ssr-plus/shadowsocksr-libev/src/src/manager.h | /*
* server.h - Define shadowsocks server's buffers and callbacks
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _MANAGER_H
#define _MANAGER_H
#include <ev.h>
#include <time.h>
#include <libcork/ds.h>
#include "jconf.h"
#include "common.h"
struct manager_ctx {
ev_io io;
int fd;
int fast_open;
int verbose;
int mode;
char *password;
char *timeout;
char *method;
char *iface;
char *acl;
char *user;
char *manager_address;
char **hosts;
int host_num;
char **nameservers;
int nameserver_num;
int mtu;
#ifdef HAVE_SETRLIMIT
int nofile;
#endif
};
struct server {
char port[8];
char password[128];
uint64_t traffic;
};
#endif // _MANAGER_H
|
281677160/openwrt-package | 30,921 | luci-app-ssr-plus/shadowsocksr-libev/src/src/json.c | /* vim: set et ts=3 sw=3 sts=3 ft=c:
*
* Copyright (C) 2012, 2013, 2014 James McLaughlin et al. All rights reserved.
* https://github.com/udp/json-parser
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "json.h"
#include "utils.h"
#ifdef _MSC_VER
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#endif
#ifdef __cplusplus
const struct _json_value json_value_none; /* zero-d by ctor */
#else
const struct _json_value json_value_none = { NULL, 0, { 0 }, { NULL } };
#endif
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
typedef unsigned short json_uchar;
static unsigned char
hex_value(json_char c)
{
if (isdigit((uint8_t)c)) {
return c - '0';
}
switch (c) {
case 'a':
case 'A':
return 0x0A;
case 'b':
case 'B':
return 0x0B;
case 'c':
case 'C':
return 0x0C;
case 'd':
case 'D':
return 0x0D;
case 'e':
case 'E':
return 0x0E;
case 'f':
case 'F':
return 0x0F;
default:
return 0xFF;
}
}
typedef struct {
unsigned long used_memory;
unsigned int uint_max;
unsigned long ulong_max;
json_settings settings;
int first_pass;
} json_state;
static void *
default_alloc(size_t size, int zero, void *user_data)
{
return zero ? calloc(1, size) : ss_malloc(size);
}
static void
default_free(void *ptr, void *user_data)
{
ss_free(ptr);
}
static void *
json_alloc(json_state *state, unsigned long size, int zero)
{
if ((state->ulong_max - state->used_memory) < size) {
return 0;
}
if (state->settings.max_memory
&& (state->used_memory += size) > state->settings.max_memory) {
return 0;
}
return state->settings.mem_alloc(size, zero, state->settings.user_data);
}
static int
new_value(json_state *state, json_value **top, json_value **root,
json_value **alloc, json_type type)
{
json_value *value;
int values_size;
if (!state->first_pass) {
value = *top = *alloc;
*alloc = (*alloc)->_reserved.next_alloc;
if (!*root) {
*root = value;
}
switch (value->type) {
case json_array:
if (!(value->u.array.values = (json_value **)json_alloc
(state, value->u.array.length *
sizeof(json_value *), 0))) {
return 0;
}
value->u.array.length = 0;
break;
case json_object:
values_size = sizeof(*value->u.object.values) *
value->u.object.length;
if (!((*(void **)&value->u.object.values) = json_alloc
(state,
values_size +
((size_t)value->u.
object.values),
0))) {
return 0;
}
value->_reserved.object_mem = (*(char **)&value->u.object.values) +
values_size;
value->u.object.length = 0;
break;
case json_string:
if (!(value->u.string.ptr = (json_char *)json_alloc
(state,
(value->u.string.length +
1) * sizeof(json_char), 0))) {
return 0;
}
value->u.string.length = 0;
break;
default:
break;
}
return 1;
}
value = (json_value *)json_alloc(state, sizeof(json_value), 1);
if (!value) {
return 0;
}
if (!*root) {
*root = value;
}
value->type = type;
value->parent = *top;
if (*alloc) {
(*alloc)->_reserved.next_alloc = value;
}
*alloc = *top = value;
return 1;
}
#define e_off \
((int)(i - cur_line_begin))
#define whitespace \
case '\n': \
++cur_line; cur_line_begin = i; \
case ' ': \
case '\t': \
case '\r'
#define string_add(b) \
do { if (!state.first_pass) { string[string_length] = b; \
} ++string_length; } while (0)
static const long
flag_next = 1 << 0,
flag_reproc = 1 << 1,
flag_need_comma = 1 << 2,
flag_seek_value = 1 << 3,
flag_escaped = 1 << 4,
flag_string = 1 << 5,
flag_need_colon = 1 << 6,
flag_done = 1 << 7,
flag_num_negative = 1 << 8,
flag_num_zero = 1 << 9,
flag_num_e = 1 << 10,
flag_num_e_got_sign = 1 << 11,
flag_num_e_negative = 1 << 12,
flag_line_comment = 1 << 13,
flag_block_comment = 1 << 14;
json_value *
json_parse_ex(json_settings *settings,
const json_char *json,
size_t length,
char *error_buf)
{
json_char error[json_error_max];
int cur_line;
const json_char *cur_line_begin, *i, *end;
json_value *top, *root, *alloc = 0;
json_state state = { 0UL, 0U, 0UL, { 0UL, 0, NULL, NULL, NULL }, 0 };
long flags;
long num_digits = 0, num_e = 0;
json_int_t num_fraction = 0;
/* Skip UTF-8 BOM
*/
if (length >= 3 && ((unsigned char)json[0]) == 0xEF
&& ((unsigned char)json[1]) == 0xBB
&& ((unsigned char)json[2]) == 0xBF) {
json += 3;
length -= 3;
}
error[0] = '\0';
end = (json + length);
memcpy(&state.settings, settings, sizeof(json_settings));
if (!state.settings.mem_alloc) {
state.settings.mem_alloc = default_alloc;
}
if (!state.settings.mem_free) {
state.settings.mem_free = default_free;
}
memset(&state.uint_max, 0xFF, sizeof(state.uint_max));
memset(&state.ulong_max, 0xFF, sizeof(state.ulong_max));
state.uint_max -= 8; /* limit of how much can be added before next check */
state.ulong_max -= 8;
for (state.first_pass = 1; state.first_pass >= 0; --state.first_pass) {
json_uchar uchar;
unsigned char uc_b1, uc_b2, uc_b3, uc_b4;
json_char *string = 0;
unsigned int string_length = 0;
top = root = 0;
flags = flag_seek_value;
cur_line = 1;
cur_line_begin = json;
for (i = json;; ++i) {
json_char b = (i == end ? 0 : *i);
if (flags & flag_string) {
if (!b) {
sprintf(error, "Unexpected EOF in string (at %d:%d)",
cur_line, e_off);
goto e_failed;
}
if (string_length > state.uint_max) {
goto e_overflow;
}
if (flags & flag_escaped) {
flags &= ~flag_escaped;
switch (b) {
case 'b':
string_add('\b');
break;
case 'f':
string_add('\f');
break;
case 'n':
string_add('\n');
break;
case 'r':
string_add('\r');
break;
case 't':
string_add('\t');
break;
case 'u':
if (end - i < 4 ||
(uc_b1 = hex_value(*++i)) == 0xFF ||
(uc_b2 = hex_value(*++i)) == 0xFF
|| (uc_b3 = hex_value(*++i)) == 0xFF ||
(uc_b4 = hex_value(*++i)) == 0xFF) {
sprintf(error,
"Invalid character value `%c` (at %d:%d)",
b, cur_line, e_off);
goto e_failed;
}
uc_b1 = uc_b1 * 16 + uc_b2;
uc_b2 = uc_b3 * 16 + uc_b4;
uchar = ((json_char)uc_b1) * 256 + uc_b2;
if (sizeof(json_char) >= sizeof(json_uchar) ||
(uc_b1 == 0 && uc_b2 <= 0x7F)) {
string_add((json_char)uchar);
break;
}
if (uchar <= 0x7FF) {
if (state.first_pass) {
string_length += 2;
} else {
string[string_length++] = 0xC0 |
((uc_b2 &
0xC0) >>
6) |
((uc_b1 & 0x7) << 2);
string[string_length++] = 0x80 |
(uc_b2 & 0x3F);
}
break;
}
if (state.first_pass) {
string_length += 3;
} else {
string[string_length++] = 0xE0 |
((uc_b1 & 0xF0) >> 4);
string[string_length++] = 0x80 |
((uc_b1 &
0xF) <<
2) |
((uc_b2 & 0xC0) >> 6);
string[string_length++] = 0x80 | (uc_b2 & 0x3F);
}
break;
default:
string_add(b);
}
continue;
}
if (b == '\\') {
flags |= flag_escaped;
continue;
}
if (b == '"') {
if (!state.first_pass) {
string[string_length] = 0;
}
flags &= ~flag_string;
string = 0;
switch (top->type) {
case json_string:
top->u.string.length = string_length;
flags |= flag_next;
break;
case json_object:
if (state.first_pass) {
(*(json_char **)&top->u.object.values) +=
string_length + 1;
} else {
top->u.object.values[top->u.object.length].name
= (json_char *)top->_reserved.object_mem;
top->u.object.values[top->u.object.length].
name_length
= string_length;
(*(json_char **)&top->_reserved.object_mem) +=
string_length + 1;
}
flags |= flag_seek_value | flag_need_colon;
continue;
default:
break;
}
} else {
string_add(b);
continue;
}
}
if (state.settings.settings & json_enable_comments) {
if (flags & (flag_line_comment | flag_block_comment)) {
if (flags & flag_line_comment) {
if (b == '\r' || b == '\n' || !b) {
flags &= ~flag_line_comment;
--i; /* so null can be reproc'd */
}
continue;
}
if (flags & flag_block_comment) {
if (!b) {
sprintf(error,
"%d:%d: Unexpected EOF in block comment",
cur_line, e_off);
goto e_failed;
}
if (b == '*' && i < (end - 1) && i[1] == '/') {
flags &= ~flag_block_comment;
++i; /* skip closing sequence */
}
continue;
}
} else if (b == '/') {
if (!(flags & (flag_seek_value | flag_done)) && top->type !=
json_object) {
sprintf(error, "%d:%d: Comment not allowed here",
cur_line, e_off);
goto e_failed;
}
if (++i == end) {
sprintf(error, "%d:%d: EOF unexpected", cur_line,
e_off);
goto e_failed;
}
switch (b = *i) {
case '/':
flags |= flag_line_comment;
continue;
case '*':
flags |= flag_block_comment;
continue;
default:
sprintf(error,
"%d:%d: Unexpected `%c` in comment opening sequence", cur_line, e_off,
b);
goto e_failed;
}
}
}
if (flags & flag_done) {
if (!b) {
break;
}
switch (b) {
whitespace:
continue;
default:
sprintf(error, "%d:%d: Trailing garbage: `%c`", cur_line,
e_off, b);
goto e_failed;
}
}
if (flags & flag_seek_value) {
switch (b) {
whitespace:
continue;
case ']':
if (top->type == json_array) {
flags =
(flags &
~(flag_need_comma | flag_seek_value)) | flag_next;
} else {
sprintf(error, "%d:%d: Unexpected ]", cur_line, e_off);
goto e_failed;
}
break;
default:
if (flags & flag_need_comma) {
if (b == ',') {
flags &= ~flag_need_comma;
continue;
} else {
sprintf(error, "%d:%d: Expected , before %c",
cur_line, e_off, b);
goto e_failed;
}
}
if (flags & flag_need_colon) {
if (b == ':') {
flags &= ~flag_need_colon;
continue;
} else {
sprintf(error, "%d:%d: Expected : before %c",
cur_line, e_off, b);
goto e_failed;
}
}
flags &= ~flag_seek_value;
switch (b) {
case '{':
if (!new_value(&state, &top, &root, &alloc,
json_object)) {
goto e_alloc_failure;
}
continue;
case '[':
if (!new_value(&state, &top, &root, &alloc,
json_array)) {
goto e_alloc_failure;
}
flags |= flag_seek_value;
continue;
case '"':
if (!new_value(&state, &top, &root, &alloc,
json_string)) {
goto e_alloc_failure;
}
flags |= flag_string;
string = top->u.string.ptr;
string_length = 0;
continue;
case 't':
if ((end - i) < 3 || *(++i) != 'r' || *(++i) != 'u' ||
*(++i) != 'e') {
goto e_unknown_value;
}
if (!new_value(&state, &top, &root, &alloc,
json_boolean)) {
goto e_alloc_failure;
}
top->u.boolean = 1;
flags |= flag_next;
break;
case 'f':
if ((end - i) < 4 || *(++i) != 'a' || *(++i) != 'l' ||
*(++i) != 's' || *(++i) != 'e') {
goto e_unknown_value;
}
if (!new_value(&state, &top, &root, &alloc,
json_boolean)) {
goto e_alloc_failure;
}
flags |= flag_next;
break;
case 'n':
if ((end - i) < 3 || *(++i) != 'u' || *(++i) != 'l' ||
*(++i) != 'l') {
goto e_unknown_value;
}
if (!new_value(&state, &top, &root, &alloc,
json_null)) {
goto e_alloc_failure;
}
flags |= flag_next;
break;
default:
if (isdigit((uint8_t)b) || b == '-') {
if (!new_value(&state, &top, &root, &alloc,
json_integer)) {
goto e_alloc_failure;
}
if (!state.first_pass) {
while (isdigit((uint8_t)b) || b == '+' || b ==
'-'
|| b == 'e' || b == 'E' || b == '.') {
if ((++i) == end) {
b = 0;
break;
}
b = *i;
}
flags |= flag_next | flag_reproc;
break;
}
flags &= ~(flag_num_negative | flag_num_e |
flag_num_e_got_sign |
flag_num_e_negative |
flag_num_zero);
num_digits = 0;
num_fraction = 0;
num_e = 0;
if (b != '-') {
flags |= flag_reproc;
break;
}
flags |= flag_num_negative;
continue;
} else {
sprintf(error,
"%d:%d: Unexpected %c when seeking value",
cur_line, e_off, b);
goto e_failed;
}
}
}
} else {
switch (top->type) {
case json_object:
switch (b) {
whitespace:
continue;
case '"':
if (flags & flag_need_comma) {
sprintf(error, "%d:%d: Expected , before \"",
cur_line, e_off);
goto e_failed;
}
flags |= flag_string;
string = (json_char *)top->_reserved.object_mem;
string_length = 0;
break;
case '}':
flags = (flags & ~flag_need_comma) | flag_next;
break;
case ',':
if (flags & flag_need_comma) {
flags &= ~flag_need_comma;
break;
}
default:
sprintf(error, "%d:%d: Unexpected `%c` in object",
cur_line, e_off, b);
goto e_failed;
}
break;
case json_integer:
case json_double:
if (isdigit((uint8_t)b)) {
++num_digits;
if (top->type == json_integer || flags & flag_num_e) {
if (!(flags & flag_num_e)) {
if (flags & flag_num_zero) {
sprintf(error,
"%d:%d: Unexpected `0` before `%c`",
cur_line, e_off, b);
goto e_failed;
}
if (num_digits == 1 && b == '0') {
flags |= flag_num_zero;
}
} else {
flags |= flag_num_e_got_sign;
num_e = (num_e * 10) + (b - '0');
continue;
}
top->u.integer = (top->u.integer * 10) + (b - '0');
continue;
}
num_fraction = (num_fraction * 10) + (b - '0');
continue;
}
if (b == '+' || b == '-') {
if ((flags & flag_num_e) &&
!(flags & flag_num_e_got_sign)) {
flags |= flag_num_e_got_sign;
if (b == '-') {
flags |= flag_num_e_negative;
}
continue;
}
} else if (b == '.' && top->type == json_integer) {
if (!num_digits) {
sprintf(error, "%d:%d: Expected digit before `.`",
cur_line, e_off);
goto e_failed;
}
top->type = json_double;
top->u.dbl = (double)top->u.integer;
num_digits = 0;
continue;
}
if (!(flags & flag_num_e)) {
if (top->type == json_double) {
if (!num_digits) {
sprintf(error,
"%d:%d: Expected digit after `.`",
cur_line, e_off);
goto e_failed;
}
top->u.dbl += ((double)num_fraction) /
(pow(10, (double)num_digits));
}
if (b == 'e' || b == 'E') {
flags |= flag_num_e;
if (top->type == json_integer) {
top->type = json_double;
top->u.dbl = (double)top->u.integer;
}
num_digits = 0;
flags &= ~flag_num_zero;
continue;
}
} else {
if (!num_digits) {
sprintf(error, "%d:%d: Expected digit after `e`",
cur_line, e_off);
goto e_failed;
}
top->u.dbl *=
pow(10,
(double)((flags &
flag_num_e_negative) ? -num_e : num_e));
}
if (flags & flag_num_negative) {
if (top->type == json_integer) {
top->u.integer = -top->u.integer;
} else {
top->u.dbl = -top->u.dbl;
}
}
flags |= flag_next | flag_reproc;
break;
default:
break;
}
}
if (flags & flag_reproc) {
flags &= ~flag_reproc;
--i;
}
if (flags & flag_next) {
flags = (flags & ~flag_next) | flag_need_comma;
if (!top->parent) {
/* root value done */
flags |= flag_done;
continue;
}
if (top->parent->type == json_array) {
flags |= flag_seek_value;
}
if (!state.first_pass) {
json_value *parent = top->parent;
switch (parent->type) {
case json_object:
parent->u.object.values
[parent->u.object.length].value = top;
break;
case json_array:
parent->u.array.values
[parent->u.array.length] = top;
break;
default:
break;
}
}
if ((++top->parent->u.array.length) > state.uint_max) {
goto e_overflow;
}
top = top->parent;
continue;
}
}
alloc = root;
}
return root;
e_unknown_value:
sprintf(error, "%d:%d: Unknown value", cur_line, e_off);
goto e_failed;
e_alloc_failure:
strcpy(error, "Memory allocation failure");
goto e_failed;
e_overflow:
sprintf(error, "%d:%d: Too long (caught overflow)", cur_line, e_off);
goto e_failed;
e_failed:
if (error_buf) {
if (*error) {
strcpy(error_buf, error);
} else {
strcpy(error_buf, "Unknown error");
}
}
if (state.first_pass) {
alloc = root;
}
while (alloc) {
top = alloc->_reserved.next_alloc;
state.settings.mem_free(alloc, state.settings.user_data);
alloc = top;
}
if (!state.first_pass) {
json_value_free_ex(&state.settings, root);
}
return 0;
}
json_value *
json_parse(const json_char *json, size_t length)
{
json_settings settings = { 0UL, 0, NULL, NULL, NULL };
return json_parse_ex(&settings, json, length, 0);
}
void
json_value_free_ex(json_settings *settings, json_value *value)
{
json_value *cur_value;
if (!value) {
return;
}
value->parent = 0;
while (value) {
switch (value->type) {
case json_array:
if (!value->u.array.length) {
settings->mem_free(value->u.array.values, settings->user_data);
break;
}
value = value->u.array.values[--value->u.array.length];
continue;
case json_object:
if (!value->u.object.length) {
settings->mem_free(value->u.object.values, settings->user_data);
break;
}
value = value->u.object.values[--value->u.object.length].value;
continue;
case json_string:
settings->mem_free(value->u.string.ptr, settings->user_data);
break;
default:
break;
}
cur_value = value;
value = value->parent;
settings->mem_free(cur_value, settings->user_data);
}
}
void
json_value_free(json_value *value)
{
json_settings settings = { 0UL, 0, NULL, NULL, NULL };
settings.mem_free = default_free;
json_value_free_ex(&settings, value);
}
|
281677160/openwrt-package | 5,388 | luci-app-ssr-plus/shadowsocksr-libev/src/src/ss-nat | #!/bin/bash
#
# Copyright (C) 2015 OpenWrt-dist
# Copyright (C) 2015 Jian Chang <aa65535@live.com>
#
# This is free software, licensed under the GNU General Public License v3.
# See /LICENSE for more information.
#
TAG="SS_SPEC" # iptables tag
IPT="iptables -t nat" # alias of iptables
FWI=$(uci get firewall.shadowsocks.path 2>/dev/null) # firewall include file
usage() {
cat <<-EOF
Copyright (C) 2015 OpenWrt-dist
Copyright (C) 2015 Jian Chang <aa65535@live.com>
Usage: ss-nat [options]
Valid options are:
-s <server_ip> ip address of shadowsocks remote server
-l <local_port> port number of shadowsocks local server
-S <server_ip> ip address of shadowsocks remote UDP server
-L <local_port> port number of shadowsocks local UDP server
-i <ip_list_file> a file content is bypassed ip list
-a <lan_ips> lan ip of access control, need a prefix to
define access control mode
-b <wan_ips> wan ip of will be bypassed
-w <wan_ips> wan ip of will be forwarded
-e <extra_options> extra options for iptables
-o apply the rules to the OUTPUT chain
-u enable udprelay mode, TPROXY is required
-U enable udprelay mode, using different IP
and ports for TCP and UDP
-f flush the rules
-h show this help message and exit
This is free software, licensed under the GNU General Public License v3.
See /LICENSE for more information.
EOF
exit $1
}
loger() {
# 1.alert 2.crit 3.err 4.warn 5.notice 6.info 7.debug
logger -st ss-rules[$$] -p$1 $2
}
flush_r() {
iptables-save -c | grep -v "$TAG" | iptables-restore -c
ip rule del fwmark 0x01/0x01 table 100 2>/dev/null
ip route del local 0.0.0.0/0 dev lo table 100 2>/dev/null
ipset -X ss_spec_lan_ac 2>/dev/null
ipset -X ss_spec_wan_ac 2>/dev/null
[ -n "$FWI" ] && echo '#!/bin/sh' >$FWI
return 0
}
ipset_r() {
ipset -! -R <<-EOF || return 1
create ss_spec_wan_ac hash:net
$(gen_iplist | sed "/^\s*$/d" | sed -e "s/^/add ss_spec_wan_ac /")
$(for ip in $WAN_FW_IP; do echo "add ss_spec_wan_ac $ip nomatch"; done)
EOF
$IPT -N SS_SPEC_WAN_AC && \
$IPT -A SS_SPEC_WAN_AC -m set --match-set ss_spec_wan_ac dst -j RETURN && \
$IPT -A SS_SPEC_WAN_AC -j SS_SPEC_WAN_FW
return $?
}
fw_rule() {
$IPT -N SS_SPEC_WAN_FW && \
$IPT -A SS_SPEC_WAN_FW -p tcp \
-j REDIRECT --to-ports $local_port 2>/dev/null || {
loger 3 "Can't redirect, please check the iptables."
exit 1
}
return $?
}
ac_rule() {
if [ -n "$LAN_AC_IP" ]; then
case "${LAN_AC_IP:0:1}" in
w|W)
MATCH_SET="-m set --match-set ss_spec_lan_ac src"
;;
b|B)
MATCH_SET="-m set ! --match-set ss_spec_lan_ac src"
;;
*)
loger 3 "Illegal argument \`-a $LAN_AC_IP\`."
return 2
;;
esac
fi
IFNAME=eth0
ipset -! -R <<-EOF || return 1
create ss_spec_lan_ac hash:net
$(for ip in ${LAN_AC_IP:1}; do echo "add ss_spec_lan_ac $ip"; done)
EOF
$IPT -I PREROUTING 1 ${IFNAME:+-i $IFNAME} -p tcp $EXT_ARGS $MATCH_SET \
-j SS_SPEC_WAN_AC
if [ "$OUTPUT" = 1 ]; then
$IPT -I OUTPUT 1 -p tcp $EXT_ARGS -j SS_SPEC_WAN_AC
fi
return $?
}
tp_rule() {
lsmod | grep -q TPROXY || return 0
[ -n "$TPROXY" ] || return 0
ip rule add fwmark 0x01/0x01 table 100
ip route add local 0.0.0.0/0 dev lo table 100
local ipt="iptables -t mangle"
$ipt -N SS_SPEC_TPROXY
$ipt -A SS_SPEC_TPROXY -p udp -m set ! --match-set ss_spec_wan_ac dst \
-j TPROXY --on-port "$LOCAL_PORT" --tproxy-mark 0x01/0x01
$ipt -I PREROUTING 1 ${IFNAME:+-i $IFNAME} -p udp $EXT_ARGS $MATCH_SET \
-j SS_SPEC_TPROXY
return $?
}
get_wan_ip() {
cat <<-EOF | grep -E "^([0-9]{1,3}\.){3}[0-9]{1,3}"
$server
$SERVER
$WAN_BP_IP
EOF
}
gen_iplist() {
cat <<-EOF
0.0.0.0/8
10.0.0.0/8
100.64.0.0/10
127.0.0.0/8
169.254.0.0/16
172.16.0.0/12
192.0.0.0/24
192.0.2.0/24
192.88.99.0/24
192.168.0.0/16
198.18.0.0/15
198.51.100.0/24
203.0.113.0/24
224.0.0.0/4
240.0.0.0/4
255.255.255.255
$(get_wan_ip)
$(cat ${IGNORE_LIST:=/dev/null} 2>/dev/null)
EOF
}
gen_include() {
[ -n "$FWI" ] || return 0
cat <<-EOF >>$FWI
iptables-restore -n <<-EOT
$(iptables-save | grep -E "$TAG|^\*|^COMMIT" |\
sed -e "s/^-A \(OUTPUT\|PREROUTING\)/-I \1 1/")
EOT
EOF
return $?
}
while getopts ":s:l:S:L:i:e:a:b:w:ouUfh" arg; do
case "$arg" in
s)
server=$OPTARG
;;
l)
local_port=$OPTARG
;;
S)
SERVER=$OPTARG
;;
L)
LOCAL_PORT=$OPTARG
;;
i)
IGNORE_LIST=$OPTARG
;;
e)
EXT_ARGS=$OPTARG
;;
a)
LAN_AC_IP=$OPTARG
;;
b)
WAN_BP_IP=$(for ip in $OPTARG; do echo $ip; done)
;;
w)
WAN_FW_IP=$OPTARG
;;
o)
OUTPUT=1
;;
u)
TPROXY=1
;;
U)
TPROXY=2
;;
f)
flush_r
exit 0
;;
h)
usage 0
;;
esac
done
if [ -z "$server" -o -z "$local_port" ]; then
usage 2
fi
if [ "$TPROXY" = 1 ]; then
SERVER=$server
LOCAL_PORT=$local_port
elif [ "$TPROXY" = 2 ]; then
: ${SERVER:?"You must assign an ip for the udp relay server."}
: ${LOCAL_PORT:?"You must assign a port for the udp relay server."}
fi
flush_r && fw_rule && ipset_r && ac_rule && tp_rule && gen_include
[ "$?" = 0 ] || loger 3 "Start failed!"
exit $?
|
281677160/openwrt-package | 2,036 | luci-app-ssr-plus/shadowsocksr-libev/src/src/rule.h | /*
* Copyright (c) 2011 and 2012, Dustin Lundquist <dustin@null-ptr.net>
* Copyright (c) 2011 Manuel Kasper <mk@neon1.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RULE_H
#define RULE_H
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <libcork/ds.h>
#ifdef HAVE_PCRE_H
#include <pcre.h>
#elif HAVE_PCRE_PCRE_H
#include <pcre/pcre.h>
#endif
typedef struct rule {
char *pattern;
/* Runtime fields */
pcre *pattern_re;
struct cork_dllist_item entries;
} rule_t;
void add_rule(struct cork_dllist *, rule_t *);
int init_rule(rule_t *);
rule_t *lookup_rule(const struct cork_dllist *, const char *, size_t);
void remove_rule(rule_t *);
rule_t *new_rule();
int accept_rule_arg(rule_t *, const char *);
#endif
|
281677160/openwrt-package | 7,105 | luci-app-ssr-plus/shadowsocksr-libev/src/src/cache.c | /*
* cache.c - Manage the connection cache for UDPRELAY
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
/*
* Original Author: Oliver Lorenz (ol), olli@olorenz.org, https://olorenz.org
* License: This is licensed under the same terms as uthash itself
*/
#include <errno.h>
#include <stdlib.h>
#include "cache.h"
#include "utils.h"
#ifdef __MINGW32__
#include "win32.h"
#endif
/** Creates a new cache object
*
* @param dst
* Where the newly allocated cache object will be stored in
*
* @param capacity
* The maximum number of elements this cache object can hold
*
* @return EINVAL if dst is NULL, ENOMEM if malloc fails, 0 otherwise
*/
int
cache_create(struct cache **dst, const size_t capacity,
void (*free_cb)(void *key, void *element))
{
struct cache *new = NULL;
if (!dst) {
return EINVAL;
}
if ((new = malloc(sizeof(*new))) == NULL) {
return ENOMEM;
}
new->max_entries = capacity;
new->entries = NULL;
new->free_cb = free_cb;
*dst = new;
return 0;
}
/** Frees an allocated cache object
*
* @param cache
* The cache object to free
*
* @param keep_data
* Whether to free contained data or just delete references to it
*
* @return EINVAL if cache is NULL, 0 otherwise
*/
int
cache_delete(struct cache *cache, int keep_data)
{
struct cache_entry *entry, *tmp;
if (!cache) {
return EINVAL;
}
if (keep_data) {
HASH_CLEAR(hh, cache->entries);
} else {
HASH_ITER(hh, cache->entries, entry, tmp){
HASH_DEL(cache->entries, entry);
if (entry->data != NULL) {
if (cache->free_cb) {
cache->free_cb(entry->key, entry->data);
} else {
ss_free(entry->data);
}
}
ss_free(entry->key);
ss_free(entry);
}
}
ss_free(cache);
return 0;
}
/** Clear old cache object
*
* @param cache
* The cache object to clear
*
* @param age
* Clear only objects older than the age (sec)
*
* @return EINVAL if cache is NULL, 0 otherwise
*/
int
cache_clear(struct cache *cache, ev_tstamp age)
{
struct cache_entry *entry, *tmp;
if (!cache) {
return EINVAL;
}
ev_tstamp now = ev_time();
HASH_ITER(hh, cache->entries, entry, tmp){
if (now - entry->ts > age) {
HASH_DEL(cache->entries, entry);
if (entry->data != NULL) {
if (cache->free_cb) {
cache->free_cb(entry->key, entry->data);
} else {
ss_free(entry->data);
}
}
ss_free(entry->key);
ss_free(entry);
}
}
return 0;
}
/** Removes a cache entry
*
* @param cache
* The cache object
*
* @param key
* The key of the entry to remove
*
* @param key_len
* The length of key
*
* @return EINVAL if cache is NULL, 0 otherwise
*/
int
cache_remove(struct cache *cache, char *key, size_t key_len)
{
struct cache_entry *tmp;
if (!cache || !key) {
return EINVAL;
}
HASH_FIND(hh, cache->entries, key, key_len, tmp);
if (tmp) {
HASH_DEL(cache->entries, tmp);
if (tmp->data != NULL) {
if (cache->free_cb) {
cache->free_cb(tmp->key, tmp->data);
} else {
ss_free(tmp->data);
}
}
ss_free(tmp->key);
ss_free(tmp);
}
return 0;
}
/** Checks if a given key is in the cache
*
* @param cache
* The cache object
*
* @param key
* The key to look-up
*
* @param key_len
* The length of key
*
* @param result
* Where to store the result if key is found.
*
* A warning: Even though result is just a pointer,
* you have to call this function with a **ptr,
* otherwise this will blow up in your face.
*
* @return EINVAL if cache is NULL, 0 otherwise
*/
int
cache_lookup(struct cache *cache, char *key, size_t key_len, void *result)
{
struct cache_entry *tmp = NULL;
char **dirty_hack = result;
if (!cache || !key || !result) {
return EINVAL;
}
HASH_FIND(hh, cache->entries, key, key_len, tmp);
if (tmp) {
HASH_DELETE(hh, cache->entries, tmp);
tmp->ts = ev_time();
HASH_ADD_KEYPTR(hh, cache->entries, tmp->key, key_len, tmp);
*dirty_hack = tmp->data;
} else {
*dirty_hack = result = NULL;
}
return 0;
}
int
cache_key_exist(struct cache *cache, char *key, size_t key_len)
{
struct cache_entry *tmp = NULL;
if (!cache || !key) {
return 0;
}
HASH_FIND(hh, cache->entries, key, key_len, tmp);
if (tmp) {
HASH_DELETE(hh, cache->entries, tmp);
tmp->ts = ev_time();
HASH_ADD_KEYPTR(hh, cache->entries, tmp->key, key_len, tmp);
return 1;
} else {
return 0;
}
return 0;
}
/** Inserts a given <key, value> pair into the cache
*
* @param cache
* The cache object
*
* @param key
* The key that identifies <value>
*
* @param key_len
* The length of key
*
* @param data
* Data associated with <key>
*
* @return EINVAL if cache is NULL, ENOMEM if malloc fails, 0 otherwise
*/
int
cache_insert(struct cache *cache, char *key, size_t key_len, void *data)
{
struct cache_entry *entry = NULL;
struct cache_entry *tmp_entry = NULL;
if (!cache) {
return EINVAL;
}
if ((entry = malloc(sizeof(*entry))) == NULL) {
return ENOMEM;
}
entry->key = ss_malloc(key_len + 1);
memcpy(entry->key, key, key_len);
entry->key[key_len] = 0;
entry->data = data;
entry->ts = ev_time();
HASH_ADD_KEYPTR(hh, cache->entries, entry->key, key_len, entry);
if (HASH_COUNT(cache->entries) >= cache->max_entries) {
HASH_ITER(hh, cache->entries, entry, tmp_entry){
HASH_DELETE(hh, cache->entries, entry);
if (entry->data != NULL) {
if (cache->free_cb) {
cache->free_cb(entry->key, entry->data);
} else {
ss_free(entry->data);
}
}
ss_free(entry->key);
ss_free(entry);
break;
}
}
return 0;
}
|
281677160/openwrt-package | 5,840 | luci-app-ssr-plus/shadowsocksr-libev/src/src/json.h | /* vim: set et ts=3 sw=3 sts=3 ft=c:
*
* Copyright (C) 2012, 2013, 2014 James McLaughlin et al. All rights reserved.
* https://github.com/udp/json-parser
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _JSON_H
#define _JSON_H
#ifndef json_char
#define json_char char
#endif
#ifndef json_int_t
#ifndef _MSC_VER
#include <inttypes.h>
#define json_int_t int64_t
#else
#define json_int_t __int64
#endif
#endif
#include <stdlib.h>
#ifdef __cplusplus
#include <string.h>
extern "C"
{
#endif
typedef struct {
unsigned long max_memory;
int settings;
/* Custom allocator support (leave null to use malloc/free)
*/
void * (*mem_alloc)(size_t, int zero, void *user_data);
void (*mem_free)(void *, void *user_data);
void *user_data; /* will be passed to mem_alloc and mem_free */
} json_settings;
#define json_enable_comments 0x01
typedef enum {
json_none,
json_object,
json_array,
json_integer,
json_double,
json_string,
json_boolean,
json_null
} json_type;
extern const struct _json_value json_value_none;
typedef struct _json_value {
struct _json_value *parent;
json_type type;
union {
int boolean;
json_int_t integer;
double dbl;
struct {
unsigned int length;
json_char *ptr; /* null terminated */
} string;
struct {
unsigned int length;
struct {
json_char *name;
unsigned int name_length;
struct _json_value *value;
} *values;
#if defined(__cplusplus) && __cplusplus >= 201103L
decltype(values) begin() const
{
return values;
}
decltype(values) end() const
{
return values + length;
}
#endif
} object;
struct {
unsigned int length;
struct _json_value **values;
#if defined(__cplusplus) && __cplusplus >= 201103L
decltype(values) begin() const
{
return values;
}
decltype(values) end() const
{
return values + length;
}
#endif
} array;
} u;
union {
struct _json_value *next_alloc;
void *object_mem;
} _reserved;
/* Some C++ operator sugar */
#ifdef __cplusplus
public:
inline _json_value(){
memset(this, 0, sizeof(_json_value));
}
inline const struct _json_value &operator [] (int index) const {
if (type != json_array || index < 0
|| ((unsigned int)index) >= u.array.length) {
return json_value_none;
}
return *u.array.values[index];
}
inline const struct _json_value &operator [] (const char *index) const {
if (type != json_object) {
return json_value_none;
}
for (unsigned int i = 0; i < u.object.length; ++i)
if (!strcmp(u.object.values[i].name, index)) {
return *u.object.values[i].value;
}
return json_value_none;
}
inline operator const char * () const
{
switch (type) {
case json_string:
return u.string.ptr;
default:
return "";
}
}
inline operator
json_int_t() const
{
switch (type) {
case json_integer:
return u.integer;
case json_double:
return (json_int_t)u.dbl;
default:
return 0;
}
}
inline operator
bool() const
{
if (type != json_boolean) {
return false;
}
return u.boolean != 0;
}
inline operator double () const
{
switch (type) {
case json_integer:
return (double)u.integer;
case json_double:
return u.dbl;
default:
return 0;
}
}
#endif
} json_value;
json_value *json_parse(const json_char *json,
size_t length);
#define json_error_max 128
json_value *json_parse_ex(json_settings *settings,
const json_char *json,
size_t length,
char *error);
void json_value_free(json_value *);
/* Not usually necessary, unless you used a custom mem_alloc and now want to
* use a custom mem_free.
*/
void json_value_free_ex(json_settings *settings,
json_value *);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
|
281677160/openwrt-package | 2,816 | luci-app-ssr-plus/shadowsocksr-libev/src/src/netutils.h | /*
* netutils.h - Network utilities
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _NETUTILS_H
#define _NETUTILS_H
#if defined(__linux__)
#include <netdb.h>
#elif !defined(__MINGW32__)
#include <netinet/tcp.h>
#endif
// only enable TCP_FASTOPEN on linux
#if defined(__linux__)
#include <linux/tcp.h>
/* conditional define for TCP_FASTOPEN */
#ifndef TCP_FASTOPEN
#define TCP_FASTOPEN 23
#endif
/* conditional define for MSG_FASTOPEN */
#ifndef MSG_FASTOPEN
#define MSG_FASTOPEN 0x20000000
#endif
#elif !defined(__APPLE__)
#ifdef TCP_FASTOPEN
#undef TCP_FASTOPEN
#endif
#endif
/* Backward compatibility for MPTCP_ENABLED between kernel 3 & 4 */
#ifndef MPTCP_ENABLED
#ifdef TCP_CC_INFO
#define MPTCP_ENABLED 42
#else
#define MPTCP_ENABLED 26
#endif
#endif
/** byte size of ip4 address */
#define INET_SIZE 4
/** byte size of ip6 address */
#define INET6_SIZE 16
size_t get_sockaddr_len(struct sockaddr *addr);
ssize_t get_sockaddr(char *host, char *port,
struct sockaddr_storage *storage, int block,
int ipv6first);
int set_reuseport(int socket);
#ifdef SET_INTERFACE
int setinterface(int socket_fd, const char *interface_name);
#endif
int bind_to_address(int socket_fd, const char *address);
/**
* Compare two sockaddrs. Imposes an ordering on the addresses.
* Compares address and port.
* @param addr1: address 1.
* @param addr2: address 2.
* @param len: lengths of addr.
* @return: 0 if addr1 == addr2. -1 if addr1 is smaller, +1 if larger.
*/
int sockaddr_cmp(struct sockaddr_storage *addr1,
struct sockaddr_storage *addr2, socklen_t len);
/**
* Compare two sockaddrs. Compares address, not the port.
* @param addr1: address 1.
* @param addr2: address 2.
* @param len: lengths of addr.
* @return: 0 if addr1 == addr2. -1 if addr1 is smaller, +1 if larger.
*/
int sockaddr_cmp_addr(struct sockaddr_storage *addr1,
struct sockaddr_storage *addr2, socklen_t len);
int validate_hostname(const char *hostname, const int hostname_len);
#endif
|
281677160/openwrt-package | 2,129 | luci-app-ssr-plus/shadowsocksr-libev/src/src/cache.h | /*
* cache.h - Define the cache manager interface
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
/*
* Original Author: Oliver Lorenz (ol), olli@olorenz.org, https://olorenz.org
* License: This is licensed under the same terms as uthash itself
*/
#ifndef _CACHE_
#define _CACHE_
#include "uthash.h"
#include "ev.h"
/**
* A cache entry
*/
struct cache_entry {
char *key; /**<The key */
void *data; /**<Payload */
ev_tstamp ts; /**<Timestamp */
UT_hash_handle hh; /**<Hash Handle for uthash */
};
/**
* A cache object
*/
struct cache {
size_t max_entries; /**<Amount of entries this cache object can hold */
struct cache_entry *entries; /**<Head pointer for uthash */
void (*free_cb) (void *key, void *element); /**<Callback function to free cache entries */
};
int cache_create(struct cache **dst, const size_t capacity,
void (*free_cb)(void *key, void *element));
int cache_delete(struct cache *cache, int keep_data);
int cache_clear(struct cache *cache, ev_tstamp age);
int cache_lookup(struct cache *cache, char *key, size_t key_len, void *result);
int cache_insert(struct cache *cache, char *key, size_t key_len, void *data);
int cache_remove(struct cache *cache, char *key, size_t key_len);
int cache_key_exist(struct cache *cache, char *key, size_t key_len);
#endif
|
281677160/openwrt-package | 13,726 | luci-app-ssr-plus/shadowsocksr-libev/src/src/resolv.c | /*
* Copyright (c) 2014, Dustin Lundquist <dustin@null-ptr.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <ev.h>
#include <udns.h>
#ifdef __MINGW32__
#include "win32.h"
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#endif
#include "resolv.h"
#include "utils.h"
#include "netutils.h"
/*
* Implement DNS resolution interface using libudns
*/
struct ResolvQuery {
void (*client_cb)(struct sockaddr *, void *);
void (*client_free_cb)(void *);
void *client_cb_data;
struct dns_query *queries[2];
size_t response_count;
struct sockaddr **responses;
uint16_t port;
};
extern int verbose;
static struct ev_io resolv_io_watcher;
static struct ev_timer resolv_timeout_watcher;
static const int MODE_IPV4_ONLY = 0;
static const int MODE_IPV6_ONLY = 1;
static const int MODE_IPV4_FIRST = 2;
static const int MODE_IPV6_FIRST = 3;
static int resolv_mode = 0;
static void resolv_sock_cb(struct ev_loop *, struct ev_io *, int);
static void resolv_timeout_cb(struct ev_loop *, struct ev_timer *, int);
static void dns_query_v4_cb(struct dns_ctx *, struct dns_rr_a4 *, void *);
static void dns_query_v6_cb(struct dns_ctx *, struct dns_rr_a6 *, void *);
static void dns_timer_setup_cb(struct dns_ctx *, int, void *);
static void process_client_callback(struct ResolvQuery *);
static inline int all_queries_are_null(struct ResolvQuery *);
static struct sockaddr *choose_ipv4_first(struct ResolvQuery *);
static struct sockaddr *choose_ipv6_first(struct ResolvQuery *);
static struct sockaddr *choose_any(struct ResolvQuery *);
int
resolv_init(struct ev_loop *loop, char **nameservers, int nameserver_num, int ipv6first)
{
if (ipv6first)
resolv_mode = MODE_IPV6_FIRST;
else
resolv_mode = MODE_IPV4_FIRST;
struct dns_ctx *ctx = &dns_defctx;
if (nameservers == NULL) {
/* Nameservers not specified, use system resolver config */
dns_init(ctx, 0);
} else {
dns_reset(ctx);
for (int i = 0; i < nameserver_num; i++) {
char *server = nameservers[i];
dns_add_serv(ctx, server);
}
}
int sockfd = dns_open(ctx);
if (sockfd < 0) {
FATAL("Failed to open DNS resolver socket");
}
if (nameserver_num == 1 && nameservers != NULL) {
if (strncmp("127.0.0.1", nameservers[0], 9) == 0
|| strncmp("::1", nameservers[0], 3) == 0) {
if (verbose) {
LOGI("bind UDP resolver to %s", nameservers[0]);
}
if (bind_to_address(sockfd, nameservers[0]) == -1)
ERROR("bind_to_address");
}
}
#ifdef __MINGW32__
setnonblocking(sockfd);
#else
int flags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
#endif
ev_io_init(&resolv_io_watcher, resolv_sock_cb, sockfd, EV_READ);
resolv_io_watcher.data = ctx;
ev_io_start(loop, &resolv_io_watcher);
ev_timer_init(&resolv_timeout_watcher, resolv_timeout_cb, 0.0, 0.0);
resolv_timeout_watcher.data = ctx;
dns_set_tmcbck(ctx, dns_timer_setup_cb, loop);
return sockfd;
}
void
resolv_shutdown(struct ev_loop *loop)
{
struct dns_ctx *ctx = (struct dns_ctx *)resolv_io_watcher.data;
ev_io_stop(loop, &resolv_io_watcher);
if (ev_is_active(&resolv_timeout_watcher)) {
ev_timer_stop(loop, &resolv_timeout_watcher);
}
dns_close(ctx);
}
struct ResolvQuery *
resolv_query(const char *hostname, void (*client_cb)(struct sockaddr *, void *),
void (*client_free_cb)(void *), void *client_cb_data,
uint16_t port)
{
struct dns_ctx *ctx = (struct dns_ctx *)resolv_io_watcher.data;
/*
* Wrap udns's call back in our own
*/
struct ResolvQuery *cb_data = ss_malloc(sizeof(struct ResolvQuery));
if (cb_data == NULL) {
LOGE("Failed to allocate memory for DNS query callback data.");
return NULL;
}
memset(cb_data, 0, sizeof(struct ResolvQuery));
cb_data->client_cb = client_cb;
cb_data->client_free_cb = client_free_cb;
cb_data->client_cb_data = client_cb_data;
memset(cb_data->queries, 0, sizeof(cb_data->queries));
cb_data->response_count = 0;
cb_data->responses = NULL;
cb_data->port = port;
/* Submit A and AAAA queries */
if (resolv_mode != MODE_IPV6_ONLY) {
cb_data->queries[0] = dns_submit_a4(ctx,
hostname, 0,
dns_query_v4_cb, cb_data);
if (cb_data->queries[0] == NULL) {
LOGE("Failed to submit DNS query: %s",
dns_strerror(dns_status(ctx)));
}
}
if (resolv_mode != MODE_IPV4_ONLY) {
cb_data->queries[1] = dns_submit_a6(ctx,
hostname, 0,
dns_query_v6_cb, cb_data);
if (cb_data->queries[1] == NULL) {
LOGE("Failed to submit DNS query: %s",
dns_strerror(dns_status(ctx)));
}
}
if (all_queries_are_null(cb_data)) {
if (cb_data->client_free_cb != NULL) {
cb_data->client_free_cb(cb_data->client_cb_data);
}
ss_free(cb_data);
}
return cb_data;
}
void
resolv_cancel(struct ResolvQuery *query_handle)
{
struct ResolvQuery *cb_data = (struct ResolvQuery *)query_handle;
struct dns_ctx *ctx = (struct dns_ctx *)resolv_io_watcher.data;
for (int i = 0; i < sizeof(cb_data->queries) / sizeof(cb_data->queries[0]);
i++)
if (cb_data->queries[i] != NULL) {
dns_cancel(ctx, cb_data->queries[i]);
ss_free(cb_data->queries[i]);
}
if (cb_data->client_free_cb != NULL) {
cb_data->client_free_cb(cb_data->client_cb_data);
}
ss_free(cb_data);
}
/*
* DNS UDP socket activity callback
*/
static void
resolv_sock_cb(struct ev_loop *loop, struct ev_io *w, int revents)
{
struct dns_ctx *ctx = (struct dns_ctx *)w->data;
if (revents & EV_READ) {
dns_ioevent(ctx, ev_now(loop));
}
}
/*
* Wrapper for client callback we provide to udns
*/
static void
dns_query_v4_cb(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data)
{
struct ResolvQuery *cb_data = (struct ResolvQuery *)data;
if (result == NULL) {
if (verbose) {
LOGI("IPv4 resolv: %s", dns_strerror(dns_status(ctx)));
}
} else if (result->dnsa4_nrr > 0) {
struct sockaddr **new_responses = ss_realloc(cb_data->responses,
(cb_data->response_count +
result->dnsa4_nrr) *
sizeof(struct sockaddr *));
if (new_responses == NULL) {
LOGE("Failed to allocate memory for additional DNS responses");
} else {
cb_data->responses = new_responses;
for (int i = 0; i < result->dnsa4_nrr; i++) {
struct sockaddr_in *sa = ss_malloc(sizeof(struct sockaddr_in));
memset(sa, 0, sizeof(struct sockaddr_in));
sa->sin_family = AF_INET;
sa->sin_port = cb_data->port;
sa->sin_addr = result->dnsa4_addr[i];
cb_data->responses[cb_data->response_count] =
(struct sockaddr *)sa;
if (cb_data->responses[cb_data->response_count] == NULL) {
LOGE(
"Failed to allocate memory for DNS query result address");
} else {
cb_data->response_count++;
}
}
}
}
ss_free(result);
cb_data->queries[0] = NULL; /* mark A query as being completed */
/* Once all queries have completed, call client callback */
if (all_queries_are_null(cb_data)) {
return process_client_callback(cb_data);
}
}
static void
dns_query_v6_cb(struct dns_ctx *ctx, struct dns_rr_a6 *result, void *data)
{
struct ResolvQuery *cb_data = (struct ResolvQuery *)data;
if (result == NULL) {
if (verbose) {
LOGI("IPv6 resolv: %s", dns_strerror(dns_status(ctx)));
}
} else if (result->dnsa6_nrr > 0) {
struct sockaddr **new_responses = ss_realloc(cb_data->responses,
(cb_data->response_count +
result->dnsa6_nrr) *
sizeof(struct sockaddr *));
if (new_responses == NULL) {
LOGE("Failed to allocate memory for additional DNS responses");
} else {
cb_data->responses = new_responses;
for (int i = 0; i < result->dnsa6_nrr; i++) {
struct sockaddr_in6 *sa = ss_malloc(sizeof(struct sockaddr_in6));
memset(sa, 0, sizeof(struct sockaddr_in6));
sa->sin6_family = AF_INET6;
sa->sin6_port = cb_data->port;
sa->sin6_addr = result->dnsa6_addr[i];
cb_data->responses[cb_data->response_count] =
(struct sockaddr *)sa;
if (cb_data->responses[cb_data->response_count] == NULL) {
LOGE(
"Failed to allocate memory for DNS query result address");
} else {
cb_data->response_count++;
}
}
}
}
ss_free(result);
cb_data->queries[1] = NULL; /* mark AAAA query as being completed */
/* Once all queries have completed, call client callback */
if (all_queries_are_null(cb_data)) {
return process_client_callback(cb_data);
}
}
/*
* Called once all queries have been completed
*/
static void
process_client_callback(struct ResolvQuery *cb_data)
{
struct sockaddr *best_address = NULL;
if (resolv_mode == MODE_IPV4_FIRST) {
best_address = choose_ipv4_first(cb_data);
} else if (resolv_mode == MODE_IPV6_FIRST) {
best_address = choose_ipv6_first(cb_data);
} else {
best_address = choose_any(cb_data);
}
cb_data->client_cb(best_address, cb_data->client_cb_data);
for (int i = 0; i < cb_data->response_count; i++)
ss_free(cb_data->responses[i]);
ss_free(cb_data->responses);
if (cb_data->client_free_cb != NULL) {
cb_data->client_free_cb(cb_data->client_cb_data);
}
ss_free(cb_data);
}
static struct sockaddr *
choose_ipv4_first(struct ResolvQuery *cb_data)
{
for (int i = 0; i < cb_data->response_count; i++)
if (cb_data->responses[i]->sa_family == AF_INET) {
return cb_data->responses[i];
}
return choose_any(cb_data);
}
static struct sockaddr *
choose_ipv6_first(struct ResolvQuery *cb_data)
{
for (int i = 0; i < cb_data->response_count; i++)
if (cb_data->responses[i]->sa_family == AF_INET6) {
return cb_data->responses[i];
}
return choose_any(cb_data);
}
static struct sockaddr *
choose_any(struct ResolvQuery *cb_data)
{
if (cb_data->response_count >= 1) {
return cb_data->responses[0];
}
return NULL;
}
/*
* DNS timeout callback
*/
static void
resolv_timeout_cb(struct ev_loop *loop, struct ev_timer *w, int revents)
{
struct dns_ctx *ctx = (struct dns_ctx *)w->data;
if (revents & EV_TIMER) {
dns_timeouts(ctx, 30, ev_now(loop));
}
}
/*
* Callback to setup DNS timeout callback
*/
static void
dns_timer_setup_cb(struct dns_ctx *ctx, int timeout, void *data)
{
struct ev_loop *loop = (struct ev_loop *)data;
if (ev_is_active(&resolv_timeout_watcher)) {
ev_timer_stop(loop, &resolv_timeout_watcher);
}
if (ctx != NULL && timeout >= 0) {
ev_timer_set(&resolv_timeout_watcher, timeout, 0.0);
ev_timer_start(loop, &resolv_timeout_watcher);
}
}
static inline int
all_queries_are_null(struct ResolvQuery *cb_data)
{
int result = 1;
for (int i = 0; i < sizeof(cb_data->queries) / sizeof(cb_data->queries[0]);
i++)
result = result && cb_data->queries[i] == NULL;
return result;
}
|
281677160/openwrt-package | 26,035 | luci-app-ssr-plus/shadowsocksr-libev/src/src/manager.c | /*
* server.c - Provide shadowsocks service
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <locale.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <math.h>
#include <ctype.h>
#include <limits.h>
#include <dirent.h>
#ifndef __MINGW32__
#include <netdb.h>
#include <errno.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <pwd.h>
#endif
#include <libcork/core.h>
#ifdef __MINGW32__
#include "win32.h"
#endif
#if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H) && defined(__linux__)
#include <net/if.h>
#include <sys/ioctl.h>
#define SET_INTERFACE
#endif
#include "json.h"
#include "utils.h"
#include "manager.h"
#ifndef BUF_SIZE
#define BUF_SIZE 65535
#endif
int verbose = 0;
char *executable = "ss-server";
char *working_dir = NULL;
int working_dir_size = 0;
static struct cork_hash_table *server_table;
#ifndef __MINGW32__
static int
setnonblocking(int fd)
{
int flags;
if (-1 == (flags = fcntl(fd, F_GETFL, 0))) {
flags = 0;
}
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
#endif
static void
build_config(char *prefix, struct server *server)
{
char *path = NULL;
int path_size = strlen(prefix) + strlen(server->port) + 20;
path = ss_malloc(path_size);
snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port);
FILE *f = fopen(path, "w+");
if (f == NULL) {
if (verbose) {
LOGE("unable to open config file");
}
ss_free(path);
return;
}
fprintf(f, "{\n");
fprintf(f, "\"server_port\":\"%s\",\n", server->port);
fprintf(f, "\"password\":\"%s\",\n", server->password);
fprintf(f, "}\n");
fclose(f);
ss_free(path);
}
static char *
construct_command_line(struct manager_ctx *manager, struct server *server)
{
static char cmd[BUF_SIZE];
int i;
build_config(working_dir, server);
memset(cmd, 0, BUF_SIZE);
snprintf(cmd, BUF_SIZE,
"%s -m %s --manager-address %s -f %s/.shadowsocks_%s.pid -c %s/.shadowsocks_%s.conf",
executable, manager->method, manager->manager_address,
working_dir, server->port, working_dir, server->port);
if (manager->acl != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --acl %s", manager->acl);
}
if (manager->timeout != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -t %s", manager->timeout);
}
#ifdef HAVE_SETRLIMIT
if (manager->nofile) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -n %d", manager->nofile);
}
#endif
if (manager->user != NULL) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -a %s", manager->user);
}
if (manager->verbose) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -v");
}
if (manager->mode == UDP_ONLY) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -U");
}
if (manager->mode == TCP_AND_UDP) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -u");
}
if (manager->fast_open) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --fast-open");
}
if (manager->mtu) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " --mtu %d", manager->mtu);
}
for (i = 0; i < manager->nameserver_num; i++) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -d %s", manager->nameservers[i]);
}
for (i = 0; i < manager->host_num; i++) {
int len = strlen(cmd);
snprintf(cmd + len, BUF_SIZE - len, " -s %s", manager->hosts[i]);
}
if (verbose) {
LOGI("cmd: %s", cmd);
}
return cmd;
}
static char *
get_data(char *buf, int len)
{
char *data;
int pos = 0;
while (buf[pos] != '{' && pos < len)
pos++;
if (pos == len) {
return NULL;
}
data = buf + pos - 1;
return data;
}
static char *
get_action(char *buf, int len)
{
char *action;
int pos = 0;
while (isspace((unsigned char)buf[pos]) && pos < len)
pos++;
if (pos == len) {
return NULL;
}
action = buf + pos;
while ((!isspace((unsigned char)buf[pos]) && buf[pos] != ':') && pos < len)
pos++;
buf[pos] = '\0';
return action;
}
static struct server *
get_server(char *buf, int len)
{
char *data = get_data(buf, len);
char error_buf[512];
if (data == NULL) {
LOGE("No data found");
return NULL;
}
json_settings settings = { 0 };
json_value *obj = json_parse_ex(&settings, data, strlen(data), error_buf);
if (obj == NULL) {
LOGE("%s", error_buf);
return NULL;
}
struct server *server = ss_malloc(sizeof(struct server));
memset(server, 0, sizeof(struct server));
if (obj->type == json_object) {
int i = 0;
for (i = 0; i < obj->u.object.length; i++) {
char *name = obj->u.object.values[i].name;
json_value *value = obj->u.object.values[i].value;
if (strcmp(name, "server_port") == 0) {
if (value->type == json_string) {
strncpy(server->port, value->u.string.ptr, 8);
} else if (value->type == json_integer) {
snprintf(server->port, 8, "%" PRIu64 "", value->u.integer);
}
} else if (strcmp(name, "password") == 0) {
if (value->type == json_string) {
strncpy(server->password, value->u.string.ptr, 128);
}
} else {
LOGE("invalid data: %s", data);
break;
}
}
}
json_value_free(obj);
return server;
}
static int
parse_traffic(char *buf, int len, char *port, uint64_t *traffic)
{
char *data = get_data(buf, len);
char error_buf[512];
json_settings settings = { 0 };
if (data == NULL) {
LOGE("No data found");
return -1;
}
json_value *obj = json_parse_ex(&settings, data, strlen(data), error_buf);
if (obj == NULL) {
LOGE("%s", error_buf);
return -1;
}
if (obj->type == json_object) {
int i = 0;
for (i = 0; i < obj->u.object.length; i++) {
char *name = obj->u.object.values[i].name;
json_value *value = obj->u.object.values[i].value;
if (value->type == json_integer) {
strncpy(port, name, 8);
*traffic = value->u.integer;
}
}
}
json_value_free(obj);
return 0;
}
static void
add_server(struct manager_ctx *manager, struct server *server)
{
bool new = false;
cork_hash_table_put(server_table, (void *)server->port, (void *)server, &new, NULL, NULL);
char *cmd = construct_command_line(manager, server);
if (system(cmd) == -1) {
ERROR("add_server_system");
}
}
static void
kill_server(char *prefix, char *pid_file)
{
char *path = NULL;
int pid, path_size = strlen(prefix) + strlen(pid_file) + 2;
path = ss_malloc(path_size);
snprintf(path, path_size, "%s/%s", prefix, pid_file);
FILE *f = fopen(path, "r");
if (f == NULL) {
if (verbose) {
LOGE("unable to open pid file");
}
ss_free(path);
return;
}
if (fscanf(f, "%d", &pid) != EOF) {
kill(pid, SIGTERM);
}
fclose(f);
remove(path);
ss_free(path);
}
static void
stop_server(char *prefix, char *port)
{
char *path = NULL;
int pid, path_size = strlen(prefix) + strlen(port) + 20;
path = ss_malloc(path_size);
snprintf(path, path_size, "%s/.shadowsocks_%s.pid", prefix, port);
FILE *f = fopen(path, "r");
if (f == NULL) {
if (verbose) {
LOGE("unable to open pid file");
}
ss_free(path);
return;
}
if (fscanf(f, "%d", &pid) != EOF) {
kill(pid, SIGTERM);
}
fclose(f);
ss_free(path);
}
static void
remove_server(char *prefix, char *port)
{
char *old_port = NULL;
struct server *old_server = NULL;
cork_hash_table_delete(server_table, (void *)port, (void **)&old_port, (void **)&old_server);
if (old_server != NULL) {
ss_free(old_server);
}
stop_server(prefix, port);
}
static void
update_stat(char *port, uint64_t traffic)
{
void *ret = cork_hash_table_get(server_table, (void *)port);
if (ret != NULL) {
struct server *server = (struct server *)ret;
server->traffic = traffic;
}
}
static void
manager_recv_cb(EV_P_ ev_io *w, int revents)
{
struct manager_ctx *manager = (struct manager_ctx *)w;
socklen_t len;
size_t r;
struct sockaddr_un claddr;
char buf[BUF_SIZE];
memset(buf, 0, BUF_SIZE);
len = sizeof(struct sockaddr_un);
r = recvfrom(manager->fd, buf, BUF_SIZE, 0, (struct sockaddr *)&claddr, &len);
if (r == -1) {
ERROR("manager_recvfrom");
return;
}
if (r > BUF_SIZE / 2) {
LOGE("too large request: %d", (int)r);
return;
}
char *action = get_action(buf, r);
if (action == NULL) {
return;
}
if (strcmp(action, "add") == 0) {
struct server *server = get_server(buf, r);
if (server == NULL || server->port[0] == 0 || server->password[0] == 0) {
LOGE("invalid command: %s:%s", buf, get_data(buf, r));
if (server != NULL) {
ss_free(server);
}
goto ERROR_MSG;
}
remove_server(working_dir, server->port);
add_server(manager, server);
char msg[3] = "ok";
if (sendto(manager->fd, msg, 2, 0, (struct sockaddr *)&claddr, len) != 2) {
ERROR("add_sendto");
}
} else if (strcmp(action, "remove") == 0) {
struct server *server = get_server(buf, r);
if (server == NULL || server->port[0] == 0) {
LOGE("invalid command: %s:%s", buf, get_data(buf, r));
if (server != NULL) {
ss_free(server);
}
goto ERROR_MSG;
}
remove_server(working_dir, server->port);
ss_free(server);
char msg[3] = "ok";
if (sendto(manager->fd, msg, 2, 0, (struct sockaddr *)&claddr, len) != 2) {
ERROR("remove_sendto");
}
} else if (strcmp(action, "stat") == 0) {
char port[8];
uint64_t traffic = 0;
if (parse_traffic(buf, r, port, &traffic) == -1) {
LOGE("invalid command: %s:%s", buf, get_data(buf, r));
return;
}
update_stat(port, traffic);
} else if (strcmp(action, "ping") == 0) {
struct cork_hash_table_entry *entry;
struct cork_hash_table_iterator server_iter;
char buf[BUF_SIZE];
memset(buf, 0, BUF_SIZE);
sprintf(buf, "stat: {");
cork_hash_table_iterator_init(server_table, &server_iter);
while ((entry = cork_hash_table_iterator_next(&server_iter)) != NULL) {
struct server *server = (struct server *)entry->value;
size_t pos = strlen(buf);
if (pos > BUF_SIZE / 2) {
buf[pos - 1] = '}';
if (sendto(manager->fd, buf, pos, 0, (struct sockaddr *)&claddr, len)
!= pos) {
ERROR("ping_sendto");
}
memset(buf, 0, BUF_SIZE);
} else {
sprintf(buf + pos, "\"%s\":%" PRIu64 ",", server->port, server->traffic);
}
}
size_t pos = strlen(buf);
if (pos > 7) {
buf[pos - 1] = '}';
} else {
buf[pos] = '}';
pos++;
}
if (sendto(manager->fd, buf, pos, 0, (struct sockaddr *)&claddr, len)
!= pos) {
ERROR("ping_sendto");
}
}
return;
ERROR_MSG:
strcpy(buf, "err");
if (sendto(manager->fd, buf, 3, 0, (struct sockaddr *)&claddr, len) != 3) {
ERROR("error_sendto");
}
}
static void
signal_cb(EV_P_ ev_signal *w, int revents)
{
if (revents & EV_SIGNAL) {
switch (w->signum) {
case SIGINT:
case SIGTERM:
ev_unloop(EV_A_ EVUNLOOP_ALL);
}
}
}
int
create_server_socket(const char *host, const char *port)
{
struct addrinfo hints;
struct addrinfo *result, *rp, *ipv4v6bindall;
int s, server_sock;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
hints.ai_socktype = SOCK_DGRAM; /* We want a UDP socket */
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; /* For wildcard IP address */
hints.ai_protocol = IPPROTO_UDP;
s = getaddrinfo(host, port, &hints, &result);
if (s != 0) {
LOGE("getaddrinfo: %s", gai_strerror(s));
return -1;
}
rp = result;
/*
* On Linux, with net.ipv6.bindv6only = 0 (the default), getaddrinfo(NULL) with
* AI_PASSIVE returns 0.0.0.0 and :: (in this order). AI_PASSIVE was meant to
* return a list of addresses to listen on, but it is impossible to listen on
* 0.0.0.0 and :: at the same time, if :: implies dualstack mode.
*/
if (!host) {
ipv4v6bindall = result;
/* Loop over all address infos found until a IPV6 address is found. */
while (ipv4v6bindall) {
if (ipv4v6bindall->ai_family == AF_INET6) {
rp = ipv4v6bindall; /* Take first IPV6 address available */
break;
}
ipv4v6bindall = ipv4v6bindall->ai_next; /* Get next address info, if any */
}
}
for (/*rp = result*/; rp != NULL; rp = rp->ai_next) {
server_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (server_sock == -1) {
continue;
}
if (rp->ai_family == AF_INET6) {
int ipv6only = host ? 1 : 0;
setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6only, sizeof(ipv6only));
}
int opt = 1;
setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
s = bind(server_sock, rp->ai_addr, rp->ai_addrlen);
if (s == 0) {
/* We managed to bind successfully! */
break;
} else {
ERROR("bind");
}
close(server_sock);
}
if (rp == NULL) {
LOGE("cannot bind");
return -1;
}
freeaddrinfo(result);
return server_sock;
}
int
main(int argc, char **argv)
{
int i, c;
int pid_flags = 0;
char *acl = NULL;
char *user = NULL;
char *password = NULL;
char *timeout = NULL;
char *method = NULL;
char *pid_path = NULL;
char *conf_path = NULL;
char *iface = NULL;
char *manager_address = NULL;
int fast_open = 0;
int mode = TCP_ONLY;
int mtu = 0;
#ifdef HAVE_SETRLIMIT
static int nofile = 0;
#endif
int server_num = 0;
char *server_host[MAX_REMOTE_NUM];
char *nameservers[MAX_DNS_NUM + 1];
int nameserver_num = 0;
jconf_t *conf = NULL;
int option_index = 0;
static struct option long_options[] = {
{ "fast-open", no_argument, 0, 0 },
{ "acl", required_argument, 0, 0 },
{ "manager-address", required_argument, 0, 0 },
{ "executable", required_argument, 0, 0 },
{ "mtu", required_argument, 0, 0 },
{ "help", no_argument, 0, 0 },
{ 0, 0, 0, 0 }
};
opterr = 0;
USE_TTY();
while ((c = getopt_long(argc, argv, "f:s:l:k:t:m:c:i:d:a:n:huUvA",
long_options, &option_index)) != -1)
switch (c) {
case 0:
if (option_index == 0) {
fast_open = 1;
} else if (option_index == 1) {
acl = optarg;
} else if (option_index == 2) {
manager_address = optarg;
} else if (option_index == 3) {
executable = optarg;
} else if (option_index == 4) {
mtu = atoi(optarg);
LOGI("set MTU to %d", mtu);
} else if (option_index == 5) {
usage();
exit(EXIT_SUCCESS);
}
break;
case 's':
if (server_num < MAX_REMOTE_NUM) {
server_host[server_num++] = optarg;
}
break;
case 'k':
password = optarg;
break;
case 'f':
pid_flags = 1;
pid_path = optarg;
break;
case 't':
timeout = optarg;
break;
case 'm':
method = optarg;
break;
case 'c':
conf_path = optarg;
break;
case 'i':
iface = optarg;
break;
case 'd':
if (nameserver_num < MAX_DNS_NUM) {
nameservers[nameserver_num++] = optarg;
}
break;
case 'a':
user = optarg;
break;
case 'u':
mode = TCP_AND_UDP;
break;
case 'U':
mode = UDP_ONLY;
break;
case 'v':
verbose = 1;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'A':
LOGI("The 'A' argument is deprecate! Ignored.");
break;
#ifdef HAVE_SETRLIMIT
case 'n':
nofile = atoi(optarg);
break;
#endif
case '?':
// The option character is not recognized.
LOGE("Unrecognized option: %s", optarg);
opterr = 1;
break;
}
if (opterr) {
usage();
exit(EXIT_FAILURE);
}
if (conf_path != NULL) {
conf = read_jconf(conf_path);
if (server_num == 0) {
server_num = conf->server_new_1.server_num;
//for (i = 0; i < server_num; i++)
// server_host[i].host = conf->server_new_1.servers[i].server;
// server_host[i].port = conf->server_new_1.servers[i].server_port;
//}
} else {
conf->server_new_1.server_num = 1;
}
if (password == NULL) {
password = conf->server_new_1.servers[0].password;
}
if (method == NULL) {
method = conf->server_new_1.servers[0].method;
}
if (timeout == NULL) {
timeout = conf->timeout;
}
if (user == NULL) {
user = conf->user;
}
#ifdef TCP_FASTOPEN
if (fast_open == 0) {
fast_open = conf->fast_open;
}
#endif
if (conf->nameserver != NULL) {
nameservers[nameserver_num++] = conf->nameserver;
}
if (mode == TCP_ONLY) {
mode = conf->mode;
}
if (mtu == 0) {
mtu = conf->mtu;
}
#ifdef HAVE_SETRLIMIT
if (nofile == 0) {
nofile = conf->nofile;
}
#endif
}
if (server_num == 0) {
server_host[server_num++] = "0.0.0.0";
}
if (method == NULL) {
method = "table";
}
if (timeout == NULL) {
timeout = "60";
}
if (pid_flags) {
USE_SYSLOG(argv[0]);
daemonize(pid_path);
}
if (server_num == 0 || manager_address == NULL) {
usage();
exit(EXIT_FAILURE);
}
if (fast_open == 1) {
#ifdef TCP_FASTOPEN
LOGI("using tcp fast open");
#else
LOGE("tcp fast open is not supported by this environment");
#endif
}
#ifdef __MINGW32__
winsock_init();
#else
// ignore SIGPIPE
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
signal(SIGABRT, SIG_IGN);
#endif
struct ev_signal sigint_watcher;
struct ev_signal sigterm_watcher;
ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
ev_signal_start(EV_DEFAULT, &sigint_watcher);
ev_signal_start(EV_DEFAULT, &sigterm_watcher);
struct manager_ctx manager;
memset(&manager, 0, sizeof(struct manager_ctx));
manager.fast_open = fast_open;
manager.verbose = verbose;
manager.mode = mode;
manager.password = password;
manager.timeout = timeout;
manager.method = method;
manager.iface = iface;
manager.acl = acl;
manager.user = user;
manager.manager_address = manager_address;
manager.hosts = server_host;
manager.host_num = server_num;
manager.nameservers = nameservers;
manager.nameserver_num = nameserver_num;
manager.mtu = mtu;
#ifdef HAVE_SETRLIMIT
manager.nofile = nofile;
#endif
// initialize ev loop
struct ev_loop *loop = EV_DEFAULT;
// setuid
if (user != NULL && ! run_as(user)) {
FATAL("failed to switch user");
}
#ifndef __MINGW32__
if (geteuid() == 0){
LOGI("running from root user");
}
#endif
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
working_dir_size = strlen(homedir) + 15;
working_dir = ss_malloc(working_dir_size);
snprintf(working_dir, working_dir_size, "%s/.shadowsocks", homedir);
int err = mkdir(working_dir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (err != 0 && errno != EEXIST) {
ERROR("mkdir");
ss_free(working_dir);
FATAL("unable to create working directory");
}
// Clean up all existed processes
DIR *dp;
struct dirent *ep;
dp = opendir(working_dir);
if (dp != NULL) {
while ((ep = readdir(dp)) != NULL) {
size_t len = strlen(ep->d_name);
if (strcmp(ep->d_name + len - 3, "pid") == 0) {
kill_server(working_dir, ep->d_name);
if (verbose)
LOGI("kill %s", ep->d_name);
}
}
closedir(dp);
} else {
ss_free(working_dir);
FATAL("Couldn't open the directory");
}
server_table = cork_string_hash_table_new(MAX_PORT_NUM, 0);
if (conf != NULL) {
for (i = 0; i < conf->server_new_1.server_num; i++) {
struct server *server = ss_malloc(sizeof(struct server));
memset(server, 0, sizeof(struct server));
//strncpy(server->port, conf->server_new_1.servers[i].server_port, 8);
snprintf(server->port, 8, "%d", conf->server_new_1.servers[i].server_port);
strncpy(server->password, conf->server_new_1.servers[i].password, 128);
add_server(&manager, server);
}
}
int sfd;
ss_addr_t ip_addr = { .host = NULL, .port = NULL };
parse_addr(manager_address, &ip_addr);
if (ip_addr.host == NULL || ip_addr.port == NULL) {
struct sockaddr_un svaddr;
sfd = socket(AF_UNIX, SOCK_DGRAM, 0); /* Create server socket */
if (sfd == -1) {
ss_free(working_dir);
FATAL("socket");
}
setnonblocking(sfd);
if (remove(manager_address) == -1 && errno != ENOENT) {
ERROR("bind");
ss_free(working_dir);
exit(EXIT_FAILURE);
}
memset(&svaddr, 0, sizeof(struct sockaddr_un));
svaddr.sun_family = AF_UNIX;
strncpy(svaddr.sun_path, manager_address, sizeof(svaddr.sun_path) - 1);
if (bind(sfd, (struct sockaddr *)&svaddr, sizeof(struct sockaddr_un)) == -1) {
ERROR("bind");
ss_free(working_dir);
exit(EXIT_FAILURE);
}
} else {
sfd = create_server_socket(ip_addr.host, ip_addr.port);
if (sfd == -1) {
ss_free(working_dir);
FATAL("socket");
}
}
manager.fd = sfd;
ev_io_init(&manager.io, manager_recv_cb, manager.fd, EV_READ);
ev_io_start(loop, &manager.io);
// start ev loop
ev_run(loop, 0);
if (verbose) {
LOGI("closed gracefully");
}
// Clean up
struct cork_hash_table_entry *entry;
struct cork_hash_table_iterator server_iter;
cork_hash_table_iterator_init(server_table, &server_iter);
while ((entry = cork_hash_table_iterator_next(&server_iter)) != NULL) {
struct server *server = (struct server *)entry->value;
stop_server(working_dir, server->port);
}
#ifdef __MINGW32__
winsock_cleanup();
#endif
ev_signal_stop(EV_DEFAULT, &sigint_watcher);
ev_signal_stop(EV_DEFAULT, &sigterm_watcher);
ss_free(working_dir);
return 0;
}
|
281677160/openwrt-package | 72,180 | luci-app-ssr-plus/shadowsocksr-libev/src/src/local.c | /*
* local.c - Setup a socks5 proxy through remote shadowsocks server
*
* Copyright (C) 2013 - 2015, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <locale.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <getopt.h>
#ifndef __MINGW32__
#include <errno.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#endif
#ifdef LIB_ONLY
#include <pthread.h>
#include "shadowsocks.h"
#endif
#if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H) && defined(__linux__)
#include <net/if.h>
#include <sys/ioctl.h>
#define SET_INTERFACE
#endif
#include <libcork/core.h>
#include <udns.h>
#ifdef __MINGW32__
#include "win32.h"
#endif
#include "netutils.h"
#include "utils.h"
#include "socks5.h"
#include "acl.h"
#include "http.h"
#include "tls.h"
#include "local.h"
#ifndef LIB_ONLY
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#if defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10
#include <launch.h>
#define HAVE_LAUNCHD
#endif
#endif
#endif
#ifndef EAGAIN
#define EAGAIN EWOULDBLOCK
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK EAGAIN
#endif
#ifndef BUF_SIZE
#define BUF_SIZE 2048
#endif
int verbose = 0;
int keep_resolving = 1;
#ifdef ANDROID
int log_tx_rx = 0;
int vpn = 0;
uint64_t tx = 0;
uint64_t rx = 0;
ev_tstamp last = 0;
char *prefix;
#endif
#include "includeobfs.h" // I don't want to modify makefile
#include "jconf.h"
#include "obfs/obfs.h"
static int acl = 0;
static int mode = TCP_ONLY;
static int ipv6first = 0;
static int fast_open = 0;
#ifdef HAVE_SETRLIMIT
#ifndef LIB_ONLY
static int nofile = 0;
#endif
#endif
static void server_recv_cb(EV_P_ ev_io *w, int revents);
static void server_send_cb(EV_P_ ev_io *w, int revents);
static void remote_recv_cb(EV_P_ ev_io *w, int revents);
static void remote_send_cb(EV_P_ ev_io *w, int revents);
static void accept_cb(EV_P_ ev_io *w, int revents);
static void signal_cb(EV_P_ ev_signal *w, int revents);
static int create_and_bind(const char *addr, const char *port);
#ifdef HAVE_LAUNCHD
static int launch_or_create(const char *addr, const char *port);
#endif
static remote_t *create_remote(listen_ctx_t *listener, struct sockaddr *addr);
static void free_remote(remote_t *remote);
static void close_and_free_remote(EV_P_ remote_t *remote);
static void free_server(server_t *server);
static void close_and_free_server(EV_P_ server_t *server);
static remote_t *new_remote(int fd, int timeout);
static server_t *new_server(int fd, listen_ctx_t *profile);
static struct cork_dllist inactive_profiles;
static listen_ctx_t *current_profile;
static struct cork_dllist all_connections;
#ifndef __MINGW32__
int
setnonblocking(int fd)
{
int flags;
if (-1 == (flags = fcntl(fd, F_GETFL, 0))) {
flags = 0;
}
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
#endif
void
ev_io_remote_send(EV_P_ server_t *server, remote_t *remote) {
ev_io_stop(EV_A_ &remote->send_ctx->io);
ev_io_start(EV_A_ &server->recv_ctx->io);
}
void
ev_io_remote_recv(EV_P_ server_t *server, remote_t *remote) {
ev_io_stop(EV_A_ &remote->recv_ctx->io);
ev_io_start(EV_A_ &server->send_ctx->io);
}
void
ev_io_server_send(EV_P_ server_t *server, remote_t *remote) {
ev_io_stop(EV_A_ &server->send_ctx->io);
ev_io_start(EV_A_ &remote->recv_ctx->io);
}
void
ev_io_server_recv(EV_P_ server_t *server, remote_t *remote) {
ev_io_stop(EV_A_ &server->recv_ctx->io);
ev_io_start(EV_A_ &remote->send_ctx->io);
}
int
create_and_bind(const char *addr, const char *port) {
struct addrinfo hints;
struct addrinfo *result, *rp;
int s, listen_sock;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */
s = getaddrinfo(addr, port, &hints, &result);
if (s != 0) {
LOGI("getaddrinfo: %s", gai_strerror(s));
return -1;
}
if (result == NULL) {
LOGE("Could not bind");
return -1;
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
listen_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (listen_sock == -1) {
continue;
}
int opt = 1;
setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(listen_sock, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
int err = set_reuseport(listen_sock);
if (err == 0) {
LOGI("tcp port reuse enabled");
}
s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen);
if (s == 0) {
/* We managed to bind successfully! */
break;
} else {
ERROR("bind");
}
close(listen_sock);
listen_sock = -1;
}
freeaddrinfo(result);
return listen_sock;
}
#ifdef HAVE_LAUNCHD
int
launch_or_create(const char *addr, const char *port)
{
int *fds;
size_t cnt;
int error = launch_activate_socket("Listeners", &fds, &cnt);
if (error == 0) {
if (cnt == 1) {
return fds[0];
} else {
FATAL("please don't specify multi entry");
}
} else if (error == ESRCH || error == ENOENT) {
/* ESRCH: The calling process is not managed by launchd(8).
* ENOENT: The socket name specified does not exist
* in the caller's launchd.plist(5).
*/
if (port == NULL) {
usage();
exit(EXIT_FAILURE);
}
return create_and_bind(addr, port);
} else {
FATAL("launch_activate_socket() error");
}
return -1;
}
#endif
static void
free_connections(struct ev_loop *loop) {
struct cork_dllist_item *curr, *next;
cork_dllist_foreach_void(&all_connections, curr, next) {
server_t *server = cork_container_of(curr, server_t, entries_all);
remote_t *remote = server->remote;
close_and_free_remote(loop, remote);
close_and_free_server(loop, server);
}
}
static void
server_recv_cb(EV_P_ ev_io *w, int revents) {
server_ctx_t *server_recv_ctx = (server_ctx_t *) w;
server_t *server = server_recv_ctx->server;
remote_t *remote = server->remote;
buffer_t *buf;
ssize_t r;
if (remote == NULL) {
buf = server->buf;
} else {
buf = remote->buf;
}
r = recv(server->fd, buf->array + buf->len, BUF_SIZE - buf->len, 0);
if (r == 0) {
// connection closed
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else if (r == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data
// continue to wait for recv
return;
} else {
if (verbose)
ERROR("server_recv_cb_recv");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
buf->len += r;
if (server->stage == STAGE_INIT) {
char *host = server->listener->tunnel_addr.host;
char *port = server->listener->tunnel_addr.port;
if (host && port) {
server->stage = STAGE_PARSE;
int addr_len = strlen(host);
int header_len = addr_len + 3 + 4;
int port_num = atoi(port);
memmove(buf->array + header_len, buf->array, buf->len);
buf->len += header_len;
buf->array[0] = 5;
buf->array[1] = 1;
buf->array[2] = 0;
buf->array[3] = 3;
buf->array[4] = addr_len;
memcpy(buf->array + 5, host, addr_len);
buf->array[addr_len + 5] = port_num >> 8;
buf->array[addr_len + 6] = port_num;
}
}
while (1) {
// local socks5 server
if (server->stage == STAGE_STREAM) {
if (remote == NULL) {
LOGE("invalid remote");
close_and_free_server(EV_A_ server);
return;
}
// insert shadowsocks header
if (!remote->direct) {
server_def_t *server_env = server->server_env;
// SSR beg
if (server_env->protocol_plugin) {
obfs_class *protocol_plugin = server_env->protocol_plugin;
if (protocol_plugin->client_pre_encrypt) {
remote->buf->len = (size_t) protocol_plugin->client_pre_encrypt(
server->protocol,
&remote->buf->array,
(int) remote->buf->len,
&remote->buf->capacity
);
}
}
int err = ss_encrypt(&server_env->cipher, remote->buf, server->e_ctx, BUF_SIZE);
if (err) {
LOGE("server invalid password or cipher");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (server_env->obfs_plugin) {
obfs_class *obfs_plugin = server_env->obfs_plugin;
if (obfs_plugin->client_encode) {
remote->buf->len = (size_t) obfs_plugin->client_encode(
server->obfs,
&remote->buf->array,
(int) remote->buf->len,
&remote->buf->capacity
);
}
}
// SSR end
#ifdef ANDROID
if (log_tx_rx)
tx += buf->len;
#endif
}
if (!remote->send_ctx->connected) {
#ifdef ANDROID
if (vpn) {
int not_protect = 0;
if (remote->direct_addr.addr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&remote->direct_addr.addr;
if (s->sin_addr.s_addr == inet_addr("127.0.0.1"))
not_protect = 1;
}
if (!not_protect) {
if (protect_socket(remote->fd) == -1) {
ERROR("protect_socket");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
}
#endif
remote->buf->idx = 0;
if (!fast_open || remote->direct) {
// connecting, wait until connected
int r = connect(
remote->fd,
(struct sockaddr *) &(remote->direct_addr.addr),
remote->direct_addr.addr_len
);
if (r == -1 && errno != CONNECT_IN_PROGRESS) {
ERROR("connect");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
// wait on remote connected event
ev_io_server_recv(EV_A_ server, remote);
ev_timer_start(EV_A_ &remote->send_ctx->watcher);
} else {
#ifdef TCP_FASTOPEN
#ifdef __APPLE__
((struct sockaddr_in *)&(remote->direct_addr.addr))->sin_len = sizeof(struct sockaddr_in);
sa_endpoints_t endpoints;
memset((char *)&endpoints, 0, sizeof(endpoints));
endpoints.sae_dstaddr = (struct sockaddr *)&(remote->direct_addr.addr);
endpoints.sae_dstaddrlen = remote->direct_addr.addr_len;
int s = connectx(remote->fd, &endpoints, SAE_ASSOCID_ANY,
CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
NULL, 0, NULL, NULL);
if (s == 0) {
s = send(remote->fd, remote->buf->array, remote->buf->len, 0);
}
#else
int s = sendto(remote->fd, remote->buf->array, remote->buf->len, MSG_FASTOPEN,
(struct sockaddr *)&(remote->direct_addr.addr), remote->direct_addr.addr_len);
#endif
if (s == -1) {
if (errno == CONNECT_IN_PROGRESS) {
// in progress, wait until connected
remote->buf->idx = 0;
ev_io_server_recv(EV_A_ server, remote);
return;
} else {
ERROR("sendto");
if (errno == ENOTCONN) {
LOGE("fast open is not supported on this platform");
// just turn it off
fast_open = 0;
}
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
} else if (s < (int)(remote->buf->len)) {
remote->buf->len -= s;
remote->buf->idx = s;
ev_io_server_recv(EV_A_ server, remote);
ev_timer_start(EV_A_ & remote->send_ctx->watcher);
return;
} else {
// Just connected
remote->buf->idx = 0;
remote->buf->len = 0;
#ifdef __APPLE__
ev_io_server_recv(EV_A_ server, remote);
ev_timer_start(EV_A_ & remote->send_ctx->watcher);
#else
remote->send_ctx->connected = 1;
ev_timer_stop(EV_A_ & remote->send_ctx->watcher);
ev_timer_start(EV_A_ & remote->recv_ctx->watcher);
ev_io_start(EV_A_ & remote->recv_ctx->io);
return;
#endif
}
#else
// if TCP_FASTOPEN is not defined, fast_open will always be 0
LOGE("can't come here");
exit(1);
#endif
}
} else {
if (r > 0 && remote->buf->len == 0) {
remote->buf->idx = 0;
ev_io_stop(EV_A_ &server_recv_ctx->io);
return;
}
int s = send(remote->fd, remote->buf->array, remote->buf->len, 0);
if (s == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data, wait for send
remote->buf->idx = 0;
ev_io_server_recv(EV_A_ server, remote);
return;
} else {
ERROR("server_recv_cb_send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
} else if (s < (int) (remote->buf->len)) {
remote->buf->len -= s;
remote->buf->idx = s;
ev_io_server_recv(EV_A_ server, remote);
return;
} else {
remote->buf->idx = 0;
remote->buf->len = 0;
}
}
// all processed
return;
} else if (server->stage == STAGE_INIT) {
struct method_select_response response;
response.ver = SVERSION;
response.method = 0;
char *send_buf = (char *) &response;
send(server->fd, send_buf, sizeof(response), 0);
server->stage = STAGE_HANDSHAKE;
int off = (buf->array[1] & 0xff) + 2;
if (buf->array[0] == 0x05 && off < (int) (buf->len)) {
memmove(buf->array, buf->array + off, buf->len - off);
buf->len -= off;
continue;
}
buf->len = 0;
return;
} else if (server->stage == STAGE_HANDSHAKE || server->stage == STAGE_PARSE) {
struct socks5_request *request = (struct socks5_request *) buf->array;
struct sockaddr_in sock_addr;
memset(&sock_addr, 0, sizeof(sock_addr));
int udp_assc = 0;
if (request->cmd == 3) {
udp_assc = 1;
socklen_t addr_len = sizeof(sock_addr);
getsockname(server->fd, (struct sockaddr *) &sock_addr,
&addr_len);
if (verbose) {
LOGI("udp assc request accepted");
}
} else if (request->cmd != 1) {
LOGE("unsupported cmd: %d", request->cmd);
struct socks5_response response;
response.ver = SVERSION;
response.rep = CMD_NOT_SUPPORTED;
response.rsv = 0;
response.atyp = 1;
char *send_buf = (char *) &response;
send(server->fd, send_buf, 4, 0);
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
// Fake reply
if (server->stage == STAGE_HANDSHAKE) {
struct socks5_response response;
response.ver = SVERSION;
response.rep = 0;
response.rsv = 0;
response.atyp = 1;
buffer_t resp_to_send;
buffer_t *resp_buf = &resp_to_send;
balloc(resp_buf, BUF_SIZE);
memcpy(resp_buf->array, &response, sizeof(struct socks5_response));
memcpy(resp_buf->array + sizeof(struct socks5_response),
&sock_addr.sin_addr, sizeof(sock_addr.sin_addr));
memcpy(resp_buf->array + sizeof(struct socks5_response) +
sizeof(sock_addr.sin_addr),
&sock_addr.sin_port, sizeof(sock_addr.sin_port));
int reply_size = sizeof(struct socks5_response) +
sizeof(sock_addr.sin_addr) + sizeof(sock_addr.sin_port);
int s = send(server->fd, resp_buf->array, reply_size, 0);
bfree(resp_buf);
if (s < reply_size) {
LOGE("failed to send fake reply");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (udp_assc) {
// Wait until client closes the connection
return;
}
}
char host[257], ip[INET6_ADDRSTRLEN], port[16];
buffer_t ss_addr_to_send;
buffer_t *abuf = &ss_addr_to_send;
balloc(abuf, BUF_SIZE);
abuf->array[abuf->len++] = request->atyp;
int atyp = request->atyp;
// get remote addr and port
if (atyp == 1) {
// IP V4
size_t in_addr_len = sizeof(struct in_addr);
memcpy(abuf->array + abuf->len, buf->array + 4, in_addr_len + 2);
abuf->len += in_addr_len + 2;
if (acl || verbose) {
uint16_t p = ntohs(*(uint16_t *) (buf->array + 4 + in_addr_len));
dns_ntop(AF_INET,
(const void *) (buf->array + 4),
ip,
INET_ADDRSTRLEN
);
sprintf(port, "%d", p);
}
} else if (atyp == 3) {
// Domain name
uint8_t name_len = *(uint8_t *) (buf->array + 4);
abuf->array[abuf->len++] = name_len;
memcpy(abuf->array + abuf->len, buf->array + 4 + 1, name_len + 2);
abuf->len += name_len + 2;
if (acl || verbose) {
uint16_t p = ntohs(*(uint16_t *) (buf->array + 4 + 1 + name_len));
memcpy(host, buf->array + 4 + 1, name_len);
host[name_len] = '\0';
sprintf(port, "%d", p);
}
} else if (atyp == 4) {
// IP V6
size_t in6_addr_len = sizeof(struct in6_addr);
memcpy(abuf->array + abuf->len, buf->array + 4, in6_addr_len + 2);
abuf->len += in6_addr_len + 2;
if (acl || verbose) {
uint16_t p = ntohs(*(uint16_t *) (buf->array + 4 + in6_addr_len));
dns_ntop(AF_INET6,
(const void *) (buf->array + 4),
ip,
INET6_ADDRSTRLEN
);
sprintf(port, "%d", p);
}
} else {
bfree(abuf);
LOGE("unsupported addrtype: %d", request->atyp);
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
size_t abuf_len = abuf->len;
int sni_detected = 0;
if (atyp == 1 || atyp == 4) {
char *hostname;
uint16_t p = ntohs(*(uint16_t *) (abuf->array + abuf->len - 2));
int ret = 0;
if (p == http_protocol->default_port)
ret = http_protocol->parse_packet(buf->array + 3 + abuf->len,
buf->len - 3 - abuf->len, &hostname);
else if (p == tls_protocol->default_port)
ret = tls_protocol->parse_packet(buf->array + 3 + abuf->len,
buf->len - 3 - abuf->len, &hostname);
if (ret == -1 && buf->len < BUF_SIZE) {
server->stage = STAGE_PARSE;
bfree(abuf);
return;
} else if (ret > 0) {
sni_detected = 1;
// Reconstruct address buffer
abuf->len = 0;
abuf->array[abuf->len++] = 3;
abuf->array[abuf->len++] = ret;
memcpy(abuf->array + abuf->len, hostname, ret);
abuf->len += ret;
p = htons(p);
memcpy(abuf->array + abuf->len, &p, 2);
abuf->len += 2;
if (acl || verbose) {
memcpy(host, hostname, ret);
host[ret] = '\0';
}
ss_free(hostname);
} else {
strncpy(host, ip, sizeof(ip));
}
}
server->stage = STAGE_STREAM;
buf->len -= (3 + abuf_len);
if (buf->len > 0) {
memmove(buf->array, buf->array + 3 + abuf_len, buf->len);
}
if (acl) {
if (outbound_block_match_host(host) == 1) {
if (verbose)
LOGI("outbound blocked %s", host);
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
int host_match = acl_match_host(host);
int bypass = 0;
int resolved = 0;
struct sockaddr_storage storage;
memset(&storage, 0, sizeof(struct sockaddr_storage));
int err;
if (verbose)
LOGI("acl_match_host %s result %d", host, host_match);
if (host_match > 0)
bypass = 0; // bypass hostnames in black list
else if (host_match < 0)
bypass = 1; // proxy hostnames in white list
else {
#ifndef ANDROID
if (atyp == 3) { // resolve domain so we can bypass domain with geoip
err = get_sockaddr(host, port, &storage, 0, ipv6first);
if (err != -1) {
resolved = 1;
switch (((struct sockaddr *) &storage)->sa_family) {
case AF_INET: {
struct sockaddr_in *addr_in = (struct sockaddr_in *) &storage;
dns_ntop(AF_INET, &(addr_in->sin_addr), ip, INET_ADDRSTRLEN);
break;
}
case AF_INET6: {
struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *) &storage;
dns_ntop(AF_INET6, &(addr_in6->sin6_addr), ip, INET6_ADDRSTRLEN);
break;
}
default:
break;
}
}
}
#endif
if (outbound_block_match_host(ip) == 1) {
if (verbose)
LOGI("outbound blocked %s", ip);
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
int ip_match = acl_match_host(ip);// -1 if IP in white list or 1 if IP in black list
if (verbose)
LOGI("acl_match_host ip %s result %d mode %d", ip, ip_match, get_acl_mode());
if (ip_match < 0)
bypass = 1;
else if (ip_match > 0)
bypass = 0;
else
bypass = (get_acl_mode() == BLACK_LIST);
}
if (bypass) {
if (verbose) {
if (sni_detected || atyp == 3)
LOGI("bypass %s:%s", host, port);
else if (atyp == 1)
LOGI("bypass %s:%s", ip, port);
else if (atyp == 4)
LOGI("bypass [%s]:%s", ip, port);
}
struct sockaddr_storage storage;
memset(&storage, 0, sizeof(struct sockaddr_storage));
int err;
#ifndef ANDROID
if (atyp == 3 && resolved != 1)
err = get_sockaddr(host, port, &storage, 0, ipv6first);
else
#endif
err = get_sockaddr(ip, port, &storage, 0, ipv6first);
if (err != -1) {
remote = create_remote(server->listener, (struct sockaddr *) &storage);
if (remote != NULL) remote->direct = 1;
}
}
}
// Not match ACL
if (remote == NULL) {
// pick a server
listen_ctx_t *profile = server->listener;
int index = rand() % profile->server_num;
server_def_t *server_env = &profile->servers[index];
if (verbose) {
if (sni_detected || atyp == 3)
LOGI("connect to %s:%s via %s:%d", host, port, server_env->host, server_env->port);
else if (atyp == 1)
LOGI("connect to %s:%s via %s:%d", ip, port, server_env->host, server_env->port);
else if (atyp == 4)
LOGI("connect to [%s]:%s via %s:%d", ip, port, server_env->host, server_env->port);
}
server->server_env = server_env;
remote = create_remote(profile, (struct sockaddr *) server_env->addr);
}
if (remote == NULL) {
bfree(abuf);
LOGE("invalid remote addr");
close_and_free_server(EV_A_ server);
return;
}
if (!remote->direct) {
server_def_t *server_env = server->server_env;
// expelled from eden
{ cork_dllist_remove(&server->entries); };
{ cork_dllist_add(&server_env->connections, &server->entries); };
// init server cipher
if (server_env->cipher.enc_method > TABLE) {
server->e_ctx = ss_malloc(sizeof(struct enc_ctx));
server->d_ctx = ss_malloc(sizeof(struct enc_ctx));
enc_ctx_init(&server_env->cipher, server->e_ctx, 1);
enc_ctx_init(&server_env->cipher, server->d_ctx, 0);
} else {
server->e_ctx = NULL;
server->d_ctx = NULL;
}
// SSR beg
server_info _server_info;
memset(&_server_info, 0, sizeof(server_info));
if (server_env->hostname)
strcpy(_server_info.host, server_env->hostname);
else
strcpy(_server_info.host, server_env->host);
if (verbose) {
LOGI("server_info host %s", _server_info.host);
}
_server_info.port = server_env->port;
_server_info.head_len = get_head_size(ss_addr_to_send.array, 320, 30);
_server_info.iv = server->e_ctx->evp.iv;
_server_info.iv_len = enc_get_iv_len(&server_env->cipher);
_server_info.key = enc_get_key(&server_env->cipher);
_server_info.key_len = enc_get_key_len(&server_env->cipher);
_server_info.tcp_mss = 1452;
_server_info.buffer_size = BUF_SIZE;
_server_info.cipher_env = &server_env->cipher;
_server_info.param = server_env->obfs_param;
_server_info.g_data = server_env->obfs_global;
if (server_env->obfs_plugin) {
server->obfs = server_env->obfs_plugin->new_obfs();
server_env->obfs_plugin->set_server_info(server->obfs, &_server_info);
}
_server_info.param = server_env->protocol_param;
_server_info.g_data = server_env->protocol_global;
if (server_env->protocol_plugin) {
server->protocol = server_env->protocol_plugin->new_obfs();
// overhead must count on this
_server_info.overhead = (uint16_t)
(
(server_env->protocol_plugin ?
server_env->protocol_plugin->get_overhead(server->protocol) : 0)
+
(server_env->obfs_plugin ?
server_env->obfs_plugin->get_overhead(server->obfs) : 0)
);
server_env->protocol_plugin->set_server_info(server->protocol, &_server_info);
}
// SSR end
brealloc(remote->buf, buf->len + abuf->len, BUF_SIZE);
memcpy(remote->buf->array, abuf->array, abuf->len);
remote->buf->len = buf->len + abuf->len;
if (buf->len > 0) {
memcpy(remote->buf->array + abuf->len, buf->array, buf->len);
}
} else {
if (buf->len > 0) {
memcpy(remote->buf->array, buf->array, buf->len);
remote->buf->len = buf->len;
}
}
server->remote = remote;
remote->server = server;
bfree(abuf);
}
}
}
static void
server_send_cb(EV_P_ ev_io *w, int revents) {
server_ctx_t *server_send_ctx = (server_ctx_t *) w;
server_t *server = server_send_ctx->server;
remote_t *remote = server->remote;
if (server->buf->len == 0) {
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else {
// has data to send
ssize_t s = send(server->fd, server->buf->array + server->buf->idx,
server->buf->len, 0);
if (s == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
ERROR("server_send_cb_send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
} else if (s < (ssize_t) (server->buf->len)) {
// partly sent, move memory, wait for the next time to send
server->buf->len -= s;
server->buf->idx += s;
return;
} else {
// all sent out, wait for reading
server->buf->len = 0;
server->buf->idx = 0;
ev_io_server_send(EV_A_ server, remote);
return;
}
}
}
#ifdef ANDROID
static void
stat_update_cb()
{
if (log_tx_rx) {
ev_tstamp now = ev_time();
if (now - last > 1.0) {
send_traffic_stat(tx, rx);
last = now;
}
}
}
#endif
static void
remote_timeout_cb(EV_P_ ev_timer *watcher, int revents) {
remote_ctx_t *remote_ctx
= cork_container_of(watcher, remote_ctx_t, watcher);
remote_t *remote = remote_ctx->remote;
server_t *server = remote->server;
if (verbose) {
LOGI("TCP connection timeout");
}
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
static void
remote_recv_cb(EV_P_ ev_io *w, int revents) {
remote_ctx_t *remote_recv_ctx = (remote_ctx_t *) w;
remote_t *remote = remote_recv_ctx->remote;
server_t *server = remote->server;
server_def_t *server_env = server->server_env;
ev_timer_again(EV_A_ &remote->recv_ctx->watcher);
#ifdef ANDROID
stat_update_cb();
#endif
ssize_t r = recv(remote->fd, server->buf->array, BUF_SIZE, 0);
if (r == 0) {
// connection closed
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else if (r == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data
// continue to wait for recv
return;
} else {
ERROR("remote_recv_cb_recv");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
server->buf->len = r;
if (!remote->direct) {
#ifdef ANDROID
if (log_tx_rx)
rx += server->buf->len;
#endif
if (r == 0)
return;
// SSR beg
if (server_env->obfs_plugin) {
obfs_class *obfs_plugin = server_env->obfs_plugin;
if (obfs_plugin->client_decode) {
int needsendback;
server->buf->len =
(size_t) obfs_plugin->client_decode(
server->obfs,
&server->buf->array,
server->buf->len,
&server->buf->capacity,
&needsendback
);
if ((int) server->buf->len < 0) {
LOGE("client_decode");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (needsendback) {
if (obfs_plugin->client_encode) {
remote->buf->len =
(size_t) obfs_plugin->client_encode(
server->obfs,
&remote->buf->array,
0,
&remote->buf->capacity
);
ssize_t s = send(remote->fd, remote->buf->array, remote->buf->len, 0);
if (s == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
ERROR("remote_recv_cb_send");
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
} else if (s < (ssize_t) (remote->buf->len)) {
// partly sent, move memory, wait for the next time to send
remote->buf->len -= s;
remote->buf->idx += s;
return;
} else {
// all sent out, wait for reading
remote->buf->len = 0;
remote->buf->idx = 0;
ev_io_remote_send(EV_A_ server, remote);
}
}
}
}
}
if (server->buf->len > 0) {
int err = ss_decrypt(&server_env->cipher, server->buf, server->d_ctx, BUF_SIZE);
if (err) {
LOGE("remote invalid password or cipher");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
if (server_env->protocol_plugin) {
obfs_class *protocol_plugin = server_env->protocol_plugin;
if (protocol_plugin->client_post_decrypt) {
server->buf->len =
(size_t) protocol_plugin->client_post_decrypt(
server->protocol,
&server->buf->array,
server->buf->len,
&server->buf->capacity
);
if ((int) server->buf->len < 0) {
LOGE("client_post_decrypt");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (server->buf->len == 0)
return;
}
}
// SSR end
}
int s = send(server->fd, server->buf->array, server->buf->len, 0);
if (s == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data, wait for send
server->buf->idx = 0;
ev_io_remote_recv(EV_A_ server, remote);
} else {
ERROR("remote_recv_cb_send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
} else if (s < (int) (server->buf->len)) {
server->buf->len -= s;
server->buf->idx = s;
ev_io_remote_recv(EV_A_ server, remote);
}
}
static void
remote_send_cb(EV_P_ ev_io *w, int revents) {
remote_ctx_t *remote_send_ctx = (remote_ctx_t *) w;
remote_t *remote = remote_send_ctx->remote;
server_t *server = remote->server;
if (!remote_send_ctx->connected) {
int err_no = 0;
socklen_t len = sizeof err_no;
#ifdef __MINGW32__
int r = getsockopt(remote->fd, SOL_SOCKET, SO_ERROR, (char *) &err_no, &len);
#else
int r = getsockopt(remote->fd, SOL_SOCKET, SO_ERROR, &err_no, &len);
#endif
if (r == 0 && err_no == 0) {
remote_send_ctx->connected = 1;
ev_timer_stop(EV_A_ &remote_send_ctx->watcher);
ev_timer_start(EV_A_ &remote->recv_ctx->watcher);
ev_io_start(EV_A_ &remote->recv_ctx->io);
// no need to send any data
if (remote->buf->len == 0) {
ev_io_remote_send(EV_A_ server, remote);
return;
}
} else {
// not connected
LOGE("getsockopt error code %d %d", r, err_no);
ERROR("getsockopt");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
if (remote->buf->len == 0) {
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else {
// has data to send
ssize_t s = send(remote->fd, remote->buf->array + remote->buf->idx,
remote->buf->len, 0);
if (s == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
ERROR("remote_send_cb_send");
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
} else if (s < (ssize_t) (remote->buf->len)) {
// partly sent, move memory, wait for the next time to send
remote->buf->len -= s;
remote->buf->idx += s;
return;
} else {
// all sent out, wait for reading
remote->buf->len = 0;
remote->buf->idx = 0;
ev_io_remote_send(EV_A_ server, remote);
}
}
}
static remote_t *
new_remote(int fd, int timeout) {
remote_t *remote;
remote = ss_malloc(sizeof(remote_t));
memset(remote, 0, sizeof(remote_t));
remote->buf = ss_malloc(sizeof(buffer_t));
remote->recv_ctx = ss_malloc(sizeof(remote_ctx_t));
remote->send_ctx = ss_malloc(sizeof(remote_ctx_t));
balloc(remote->buf, BUF_SIZE);
memset(remote->recv_ctx, 0, sizeof(remote_ctx_t));
memset(remote->send_ctx, 0, sizeof(remote_ctx_t));
remote->recv_ctx->connected = 0;
remote->send_ctx->connected = 0;
remote->fd = fd;
remote->recv_ctx->remote = remote;
remote->send_ctx->remote = remote;
ev_io_init(&remote->recv_ctx->io, remote_recv_cb, fd, EV_READ);
ev_io_init(&remote->send_ctx->io, remote_send_cb, fd, EV_WRITE);
ev_timer_init(&remote->send_ctx->watcher, remote_timeout_cb,
min(MAX_CONNECT_TIMEOUT, timeout), 0);
ev_timer_init(&remote->recv_ctx->watcher, remote_timeout_cb,
timeout, timeout);
return remote;
}
static void
free_remote(remote_t *remote) {
if (remote->server != NULL) {
remote->server->remote = NULL;
}
if (remote->buf != NULL) {
bfree(remote->buf);
ss_free(remote->buf);
}
ss_free(remote->recv_ctx);
ss_free(remote->send_ctx);
ss_free(remote);
}
static void
close_and_free_remote(EV_P_ remote_t *remote) {
if (remote != NULL) {
ev_timer_stop(EV_A_ &remote->send_ctx->watcher);
ev_timer_stop(EV_A_ &remote->recv_ctx->watcher);
ev_io_stop(EV_A_ &remote->send_ctx->io);
ev_io_stop(EV_A_ &remote->recv_ctx->io);
close(remote->fd);
free_remote(remote);
}
}
static server_t *
new_server(int fd, listen_ctx_t *profile) {
server_t *server;
server = ss_malloc(sizeof(server_t));
memset(server, 0, sizeof(server_t));
server->listener = profile;
server->recv_ctx = ss_malloc(sizeof(server_ctx_t));
server->send_ctx = ss_malloc(sizeof(server_ctx_t));
server->buf = ss_malloc(sizeof(buffer_t));
balloc(server->buf, BUF_SIZE);
memset(server->recv_ctx, 0, sizeof(server_ctx_t));
memset(server->send_ctx, 0, sizeof(server_ctx_t));
server->stage = STAGE_INIT;
server->recv_ctx->connected = 0;
server->send_ctx->connected = 0;
server->fd = fd;
server->recv_ctx->server = server;
server->send_ctx->server = server;
ev_io_init(&server->recv_ctx->io, server_recv_cb, fd, EV_READ);
ev_io_init(&server->send_ctx->io, server_send_cb, fd, EV_WRITE);
cork_dllist_add(&profile->connections_eden, &server->entries);
cork_dllist_add(&all_connections, &server->entries_all);
return server;
}
static void
release_profile(listen_ctx_t *profile) {
int i;
ss_free(profile->iface);
for (i = 0; i < profile->server_num; i++) {
server_def_t *server_env = &profile->servers[i];
ss_free(server_env->host);
if (server_env->addr != server_env->addr_udp) {
ss_free(server_env->addr_udp);
}
ss_free(server_env->addr);
ss_free(server_env->psw);
ss_free(server_env->protocol_name);
ss_free(server_env->obfs_name);
ss_free(server_env->protocol_param);
ss_free(server_env->obfs_param);
ss_free(server_env->protocol_global);
ss_free(server_env->obfs_global);
if (server_env->protocol_plugin) {
free_obfs_class(server_env->protocol_plugin);
}
if (server_env->obfs_plugin) {
free_obfs_class(server_env->obfs_plugin);
}
ss_free(server_env->id);
ss_free(server_env->group);
enc_release(&server_env->cipher);
}
ss_free(profile);
}
static void
check_and_free_profile(listen_ctx_t *profile) {
int i;
if (profile == current_profile) {
return;
}
// if this connection is created from an inactive profile, then we need to free the profile
// when the last connection of that profile is colsed
if (!cork_dllist_is_empty(&profile->connections_eden)) {
return;
}
for (i = 0; i < profile->server_num; i++) {
if (!cork_dllist_is_empty(&profile->servers[i].connections)) {
return;
}
}
// No connections anymore
cork_dllist_remove(&profile->entries);
release_profile(profile);
}
static void
free_server(server_t *server) {
listen_ctx_t *profile = server->listener;
server_def_t *server_env = server->server_env;
cork_dllist_remove(&server->entries);
cork_dllist_remove(&server->entries_all);
if (server->remote != NULL) {
server->remote->server = NULL;
}
if (server->buf != NULL) {
bfree(server->buf);
ss_free(server->buf);
}
if (server_env) {
if (server->e_ctx != NULL) {
enc_ctx_release(&server_env->cipher, server->e_ctx);
ss_free(server->e_ctx);
}
if (server->d_ctx != NULL) {
enc_ctx_release(&server_env->cipher, server->d_ctx);
ss_free(server->d_ctx);
}
// SSR beg
if (server_env->obfs_plugin) {
server_env->obfs_plugin->dispose(server->obfs);
server->obfs = NULL;
}
if (server_env->protocol_plugin) {
server_env->protocol_plugin->dispose(server->protocol);
server->protocol = NULL;
}
// SSR end
}
ss_free(server->recv_ctx);
ss_free(server->send_ctx);
ss_free(server);
// after free server, we need to check the profile
check_and_free_profile(profile);
}
static void
close_and_free_server(EV_P_ server_t *server) {
if (server != NULL) {
ev_io_stop(EV_A_ &server->send_ctx->io);
ev_io_stop(EV_A_ &server->recv_ctx->io);
close(server->fd);
free_server(server);
}
}
static remote_t *
create_remote(listen_ctx_t *profile, struct sockaddr *addr) {
int remotefd = socket(addr->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (remotefd == -1) {
ERROR("socket");
return NULL;
}
int opt = 1;
setsockopt(remotefd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(remotefd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
if (profile->mptcp == 1) {
int err = setsockopt(remotefd, SOL_TCP, MPTCP_ENABLED, &opt, sizeof(opt));
if (err == -1) {
ERROR("failed to enable multipath TCP");
}
}
// Setup
setnonblocking(remotefd);
#ifdef SET_INTERFACE
if (profile->iface) {
if (setinterface(remotefd, profile->iface) == -1)
ERROR("setinterface");
}
#endif
remote_t *remote = new_remote(remotefd, profile->timeout);
remote->direct_addr.addr_len = get_sockaddr_len(addr);
memcpy(&(remote->direct_addr.addr), addr, remote->direct_addr.addr_len);
// remote->direct_addr.remote_index = index;
return remote;
}
static void
signal_cb(EV_P_ ev_signal *w, int revents) {
if (revents & EV_SIGNAL) {
switch (w->signum) {
case SIGINT:
case SIGTERM:
#ifndef __MINGW32__
case SIGUSR1:
#endif
ev_unloop(EV_A_ EVUNLOOP_ALL);
}
}
}
void
accept_cb(EV_P_ ev_io *w, int revents) {
listen_ctx_t *listener = (listen_ctx_t *) w;
int serverfd = accept(listener->fd, NULL, NULL);
if (serverfd == -1) {
ERROR("accept");
return;
}
setnonblocking(serverfd);
int opt = 1;
setsockopt(serverfd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(serverfd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
server_t *server = new_server(serverfd, listener);
ev_io_start(EV_A_ &server->recv_ctx->io);
}
void
resolve_int_cb(int dummy) {
keep_resolving = 0;
}
static void
init_obfs(server_def_t *serv, char *protocol, char *protocol_param, char *obfs, char *obfs_param) {
serv->protocol_name = protocol;
serv->protocol_param = protocol_param;
serv->protocol_plugin = new_obfs_class(protocol);
serv->obfs_name = obfs;
serv->obfs_param = obfs_param;
serv->obfs_plugin = new_obfs_class(obfs);
if (serv->obfs_plugin) {
serv->obfs_global = serv->obfs_plugin->init_data();
}
if (serv->protocol_plugin) {
serv->protocol_global = serv->protocol_plugin->init_data();
}
}
#ifndef LIB_ONLY
int
main(int argc, char **argv)
{
int i, c;
int pid_flags = 0;
int mtu = 0;
int mptcp = 0;
char *user = NULL;
char *local_port = NULL;
char *local_addr = NULL;
char *password = NULL;
char *timeout = NULL;
char *protocol = NULL; // SSR
char *protocol_param = NULL; // SSR
char *method = NULL;
char *obfs = NULL; // SSR
char *obfs_param = NULL; // SSR
char *pid_path = NULL;
char *conf_path = NULL;
char *iface = NULL;
int remote_num = 0;
char *hostnames[MAX_REMOTE_NUM] = {NULL};
ss_addr_t remote_addr[MAX_REMOTE_NUM];
char *remote_port = NULL;
int use_new_profile = 0;
jconf_t *conf = NULL;
ss_addr_t tunnel_addr = { .host = NULL, .port = NULL };
char *tunnel_addr_str = NULL;
int option_index = 0;
static struct option long_options[] = {
{ "fast-open", no_argument, 0, 0 },
{ "acl", required_argument, 0, 0 },
{ "mtu", required_argument, 0, 0 },
{ "mptcp", no_argument, 0, 0 },
{ "help", no_argument, 0, 0 },
{ "host", required_argument, 0, 0 },
{ 0, 0, 0, 0 }
};
opterr = 0;
USE_TTY();
#ifdef ANDROID
while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:n:P:xhuUvVA6"
"O:o:G:g:",
long_options, &option_index)) != -1)
#else
while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:n:huUvA6"
"O:o:G:g:",
long_options, &option_index)) != -1)
#endif
{
switch (c) {
case 0:
if (option_index == 0) {
fast_open = 1;
} else if (option_index == 1) {
LOGI("initializing acl...");
acl = !init_acl(optarg);
} else if (option_index == 2) {
mtu = atoi(optarg);
LOGI("set MTU to %d", mtu);
} else if (option_index == 3) {
mptcp = 1;
LOGI("enable multipath TCP");
} else if (option_index == 4) {
usage();
exit(EXIT_SUCCESS);
} else if (option_index == 5) {
hostnames[remote_num] = optarg;
}
break;
case 's':
if (remote_num < MAX_REMOTE_NUM) {
remote_addr[remote_num].host = optarg;
remote_addr[remote_num++].port = NULL;
}
break;
case 'p':
remote_port = optarg;
break;
case 'l':
local_port = optarg;
break;
case 'k':
password = optarg;
break;
case 'f':
pid_flags = 1;
pid_path = optarg;
break;
case 't':
timeout = optarg;
break;
// SSR beg
case 'O':
protocol = optarg;
break;
case 'm':
method = optarg;
break;
case 'o':
obfs = optarg;
break;
case 'G':
protocol_param = optarg;
break;
case 'g':
obfs_param = optarg;
break;
// SSR end
case 'c':
conf_path = optarg;
break;
case 'i':
iface = optarg;
break;
case 'b':
local_addr = optarg;
break;
case 'L':
tunnel_addr_str = optarg;
break;
case 'a':
user = optarg;
break;
#ifdef HAVE_SETRLIMIT
case 'n':
nofile = atoi(optarg);
break;
#endif
case 'u':
mode = TCP_AND_UDP;
break;
case 'U':
mode = UDP_ONLY;
break;
case 'v':
verbose = 1;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'A':
LOGI("The 'A' argument is deprecate! Ignored.");
break;
case '6':
ipv6first = 1;
break;
#ifdef ANDROID
case 'V':
vpn = 1;
break;
case 'P':
prefix = optarg;
break;
case 'x':
log_tx_rx = 1;
break;
#endif
case '?':
// The option character is not recognized.
LOGE("Unrecognized option: %s", optarg);
opterr = 1;
break;
}
}
if (opterr) {
usage();
exit(EXIT_FAILURE);
}
if (argc == 1) {
if (conf_path == NULL) {
conf_path = DEFAULT_CONF_PATH;
}
}
if (conf_path != NULL) {
conf = read_jconf(conf_path);
if(conf->conf_ver != CONF_VER_LEGACY){
use_new_profile = 1;
} else {
if (remote_num == 0) {
remote_num = conf->server_legacy.remote_num;
for (i = 0; i < remote_num; i++)
remote_addr[i] = conf->server_legacy.remote_addr[i];
}
if (remote_port == NULL) {
remote_port = conf->server_legacy.remote_port;
}
if (local_addr == NULL) {
local_addr = conf->server_legacy.local_addr;
}
if (local_port == NULL) {
local_port = conf->server_legacy.local_port;
}
if (password == NULL) {
password = conf->server_legacy.password;
}
// SSR beg
if (protocol == NULL) {
protocol = conf->server_legacy.protocol;
LOGI("protocol %s", protocol);
}
if (protocol_param == NULL) {
protocol_param = conf->server_legacy.protocol_param;
LOGI("protocol_param %s", protocol_param);
}
if (method == NULL) {
method = conf->server_legacy.method;
LOGI("method %s", method);
}
if (obfs == NULL) {
obfs = conf->server_legacy.obfs;
LOGI("obfs %s", obfs);
}
if (obfs_param == NULL) {
obfs_param = conf->server_legacy.obfs_param;
LOGI("obfs_param %s", obfs_param);
}
// SSR end
}
if (timeout == NULL) {
timeout = conf->timeout;
}
if (user == NULL) {
user = conf->user;
}
if (tunnel_addr_str == NULL) {
tunnel_addr_str = conf->tunnel_address;
}
if (fast_open == 0) {
fast_open = conf->fast_open;
}
if (mode == TCP_ONLY) {
mode = conf->mode;
}
if (mtu == 0) {
mtu = conf->mtu;
}
if (mptcp == 0) {
mptcp = conf->mptcp;
}
#ifdef HAVE_SETRLIMIT
if (nofile == 0) {
nofile = conf->nofile;
}
#endif
}
if (protocol && strcmp(protocol, "verify_sha1") == 0) {
LOGI("The verify_sha1 protocol is deprecate! Fallback to origin protocol.");
protocol = NULL;
}
if (remote_num == 0 || remote_port == NULL ||
#ifndef HAVE_LAUNCHD
local_port == NULL ||
#endif
password == NULL) {
usage();
exit(EXIT_FAILURE);
}
if (method == NULL) {
method = "rc4-md5";
}
if (timeout == NULL) {
timeout = "60";
}
#ifdef HAVE_SETRLIMIT
/*
* no need to check the return value here since we will show
* the user an error message if setrlimit(2) fails
*/
if (nofile > 1024) {
if (verbose) {
LOGI("setting NOFILE to %d", nofile);
}
set_nofile(nofile);
}
#endif
if (local_addr == NULL) {
local_addr = "127.0.0.1";
}
if (pid_flags) {
USE_SYSLOG(argv[0]);
daemonize(pid_path);
}
if (fast_open == 1) {
#ifdef TCP_FASTOPEN
LOGI("using tcp fast open");
#else
LOGE("tcp fast open is not supported by this environment");
fast_open = 0;
#endif
}
if (ipv6first) {
LOGI("resolving hostname to IPv6 address first");
}
srand(time(NULL));
// parse tunnel addr
if (tunnel_addr_str) {
parse_addr(tunnel_addr_str, &tunnel_addr);
}
#ifdef __MINGW32__
winsock_init();
#else
// ignore SIGPIPE
signal(SIGPIPE, SIG_IGN);
signal(SIGABRT, SIG_IGN);
signal(SIGINT, resolve_int_cb);
signal(SIGTERM, resolve_int_cb);
#endif
// Setup profiles
listen_ctx_t *profile = (listen_ctx_t *)ss_malloc(sizeof(listen_ctx_t));
memset(profile, 0, sizeof(listen_ctx_t));
cork_dllist_init(&profile->connections_eden);
profile->timeout = atoi(timeout);
profile->iface = ss_strdup(iface);
profile->mptcp = mptcp;
profile->tunnel_addr = tunnel_addr;
if(use_new_profile) {
char port[6];
ss_server_new_1_t *servers = &conf->server_new_1;
profile->server_num = servers->server_num;
for(i = 0; i < servers->server_num; i++) {
server_def_t *serv = &profile->servers[i];
ss_server_t *serv_cfg = &servers->servers[i];
struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage));
char *host = serv_cfg->server;
snprintf(port, sizeof(port), "%d", serv_cfg->server_port);
if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) {
FATAL("failed to resolve the provided hostname");
}
serv->addr = serv->addr_udp = storage;
serv->addr_len = serv->addr_udp_len = get_sockaddr_len((struct sockaddr *) storage);
serv->port = serv->udp_port = serv_cfg->server_port;
// set udp port
if (serv_cfg->server_udp_port != 0 && serv_cfg->server_udp_port != serv_cfg->server_port) {
storage = ss_malloc(sizeof(struct sockaddr_storage));
snprintf(port, sizeof(port), "%d", serv_cfg->server_udp_port);
if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) {
FATAL("failed to resolve the provided hostname");
}
serv->addr_udp = storage;
serv->addr_udp_len = get_sockaddr_len((struct sockaddr *) storage);
serv->udp_port = serv_cfg->server_udp_port;
}
serv->host = ss_strdup(host);
if (hostnames[i])
serv->hostname = hostnames[i];
// Setup keys
LOGI("initializing ciphers... %s", serv_cfg->method);
enc_init(&serv->cipher, serv_cfg->password, serv_cfg->method);
serv->psw = ss_strdup(serv_cfg->password);
if (serv_cfg->protocol && strcmp(serv_cfg->protocol, "verify_sha1") == 0) {
ss_free(serv_cfg->protocol);
}
cork_dllist_init(&serv->connections);
// init obfs
init_obfs(serv, ss_strdup(serv_cfg->protocol), ss_strdup(serv_cfg->protocol_param), ss_strdup(serv_cfg->obfs), ss_strdup(serv_cfg->obfs_param));
serv->enable = serv_cfg->enable;
serv->id = ss_strdup(serv_cfg->id);
serv->group = ss_strdup(serv_cfg->group);
serv->udp_over_tcp = serv_cfg->udp_over_tcp;
}
} else {
profile->server_num = remote_num;
for(i = 0; i < remote_num; i++) {
server_def_t *serv = &profile->servers[i];
char *host = remote_addr[i].host;
char *port = remote_addr[i].port == NULL ? remote_port :
remote_addr[i].port;
struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage));
if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) {
FATAL("failed to resolve the provided hostname");
}
serv->host = ss_strdup(host);
if (hostnames[i])
serv->hostname = hostnames[i];
serv->addr = serv->addr_udp = storage;
serv->addr_len = serv->addr_udp_len = get_sockaddr_len((struct sockaddr *)storage);
serv->port = serv->udp_port = atoi(port);
// Setup keys
LOGI("initializing ciphers... %s", method);
enc_init(&serv->cipher, password, method);
serv->psw = ss_strdup(password);
cork_dllist_init(&serv->connections);
// init obfs
init_obfs(serv, ss_strdup(protocol), ss_strdup(protocol_param), ss_strdup(obfs), ss_strdup(obfs_param));
serv->enable = 1;
}
}
// Init profiles
cork_dllist_init(&inactive_profiles);
current_profile = profile;
// Setup signal handler
struct ev_signal sigint_watcher;
struct ev_signal sigterm_watcher;
ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
ev_signal_start(EV_DEFAULT, &sigint_watcher);
ev_signal_start(EV_DEFAULT, &sigterm_watcher);
struct ev_loop *loop = EV_DEFAULT;
listen_ctx_t *listen_ctx = current_profile;
if (mode != UDP_ONLY) {
// Setup socket
int listenfd;
#ifdef HAVE_LAUNCHD
listenfd = launch_or_create(local_addr, local_port);
#else
listenfd = create_and_bind(local_addr, local_port);
#endif
if (listenfd == -1) {
FATAL("bind() error");
}
if (listen(listenfd, SOMAXCONN) == -1) {
FATAL("listen() error");
}
setnonblocking(listenfd);
listen_ctx->fd = listenfd;
ev_io_init(&listen_ctx->io, accept_cb, listenfd, EV_READ);
ev_io_start(loop, &listen_ctx->io);
}
// Setup UDP
if (mode != TCP_ONLY) {
LOGI("udprelay enabled");
init_udprelay(local_addr, local_port, (struct sockaddr*)listen_ctx->servers[0].addr_udp,
listen_ctx->servers[0].addr_udp_len, tunnel_addr, mtu, listen_ctx->timeout, profile->iface, &listen_ctx->servers[0].cipher, listen_ctx->servers[0].protocol_name, listen_ctx->servers[0].protocol_param);
}
#ifdef HAVE_LAUNCHD
if (local_port == NULL)
LOGI("listening through launchd");
else
#endif
if (strcmp(local_addr, ":") > 0)
LOGI("listening at [%s]:%s", local_addr, local_port);
else
LOGI("listening at %s:%s", local_addr, local_port);
// setuid
if (user != NULL && ! run_as(user)) {
FATAL("failed to switch user");
}
#ifndef __MINGW32__
if (geteuid() == 0){
LOGI("running from root user");
}
#endif
cork_dllist_init(&all_connections);
free_jconf(conf);
// Enter the loop
ev_run(loop, 0);
if (verbose) {
LOGI("closed gracefully");
}
// Clean up
if (mode != TCP_ONLY) {
free_udprelay(); // udp relay use some data from profile, so we need to release udp first
}
if (mode != UDP_ONLY) {
ev_io_stop(loop, &listen_ctx->io);
free_connections(loop); // after this, all inactive profile should be released already, so we only need to release the current_profile
release_profile(current_profile);
}
#ifdef __MINGW32__
winsock_cleanup();
#endif
ev_signal_stop(EV_DEFAULT, &sigint_watcher);
ev_signal_stop(EV_DEFAULT, &sigterm_watcher);
return 0;
}
#else
int
start_ss_local_server(profile_t profile) {
srand(time(NULL));
char *remote_host = profile.remote_host;
char *local_addr = profile.local_addr;
char *method = profile.method;
char *password = profile.password;
char *log = profile.log;
int remote_port = profile.remote_port;
int local_port = profile.local_port;
int timeout = profile.timeout;
int mtu = 0;
int mptcp = 0;
ss_addr_t tunnel_addr = {.host = NULL, .port = NULL};
mode = profile.mode;
fast_open = profile.fast_open;
verbose = profile.verbose;
mtu = profile.mtu;
mptcp = profile.mptcp;
char local_port_str[16];
char remote_port_str[16];
sprintf(local_port_str, "%d", local_port);
sprintf(remote_port_str, "%d", remote_port);
USE_LOGFILE(log);
if (profile.acl != NULL) {
acl = !init_acl(profile.acl);
}
if (local_addr == NULL) {
local_addr = "127.0.0.1";
}
#ifdef __MINGW32__
winsock_init();
#else
// ignore SIGPIPE
signal(SIGPIPE, SIG_IGN);
signal(SIGABRT, SIG_IGN);
#endif
struct ev_signal sigint_watcher;
struct ev_signal sigterm_watcher;
ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
ev_signal_start(EV_DEFAULT, &sigint_watcher);
ev_signal_start(EV_DEFAULT, &sigterm_watcher);
#ifndef __MINGW32__
struct ev_signal sigusr1_watcher;
ev_signal_init(&sigusr1_watcher, signal_cb, SIGUSR1);
ev_signal_start(EV_DEFAULT, &sigusr1_watcher);
#endif
struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage));
memset(storage, 0, sizeof(struct sockaddr_storage));
if (get_sockaddr(remote_host, remote_port_str, storage, 0, ipv6first) == -1) {
return -1;
}
// Setup proxy context
struct ev_loop *loop = EV_DEFAULT;
listen_ctx_t listen_ctx;
listen_ctx.server_num = 1;
server_def_t *serv = &listen_ctx.servers[0];
ss_server_t server_cfg;
ss_server_t *serv_cfg = &server_cfg;
server_cfg.protocol = 0;
server_cfg.protocol_param = 0;
server_cfg.obfs = 0;
server_cfg.obfs_param = 0;
serv->addr = serv->addr_udp = storage;
serv->addr_len = serv->addr_udp_len = get_sockaddr_len((struct sockaddr *) storage);
listen_ctx.timeout = timeout;
listen_ctx.iface = NULL;
listen_ctx.mptcp = mptcp;
if (mode != UDP_ONLY) {
// Setup socket
int listenfd;
listenfd = create_and_bind(local_addr, local_port_str);
if (listenfd == -1) {
ERROR("bind()");
return -1;
}
if (listen(listenfd, SOMAXCONN) == -1) {
ERROR("listen()");
return -1;
}
setnonblocking(listenfd);
listen_ctx.fd = listenfd;
ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
ev_io_start(loop, &listen_ctx.io);
}
// Setup UDP
if (mode != TCP_ONLY) {
LOGI("udprelay enabled");
init_udprelay(
local_addr,
local_port_str,
(struct sockaddr *) listen_ctx.servers[0].addr_udp,
listen_ctx.servers[0].addr_udp_len,
tunnel_addr,
mtu,
listen_ctx.timeout,
listen_ctx.iface,
&listen_ctx.servers[0].cipher,
listen_ctx.servers[0].protocol_name,
listen_ctx.servers[0].protocol_param
);
}
if (strcmp(local_addr, ":") > 0)
LOGI("listening at [%s]:%s", local_addr, local_port_str);
else
LOGI("listening at %s:%s", local_addr, local_port_str);
// Setup keys
LOGI("initializing ciphers... %s", method);
enc_init(&serv->cipher, password, method);
// init obfs
init_obfs(
serv,
ss_strdup(serv_cfg->protocol),
ss_strdup(serv_cfg->protocol_param),
ss_strdup(serv_cfg->obfs),
ss_strdup(serv_cfg->obfs_param)
);
// Init connections
cork_dllist_init(&serv->connections);
cork_dllist_init(&inactive_profiles); //
// Enter the loop
ev_run(loop, 0);
if (verbose) {
LOGI("closed gracefully");
}
// Clean up
if (mode != TCP_ONLY) {
free_udprelay();
}
if (mode != UDP_ONLY) {
ev_io_stop(loop, &listen_ctx.io);
free_connections(loop);
close(listen_ctx.fd);
}
ss_free(serv->addr);
#ifdef __MINGW32__
winsock_cleanup();
#endif
ev_signal_stop(EV_DEFAULT, &sigint_watcher);
ev_signal_stop(EV_DEFAULT, &sigterm_watcher);
#ifndef __MINGW32__
ev_signal_stop(EV_DEFAULT, &sigusr1_watcher);
#endif
// cannot reach here
return 0;
}
#endif
|
281677160/openwrt-package | 9,047 | luci-app-ssr-plus/shadowsocksr-libev/src/src/utils.h | /*
* utils.h - Misc utilities
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#if defined(USE_CRYPTO_OPENSSL)
#include <openssl/opensslv.h>
#define USING_CRYPTO OPENSSL_VERSION_TEXT
#elif defined(USE_CRYPTO_POLARSSL)
#include <polarssl/version.h>
#define USING_CRYPTO POLARSSL_VERSION_STRING_FULL
#elif defined(USE_CRYPTO_MBEDTLS)
#include <mbedtls/version.h>
#define USING_CRYPTO MBEDTLS_VERSION_STRING_FULL
#endif
#ifndef _UTILS_H
#define _UTILS_H
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define PORTSTRLEN 16
#define SS_ADDRSTRLEN (INET6_ADDRSTRLEN + PORTSTRLEN + 1)
#ifdef ANDROID
#include <android/log.h>
#define USE_TTY()
#define USE_SYSLOG(ident)
#define LOGI(...) \
((void)__android_log_print(ANDROID_LOG_DEBUG, "shadowsocks", \
__VA_ARGS__))
#define LOGE(...) \
((void)__android_log_print(ANDROID_LOG_ERROR, "shadowsocks", \
__VA_ARGS__))
#else
#define STR(x) # x
#define TOSTR(x) STR(x)
#ifdef LIB_ONLY
extern FILE *logfile;
#define TIME_FORMAT "%Y-%m-%d %H:%M:%S"
#define USE_TTY()
#define USE_SYSLOG(ident)
#define USE_LOGFILE(ident) \
do { \
if (ident != NULL) { logfile = fopen(ident, "w+"); } } \
while (0)
#define CLOSE_LOGFILE \
do { \
if (logfile != NULL) { fclose(logfile); } } \
while (0)
#define LOGI(format, ...) \
do { \
if (logfile != NULL) { \
time_t now = time(NULL); \
char timestr[20]; \
strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \
fprintf(logfile, " %s INFO: " format "\n", timestr, ## __VA_ARGS__); \
fflush(logfile); } \
} \
while (0)
#define LOGE(format, ...) \
do { \
if (logfile != NULL) { \
time_t now = time(NULL); \
char timestr[20]; \
strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \
fprintf(logfile, " %s ERROR: " format "\n", timestr, \
## __VA_ARGS__); \
fflush(logfile); } \
} \
while (0)
#elif defined(_WIN32)
#define TIME_FORMAT "%Y-%m-%d %H:%M:%S"
#define USE_TTY()
#define USE_SYSLOG(ident)
#define LOGI(format, ...) \
do { \
time_t now = time(NULL); \
char timestr[20]; \
strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \
fprintf(stderr, " %s INFO: " format "\n", timestr, ## __VA_ARGS__); \
fflush(stderr); } \
while (0)
#define LOGE(format, ...) \
do { \
time_t now = time(NULL); \
char timestr[20]; \
strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \
fprintf(stderr, " %s ERROR: " format "\n", timestr, ## __VA_ARGS__); \
fflush(stderr); } \
while (0)
#else
#include <syslog.h>
extern int use_tty;
#define USE_TTY() \
do { \
use_tty = isatty(STDERR_FILENO); \
} while (0) \
#define HAS_SYSLOG
extern int use_syslog;
#define TIME_FORMAT "%F %T"
#define USE_SYSLOG(ident) \
do { \
use_syslog = 1; \
openlog((ident), LOG_CONS | LOG_PID, 0); } \
while (0)
#define LOGI(format, ...) \
do { \
if (use_syslog) { \
syslog(LOG_INFO, format, ## __VA_ARGS__); \
} else { \
time_t now = time(NULL); \
char timestr[20]; \
strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \
if (use_tty) { \
fprintf(stderr, "\e[01;32m %s INFO: \e[0m" format "\n", timestr, \
## __VA_ARGS__); \
} else { \
fprintf(stderr, " %s INFO: " format "\n", timestr, \
## __VA_ARGS__); \
} \
} \
} \
while (0)
#define LOGE(format, ...) \
do { \
if (use_syslog) { \
syslog(LOG_ERR, format, ## __VA_ARGS__); \
} else { \
time_t now = time(NULL); \
char timestr[20]; \
strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \
if (use_tty) { \
fprintf(stderr, "\e[01;35m %s ERROR: \e[0m" format "\n", timestr, \
## __VA_ARGS__); \
} else { \
fprintf(stderr, " %s ERROR: " format "\n", timestr, \
## __VA_ARGS__); \
} \
} } \
while (0)
#endif
/* _WIN32 */
#endif
#ifdef __MINGW32__
#ifdef ERROR
#undef ERROR
#endif
#define ERROR(s) ss_error(s)
#else
void ERROR(const char *s);
#endif
char *ss_itoa(int i);
int ss_isnumeric(const char *s);
int run_as(const char *user);
void FATAL(const char *msg);
void usage(void);
void daemonize(const char *path);
char *ss_strndup(const char *s, size_t n);
char *ss_strdup(const char *s);
#ifdef HAVE_SETRLIMIT
int set_nofile(int nofile);
#endif
void *ss_malloc(size_t size);
void *ss_realloc(void *ptr, size_t new_size);
#define ss_free(ptr) \
do { \
free(ptr); \
ptr = NULL; \
} while (0)
#endif // _UTILS_H
|
281677160/openwrt-package | 36,693 | luci-app-ssr-plus/shadowsocksr-libev/src/src/tunnel.c | /*
* tunnel.c - Setup a local port forwarding through remote shadowsocks server
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <locale.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <getopt.h>
#ifndef __MINGW32__
#include <errno.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H) && defined(__linux__)
#include <net/if.h>
#include <sys/ioctl.h>
#define SET_INTERFACE
#endif
#ifdef __MINGW32__
#include "win32.h"
#endif
#include <libcork/core.h>
#include <udns.h>
#include "netutils.h"
#include "utils.h"
#include "tunnel.h"
#ifndef EAGAIN
#define EAGAIN EWOULDBLOCK
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK EAGAIN
#endif
#ifndef BUF_SIZE
#define BUF_SIZE 2048
#endif
#include "includeobfs.h" // I don't want to modify makefile
static void accept_cb(EV_P_ ev_io *w, int revents);
static void server_recv_cb(EV_P_ ev_io *w, int revents);
static void server_send_cb(EV_P_ ev_io *w, int revents);
static void remote_recv_cb(EV_P_ ev_io *w, int revents);
static void remote_send_cb(EV_P_ ev_io *w, int revents);
static remote_t *new_remote(int fd, int timeout);
static server_t *new_server(int fd, int method);
static void free_remote(remote_t *remote);
static void close_and_free_remote(EV_P_ remote_t *remote);
static void free_server(server_t *server);
static void close_and_free_server(EV_P_ server_t *server);
#ifdef ANDROID
int vpn = 0;
char *prefix;
#endif
int verbose = 0;
int keep_resolving = 1;
static int ipv6first = 0;
static int mode = TCP_ONLY;
#ifdef HAVE_SETRLIMIT
static int nofile = 0;
#endif
#ifndef __MINGW32__
static int
setnonblocking(int fd)
{
int flags;
if (-1 == (flags = fcntl(fd, F_GETFL, 0))) {
flags = 0;
}
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
#endif
int
create_and_bind(const char *addr, const char *port)
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int s, listen_sock;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */
s = getaddrinfo(addr, port, &hints, &result);
if (s != 0) {
LOGI("getaddrinfo: %s", gai_strerror(s));
return -1;
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
listen_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (listen_sock == -1) {
continue;
}
int opt = 1;
setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(listen_sock, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
int err = set_reuseport(listen_sock);
if (err == 0) {
LOGI("tcp port reuse enabled");
}
s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen);
if (s == 0) {
/* We managed to bind successfully! */
break;
} else {
ERROR("bind");
}
close(listen_sock);
}
if (rp == NULL) {
LOGE("Could not bind");
return -1;
}
freeaddrinfo(result);
return listen_sock;
}
static void
server_recv_cb(EV_P_ ev_io *w, int revents)
{
server_ctx_t *server_recv_ctx = (server_ctx_t *)w;
server_t *server = server_recv_ctx->server;
remote_t *remote = server->remote;
if (remote == NULL) {
close_and_free_server(EV_A_ server);
return;
}
ssize_t r = recv(server->fd, remote->buf->array, BUF_SIZE, 0);
if (r == 0) {
// connection closed
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else if (r == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data
// continue to wait for recv
return;
} else {
ERROR("server recv");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
remote->buf->len = r;
// SSR beg
if (server->protocol_plugin) {
obfs_class *protocol_plugin = server->protocol_plugin;
if (protocol_plugin->client_pre_encrypt) {
remote->buf->len = protocol_plugin->client_pre_encrypt(server->protocol, &remote->buf->array, remote->buf->len, &remote->buf->capacity);
}
}
int err = ss_encrypt(&cipher_env, remote->buf, server->e_ctx, BUF_SIZE);
if (err) {
LOGE("server invalid password or cipher");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (server->obfs_plugin) {
obfs_class *obfs_plugin = server->obfs_plugin;
if (obfs_plugin->client_encode) {
remote->buf->len = obfs_plugin->client_encode(server->obfs, &remote->buf->array, remote->buf->len, &remote->buf->capacity);
}
}
// SSR end
if (r > 0 && remote->buf->len == 0) { // SSR pause recv
remote->buf->idx = 0;
ev_io_stop(EV_A_ & server_recv_ctx->io);
return;
}
int s = send(remote->fd, remote->buf->array, remote->buf->len, 0);
if (s == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data, wait for send
remote->buf->idx = 0;
ev_io_stop(EV_A_ & server_recv_ctx->io);
ev_io_start(EV_A_ & remote->send_ctx->io);
return;
} else {
ERROR("send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
} else if (s < remote->buf->len) {
remote->buf->len -= s;
remote->buf->idx = s;
ev_io_stop(EV_A_ & server_recv_ctx->io);
ev_io_start(EV_A_ & remote->send_ctx->io);
return;
}
}
static void
server_send_cb(EV_P_ ev_io *w, int revents)
{
server_ctx_t *server_send_ctx = (server_ctx_t *)w;
server_t *server = server_send_ctx->server;
remote_t *remote = server->remote;
if (server->buf->len == 0) {
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else {
// has data to send
ssize_t s = send(server->fd, server->buf->array + server->buf->idx,
server->buf->len, 0);
if (s == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
ERROR("send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
} else if (s < server->buf->len) {
// partly sent, move memory, wait for the next time to send
server->buf->len -= s;
server->buf->idx += s;
return;
} else {
// all sent out, wait for reading
server->buf->len = 0;
server->buf->idx = 0;
ev_io_stop(EV_A_ & server_send_ctx->io);
if (remote != NULL) {
ev_io_start(EV_A_ & remote->recv_ctx->io);
} else {
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
}
}
static void
remote_timeout_cb(EV_P_ ev_timer *watcher, int revents)
{
remote_ctx_t *remote_ctx
= cork_container_of(watcher, remote_ctx_t, watcher);
remote_t *remote = remote_ctx->remote;
server_t *server = remote->server;
if (verbose) {
LOGI("TCP connection timeout");
}
ev_timer_stop(EV_A_ watcher);
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
static void
remote_recv_cb(EV_P_ ev_io *w, int revents)
{
remote_ctx_t *remote_recv_ctx = (remote_ctx_t *)w;
remote_t *remote = remote_recv_ctx->remote;
server_t *server = remote->server;
ssize_t r = recv(remote->fd, server->buf->array, BUF_SIZE, 0);
if (r == 0) {
// connection closed
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else if (r == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data
// continue to wait for recv
return;
} else {
ERROR("remote recv");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
}
server->buf->len = r;
// SSR beg
if (server->obfs_plugin) {
obfs_class *obfs_plugin = server->obfs_plugin;
if (obfs_plugin->client_decode) {
int needsendback;
server->buf->len = obfs_plugin->client_decode(server->obfs, &server->buf->array, server->buf->len, &server->buf->capacity, &needsendback);
if ((int)server->buf->len < 0) {
LOGE("client_decode");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (needsendback) {
obfs_class *obfs_plugin = server->obfs_plugin;
if (obfs_plugin->client_encode) {
remote->buf->len = obfs_plugin->client_encode(server->obfs, &remote->buf->array, 0, &remote->buf->capacity);
ssize_t s = send(remote->fd, remote->buf->array, remote->buf->len, 0);
if (s == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
ERROR("remote_send_cb_send");
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
} else if (s < (ssize_t)(remote->buf->len)) {
// partly sent, move memory, wait for the next time to send
remote->buf->len -= s;
remote->buf->idx += s;
return;
} else {
// all sent out, wait for reading
remote->buf->len = 0;
remote->buf->idx = 0;
ev_io_stop(EV_A_ & remote->send_ctx->io);
ev_io_start(EV_A_ & server->recv_ctx->io);
}
}
}
}
}
if ( server->buf->len == 0 )
return;
int err = ss_decrypt(&cipher_env, server->buf, server->d_ctx, BUF_SIZE);
if (err) {
LOGE("invalid password or cipher");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (server->protocol_plugin) {
obfs_class *protocol_plugin = server->protocol_plugin;
if (protocol_plugin->client_post_decrypt) {
server->buf->len = protocol_plugin->client_post_decrypt(server->protocol, &server->buf->array, server->buf->len, &server->buf->capacity);
if ((int)server->buf->len < 0) {
LOGE("client_post_decrypt");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if ( server->buf->len == 0 )
return;
}
}
// SSR end
int s = send(server->fd, server->buf->array, server->buf->len, 0);
if (s == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// no data, wait for send
server->buf->idx = 0;
ev_io_stop(EV_A_ & remote_recv_ctx->io);
ev_io_start(EV_A_ & server->send_ctx->io);
} else {
ERROR("send");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
} else if (s < server->buf->len) {
server->buf->len -= s;
server->buf->idx = s;
ev_io_stop(EV_A_ & remote_recv_ctx->io);
ev_io_start(EV_A_ & server->send_ctx->io);
}
}
static void
remote_send_cb(EV_P_ ev_io *w, int revents)
{
remote_ctx_t *remote_send_ctx = (remote_ctx_t *)w;
remote_t *remote = remote_send_ctx->remote;
server_t *server = remote->server;
if (!remote_send_ctx->connected) {
struct sockaddr_storage addr;
socklen_t len = sizeof(struct sockaddr_storage);
int r = getpeername(remote->fd, (struct sockaddr *)&addr, &len);
if (r == 0) {
remote_send_ctx->connected = 1;
ev_io_stop(EV_A_ & remote_send_ctx->io);
ev_timer_stop(EV_A_ & remote_send_ctx->watcher);
buffer_t ss_addr_to_send;
buffer_t *abuf = &ss_addr_to_send;
balloc(abuf, BUF_SIZE);
ss_addr_t *sa = &server->destaddr;
struct cork_ip ip;
if (cork_ip_init(&ip, sa->host) != -1) {
if (ip.version == 4) {
// send as IPv4
struct in_addr host;
memset(&host, 0, sizeof(struct in_addr));
int host_len = sizeof(struct in_addr);
if (dns_pton(AF_INET, sa->host, &host) == -1) {
FATAL("IP parser error");
}
abuf->array[abuf->len++] = 1;
memcpy(abuf->array + abuf->len, &host, host_len);
abuf->len += host_len;
} else if (ip.version == 6) {
// send as IPv6
struct in6_addr host;
memset(&host, 0, sizeof(struct in6_addr));
int host_len = sizeof(struct in6_addr);
if (dns_pton(AF_INET6, sa->host, &host) == -1) {
FATAL("IP parser error");
}
abuf->array[abuf->len++] = 4;
memcpy(abuf->array + abuf->len, &host, host_len);
abuf->len += host_len;
} else {
FATAL("IP parser error");
}
} else {
// send as domain
int host_len = strlen(sa->host);
abuf->array[abuf->len++] = 3;
abuf->array[abuf->len++] = host_len;
memcpy(abuf->array + abuf->len, sa->host, host_len);
abuf->len += host_len;
}
uint16_t port = htons(atoi(sa->port));
memcpy(abuf->array + abuf->len, &port, 2);
abuf->len += 2;
if (remote->buf->len > 0) {
brealloc(remote->buf, remote->buf->len + abuf->len, BUF_SIZE);
memmove(remote->buf->array + abuf->len, remote->buf->array, remote->buf->len);
memcpy(remote->buf->array, abuf->array, abuf->len);
remote->buf->len += abuf->len;
} else {
brealloc(remote->buf, abuf->len, BUF_SIZE);
memcpy(remote->buf->array, abuf->array, abuf->len);
remote->buf->len = abuf->len;
}
bfree(abuf);
// SSR beg
server_info _server_info;
if (server->obfs_plugin) {
server->obfs_plugin->get_server_info(server->obfs, &_server_info);
_server_info.head_len = get_head_size(remote->buf->array, remote->buf->len, 30);
server->obfs_plugin->set_server_info(server->obfs, &_server_info);
}
if (server->protocol_plugin) {
obfs_class *protocol_plugin = server->protocol_plugin;
if (protocol_plugin->client_pre_encrypt) {
remote->buf->len = protocol_plugin->client_pre_encrypt(server->protocol, &remote->buf->array, remote->buf->len, &remote->buf->capacity);
}
}
int err = ss_encrypt(&cipher_env, remote->buf, server->e_ctx, BUF_SIZE);
if (err) {
LOGE("invalid password or cipher");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
if (server->obfs_plugin) {
obfs_class *obfs_plugin = server->obfs_plugin;
if (obfs_plugin->client_encode) {
remote->buf->len = obfs_plugin->client_encode(server->obfs, &remote->buf->array, remote->buf->len, &remote->buf->capacity);
}
}
int s = send(remote->fd, remote->buf->array, remote->buf->len, 0);
if (s < remote->buf->len) {
LOGE("failed to send addr");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
remote->buf->len = 0;
remote->buf->idx = 0;
// SSR end
ev_io_start(EV_A_ & remote->recv_ctx->io);
ev_io_start(EV_A_ & server->recv_ctx->io);
return;
} else {
ERROR("getpeername");
// not connected
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
} else {
if (remote->buf->len == 0) {
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
} else {
// has data to send
ssize_t s = send(remote->fd, remote->buf->array + remote->buf->idx,
remote->buf->len, 0);
if (s == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
ERROR("send");
// close and free
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
}
return;
} else if (s < remote->buf->len) {
// partly sent, move memory, wait for the next time to send
remote->buf->len -= s;
remote->buf->idx += s;
return;
} else {
// all sent out, wait for reading
remote->buf->len = 0;
remote->buf->idx = 0;
ev_io_stop(EV_A_ & remote_send_ctx->io);
ev_io_start(EV_A_ & server->recv_ctx->io);
}
}
}
}
static remote_t *
new_remote(int fd, int timeout)
{
remote_t *remote = ss_malloc(sizeof(remote_t));
memset(remote, 0, sizeof(remote_t));
remote->buf = ss_malloc(sizeof(buffer_t));
remote->recv_ctx = ss_malloc(sizeof(remote_ctx_t));
remote->send_ctx = ss_malloc(sizeof(remote_ctx_t));
balloc(remote->buf, BUF_SIZE);
memset(remote->recv_ctx, 0, sizeof(remote_ctx_t));
memset(remote->send_ctx, 0, sizeof(remote_ctx_t));
remote->fd = fd;
remote->recv_ctx->remote = remote;
remote->recv_ctx->connected = 0;
remote->send_ctx->remote = remote;
remote->send_ctx->connected = 0;
ev_io_init(&remote->recv_ctx->io, remote_recv_cb, fd, EV_READ);
ev_io_init(&remote->send_ctx->io, remote_send_cb, fd, EV_WRITE);
ev_timer_init(&remote->send_ctx->watcher, remote_timeout_cb,
min(MAX_CONNECT_TIMEOUT, timeout), 0);
return remote;
}
static void
free_remote(remote_t *remote)
{
if (remote != NULL) {
if (remote->server != NULL) {
remote->server->remote = NULL;
}
if (remote->buf) {
bfree(remote->buf);
ss_free(remote->buf);
}
ss_free(remote->recv_ctx);
ss_free(remote->send_ctx);
ss_free(remote);
}
}
static void
close_and_free_remote(EV_P_ remote_t *remote)
{
if (remote != NULL) {
ev_timer_stop(EV_A_ & remote->send_ctx->watcher);
ev_io_stop(EV_A_ & remote->send_ctx->io);
ev_io_stop(EV_A_ & remote->recv_ctx->io);
close(remote->fd);
free_remote(remote);
}
}
static server_t *
new_server(int fd, int method)
{
server_t *server = ss_malloc(sizeof(server_t));
memset(server, 0, sizeof(server_t));
server->buf = ss_malloc(sizeof(buffer_t));
server->recv_ctx = ss_malloc(sizeof(server_ctx_t));
server->send_ctx = ss_malloc(sizeof(server_ctx_t));
balloc(server->buf, BUF_SIZE);
memset(server->recv_ctx, 0, sizeof(server_ctx_t));
memset(server->send_ctx, 0, sizeof(server_ctx_t));
server->fd = fd;
server->recv_ctx->server = server;
server->recv_ctx->connected = 0;
server->send_ctx->server = server;
server->send_ctx->connected = 0;
if (method) {
server->e_ctx = ss_malloc(sizeof(struct enc_ctx));
server->d_ctx = ss_malloc(sizeof(struct enc_ctx));
enc_ctx_init(&cipher_env, server->e_ctx, 1);
enc_ctx_init(&cipher_env, server->d_ctx, 0);
} else {
server->e_ctx = NULL;
server->d_ctx = NULL;
}
ev_io_init(&server->recv_ctx->io, server_recv_cb, fd, EV_READ);
ev_io_init(&server->send_ctx->io, server_send_cb, fd, EV_WRITE);
return server;
}
static void
free_server(server_t *server)
{
if (server != NULL) {
if (server->remote != NULL) {
server->remote->server = NULL;
}
if (server->e_ctx != NULL) {
enc_ctx_release(&cipher_env, server->e_ctx);
ss_free(server->e_ctx);
}
if (server->d_ctx != NULL) {
enc_ctx_release(&cipher_env, server->d_ctx);
ss_free(server->d_ctx);
}
if (server->buf) {
bfree(server->buf);
ss_free(server->buf);
}
// SSR beg
if (server->obfs_plugin) {
server->obfs_plugin->dispose(server->obfs);
server->obfs = NULL;
free_obfs_class(server->obfs_plugin);
server->obfs_plugin = NULL;
}
if (server->protocol_plugin) {
server->protocol_plugin->dispose(server->protocol);
server->protocol = NULL;
free_obfs_class(server->protocol_plugin);
server->protocol_plugin = NULL;
}
// SSR end
ss_free(server->recv_ctx);
ss_free(server->send_ctx);
ss_free(server);
}
}
static void
close_and_free_server(EV_P_ server_t *server)
{
if (server != NULL) {
ev_io_stop(EV_A_ & server->send_ctx->io);
ev_io_stop(EV_A_ & server->recv_ctx->io);
close(server->fd);
free_server(server);
}
}
static void
accept_cb(EV_P_ ev_io *w, int revents)
{
struct listen_ctx *listener = (struct listen_ctx *)w;
int serverfd = accept(listener->fd, NULL, NULL);
if (serverfd == -1) {
ERROR("accept");
return;
}
setnonblocking(serverfd);
int opt = 1;
setsockopt(serverfd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(serverfd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
int index = rand() % listener->remote_num;
struct sockaddr *remote_addr = listener->remote_addr[index];
int remotefd = socket(remote_addr->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (remotefd == -1) {
ERROR("socket");
return;
}
#ifdef ANDROID
if (vpn) {
int not_protect = 0;
if (remote_addr->sa_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)remote_addr;
if (s->sin_addr.s_addr == inet_addr("127.0.0.1"))
not_protect = 1;
}
if (!not_protect) {
if (protect_socket(remotefd) == -1) {
ERROR("protect_socket");
close(remotefd);
return;
}
}
}
#endif
setsockopt(remotefd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt));
#ifdef SO_NOSIGPIPE
setsockopt(remotefd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt));
#endif
if (listener->mptcp == 1) {
int err = setsockopt(remotefd, SOL_TCP, MPTCP_ENABLED, &opt, sizeof(opt));
if (err == -1) {
ERROR("failed to enable multipath TCP");
}
}
// Setup
setnonblocking(remotefd);
#ifdef SET_INTERFACE
if (listener->iface) {
if (setinterface(remotefd, listener->iface) == -1)
ERROR("setinterface");
}
#endif
server_t *server = new_server(serverfd, listener->method);
remote_t *remote = new_remote(remotefd, listener->timeout);
server->destaddr = listener->tunnel_addr;
server->remote = remote;
remote->server = server;
int r = connect(remotefd, remote_addr, get_sockaddr_len(remote_addr));
if (r == -1 && errno != CONNECT_IN_PROGRESS) {
ERROR("connect");
close_and_free_remote(EV_A_ remote);
close_and_free_server(EV_A_ server);
return;
}
// listen to remote connected event
ev_io_start(EV_A_ & remote->send_ctx->io);
ev_timer_start(EV_A_ & remote->send_ctx->watcher);
}
void
signal_cb(int dummy)
{
keep_resolving = 0;
exit(-1);
}
int
main(int argc, char **argv)
{
srand(time(NULL));
int i, c;
int pid_flags = 0;
int mptcp = 0;
int mtu = 0;
char *user = NULL;
char *local_port = NULL;
char *local_addr = NULL;
char *password = NULL;
char *timeout = NULL;
char *protocol = NULL; // SSR
char *protocol_param = NULL; // SSR
char *method = NULL;
char *obfs = NULL; // SSR
char *obfs_param = NULL; // SSR
char *pid_path = NULL;
char *conf_path = NULL;
char *iface = NULL;
int remote_num = 0;
ss_addr_t remote_addr[MAX_REMOTE_NUM];
char *remote_port = NULL;
ss_addr_t tunnel_addr = { .host = NULL, .port = NULL };
char *tunnel_addr_str = NULL;
int option_index = 0;
static struct option long_options[] = {
{ "mtu", required_argument, 0, 0 },
{ "mptcp", no_argument, 0, 0 },
{ "help", no_argument, 0, 0 },
{ 0, 0, 0, 0 }
};
opterr = 0;
USE_TTY();
#ifdef ANDROID
while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:n:P:huUvVA6"
"O:o:G:g:",
long_options, &option_index)) != -1) {
#else
while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:n:huUvA6"
"O:o:G:g:",
long_options, &option_index)) != -1) {
#endif
switch (c) {
case 0:
if (option_index == 0) {
mtu = atoi(optarg);
LOGI("set MTU to %d", mtu);
} else if (option_index == 1) {
mptcp = 1;
LOGI("enable multipath TCP");
} else if (option_index == 2) {
usage();
exit(EXIT_SUCCESS);
}
break;
case 's':
if (remote_num < MAX_REMOTE_NUM) {
remote_addr[remote_num].host = optarg;
remote_addr[remote_num++].port = NULL;
}
break;
case 'p':
remote_port = optarg;
break;
case 'l':
local_port = optarg;
break;
case 'k':
password = optarg;
break;
case 'f':
pid_flags = 1;
pid_path = optarg;
break;
case 't':
timeout = optarg;
break;
// SSR beg
case 'O':
protocol = optarg;
break;
case 'm':
method = optarg;
break;
case 'o':
obfs = optarg;
break;
case 'G':
protocol_param = optarg;
break;
case 'g':
obfs_param = optarg;
break;
// SSR end
case 'c':
conf_path = optarg;
break;
case 'i':
iface = optarg;
break;
case 'b':
local_addr = optarg;
break;
case 'u':
mode = TCP_AND_UDP;
break;
case 'U':
mode = UDP_ONLY;
break;
case 'L':
tunnel_addr_str = optarg;
break;
case 'a':
user = optarg;
break;
#ifdef HAVE_SETRLIMIT
case 'n':
nofile = atoi(optarg);
break;
#endif
case 'v':
verbose = 1;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'A':
LOGI("The 'A' argument is deprecate! Ignored.");
break;
case '6':
ipv6first = 1;
break;
#ifdef ANDROID
case 'V':
vpn = 1;
break;
case 'P':
prefix = optarg;
break;
#endif
case '?':
// The option character is not recognized.
LOGE("Unrecognized option: %s", optarg);
opterr = 1;
break;
}
}
if (opterr) {
usage();
exit(EXIT_FAILURE);
}
if (argc == 1) {
if (conf_path == NULL) {
conf_path = DEFAULT_CONF_PATH;
}
}
if (conf_path != NULL) {
jconf_t *conf = read_jconf(conf_path);
if (remote_num == 0) {
remote_num = conf->remote_num;
for (i = 0; i < remote_num; i++)
remote_addr[i] = conf->remote_addr[i];
}
if (remote_port == NULL) {
remote_port = conf->remote_port;
}
if (local_addr == NULL) {
local_addr = conf->local_addr;
}
if (local_port == NULL) {
local_port = conf->local_port;
}
if (password == NULL) {
password = conf->password;
}
// SSR beg
if (protocol == NULL) {
protocol = conf->protocol;
LOGI("protocol %s", protocol);
}
if (protocol_param == NULL) {
protocol_param = conf->protocol_param;
LOGI("protocol_param %s", protocol_param);
}
if (method == NULL) {
method = conf->method;
LOGI("method %s", method);
}
if (obfs == NULL) {
obfs = conf->obfs;
LOGI("obfs %s", obfs);
}
if (obfs_param == NULL) {
obfs_param = conf->obfs_param;
LOGI("obfs_param %s", obfs_param);
}
// SSR end
if (timeout == NULL) {
timeout = conf->timeout;
}
if (user == NULL) {
user = conf->user;
}
if (tunnel_addr_str == NULL) {
tunnel_addr_str = conf->tunnel_address;
}
if (mode == TCP_ONLY) {
mode = conf->mode;
}
if (mtu == 0) {
mtu = conf->mtu;
}
if (mptcp == 0) {
mptcp = conf->mptcp;
}
#ifdef HAVE_SETRLIMIT
if (nofile == 0) {
nofile = conf->nofile;
}
#endif
}
if (protocol && strcmp(protocol, "verify_sha1") == 0) {
LOGI("The verify_sha1 protocol is deprecate! Fallback to origin protocol.");
protocol = NULL;
}
if (remote_num == 0 || remote_port == NULL || tunnel_addr_str == NULL ||
local_port == NULL || password == NULL) {
usage();
exit(EXIT_FAILURE);
}
if (method == NULL) {
method = "rc4-md5";
}
if (timeout == NULL) {
timeout = "60";
}
#ifdef HAVE_SETRLIMIT
/*
* no need to check the return value here since we will show
* the user an error message if setrlimit(2) fails
*/
if (nofile > 1024) {
if (verbose) {
LOGI("setting NOFILE to %d", nofile);
}
set_nofile(nofile);
}
#endif
if (local_addr == NULL) {
local_addr = "127.0.0.1";
}
if (pid_flags) {
USE_SYSLOG(argv[0]);
daemonize(pid_path);
}
if (ipv6first) {
LOGI("resolving hostname to IPv6 address first");
}
// parse tunnel addr
parse_addr(tunnel_addr_str, &tunnel_addr);
if (tunnel_addr.port == NULL) {
FATAL("tunnel port is not defined");
}
#ifdef __MINGW32__
winsock_init();
#else
// ignore SIGPIPE
signal(SIGPIPE, SIG_IGN);
signal(SIGABRT, SIG_IGN);
signal(SIGINT, signal_cb);
signal(SIGTERM, signal_cb);
#endif
// Setup keys
LOGI("initializing ciphers... %s", method);
int m = enc_init(&cipher_env, password, method);
// Setup proxy context
struct listen_ctx listen_ctx;
memset(&listen_ctx, 0, sizeof(struct listen_ctx));
listen_ctx.tunnel_addr = tunnel_addr;
listen_ctx.remote_num = remote_num;
listen_ctx.remote_addr = ss_malloc(sizeof(struct sockaddr *) * remote_num);
memset(listen_ctx.remote_addr, 0, sizeof(struct sockaddr *) * remote_num);
for (i = 0; i < remote_num; i++) {
char *host = remote_addr[i].host;
char *port = remote_addr[i].port == NULL ? remote_port :
remote_addr[i].port;
struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage));
memset(storage, 0, sizeof(struct sockaddr_storage));
if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) {
FATAL("failed to resolve the provided hostname");
}
listen_ctx.remote_addr[i] = (struct sockaddr *)storage;
}
listen_ctx.timeout = atoi(timeout);
listen_ctx.iface = iface;
// SSR beg
listen_ctx.protocol_name = protocol;
listen_ctx.protocol_param = protocol_param;
listen_ctx.method = m;
listen_ctx.obfs_name = obfs;
listen_ctx.obfs_param = obfs_param;
listen_ctx.list_protocol_global = malloc(sizeof(void *) * remote_num);
listen_ctx.list_obfs_global = malloc(sizeof(void *) * remote_num);
memset(listen_ctx.list_protocol_global, 0, sizeof(void *) * remote_num);
memset(listen_ctx.list_obfs_global, 0, sizeof(void *) * remote_num);
// SSR end
listen_ctx.mptcp = mptcp;
struct ev_loop *loop = EV_DEFAULT;
if (mode != UDP_ONLY) {
// Setup socket
int listenfd;
listenfd = create_and_bind(local_addr, local_port);
if (listenfd == -1) {
FATAL("bind() error:");
}
if (listen(listenfd, SOMAXCONN) == -1) {
FATAL("listen() error:");
}
setnonblocking(listenfd);
listen_ctx.fd = listenfd;
ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
ev_io_start(loop, &listen_ctx.io);
}
// Setup UDP
if (mode != TCP_ONLY) {
LOGI("UDP relay enabled");
init_udprelay(local_addr, local_port, listen_ctx.remote_addr[0],
get_sockaddr_len(listen_ctx.remote_addr[0]),
tunnel_addr, mtu, listen_ctx.timeout, iface, protocol, protocol_param);
}
if (mode == UDP_ONLY) {
LOGI("TCP relay disabled");
}
LOGI("listening at %s:%s", local_addr, local_port);
// setuid
if (user != NULL && ! run_as(user)) {
FATAL("failed to switch user");
}
#ifndef __MINGW32__
if (geteuid() == 0){
LOGI("running from root user");
}
#endif
ev_run(loop, 0);
#ifdef __MINGW32__
winsock_cleanup();
#endif
return 0;
}
|
281677160/openwrt-package | 2,756 | luci-app-ssr-plus/shadowsocksr-libev/src/src/shadowsocks.h | /*
* shadowsocks.h - Header files of library interfaces
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _SHADOWSOCKS_H
#define _SHADOWSOCKS_H
typedef struct {
/* Required */
char *remote_host; // hostname or ip of remote server
char *local_addr; // local ip to bind
char *method; // encryption method
char *password; // password of remote server
int remote_port; // port number of remote server
int local_port; // port number of local server
int timeout; // connection timeout
/* Optional, set NULL if not valid */
char *acl; // file path to acl
char *log; // file path to log
int fast_open; // enable tcp fast open
int mode; // enable udp relay
int mtu; // MTU of interface
int mptcp; // enable multipath TCP
int verbose; // verbose mode
} profile_t;
/* An example profile
*
* const profile_t EXAMPLE_PROFILE = {
* .remote_host = "example.com",
* .local_addr = "127.0.0.1",
* .method = "bf-cfb",
* .password = "barfoo!",
* .remote_port = 8338,
* .local_port = 1080,
* .timeout = 600;
* .acl = NULL,
* .log = NULL,
* .fast_open = 0,
* .mode = 0,
* .verbose = 0
* };
*/
#ifdef __cplusplus
extern "C" {
#endif
/*
* Create and start a shadowsocks local server.
*
* Calling this function will block the current thread forever if the server
* starts successfully.
*
* Make sure start the server in a separate process to avoid any potential
* memory and socket leak.
*
* If failed, -1 is returned. Errors will output to the log file.
*/
int start_ss_local_server(profile_t profile);
#ifdef __cplusplus
}
#endif
// To stop the service on posix system, just kill the daemon process
// kill(pid, SIGKILL);
// Otherwise, If you start the service in a thread, you may need to send a signal SIGUSER1 to the thread.
// pthread_kill(pthread_t, SIGUSR1);
#endif // _SHADOWSOCKS_H
|
281677160/openwrt-package | 14,621 | luci-app-ssr-plus/shadowsocksr-libev/src/src/jconf.c | /*
* jconf.c - Parse the JSON format config file
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include "utils.h"
#include "jconf.h"
#include "json.h"
#include "string.h"
#include <libcork/core.h>
#define check_json_value_type(value, expected_type, message) \
do { \
if ((value)->type != (expected_type)) \
FATAL((message)); \
} while(0)
static char *
to_string(const json_value *value)
{
if (value->type == json_string) {
return ss_strndup(value->u.string.ptr, value->u.string.length);
} else if (value->type == json_integer) {
return strdup(ss_itoa(value->u.integer));
} else if (value->type == json_null) {
return "null";
} else {
LOGE("%d", value->type);
FATAL("Invalid config format.");
}
return 0;
}
void
free_addr(ss_addr_t *addr)
{
ss_free(addr->host);
ss_free(addr->port);
}
void
parse_addr(const char *str, ss_addr_t *addr)
{
int ipv6 = 0, ret = -1, n = 0;
char *pch;
struct cork_ip ip;
if (cork_ip_init(&ip, str) != -1) {
addr->host = strdup(str);
addr->port = NULL;
return;
}
pch = strchr(str, ':');
while (pch != NULL) {
n++;
ret = pch - str;
pch = strchr(pch + 1, ':');
}
if (n > 1) {
ipv6 = 1;
if (str[ret - 1] != ']') {
ret = -1;
}
}
if (ret == -1) {
if (ipv6) {
addr->host = ss_strndup(str + 1, strlen(str) - 2);
} else {
addr->host = strdup(str);
}
addr->port = NULL;
} else {
if (ipv6) {
addr->host = ss_strndup(str + 1, ret - 2);
} else {
addr->host = ss_strndup(str, ret);
}
addr->port = strdup(str + ret + 1);
}
}
void parse_ss_server(ss_server_t *server, json_value* json) {
unsigned int i;
// TODO: set default value
for (i = 0; i < json->u.object.length; i++) {
char *name = json->u.object.values[i].name;
json_value *value = json->u.object.values[i].value;
if (strcmp(name, "id") == 0) {
server->id = to_string(value);
} else if (strcmp(name, "server") == 0) {
server->server = to_string(value);
} else if (strcmp(name, "server_port") == 0) {
check_json_value_type(value, json_integer,
"invalid config file: option 'server_port' must be an integer");
server->server_port = value->u.integer;
} else if (strcmp(name, "server_udp_port") == 0) { // SSR
check_json_value_type(value, json_integer,
"invalid config file: option 'server_udp_port' must be an integer");
server->server_udp_port = value->u.integer;
} else if (strcmp(name, "password") == 0) {
server->password = to_string(value);
} else if (strcmp(name, "method") == 0) {
server->method = to_string(value);
} else if (strcmp(name, "protocol") == 0) { // SSR
server->protocol = to_string(value);
} else if (strcmp(name, "protocol_param") == 0) { //SSR
server->protocol_param = to_string(value);
} else if (strcmp(name, "obfs") == 0) { // SSR
server->obfs = to_string(value);
} else if (strcmp(name, "obfs_param") == 0) { // SSR
server->obfs_param = to_string(value);
} else if (strcmp(name, "group") == 0) { // SSR
server->group = to_string(value);
} else if (strcmp(name, "enable") == 0) { // SSR
check_json_value_type(value, json_boolean,
"invalid config file: option 'enable' must be an boolean");
server->enable = value->u.boolean;
} else if (strcmp(name, "udp_over_tcp") == 0) { // SSR
check_json_value_type(value, json_boolean,
"invalid config file: option 'udp_over_tcp' must be an boolean");
server->udp_over_tcp = value->u.boolean;
}
}
}
jconf_t *
read_jconf(const char *file)
{
static jconf_t conf;
memset(&conf, 0, sizeof(jconf_t));
conf.conf_ver = CONF_VER_LEGACY; // try legacy version first
char *buf;
json_value *obj;
FILE *f = fopen(file, "rb");
if (f == NULL) {
FATAL("Invalid config path.");
}
fseek(f, 0, SEEK_END);
long pos = ftell(f);
fseek(f, 0, SEEK_SET);
if (pos >= MAX_CONF_SIZE) {
FATAL("Too large config file.");
}
buf = ss_malloc(pos + 1);
if (buf == NULL) {
FATAL("No enough memory.");
}
int nread = fread(buf, pos, 1, f);
if (!nread) {
FATAL("Failed to read the config file.");
}
fclose(f);
buf[pos] = '\0'; // end of string
json_settings settings = { 0UL, 0, NULL, NULL, NULL };
char error_buf[512];
obj = json_parse_ex(&settings, buf, pos, error_buf);
if (obj == NULL) {
FATAL(error_buf);
}
if (obj->type == json_object) {
unsigned int i, j;
for (i = 0; i < obj->u.object.length; i++) {
char *name = obj->u.object.values[i].name;
json_value *value = obj->u.object.values[i].value;
int match = 1;
// Legacy server config format
if (conf.conf_ver == CONF_VER_LEGACY) {
if (strcmp(name, "server") == 0) {
if (value->type == json_array) {
for (j = 0; j < value->u.array.length; j++) {
if (j >= MAX_REMOTE_NUM) {
break;
}
json_value *v = value->u.array.values[j];
char *addr_str = to_string(v);
parse_addr(addr_str, conf.server_legacy.remote_addr + j);
ss_free(addr_str);
conf.server_legacy.remote_num = j + 1;
}
} else if (value->type == json_string) {
conf.server_legacy.remote_addr[0].host = to_string(value);
conf.server_legacy.remote_addr[0].port = NULL;
conf.server_legacy.remote_num = 1;
}
} else if (strcmp(name, "port_password") == 0) {
if (value->type == json_object) {
for (j = 0; j < value->u.object.length; j++) {
if (j >= MAX_PORT_NUM) {
break;
}
json_value *v = value->u.object.values[j].value;
if (v->type == json_string) {
conf.server_legacy.port_password[j].port = ss_strndup(value->u.object.values[j].name,
value->u.object.values[j].name_length);
conf.server_legacy.port_password[j].password = to_string(v);
conf.server_legacy.port_password_num = j + 1;
}
}
}
} else if (strcmp(name, "server_port") == 0) {
conf.server_legacy.remote_port = to_string(value);
} else if (strcmp(name, "local_address") == 0) {
conf.server_legacy.local_addr = to_string(value);
} else if (strcmp(name, "local_port") == 0) {
conf.server_legacy.local_port = to_string(value);
} else if (strcmp(name, "password") == 0) {
conf.server_legacy.password = to_string(value);
} else if (strcmp(name, "auth") == 0) {
LOGI("auth is deprecated, ignored");
} else if (strcmp(name, "protocol") == 0) { // SSR
conf.server_legacy.protocol = to_string(value);
} else if (strcmp(name, "protocol_param") == 0) { //SSR
conf.server_legacy.protocol_param = to_string(value);
} else if (strcmp(name, "method") == 0) {
conf.server_legacy.method = to_string(value);
} else if (strcmp(name, "obfs") == 0) { // SSR
conf.server_legacy.obfs = to_string(value);
} else if (strcmp(name, "obfs_param") == 0) { // SSR
conf.server_legacy.obfs_param = to_string(value);
} else {
match = 0;
}
}
if (!match) {
if(strcmp(name, "servers") == 0) {
if(conf.conf_ver == CONF_VER_LEGACY) {
memset(&conf.server_new_1, 0, sizeof(conf.server_new_1));
conf.conf_ver = CONF_VER_1;
}
if (value->type == json_array) {
for (j = 0; j < value->u.array.length; j++) {
if (conf.server_new_1.server_num >= MAX_SERVER_NUM) {
LOGI("Max servers exceed, ignore remain server defines.");
break;
}
json_value *v = value->u.array.values[j];
if(v->type == json_object) {
parse_ss_server(&conf.server_new_1.servers[conf.server_new_1.server_num], v);
conf.server_new_1.server_num++;
}
}
}
} else if (strcmp(name, "timeout") == 0) {
conf.timeout = to_string(value);
} else if (strcmp(name, "user") == 0) {
conf.user = to_string(value);
} else if (strcmp(name, "fast_open") == 0) {
check_json_value_type(value, json_boolean,
"invalid config file: option 'fast_open' must be a boolean");
conf.fast_open = value->u.boolean;
} else if (strcmp(name, "nofile") == 0) {
check_json_value_type(value, json_integer,
"invalid config file: option 'nofile' must be an integer");
conf.nofile = value->u.integer;
} else if (strcmp(name, "nameserver") == 0) {
conf.nameserver = to_string(value);
} else if (strcmp(name, "tunnel_address") == 0) {
conf.tunnel_address = to_string(value);
} else if (strcmp(name, "mode") == 0) {
char *mode_str = to_string(value);
if (strcmp(mode_str, "tcp_only") == 0)
conf.mode = TCP_ONLY;
else if (strcmp(mode_str, "tcp_and_udp") == 0)
conf.mode = TCP_AND_UDP;
else if (strcmp(mode_str, "udp_only") == 0)
conf.mode = UDP_ONLY;
else
LOGI("ignore unknown mode: %s, use tcp_only as fallback",
mode_str);
ss_free(mode_str);
} else if (strcmp(name, "mtu") == 0) {
check_json_value_type(value, json_integer,
"invalid config file: option 'mtu' must be an integer");
conf.mtu = value->u.integer;
} else if (strcmp(name, "mptcp") == 0) {
check_json_value_type(value, json_boolean,
"invalid config file: option 'mptcp' must be a boolean");
conf.mptcp = value->u.boolean;
} else if (strcmp(name, "ipv6_first") == 0) {
check_json_value_type(value, json_boolean,
"invalid config file: option 'ipv6_first' must be a boolean");
conf.ipv6_first = value->u.boolean;
}
}
}
} else {
FATAL("Invalid config file");
}
ss_free(buf);
json_value_free(obj);
return &conf;
}
void free_jconf(jconf_t *conf) {
int i;
if (!conf) {
return;
}
ss_free(conf->timeout);
ss_free(conf->user);
ss_free(conf->nameserver);
ss_free(conf->tunnel_address);
if(conf->conf_ver == CONF_VER_LEGACY){
ss_server_legacy_t *legacy = &conf->server_legacy;
for(i = 0; i < legacy->remote_num; i++){
free_addr(&legacy->remote_addr[i]);
}
for(i = 0; i < legacy->port_password_num; i++){
ss_free(legacy->port_password[i].port);
ss_free(legacy->port_password[i].password);
}
ss_free(legacy->remote_port);
ss_free(legacy->local_addr);
ss_free(legacy->local_port);
ss_free(legacy->password);
ss_free(legacy->protocol);
ss_free(legacy->protocol_param);
ss_free(legacy->method);
ss_free(legacy->obfs);
ss_free(legacy->obfs_param);
} else {
ss_server_new_1_t *ss_server_new_1 = &conf->server_new_1;
for(i = 0; i < ss_server_new_1->server_num; i++){
ss_server_t *serv = &ss_server_new_1->servers[i];
ss_free(serv->server);
ss_free(serv->password);
ss_free(serv->method);
ss_free(serv->protocol);
ss_free(serv->protocol_param);
ss_free(serv->obfs);
ss_free(serv->obfs_param);
ss_free(serv->id);
ss_free(serv->group);
}
}
}
|
281677160/openwrt-package | 2,761 | luci-app-ssr-plus/shadowsocksr-libev/src/src/jconf.h | /*
* jconf.h - Define the config data structure
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _JCONF_H
#define _JCONF_H
#define MAX_PORT_NUM 1024
#define MAX_REMOTE_NUM 10
#define MAX_SERVER_NUM 10
#define MAX_CONF_SIZE 128 * 1024
#define MAX_DNS_NUM 4
#define MAX_CONNECT_TIMEOUT 10
#define MAX_REQUEST_TIMEOUT 60
#define MIN_UDP_TIMEOUT 10
#define TCP_ONLY 0
#define TCP_AND_UDP 1
#define UDP_ONLY 3
typedef struct {
char *host;
char *port;
} ss_addr_t;
typedef struct {
char *port;
char *password;
} ss_port_password_t;
typedef struct {
// address from input (cmd or config file)
char *server;
int server_port;
int server_udp_port;
char *password; // raw password
char *method;
char *protocol;
char *protocol_param;
char *obfs;
char *obfs_param;
char *id;
char *group;
int enable;
int udp_over_tcp;
} ss_server_t;
typedef struct {
int remote_num;
ss_addr_t remote_addr[MAX_REMOTE_NUM];
int port_password_num;
ss_port_password_t port_password[MAX_PORT_NUM];
char *remote_port;
char *local_addr;
char *local_port;
char *password;
char *protocol; // SSR
char *protocol_param; // SSR
char *method;
char *obfs; // SSR
char *obfs_param; // SSR
} ss_server_legacy_t;
typedef struct {
size_t server_num;
ss_server_t servers[MAX_SERVER_NUM];
} ss_server_new_1_t;
#define CONF_VER_LEGACY 0
#define CONF_VER_1 1
typedef struct {
int conf_ver; // 0 for legacy, > 0 for server_new_X
union {
ss_server_legacy_t server_legacy;
ss_server_new_1_t server_new_1;
};
char *timeout;
char *user;
int fast_open;
int nofile;
char *nameserver;
char *tunnel_address;
int mode;
int mtu;
int mptcp;
int ipv6_first;
} jconf_t;
jconf_t *read_jconf(const char *file);
void free_jconf(jconf_t *conf);
void parse_addr(const char *str, ss_addr_t *addr);
void free_addr(ss_addr_t *addr);
#endif // _JCONF_H
|
281677160/openwrt-package | 16,230 | luci-app-ssr-plus/shadowsocksr-libev/src/src/acl.c | /*
* acl.c - Manage the ACL (Access Control List)
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <ipset/ipset.h>
#include <ctype.h>
#include "rule.h"
#include "utils.h"
#include "cache.h"
#include "acl.h"
/*
* definition:
* white list: you can connect directly
* black list: you have to connect via proxy, or which has been blocked
*/
static struct ip_set white_list_ipv4;
static struct ip_set white_list_ipv6;
static struct ip_set black_list_ipv4;
static struct ip_set black_list_ipv6;
static struct cork_dllist black_list_rules;
static struct cork_dllist white_list_rules;
static int acl_mode = BLACK_LIST;
static struct cache *block_list;
static struct ip_set outbound_block_list_ipv4;
static struct ip_set outbound_block_list_ipv6;
static struct cork_dllist outbound_block_list_rules;
#ifdef __linux__
#include <unistd.h>
#include <stdio.h>
#define NO_FIREWALL_MODE 0
#define IPTABLES_MODE 1
#define FIREWALLD_MODE 2
static FILE *shell_stdin;
static int mode = NO_FIREWALL_MODE;
static char chain_name[64];
static char *iptables_init_chain =
"iptables -N %s; iptables -F %s; iptables -A OUTPUT -p tcp --tcp-flags RST RST -j %s";
static char *iptables_remove_chain =
"iptables -D OUTPUT -p tcp --tcp-flags RST RST -j %s; iptables -F %s; iptables -X %s";
static char *iptables_add_rule = "iptables -A %s -d %s -j DROP";
static char *iptables_remove_rule = "iptables -D %s -d %s -j DROP";
static char *ip6tables_init_chain =
"ip6tables -N %s; ip6tables -F %s; ip6tables -A OUTPUT -p tcp --tcp-flags RST RST -j %s";
static char *ip6tables_remove_chain =
"ip6tables -D OUTPUT -p tcp --tcp-flags RST RST -j %s; ip6tables -F %s; ip6tables -X %s";
static char *ip6tables_add_rule = "ip6tables -A %s -d %s -j DROP";
static char *ip6tables_remove_rule = "ip6tables -D %s -d %s -j DROP";
static char *firewalld_init_chain =
"firewall-cmd --direct --add-chain ipv4 filter %s; \
firewall-cmd --direct --passthrough ipv4 -F %s; \
firewall-cmd --direct --passthrough ipv4 -A OUTPUT -p tcp --tcp-flags RST RST -j %s";
static char *firewalld_remove_chain =
"firewall-cmd --direct --passthrough ipv4 -D OUTPUT -p tcp --tcp-flags RST RST -j %s; \
firewall-cmd --direct --passthrough ipv4 -F %s; \
firewall-cmd --direct --remove-chain ipv4 filter %s";
static char *firewalld_add_rule = "firewall-cmd --direct --passthrough ipv4 -A %s -d %s -j DROP";
static char *firewalld_remove_rule = "firewall-cmd --direct --passthrough ipv4 -D %s -d %s -j DROP";
static char *firewalld6_init_chain =
"firewall-cmd --direct --add-chain ipv6 filter %s; \
firewall-cmd --direct --passthrough ipv6 -F %s; \
firewall-cmd --direct --passthrough ipv6 -A OUTPUT -p tcp --tcp-flags RST RST -j %s";
static char *firewalld6_remove_chain =
"firewall-cmd --direct --passthrough ipv6 -D OUTPUT -p tcp --tcp-flags RST RST -j %s; \
firewall-cmd --direct --passthrough ipv6 -F %s; \
firewall-cmd --direct --remove-chain ipv6 filter %s";
static char *firewalld6_add_rule = "firewall-cmd --direct --passthrough ipv6 -A %s -d %s -j DROP";
static char *firewalld6_remove_rule = "firewall-cmd --direct --passthrough ipv6 -D %s -d %s -j DROP";
static int
run_cmd(const char *cmd)
{
int ret = 0;
char cmdstring[256];
sprintf(cmdstring, "%s\n", cmd);
size_t len = strlen(cmdstring);
if (shell_stdin != NULL) {
ret = fwrite(cmdstring, 1, len, shell_stdin);
fflush(shell_stdin);
}
return ret == len;
}
static int
init_firewall()
{
int ret = 0;
char cli[256];
FILE *fp;
if (getuid() != 0)
return -1;
sprintf(cli, "firewall-cmd --version 2>&1");
fp = popen(cli, "r");
if (fp == NULL)
return -1;
if (pclose(fp) == 0) {
mode = FIREWALLD_MODE;
} else {
/* Check whether we have permission to operate iptables.
* Note that checking `iptables --version` is insufficient:
* eg, running within a child user namespace.
*/
sprintf(cli, "iptables -L 2>&1");
fp = popen(cli, "r");
if (fp == NULL)
return -1;
if (pclose(fp) == 0)
mode = IPTABLES_MODE;
}
sprintf(chain_name, "SHADOWSOCKS_LIBEV_%d", getpid());
if (mode == FIREWALLD_MODE) {
sprintf(cli, firewalld6_init_chain, chain_name, chain_name, chain_name);
ret |= system(cli);
sprintf(cli, firewalld_init_chain, chain_name, chain_name, chain_name);
ret |= system(cli);
} else if (mode == IPTABLES_MODE) {
sprintf(cli, ip6tables_init_chain, chain_name, chain_name, chain_name);
ret |= system(cli);
sprintf(cli, iptables_init_chain, chain_name, chain_name, chain_name);
ret |= system(cli);
}
shell_stdin = popen("/bin/sh", "w");
return ret;
}
static int
reset_firewall()
{
int ret = 0;
char cli[256];
if (getuid() != 0)
return -1;
if (mode == IPTABLES_MODE) {
sprintf(cli, ip6tables_remove_chain, chain_name, chain_name, chain_name);
ret |= system(cli);
sprintf(cli, iptables_remove_chain, chain_name, chain_name, chain_name);
ret |= system(cli);
} else if (mode == FIREWALLD_MODE) {
sprintf(cli, firewalld6_remove_chain, chain_name, chain_name, chain_name);
ret |= system(cli);
sprintf(cli, firewalld_remove_chain, chain_name, chain_name, chain_name);
ret |= system(cli);
}
if (shell_stdin != NULL) {
run_cmd("exit 0");
pclose(shell_stdin);
}
return ret;
}
static int
set_firewall_rule(char *addr, int add)
{
char cli[256];
struct cork_ip ip;
if (getuid() != 0)
return -1;
if (cork_ip_init(&ip, addr))
return -1;
if (add) {
if (mode == IPTABLES_MODE)
sprintf(cli, ip.version == 4 ? iptables_add_rule : ip6tables_add_rule,
chain_name, addr);
else if (mode == FIREWALLD_MODE)
sprintf(cli, ip.version == 4 ? firewalld_add_rule : firewalld6_add_rule,
chain_name, addr);
return run_cmd(cli);
} else {
if (mode == IPTABLES_MODE)
sprintf(cli, ip.version == 4 ? iptables_remove_rule : ip6tables_remove_rule,
chain_name, addr);
else if (mode == FIREWALLD_MODE)
sprintf(cli, ip.version == 4 ? firewalld_remove_rule : firewalld6_remove_rule,
chain_name, addr);
return run_cmd(cli);
}
return 0;
}
static void
free_firewall_rule(void *key, void *element)
{
if (key == NULL)
return;
char *addr = (char *)key;
set_firewall_rule(addr, 0);
ss_free(element);
}
#endif
void
init_block_list(int firewall)
{
// Initialize cache
#ifdef __linux__
if (firewall)
init_firewall();
else
mode = NO_FIREWALL_MODE;
cache_create(&block_list, 256, free_firewall_rule);
#else
cache_create(&block_list, 256, NULL);
#endif
}
void
free_block_list()
{
#ifdef __linux__
if (mode != NO_FIREWALL_MODE)
reset_firewall();
#endif
cache_clear(block_list, 0); // Remove all items
}
int
remove_from_block_list(char *addr)
{
size_t addr_len = strlen(addr);
return cache_remove(block_list, addr, addr_len);
}
void
clear_block_list()
{
cache_clear(block_list, 3600); // Clear items older than 1 hour
}
int
check_block_list(char *addr)
{
size_t addr_len = strlen(addr);
if (cache_key_exist(block_list, addr, addr_len)) {
int *count = NULL;
cache_lookup(block_list, addr, addr_len, &count);
if (count != NULL && *count > MAX_TRIES)
return 1;
}
return 0;
}
int
update_block_list(char *addr, int err_level)
{
size_t addr_len = strlen(addr);
if (cache_key_exist(block_list, addr, addr_len)) {
int *count = NULL;
cache_lookup(block_list, addr, addr_len, &count);
if (count != NULL) {
if (*count > MAX_TRIES)
return 1;
(*count) += err_level;
}
} else if (err_level > 0) {
int *count = (int *)ss_malloc(sizeof(int));
*count = 1;
cache_insert(block_list, addr, addr_len, count);
#ifdef __linux__
if (mode != NO_FIREWALL_MODE)
set_firewall_rule(addr, 1);
#endif
}
return 0;
}
static void
parse_addr_cidr(const char *str, char *host, int *cidr)
{
int ret = -1, n = 0;
char *pch;
pch = strchr(str, '/');
while (pch != NULL) {
n++;
ret = pch - str;
pch = strchr(pch + 1, '/');
}
if (ret == -1) {
strcpy(host, str);
*cidr = -1;
} else {
memcpy(host, str, ret);
host[ret] = '\0';
*cidr = atoi(str + ret + 1);
}
}
char *
trimwhitespace(char *str)
{
char *end;
// Trim leading space
while (isspace(*str))
str++;
if (*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while (end > str && isspace(*end))
end--;
// Write new null terminator
*(end + 1) = 0;
return str;
}
int
init_acl(const char *path)
{
// initialize ipset
ipset_init_library();
ipset_init(&white_list_ipv4);
ipset_init(&white_list_ipv6);
ipset_init(&black_list_ipv4);
ipset_init(&black_list_ipv6);
ipset_init(&outbound_block_list_ipv4);
ipset_init(&outbound_block_list_ipv6);
cork_dllist_init(&black_list_rules);
cork_dllist_init(&white_list_rules);
cork_dllist_init(&outbound_block_list_rules);
struct ip_set *list_ipv4 = &black_list_ipv4;
struct ip_set *list_ipv6 = &black_list_ipv6;
struct cork_dllist *rules = &black_list_rules;
FILE *f = fopen(path, "r");
if (f == NULL) {
LOGE("Invalid acl path.");
return -1;
}
char buf[257];
while (!feof(f))
if (fgets(buf, 256, f)) {
// Trim the newline
int len = strlen(buf);
if (len > 0 && buf[len - 1] == '\n') {
buf[len - 1] = '\0';
}
char *comment = strchr(buf, '#');
if (comment) {
*comment = '\0';
}
char *line = trimwhitespace(buf);
if (strlen(line) == 0) {
continue;
}
if (strcmp(line, "[outbound_block_list]") == 0) {
list_ipv4 = &outbound_block_list_ipv4;
list_ipv6 = &outbound_block_list_ipv6;
rules = &outbound_block_list_rules;
continue;
} else if (strcmp(line, "[white_list]") == 0
|| strcmp(line, "[proxy_list]") == 0) {
list_ipv4 = &black_list_ipv4;
list_ipv6 = &black_list_ipv6;
rules = &black_list_rules;
continue;
} else if (strcmp(line, "[black_list]") == 0
|| strcmp(line, "[bypass_list]") == 0) {
list_ipv4 = &white_list_ipv4;
list_ipv6 = &white_list_ipv6;
rules = &white_list_rules;
continue;
} else if (strcmp(line, "[reject_all]") == 0
|| strcmp(line, "[bypass_all]") == 0) {
acl_mode = BLACK_LIST;
continue;
} else if (strcmp(line, "[accept_all]") == 0
|| strcmp(line, "[proxy_all]") == 0) {
acl_mode = WHITE_LIST;
continue;
} else if (strcmp(line, "[remote_dns]") == 0) {
continue;
}
char host[257];
int cidr;
parse_addr_cidr(line, host, &cidr);
struct cork_ip addr;
int err = cork_ip_init(&addr, host);
if (!err) {
if (addr.version == 4) {
if (cidr >= 0) {
ipset_ipv4_add_network(list_ipv4, &(addr.ip.v4), cidr);
} else {
ipset_ipv4_add(list_ipv4, &(addr.ip.v4));
}
} else if (addr.version == 6) {
if (cidr >= 0) {
ipset_ipv6_add_network(list_ipv6, &(addr.ip.v6), cidr);
} else {
ipset_ipv6_add(list_ipv6, &(addr.ip.v6));
}
}
} else {
rule_t *rule = new_rule();
accept_rule_arg(rule, line);
init_rule(rule);
add_rule(rules, rule);
}
}
fclose(f);
return 0;
}
void
free_rules(struct cork_dllist *rules)
{
struct cork_dllist_item *iter;
while ((iter = cork_dllist_head(rules)) != NULL) {
rule_t *rule = cork_container_of(iter, rule_t, entries);
remove_rule(rule);
}
}
void
free_acl(void)
{
ipset_done(&black_list_ipv4);
ipset_done(&black_list_ipv6);
ipset_done(&white_list_ipv4);
ipset_done(&white_list_ipv6);
free_rules(&black_list_rules);
free_rules(&white_list_rules);
}
int
get_acl_mode(void)
{
return acl_mode;
}
/*
* Return 0, if not match.
* Return 1, if match black list.
* Return -1, if match white list.
*/
int
acl_match_host(const char *host)
{
struct cork_ip addr;
int ret = 0;
int err = cork_ip_init(&addr, host);
if (err) {
int host_len = strlen(host);
if (lookup_rule(&black_list_rules, host, host_len) != NULL)
ret = 1;
else if (lookup_rule(&white_list_rules, host, host_len) != NULL)
ret = -1;
return ret;
}
if (addr.version == 4) {
if (ipset_contains_ipv4(&black_list_ipv4, &(addr.ip.v4)))
ret = 1;
else if (ipset_contains_ipv4(&white_list_ipv4, &(addr.ip.v4)))
ret = -1;
} else if (addr.version == 6) {
if (ipset_contains_ipv6(&black_list_ipv6, &(addr.ip.v6)))
ret = 1;
else if (ipset_contains_ipv6(&white_list_ipv6, &(addr.ip.v6)))
ret = -1;
}
return ret;
}
int
acl_add_ip(const char *ip)
{
struct cork_ip addr;
int err = cork_ip_init(&addr, ip);
if (err) {
return -1;
}
if (addr.version == 4) {
ipset_ipv4_add(&black_list_ipv4, &(addr.ip.v4));
} else if (addr.version == 6) {
ipset_ipv6_add(&black_list_ipv6, &(addr.ip.v6));
}
return 0;
}
int
acl_remove_ip(const char *ip)
{
struct cork_ip addr;
int err = cork_ip_init(&addr, ip);
if (err) {
return -1;
}
if (addr.version == 4) {
ipset_ipv4_remove(&black_list_ipv4, &(addr.ip.v4));
} else if (addr.version == 6) {
ipset_ipv6_remove(&black_list_ipv6, &(addr.ip.v6));
}
return 0;
}
/*
* Return 0, if not match.
* Return 1, if match black list.
*/
int
outbound_block_match_host(const char *host)
{
struct cork_ip addr;
int ret = 0;
int err = cork_ip_init(&addr, host);
if (err) {
int host_len = strlen(host);
if (lookup_rule(&outbound_block_list_rules, host, host_len) != NULL)
ret = 1;
return ret;
}
if (addr.version == 4) {
if (ipset_contains_ipv4(&outbound_block_list_ipv4, &(addr.ip.v4)))
ret = 1;
} else if (addr.version == 6) {
if (ipset_contains_ipv6(&outbound_block_list_ipv6, &(addr.ip.v6)))
ret = 1;
}
return ret;
}
|
281677160/openwrt-package | 7,668 | luci-app-ssr-plus/shadowsocksr-libev/src/src/tls.c | /*
* Copyright (c) 2011 and 2012, Dustin Lundquist <dustin@null-ptr.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This is a minimal TLS implementation intended only to parse the server name
* extension. This was created based primarily on Wireshark dissection of a
* TLS handshake and RFC4366.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h> /* malloc() */
#include <string.h> /* strncpy() */
#ifndef __MINGW32__
#include <sys/socket.h>
#else
#include "win32.h"
#endif
#include "tls.h"
#include "protocol.h"
#include "utils.h"
#define SERVER_NAME_LEN 256
#define TLS_HEADER_LEN 5
#define TLS_HANDSHAKE_CONTENT_TYPE 0x16
#define TLS_HANDSHAKE_TYPE_CLIENT_HELLO 0x01
#ifndef MIN
#define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
#endif
extern int verbose;
static int parse_tls_header(const char *, size_t, char **);
static int parse_extensions(const char *, size_t, char **);
static int parse_server_name_extension(const char *, size_t, char **);
static const protocol_t tls_protocol_st = {
.default_port = 443,
.parse_packet = &parse_tls_header,
};
const protocol_t *const tls_protocol = &tls_protocol_st;
/* Parse a TLS packet for the Server Name Indication extension in the client
* hello handshake, returning the first servername found (pointer to static
* array)
*
* Returns:
* >=0 - length of the hostname and updates *hostname
* caller is responsible for freeing *hostname
* -1 - Incomplete request
* -2 - No Host header included in this request
* -3 - Invalid hostname pointer
* -4 - malloc failure
* < -4 - Invalid TLS client hello
*/
static int
parse_tls_header(const char *data, size_t data_len, char **hostname)
{
char tls_content_type;
char tls_version_major;
char tls_version_minor;
size_t pos = TLS_HEADER_LEN;
size_t len;
if (hostname == NULL)
return -3;
/* Check that our TCP payload is at least large enough for a TLS header */
if (data_len < TLS_HEADER_LEN)
return -1;
/* SSL 2.0 compatible Client Hello
*
* High bit of first byte (length) and content type is Client Hello
*
* See RFC5246 Appendix E.2
*/
if (data[0] & 0x80 && data[2] == 1) {
if (verbose)
LOGI("Received SSL 2.0 Client Hello which can not support SNI.");
return -2;
}
tls_content_type = data[0];
if (tls_content_type != TLS_HANDSHAKE_CONTENT_TYPE) {
if (verbose)
LOGI("Request did not begin with TLS handshake.");
return -5;
}
tls_version_major = data[1];
tls_version_minor = data[2];
if (tls_version_major < 3) {
if (verbose)
LOGI("Received SSL %d.%d handshake which can not support SNI.",
tls_version_major, tls_version_minor);
return -2;
}
/* TLS record length */
len = ((unsigned char)data[3] << 8) +
(unsigned char)data[4] + TLS_HEADER_LEN;
data_len = MIN(data_len, len);
/* Check we received entire TLS record length */
if (data_len < len)
return -1;
/*
* Handshake
*/
if (pos + 1 > data_len) {
return -5;
}
if (data[pos] != TLS_HANDSHAKE_TYPE_CLIENT_HELLO) {
if (verbose)
LOGI("Not a client hello");
return -5;
}
/* Skip past fixed length records:
* 1 Handshake Type
* 3 Length
* 2 Version (again)
* 32 Random
* to Session ID Length
*/
pos += 38;
/* Session ID */
if (pos + 1 > data_len)
return -5;
len = (unsigned char)data[pos];
pos += 1 + len;
/* Cipher Suites */
if (pos + 2 > data_len)
return -5;
len = ((unsigned char)data[pos] << 8) + (unsigned char)data[pos + 1];
pos += 2 + len;
/* Compression Methods */
if (pos + 1 > data_len)
return -5;
len = (unsigned char)data[pos];
pos += 1 + len;
if (pos == data_len && tls_version_major == 3 && tls_version_minor == 0) {
if (verbose)
LOGI("Received SSL 3.0 handshake without extensions");
return -2;
}
/* Extensions */
if (pos + 2 > data_len)
return -5;
len = ((unsigned char)data[pos] << 8) + (unsigned char)data[pos + 1];
pos += 2;
if (pos + len > data_len)
return -5;
return parse_extensions(data + pos, len, hostname);
}
static int
parse_extensions(const char *data, size_t data_len, char **hostname)
{
size_t pos = 0;
size_t len;
/* Parse each 4 bytes for the extension header */
while (pos + 4 <= data_len) {
/* Extension Length */
len = ((unsigned char)data[pos + 2] << 8) +
(unsigned char)data[pos + 3];
/* Check if it's a server name extension */
if (data[pos] == 0x00 && data[pos + 1] == 0x00) {
/* There can be only one extension of each type, so we break
* our state and move p to beinnging of the extension here */
if (pos + 4 + len > data_len)
return -5;
return parse_server_name_extension(data + pos + 4, len, hostname);
}
pos += 4 + len; /* Advance to the next extension header */
}
/* Check we ended where we expected to */
if (pos != data_len)
return -5;
return -2;
}
static int
parse_server_name_extension(const char *data, size_t data_len,
char **hostname)
{
size_t pos = 2; /* skip server name list length */
size_t len;
while (pos + 3 < data_len) {
len = ((unsigned char)data[pos + 1] << 8) +
(unsigned char)data[pos + 2];
if (pos + 3 + len > data_len)
return -5;
switch (data[pos]) { /* name type */
case 0x00: /* host_name */
*hostname = malloc(len + 1);
if (*hostname == NULL) {
ERROR("malloc() failure");
return -4;
}
strncpy(*hostname, data + pos + 3, len);
(*hostname)[len] = '\0';
return len;
default:
if (verbose)
LOGI("Unknown server name extension name type: %d",
data[pos]);
}
pos += 3 + len;
}
/* Check we ended where we expected to */
if (pos != data_len)
return -5;
return -2;
}
|
281677160/openwrt-package | 41,457 | luci-app-ssr-plus/shadowsocksr-libev/src/src/encrypt.c | /*
* encrypt.c - Manage the global encryptor
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if defined(USE_CRYPTO_OPENSSL)
#include <openssl/md5.h>
#include <openssl/rand.h>
#include <openssl/hmac.h>
#include <openssl/aes.h>
#elif defined(USE_CRYPTO_POLARSSL)
#include <polarssl/md5.h>
#include <polarssl/sha1.h>
#include <polarssl/aes.h>
#include <polarssl/entropy.h>
#include <polarssl/ctr_drbg.h>
#include <polarssl/version.h>
#define CIPHER_UNSUPPORTED "unsupported"
#ifdef __MINGW32__
#include "winsock2.h"
#endif
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#include <wincrypt.h>
#else
#include <stdio.h>
#endif
#elif defined(USE_CRYPTO_MBEDTLS)
#include <mbedtls/md5.h>
#include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/version.h>
#include <mbedtls/aes.h>
#define CIPHER_UNSUPPORTED "unsupported"
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#include <wincrypt.h>
#else
#include <stdio.h>
#endif
#endif
#include <sodium.h>
#ifndef __MINGW32__
#include <arpa/inet.h>
#endif
#include "cache.h"
#include "encrypt.h"
#include "utils.h"
#define OFFSET_ROL(p, o) ((uint64_t)(*(p + o)) << (8 * o))
#ifdef DEBUG
static void
dump(char *tag, char *text, int len)
{
int i;
printf("%s: ", tag);
for (i = 0; i < len; i++)
printf("0x%02x ", (uint8_t)text[i]);
printf("\n");
}
#endif
//cipher_env_t cipher_env;
static const char *supported_ciphers[CIPHER_NUM] = {
"none",
"table",
"rc4",
"rc4-md5-6",
"rc4-md5",
"aes-128-cfb",
"aes-192-cfb",
"aes-256-cfb",
"aes-128-ctr",
"aes-192-ctr",
"aes-256-ctr",
"bf-cfb",
"camellia-128-cfb",
"camellia-192-cfb",
"camellia-256-cfb",
"cast5-cfb",
"des-cfb",
"idea-cfb",
"rc2-cfb",
"seed-cfb",
"salsa20",
"chacha20",
"chacha20-ietf"
};
#ifdef USE_CRYPTO_POLARSSL
static const char *supported_ciphers_polarssl[CIPHER_NUM] = {
"none",
"table",
"ARC4-128",
"ARC4-128",
"ARC4-128",
"AES-128-CFB128",
"AES-192-CFB128",
"AES-256-CFB128",
"AES-128-CTR",
"AES-192-CTR",
"AES-256-CTR",
"BLOWFISH-CFB64",
"CAMELLIA-128-CFB128",
"CAMELLIA-192-CFB128",
"CAMELLIA-256-CFB128",
CIPHER_UNSUPPORTED,
CIPHER_UNSUPPORTED,
CIPHER_UNSUPPORTED,
CIPHER_UNSUPPORTED,
CIPHER_UNSUPPORTED,
"salsa20",
"chacha20",
"chacha20-ietf"
};
#endif
#ifdef USE_CRYPTO_MBEDTLS
static const char *supported_ciphers_mbedtls[CIPHER_NUM] = {
"none",
"table",
"ARC4-128",
"ARC4-128",
"ARC4-128",
"AES-128-CFB128",
"AES-192-CFB128",
"AES-256-CFB128",
"AES-128-CTR",
"AES-192-CTR",
"AES-256-CTR",
"BLOWFISH-CFB64",
"CAMELLIA-128-CFB128",
"CAMELLIA-192-CFB128",
"CAMELLIA-256-CFB128",
CIPHER_UNSUPPORTED,
CIPHER_UNSUPPORTED,
CIPHER_UNSUPPORTED,
CIPHER_UNSUPPORTED,
CIPHER_UNSUPPORTED,
"salsa20",
"chacha20",
"chacha20-ietf"
};
#endif
#ifdef USE_CRYPTO_APPLECC
static const CCAlgorithm supported_ciphers_applecc[CIPHER_NUM] = {
kCCAlgorithmInvalid,
kCCAlgorithmInvalid,
kCCAlgorithmRC4,
kCCAlgorithmRC4,
kCCAlgorithmRC4,
kCCAlgorithmAES,
kCCAlgorithmAES,
kCCAlgorithmAES,
kCCAlgorithmAES,
kCCAlgorithmAES,
kCCAlgorithmAES,
kCCAlgorithmBlowfish,
kCCAlgorithmInvalid,
kCCAlgorithmInvalid,
kCCAlgorithmInvalid,
kCCAlgorithmCAST,
kCCAlgorithmDES,
kCCAlgorithmInvalid,
kCCAlgorithmRC2,
kCCAlgorithmInvalid,
kCCAlgorithmInvalid,
kCCAlgorithmInvalid,
kCCAlgorithmInvalid
};
static const CCMode supported_modes_applecc[CIPHER_NUM] = {
kCCAlgorithmInvalid,
kCCAlgorithmInvalid,
kCCAlgorithmInvalid,
kCCModeRC4,
kCCModeRC4,
kCCModeCFB,
kCCModeCFB,
kCCModeCFB,
kCCModeCTR,
kCCModeCTR,
kCCModeCTR,
kCCModeCFB,
kCCAlgorithmInvalid,
kCCAlgorithmInvalid,
kCCAlgorithmInvalid,
kCCModeCFB,
kCCModeCFB,
kCCModeCFB,
kCCModeCFB,
kCCAlgorithmInvalid,
kCCAlgorithmInvalid,
kCCAlgorithmInvalid,
kCCAlgorithmInvalid
};
#endif
static const int supported_ciphers_iv_size[CIPHER_NUM] = {
0 , 0, 0, 6, 16, 16, 16, 16, 16, 16, 16, 8, 16, 16, 16, 8, 8, 8, 8, 16, 8, 8, 12
};
static const int supported_ciphers_key_size[CIPHER_NUM] = {
16, 16, 16, 16, 16, 16, 24, 32, 16, 24, 32, 16, 16, 24, 32, 16, 8, 16, 16, 16, 32, 32, 32
};
int
balloc(buffer_t *ptr, size_t capacity)
{
sodium_memzero(ptr, sizeof(buffer_t));
ptr->array = ss_malloc(capacity);
ptr->capacity = capacity;
return capacity;
}
int
brealloc(buffer_t *ptr, size_t len, size_t capacity)
{
if (ptr == NULL)
return -1;
size_t real_capacity = max(len, capacity);
if (ptr->capacity < real_capacity) {
ptr->array = ss_realloc(ptr->array, real_capacity);
ptr->capacity = real_capacity;
}
return real_capacity;
}
void
bfree(buffer_t *ptr)
{
if (ptr == NULL)
return;
ptr->idx = 0;
ptr->len = 0;
ptr->capacity = 0;
if (ptr->array != NULL) {
ss_free(ptr->array);
}
}
static int
crypto_stream_xor_ic(uint8_t *c, const uint8_t *m, uint64_t mlen,
const uint8_t *n, uint64_t ic, const uint8_t *k,
int method)
{
switch (method) {
case SALSA20:
return crypto_stream_salsa20_xor_ic(c, m, mlen, n, ic, k);
case CHACHA20:
return crypto_stream_chacha20_xor_ic(c, m, mlen, n, ic, k);
case CHACHA20IETF:
return crypto_stream_chacha20_ietf_xor_ic(c, m, mlen, n, (uint32_t)ic, k);
}
// always return 0
return 0;
}
static int
random_compare(const void *_x, const void *_y, uint32_t i,
uint64_t a)
{
uint8_t x = *((uint8_t *)_x);
uint8_t y = *((uint8_t *)_y);
return a % (x + i) - a % (y + i);
}
static void
merge(uint8_t *left, int llength, uint8_t *right,
int rlength, uint32_t salt, uint64_t key)
{
uint8_t *ltmp = (uint8_t *)malloc(llength * sizeof(uint8_t));
uint8_t *rtmp = (uint8_t *)malloc(rlength * sizeof(uint8_t));
uint8_t *ll = ltmp;
uint8_t *rr = rtmp;
uint8_t *result = left;
memcpy(ltmp, left, llength * sizeof(uint8_t));
memcpy(rtmp, right, rlength * sizeof(uint8_t));
while (llength > 0 && rlength > 0) {
if (random_compare(ll, rr, salt, key) <= 0) {
*result = *ll;
++ll;
--llength;
} else {
*result = *rr;
++rr;
--rlength;
}
++result;
}
if (llength > 0) {
while (llength > 0) {
*result = *ll;
++result;
++ll;
--llength;
}
} else {
while (rlength > 0) {
*result = *rr;
++result;
++rr;
--rlength;
}
}
ss_free(ltmp);
ss_free(rtmp);
}
static void
merge_sort(uint8_t array[], int length,
uint32_t salt, uint64_t key)
{
uint8_t middle;
uint8_t *left, *right;
int llength;
if (length <= 1) {
return;
}
middle = length / 2;
llength = length - middle;
left = array;
right = array + llength;
merge_sort(left, llength, salt, key);
merge_sort(right, middle, salt, key);
merge(left, llength, right, middle, salt, key);
}
int
enc_get_iv_len(cipher_env_t *env)
{
return env->enc_iv_len;
}
uint8_t* enc_get_key(cipher_env_t *env)
{
return env->enc_key;
}
int enc_get_key_len(cipher_env_t *env)
{
return env->enc_key_len;
}
unsigned char *enc_md5(const unsigned char *d, size_t n, unsigned char *md)
{
#if defined(USE_CRYPTO_OPENSSL)
return MD5(d, n, md);
#elif defined(USE_CRYPTO_POLARSSL)
static unsigned char m[16];
if (md == NULL) {
md = m;
}
md5(d, n, md);
return md;
#elif defined(USE_CRYPTO_MBEDTLS)
static unsigned char m[16];
if (md == NULL) {
md = m;
}
mbedtls_md5(d, n, md);
return md;
#endif
}
int
cipher_iv_size(const cipher_t *cipher)
{
#if defined(USE_CRYPTO_OPENSSL)
if (cipher->info == NULL)
return cipher->iv_len;
else
return EVP_CIPHER_iv_length(cipher->info);
#elif defined(USE_CRYPTO_POLARSSL) || defined(USE_CRYPTO_MBEDTLS)
if (cipher == NULL) {
return 0;
}
return cipher->info->iv_size;
#endif
}
int
cipher_key_size(const cipher_t *cipher)
{
#if defined(USE_CRYPTO_OPENSSL)
if (cipher->info == NULL)
return cipher->key_len;
else
return EVP_CIPHER_key_length(cipher->info);
#elif defined(USE_CRYPTO_POLARSSL)
if (cipher == NULL) {
return 0;
}
/* Override PolarSSL 32 bit default key size with sane 128 bit default */
if (cipher->info->base != NULL && POLARSSL_CIPHER_ID_BLOWFISH ==
cipher->info->base->cipher) {
return 128 / 8;
}
return cipher->info->key_length / 8;
#elif defined(USE_CRYPTO_MBEDTLS)
/*
* Semi-API changes (technically public, morally private)
* Renamed a few headers to include _internal in the name. Those headers are
* not supposed to be included by users.
* Changed md_info_t into an opaque structure (use md_get_xxx() accessors).
* Changed pk_info_t into an opaque structure.
* Changed cipher_base_t into an opaque structure.
*/
if (cipher == NULL) {
return 0;
}
/* From Version 1.2.7 released 2013-04-13 Default Blowfish keysize is now 128-bits */
return cipher->info->key_bitlen / 8;
#endif
}
void
bytes_to_key_with_size(const char *pass, size_t len, uint8_t *md, size_t md_size)
{
uint8_t result[128];
enc_md5((const unsigned char *)pass, len, result);
memcpy(md, result, 16);
int i = 16;
for (; i < md_size; i += 16) {
memcpy(result + 16, pass, len);
enc_md5(result, 16 + len, result);
memcpy(md + i, result, 16);
}
}
int
bytes_to_key(const cipher_t *cipher, const digest_type_t *md,
const uint8_t *pass, uint8_t *key)
{
size_t datal;
datal = strlen((const char *)pass);
#if defined(USE_CRYPTO_OPENSSL)
MD5_CTX c;
unsigned char md_buf[MAX_MD_SIZE];
int nkey;
int addmd;
unsigned int i, j, mds;
mds = 16;
nkey = 16;
if (cipher != NULL) {
nkey = cipher_key_size(cipher);
}
if (pass == NULL)
return nkey;
memset(&c, 0, sizeof(MD5_CTX));
for (j = 0, addmd = 0; j < nkey; addmd++) {
MD5_Init(&c);
if (addmd) {
MD5_Update(&c, md_buf, mds);
}
MD5_Update(&c, pass, datal);
MD5_Final(md_buf, &c);
for (i = 0; i < mds; i++, j++) {
if (j >= nkey)
break;
key[j] = md_buf[i];
}
}
return nkey;
#elif defined(USE_CRYPTO_POLARSSL)
md_context_t c;
unsigned char md_buf[MAX_MD_SIZE];
int nkey;
int addmd;
unsigned int i, j, mds;
nkey = 16;
if (cipher != NULL) {
nkey = cipher_key_size(cipher);
}
mds = md_get_size(md);
memset(&c, 0, sizeof(md_context_t));
if (pass == NULL)
return nkey;
if (md_init_ctx(&c, md))
return 0;
for (j = 0, addmd = 0; j < nkey; addmd++) {
md_starts(&c);
if (addmd) {
md_update(&c, md_buf, mds);
}
md_update(&c, pass, datal);
md_finish(&c, md_buf);
for (i = 0; i < mds; i++, j++) {
if (j >= nkey)
break;
key[j] = md_buf[i];
}
}
md_free_ctx(&c);
return nkey;
#elif defined(USE_CRYPTO_MBEDTLS)
mbedtls_md_context_t c;
unsigned char md_buf[MAX_MD_SIZE];
int nkey;
int addmd;
unsigned int i, j, mds;
nkey = 16;
if (cipher != NULL) {
nkey = cipher_key_size(cipher);
}
mds = mbedtls_md_get_size(md);
memset(&c, 0, sizeof(mbedtls_md_context_t));
if (pass == NULL)
return nkey;
if (mbedtls_md_setup(&c, md, 1))
return 0;
for (j = 0, addmd = 0; j < nkey; addmd++) {
mbedtls_md_starts(&c);
if (addmd) {
mbedtls_md_update(&c, md_buf, mds);
}
mbedtls_md_update(&c, pass, datal);
mbedtls_md_finish(&c, &(md_buf[0]));
for (i = 0; i < mds; i++, j++) {
if (j >= nkey)
break;
key[j] = md_buf[i];
}
}
mbedtls_md_free(&c);
return nkey;
#endif
}
int
rand_bytes(uint8_t *output, int len)
{
randombytes_buf(output, len);
// always return success
return 0;
}
const cipher_kt_t *
get_cipher_type(int method)
{
if (method < NONE || method >= CIPHER_NUM) {
LOGE("get_cipher_type(): Illegal method");
return NULL;
}
if (method == RC4_MD5 || method == RC4_MD5_6) {
method = RC4;
}
if (method >= SALSA20) {
return NULL;
}
const char *ciphername = supported_ciphers[method];
#if defined(USE_CRYPTO_OPENSSL)
return EVP_get_cipherbyname(ciphername);
#elif defined(USE_CRYPTO_POLARSSL)
const char *polarname = supported_ciphers_polarssl[method];
if (strcmp(polarname, CIPHER_UNSUPPORTED) == 0) {
LOGE("Cipher %s currently is not supported by PolarSSL library",
ciphername);
return NULL;
}
return cipher_info_from_string(polarname);
#elif defined(USE_CRYPTO_MBEDTLS)
const char *mbedtlsname = supported_ciphers_mbedtls[method];
if (strcmp(mbedtlsname, CIPHER_UNSUPPORTED) == 0) {
LOGE("Cipher %s currently is not supported by mbed TLS library",
ciphername);
return NULL;
}
return mbedtls_cipher_info_from_string(mbedtlsname);
#endif
}
const digest_type_t *
get_digest_type(const char *digest)
{
if (digest == NULL) {
LOGE("get_digest_type(): Digest name is null");
return NULL;
}
#if defined(USE_CRYPTO_OPENSSL)
return EVP_get_digestbyname(digest);
#elif defined(USE_CRYPTO_POLARSSL)
return md_info_from_string(digest);
#elif defined(USE_CRYPTO_MBEDTLS)
return mbedtls_md_info_from_string(digest);
#endif
}
void
cipher_context_init(cipher_env_t *env, cipher_ctx_t *ctx, int enc)
{
int method = env->enc_method;
if (method < NONE || method >= CIPHER_NUM) {
LOGE("cipher_context_init(): Illegal method");
return;
}
if (method >= SALSA20) {
// enc_iv_len = supported_ciphers_iv_size[method];
return;
}
const char *ciphername = supported_ciphers[method];
#if defined(USE_CRYPTO_APPLECC)
cipher_cc_t *cc = &ctx->cc;
cc->cryptor = NULL;
cc->cipher = supported_ciphers_applecc[method];
if (cc->cipher == kCCAlgorithmInvalid) {
cc->valid = kCCContextInvalid;
} else {
cc->valid = kCCContextValid;
if (cc->cipher == kCCAlgorithmRC4) {
cc->mode = supported_modes_applecc[method];
cc->padding = ccNoPadding;
} else {
cc->mode = supported_modes_applecc[method];
if (cc->mode == kCCModeCTR) {
cc->padding = ccNoPadding;
} else {
cc->padding = ccPKCS7Padding;
}
}
return;
}
#endif
const cipher_kt_t *cipher = get_cipher_type(method);
#if defined(USE_CRYPTO_OPENSSL)
ctx->evp = EVP_CIPHER_CTX_new();
cipher_evp_t *evp = ctx->evp;
if (cipher == NULL) {
LOGE("Cipher %s not found in OpenSSL library", ciphername);
FATAL("Cannot initialize cipher");
}
if (!EVP_CipherInit_ex(evp, cipher, NULL, NULL, NULL, enc)) {
LOGE("Cannot initialize cipher %s", ciphername);
exit(EXIT_FAILURE);
}
if (!EVP_CIPHER_CTX_set_key_length(evp, env->enc_key_len)) {
EVP_CIPHER_CTX_cleanup(evp);
LOGE("Invalid key length: %d", env->enc_key_len);
exit(EXIT_FAILURE);
}
if (method > RC4_MD5) {
EVP_CIPHER_CTX_set_padding(evp, 1);
}
#elif defined(USE_CRYPTO_POLARSSL)
ctx->evp = (cipher_evp_t *)ss_malloc(sizeof(cipher_evp_t));
cipher_evp_t *evp = ctx->evp;
if (cipher == NULL) {
LOGE("Cipher %s not found in PolarSSL library", ciphername);
FATAL("Cannot initialize PolarSSL cipher");
}
if (cipher_init_ctx(evp, cipher) != 0) {
FATAL("Cannot initialize PolarSSL cipher context");
}
#elif defined(USE_CRYPTO_MBEDTLS)
ctx->evp = ss_malloc(sizeof(cipher_evp_t));
memset(ctx->evp, 0, sizeof(cipher_evp_t));
cipher_evp_t *evp = ctx->evp;
if (cipher == NULL) {
LOGE("Cipher %s not found in mbed TLS library", ciphername);
FATAL("Cannot initialize mbed TLS cipher");
}
mbedtls_cipher_init(evp);
if (mbedtls_cipher_setup(evp, cipher) != 0) {
FATAL("Cannot initialize mbed TLS cipher context");
}
#endif
}
void
cipher_context_set_iv(cipher_env_t *env, cipher_ctx_t *ctx, uint8_t *iv, size_t iv_len,
int enc)
{
const unsigned char *true_key;
if (iv == NULL) {
LOGE("cipher_context_set_iv(): IV is null");
return;
}
if (!enc) {
memcpy(ctx->iv, iv, iv_len);
}
if (env->enc_method >= SALSA20) {
return;
}
if (env->enc_method == RC4_MD5 || env->enc_method == RC4_MD5_6) {
unsigned char key_iv[32];
memcpy(key_iv, env->enc_key, 16);
memcpy(key_iv + 16, iv, iv_len);
true_key = enc_md5(key_iv, 16 + iv_len, NULL);
iv_len = 0;
} else {
true_key = env->enc_key;
}
#ifdef USE_CRYPTO_APPLECC
cipher_cc_t *cc = &ctx->cc;
if (cc->valid == kCCContextValid) {
memcpy(cc->iv, iv, iv_len);
memcpy(cc->key, true_key, env->enc_key_len);
cc->iv_len = iv_len;
cc->key_len = env->enc_key_len;
cc->encrypt = enc ? kCCEncrypt : kCCDecrypt;
if (cc->cryptor != NULL) {
CCCryptorRelease(cc->cryptor);
cc->cryptor = NULL;
}
CCCryptorStatus ret;
ret = CCCryptorCreateWithMode(
cc->encrypt,
cc->mode,
cc->cipher,
cc->padding,
cc->iv, cc->key, cc->key_len,
NULL, 0, 0, kCCModeOptionCTR_BE,
&cc->cryptor);
if (ret != kCCSuccess) {
if (cc->cryptor != NULL) {
CCCryptorRelease(cc->cryptor);
cc->cryptor = NULL;
}
FATAL("Cannot set CommonCrypto key and IV");
}
return;
}
#endif
cipher_evp_t *evp = ctx->evp;
if (evp == NULL) {
LOGE("cipher_context_set_iv(): Cipher context is null");
return;
}
#if defined(USE_CRYPTO_OPENSSL)
if (!EVP_CipherInit_ex(evp, NULL, NULL, true_key, iv, enc)) {
EVP_CIPHER_CTX_cleanup(evp);
FATAL("Cannot set key and IV");
}
#elif defined(USE_CRYPTO_POLARSSL)
// XXX: PolarSSL 1.3.11: cipher_free_ctx deprecated, Use cipher_free() instead.
if (cipher_setkey(evp, true_key, env->enc_key_len * 8, enc) != 0) {
cipher_free_ctx(evp);
FATAL("Cannot set PolarSSL cipher key");
}
#if POLARSSL_VERSION_NUMBER >= 0x01030000
if (cipher_set_iv(evp, iv, iv_len) != 0) {
cipher_free_ctx(evp);
FATAL("Cannot set PolarSSL cipher IV");
}
if (cipher_reset(evp) != 0) {
cipher_free_ctx(evp);
FATAL("Cannot finalize PolarSSL cipher context");
}
#else
if (cipher_reset(evp, iv) != 0) {
cipher_free_ctx(evp);
FATAL("Cannot set PolarSSL cipher IV");
}
#endif
#elif defined(USE_CRYPTO_MBEDTLS)
if (mbedtls_cipher_setkey(evp, true_key, env->enc_key_len * 8, enc) != 0) {
mbedtls_cipher_free(evp);
FATAL("Cannot set mbed TLS cipher key");
}
if (mbedtls_cipher_set_iv(evp, iv, iv_len) != 0) {
mbedtls_cipher_free(evp);
FATAL("Cannot set mbed TLS cipher IV");
}
if (mbedtls_cipher_reset(evp) != 0) {
mbedtls_cipher_free(evp);
FATAL("Cannot finalize mbed TLS cipher context");
}
#endif
#ifdef DEBUG
dump("IV", (char *)iv, iv_len);
#endif
}
void
cipher_context_release(cipher_env_t *env, cipher_ctx_t *ctx)
{
if (env->enc_method >= SALSA20) {
return;
}
#ifdef USE_CRYPTO_APPLECC
cipher_cc_t *cc = &ctx->cc;
if (cc->cryptor != NULL) {
CCCryptorRelease(cc->cryptor);
cc->cryptor = NULL;
}
if (cc->valid == kCCContextValid) {
return;
}
#endif
#if defined(USE_CRYPTO_OPENSSL)
EVP_CIPHER_CTX_free(ctx->evp);
#elif defined(USE_CRYPTO_POLARSSL)
// NOTE: cipher_free_ctx deprecated in PolarSSL 1.3.11
cipher_free_ctx(ctx->evp);
ss_free(ctx->evp);
#elif defined(USE_CRYPTO_MBEDTLS)
// NOTE: cipher_free_ctx deprecated
mbedtls_cipher_free(ctx->evp);
ss_free(ctx->evp);
#endif
}
static int
cipher_context_update(cipher_ctx_t *ctx, uint8_t *output, size_t *olen,
const uint8_t *input, size_t ilen)
{
#ifdef USE_CRYPTO_APPLECC
cipher_cc_t *cc = &ctx->cc;
if (cc->valid == kCCContextValid) {
CCCryptorStatus ret;
ret = CCCryptorUpdate(cc->cryptor, input, ilen, output,
ilen, olen);
return (ret == kCCSuccess) ? 1 : 0;
}
#endif
cipher_evp_t *evp = ctx->evp;
#if defined(USE_CRYPTO_OPENSSL)
int err = 0, tlen = *olen;
err = EVP_CipherUpdate(evp, (uint8_t *)output, &tlen,
(const uint8_t *)input, ilen);
*olen = tlen;
return err;
#elif defined(USE_CRYPTO_POLARSSL)
return !cipher_update(evp, (const uint8_t *)input, ilen,
(uint8_t *)output, olen);
#elif defined(USE_CRYPTO_MBEDTLS)
return !mbedtls_cipher_update(evp, (const uint8_t *)input, ilen,
(uint8_t *)output, olen);
#endif
}
int ss_md5_hmac_with_key(char *auth, char *msg, int msg_len, uint8_t *auth_key, int key_len)
{
uint8_t hash[MD5_BYTES];
#if defined(USE_CRYPTO_OPENSSL)
HMAC(EVP_md5(), auth_key, key_len, (uint8_t *)msg, msg_len, (uint8_t *)hash, NULL);
#elif defined(USE_CRYPTO_MBEDTLS)
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_MD5), auth_key, key_len, (uint8_t *)msg, msg_len, (uint8_t *)hash);
#else
md5_hmac(auth_key, key_len, (uint8_t *)msg, msg_len, (uint8_t *)hash);
#endif
memcpy(auth, hash, MD5_BYTES);
return 0;
}
int ss_md5_hash_func(char *auth, char *msg, int msg_len)
{
uint8_t hash[MD5_BYTES];
#if defined(USE_CRYPTO_OPENSSL)
MD5((uint8_t *)msg, msg_len, (uint8_t *)hash);
#elif defined(USE_CRYPTO_MBEDTLS)
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_MD5), (uint8_t *)msg, msg_len, (uint8_t *)hash);
#else
md5((uint8_t *)msg, msg_len, (uint8_t *)hash);
#endif
memcpy(auth, hash, MD5_BYTES);
return 0;
}
int ss_sha1_hmac_with_key(char *auth, char *msg, int msg_len, uint8_t *auth_key, int key_len)
{
uint8_t hash[SHA1_BYTES];
#if defined(USE_CRYPTO_OPENSSL)
HMAC(EVP_sha1(), auth_key, key_len, (uint8_t *)msg, msg_len, (uint8_t *)hash, NULL);
#elif defined(USE_CRYPTO_MBEDTLS)
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), auth_key, key_len, (uint8_t *)msg, msg_len, (uint8_t *)hash);
#else
sha1_hmac(auth_key, key_len, (uint8_t *)msg, msg_len, (uint8_t *)hash);
#endif
memcpy(auth, hash, SHA1_BYTES);
return 0;
}
int ss_sha1_hash_func(char *auth, char *msg, int msg_len)
{
uint8_t hash[SHA1_BYTES];
#if defined(USE_CRYPTO_OPENSSL)
SHA1((uint8_t *)msg, msg_len, (uint8_t *)hash);
#elif defined(USE_CRYPTO_MBEDTLS)
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), (uint8_t *)msg, msg_len, (uint8_t *)hash);
#else
sha1((uint8_t *)msg, msg_len, (uint8_t *)hash);
#endif
memcpy(auth, hash, SHA1_BYTES);
return 0;
}
int ss_aes_128_cbc(char *encrypt, char *out_data, char *key)
{
unsigned char iv[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
#if defined(USE_CRYPTO_OPENSSL)
AES_KEY aes;
AES_set_encrypt_key((unsigned char*)key, 128, &aes);
AES_cbc_encrypt((const unsigned char *)encrypt, (unsigned char *)out_data, 16, &aes, iv, AES_ENCRYPT);
#elif defined(USE_CRYPTO_MBEDTLS)
mbedtls_aes_context aes;
unsigned char output[16];
mbedtls_aes_setkey_enc( &aes, (unsigned char *)key, 128 );
mbedtls_aes_crypt_cbc( &aes, MBEDTLS_AES_ENCRYPT, 16, iv, (unsigned char *)encrypt, output );
memcpy(out_data, output, 16);
#else
aes_context aes;
unsigned char output[16];
aes_setkey_enc( &aes, (unsigned char *)key, 128 );
aes_crypt_cbc( &aes, AES_ENCRYPT, 16, iv, (unsigned char *)encrypt, output );
memcpy(out_data, output, 16);
#endif
return 0;
}
int
ss_encrypt_all(cipher_env_t* env, buffer_t *plain, size_t capacity)
{
int method = env->enc_method;
if (method > TABLE) {
cipher_ctx_t evp;
cipher_context_init(env, &evp, 1);
size_t iv_len = env->enc_iv_len;
int err = 1;
static buffer_t tmp = { 0, 0, 0, NULL };
brealloc(&tmp, iv_len + plain->len, capacity);
buffer_t *cipher = &tmp;
cipher->len = plain->len;
uint8_t iv[MAX_IV_LENGTH];
rand_bytes(iv, iv_len);
cipher_context_set_iv(env, &evp, iv, iv_len, 1);
memcpy(cipher->array, iv, iv_len);
if (method >= SALSA20) {
crypto_stream_xor_ic((uint8_t *)(cipher->array + iv_len),
(const uint8_t *)plain->array, (uint64_t)(plain->len),
(const uint8_t *)iv,
0, env->enc_key, method);
} else {
err = cipher_context_update(&evp, (uint8_t *)(cipher->array + iv_len),
&cipher->len, (const uint8_t *)plain->array,
plain->len);
}
if (!err) {
bfree(plain);
cipher_context_release(env, &evp);
return -1;
}
#ifdef DEBUG
dump("PLAIN", plain->array, plain->len);
dump("CIPHER", cipher->array + iv_len, cipher->len);
#endif
cipher_context_release(env, &evp);
brealloc(plain, iv_len + cipher->len, capacity);
memcpy(plain->array, cipher->array, iv_len + cipher->len);
plain->len = iv_len + cipher->len;
return 0;
} else {
if (env->enc_method == TABLE) {
char *begin = plain->array;
char *ptr = plain->array;
while (ptr < begin + plain->len) {
*ptr = (char)env->enc_table[(uint8_t)*ptr];
ptr++;
}
}
return 0;
}
}
int
ss_encrypt(cipher_env_t *env, buffer_t *plain, enc_ctx_t *ctx, size_t capacity)
{
if (ctx != NULL) {
static buffer_t tmp = { 0, 0, 0, NULL };
int err = 1;
size_t iv_len = 0;
if (!ctx->init) {
iv_len = env->enc_iv_len;
}
brealloc(&tmp, iv_len + plain->len, capacity);
buffer_t *cipher = &tmp;
cipher->len = plain->len;
if (!ctx->init) {
cipher_context_set_iv(env, &ctx->evp, ctx->evp.iv, iv_len, 1);
memcpy(cipher->array, ctx->evp.iv, iv_len);
ctx->counter = 0;
ctx->init = 1;
}
if (env->enc_method >= SALSA20) {
int padding = ctx->counter % SODIUM_BLOCK_SIZE;
brealloc(cipher, iv_len + (padding + cipher->len) * 2, capacity);
if (padding) {
brealloc(plain, plain->len + padding, capacity);
memmove(plain->array + padding, plain->array, plain->len);
sodium_memzero(plain->array, padding);
}
crypto_stream_xor_ic((uint8_t *)(cipher->array + iv_len),
(const uint8_t *)plain->array,
(uint64_t)(plain->len + padding),
(const uint8_t *)ctx->evp.iv,
ctx->counter / SODIUM_BLOCK_SIZE, env->enc_key,
env->enc_method);
ctx->counter += plain->len;
if (padding) {
memmove(cipher->array + iv_len,
cipher->array + iv_len + padding, cipher->len);
}
} else {
err =
cipher_context_update(&ctx->evp,
(uint8_t *)(cipher->array + iv_len),
&cipher->len, (const uint8_t *)plain->array,
plain->len);
if (!err) {
return -1;
}
}
#ifdef DEBUG
dump("PLAIN", plain->array, plain->len);
dump("CIPHER", cipher->array + iv_len, cipher->len);
#endif
brealloc(plain, iv_len + cipher->len, capacity);
memcpy(plain->array, cipher->array, iv_len + cipher->len);
plain->len = iv_len + cipher->len;
return 0;
} else {
if (env->enc_method == TABLE) {
char *begin = plain->array;
char *ptr = plain->array;
while (ptr < begin + plain->len) {
*ptr = (char)env->enc_table[(uint8_t)*ptr];
ptr++;
}
}
return 0;
}
}
int
ss_decrypt_all(cipher_env_t* env, buffer_t *cipher, size_t capacity)
{
int method = env->enc_method;
if (method > TABLE) {
size_t iv_len = env->enc_iv_len;
int ret = 1;
if (cipher->len <= iv_len) {
return -1;
}
cipher_ctx_t evp;
cipher_context_init(env, &evp, 0);
static buffer_t tmp = { 0, 0, 0, NULL };
brealloc(&tmp, cipher->len, capacity);
buffer_t *plain = &tmp;
plain->len = cipher->len - iv_len;
uint8_t iv[MAX_IV_LENGTH];
memcpy(iv, cipher->array, iv_len);
cipher_context_set_iv(env, &evp, iv, iv_len, 0);
if (method >= SALSA20) {
crypto_stream_xor_ic((uint8_t *)plain->array,
(const uint8_t *)(cipher->array + iv_len),
(uint64_t)(cipher->len - iv_len),
(const uint8_t *)iv, 0, env->enc_key, method);
} else {
ret = cipher_context_update(&evp, (uint8_t *)plain->array, &plain->len,
(const uint8_t *)(cipher->array + iv_len),
cipher->len - iv_len);
}
if (!ret) {
bfree(cipher);
cipher_context_release(env, &evp);
return -1;
}
#ifdef DEBUG
dump("PLAIN", plain->array, plain->len);
dump("CIPHER", cipher->array + iv_len, cipher->len - iv_len);
#endif
cipher_context_release(env, &evp);
brealloc(cipher, plain->len, capacity);
memcpy(cipher->array, plain->array, plain->len);
cipher->len = plain->len;
return 0;
} else {
if (method == TABLE) {
char *begin = cipher->array;
char *ptr = cipher->array;
while (ptr < begin + cipher->len) {
*ptr = (char)env->dec_table[(uint8_t)*ptr];
ptr++;
}
}
return 0;
}
}
int
ss_decrypt(cipher_env_t* env, buffer_t *cipher, enc_ctx_t *ctx, size_t capacity)
{
if (ctx != NULL) {
static buffer_t tmp = { 0, 0, 0, NULL };
size_t iv_len = 0;
int err = 1;
brealloc(&tmp, cipher->len, capacity);
buffer_t *plain = &tmp;
plain->len = cipher->len;
if (!ctx->init) {
uint8_t iv[MAX_IV_LENGTH];
iv_len = env->enc_iv_len;
plain->len -= iv_len;
memcpy(iv, cipher->array, iv_len);
cipher_context_set_iv(env, &ctx->evp, iv, iv_len, 0);
ctx->counter = 0;
ctx->init = 1;
if (env->enc_method > RC4) {
if (cache_key_exist(env->iv_cache, (char *)iv, iv_len)) {
bfree(cipher);
return -1;
} else {
cache_insert(env->iv_cache, (char *)iv, iv_len, NULL);
}
}
}
if (env->enc_method >= SALSA20) {
int padding = ctx->counter % SODIUM_BLOCK_SIZE;
brealloc(plain, (plain->len + padding) * 2, capacity);
if (padding) {
brealloc(cipher, cipher->len + padding, capacity);
memmove(cipher->array + iv_len + padding, cipher->array + iv_len,
cipher->len - iv_len);
sodium_memzero(cipher->array + iv_len, padding);
}
crypto_stream_xor_ic((uint8_t *)plain->array,
(const uint8_t *)(cipher->array + iv_len),
(uint64_t)(cipher->len - iv_len + padding),
(const uint8_t *)ctx->evp.iv,
ctx->counter / SODIUM_BLOCK_SIZE, env->enc_key,
env->enc_method);
ctx->counter += cipher->len - iv_len;
if (padding) {
memmove(plain->array, plain->array + padding, plain->len);
}
} else {
err = cipher_context_update(&ctx->evp, (uint8_t *)plain->array, &plain->len,
(const uint8_t *)(cipher->array + iv_len),
cipher->len - iv_len);
}
if (!err) {
bfree(cipher);
return -1;
}
#ifdef DEBUG
dump("PLAIN", plain->array, plain->len);
dump("CIPHER", cipher->array + iv_len, cipher->len - iv_len);
#endif
brealloc(cipher, plain->len, capacity);
memcpy(cipher->array, plain->array, plain->len);
cipher->len = plain->len;
return 0;
} else {
if(env->enc_method == TABLE) {
char *begin = cipher->array;
char *ptr = cipher->array;
while (ptr < begin + cipher->len) {
*ptr = (char)env->dec_table[(uint8_t)*ptr];
ptr++;
}
}
return 0;
}
}
int
ss_encrypt_buffer(cipher_env_t *env, enc_ctx_t *ctx, char *in, size_t in_size, char *out, size_t *out_size)
{
buffer_t cipher;
memset(&cipher, 0, sizeof(buffer_t));
balloc(&cipher, in_size + 32);
cipher.len = in_size;
memcpy(cipher.array, in, in_size);
int s = ss_encrypt(env, &cipher, ctx, in_size + 32);
if (s == 0) {
*out_size = cipher.len;
memcpy(out, cipher.array, cipher.len);
}
bfree(&cipher);
return s;
}
int
ss_decrypt_buffer(cipher_env_t *env, enc_ctx_t *ctx, char *in, size_t in_size, char *out, size_t *out_size)
{
buffer_t cipher;
memset(&cipher, 0, sizeof(buffer_t));
balloc(&cipher, in_size + 32);
cipher.len = in_size;
memcpy(cipher.array, in, in_size);
int s = ss_decrypt(env, &cipher, ctx, in_size + 32);
if (s == 0) {
*out_size = cipher.len;
memcpy(out, cipher.array, cipher.len);
}
bfree(&cipher);
return s;
}
void
enc_ctx_init(cipher_env_t *env, enc_ctx_t *ctx, int enc)
{
sodium_memzero(ctx, sizeof(enc_ctx_t));
cipher_context_init(env, &ctx->evp, enc);
if (enc) {
rand_bytes(ctx->evp.iv, env->enc_iv_len);
}
}
void
enc_ctx_release(cipher_env_t *env, enc_ctx_t *ctx)
{
cipher_context_release(env, &ctx->evp);
}
void
enc_table_init(cipher_env_t * env, int method, const char *pass)
{
uint32_t i;
uint64_t key = 0;
uint8_t *digest;
env->enc_table = ss_malloc(256);
env->dec_table = ss_malloc(256);
digest = enc_md5((const uint8_t *)pass, strlen(pass), NULL);
for (i = 0; i < 8; i++)
key += OFFSET_ROL(digest, i);
for (i = 0; i < 256; ++i)
env->enc_table[i] = i;
for (i = 1; i < 1024; ++i)
merge_sort(env->enc_table, 256, i, key);
for (i = 0; i < 256; ++i)
// gen decrypt table from encrypt table
env->dec_table[env->enc_table[i]] = i;
if (method == TABLE) {
env->enc_key_len = strlen(pass);
memcpy(&env->enc_key, pass, env->enc_key_len);
} else {
const digest_type_t *md = get_digest_type("MD5");
env->enc_key_len = bytes_to_key(NULL, md, (const uint8_t *)pass, env->enc_key);
if (env->enc_key_len == 0) {
FATAL("Cannot generate key and IV");
}
}
env->enc_iv_len = 0;
env->enc_method = method;
}
void
enc_key_init(cipher_env_t *env, int method, const char *pass)
{
if (method < NONE || method >= CIPHER_NUM) {
LOGE("enc_key_init(): Illegal method");
return;
}
// Initialize cache
cache_create(&env->iv_cache, 256, NULL);
#if defined(USE_CRYPTO_OPENSSL)
OpenSSL_add_all_algorithms();
#else
cipher_kt_t cipher_info;
#endif
cipher_t cipher;
memset(&cipher, 0, sizeof(cipher_t));
// Initialize sodium for random generator
if (sodium_init() == -1) {
FATAL("Failed to initialize sodium");
}
if (method == SALSA20 || method == CHACHA20 || method == CHACHA20IETF) {
#if defined(USE_CRYPTO_OPENSSL)
cipher.info = NULL;
cipher.key_len = supported_ciphers_key_size[method];
cipher.iv_len = supported_ciphers_iv_size[method];
#endif
#if defined(USE_CRYPTO_POLARSSL)
cipher.info = &cipher_info;
cipher.info->base = NULL;
cipher.info->key_length = supported_ciphers_key_size[method] * 8;
cipher.info->iv_size = supported_ciphers_iv_size[method];
#endif
#if defined(USE_CRYPTO_MBEDTLS)
// XXX: key_length changed to key_bitlen in mbed TLS 2.0.0
cipher.info = &cipher_info;
cipher.info->base = NULL;
cipher.info->key_bitlen = supported_ciphers_key_size[method] * 8;
cipher.info->iv_size = supported_ciphers_iv_size[method];
#endif
} else {
cipher.info = (cipher_kt_t *)get_cipher_type(method);
}
if (cipher.info == NULL && cipher.key_len == 0) {
do {
#if defined(USE_CRYPTO_POLARSSL) && defined(USE_CRYPTO_APPLECC)
if (supported_ciphers_applecc[method] != kCCAlgorithmInvalid) {
cipher_info.base = NULL;
cipher_info.key_length = supported_ciphers_key_size[method] * 8;
cipher_info.iv_size = supported_ciphers_iv_size[method];
cipher.info = (cipher_kt_t *)&cipher_info;
break;
}
#endif
#if defined(USE_CRYPTO_MBEDTLS) && defined(USE_CRYPTO_APPLECC)
// XXX: key_length changed to key_bitlen in mbed TLS 2.0.0
if (supported_ciphers_applecc[method] != kCCAlgorithmInvalid) {
cipher_info.base = NULL;
cipher_info.key_bitlen = supported_ciphers_key_size[method] * 8;
cipher_info.iv_size = supported_ciphers_iv_size[method];
cipher.info = (cipher_kt_t *)&cipher_info;
break;
}
#endif
LOGE("Cipher %s not found in crypto library", supported_ciphers[method]);
FATAL("Cannot initialize cipher");
} while (0);
}
const digest_type_t *md = get_digest_type("MD5");
if (md == NULL) {
FATAL("MD5 Digest not found in crypto library");
}
env->enc_key_len = bytes_to_key(&cipher, md, (const uint8_t *)pass, env->enc_key);
if (env->enc_key_len == 0) {
FATAL("Cannot generate key and IV");
}
if (method == RC4_MD5 || method == RC4_MD5_6) {
env->enc_iv_len = supported_ciphers_iv_size[method];
} else {
env->enc_iv_len = cipher_iv_size(&cipher);
}
env->enc_method = method;
}
int
enc_init(cipher_env_t *env, const char *pass, const char *method)
{
int m = NONE;
if (method != NULL) {
for (m = NONE; m < CIPHER_NUM; m++)
if (strcmp(method, supported_ciphers[m]) == 0) {
break;
}
if (m >= CIPHER_NUM) {
LOGE("Invalid cipher name: %s, use rc4-md5 instead", method);
m = RC4_MD5;
}
}
if (m <= TABLE) {
enc_table_init(env, m, pass);
} else {
enc_key_init(env, m, pass);
}
env->enc_method = m;
return m;
}
void
enc_release(cipher_env_t *env) {
if (env->enc_method == TABLE) {
ss_free(env->enc_table);
ss_free(env->dec_table);
} else {
cache_delete(env->iv_cache, 0);
}
}
|
281677160/openwrt-package | 2,295 | luci-app-ssr-plus/shadowsocksr-libev/src/src/udprelay.h | /*
* udprelay.h - Define UDP relay's buffers and callbacks
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _UDPRELAY_H
#define _UDPRELAY_H
#include <ev.h>
#include <time.h>
#include "encrypt.h"
#include "jconf.h"
#include "obfs/obfs.h"
#ifdef MODULE_REMOTE
#include "resolv.h"
#endif
#include "cache.h"
#include "common.h"
#define MAX_UDP_PACKET_SIZE (65507)
#define DEFAULT_PACKET_SIZE MAX_UDP_PACKET_SIZE // 1492 - 1 - 28 - 2 - 64 = 1397, the default MTU for UDP relay
typedef struct server_ctx {
ev_io io;
int fd;
// int method;
int timeout;
const char *iface;
struct cache *conn_cache;
#ifdef MODULE_LOCAL
const struct sockaddr *remote_addr;
int remote_addr_len;
ss_addr_t tunnel_addr;
#endif
#ifdef MODULE_REMOTE
struct ev_loop *loop;
#endif
cipher_env_t* cipher_env;
// SSR
obfs *protocol;
obfs_class *protocol_plugin;
void *protocol_global;
} server_ctx_t;
#ifdef MODULE_REMOTE
typedef struct query_ctx {
struct ResolvQuery *query;
struct sockaddr_storage src_addr;
buffer_t *buf;
int addr_header_len;
char addr_header[384];
struct server_ctx *server_ctx;
struct remote_ctx *remote_ctx;
} query_ctx_t;
#endif
typedef struct remote_ctx {
ev_io io;
ev_timer watcher;
int af;
int fd;
int addr_header_len;
char addr_header[384];
struct sockaddr_storage src_addr;
#ifdef MODULE_REMOTE
struct sockaddr_storage dst_addr;
#endif
struct server_ctx *server_ctx;
} remote_ctx_t;
#endif // _UDPRELAY_H
|
281677160/openwrt-package | 2,401 | luci-app-ssr-plus/shadowsocksr-libev/src/src/local.h | /*
* local.h - Define the client's buffers and callbacks
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#ifndef _LOCAL_H
#define _LOCAL_H
#include <ev.h>
#include <libcork/ds.h>
#include "encrypt.h"
#include "jconf.h"
#include "protocol.h"
#include "common.h"
// use this as a profile or environment
typedef struct listen_ctx{
ev_io io;
ss_addr_t tunnel_addr;
struct cork_dllist_item entries; // for inactive profile list
struct cork_dllist connections_eden; // For connections just created but not attach to a server
char *iface;
int timeout;
int fd;
int mptcp;
int server_num;
server_def_t servers[MAX_SERVER_NUM];
} listen_ctx_t;
typedef struct server_ctx {
ev_io io;
int connected;
struct server *server;
} server_ctx_t;
typedef struct remote_ctx {
ev_io io;
ev_timer watcher;
int connected;
struct remote *remote;
} remote_ctx_t;
typedef struct remote {
int fd;
buffer_t *buf;
remote_ctx_t *recv_ctx;
remote_ctx_t *send_ctx;
uint32_t counter;
struct server *server;
int direct;
struct { // direct = 1
struct sockaddr_storage addr;
int addr_len;
} direct_addr;
} remote_t;
typedef struct server {
int fd;
char stage;
enc_ctx_t *e_ctx;
enc_ctx_t *d_ctx;
server_ctx_t *recv_ctx;
server_ctx_t *send_ctx;
listen_ctx_t *listener;
remote_t *remote;
buffer_t *buf;
struct cork_dllist_item entries;
struct cork_dllist_item entries_all; // for all_connections
server_def_t *server_env;
// SSR
obfs *protocol;
obfs *obfs;
} server_t;
#endif // _LOCAL_H
|
281677160/openwrt-package | 8,977 | luci-app-ssr-plus/shadowsocksr-libev/src/src/netutils.c | /*
* netutils.c - Network utilities
*
* Copyright (C) 2013 - 2016, Max Lv <max.c.lv@gmail.com>
*
* This file is part of the shadowsocks-libev.
*
* shadowsocks-libev is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* shadowsocks-libev is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with shadowsocks-libev; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <math.h>
#include <libcork/core.h>
#include <udns.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef __MINGW32__
#include "win32.h"
#define sleep(n) Sleep(1000 * (n))
#else
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#endif
#if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H) && defined(__linux__)
#include <net/if.h>
#include <sys/ioctl.h>
#define SET_INTERFACE
#endif
#include "netutils.h"
#include "utils.h"
#ifndef SO_REUSEPORT
#define SO_REUSEPORT 15
#endif
extern int verbose;
static const char valid_label_bytes[] =
"-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
#if defined(MODULE_LOCAL)
extern int keep_resolving;
#endif
int
set_reuseport(int socket)
{
int opt = 1;
return setsockopt(socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
}
size_t
get_sockaddr_len(struct sockaddr *addr)
{
if (addr->sa_family == AF_INET) {
return sizeof(struct sockaddr_in);
} else if (addr->sa_family == AF_INET6) {
return sizeof(struct sockaddr_in6);
}
return 0;
}
#ifdef SET_INTERFACE
int
setinterface(int socket_fd, const char *interface_name)
{
struct ifreq interface;
memset(&interface, 0, sizeof(struct ifreq));
strncpy(interface.ifr_name, interface_name, IFNAMSIZ);
int res = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, &interface,
sizeof(struct ifreq));
return res;
}
#endif
int
bind_to_address(int socket_fd, const char *host)
{
if (host != NULL) {
struct cork_ip ip;
struct sockaddr_storage storage;
memset(&storage, 0, sizeof(struct sockaddr_storage));
if (cork_ip_init(&ip, host) != -1) {
if (ip.version == 4) {
struct sockaddr_in *addr = (struct sockaddr_in *)&storage;
dns_pton(AF_INET, host, &addr->sin_addr);
addr->sin_family = AF_INET;
return bind(socket_fd, (struct sockaddr *)addr, sizeof(struct sockaddr_in));
} else if (ip.version == 6) {
struct sockaddr_in6 *addr = (struct sockaddr_in6 *)&storage;
dns_pton(AF_INET6, host, &addr->sin6_addr);
addr->sin6_family = AF_INET6;
return bind(socket_fd, (struct sockaddr *)addr, sizeof(struct sockaddr_in6));
}
}
}
return -1;
}
ssize_t
get_sockaddr(char *host, char *port,
struct sockaddr_storage *storage, int block,
int ipv6first)
{
struct cork_ip ip;
if (cork_ip_init(&ip, host) != -1) {
if (ip.version == 4) {
struct sockaddr_in *addr = (struct sockaddr_in *)storage;
addr->sin_family = AF_INET;
dns_pton(AF_INET, host, &(addr->sin_addr));
if (port != NULL) {
addr->sin_port = htons(atoi(port));
}
} else if (ip.version == 6) {
struct sockaddr_in6 *addr = (struct sockaddr_in6 *)storage;
addr->sin6_family = AF_INET6;
dns_pton(AF_INET6, host, &(addr->sin6_addr));
if (port != NULL) {
addr->sin6_port = htons(atoi(port));
}
}
return 0;
} else {
struct addrinfo hints;
struct addrinfo *result, *rp;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */
hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */
int err, i;
for (i = 1; i < 8; i++) {
err = getaddrinfo(host, port, &hints, &result);
#if defined(MODULE_LOCAL)
if (!keep_resolving)
break;
#endif
if ((!block || !err)) {
break;
} else {
sleep(pow(2, i));
LOGE("failed to resolve server name, wait %.0f seconds", pow(2, i));
}
}
if (err != 0) {
LOGE("getaddrinfo: %s", gai_strerror(err));
return -1;
}
int prefer_af = ipv6first ? AF_INET6 : AF_INET;
for (rp = result; rp != NULL; rp = rp->ai_next)
if (rp->ai_family == prefer_af) {
if (rp->ai_family == AF_INET)
memcpy(storage, rp->ai_addr, sizeof(struct sockaddr_in));
else if (rp->ai_family == AF_INET6)
memcpy(storage, rp->ai_addr, sizeof(struct sockaddr_in6));
break;
}
if (rp == NULL) {
for (rp = result; rp != NULL; rp = rp->ai_next) {
if (rp->ai_family == AF_INET)
memcpy(storage, rp->ai_addr, sizeof(struct sockaddr_in));
else if (rp->ai_family == AF_INET6)
memcpy(storage, rp->ai_addr, sizeof(struct sockaddr_in6));
break;
}
}
if (rp == NULL) {
LOGE("failed to resolve remote addr");
return -1;
}
freeaddrinfo(result);
return 0;
}
return -1;
}
int
sockaddr_cmp(struct sockaddr_storage *addr1,
struct sockaddr_storage *addr2, socklen_t len)
{
struct sockaddr_in *p1_in = (struct sockaddr_in *)addr1;
struct sockaddr_in *p2_in = (struct sockaddr_in *)addr2;
struct sockaddr_in6 *p1_in6 = (struct sockaddr_in6 *)addr1;
struct sockaddr_in6 *p2_in6 = (struct sockaddr_in6 *)addr2;
if (p1_in->sin_family < p2_in->sin_family)
return -1;
if (p1_in->sin_family > p2_in->sin_family)
return 1;
/* compare ip4 */
if (p1_in->sin_family == AF_INET) {
/* just order it, ntohs not required */
if (p1_in->sin_port < p2_in->sin_port)
return -1;
if (p1_in->sin_port > p2_in->sin_port)
return 1;
return memcmp(&p1_in->sin_addr, &p2_in->sin_addr, INET_SIZE);
} else if (p1_in6->sin6_family == AF_INET6) {
/* just order it, ntohs not required */
if (p1_in6->sin6_port < p2_in6->sin6_port)
return -1;
if (p1_in6->sin6_port > p2_in6->sin6_port)
return 1;
return memcmp(&p1_in6->sin6_addr, &p2_in6->sin6_addr,
INET6_SIZE);
} else {
/* eek unknown type, perform this comparison for sanity. */
return memcmp(addr1, addr2, len);
}
}
int
sockaddr_cmp_addr(struct sockaddr_storage *addr1,
struct sockaddr_storage *addr2, socklen_t len)
{
struct sockaddr_in *p1_in = (struct sockaddr_in *)addr1;
struct sockaddr_in *p2_in = (struct sockaddr_in *)addr2;
struct sockaddr_in6 *p1_in6 = (struct sockaddr_in6 *)addr1;
struct sockaddr_in6 *p2_in6 = (struct sockaddr_in6 *)addr2;
if (p1_in->sin_family < p2_in->sin_family)
return -1;
if (p1_in->sin_family > p2_in->sin_family)
return 1;
/* compare ip4 */
if (p1_in->sin_family == AF_INET) {
return memcmp(&p1_in->sin_addr, &p2_in->sin_addr, INET_SIZE);
} else if (p1_in6->sin6_family == AF_INET6) {
return memcmp(&p1_in6->sin6_addr, &p2_in6->sin6_addr,
INET6_SIZE);
} else {
/* eek unknown type, perform this comparison for sanity. */
return memcmp(addr1, addr2, len);
}
}
int
validate_hostname(const char *hostname, const int hostname_len)
{
if (hostname == NULL)
return 0;
if (hostname_len < 1 || hostname_len > 255)
return 0;
if (hostname[0] == '.')
return 0;
const char *label = hostname;
while (label < hostname + hostname_len) {
size_t label_len = hostname_len - (label - hostname);
char *next_dot = strchr(label, '.');
if (next_dot != NULL)
label_len = next_dot - label;
if (label + label_len > hostname + hostname_len)
return 0;
if (label_len > 63 || label_len < 1)
return 0;
if (label[0] == '-' || label[label_len - 1] == '-')
return 0;
if (strspn(label, valid_label_bytes) < label_len)
return 0;
label += label_len + 1;
}
return 1;
}
|
281677160/openwrt-package | 3,004 | luci-app-ssr-plus/shadowsocksr-libev/src/libsodium/AUTHORS |
Designers
=========
blake2 Jean-Philippe Aumasson
Christian Winnerlein
Samuel Neves
Zooko Wilcox-O'Hearn
chacha20 Daniel J. Bernstein
salsa20 Daniel J. Bernstein
chacha20poly1305 Adam Langley
curve25519 Daniel J. Bernstein
curve25519xsalsa20poly1305 Daniel J. Bernstein
ed25519 Daniel J. Bernstein
Bo-Yin Yang
Niels Duif
Peter Schwabe
Tanja Lange
poly1305 Daniel J. Bernstein
siphash Jean-Philippe Aumasson
Daniel J. Bernstein
scrypt Colin Percival
Implementors
============
crypto_aead/aes256gcm/aesni Romain Dolbeau
Frank Denis
crypto_aead/chacha20poly1305 Frank Denis
crypto_box/curve25519xsalsa20poly1305 Daniel J. Bernstein
crypto_core/hsalsa20 Daniel J. Bernstein
crypto_core/salsa20
crypto_core/salsa2012
crypto_core/salsa208
crypto_hash/sha256 Colin Percival
crypto_hash/sha512
crypto_hash/sha512256
crypto_auth/hmacsha256 Colin Percival
crypto_auth/hmacsha512
crypto_auth/hmacsha512256
crypto_scalarmult/curve25519/ref10 Daniel J. Bernstein
crypto_scalarmult/curve25519/donna_c64 Adam Langley
crypto_scalarmult/curve25519/sandy2x Tung Chou
crypto_secretbox/xsalsa20poly1305 Daniel J. Bernstein
crypto_sign/ed25519 Peter Schwabe
Daniel J. Bernstein
Niels Duif
Tanja Lange
Bo-Yin Yang
crypto_stream/aes128ctr Peter Schwabe
crypto_stream/chacha20/ref Daniel J. Bernstein
crypto_stream/chacha20/vec Ted Krovetz
crypto_stream/salsa20 Daniel J. Bernstein
crypto_stream/salsa2012
crypto_stream/salsa208
crypto_stream/xsalsa20
crypto_shorthash/siphash24 Jean-Philippe Aumasson
Daniel J. Bernstein
crypto_generichash/blake2b Jean-Philippe Aumasson
Christian Winnerlein
Samuel Neves
Zooko Wilcox-O'Hearn
crypto_onetimeauth/poly1305/donna Andrew "floodyberry" Moon
crypto_onetimeauth/poly1305/sse2 Andrew "floodyberry" Moon
crypto_pwhash/scryptsalsa208sha256 Colin Percival
Alexander Peslyak
|
281677160/openwrt-package | 1,270 | luci-app-ssr-plus/shadowsocksr-libev/src/libsodium/README.markdown | [](https://travis-ci.org/jedisct1/libsodium?branch=master)
[](https://scan.coverity.com/projects/2397)

============
Sodium is a new, easy-to-use software library for encryption,
decryption, signatures, password hashing and more.
It is a portable, cross-compilable, installable, packageable
fork of [NaCl](http://nacl.cr.yp.to/), with a compatible API, and an
extended API to improve usability even further.
Its goal is to provide all of the core operations needed to build
higher-level cryptographic tools.
Sodium supports a variety of compilers and operating systems,
including Windows (with MingW or Visual Studio, x86 and x64), iOS and Android.
## Documentation
The documentation is a work-in-progress, and is being written using
Gitbook:
[libsodium documentation](https://download.libsodium.org/doc/)
## Community
A mailing-list is available to discuss libsodium.
In order to join, just send a random mail to `sodium-subscribe` {at}
`pureftpd` {dot} `org`.
## License
[ISC license](https://en.wikipedia.org/wiki/ISC_license).
|
281677160/openwrt-package | 14,418 | luci-app-ssr-plus/shadowsocksr-libev/src/libsodium/ChangeLog |
* Version 1.0.7
- More functions whose return value should be checked have been
tagged with `__attribute__ ((warn_unused_result))`: `crypto_box_easy()`,
`crypto_box_detached()`, `crypto_box_beforenm()`, `crypto_box()`, and
`crypto_scalarmult()`.
- Sandy2x, the fastest Curve25519 implementation ever, has been
merged in, and is automatically used on CPUs supporting the AVX
instructions set.
- An SSE2 optimized implementation of Poly1305 was added, and is
twice as fast as the portable one.
- An SSSE3 optimized implementation of ChaCha20 was added, and is
twice as fast as the portable one.
- Faster `sodium_increment()` for common nonce sizes.
- New helper functions have been added: `sodium_is_zero()` and
`sodium_add()`.
- `sodium_runtime_has_aesni()` now properly detects the CPU flag when
compiled using Visual Studio.
* Version 1.0.6
- Optimized implementations of Blake2 have been added for modern
Intel platforms. `crypto_generichash()` is now faster than MD5 and SHA1
implementations while being far more secure.
- Functions for which the return value should be checked have been
tagged with `__attribute__ ((warn_unused_result))`. This will
intentionally break code compiled with `-Werror` that didn't bother
checking critical return values.
- The `crypto_sign_edwards25519sha512batch_*()` functions have been
tagged as deprecated.
- Undocumented symbols that were exported, but were only useful for
internal purposes have been removed or made private:
`sodium_runtime_get_cpu_features()`, the implementation-specific
`crypto_onetimeauth_poly1305_donna()` symbols,
`crypto_onetimeauth_poly1305_set_implementation()`,
`crypto_onetimeauth_poly1305_implementation_name()` and
`crypto_onetimeauth_pick_best_implementation()`.
- `sodium_compare()` now works as documented, and compares numbers
in little-endian format instead of behaving like `memcmp()`.
- The previous changes should not break actual applications, but to be
safe, the library version major was incremented.
- `sodium_runtime_has_ssse3()` and `sodium_runtime_has_sse41()` have
been added.
- The library can now be compiled with the CompCert compiler.
* Version 1.0.5
- Compilation issues on some platforms were fixed: missing alignment
directives were added (required at least on RHEL-6/i386), a workaround
for a VRP bug on gcc/armv7 was added, and the library can now be compiled
with the SunPro compiler.
- Javascript target: io.js is not supported any more. Use nodejs.
* Version 1.0.4
- Support for AES256-GCM has been added. This requires
a CPU with the aesni and pclmul extensions, and is accessible via the
crypto_aead_aes256gcm_*() functions.
- The Javascript target doesn't use eval() any more, so that the
library can be used in Chrome packaged applications.
- QNX and CloudABI are now supported.
- Support for NaCl has finally been added.
- ChaCha20 with an extended (96 bit) nonce and a 32-bit counter has
been implemented as crypto_stream_chacha20_ietf(),
crypto_stream_chacha20_ietf_xor() and crypto_stream_chacha20_ietf_xor_ic().
An IETF-compatible version of ChaCha20Poly1305 is available as
crypto_aead_chacha20poly1305_ietf_npubbytes(),
crypto_aead_chacha20poly1305_ietf_encrypt() and
crypto_aead_chacha20poly1305_ietf_decrypt().
- The sodium_increment() helper function has been added, to increment
an arbitrary large number (such as a nonce).
- The sodium_compare() helper function has been added, to compare
arbitrary large numbers (such as nonces, in order to prevent replay
attacks).
* Version 1.0.3
- In addition to sodium_bin2hex(), sodium_hex2bin() is now a
constant-time function.
- crypto_stream_xsalsa20_ic() has been added.
- crypto_generichash_statebytes(), crypto_auth_*_statebytes() and
crypto_hash_*_statebytes() have been added in order to retrieve the
size of structures keeping states from foreign languages.
- The JavaScript target doesn't require /dev/urandom or an external
randombytes() implementation any more. Other minor Emscripten-related
improvements have been made in order to support libsodium.js
- Custom randombytes implementations do not need to provide their own
implementation of randombytes_uniform() any more. randombytes_stir()
and randombytes_close() can also be NULL pointers if they are not
required.
- On Linux, getrandom(2) is being used instead of directly accessing
/dev/urandom, if the kernel supports this system call.
- crypto_box_seal() and crypto_box_seal_open() have been added.
- A solutions for Visual Studio 2015 was added.
* Version 1.0.2
- The _easy and _detached APIs now support precalculated keys;
crypto_box_easy_afternm(), crypto_box_open_easy_afternm(),
crypto_box_detached_afternm() and crypto_box_open_detached_afternm()
have been added as an alternative to the NaCl interface.
- Memory allocation functions can now be used on operating systems with
no memory protection.
- crypto_sign_open() and crypto_sign_edwards25519sha512batch_open()
now accept a NULL pointer instead of a pointer to the message size, if
storing this information is not required.
- The close-on-exec flag is now set on the descriptor returned when
opening /dev/urandom.
- A libsodium-uninstalled.pc file to use pkg-config even when
libsodium is not installed, has been added.
- The iOS target now includes armv7s and arm64 optimized code, as well
as i386 and x86_64 code for the iOS simulator.
- sodium_free() can now be called on regions with PROT_NONE protection.
- The Javascript tests can run on Ubuntu, where the node binary was
renamed nodejs. io.js can also be used instead of node.
* Version 1.0.1
- DLL_EXPORT was renamed SODIUM_DLL_EXPORT in order to avoid
collisions with similar macros defined by other libraries.
- sodium_bin2hex() is now constant-time.
- crypto_secretbox_detached() now supports overlapping input and output
regions.
- NaCl's donna_c64 implementation of curve25519 was reading an extra byte
past the end of the buffer containing the base point. This has been
fixed.
* Version 1.0.0
- The API and ABI are now stable. New features will be added, but
backward-compatibility is guaranteed through all the 1.x.y releases.
- crypto_sign() properly works with overlapping regions again. Thanks
to @pysiak for reporting this regression introduced in version 0.6.1.
- The test suite has been extended.
* Version 0.7.1 (1.0 RC2)
- This is the second release candidate of Sodium 1.0. Minor
compilation, readability and portability changes have been made and the
test suite was improved, but the API is the same as the previous release
candidate.
* Version 0.7.0 (1.0 RC1)
- Allocating memory to store sensitive data can now be done using
sodium_malloc() and sodium_allocarray(). These functions add guard
pages around the protected data to make it less likely to be
accessible in a heartbleed-like scenario. In addition, the protection
for memory regions allocated that way can be changed using
sodium_mprotect_noaccess(), sodium_mprotect_readonly() and
sodium_mprotect_readwrite().
- ed25519 keys can be converted to curve25519 keys with
crypto_sign_ed25519_pk_to_curve25519() and
crypto_sign_ed25519_sk_to_curve25519(). This allows using the same
keys for signature and encryption.
- The seed and the public key can be extracted from an ed25519 key
using crypto_sign_ed25519_sk_to_seed() and crypto_sign_ed25519_sk_to_pk().
- aes256 was removed. A timing-attack resistant implementation might
be added later, but not before version 1.0 is tagged.
- The crypto_pwhash_scryptxsalsa208sha256_* compatibility layer was
removed. Use crypto_pwhash_scryptsalsa208sha256_*.
- The compatibility layer for implementation-specific functions was
removed.
- Compilation issues with Mingw64 on MSYS (not MSYS2) were fixed.
- crypto_pwhash_scryptsalsa208sha256_STRPREFIX was added: it contains
the prefix produced by crypto_pwhash_scryptsalsa208sha256_str()
* Version 0.6.1
- Important bug fix: when crypto_sign_open() was given a signed
message too short to even contain a signature, it was putting an
unlimited amount of zeros into the target buffer instead of
immediately returning -1. The bug was introduced in version 0.5.0.
- New API: crypto_sign_detached() and crypto_sign_verify_detached()
to produce and verify ed25519 signatures without having to duplicate
the message.
- New ./configure switch: --enable-minimal, to create a smaller
library, with only the functions required for the high-level API.
Mainly useful for the JavaScript target and embedded systems.
- All the symbols are now exported by the Emscripten build script.
- The pkg-config .pc file is now always installed even if the
pkg-config tool is not available during the installation.
* Version 0.6.0
- The ChaCha20 stream cipher has been added, as crypto_stream_chacha20_*
- The ChaCha20Poly1305 AEAD construction has been implemented, as
crypto_aead_chacha20poly1305_*
- The _easy API does not require any heap allocations any more and
does not have any overhead over the NaCl API. With the password
hashing function being an obvious exception, the library doesn't
allocate and will not allocate heap memory ever.
- crypto_box and crypto_secretbox have a new _detached API to store
the authentication tag and the encrypted message separately.
- crypto_pwhash_scryptxsalsa208sha256*() functions have been renamed
crypto_pwhash_scryptsalsa208sha256*().
- The low-level crypto_pwhash_scryptsalsa208sha256_ll() function
allows setting individual parameters of the scrypt function.
- New macros and functions for recommended crypto_pwhash_* parameters
have been added.
- Similarly to crypto_sign_seed_keypair(), crypto_box_seed_keypair()
has been introduced to deterministically generate a key pair from a seed.
- crypto_onetimeauth() now provides a streaming interface.
- crypto_stream_chacha20_xor_ic() and crypto_stream_salsa20_xor_ic()
have been added to use a non-zero initial block counter.
- On Windows, CryptGenRandom() was replaced by RtlGenRandom(), which
doesn't require the Crypt API.
- The high bit in curve25519 is masked instead of processing the key as
a 256-bit value.
- The curve25519 ref implementation was replaced by the latest ref10
implementation from Supercop.
- sodium_mlock() now prevents memory from being included in coredumps
on Linux 3.4+
* Version 0.5.0
- sodium_mlock()/sodium_munlock() have been introduced to lock pages
in memory before storing sensitive data, and to zero them before
unlocking them.
- High-level wrappers for crypto_box and crypto_secretbox
(crypto_box_easy and crypto_secretbox_easy) can be used to avoid
dealing with the specific memory layout regular functions depend on.
- crypto_pwhash_scryptsalsa208sha256* functions have been added
to derive a key from a password, and for password storage.
- Salsa20 and ed25519 implementations now support overlapping
inputs/keys/outputs (changes imported from supercop-20140505).
- New build scripts for Visual Studio, Emscripten, different Android
architectures and msys2 are available.
- The poly1305-53 implementation has been replaced with Floodyberry's
poly1305-donna32 and poly1305-donna64 implementations.
- sodium_hex2bin() has been added to complement sodium_bin2hex().
- On OpenBSD and Bitrig, arc4random() is used instead of reading
/dev/urandom.
- crypto_auth_hmac_sha512() has been implemented.
- sha256 and sha512 now have a streaming interface.
- hmacsha256, hmacsha512 and hmacsha512256 now support keys of
arbitrary length, and have a streaming interface.
- crypto_verify_64() has been implemented.
- first-class Visual Studio build system, thanks to @evoskuil
- CPU features are now detected at runtime.
* Version 0.4.5
- Restore compatibility with OSX <= 10.6
* Version 0.4.4
- Visual Studio is officially supported (VC 2010 & VC 2013)
- mingw64 is now supported
- big-endian architectures are now supported as well
- The donna_c64 implementation of curve25519_donna_c64 now handles
non-canonical points like the ref implementation
- Missing scalarmult_curve25519 and stream_salsa20 constants are now exported
- A crypto_onetimeauth_poly1305_ref() wrapper has been added
* Version 0.4.3
- crypto_sign_seedbytes() and crypto_sign_SEEDBYTES were added.
- crypto_onetimeauth_poly1305_implementation_name() was added.
- poly1305-ref has been replaced by a faster implementation,
Floodyberry's poly1305-donna-unrolled.
- Stackmarkings have been added to assembly code, for Hardened Gentoo.
- pkg-config can now be used in order to retrieve compilations flags for
using libsodium.
- crypto_stream_aes256estream_*() can now deal with unaligned input
on platforms that require word alignment.
- portability improvements.
* Version 0.4.2
- All NaCl constants are now also exposed as functions.
- The Android and iOS cross-compilation script have been improved.
- libsodium can now be cross-compiled to Windows from Linux.
- libsodium can now be compiled with emscripten.
- New convenience function (prototyped in utils.h): sodium_bin2hex().
* Version 0.4.1
- sodium_version_*() functions were not exported in version 0.4. They
are now visible as intended.
- sodium_init() now calls randombytes_stir().
- optimized assembly version of salsa20 is now used on amd64.
- further cleanups and enhanced compatibility with non-C99 compilers.
* Version 0.4
- Most constants and operations are now available as actual functions
instead of macros, making it easier to use from other languages.
- New operation: crypto_generichash, featuring a variable key size, a
variable output size, and a streaming API. Currently implemented using
Blake2b.
- The package can be compiled in a separate directory.
- aes128ctr functions are exported.
- Optimized versions of curve25519 (curve25519_donna_c64), poly1305
(poly1305_53) and ed25519 (ed25519_ref10) are available. Optionally calling
sodium_init() once before using the library makes it pick the fastest
implementation.
- New convenience function: sodium_memzero() in order to securely
wipe a memory area.
- A whole bunch of cleanups and portability enhancements.
- On Windows, a .REF file is generated along with the shared library,
for use with Visual Studio. The installation path for these has become
$prefix/bin as expected by MingW.
* Version 0.3
- The crypto_shorthash operation has been added, implemented using
SipHash-2-4.
* Version 0.2
- crypto_sign_seed_keypair() has been added
* Version 0.1
- Initial release.
|
281677160/openwrt-package | 29,716 | luci-app-ssr-plus/shadowsocksr-libev/src/libsodium/libsodium.vcxproj.filters | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="src\libsodium\include\sodium\core.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_auth.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_auth_hmacsha256.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_auth_hmacsha512.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_auth_hmacsha512256.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_box.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_box_curve25519xsalsa20poly1305.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_core_hsalsa20.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_core_salsa20.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_core_salsa208.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_core_salsa2012.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_generichash.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_generichash_blake2b.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_hash.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_hash_sha256.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_hash_sha512.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_int32.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_int64.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_onetimeauth.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_scalarmult.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_scalarmult_curve25519.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_secretbox.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_secretbox_xsalsa20poly1305.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_shorthash.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_shorthash_siphash24.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_sign.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_sign_ed25519.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_sign_edwards25519sha512batch.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_stream.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_stream_aes128ctr.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_stream_salsa20.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_stream_salsa208.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_stream_salsa2012.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_stream_xsalsa20.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_uint8.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_uint16.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_uint32.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_uint64.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_verify_16.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_verify_32.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_verify_64.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\export.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\randombytes.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\randombytes_salsa20_random.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\randombytes_sysrandom.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\utils.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\version.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_pwhash_scryptsalsa208sha256.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\runtime.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_stream_chacha20.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_aead_aes256gcm.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_aead_chacha20poly1305.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\include\sodium\crypto_onetimeauth_poly1305.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\crypto_generichash\blake2\ref\blake2b-load-sse2.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\crypto_generichash\blake2\ref\blake2b-load-sse41.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\crypto_generichash\blake2\ref\blake2b-round.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="src\libsodium\crypto_onetimeauth\poly1305\onetimeauth_poly1305.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="src\libsodium\crypto_core\hsalsa20\ref2\core_hsalsa20.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_core\hsalsa20\core_hsalsa20_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_core\salsa20\ref\core_salsa20.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_core\salsa208\ref\core_salsa208.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_core\salsa2012\ref\core_salsa2012.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_auth\hmacsha256\auth_hmacsha256_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_auth\hmacsha512\auth_hmacsha512_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_auth\hmacsha512256\auth_hmacsha512256_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_auth\crypto_auth.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_auth\hmacsha256\cp\hmac_hmacsha256.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_auth\hmacsha512\cp\hmac_hmacsha512.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_auth\hmacsha512256\cp\hmac_hmacsha512256.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_auth\hmacsha512\cp\verify_hmacsha512.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_auth\hmacsha512256\cp\verify_hmacsha512256.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_box\curve25519xsalsa20poly1305\ref\after_curve25519xsalsa20poly1305.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_box\curve25519xsalsa20poly1305\ref\box_curve25519xsalsa20poly1305.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_box\curve25519xsalsa20poly1305\box_curve25519xsalsa20poly1305_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_box\crypto_box.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_box\curve25519xsalsa20poly1305\ref\keypair_curve25519xsalsa20poly1305.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_core\salsa20\core_salsa20_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_core\salsa208\core_salsa208_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_core\salsa2012\core_salsa2012_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_generichash\blake2\ref\blake2b-ref.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_generichash\crypto_generichash.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_generichash\blake2\generichash_blake2_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_generichash\blake2\ref\generichash_blake2b.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_hash\crypto_hash.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_hash\sha256\cp\hash_sha256.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_hash\sha256\hash_sha256_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_hash\sha512\cp\hash_sha512.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_hash\sha512\hash_sha512_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_onetimeauth\crypto_onetimeauth.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_onetimeauth\poly1305\onetimeauth_poly1305.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\crypto_scalarmult.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_secretbox\xsalsa20poly1305\ref\box_xsalsa20poly1305.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_secretbox\crypto_secretbox.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_secretbox\xsalsa20poly1305\secretbox_xsalsa20poly1305_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_shorthash\crypto_shorthash.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_shorthash\siphash24\ref\shorthash_siphash24.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_shorthash\siphash24\shorthash_siphash24_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\crypto_sign.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_0.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_1.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_add.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_cmov.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_copy.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_frombytes.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_invert.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_isnegative.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_isnonzero.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_mul.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_neg.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_pow22523.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_sq.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_sq2.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_sub.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\fe_tobytes.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_add.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_double_scalarmult.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_frombytes.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_madd.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_msub.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_p1p1_to_p2.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_p1p1_to_p3.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_p2_0.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_p2_dbl.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_p3_0.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_p3_dbl.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_p3_to_cached.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_p3_to_p2.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_p3_tobytes.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_precomp_0.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_scalarmult_base.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_sub.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\ge_tobytes.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\keypair.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\open.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\sc_muladd.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\sc_reduce.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\sign.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\sign_ed25519_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\aes128ctr\portable\afternm_aes128ctr.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\aes128ctr\portable\beforenm_aes128ctr.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\aes128ctr\portable\common_aes128ctr.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\aes128ctr\portable\consts_aes128ctr.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\crypto_stream.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\aes128ctr\portable\int128_aes128ctr.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\aes128ctr\portable\stream_aes128ctr.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\aes128ctr\stream_aes128ctr_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\salsa20\stream_salsa20_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\salsa20\ref\stream_salsa20_ref.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\salsa208\ref\stream_salsa208.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\salsa208\stream_salsa208_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\salsa2012\ref\stream_salsa2012.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\salsa2012\stream_salsa2012_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\xsalsa20\ref\stream_xsalsa20.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\xsalsa20\stream_xsalsa20_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\aes128ctr\portable\xor_afternm_aes128ctr.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\salsa20\ref\xor_salsa20_ref.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\salsa208\ref\xor_salsa208.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\salsa2012\ref\xor_salsa2012.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\xsalsa20\ref\xor_xsalsa20.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_verify\16\ref\verify_16.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_verify\16\verify_16_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_verify\32\ref\verify_32.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_verify\32\verify_32_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_verify\64\ref\verify_64.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_verify\64\verify_64_api.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\sodium\core.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\sodium\utils.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\sodium\version.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\randombytes\randombytes.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\randombytes\salsa20\randombytes_salsa20_random.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\randombytes\sysrandom\randombytes_sysrandom.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_auth\hmacsha256\cp\verify_hmacsha256.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_pwhash\scryptsalsa208sha256\crypto_scrypt-common.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_pwhash\scryptsalsa208sha256\pbkdf2-sha256.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_pwhash\scryptsalsa208sha256\pwhash_scryptsalsa208sha256.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_pwhash\scryptsalsa208sha256\scrypt_platform.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\sodium\runtime.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_box\crypto_box_easy.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_box\crypto_box_seal.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_secretbox\crypto_secretbox_easy.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_pwhash\scryptsalsa208sha256\nosse\pwhash_scryptsalsa208sha256_nosse.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_pwhash\scryptsalsa208sha256\sse\pwhash_scryptsalsa208sha256_sse.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\chacha20\stream_chacha20.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_stream\chacha20\ref\stream_chacha20_ref.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_0_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_1_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_add_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_copy_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_cswap_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_frombytes_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_invert_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_mul_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_mul121666_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_sq_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_sub_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\fe_tobytes_curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_box\curve25519xsalsa20poly1305\ref\before_curve25519xsalsa20poly1305.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_aead\aes256gcm\aesni\aead_aes256gcm_aesni.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_aead\chacha20poly1305\sodium\aead_chacha20poly1305.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_generichash\blake2\ref\blake2b-compress-ref.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_generichash\blake2\ref\blake2b-compress-sse41.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_generichash\blake2\ref\blake2b-compress-ssse3.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\scalarmult_curve25519.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\donna_c64\curve25519_donna_c64.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\ref10\curve25519_ref10.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\sandy2x\curve25519_sandy2x.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\sandy2x\fe_frombytes_sandy2x.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_scalarmult\curve25519\sandy2x\fe51_invert.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_onetimeauth\poly1305\donna\poly1305_donna.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\libsodium\crypto_sign\ed25519\ref10\obsolete.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="src\libsodium\crypto_scalarmult\curve25519\sandy2x\sandy2x.S">
<Filter>Source Files</Filter>
</None>
</ItemGroup>
</Project>
|
281677160/openwrt-package | 1,070 | luci-app-ssr-plus/shadowsocksr-libev/src/libsodium/THANKS | @alethia7
@dnaq
@harleqin
@joshjdevl
@jshahbazi
@lvh
@neheb
Amit Murthy (@amitmurthy)
Bruno Oliveira (@abstractj)
Christian Wiese (@morfoh)
Chris Rebert (@cvrebert)
Colm MacCárthaigh (@colmmacc)
Donald Stufft (@dstufft)
Douglas Campos (@qmx)
Drew Crawford (@drewcrawford)
Eric Dong (@quantum1423)
Eric Voskuil (@evoskuil)
Frank Siebenlist (@franks42)
Gabriel Handford (@gabriel)
Jachym Holecek (@freza)
Jan de Muijnck-Hughes (@jfdm)
Jason McCampbell (@jasonmccampbell)
Jeroen Habraken (@VeXocide)
Jesper Louis Andersen (@jlouis)
Joseph Abrahamson (@tel)
Kenneth Ballenegger (@kballenegger)
Loic Maury (@loicmaury)
Michael Gorlick (@mgorlick)
Michael Gregorowicz (@mgregoro)
Omar Ayub (@electricFeel)
Pedro Paixao (@paixaop)
Project ArteMisc (@artemisc)
Ruben De Visscher (@rubendv)
Rudolf Von Krugstein (@rudolfvonkrugstein)
Samuel Neves (@sneves)
Scott Arciszewski (@paragonie-scott)
Stefan Marsiske
Stephan Touset (@stouset)
Steve Gibson (@sggrc)
Tony Arcieri (@bascule)
Tony Garnock-Jones (@tonyg)
Y. T. Chung (@zonyitoo)
FSF France
Coverity, Inc.
OpenDNS, Inc.
OVH
|
281677160/openwrt-package | 1,282 | luci-app-ssr-plus/shadowsocksr-libev/src/cmake/CheckPrototypeExists.cmake | # - Check if the prototype for a function exists.
# CHECK_PROTOTYPE_EXISTS (FUNCTION HEADER VARIABLE)
#
# FUNCTION - the name of the function you are looking for
# HEADER - the header(s) where the prototype should be declared
# VARIABLE - variable to store the result
#
# The following variables may be set before calling this macro to
# modify the way the check is run:
#
# CMAKE_REQUIRED_FLAGS = string of compile command line flags
# CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
# CMAKE_REQUIRED_INCLUDES = list of include directories
# Copyright (c) 2006, Alexander Neundorf, <neundorf@kde.org>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
INCLUDE(CheckCSourceCompiles)
MACRO (CHECK_PROTOTYPE_EXISTS _SYMBOL _HEADER _RESULT)
SET(_INCLUDE_FILES)
FOREACH (it ${_HEADER})
SET(_INCLUDE_FILES "${_INCLUDE_FILES}#include <${it}>\n")
ENDFOREACH (it)
SET(_CHECK_PROTO_EXISTS_SOURCE_CODE "
${_INCLUDE_FILES}
int main()
{
#ifndef ${_SYMBOL}
int i = sizeof(&${_SYMBOL});
#endif
return 0;
}
")
CHECK_C_SOURCE_COMPILES("${_CHECK_PROTO_EXISTS_SOURCE_CODE}" ${_RESULT})
ENDMACRO (CHECK_PROTOTYPE_EXISTS _SYMBOL _HEADER _RESULT)
|
281677160/openwrt-package | 1,321 | luci-app-ssr-plus/shadowsocksr-libev/src/cmake/CheckSTDC.cmake | message(STATUS "Checking whether system has ANSI C header files")
include(CheckPrototypeExists)
include(CheckIncludeFiles)
check_include_files("dlfcn.h;stdint.h;stddef.h;inttypes.h;stdlib.h;strings.h;string.h;float.h" StandardHeadersExist)
if(StandardHeadersExist)
check_prototype_exists(memchr string.h memchrExists)
if(memchrExists)
check_prototype_exists(free stdlib.h freeExists)
if(freeExists)
message(STATUS "ANSI C header files - found")
set(STDC_HEADERS 1 CACHE INTERNAL "System has ANSI C header files")
set(HAVE_STRINGS_H 1)
set(HAVE_STRING_H 1)
set(HAVE_FLOAT_H 1)
set(HAVE_STDLIB_H 1)
set(HAVE_STDDEF_H 1)
set(HAVE_STDINT_H 1)
set(HAVE_INTTYPES_H 1)
set(HAVE_DLFCN_H 1)
endif(freeExists)
endif(memchrExists)
endif(StandardHeadersExist)
if(NOT STDC_HEADERS)
message(STATUS "ANSI C header files - not found")
set(STDC_HEADERS 0 CACHE INTERNAL "System has ANSI C header files")
endif(NOT STDC_HEADERS)
check_include_files(unistd.h HAVE_UNISTD_H)
include(CheckDIRSymbolExists)
check_dirsymbol_exists("sys/stat.h;sys/types.h;dirent.h" HAVE_DIRENT_H)
if (HAVE_DIRENT_H)
set(HAVE_SYS_STAT_H 1)
set(HAVE_SYS_TYPES_H 1)
endif (HAVE_DIRENT_H)
|
281677160/openwrt-package | 5,353 | luci-app-ssr-plus/shadowsocksr-libev/src/cmake/FindPCRE.cmake | #.rst:
# FindPCRE
# --------
#
# Find the native PCRE includes and library.
#
# IMPORTED Targets
# ^^^^^^^^^^^^^^^^
#
# This module defines :prop_tgt:`IMPORTED` target ``PCRE::PCRE``, if
# PCRE has been found.
#
# Result Variables
# ^^^^^^^^^^^^^^^^
#
# This module defines the following variables:
#
# ::
#
# PCRE_INCLUDE_DIRS - where to find pcre.h, etc.
# PCRE_LIBRARIES - List of libraries when using pcre.
# PCRE_FOUND - True if pcre found.
#
# ::
#
# PCRE_VERSION_STRING - The version of pcre found (x.y.z)
# PCRE_VERSION_MAJOR - The major version of zlib
# PCRE_VERSION_MINOR - The minor version of zlib
# PCRE_VERSION_PATCH - The patch version of zlib
# PCRE_VERSION_TWEAK - The tweak version of zlib
#
# Backward Compatibility
# ^^^^^^^^^^^^^^^^^^^^^^
#
# The following variable are provided for backward compatibility
#
# ::
#
# PCRE_MAJOR_VERSION - The major version of zlib
# PCRE_MINOR_VERSION - The minor version of zlib
# PCRE_PATCH_VERSION - The patch version of zlib
#
# Hints
# ^^^^^
#
# A user may set ``PCRE_ROOT`` to a zlib installation root to tell this
# module where to look.
#=============================================================================
# Copyright 2001-2011 Kitware, Inc.
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
set(_PCRE_SEARCHES)
# Search PCRE_ROOT first if it is set.
if(PCRE_ROOT)
set(_PCRE_SEARCH_ROOT PATHS ${PCRE_ROOT} NO_DEFAULT_PATH)
list(APPEND _PCRE_SEARCHES _PCRE_SEARCH_ROOT)
endif()
# Normal search.
set(_PCRE_SEARCH_NORMAL
PATHS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\GnuWin32\\Pcre;InstallPath]"
"$ENV{PROGRAMFILES}/pcre"
)
list(APPEND _PCRE_SEARCHES _PCRE_SEARCH_NORMAL)
set(PCRE_NAMES pcre pcredll)
set(PCRE_NAMES_DEBUG pcred)
# Try each search configuration.
foreach(search ${_PCRE_SEARCHES})
find_path(PCRE_INCLUDE_DIR NAMES pcre.h ${${search}} PATH_SUFFIXES include)
endforeach()
# Allow PCRE_LIBRARY to be set manually, as the location of the pcre library
if(NOT PCRE_LIBRARY)
foreach(search ${_PCRE_SEARCHES})
find_library(PCRE_LIBRARY_RELEASE NAMES ${PCRE_NAMES} ${${search}} PATH_SUFFIXES lib)
find_library(PCRE_LIBRARY_DEBUG NAMES ${PCRE_NAMES_DEBUG} ${${search}} PATH_SUFFIXES lib)
endforeach()
include(SelectLibraryConfigurations)
select_library_configurations(PCRE)
endif()
unset(PCRE_NAMES)
unset(PCRE_NAMES_DEBUG)
mark_as_advanced(PCRE_LIBRARY PCRE_INCLUDE_DIR)
if(PCRE_INCLUDE_DIR AND EXISTS "${PCRE_INCLUDE_DIR}/pcre.h")
file(STRINGS "${PCRE_INCLUDE_DIR}/pcre.h" PCRE_H REGEX "^#define PCRE_VERSION \"[^\"]*\"$")
string(REGEX REPLACE "^.*PCRE_VERSION \"([0-9]+).*$" "\\1" PCRE_VERSION_MAJOR "${PCRE_H}")
string(REGEX REPLACE "^.*PCRE_VERSION \"[0-9]+\\.([0-9]+).*$" "\\1" PCRE_VERSION_MINOR "${PCRE_H}")
string(REGEX REPLACE "^.*PCRE_VERSION \"[0-9]+\\.[0-9]+\\.([0-9]+).*$" "\\1" PCRE_VERSION_PATCH "${PCRE_H}")
set(PCRE_VERSION_STRING "${PCRE_VERSION_MAJOR}.${PCRE_VERSION_MINOR}.${PCRE_VERSION_PATCH}")
# only append a TWEAK version if it exists:
set(PCRE_VERSION_TWEAK "")
if( "${PCRE_H}" MATCHES "PCRE_VERSION \"[0-9]+\\.[0-9]+\\.[0-9]+\\.([0-9]+)")
set(PCRE_VERSION_TWEAK "${CMAKE_MATCH_1}")
set(PCRE_VERSION_STRING "${PCRE_VERSION_STRING}.${PCRE_VERSION_TWEAK}")
endif()
set(PCRE_MAJOR_VERSION "${PCRE_VERSION_MAJOR}")
set(PCRE_MINOR_VERSION "${PCRE_VERSION_MINOR}")
set(PCRE_PATCH_VERSION "${PCRE_VERSION_PATCH}")
endif()
# handle the QUIETLY and REQUIRED arguments and set PCRE_FOUND to TRUE if
# all listed variables are TRUE
include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(PCRE REQUIRED_VARS PCRE_LIBRARY PCRE_INCLUDE_DIR
VERSION_VAR PCRE_VERSION_STRING)
if(PCRE_FOUND)
set(PCRE_INCLUDE_DIRS ${PCRE_INCLUDE_DIR})
if(NOT PCRE_LIBRARIES)
set(PCRE_LIBRARIES ${PCRE_LIBRARY})
endif()
if(NOT TARGET PCRE::PCRE)
add_library(PCRE::PCRE UNKNOWN IMPORTED)
set_target_properties(PCRE::PCRE PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${PCRE_INCLUDE_DIRS}")
if(PCRE_LIBRARY_RELEASE)
set_property(TARGET PCRE::PCRE APPEND PROPERTY
IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(PCRE::PCRE PROPERTIES
IMPORTED_LOCATION_RELEASE "${PCRE_LIBRARY_RELEASE}")
endif()
if(PCRE_LIBRARY_DEBUG)
set_property(TARGET PCRE::PCRE APPEND PROPERTY
IMPORTED_CONFIGURATIONS DEBUG)
set_target_properties(PCRE::PCRE PROPERTIES
IMPORTED_LOCATION_DEBUG "${PCRE_LIBRARY_DEBUG}")
endif()
if(NOT PCRE_LIBRARY_RELEASE AND NOT PCRE_LIBRARY_DEBUG)
set_property(TARGET PCRE::PCRE APPEND PROPERTY
IMPORTED_LOCATION "${PCRE_LIBRARY}")
endif()
endif()
endif()
|
281677160/openwrt-package | 3,801 | luci-app-ssr-plus/shadowsocksr-libev/src/cmake/CheckDIRSymbolExists.cmake | # - Check if the DIR symbol exists like in AC_HEADER_DIRENT.
# CHECK_DIRSYMBOL_EXISTS(FILES VARIABLE)
#
# FILES - include files to check
# VARIABLE - variable to return result
#
# This module is a small but important variation on CheckSymbolExists.cmake.
# The symbol always searched for is DIR, and the test programme follows
# the AC_HEADER_DIRENT test programme rather than the CheckSymbolExists.cmake
# test programme which always fails since DIR tends to be typedef'd
# rather than #define'd.
#
# The following variables may be set before calling this macro to
# modify the way the check is run:
#
# CMAKE_REQUIRED_FLAGS = string of compile command line flags
# CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
# CMAKE_REQUIRED_INCLUDES = list of include directories
# CMAKE_REQUIRED_LIBRARIES = list of libraries to link
MACRO(CHECK_DIRSYMBOL_EXISTS FILES VARIABLE)
IF(NOT DEFINED ${VARIABLE})
SET(CMAKE_CONFIGURABLE_FILE_CONTENT "/* */\n")
SET(MACRO_CHECK_DIRSYMBOL_EXISTS_FLAGS ${CMAKE_REQUIRED_FLAGS})
IF(CMAKE_REQUIRED_LIBRARIES)
SET(CHECK_DIRSYMBOL_EXISTS_LIBS
"-DLINK_LIBRARIES:STRING=${CMAKE_REQUIRED_LIBRARIES}")
ELSE(CMAKE_REQUIRED_LIBRARIES)
SET(CHECK_DIRSYMBOL_EXISTS_LIBS)
ENDIF(CMAKE_REQUIRED_LIBRARIES)
IF(CMAKE_REQUIRED_INCLUDES)
SET(CMAKE_DIRSYMBOL_EXISTS_INCLUDES
"-DINCLUDE_DIRECTORIES:STRING=${CMAKE_REQUIRED_INCLUDES}")
ELSE(CMAKE_REQUIRED_INCLUDES)
SET(CMAKE_DIRSYMBOL_EXISTS_INCLUDES)
ENDIF(CMAKE_REQUIRED_INCLUDES)
FOREACH(FILE ${FILES})
SET(CMAKE_CONFIGURABLE_FILE_CONTENT
"${CMAKE_CONFIGURABLE_FILE_CONTENT}#include <${FILE}>\n")
ENDFOREACH(FILE)
SET(CMAKE_CONFIGURABLE_FILE_CONTENT
"${CMAKE_CONFIGURABLE_FILE_CONTENT}\nint main()\n{if ((DIR *) 0) return 0;}\n")
CONFIGURE_FILE("${CMAKE_ROOT}/Modules/CMakeConfigurableFile.in"
"${CMAKE_BINARY_DIR}/CMakeFiles/CMakeTmp/CheckDIRSymbolExists.c" @ONLY)
MESSAGE(STATUS "Looking for DIR in ${FILES}")
TRY_COMPILE(${VARIABLE}
${CMAKE_BINARY_DIR}
${CMAKE_BINARY_DIR}/CMakeFiles/CMakeTmp/CheckDIRSymbolExists.c
COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS}
CMAKE_FLAGS
-DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_DIRSYMBOL_EXISTS_FLAGS}
"${CHECK_DIRSYMBOL_EXISTS_LIBS}"
"${CMAKE_DIRSYMBOL_EXISTS_INCLUDES}"
OUTPUT_VARIABLE OUTPUT)
IF(${VARIABLE})
MESSAGE(STATUS "Looking for DIR in ${FILES} - found")
SET(${VARIABLE} 1 CACHE INTERNAL "Have symbol DIR")
FILE(APPEND ${CMAKE_BINARY_DIR}/CMakeFiles/CMakeOutput.log
"Determining if the DIR symbol is defined as in AC_HEADER_DIRENT "
"passed with the following output:\n"
"${OUTPUT}\nFile ${CMAKE_BINARY_DIR}/CMakeFiles/CMakeTmp/CheckDIRSymbolExists.c:\n"
"${CMAKE_CONFIGURABLE_FILE_CONTENT}\n")
ELSE(${VARIABLE})
MESSAGE(STATUS "Looking for DIR in ${FILES} - not found.")
SET(${VARIABLE} "" CACHE INTERNAL "Have symbol DIR")
FILE(APPEND ${CMAKE_BINARY_DIR}/CMakeFiles/CMakeError.log
"Determining if the DIR symbol is defined as in AC_HEADER_DIRENT "
"failed with the following output:\n"
"${OUTPUT}\nFile ${CMAKE_BINARY_DIR}/CMakeFiles/CMakeTmp/CheckDIRSymbolExists.c:\n"
"${CMAKE_CONFIGURABLE_FILE_CONTENT}\n")
ENDIF(${VARIABLE})
ENDIF(NOT DEFINED ${VARIABLE})
ENDMACRO(CHECK_DIRSYMBOL_EXISTS)
|
281677160/openwrt-package | 7,176 | luci-app-ssr-plus/shadowsocksr-libev/src/cmake/configure.cmake | # Build args
if (${with_crypto_library} STREQUAL "openssl")
find_package(ZLIB REQUIRED)
find_package(OpenSSL REQUIRED)
set(USE_CRYPTO_OPENSSL 1)
set(LIBCRYPTO
${ZLIB_LIBRARIES}
${OPENSSL_CRYPTO_LIBRARY})
include_directories(${ZLIB_INCLUDE_DIR})
include_directories(${OPENSSL_INCLUDE_DIR})
list ( APPEND CMAKE_REQUIRED_INCLUDES ${ZLIB_INCLUDE_DIR} ${OPENSSL_INCLUDE_DIR})
elseif(${with_crypto_library} STREQUAL "polarssl")
find_package(polarssl REQUIRED)
set(USE_CRYPTO_POLARSSL 1)
elseif(${with_crypto_library} STREQUAL "mbedtls")
find_package(mbedtls REQUIRED)
set(USE_CRYPTO_MBEDTLS 1)
endif()
find_package(PCRE REQUIRED)
include_directories(${PCRE_INCLUDE_DIR})
list ( APPEND CMAKE_REQUIRED_INCLUDES ${PCRE_INCLUDE_DIR})
# Platform checks
include ( CheckFunctionExists )
include ( CheckIncludeFiles )
include ( CheckSymbolExists )
include ( CheckCSourceCompiles )
include ( CheckTypeSize )
include ( CheckSTDC )
check_include_files ( "arpa/inet.h" HAVE_ARPA_INET_H )
check_include_files ( "CommonCrypto/CommonCrypto.h" HAVE_COMMONCRYPTO_COMMONCRYPTO_H )
check_include_files ( dlfcn.h HAVE_DLFCN_H )
check_include_files ( fcntl.h HAVE_FCNTL_H )
check_include_files ( inttypes.h HAVE_INTTYPES_H )
check_include_files ( langinfo.h HAVE_LANGINFO_H )
check_include_files ( limits.h HAVE_LIMITS_H )
check_include_files ( "linux/if.h" HAVE_LINUX_IF_H )
check_include_files ( "linux/netfilter_ipv4.h" HAVE_LINUX_NETFILTER_IPV4_H )
check_include_files ( "linux/netfilter_ipv6/ip6_tables.h" HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H )
check_include_files ( locale.h HAVE_LOCALE_H )
check_include_files ( memory.h HAVE_MEMORY_H )
check_include_files ( netdb.h HAVE_NETDB_H )
check_include_files ( "net/if.h" HAVE_NET_IF_H )
check_include_files ( "openssl/engine.h" HAVE_OPENSSL_ENGINE_H )
check_include_files ( "openssl/err.h" HAVE_OPENSSL_ERR_H )
check_include_files ( "openssl/evp.h" HAVE_OPENSSL_EVP_H )
check_include_files ( "openssl/pem.h" HAVE_OPENSSL_PEM_H )
check_include_files ( "openssl/rand.h" HAVE_OPENSSL_RAND_H )
check_include_files ( "openssl/rsa.h" HAVE_OPENSSL_RSA_H )
check_include_files ( "openssl/sha.h" HAVE_OPENSSL_SHA_H )
check_include_files ( pcre.h HAVE_PCRE_H )
check_include_files ( "pcre/pcre.h" HAVE_PCRE_PCRE_H )
check_include_files ( poll.h HAVE_POLL_H )
check_include_files ( port.h HAVE_PORT_H )
check_include_files ( stdint.h HAVE_STDINT_H )
check_include_files ( stdlib.h HAVE_STDLIB_H )
check_include_files ( strings.h HAVE_STRINGS_H )
check_include_files ( string.h HAVE_STRING_H )
check_include_files ( "sys/epoll.h" HAVE_SYS_EPOLL_H )
check_include_files ( "sys/eventfd.h" HAVE_SYS_EVENTFD_H )
check_include_files ( "sys/event.h" HAVE_SYS_EVENT_H )
check_include_files ( "sys/inotify.h" HAVE_SYS_INOTIFY_H )
check_include_files ( "sys/ioctl.h" HAVE_SYS_IOCTL_H )
check_include_files ( "sys/select.h" HAVE_SYS_SELECT_H )
check_include_files ( "sys/signalfd.h" HAVE_SYS_SIGNALFD_H )
check_include_files ( "sys/socket.h" HAVE_SYS_SOCKET_H )
check_include_files ( "sys/stat.h" HAVE_SYS_STAT_H )
check_include_files ( "sys/types.h" HAVE_SYS_TYPES_H )
check_include_files ( "sys/wait.h" HAVE_SYS_WAIT_H )
check_include_files ( unistd.h HAVE_UNISTD_H )
check_include_files ( vfork.h HAVE_VFORK_H )
check_include_files ( windows.h HAVE_WINDOWS_H )
check_include_files ( winsock2.h HAVE_WINSOCK2_H )
check_include_files ( ws2tcpip.h HAVE_WS2TCPIP_H )
check_include_files ( zlib.h HAVE_ZLIB_H )
check_include_files ( "sys/syscall.h" HAVE_SYS_CALL_H )
check_include_files ( "minix/config.h" _MINIX)
check_function_exists ( CCCryptorCreateWithMode HAVE_CCCRYPTORCREATEWITHMODE )
check_function_exists ( clock_gettime HAVE_CLOCK_GETTIME )
check_function_exists ( epoll_ctl HAVE_EPOLL_CTL )
check_function_exists ( eventfd HAVE_EVENTFD )
check_function_exists ( EVP_EncryptInit_ex HAVE_EVP_ENCRYPTINIT_EX )
check_function_exists ( floor HAVE_FLOOR )
check_function_exists ( fork HAVE_FORK )
check_function_exists ( getpwnam_r HAVE_GETPWNAM_R )
check_function_exists ( inet_ntop HAVE_INET_NTOP )
check_function_exists ( inotify_init HAVE_INOTIFY_INIT )
check_function_exists ( kqueue HAVE_KQUEUE )
check_function_exists ( malloc HAVE_MALLOC )
check_function_exists ( memset HAVE_MEMSET )
check_function_exists ( nanosleep HAVE_NANOSLEEP )
check_function_exists ( poll HAVE_POLL )
check_function_exists ( port_create HAVE_PORT_CREATE )
check_function_exists ( RAND_pseudo_bytes HAVE_RAND_PSEUDO_BYTES )
check_function_exists ( select HAVE_SELECT )
check_function_exists ( setresuid HAVE_SETRESUID )
check_function_exists ( setreuid HAVE_SETREUID )
check_function_exists ( setrlimit HAVE_SETRLIMIT )
check_function_exists ( signalfd HAVE_SIGNALFD )
check_function_exists ( socket HAVE_SOCKET )
check_function_exists ( strerror HAVE_STRERROR )
check_function_exists ( vfork HAVE_VFORK )
check_function_exists ( inet_ntop HAVE_DECL_INET_NTOP )
check_symbol_exists ( PTHREAD_PRIO_INHERIT "pthread.h" HAVE_PTHREAD_PRIO_INHERIT )
check_symbol_exists ( PTHREAD_CREATE_JOINABLE "pthread.h" HAVE_PTHREAD_CREATE_JOINABLE )
check_symbol_exists ( EINPROGRESS "sys/errno.h" HAVE_EINPROGRESS )
check_symbol_exists ( WSAEWOULDBLOCK "winerror.h" HAVE_WSAEWOULDBLOCK )
# winsock2.h and ws2_32 should provide these
if(HAVE_WINSOCK2_H)
set(HAVE_GETHOSTNAME ON)
set(HAVE_SELECT ON)
set(HAVE_SOCKET ON)
set(HAVE_INET_NTOA ON)
set(HAVE_RECV ON)
set(HAVE_SEND ON)
set(HAVE_RECVFROM ON)
set(HAVE_SENDTO ON)
set(HAVE_GETHOSTBYNAME ON)
set(HAVE_GETSERVBYNAME ON)
else(HAVE_WINSOCK2_H)
check_function_exists(gethostname HAVE_GETHOSTNAME)
check_function_exists(select HAVE_SELECT)
check_function_exists(socket HAVE_SOCKET)
check_function_exists(inet_ntoa HAVE_INET_NTOA)
check_function_exists(recv HAVE_RECV)
check_function_exists(send HAVE_SEND)
check_function_exists(recvfrom HAVE_RECVFROM)
check_function_exists(sendto HAVE_SENDTO)
check_function_exists(gethostbyname HAVE_GETHOSTBYNAME)
check_function_exists(getservbyname HAVE_GETSERVBYNAME)
endif(HAVE_WINSOCK2_H)
find_library ( HAVE_LIBPCRE pcre )
find_library ( HAVE_LIBRT rt )
find_library ( HAVE_LIBSOCKET socket )
check_c_source_compiles(
"
#include <sys/time.h>
#include <time.h>
int main(int argc, char** argv) {return 0;}
"
TIME_WITH_SYS_TIME
)
check_c_source_compiles("
__thread int tls;
int main(void) {
return 0;
}" TLS)
check_type_size(pid_t PID_T)
# Tweaks
if (${HAVE_SYS_CALL_H})
set(HAVE_CLOCK_SYSCALL ${HAVE_CLOCK_GETTIME})
endif ()
if (ZLIB_FOUND)
set (HAVE_ZLIB 1)
endif()
if (NOT HAVE_DECL_INET_NTOP)
set(HAVE_DECL_INET_NTOP 0)
endif()
if (NOT HAVE_PTHREAD_CREATE_JOINABLE)
set (PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED)
endif()
if (${_MINIX})
set (_POSIX_1_SOURCE 2)
set (_POSIX_SOURCE 1)
endif()
if (${HAVE_EINPROGRESS})
set (CONNECT_IN_PROGRESS EINPROGRESS)
elseif(${HAVE_WSAEWOULDBLOCK})
set (CONNECT_IN_PROGRESS WSAEWOULDBLOCK)
endif()
#SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99")
set (HAVE_IPv6 1)
ADD_DEFINITIONS(-DHAVE_CONFIG_H)
ADD_DEFINITIONS(-D__USE_MINGW_ANSI_STDIO=1)
|
281677160/openwrt-package | 6,617 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/ds/managed-buffer.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <stdlib.h>
#include <string.h>
#include "libcork/core/error.h"
#include "libcork/core/types.h"
#include "libcork/ds/managed-buffer.h"
#include "libcork/ds/slice.h"
#include "libcork/helpers/errors.h"
/*-----------------------------------------------------------------------
* Error handling
*/
static void
cork_slice_invalid_slice_set(size_t buf_size, size_t requested_offset,
size_t requested_length)
{
cork_error_set
(CORK_SLICE_ERROR, CORK_SLICE_INVALID_SLICE,
"Cannot slice %zu-byte buffer at %zu:%zu",
buf_size, requested_offset, requested_length);
}
/*-----------------------------------------------------------------------
* Managed buffers
*/
struct cork_managed_buffer_wrapped {
struct cork_managed_buffer parent;
void *buf;
size_t size;
cork_managed_buffer_freer free;
};
static void
cork_managed_buffer_wrapped__free(struct cork_managed_buffer *vself)
{
struct cork_managed_buffer_wrapped *self =
cork_container_of(vself, struct cork_managed_buffer_wrapped, parent);
self->free(self->buf, self->size);
cork_delete(struct cork_managed_buffer_wrapped, self);
}
static struct cork_managed_buffer_iface CORK_MANAGED_BUFFER_WRAPPED = {
cork_managed_buffer_wrapped__free
};
struct cork_managed_buffer *
cork_managed_buffer_new(const void *buf, size_t size,
cork_managed_buffer_freer free)
{
/*
DEBUG("Creating new struct cork_managed_buffer [%p:%zu], refcount now 1",
buf, size);
*/
struct cork_managed_buffer_wrapped *self =
cork_new(struct cork_managed_buffer_wrapped);
self->parent.buf = buf;
self->parent.size = size;
self->parent.ref_count = 1;
self->parent.iface = &CORK_MANAGED_BUFFER_WRAPPED;
self->buf = (void *) buf;
self->size = size;
self->free = free;
return &self->parent;
}
struct cork_managed_buffer_copied {
struct cork_managed_buffer parent;
};
#define cork_managed_buffer_copied_data(self) \
(((void *) (self)) + sizeof(struct cork_managed_buffer_copied))
#define cork_managed_buffer_copied_sizeof(sz) \
((sz) + sizeof(struct cork_managed_buffer_copied))
static void
cork_managed_buffer_copied__free(struct cork_managed_buffer *vself)
{
struct cork_managed_buffer_copied *self =
cork_container_of(vself, struct cork_managed_buffer_copied, parent);
size_t allocated_size =
cork_managed_buffer_copied_sizeof(self->parent.size);
cork_free(self, allocated_size);
}
static struct cork_managed_buffer_iface CORK_MANAGED_BUFFER_COPIED = {
cork_managed_buffer_copied__free
};
struct cork_managed_buffer *
cork_managed_buffer_new_copy(const void *buf, size_t size)
{
size_t allocated_size = cork_managed_buffer_copied_sizeof(size);
struct cork_managed_buffer_copied *self = cork_malloc(allocated_size);
if (self == NULL) {
return NULL;
}
self->parent.buf = cork_managed_buffer_copied_data(self);
self->parent.size = size;
self->parent.ref_count = 1;
self->parent.iface = &CORK_MANAGED_BUFFER_COPIED;
memcpy((void *) self->parent.buf, buf, size);
return &self->parent;
}
static void
cork_managed_buffer_free(struct cork_managed_buffer *self)
{
/*
DEBUG("Freeing struct cork_managed_buffer [%p:%zu]", self->buf, self->size);
*/
self->iface->free(self);
}
struct cork_managed_buffer *
cork_managed_buffer_ref(struct cork_managed_buffer *self)
{
/*
int old_count = self->ref_count++;
DEBUG("Referencing struct cork_managed_buffer [%p:%zu], refcount now %d",
self->buf, self->size, old_count + 1);
*/
self->ref_count++;
return self;
}
void
cork_managed_buffer_unref(struct cork_managed_buffer *self)
{
/*
int old_count = self->ref_count--;
DEBUG("Dereferencing struct cork_managed_buffer [%p:%zu], refcount now %d",
self->buf, self->size, old_count - 1);
*/
if (--self->ref_count == 0) {
cork_managed_buffer_free(self);
}
}
static struct cork_slice_iface CORK_MANAGED_BUFFER__SLICE;
static void
cork_managed_buffer__slice_free(struct cork_slice *self)
{
struct cork_managed_buffer *mbuf = self->user_data;
cork_managed_buffer_unref(mbuf);
}
static int
cork_managed_buffer__slice_copy(struct cork_slice *dest,
const struct cork_slice *src,
size_t offset, size_t length)
{
struct cork_managed_buffer *mbuf = src->user_data;
dest->buf = src->buf + offset;
dest->size = length;
dest->iface = &CORK_MANAGED_BUFFER__SLICE;
dest->user_data = cork_managed_buffer_ref(mbuf);
return 0;
}
static struct cork_slice_iface CORK_MANAGED_BUFFER__SLICE = {
cork_managed_buffer__slice_free,
cork_managed_buffer__slice_copy,
cork_managed_buffer__slice_copy,
NULL
};
int
cork_managed_buffer_slice(struct cork_slice *dest,
struct cork_managed_buffer *buffer,
size_t offset, size_t length)
{
if ((buffer != NULL) &&
(offset <= buffer->size) &&
((offset + length) <= buffer->size)) {
/*
DEBUG("Slicing [%p:%zu] at %zu:%zu, gives <%p:%zu>",
buffer->buf, buffer->size,
offset, length,
buffer->buf + offset, length);
*/
dest->buf = buffer->buf + offset;
dest->size = length;
dest->iface = &CORK_MANAGED_BUFFER__SLICE;
dest->user_data = cork_managed_buffer_ref(buffer);
return 0;
}
else {
/*
DEBUG("Cannot slice [%p:%zu] at %zu:%zu",
buffer->buf, buffer->size,
offset, length);
*/
cork_slice_clear(dest);
cork_slice_invalid_slice_set(0, offset, 0);
return -1;
}
}
int
cork_managed_buffer_slice_offset(struct cork_slice *dest,
struct cork_managed_buffer *buffer,
size_t offset)
{
if (buffer == NULL) {
cork_slice_clear(dest);
cork_slice_invalid_slice_set(0, offset, 0);
return -1;
} else {
return cork_managed_buffer_slice
(dest, buffer, offset, buffer->size - offset);
}
}
|
281677160/openwrt-package | 10,225 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/ds/array.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2013, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "libcork/core/types.h"
#include "libcork/ds/array.h"
#include "libcork/helpers/errors.h"
#ifndef CORK_ARRAY_DEBUG
#define CORK_ARRAY_DEBUG 0
#endif
#if CORK_ARRAY_DEBUG
#include <stdio.h>
#define DEBUG(...) \
do { \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
} while (0)
#else
#define DEBUG(...) /* nothing */
#endif
/*-----------------------------------------------------------------------
* Resizable arrays
*/
struct cork_array_priv {
size_t allocated_count;
size_t allocated_size;
size_t element_size;
size_t initialized_count;
void *user_data;
cork_free_f free_user_data;
cork_init_f init;
cork_done_f done;
cork_init_f reuse;
cork_done_f remove;
};
void
cork_raw_array_init(struct cork_raw_array *array, size_t element_size)
{
array->items = NULL;
array->size = 0;
array->priv = cork_new(struct cork_array_priv);
array->priv->allocated_count = 0;
array->priv->allocated_size = 0;
array->priv->element_size = element_size;
array->priv->initialized_count = 0;
array->priv->user_data = NULL;
array->priv->free_user_data = NULL;
array->priv->init = NULL;
array->priv->done = NULL;
array->priv->reuse = NULL;
array->priv->remove = NULL;
}
void
cork_raw_array_done(struct cork_raw_array *array)
{
if (array->priv->done != NULL) {
size_t i;
char *element = array->items;
for (i = 0; i < array->priv->initialized_count; i++) {
array->priv->done(array->priv->user_data, element);
element += array->priv->element_size;
}
}
if (array->items != NULL) {
cork_free(array->items, array->priv->allocated_size);
}
cork_free_user_data(array->priv);
cork_delete(struct cork_array_priv, array->priv);
}
void
cork_raw_array_set_callback_data(struct cork_raw_array *array,
void *user_data, cork_free_f free_user_data)
{
array->priv->user_data = user_data;
array->priv->free_user_data = free_user_data;
}
void
cork_raw_array_set_init(struct cork_raw_array *array, cork_init_f init)
{
array->priv->init = init;
}
void
cork_raw_array_set_done(struct cork_raw_array *array, cork_done_f done)
{
array->priv->done = done;
}
void
cork_raw_array_set_reuse(struct cork_raw_array *array, cork_init_f reuse)
{
array->priv->reuse = reuse;
}
void
cork_raw_array_set_remove(struct cork_raw_array *array, cork_done_f remove)
{
array->priv->remove = remove;
}
size_t
cork_raw_array_element_size(const struct cork_raw_array *array)
{
return array->priv->element_size;
}
void
cork_raw_array_clear(struct cork_raw_array *array)
{
if (array->priv->remove != NULL) {
size_t i;
char *element = array->items;
for (i = 0; i < array->priv->initialized_count; i++) {
array->priv->remove(array->priv->user_data, element);
element += array->priv->element_size;
}
}
array->size = 0;
}
void *
cork_raw_array_elements(const struct cork_raw_array *array)
{
return array->items;
}
void *
cork_raw_array_at(const struct cork_raw_array *array, size_t index)
{
return ((char *) array->items) + (array->priv->element_size * index);
}
size_t
cork_raw_array_size(const struct cork_raw_array *array)
{
return array->size;
}
bool
cork_raw_array_is_empty(const struct cork_raw_array *array)
{
return (array->size == 0);
}
void
cork_raw_array_ensure_size(struct cork_raw_array *array, size_t desired_count)
{
size_t desired_size;
DEBUG("--- Array %p: Ensure %zu %zu-byte elements",
array, desired_count, array->priv->element_size);
desired_size = desired_count * array->priv->element_size;
if (desired_size > array->priv->allocated_size) {
size_t new_count = array->priv->allocated_count * 2;
size_t new_size = array->priv->allocated_size * 2;
if (desired_size > new_size) {
new_count = desired_count;
new_size = desired_size;
}
DEBUG("--- Array %p: Reallocating %zu->%zu bytes",
array, array->priv->allocated_size, new_size);
array->items =
cork_realloc(array->items, array->priv->allocated_size, new_size);
array->priv->allocated_count = new_count;
array->priv->allocated_size = new_size;
}
}
void *
cork_raw_array_append(struct cork_raw_array *array)
{
size_t index;
void *element;
index = array->size++;
cork_raw_array_ensure_size(array, array->size);
element = cork_raw_array_at(array, index);
/* Call the init or reset callback, depending on whether this entry has been
* initialized before. */
/* Since we can currently only add elements by appending them one at a time,
* then this entry is either already initialized, or is the first
* uninitialized entry. */
assert(index <= array->priv->initialized_count);
if (index == array->priv->initialized_count) {
/* This element has not been initialized yet. */
array->priv->initialized_count++;
if (array->priv->init != NULL) {
array->priv->init(array->priv->user_data, element);
}
} else {
/* This element has already been initialized. */
if (array->priv->reuse != NULL) {
array->priv->reuse(array->priv->user_data, element);
}
}
return element;
}
int
cork_raw_array_copy(struct cork_raw_array *dest,
const struct cork_raw_array *src,
cork_copy_f copy, void *user_data)
{
size_t i;
size_t reuse_count;
char *dest_element;
DEBUG("--- Copying %zu elements (%zu bytes) from %p to %p",
src->size, src->size * dest->priv->element_size, src, dest);
assert(dest->priv->element_size == src->priv->element_size);
cork_array_clear(dest);
cork_array_ensure_size(dest, src->size);
/* Initialize enough elements to hold the contents of src */
reuse_count = dest->priv->initialized_count;
if (src->size < reuse_count) {
reuse_count = src->size;
}
dest_element = dest->items;
if (dest->priv->reuse != NULL) {
DEBUG(" Calling reuse on elements 0-%zu", reuse_count);
for (i = 0; i < reuse_count; i++) {
dest->priv->reuse(dest->priv->user_data, dest_element);
dest_element += dest->priv->element_size;
}
} else {
dest_element += reuse_count * dest->priv->element_size;
}
if (dest->priv->init != NULL) {
DEBUG(" Calling init on elements %zu-%zu", reuse_count, src->size);
for (i = reuse_count; i < src->size; i++) {
dest->priv->init(dest->priv->user_data, dest_element);
dest_element += dest->priv->element_size;
}
}
if (src->size > dest->priv->initialized_count) {
dest->priv->initialized_count = src->size;
}
/* If the caller provided a copy function, let it copy each element in turn.
* Otherwise, bulk copy everything using memcpy. */
if (copy == NULL) {
memcpy(dest->items, src->items, src->size * dest->priv->element_size);
} else {
const char *src_element = src->items;
dest_element = dest->items;
for (i = 0; i < src->size; i++) {
rii_check(copy(user_data, dest_element, src_element));
dest_element += dest->priv->element_size;
src_element += dest->priv->element_size;
}
}
dest->size = src->size;
return 0;
}
/*-----------------------------------------------------------------------
* Pointer arrays
*/
struct cork_pointer_array {
cork_free_f free;
};
static void
pointer__init(void *user_data, void *vvalue)
{
void **value = vvalue;
*value = NULL;
}
static void
pointer__done(void *user_data, void *vvalue)
{
struct cork_pointer_array *ptr_array = user_data;
void **value = vvalue;
if (*value != NULL) {
ptr_array->free(*value);
}
}
static void
pointer__remove(void *user_data, void *vvalue)
{
struct cork_pointer_array *ptr_array = user_data;
void **value = vvalue;
if (*value != NULL) {
ptr_array->free(*value);
}
*value = NULL;
}
static void
pointer__free(void *user_data)
{
struct cork_pointer_array *ptr_array = user_data;
cork_delete(struct cork_pointer_array, ptr_array);
}
void
cork_raw_pointer_array_init(struct cork_raw_array *array, cork_free_f free_ptr)
{
struct cork_pointer_array *ptr_array = cork_new(struct cork_pointer_array);
ptr_array->free = free_ptr;
cork_raw_array_init(array, sizeof(void *));
cork_array_set_callback_data(array, ptr_array, pointer__free);
cork_array_set_init(array, pointer__init);
cork_array_set_done(array, pointer__done);
cork_array_set_remove(array, pointer__remove);
}
/*-----------------------------------------------------------------------
* String arrays
*/
void
cork_string_array_init(struct cork_string_array *array)
{
cork_raw_pointer_array_init
((struct cork_raw_array *) array, (cork_free_f) cork_strfree);
}
void
cork_string_array_append(struct cork_string_array *array, const char *str)
{
const char *copy = cork_strdup(str);
cork_array_append(array, copy);
}
static int
string__copy(void *user_data, void *vdest, const void *vsrc)
{
const char **dest = vdest;
const char **src = (const char **) vsrc;
*dest = cork_strdup(*src);
return 0;
}
void
cork_string_array_copy(struct cork_string_array *dest,
const struct cork_string_array *src)
{
CORK_ATTR_UNUSED int rc;
rc = cork_array_copy(dest, src, string__copy, NULL);
/* cork_array_copy can only fail if the copy callback fails, and ours
* doesn't! */
assert(rc == 0);
}
|
281677160/openwrt-package | 7,426 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/ds/slice.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2012, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license
* details.
* ----------------------------------------------------------------------
*/
#include <string.h>
#include "libcork/core/error.h"
#include "libcork/core/types.h"
#include "libcork/ds/managed-buffer.h"
#include "libcork/ds/slice.h"
#include "libcork/helpers/errors.h"
/*-----------------------------------------------------------------------
* Error handling
*/
static void
cork_slice_invalid_slice_set(size_t buf_size, size_t requested_offset,
size_t requested_length)
{
cork_error_set
(CORK_SLICE_ERROR, CORK_SLICE_INVALID_SLICE,
"Cannot slice %zu-byte buffer at %zu:%zu",
buf_size, requested_offset, requested_length);
}
/*-----------------------------------------------------------------------
* Slices
*/
void
cork_slice_clear(struct cork_slice *slice)
{
slice->buf = NULL;
slice->size = 0;
slice->iface = NULL;
slice->user_data = NULL;
}
int
cork_slice_copy(struct cork_slice *dest, const struct cork_slice *slice,
size_t offset, size_t length)
{
if ((slice != NULL) &&
(offset <= slice->size) &&
((offset + length) <= slice->size)) {
/*
DEBUG("Slicing <%p:%zu> at %zu:%zu, gives <%p:%zu>",
slice->buf, slice->size,
offset, length,
slice->buf + offset, length);
*/
return slice->iface->copy(dest, slice, offset, length);
}
else {
/*
DEBUG("Cannot slice <%p:%zu> at %zu:%zu",
slice->buf, slice->size,
offset, length);
*/
cork_slice_clear(dest);
cork_slice_invalid_slice_set
((slice == NULL)? 0: slice->size, offset, length);
return -1;
}
}
int
cork_slice_copy_offset(struct cork_slice *dest, const struct cork_slice *slice,
size_t offset)
{
if (slice == NULL) {
cork_slice_clear(dest);
cork_slice_invalid_slice_set(0, offset, 0);
return -1;
} else {
return cork_slice_copy
(dest, slice, offset, slice->size - offset);
}
}
int
cork_slice_light_copy(struct cork_slice *dest, const struct cork_slice *slice,
size_t offset, size_t length)
{
if ((slice != NULL) &&
(offset <= slice->size) &&
((offset + length) <= slice->size)) {
/*
DEBUG("Slicing <%p:%zu> at %zu:%zu, gives <%p:%zu>",
slice->buf, slice->size,
offset, length,
slice->buf + offset, length);
*/
return slice->iface->light_copy(dest, slice, offset, length);
}
else {
/*
DEBUG("Cannot slice <%p:%zu> at %zu:%zu",
slice->buf, slice->size,
offset, length);
*/
cork_slice_clear(dest);
cork_slice_invalid_slice_set
((slice == NULL)? 0: slice->size, offset, length);
return -1;
}
}
int
cork_slice_light_copy_offset(struct cork_slice *dest,
const struct cork_slice *slice, size_t offset)
{
if (slice == NULL) {
cork_slice_clear(dest);
cork_slice_invalid_slice_set(0, offset, 0);
return -1;
} else {
return cork_slice_light_copy
(dest, slice, offset, slice->size - offset);
}
}
int
cork_slice_slice(struct cork_slice *slice, size_t offset, size_t length)
{
if ((slice != NULL) &&
(offset <= slice->size) &&
((offset + length) <= slice->size)) {
/*
DEBUG("Slicing <%p:%zu> at %zu:%zu, gives <%p:%zu>",
slice->buf, slice->size,
offset, length,
slice->buf + offset, length);
*/
if (slice->iface->slice == NULL) {
slice->buf += offset;
slice->size = length;
return 0;
} else {
return slice->iface->slice(slice, offset, length);
}
}
else {
/*
DEBUG("Cannot slice <%p:%zu> at %zu:%zu",
slice->buf, slice->size,
offset, length);
*/
if (slice != NULL)
cork_slice_invalid_slice_set(slice->size, offset, length);
return -1;
}
}
int
cork_slice_slice_offset(struct cork_slice *slice, size_t offset)
{
if (slice == NULL) {
cork_slice_invalid_slice_set(0, offset, 0);
return -1;
} else {
return cork_slice_slice
(slice, offset, slice->size - offset);
}
}
void
cork_slice_finish(struct cork_slice *slice)
{
/*
DEBUG("Finalizing <%p:%zu>", dest->buf, dest->size);
*/
if (slice->iface != NULL && slice->iface->free != NULL) {
slice->iface->free(slice);
}
cork_slice_clear(slice);
}
bool
cork_slice_equal(const struct cork_slice *slice1,
const struct cork_slice *slice2)
{
if (slice1 == slice2) {
return true;
}
if (slice1->size != slice2->size) {
return false;
}
return (memcmp(slice1->buf, slice2->buf, slice1->size) == 0);
}
/*-----------------------------------------------------------------------
* Slices of static content
*/
static struct cork_slice_iface cork_static_slice;
static int
cork_static_slice_copy(struct cork_slice *dest, const struct cork_slice *src,
size_t offset, size_t length)
{
dest->buf = src->buf + offset;
dest->size = length;
dest->iface = &cork_static_slice;
dest->user_data = NULL;
return 0;
}
static struct cork_slice_iface cork_static_slice = {
NULL,
cork_static_slice_copy,
cork_static_slice_copy,
NULL
};
void
cork_slice_init_static(struct cork_slice *dest, const void *buf, size_t size)
{
dest->buf = buf;
dest->size = size;
dest->iface = &cork_static_slice;
dest->user_data = NULL;
}
/*-----------------------------------------------------------------------
* Copy-once slices
*/
static struct cork_slice_iface cork_copy_once_slice;
static int
cork_copy_once_slice__copy(struct cork_slice *dest,
const struct cork_slice *src,
size_t offset, size_t length)
{
struct cork_managed_buffer *mbuf =
cork_managed_buffer_new_copy(src->buf, src->size);
rii_check(cork_managed_buffer_slice(dest, mbuf, offset, length));
rii_check(cork_managed_buffer_slice
((struct cork_slice *) src, mbuf, 0, src->size));
cork_managed_buffer_unref(mbuf);
return 0;
}
static int
cork_copy_once_slice__light_copy(struct cork_slice *dest,
const struct cork_slice *src,
size_t offset, size_t length)
{
dest->buf = src->buf + offset;
dest->size = length;
dest->iface = &cork_copy_once_slice;
dest->user_data = NULL;
return 0;
}
static struct cork_slice_iface cork_copy_once_slice = {
NULL,
cork_copy_once_slice__copy,
cork_copy_once_slice__light_copy,
NULL
};
void
cork_slice_init_copy_once(struct cork_slice *dest, const void *buf, size_t size)
{
dest->buf = buf;
dest->size = size;
dest->iface = &cork_copy_once_slice;
dest->user_data = NULL;
}
|
281677160/openwrt-package | 12,950 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/ds/buffer.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "libcork/core/allocator.h"
#include "libcork/core/types.h"
#include "libcork/ds/buffer.h"
#include "libcork/ds/managed-buffer.h"
#include "libcork/ds/stream.h"
#include "libcork/helpers/errors.h"
void
cork_buffer_init(struct cork_buffer *buffer)
{
buffer->buf = NULL;
buffer->size = 0;
buffer->allocated_size = 0;
}
struct cork_buffer *
cork_buffer_new(void)
{
struct cork_buffer *buffer = cork_new(struct cork_buffer);
cork_buffer_init(buffer);
return buffer;
}
void
cork_buffer_done(struct cork_buffer *buffer)
{
if (buffer->buf != NULL) {
cork_free(buffer->buf, buffer->allocated_size);
buffer->buf = NULL;
}
buffer->size = 0;
buffer->allocated_size = 0;
}
void
cork_buffer_free(struct cork_buffer *buffer)
{
cork_buffer_done(buffer);
cork_delete(struct cork_buffer, buffer);
}
bool
cork_buffer_equal(const struct cork_buffer *buffer1,
const struct cork_buffer *buffer2)
{
if (buffer1 == buffer2) {
return true;
}
if (buffer1->size != buffer2->size) {
return false;
}
return (memcmp(buffer1->buf, buffer2->buf, buffer1->size) == 0);
}
static void
cork_buffer_ensure_size_int(struct cork_buffer *buffer, size_t desired_size)
{
size_t new_size;
if (CORK_LIKELY(buffer->allocated_size >= desired_size)) {
return;
}
/* Make sure we at least double the old size when reallocating. */
new_size = buffer->allocated_size * 2;
if (desired_size > new_size) {
new_size = desired_size;
}
buffer->buf = cork_realloc(buffer->buf, buffer->allocated_size, new_size);
buffer->allocated_size = new_size;
}
void
cork_buffer_ensure_size(struct cork_buffer *buffer, size_t desired_size)
{
cork_buffer_ensure_size_int(buffer, desired_size);
}
void
cork_buffer_clear(struct cork_buffer *buffer)
{
buffer->size = 0;
if (buffer->buf != NULL) {
((char *) buffer->buf)[0] = '\0';
}
}
void
cork_buffer_truncate(struct cork_buffer *buffer, size_t length)
{
if (buffer->size > length) {
buffer->size = length;
if (length == 0) {
if (buffer->buf != NULL) {
((char *) buffer->buf)[0] = '\0';
}
} else {
((char *) buffer->buf)[length] = '\0';
}
}
}
void
cork_buffer_set(struct cork_buffer *buffer, const void *src, size_t length)
{
cork_buffer_ensure_size_int(buffer, length+1);
memcpy(buffer->buf, src, length);
((char *) buffer->buf)[length] = '\0';
buffer->size = length;
}
void
cork_buffer_append(struct cork_buffer *buffer, const void *src, size_t length)
{
cork_buffer_ensure_size_int(buffer, buffer->size + length + 1);
memcpy(buffer->buf + buffer->size, src, length);
buffer->size += length;
((char *) buffer->buf)[buffer->size] = '\0';
}
void
cork_buffer_set_string(struct cork_buffer *buffer, const char *str)
{
cork_buffer_set(buffer, str, strlen(str));
}
void
cork_buffer_append_string(struct cork_buffer *buffer, const char *str)
{
cork_buffer_append(buffer, str, strlen(str));
}
void
cork_buffer_append_vprintf(struct cork_buffer *buffer, const char *format,
va_list args)
{
size_t format_size;
va_list args1;
va_copy(args1, args);
format_size = vsnprintf(buffer->buf + buffer->size,
buffer->allocated_size - buffer->size,
format, args1);
va_end(args1);
/* If the first call works, then set buffer->size and return. */
if (format_size < (buffer->allocated_size - buffer->size)) {
buffer->size += format_size;
return;
}
/* If the first call fails, resize buffer and try again. */
cork_buffer_ensure_size_int
(buffer, buffer->allocated_size + format_size + 1);
format_size = vsnprintf(buffer->buf + buffer->size,
buffer->allocated_size - buffer->size,
format, args);
buffer->size += format_size;
}
void
cork_buffer_vprintf(struct cork_buffer *buffer, const char *format,
va_list args)
{
cork_buffer_clear(buffer);
cork_buffer_append_vprintf(buffer, format, args);
}
void
cork_buffer_append_printf(struct cork_buffer *buffer, const char *format, ...)
{
va_list args;
va_start(args, format);
cork_buffer_append_vprintf(buffer, format, args);
va_end(args);
}
void
cork_buffer_printf(struct cork_buffer *buffer, const char *format, ...)
{
va_list args;
va_start(args, format);
cork_buffer_vprintf(buffer, format, args);
va_end(args);
}
void
cork_buffer_append_indent(struct cork_buffer *buffer, size_t indent)
{
cork_buffer_ensure_size_int(buffer, buffer->size + indent + 1);
memset(buffer->buf + buffer->size, ' ', indent);
buffer->size += indent;
((char *) buffer->buf)[buffer->size] = '\0';
}
/* including space */
#define is_sprint(ch) ((ch) >= 0x20 && (ch) <= 0x7e)
/* not including space */
#define is_print(ch) ((ch) > 0x20 && (ch) <= 0x7e)
#define is_space(ch) \
((ch) == ' ' || \
(ch) == '\f' || \
(ch) == '\n' || \
(ch) == '\r' || \
(ch) == '\t' || \
(ch) == '\v')
#define to_hex(nybble) \
((nybble) < 10? '0' + (nybble): 'a' - 10 + (nybble))
void
cork_buffer_append_c_string(struct cork_buffer *dest,
const char *chars, size_t length)
{
size_t i;
cork_buffer_append(dest, "\"", 1);
for (i = 0; i < length; i++) {
char ch = chars[i];
switch (ch) {
case '\"':
cork_buffer_append_literal(dest, "\\\"");
break;
case '\\':
cork_buffer_append_literal(dest, "\\\\");
break;
case '\f':
cork_buffer_append_literal(dest, "\\f");
break;
case '\n':
cork_buffer_append_literal(dest, "\\n");
break;
case '\r':
cork_buffer_append_literal(dest, "\\r");
break;
case '\t':
cork_buffer_append_literal(dest, "\\t");
break;
case '\v':
cork_buffer_append_literal(dest, "\\v");
break;
default:
if (is_sprint(ch)) {
cork_buffer_append(dest, &chars[i], 1);
} else {
uint8_t byte = ch;
cork_buffer_append_printf(dest, "\\x%02" PRIx8, byte);
}
break;
}
}
cork_buffer_append(dest, "\"", 1);
}
void
cork_buffer_append_hex_dump(struct cork_buffer *dest, size_t indent,
const char *chars, size_t length)
{
char hex[3 * 16];
char print[16];
char *curr_hex = hex;
char *curr_print = print;
size_t i;
size_t column = 0;
for (i = 0; i < length; i++) {
char ch = chars[i];
uint8_t u8 = ch;
*curr_hex++ = to_hex(u8 >> 4);
*curr_hex++ = to_hex(u8 & 0x0f);
*curr_hex++ = ' ';
*curr_print++ = is_sprint(ch)? ch: '.';
if (column == 0 && i != 0) {
cork_buffer_append_literal(dest, "\n");
cork_buffer_append_indent(dest, indent);
column++;
} else if (column == 15) {
cork_buffer_append_printf
(dest, "%-48.*s", (int) (curr_hex - hex), hex);
cork_buffer_append_literal(dest, " |");
cork_buffer_append(dest, print, curr_print - print);
cork_buffer_append_literal(dest, "|");
curr_hex = hex;
curr_print = print;
column = 0;
} else {
column++;
}
}
if (column > 0) {
cork_buffer_append_printf(dest, "%-48.*s", (int) (curr_hex - hex), hex);
cork_buffer_append_literal(dest, " |");
cork_buffer_append(dest, print, curr_print - print);
cork_buffer_append_literal(dest, "|");
}
}
void
cork_buffer_append_multiline(struct cork_buffer *dest, size_t indent,
const char *chars, size_t length)
{
size_t i;
for (i = 0; i < length; i++) {
char ch = chars[i];
if (ch == '\n') {
cork_buffer_append_literal(dest, "\n");
cork_buffer_append_indent(dest, indent);
} else {
cork_buffer_append(dest, &chars[i], 1);
}
}
}
void
cork_buffer_append_binary(struct cork_buffer *dest, size_t indent,
const char *chars, size_t length)
{
size_t i;
bool newline = false;
/* If there are any non-printable characters, print out a hex dump */
for (i = 0; i < length; i++) {
if (!is_print(chars[i]) && !is_space(chars[i])) {
cork_buffer_append_literal(dest, "(hex)\n");
cork_buffer_append_indent(dest, indent);
cork_buffer_append_hex_dump(dest, indent, chars, length);
return;
} else if (chars[i] == '\n') {
newline = true;
/* Don't immediately use the multiline format, since there might be
* a non-printable character later on that kicks us over to the hex
* dump format. */
}
}
if (newline) {
cork_buffer_append_literal(dest, "(multiline)\n");
cork_buffer_append_indent(dest, indent);
cork_buffer_append_multiline(dest, indent, chars, length);
} else {
cork_buffer_append(dest, chars, length);
}
}
struct cork_buffer__managed_buffer {
struct cork_managed_buffer parent;
struct cork_buffer *buffer;
};
static void
cork_buffer__managed_free(struct cork_managed_buffer *vself)
{
struct cork_buffer__managed_buffer *self =
cork_container_of(vself, struct cork_buffer__managed_buffer, parent);
cork_buffer_free(self->buffer);
cork_delete(struct cork_buffer__managed_buffer, self);
}
static struct cork_managed_buffer_iface CORK_BUFFER__MANAGED_BUFFER = {
cork_buffer__managed_free
};
struct cork_managed_buffer *
cork_buffer_to_managed_buffer(struct cork_buffer *buffer)
{
struct cork_buffer__managed_buffer *self =
cork_new(struct cork_buffer__managed_buffer);
self->parent.buf = buffer->buf;
self->parent.size = buffer->size;
self->parent.ref_count = 1;
self->parent.iface = &CORK_BUFFER__MANAGED_BUFFER;
self->buffer = buffer;
return &self->parent;
}
int
cork_buffer_to_slice(struct cork_buffer *buffer, struct cork_slice *slice)
{
struct cork_managed_buffer *managed =
cork_buffer_to_managed_buffer(buffer);
/* We don't have to check for NULL; cork_managed_buffer_slice_offset
* will do that for us. */
int rc = cork_managed_buffer_slice_offset(slice, managed, 0);
/* Before returning, drop our reference to the managed buffer. If
* the slicing succeeded, then there will be one remaining reference
* in the slice. If it didn't succeed, this will free the managed
* buffer for us. */
cork_managed_buffer_unref(managed);
return rc;
}
struct cork_buffer__stream_consumer {
struct cork_stream_consumer consumer;
struct cork_buffer *buffer;
};
static int
cork_buffer_stream_consumer_data(struct cork_stream_consumer *consumer,
const void *buf, size_t size,
bool is_first_chunk)
{
struct cork_buffer__stream_consumer *bconsumer = cork_container_of
(consumer, struct cork_buffer__stream_consumer, consumer);
cork_buffer_append(bconsumer->buffer, buf, size);
return 0;
}
static int
cork_buffer_stream_consumer_eof(struct cork_stream_consumer *consumer)
{
return 0;
}
static void
cork_buffer_stream_consumer_free(struct cork_stream_consumer *consumer)
{
struct cork_buffer__stream_consumer *bconsumer =
cork_container_of
(consumer, struct cork_buffer__stream_consumer, consumer);
cork_delete(struct cork_buffer__stream_consumer, bconsumer);
}
struct cork_stream_consumer *
cork_buffer_to_stream_consumer(struct cork_buffer *buffer)
{
struct cork_buffer__stream_consumer *bconsumer =
cork_new(struct cork_buffer__stream_consumer);
bconsumer->consumer.data = cork_buffer_stream_consumer_data;
bconsumer->consumer.eof = cork_buffer_stream_consumer_eof;
bconsumer->consumer.free = cork_buffer_stream_consumer_free;
bconsumer->buffer = buffer;
return &bconsumer->consumer;
}
|
281677160/openwrt-package | 20,285 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/ds/hash-table.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <stdlib.h>
#include <string.h>
#include "libcork/core/callbacks.h"
#include "libcork/core/hash.h"
#include "libcork/core/types.h"
#include "libcork/ds/dllist.h"
#include "libcork/ds/hash-table.h"
#include "libcork/helpers/errors.h"
#ifndef CORK_HASH_TABLE_DEBUG
#define CORK_HASH_TABLE_DEBUG 0
#endif
#if CORK_HASH_TABLE_DEBUG
#include <stdio.h>
#define DEBUG(...) \
do { \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
} while (0)
#else
#define DEBUG(...) /* nothing */
#endif
/*-----------------------------------------------------------------------
* Hash tables
*/
struct cork_hash_table_entry_priv {
struct cork_hash_table_entry public;
struct cork_dllist_item in_bucket;
struct cork_dllist_item insertion_order;
};
struct cork_hash_table {
struct cork_dllist *bins;
struct cork_dllist insertion_order;
size_t bin_count;
size_t bin_mask;
size_t entry_count;
void *user_data;
cork_free_f free_user_data;
cork_hash_f hash;
cork_equals_f equals;
cork_free_f free_key;
cork_free_f free_value;
};
static cork_hash
cork_hash_table__default_hash(void *user_data, const void *key)
{
return (cork_hash) (uintptr_t) key;
}
static bool
cork_hash_table__default_equals(void *user_data,
const void *key1, const void *key2)
{
return key1 == key2;
}
/* The default initial number of bins to allocate in a new table. */
#define CORK_HASH_TABLE_DEFAULT_INITIAL_SIZE 8
/* The default number of entries per bin to allow before increasing the
* number of bins. */
#define CORK_HASH_TABLE_MAX_DENSITY 5
/* Return a power-of-2 bin count that's at least as big as the given requested
* size. */
static inline size_t
cork_hash_table_new_size(size_t desired_count)
{
size_t v = desired_count;
size_t r = 1;
while (v >>= 1) {
r <<= 1;
}
if (r != desired_count) {
r <<= 1;
}
return r;
}
#define bin_index(table, hash) ((hash) & (table)->bin_mask)
/* Allocates a new bins array in a hash table. We overwrite the old
* array, so make sure to stash it away somewhere safe first. */
static void
cork_hash_table_allocate_bins(struct cork_hash_table *table,
size_t desired_count)
{
size_t i;
table->bin_count = cork_hash_table_new_size(desired_count);
table->bin_mask = table->bin_count - 1;
DEBUG("Allocate %zu bins", table->bin_count);
table->bins = cork_calloc(table->bin_count, sizeof(struct cork_dllist));
for (i = 0; i < table->bin_count; i++) {
cork_dllist_init(&table->bins[i]);
}
}
static struct cork_hash_table_entry_priv *
cork_hash_table_new_entry(struct cork_hash_table *table,
cork_hash hash, void *key, void *value)
{
struct cork_hash_table_entry_priv *entry =
cork_new(struct cork_hash_table_entry_priv);
cork_dllist_add(&table->insertion_order, &entry->insertion_order);
entry->public.hash = hash;
entry->public.key = key;
entry->public.value = value;
return entry;
}
static void
cork_hash_table_free_entry(struct cork_hash_table *table,
struct cork_hash_table_entry_priv *entry)
{
if (table->free_key != NULL) {
table->free_key(entry->public.key);
}
if (table->free_value != NULL) {
table->free_value(entry->public.value);
}
cork_dllist_remove(&entry->insertion_order);
cork_delete(struct cork_hash_table_entry_priv, entry);
}
struct cork_hash_table *
cork_hash_table_new(size_t initial_size, unsigned int flags)
{
struct cork_hash_table *table = cork_new(struct cork_hash_table);
table->entry_count = 0;
table->user_data = NULL;
table->free_user_data = NULL;
table->hash = cork_hash_table__default_hash;
table->equals = cork_hash_table__default_equals;
table->free_key = NULL;
table->free_value = NULL;
cork_dllist_init(&table->insertion_order);
if (initial_size < CORK_HASH_TABLE_DEFAULT_INITIAL_SIZE) {
initial_size = CORK_HASH_TABLE_DEFAULT_INITIAL_SIZE;
}
cork_hash_table_allocate_bins(table, initial_size);
return table;
}
void
cork_hash_table_clear(struct cork_hash_table *table)
{
size_t i;
struct cork_dllist_item *curr;
struct cork_dllist_item *next;
DEBUG("(clear) Remove all entries");
for (curr = cork_dllist_start(&table->insertion_order);
!cork_dllist_is_end(&table->insertion_order, curr);
curr = next) {
struct cork_hash_table_entry_priv *entry =
cork_container_of
(curr, struct cork_hash_table_entry_priv, insertion_order);
next = curr->next;
cork_hash_table_free_entry(table, entry);
}
cork_dllist_init(&table->insertion_order);
DEBUG("(clear) Clear bins");
for (i = 0; i < table->bin_count; i++) {
DEBUG(" Bin %zu", i);
cork_dllist_init(&table->bins[i]);
}
table->entry_count = 0;
}
void
cork_hash_table_free(struct cork_hash_table *table)
{
cork_hash_table_clear(table);
cork_cfree(table->bins, table->bin_count, sizeof(struct cork_dllist));
cork_delete(struct cork_hash_table, table);
}
size_t
cork_hash_table_size(const struct cork_hash_table *table)
{
return table->entry_count;
}
void
cork_hash_table_set_user_data(struct cork_hash_table *table,
void *user_data, cork_free_f free_user_data)
{
table->user_data = user_data;
table->free_user_data = free_user_data;
}
void
cork_hash_table_set_hash(struct cork_hash_table *table, cork_hash_f hash)
{
table->hash = hash;
}
void
cork_hash_table_set_equals(struct cork_hash_table *table, cork_equals_f equals)
{
table->equals = equals;
}
void
cork_hash_table_set_free_key(struct cork_hash_table *table, cork_free_f free)
{
table->free_key = free;
}
void
cork_hash_table_set_free_value(struct cork_hash_table *table, cork_free_f free)
{
table->free_value = free;
}
void
cork_hash_table_ensure_size(struct cork_hash_table *table, size_t desired_count)
{
if (desired_count > table->bin_count) {
struct cork_dllist *old_bins = table->bins;
size_t old_bin_count = table->bin_count;
cork_hash_table_allocate_bins(table, desired_count);
if (old_bins != NULL) {
size_t i;
for (i = 0; i < old_bin_count; i++) {
struct cork_dllist *bin = &old_bins[i];
struct cork_dllist_item *curr = cork_dllist_start(bin);
while (!cork_dllist_is_end(bin, curr)) {
struct cork_hash_table_entry_priv *entry =
cork_container_of
(curr, struct cork_hash_table_entry_priv, in_bucket);
struct cork_dllist_item *next = curr->next;
size_t bin_index = bin_index(table, entry->public.hash);
DEBUG(" Rehash %p from bin %zu to bin %zu",
entry, i, bin_index);
cork_dllist_add(&table->bins[bin_index], curr);
curr = next;
}
}
cork_cfree(old_bins, old_bin_count, sizeof(struct cork_dllist));
}
}
}
static void
cork_hash_table_rehash(struct cork_hash_table *table)
{
DEBUG(" Reached maximum density; rehash");
cork_hash_table_ensure_size(table, table->bin_count + 1);
}
struct cork_hash_table_entry *
cork_hash_table_get_entry_hash(const struct cork_hash_table *table,
cork_hash hash, const void *key)
{
size_t bin_index;
struct cork_dllist *bin;
struct cork_dllist_item *curr;
if (table->bin_count == 0) {
DEBUG("(get) Empty table when searching for key %p "
"(hash 0x%08" PRIx32 ")",
key, hash);
return NULL;
}
bin_index = bin_index(table, hash);
DEBUG("(get) Search for key %p (hash 0x%08" PRIx32 ", bin %zu)",
key, hash, bin_index);
bin = &table->bins[bin_index];
curr = cork_dllist_start(bin);
while (!cork_dllist_is_end(bin, curr)) {
struct cork_hash_table_entry_priv *entry =
cork_container_of
(curr, struct cork_hash_table_entry_priv, in_bucket);
DEBUG(" Check entry %p", entry);
if (table->equals(table->user_data, key, entry->public.key)) {
DEBUG(" Match");
return &entry->public;
}
curr = curr->next;
}
DEBUG(" Entry not found");
return NULL;
}
struct cork_hash_table_entry *
cork_hash_table_get_entry(const struct cork_hash_table *table, const void *key)
{
cork_hash hash = table->hash(table->user_data, key);
return cork_hash_table_get_entry_hash(table, hash, key);
}
void *
cork_hash_table_get_hash(const struct cork_hash_table *table,
cork_hash hash, const void *key)
{
struct cork_hash_table_entry *entry =
cork_hash_table_get_entry_hash(table, hash, key);
if (entry == NULL) {
return NULL;
} else {
DEBUG(" Extract value pointer %p", entry->value);
return entry->value;
}
}
void *
cork_hash_table_get(const struct cork_hash_table *table, const void *key)
{
struct cork_hash_table_entry *entry =
cork_hash_table_get_entry(table, key);
if (entry == NULL) {
return NULL;
} else {
DEBUG(" Extract value pointer %p", entry->value);
return entry->value;
}
}
struct cork_hash_table_entry *
cork_hash_table_get_or_create_hash(struct cork_hash_table *table,
cork_hash hash, void *key, bool *is_new)
{
struct cork_hash_table_entry_priv *entry;
size_t bin_index;
if (table->bin_count > 0) {
struct cork_dllist *bin;
struct cork_dllist_item *curr;
bin_index = bin_index(table, hash);
DEBUG("(get_or_create) Search for key %p "
"(hash 0x%08" PRIx32 ", bin %zu)",
key, hash, bin_index);
bin = &table->bins[bin_index];
curr = cork_dllist_start(bin);
while (!cork_dllist_is_end(bin, curr)) {
struct cork_hash_table_entry_priv *entry =
cork_container_of
(curr, struct cork_hash_table_entry_priv, in_bucket);
DEBUG(" Check entry %p", entry);
if (table->equals(table->user_data, key, entry->public.key)) {
DEBUG(" Match");
DEBUG(" Return value pointer %p", entry->public.value);
*is_new = false;
return &entry->public;
}
curr = curr->next;
}
/* create a new entry */
DEBUG(" Entry not found");
if ((table->entry_count / table->bin_count) >
CORK_HASH_TABLE_MAX_DENSITY) {
cork_hash_table_rehash(table);
bin_index = bin_index(table, hash);
}
} else {
DEBUG("(get_or_create) Search for key %p (hash 0x%08" PRIx32 ")",
key, hash);
DEBUG(" Empty table");
cork_hash_table_rehash(table);
bin_index = bin_index(table, hash);
}
DEBUG(" Allocate new entry");
entry = cork_hash_table_new_entry(table, hash, key, NULL);
DEBUG(" Created new entry %p", entry);
DEBUG(" Add entry into bin %zu", bin_index);
cork_dllist_add(&table->bins[bin_index], &entry->in_bucket);
table->entry_count++;
*is_new = true;
return &entry->public;
}
struct cork_hash_table_entry *
cork_hash_table_get_or_create(struct cork_hash_table *table,
void *key, bool *is_new)
{
cork_hash hash = table->hash(table->user_data, key);
return cork_hash_table_get_or_create_hash(table, hash, key, is_new);
}
void
cork_hash_table_put_hash(struct cork_hash_table *table,
cork_hash hash, void *key, void *value,
bool *is_new, void **old_key, void **old_value)
{
struct cork_hash_table_entry_priv *entry;
size_t bin_index;
if (table->bin_count > 0) {
struct cork_dllist *bin;
struct cork_dllist_item *curr;
bin_index = bin_index(table, hash);
DEBUG("(put) Search for key %p (hash 0x%08" PRIx32 ", bin %zu)",
key, hash, bin_index);
bin = &table->bins[bin_index];
curr = cork_dllist_start(bin);
while (!cork_dllist_is_end(bin, curr)) {
struct cork_hash_table_entry_priv *entry =
cork_container_of
(curr, struct cork_hash_table_entry_priv, in_bucket);
DEBUG(" Check entry %p", entry);
if (table->equals(table->user_data, key, entry->public.key)) {
DEBUG(" Found existing entry; overwriting");
DEBUG(" Return old key %p", entry->public.key);
if (old_key != NULL) {
*old_key = entry->public.key;
}
DEBUG(" Return old value %p", entry->public.value);
if (old_value != NULL) {
*old_value = entry->public.value;
}
DEBUG(" Copy key %p into entry", key);
entry->public.key = key;
DEBUG(" Copy value %p into entry", value);
entry->public.value = value;
if (is_new != NULL) {
*is_new = false;
}
return;
}
curr = curr->next;
}
/* create a new entry */
DEBUG(" Entry not found");
if ((table->entry_count / table->bin_count) >
CORK_HASH_TABLE_MAX_DENSITY) {
cork_hash_table_rehash(table);
bin_index = bin_index(table, hash);
}
} else {
DEBUG("(put) Search for key %p (hash 0x%08" PRIx32 ")",
key, hash);
DEBUG(" Empty table");
cork_hash_table_rehash(table);
bin_index = bin_index(table, hash);
}
DEBUG(" Allocate new entry");
entry = cork_hash_table_new_entry(table, hash, key, value);
DEBUG(" Created new entry %p", entry);
DEBUG(" Add entry into bin %zu", bin_index);
cork_dllist_add(&table->bins[bin_index], &entry->in_bucket);
table->entry_count++;
if (old_key != NULL) {
*old_key = NULL;
}
if (old_value != NULL) {
*old_value = NULL;
}
if (is_new != NULL) {
*is_new = true;
}
}
void
cork_hash_table_put(struct cork_hash_table *table,
void *key, void *value,
bool *is_new, void **old_key, void **old_value)
{
cork_hash hash = table->hash(table->user_data, key);
cork_hash_table_put_hash
(table, hash, key, value, is_new, old_key, old_value);
}
void
cork_hash_table_delete_entry(struct cork_hash_table *table,
struct cork_hash_table_entry *ventry)
{
struct cork_hash_table_entry_priv *entry =
cork_container_of(ventry, struct cork_hash_table_entry_priv, public);
cork_dllist_remove(&entry->in_bucket);
table->entry_count--;
cork_hash_table_free_entry(table, entry);
}
bool
cork_hash_table_delete_hash(struct cork_hash_table *table,
cork_hash hash, const void *key,
void **deleted_key, void **deleted_value)
{
size_t bin_index;
struct cork_dllist *bin;
struct cork_dllist_item *curr;
if (table->bin_count == 0) {
DEBUG("(delete) Empty table when searching for key %p "
"(hash 0x%08" PRIx32 ")",
key, hash);
return false;
}
bin_index = bin_index(table, hash);
DEBUG("(delete) Search for key %p (hash 0x%08" PRIx32 ", bin %zu)",
key, hash, bin_index);
bin = &table->bins[bin_index];
curr = cork_dllist_start(bin);
while (!cork_dllist_is_end(bin, curr)) {
struct cork_hash_table_entry_priv *entry =
cork_container_of
(curr, struct cork_hash_table_entry_priv, in_bucket);
DEBUG(" Check entry %p", entry);
if (table->equals(table->user_data, key, entry->public.key)) {
DEBUG(" Match");
if (deleted_key != NULL) {
*deleted_key = entry->public.key;
}
if (deleted_value != NULL) {
*deleted_value = entry->public.value;
}
DEBUG(" Remove entry from hash bin %zu", bin_index);
cork_dllist_remove(curr);
table->entry_count--;
DEBUG(" Free entry %p", entry);
cork_hash_table_free_entry(table, entry);
return true;
}
curr = curr->next;
}
DEBUG(" Entry not found");
return false;
}
bool
cork_hash_table_delete(struct cork_hash_table *table, const void *key,
void **deleted_key, void **deleted_value)
{
cork_hash hash = table->hash(table->user_data, key);
return cork_hash_table_delete_hash
(table, hash, key, deleted_key, deleted_value);
}
void
cork_hash_table_map(struct cork_hash_table *table, void *user_data,
cork_hash_table_map_f map)
{
struct cork_dllist_item *curr;
DEBUG("Map across hash table");
curr = cork_dllist_start(&table->insertion_order);
while (!cork_dllist_is_end(&table->insertion_order, curr)) {
struct cork_hash_table_entry_priv *entry =
cork_container_of
(curr, struct cork_hash_table_entry_priv, insertion_order);
struct cork_dllist_item *next = curr->next;
enum cork_hash_table_map_result result;
DEBUG(" Apply function to entry %p", entry);
result = map(user_data, &entry->public);
if (result == CORK_HASH_TABLE_MAP_ABORT) {
return;
} else if (result == CORK_HASH_TABLE_MAP_DELETE) {
DEBUG(" Delete requested");
cork_dllist_remove(curr);
cork_dllist_remove(&entry->in_bucket);
table->entry_count--;
cork_hash_table_free_entry(table, entry);
}
curr = next;
}
}
void
cork_hash_table_iterator_init(struct cork_hash_table *table,
struct cork_hash_table_iterator *iterator)
{
DEBUG("Iterate through hash table");
iterator->table = table;
iterator->priv = cork_dllist_start(&table->insertion_order);
}
struct cork_hash_table_entry *
cork_hash_table_iterator_next(struct cork_hash_table_iterator *iterator)
{
struct cork_hash_table *table = iterator->table;
struct cork_dllist_item *curr = iterator->priv;
struct cork_hash_table_entry_priv *entry;
if (cork_dllist_is_end(&table->insertion_order, curr)) {
return NULL;
}
entry = cork_container_of
(curr, struct cork_hash_table_entry_priv, insertion_order);
DEBUG(" Return entry %p", entry);
iterator->priv = curr->next;
return &entry->public;
}
/*-----------------------------------------------------------------------
* Built-in key types
*/
static cork_hash
string_hash(void *user_data, const void *vk)
{
const char *k = vk;
size_t len = strlen(k);
return cork_hash_buffer(0, k, len);
}
static bool
string_equals(void *user_data, const void *vk1, const void *vk2)
{
const char *k1 = vk1;
const char *k2 = vk2;
return strcmp(k1, k2) == 0;
}
struct cork_hash_table *
cork_string_hash_table_new(size_t initial_size, unsigned int flags)
{
struct cork_hash_table *table = cork_hash_table_new(initial_size, flags);
cork_hash_table_set_hash(table, string_hash);
cork_hash_table_set_equals(table, string_equals);
return table;
}
struct cork_hash_table *
cork_pointer_hash_table_new(size_t initial_size, unsigned int flags)
{
return cork_hash_table_new(initial_size, flags);
}
|
281677160/openwrt-package | 5,600 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/ds/file-stream.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2012-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include "libcork/ds/stream.h"
#include "libcork/helpers/errors.h"
#include "libcork/helpers/posix.h"
#define BUFFER_SIZE 4096
/*-----------------------------------------------------------------------
* Producers
*/
int
cork_consume_fd(struct cork_stream_consumer *consumer, int fd)
{
char buf[BUFFER_SIZE];
ssize_t bytes_read;
bool first = true;
while (true) {
while ((bytes_read = read(fd, buf, BUFFER_SIZE)) > 0) {
rii_check(cork_stream_consumer_data
(consumer, buf, bytes_read, first));
first = false;
}
if (bytes_read == 0) {
return cork_stream_consumer_eof(consumer);
} else if (errno != EINTR) {
cork_system_error_set();
return -1;
}
}
}
int
cork_consume_file(struct cork_stream_consumer *consumer, FILE *fp)
{
char buf[BUFFER_SIZE];
size_t bytes_read;
bool first = true;
while (true) {
while ((bytes_read = fread(buf, 1, BUFFER_SIZE, fp)) > 0) {
rii_check(cork_stream_consumer_data
(consumer, buf, bytes_read, first));
first = false;
}
if (feof(fp)) {
return cork_stream_consumer_eof(consumer);
} else if (errno != EINTR) {
cork_system_error_set();
return -1;
}
}
}
int
cork_consume_file_from_path(struct cork_stream_consumer *consumer,
const char *path, int flags)
{
int fd;
rii_check_posix(fd = open(path, flags));
ei_check(cork_consume_fd(consumer, fd));
rii_check_posix(close(fd));
return 0;
error:
rii_check_posix(close(fd));
return -1;
}
/*-----------------------------------------------------------------------
* Consumers
*/
struct cork_file_consumer {
struct cork_stream_consumer parent;
FILE *fp;
};
static int
cork_file_consumer__data(struct cork_stream_consumer *vself,
const void *buf, size_t size, bool is_first)
{
struct cork_file_consumer *self =
cork_container_of(vself, struct cork_file_consumer, parent);
size_t bytes_written = fwrite(buf, 1, size, self->fp);
/* If there was an error writing to the file, then signal this to
* the producer */
if (bytes_written == size) {
return 0;
} else {
cork_system_error_set();
return -1;
}
}
static int
cork_file_consumer__eof(struct cork_stream_consumer *vself)
{
/* We never close the file with this version of the consumer, so there's
* nothing special to do at end-of-stream. */
return 0;
}
static void
cork_file_consumer__free(struct cork_stream_consumer *vself)
{
struct cork_file_consumer *self =
cork_container_of(vself, struct cork_file_consumer, parent);
cork_delete(struct cork_file_consumer, self);
}
struct cork_stream_consumer *
cork_file_consumer_new(FILE *fp)
{
struct cork_file_consumer *self = cork_new(struct cork_file_consumer);
self->parent.data = cork_file_consumer__data;
self->parent.eof = cork_file_consumer__eof;
self->parent.free = cork_file_consumer__free;
self->fp = fp;
return &self->parent;
}
struct cork_fd_consumer {
struct cork_stream_consumer parent;
int fd;
};
static int
cork_fd_consumer__data(struct cork_stream_consumer *vself,
const void *buf, size_t size, bool is_first)
{
struct cork_fd_consumer *self =
cork_container_of(vself, struct cork_fd_consumer, parent);
size_t bytes_left = size;
while (bytes_left > 0) {
ssize_t rc = write(self->fd, buf, bytes_left);
if (rc == -1 && errno != EINTR) {
cork_system_error_set();
return -1;
} else {
bytes_left -= rc;
buf += rc;
}
}
return 0;
}
static int
cork_fd_consumer__eof_close(struct cork_stream_consumer *vself)
{
int rc;
struct cork_fd_consumer *self =
cork_container_of(vself, struct cork_fd_consumer, parent);
rii_check_posix(rc = close(self->fd));
return 0;
}
static void
cork_fd_consumer__free(struct cork_stream_consumer *vself)
{
struct cork_fd_consumer *self =
cork_container_of(vself, struct cork_fd_consumer, parent);
cork_delete(struct cork_fd_consumer, self);
}
struct cork_stream_consumer *
cork_fd_consumer_new(int fd)
{
struct cork_fd_consumer *self = cork_new(struct cork_fd_consumer);
self->parent.data = cork_fd_consumer__data;
/* We don't want to close fd, so we reuse file_consumer's eof method */
self->parent.eof = cork_file_consumer__eof;
self->parent.free = cork_fd_consumer__free;
self->fd = fd;
return &self->parent;
}
struct cork_stream_consumer *
cork_file_from_path_consumer_new(const char *path, int flags)
{
int fd;
struct cork_fd_consumer *self;
rpi_check_posix(fd = open(path, flags));
self = cork_new(struct cork_fd_consumer);
self->parent.data = cork_fd_consumer__data;
self->parent.eof = cork_fd_consumer__eof_close;
self->parent.free = cork_fd_consumer__free;
self->fd = fd;
return &self->parent;
}
|
281677160/openwrt-package | 2,025 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/ds/ring-buffer.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <stdlib.h>
#include "libcork/core/allocator.h"
#include "libcork/core/types.h"
#include "libcork/ds/ring-buffer.h"
int
cork_ring_buffer_init(struct cork_ring_buffer *self, size_t size)
{
self->elements = cork_calloc(size, sizeof(void *));
self->allocated_size = size;
self->size = 0;
self->read_index = 0;
self->write_index = 0;
return 0;
}
struct cork_ring_buffer *
cork_ring_buffer_new(size_t size)
{
struct cork_ring_buffer *buf = cork_new(struct cork_ring_buffer);
cork_ring_buffer_init(buf, size);
return buf;
}
void
cork_ring_buffer_done(struct cork_ring_buffer *self)
{
cork_cfree(self->elements, self->allocated_size, sizeof(void *));
}
void
cork_ring_buffer_free(struct cork_ring_buffer *buf)
{
cork_ring_buffer_done(buf);
cork_delete(struct cork_ring_buffer, buf);
}
int
cork_ring_buffer_add(struct cork_ring_buffer *self, void *element)
{
if (cork_ring_buffer_is_full(self)) {
return -1;
}
self->elements[self->write_index++] = element;
self->size++;
if (self->write_index == self->allocated_size) {
self->write_index = 0;
}
return 0;
}
void *
cork_ring_buffer_pop(struct cork_ring_buffer *self)
{
if (cork_ring_buffer_is_empty(self)) {
return NULL;
} else {
void *result = self->elements[self->read_index++];
self->size--;
if (self->read_index == self->allocated_size) {
self->read_index = 0;
}
return result;
}
}
void *
cork_ring_buffer_peek(struct cork_ring_buffer *self)
{
if (cork_ring_buffer_is_empty(self)) {
return NULL;
} else {
return self->elements[self->read_index];
}
}
|
281677160/openwrt-package | 1,475 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/ds/bitset.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2013-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <string.h>
#include "libcork/core/allocator.h"
#include "libcork/core/api.h"
#include "libcork/core/types.h"
#include "libcork/ds/bitset.h"
static size_t
bytes_needed(size_t bit_count)
{
/* We need one byte for every bit... */
size_t bytes_needed = bit_count / 8;
/* Plus one extra for the leftovers that don't fit into a whole byte. */
bytes_needed += ((bit_count % 8) > 0);
return bytes_needed;
}
void
cork_bitset_init(struct cork_bitset *set, size_t bit_count)
{
set->bit_count = bit_count;
set->byte_count = bytes_needed(bit_count);
set->bits = cork_malloc(set->byte_count);
memset(set->bits, 0, set->byte_count);
}
struct cork_bitset *
cork_bitset_new(size_t bit_count)
{
struct cork_bitset *set = cork_new(struct cork_bitset);
cork_bitset_init(set, bit_count);
return set;
}
void
cork_bitset_done(struct cork_bitset *set)
{
cork_free(set->bits, set->byte_count);
}
void
cork_bitset_free(struct cork_bitset *set)
{
cork_bitset_done(set);
cork_delete(struct cork_bitset, set);
}
void
cork_bitset_clear(struct cork_bitset *set)
{
memset(set->bits, 0, set->byte_count);
}
|
281677160/openwrt-package | 1,516 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/ds/dllist.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include "libcork/core/api.h"
#include "libcork/core/types.h"
#include "libcork/ds/dllist.h"
/* Include a linkable (but deprecated) version of this to maintain ABI
* compatibility. */
#undef cork_dllist_init
CORK_API void
cork_dllist_init(struct cork_dllist *list)
{
list->head.next = &list->head;
list->head.prev = &list->head;
}
void
cork_dllist_map(struct cork_dllist *list,
cork_dllist_map_func func, void *user_data)
{
struct cork_dllist_item *curr;
struct cork_dllist_item *next;
cork_dllist_foreach_void(list, curr, next) {
func(curr, user_data);
}
}
int
cork_dllist_visit(struct cork_dllist *list, void *ud,
cork_dllist_visit_f *visit)
{
struct cork_dllist_item *curr;
struct cork_dllist_item *next;
cork_dllist_foreach_void(list, curr, next) {
int rc = visit(ud, curr);
if (rc != 0) {
return rc;
}
}
return 0;
}
size_t
cork_dllist_size(const struct cork_dllist *list)
{
size_t size = 0;
struct cork_dllist_item *curr;
struct cork_dllist_item *next;
cork_dllist_foreach_void(list, curr, next) {
size++;
}
return size;
}
|
281677160/openwrt-package | 5,961 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/cli/commands.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2012, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license
* details.
* ----------------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "libcork/cli.h"
#include "libcork/core.h"
#include "libcork/ds.h"
#define streq(a,b) (strcmp((a), (b)) == 0)
static struct cork_buffer breadcrumbs_buf = CORK_BUFFER_INIT();
static void
cork_command_add_breadcrumb(struct cork_command *command)
{
cork_buffer_append_printf(&breadcrumbs_buf, " %s", command->name);
}
#define cork_command_breadcrumbs() ((char *) breadcrumbs_buf.buf)
static void
cork_command_run(struct cork_command *command, int argc, char **argv);
static struct cork_command *
cork_command_set_get_subcommand(struct cork_command *command,
const char *command_name)
{
struct cork_command **curr;
for (curr = command->set; *curr != NULL; curr++) {
if (streq(command_name, (*curr)->name)) {
return *curr;
}
}
return NULL;
}
static void
cork_command_set_show_help(struct cork_command *command)
{
size_t max_length = 0;
struct cork_command **curr;
/* Calculate the length of the longest command name. */
for (curr = command->set; *curr != NULL; curr++) {
size_t len = strlen((*curr)->name);
if (len > max_length) {
max_length = len;
}
}
/* Then print out the available commands. */
printf("Usage:%s <command> [<options>]\n"
"\nAvailable commands:\n",
cork_command_breadcrumbs());
for (curr = command->set; *curr != NULL; curr++) {
printf(" %*s", (int) -max_length, (*curr)->name);
if ((*curr)->short_desc != NULL) {
printf(" %s\n", (*curr)->short_desc);
} else {
printf("\n");
}
}
}
static void
cork_command_leaf_show_help(struct cork_command *command)
{
printf("Usage:%s", cork_command_breadcrumbs());
if (command->usage_suffix != NULL) {
printf(" %s", command->usage_suffix);
}
if (command->full_help != NULL) {
printf("\n\n%s", command->full_help);
} else {
printf("\n");
}
}
void
cork_command_show_help(struct cork_command *command, const char *message)
{
if (message != NULL) {
printf("%s\n", message);
}
if (command->type == CORK_COMMAND_SET) {
cork_command_set_show_help(command);
} else if (command->type == CORK_LEAF_COMMAND) {
cork_command_leaf_show_help(command);
}
}
static void
cork_command_set_run_help(struct cork_command *command, int argc, char **argv)
{
/* When we see the help command when processing a command set, we use any
* remaining arguments to identifity which subcommand the user wants help
* with. */
/* Skip over the name of the command set */
argc--;
argv++;
while (argc > 0 && command->type == CORK_COMMAND_SET) {
struct cork_command *subcommand =
cork_command_set_get_subcommand(command, argv[0]);
if (subcommand == NULL) {
printf("Unknown command \"%s\".\n"
"Usage:%s <command> [<options>]\n",
argv[0], cork_command_breadcrumbs());
exit(EXIT_FAILURE);
}
cork_command_add_breadcrumb(subcommand);
command = subcommand;
argc--;
argv++;
}
cork_command_show_help(command, NULL);
}
static void
cork_command_set_run(struct cork_command *command, int argc, char **argv)
{
const char *command_name;
struct cork_command *subcommand;
if (argc == 0) {
printf("No command given.\n");
cork_command_set_show_help(command);
exit(EXIT_FAILURE);
}
command_name = argv[0];
/* The "help" command is special. */
if (streq(command_name, "help")) {
cork_command_set_run_help(command, argc, argv);
return;
}
/* Otherwise look for a real subcommand with this name. */
subcommand = cork_command_set_get_subcommand(command, command_name);
if (subcommand == NULL) {
printf("Unknown command \"%s\".\n"
"Usage:%s <command> [<options>]\n",
command_name, cork_command_breadcrumbs());
exit(EXIT_FAILURE);
} else {
cork_command_run(subcommand, argc, argv);
}
}
static void
cork_command_leaf_run(struct cork_command *command, int argc, char **argv)
{
command->run(argc, argv);
}
static void
cork_command_cleanup(void)
{
cork_buffer_done(&breadcrumbs_buf);
}
static void
cork_command_run(struct cork_command *command, int argc, char **argv)
{
cork_command_add_breadcrumb(command);
/* If the gives the --help option at this point, describe the current
* command. */
if (argc >= 2 && (streq(argv[1], "--help") || streq(argv[1], "-h"))) {
cork_command_show_help(command, NULL);
return;
}
/* Otherwise let the command parse any options that occur here. */
if (command->parse_options != NULL) {
int option_count = command->parse_options(argc, argv);
argc -= option_count;
argv += option_count;
} else {
argc--;
argv++;
}
switch (command->type) {
case CORK_COMMAND_SET:
cork_command_set_run(command, argc, argv);
return;
case CORK_LEAF_COMMAND:
cork_command_leaf_run(command, argc, argv);
return;
default:
cork_unreachable();
}
}
int
cork_command_main(struct cork_command *root, int argc, char **argv)
{
/* Clean up after ourselves when the command finishes. */
atexit(cork_command_cleanup);
/* Run the root command. */
cork_command_run(root, argc, argv);
return EXIT_SUCCESS;
}
|
281677160/openwrt-package | 23,001 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/posix/files.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2013-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#ifdef __GNU__
#define _GNU_SOURCE
#endif
#include <assert.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "libcork/core/attributes.h"
#include "libcork/core/error.h"
#include "libcork/core/types.h"
#include "libcork/ds/array.h"
#include "libcork/ds/buffer.h"
#include "libcork/helpers/errors.h"
#include "libcork/helpers/posix.h"
#include "libcork/os/files.h"
#include "libcork/os/subprocess.h"
#if !defined(CORK_DEBUG_FILES)
#define CORK_DEBUG_FILES 0
#endif
#if CORK_DEBUG_FILES
#include <stdio.h>
#define DEBUG(...) fprintf(stderr, __VA_ARGS__)
#else
#define DEBUG(...) /* no debug messages */
#endif
/*-----------------------------------------------------------------------
* Paths
*/
struct cork_path {
struct cork_buffer given;
};
static struct cork_path *
cork_path_new_internal(const char *str, size_t length)
{
struct cork_path *path = cork_new(struct cork_path);
cork_buffer_init(&path->given);
if (length == 0) {
cork_buffer_ensure_size(&path->given, 16);
cork_buffer_set(&path->given, "", 0);
} else {
cork_buffer_set(&path->given, str, length);
}
return path;
}
struct cork_path *
cork_path_new(const char *source)
{
return cork_path_new_internal(source, source == NULL? 0: strlen(source));
}
struct cork_path *
cork_path_clone(const struct cork_path *other)
{
return cork_path_new_internal(other->given.buf, other->given.size);
}
void
cork_path_free(struct cork_path *path)
{
cork_buffer_done(&path->given);
cork_delete(struct cork_path, path);
}
void
cork_path_set(struct cork_path *path, const char *content)
{
if (content == NULL) {
cork_buffer_clear(&path->given);
} else {
cork_buffer_set_string(&path->given, content);
}
}
const char *
cork_path_get(const struct cork_path *path)
{
return path->given.buf;
}
#define cork_path_get(path) ((const char *) (path)->given.buf)
#define cork_path_size(path) ((path)->given.size)
#define cork_path_truncate(path, size) \
(cork_buffer_truncate(&(path)->given, (size)))
int
cork_path_set_cwd(struct cork_path *path)
{
#ifdef __GNU__
char *dirname = get_current_dir_name();
rip_check_posix(dirname);
cork_buffer_set(&path->given, dirname, strlen(dirname));
free(dirname);
#else
cork_buffer_ensure_size(&path->given, PATH_MAX);
rip_check_posix(getcwd(path->given.buf, PATH_MAX));
path->given.size = strlen(path->given.buf);
#endif
return 0;
}
struct cork_path *
cork_path_cwd(void)
{
struct cork_path *path = cork_path_new(NULL);
ei_check(cork_path_set_cwd(path));
return path;
error:
cork_path_free(path);
return NULL;
}
int
cork_path_set_absolute(struct cork_path *path)
{
struct cork_buffer buf;
if (path->given.size > 0 &&
cork_buffer_char(&path->given, 0) == '/') {
/* The path is already absolute. */
return 0;
}
#ifdef __GNU__
char *dirname;
dirname = get_current_dir_name();
ep_check_posix(dirname);
cork_buffer_init(&buf);
cork_buffer_set(&buf, dirname, strlen(dirname));
free(dirname);
#else
cork_buffer_init(&buf);
cork_buffer_ensure_size(&buf, PATH_MAX);
ep_check_posix(getcwd(buf.buf, PATH_MAX));
buf.size = strlen(buf.buf);
#endif
cork_buffer_append(&buf, "/", 1);
cork_buffer_append_copy(&buf, &path->given);
cork_buffer_done(&path->given);
path->given = buf;
return 0;
error:
cork_buffer_done(&buf);
return -1;
}
struct cork_path *
cork_path_absolute(const struct cork_path *other)
{
struct cork_path *path = cork_path_clone(other);
ei_check(cork_path_set_absolute(path));
return path;
error:
cork_path_free(path);
return NULL;
}
void
cork_path_append(struct cork_path *path, const char *more)
{
if (more == NULL || more[0] == '\0') {
return;
}
if (more[0] == '/') {
/* If more starts with a "/", then it's absolute, and should replace
* the contents of the current path. */
cork_buffer_set_string(&path->given, more);
} else {
/* Otherwise, more is relative, and should be appended to the current
* path. If the current given path doesn't end in a "/", then we need
* to add one to keep the path well-formed. */
if (path->given.size > 0 &&
cork_buffer_char(&path->given, path->given.size - 1) != '/') {
cork_buffer_append(&path->given, "/", 1);
}
cork_buffer_append_string(&path->given, more);
}
}
struct cork_path *
cork_path_join(const struct cork_path *other, const char *more)
{
struct cork_path *path = cork_path_clone(other);
cork_path_append(path, more);
return path;
}
void
cork_path_append_path(struct cork_path *path, const struct cork_path *more)
{
cork_path_append(path, more->given.buf);
}
struct cork_path *
cork_path_join_path(const struct cork_path *other, const struct cork_path *more)
{
struct cork_path *path = cork_path_clone(other);
cork_path_append_path(path, more);
return path;
}
void
cork_path_set_basename(struct cork_path *path)
{
char *given = path->given.buf;
const char *last_slash = strrchr(given, '/');
if (last_slash != NULL) {
size_t offset = last_slash - given;
size_t basename_length = path->given.size - offset - 1;
memmove(given, last_slash + 1, basename_length);
given[basename_length] = '\0';
path->given.size = basename_length;
}
}
struct cork_path *
cork_path_basename(const struct cork_path *other)
{
struct cork_path *path = cork_path_clone(other);
cork_path_set_basename(path);
return path;
}
void
cork_path_set_dirname(struct cork_path *path)
{
const char *given = path->given.buf;
const char *last_slash = strrchr(given, '/');
if (last_slash == NULL) {
cork_buffer_clear(&path->given);
} else {
size_t offset = last_slash - given;
if (offset == 0) {
/* A special case for the immediate subdirectories of "/" */
cork_buffer_truncate(&path->given, 1);
} else {
cork_buffer_truncate(&path->given, offset);
}
}
}
struct cork_path *
cork_path_dirname(const struct cork_path *other)
{
struct cork_path *path = cork_path_clone(other);
cork_path_set_dirname(path);
return path;
}
/*-----------------------------------------------------------------------
* Lists of paths
*/
struct cork_path_list {
cork_array(struct cork_path *) array;
struct cork_buffer string;
};
struct cork_path_list *
cork_path_list_new_empty(void)
{
struct cork_path_list *list = cork_new(struct cork_path_list);
cork_array_init(&list->array);
cork_buffer_init(&list->string);
return list;
}
void
cork_path_list_free(struct cork_path_list *list)
{
size_t i;
for (i = 0; i < cork_array_size(&list->array); i++) {
struct cork_path *path = cork_array_at(&list->array, i);
cork_path_free(path);
}
cork_array_done(&list->array);
cork_buffer_done(&list->string);
cork_delete(struct cork_path_list, list);
}
const char *
cork_path_list_to_string(const struct cork_path_list *list)
{
return list->string.buf;
}
void
cork_path_list_add(struct cork_path_list *list, struct cork_path *path)
{
cork_array_append(&list->array, path);
if (cork_array_size(&list->array) > 1) {
cork_buffer_append(&list->string, ":", 1);
}
cork_buffer_append_string(&list->string, cork_path_get(path));
}
size_t
cork_path_list_size(const struct cork_path_list *list)
{
return cork_array_size(&list->array);
}
const struct cork_path *
cork_path_list_get(const struct cork_path_list *list, size_t index)
{
return cork_array_at(&list->array, index);
}
static void
cork_path_list_append_string(struct cork_path_list *list, const char *str)
{
struct cork_path *path;
const char *curr = str;
const char *next;
while ((next = strchr(curr, ':')) != NULL) {
size_t size = next - curr;
path = cork_path_new_internal(curr, size);
cork_path_list_add(list, path);
curr = next + 1;
}
path = cork_path_new(curr);
cork_path_list_add(list, path);
}
struct cork_path_list *
cork_path_list_new(const char *str)
{
struct cork_path_list *list = cork_path_list_new_empty();
cork_path_list_append_string(list, str);
return list;
}
/*-----------------------------------------------------------------------
* Files
*/
struct cork_file {
struct cork_path *path;
struct stat stat;
enum cork_file_type type;
bool has_stat;
};
static void
cork_file_init(struct cork_file *file, struct cork_path *path)
{
file->path = path;
file->has_stat = false;
}
struct cork_file *
cork_file_new(const char *path)
{
return cork_file_new_from_path(cork_path_new(path));
}
struct cork_file *
cork_file_new_from_path(struct cork_path *path)
{
struct cork_file *file = cork_new(struct cork_file);
cork_file_init(file, path);
return file;
}
static void
cork_file_reset(struct cork_file *file)
{
file->has_stat = false;
}
static void
cork_file_done(struct cork_file *file)
{
cork_path_free(file->path);
}
void
cork_file_free(struct cork_file *file)
{
cork_file_done(file);
cork_delete(struct cork_file, file);
}
const struct cork_path *
cork_file_path(struct cork_file *file)
{
return file->path;
}
static int
cork_file_stat(struct cork_file *file)
{
if (file->has_stat) {
return 0;
} else {
int rc;
rc = stat(cork_path_get(file->path), &file->stat);
if (rc == -1) {
if (errno == ENOENT || errno == ENOTDIR) {
file->type = CORK_FILE_MISSING;
file->has_stat = true;
return 0;
} else {
cork_system_error_set();
return -1;
}
}
if (S_ISREG(file->stat.st_mode)) {
file->type = CORK_FILE_REGULAR;
} else if (S_ISDIR(file->stat.st_mode)) {
file->type = CORK_FILE_DIRECTORY;
} else if (S_ISLNK(file->stat.st_mode)) {
file->type = CORK_FILE_SYMLINK;
} else {
file->type = CORK_FILE_UNKNOWN;
}
file->has_stat = true;
return 0;
}
}
int
cork_file_exists(struct cork_file *file, bool *exists)
{
rii_check(cork_file_stat(file));
*exists = (file->type != CORK_FILE_MISSING);
return 0;
}
int
cork_file_type(struct cork_file *file, enum cork_file_type *type)
{
rii_check(cork_file_stat(file));
*type = file->type;
return 0;
}
struct cork_file *
cork_path_list_find_file(const struct cork_path_list *list,
const char *rel_path)
{
size_t i;
size_t count = cork_path_list_size(list);
struct cork_file *file;
for (i = 0; i < count; i++) {
const struct cork_path *path = cork_path_list_get(list, i);
struct cork_path *joined = cork_path_join(path, rel_path);
bool exists;
file = cork_file_new_from_path(joined);
ei_check(cork_file_exists(file, &exists));
if (exists) {
return file;
} else {
cork_file_free(file);
}
}
cork_error_set_printf
(ENOENT, "%s not found in %s",
rel_path, cork_path_list_to_string(list));
return NULL;
error:
cork_file_free(file);
return NULL;
}
/*-----------------------------------------------------------------------
* Directories
*/
int
cork_file_iterate_directory(struct cork_file *file,
cork_file_directory_iterator iterator,
void *user_data)
{
DIR *dir = NULL;
struct dirent *entry;
size_t dir_path_size;
struct cork_path *child_path;
struct cork_file child_file;
rip_check_posix(dir = opendir(cork_path_get(file->path)));
child_path = cork_path_clone(file->path);
cork_file_init(&child_file, child_path);
dir_path_size = cork_path_size(child_path);
errno = 0;
while ((entry = readdir(dir)) != NULL) {
/* Skip the "." and ".." entries */
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0) {
continue;
}
cork_path_append(child_path, entry->d_name);
ei_check(cork_file_stat(&child_file));
/* If the entry is a subdirectory, recurse into it. */
ei_check(iterator(&child_file, entry->d_name, user_data));
/* Remove this entry name from the path buffer. */
cork_path_truncate(child_path, dir_path_size);
cork_file_reset(&child_file);
/* We have to reset errno to 0 because of the ambiguous way readdir uses
* a return value of NULL. Other functions may return normally yet set
* errno to a non-zero value. dlopen on Mac OS X is an ogreish example.
* Since an error readdir is indicated by returning NULL and setting
* errno to indicate the error, then we need to reset it to zero before
* each call. We shall assume, perhaps to our great misery, that
* functions within this loop do proper error checking and act
* accordingly. */
errno = 0;
}
/* Check errno immediately after the while loop terminates */
if (CORK_UNLIKELY(errno != 0)) {
cork_system_error_set();
goto error;
}
cork_file_done(&child_file);
rii_check_posix(closedir(dir));
return 0;
error:
cork_file_done(&child_file);
rii_check_posix(closedir(dir));
return -1;
}
static int
cork_file_mkdir_one(struct cork_file *file, cork_file_mode mode,
unsigned int flags)
{
DEBUG("mkdir %s\n", cork_path_get(file->path));
/* First check if the directory already exists. */
rii_check(cork_file_stat(file));
if (file->type == CORK_FILE_DIRECTORY) {
DEBUG(" Already exists!\n");
if (!(flags & CORK_FILE_PERMISSIVE)) {
cork_system_error_set_explicit(EEXIST);
return -1;
} else {
return 0;
}
} else if (file->type != CORK_FILE_MISSING) {
DEBUG(" Exists and not a directory!\n");
cork_system_error_set_explicit(EEXIST);
return -1;
}
/* If the caller asked for a recursive mkdir, then make sure the parent
* directory exists. */
if (flags & CORK_FILE_RECURSIVE) {
struct cork_path *parent = cork_path_dirname(file->path);
DEBUG(" Checking parent %s\n", cork_path_get(parent));
if (parent->given.size == 0) {
/* There is no parent; we're either at the filesystem root (for an
* absolute path) or the current directory (for a relative one).
* Either way, we can assume it already exists. */
cork_path_free(parent);
} else {
int rc;
struct cork_file parent_file;
cork_file_init(&parent_file, parent);
rc = cork_file_mkdir_one
(&parent_file, mode, flags | CORK_FILE_PERMISSIVE);
cork_file_done(&parent_file);
rii_check(rc);
}
}
/* Create the directory already! */
DEBUG(" Creating %s\n", cork_path_get(file->path));
rii_check_posix(mkdir(cork_path_get(file->path), mode));
return 0;
}
int
cork_file_mkdir(struct cork_file *file, cork_file_mode mode,
unsigned int flags)
{
return cork_file_mkdir_one(file, mode, flags);
}
static int
cork_file_remove_iterator(struct cork_file *file, const char *rel_name,
void *user_data)
{
unsigned int *flags = user_data;
return cork_file_remove(file, *flags);
}
int
cork_file_remove(struct cork_file *file, unsigned int flags)
{
DEBUG("rm %s\n", cork_path_get(file->path));
rii_check(cork_file_stat(file));
if (file->type == CORK_FILE_MISSING) {
if (flags & CORK_FILE_PERMISSIVE) {
return 0;
} else {
cork_system_error_set_explicit(ENOENT);
return -1;
}
} else if (file->type == CORK_FILE_DIRECTORY) {
if (flags & CORK_FILE_RECURSIVE) {
/* The user asked that we delete the contents of the directory
* first. */
rii_check(cork_file_iterate_directory
(file, cork_file_remove_iterator, &flags));
}
rii_check_posix(rmdir(cork_path_get(file->path)));
return 0;
} else {
rii_check(unlink(cork_path_get(file->path)));
return 0;
}
}
/*-----------------------------------------------------------------------
* Lists of files
*/
struct cork_file_list {
cork_array(struct cork_file *) array;
};
struct cork_file_list *
cork_file_list_new_empty(void)
{
struct cork_file_list *list = cork_new(struct cork_file_list);
cork_array_init(&list->array);
return list;
}
void
cork_file_list_free(struct cork_file_list *list)
{
size_t i;
for (i = 0; i < cork_array_size(&list->array); i++) {
struct cork_file *file = cork_array_at(&list->array, i);
cork_file_free(file);
}
cork_array_done(&list->array);
cork_delete(struct cork_file_list, list);
}
void
cork_file_list_add(struct cork_file_list *list, struct cork_file *file)
{
cork_array_append(&list->array, file);
}
size_t
cork_file_list_size(struct cork_file_list *list)
{
return cork_array_size(&list->array);
}
struct cork_file *
cork_file_list_get(struct cork_file_list *list, size_t index)
{
return cork_array_at(&list->array, index);
}
struct cork_file_list *
cork_file_list_new(struct cork_path_list *path_list)
{
struct cork_file_list *list = cork_file_list_new_empty();
size_t count = cork_path_list_size(path_list);
size_t i;
for (i = 0; i < count; i++) {
const struct cork_path *path = cork_path_list_get(path_list, i);
struct cork_file *file = cork_file_new(cork_path_get(path));
cork_array_append(&list->array, file);
}
return list;
}
struct cork_file_list *
cork_path_list_find_files(const struct cork_path_list *path_list,
const char *rel_path)
{
size_t i;
size_t count = cork_path_list_size(path_list);
struct cork_file_list *list = cork_file_list_new_empty();
struct cork_file *file;
for (i = 0; i < count; i++) {
const struct cork_path *path = cork_path_list_get(path_list, i);
struct cork_path *joined = cork_path_join(path, rel_path);
bool exists;
file = cork_file_new_from_path(joined);
ei_check(cork_file_exists(file, &exists));
if (exists) {
cork_file_list_add(list, file);
} else {
cork_file_free(file);
}
}
return list;
error:
cork_file_list_free(list);
cork_file_free(file);
return NULL;
}
/*-----------------------------------------------------------------------
* Standard paths and path lists
*/
#define empty_string(str) ((str) == NULL || (str)[0] == '\0')
struct cork_path *
cork_path_home(void)
{
const char *path = cork_env_get(NULL, "HOME");
if (empty_string(path)) {
cork_undefined("Cannot determine home directory");
return NULL;
} else {
return cork_path_new(path);
}
}
struct cork_path_list *
cork_path_config_paths(void)
{
struct cork_path_list *list = cork_path_list_new_empty();
const char *var;
struct cork_path *path;
/* The first entry should be the user's configuration directory. This is
* specified by $XDG_CONFIG_HOME, with $HOME/.config as the default. */
var = cork_env_get(NULL, "XDG_CONFIG_HOME");
if (empty_string(var)) {
ep_check(path = cork_path_home());
cork_path_append(path, ".config");
cork_path_list_add(list, path);
} else {
path = cork_path_new(var);
cork_path_list_add(list, path);
}
/* The remaining entries should be the system-wide configuration
* directories. These are specified by $XDG_CONFIG_DIRS, with /etc/xdg as
* the default. */
var = cork_env_get(NULL, "XDG_CONFIG_DIRS");
if (empty_string(var)) {
path = cork_path_new("/etc/xdg");
cork_path_list_add(list, path);
} else {
cork_path_list_append_string(list, var);
}
return list;
error:
cork_path_list_free(list);
return NULL;
}
struct cork_path_list *
cork_path_data_paths(void)
{
struct cork_path_list *list = cork_path_list_new_empty();
const char *var;
struct cork_path *path;
/* The first entry should be the user's data directory. This is specified
* by $XDG_DATA_HOME, with $HOME/.local/share as the default. */
var = cork_env_get(NULL, "XDG_DATA_HOME");
if (empty_string(var)) {
ep_check(path = cork_path_home());
cork_path_append(path, ".local/share");
cork_path_list_add(list, path);
} else {
path = cork_path_new(var);
cork_path_list_add(list, path);
}
/* The remaining entries should be the system-wide configuration
* directories. These are specified by $XDG_DATA_DIRS, with
* /usr/local/share:/usr/share as the the default. */
var = cork_env_get(NULL, "XDG_DATA_DIRS");
if (empty_string(var)) {
path = cork_path_new("/usr/local/share");
cork_path_list_add(list, path);
path = cork_path_new("/usr/share");
cork_path_list_add(list, path);
} else {
cork_path_list_append_string(list, var);
}
return list;
error:
cork_path_list_free(list);
return NULL;
}
struct cork_path *
cork_path_user_cache_path(void)
{
const char *var;
struct cork_path *path;
/* The user's cache directory is specified by $XDG_CACHE_HOME, with
* $HOME/.cache as the default. */
var = cork_env_get(NULL, "XDG_CACHE_HOME");
if (empty_string(var)) {
rpp_check(path = cork_path_home());
cork_path_append(path, ".cache");
return path;
} else {
return cork_path_new(var);
}
}
struct cork_path *
cork_path_user_runtime_path(void)
{
const char *var;
/* The user's cache directory is specified by $XDG_RUNTIME_DIR, with
* no default given by the spec. */
var = cork_env_get(NULL, "XDG_RUNTIME_DIR");
if (empty_string(var)) {
cork_undefined("Cannot determine user-specific runtime directory");
return NULL;
} else {
return cork_path_new(var);
}
}
|
281677160/openwrt-package | 6,440 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/posix/env.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2013-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "libcork/core.h"
#include "libcork/ds.h"
#include "libcork/os/subprocess.h"
#include "libcork/helpers/errors.h"
#if defined(__APPLE__)
/* Apple doesn't provide access to the "environ" variable from a shared library.
* There's a workaround function to grab the environ pointer described at [1].
*
* [1] http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man7/environ.7.html
*/
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#elif !defined(__MINGW32__)
/* On all other POSIX platforms, we assume that environ is available in shared
* libraries. */
extern char **environ;
#endif
#ifdef __MINGW32__
int setenv(const char *name, const char *value, int replace)
{
int out;
size_t namelen, valuelen;
char *envstr;
if (!name || !value) return -1;
if (!replace) {
char *oldval = NULL;
oldval = getenv(name);
if (oldval) return 0;
}
namelen = strlen(name);
valuelen = strlen(value);
envstr = malloc((namelen + valuelen + 2));
if (!envstr) return -1;
memcpy(envstr, name, namelen);
envstr[namelen] = '=';
memcpy(envstr + namelen + 1, value, valuelen);
envstr[namelen + valuelen + 1] = 0;
out = putenv(envstr);
/* putenv(3) makes the argument string part of the environment,
* and changing that string modifies the environment --- which
* means we do not own that storage anymore. Do not free
* envstr.
*/
return out;
}
int unsetenv(const char *env)
{
char *name;
int ret;
name = malloc(strlen(env)+2);
strcat(strcpy(name, env), "=");
ret = putenv(name);
free(name);
return ret;
}
int clearenv(void)
{
char **env = environ;
if (!env)
return 0;
while (*env) {
free(*env);
env++;
}
free(env);
environ = NULL;
return 0;
}
#endif
struct cork_env_var {
const char *name;
const char *value;
};
static struct cork_env_var *
cork_env_var_new(const char *name, const char *value)
{
struct cork_env_var *var = cork_new(struct cork_env_var);
var->name = cork_strdup(name);
var->value = cork_strdup(value);
return var;
}
static void
cork_env_var_free(void *vvar)
{
struct cork_env_var *var = vvar;
cork_strfree(var->name);
cork_strfree(var->value);
cork_delete(struct cork_env_var, var);
}
struct cork_env {
struct cork_hash_table *variables;
struct cork_buffer buffer;
};
struct cork_env *
cork_env_new(void)
{
struct cork_env *env = cork_new(struct cork_env);
env->variables = cork_string_hash_table_new(0, 0);
cork_hash_table_set_free_value(env->variables, cork_env_var_free);
cork_buffer_init(&env->buffer);
return env;
}
static void
cork_env_add_internal(struct cork_env *env, const char *name, const char *value)
{
if (env == NULL) {
setenv(name, value, true);
} else {
struct cork_env_var *var = cork_env_var_new(name, value);
void *old_var;
cork_hash_table_put
(env->variables, (void *) var->name, var, NULL, NULL, &old_var);
if (old_var != NULL) {
cork_env_var_free(old_var);
}
}
}
struct cork_env *
cork_env_clone_current(void)
{
char **curr;
struct cork_env *env = cork_env_new();
for (curr = environ; *curr != NULL; curr++) {
const char *entry = *curr;
const char *equal;
equal = strchr(entry, '=');
if (CORK_UNLIKELY(equal == NULL)) {
/* This environment entry is malformed; skip it. */
continue;
}
/* Make a copy of the name so that it's NUL-terminated rather than
* equal-terminated. */
cork_buffer_set(&env->buffer, entry, equal - entry);
cork_env_add_internal(env, env->buffer.buf, equal + 1);
}
return env;
}
void
cork_env_free(struct cork_env *env)
{
cork_hash_table_free(env->variables);
cork_buffer_done(&env->buffer);
cork_delete(struct cork_env, env);
}
const char *
cork_env_get(struct cork_env *env, const char *name)
{
if (env == NULL) {
return getenv(name);
} else {
struct cork_env_var *var =
cork_hash_table_get(env->variables, (void *) name);
return (var == NULL)? NULL: var->value;
}
}
void
cork_env_add(struct cork_env *env, const char *name, const char *value)
{
cork_env_add_internal(env, name, value);
}
void
cork_env_add_vprintf(struct cork_env *env, const char *name,
const char *format, va_list args)
{
cork_buffer_vprintf(&env->buffer, format, args);
cork_env_add_internal(env, name, env->buffer.buf);
}
void
cork_env_add_printf(struct cork_env *env, const char *name,
const char *format, ...)
{
va_list args;
va_start(args, format);
cork_env_add_vprintf(env, name, format, args);
va_end(args);
}
void
cork_env_remove(struct cork_env *env, const char *name)
{
if (env == NULL) {
unsetenv(name);
} else {
void *old_var;
cork_hash_table_delete(env->variables, (void *) name, NULL, &old_var);
if (old_var != NULL) {
cork_env_var_free(old_var);
}
}
}
static enum cork_hash_table_map_result
cork_env_set_vars(void *user_data, struct cork_hash_table_entry *entry)
{
struct cork_env_var *var = entry->value;
setenv(var->name, var->value, false);
return CORK_HASH_TABLE_MAP_CONTINUE;
}
#if ((defined(__APPLE__) || (defined(BSD) && (BSD >= 199103))) && !defined(__GNU__)) || defined (__CYGWIN__)
/* A handful of platforms [1] don't provide clearenv(), so we must implement our
* own version that clears the environ array directly.
*
* [1] http://www.gnu.org/software/gnulib/manual/html_node/clearenv.html
*/
static void
clearenv(void)
{
*environ = NULL;
}
#else
/* Otherwise assume that we have clearenv available. */
#endif
void
cork_env_replace_current(struct cork_env *env)
{
clearenv();
cork_hash_table_map(env->variables, NULL, cork_env_set_vars);
}
|
281677160/openwrt-package | 3,578 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/posix/process.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2013-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <stdlib.h>
#include "libcork/core.h"
#include "libcork/ds.h"
#include "libcork/os/process.h"
#include "libcork/helpers/errors.h"
#if !defined(CORK_DEBUG_PROCESS)
#define CORK_DEBUG_PROCESS 0
#endif
#if CORK_DEBUG_PROCESS
#include <stdio.h>
#define DEBUG(...) fprintf(stderr, __VA_ARGS__)
#else
#define DEBUG(...) /* no debug messages */
#endif
struct cork_cleanup_entry {
struct cork_dllist_item item;
int priority;
const char *name;
cork_cleanup_function function;
};
static struct cork_cleanup_entry *
cork_cleanup_entry_new(const char *name, int priority,
cork_cleanup_function function)
{
struct cork_cleanup_entry *self = cork_new(struct cork_cleanup_entry);
self->priority = priority;
self->name = cork_strdup(name);
self->function = function;
return self;
}
static void
cork_cleanup_entry_free(struct cork_cleanup_entry *self)
{
cork_strfree(self->name);
cork_delete(struct cork_cleanup_entry, self);
}
static struct cork_dllist cleanup_entries = CORK_DLLIST_INIT(cleanup_entries);
static bool cleanup_registered = false;
static void
cork_cleanup_call_one(struct cork_dllist_item *item, void *user_data)
{
struct cork_cleanup_entry *entry =
cork_container_of(item, struct cork_cleanup_entry, item);
cork_cleanup_function function = entry->function;
DEBUG("Call cleanup function [%d] %s\n", entry->priority, entry->name);
/* We need to free the entry before calling the entry's function, since one
* of the functions that libcork registers frees the allocator instance that
* we'd use to free the entry. If we called the function first, the
* allocator would be freed before we could use it to free the entry. */
cork_cleanup_entry_free(entry);
function();
}
static void
cork_cleanup_call_all(void)
{
cork_dllist_map(&cleanup_entries, cork_cleanup_call_one, NULL);
}
static void
cork_cleanup_entry_add(struct cork_cleanup_entry *entry)
{
struct cork_dllist_item *curr;
if (CORK_UNLIKELY(!cleanup_registered)) {
atexit(cork_cleanup_call_all);
cleanup_registered = true;
}
/* Linear search through the list of existing cleanup functions. When we
* find the first existing function with a higher priority, we've found
* where to insert the new function. */
for (curr = cork_dllist_start(&cleanup_entries);
!cork_dllist_is_end(&cleanup_entries, curr); curr = curr->next) {
struct cork_cleanup_entry *existing =
cork_container_of(curr, struct cork_cleanup_entry, item);
if (existing->priority > entry->priority) {
cork_dllist_add_before(&existing->item, &entry->item);
return;
}
}
/* If we fall through the loop, then the new function should be appended to
* the end of the list. */
cork_dllist_add(&cleanup_entries, &entry->item);
}
CORK_API void
cork_cleanup_at_exit_named(const char *name, int priority,
cork_cleanup_function function)
{
struct cork_cleanup_entry *entry =
cork_cleanup_entry_new(name, priority, function);
DEBUG("Register cleanup function [%d] %s\n", priority, name);
cork_cleanup_entry_add(entry);
}
|
281677160/openwrt-package | 16,968 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/posix/subprocess.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2012-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#ifndef __MINGW32__
//#include <sys/select.h>
#include <sys/wait.h>
#endif
#include <unistd.h>
#include "libcork/core.h"
#include "libcork/ds.h"
#include "libcork/os/subprocess.h"
#include "libcork/threads/basics.h"
#include "libcork/helpers/errors.h"
#include "libcork/helpers/posix.h"
#if !defined(CORK_DEBUG_SUBPROCESS)
#define CORK_DEBUG_SUBPROCESS 0
#endif
#if CORK_DEBUG_SUBPROCESS
#include <stdio.h>
#define DEBUG(...) fprintf(stderr, __VA_ARGS__)
#else
#define DEBUG(...) /* no debug messages */
#endif
/*-----------------------------------------------------------------------
* Subprocess groups
*/
#define BUF_SIZE 4096
struct cork_subprocess_group {
cork_array(struct cork_subprocess *) subprocesses;
};
struct cork_subprocess_group *
cork_subprocess_group_new(void)
{
struct cork_subprocess_group *group =
cork_new(struct cork_subprocess_group);
cork_pointer_array_init
(&group->subprocesses, (cork_free_f) cork_subprocess_free);
return group;
}
void
cork_subprocess_group_free(struct cork_subprocess_group *group)
{
cork_array_done(&group->subprocesses);
cork_delete(struct cork_subprocess_group, group);
}
void
cork_subprocess_group_add(struct cork_subprocess_group *group,
struct cork_subprocess *sub)
{
cork_array_append(&group->subprocesses, sub);
}
/*-----------------------------------------------------------------------
* Pipes (parent reads)
*/
struct cork_read_pipe {
struct cork_stream_consumer *consumer;
int fds[2];
bool first;
};
static void
cork_read_pipe_init(struct cork_read_pipe *p, struct cork_stream_consumer *consumer)
{
p->consumer = consumer;
p->fds[0] = -1;
p->fds[1] = -1;
}
static int
cork_read_pipe_close_read(struct cork_read_pipe *p)
{
if (p->fds[0] != -1) {
DEBUG("Closing read pipe %d\n", p->fds[0]);
rii_check_posix(close(p->fds[0]));
p->fds[0] = -1;
}
return 0;
}
static int
cork_read_pipe_close_write(struct cork_read_pipe *p)
{
if (p->fds[1] != -1) {
DEBUG("Closing write pipe %d\n", p->fds[1]);
rii_check_posix(close(p->fds[1]));
p->fds[1] = -1;
}
return 0;
}
static void
cork_read_pipe_close(struct cork_read_pipe *p)
{
cork_read_pipe_close_read(p);
cork_read_pipe_close_write(p);
}
static void
cork_read_pipe_done(struct cork_read_pipe *p)
{
cork_read_pipe_close(p);
}
static int
cork_read_pipe_open(struct cork_read_pipe *p)
{
if (p->consumer != NULL) {
int flags;
/* We want the read end of the pipe to be non-blocking. */
DEBUG("[read] Opening pipe\n");
rii_check_posix(pipe(p->fds));
DEBUG("[read] Got read=%d write=%d\n", p->fds[0], p->fds[1]);
DEBUG("[read] Setting non-blocking flag on read pipe\n");
ei_check_posix(flags = fcntl(p->fds[0], F_GETFD));
flags |= O_NONBLOCK;
ei_check_posix(fcntl(p->fds[0], F_SETFD, flags));
}
p->first = true;
return 0;
error:
cork_read_pipe_close(p);
return -1;
}
static int
cork_read_pipe_dup(struct cork_read_pipe *p, int fd)
{
if (p->fds[1] != -1) {
rii_check_posix(dup2(p->fds[1], fd));
}
return 0;
}
static int
cork_read_pipe_read(struct cork_read_pipe *p, char *buf, bool *progress)
{
if (p->fds[0] == -1) {
return 0;
}
do {
DEBUG("[read] Reading from pipe %d\n", p->fds[0]);
ssize_t bytes_read = read(p->fds[0], buf, BUF_SIZE);
if (bytes_read == -1) {
if (errno == EAGAIN) {
/* We've exhausted all of the data currently available. */
DEBUG("[read] No more bytes without blocking\n");
return 0;
} else if (errno == EINTR) {
/* Interrupted by a signal; return so that our wait loop can
* catch that. */
DEBUG("[read] Interrupted by signal\n");
return 0;
} else {
/* An actual error */
cork_system_error_set();
DEBUG("[read] Error: %s\n", cork_error_message());
return -1;
}
} else if (bytes_read == 0) {
DEBUG("[read] End of stream\n");
*progress = true;
rii_check(cork_stream_consumer_eof(p->consumer));
rii_check_posix(close(p->fds[0]));
p->fds[0] = -1;
return 0;
} else {
DEBUG("[read] Got %zd bytes\n", bytes_read);
*progress = true;
rii_check(cork_stream_consumer_data
(p->consumer, buf, bytes_read, p->first));
p->first = false;
}
} while (true);
}
static bool
cork_read_pipe_is_finished(struct cork_read_pipe *p)
{
return p->fds[0] == -1;
}
/*-----------------------------------------------------------------------
* Pipes (parent writes)
*/
struct cork_write_pipe {
struct cork_stream_consumer consumer;
int fds[2];
};
static int
cork_write_pipe_close_read(struct cork_write_pipe *p)
{
if (p->fds[0] != -1) {
DEBUG("[write] Closing read pipe %d\n", p->fds[0]);
rii_check_posix(close(p->fds[0]));
p->fds[0] = -1;
}
return 0;
}
static int
cork_write_pipe_close_write(struct cork_write_pipe *p)
{
if (p->fds[1] != -1) {
DEBUG("[write] Closing write pipe %d\n", p->fds[1]);
rii_check_posix(close(p->fds[1]));
p->fds[1] = -1;
}
return 0;
}
static int
cork_write_pipe__data(struct cork_stream_consumer *consumer,
const void *buf, size_t size, bool is_first_chunk)
{
struct cork_write_pipe *p =
cork_container_of(consumer, struct cork_write_pipe, consumer);
rii_check_posix(write(p->fds[1], buf, size));
return 0;
}
static int
cork_write_pipe__eof(struct cork_stream_consumer *consumer)
{
struct cork_write_pipe *p =
cork_container_of(consumer, struct cork_write_pipe, consumer);
return cork_write_pipe_close_write(p);
}
static void
cork_write_pipe__free(struct cork_stream_consumer *consumer)
{
}
static void
cork_write_pipe_init(struct cork_write_pipe *p)
{
p->consumer.data = cork_write_pipe__data;
p->consumer.eof = cork_write_pipe__eof;
p->consumer.free = cork_write_pipe__free;
p->fds[0] = -1;
p->fds[1] = -1;
}
static void
cork_write_pipe_close(struct cork_write_pipe *p)
{
cork_write_pipe_close_read(p);
cork_write_pipe_close_write(p);
}
static void
cork_write_pipe_done(struct cork_write_pipe *p)
{
cork_write_pipe_close(p);
}
static int
cork_write_pipe_open(struct cork_write_pipe *p)
{
DEBUG("[write] Opening writer pipe\n");
rii_check_posix(pipe(p->fds));
DEBUG("[write] Got read=%d write=%d\n", p->fds[0], p->fds[1]);
return 0;
}
static int
cork_write_pipe_dup(struct cork_write_pipe *p, int fd)
{
if (p->fds[0] != -1) {
rii_check_posix(dup2(p->fds[0], fd));
}
return 0;
}
/*-----------------------------------------------------------------------
* Subprocesses
*/
struct cork_subprocess {
pid_t pid;
struct cork_write_pipe stdin_pipe;
struct cork_read_pipe stdout_pipe;
struct cork_read_pipe stderr_pipe;
void *user_data;
cork_free_f free_user_data;
cork_run_f run;
int *exit_code;
char buf[BUF_SIZE];
};
struct cork_subprocess *
cork_subprocess_new(void *user_data, cork_free_f free_user_data,
cork_run_f run,
struct cork_stream_consumer *stdout_consumer,
struct cork_stream_consumer *stderr_consumer,
int *exit_code)
{
struct cork_subprocess *self = cork_new(struct cork_subprocess);
cork_write_pipe_init(&self->stdin_pipe);
cork_read_pipe_init(&self->stdout_pipe, stdout_consumer);
cork_read_pipe_init(&self->stderr_pipe, stderr_consumer);
self->pid = 0;
self->user_data = user_data;
self->free_user_data = free_user_data;
self->run = run;
self->exit_code = exit_code;
return self;
}
void
cork_subprocess_free(struct cork_subprocess *self)
{
cork_free_user_data(self);
cork_write_pipe_done(&self->stdin_pipe);
cork_read_pipe_done(&self->stdout_pipe);
cork_read_pipe_done(&self->stderr_pipe);
cork_delete(struct cork_subprocess, self);
}
struct cork_stream_consumer *
cork_subprocess_stdin(struct cork_subprocess *self)
{
return &self->stdin_pipe.consumer;
}
/*-----------------------------------------------------------------------
* Executing another program
*/
static int
cork_exec__run(void *vself)
{
struct cork_exec *exec = vself;
return cork_exec_run(exec);
}
static void
cork_exec__free(void *vself)
{
struct cork_exec *exec = vself;
cork_exec_free(exec);
}
struct cork_subprocess *
cork_subprocess_new_exec(struct cork_exec *exec,
struct cork_stream_consumer *out,
struct cork_stream_consumer *err,
int *exit_code)
{
return cork_subprocess_new
(exec, cork_exec__free,
cork_exec__run,
out, err, exit_code);
}
/*-----------------------------------------------------------------------
* Running subprocesses
*/
int
cork_subprocess_start(struct cork_subprocess *self)
{
pid_t pid;
/* Create the stdout and stderr pipes. */
if (cork_write_pipe_open(&self->stdin_pipe) == -1) {
return -1;
}
if (cork_read_pipe_open(&self->stdout_pipe) == -1) {
cork_write_pipe_close(&self->stdin_pipe);
return -1;
}
if (cork_read_pipe_open(&self->stderr_pipe) == -1) {
cork_write_pipe_close(&self->stdin_pipe);
cork_read_pipe_close(&self->stdout_pipe);
return -1;
}
/* Fork the child process. */
DEBUG("Forking child process\n");
pid = fork();
if (pid == 0) {
/* Child process */
int rc;
/* Close the parent's end of the pipes */
DEBUG("[child] ");
cork_write_pipe_close_write(&self->stdin_pipe);
DEBUG("[child] ");
cork_read_pipe_close_read(&self->stdout_pipe);
DEBUG("[child] ");
cork_read_pipe_close_read(&self->stderr_pipe);
/* Bind the stdout and stderr pipes */
if (cork_write_pipe_dup(&self->stdin_pipe, STDIN_FILENO) == -1) {
_exit(EXIT_FAILURE);
}
if (cork_read_pipe_dup(&self->stdout_pipe, STDOUT_FILENO) == -1) {
_exit(EXIT_FAILURE);
}
if (cork_read_pipe_dup(&self->stderr_pipe, STDERR_FILENO) == -1) {
_exit(EXIT_FAILURE);
}
/* Run the subprocess */
rc = self->run(self->user_data);
if (CORK_LIKELY(rc == 0)) {
_exit(EXIT_SUCCESS);
} else {
fprintf(stderr, "%s\n", cork_error_message());
_exit(EXIT_FAILURE);
}
} else if (pid < 0) {
/* Error forking */
cork_system_error_set();
return -1;
} else {
/* Parent process */
DEBUG(" Child PID=%d\n", (int) pid);
self->pid = pid;
cork_write_pipe_close_read(&self->stdin_pipe);
cork_read_pipe_close_write(&self->stdout_pipe);
cork_read_pipe_close_write(&self->stderr_pipe);
return 0;
}
}
static int
cork_subprocess_reap(struct cork_subprocess *self, int flags, bool *progress)
{
int pid;
int status;
rii_check_posix(pid = waitpid(self->pid, &status, flags));
if (pid == self->pid) {
*progress = true;
self->pid = 0;
if (self->exit_code != NULL) {
*self->exit_code = WEXITSTATUS(status);
}
}
return 0;
}
int
cork_subprocess_abort(struct cork_subprocess *self)
{
if (self->pid > 0) {
CORK_ATTR_UNUSED bool progress;
DEBUG("Terminating child process %d\n", (int) self->pid);
kill(self->pid, SIGTERM);
return cork_subprocess_reap(self, 0, &progress);
} else {
return 0;
}
}
bool
cork_subprocess_is_finished(struct cork_subprocess *self)
{
return (self->pid == 0)
&& cork_read_pipe_is_finished(&self->stdout_pipe)
&& cork_read_pipe_is_finished(&self->stderr_pipe);
}
#if defined(__APPLE__) || defined(__MINGW32__)
#include <pthread.h>
#define THREAD_YIELD pthread_yield_np
#elif defined(__linux__) || defined(BSD) || defined(__sun) || defined(__FreeBSD_kernel__) || defined(__GNU__) || defined(__CYGWIN__)
#include <sched.h>
#define THREAD_YIELD sched_yield
#else
#error "Unknown thread yield implementation"
#endif
static void
cork_subprocess_yield(unsigned int *spin_count)
{
/* Adapted from
* http://www.1024cores.net/home/lock-free-algorithms/tricks/spinning */
if (*spin_count < 10) {
/* Spin-wait */
cork_pause();
} else if (*spin_count < 20) {
/* A more intense spin-wait */
int i;
for (i = 0; i < 50; i++) {
cork_pause();
}
} else if (*spin_count < 22) {
THREAD_YIELD();
} else if (*spin_count < 24) {
usleep(0);
} else if (*spin_count < 50) {
usleep(1);
} else if (*spin_count < 75) {
usleep((*spin_count - 49) * 1000);
} else {
usleep(25000);
}
(*spin_count)++;
}
static int
cork_subprocess_drain_(struct cork_subprocess *self, bool *progress)
{
rii_check(cork_read_pipe_read(&self->stdout_pipe, self->buf, progress));
rii_check(cork_read_pipe_read(&self->stderr_pipe, self->buf, progress));
if (self->pid > 0) {
return cork_subprocess_reap(self, WNOHANG, progress);
} else {
return 0;
}
}
bool
cork_subprocess_drain(struct cork_subprocess *self)
{
bool progress;
cork_subprocess_drain_(self, &progress);
return progress;
}
int
cork_subprocess_wait(struct cork_subprocess *self)
{
unsigned int spin_count = 0;
bool progress;
while (!cork_subprocess_is_finished(self)) {
progress = false;
rii_check(cork_subprocess_drain_(self, &progress));
if (!progress) {
cork_subprocess_yield(&spin_count);
}
}
return 0;
}
/*-----------------------------------------------------------------------
* Running subprocess groups
*/
static int
cork_subprocess_group_terminate(struct cork_subprocess_group *group)
{
size_t i;
for (i = 0; i < cork_array_size(&group->subprocesses); i++) {
struct cork_subprocess *sub = cork_array_at(&group->subprocesses, i);
rii_check(cork_subprocess_abort(sub));
}
return 0;
}
int
cork_subprocess_group_start(struct cork_subprocess_group *group)
{
size_t i;
DEBUG("Starting subprocess group\n");
/* Start each subprocess. */
for (i = 0; i < cork_array_size(&group->subprocesses); i++) {
struct cork_subprocess *sub = cork_array_at(&group->subprocesses, i);
ei_check(cork_subprocess_start(sub));
}
return 0;
error:
cork_subprocess_group_terminate(group);
return -1;
}
int
cork_subprocess_group_abort(struct cork_subprocess_group *group)
{
DEBUG("Aborting subprocess group\n");
return cork_subprocess_group_terminate(group);
}
bool
cork_subprocess_group_is_finished(struct cork_subprocess_group *group)
{
size_t i;
for (i = 0; i < cork_array_size(&group->subprocesses); i++) {
struct cork_subprocess *sub = cork_array_at(&group->subprocesses, i);
bool sub_finished = cork_subprocess_is_finished(sub);
if (!sub_finished) {
return false;
}
}
return true;
}
static int
cork_subprocess_group_drain_(struct cork_subprocess_group *group,
bool *progress)
{
size_t i;
for (i = 0; i < cork_array_size(&group->subprocesses); i++) {
struct cork_subprocess *sub = cork_array_at(&group->subprocesses, i);
rii_check(cork_subprocess_drain_(sub, progress));
}
return 0;
}
bool
cork_subprocess_group_drain(struct cork_subprocess_group *group)
{
bool progress = false;
cork_subprocess_group_drain_(group, &progress);
return progress;
}
int
cork_subprocess_group_wait(struct cork_subprocess_group *group)
{
unsigned int spin_count = 0;
bool progress;
DEBUG("Waiting for subprocess group to finish\n");
while (!cork_subprocess_group_is_finished(group)) {
progress = false;
rii_check(cork_subprocess_group_drain_(group, &progress));
if (!progress) {
cork_subprocess_yield(&spin_count);
}
}
return 0;
}
|
281677160/openwrt-package | 3,846 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/posix/directory-walker.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2012, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license
* details.
* ----------------------------------------------------------------------
*/
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "libcork/core/attributes.h"
#include "libcork/core/error.h"
#include "libcork/core/types.h"
#include "libcork/ds/buffer.h"
#include "libcork/helpers/errors.h"
#include "libcork/helpers/posix.h"
#include "libcork/os/files.h"
static int
cork_walk_one_directory(struct cork_dir_walker *w, struct cork_buffer *path,
size_t root_path_size)
{
DIR *dir = NULL;
struct dirent *entry;
size_t dir_path_size;
rip_check_posix(dir = opendir(path->buf));
cork_buffer_append(path, "/", 1);
dir_path_size = path->size;
errno = 0;
while ((entry = readdir(dir)) != NULL) {
struct stat info;
/* Skip the "." and ".." entries */
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0) {
continue;
}
/* Stat the directory entry */
cork_buffer_append_string(path, entry->d_name);
ei_check_posix(stat(path->buf, &info));
/* If the entry is a subdirectory, recurse into it. */
if (S_ISDIR(info.st_mode)) {
int rc = cork_dir_walker_enter_directory
(w, path->buf, path->buf + root_path_size,
path->buf + dir_path_size);
if (rc != CORK_SKIP_DIRECTORY) {
ei_check(cork_walk_one_directory(w, path, root_path_size));
ei_check(cork_dir_walker_leave_directory
(w, path->buf, path->buf + root_path_size,
path->buf + dir_path_size));
}
} else if (S_ISREG(info.st_mode)) {
ei_check(cork_dir_walker_file
(w, path->buf, path->buf + root_path_size,
path->buf + dir_path_size));
}
/* Remove this entry name from the path buffer. */
cork_buffer_truncate(path, dir_path_size);
/* We have to reset errno to 0 because of the ambiguous way
* readdir uses a return value of NULL. Other functions may
* return normally yet set errno to a non-zero value. dlopen
* on Mac OS X is an ogreish example. Since an error readdir
* is indicated by returning NULL and setting errno to indicate
* the error, then we need to reset it to zero before each call.
* We shall assume, perhaps to our great misery, that functions
* within this loop do proper error checking and act accordingly.
*/
errno = 0;
}
/* Check errno immediately after the while loop terminates */
if (CORK_UNLIKELY(errno != 0)) {
cork_system_error_set();
goto error;
}
/* Remove the trailing '/' from the path buffer. */
cork_buffer_truncate(path, dir_path_size - 1);
rii_check_posix(closedir(dir));
return 0;
error:
if (dir != NULL) {
rii_check_posix(closedir(dir));
}
return -1;
}
int
cork_walk_directory(const char *path, struct cork_dir_walker *w)
{
int rc;
char *p;
struct cork_buffer buf = CORK_BUFFER_INIT();
/* Seed the buffer with the directory's path, ensuring that there's no
* trailing '/' */
cork_buffer_append_string(&buf, path);
p = buf.buf;
while (p[buf.size-1] == '/') {
buf.size--;
p[buf.size] = '\0';
}
rc = cork_walk_one_directory(w, &buf, buf.size + 1);
cork_buffer_done(&buf);
return rc;
}
|
281677160/openwrt-package | 4,431 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/posix/exec.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2013-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <errno.h>
#include <unistd.h>
#include "libcork/core.h"
#include "libcork/ds.h"
#include "libcork/os/subprocess.h"
#include "libcork/helpers/errors.h"
#define ri_check_posix(call) \
do { \
while (true) { \
if ((call) == -1) { \
if (errno == EINTR) { \
continue; \
} else { \
cork_system_error_set(); \
CORK_PRINT_ERROR(); \
return -1; \
} \
} else { \
break; \
} \
} \
} while (0)
struct cork_exec {
const char *program;
struct cork_string_array params;
struct cork_env *env;
const char *cwd;
struct cork_buffer description;
};
struct cork_exec *
cork_exec_new(const char *program)
{
struct cork_exec *exec = cork_new(struct cork_exec);
exec->program = cork_strdup(program);
cork_string_array_init(&exec->params);
exec->env = NULL;
exec->cwd = NULL;
cork_buffer_init(&exec->description);
cork_buffer_set_string(&exec->description, program);
return exec;
}
struct cork_exec *
cork_exec_new_with_params(const char *program, ...)
{
struct cork_exec *exec;
va_list args;
const char *param;
exec = cork_exec_new(program);
cork_exec_add_param(exec, program);
va_start(args, program);
while ((param = va_arg(args, const char *)) != NULL) {
cork_exec_add_param(exec, param);
}
return exec;
}
struct cork_exec *
cork_exec_new_with_param_array(const char *program, char * const *params)
{
char * const *curr;
struct cork_exec *exec = cork_exec_new(program);
for (curr = params; *curr != NULL; curr++) {
cork_exec_add_param(exec, *curr);
}
return exec;
}
void
cork_exec_free(struct cork_exec *exec)
{
cork_strfree(exec->program);
cork_array_done(&exec->params);
if (exec->env != NULL) {
cork_env_free(exec->env);
}
if (exec->cwd != NULL) {
cork_strfree(exec->cwd);
}
cork_buffer_done(&exec->description);
cork_delete(struct cork_exec, exec);
}
const char *
cork_exec_description(struct cork_exec *exec)
{
return exec->description.buf;
}
const char *
cork_exec_program(struct cork_exec *exec)
{
return exec->program;
}
size_t
cork_exec_param_count(struct cork_exec *exec)
{
return cork_array_size(&exec->params);
}
const char *
cork_exec_param(struct cork_exec *exec, size_t index)
{
return cork_array_at(&exec->params, index);
}
void
cork_exec_add_param(struct cork_exec *exec, const char *param)
{
/* Don't add the first parameter to the description; that's a copy of the
* program name, which we've already added. */
if (!cork_array_is_empty(&exec->params)) {
cork_buffer_append(&exec->description, " ", 1);
cork_buffer_append_string(&exec->description, param);
}
cork_array_append(&exec->params, cork_strdup(param));
}
struct cork_env *
cork_exec_env(struct cork_exec *exec)
{
return exec->env;
}
void
cork_exec_set_env(struct cork_exec *exec, struct cork_env *env)
{
if (exec->env != NULL) {
cork_env_free(exec->env);
}
exec->env = env;
}
const char *
cork_exec_cwd(struct cork_exec *exec)
{
return exec->cwd;
}
void
cork_exec_set_cwd(struct cork_exec *exec, const char *directory)
{
if (exec->cwd != NULL) {
cork_strfree(exec->cwd);
}
exec->cwd = cork_strdup(directory);
}
int
cork_exec_run(struct cork_exec *exec)
{
const char **params;
/* Make sure the parameter array is NULL-terminated. */
cork_array_append(&exec->params, NULL);
params = cork_array_elements(&exec->params);
/* Fill in the requested environment */
if (exec->env != NULL) {
cork_env_replace_current(exec->env);
}
/* Change the working directory, if requested */
if (exec->cwd != NULL) {
ri_check_posix(chdir(exec->cwd));
}
/* Execute the new program */
ri_check_posix(execvp(exec->program, (char * const *) params));
/* This is unreachable */
return 0;
}
|
281677160/openwrt-package | 2,317 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/core/u128.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2013, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <string.h>
#include <stdio.h>
#include "libcork/core/types.h"
#include "libcork/core/u128.h"
/* From http://stackoverflow.com/questions/8023414/how-to-convert-a-128-bit-integer-to-a-decimal-ascii-string-in-c */
const char *
cork_u128_to_decimal(char *dest, cork_u128 val)
{
uint32_t n[4];
char *s = dest;
char *p = dest;
unsigned int i;
/* This algorithm assumes that n[3] is the MSW. */
n[3] = cork_u128_be32(val, 0);
n[2] = cork_u128_be32(val, 1);
n[1] = cork_u128_be32(val, 2);
n[0] = cork_u128_be32(val, 3);
memset(s, '0', CORK_U128_DECIMAL_LENGTH - 1);
s[CORK_U128_DECIMAL_LENGTH - 1] = '\0';
for (i = 0; i < 128; i++) {
unsigned int j;
unsigned int carry;
carry = (n[3] >= 0x80000000);
/* Shift n[] left, doubling it */
n[3] = ((n[3] << 1) & 0xFFFFFFFF) + (n[2] >= 0x80000000);
n[2] = ((n[2] << 1) & 0xFFFFFFFF) + (n[1] >= 0x80000000);
n[1] = ((n[1] << 1) & 0xFFFFFFFF) + (n[0] >= 0x80000000);
n[0] = ((n[0] << 1) & 0xFFFFFFFF);
/* Add s[] to itself in decimal, doubling it */
for (j = CORK_U128_DECIMAL_LENGTH - 1; j-- > 0; ) {
s[j] += s[j] - '0' + carry;
carry = (s[j] > '9');
if (carry) {
s[j] -= 10;
}
}
}
while ((p[0] == '0') && (p < &s[CORK_U128_DECIMAL_LENGTH - 2])) {
p++;
}
return p;
}
const char *
cork_u128_to_hex(char *buf, cork_u128 val)
{
uint64_t hi = val._.be64.hi;
uint64_t lo = val._.be64.lo;
if (hi == 0) {
snprintf(buf, CORK_U128_HEX_LENGTH, "%" PRIx64, lo);
} else {
snprintf(buf, CORK_U128_HEX_LENGTH, "%" PRIx64 "%016" PRIx64, hi, lo);
}
return buf;
}
const char *
cork_u128_to_padded_hex(char *buf, cork_u128 val)
{
uint64_t hi = val._.be64.hi;
uint64_t lo = val._.be64.lo;
snprintf(buf, CORK_U128_HEX_LENGTH, "%016" PRIx64 "%016" PRIx64, hi, lo);
return buf;
}
|
281677160/openwrt-package | 10,884 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/core/allocator.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "libcork/core/allocator.h"
#include "libcork/core/attributes.h"
#include "libcork/core/error.h"
#include "libcork/core/types.h"
#include "libcork/os/process.h"
/*-----------------------------------------------------------------------
* Allocator interface
*/
struct cork_alloc_priv {
struct cork_alloc public;
struct cork_alloc_priv *next;
};
static void *
cork_alloc__default_calloc(const struct cork_alloc *alloc,
size_t count, size_t size)
{
void *result = cork_alloc_xcalloc(alloc, count, size);
if (CORK_UNLIKELY(result == NULL)) {
abort();
}
return result;
}
static void *
cork_alloc__default_malloc(const struct cork_alloc *alloc, size_t size)
{
void *result = cork_alloc_xmalloc(alloc, size);
if (CORK_UNLIKELY(result == NULL)) {
abort();
}
return result;
}
static void *
cork_alloc__default_realloc(const struct cork_alloc *alloc, void *ptr,
size_t old_size, size_t new_size)
{
void *result = cork_alloc_xrealloc(alloc, ptr, old_size, new_size);
if (CORK_UNLIKELY(result == NULL)) {
abort();
}
return result;
}
static void *
cork_alloc__default_xcalloc(const struct cork_alloc *alloc,
size_t count, size_t size)
{
void *result;
assert(count < (SIZE_MAX / size));
result = cork_alloc_xmalloc(alloc, count * size);
if (result != NULL) {
memset(result, 0, count * size);
}
return result;
}
static void *
cork_alloc__default_xmalloc(const struct cork_alloc *alloc, size_t size)
{
cork_abort("%s isn't defined", "cork_alloc:xmalloc");
}
static void *
cork_alloc__default_xrealloc(const struct cork_alloc *alloc, void *ptr,
size_t old_size, size_t new_size)
{
void *result = cork_alloc_xmalloc(alloc, new_size);
if (CORK_LIKELY(result != NULL) && ptr != NULL) {
size_t min_size = (new_size < old_size)? new_size: old_size;
memcpy(result, ptr, min_size);
cork_alloc_free(alloc, ptr, old_size);
}
return result;
}
static void
cork_alloc__default_free(const struct cork_alloc *alloc, void *ptr, size_t size)
{
cork_abort("%s isn't defined", "cork_alloc:free");
}
static bool cleanup_registered = false;
static struct cork_alloc_priv *all_allocs = NULL;
static void
cork_alloc_free_alloc(struct cork_alloc_priv *alloc)
{
cork_free_user_data(&alloc->public);
cork_alloc_delete(alloc->public.parent, struct cork_alloc_priv, alloc);
}
static void
cork_alloc_free_all(void)
{
struct cork_alloc_priv *curr;
struct cork_alloc_priv *next;
for (curr = all_allocs; curr != NULL; curr = next) {
next = curr->next;
cork_alloc_free_alloc(curr);
}
}
static void
cork_alloc_register_cleanup(void)
{
if (CORK_UNLIKELY(!cleanup_registered)) {
/* We don't use cork_cleanup because that requires the allocators to
* have already been set up! (atexit calls its functions in reverse
* order, and this one will be registered before cork_cleanup's, which
* makes it safe for cork_cleanup functions to still use the allocator,
* since the allocator atexit function will be called last.) */
atexit(cork_alloc_free_all);
cleanup_registered = true;
}
}
struct cork_alloc *
cork_alloc_new_alloc(const struct cork_alloc *parent)
{
struct cork_alloc_priv *alloc =
cork_alloc_new(parent, struct cork_alloc_priv);
alloc->public.parent = parent;
alloc->public.user_data = NULL;
alloc->public.free_user_data = NULL;
alloc->public.calloc = cork_alloc__default_calloc;
alloc->public.malloc = cork_alloc__default_malloc;
alloc->public.realloc = cork_alloc__default_realloc;
alloc->public.xcalloc = cork_alloc__default_xcalloc;
alloc->public.xmalloc = cork_alloc__default_xmalloc;
alloc->public.xrealloc = cork_alloc__default_xrealloc;
alloc->public.free = cork_alloc__default_free;
cork_alloc_register_cleanup();
alloc->next = all_allocs;
all_allocs = alloc;
return &alloc->public;
}
void
cork_alloc_set_user_data(struct cork_alloc *alloc,
void *user_data, cork_free_f free_user_data)
{
cork_free_user_data(alloc);
alloc->user_data = user_data;
alloc->free_user_data = free_user_data;
}
void
cork_alloc_set_calloc(struct cork_alloc *alloc, cork_alloc_calloc_f calloc)
{
alloc->calloc = calloc;
}
void
cork_alloc_set_malloc(struct cork_alloc *alloc, cork_alloc_malloc_f malloc)
{
alloc->malloc = malloc;
}
void
cork_alloc_set_realloc(struct cork_alloc *alloc, cork_alloc_realloc_f realloc)
{
alloc->realloc = realloc;
}
void
cork_alloc_set_xcalloc(struct cork_alloc *alloc, cork_alloc_calloc_f xcalloc)
{
alloc->xcalloc = xcalloc;
}
void
cork_alloc_set_xmalloc(struct cork_alloc *alloc, cork_alloc_malloc_f xmalloc)
{
alloc->xmalloc = xmalloc;
}
void
cork_alloc_set_xrealloc(struct cork_alloc *alloc,
cork_alloc_realloc_f xrealloc)
{
alloc->xrealloc = xrealloc;
}
void
cork_alloc_set_free(struct cork_alloc *alloc, cork_alloc_free_f free)
{
alloc->free = free;
}
/*-----------------------------------------------------------------------
* Allocating strings
*/
static inline const char *
strndup_internal(const struct cork_alloc *alloc,
const char *str, size_t len)
{
char *dest;
size_t allocated_size = len + sizeof(size_t) + 1;
size_t *new_str = cork_alloc_malloc(alloc, allocated_size);
*new_str = allocated_size;
dest = (char *) (void *) (new_str + 1);
memcpy(dest, str, len);
dest[len] = '\0';
return dest;
}
const char *
cork_alloc_strdup(const struct cork_alloc *alloc, const char *str)
{
return strndup_internal(alloc, str, strlen(str));
}
const char *
cork_alloc_strndup(const struct cork_alloc *alloc,
const char *str, size_t size)
{
return strndup_internal(alloc, str, size);
}
static inline const char *
xstrndup_internal(const struct cork_alloc *alloc,
const char *str, size_t len)
{
size_t allocated_size = len + sizeof(size_t) + 1;
size_t *new_str = cork_alloc_xmalloc(alloc, allocated_size);
if (CORK_UNLIKELY(new_str == NULL)) {
return NULL;
} else {
char *dest;
*new_str = allocated_size;
dest = (char *) (void *) (new_str + 1);
memcpy(dest, str, len);
dest[len] = '\0';
return dest;
}
}
const char *
cork_alloc_xstrdup(const struct cork_alloc *alloc, const char *str)
{
return xstrndup_internal(alloc, str, strlen(str));
}
const char *
cork_alloc_xstrndup(const struct cork_alloc *alloc,
const char *str, size_t size)
{
return xstrndup_internal(alloc, str, size);
}
void
cork_alloc_strfree(const struct cork_alloc *alloc, const char *str)
{
size_t *base = ((size_t *) str) - 1;
cork_alloc_free(alloc, base, *base);
}
/*-----------------------------------------------------------------------
* stdlib allocator
*/
static void *
cork_stdlib_alloc__calloc(const struct cork_alloc *alloc,
size_t count, size_t size)
{
void *result = calloc(count, size);
if (CORK_UNLIKELY(result == NULL)) {
abort();
}
return result;
}
static void *
cork_stdlib_alloc__malloc(const struct cork_alloc *alloc, size_t size)
{
void *result = malloc(size);
if (CORK_UNLIKELY(result == NULL)) {
abort();
}
return result;
}
static void *
cork_stdlib_alloc__realloc(const struct cork_alloc *alloc, void *ptr,
size_t old_size, size_t new_size)
{
/* Technically we don't really need to free `ptr` if the reallocation fails,
* since we'll abort the process immediately after. But my sense of
* cleanliness makes me do it anyway. */
#if CORK_HAVE_REALLOCF
void *result = reallocf(ptr, new_size);
if (result == NULL) {
abort();
}
return result;
#else
void *result = realloc(ptr, new_size);
if (result == NULL) {
free(ptr);
abort();
}
return result;
#endif
}
static void *
cork_stdlib_alloc__xcalloc(const struct cork_alloc *alloc,
size_t count, size_t size)
{
return calloc(count, size);
}
static void *
cork_stdlib_alloc__xmalloc(const struct cork_alloc *alloc, size_t size)
{
return malloc(size);
}
static void *
cork_stdlib_alloc__xrealloc(const struct cork_alloc *alloc, void *ptr,
size_t old_size, size_t new_size)
{
return realloc(ptr, new_size);
}
static void
cork_stdlib_alloc__free(const struct cork_alloc *alloc, void *ptr, size_t size)
{
free(ptr);
}
static const struct cork_alloc default_allocator = {
NULL,
NULL,
NULL,
cork_stdlib_alloc__calloc,
cork_stdlib_alloc__malloc,
cork_stdlib_alloc__realloc,
cork_stdlib_alloc__xcalloc,
cork_stdlib_alloc__xmalloc,
cork_stdlib_alloc__xrealloc,
cork_stdlib_alloc__free
};
/*-----------------------------------------------------------------------
* Customizing libcork's allocator
*/
const struct cork_alloc *cork_allocator = &default_allocator;
void
cork_set_allocator(const struct cork_alloc *alloc)
{
cork_allocator = alloc;
}
/*-----------------------------------------------------------------------
* Debugging allocator
*/
static void *
cork_debug_alloc__xmalloc(const struct cork_alloc *alloc, size_t size)
{
size_t real_size = size + sizeof(size_t);
size_t *base = cork_alloc_xmalloc(alloc->parent, real_size);
*base = size;
return base + 1;
}
static void
cork_debug_alloc__free(const struct cork_alloc *alloc, void *ptr,
size_t expected_size)
{
size_t *base = ((size_t *) ptr) - 1;
size_t actual_size = *base;
size_t real_size = actual_size + sizeof(size_t);
if (CORK_UNLIKELY(actual_size != expected_size)) {
cork_abort
("Incorrect size when freeing pointer (got %zu, expected %zu)",
expected_size, actual_size);
}
cork_alloc_free(alloc->parent, base, real_size);
}
struct cork_alloc *
cork_debug_alloc_new(const struct cork_alloc *parent)
{
struct cork_alloc *debug = cork_alloc_new_alloc(parent);
cork_alloc_set_xmalloc(debug, cork_debug_alloc__xmalloc);
cork_alloc_set_free(debug, cork_debug_alloc__free);
return debug;
}
|
281677160/openwrt-package | 11,395 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/core/gc.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <stdlib.h>
#include "libcork/config/config.h"
#include "libcork/core/allocator.h"
#include "libcork/core/gc.h"
#include "libcork/core/types.h"
#include "libcork/ds/dllist.h"
#include "libcork/threads/basics.h"
#if !defined(CORK_DEBUG_GC)
#define CORK_DEBUG_GC 0
#endif
#if CORK_DEBUG_GC
#include <stdio.h>
#define DEBUG(...) fprintf(stderr, __VA_ARGS__)
#else
#define DEBUG(...) /* no debug messages */
#endif
/*-----------------------------------------------------------------------
* GC context life cycle
*/
#define ROOTS_SIZE 1024
/* An internal structure allocated with every garbage-collected object. */
struct cork_gc_header;
/* A garbage collector context. */
struct cork_gc {
/* The number of used entries in roots. */
size_t root_count;
/* The possible roots of garbage cycles */
struct cork_gc_header *roots[ROOTS_SIZE];
};
cork_tls(struct cork_gc, cork_gc);
static void
cork_gc_collect_cycles(struct cork_gc *gc);
/*-----------------------------------------------------------------------
* Garbage collection functions
*/
struct cork_gc_header {
/* The current reference count for this object, along with its color
* during the mark/sweep process. */
volatile int ref_count_color;
/* The allocated size of this garbage-collected object (including
* the header). */
size_t allocated_size;
/* The garbage collection interface for this object. */
struct cork_gc_obj_iface *iface;
};
/*
* Structure of ref_count_color:
*
* +-----+---+---+---+---+---+
* | ... | 4 | 3 | 2 | 1 | 0 |
* +-----+---+---+---+---+---+
* ref_count | color
* |
* buffered --/
*/
#define cork_gc_ref_count_color(count, buffered, color) \
(((count) << 3) | ((buffered) << 2) | (color))
#define cork_gc_get_ref_count(hdr) \
((hdr)->ref_count_color >> 3)
#define cork_gc_inc_ref_count(hdr) \
do { \
(hdr)->ref_count_color += (1 << 3); \
} while (0)
#define cork_gc_dec_ref_count(hdr) \
do { \
(hdr)->ref_count_color -= (1 << 3); \
} while (0)
#define cork_gc_get_color(hdr) \
((hdr)->ref_count_color & 0x3)
#define cork_gc_set_color(hdr, color) \
do { \
(hdr)->ref_count_color = \
((hdr)->ref_count_color & ~0x3) | (color & 0x3); \
} while (0)
#define cork_gc_get_buffered(hdr) \
(((hdr)->ref_count_color & 0x4) != 0)
#define cork_gc_set_buffered(hdr, buffered) \
do { \
(hdr)->ref_count_color = \
((hdr)->ref_count_color & ~0x4) | (((buffered) & 1) << 2); \
} while (0)
#define cork_gc_free(hdr) \
do { \
if ((hdr)->iface->free != NULL) { \
(hdr)->iface->free(cork_gc_get_object((hdr))); \
} \
cork_free((hdr), (hdr)->allocated_size); \
} while (0)
#define cork_gc_recurse(gc, hdr, recurser) \
do { \
if ((hdr)->iface->recurse != NULL) { \
(hdr)->iface->recurse \
((gc), cork_gc_get_object((hdr)), (recurser), NULL); \
} \
} while (0)
enum cork_gc_color {
/* In use or free */
GC_BLACK = 0,
/* Possible member of garbage cycle */
GC_GRAY = 1,
/* Member of garbage cycle */
GC_WHITE = 2,
/* Possible root of garbage cycle */
GC_PURPLE = 3
};
#define cork_gc_get_header(obj) \
(((struct cork_gc_header *) (obj)) - 1)
#define cork_gc_get_object(hdr) \
((void *) (((struct cork_gc_header *) (hdr)) + 1))
void
cork_gc_init(void)
{
cork_gc_get();
}
void
cork_gc_done(void)
{
cork_gc_collect_cycles(cork_gc_get());
}
void *
cork_gc_alloc(size_t instance_size, struct cork_gc_obj_iface *iface)
{
size_t full_size = instance_size + sizeof(struct cork_gc_header);
DEBUG("Allocating %zu (%zu) bytes\n", instance_size, full_size);
struct cork_gc_header *header = cork_malloc(full_size);
DEBUG(" Result is %p[%p]\n", cork_gc_get_object(header), header);
header->ref_count_color = cork_gc_ref_count_color(1, false, GC_BLACK);
header->allocated_size = full_size;
header->iface = iface;
return cork_gc_get_object(header);
}
void *
cork_gc_incref(void *obj)
{
if (obj != NULL) {
struct cork_gc_header *header = cork_gc_get_header(obj);
cork_gc_inc_ref_count(header);
DEBUG("Incrementing %p -> %d\n",
obj, cork_gc_get_ref_count(header));
cork_gc_set_color(header, GC_BLACK);
}
return obj;
}
static void
cork_gc_decref_step(struct cork_gc *gc, void *obj, void *ud);
static void
cork_gc_release(struct cork_gc *gc, struct cork_gc_header *header)
{
cork_gc_recurse(gc, header, cork_gc_decref_step);
cork_gc_set_color(header, GC_BLACK);
if (!cork_gc_get_buffered(header)) {
cork_gc_free(header);
}
}
static void
cork_gc_possible_root(struct cork_gc *gc, struct cork_gc_header *header)
{
if (cork_gc_get_color(header) != GC_PURPLE) {
DEBUG(" Possible garbage cycle root\n");
cork_gc_set_color(header, GC_PURPLE);
if (!cork_gc_get_buffered(header)) {
cork_gc_set_buffered(header, true);
if (gc->root_count >= ROOTS_SIZE) {
cork_gc_collect_cycles(gc);
}
gc->roots[gc->root_count++] = header;
}
} else {
DEBUG(" Already marked as possible garbage cycle root\n");
}
}
static void
cork_gc_decref_step(struct cork_gc *gc, void *obj, void *ud)
{
if (obj != NULL) {
struct cork_gc_header *header = cork_gc_get_header(obj);
cork_gc_dec_ref_count(header);
DEBUG("Decrementing %p -> %d\n",
obj, cork_gc_get_ref_count(header));
if (cork_gc_get_ref_count(header) == 0) {
DEBUG(" Releasing %p\n", header);
cork_gc_release(gc, header);
} else {
cork_gc_possible_root(gc, header);
}
}
}
void
cork_gc_decref(void *obj)
{
if (obj != NULL) {
struct cork_gc *gc = cork_gc_get();
struct cork_gc_header *header = cork_gc_get_header(obj);
cork_gc_dec_ref_count(header);
DEBUG("Decrementing %p -> %d\n",
obj, cork_gc_get_ref_count(header));
if (cork_gc_get_ref_count(header) == 0) {
DEBUG(" Releasing %p\n", header);
cork_gc_release(gc, header);
} else {
cork_gc_possible_root(gc, header);
}
}
}
static void
cork_gc_mark_gray_step(struct cork_gc *gc, void *obj, void *ud);
static void
cork_gc_mark_gray(struct cork_gc *gc, struct cork_gc_header *header)
{
if (cork_gc_get_color(header) != GC_GRAY) {
DEBUG(" Setting color to gray\n");
cork_gc_set_color(header, GC_GRAY);
cork_gc_recurse(gc, header, cork_gc_mark_gray_step);
}
}
static void
cork_gc_mark_gray_step(struct cork_gc *gc, void *obj, void *ud)
{
if (obj != NULL) {
DEBUG(" cork_gc_mark_gray(%p)\n", obj);
struct cork_gc_header *header = cork_gc_get_header(obj);
cork_gc_dec_ref_count(header);
DEBUG(" Reference count now %d\n", cork_gc_get_ref_count(header));
cork_gc_mark_gray(gc, header);
}
}
static void
cork_gc_mark_roots(struct cork_gc *gc)
{
size_t i;
for (i = 0; i < gc->root_count; i++) {
struct cork_gc_header *header = gc->roots[i];
if (cork_gc_get_color(header) == GC_PURPLE) {
DEBUG(" Checking possible garbage cycle root %p\n",
cork_gc_get_object(header));
DEBUG(" cork_gc_mark_gray(%p)\n",
cork_gc_get_object(header));
cork_gc_mark_gray(gc, header);
} else {
DEBUG(" Possible garbage cycle root %p already checked\n",
cork_gc_get_object(header));
cork_gc_set_buffered(header, false);
gc->roots[i] = NULL;
if (cork_gc_get_color(header) == GC_BLACK &&
cork_gc_get_ref_count(header) == 0) {
DEBUG(" Freeing %p\n", header);
cork_gc_free(header);
}
}
}
}
static void
cork_gc_scan_black_step(struct cork_gc *gc, void *obj, void *ud);
static void
cork_gc_scan_black(struct cork_gc *gc, struct cork_gc_header *header)
{
DEBUG(" Setting color of %p to BLACK\n",
cork_gc_get_object(header));
cork_gc_set_color(header, GC_BLACK);
cork_gc_recurse(gc, header, cork_gc_scan_black_step);
}
static void
cork_gc_scan_black_step(struct cork_gc *gc, void *obj, void *ud)
{
if (obj != NULL) {
struct cork_gc_header *header = cork_gc_get_header(obj);
cork_gc_inc_ref_count(header);
DEBUG(" Increasing reference count %p -> %d\n",
obj, cork_gc_get_ref_count(header));
if (cork_gc_get_color(header) != GC_BLACK) {
cork_gc_scan_black(gc, header);
}
}
}
static void
cork_gc_scan(struct cork_gc *gc, void *obj, void *ud)
{
if (obj != NULL) {
DEBUG(" Scanning possible garbage cycle entry %p\n", obj);
struct cork_gc_header *header = cork_gc_get_header(obj);
if (cork_gc_get_color(header) == GC_GRAY) {
if (cork_gc_get_ref_count(header) > 0) {
DEBUG(" Remaining references; can't be a cycle\n");
cork_gc_scan_black(gc, header);
} else {
DEBUG(" Definitely a garbage cycle\n");
cork_gc_set_color(header, GC_WHITE);
cork_gc_recurse(gc, header, cork_gc_scan);
}
} else {
DEBUG(" Already checked\n");
}
}
}
static void
cork_gc_scan_roots(struct cork_gc *gc)
{
size_t i;
for (i = 0; i < gc->root_count; i++) {
if (gc->roots[i] != NULL) {
void *obj = cork_gc_get_object(gc->roots[i]);
cork_gc_scan(gc, obj, NULL);
}
}
}
static void
cork_gc_collect_white(struct cork_gc *gc, void *obj, void *ud)
{
if (obj != NULL) {
struct cork_gc_header *header = cork_gc_get_header(obj);
if (cork_gc_get_color(header) == GC_WHITE &&
!cork_gc_get_buffered(header)) {
DEBUG(" Releasing %p\n", obj);
cork_gc_set_color(header, GC_BLACK);
cork_gc_recurse(gc, header, cork_gc_collect_white);
DEBUG(" Freeing %p\n", header);
cork_gc_free(header);
}
}
}
static void
cork_gc_collect_roots(struct cork_gc *gc)
{
size_t i;
for (i = 0; i < gc->root_count; i++) {
if (gc->roots[i] != NULL) {
struct cork_gc_header *header = gc->roots[i];
void *obj = cork_gc_get_object(header);
cork_gc_set_buffered(header, false);
DEBUG("Collecting cycles from garbage root %p\n", obj);
cork_gc_collect_white(gc, obj, NULL);
gc->roots[i] = NULL;
}
}
gc->root_count = 0;
}
static void
cork_gc_collect_cycles(struct cork_gc *gc)
{
DEBUG("Collecting garbage cycles\n");
cork_gc_mark_roots(gc);
cork_gc_scan_roots(gc);
cork_gc_collect_roots(gc);
}
|
281677160/openwrt-package | 16,425 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/core/ip-address.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2013, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <stdio.h>
#include <string.h>
#include "libcork/core/byte-order.h"
#include "libcork/core/error.h"
#include "libcork/core/net-addresses.h"
#include "libcork/core/types.h"
#ifndef CORK_IP_ADDRESS_DEBUG
#define CORK_IP_ADDRESS_DEBUG 0
#endif
#if CORK_IP_ADDRESS_DEBUG
#include <stdio.h>
#define DEBUG(...) \
do { \
fprintf(stderr, __VA_ARGS__); \
} while (0)
#else
#define DEBUG(...) /* nothing */
#endif
/*-----------------------------------------------------------------------
* IP addresses
*/
/*** IPv4 ***/
static inline const char *
cork_ipv4_parse(struct cork_ipv4 *addr, const char *str)
{
const char *ch;
bool seen_digit_in_octet = false;
unsigned int octets = 0;
unsigned int digit = 0;
uint8_t result[4];
for (ch = str; *ch != '\0'; ch++) {
DEBUG("%2u: %c\t", (unsigned int) (ch-str), *ch);
switch (*ch) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
seen_digit_in_octet = true;
digit *= 10;
digit += (*ch - '0');
DEBUG("digit = %u\n", digit);
if (CORK_UNLIKELY(digit > 255)) {
DEBUG("\t");
goto parse_error;
}
break;
case '.':
/* If this would be the fourth octet, it can't have a trailing
* period. */
if (CORK_UNLIKELY(octets == 3)) {
goto parse_error;
}
DEBUG("octet %u = %u\n", octets, digit);
result[octets] = digit;
digit = 0;
octets++;
seen_digit_in_octet = false;
break;
default:
/* Any other character is a parse error. */
goto parse_error;
}
}
/* If we have a valid octet at the end, and that would be the fourth octet,
* then we've got a valid final parse. */
DEBUG("%2u:\t", (unsigned int) (ch-str));
if (CORK_LIKELY(seen_digit_in_octet && octets == 3)) {
#if CORK_IP_ADDRESS_DEBUG
char parsed_ipv4[CORK_IPV4_STRING_LENGTH];
#endif
DEBUG("octet %u = %u\n", octets, digit);
result[octets] = digit;
cork_ipv4_copy(addr, result);
#if CORK_IP_ADDRESS_DEBUG
cork_ipv4_to_raw_string(addr, parsed_ipv4);
DEBUG("\tParsed address: %s\n", parsed_ipv4);
#endif
return ch;
}
parse_error:
DEBUG("parse error\n");
cork_parse_error("Invalid IPv4 address: \"%s\"", str);
return NULL;
}
int
cork_ipv4_init(struct cork_ipv4 *addr, const char *str)
{
return cork_ipv4_parse(addr, str) == NULL? -1: 0;
}
bool
cork_ipv4_equal_(const struct cork_ipv4 *addr1, const struct cork_ipv4 *addr2)
{
return cork_ipv4_equal(addr1, addr2);
}
void
cork_ipv4_to_raw_string(const struct cork_ipv4 *addr, char *dest)
{
snprintf(dest, CORK_IPV4_STRING_LENGTH, "%u.%u.%u.%u",
addr->_.u8[0], addr->_.u8[1], addr->_.u8[2], addr->_.u8[3]);
}
bool
cork_ipv4_is_valid_network(const struct cork_ipv4 *addr,
unsigned int cidr_prefix)
{
uint32_t cidr_mask;
if (cidr_prefix > 32) {
return false;
} else if (cidr_prefix == 32) {
/* This handles undefined behavior for overflow bit shifts. */
cidr_mask = 0;
} else {
cidr_mask = 0xffffffff >> cidr_prefix;
}
return (CORK_UINT32_BIG_TO_HOST(addr->_.u32) & cidr_mask) == 0;
}
/*** IPv6 ***/
int
cork_ipv6_init(struct cork_ipv6 *addr, const char *str)
{
const char *ch;
uint16_t digit = 0;
unsigned int before_count = 0;
uint16_t before_double_colon[8];
uint16_t after_double_colon[8];
uint16_t *dest = before_double_colon;
unsigned int digits_seen = 0;
unsigned int hextets_seen = 0;
bool another_required = true;
bool digit_allowed = true;
bool colon_allowed = true;
bool double_colon_allowed = true;
bool just_saw_colon = false;
for (ch = str; *ch != '\0'; ch++) {
DEBUG("%2u: %c\t", (unsigned int) (ch-str), *ch);
switch (*ch) {
#define process_digit(base) \
/* Make sure a digit is allowed here. */ \
if (CORK_UNLIKELY(!digit_allowed)) { \
goto parse_error; \
} \
/* If we've already seen 4 digits, it's a parse error. */ \
if (CORK_UNLIKELY(digits_seen == 4)) { \
goto parse_error; \
} \
\
digits_seen++; \
colon_allowed = true; \
just_saw_colon = false; \
digit <<= 4; \
digit |= (*ch - (base)); \
DEBUG("digit = %04x\n", digit);
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
process_digit('0');
break;
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
process_digit('a'-10);
break;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
process_digit('A'-10);
break;
#undef process_digit
case ':':
/* We can only see a colon immediately after a hextet or as part
* of a double-colon. */
if (CORK_UNLIKELY(!colon_allowed)) {
goto parse_error;
}
/* If this is a double-colon, start parsing hextets into our
* second array. */
if (just_saw_colon) {
DEBUG("double-colon\n");
colon_allowed = false;
digit_allowed = true;
another_required = false;
double_colon_allowed = false;
before_count = hextets_seen;
dest = after_double_colon;
continue;
}
/* If this would end the eighth hextet (regardless of the
* placement of a double-colon), then there can't be a trailing
* colon. */
if (CORK_UNLIKELY(hextets_seen == 8)) {
goto parse_error;
}
/* If this is the very beginning of the string, then we can only
* have a double-colon, not a single colon. */
if (digits_seen == 0 && hextets_seen == 0) {
DEBUG("initial colon\n");
colon_allowed = true;
digit_allowed = false;
just_saw_colon = true;
another_required = true;
continue;
}
/* Otherwise this ends the current hextet. */
DEBUG("hextet %u = %04x\n", hextets_seen, digit);
*(dest++) = CORK_UINT16_HOST_TO_BIG(digit);
digit = 0;
hextets_seen++;
digits_seen = 0;
colon_allowed = double_colon_allowed;
just_saw_colon = true;
another_required = true;
break;
case '.':
{
/* If we see a period, then we must be in the middle of an IPv4
* address at the end of the IPv6 address. */
struct cork_ipv4 *ipv4 = (struct cork_ipv4 *) dest;
DEBUG("Detected IPv4 address %s\n", ch-digits_seen);
/* Ensure that we have space for the two hextets that the IPv4
* address will take up. */
if (CORK_UNLIKELY(hextets_seen >= 7)) {
goto parse_error;
}
/* Parse the IPv4 address directly into our current hextet
* buffer. */
ch = cork_ipv4_parse(ipv4, ch - digits_seen);
if (CORK_LIKELY(ch != NULL)) {
hextets_seen += 2;
digits_seen = 0;
another_required = false;
/* ch now points at the NUL terminator, but we're about to
* increment ch. */
ch--;
break;
}
/* The IPv4 parse failed, so we have an IPv6 parse error. */
goto parse_error;
}
default:
/* Any other character is a parse error. */
goto parse_error;
}
}
/* If we have a valid hextet at the end, and we've either seen a
* double-colon, or we have eight hextets in total, then we've got a valid
* final parse. */
DEBUG("%2u:\t", (unsigned int) (ch-str));
if (CORK_LIKELY(digits_seen > 0)) {
/* If there are trailing digits that would form a ninth hextet
* (regardless of the placement of a double-colon), then we have a parse
* error. */
if (CORK_UNLIKELY(hextets_seen == 8)) {
goto parse_error;
}
DEBUG("hextet %u = %04x\n\t", hextets_seen, digit);
*(dest++) = CORK_UINT16_HOST_TO_BIG(digit);
hextets_seen++;
} else if (CORK_UNLIKELY(another_required)) {
goto parse_error;
}
if (!double_colon_allowed) {
/* We've seen a double-colon, so use 0000 for any hextets that weren't
* present. */
#if CORK_IP_ADDRESS_DEBUG
char parsed_result[CORK_IPV6_STRING_LENGTH];
#endif
unsigned int after_count = hextets_seen - before_count;
DEBUG("Saw double-colon; %u hextets before, %u after\n",
before_count, after_count);
memset(addr, 0, sizeof(struct cork_ipv6));
memcpy(addr, before_double_colon,
sizeof(uint16_t) * before_count);
memcpy(&addr->_.u16[8-after_count], after_double_colon,
sizeof(uint16_t) * after_count);
#if CORK_IP_ADDRESS_DEBUG
cork_ipv6_to_raw_string(addr, parsed_result);
DEBUG("\tParsed address: %s\n", parsed_result);
#endif
return 0;
} else if (hextets_seen == 8) {
/* No double-colon, so we must have exactly eight hextets. */
#if CORK_IP_ADDRESS_DEBUG
char parsed_result[CORK_IPV6_STRING_LENGTH];
#endif
DEBUG("No double-colon\n");
cork_ipv6_copy(addr, before_double_colon);
#if CORK_IP_ADDRESS_DEBUG
cork_ipv6_to_raw_string(addr, parsed_result);
DEBUG("\tParsed address: %s\n", parsed_result);
#endif
return 0;
}
parse_error:
DEBUG("parse error\n");
cork_parse_error("Invalid IPv6 address: \"%s\"", str);
return -1;
}
bool
cork_ipv6_equal_(const struct cork_ipv6 *addr1, const struct cork_ipv6 *addr2)
{
return cork_ipv6_equal(addr1, addr2);
}
#define NS_IN6ADDRSZ 16
#define NS_INT16SZ 2
void
cork_ipv6_to_raw_string(const struct cork_ipv6 *addr, char *dest)
{
const uint8_t *src = addr->_.u8;
/*
* Note that int32_t and int16_t need only be "at least" large enough
* to contain a value of the specified size. On some systems, like
* Crays, there is no such thing as an integer variable with 16 bits.
* Keep this in mind if you think this function should have been coded
* to use pointer overlays. All the world's not a VAX.
*/
char *tp;
struct { int base, len; } best, cur;
unsigned int words[NS_IN6ADDRSZ / NS_INT16SZ];
int i;
/*
* Preprocess:
* Copy the input (bytewise) array into a wordwise array.
* Find the longest run of 0x00's in src[] for :: shorthanding.
*/
memset(words, '\0', sizeof words);
for (i = 0; i < NS_IN6ADDRSZ; i++)
words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
best.base = -1;
best.len = 0;
cur.base = -1;
cur.len = 0;
for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
if (words[i] == 0) {
if (cur.base == -1)
cur.base = i, cur.len = 1;
else
cur.len++;
} else {
if (cur.base != -1) {
if (best.base == -1 || cur.len > best.len)
best = cur;
cur.base = -1;
}
}
}
if (cur.base != -1) {
if (best.base == -1 || cur.len > best.len)
best = cur;
}
if (best.base != -1 && best.len < 2)
best.base = -1;
/*
* Format the result.
*/
tp = dest;
for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
/* Are we inside the best run of 0x00's? */
if (best.base != -1 && i >= best.base &&
i < (best.base + best.len)) {
if (i == best.base)
*tp++ = ':';
continue;
}
/* Are we following an initial run of 0x00s or any real hex? */
if (i != 0)
*tp++ = ':';
/* Is this address an encapsulated IPv4? */
if (i == 6 && best.base == 0 &&
(best.len == 6 || (best.len == 5 && words[5] == 0xffff))) {
tp += sprintf(tp, "%u.%u.%u.%u",
src[12], src[13], src[14], src[15]);
break;
}
tp += sprintf(tp, "%x", words[i]);
}
/* Was it a trailing run of 0x00's? */
if (best.base != -1 && (best.base + best.len) ==
(NS_IN6ADDRSZ / NS_INT16SZ))
*tp++ = ':';
*tp++ = '\0';
}
bool
cork_ipv6_is_valid_network(const struct cork_ipv6 *addr,
unsigned int cidr_prefix)
{
uint64_t cidr_mask[2];
if (cidr_prefix > 128) {
return false;
} else if (cidr_prefix == 128) {
/* This handles undefined behavior for overflow bit shifts. */
cidr_mask[0] = cidr_mask[1] = 0;
} else if (cidr_prefix == 64) {
/* This handles undefined behavior for overflow bit shifts. */
cidr_mask[0] = 0;
cidr_mask[1] = UINT64_C(0xffffffffffffffff);
} else if (cidr_prefix > 64) {
cidr_mask[0] = 0;
cidr_mask[1] = UINT64_C(0xffffffffffffffff) >> (cidr_prefix-64);
} else {
cidr_mask[0] = UINT64_C(0xffffffffffffffff) >> cidr_prefix;
cidr_mask[1] = UINT64_C(0xffffffffffffffff);
}
return (CORK_UINT64_BIG_TO_HOST(addr->_.u64[0] & cidr_mask[0]) == 0) &&
(CORK_UINT64_BIG_TO_HOST(addr->_.u64[1] & cidr_mask[1]) == 0);
}
/*** IP ***/
void
cork_ip_from_ipv4_(struct cork_ip *addr, const void *src)
{
cork_ip_from_ipv4(addr, src);
}
void
cork_ip_from_ipv6_(struct cork_ip *addr, const void *src)
{
cork_ip_from_ipv6(addr, src);
}
int
cork_ip_init(struct cork_ip *addr, const char *str)
{
int rc;
/* Try IPv4 first */
rc = cork_ipv4_init(&addr->ip.v4, str);
if (rc == 0) {
/* successful parse */
addr->version = 4;
return 0;
}
/* Then try IPv6 */
cork_error_clear();
rc = cork_ipv6_init(&addr->ip.v6, str);
if (rc == 0) {
/* successful parse */
addr->version = 6;
return 0;
}
/* Parse error for both address types */
cork_parse_error("Invalid IP address: \"%s\"", str);
return -1;
}
bool
cork_ip_equal_(const struct cork_ip *addr1, const struct cork_ip *addr2)
{
return cork_ip_equal(addr1, addr2);
}
void
cork_ip_to_raw_string(const struct cork_ip *addr, char *dest)
{
switch (addr->version) {
case 4:
cork_ipv4_to_raw_string(&addr->ip.v4, dest);
return;
case 6:
cork_ipv6_to_raw_string(&addr->ip.v6, dest);
return;
default:
strncpy(dest, "<INVALID>", CORK_IP_STRING_LENGTH);
return;
}
}
bool
cork_ip_is_valid_network(const struct cork_ip *addr, unsigned int cidr_prefix)
{
switch (addr->version) {
case 4:
return cork_ipv4_is_valid_network(&addr->ip.v4, cidr_prefix);
case 6:
return cork_ipv6_is_valid_network(&addr->ip.v6, cidr_prefix);
default:
return false;
}
}
|
281677160/openwrt-package | 5,740 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/core/error.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2014, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <assert.h>
#include <errno.h>
#include <stdarg.h>
#include <string.h>
#include "libcork/config.h"
#include "libcork/core/allocator.h"
#include "libcork/core/error.h"
#include "libcork/ds/buffer.h"
#include "libcork/os/process.h"
#include "libcork/threads/basics.h"
/*-----------------------------------------------------------------------
* Life cycle
*/
struct cork_error {
cork_error code;
struct cork_buffer *message;
struct cork_buffer *other;
struct cork_buffer buf1;
struct cork_buffer buf2;
struct cork_error *next;
};
static struct cork_error *
cork_error_new(void)
{
struct cork_error *error = cork_new(struct cork_error);
error->code = CORK_ERROR_NONE;
cork_buffer_init(&error->buf1);
cork_buffer_init(&error->buf2);
error->message = &error->buf1;
error->other = &error->buf2;
return error;
}
static void
cork_error_free(struct cork_error *error)
{
cork_buffer_done(&error->buf1);
cork_buffer_done(&error->buf2);
cork_delete(struct cork_error, error);
}
static struct cork_error * volatile errors;
cork_once_barrier(cork_error_list);
static void
cork_error_list_done(void)
{
struct cork_error *curr;
struct cork_error *next;
for (curr = errors; curr != NULL; curr = next) {
next = curr->next;
cork_error_free(curr);
}
}
static void
cork_error_list_init(void)
{
cork_cleanup_at_exit(0, cork_error_list_done);
}
cork_tls(struct cork_error *, cork_error_);
static struct cork_error *
cork_error_get(void)
{
struct cork_error **error_ptr = cork_error__get();
if (CORK_UNLIKELY(*error_ptr == NULL)) {
struct cork_error *old_head;
struct cork_error *error = cork_error_new();
cork_once(cork_error_list, cork_error_list_init());
do {
old_head = errors;
error->next = old_head;
} while (cork_ptr_cas(&errors, old_head, error) != old_head);
*error_ptr = error;
return error;
} else {
return *error_ptr;
}
}
/*-----------------------------------------------------------------------
* Public error API
*/
bool
cork_error_occurred(void)
{
struct cork_error *error = cork_error_get();
return error->code != CORK_ERROR_NONE;
}
cork_error
cork_error_code(void)
{
struct cork_error *error = cork_error_get();
return error->code;
}
const char *
cork_error_message(void)
{
struct cork_error *error = cork_error_get();
return error->message->buf;
}
void
cork_error_clear(void)
{
struct cork_error *error = cork_error_get();
error->code = CORK_ERROR_NONE;
cork_buffer_clear(error->message);
}
void
cork_error_set_printf(cork_error code, const char *format, ...)
{
va_list args;
struct cork_error *error = cork_error_get();
error->code = code;
va_start(args, format);
cork_buffer_vprintf(error->message, format, args);
va_end(args);
}
void
cork_error_set_string(cork_error code, const char *str)
{
struct cork_error *error = cork_error_get();
error->code = code;
cork_buffer_set_string(error->message, str);
}
void
cork_error_set_vprintf(cork_error code, const char *format, va_list args)
{
struct cork_error *error = cork_error_get();
error->code = code;
cork_buffer_vprintf(error->message, format, args);
}
void
cork_error_prefix_printf(const char *format, ...)
{
va_list args;
struct cork_error *error = cork_error_get();
struct cork_buffer *temp;
va_start(args, format);
cork_buffer_vprintf(error->other, format, args);
va_end(args);
cork_buffer_append_copy(error->other, error->message);
temp = error->other;
error->other = error->message;
error->message = temp;
}
void
cork_error_prefix_string(const char *str)
{
struct cork_error *error = cork_error_get();
struct cork_buffer *temp;
cork_buffer_set_string(error->other, str);
cork_buffer_append_copy(error->other, error->message);
temp = error->other;
error->other = error->message;
error->message = temp;
}
void
cork_error_prefix_vprintf(const char *format, va_list args)
{
struct cork_error *error = cork_error_get();
struct cork_buffer *temp;
cork_buffer_vprintf(error->other, format, args);
cork_buffer_append_copy(error->other, error->message);
temp = error->other;
error->other = error->message;
error->message = temp;
}
/*-----------------------------------------------------------------------
* Deprecated
*/
void
cork_error_set(uint32_t error_class, unsigned int error_code,
const char *format, ...)
{
/* Create a fallback error code that's most likely not very useful. */
va_list args;
va_start(args, format);
cork_error_set_vprintf(error_class + error_code, format, args);
va_end(args);
}
void
cork_error_prefix(const char *format, ...)
{
va_list args;
va_start(args, format);
cork_error_prefix_vprintf(format, args);
va_end(args);
}
/*-----------------------------------------------------------------------
* Built-in errors
*/
void
cork_system_error_set_explicit(int err)
{
cork_error_set_string(err, strerror(err));
}
void
cork_system_error_set(void)
{
cork_error_set_string(errno, strerror(errno));
}
void
cork_unknown_error_set_(const char *location)
{
cork_error_set_printf(CORK_UNKNOWN_ERROR, "Unknown error in %s", location);
}
|
281677160/openwrt-package | 5,535 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/core/mempool.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2012-2015, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <assert.h>
#include <stdlib.h>
#include "libcork/core/callbacks.h"
#include "libcork/core/mempool.h"
#include "libcork/core/types.h"
#include "libcork/helpers/errors.h"
#if !defined(CORK_DEBUG_MEMPOOL)
#define CORK_DEBUG_MEMPOOL 0
#endif
#if CORK_DEBUG_MEMPOOL
#include <stdio.h>
#define DEBUG(...) fprintf(stderr, __VA_ARGS__)
#else
#define DEBUG(...) /* no debug messages */
#endif
struct cork_mempool {
size_t element_size;
size_t block_size;
struct cork_mempool_object *free_list;
/* The number of objects that have been given out by
* cork_mempool_new but not returned via cork_mempool_free. */
size_t allocated_count;
struct cork_mempool_block *blocks;
void *user_data;
cork_free_f free_user_data;
cork_init_f init_object;
cork_done_f done_object;
};
struct cork_mempool_object {
/* When this object is unclaimed, it will be in the cork_mempool
* object's free_list using this pointer. */
struct cork_mempool_object *next_free;
};
struct cork_mempool_block {
struct cork_mempool_block *next_block;
};
#define cork_mempool_object_size(mp) \
(sizeof(struct cork_mempool_object) + (mp)->element_size)
#define cork_mempool_get_header(obj) \
(((struct cork_mempool_object *) (obj)) - 1)
#define cork_mempool_get_object(hdr) \
((void *) (((struct cork_mempool_object *) (hdr)) + 1))
struct cork_mempool *
cork_mempool_new_size_ex(size_t element_size, size_t block_size)
{
struct cork_mempool *mp = cork_new(struct cork_mempool);
mp->element_size = element_size;
mp->block_size = block_size;
mp->free_list = NULL;
mp->allocated_count = 0;
mp->blocks = NULL;
mp->user_data = NULL;
mp->free_user_data = NULL;
mp->init_object = NULL;
mp->done_object = NULL;
return mp;
}
void
cork_mempool_free(struct cork_mempool *mp)
{
struct cork_mempool_block *curr;
assert(mp->allocated_count == 0);
if (mp->done_object != NULL) {
struct cork_mempool_object *obj;
for (obj = mp->free_list; obj != NULL; obj = obj->next_free) {
mp->done_object
(mp->user_data, cork_mempool_get_object(obj));
}
}
for (curr = mp->blocks; curr != NULL; ) {
struct cork_mempool_block *next = curr->next_block;
cork_free(curr, mp->block_size);
/* Do this here instead of in the for statement to avoid
* accessing the just-freed block. */
curr = next;
}
cork_free_user_data(mp);
cork_delete(struct cork_mempool, mp);
}
void
cork_mempool_set_user_data(struct cork_mempool *mp,
void *user_data, cork_free_f free_user_data)
{
cork_free_user_data(mp);
mp->user_data = user_data;
mp->free_user_data = free_user_data;
}
void
cork_mempool_set_init_object(struct cork_mempool *mp, cork_init_f init_object)
{
mp->init_object = init_object;
}
void
cork_mempool_set_done_object(struct cork_mempool *mp, cork_done_f done_object)
{
mp->done_object = done_object;
}
void
cork_mempool_set_callbacks(struct cork_mempool *mp,
void *user_data, cork_free_f free_user_data,
cork_init_f init_object,
cork_done_f done_object)
{
cork_mempool_set_user_data(mp, user_data, free_user_data);
cork_mempool_set_init_object(mp, init_object);
cork_mempool_set_done_object(mp, done_object);
}
/* If this function succeeds, then we guarantee that there will be at
* least one object in mp->free_list. */
static void
cork_mempool_new_block(struct cork_mempool *mp)
{
/* Allocate the new block and add it to mp's block list. */
struct cork_mempool_block *block;
void *vblock;
DEBUG("Allocating new %zu-byte block\n", mp->block_size);
block = cork_malloc(mp->block_size);
block->next_block = mp->blocks;
mp->blocks = block;
vblock = block;
/* Divide the block's memory region into a bunch of objects. */
size_t index = sizeof(struct cork_mempool_block);
for (index = sizeof(struct cork_mempool_block);
(index + cork_mempool_object_size(mp)) <= mp->block_size;
index += cork_mempool_object_size(mp)) {
struct cork_mempool_object *obj = vblock + index;
DEBUG(" New object at %p[%p]\n", cork_mempool_get_object(obj), obj);
if (mp->init_object != NULL) {
mp->init_object
(mp->user_data, cork_mempool_get_object(obj));
}
obj->next_free = mp->free_list;
mp->free_list = obj;
}
}
void *
cork_mempool_new_object(struct cork_mempool *mp)
{
struct cork_mempool_object *obj;
void *ptr;
if (CORK_UNLIKELY(mp->free_list == NULL)) {
cork_mempool_new_block(mp);
}
obj = mp->free_list;
mp->free_list = obj->next_free;
mp->allocated_count++;
ptr = cork_mempool_get_object(obj);
return ptr;
}
void
cork_mempool_free_object(struct cork_mempool *mp, void *ptr)
{
struct cork_mempool_object *obj = cork_mempool_get_header(ptr);
DEBUG("Returning %p[%p] to memory pool\n", ptr, obj);
obj->next_free = mp->free_list;
mp->free_list = obj;
mp->allocated_count--;
}
|
281677160/openwrt-package | 5,014 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/core/timestamp.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2013, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "libcork/core/timestamp.h"
#include "libcork/core/types.h"
#include "libcork/helpers/errors.h"
void
cork_timestamp_init_now(cork_timestamp *ts)
{
struct timeval tp;
gettimeofday(&tp, NULL);
cork_timestamp_init_usec(ts, tp.tv_sec, tp.tv_usec);
}
#define is_digit(ch) ((ch) >= '0' && (ch) <= '9')
static uint64_t
power_of_10(unsigned int width)
{
uint64_t accumulator = 10;
uint64_t result = 1;
while (width != 0) {
if ((width % 2) == 1) {
result *= accumulator;
width--;
}
accumulator *= accumulator;
width /= 2;
}
return result;
}
static int
append_fractional(const cork_timestamp ts, unsigned int width,
struct cork_buffer *dest)
{
if (CORK_UNLIKELY(width == 0 || width > 9)) {
cork_error_set_printf
(EINVAL,
"Invalid width %u for fractional cork_timestamp", width);
return -1;
} else {
uint64_t denom = power_of_10(width);
uint64_t frac = cork_timestamp_gsec_to_units(ts, denom);
cork_buffer_append_printf(dest, "%0*" PRIu64, width, frac);
return 0;
}
}
static int
cork_timestamp_format_parts(const cork_timestamp ts, struct tm *tm,
const char *format, struct cork_buffer *dest)
{
const char *next_percent;
while ((next_percent = strchr(format, '%')) != NULL) {
const char *spec = next_percent + 1;
unsigned int width = 0;
/* First append any text in between the previous format specifier and
* this one. */
cork_buffer_append(dest, format, next_percent - format);
/* Then parse the format specifier */
while (is_digit(*spec)) {
width *= 10;
width += (*spec++ - '0');
}
switch (*spec) {
case '\0':
cork_error_set_string
(EINVAL,
"Trailing %% at end of cork_timestamp format string");
return -1;
case '%':
cork_buffer_append(dest, "%", 1);
break;
case 'Y':
cork_buffer_append_printf(dest, "%04d", tm->tm_year + 1900);
break;
case 'm':
cork_buffer_append_printf(dest, "%02d", tm->tm_mon + 1);
break;
case 'd':
cork_buffer_append_printf(dest, "%02d", tm->tm_mday);
break;
case 'H':
cork_buffer_append_printf(dest, "%02d", tm->tm_hour);
break;
case 'M':
cork_buffer_append_printf(dest, "%02d", tm->tm_min);
break;
case 'S':
cork_buffer_append_printf(dest, "%02d", tm->tm_sec);
break;
case 's':
cork_buffer_append_printf
(dest, "%" PRIu32, cork_timestamp_sec(ts));
break;
case 'f':
rii_check(append_fractional(ts, width, dest));
break;
default:
cork_error_set_printf
(EINVAL,
"Unknown cork_timestamp format specifier %%%c", *spec);
return -1;
}
format = spec + 1;
}
/* When we fall through, there is some additional content after the final
* format specifier. */
cork_buffer_append_string(dest, format);
return 0;
}
#ifdef __MINGW32__
static struct tm *__cdecl gmtime_r(const time_t *_Time, struct tm *_Tm)
{
struct tm *p = gmtime(_Time);
if (!p)
return NULL;
if (_Tm) {
memcpy(_Tm, p, sizeof(struct tm));
return _Tm;
} else
return p;
}
static struct tm *__cdecl localtime_r(const time_t *_Time, struct tm *_Tm)
{
struct tm *p = localtime(_Time);
if (!p)
return NULL;
if (_Tm) {
memcpy(_Tm, p, sizeof(struct tm));
return _Tm;
} else
return p;
}
#endif
int
cork_timestamp_format_utc(const cork_timestamp ts, const char *format,
struct cork_buffer *dest)
{
time_t clock;
struct tm tm;
clock = cork_timestamp_sec(ts);
gmtime_r(&clock, &tm);
return cork_timestamp_format_parts(ts, &tm, format, dest);
}
int
cork_timestamp_format_local(const cork_timestamp ts, const char *format,
struct cork_buffer *dest)
{
time_t clock;
struct tm tm;
clock = cork_timestamp_sec(ts);
localtime_r(&clock, &tm);
return cork_timestamp_format_parts(ts, &tm, format, dest);
}
|
281677160/openwrt-package | 5,992 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/pthreads/thread.c | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2013-2015, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#if defined(__linux)
/* This is needed on Linux to get the pthread_setname_np function. */
#if !defined(_GNU_SOURCE)
#define _GNU_SOURCE 1
#endif
#endif
#include <assert.h>
#include <string.h>
#include <pthread.h>
#include "libcork/core/allocator.h"
#include "libcork/core/error.h"
#include "libcork/core/types.h"
#include "libcork/ds/buffer.h"
#include "libcork/threads/basics.h"
/*-----------------------------------------------------------------------
* Current thread
*/
static volatile cork_thread_id last_thread_descriptor = 0;
struct cork_thread {
const char *name;
cork_thread_id id;
pthread_t thread_id;
void *user_data;
cork_free_f free_user_data;
cork_run_f run;
cork_error error_code;
struct cork_buffer error_message;
bool started;
bool joined;
};
struct cork_thread_descriptor {
struct cork_thread *current_thread;
cork_thread_id id;
};
cork_tls(struct cork_thread_descriptor, cork_thread_descriptor);
struct cork_thread *
cork_current_thread_get(void)
{
struct cork_thread_descriptor *desc = cork_thread_descriptor_get();
return desc->current_thread;
}
cork_thread_id
cork_current_thread_get_id(void)
{
struct cork_thread_descriptor *desc = cork_thread_descriptor_get();
if (CORK_UNLIKELY(desc->id == 0)) {
if (desc->current_thread == NULL) {
desc->id = cork_uint_atomic_add(&last_thread_descriptor, 1);
} else {
desc->id = desc->current_thread->id;
}
}
return desc->id;
}
/*-----------------------------------------------------------------------
* Threads
*/
struct cork_thread *
cork_thread_new(const char *name,
void *user_data, cork_free_f free_user_data,
cork_run_f run)
{
struct cork_thread *self = cork_new(struct cork_thread);
self->name = cork_strdup(name);
self->id = cork_uint_atomic_add(&last_thread_descriptor, 1);
self->user_data = user_data;
self->free_user_data = free_user_data;
self->run = run;
self->error_code = CORK_ERROR_NONE;
cork_buffer_init(&self->error_message);
self->started = false;
self->joined = false;
return self;
}
static void
cork_thread_free_private(struct cork_thread *self)
{
cork_strfree(self->name);
cork_free_user_data(self);
cork_buffer_done(&self->error_message);
cork_delete(struct cork_thread, self);
}
void
cork_thread_free(struct cork_thread *self)
{
assert(!self->started);
cork_thread_free_private(self);
}
const char *
cork_thread_get_name(struct cork_thread *self)
{
return self->name;
}
cork_thread_id
cork_thread_get_id(struct cork_thread *self)
{
return self->id;
}
#define PTHREADS_MAX_THREAD_NAME_LENGTH 16
static void *
cork_thread_pthread_run(void *vself)
{
int rc;
struct cork_thread *self = vself;
struct cork_thread_descriptor *desc = cork_thread_descriptor_get();
#if defined(__APPLE__) && defined(__MACH__)
char thread_name[PTHREADS_MAX_THREAD_NAME_LENGTH];
#endif
desc->current_thread = self;
desc->id = self->id;
rc = self->run(self->user_data);
#if defined(__APPLE__) && defined(__MACH__)
/* On Mac OS X, we set the name of the current thread, not of an arbitrary
* thread of our choosing. */
strncpy(thread_name, self->name, PTHREADS_MAX_THREAD_NAME_LENGTH);
thread_name[PTHREADS_MAX_THREAD_NAME_LENGTH - 1] = '\0';
pthread_setname_np(thread_name);
#endif
/* If an error occurred in the body of the thread, save the error into the
* cork_thread object so that we can propagate that error when some calls
* cork_thread_join. */
if (CORK_UNLIKELY(rc != 0)) {
if (CORK_LIKELY(cork_error_occurred())) {
self->error_code = cork_error_code();
cork_buffer_set_string(&self->error_message, cork_error_message());
} else {
self->error_code = CORK_UNKNOWN_ERROR;
cork_buffer_set_string(&self->error_message, "Unknown error");
}
}
return NULL;
}
int
cork_thread_start(struct cork_thread *self)
{
int rc;
pthread_t thread_id;
#if defined(__linux) && ((__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12))
char thread_name[PTHREADS_MAX_THREAD_NAME_LENGTH];
#endif
assert(!self->started);
rc = pthread_create(&thread_id, NULL, cork_thread_pthread_run, self);
if (CORK_UNLIKELY(rc != 0)) {
cork_system_error_set_explicit(rc);
return -1;
}
#if defined(__linux) && ((__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 12))
/* On Linux we choose which thread to name via an explicit thread ID.
* However, pthread_setname_np() isn't supported on versions of glibc
* earlier than 2.12. So we need to check for a MINOR version of 12 or
* higher. */
strncpy(thread_name, self->name, PTHREADS_MAX_THREAD_NAME_LENGTH);
thread_name[PTHREADS_MAX_THREAD_NAME_LENGTH - 1] = '\0';
pthread_setname_np(thread_id, thread_name);
#endif
self->thread_id = thread_id;
self->started = true;
return 0;
}
int
cork_thread_join(struct cork_thread *self)
{
int rc;
assert(self->started && !self->joined);
rc = pthread_join(self->thread_id, NULL);
if (CORK_UNLIKELY(rc != 0)) {
cork_system_error_set_explicit(rc);
cork_thread_free_private(self);
return -1;
}
if (CORK_UNLIKELY(self->error_code != CORK_ERROR_NONE)) {
cork_error_set_printf
(self->error_code, "Error from thread %s: %s",
self->name, (char *) self->error_message.buf);
cork_thread_free_private(self);
return -1;
}
cork_thread_free_private(self);
return 0;
}
|
281677160/openwrt-package | 2,526 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/cmake/FindCTargets.cmake | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Copyright © 2015, RedJack, LLC.
# All rights reserved.
#
# Please see the COPYING file in this distribution for license details.
# ----------------------------------------------------------------------
#-----------------------------------------------------------------------
# Library, with options to build both shared and static versions
function(target_add_static_libraries TARGET_NAME LIBRARIES LOCAL_LIBRARIES)
foreach(lib ${LIBRARIES})
string(REPLACE "-" "_" lib ${lib})
string(TOUPPER ${lib} upperlib)
target_link_libraries(
${TARGET_NAME}
${${upperlib}_STATIC_LDFLAGS}
)
endforeach(lib)
foreach(lib ${LOCAL_LIBRARIES})
target_link_libraries(${TARGET_NAME} ${lib})
endforeach(lib)
endfunction(target_add_static_libraries)
set_property(GLOBAL PROPERTY ALL_LOCAL_LIBRARIES "")
function(add_c_library __TARGET_NAME)
set(options)
set(one_args OUTPUT_NAME PKGCONFIG_NAME VERSION)
set(multi_args LIBRARIES LOCAL_LIBRARIES SOURCES)
cmake_parse_arguments(_ "${options}" "${one_args}" "${multi_args}" ${ARGN})
if (__VERSION MATCHES "^([0-9]+)\\.([0-9]+)\\.([0-9]+)(-dev)?$")
set(__VERSION_CURRENT "${CMAKE_MATCH_1}")
set(__VERSION_REVISION "${CMAKE_MATCH_2}")
set(__VERSION_AGE "${CMAKE_MATCH_3}")
else (__VERSION MATCHES "^([0-9]+)\\.([0-9]+)\\.([0-9]+)(-dev)?$")
message(FATAL_ERROR "Invalid library version number: ${__VERSION}")
endif (__VERSION MATCHES "^([0-9]+)\\.([0-9]+)\\.([0-9]+)(-dev)?$")
math(EXPR __SOVERSION "${__VERSION_CURRENT} - ${__VERSION_AGE}")
get_property(ALL_LOCAL_LIBRARIES GLOBAL PROPERTY ALL_LOCAL_LIBRARIES)
list(APPEND ALL_LOCAL_LIBRARIES ${__TARGET_NAME})
set_property(GLOBAL PROPERTY ALL_LOCAL_LIBRARIES "${ALL_LOCAL_LIBRARIES}")
include_directories(
${PROJECT_SOURCE_DIR}/include
${PROJECT_BINARY_DIR}/include
)
add_library(${__TARGET_NAME} STATIC ${__SOURCES})
set_target_properties(
${__TARGET_NAME} PROPERTIES
OUTPUT_NAME ${__OUTPUT_NAME}
CLEAN_DIRECT_OUTPUT 1
)
target_include_directories(
${__TARGET_NAME} PUBLIC
${CMAKE_SOURCE_DIR}/include
${CMAKE_BINARY_DIR}/include
)
target_add_static_libraries(
${__TARGET_NAME}
"${__LIBRARIES}"
"${__LOCAL_LIBRARIES}"
)
endfunction(add_c_library)
|
281677160/openwrt-package | 4,805 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/include/libcork/ds/array.h | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2013, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license details.
* ----------------------------------------------------------------------
*/
#ifndef LIBCORK_DS_ARRAY_H
#define LIBCORK_DS_ARRAY_H
#include <libcork/core/api.h>
#include <libcork/core/callbacks.h>
#include <libcork/core/types.h>
/*-----------------------------------------------------------------------
* Resizable arrays
*/
struct cork_array_priv;
struct cork_raw_array {
void *items;
size_t size;
struct cork_array_priv *priv;
};
CORK_API void
cork_raw_array_init(struct cork_raw_array *array, size_t element_size);
CORK_API void
cork_raw_array_done(struct cork_raw_array *array);
CORK_API void
cork_raw_array_set_callback_data(struct cork_raw_array *array,
void *user_data, cork_free_f free_user_data);
CORK_API void
cork_raw_array_set_init(struct cork_raw_array *array, cork_init_f init);
CORK_API void
cork_raw_array_set_done(struct cork_raw_array *array, cork_done_f done);
CORK_API void
cork_raw_array_set_reuse(struct cork_raw_array *array, cork_init_f reuse);
CORK_API void
cork_raw_array_set_remove(struct cork_raw_array *array, cork_done_f remove);
CORK_API size_t
cork_raw_array_element_size(const struct cork_raw_array *array);
CORK_API void
cork_raw_array_clear(struct cork_raw_array *array);
CORK_API void *
cork_raw_array_elements(const struct cork_raw_array *array);
CORK_API void *
cork_raw_array_at(const struct cork_raw_array *array, size_t index);
CORK_API size_t
cork_raw_array_size(const struct cork_raw_array *array);
CORK_API bool
cork_raw_array_is_empty(const struct cork_raw_array *array);
CORK_API void
cork_raw_array_ensure_size(struct cork_raw_array *array, size_t count);
CORK_API void *
cork_raw_array_append(struct cork_raw_array *array);
CORK_API int
cork_raw_array_copy(struct cork_raw_array *dest,
const struct cork_raw_array *src,
cork_copy_f copy, void *user_data);
/*-----------------------------------------------------------------------
* Type-checked resizable arrays
*/
#define cork_array(T) \
struct { \
T *items; \
size_t size; \
struct cork_array_priv *priv; \
}
#define cork_array_element_size(arr) (sizeof((arr)->items[0]))
#define cork_array_elements(arr) ((arr)->items)
#define cork_array_at(arr, i) ((arr)->items[(i)])
#define cork_array_size(arr) ((arr)->size)
#define cork_array_is_empty(arr) ((arr)->size == 0)
#define cork_array_to_raw(arr) ((struct cork_raw_array *) (void *) (arr))
#define cork_array_init(arr) \
(cork_raw_array_init(cork_array_to_raw(arr), cork_array_element_size(arr)))
#define cork_array_done(arr) \
(cork_raw_array_done(cork_array_to_raw(arr)))
#define cork_array_set_callback_data(arr, ud, fud) \
(cork_raw_array_set_callback_data(cork_array_to_raw(arr), (ud), (fud)))
#define cork_array_set_init(arr, i) \
(cork_raw_array_set_init(cork_array_to_raw(arr), (i)))
#define cork_array_set_done(arr, d) \
(cork_raw_array_set_done(cork_array_to_raw(arr), (d)))
#define cork_array_set_reuse(arr, r) \
(cork_raw_array_set_reuse(cork_array_to_raw(arr), (r)))
#define cork_array_set_remove(arr, r) \
(cork_raw_array_set_remove(cork_array_to_raw(arr), (r)))
#define cork_array_clear(arr) \
(cork_raw_array_clear(cork_array_to_raw(arr)))
#define cork_array_copy(d, s, c, ud) \
(cork_raw_array_copy(cork_array_to_raw(d), cork_array_to_raw(s), (c), (ud)))
#define cork_array_ensure_size(arr, count) \
(cork_raw_array_ensure_size(cork_array_to_raw(arr), (count)))
#define cork_array_append(arr, element) \
(cork_raw_array_append(cork_array_to_raw(arr)), \
((arr)->items[(arr)->size - 1] = (element), (void) 0))
#define cork_array_append_get(arr) \
(cork_raw_array_append(cork_array_to_raw(arr)), \
&(arr)->items[(arr)->size - 1])
/*-----------------------------------------------------------------------
* Builtin array types
*/
CORK_API void
cork_raw_pointer_array_init(struct cork_raw_array *array, cork_free_f free);
#define cork_pointer_array_init(arr, f) \
(cork_raw_pointer_array_init(cork_array_to_raw(arr), (f)))
struct cork_string_array {
const char **items;
size_t size;
struct cork_array_priv *priv;
};
CORK_API void
cork_string_array_init(struct cork_string_array *array);
CORK_API void
cork_string_array_append(struct cork_string_array *array, const char *str);
CORK_API void
cork_string_array_copy(struct cork_string_array *dest,
const struct cork_string_array *src);
#endif /* LIBCORK_DS_ARRAY_H */
|
281677160/openwrt-package | 4,406 | luci-app-ssr-plus/shadowsocksr-libev/src/libcork/include/libcork/ds/buffer.h | /* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2012, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license
* details.
* ----------------------------------------------------------------------
*/
#ifndef LIBCORK_DS_BUFFER_H
#define LIBCORK_DS_BUFFER_H
#include <stdarg.h>
#include <libcork/core/api.h>
#include <libcork/core/attributes.h>
#include <libcork/core/types.h>
struct cork_buffer {
/* The current contents of the buffer. */
void *buf;
/* The current size of the buffer. */
size_t size;
/* The amount of space allocated for buf. */
size_t allocated_size;
};
CORK_API void
cork_buffer_init(struct cork_buffer *buffer);
#define CORK_BUFFER_INIT() { NULL, 0, 0 }
CORK_API struct cork_buffer *
cork_buffer_new(void);
CORK_API void
cork_buffer_done(struct cork_buffer *buffer);
CORK_API void
cork_buffer_free(struct cork_buffer *buffer);
CORK_API bool
cork_buffer_equal(const struct cork_buffer *buffer1,
const struct cork_buffer *buffer2);
CORK_API void
cork_buffer_ensure_size(struct cork_buffer *buffer, size_t desired_size);
CORK_API void
cork_buffer_clear(struct cork_buffer *buffer);
CORK_API void
cork_buffer_truncate(struct cork_buffer *buffer, size_t length);
#define cork_buffer_byte(buffer, i) (((const uint8_t *) (buffer)->buf)[(i)])
#define cork_buffer_char(buffer, i) (((const char *) (buffer)->buf)[(i)])
/*-----------------------------------------------------------------------
* A whole bunch of methods for adding data
*/
#define cork_buffer_copy(dest, src) \
(cork_buffer_set((dest), (src)->buf, (src)->size))
CORK_API void
cork_buffer_set(struct cork_buffer *buffer, const void *src, size_t length);
#define cork_buffer_append_copy(dest, src) \
(cork_buffer_append((dest), (src)->buf, (src)->size))
CORK_API void
cork_buffer_append(struct cork_buffer *buffer, const void *src, size_t length);
CORK_API void
cork_buffer_set_string(struct cork_buffer *buffer, const char *str);
CORK_API void
cork_buffer_append_string(struct cork_buffer *buffer, const char *str);
#define cork_buffer_set_literal(buffer, str) \
(cork_buffer_set((buffer), (str), sizeof((str)) - 1))
#define cork_buffer_append_literal(buffer, str) \
(cork_buffer_append((buffer), (str), sizeof((str)) - 1))
CORK_API void
cork_buffer_printf(struct cork_buffer *buffer, const char *format, ...)
CORK_ATTR_PRINTF(2,3);
CORK_API void
cork_buffer_append_printf(struct cork_buffer *buffer, const char *format, ...)
CORK_ATTR_PRINTF(2,3);
CORK_API void
cork_buffer_vprintf(struct cork_buffer *buffer, const char *format,
va_list args)
CORK_ATTR_PRINTF(2,0);
CORK_API void
cork_buffer_append_vprintf(struct cork_buffer *buffer, const char *format,
va_list args)
CORK_ATTR_PRINTF(2,0);
/*-----------------------------------------------------------------------
* Some helpers for pretty-printing data
*/
CORK_API void
cork_buffer_append_indent(struct cork_buffer *buffer, size_t indent);
CORK_API void
cork_buffer_append_c_string(struct cork_buffer *buffer,
const char *src, size_t length);
CORK_API void
cork_buffer_append_hex_dump(struct cork_buffer *buffer, size_t indent,
const char *src, size_t length);
CORK_API void
cork_buffer_append_multiline(struct cork_buffer *buffer, size_t indent,
const char *src, size_t length);
CORK_API void
cork_buffer_append_binary(struct cork_buffer *buffer, size_t indent,
const char *src, size_t length);
/*-----------------------------------------------------------------------
* Buffer's managed buffer/slice implementation
*/
#include <libcork/ds/managed-buffer.h>
#include <libcork/ds/slice.h>
CORK_API struct cork_managed_buffer *
cork_buffer_to_managed_buffer(struct cork_buffer *buffer);
CORK_API int
cork_buffer_to_slice(struct cork_buffer *buffer, struct cork_slice *slice);
/*-----------------------------------------------------------------------
* Buffer's stream consumer implementation
*/
#include <libcork/ds/stream.h>
CORK_API struct cork_stream_consumer *
cork_buffer_to_stream_consumer(struct cork_buffer *buffer);
#endif /* LIBCORK_DS_BUFFER_H */
|
Subsets and Splits
PyTorch Neural Network Imports
This query filters for code examples containing a specific PyTorch import pattern, which is useful for finding code snippets that use PyTorch's neural network module but doesn't provide deeper analytical insights about the dataset.
HTML Files in Train Set
Retrieves all records from the dataset where the file path ends with .html or .htm, providing a basic filter for HTML files.
SQL Console for nick007x/github-code-2025
Retrieves 200 file paths that end with '.html' or '.htm', providing a basic overview of HTML files in the dataset.
Top HTML Files
The query retrieves a sample of HTML file paths, providing basic filtering but limited analytical value.
CSharp Repositories Excluding Unity
Retrieves all records for repositories that contain C# files but are not related to Unity, providing a basic filter of the dataset.
C# File Count per Repository
Counts the total number of C# files across distinct repositories, providing a basic measure of C# file presence.
SQL Console for nick007x/github-code-2025
Lists unique repository IDs containing C# files, providing basic filtering to understand which repositories have C# code.
Select Groovy Files: Train Set
Retrieves the first 1000 entries from the 'train' dataset where the file path ends with '.groovy', providing a basic sample of Groovy files.
GitHub Repos with WiFiClientSecure
Finds specific file paths in repositories that contain particular code snippets related to WiFiClientSecure and ChatGPT, providing basic filtering of relevant files.