├── src ├── goodbyedpi-rc.rc ├── icon.ico ├── utils │ ├── repl_str.h │ ├── getline.h │ ├── repl_str.c │ ├── getline.c │ └── uthash.h ├── service.h ├── blackwhitelist.h ├── goodbyedpi.h ├── goodbyedpi.exe.manifest ├── fakepackets.h ├── dnsredir.h ├── Makefile ├── service.c ├── blackwhitelist.c ├── fakepackets.c ├── dnsredir.c └── goodbyedpi.c ├── .editorconfig ├── .github └── ISSUE_TEMPLATE │ ├── feature-request------------------------------------.md │ └── bug-report----------------------.md ├── README.md └── LICENSE /src/goodbyedpi-rc.rc: -------------------------------------------------------------------------------- 1 | 1 24 "goodbyedpi.exe.manifest" 2 | id ICON "icon.ico" 3 | -------------------------------------------------------------------------------- /src/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vmfunc/GoodbyeDPI/master/src/icon.ico -------------------------------------------------------------------------------- /src/utils/repl_str.h: -------------------------------------------------------------------------------- 1 | char *repl_str(const char *str, const char *from, const char *to); 2 | -------------------------------------------------------------------------------- /src/service.h: -------------------------------------------------------------------------------- 1 | int service_register(); 2 | void service_main(int argc, char *argv[]); 3 | void service_controlhandler(DWORD request); 4 | -------------------------------------------------------------------------------- /src/blackwhitelist.h: -------------------------------------------------------------------------------- 1 | int blackwhitelist_load_list(const char *filename); 2 | int blackwhitelist_check_hostname(const char *host_addr, size_t host_len); 3 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 4 7 | insert_final_newline = true 8 | end_of_line = lf 9 | -------------------------------------------------------------------------------- /src/utils/getline.h: -------------------------------------------------------------------------------- 1 | #if !HAVE_GETDELIM 2 | ssize_t getdelim(char **, size_t *, int, FILE *); 3 | #endif 4 | 5 | #if !HAVE_GETLINE 6 | ssize_t getline(char **, size_t *, FILE *); 7 | #endif 8 | -------------------------------------------------------------------------------- /src/goodbyedpi.h: -------------------------------------------------------------------------------- 1 | #define HOST_MAXLEN 253 2 | #define MAX_PACKET_SIZE 9016 3 | 4 | #ifndef DEBUG 5 | #define debug(...) do {} while (0) 6 | #else 7 | #define debug(...) printf(__VA_ARGS__) 8 | #endif 9 | 10 | int main(int argc, char *argv[]); 11 | void deinit_all(); 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request------------------------------------.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request / предложить новую функциональность 3 | about: Suggest an idea or function for this project / предложить новую идею или функциональность 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Description / Описание** 11 | A clear and concise description of your suggestion. 12 | Детальное описание вашего предложения. 13 | -------------------------------------------------------------------------------- /src/goodbyedpi.exe.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GoodbyeDPI 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/fakepackets.h: -------------------------------------------------------------------------------- 1 | int send_fake_http_request(const HANDLE w_filter, 2 | const PWINDIVERT_ADDRESS addr, 3 | const char *pkt, 4 | const UINT packetLen, 5 | const BOOL is_ipv6, 6 | const BYTE set_ttl, 7 | const BYTE set_checksum 8 | ); 9 | int send_fake_https_request(const HANDLE w_filter, 10 | const PWINDIVERT_ADDRESS addr, 11 | const char *pkt, 12 | const UINT packetLen, 13 | const BOOL is_ipv6, 14 | const BYTE set_ttl, 15 | const BYTE set_checksum 16 | ); 17 | -------------------------------------------------------------------------------- /src/dnsredir.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef struct conntrack_info { 4 | uint8_t is_ipv6; 5 | uint32_t srcip[4]; 6 | uint16_t srcport; 7 | uint32_t dstip[4]; 8 | uint16_t dstport; 9 | } conntrack_info_t; 10 | 11 | inline static void ipv4_copy_addr(uint32_t dst[4], const uint32_t src[4]) { 12 | dst[0] = src[0]; 13 | dst[1] = 0; 14 | dst[2] = 0; 15 | dst[3] = 0; 16 | } 17 | 18 | inline static void ipv6_copy_addr(uint32_t dst[4], const uint32_t src[4]) { 19 | dst[0] = src[0]; 20 | dst[1] = src[1]; 21 | dst[2] = src[2]; 22 | dst[3] = src[3]; 23 | } 24 | 25 | int dns_handle_incoming(const uint32_t srcip[4], const uint16_t srcport, 26 | const char *packet_data, const UINT packet_dataLen, 27 | conntrack_info_t *conn_info, const uint8_t is_ipv6); 28 | 29 | int dns_handle_outgoing(const uint32_t srcip[4], const uint16_t srcport, 30 | const uint32_t dstip[4], const uint16_t dstport, 31 | const char *packet_data, const UINT packet_dataLen, 32 | const uint8_t is_ipv6 33 | ); 34 | 35 | void flush_dns_cache(); 36 | int dns_is_dns_packet(const char *packet_data, const UINT packet_dataLen, const int outgoing); 37 | -------------------------------------------------------------------------------- /src/Makefile: -------------------------------------------------------------------------------- 1 | ifndef MSYSTEM 2 | CPREFIX = x86_64-w64-mingw32- 3 | endif 4 | 5 | WINDIVERTHEADERS = ../../../include 6 | WINDIVERTLIBS = ../../binary 7 | MINGWLIB = /usr/x86_64-w64-mingw32/lib/ 8 | 9 | TARGET = goodbyedpi.exe 10 | # Linking SSP does not work for some reason, the executable doesn't start. 11 | #LIBS = -L$(WINDIVERTLIBS) -Wl,-Bstatic -lssp -Wl,-Bdynamic -lWinDivert -lws2_32 12 | LIBS = -L$(WINDIVERTLIBS) -lWinDivert -lws2_32 13 | CC = $(CPREFIX)gcc 14 | CCWINDRES = $(CPREFIX)windres 15 | CFLAGS = -std=c99 -pie -fPIE -pipe -I$(WINDIVERTHEADERS) -L$(WINDIVERTLIBS) \ 16 | -O2 -D_FORTIFY_SOURCE=2 \ 17 | -Wall -Wextra -Wpedantic -Wformat=2 -Wshadow -Wstrict-aliasing=1 -Werror=format-security \ 18 | -Wfloat-equal -Wcast-align -Wsign-conversion \ 19 | #-fstack-protector-strong 20 | LDFLAGS = -Wl,-O1,-pie,--dynamicbase,--nxcompat,--sort-common,--as-needed \ 21 | -Wl,--image-base,0x140000000 -Wl,--disable-auto-image-base 22 | 23 | ifdef BIT64 24 | LDFLAGS += -Wl,--high-entropy-va -Wl,--pic-executable,-e,mainCRTStartup 25 | else 26 | LDFLAGS += -Wl,--pic-executable,-e,_mainCRTStartup 27 | endif 28 | 29 | .PHONY: default all clean 30 | 31 | default: manifest $(TARGET) 32 | all: default 33 | 34 | OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c utils/*.c)) goodbyedpi-rc.o 35 | HEADERS = $(wildcard *.h utils/*.h) 36 | 37 | %.o: %.c $(HEADERS) 38 | $(CC) $(CFLAGS) -c $< -o $@ 39 | 40 | manifest: 41 | $(CCWINDRES) goodbyedpi-rc.rc goodbyedpi-rc.o 42 | 43 | .PRECIOUS: $(TARGET) $(OBJECTS) 44 | 45 | $(TARGET): $(OBJECTS) 46 | $(CC) $(OBJECTS) $(LDFLAGS) $(LIBS) -s -o $@ 47 | 48 | clean: 49 | -rm -f *.o utils/*.o 50 | -rm -f $(TARGET) 51 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report----------------------.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report / сообщение об ошибке 3 | about: Report software issue / сообщить об ошибке в программе 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 21 | 22 | **Describe the bug / Опишите проблему** 23 | A clear and concise description of what the bug is. If the issue about software incompatibility, include your operating system version and software name/version. 24 | Подробно опишите, в чём заключается проблема. Если проблема касается совместимости с другими программами, укажите версию вашей операционной системы, имя и версию программы. 25 | 26 | **To Reproduce / Шаги воспроизведения проблемы** 27 | Steps to reproduce the behavior: 28 | 1. Go to '...' 29 | 2. Click on '....' 30 | 3. Scroll down to '....' 31 | 4. See error 32 | 33 | **Expected behavior / ожидаемое поведение программы** 34 | A clear and concise description of what you expected to happen. 35 | Подробно опишите, как вы ожидаете, чтобы программа работала. 36 | 37 | **Actual behavior / текущее поведение программы** 38 | A clear and concise description of what you expected to happen. 39 | Подробно опишите, что происходит с программой на текущий момент. 40 | 41 | **Screenshots / Скриншоты** 42 | If applicable, add screenshots to help explain your problem. 43 | Если необходимо, добавьте скриншоты, объясняющие проблему. 44 | 45 | **Additional context / дополнительная информация** 46 | -------------------------------------------------------------------------------- /src/utils/repl_str.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #if (__STDC_VERSION__ >= 199901L) 6 | #include 7 | #endif 8 | 9 | char *repl_str(const char *str, const char *from, const char *to) { 10 | 11 | /* Adjust each of the below values to suit your needs. */ 12 | 13 | /* Increment positions cache size initially by this number. */ 14 | size_t cache_sz_inc = 16; 15 | /* Thereafter, each time capacity needs to be increased, 16 | * multiply the increment by this factor. */ 17 | const size_t cache_sz_inc_factor = 3; 18 | /* But never increment capacity by more than this number. */ 19 | const size_t cache_sz_inc_max = 1048576; 20 | 21 | char *pret, *ret = NULL; 22 | const char *pstr2, *pstr = str; 23 | size_t i, count = 0; 24 | #if (__STDC_VERSION__ >= 199901L) 25 | uintptr_t *pos_cache_tmp, *pos_cache = NULL; 26 | #else 27 | ptrdiff_t *pos_cache_tmp, *pos_cache = NULL; 28 | #endif 29 | size_t cache_sz = 0; 30 | size_t cpylen, orglen, retlen, tolen, fromlen = strlen(from); 31 | 32 | /* Find all matches and cache their positions. */ 33 | while ((pstr2 = strstr(pstr, from)) != NULL) { 34 | count++; 35 | 36 | /* Increase the cache size when necessary. */ 37 | if (cache_sz < count) { 38 | cache_sz += cache_sz_inc; 39 | pos_cache_tmp = realloc(pos_cache, sizeof(*pos_cache) * cache_sz); 40 | if (pos_cache_tmp == NULL) { 41 | goto end_repl_str; 42 | } else pos_cache = pos_cache_tmp; 43 | cache_sz_inc *= cache_sz_inc_factor; 44 | if (cache_sz_inc > cache_sz_inc_max) { 45 | cache_sz_inc = cache_sz_inc_max; 46 | } 47 | } 48 | 49 | pos_cache[count-1] = pstr2 - str; 50 | pstr = pstr2 + fromlen; 51 | } 52 | 53 | orglen = pstr - str + strlen(pstr); 54 | 55 | /* Allocate memory for the post-replacement string. */ 56 | if (count > 0) { 57 | tolen = strlen(to); 58 | retlen = orglen + (tolen - fromlen) * count; 59 | } else retlen = orglen; 60 | ret = malloc(retlen + 1); 61 | if (ret == NULL) { 62 | goto end_repl_str; 63 | } 64 | 65 | if (count == 0) { 66 | /* If no matches, then just duplicate the string. */ 67 | strcpy(ret, str); 68 | } else { 69 | /* Otherwise, duplicate the string whilst performing 70 | * the replacements using the position cache. */ 71 | pret = ret; 72 | memcpy(pret, str, pos_cache[0]); 73 | pret += pos_cache[0]; 74 | for (i = 0; i < count; i++) { 75 | memcpy(pret, to, tolen); 76 | pret += tolen; 77 | pstr = str + pos_cache[i] + fromlen; 78 | cpylen = (i == count-1 ? orglen : pos_cache[i+1]) - pos_cache[i] - fromlen; 79 | memcpy(pret, pstr, cpylen); 80 | pret += cpylen; 81 | } 82 | ret[retlen] = '\0'; 83 | } 84 | 85 | end_repl_str: 86 | /* Free the cache and return the post-replacement string, 87 | * which will be NULL in the event of an error. */ 88 | free(pos_cache); 89 | return ret; 90 | } 91 | -------------------------------------------------------------------------------- /src/utils/getline.c: -------------------------------------------------------------------------------- 1 | /* $NetBSD: getdelim.c,v 1.2 2015/12/25 20:12:46 joerg Exp $ */ 2 | /* NetBSD-src: getline.c,v 1.2 2014/09/16 17:23:50 christos Exp */ 3 | 4 | /*- 5 | * Copyright (c) 2011 The NetBSD Foundation, Inc. 6 | * All rights reserved. 7 | * 8 | * This code is derived from software contributed to The NetBSD Foundation 9 | * by Christos Zoulas. 10 | * 11 | * Redistribution and use in source and binary forms, with or without 12 | * modification, are permitted provided that the following conditions 13 | * are met: 14 | * 1. Redistributions of source code must retain the above copyright 15 | * notice, this list of conditions and the following disclaimer. 16 | * 2. Redistributions in binary form must reproduce the above copyright 17 | * notice, this list of conditions and the following disclaimer in the 18 | * documentation and/or other materials provided with the distribution. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 21 | * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 22 | * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 23 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 24 | * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 | * POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #include 34 | #include 35 | #include "getline.h" 36 | 37 | #if !HAVE_GETDELIM 38 | 39 | ssize_t 40 | getdelim(char **buf, size_t *bufsiz, int delimiter, FILE *fp) 41 | { 42 | char *ptr, *eptr; 43 | 44 | 45 | if (*buf == NULL || *bufsiz == 0) { 46 | *bufsiz = BUFSIZ; 47 | if ((*buf = malloc(*bufsiz)) == NULL) 48 | return -1; 49 | } 50 | 51 | for (ptr = *buf, eptr = *buf + *bufsiz;;) { 52 | int c = fgetc(fp); 53 | if (c == -1) { 54 | if (feof(fp)) { 55 | ssize_t diff = (ssize_t)(ptr - *buf); 56 | if (diff != 0) { 57 | *ptr = '\0'; 58 | return diff; 59 | } 60 | } 61 | return -1; 62 | } 63 | *ptr++ = c; 64 | if (c == delimiter) { 65 | *ptr = '\0'; 66 | return ptr - *buf; 67 | } 68 | if (ptr + 2 >= eptr) { 69 | char *nbuf; 70 | size_t nbufsiz = *bufsiz * 2; 71 | ssize_t d = ptr - *buf; 72 | if ((nbuf = realloc(*buf, nbufsiz)) == NULL) 73 | return -1; 74 | *buf = nbuf; 75 | *bufsiz = nbufsiz; 76 | eptr = nbuf + nbufsiz; 77 | ptr = nbuf + d; 78 | } 79 | } 80 | } 81 | 82 | #endif 83 | 84 | #if !HAVE_GETLINE 85 | 86 | ssize_t 87 | getline(char **buf, size_t *bufsiz, FILE *fp) 88 | { 89 | return getdelim(buf, bufsiz, '\n', fp); 90 | } 91 | 92 | #endif 93 | -------------------------------------------------------------------------------- /src/service.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "goodbyedpi.h" 4 | #include "service.h" 5 | 6 | #define SERVICE_NAME "GoodbyeDPI" 7 | 8 | static SERVICE_STATUS ServiceStatus; 9 | static SERVICE_STATUS_HANDLE hStatus; 10 | static int service_argc = 0; 11 | static char **service_argv = NULL; 12 | 13 | int service_register(int argc, char *argv[]) 14 | { 15 | int i, ret; 16 | SERVICE_TABLE_ENTRY ServiceTable[] = { 17 | {SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)service_main}, 18 | {NULL, NULL} 19 | }; 20 | /* 21 | * Save argc & argv as service_main is called with different 22 | * arguments, which are passed from "start" command, not 23 | * from the program command line. 24 | * We don't need this behaviour. 25 | * 26 | * Note that if StartServiceCtrlDispatcher() succeedes 27 | * it does not return until the service is stopped, 28 | * so we should copy all arguments first and then 29 | * handle the failure. 30 | */ 31 | if (!service_argc && !service_argv) { 32 | service_argc = argc; 33 | service_argv = malloc(sizeof(void*) * argc); 34 | for (i = 0; i < argc; i++) { 35 | service_argv[i] = strdup(argv[i]); 36 | } 37 | } 38 | 39 | ret = StartServiceCtrlDispatcher(ServiceTable); 40 | 41 | if (service_argc && service_argv) { 42 | for (i = 0; i < service_argc; i++) { 43 | free(service_argv[i]); 44 | } 45 | free(service_argv); 46 | } 47 | 48 | return ret; 49 | } 50 | 51 | void service_main(int argc __attribute__((unused)), 52 | char *argv[] __attribute__((unused))) 53 | { 54 | ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; 55 | ServiceStatus.dwCurrentState = SERVICE_RUNNING; 56 | ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; 57 | ServiceStatus.dwWin32ExitCode = 0; 58 | ServiceStatus.dwServiceSpecificExitCode = 0; 59 | ServiceStatus.dwCheckPoint = 1; 60 | ServiceStatus.dwWaitHint = 0; 61 | 62 | hStatus = RegisterServiceCtrlHandler( 63 | SERVICE_NAME, 64 | (LPHANDLER_FUNCTION)service_controlhandler); 65 | if (hStatus == (SERVICE_STATUS_HANDLE)0) 66 | { 67 | // Registering Control Handler failed 68 | return; 69 | } 70 | 71 | SetServiceStatus(hStatus, &ServiceStatus); 72 | 73 | // Calling main with saved argc & argv 74 | ServiceStatus.dwWin32ExitCode = main(service_argc, service_argv); 75 | ServiceStatus.dwCurrentState = SERVICE_STOPPED; 76 | SetServiceStatus(hStatus, &ServiceStatus); 77 | return; 78 | } 79 | 80 | // Control handler function 81 | void service_controlhandler(DWORD request) 82 | { 83 | switch(request) 84 | { 85 | case SERVICE_CONTROL_STOP: 86 | case SERVICE_CONTROL_SHUTDOWN: 87 | deinit_all(); 88 | ServiceStatus.dwWin32ExitCode = 0; 89 | ServiceStatus.dwCurrentState = SERVICE_STOPPED; 90 | default: 91 | break; 92 | } 93 | // Report current status 94 | SetServiceStatus(hStatus, &ServiceStatus); 95 | return; 96 | } 97 | -------------------------------------------------------------------------------- /src/blackwhitelist.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Blacklist for GoodbyeDPI HTTP DPI circumvention tricks 3 | * 4 | * This is a simple domain hash table. 5 | * Domain records are added from a text file, where every 6 | * domain is separated with a new line. 7 | */ 8 | #include 9 | #include 10 | #include "goodbyedpi.h" 11 | #include "utils/uthash.h" 12 | #include "utils/getline.h" 13 | 14 | typedef struct blackwhitelist_record { 15 | const char *host; 16 | UT_hash_handle hh; /* makes this structure hashable */ 17 | } blackwhitelist_record_t; 18 | 19 | static blackwhitelist_record_t *blackwhitelist = NULL; 20 | 21 | static int check_get_hostname(const char *host) { 22 | blackwhitelist_record_t *tmp_record = NULL; 23 | if (!blackwhitelist) return FALSE; 24 | 25 | HASH_FIND_STR(blackwhitelist, host, tmp_record); 26 | if (tmp_record) { 27 | debug("check_get_hostname found host\n"); 28 | return TRUE; 29 | } 30 | debug("check_get_hostname host not found\n"); 31 | return FALSE; 32 | } 33 | 34 | static int add_hostname(const char *host) { 35 | if (!host) 36 | return FALSE; 37 | 38 | int host_len = strlen(host); 39 | 40 | blackwhitelist_record_t *tmp_record = malloc(sizeof(blackwhitelist_record_t)); 41 | char *host_c = malloc(host_len + 1); 42 | 43 | if (!check_get_hostname(host)) { 44 | strncpy(host_c, host, host_len); 45 | host_c[host_len] = '\0'; 46 | tmp_record->host = host_c; 47 | HASH_ADD_KEYPTR(hh, blackwhitelist, tmp_record->host, 48 | strlen(tmp_record->host), tmp_record); 49 | debug("Added host %s\n", host_c); 50 | return TRUE; 51 | } 52 | debug("Not added host %s\n", host); 53 | free(tmp_record); 54 | free(host_c); 55 | return FALSE; 56 | } 57 | 58 | int blackwhitelist_load_list(const char *filename) { 59 | char *line = malloc(HOST_MAXLEN + 1); 60 | size_t linelen = HOST_MAXLEN + 1; 61 | int cnt = 0; 62 | ssize_t read; 63 | 64 | FILE *fp = fopen(filename, "r"); 65 | if (!fp) return FALSE; 66 | 67 | while ((read = getline(&line, &linelen, fp)) != -1) { 68 | /* works with both \n and \r\n */ 69 | line[strcspn(line, "\r\n")] = '\0'; 70 | if (strlen(line) > HOST_MAXLEN) { 71 | printf("WARNING: host %s exceeds maximum host length and has not been added\n", 72 | line); 73 | continue; 74 | } 75 | if (strlen(line) < 4) 76 | continue; 77 | if (add_hostname(line)) 78 | cnt++; 79 | } 80 | free(line); 81 | if (!blackwhitelist) return FALSE; 82 | printf("Loaded %d hosts from file %s\n", cnt, filename); 83 | fclose(fp); 84 | return TRUE; 85 | } 86 | 87 | int blackwhitelist_check_hostname(const char *host_addr, size_t host_len) { 88 | char current_host[HOST_MAXLEN + 1]; 89 | char *tokenized_host = NULL; 90 | 91 | if (host_len > HOST_MAXLEN) return FALSE; 92 | if (host_addr && host_len) { 93 | memcpy(current_host, host_addr, host_len); 94 | current_host[host_len] = '\0'; 95 | } 96 | 97 | if (check_get_hostname(current_host)) 98 | return TRUE; 99 | 100 | tokenized_host = strchr(current_host, '.'); 101 | while (tokenized_host != NULL && tokenized_host < (current_host + HOST_MAXLEN)) { 102 | /* Search hostname only if there is next token */ 103 | if (strchr(tokenized_host + 1, '.') && check_get_hostname(tokenized_host + 1)) 104 | return TRUE; 105 | tokenized_host = strchr(tokenized_host + 1, '.'); 106 | } 107 | 108 | debug("____blackwhitelist_check_hostname FALSE: host %s\n", current_host); 109 | return FALSE; 110 | } 111 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | GoodbyeDPI — Passive Deep Packet Inspection blocker and Active DPI circumvention utility 2 | ========================= 3 | 4 | This software designed to bypass Deep Packet Inspection systems found in many Internet Service Providers which block access to certain websites. 5 | 6 | It handles DPI connected using optical splitter or port mirroring (**Passive DPI**) which do not block any data but just replying faster than requested destination, and **Active DPI** connected in sequence. 7 | 8 | **Windows 7, 8, 8.1 and 10** with administrator privileges required. 9 | 10 | # How to use 11 | 12 | Download [latest version from Releases page](https://github.com/ValdikSS/GoodbyeDPI/releases) and run. 13 | 14 | ``` 15 | Usage: goodbyedpi.exe [OPTION...] 16 | -p block passive DPI 17 | -r replace Host with hoSt 18 | -s remove space between host header and its value 19 | -m mix Host header case (test.com -> tEsT.cOm) 20 | -f [value] set HTTP fragmentation to value 21 | -k [value] enable HTTP persistent (keep-alive) fragmentation and set it to value 22 | -n do not wait for first segment ACK when -k is enabled 23 | -e [value] set HTTPS fragmentation to value 24 | -a additional space between Method and Request-URI (enables -s, may break sites) 25 | -w try to find and parse HTTP traffic on all processed ports (not only on port 80) 26 | --port [value] additional TCP port to perform fragmentation on (and HTTP tricks with -w) 27 | --ip-id [value] handle additional IP ID (decimal, drop redirects and TCP RSTs with this ID). 28 | This option can be supplied multiple times. 29 | --dns-addr [value] redirect UDP DNS requests to the supplied IP address (experimental) 30 | --dns-port [value] redirect UDP DNS requests to the supplied port (53 by default) 31 | --dnsv6-addr [value] redirect UDPv6 DNS requests to the supplied IPv6 address (experimental) 32 | --dnsv6-port [value] redirect UDPv6 DNS requests to the supplied port (53 by default) 33 | --dns-verb print verbose DNS redirection messages 34 | --blacklist [txtfile] perform HTTP tricks only to host names and subdomains from 35 | supplied text file. This option can be supplied multiple times. 36 | --set-ttl [value] activate Fake Request Mode and send it with supplied TTL value. 37 | DANGEROUS! May break websites in unexpected ways. Use with care. 38 | --wrong-chksum activate Fake Request Mode and send it with incorrect TCP checksum. 39 | May not work in a VM or with some routers, but is safer than set-ttl. 40 | 41 | -1 -p -r -s -f 2 -k 2 -n -e 2 (most compatible mode, default) 42 | -2 -p -r -s -f 2 -k 2 -n -e 40 (better speed for HTTPS yet still compatible) 43 | -3 -p -r -s -e 40 (better speed for HTTP and HTTPS) 44 | -4 -p -r -s (best speed) 45 | ``` 46 | 47 | To check if your ISP's DPI could be circumvented, run `3_all_dnsredir_hardcore.cmd` first. This is the most hardcore mode which will show if this program is suitable for your ISP and DPI vendor at all. If you can open blocked websites with this mode, it means your ISP has DPI which can be circumvented. This is the slowest and prone to break websites mode, but suitable for most DPI. 48 | 49 | Try `goodbyedpi -1` to see if it works too. 50 | 51 | Then try `goodbyedpi.exe -2`. It should be faster for HTTPS sites. Mode `-3` speed ups HTTP websites. 52 | 53 | Use `goodbyedpi.exe -4` if it works for your ISP's DPI. This is the fastest mode but not compatible with every DPI. 54 | 55 | # How does it work 56 | 57 | ### Passive DPI 58 | 59 | Most Passive DPI send HTTP 302 Redirect if you try to access blocked website over HTTP and TCP Reset in case of HTTPS, faster than destination website. Packets sent by DPI usually have IP Identification field equal to `0x0000` or `0x0001`, as seen with Russian providers. These packets, if they redirect you to another website (censorship page), are blocked by GoodbyeDPI. 60 | 61 | ### Active DPI 62 | 63 | Active DPI is more tricky to fool. Currently the software uses 7 methods to circumvent Active DPI: 64 | 65 | * TCP-level fragmentation for first data packet 66 | * TCP-level fragmentation for persistent (keep-alive) HTTP sessions 67 | * Replacing `Host` header with `hoSt` 68 | * Removing space between header name and value in `Host` header 69 | * Adding additional space between HTTP Method (GET, POST etc) and URI 70 | * Mixing case of Host header value 71 | * Sending fake HTTP/HTTPS packets with low Time-To-Live value or incorrect checksum to fool DPI and prevent delivering them to the destination 72 | 73 | These methods should not break any website as they're fully compatible with TCP and HTTP standards, yet it's sufficient to prevent DPI data classification and to circumvent censorship. Additional space may break some websites, although it's acceptable by HTTP/1.1 specification (see 19.3 Tolerant Applications). 74 | 75 | The program loads WinDivert driver which uses Windows Filtering Platform to set filters and redirect packets to the userspace. It's running as long as console window is visible and terminates when you close the window. 76 | 77 | # How to build from source 78 | 79 | This project can be build using **GNU Make** and [**mingw**](https://mingw-w64.org). The only dependency is [WinDivert](https://github.com/basil00/Divert). 80 | 81 | To build x86 exe run: 82 | 83 | `make CPREFIX=i686-w64-mingw32- WINDIVERTHEADERS=/path/to/windivert/include WINDIVERTLIBS=/path/to/windivert/x86` 84 | 85 | And for x86_64: 86 | 87 | `make CPREFIX=x86_64-w64-mingw32- BIT64=1 WINDIVERTHEADERS=/path/to/windivert/include WINDIVERTLIBS=/path/to/windivert/amd64` 88 | 89 | # How to install as Windows Service 90 | 91 | Use `service_install_russia_blacklist.cmd`, `service_install_russia_blacklist_dnsredir.cmd` and `service_remove.cmd` scripts. 92 | Modify them according to your own needs. 93 | 94 | # Known issues 95 | 96 | * Horribly outdated Windows 7 installations are not able to load WinDivert driver due to missing support for SHA256 digital signatures. Install KB3033929 [x86](https://www.microsoft.com/en-us/download/details.aspx?id=46078)/[x64](https://www.microsoft.com/en-us/download/details.aspx?id=46148), or better, update the whole system using Windows Update. 97 | * Some SSL/TLS stacks unable to process fragmented ClientHello packets, and HTTPS websites won't open. Bug: [#4](https://github.com/ValdikSS/GoodbyeDPI/issues/4), [#64](https://github.com/ValdikSS/GoodbyeDPI/issues/64). 98 | * ESET Antivirus is incompatible with WinDivert driver [#91](https://github.com/ValdikSS/GoodbyeDPI/issues/91). This is most probably antivirus bug, not WinDivert. 99 | 100 | 101 | # Similar projects 102 | 103 | - **[zapret](https://github.com/bol-van/zapret)** by @bol-van (for Linux). 104 | - **[Green Tunnel](https://github.com/SadeghHayeri/GreenTunnel)** by @SadeghHayeri (for MacOS, Linux and Windows). 105 | - **[DPITunnel](https://github.com/zhenyolka/DPITunnel)** by @zhenyolka (for Android). 106 | - **[PowerTunnel](https://github.com/krlvm/PowerTunnel)** by @krlvm (for Windows, MacOS and Linux). 107 | - **[PowerTunnel for Android](https://github.com/krlvm/PowerTunnel-Android)** by @krlvm (for Android). 108 | 109 | # Kudos 110 | 111 | Thanks @basil00 for [WinDivert](https://github.com/basil00/Divert). That's the main part of this program. 112 | 113 | Thanks for every [BlockCheck](https://github.com/ValdikSS/blockcheck) contributor. It would be impossible to understand DPI behaviour without this utility. 114 | -------------------------------------------------------------------------------- /src/fakepackets.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "windivert.h" 8 | #include "goodbyedpi.h" 9 | 10 | static const char fake_http_request[] = "GET / HTTP/1.1\r\nHost: www.w3.org\r\n" 11 | "User-Agent: curl/7.65.3\r\nAccept: */*\r\n" 12 | "Accept-Encoding: deflate, gzip, br\r\n\r\n"; 13 | static const unsigned char fake_https_request[] = { 14 | 0x16, 0x03, 0x01, 0x02, 0x00, 0x01, 0x00, 0x01, 0xfc, 0x03, 0x03, 0x9a, 0x8f, 0xa7, 0x6a, 0x5d, 15 | 0x57, 0xf3, 0x62, 0x19, 0xbe, 0x46, 0x82, 0x45, 0xe2, 0x59, 0x5c, 0xb4, 0x48, 0x31, 0x12, 0x15, 16 | 0x14, 0x79, 0x2c, 0xaa, 0xcd, 0xea, 0xda, 0xf0, 0xe1, 0xfd, 0xbb, 0x20, 0xf4, 0x83, 0x2a, 0x94, 17 | 0xf1, 0x48, 0x3b, 0x9d, 0xb6, 0x74, 0xba, 0x3c, 0x81, 0x63, 0xbc, 0x18, 0xcc, 0x14, 0x45, 0x57, 18 | 0x6c, 0x80, 0xf9, 0x25, 0xcf, 0x9c, 0x86, 0x60, 0x50, 0x31, 0x2e, 0xe9, 0x00, 0x22, 0x13, 0x01, 19 | 0x13, 0x03, 0x13, 0x02, 0xc0, 0x2b, 0xc0, 0x2f, 0xcc, 0xa9, 0xcc, 0xa8, 0xc0, 0x2c, 0xc0, 0x30, 20 | 0xc0, 0x0a, 0xc0, 0x09, 0xc0, 0x13, 0xc0, 0x14, 0x00, 0x33, 0x00, 0x39, 0x00, 0x2f, 0x00, 0x35, 21 | 0x01, 0x00, 0x01, 0x91, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x0d, 0x00, 0x00, 0x0a, 0x77, 0x77, 0x77, 22 | 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x00, 0x17, 0x00, 0x00, 0xff, 0x01, 0x00, 0x01, 0x00, 23 | 0x00, 0x0a, 0x00, 0x0e, 0x00, 0x0c, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x18, 0x00, 0x19, 0x01, 0x00, 24 | 0x01, 0x01, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0e, 25 | 0x00, 0x0c, 0x02, 0x68, 0x32, 0x08, 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31, 0x00, 0x05, 26 | 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x00, 0x6b, 0x00, 0x69, 0x00, 0x1d, 0x00, 27 | 0x20, 0xb0, 0xe4, 0xda, 0x34, 0xb4, 0x29, 0x8d, 0xd3, 0x5c, 0x70, 0xd3, 0xbe, 0xe8, 0xa7, 0x2a, 28 | 0x6b, 0xe4, 0x11, 0x19, 0x8b, 0x18, 0x9d, 0x83, 0x9a, 0x49, 0x7c, 0x83, 0x7f, 0xa9, 0x03, 0x8c, 29 | 0x3c, 0x00, 0x17, 0x00, 0x41, 0x04, 0x4c, 0x04, 0xa4, 0x71, 0x4c, 0x49, 0x75, 0x55, 0xd1, 0x18, 30 | 0x1e, 0x22, 0x62, 0x19, 0x53, 0x00, 0xde, 0x74, 0x2f, 0xb3, 0xde, 0x13, 0x54, 0xe6, 0x78, 0x07, 31 | 0x94, 0x55, 0x0e, 0xb2, 0x6c, 0xb0, 0x03, 0xee, 0x79, 0xa9, 0x96, 0x1e, 0x0e, 0x98, 0x17, 0x78, 32 | 0x24, 0x44, 0x0c, 0x88, 0x80, 0x06, 0x8b, 0xd4, 0x80, 0xbf, 0x67, 0x7c, 0x37, 0x6a, 0x5b, 0x46, 33 | 0x4c, 0xa7, 0x98, 0x6f, 0xb9, 0x22, 0x00, 0x2b, 0x00, 0x09, 0x08, 0x03, 0x04, 0x03, 0x03, 0x03, 34 | 0x02, 0x03, 0x01, 0x00, 0x0d, 0x00, 0x18, 0x00, 0x16, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03, 0x08, 35 | 0x04, 0x08, 0x05, 0x08, 0x06, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01, 0x02, 0x03, 0x02, 0x01, 0x00, 36 | 0x2d, 0x00, 0x02, 0x01, 0x01, 0x00, 0x1c, 0x00, 0x02, 0x40, 0x01, 0x00, 0x15, 0x00, 0x96, 0x00, 37 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 38 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 39 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 40 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 41 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 42 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 43 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 44 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 45 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 46 | 0x00, 0x00, 0x00, 0x00, 0x00 47 | }; 48 | 49 | static int send_fake_data(const HANDLE w_filter, 50 | const PWINDIVERT_ADDRESS addr, 51 | const char *pkt, 52 | const UINT packetLen, 53 | const BOOL is_ipv6, 54 | const BOOL is_https, 55 | const BYTE set_ttl, 56 | const BYTE set_checksum 57 | ) { 58 | char packet_fake[MAX_PACKET_SIZE]; 59 | WINDIVERT_ADDRESS addr_new; 60 | PVOID packet_data; 61 | UINT packet_dataLen; 62 | UINT packetLen_new; 63 | PWINDIVERT_IPHDR ppIpHdr; 64 | PWINDIVERT_IPV6HDR ppIpV6Hdr; 65 | PWINDIVERT_TCPHDR ppTcpHdr; 66 | char *fake_request_data = is_https ? fake_https_request : fake_http_request; 67 | UINT fake_request_size = is_https ? sizeof(fake_https_request) : sizeof(fake_http_request) - 1; 68 | 69 | memcpy(&addr_new, addr, sizeof(WINDIVERT_ADDRESS)); 70 | memcpy(packet_fake, pkt, packetLen); 71 | 72 | if (!is_ipv6) { 73 | // IPv4 TCP Data packet 74 | if (!WinDivertHelperParsePacket(packet_fake, packetLen, &ppIpHdr, 75 | NULL, NULL, NULL, &ppTcpHdr, NULL, &packet_data, &packet_dataLen)) 76 | return 1; 77 | } 78 | else { 79 | // IPv6 TCP Data packet 80 | if (!WinDivertHelperParsePacket(packet_fake, packetLen, NULL, 81 | &ppIpV6Hdr, NULL, NULL, &ppTcpHdr, NULL, &packet_data, &packet_dataLen)) 82 | return 1; 83 | } 84 | 85 | if (packetLen + fake_request_size + 1 > MAX_PACKET_SIZE) 86 | return 2; 87 | 88 | memcpy(packet_data, fake_request_data, fake_request_size); 89 | packetLen_new = packetLen - packet_dataLen + fake_request_size; 90 | 91 | if (!is_ipv6) { 92 | ppIpHdr->Length = htons( 93 | ntohs(ppIpHdr->Length) - 94 | packet_dataLen + fake_request_size 95 | ); 96 | 97 | if (set_ttl) 98 | ppIpHdr->TTL = set_ttl; 99 | } 100 | else { 101 | ppIpV6Hdr->Length = htons( 102 | ntohs(ppIpV6Hdr->Length) - 103 | packet_dataLen + fake_request_size 104 | ); 105 | 106 | if (set_ttl) 107 | ppIpV6Hdr->HopLimit = set_ttl; 108 | } 109 | 110 | // Recalculate the checksum 111 | addr_new.PseudoTCPChecksum = 0; 112 | WinDivertHelperCalcChecksums(packet_fake, packetLen_new, &addr_new, NULL); 113 | 114 | if (set_checksum) { 115 | // ...and damage it 116 | ppTcpHdr->Checksum = htons(ntohs(ppTcpHdr->Checksum) - 1); 117 | } 118 | //printf("Pseudo checksum: %d\n", addr_new.PseudoTCPChecksum); 119 | 120 | WinDivertSend( 121 | w_filter, packet_fake, 122 | packetLen_new, 123 | &addr_new, NULL 124 | ); 125 | debug("Fake packet: OK"); 126 | 127 | return 0; 128 | } 129 | 130 | int send_fake_http_request(const HANDLE w_filter, 131 | const PWINDIVERT_ADDRESS addr, 132 | const char *pkt, 133 | const UINT packetLen, 134 | const BOOL is_ipv6, 135 | const BYTE set_ttl, 136 | const BYTE set_checksum 137 | ) { 138 | return send_fake_data(w_filter, 139 | addr, 140 | pkt, 141 | packetLen, 142 | is_ipv6, 143 | FALSE, 144 | set_ttl, 145 | set_checksum 146 | ); 147 | } 148 | 149 | int send_fake_https_request(const HANDLE w_filter, 150 | const PWINDIVERT_ADDRESS addr, 151 | const char *pkt, 152 | const UINT packetLen, 153 | const BOOL is_ipv6, 154 | const BYTE set_ttl, 155 | const BYTE set_checksum 156 | ) { 157 | return send_fake_data(w_filter, 158 | addr, 159 | pkt, 160 | packetLen, 161 | is_ipv6, 162 | TRUE, 163 | set_ttl, 164 | set_checksum 165 | ); 166 | } 167 | -------------------------------------------------------------------------------- /src/dnsredir.c: -------------------------------------------------------------------------------- 1 | /* 2 | * DNS UDP Connection Tracker for GoodbyeDPI 3 | * 4 | * This is a simple connection tracker for DNS UDP data. 5 | * It's not a proper one. The caveats as follows: 6 | * * Uses only source IP address and port as a hash key; 7 | * * One-shot only. Removes conntrack record as soon as gets the reply; 8 | * * Does not properly parse DNS request and response, only checks some bytes; 9 | * 10 | * But anyway, it works fine for DNS. 11 | */ 12 | 13 | #include 14 | #include 15 | #include 16 | #include "goodbyedpi.h" 17 | #include "dnsredir.h" 18 | #include "utils/uthash.h" 19 | 20 | /* key ('4' for IPv4 or '6' for IPv6 + srcip[16] + srcport[2]) */ 21 | #define UDP_CONNRECORD_KEY_LEN 19 22 | 23 | #define DNS_CLEANUP_INTERVAL_SEC 30 24 | 25 | /* HACK! 26 | * uthash uses strlen() for HASH_FIND_STR. 27 | * We have null bytes in our key, so we can't use strlen() 28 | * And since it's always UDP_CONNRECORD_KEY_LEN bytes long, 29 | * we don't need to use any string function to determine length. 30 | */ 31 | #undef uthash_strlen 32 | #define uthash_strlen(s) UDP_CONNRECORD_KEY_LEN 33 | 34 | typedef struct udp_connrecord { 35 | /* key ('4' for IPv4 or '6' for IPv6 + srcip[16] + srcport[2]) */ 36 | char key[UDP_CONNRECORD_KEY_LEN]; 37 | time_t time; /* time when this record was added */ 38 | uint32_t dstip[4]; 39 | uint16_t dstport; 40 | UT_hash_handle hh; /* makes this structure hashable */ 41 | } udp_connrecord_t; 42 | 43 | static time_t last_cleanup = 0; 44 | static udp_connrecord_t *conntrack = NULL; 45 | 46 | void flush_dns_cache() { 47 | BOOL WINAPI (*DnsFlushResolverCache)(); 48 | 49 | HMODULE dnsapi = LoadLibrary("dnsapi.dll"); 50 | if (dnsapi == NULL) 51 | { 52 | printf("Can't load dnsapi.dll to flush DNS cache!\n"); 53 | exit(EXIT_FAILURE); 54 | } 55 | 56 | DnsFlushResolverCache = (void*)GetProcAddress(dnsapi, "DnsFlushResolverCache"); 57 | if (DnsFlushResolverCache == NULL || !DnsFlushResolverCache()) 58 | printf("Can't flush DNS cache!"); 59 | FreeLibrary(dnsapi); 60 | } 61 | 62 | inline static void fill_key_data(char *key, const uint8_t is_ipv6, const uint32_t srcip[4], 63 | const uint16_t srcport) 64 | { 65 | if (is_ipv6) { 66 | *(uint8_t*)(key) = '6'; 67 | ipv6_copy_addr((uint32_t*)(key + sizeof(uint8_t)), srcip); 68 | } 69 | else { 70 | *(uint8_t*)(key) = '4'; 71 | ipv4_copy_addr((uint32_t*)(key + sizeof(uint8_t)), srcip); 72 | } 73 | 74 | *(uint16_t*)(key + sizeof(uint8_t) + sizeof(uint32_t) * 4) = srcport; 75 | } 76 | 77 | inline static void fill_data_from_key(uint8_t *is_ipv6, uint32_t srcip[4], uint16_t *srcport, 78 | const char *key) 79 | { 80 | if (key[0] == '6') { 81 | *is_ipv6 = 1; 82 | ipv6_copy_addr(srcip, (uint32_t*)(key + sizeof(uint8_t))); 83 | } 84 | else { 85 | *is_ipv6 = 0; 86 | ipv4_copy_addr(srcip, (uint32_t*)(key + sizeof(uint8_t))); 87 | } 88 | *srcport = *(uint16_t*)(key + sizeof(uint8_t) + sizeof(uint32_t) * 4); 89 | } 90 | 91 | inline static void construct_key(const uint32_t srcip[4], const uint16_t srcport, 92 | char *key, const uint8_t is_ipv6) 93 | { 94 | debug("Construct key enter\n"); 95 | if (key) { 96 | debug("Constructing key\n"); 97 | fill_key_data(key, is_ipv6, srcip, srcport); 98 | } 99 | debug("Construct key end\n"); 100 | } 101 | 102 | inline static void deconstruct_key(const char *key, const udp_connrecord_t *connrecord, 103 | conntrack_info_t *conn_info) 104 | { 105 | debug("Deconstruct key enter\n"); 106 | if (key && conn_info) { 107 | debug("Deconstructing key\n"); 108 | fill_data_from_key(&conn_info->is_ipv6, conn_info->srcip, 109 | &conn_info->srcport, key); 110 | 111 | if (conn_info->is_ipv6) 112 | ipv6_copy_addr(conn_info->dstip, connrecord->dstip); 113 | else 114 | ipv4_copy_addr(conn_info->dstip, connrecord->dstip); 115 | 116 | conn_info->dstport = connrecord->dstport; 117 | } 118 | debug("Deconstruct key end\n"); 119 | } 120 | 121 | static int check_get_udp_conntrack_key(const char *key, udp_connrecord_t **connrecord) { 122 | udp_connrecord_t *tmp_connrecord = NULL; 123 | if (!conntrack) return FALSE; 124 | 125 | HASH_FIND_STR(conntrack, key, tmp_connrecord); 126 | if (tmp_connrecord) { 127 | if (connrecord) 128 | *connrecord = tmp_connrecord; 129 | debug("check_get_udp_conntrack_key found key\n"); 130 | return TRUE; 131 | } 132 | debug("check_get_udp_conntrack_key key not found\n"); 133 | return FALSE; 134 | } 135 | 136 | static int add_udp_conntrack(const uint32_t srcip[4], const uint16_t srcport, 137 | const uint32_t dstip[4], const uint16_t dstport, 138 | const uint8_t is_ipv6 139 | ) 140 | { 141 | if (!(srcip && srcport && dstip && dstport)) 142 | return FALSE; 143 | 144 | udp_connrecord_t *tmp_connrecord = malloc(sizeof(udp_connrecord_t)); 145 | construct_key(srcip, srcport, tmp_connrecord->key, is_ipv6); 146 | 147 | if (!check_get_udp_conntrack_key(tmp_connrecord->key, NULL)) { 148 | tmp_connrecord->time = time(NULL); 149 | 150 | if (is_ipv6) { 151 | ipv6_copy_addr(tmp_connrecord->dstip, dstip); 152 | } 153 | else { 154 | ipv4_copy_addr(tmp_connrecord->dstip, dstip); 155 | } 156 | tmp_connrecord->dstport = dstport; 157 | HASH_ADD_STR(conntrack, key, tmp_connrecord); 158 | debug("Added UDP conntrack\n"); 159 | return TRUE; 160 | } 161 | debug("Not added UDP conntrack\n"); 162 | free(tmp_connrecord); 163 | return FALSE; 164 | } 165 | 166 | static void dns_cleanup() { 167 | udp_connrecord_t *tmp_connrecord, *tmp_connrecord2 = NULL; 168 | 169 | if (last_cleanup == 0) { 170 | last_cleanup = time(NULL); 171 | return; 172 | } 173 | 174 | if (difftime(time(NULL), last_cleanup) >= DNS_CLEANUP_INTERVAL_SEC) { 175 | last_cleanup = time(NULL); 176 | 177 | HASH_ITER(hh, conntrack, tmp_connrecord, tmp_connrecord2) { 178 | if (difftime(last_cleanup, tmp_connrecord->time) >= DNS_CLEANUP_INTERVAL_SEC) { 179 | HASH_DEL(conntrack, tmp_connrecord); 180 | free(tmp_connrecord); 181 | } 182 | } 183 | } 184 | } 185 | 186 | int dns_is_dns_packet(const char *packet_data, const UINT packet_dataLen, const int outgoing) { 187 | if (packet_dataLen < 16) return FALSE; 188 | 189 | if (outgoing && (ntohs(*(const uint16_t*)(packet_data + 2)) & 0xFA00) == 0 && 190 | (ntohs(*(const uint32_t*)(packet_data + 6))) == 0) { 191 | return TRUE; 192 | } 193 | else if (!outgoing && 194 | (ntohs(*(const uint16_t*)(packet_data + 2)) & 0xF800) == 0x8000) { 195 | return TRUE; 196 | } 197 | return FALSE; 198 | } 199 | 200 | int dns_handle_outgoing(const uint32_t srcip[4], const uint16_t srcport, 201 | const uint32_t dstip[4], const uint16_t dstport, 202 | const char *packet_data, const UINT packet_dataLen, 203 | const uint8_t is_ipv6) 204 | { 205 | if (packet_dataLen < 16) 206 | return FALSE; 207 | 208 | dns_cleanup(); 209 | 210 | if (dns_is_dns_packet(packet_data, packet_dataLen, 1)) { 211 | /* Looks like DNS request */ 212 | debug("trying to add srcport = %hu, dstport = %hu\n", ntohs(srcport), ntohs(dstport)); 213 | return add_udp_conntrack(srcip, srcport, dstip, dstport, is_ipv6); 214 | } 215 | debug("____dns_handle_outgoing FALSE: srcport = %hu, dstport = %hu\n", ntohs(srcport), ntohs(dstport)); 216 | return FALSE; 217 | } 218 | 219 | int dns_handle_incoming(const uint32_t srcip[4], const uint16_t srcport, 220 | const char *packet_data, const UINT packet_dataLen, 221 | conntrack_info_t *conn_info, const uint8_t is_ipv6) 222 | { 223 | char key[UDP_CONNRECORD_KEY_LEN]; 224 | udp_connrecord_t *tmp_connrecord = NULL; 225 | 226 | if (packet_dataLen < 16 || !conn_info) 227 | return FALSE; 228 | 229 | dns_cleanup(); 230 | 231 | if (dns_is_dns_packet(packet_data, packet_dataLen, 0)) { 232 | /* Looks like DNS response */ 233 | construct_key(srcip, srcport, key, is_ipv6); 234 | if (check_get_udp_conntrack_key(key, &tmp_connrecord) && tmp_connrecord) { 235 | /* Connection exists in conntrack, moving on */ 236 | deconstruct_key(key, tmp_connrecord, conn_info); 237 | HASH_DEL(conntrack, tmp_connrecord); 238 | free(tmp_connrecord); 239 | return TRUE; 240 | } 241 | } 242 | debug("____dns_handle_incoming FALSE: srcport = %hu\n", ntohs(srcport)); 243 | return FALSE; 244 | } 245 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/goodbyedpi.c: -------------------------------------------------------------------------------- 1 | /* 2 | * GoodbyeDPI — Passive DPI blocker and Active DPI circumvention utility. 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "windivert.h" 15 | #include "goodbyedpi.h" 16 | #include "utils/repl_str.h" 17 | #include "service.h" 18 | #include "dnsredir.h" 19 | #include "blackwhitelist.h" 20 | #include "fakepackets.h" 21 | 22 | // My mingw installation does not load inet_pton definition for some reason 23 | WINSOCK_API_LINKAGE INT WSAAPI inet_pton(INT Family, LPCSTR pStringBuf, PVOID pAddr); 24 | 25 | #define GOODBYEDPI_VERSION "v0.1.6" 26 | 27 | #define die() do { sleep(20); exit(EXIT_FAILURE); } while (0) 28 | 29 | #define MAX_FILTERS 4 30 | 31 | #define DIVERT_NO_LOCALNETSv4_DST "(" \ 32 | "(ip.DstAddr < 127.0.0.1 or ip.DstAddr > 127.255.255.255) and " \ 33 | "(ip.DstAddr < 10.0.0.0 or ip.DstAddr > 10.255.255.255) and " \ 34 | "(ip.DstAddr < 192.168.0.0 or ip.DstAddr > 192.168.255.255) and " \ 35 | "(ip.DstAddr < 172.16.0.0 or ip.DstAddr > 172.31.255.255) and " \ 36 | "(ip.DstAddr < 169.254.0.0 or ip.DstAddr > 169.254.255.255)" \ 37 | ")" 38 | #define DIVERT_NO_LOCALNETSv4_SRC "(" \ 39 | "(ip.SrcAddr < 127.0.0.1 or ip.SrcAddr > 127.255.255.255) and " \ 40 | "(ip.SrcAddr < 10.0.0.0 or ip.SrcAddr > 10.255.255.255) and " \ 41 | "(ip.SrcAddr < 192.168.0.0 or ip.SrcAddr > 192.168.255.255) and " \ 42 | "(ip.SrcAddr < 172.16.0.0 or ip.SrcAddr > 172.31.255.255) and " \ 43 | "(ip.SrcAddr < 169.254.0.0 or ip.SrcAddr > 169.254.255.255)" \ 44 | ")" 45 | 46 | #define DIVERT_NO_LOCALNETSv6_DST "(" \ 47 | "(ipv6.DstAddr > ::1) and " \ 48 | "(ipv6.DstAddr < 2001::0 or ipv6.DstAddr > 2001:1::0) and " \ 49 | "(ipv6.DstAddr < fc00::0 or ipv6.DstAddr > fe00::0) and " \ 50 | "(ipv6.DstAddr < fe80::0 or ipv6.DstAddr > fec0::0) and " \ 51 | "(ipv6.DstAddr < ff00::0 or ipv6.DstAddr > ffff::0)" \ 52 | ")" 53 | #define DIVERT_NO_LOCALNETSv6_SRC "(" \ 54 | "(ipv6.SrcAddr > ::1) and " \ 55 | "(ipv6.SrcAddr < 2001::0 or ipv6.SrcAddr > 2001:1::0) and " \ 56 | "(ipv6.SrcAddr < fc00::0 or ipv6.SrcAddr > fe00::0) and " \ 57 | "(ipv6.SrcAddr < fe80::0 or ipv6.SrcAddr > fec0::0) and " \ 58 | "(ipv6.SrcAddr < ff00::0 or ipv6.SrcAddr > ffff::0)" \ 59 | ")" 60 | 61 | /* #IPID# is a template to find&replace */ 62 | #define IPID_TEMPLATE "#IPID#" 63 | #define FILTER_STRING_TEMPLATE \ 64 | "(tcp and !impostor and !loopback and " \ 65 | "((inbound and (" \ 66 | "(" \ 67 | "(" \ 68 | "(ipv6 or (ip.Id >= 0x0 and ip.Id <= 0xF) " IPID_TEMPLATE \ 69 | ") and " \ 70 | "tcp.SrcPort == 80 and tcp.Ack" \ 71 | ") or " \ 72 | "((tcp.SrcPort == 80 or tcp.SrcPort == 443) and tcp.Ack and tcp.Syn)" \ 73 | ")" \ 74 | " and (" DIVERT_NO_LOCALNETSv4_SRC " or " DIVERT_NO_LOCALNETSv6_SRC "))) or " \ 75 | "(outbound and " \ 76 | "(tcp.DstPort == 80 or tcp.DstPort == 443) and tcp.Ack and " \ 77 | "(" DIVERT_NO_LOCALNETSv4_DST " or " DIVERT_NO_LOCALNETSv6_DST "))" \ 78 | "))" 79 | #define FILTER_PASSIVE_STRING_TEMPLATE "inbound and ip and tcp and " \ 80 | "!impostor and !loopback and " \ 81 | "((ip.Id <= 0xF and ip.Id >= 0x0) " IPID_TEMPLATE ") and " \ 82 | "(tcp.SrcPort == 443 or tcp.SrcPort == 80) and tcp.Rst and " \ 83 | DIVERT_NO_LOCALNETSv4_SRC 84 | 85 | #define SET_HTTP_FRAGMENT_SIZE_OPTION(fragment_size) do { \ 86 | if (!http_fragment_size) { \ 87 | http_fragment_size = (unsigned int)fragment_size; \ 88 | } \ 89 | else if (http_fragment_size != (unsigned int)fragment_size) { \ 90 | printf( \ 91 | "WARNING: HTTP fragment size is already set to %d, not changing.\n", \ 92 | http_fragment_size \ 93 | ); \ 94 | } \ 95 | } while (0) 96 | 97 | static int running_from_service = 0; 98 | static HANDLE filters[MAX_FILTERS]; 99 | static int filter_num = 0; 100 | static const char http10_redirect_302[] = "HTTP/1.0 302 "; 101 | static const char http11_redirect_302[] = "HTTP/1.1 302 "; 102 | static const char http_host_find[] = "\r\nHost: "; 103 | static const char http_host_replace[] = "\r\nhoSt: "; 104 | static const char http_useragent_find[] = "\r\nUser-Agent: "; 105 | static const char location_http[] = "\r\nLocation: http://"; 106 | static const char connection_close[] = "\r\nConnection: close"; 107 | static const char *http_methods[] = { 108 | "GET ", 109 | "HEAD ", 110 | "POST ", 111 | "PUT ", 112 | "DELETE ", 113 | "CONNECT ", 114 | "OPTIONS ", 115 | }; 116 | 117 | static struct option long_options[] = { 118 | {"port", required_argument, 0, 'z' }, 119 | {"dns-addr", required_argument, 0, 'd' }, 120 | {"dns-port", required_argument, 0, 'g' }, 121 | {"dnsv6-addr", required_argument, 0, '!' }, 122 | {"dnsv6-port", required_argument, 0, '@' }, 123 | {"dns-verb", no_argument, 0, 'v' }, 124 | {"blacklist", required_argument, 0, 'b' }, 125 | {"ip-id", required_argument, 0, 'i' }, 126 | {"set-ttl", required_argument, 0, '$' }, 127 | {"wrong-chksum",no_argument, 0, '%' }, 128 | {0, 0, 0, 0 } 129 | }; 130 | 131 | static char *filter_string = NULL; 132 | static char *filter_passive_string = NULL; 133 | 134 | static void add_filter_str(int proto, int port) { 135 | const char *udp = " or (udp and !impostor and !loopback and " \ 136 | "(udp.SrcPort == %d or udp.DstPort == %d))"; 137 | const char *tcp = " or (tcp and !impostor and !loopback and " \ 138 | "(tcp.SrcPort == %d or tcp.DstPort == %d))"; 139 | 140 | char *current_filter = filter_string; 141 | size_t new_filter_size = strlen(current_filter) + 142 | (proto == IPPROTO_UDP ? strlen(udp) : strlen(tcp)) + 16; 143 | char *new_filter = malloc(new_filter_size); 144 | 145 | strcpy(new_filter, current_filter); 146 | if (proto == IPPROTO_UDP) 147 | sprintf(&(new_filter[strlen(new_filter)]), udp, port, port); 148 | else 149 | sprintf(&(new_filter[strlen(new_filter)]), tcp, port, port); 150 | 151 | filter_string = new_filter; 152 | free(current_filter); 153 | } 154 | 155 | static void add_ip_id_str(int id) { 156 | char *newstr; 157 | const char *ipid = " or ip.Id == %d"; 158 | char *addfilter = malloc(strlen(ipid) + 16); 159 | 160 | sprintf(addfilter, ipid, id); 161 | 162 | newstr = repl_str(filter_string, IPID_TEMPLATE, addfilter); 163 | free(filter_string); 164 | filter_string = newstr; 165 | 166 | newstr = repl_str(filter_passive_string, IPID_TEMPLATE, addfilter); 167 | free(filter_passive_string); 168 | filter_passive_string = newstr; 169 | } 170 | 171 | static void finalize_filter_strings() { 172 | char *newstr; 173 | 174 | newstr = repl_str(filter_string, IPID_TEMPLATE, ""); 175 | free(filter_string); 176 | filter_string = newstr; 177 | 178 | newstr = repl_str(filter_passive_string, IPID_TEMPLATE, ""); 179 | free(filter_passive_string); 180 | filter_passive_string = newstr; 181 | } 182 | 183 | static char* dumb_memmem(const char* haystack, unsigned int hlen, 184 | const char* needle, size_t nlen) 185 | { 186 | // naive implementation 187 | if (nlen > hlen) return NULL; 188 | size_t i; 189 | for (i=0; i limitValue) { 204 | puts(msg); 205 | exit(EXIT_FAILURE); 206 | } 207 | return (unsigned short int)res; 208 | } 209 | 210 | BYTE atoub(const char *str, const char *msg) { 211 | long unsigned int res = strtoul(str, NULL, 10u); 212 | enum { 213 | limitValue=0xFFu 214 | }; 215 | 216 | if(res > limitValue) { 217 | puts(msg); 218 | exit(EXIT_FAILURE); 219 | } 220 | return (BYTE)res; 221 | } 222 | 223 | 224 | static HANDLE init(char *filter, UINT64 flags) { 225 | LPTSTR errormessage = NULL; 226 | DWORD errorcode = 0; 227 | filter = WinDivertOpen(filter, WINDIVERT_LAYER_NETWORK, 0, flags); 228 | if (filter != INVALID_HANDLE_VALUE) 229 | return filter; 230 | errorcode = GetLastError(); 231 | FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | 232 | FORMAT_MESSAGE_IGNORE_INSERTS, 233 | NULL, errorcode, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), 234 | (LPTSTR)&errormessage, 0, NULL); 235 | printf("Error opening filter: %s", errormessage); 236 | LocalFree(errormessage); 237 | if (errorcode == 577) 238 | printf("Windows Server 2016 systems must have secure boot disabled to be " 239 | "able to load WinDivert driver.\n" 240 | "Windows 7 systems must be up-to-date or at least have KB3033929 installed.\n" 241 | "https://www.microsoft.com/en-us/download/details.aspx?id=46078\n\n" 242 | "WARNING! If you see this error on Windows 7, it means your system is horribly " 243 | "outdated and SHOULD NOT BE USED TO ACCESS THE INTERNET!\n" 244 | "Most probably, you don't have security patches installed and anyone in you LAN or " 245 | "public Wi-Fi network can get full access to your computer (MS17-010 and others).\n" 246 | "You should install updates IMMEDIATELY.\n"); 247 | return NULL; 248 | } 249 | 250 | static int deinit(HANDLE handle) { 251 | if (handle) { 252 | WinDivertClose(handle); 253 | return TRUE; 254 | } 255 | return FALSE; 256 | } 257 | 258 | void deinit_all() { 259 | for (int i = 0; i < filter_num; i++) { 260 | deinit(filters[i]); 261 | } 262 | } 263 | 264 | static void sigint_handler(int sig __attribute__((unused))) { 265 | deinit_all(); 266 | exit(EXIT_SUCCESS); 267 | } 268 | 269 | static void mix_case(char *pktdata, unsigned int pktlen) { 270 | unsigned int i; 271 | 272 | if (pktlen <= 0) return; 273 | for (i = 0; i < pktlen; i++) { 274 | if (i % 2) { 275 | pktdata[i] = (char) toupper(pktdata[i]); 276 | } 277 | } 278 | } 279 | 280 | static int is_passivedpi_redirect(const char *pktdata, unsigned int pktlen) { 281 | /* First check if this is HTTP 302 redirect */ 282 | if (memcmp(pktdata, http11_redirect_302, sizeof(http11_redirect_302)-1) == 0 || 283 | memcmp(pktdata, http10_redirect_302, sizeof(http10_redirect_302)-1) == 0) 284 | { 285 | /* Then check if this is a redirect to new http site with Connection: close */ 286 | if (dumb_memmem(pktdata, pktlen, location_http, sizeof(location_http)-1) && 287 | dumb_memmem(pktdata, pktlen, connection_close, sizeof(connection_close)-1)) { 288 | return TRUE; 289 | } 290 | } 291 | return FALSE; 292 | } 293 | 294 | static int find_header_and_get_info(const char *pktdata, unsigned int pktlen, 295 | const char *hdrname, 296 | char **hdrnameaddr, 297 | char **hdrvalueaddr, unsigned int *hdrvaluelen) { 298 | char *data_addr_rn; 299 | char *hdr_begin; 300 | 301 | *hdrvaluelen = 0u; 302 | *hdrnameaddr = NULL; 303 | *hdrvalueaddr = NULL; 304 | 305 | /* Search for the header */ 306 | hdr_begin = dumb_memmem(pktdata, pktlen, 307 | hdrname, strlen(hdrname)); 308 | if (!hdr_begin) return FALSE; 309 | if ((PVOID)pktdata > (PVOID)hdr_begin) return FALSE; 310 | 311 | /* Set header address */ 312 | *hdrnameaddr = hdr_begin; 313 | *hdrvalueaddr = (PVOID)hdr_begin + strlen(hdrname); 314 | 315 | /* Search for header end (\r\n) */ 316 | data_addr_rn = dumb_memmem(*hdrvalueaddr, 317 | pktlen - ((PVOID)*hdrvalueaddr - (PVOID)pktdata), 318 | "\r\n", 2); 319 | if (data_addr_rn) { 320 | *hdrvaluelen = (PVOID)data_addr_rn - (PVOID)*hdrvalueaddr; 321 | if (*hdrvaluelen > 0u && *hdrvaluelen <= 512u) 322 | return TRUE; 323 | } 324 | return FALSE; 325 | } 326 | 327 | static inline void change_window_size(const PWINDIVERT_TCPHDR ppTcpHdr, unsigned int size) { 328 | if (size >= 1 && size <= 0xFFFFu) { 329 | ppTcpHdr->Window = htons((u_short)size); 330 | } 331 | } 332 | 333 | /* HTTP method end without trailing space */ 334 | static PVOID find_http_method_end(const char *pkt, unsigned int http_frag, int *is_fragmented) { 335 | unsigned int i; 336 | for (i = 0; i<(sizeof(http_methods) / sizeof(*http_methods)); i++) { 337 | if (memcmp(pkt, http_methods[i], strlen(http_methods[i])) == 0) { 338 | if (is_fragmented) 339 | *is_fragmented = 0; 340 | return (char*)pkt + strlen(http_methods[i]) - 1; 341 | } 342 | /* Try to find HTTP method in a second part of fragmented packet */ 343 | if ((http_frag == 1 || http_frag == 2) && 344 | memcmp(pkt, http_methods[i] + http_frag, 345 | strlen(http_methods[i]) - http_frag) == 0 346 | ) 347 | { 348 | if (is_fragmented) 349 | *is_fragmented = 1; 350 | return (char*)pkt + strlen(http_methods[i]) - http_frag - 1; 351 | } 352 | } 353 | return NULL; 354 | } 355 | 356 | int main(int argc, char *argv[]) { 357 | static enum packet_type_e { 358 | unknown, 359 | ipv4_tcp, ipv4_tcp_data, ipv4_udp_data, 360 | ipv6_tcp, ipv6_tcp_data, ipv6_udp_data 361 | } packet_type; 362 | int i, should_reinject, should_recalc_checksum = 0; 363 | int opt; 364 | int packet_v4, packet_v6; 365 | HANDLE w_filter = NULL; 366 | WINDIVERT_ADDRESS addr; 367 | char packet[MAX_PACKET_SIZE]; 368 | PVOID packet_data; 369 | UINT packetLen; 370 | UINT packet_dataLen; 371 | PWINDIVERT_IPHDR ppIpHdr; 372 | PWINDIVERT_IPV6HDR ppIpV6Hdr; 373 | PWINDIVERT_TCPHDR ppTcpHdr; 374 | PWINDIVERT_UDPHDR ppUdpHdr; 375 | conntrack_info_t dns_conn_info; 376 | 377 | int do_passivedpi = 0, do_fragment_http = 0, 378 | do_fragment_http_persistent = 0, 379 | do_fragment_http_persistent_nowait = 0, 380 | do_fragment_https = 0, do_host = 0, 381 | do_host_removespace = 0, do_additional_space = 0, 382 | do_http_allports = 0, 383 | do_host_mixedcase = 0, 384 | do_dnsv4_redirect = 0, do_dnsv6_redirect = 0, 385 | do_dns_verb = 0, do_blacklist = 0, 386 | do_wrong_chksum = 0; 387 | unsigned int http_fragment_size = 0; 388 | unsigned int https_fragment_size = 0; 389 | BYTE ttl_of_fake_packet = 0; 390 | uint32_t dnsv4_addr = 0; 391 | struct in6_addr dnsv6_addr = {0}; 392 | struct in6_addr dns_temp_addr = {0}; 393 | uint16_t dnsv4_port = htons(53); 394 | uint16_t dnsv6_port = htons(53); 395 | char *host_addr, *useragent_addr, *method_addr; 396 | unsigned int host_len, useragent_len; 397 | int http_req_fragmented; 398 | 399 | char *hdr_name_addr = NULL, *hdr_value_addr = NULL; 400 | unsigned int hdr_value_len; 401 | 402 | // Make sure to search DLLs only in safe path, not in current working dir. 403 | SetDllDirectory(""); 404 | SetSearchPathMode(BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT); 405 | 406 | if (!running_from_service) { 407 | running_from_service = 1; 408 | if (service_register(argc, argv)) { 409 | /* We've been called as a service. Register service 410 | * and exit this thread. main() would be called from 411 | * service.c next time. 412 | * 413 | * Note that if service_register() succeedes it does 414 | * not return until the service is stopped. 415 | * That is why we should set running_from_service 416 | * before calling service_register and unset it 417 | * afterwards. 418 | */ 419 | return 0; 420 | } 421 | running_from_service = 0; 422 | } 423 | 424 | if (filter_string == NULL) 425 | filter_string = strdup(FILTER_STRING_TEMPLATE); 426 | if (filter_passive_string == NULL) 427 | filter_passive_string = strdup(FILTER_PASSIVE_STRING_TEMPLATE); 428 | 429 | printf( 430 | "GoodbyeDPI " GOODBYEDPI_VERSION 431 | ": Passive DPI blocker and Active DPI circumvention utility\n" 432 | "https://github.com/ValdikSS/GoodbyeDPI\n\n" 433 | ); 434 | 435 | if (argc == 1) { 436 | /* enable mode -1 by default */ 437 | http_fragment_size = https_fragment_size = 2; 438 | do_passivedpi = do_host = do_host_removespace \ 439 | = do_fragment_http = do_fragment_https \ 440 | = do_fragment_http_persistent \ 441 | = do_fragment_http_persistent_nowait = 1; 442 | } 443 | 444 | while ((opt = getopt_long(argc, argv, "1234prsaf:e:mwk:n", long_options, NULL)) != -1) { 445 | switch (opt) { 446 | case '1': 447 | do_passivedpi = do_host = do_host_removespace \ 448 | = do_fragment_http = do_fragment_https \ 449 | = do_fragment_http_persistent \ 450 | = do_fragment_http_persistent_nowait = 1; 451 | break; 452 | case '2': 453 | do_passivedpi = do_host = do_host_removespace \ 454 | = do_fragment_http = do_fragment_https \ 455 | = do_fragment_http_persistent \ 456 | = do_fragment_http_persistent_nowait = 1; 457 | https_fragment_size = 40u; 458 | break; 459 | case '3': 460 | do_passivedpi = do_host = do_host_removespace \ 461 | = do_fragment_https = 1; 462 | https_fragment_size = 40u; 463 | break; 464 | case '4': 465 | do_passivedpi = do_host = do_host_removespace = 1; 466 | break; 467 | case 'p': 468 | do_passivedpi = 1; 469 | break; 470 | case 'r': 471 | do_host = 1; 472 | break; 473 | case 's': 474 | do_host_removespace = 1; 475 | break; 476 | case 'a': 477 | do_additional_space = 1; 478 | do_host_removespace = 1; 479 | break; 480 | case 'm': 481 | do_host_mixedcase = 1; 482 | break; 483 | case 'f': 484 | do_fragment_http = 1; 485 | SET_HTTP_FRAGMENT_SIZE_OPTION(atousi(optarg, "Fragment size should be in range [0 - 0xFFFF]\n")); 486 | break; 487 | case 'k': 488 | do_fragment_http_persistent = 1; 489 | SET_HTTP_FRAGMENT_SIZE_OPTION(atousi(optarg, "Fragment size should be in range [0 - 0xFFFF]\n")); 490 | break; 491 | case 'n': 492 | do_fragment_http_persistent_nowait = 1; 493 | break; 494 | case 'e': 495 | do_fragment_https = 1; 496 | https_fragment_size = atousi(optarg, "Fragment size should be in range [0 - 65535]\n"); 497 | break; 498 | case 'w': 499 | do_http_allports = 1; 500 | break; 501 | case 'z': 502 | /* i is used as a temporary variable here */ 503 | i = atoi(optarg); 504 | if (i <= 0 || i > 65535) { 505 | printf("Port parameter error!\n"); 506 | exit(EXIT_FAILURE); 507 | } 508 | if (i != 80 && i != 443) 509 | add_filter_str(IPPROTO_TCP, i); 510 | i = 0; 511 | break; 512 | case 'i': 513 | /* i is used as a temporary variable here */ 514 | i = atousi(optarg, "IP ID parameter error!\n"); 515 | add_ip_id_str(i); 516 | i = 0; 517 | break; 518 | case 'd': 519 | if ((inet_pton(AF_INET, optarg, dns_temp_addr.s6_addr) == 1) && 520 | !do_dnsv4_redirect) 521 | { 522 | do_dnsv4_redirect = 1; 523 | if (inet_pton(AF_INET, optarg, &dnsv4_addr) != 1) { 524 | puts("DNS address parameter error!"); 525 | exit(EXIT_FAILURE); 526 | } 527 | add_filter_str(IPPROTO_UDP, 53); 528 | flush_dns_cache(); 529 | break; 530 | } 531 | puts("DNS address parameter error!"); 532 | exit(EXIT_FAILURE); 533 | break; 534 | case '!': 535 | if ((inet_pton(AF_INET6, optarg, dns_temp_addr.s6_addr) == 1) && 536 | !do_dnsv6_redirect) 537 | { 538 | do_dnsv6_redirect = 1; 539 | if (inet_pton(AF_INET6, optarg, dnsv6_addr.s6_addr) != 1) { 540 | puts("DNS address parameter error!"); 541 | exit(EXIT_FAILURE); 542 | } 543 | add_filter_str(IPPROTO_UDP, 53); 544 | flush_dns_cache(); 545 | break; 546 | } 547 | puts("DNS address parameter error!"); 548 | exit(EXIT_FAILURE); 549 | break; 550 | case 'g': 551 | if (!do_dnsv4_redirect) { 552 | puts("--dns-port should be used with --dns-addr!\n" 553 | "Make sure you use --dns-addr and pass it before " 554 | "--dns-port"); 555 | exit(EXIT_FAILURE); 556 | } 557 | dnsv4_port = atousi(optarg, "DNS port parameter error!"); 558 | if (dnsv4_port != 53) { 559 | add_filter_str(IPPROTO_UDP, dnsv4_port); 560 | } 561 | dnsv4_port = htons(dnsv4_port); 562 | break; 563 | case '@': 564 | if (!do_dnsv6_redirect) { 565 | puts("--dnsv6-port should be used with --dnsv6-addr!\n" 566 | "Make sure you use --dnsv6-addr and pass it before " 567 | "--dnsv6-port"); 568 | exit(EXIT_FAILURE); 569 | } 570 | dnsv6_port = atousi(optarg, "DNS port parameter error!"); 571 | if (dnsv6_port != 53) { 572 | add_filter_str(IPPROTO_UDP, dnsv6_port); 573 | } 574 | dnsv6_port = htons(dnsv6_port); 575 | break; 576 | case 'v': 577 | do_dns_verb = 1; 578 | break; 579 | case 'b': 580 | do_blacklist = 1; 581 | if (!blackwhitelist_load_list(optarg)) { 582 | printf("Can't load blacklist from file!\n"); 583 | exit(EXIT_FAILURE); 584 | } 585 | break; 586 | case '$': 587 | ttl_of_fake_packet = atoub(optarg, "Set TTL parameter error!"); 588 | break; 589 | case '%': 590 | do_wrong_chksum = 1; 591 | break; 592 | default: 593 | puts("Usage: goodbyedpi.exe [OPTION...]\n" 594 | " -p block passive DPI\n" 595 | " -r replace Host with hoSt\n" 596 | " -s remove space between host header and its value\n" 597 | " -a additional space between Method and Request-URI (enables -s, may break sites)\n" 598 | " -m mix Host header case (test.com -> tEsT.cOm)\n" 599 | " -f [value] set HTTP fragmentation to value\n" 600 | " -k [value] enable HTTP persistent (keep-alive) fragmentation and set it to value\n" 601 | " -n do not wait for first segment ACK when -k is enabled\n" 602 | " -e [value] set HTTPS fragmentation to value\n" 603 | " -w try to find and parse HTTP traffic on all processed ports (not only on port 80)\n" 604 | " --port [value] additional TCP port to perform fragmentation on (and HTTP tricks with -w)\n" 605 | " --ip-id [value] handle additional IP ID (decimal, drop redirects and TCP RSTs with this ID).\n" 606 | " --dns-addr [value] redirect UDPv4 DNS requests to the supplied IPv4 address (experimental)\n" 607 | " --dns-port [value] redirect UDPv4 DNS requests to the supplied port (53 by default)\n" 608 | " --dnsv6-addr [value] redirect UDPv6 DNS requests to the supplied IPv6 address (experimental)\n" 609 | " --dnsv6-port [value] redirect UDPv6 DNS requests to the supplied port (53 by default)\n" 610 | " --dns-verb print verbose DNS redirection messages\n" 611 | " --blacklist [txtfile] perform HTTP tricks only to host names and subdomains from\n" 612 | " supplied text file. This option can be supplied multiple times.\n" 613 | " --set-ttl [value] activate Fake Request Mode and send it with supplied TTL value.\n" 614 | " DANGEROUS! May break websites in unexpected ways. Use with care.\n" 615 | " Could be combined with --wrong-chksum.\n" 616 | " --wrong-chksum activate Fake Request Mode and send it with incorrect TCP checksum.\n" 617 | " May not work in a VM or with some routers, but is safer than set-ttl.\n" 618 | " Could be combined with --set-ttl\n." 619 | "\n" 620 | " -1 -p -r -s -f 2 -k 2 -n -e 2 (most compatible mode, default)\n" 621 | " -2 -p -r -s -f 2 -k 2 -n -e 40 (better speed for HTTPS yet still compatible)\n" 622 | " -3 -p -r -s -e 40 (better speed for HTTP and HTTPS)\n" 623 | " -4 -p -r -s (best speed)"); 624 | exit(EXIT_FAILURE); 625 | } 626 | } 627 | 628 | if (!http_fragment_size) 629 | http_fragment_size = 2; 630 | if (!https_fragment_size) 631 | https_fragment_size = 2; 632 | 633 | printf("Block passive: %d\nFragment HTTP: %d\nFragment persistent HTTP: %d\n" 634 | "Fragment HTTPS: %d\nhoSt: %d\nHost no space: %d\nAdditional space: %d\n" 635 | "Mix Host: %d\nHTTP AllPorts: %d\nHTTP Persistent Nowait: %d\n" 636 | "DNS redirect: %d\nDNSv6 redirect: %d\n" 637 | "Fake requests, TTL: %hu\nFake requests, wrong checksum: %d\n", 638 | do_passivedpi, (do_fragment_http ? http_fragment_size : 0), 639 | (do_fragment_http_persistent ? http_fragment_size : 0), 640 | (do_fragment_https ? https_fragment_size : 0), 641 | do_host, do_host_removespace, do_additional_space, do_host_mixedcase, 642 | do_http_allports, do_fragment_http_persistent_nowait, do_dnsv4_redirect, 643 | do_dnsv6_redirect, ttl_of_fake_packet, do_wrong_chksum 644 | ); 645 | 646 | if (do_fragment_http && http_fragment_size > 2) { 647 | printf("WARNING: HTTP fragmentation values > 2 are not fully compatible " 648 | "with other options. Please use values <= 2 or disable HTTP fragmentation " 649 | "completely.\n"); 650 | } 651 | 652 | printf("\nOpening filter\n"); 653 | finalize_filter_strings(); 654 | filter_num = 0; 655 | 656 | if (do_passivedpi) { 657 | /* IPv4 only filter for inbound RST packets with ID [0x0; 0xF] */ 658 | filters[filter_num] = init( 659 | filter_passive_string, 660 | WINDIVERT_FLAG_DROP); 661 | if (filters[filter_num] == NULL) 662 | die(); 663 | filter_num++; 664 | } 665 | 666 | /* 667 | * IPv4 & IPv6 filter for inbound HTTP redirection packets and 668 | * active DPI circumvention 669 | */ 670 | filters[filter_num] = init(filter_string, 0); 671 | 672 | w_filter = filters[filter_num]; 673 | filter_num++; 674 | 675 | for (i = 0; i < filter_num; i++) { 676 | if (filters[i] == NULL) 677 | die(); 678 | } 679 | 680 | printf("Filter activated!\n"); 681 | signal(SIGINT, sigint_handler); 682 | 683 | while (1) { 684 | if (WinDivertRecv(w_filter, packet, sizeof(packet), &addr, &packetLen)) { 685 | debug("Got %s packet, len=%d!\n", addr.Direction ? "inbound" : "outbound", 686 | packetLen); 687 | should_reinject = 1; 688 | should_recalc_checksum = 0; 689 | 690 | ppIpHdr = (PWINDIVERT_IPHDR)NULL; 691 | ppIpV6Hdr = (PWINDIVERT_IPV6HDR)NULL; 692 | ppTcpHdr = (PWINDIVERT_TCPHDR)NULL; 693 | ppUdpHdr = (PWINDIVERT_UDPHDR)NULL; 694 | packet_v4 = packet_v6 = 0; 695 | packet_type = unknown; 696 | 697 | // Parse network packet and set it's type 698 | if ((packet_v4 = WinDivertHelperParsePacket(packet, packetLen, &ppIpHdr, 699 | NULL, NULL, NULL, &ppTcpHdr, NULL, &packet_data, &packet_dataLen))) 700 | { 701 | packet_type = ipv4_tcp_data; 702 | } 703 | else if ((packet_v6 = WinDivertHelperParsePacket(packet, packetLen, NULL, 704 | &ppIpV6Hdr, NULL, NULL, &ppTcpHdr, NULL, &packet_data, &packet_dataLen))) 705 | { 706 | packet_type = ipv6_tcp_data; 707 | } 708 | else if ((packet_v4 = WinDivertHelperParsePacket(packet, packetLen, &ppIpHdr, 709 | NULL, NULL, NULL, &ppTcpHdr, NULL, NULL, NULL))) 710 | { 711 | packet_type = ipv4_tcp; 712 | } 713 | else if ((packet_v6 = WinDivertHelperParsePacket(packet, packetLen, NULL, 714 | &ppIpV6Hdr, NULL, NULL, &ppTcpHdr, NULL, NULL, NULL))) 715 | { 716 | packet_type = ipv6_tcp; 717 | } 718 | else if ((packet_v4 = WinDivertHelperParsePacket(packet, packetLen, &ppIpHdr, 719 | NULL, NULL, NULL, NULL, &ppUdpHdr, &packet_data, &packet_dataLen))) 720 | { 721 | packet_type = ipv4_udp_data; 722 | } 723 | else if ((packet_v6 = WinDivertHelperParsePacket(packet, packetLen, NULL, 724 | &ppIpV6Hdr, NULL, NULL, NULL, &ppUdpHdr, &packet_data, &packet_dataLen))) 725 | { 726 | packet_type = ipv6_udp_data; 727 | } 728 | 729 | debug("packet_type: %d, packet_v4: %d, packet_v6: %d\n", packet_type, packet_v4, packet_v6); 730 | 731 | if (packet_type == ipv4_tcp_data || packet_type == ipv6_tcp_data) { 732 | //printf("Got parsed packet, len=%d!\n", packet_dataLen); 733 | /* Got a TCP packet WITH DATA */ 734 | 735 | /* Handle INBOUND packet with data and find HTTP REDIRECT in there */ 736 | if (addr.Direction == WINDIVERT_DIRECTION_INBOUND && packet_dataLen > 16) { 737 | /* If INBOUND packet with DATA (tcp.Ack) */ 738 | 739 | /* Drop packets from filter with HTTP 30x Redirect */ 740 | if (do_passivedpi && is_passivedpi_redirect(packet_data, packet_dataLen)) { 741 | if (packet_v4) { 742 | //printf("Dropping HTTP Redirect packet!\n"); 743 | should_reinject = 0; 744 | } 745 | else if (packet_v6 && WINDIVERT_IPV6HDR_GET_FLOWLABEL(ppIpV6Hdr) == 0x0) { 746 | /* Contrary to IPv4 where we get only packets with IP ID 0x0-0xF, 747 | * for IPv6 we got all the incoming data packets since we can't 748 | * filter them in a driver. 749 | * 750 | * Handle only IPv6 Flow Label == 0x0 for now 751 | */ 752 | //printf("Dropping HTTP Redirect packet!\n"); 753 | should_reinject = 0; 754 | } 755 | } 756 | } 757 | /* Handle OUTBOUND packet on port 443, search for something that resembles 758 | * TLS handshake, send fake request. 759 | */ 760 | else if (addr.Direction == WINDIVERT_DIRECTION_OUTBOUND && 761 | ((do_fragment_https ? packet_dataLen == https_fragment_size : 0) || 762 | packet_dataLen > 16) && 763 | ppTcpHdr->DstPort != htons(80) && 764 | (ttl_of_fake_packet || do_wrong_chksum) 765 | ) 766 | { 767 | if (packet_dataLen >=2 && memcmp(packet_data, "\x16\x03", 2) == 0) { 768 | send_fake_https_request(w_filter, &addr, packet, packetLen, packet_v6, 769 | ttl_of_fake_packet, do_wrong_chksum); 770 | } 771 | } 772 | /* Handle OUTBOUND packet on port 80, search for Host header */ 773 | else if (addr.Direction == WINDIVERT_DIRECTION_OUTBOUND && 774 | packet_dataLen > 16 && 775 | (do_http_allports ? 1 : (ppTcpHdr->DstPort == htons(80))) && 776 | find_http_method_end(packet_data, 777 | (do_fragment_http ? http_fragment_size : 0u), 778 | &http_req_fragmented) && 779 | (do_host || do_host_removespace || 780 | do_host_mixedcase || do_fragment_http_persistent)) 781 | { 782 | 783 | /* Find Host header */ 784 | if (find_header_and_get_info(packet_data, packet_dataLen, 785 | http_host_find, &hdr_name_addr, &hdr_value_addr, &hdr_value_len) && 786 | hdr_value_len > 0 && hdr_value_len <= HOST_MAXLEN && 787 | (do_blacklist ? blackwhitelist_check_hostname(hdr_value_addr, hdr_value_len) : 1)) 788 | { 789 | host_addr = hdr_value_addr; 790 | host_len = hdr_value_len; 791 | 792 | if (ttl_of_fake_packet || do_wrong_chksum) 793 | send_fake_http_request(w_filter, &addr, packet, packetLen, packet_v6, 794 | ttl_of_fake_packet, do_wrong_chksum); 795 | 796 | 797 | /* 798 | * Handle new HTTP request in new 799 | * connection (when Window Size modification disabled) 800 | * or already established connection (keep-alive). 801 | * We split HTTP request into two packets: one of http_fragment_size length 802 | * and another of original_size - http_fragment_size length. 803 | * 804 | * The second packet of a splitted part is not really needed to be sent 805 | * as Windows understand that is hasn't been sent by checking 806 | * ack number of received packet and retransmitting missing part again, 807 | * but it's better to send it anyway since it eliminates one RTT. 808 | */ 809 | if (do_fragment_http_persistent && !http_req_fragmented && 810 | (packet_dataLen > http_fragment_size)) 811 | { 812 | if (packet_v4) 813 | ppIpHdr->Length = htons( 814 | ntohs(ppIpHdr->Length) - 815 | packet_dataLen + http_fragment_size 816 | ); 817 | else if (packet_v6) 818 | ppIpV6Hdr->Length = htons( 819 | ntohs(ppIpV6Hdr->Length) - 820 | packet_dataLen + http_fragment_size 821 | ); 822 | 823 | WinDivertHelperCalcChecksums( 824 | packet, packetLen - packet_dataLen + http_fragment_size, &addr, 0 825 | ); 826 | WinDivertSend( 827 | w_filter, packet, 828 | packetLen - packet_dataLen + http_fragment_size, 829 | &addr, NULL 830 | ); 831 | 832 | if (do_fragment_http_persistent_nowait) { 833 | if (packet_v4) 834 | ppIpHdr->Length = htons( 835 | ntohs(ppIpHdr->Length) - 836 | http_fragment_size + packet_dataLen - http_fragment_size 837 | ); 838 | else if (packet_v6) 839 | ppIpV6Hdr->Length = htons( 840 | ntohs(ppIpV6Hdr->Length) - 841 | http_fragment_size + packet_dataLen - http_fragment_size 842 | ); 843 | memmove(packet_data, 844 | packet_data + http_fragment_size, 845 | packet_dataLen); 846 | packet_dataLen -= http_fragment_size; 847 | packetLen -= http_fragment_size; 848 | hdr_value_addr -= http_fragment_size; 849 | hdr_name_addr -= http_fragment_size; 850 | host_addr = hdr_value_addr; 851 | 852 | ppTcpHdr->SeqNum = htonl(ntohl(ppTcpHdr->SeqNum) + http_fragment_size); 853 | should_recalc_checksum = 1; 854 | } 855 | else { 856 | continue; 857 | } 858 | } 859 | 860 | if (do_host_mixedcase) { 861 | mix_case(host_addr, host_len); 862 | should_recalc_checksum = 1; 863 | } 864 | 865 | if (do_host) { 866 | /* Replace "Host: " with "hoSt: " */ 867 | memcpy(hdr_name_addr, http_host_replace, strlen(http_host_replace)); 868 | should_recalc_checksum = 1; 869 | //printf("Replaced Host header!\n"); 870 | } 871 | 872 | /* If removing space between host header and its value 873 | * and adding additional space between Method and Request-URI */ 874 | if (do_additional_space && do_host_removespace) { 875 | /* End of "Host:" without trailing space */ 876 | method_addr = find_http_method_end(packet_data, 877 | (do_fragment_http ? http_fragment_size : 0), 878 | NULL); 879 | 880 | if (method_addr) { 881 | memmove(method_addr + 1, method_addr, 882 | (PVOID)host_addr - (PVOID)method_addr - 1); 883 | should_recalc_checksum = 1; 884 | } 885 | } 886 | /* If just removing space between host header and its value */ 887 | else if (do_host_removespace) { 888 | if (find_header_and_get_info(packet_data, packet_dataLen, 889 | http_useragent_find, &hdr_name_addr, 890 | &hdr_value_addr, &hdr_value_len)) 891 | { 892 | useragent_addr = hdr_value_addr; 893 | useragent_len = hdr_value_len; 894 | 895 | /* We move Host header value by one byte to the left and then 896 | * "insert" stolen space to the end of User-Agent value because 897 | * some web servers are not tolerant to additional space in the 898 | * end of Host header. 899 | * 900 | * Nothing is done if User-Agent header is missing. 901 | */ 902 | if (useragent_addr && useragent_len > 0) { 903 | /* useragent_addr is in the beginning of User-Agent value */ 904 | 905 | if (useragent_addr > host_addr) { 906 | /* Move one byte to the LEFT from "Host:" 907 | * to the end of User-Agent 908 | */ 909 | memmove(host_addr - 1, host_addr, 910 | (PVOID)useragent_addr + useragent_len - (PVOID)host_addr); 911 | host_addr -= 1; 912 | /* Put space in the end of User-Agent header */ 913 | *(char*)((PVOID)useragent_addr + useragent_len - 1) = ' '; 914 | should_recalc_checksum = 1; 915 | //printf("Replaced Host header!\n"); 916 | } 917 | else { 918 | /* User-Agent goes BEFORE Host header */ 919 | 920 | /* Move one byte to the RIGHT from the end of User-Agent 921 | * to the "Host:" 922 | */ 923 | memmove((PVOID)useragent_addr + useragent_len + 1, 924 | (PVOID)useragent_addr + useragent_len, 925 | (PVOID)host_addr - 1 - ((PVOID)useragent_addr + useragent_len)); 926 | /* Put space in the end of User-Agent header */ 927 | *(char*)((PVOID)useragent_addr + useragent_len) = ' '; 928 | should_recalc_checksum = 1; 929 | //printf("Replaced Host header!\n"); 930 | } 931 | } /* if (host_len <= HOST_MAXLEN && useragent_addr) */ 932 | } /* if (find_header_and_get_info http_useragent) */ 933 | } /* else if (do_host_removespace) */ 934 | } /* if (find_header_and_get_info http_host) */ 935 | } /* Handle OUTBOUND packet with data */ 936 | } /* Handle TCP packet with data */ 937 | 938 | /* Else if we got TCP packet without data */ 939 | else if (packet_type == ipv4_tcp || packet_type == ipv6_tcp) { 940 | /* If we got INBOUND SYN+ACK packet */ 941 | if (addr.Direction == WINDIVERT_DIRECTION_INBOUND && 942 | ppTcpHdr->Syn == 1 && ppTcpHdr->Ack == 1) { 943 | //printf("Changing Window Size!\n"); 944 | /* 945 | * Window Size is changed even if do_fragment_http_persistent 946 | * is enabled as there could be non-HTTP data on port 80 947 | */ 948 | if (do_fragment_http && ppTcpHdr->SrcPort == htons(80)) { 949 | change_window_size(ppTcpHdr, http_fragment_size); 950 | should_recalc_checksum = 1; 951 | } 952 | else if (do_fragment_https && ppTcpHdr->SrcPort != htons(80)) { 953 | change_window_size(ppTcpHdr, https_fragment_size); 954 | should_recalc_checksum = 1; 955 | } 956 | } 957 | } 958 | 959 | /* Else if we got UDP packet with data */ 960 | else if ((do_dnsv4_redirect && (packet_type == ipv4_udp_data)) || 961 | (do_dnsv6_redirect && (packet_type == ipv6_udp_data))) 962 | { 963 | if (addr.Direction == WINDIVERT_DIRECTION_INBOUND) { 964 | if ((packet_v4 && dns_handle_incoming(&ppIpHdr->DstAddr, ppUdpHdr->DstPort, 965 | packet_data, packet_dataLen, 966 | &dns_conn_info, 0)) 967 | || 968 | (packet_v6 && dns_handle_incoming(ppIpV6Hdr->DstAddr, ppUdpHdr->DstPort, 969 | packet_data, packet_dataLen, 970 | &dns_conn_info, 1))) 971 | { 972 | /* Changing source IP and port to the values 973 | * from DNS conntrack */ 974 | if (packet_v4) 975 | ppIpHdr->SrcAddr = dns_conn_info.dstip[0]; 976 | else if (packet_v6) 977 | ipv6_copy_addr(ppIpV6Hdr->SrcAddr, dns_conn_info.dstip); 978 | ppUdpHdr->DstPort = dns_conn_info.srcport; 979 | ppUdpHdr->SrcPort = dns_conn_info.dstport; 980 | should_recalc_checksum = 1; 981 | } 982 | else { 983 | if (dns_is_dns_packet(packet_data, packet_dataLen, 0)) 984 | should_reinject = 0; 985 | 986 | if (do_dns_verb && !should_reinject) { 987 | printf("[DNS] Error handling incoming packet: srcport = %hu, dstport = %hu\n", 988 | ntohs(ppUdpHdr->SrcPort), ntohs(ppUdpHdr->DstPort)); 989 | } 990 | } 991 | } 992 | 993 | else if (addr.Direction == WINDIVERT_DIRECTION_OUTBOUND) { 994 | if ((packet_v4 && dns_handle_outgoing(&ppIpHdr->SrcAddr, ppUdpHdr->SrcPort, 995 | &ppIpHdr->DstAddr, ppUdpHdr->DstPort, 996 | packet_data, packet_dataLen, 0)) 997 | || 998 | (packet_v6 && dns_handle_outgoing(ppIpV6Hdr->SrcAddr, ppUdpHdr->SrcPort, 999 | ppIpV6Hdr->DstAddr, ppUdpHdr->DstPort, 1000 | packet_data, packet_dataLen, 1))) 1001 | { 1002 | /* Changing destination IP and port to the values 1003 | * from configuration */ 1004 | if (packet_v4) { 1005 | ppIpHdr->DstAddr = dnsv4_addr; 1006 | ppUdpHdr->DstPort = dnsv4_port; 1007 | } 1008 | else if (packet_v6) { 1009 | ipv6_copy_addr(ppIpV6Hdr->DstAddr, (uint32_t*)dnsv6_addr.s6_addr); 1010 | ppUdpHdr->DstPort = dnsv6_port; 1011 | } 1012 | should_recalc_checksum = 1; 1013 | } 1014 | else { 1015 | if (dns_is_dns_packet(packet_data, packet_dataLen, 1)) 1016 | should_reinject = 0; 1017 | 1018 | if (do_dns_verb && !should_reinject) { 1019 | printf("[DNS] Error handling outgoing packet: srcport = %hu, dstport = %hu\n", 1020 | ntohs(ppUdpHdr->SrcPort), ntohs(ppUdpHdr->DstPort)); 1021 | } 1022 | } 1023 | } 1024 | } 1025 | 1026 | if (should_reinject) { 1027 | //printf("Re-injecting!\n"); 1028 | if (should_recalc_checksum) { 1029 | WinDivertHelperCalcChecksums(packet, packetLen, &addr, NULL); 1030 | } 1031 | WinDivertSend(w_filter, packet, packetLen, &addr, NULL); 1032 | } 1033 | } 1034 | else { 1035 | // error, ignore 1036 | printf("Error receiving packet!\n"); 1037 | break; 1038 | } 1039 | } 1040 | } 1041 | -------------------------------------------------------------------------------- /src/utils/uthash.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2003-2017, Troy D. Hanson http://troydhanson.github.com/uthash/ 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | 11 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 12 | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 13 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 14 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 15 | OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 16 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 17 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 18 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 19 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 20 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | */ 23 | 24 | #ifndef UTHASH_H 25 | #define UTHASH_H 26 | 27 | #define UTHASH_VERSION 2.0.2 28 | 29 | #include /* memcmp, memset, strlen */ 30 | #include /* ptrdiff_t */ 31 | #include /* exit */ 32 | 33 | /* These macros use decltype or the earlier __typeof GNU extension. 34 | As decltype is only available in newer compilers (VS2010 or gcc 4.3+ 35 | when compiling c++ source) this code uses whatever method is needed 36 | or, for VS2008 where neither is available, uses casting workarounds. */ 37 | #if !defined(DECLTYPE) && !defined(NO_DECLTYPE) 38 | #if defined(_MSC_VER) /* MS compiler */ 39 | #if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ 40 | #define DECLTYPE(x) (decltype(x)) 41 | #else /* VS2008 or older (or VS2010 in C mode) */ 42 | #define NO_DECLTYPE 43 | #endif 44 | #elif defined(__BORLANDC__) || defined(__ICCARM__) || defined(__LCC__) || defined(__WATCOMC__) 45 | #define NO_DECLTYPE 46 | #else /* GNU, Sun and other compilers */ 47 | #define DECLTYPE(x) (__typeof(x)) 48 | #endif 49 | #endif 50 | 51 | #ifdef NO_DECLTYPE 52 | #define DECLTYPE(x) 53 | #define DECLTYPE_ASSIGN(dst,src) \ 54 | do { \ 55 | char **_da_dst = (char**)(&(dst)); \ 56 | *_da_dst = (char*)(src); \ 57 | } while (0) 58 | #else 59 | #define DECLTYPE_ASSIGN(dst,src) \ 60 | do { \ 61 | (dst) = DECLTYPE(dst)(src); \ 62 | } while (0) 63 | #endif 64 | 65 | /* a number of the hash function use uint32_t which isn't defined on Pre VS2010 */ 66 | #if defined(_WIN32) 67 | #if defined(_MSC_VER) && _MSC_VER >= 1600 68 | #include 69 | #elif defined(__WATCOMC__) || defined(__MINGW32__) || defined(__CYGWIN__) 70 | #include 71 | #else 72 | typedef unsigned int uint32_t; 73 | typedef unsigned char uint8_t; 74 | #endif 75 | #elif defined(__GNUC__) && !defined(__VXWORKS__) 76 | #include 77 | #else 78 | typedef unsigned int uint32_t; 79 | typedef unsigned char uint8_t; 80 | #endif 81 | 82 | #ifndef uthash_malloc 83 | #define uthash_malloc(sz) malloc(sz) /* malloc fcn */ 84 | #endif 85 | #ifndef uthash_free 86 | #define uthash_free(ptr,sz) free(ptr) /* free fcn */ 87 | #endif 88 | #ifndef uthash_bzero 89 | #define uthash_bzero(a,n) memset(a,'\0',n) 90 | #endif 91 | #ifndef uthash_memcmp 92 | #define uthash_memcmp(a,b,n) memcmp(a,b,n) 93 | #endif 94 | #ifndef uthash_strlen 95 | #define uthash_strlen(s) strlen(s) 96 | #endif 97 | 98 | #ifndef uthash_noexpand_fyi 99 | #define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ 100 | #endif 101 | #ifndef uthash_expand_fyi 102 | #define uthash_expand_fyi(tbl) /* can be defined to log expands */ 103 | #endif 104 | 105 | #ifndef HASH_NONFATAL_OOM 106 | #define HASH_NONFATAL_OOM 0 107 | #endif 108 | 109 | #if HASH_NONFATAL_OOM 110 | /* malloc failures can be recovered from */ 111 | 112 | #ifndef uthash_nonfatal_oom 113 | #define uthash_nonfatal_oom(obj) do {} while (0) /* non-fatal OOM error */ 114 | #endif 115 | 116 | #define HASH_RECORD_OOM(oomed) do { (oomed) = 1; } while (0) 117 | #define IF_HASH_NONFATAL_OOM(x) x 118 | 119 | #else 120 | /* malloc failures result in lost memory, hash tables are unusable */ 121 | 122 | #ifndef uthash_fatal 123 | #define uthash_fatal(msg) exit(-1) /* fatal OOM error */ 124 | #endif 125 | 126 | #define HASH_RECORD_OOM(oomed) uthash_fatal("out of memory") 127 | #define IF_HASH_NONFATAL_OOM(x) 128 | 129 | #endif 130 | 131 | /* initial number of buckets */ 132 | #define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */ 133 | #define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */ 134 | #define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */ 135 | 136 | /* calculate the element whose hash handle address is hhp */ 137 | #define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) 138 | /* calculate the hash handle from element address elp */ 139 | #define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle *)(((char*)(elp)) + ((tbl)->hho))) 140 | 141 | #define HASH_ROLLBACK_BKT(hh, head, itemptrhh) \ 142 | do { \ 143 | struct UT_hash_handle *_hd_hh_item = (itemptrhh); \ 144 | unsigned _hd_bkt; \ 145 | HASH_TO_BKT(_hd_hh_item->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ 146 | (head)->hh.tbl->buckets[_hd_bkt].count++; \ 147 | _hd_hh_item->hh_next = NULL; \ 148 | _hd_hh_item->hh_prev = NULL; \ 149 | } while (0) 150 | 151 | #define HASH_VALUE(keyptr,keylen,hashv) \ 152 | do { \ 153 | HASH_FCN(keyptr, keylen, hashv); \ 154 | } while (0) 155 | 156 | #define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out) \ 157 | do { \ 158 | (out) = NULL; \ 159 | if (head) { \ 160 | unsigned _hf_bkt; \ 161 | HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \ 162 | if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) { \ 163 | HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \ 164 | } \ 165 | } \ 166 | } while (0) 167 | 168 | #define HASH_FIND(hh,head,keyptr,keylen,out) \ 169 | do { \ 170 | unsigned _hf_hashv; \ 171 | HASH_VALUE(keyptr, keylen, _hf_hashv); \ 172 | HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \ 173 | } while (0) 174 | 175 | #ifdef HASH_BLOOM 176 | #define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM) 177 | #define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL) 178 | #define HASH_BLOOM_MAKE(tbl,oomed) \ 179 | do { \ 180 | (tbl)->bloom_nbits = HASH_BLOOM; \ 181 | (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ 182 | if (!(tbl)->bloom_bv) { \ 183 | HASH_RECORD_OOM(oomed); \ 184 | } else { \ 185 | uthash_bzero((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ 186 | (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ 187 | } \ 188 | } while (0) 189 | 190 | #define HASH_BLOOM_FREE(tbl) \ 191 | do { \ 192 | uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ 193 | } while (0) 194 | 195 | #define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8U] |= (1U << ((idx)%8U))) 196 | #define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8U] & (1U << ((idx)%8U))) 197 | 198 | #define HASH_BLOOM_ADD(tbl,hashv) \ 199 | HASH_BLOOM_BITSET((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) 200 | 201 | #define HASH_BLOOM_TEST(tbl,hashv) \ 202 | HASH_BLOOM_BITTEST((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) 203 | 204 | #else 205 | #define HASH_BLOOM_MAKE(tbl,oomed) 206 | #define HASH_BLOOM_FREE(tbl) 207 | #define HASH_BLOOM_ADD(tbl,hashv) 208 | #define HASH_BLOOM_TEST(tbl,hashv) (1) 209 | #define HASH_BLOOM_BYTELEN 0U 210 | #endif 211 | 212 | #define HASH_MAKE_TABLE(hh,head,oomed) \ 213 | do { \ 214 | (head)->hh.tbl = (UT_hash_table*)uthash_malloc(sizeof(UT_hash_table)); \ 215 | if (!(head)->hh.tbl) { \ 216 | HASH_RECORD_OOM(oomed); \ 217 | } else { \ 218 | uthash_bzero((head)->hh.tbl, sizeof(UT_hash_table)); \ 219 | (head)->hh.tbl->tail = &((head)->hh); \ 220 | (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ 221 | (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ 222 | (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ 223 | (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ 224 | HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ 225 | (head)->hh.tbl->signature = HASH_SIGNATURE; \ 226 | if (!(head)->hh.tbl->buckets) { \ 227 | HASH_RECORD_OOM(oomed); \ 228 | uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ 229 | } else { \ 230 | uthash_bzero((head)->hh.tbl->buckets, \ 231 | HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ 232 | HASH_BLOOM_MAKE((head)->hh.tbl, oomed); \ 233 | IF_HASH_NONFATAL_OOM( \ 234 | if (oomed) { \ 235 | uthash_free((head)->hh.tbl->buckets, \ 236 | HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ 237 | uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ 238 | } \ 239 | ) \ 240 | } \ 241 | } \ 242 | } while (0) 243 | 244 | #define HASH_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \ 245 | do { \ 246 | (replaced) = NULL; \ 247 | HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ 248 | if (replaced) { \ 249 | HASH_DELETE(hh, head, replaced); \ 250 | } \ 251 | HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \ 252 | } while (0) 253 | 254 | #define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \ 255 | do { \ 256 | (replaced) = NULL; \ 257 | HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ 258 | if (replaced) { \ 259 | HASH_DELETE(hh, head, replaced); \ 260 | } \ 261 | HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \ 262 | } while (0) 263 | 264 | #define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ 265 | do { \ 266 | unsigned _hr_hashv; \ 267 | HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ 268 | HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \ 269 | } while (0) 270 | 271 | #define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn) \ 272 | do { \ 273 | unsigned _hr_hashv; \ 274 | HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ 275 | HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \ 276 | } while (0) 277 | 278 | #define HASH_APPEND_LIST(hh, head, add) \ 279 | do { \ 280 | (add)->hh.next = NULL; \ 281 | (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ 282 | (head)->hh.tbl->tail->next = (add); \ 283 | (head)->hh.tbl->tail = &((add)->hh); \ 284 | } while (0) 285 | 286 | #define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \ 287 | do { \ 288 | do { \ 289 | if (cmpfcn(DECLTYPE(head)(_hs_iter), add) > 0) { \ 290 | break; \ 291 | } \ 292 | } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ 293 | } while (0) 294 | 295 | #ifdef NO_DECLTYPE 296 | #undef HASH_AKBI_INNER_LOOP 297 | #define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \ 298 | do { \ 299 | char *_hs_saved_head = (char*)(head); \ 300 | do { \ 301 | DECLTYPE_ASSIGN(head, _hs_iter); \ 302 | if (cmpfcn(head, add) > 0) { \ 303 | DECLTYPE_ASSIGN(head, _hs_saved_head); \ 304 | break; \ 305 | } \ 306 | DECLTYPE_ASSIGN(head, _hs_saved_head); \ 307 | } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ 308 | } while (0) 309 | #endif 310 | 311 | #if HASH_NONFATAL_OOM 312 | 313 | #define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed) \ 314 | do { \ 315 | if (!(oomed)) { \ 316 | unsigned _ha_bkt; \ 317 | (head)->hh.tbl->num_items++; \ 318 | HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ 319 | HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \ 320 | if (oomed) { \ 321 | HASH_ROLLBACK_BKT(hh, head, &(add)->hh); \ 322 | HASH_DELETE_HH(hh, head, &(add)->hh); \ 323 | (add)->hh.tbl = NULL; \ 324 | uthash_nonfatal_oom(add); \ 325 | } else { \ 326 | HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ 327 | HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ 328 | } \ 329 | } else { \ 330 | (add)->hh.tbl = NULL; \ 331 | uthash_nonfatal_oom(add); \ 332 | } \ 333 | } while (0) 334 | 335 | #else 336 | 337 | #define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed) \ 338 | do { \ 339 | unsigned _ha_bkt; \ 340 | (head)->hh.tbl->num_items++; \ 341 | HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ 342 | HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \ 343 | HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ 344 | HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ 345 | } while (0) 346 | 347 | #endif 348 | 349 | 350 | #define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \ 351 | do { \ 352 | IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; ) \ 353 | (add)->hh.hashv = (hashval); \ 354 | (add)->hh.key = (char*) (keyptr); \ 355 | (add)->hh.keylen = (unsigned) (keylen_in); \ 356 | if (!(head)) { \ 357 | (add)->hh.next = NULL; \ 358 | (add)->hh.prev = NULL; \ 359 | HASH_MAKE_TABLE(hh, add, _ha_oomed); \ 360 | IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { ) \ 361 | (head) = (add); \ 362 | IF_HASH_NONFATAL_OOM( } ) \ 363 | } else { \ 364 | void *_hs_iter = (head); \ 365 | (add)->hh.tbl = (head)->hh.tbl; \ 366 | HASH_AKBI_INNER_LOOP(hh, head, add, cmpfcn); \ 367 | if (_hs_iter) { \ 368 | (add)->hh.next = _hs_iter; \ 369 | if (((add)->hh.prev = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev)) { \ 370 | HH_FROM_ELMT((head)->hh.tbl, (add)->hh.prev)->next = (add); \ 371 | } else { \ 372 | (head) = (add); \ 373 | } \ 374 | HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev = (add); \ 375 | } else { \ 376 | HASH_APPEND_LIST(hh, head, add); \ 377 | } \ 378 | } \ 379 | HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \ 380 | HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE_INORDER"); \ 381 | } while (0) 382 | 383 | #define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn) \ 384 | do { \ 385 | unsigned _hs_hashv; \ 386 | HASH_VALUE(keyptr, keylen_in, _hs_hashv); \ 387 | HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \ 388 | } while (0) 389 | 390 | #define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \ 391 | HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn) 392 | 393 | #define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn) \ 394 | HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn) 395 | 396 | #define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add) \ 397 | do { \ 398 | IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; ) \ 399 | (add)->hh.hashv = (hashval); \ 400 | (add)->hh.key = (char*) (keyptr); \ 401 | (add)->hh.keylen = (unsigned) (keylen_in); \ 402 | if (!(head)) { \ 403 | (add)->hh.next = NULL; \ 404 | (add)->hh.prev = NULL; \ 405 | HASH_MAKE_TABLE(hh, add, _ha_oomed); \ 406 | IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { ) \ 407 | (head) = (add); \ 408 | IF_HASH_NONFATAL_OOM( } ) \ 409 | } else { \ 410 | (add)->hh.tbl = (head)->hh.tbl; \ 411 | HASH_APPEND_LIST(hh, head, add); \ 412 | } \ 413 | HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \ 414 | HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE"); \ 415 | } while (0) 416 | 417 | #define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ 418 | do { \ 419 | unsigned _ha_hashv; \ 420 | HASH_VALUE(keyptr, keylen_in, _ha_hashv); \ 421 | HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \ 422 | } while (0) 423 | 424 | #define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add) \ 425 | HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add) 426 | 427 | #define HASH_ADD(hh,head,fieldname,keylen_in,add) \ 428 | HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add) 429 | 430 | #define HASH_TO_BKT(hashv,num_bkts,bkt) \ 431 | do { \ 432 | bkt = ((hashv) & ((num_bkts) - 1U)); \ 433 | } while (0) 434 | 435 | /* delete "delptr" from the hash table. 436 | * "the usual" patch-up process for the app-order doubly-linked-list. 437 | * The use of _hd_hh_del below deserves special explanation. 438 | * These used to be expressed using (delptr) but that led to a bug 439 | * if someone used the same symbol for the head and deletee, like 440 | * HASH_DELETE(hh,users,users); 441 | * We want that to work, but by changing the head (users) below 442 | * we were forfeiting our ability to further refer to the deletee (users) 443 | * in the patch-up process. Solution: use scratch space to 444 | * copy the deletee pointer, then the latter references are via that 445 | * scratch pointer rather than through the repointed (users) symbol. 446 | */ 447 | #define HASH_DELETE(hh,head,delptr) \ 448 | HASH_DELETE_HH(hh, head, &(delptr)->hh) 449 | 450 | #define HASH_DELETE_HH(hh,head,delptrhh) \ 451 | do { \ 452 | struct UT_hash_handle *_hd_hh_del = (delptrhh); \ 453 | if ((_hd_hh_del->prev == NULL) && (_hd_hh_del->next == NULL)) { \ 454 | HASH_BLOOM_FREE((head)->hh.tbl); \ 455 | uthash_free((head)->hh.tbl->buckets, \ 456 | (head)->hh.tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ 457 | uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ 458 | (head) = NULL; \ 459 | } else { \ 460 | unsigned _hd_bkt; \ 461 | if (_hd_hh_del == (head)->hh.tbl->tail) { \ 462 | (head)->hh.tbl->tail = HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev); \ 463 | } \ 464 | if (_hd_hh_del->prev != NULL) { \ 465 | HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev)->next = _hd_hh_del->next; \ 466 | } else { \ 467 | DECLTYPE_ASSIGN(head, _hd_hh_del->next); \ 468 | } \ 469 | if (_hd_hh_del->next != NULL) { \ 470 | HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->next)->prev = _hd_hh_del->prev; \ 471 | } \ 472 | HASH_TO_BKT(_hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ 473 | HASH_DEL_IN_BKT((head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ 474 | (head)->hh.tbl->num_items--; \ 475 | } \ 476 | HASH_FSCK(hh, head, "HASH_DELETE_HH"); \ 477 | } while (0) 478 | 479 | /* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ 480 | #define HASH_FIND_STR(head,findstr,out) \ 481 | HASH_FIND(hh,head,findstr,(unsigned)uthash_strlen(findstr),out) 482 | #define HASH_ADD_STR(head,strfield,add) \ 483 | HASH_ADD(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add) 484 | #define HASH_REPLACE_STR(head,strfield,add,replaced) \ 485 | HASH_REPLACE(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add,replaced) 486 | #define HASH_FIND_INT(head,findint,out) \ 487 | HASH_FIND(hh,head,findint,sizeof(int),out) 488 | #define HASH_ADD_INT(head,intfield,add) \ 489 | HASH_ADD(hh,head,intfield,sizeof(int),add) 490 | #define HASH_REPLACE_INT(head,intfield,add,replaced) \ 491 | HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced) 492 | #define HASH_FIND_PTR(head,findptr,out) \ 493 | HASH_FIND(hh,head,findptr,sizeof(void *),out) 494 | #define HASH_ADD_PTR(head,ptrfield,add) \ 495 | HASH_ADD(hh,head,ptrfield,sizeof(void *),add) 496 | #define HASH_REPLACE_PTR(head,ptrfield,add,replaced) \ 497 | HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced) 498 | #define HASH_DEL(head,delptr) \ 499 | HASH_DELETE(hh,head,delptr) 500 | 501 | /* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. 502 | * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. 503 | */ 504 | #ifdef HASH_DEBUG 505 | #define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) 506 | #define HASH_FSCK(hh,head,where) \ 507 | do { \ 508 | struct UT_hash_handle *_thh; \ 509 | if (head) { \ 510 | unsigned _bkt_i; \ 511 | unsigned _count = 0; \ 512 | char *_prev; \ 513 | for (_bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; ++_bkt_i) { \ 514 | unsigned _bkt_count = 0; \ 515 | _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ 516 | _prev = NULL; \ 517 | while (_thh) { \ 518 | if (_prev != (char*)(_thh->hh_prev)) { \ 519 | HASH_OOPS("%s: invalid hh_prev %p, actual %p\n", \ 520 | (where), (void*)_thh->hh_prev, (void*)_prev); \ 521 | } \ 522 | _bkt_count++; \ 523 | _prev = (char*)(_thh); \ 524 | _thh = _thh->hh_next; \ 525 | } \ 526 | _count += _bkt_count; \ 527 | if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ 528 | HASH_OOPS("%s: invalid bucket count %u, actual %u\n", \ 529 | (where), (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ 530 | } \ 531 | } \ 532 | if (_count != (head)->hh.tbl->num_items) { \ 533 | HASH_OOPS("%s: invalid hh item count %u, actual %u\n", \ 534 | (where), (head)->hh.tbl->num_items, _count); \ 535 | } \ 536 | _count = 0; \ 537 | _prev = NULL; \ 538 | _thh = &(head)->hh; \ 539 | while (_thh) { \ 540 | _count++; \ 541 | if (_prev != (char*)_thh->prev) { \ 542 | HASH_OOPS("%s: invalid prev %p, actual %p\n", \ 543 | (where), (void*)_thh->prev, (void*)_prev); \ 544 | } \ 545 | _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ 546 | _thh = (_thh->next ? HH_FROM_ELMT((head)->hh.tbl, _thh->next) : NULL); \ 547 | } \ 548 | if (_count != (head)->hh.tbl->num_items) { \ 549 | HASH_OOPS("%s: invalid app item count %u, actual %u\n", \ 550 | (where), (head)->hh.tbl->num_items, _count); \ 551 | } \ 552 | } \ 553 | } while (0) 554 | #else 555 | #define HASH_FSCK(hh,head,where) 556 | #endif 557 | 558 | /* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to 559 | * the descriptor to which this macro is defined for tuning the hash function. 560 | * The app can #include to get the prototype for write(2). */ 561 | #ifdef HASH_EMIT_KEYS 562 | #define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ 563 | do { \ 564 | unsigned _klen = fieldlen; \ 565 | write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ 566 | write(HASH_EMIT_KEYS, keyptr, (unsigned long)fieldlen); \ 567 | } while (0) 568 | #else 569 | #define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) 570 | #endif 571 | 572 | /* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ 573 | #ifdef HASH_FUNCTION 574 | #define HASH_FCN HASH_FUNCTION 575 | #else 576 | #define HASH_FCN HASH_JEN 577 | #endif 578 | 579 | /* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */ 580 | #define HASH_BER(key,keylen,hashv) \ 581 | do { \ 582 | unsigned _hb_keylen = (unsigned)keylen; \ 583 | const unsigned char *_hb_key = (const unsigned char*)(key); \ 584 | (hashv) = 0; \ 585 | while (_hb_keylen-- != 0U) { \ 586 | (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \ 587 | } \ 588 | } while (0) 589 | 590 | 591 | /* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at 592 | * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ 593 | #define HASH_SAX(key,keylen,hashv) \ 594 | do { \ 595 | unsigned _sx_i; \ 596 | const unsigned char *_hs_key = (const unsigned char*)(key); \ 597 | hashv = 0; \ 598 | for (_sx_i=0; _sx_i < keylen; _sx_i++) { \ 599 | hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ 600 | } \ 601 | } while (0) 602 | /* FNV-1a variation */ 603 | #define HASH_FNV(key,keylen,hashv) \ 604 | do { \ 605 | unsigned _fn_i; \ 606 | const unsigned char *_hf_key = (const unsigned char*)(key); \ 607 | (hashv) = 2166136261U; \ 608 | for (_fn_i=0; _fn_i < keylen; _fn_i++) { \ 609 | hashv = hashv ^ _hf_key[_fn_i]; \ 610 | hashv = hashv * 16777619U; \ 611 | } \ 612 | } while (0) 613 | 614 | #define HASH_OAT(key,keylen,hashv) \ 615 | do { \ 616 | unsigned _ho_i; \ 617 | const unsigned char *_ho_key=(const unsigned char*)(key); \ 618 | hashv = 0; \ 619 | for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ 620 | hashv += _ho_key[_ho_i]; \ 621 | hashv += (hashv << 10); \ 622 | hashv ^= (hashv >> 6); \ 623 | } \ 624 | hashv += (hashv << 3); \ 625 | hashv ^= (hashv >> 11); \ 626 | hashv += (hashv << 15); \ 627 | } while (0) 628 | 629 | #define HASH_JEN_MIX(a,b,c) \ 630 | do { \ 631 | a -= b; a -= c; a ^= ( c >> 13 ); \ 632 | b -= c; b -= a; b ^= ( a << 8 ); \ 633 | c -= a; c -= b; c ^= ( b >> 13 ); \ 634 | a -= b; a -= c; a ^= ( c >> 12 ); \ 635 | b -= c; b -= a; b ^= ( a << 16 ); \ 636 | c -= a; c -= b; c ^= ( b >> 5 ); \ 637 | a -= b; a -= c; a ^= ( c >> 3 ); \ 638 | b -= c; b -= a; b ^= ( a << 10 ); \ 639 | c -= a; c -= b; c ^= ( b >> 15 ); \ 640 | } while (0) 641 | 642 | #define HASH_JEN(key,keylen,hashv) \ 643 | do { \ 644 | unsigned _hj_i,_hj_j,_hj_k; \ 645 | unsigned const char *_hj_key=(unsigned const char*)(key); \ 646 | hashv = 0xfeedbeefu; \ 647 | _hj_i = _hj_j = 0x9e3779b9u; \ 648 | _hj_k = (unsigned)(keylen); \ 649 | while (_hj_k >= 12U) { \ 650 | _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ 651 | + ( (unsigned)_hj_key[2] << 16 ) \ 652 | + ( (unsigned)_hj_key[3] << 24 ) ); \ 653 | _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ 654 | + ( (unsigned)_hj_key[6] << 16 ) \ 655 | + ( (unsigned)_hj_key[7] << 24 ) ); \ 656 | hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ 657 | + ( (unsigned)_hj_key[10] << 16 ) \ 658 | + ( (unsigned)_hj_key[11] << 24 ) ); \ 659 | \ 660 | HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ 661 | \ 662 | _hj_key += 12; \ 663 | _hj_k -= 12U; \ 664 | } \ 665 | hashv += (unsigned)(keylen); \ 666 | switch ( _hj_k ) { \ 667 | case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \ 668 | case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \ 669 | case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \ 670 | case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \ 671 | case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \ 672 | case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \ 673 | case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \ 674 | case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \ 675 | case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \ 676 | case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \ 677 | case 1: _hj_i += _hj_key[0]; \ 678 | } \ 679 | HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ 680 | } while (0) 681 | 682 | /* The Paul Hsieh hash function */ 683 | #undef get16bits 684 | #if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ 685 | || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) 686 | #define get16bits(d) (*((const uint16_t *) (d))) 687 | #endif 688 | 689 | #if !defined (get16bits) 690 | #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ 691 | +(uint32_t)(((const uint8_t *)(d))[0]) ) 692 | #endif 693 | #define HASH_SFH(key,keylen,hashv) \ 694 | do { \ 695 | unsigned const char *_sfh_key=(unsigned const char*)(key); \ 696 | uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \ 697 | \ 698 | unsigned _sfh_rem = _sfh_len & 3U; \ 699 | _sfh_len >>= 2; \ 700 | hashv = 0xcafebabeu; \ 701 | \ 702 | /* Main loop */ \ 703 | for (;_sfh_len > 0U; _sfh_len--) { \ 704 | hashv += get16bits (_sfh_key); \ 705 | _sfh_tmp = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv; \ 706 | hashv = (hashv << 16) ^ _sfh_tmp; \ 707 | _sfh_key += 2U*sizeof (uint16_t); \ 708 | hashv += hashv >> 11; \ 709 | } \ 710 | \ 711 | /* Handle end cases */ \ 712 | switch (_sfh_rem) { \ 713 | case 3: hashv += get16bits (_sfh_key); \ 714 | hashv ^= hashv << 16; \ 715 | hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)]) << 18; \ 716 | hashv += hashv >> 11; \ 717 | break; \ 718 | case 2: hashv += get16bits (_sfh_key); \ 719 | hashv ^= hashv << 11; \ 720 | hashv += hashv >> 17; \ 721 | break; \ 722 | case 1: hashv += *_sfh_key; \ 723 | hashv ^= hashv << 10; \ 724 | hashv += hashv >> 1; \ 725 | } \ 726 | \ 727 | /* Force "avalanching" of final 127 bits */ \ 728 | hashv ^= hashv << 3; \ 729 | hashv += hashv >> 5; \ 730 | hashv ^= hashv << 4; \ 731 | hashv += hashv >> 17; \ 732 | hashv ^= hashv << 25; \ 733 | hashv += hashv >> 6; \ 734 | } while (0) 735 | 736 | #ifdef HASH_USING_NO_STRICT_ALIASING 737 | /* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads. 738 | * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. 739 | * MurmurHash uses the faster approach only on CPU's where we know it's safe. 740 | * 741 | * Note the preprocessor built-in defines can be emitted using: 742 | * 743 | * gcc -m64 -dM -E - < /dev/null (on gcc) 744 | * cc -## a.c (where a.c is a simple test file) (Sun Studio) 745 | */ 746 | #if (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86)) 747 | #define MUR_GETBLOCK(p,i) p[i] 748 | #else /* non intel */ 749 | #define MUR_PLUS0_ALIGNED(p) (((unsigned long)p & 3UL) == 0UL) 750 | #define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 3UL) == 1UL) 751 | #define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 3UL) == 2UL) 752 | #define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 3UL) == 3UL) 753 | #define WP(p) ((uint32_t*)((unsigned long)(p) & ~3UL)) 754 | #if (defined(__BIG_ENDIAN__) || defined(SPARC) || defined(__ppc__) || defined(__ppc64__)) 755 | #define MUR_THREE_ONE(p) ((((*WP(p))&0x00ffffff) << 8) | (((*(WP(p)+1))&0xff000000) >> 24)) 756 | #define MUR_TWO_TWO(p) ((((*WP(p))&0x0000ffff) <<16) | (((*(WP(p)+1))&0xffff0000) >> 16)) 757 | #define MUR_ONE_THREE(p) ((((*WP(p))&0x000000ff) <<24) | (((*(WP(p)+1))&0xffffff00) >> 8)) 758 | #else /* assume little endian non-intel */ 759 | #define MUR_THREE_ONE(p) ((((*WP(p))&0xffffff00) >> 8) | (((*(WP(p)+1))&0x000000ff) << 24)) 760 | #define MUR_TWO_TWO(p) ((((*WP(p))&0xffff0000) >>16) | (((*(WP(p)+1))&0x0000ffff) << 16)) 761 | #define MUR_ONE_THREE(p) ((((*WP(p))&0xff000000) >>24) | (((*(WP(p)+1))&0x00ffffff) << 8)) 762 | #endif 763 | #define MUR_GETBLOCK(p,i) (MUR_PLUS0_ALIGNED(p) ? ((p)[i]) : \ 764 | (MUR_PLUS1_ALIGNED(p) ? MUR_THREE_ONE(p) : \ 765 | (MUR_PLUS2_ALIGNED(p) ? MUR_TWO_TWO(p) : \ 766 | MUR_ONE_THREE(p)))) 767 | #endif 768 | #define MUR_ROTL32(x,r) (((x) << (r)) | ((x) >> (32 - (r)))) 769 | #define MUR_FMIX(_h) \ 770 | do { \ 771 | _h ^= _h >> 16; \ 772 | _h *= 0x85ebca6bu; \ 773 | _h ^= _h >> 13; \ 774 | _h *= 0xc2b2ae35u; \ 775 | _h ^= _h >> 16; \ 776 | } while (0) 777 | 778 | #define HASH_MUR(key,keylen,hashv) \ 779 | do { \ 780 | const uint8_t *_mur_data = (const uint8_t*)(key); \ 781 | const int _mur_nblocks = (int)(keylen) / 4; \ 782 | uint32_t _mur_h1 = 0xf88D5353u; \ 783 | uint32_t _mur_c1 = 0xcc9e2d51u; \ 784 | uint32_t _mur_c2 = 0x1b873593u; \ 785 | uint32_t _mur_k1 = 0; \ 786 | const uint8_t *_mur_tail; \ 787 | const uint32_t *_mur_blocks = (const uint32_t*)(_mur_data+(_mur_nblocks*4)); \ 788 | int _mur_i; \ 789 | for (_mur_i = -_mur_nblocks; _mur_i != 0; _mur_i++) { \ 790 | _mur_k1 = MUR_GETBLOCK(_mur_blocks,_mur_i); \ 791 | _mur_k1 *= _mur_c1; \ 792 | _mur_k1 = MUR_ROTL32(_mur_k1,15); \ 793 | _mur_k1 *= _mur_c2; \ 794 | \ 795 | _mur_h1 ^= _mur_k1; \ 796 | _mur_h1 = MUR_ROTL32(_mur_h1,13); \ 797 | _mur_h1 = (_mur_h1*5U) + 0xe6546b64u; \ 798 | } \ 799 | _mur_tail = (const uint8_t*)(_mur_data + (_mur_nblocks*4)); \ 800 | _mur_k1=0; \ 801 | switch ((keylen) & 3U) { \ 802 | case 0: break; \ 803 | case 3: _mur_k1 ^= (uint32_t)_mur_tail[2] << 16; /* FALLTHROUGH */ \ 804 | case 2: _mur_k1 ^= (uint32_t)_mur_tail[1] << 8; /* FALLTHROUGH */ \ 805 | case 1: _mur_k1 ^= (uint32_t)_mur_tail[0]; \ 806 | _mur_k1 *= _mur_c1; \ 807 | _mur_k1 = MUR_ROTL32(_mur_k1,15); \ 808 | _mur_k1 *= _mur_c2; \ 809 | _mur_h1 ^= _mur_k1; \ 810 | } \ 811 | _mur_h1 ^= (uint32_t)(keylen); \ 812 | MUR_FMIX(_mur_h1); \ 813 | hashv = _mur_h1; \ 814 | } while (0) 815 | #endif /* HASH_USING_NO_STRICT_ALIASING */ 816 | 817 | /* iterate over items in a known bucket to find desired item */ 818 | #define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out) \ 819 | do { \ 820 | if ((head).hh_head != NULL) { \ 821 | DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \ 822 | } else { \ 823 | (out) = NULL; \ 824 | } \ 825 | while ((out) != NULL) { \ 826 | if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \ 827 | if (uthash_memcmp((out)->hh.key, keyptr, keylen_in) == 0) { \ 828 | break; \ 829 | } \ 830 | } \ 831 | if ((out)->hh.hh_next != NULL) { \ 832 | DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (out)->hh.hh_next)); \ 833 | } else { \ 834 | (out) = NULL; \ 835 | } \ 836 | } \ 837 | } while (0) 838 | 839 | /* add an item to a bucket */ 840 | #define HASH_ADD_TO_BKT(head,hh,addhh,oomed) \ 841 | do { \ 842 | UT_hash_bucket *_ha_head = &(head); \ 843 | _ha_head->count++; \ 844 | (addhh)->hh_next = _ha_head->hh_head; \ 845 | (addhh)->hh_prev = NULL; \ 846 | if (_ha_head->hh_head != NULL) { \ 847 | _ha_head->hh_head->hh_prev = (addhh); \ 848 | } \ 849 | _ha_head->hh_head = (addhh); \ 850 | if ((_ha_head->count >= ((_ha_head->expand_mult + 1U) * HASH_BKT_CAPACITY_THRESH)) \ 851 | && !(addhh)->tbl->noexpand) { \ 852 | HASH_EXPAND_BUCKETS(addhh,(addhh)->tbl, oomed); \ 853 | IF_HASH_NONFATAL_OOM( \ 854 | if (oomed) { \ 855 | HASH_DEL_IN_BKT(head,addhh); \ 856 | } \ 857 | ) \ 858 | } \ 859 | } while (0) 860 | 861 | /* remove an item from a given bucket */ 862 | #define HASH_DEL_IN_BKT(head,delhh) \ 863 | do { \ 864 | UT_hash_bucket *_hd_head = &(head); \ 865 | _hd_head->count--; \ 866 | if (_hd_head->hh_head == (delhh)) { \ 867 | _hd_head->hh_head = (delhh)->hh_next; \ 868 | } \ 869 | if ((delhh)->hh_prev) { \ 870 | (delhh)->hh_prev->hh_next = (delhh)->hh_next; \ 871 | } \ 872 | if ((delhh)->hh_next) { \ 873 | (delhh)->hh_next->hh_prev = (delhh)->hh_prev; \ 874 | } \ 875 | } while (0) 876 | 877 | /* Bucket expansion has the effect of doubling the number of buckets 878 | * and redistributing the items into the new buckets. Ideally the 879 | * items will distribute more or less evenly into the new buckets 880 | * (the extent to which this is true is a measure of the quality of 881 | * the hash function as it applies to the key domain). 882 | * 883 | * With the items distributed into more buckets, the chain length 884 | * (item count) in each bucket is reduced. Thus by expanding buckets 885 | * the hash keeps a bound on the chain length. This bounded chain 886 | * length is the essence of how a hash provides constant time lookup. 887 | * 888 | * The calculation of tbl->ideal_chain_maxlen below deserves some 889 | * explanation. First, keep in mind that we're calculating the ideal 890 | * maximum chain length based on the *new* (doubled) bucket count. 891 | * In fractions this is just n/b (n=number of items,b=new num buckets). 892 | * Since the ideal chain length is an integer, we want to calculate 893 | * ceil(n/b). We don't depend on floating point arithmetic in this 894 | * hash, so to calculate ceil(n/b) with integers we could write 895 | * 896 | * ceil(n/b) = (n/b) + ((n%b)?1:0) 897 | * 898 | * and in fact a previous version of this hash did just that. 899 | * But now we have improved things a bit by recognizing that b is 900 | * always a power of two. We keep its base 2 log handy (call it lb), 901 | * so now we can write this with a bit shift and logical AND: 902 | * 903 | * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) 904 | * 905 | */ 906 | #define HASH_EXPAND_BUCKETS(hh,tbl,oomed) \ 907 | do { \ 908 | unsigned _he_bkt; \ 909 | unsigned _he_bkt_i; \ 910 | struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ 911 | UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ 912 | _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ 913 | 2UL * (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \ 914 | if (!_he_new_buckets) { \ 915 | HASH_RECORD_OOM(oomed); \ 916 | } else { \ 917 | uthash_bzero(_he_new_buckets, \ 918 | 2UL * (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \ 919 | (tbl)->ideal_chain_maxlen = \ 920 | ((tbl)->num_items >> ((tbl)->log2_num_buckets+1U)) + \ 921 | ((((tbl)->num_items & (((tbl)->num_buckets*2U)-1U)) != 0U) ? 1U : 0U); \ 922 | (tbl)->nonideal_items = 0; \ 923 | for (_he_bkt_i = 0; _he_bkt_i < (tbl)->num_buckets; _he_bkt_i++) { \ 924 | _he_thh = (tbl)->buckets[ _he_bkt_i ].hh_head; \ 925 | while (_he_thh != NULL) { \ 926 | _he_hh_nxt = _he_thh->hh_next; \ 927 | HASH_TO_BKT(_he_thh->hashv, (tbl)->num_buckets * 2U, _he_bkt); \ 928 | _he_newbkt = &(_he_new_buckets[_he_bkt]); \ 929 | if (++(_he_newbkt->count) > (tbl)->ideal_chain_maxlen) { \ 930 | (tbl)->nonideal_items++; \ 931 | _he_newbkt->expand_mult = _he_newbkt->count / (tbl)->ideal_chain_maxlen; \ 932 | } \ 933 | _he_thh->hh_prev = NULL; \ 934 | _he_thh->hh_next = _he_newbkt->hh_head; \ 935 | if (_he_newbkt->hh_head != NULL) { \ 936 | _he_newbkt->hh_head->hh_prev = _he_thh; \ 937 | } \ 938 | _he_newbkt->hh_head = _he_thh; \ 939 | _he_thh = _he_hh_nxt; \ 940 | } \ 941 | } \ 942 | uthash_free((tbl)->buckets, (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \ 943 | (tbl)->num_buckets *= 2U; \ 944 | (tbl)->log2_num_buckets++; \ 945 | (tbl)->buckets = _he_new_buckets; \ 946 | (tbl)->ineff_expands = ((tbl)->nonideal_items > ((tbl)->num_items >> 1)) ? \ 947 | ((tbl)->ineff_expands+1U) : 0U; \ 948 | if ((tbl)->ineff_expands > 1U) { \ 949 | (tbl)->noexpand = 1; \ 950 | uthash_noexpand_fyi(tbl); \ 951 | } \ 952 | uthash_expand_fyi(tbl); \ 953 | } \ 954 | } while (0) 955 | 956 | 957 | /* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ 958 | /* Note that HASH_SORT assumes the hash handle name to be hh. 959 | * HASH_SRT was added to allow the hash handle name to be passed in. */ 960 | #define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) 961 | #define HASH_SRT(hh,head,cmpfcn) \ 962 | do { \ 963 | unsigned _hs_i; \ 964 | unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ 965 | struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ 966 | if (head != NULL) { \ 967 | _hs_insize = 1; \ 968 | _hs_looping = 1; \ 969 | _hs_list = &((head)->hh); \ 970 | while (_hs_looping != 0U) { \ 971 | _hs_p = _hs_list; \ 972 | _hs_list = NULL; \ 973 | _hs_tail = NULL; \ 974 | _hs_nmerges = 0; \ 975 | while (_hs_p != NULL) { \ 976 | _hs_nmerges++; \ 977 | _hs_q = _hs_p; \ 978 | _hs_psize = 0; \ 979 | for (_hs_i = 0; _hs_i < _hs_insize; ++_hs_i) { \ 980 | _hs_psize++; \ 981 | _hs_q = ((_hs_q->next != NULL) ? \ 982 | HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ 983 | if (_hs_q == NULL) { \ 984 | break; \ 985 | } \ 986 | } \ 987 | _hs_qsize = _hs_insize; \ 988 | while ((_hs_psize != 0U) || ((_hs_qsize != 0U) && (_hs_q != NULL))) { \ 989 | if (_hs_psize == 0U) { \ 990 | _hs_e = _hs_q; \ 991 | _hs_q = ((_hs_q->next != NULL) ? \ 992 | HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ 993 | _hs_qsize--; \ 994 | } else if ((_hs_qsize == 0U) || (_hs_q == NULL)) { \ 995 | _hs_e = _hs_p; \ 996 | if (_hs_p != NULL) { \ 997 | _hs_p = ((_hs_p->next != NULL) ? \ 998 | HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \ 999 | } \ 1000 | _hs_psize--; \ 1001 | } else if ((cmpfcn( \ 1002 | DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_p)), \ 1003 | DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_q)) \ 1004 | )) <= 0) { \ 1005 | _hs_e = _hs_p; \ 1006 | if (_hs_p != NULL) { \ 1007 | _hs_p = ((_hs_p->next != NULL) ? \ 1008 | HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \ 1009 | } \ 1010 | _hs_psize--; \ 1011 | } else { \ 1012 | _hs_e = _hs_q; \ 1013 | _hs_q = ((_hs_q->next != NULL) ? \ 1014 | HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ 1015 | _hs_qsize--; \ 1016 | } \ 1017 | if ( _hs_tail != NULL ) { \ 1018 | _hs_tail->next = ((_hs_e != NULL) ? \ 1019 | ELMT_FROM_HH((head)->hh.tbl, _hs_e) : NULL); \ 1020 | } else { \ 1021 | _hs_list = _hs_e; \ 1022 | } \ 1023 | if (_hs_e != NULL) { \ 1024 | _hs_e->prev = ((_hs_tail != NULL) ? \ 1025 | ELMT_FROM_HH((head)->hh.tbl, _hs_tail) : NULL); \ 1026 | } \ 1027 | _hs_tail = _hs_e; \ 1028 | } \ 1029 | _hs_p = _hs_q; \ 1030 | } \ 1031 | if (_hs_tail != NULL) { \ 1032 | _hs_tail->next = NULL; \ 1033 | } \ 1034 | if (_hs_nmerges <= 1U) { \ 1035 | _hs_looping = 0; \ 1036 | (head)->hh.tbl->tail = _hs_tail; \ 1037 | DECLTYPE_ASSIGN(head, ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ 1038 | } \ 1039 | _hs_insize *= 2U; \ 1040 | } \ 1041 | HASH_FSCK(hh, head, "HASH_SRT"); \ 1042 | } \ 1043 | } while (0) 1044 | 1045 | /* This function selects items from one hash into another hash. 1046 | * The end result is that the selected items have dual presence 1047 | * in both hashes. There is no copy of the items made; rather 1048 | * they are added into the new hash through a secondary hash 1049 | * hash handle that must be present in the structure. */ 1050 | #define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ 1051 | do { \ 1052 | unsigned _src_bkt, _dst_bkt; \ 1053 | void *_last_elt = NULL, *_elt; \ 1054 | UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ 1055 | ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ 1056 | if ((src) != NULL) { \ 1057 | for (_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ 1058 | for (_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ 1059 | _src_hh != NULL; \ 1060 | _src_hh = _src_hh->hh_next) { \ 1061 | _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ 1062 | if (cond(_elt)) { \ 1063 | IF_HASH_NONFATAL_OOM( int _hs_oomed = 0; ) \ 1064 | _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ 1065 | _dst_hh->key = _src_hh->key; \ 1066 | _dst_hh->keylen = _src_hh->keylen; \ 1067 | _dst_hh->hashv = _src_hh->hashv; \ 1068 | _dst_hh->prev = _last_elt; \ 1069 | _dst_hh->next = NULL; \ 1070 | if (_last_elt_hh != NULL) { \ 1071 | _last_elt_hh->next = _elt; \ 1072 | } \ 1073 | if ((dst) == NULL) { \ 1074 | DECLTYPE_ASSIGN(dst, _elt); \ 1075 | HASH_MAKE_TABLE(hh_dst, dst, _hs_oomed); \ 1076 | IF_HASH_NONFATAL_OOM( \ 1077 | if (_hs_oomed) { \ 1078 | uthash_nonfatal_oom(_elt); \ 1079 | (dst) = NULL; \ 1080 | continue; \ 1081 | } \ 1082 | ) \ 1083 | } else { \ 1084 | _dst_hh->tbl = (dst)->hh_dst.tbl; \ 1085 | } \ 1086 | HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ 1087 | HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt], hh_dst, _dst_hh, _hs_oomed); \ 1088 | (dst)->hh_dst.tbl->num_items++; \ 1089 | IF_HASH_NONFATAL_OOM( \ 1090 | if (_hs_oomed) { \ 1091 | HASH_ROLLBACK_BKT(hh_dst, dst, _dst_hh); \ 1092 | HASH_DELETE_HH(hh_dst, dst, _dst_hh); \ 1093 | _dst_hh->tbl = NULL; \ 1094 | uthash_nonfatal_oom(_elt); \ 1095 | continue; \ 1096 | } \ 1097 | ) \ 1098 | HASH_BLOOM_ADD(_dst_hh->tbl, _dst_hh->hashv); \ 1099 | _last_elt = _elt; \ 1100 | _last_elt_hh = _dst_hh; \ 1101 | } \ 1102 | } \ 1103 | } \ 1104 | } \ 1105 | HASH_FSCK(hh_dst, dst, "HASH_SELECT"); \ 1106 | } while (0) 1107 | 1108 | #define HASH_CLEAR(hh,head) \ 1109 | do { \ 1110 | if ((head) != NULL) { \ 1111 | HASH_BLOOM_FREE((head)->hh.tbl); \ 1112 | uthash_free((head)->hh.tbl->buckets, \ 1113 | (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ 1114 | uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ 1115 | (head) = NULL; \ 1116 | } \ 1117 | } while (0) 1118 | 1119 | #define HASH_OVERHEAD(hh,head) \ 1120 | (((head) != NULL) ? ( \ 1121 | (size_t)(((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ 1122 | ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \ 1123 | sizeof(UT_hash_table) + \ 1124 | (HASH_BLOOM_BYTELEN))) : 0U) 1125 | 1126 | #ifdef NO_DECLTYPE 1127 | #define HASH_ITER(hh,head,el,tmp) \ 1128 | for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \ 1129 | (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL))) 1130 | #else 1131 | #define HASH_ITER(hh,head,el,tmp) \ 1132 | for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \ 1133 | (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL))) 1134 | #endif 1135 | 1136 | /* obtain a count of items in the hash */ 1137 | #define HASH_COUNT(head) HASH_CNT(hh,head) 1138 | #define HASH_CNT(hh,head) ((head != NULL)?((head)->hh.tbl->num_items):0U) 1139 | 1140 | typedef struct UT_hash_bucket { 1141 | struct UT_hash_handle *hh_head; 1142 | unsigned count; 1143 | 1144 | /* expand_mult is normally set to 0. In this situation, the max chain length 1145 | * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If 1146 | * the bucket's chain exceeds this length, bucket expansion is triggered). 1147 | * However, setting expand_mult to a non-zero value delays bucket expansion 1148 | * (that would be triggered by additions to this particular bucket) 1149 | * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. 1150 | * (The multiplier is simply expand_mult+1). The whole idea of this 1151 | * multiplier is to reduce bucket expansions, since they are expensive, in 1152 | * situations where we know that a particular bucket tends to be overused. 1153 | * It is better to let its chain length grow to a longer yet-still-bounded 1154 | * value, than to do an O(n) bucket expansion too often. 1155 | */ 1156 | unsigned expand_mult; 1157 | 1158 | } UT_hash_bucket; 1159 | 1160 | /* random signature used only to find hash tables in external analysis */ 1161 | #define HASH_SIGNATURE 0xa0111fe1u 1162 | #define HASH_BLOOM_SIGNATURE 0xb12220f2u 1163 | 1164 | typedef struct UT_hash_table { 1165 | UT_hash_bucket *buckets; 1166 | unsigned num_buckets, log2_num_buckets; 1167 | unsigned num_items; 1168 | struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ 1169 | ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ 1170 | 1171 | /* in an ideal situation (all buckets used equally), no bucket would have 1172 | * more than ceil(#items/#buckets) items. that's the ideal chain length. */ 1173 | unsigned ideal_chain_maxlen; 1174 | 1175 | /* nonideal_items is the number of items in the hash whose chain position 1176 | * exceeds the ideal chain maxlen. these items pay the penalty for an uneven 1177 | * hash distribution; reaching them in a chain traversal takes >ideal steps */ 1178 | unsigned nonideal_items; 1179 | 1180 | /* ineffective expands occur when a bucket doubling was performed, but 1181 | * afterward, more than half the items in the hash had nonideal chain 1182 | * positions. If this happens on two consecutive expansions we inhibit any 1183 | * further expansion, as it's not helping; this happens when the hash 1184 | * function isn't a good fit for the key domain. When expansion is inhibited 1185 | * the hash will still work, albeit no longer in constant time. */ 1186 | unsigned ineff_expands, noexpand; 1187 | 1188 | uint32_t signature; /* used only to find hash tables in external analysis */ 1189 | #ifdef HASH_BLOOM 1190 | uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ 1191 | uint8_t *bloom_bv; 1192 | uint8_t bloom_nbits; 1193 | #endif 1194 | 1195 | } UT_hash_table; 1196 | 1197 | typedef struct UT_hash_handle { 1198 | struct UT_hash_table *tbl; 1199 | void *prev; /* prev element in app order */ 1200 | void *next; /* next element in app order */ 1201 | struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ 1202 | struct UT_hash_handle *hh_next; /* next hh in bucket order */ 1203 | void *key; /* ptr to enclosing struct's key */ 1204 | unsigned keylen; /* enclosing struct's key len */ 1205 | unsigned hashv; /* result of hash-fcn(key) */ 1206 | } UT_hash_handle; 1207 | 1208 | #endif /* UTHASH_H */ 1209 | --------------------------------------------------------------------------------