Repository files navigation

Overview

XHTTP is a tunneling proxy system that establishes encrypted TCP connections between a local client and a remote server through a custom protocol. The system consists of two executables:

  • xhttp_c (Client): Runs on the local machine, listening on port 8090 for incoming connections from local applications (browsers, HTTP clients, etc.)
  • xhttp_s (Server): Runs on a remote machine, listening on port 8080 for connections from xhttp_c clients and forwarding traffic to an upstream proxy (default: localhost:3128)

Purpose: XHTTP enables secure, compressed communication through potentially restrictive networks by:

  1. Encapsulating traffic in a custom packet protocol
  2. Compressing data using zlib for bandwidth efficiency
  3. Encrypting traffic with AES-256 GCM for confidentiality and integrity
  4. Disguising encrypted packets with HTTP-like headers for potential firewall/proxy traversal

Users: Developers or network administrators who need to tunnel TCP traffic through monitored or restricted networks while maintaining security and optimizing bandwidth.

Use Case Example: A local application connects to localhost:8090 → xhttp_c encrypts and forwards to remote server at 167.71.189.187:8080 → xhttp_s decrypts and forwards to squid proxy at localhost:3128 → reaches final destination.


Project Organization

Build System Architecture

The project uses CMake as its build system, configured in CMakeLists.txt:

xhttp/
├── CMakeLists.txt # Defines build targets and dependencies
├── CMakePresets.json # CMake configuration presets
├── client/ # Client executable source
│ └── Client.c # Main client entry point and threading logic
├── server/ # Server executable source
│ └── Server.c # Main server entry point and threading logic
├── Encoder/ # Packet encoding/decoding
│ └── Encoder.c # BufferEncode/Decode, compression, encryption
├── crypt/ # Cryptography implementations
│ └── AES.c # AES-256 GCM encryption/decryption
├── logger/ # Logging subsystem
│ └── Logger.c # Error logging functions
├── utils/ # Networking utilities
│ ├── TcpClientUtility.c # Client socket creation and connection
│ ├── TcpServerUtility.c # Server socket creation and listening
│ ├── SocketUtility.c # Non-blocking socket configuration
│ ├── AddressUtility.c # Socket address printing
│ ├── Compressor.c # zlib compression/decompression
│ └── Utils.c # HTTP header generation
├── includes/ # Header files (public APIs)
│ ├── packet.h # Packet structure and flags
│ ├── utils.h # Utility function declarations
│ ├── crypt.h # Cryptography API and key definition
│ └── logger.h # Logging function declarations
└── tests/ # Test executables
└── test.c # Integration test for encoding/decoding

Core Systems

1. Client System (client/Client.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8090) for local connections
    • Spawns a new pthread for each accepted connection
    • Each thread establishes connection to PROXY_HOST:PROXY_PORT (167.71.189.187:8080)
    • Bidirectionally forwards data with custom protocol encoding
    • Uses select() for non-blocking I/O multiplexing

2. Server System (server/Server.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8080) for incoming xhttp_c connections
    • Spawns pthread per client connection
    • Establishes outbound connection to PROXY_HOST:PROXY_PORT (localhost:3128)
    • Decodes incoming packets and forwards raw data to upstream proxy
    • Encodes upstream responses back into packet format

3. Packet Protocol Layer (includes/packet.h, Encoder/Encoder.c)

  • Key Structure: struct Packet
    structPacket {
    uint32_tmsgLength; // Length of message payloaduint32_tstructSize; // Size of Packet structureuint8_tflag; // Protocol flags (compression, request/response, etc.)uint8_tmessage[BUFSIZ*3]; // Actual payload (max ~24KB)
    };
  • Encoding Pipeline: Packet → Serialize → Compress (zlib) → Encrypt (AES-GCM) → Frame (40-byte header)
  • Key Functions:
    • BufferEncode(): Serializes, compresses, encrypts packet
    • BufferDecode(): Decrypts, decompresses, deserializes packet
    • FrameToSocket(): Adds 40-byte header and sends to socket
    • FrameFromSocket(): Receives framed data and extracts payload

4. Cryptography System (crypt/AES.c, includes/crypt.h)

  • Algorithm: AES-256 GCM (authenticated encryption)
  • Key Management: Static key AES_CRYPT_KEY hardcoded in includes/crypt.h
  • Key Parameters:
    • Key size: 32 bytes (256 bits)
    • IV size: 12 bytes (96 bits, randomly generated per operation)
    • Auth tag size: 16 bytes
  • Functions:
    • aes_gcm_encrypt(): Encrypts plaintext, returns ciphertext with IV prepended
    • aes_gcm_decrypt(): Decrypts ciphertext, verifies authentication tag

5. Compression System (utils/Compressor.c)

  • Library: zlib
  • Configuration: Z_BEST_COMPRESSION level
  • Functions:
    • zlib_compress_dynamic(): Dynamically allocates compressed buffer
    • zlib_decompress_dynamic(): Dynamically allocates decompressed buffer

6. Network Utilities (utils/)

  • TCP Client: CreateClientSocket() - Establishes outbound connections
  • TCP Server: CreateServerSocket() - Creates listening sockets, AcceptTCPConnection() - Accepts clients
  • Socket Configuration: set_nonblocking_socket() - Enables non-blocking I/O
  • Options Set: SO_REUSEPORT, TCP_NODELAY

7. Logging System (logger/Logger.c, includes/logger.h)

  • Non-fatal: LogErrorWithReason() - Logs error, continues execution
  • Fatal (custom): LogErrorWithReasonX() - Logs error, calls exit(EXIT_FAILURE)
  • Fatal (system): LogSystemError() - Uses perror(), calls exit(EXIT_FAILURE)
  • All output goes to stdout

Threading Model

Both client and server use identical concurrency patterns:

  1. Main Thread: Runs accept() loop in select() for new connections
  2. Worker Threads: Spawned via pthread_create() and immediately detached with pthread_detach()
  3. Per-Thread Resources: Each thread manages two sockets (local + remote) with select() multiplexing
  4. Lifecycle: Threads self-terminate when either socket closes; no coordination with main thread

Data Flow

Client → Server Direction:

Local App → [Raw TCP Data] → Client.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket (40-byte header) → Network → Server.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Proxy

Server → Client Direction:

Proxy Response → Server.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket → Network → Client.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Local App

Build Targets

  • xhttp_c: Client executable (links all utilities + client/Client.c)
  • xhttp_s: Server executable (links all utilities + server/Server.c)
  • test_c: Test executable for encoding/decoding verification

External Dependencies

  • ZLIB: Data compression (zlib_compress_dynamic, zlib_decompress_dynamic)
  • OpenSSL::Crypto: AES-GCM cryptographic operations
  • OpenSSL::SSL: TLS/SSL support (linked but usage not visible in main code)
  • POSIX Threads: Multi-threading (pthread_create, pthread_detach)
  • POSIX Sockets: Network I/O (socket, bind, listen, accept, connect, select)

Configuration

Client Configuration (client/Client.c):

#defineDEF_LOCAL_PORT "8090" // Local listening port
#definePROXY_HOST "167.71.189.187" // Remote server IP
#definePROXY_PORT "8080" // Remote server port

Server Configuration (server/Server.c):

#defineDEF_LOCAL_PORT "8080" // Server listening port
#definePROXY_HOST "localhost" // Upstream proxy host
#definePROXY_PORT "3128" // Upstream proxy port (Squid default)

Glossary of Codebase-Specific Terms

Core Architecture Terms

  1. xhttp_c: Client executable that accepts local connections and tunnels them through encrypted protocol to xhttp_s. Built from client/Client.c. Listens on port 8090.

  2. xhttp_s: Server executable that receives encrypted connections from xhttp_c and forwards to upstream proxy. Built from server/Server.c. Listens on port 8080.

  3. Packet: Core data structure (struct Packet in includes/packet.h) containing msgLength, structSize, flag, and message[BUFSIZ*3]. Represents encapsulated application data.

  4. handle_client_thread: Function in both Client.c and Server.c that manages bidirectional data forwarding for a single connection. Each runs in a detached pthread.

  5. DEF_LOCAL_PORT: Port configuration macro. "8090" for client, "8080" for server. Defined in respective main files.

  6. PROXY_HOST/PROXY_PORT: Destination configuration. Client: 167.71.189.187:8080 (xhttp_s). Server: localhost:3128 (Squid proxy).

Protocol and Encoding

  1. BufferEncode: Function in Encoder/Encoder.c that serializes Packet, compresses with zlib, encrypts with AES-GCM. Returns uint8_t* buffer.

  2. BufferDecode: Function in Encoder/Encoder.c that reverses BufferEncode: decrypts, decompresses, deserializes into Packet structure.

  3. FrameToSocket: Function in Encoder/Encoder.c that prepends 40-byte header to data and writes to socket. Used for protocol framing.

  4. FrameFromSocket: Function in Encoder/Encoder.c that reads framed data from socket, skipping 40-byte header. Returns payload bytes.

  5. HEADER_SIZE: Constant defined as 40 in Encoder/Encoder.c. Size of HTTP-like header prepended to all transmitted packets.

  6. msgLength: Field in struct Packet storing length of actual message payload. Used for variable-length message handling.

  7. structSize: Field in struct Packet storing sizeof(struct Packet). Enables version compatibility checks or dynamic structure handling.

  8. flag: Single-byte field in struct Packet for protocol flags (COMPRESSION_FLAG, IS_REQUEST_FLAG, etc.). Defined in includes/packet.h.

Packet Flags

  1. COMPRESSION_FLAG: Value 0x0100 in includes/packet.h. Indicates packet payload is compressed. Set during encoding pipeline.

  2. IS_REQUEST_FLAG: Value 0x0500. Marks packet as client request. Used for protocol-level distinction between request/response.

  3. IS_RESPONSE_FLAG: Value 0x0300. Marks packet as server response. Complementary to IS_REQUEST_FLAG.

  4. CONTINUATION_FLAG: Value 0x0200. Indicates packet is part of multi-packet message sequence. For handling large payloads.

  5. IS_CHUNK_FLAG: Value 0x0400. Denotes packet contains data chunk, possibly for streaming or progressive transfer.

Cryptography

  1. AES_CRYPT_KEY: Static string constant in includes/crypt.h containing hardcoded 256-bit encryption key. Used by all AES operations.

  2. aes_gcm_encrypt: Function in crypt/AES.c that encrypts plaintext using AES-256 GCM. Generates random IV, prepends to ciphertext.

  3. aes_gcm_decrypt: Function in crypt/AES.c that decrypts ciphertext, extracts IV, verifies authentication tag. Returns -1 on tag mismatch.

  4. AES_KEY_SIZE: Constant 32 bytes (256 bits) in crypt/AES.c. Defines AES key length.

  5. AES_IV_SIZE: Constant 12 bytes (96 bits) in crypt/AES.c. Initialization vector size for GCM mode.

  6. TAG_SIZE: Constant 16 bytes in crypt/AES.c. Authentication tag size for GCM authenticated encryption.

Compression

  1. zlib_compress_dynamic: Function in utils/Compressor.c that compresses buffer using zlib Z_BEST_COMPRESSION. Dynamically allocates output.

  2. zlib_decompress_dynamic: Function in utils/Compressor.c that decompresses zlib buffer. Dynamically resizes output as needed.

  3. Z_BEST_COMPRESSION: zlib constant used in compression initialization. Maximizes compression ratio at cost of CPU.

Networking Utilities

  1. CreateClientSocket: Function in utils/TcpClientUtility.c that resolves hostname, creates socket, sets SO_REUSEPORT/TCP_NODELAY, connects.

  2. CreateServerSocket: Function in utils/TcpServerUtility.c that creates, binds, and sets socket to listen with MAX_CONNECTED_SOCKS backlog.

  3. AcceptTCPConnection: Function in utils/TcpServerUtility.c that monitors server socket with select() and accepts new client connections.

  4. set_nonblocking_socket: Function in utils/SocketUtility.c that uses fcntl() to set O_NONBLOCK flag on socket descriptor.

  5. MAX_CONNECTED_SOCKS: Constant 10 in utils/TcpServerUtility.c. Backlog parameter for listen() call, limits pending connection queue.

  6. STREAM_BUF_SIZE: Macro BUFSIZ * 3 in includes/utils.h. Size of I/O buffers (~24KB on most systems). Used for socket read/write.

  7. printSocketAddress: Function in utils/AddressUtility.c that formats sockaddr to human-readable IP:port string. Used for logging.

  8. generate_http_header: Function in utils/Utils.c that creates 40-byte HTTP-like header string. Used to disguise packets.

Logging

  1. LogErrorWithReason: Function in logger/Logger.c for non-fatal error logging. Outputs to stdout, continues execution.

  2. LogErrorWithReasonX: Function in logger/Logger.c for fatal errors. Logs to stdout, calls exit(EXIT_FAILURE). 'X' suffix means "exit".

  3. LogSystemError: Function in logger/Logger.c for system call failures. Uses perror(), then exits. For errno-based errors.

Threading and I/O

  1. serverSock: Global int in Client.c/Server.c. File descriptor for main listening socket created by CreateServerSocket().

  2. clntSock: Local variable in thread functions. File descriptor for accepted client connection from AcceptTCPConnection().

  3. proxySocket: Local variable in handle_client_thread. File descriptor for outbound connection to next hop (xhttp_s or Squid).

  4. client_buf/proxy_buf: Local buffers of STREAM_BUF_SIZE in thread functions. Used for reading data from respective sockets.

  5. fd_set: Standard type used with select() to monitor multiple socket descriptors. Declared as read_fd_set in thread loops.

  6. cleanup_handler: Signal handler function in Client.c/Server.c. Registered for SIGINT/SIGTERM to call cleanup() on shutdown.

Build System

  1. CMakePresets.json: File defining CMake configuration presets for build, test, configure stages. Standardizes development environments.

  2. XHTTP: Project namespace/prefix. Appears in header guards (XHTTP_PACKET_H, XHTTP_UTILS_H) and system identifier.

  3. temporal_buffer: Local variable in Encoder.c encoding/decoding functions. Intermediate buffer between compression and encryption stages.

  4. HTTP_HEADER_TEMPLATE: String constant in includes/packet.h: "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n". Template for generate_http_header().

  5. MIN_CONTENT_LENGTH/MAX_CONTENT_LENGTH: Constants 100/999 in includes/packet.h. Constraints for HTTP header content-length field.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Overview

XHTTP is a tunneling proxy system that establishes encrypted TCP connections between a local client and a remote server through a custom protocol. The system consists of two executables:

  • xhttp_c (Client): Runs on the local machine, listening on port 8090 for incoming connections from local applications (browsers, HTTP clients, etc.)
  • xhttp_s (Server): Runs on a remote machine, listening on port 8080 for connections from xhttp_c clients and forwarding traffic to an upstream proxy (default: localhost:3128)

Purpose: XHTTP enables secure, compressed communication through potentially restrictive networks by:

  1. Encapsulating traffic in a custom packet protocol
  2. Compressing data using zlib for bandwidth efficiency
  3. Encrypting traffic with AES-256 GCM for confidentiality and integrity
  4. Disguising encrypted packets with HTTP-like headers for potential firewall/proxy traversal

Users: Developers or network administrators who need to tunnel TCP traffic through monitored or restricted networks while maintaining security and optimizing bandwidth.

Use Case Example: A local application connects to localhost:8090 → xhttp_c encrypts and forwards to remote server at 167.71.189.187:8080 → xhttp_s decrypts and forwards to squid proxy at localhost:3128 → reaches final destination.


Project Organization

Build System Architecture

The project uses CMake as its build system, configured in CMakeLists.txt:

xhttp/
├── CMakeLists.txt # Defines build targets and dependencies
├── CMakePresets.json # CMake configuration presets
├── client/ # Client executable source
│ └── Client.c # Main client entry point and threading logic
├── server/ # Server executable source
│ └── Server.c # Main server entry point and threading logic
├── Encoder/ # Packet encoding/decoding
│ └── Encoder.c # BufferEncode/Decode, compression, encryption
├── crypt/ # Cryptography implementations
│ └── AES.c # AES-256 GCM encryption/decryption
├── logger/ # Logging subsystem
│ └── Logger.c # Error logging functions
├── utils/ # Networking utilities
│ ├── TcpClientUtility.c # Client socket creation and connection
│ ├── TcpServerUtility.c # Server socket creation and listening
│ ├── SocketUtility.c # Non-blocking socket configuration
│ ├── AddressUtility.c # Socket address printing
│ ├── Compressor.c # zlib compression/decompression
│ └── Utils.c # HTTP header generation
├── includes/ # Header files (public APIs)
│ ├── packet.h # Packet structure and flags
│ ├── utils.h # Utility function declarations
│ ├── crypt.h # Cryptography API and key definition
│ └── logger.h # Logging function declarations
└── tests/ # Test executables
└── test.c # Integration test for encoding/decoding

Core Systems

1. Client System (client/Client.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8090) for local connections
    • Spawns a new pthread for each accepted connection
    • Each thread establishes connection to PROXY_HOST:PROXY_PORT (167.71.189.187:8080)
    • Bidirectionally forwards data with custom protocol encoding
    • Uses select() for non-blocking I/O multiplexing

2. Server System (server/Server.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8080) for incoming xhttp_c connections
    • Spawns pthread per client connection
    • Establishes outbound connection to PROXY_HOST:PROXY_PORT (localhost:3128)
    • Decodes incoming packets and forwards raw data to upstream proxy
    • Encodes upstream responses back into packet format

3. Packet Protocol Layer (includes/packet.h, Encoder/Encoder.c)

  • Key Structure: struct Packet
    structPacket {
    uint32_tmsgLength; // Length of message payloaduint32_tstructSize; // Size of Packet structureuint8_tflag; // Protocol flags (compression, request/response, etc.)uint8_tmessage[BUFSIZ*3]; // Actual payload (max ~24KB)
    };
  • Encoding Pipeline: Packet → Serialize → Compress (zlib) → Encrypt (AES-GCM) → Frame (40-byte header)
  • Key Functions:
    • BufferEncode(): Serializes, compresses, encrypts packet
    • BufferDecode(): Decrypts, decompresses, deserializes packet
    • FrameToSocket(): Adds 40-byte header and sends to socket
    • FrameFromSocket(): Receives framed data and extracts payload

4. Cryptography System (crypt/AES.c, includes/crypt.h)

  • Algorithm: AES-256 GCM (authenticated encryption)
  • Key Management: Static key AES_CRYPT_KEY hardcoded in includes/crypt.h
  • Key Parameters:
    • Key size: 32 bytes (256 bits)
    • IV size: 12 bytes (96 bits, randomly generated per operation)
    • Auth tag size: 16 bytes
  • Functions:
    • aes_gcm_encrypt(): Encrypts plaintext, returns ciphertext with IV prepended
    • aes_gcm_decrypt(): Decrypts ciphertext, verifies authentication tag

5. Compression System (utils/Compressor.c)

  • Library: zlib
  • Configuration: Z_BEST_COMPRESSION level
  • Functions:
    • zlib_compress_dynamic(): Dynamically allocates compressed buffer
    • zlib_decompress_dynamic(): Dynamically allocates decompressed buffer

6. Network Utilities (utils/)

  • TCP Client: CreateClientSocket() - Establishes outbound connections
  • TCP Server: CreateServerSocket() - Creates listening sockets, AcceptTCPConnection() - Accepts clients
  • Socket Configuration: set_nonblocking_socket() - Enables non-blocking I/O
  • Options Set: SO_REUSEPORT, TCP_NODELAY

7. Logging System (logger/Logger.c, includes/logger.h)

  • Non-fatal: LogErrorWithReason() - Logs error, continues execution
  • Fatal (custom): LogErrorWithReasonX() - Logs error, calls exit(EXIT_FAILURE)
  • Fatal (system): LogSystemError() - Uses perror(), calls exit(EXIT_FAILURE)
  • All output goes to stdout

Threading Model

Both client and server use identical concurrency patterns:

  1. Main Thread: Runs accept() loop in select() for new connections
  2. Worker Threads: Spawned via pthread_create() and immediately detached with pthread_detach()
  3. Per-Thread Resources: Each thread manages two sockets (local + remote) with select() multiplexing
  4. Lifecycle: Threads self-terminate when either socket closes; no coordination with main thread

Data Flow

Client → Server Direction:

Local App → [Raw TCP Data] → Client.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket (40-byte header) → Network → Server.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Proxy

Server → Client Direction:

Proxy Response → Server.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket → Network → Client.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Local App

Build Targets

  • xhttp_c: Client executable (links all utilities + client/Client.c)
  • xhttp_s: Server executable (links all utilities + server/Server.c)
  • test_c: Test executable for encoding/decoding verification

External Dependencies

  • ZLIB: Data compression (zlib_compress_dynamic, zlib_decompress_dynamic)
  • OpenSSL::Crypto: AES-GCM cryptographic operations
  • OpenSSL::SSL: TLS/SSL support (linked but usage not visible in main code)
  • POSIX Threads: Multi-threading (pthread_create, pthread_detach)
  • POSIX Sockets: Network I/O (socket, bind, listen, accept, connect, select)

Configuration

Client Configuration (client/Client.c):

#defineDEF_LOCAL_PORT "8090" // Local listening port
#definePROXY_HOST "167.71.189.187" // Remote server IP
#definePROXY_PORT "8080" // Remote server port

Server Configuration (server/Server.c):

#defineDEF_LOCAL_PORT "8080" // Server listening port
#definePROXY_HOST "localhost" // Upstream proxy host
#definePROXY_PORT "3128" // Upstream proxy port (Squid default)

Glossary of Codebase-Specific Terms

Core Architecture Terms

  1. xhttp_c: Client executable that accepts local connections and tunnels them through encrypted protocol to xhttp_s. Built from client/Client.c. Listens on port 8090.

  2. xhttp_s: Server executable that receives encrypted connections from xhttp_c and forwards to upstream proxy. Built from server/Server.c. Listens on port 8080.

  3. Packet: Core data structure (struct Packet in includes/packet.h) containing msgLength, structSize, flag, and message[BUFSIZ*3]. Represents encapsulated application data.

  4. handle_client_thread: Function in both Client.c and Server.c that manages bidirectional data forwarding for a single connection. Each runs in a detached pthread.

  5. DEF_LOCAL_PORT: Port configuration macro. "8090" for client, "8080" for server. Defined in respective main files.

  6. PROXY_HOST/PROXY_PORT: Destination configuration. Client: 167.71.189.187:8080 (xhttp_s). Server: localhost:3128 (Squid proxy).

Protocol and Encoding

  1. BufferEncode: Function in Encoder/Encoder.c that serializes Packet, compresses with zlib, encrypts with AES-GCM. Returns uint8_t* buffer.

  2. BufferDecode: Function in Encoder/Encoder.c that reverses BufferEncode: decrypts, decompresses, deserializes into Packet structure.

  3. FrameToSocket: Function in Encoder/Encoder.c that prepends 40-byte header to data and writes to socket. Used for protocol framing.

  4. FrameFromSocket: Function in Encoder/Encoder.c that reads framed data from socket, skipping 40-byte header. Returns payload bytes.

  5. HEADER_SIZE: Constant defined as 40 in Encoder/Encoder.c. Size of HTTP-like header prepended to all transmitted packets.

  6. msgLength: Field in struct Packet storing length of actual message payload. Used for variable-length message handling.

  7. structSize: Field in struct Packet storing sizeof(struct Packet). Enables version compatibility checks or dynamic structure handling.

  8. flag: Single-byte field in struct Packet for protocol flags (COMPRESSION_FLAG, IS_REQUEST_FLAG, etc.). Defined in includes/packet.h.

Packet Flags

  1. COMPRESSION_FLAG: Value 0x0100 in includes/packet.h. Indicates packet payload is compressed. Set during encoding pipeline.

  2. IS_REQUEST_FLAG: Value 0x0500. Marks packet as client request. Used for protocol-level distinction between request/response.

  3. IS_RESPONSE_FLAG: Value 0x0300. Marks packet as server response. Complementary to IS_REQUEST_FLAG.

  4. CONTINUATION_FLAG: Value 0x0200. Indicates packet is part of multi-packet message sequence. For handling large payloads.

  5. IS_CHUNK_FLAG: Value 0x0400. Denotes packet contains data chunk, possibly for streaming or progressive transfer.

Cryptography

  1. AES_CRYPT_KEY: Static string constant in includes/crypt.h containing hardcoded 256-bit encryption key. Used by all AES operations.

  2. aes_gcm_encrypt: Function in crypt/AES.c that encrypts plaintext using AES-256 GCM. Generates random IV, prepends to ciphertext.

  3. aes_gcm_decrypt: Function in crypt/AES.c that decrypts ciphertext, extracts IV, verifies authentication tag. Returns -1 on tag mismatch.

  4. AES_KEY_SIZE: Constant 32 bytes (256 bits) in crypt/AES.c. Defines AES key length.

  5. AES_IV_SIZE: Constant 12 bytes (96 bits) in crypt/AES.c. Initialization vector size for GCM mode.

  6. TAG_SIZE: Constant 16 bytes in crypt/AES.c. Authentication tag size for GCM authenticated encryption.

Compression

  1. zlib_compress_dynamic: Function in utils/Compressor.c that compresses buffer using zlib Z_BEST_COMPRESSION. Dynamically allocates output.

  2. zlib_decompress_dynamic: Function in utils/Compressor.c that decompresses zlib buffer. Dynamically resizes output as needed.

  3. Z_BEST_COMPRESSION: zlib constant used in compression initialization. Maximizes compression ratio at cost of CPU.

Networking Utilities

  1. CreateClientSocket: Function in utils/TcpClientUtility.c that resolves hostname, creates socket, sets SO_REUSEPORT/TCP_NODELAY, connects.

  2. CreateServerSocket: Function in utils/TcpServerUtility.c that creates, binds, and sets socket to listen with MAX_CONNECTED_SOCKS backlog.

  3. AcceptTCPConnection: Function in utils/TcpServerUtility.c that monitors server socket with select() and accepts new client connections.

  4. set_nonblocking_socket: Function in utils/SocketUtility.c that uses fcntl() to set O_NONBLOCK flag on socket descriptor.

  5. MAX_CONNECTED_SOCKS: Constant 10 in utils/TcpServerUtility.c. Backlog parameter for listen() call, limits pending connection queue.

  6. STREAM_BUF_SIZE: Macro BUFSIZ * 3 in includes/utils.h. Size of I/O buffers (~24KB on most systems). Used for socket read/write.

  7. printSocketAddress: Function in utils/AddressUtility.c that formats sockaddr to human-readable IP:port string. Used for logging.

  8. generate_http_header: Function in utils/Utils.c that creates 40-byte HTTP-like header string. Used to disguise packets.

Logging

  1. LogErrorWithReason: Function in logger/Logger.c for non-fatal error logging. Outputs to stdout, continues execution.

  2. LogErrorWithReasonX: Function in logger/Logger.c for fatal errors. Logs to stdout, calls exit(EXIT_FAILURE). 'X' suffix means "exit".

  3. LogSystemError: Function in logger/Logger.c for system call failures. Uses perror(), then exits. For errno-based errors.

Threading and I/O

  1. serverSock: Global int in Client.c/Server.c. File descriptor for main listening socket created by CreateServerSocket().

  2. clntSock: Local variable in thread functions. File descriptor for accepted client connection from AcceptTCPConnection().

  3. proxySocket: Local variable in handle_client_thread. File descriptor for outbound connection to next hop (xhttp_s or Squid).

  4. client_buf/proxy_buf: Local buffers of STREAM_BUF_SIZE in thread functions. Used for reading data from respective sockets.

  5. fd_set: Standard type used with select() to monitor multiple socket descriptors. Declared as read_fd_set in thread loops.

  6. cleanup_handler: Signal handler function in Client.c/Server.c. Registered for SIGINT/SIGTERM to call cleanup() on shutdown.

Build System

  1. CMakePresets.json: File defining CMake configuration presets for build, test, configure stages. Standardizes development environments.

  2. XHTTP: Project namespace/prefix. Appears in header guards (XHTTP_PACKET_H, XHTTP_UTILS_H) and system identifier.

  3. temporal_buffer: Local variable in Encoder.c encoding/decoding functions. Intermediate buffer between compression and encryption stages.

  4. HTTP_HEADER_TEMPLATE: String constant in includes/packet.h: "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n". Template for generate_http_header().

  5. MIN_CONTENT_LENGTH/MAX_CONTENT_LENGTH: Constants 100/999 in includes/packet.h. Constraints for HTTP header content-length field.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Overview

XHTTP is a tunneling proxy system that establishes encrypted TCP connections between a local client and a remote server through a custom protocol. The system consists of two executables:

  • xhttp_c (Client): Runs on the local machine, listening on port 8090 for incoming connections from local applications (browsers, HTTP clients, etc.)
  • xhttp_s (Server): Runs on a remote machine, listening on port 8080 for connections from xhttp_c clients and forwarding traffic to an upstream proxy (default: localhost:3128)

Purpose: XHTTP enables secure, compressed communication through potentially restrictive networks by:

  1. Encapsulating traffic in a custom packet protocol
  2. Compressing data using zlib for bandwidth efficiency
  3. Encrypting traffic with AES-256 GCM for confidentiality and integrity
  4. Disguising encrypted packets with HTTP-like headers for potential firewall/proxy traversal

Users: Developers or network administrators who need to tunnel TCP traffic through monitored or restricted networks while maintaining security and optimizing bandwidth.

Use Case Example: A local application connects to localhost:8090 → xhttp_c encrypts and forwards to remote server at 167.71.189.187:8080 → xhttp_s decrypts and forwards to squid proxy at localhost:3128 → reaches final destination.


Project Organization

Build System Architecture

The project uses CMake as its build system, configured in CMakeLists.txt:

xhttp/
├── CMakeLists.txt # Defines build targets and dependencies
├── CMakePresets.json # CMake configuration presets
├── client/ # Client executable source
│ └── Client.c # Main client entry point and threading logic
├── server/ # Server executable source
│ └── Server.c # Main server entry point and threading logic
├── Encoder/ # Packet encoding/decoding
│ └── Encoder.c # BufferEncode/Decode, compression, encryption
├── crypt/ # Cryptography implementations
│ └── AES.c # AES-256 GCM encryption/decryption
├── logger/ # Logging subsystem
│ └── Logger.c # Error logging functions
├── utils/ # Networking utilities
│ ├── TcpClientUtility.c # Client socket creation and connection
│ ├── TcpServerUtility.c # Server socket creation and listening
│ ├── SocketUtility.c # Non-blocking socket configuration
│ ├── AddressUtility.c # Socket address printing
│ ├── Compressor.c # zlib compression/decompression
│ └── Utils.c # HTTP header generation
├── includes/ # Header files (public APIs)
│ ├── packet.h # Packet structure and flags
│ ├── utils.h # Utility function declarations
│ ├── crypt.h # Cryptography API and key definition
│ └── logger.h # Logging function declarations
└── tests/ # Test executables
└── test.c # Integration test for encoding/decoding

Core Systems

1. Client System (client/Client.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8090) for local connections
    • Spawns a new pthread for each accepted connection
    • Each thread establishes connection to PROXY_HOST:PROXY_PORT (167.71.189.187:8080)
    • Bidirectionally forwards data with custom protocol encoding
    • Uses select() for non-blocking I/O multiplexing

2. Server System (server/Server.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8080) for incoming xhttp_c connections
    • Spawns pthread per client connection
    • Establishes outbound connection to PROXY_HOST:PROXY_PORT (localhost:3128)
    • Decodes incoming packets and forwards raw data to upstream proxy
    • Encodes upstream responses back into packet format

3. Packet Protocol Layer (includes/packet.h, Encoder/Encoder.c)

  • Key Structure: struct Packet
    structPacket {
    uint32_tmsgLength; // Length of message payloaduint32_tstructSize; // Size of Packet structureuint8_tflag; // Protocol flags (compression, request/response, etc.)uint8_tmessage[BUFSIZ*3]; // Actual payload (max ~24KB)
    };
  • Encoding Pipeline: Packet → Serialize → Compress (zlib) → Encrypt (AES-GCM) → Frame (40-byte header)
  • Key Functions:
    • BufferEncode(): Serializes, compresses, encrypts packet
    • BufferDecode(): Decrypts, decompresses, deserializes packet
    • FrameToSocket(): Adds 40-byte header and sends to socket
    • FrameFromSocket(): Receives framed data and extracts payload

4. Cryptography System (crypt/AES.c, includes/crypt.h)

  • Algorithm: AES-256 GCM (authenticated encryption)
  • Key Management: Static key AES_CRYPT_KEY hardcoded in includes/crypt.h
  • Key Parameters:
    • Key size: 32 bytes (256 bits)
    • IV size: 12 bytes (96 bits, randomly generated per operation)
    • Auth tag size: 16 bytes
  • Functions:
    • aes_gcm_encrypt(): Encrypts plaintext, returns ciphertext with IV prepended
    • aes_gcm_decrypt(): Decrypts ciphertext, verifies authentication tag

5. Compression System (utils/Compressor.c)

  • Library: zlib
  • Configuration: Z_BEST_COMPRESSION level
  • Functions:
    • zlib_compress_dynamic(): Dynamically allocates compressed buffer
    • zlib_decompress_dynamic(): Dynamically allocates decompressed buffer

6. Network Utilities (utils/)

  • TCP Client: CreateClientSocket() - Establishes outbound connections
  • TCP Server: CreateServerSocket() - Creates listening sockets, AcceptTCPConnection() - Accepts clients
  • Socket Configuration: set_nonblocking_socket() - Enables non-blocking I/O
  • Options Set: SO_REUSEPORT, TCP_NODELAY

7. Logging System (logger/Logger.c, includes/logger.h)

  • Non-fatal: LogErrorWithReason() - Logs error, continues execution
  • Fatal (custom): LogErrorWithReasonX() - Logs error, calls exit(EXIT_FAILURE)
  • Fatal (system): LogSystemError() - Uses perror(), calls exit(EXIT_FAILURE)
  • All output goes to stdout

Threading Model

Both client and server use identical concurrency patterns:

  1. Main Thread: Runs accept() loop in select() for new connections
  2. Worker Threads: Spawned via pthread_create() and immediately detached with pthread_detach()
  3. Per-Thread Resources: Each thread manages two sockets (local + remote) with select() multiplexing
  4. Lifecycle: Threads self-terminate when either socket closes; no coordination with main thread

Data Flow

Client → Server Direction:

Local App → [Raw TCP Data] → Client.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket (40-byte header) → Network → Server.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Proxy

Server → Client Direction:

Proxy Response → Server.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket → Network → Client.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Local App

Build Targets

  • xhttp_c: Client executable (links all utilities + client/Client.c)
  • xhttp_s: Server executable (links all utilities + server/Server.c)
  • test_c: Test executable for encoding/decoding verification

External Dependencies

  • ZLIB: Data compression (zlib_compress_dynamic, zlib_decompress_dynamic)
  • OpenSSL::Crypto: AES-GCM cryptographic operations
  • OpenSSL::SSL: TLS/SSL support (linked but usage not visible in main code)
  • POSIX Threads: Multi-threading (pthread_create, pthread_detach)
  • POSIX Sockets: Network I/O (socket, bind, listen, accept, connect, select)

Configuration

Client Configuration (client/Client.c):

#defineDEF_LOCAL_PORT "8090" // Local listening port
#definePROXY_HOST "167.71.189.187" // Remote server IP
#definePROXY_PORT "8080" // Remote server port

Server Configuration (server/Server.c):

#defineDEF_LOCAL_PORT "8080" // Server listening port
#definePROXY_HOST "localhost" // Upstream proxy host
#definePROXY_PORT "3128" // Upstream proxy port (Squid default)

Glossary of Codebase-Specific Terms

Core Architecture Terms

  1. xhttp_c: Client executable that accepts local connections and tunnels them through encrypted protocol to xhttp_s. Built from client/Client.c. Listens on port 8090.

  2. xhttp_s: Server executable that receives encrypted connections from xhttp_c and forwards to upstream proxy. Built from server/Server.c. Listens on port 8080.

  3. Packet: Core data structure (struct Packet in includes/packet.h) containing msgLength, structSize, flag, and message[BUFSIZ*3]. Represents encapsulated application data.

  4. handle_client_thread: Function in both Client.c and Server.c that manages bidirectional data forwarding for a single connection. Each runs in a detached pthread.

  5. DEF_LOCAL_PORT: Port configuration macro. "8090" for client, "8080" for server. Defined in respective main files.

  6. PROXY_HOST/PROXY_PORT: Destination configuration. Client: 167.71.189.187:8080 (xhttp_s). Server: localhost:3128 (Squid proxy).

Protocol and Encoding

  1. BufferEncode: Function in Encoder/Encoder.c that serializes Packet, compresses with zlib, encrypts with AES-GCM. Returns uint8_t* buffer.

  2. BufferDecode: Function in Encoder/Encoder.c that reverses BufferEncode: decrypts, decompresses, deserializes into Packet structure.

  3. FrameToSocket: Function in Encoder/Encoder.c that prepends 40-byte header to data and writes to socket. Used for protocol framing.

  4. FrameFromSocket: Function in Encoder/Encoder.c that reads framed data from socket, skipping 40-byte header. Returns payload bytes.

  5. HEADER_SIZE: Constant defined as 40 in Encoder/Encoder.c. Size of HTTP-like header prepended to all transmitted packets.

  6. msgLength: Field in struct Packet storing length of actual message payload. Used for variable-length message handling.

  7. structSize: Field in struct Packet storing sizeof(struct Packet). Enables version compatibility checks or dynamic structure handling.

  8. flag: Single-byte field in struct Packet for protocol flags (COMPRESSION_FLAG, IS_REQUEST_FLAG, etc.). Defined in includes/packet.h.

Packet Flags

  1. COMPRESSION_FLAG: Value 0x0100 in includes/packet.h. Indicates packet payload is compressed. Set during encoding pipeline.

  2. IS_REQUEST_FLAG: Value 0x0500. Marks packet as client request. Used for protocol-level distinction between request/response.

  3. IS_RESPONSE_FLAG: Value 0x0300. Marks packet as server response. Complementary to IS_REQUEST_FLAG.

  4. CONTINUATION_FLAG: Value 0x0200. Indicates packet is part of multi-packet message sequence. For handling large payloads.

  5. IS_CHUNK_FLAG: Value 0x0400. Denotes packet contains data chunk, possibly for streaming or progressive transfer.

Cryptography

  1. AES_CRYPT_KEY: Static string constant in includes/crypt.h containing hardcoded 256-bit encryption key. Used by all AES operations.

  2. aes_gcm_encrypt: Function in crypt/AES.c that encrypts plaintext using AES-256 GCM. Generates random IV, prepends to ciphertext.

  3. aes_gcm_decrypt: Function in crypt/AES.c that decrypts ciphertext, extracts IV, verifies authentication tag. Returns -1 on tag mismatch.

  4. AES_KEY_SIZE: Constant 32 bytes (256 bits) in crypt/AES.c. Defines AES key length.

  5. AES_IV_SIZE: Constant 12 bytes (96 bits) in crypt/AES.c. Initialization vector size for GCM mode.

  6. TAG_SIZE: Constant 16 bytes in crypt/AES.c. Authentication tag size for GCM authenticated encryption.

Compression

  1. zlib_compress_dynamic: Function in utils/Compressor.c that compresses buffer using zlib Z_BEST_COMPRESSION. Dynamically allocates output.

  2. zlib_decompress_dynamic: Function in utils/Compressor.c that decompresses zlib buffer. Dynamically resizes output as needed.

  3. Z_BEST_COMPRESSION: zlib constant used in compression initialization. Maximizes compression ratio at cost of CPU.

Networking Utilities

  1. CreateClientSocket: Function in utils/TcpClientUtility.c that resolves hostname, creates socket, sets SO_REUSEPORT/TCP_NODELAY, connects.

  2. CreateServerSocket: Function in utils/TcpServerUtility.c that creates, binds, and sets socket to listen with MAX_CONNECTED_SOCKS backlog.

  3. AcceptTCPConnection: Function in utils/TcpServerUtility.c that monitors server socket with select() and accepts new client connections.

  4. set_nonblocking_socket: Function in utils/SocketUtility.c that uses fcntl() to set O_NONBLOCK flag on socket descriptor.

  5. MAX_CONNECTED_SOCKS: Constant 10 in utils/TcpServerUtility.c. Backlog parameter for listen() call, limits pending connection queue.

  6. STREAM_BUF_SIZE: Macro BUFSIZ * 3 in includes/utils.h. Size of I/O buffers (~24KB on most systems). Used for socket read/write.

  7. printSocketAddress: Function in utils/AddressUtility.c that formats sockaddr to human-readable IP:port string. Used for logging.

  8. generate_http_header: Function in utils/Utils.c that creates 40-byte HTTP-like header string. Used to disguise packets.

Logging

  1. LogErrorWithReason: Function in logger/Logger.c for non-fatal error logging. Outputs to stdout, continues execution.

  2. LogErrorWithReasonX: Function in logger/Logger.c for fatal errors. Logs to stdout, calls exit(EXIT_FAILURE). 'X' suffix means "exit".

  3. LogSystemError: Function in logger/Logger.c for system call failures. Uses perror(), then exits. For errno-based errors.

Threading and I/O

  1. serverSock: Global int in Client.c/Server.c. File descriptor for main listening socket created by CreateServerSocket().

  2. clntSock: Local variable in thread functions. File descriptor for accepted client connection from AcceptTCPConnection().

  3. proxySocket: Local variable in handle_client_thread. File descriptor for outbound connection to next hop (xhttp_s or Squid).

  4. client_buf/proxy_buf: Local buffers of STREAM_BUF_SIZE in thread functions. Used for reading data from respective sockets.

  5. fd_set: Standard type used with select() to monitor multiple socket descriptors. Declared as read_fd_set in thread loops.

  6. cleanup_handler: Signal handler function in Client.c/Server.c. Registered for SIGINT/SIGTERM to call cleanup() on shutdown.

Build System

  1. CMakePresets.json: File defining CMake configuration presets for build, test, configure stages. Standardizes development environments.

  2. XHTTP: Project namespace/prefix. Appears in header guards (XHTTP_PACKET_H, XHTTP_UTILS_H) and system identifier.

  3. temporal_buffer: Local variable in Encoder.c encoding/decoding functions. Intermediate buffer between compression and encryption stages.

  4. HTTP_HEADER_TEMPLATE: String constant in includes/packet.h: "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n". Template for generate_http_header().

  5. MIN_CONTENT_LENGTH/MAX_CONTENT_LENGTH: Constants 100/999 in includes/packet.h. Constraints for HTTP header content-length field.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Overview

XHTTP is a tunneling proxy system that establishes encrypted TCP connections between a local client and a remote server through a custom protocol. The system consists of two executables:

  • xhttp_c (Client): Runs on the local machine, listening on port 8090 for incoming connections from local applications (browsers, HTTP clients, etc.)
  • xhttp_s (Server): Runs on a remote machine, listening on port 8080 for connections from xhttp_c clients and forwarding traffic to an upstream proxy (default: localhost:3128)

Purpose: XHTTP enables secure, compressed communication through potentially restrictive networks by:

  1. Encapsulating traffic in a custom packet protocol
  2. Compressing data using zlib for bandwidth efficiency
  3. Encrypting traffic with AES-256 GCM for confidentiality and integrity
  4. Disguising encrypted packets with HTTP-like headers for potential firewall/proxy traversal

Users: Developers or network administrators who need to tunnel TCP traffic through monitored or restricted networks while maintaining security and optimizing bandwidth.

Use Case Example: A local application connects to localhost:8090 → xhttp_c encrypts and forwards to remote server at 167.71.189.187:8080 → xhttp_s decrypts and forwards to squid proxy at localhost:3128 → reaches final destination.


Project Organization

Build System Architecture

The project uses CMake as its build system, configured in CMakeLists.txt:

xhttp/
├── CMakeLists.txt # Defines build targets and dependencies
├── CMakePresets.json # CMake configuration presets
├── client/ # Client executable source
│ └── Client.c # Main client entry point and threading logic
├── server/ # Server executable source
│ └── Server.c # Main server entry point and threading logic
├── Encoder/ # Packet encoding/decoding
│ └── Encoder.c # BufferEncode/Decode, compression, encryption
├── crypt/ # Cryptography implementations
│ └── AES.c # AES-256 GCM encryption/decryption
├── logger/ # Logging subsystem
│ └── Logger.c # Error logging functions
├── utils/ # Networking utilities
│ ├── TcpClientUtility.c # Client socket creation and connection
│ ├── TcpServerUtility.c # Server socket creation and listening
│ ├── SocketUtility.c # Non-blocking socket configuration
│ ├── AddressUtility.c # Socket address printing
│ ├── Compressor.c # zlib compression/decompression
│ └── Utils.c # HTTP header generation
├── includes/ # Header files (public APIs)
│ ├── packet.h # Packet structure and flags
│ ├── utils.h # Utility function declarations
│ ├── crypt.h # Cryptography API and key definition
│ └── logger.h # Logging function declarations
└── tests/ # Test executables
└── test.c # Integration test for encoding/decoding

Core Systems

1. Client System (client/Client.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8090) for local connections
    • Spawns a new pthread for each accepted connection
    • Each thread establishes connection to PROXY_HOST:PROXY_PORT (167.71.189.187:8080)
    • Bidirectionally forwards data with custom protocol encoding
    • Uses select() for non-blocking I/O multiplexing

2. Server System (server/Server.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8080) for incoming xhttp_c connections
    • Spawns pthread per client connection
    • Establishes outbound connection to PROXY_HOST:PROXY_PORT (localhost:3128)
    • Decodes incoming packets and forwards raw data to upstream proxy
    • Encodes upstream responses back into packet format

3. Packet Protocol Layer (includes/packet.h, Encoder/Encoder.c)

  • Key Structure: struct Packet
    structPacket {
    uint32_tmsgLength; // Length of message payloaduint32_tstructSize; // Size of Packet structureuint8_tflag; // Protocol flags (compression, request/response, etc.)uint8_tmessage[BUFSIZ*3]; // Actual payload (max ~24KB)
    };
  • Encoding Pipeline: Packet → Serialize → Compress (zlib) → Encrypt (AES-GCM) → Frame (40-byte header)
  • Key Functions:
    • BufferEncode(): Serializes, compresses, encrypts packet
    • BufferDecode(): Decrypts, decompresses, deserializes packet
    • FrameToSocket(): Adds 40-byte header and sends to socket
    • FrameFromSocket(): Receives framed data and extracts payload

4. Cryptography System (crypt/AES.c, includes/crypt.h)

  • Algorithm: AES-256 GCM (authenticated encryption)
  • Key Management: Static key AES_CRYPT_KEY hardcoded in includes/crypt.h
  • Key Parameters:
    • Key size: 32 bytes (256 bits)
    • IV size: 12 bytes (96 bits, randomly generated per operation)
    • Auth tag size: 16 bytes
  • Functions:
    • aes_gcm_encrypt(): Encrypts plaintext, returns ciphertext with IV prepended
    • aes_gcm_decrypt(): Decrypts ciphertext, verifies authentication tag

5. Compression System (utils/Compressor.c)

  • Library: zlib
  • Configuration: Z_BEST_COMPRESSION level
  • Functions:
    • zlib_compress_dynamic(): Dynamically allocates compressed buffer
    • zlib_decompress_dynamic(): Dynamically allocates decompressed buffer

6. Network Utilities (utils/)

  • TCP Client: CreateClientSocket() - Establishes outbound connections
  • TCP Server: CreateServerSocket() - Creates listening sockets, AcceptTCPConnection() - Accepts clients
  • Socket Configuration: set_nonblocking_socket() - Enables non-blocking I/O
  • Options Set: SO_REUSEPORT, TCP_NODELAY

7. Logging System (logger/Logger.c, includes/logger.h)

  • Non-fatal: LogErrorWithReason() - Logs error, continues execution
  • Fatal (custom): LogErrorWithReasonX() - Logs error, calls exit(EXIT_FAILURE)
  • Fatal (system): LogSystemError() - Uses perror(), calls exit(EXIT_FAILURE)
  • All output goes to stdout

Threading Model

Both client and server use identical concurrency patterns:

  1. Main Thread: Runs accept() loop in select() for new connections
  2. Worker Threads: Spawned via pthread_create() and immediately detached with pthread_detach()
  3. Per-Thread Resources: Each thread manages two sockets (local + remote) with select() multiplexing
  4. Lifecycle: Threads self-terminate when either socket closes; no coordination with main thread

Data Flow

Client → Server Direction:

Local App → [Raw TCP Data] → Client.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket (40-byte header) → Network → Server.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Proxy

Server → Client Direction:

Proxy Response → Server.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket → Network → Client.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Local App

Build Targets

  • xhttp_c: Client executable (links all utilities + client/Client.c)
  • xhttp_s: Server executable (links all utilities + server/Server.c)
  • test_c: Test executable for encoding/decoding verification

External Dependencies

  • ZLIB: Data compression (zlib_compress_dynamic, zlib_decompress_dynamic)
  • OpenSSL::Crypto: AES-GCM cryptographic operations
  • OpenSSL::SSL: TLS/SSL support (linked but usage not visible in main code)
  • POSIX Threads: Multi-threading (pthread_create, pthread_detach)
  • POSIX Sockets: Network I/O (socket, bind, listen, accept, connect, select)

Configuration

Client Configuration (client/Client.c):

#defineDEF_LOCAL_PORT "8090" // Local listening port
#definePROXY_HOST "167.71.189.187" // Remote server IP
#definePROXY_PORT "8080" // Remote server port

Server Configuration (server/Server.c):

#defineDEF_LOCAL_PORT "8080" // Server listening port
#definePROXY_HOST "localhost" // Upstream proxy host
#definePROXY_PORT "3128" // Upstream proxy port (Squid default)

Glossary of Codebase-Specific Terms

Core Architecture Terms

  1. xhttp_c: Client executable that accepts local connections and tunnels them through encrypted protocol to xhttp_s. Built from client/Client.c. Listens on port 8090.

  2. xhttp_s: Server executable that receives encrypted connections from xhttp_c and forwards to upstream proxy. Built from server/Server.c. Listens on port 8080.

  3. Packet: Core data structure (struct Packet in includes/packet.h) containing msgLength, structSize, flag, and message[BUFSIZ*3]. Represents encapsulated application data.

  4. handle_client_thread: Function in both Client.c and Server.c that manages bidirectional data forwarding for a single connection. Each runs in a detached pthread.

  5. DEF_LOCAL_PORT: Port configuration macro. "8090" for client, "8080" for server. Defined in respective main files.

  6. PROXY_HOST/PROXY_PORT: Destination configuration. Client: 167.71.189.187:8080 (xhttp_s). Server: localhost:3128 (Squid proxy).

Protocol and Encoding

  1. BufferEncode: Function in Encoder/Encoder.c that serializes Packet, compresses with zlib, encrypts with AES-GCM. Returns uint8_t* buffer.

  2. BufferDecode: Function in Encoder/Encoder.c that reverses BufferEncode: decrypts, decompresses, deserializes into Packet structure.

  3. FrameToSocket: Function in Encoder/Encoder.c that prepends 40-byte header to data and writes to socket. Used for protocol framing.

  4. FrameFromSocket: Function in Encoder/Encoder.c that reads framed data from socket, skipping 40-byte header. Returns payload bytes.

  5. HEADER_SIZE: Constant defined as 40 in Encoder/Encoder.c. Size of HTTP-like header prepended to all transmitted packets.

  6. msgLength: Field in struct Packet storing length of actual message payload. Used for variable-length message handling.

  7. structSize: Field in struct Packet storing sizeof(struct Packet). Enables version compatibility checks or dynamic structure handling.

  8. flag: Single-byte field in struct Packet for protocol flags (COMPRESSION_FLAG, IS_REQUEST_FLAG, etc.). Defined in includes/packet.h.

Packet Flags

  1. COMPRESSION_FLAG: Value 0x0100 in includes/packet.h. Indicates packet payload is compressed. Set during encoding pipeline.

  2. IS_REQUEST_FLAG: Value 0x0500. Marks packet as client request. Used for protocol-level distinction between request/response.

  3. IS_RESPONSE_FLAG: Value 0x0300. Marks packet as server response. Complementary to IS_REQUEST_FLAG.

  4. CONTINUATION_FLAG: Value 0x0200. Indicates packet is part of multi-packet message sequence. For handling large payloads.

  5. IS_CHUNK_FLAG: Value 0x0400. Denotes packet contains data chunk, possibly for streaming or progressive transfer.

Cryptography

  1. AES_CRYPT_KEY: Static string constant in includes/crypt.h containing hardcoded 256-bit encryption key. Used by all AES operations.

  2. aes_gcm_encrypt: Function in crypt/AES.c that encrypts plaintext using AES-256 GCM. Generates random IV, prepends to ciphertext.

  3. aes_gcm_decrypt: Function in crypt/AES.c that decrypts ciphertext, extracts IV, verifies authentication tag. Returns -1 on tag mismatch.

  4. AES_KEY_SIZE: Constant 32 bytes (256 bits) in crypt/AES.c. Defines AES key length.

  5. AES_IV_SIZE: Constant 12 bytes (96 bits) in crypt/AES.c. Initialization vector size for GCM mode.

  6. TAG_SIZE: Constant 16 bytes in crypt/AES.c. Authentication tag size for GCM authenticated encryption.

Compression

  1. zlib_compress_dynamic: Function in utils/Compressor.c that compresses buffer using zlib Z_BEST_COMPRESSION. Dynamically allocates output.

  2. zlib_decompress_dynamic: Function in utils/Compressor.c that decompresses zlib buffer. Dynamically resizes output as needed.

  3. Z_BEST_COMPRESSION: zlib constant used in compression initialization. Maximizes compression ratio at cost of CPU.

Networking Utilities

  1. CreateClientSocket: Function in utils/TcpClientUtility.c that resolves hostname, creates socket, sets SO_REUSEPORT/TCP_NODELAY, connects.

  2. CreateServerSocket: Function in utils/TcpServerUtility.c that creates, binds, and sets socket to listen with MAX_CONNECTED_SOCKS backlog.

  3. AcceptTCPConnection: Function in utils/TcpServerUtility.c that monitors server socket with select() and accepts new client connections.

  4. set_nonblocking_socket: Function in utils/SocketUtility.c that uses fcntl() to set O_NONBLOCK flag on socket descriptor.

  5. MAX_CONNECTED_SOCKS: Constant 10 in utils/TcpServerUtility.c. Backlog parameter for listen() call, limits pending connection queue.

  6. STREAM_BUF_SIZE: Macro BUFSIZ * 3 in includes/utils.h. Size of I/O buffers (~24KB on most systems). Used for socket read/write.

  7. printSocketAddress: Function in utils/AddressUtility.c that formats sockaddr to human-readable IP:port string. Used for logging.

  8. generate_http_header: Function in utils/Utils.c that creates 40-byte HTTP-like header string. Used to disguise packets.

Logging

  1. LogErrorWithReason: Function in logger/Logger.c for non-fatal error logging. Outputs to stdout, continues execution.

  2. LogErrorWithReasonX: Function in logger/Logger.c for fatal errors. Logs to stdout, calls exit(EXIT_FAILURE). 'X' suffix means "exit".

  3. LogSystemError: Function in logger/Logger.c for system call failures. Uses perror(), then exits. For errno-based errors.

Threading and I/O

  1. serverSock: Global int in Client.c/Server.c. File descriptor for main listening socket created by CreateServerSocket().

  2. clntSock: Local variable in thread functions. File descriptor for accepted client connection from AcceptTCPConnection().

  3. proxySocket: Local variable in handle_client_thread. File descriptor for outbound connection to next hop (xhttp_s or Squid).

  4. client_buf/proxy_buf: Local buffers of STREAM_BUF_SIZE in thread functions. Used for reading data from respective sockets.

  5. fd_set: Standard type used with select() to monitor multiple socket descriptors. Declared as read_fd_set in thread loops.

  6. cleanup_handler: Signal handler function in Client.c/Server.c. Registered for SIGINT/SIGTERM to call cleanup() on shutdown.

Build System

  1. CMakePresets.json: File defining CMake configuration presets for build, test, configure stages. Standardizes development environments.

  2. XHTTP: Project namespace/prefix. Appears in header guards (XHTTP_PACKET_H, XHTTP_UTILS_H) and system identifier.

  3. temporal_buffer: Local variable in Encoder.c encoding/decoding functions. Intermediate buffer between compression and encryption stages.

  4. HTTP_HEADER_TEMPLATE: String constant in includes/packet.h: "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n". Template for generate_http_header().

  5. MIN_CONTENT_LENGTH/MAX_CONTENT_LENGTH: Constants 100/999 in includes/packet.h. Constraints for HTTP header content-length field.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Overview

XHTTP is a tunneling proxy system that establishes encrypted TCP connections between a local client and a remote server through a custom protocol. The system consists of two executables:

  • xhttp_c (Client): Runs on the local machine, listening on port 8090 for incoming connections from local applications (browsers, HTTP clients, etc.)
  • xhttp_s (Server): Runs on a remote machine, listening on port 8080 for connections from xhttp_c clients and forwarding traffic to an upstream proxy (default: localhost:3128)

Purpose: XHTTP enables secure, compressed communication through potentially restrictive networks by:

  1. Encapsulating traffic in a custom packet protocol
  2. Compressing data using zlib for bandwidth efficiency
  3. Encrypting traffic with AES-256 GCM for confidentiality and integrity
  4. Disguising encrypted packets with HTTP-like headers for potential firewall/proxy traversal

Users: Developers or network administrators who need to tunnel TCP traffic through monitored or restricted networks while maintaining security and optimizing bandwidth.

Use Case Example: A local application connects to localhost:8090 → xhttp_c encrypts and forwards to remote server at 167.71.189.187:8080 → xhttp_s decrypts and forwards to squid proxy at localhost:3128 → reaches final destination.


Project Organization

Build System Architecture

The project uses CMake as its build system, configured in CMakeLists.txt:

xhttp/
├── CMakeLists.txt # Defines build targets and dependencies
├── CMakePresets.json # CMake configuration presets
├── client/ # Client executable source
│ └── Client.c # Main client entry point and threading logic
├── server/ # Server executable source
│ └── Server.c # Main server entry point and threading logic
├── Encoder/ # Packet encoding/decoding
│ └── Encoder.c # BufferEncode/Decode, compression, encryption
├── crypt/ # Cryptography implementations
│ └── AES.c # AES-256 GCM encryption/decryption
├── logger/ # Logging subsystem
│ └── Logger.c # Error logging functions
├── utils/ # Networking utilities
│ ├── TcpClientUtility.c # Client socket creation and connection
│ ├── TcpServerUtility.c # Server socket creation and listening
│ ├── SocketUtility.c # Non-blocking socket configuration
│ ├── AddressUtility.c # Socket address printing
│ ├── Compressor.c # zlib compression/decompression
│ └── Utils.c # HTTP header generation
├── includes/ # Header files (public APIs)
│ ├── packet.h # Packet structure and flags
│ ├── utils.h # Utility function declarations
│ ├── crypt.h # Cryptography API and key definition
│ └── logger.h # Logging function declarations
└── tests/ # Test executables
└── test.c # Integration test for encoding/decoding

Core Systems

1. Client System (client/Client.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8090) for local connections
    • Spawns a new pthread for each accepted connection
    • Each thread establishes connection to PROXY_HOST:PROXY_PORT (167.71.189.187:8080)
    • Bidirectionally forwards data with custom protocol encoding
    • Uses select() for non-blocking I/O multiplexing

2. Server System (server/Server.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8080) for incoming xhttp_c connections
    • Spawns pthread per client connection
    • Establishes outbound connection to PROXY_HOST:PROXY_PORT (localhost:3128)
    • Decodes incoming packets and forwards raw data to upstream proxy
    • Encodes upstream responses back into packet format

3. Packet Protocol Layer (includes/packet.h, Encoder/Encoder.c)

  • Key Structure: struct Packet
    structPacket {
    uint32_tmsgLength; // Length of message payloaduint32_tstructSize; // Size of Packet structureuint8_tflag; // Protocol flags (compression, request/response, etc.)uint8_tmessage[BUFSIZ*3]; // Actual payload (max ~24KB)
    };
  • Encoding Pipeline: Packet → Serialize → Compress (zlib) → Encrypt (AES-GCM) → Frame (40-byte header)
  • Key Functions:
    • BufferEncode(): Serializes, compresses, encrypts packet
    • BufferDecode(): Decrypts, decompresses, deserializes packet
    • FrameToSocket(): Adds 40-byte header and sends to socket
    • FrameFromSocket(): Receives framed data and extracts payload

4. Cryptography System (crypt/AES.c, includes/crypt.h)

  • Algorithm: AES-256 GCM (authenticated encryption)
  • Key Management: Static key AES_CRYPT_KEY hardcoded in includes/crypt.h
  • Key Parameters:
    • Key size: 32 bytes (256 bits)
    • IV size: 12 bytes (96 bits, randomly generated per operation)
    • Auth tag size: 16 bytes
  • Functions:
    • aes_gcm_encrypt(): Encrypts plaintext, returns ciphertext with IV prepended
    • aes_gcm_decrypt(): Decrypts ciphertext, verifies authentication tag

5. Compression System (utils/Compressor.c)

  • Library: zlib
  • Configuration: Z_BEST_COMPRESSION level
  • Functions:
    • zlib_compress_dynamic(): Dynamically allocates compressed buffer
    • zlib_decompress_dynamic(): Dynamically allocates decompressed buffer

6. Network Utilities (utils/)

  • TCP Client: CreateClientSocket() - Establishes outbound connections
  • TCP Server: CreateServerSocket() - Creates listening sockets, AcceptTCPConnection() - Accepts clients
  • Socket Configuration: set_nonblocking_socket() - Enables non-blocking I/O
  • Options Set: SO_REUSEPORT, TCP_NODELAY

7. Logging System (logger/Logger.c, includes/logger.h)

  • Non-fatal: LogErrorWithReason() - Logs error, continues execution
  • Fatal (custom): LogErrorWithReasonX() - Logs error, calls exit(EXIT_FAILURE)
  • Fatal (system): LogSystemError() - Uses perror(), calls exit(EXIT_FAILURE)
  • All output goes to stdout

Threading Model

Both client and server use identical concurrency patterns:

  1. Main Thread: Runs accept() loop in select() for new connections
  2. Worker Threads: Spawned via pthread_create() and immediately detached with pthread_detach()
  3. Per-Thread Resources: Each thread manages two sockets (local + remote) with select() multiplexing
  4. Lifecycle: Threads self-terminate when either socket closes; no coordination with main thread

Data Flow

Client → Server Direction:

Local App → [Raw TCP Data] → Client.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket (40-byte header) → Network → Server.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Proxy

Server → Client Direction:

Proxy Response → Server.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket → Network → Client.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Local App

Build Targets

  • xhttp_c: Client executable (links all utilities + client/Client.c)
  • xhttp_s: Server executable (links all utilities + server/Server.c)
  • test_c: Test executable for encoding/decoding verification

External Dependencies

  • ZLIB: Data compression (zlib_compress_dynamic, zlib_decompress_dynamic)
  • OpenSSL::Crypto: AES-GCM cryptographic operations
  • OpenSSL::SSL: TLS/SSL support (linked but usage not visible in main code)
  • POSIX Threads: Multi-threading (pthread_create, pthread_detach)
  • POSIX Sockets: Network I/O (socket, bind, listen, accept, connect, select)

Configuration

Client Configuration (client/Client.c):

#defineDEF_LOCAL_PORT "8090" // Local listening port
#definePROXY_HOST "167.71.189.187" // Remote server IP
#definePROXY_PORT "8080" // Remote server port

Server Configuration (server/Server.c):

#defineDEF_LOCAL_PORT "8080" // Server listening port
#definePROXY_HOST "localhost" // Upstream proxy host
#definePROXY_PORT "3128" // Upstream proxy port (Squid default)

Glossary of Codebase-Specific Terms

Core Architecture Terms

  1. xhttp_c: Client executable that accepts local connections and tunnels them through encrypted protocol to xhttp_s. Built from client/Client.c. Listens on port 8090.

  2. xhttp_s: Server executable that receives encrypted connections from xhttp_c and forwards to upstream proxy. Built from server/Server.c. Listens on port 8080.

  3. Packet: Core data structure (struct Packet in includes/packet.h) containing msgLength, structSize, flag, and message[BUFSIZ*3]. Represents encapsulated application data.

  4. handle_client_thread: Function in both Client.c and Server.c that manages bidirectional data forwarding for a single connection. Each runs in a detached pthread.

  5. DEF_LOCAL_PORT: Port configuration macro. "8090" for client, "8080" for server. Defined in respective main files.

  6. PROXY_HOST/PROXY_PORT: Destination configuration. Client: 167.71.189.187:8080 (xhttp_s). Server: localhost:3128 (Squid proxy).

Protocol and Encoding

  1. BufferEncode: Function in Encoder/Encoder.c that serializes Packet, compresses with zlib, encrypts with AES-GCM. Returns uint8_t* buffer.

  2. BufferDecode: Function in Encoder/Encoder.c that reverses BufferEncode: decrypts, decompresses, deserializes into Packet structure.

  3. FrameToSocket: Function in Encoder/Encoder.c that prepends 40-byte header to data and writes to socket. Used for protocol framing.

  4. FrameFromSocket: Function in Encoder/Encoder.c that reads framed data from socket, skipping 40-byte header. Returns payload bytes.

  5. HEADER_SIZE: Constant defined as 40 in Encoder/Encoder.c. Size of HTTP-like header prepended to all transmitted packets.

  6. msgLength: Field in struct Packet storing length of actual message payload. Used for variable-length message handling.

  7. structSize: Field in struct Packet storing sizeof(struct Packet). Enables version compatibility checks or dynamic structure handling.

  8. flag: Single-byte field in struct Packet for protocol flags (COMPRESSION_FLAG, IS_REQUEST_FLAG, etc.). Defined in includes/packet.h.

Packet Flags

  1. COMPRESSION_FLAG: Value 0x0100 in includes/packet.h. Indicates packet payload is compressed. Set during encoding pipeline.

  2. IS_REQUEST_FLAG: Value 0x0500. Marks packet as client request. Used for protocol-level distinction between request/response.

  3. IS_RESPONSE_FLAG: Value 0x0300. Marks packet as server response. Complementary to IS_REQUEST_FLAG.

  4. CONTINUATION_FLAG: Value 0x0200. Indicates packet is part of multi-packet message sequence. For handling large payloads.

  5. IS_CHUNK_FLAG: Value 0x0400. Denotes packet contains data chunk, possibly for streaming or progressive transfer.

Cryptography

  1. AES_CRYPT_KEY: Static string constant in includes/crypt.h containing hardcoded 256-bit encryption key. Used by all AES operations.

  2. aes_gcm_encrypt: Function in crypt/AES.c that encrypts plaintext using AES-256 GCM. Generates random IV, prepends to ciphertext.

  3. aes_gcm_decrypt: Function in crypt/AES.c that decrypts ciphertext, extracts IV, verifies authentication tag. Returns -1 on tag mismatch.

  4. AES_KEY_SIZE: Constant 32 bytes (256 bits) in crypt/AES.c. Defines AES key length.

  5. AES_IV_SIZE: Constant 12 bytes (96 bits) in crypt/AES.c. Initialization vector size for GCM mode.

  6. TAG_SIZE: Constant 16 bytes in crypt/AES.c. Authentication tag size for GCM authenticated encryption.

Compression

  1. zlib_compress_dynamic: Function in utils/Compressor.c that compresses buffer using zlib Z_BEST_COMPRESSION. Dynamically allocates output.

  2. zlib_decompress_dynamic: Function in utils/Compressor.c that decompresses zlib buffer. Dynamically resizes output as needed.

  3. Z_BEST_COMPRESSION: zlib constant used in compression initialization. Maximizes compression ratio at cost of CPU.

Networking Utilities

  1. CreateClientSocket: Function in utils/TcpClientUtility.c that resolves hostname, creates socket, sets SO_REUSEPORT/TCP_NODELAY, connects.

  2. CreateServerSocket: Function in utils/TcpServerUtility.c that creates, binds, and sets socket to listen with MAX_CONNECTED_SOCKS backlog.

  3. AcceptTCPConnection: Function in utils/TcpServerUtility.c that monitors server socket with select() and accepts new client connections.

  4. set_nonblocking_socket: Function in utils/SocketUtility.c that uses fcntl() to set O_NONBLOCK flag on socket descriptor.

  5. MAX_CONNECTED_SOCKS: Constant 10 in utils/TcpServerUtility.c. Backlog parameter for listen() call, limits pending connection queue.

  6. STREAM_BUF_SIZE: Macro BUFSIZ * 3 in includes/utils.h. Size of I/O buffers (~24KB on most systems). Used for socket read/write.

  7. printSocketAddress: Function in utils/AddressUtility.c that formats sockaddr to human-readable IP:port string. Used for logging.

  8. generate_http_header: Function in utils/Utils.c that creates 40-byte HTTP-like header string. Used to disguise packets.

Logging

  1. LogErrorWithReason: Function in logger/Logger.c for non-fatal error logging. Outputs to stdout, continues execution.

  2. LogErrorWithReasonX: Function in logger/Logger.c for fatal errors. Logs to stdout, calls exit(EXIT_FAILURE). 'X' suffix means "exit".

  3. LogSystemError: Function in logger/Logger.c for system call failures. Uses perror(), then exits. For errno-based errors.

Threading and I/O

  1. serverSock: Global int in Client.c/Server.c. File descriptor for main listening socket created by CreateServerSocket().

  2. clntSock: Local variable in thread functions. File descriptor for accepted client connection from AcceptTCPConnection().

  3. proxySocket: Local variable in handle_client_thread. File descriptor for outbound connection to next hop (xhttp_s or Squid).

  4. client_buf/proxy_buf: Local buffers of STREAM_BUF_SIZE in thread functions. Used for reading data from respective sockets.

  5. fd_set: Standard type used with select() to monitor multiple socket descriptors. Declared as read_fd_set in thread loops.

  6. cleanup_handler: Signal handler function in Client.c/Server.c. Registered for SIGINT/SIGTERM to call cleanup() on shutdown.

Build System

  1. CMakePresets.json: File defining CMake configuration presets for build, test, configure stages. Standardizes development environments.

  2. XHTTP: Project namespace/prefix. Appears in header guards (XHTTP_PACKET_H, XHTTP_UTILS_H) and system identifier.

  3. temporal_buffer: Local variable in Encoder.c encoding/decoding functions. Intermediate buffer between compression and encryption stages.

  4. HTTP_HEADER_TEMPLATE: String constant in includes/packet.h: "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n". Template for generate_http_header().

  5. MIN_CONTENT_LENGTH/MAX_CONTENT_LENGTH: Constants 100/999 in includes/packet.h. Constraints for HTTP header content-length field.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Overview

XHTTP is a tunneling proxy system that establishes encrypted TCP connections between a local client and a remote server through a custom protocol. The system consists of two executables:

  • xhttp_c (Client): Runs on the local machine, listening on port 8090 for incoming connections from local applications (browsers, HTTP clients, etc.)
  • xhttp_s (Server): Runs on a remote machine, listening on port 8080 for connections from xhttp_c clients and forwarding traffic to an upstream proxy (default: localhost:3128)

Purpose: XHTTP enables secure, compressed communication through potentially restrictive networks by:

  1. Encapsulating traffic in a custom packet protocol
  2. Compressing data using zlib for bandwidth efficiency
  3. Encrypting traffic with AES-256 GCM for confidentiality and integrity
  4. Disguising encrypted packets with HTTP-like headers for potential firewall/proxy traversal

Users: Developers or network administrators who need to tunnel TCP traffic through monitored or restricted networks while maintaining security and optimizing bandwidth.

Use Case Example: A local application connects to localhost:8090 → xhttp_c encrypts and forwards to remote server at 167.71.189.187:8080 → xhttp_s decrypts and forwards to squid proxy at localhost:3128 → reaches final destination.


Project Organization

Build System Architecture

The project uses CMake as its build system, configured in CMakeLists.txt:

xhttp/
├── CMakeLists.txt # Defines build targets and dependencies
├── CMakePresets.json # CMake configuration presets
├── client/ # Client executable source
│ └── Client.c # Main client entry point and threading logic
├── server/ # Server executable source
│ └── Server.c # Main server entry point and threading logic
├── Encoder/ # Packet encoding/decoding
│ └── Encoder.c # BufferEncode/Decode, compression, encryption
├── crypt/ # Cryptography implementations
│ └── AES.c # AES-256 GCM encryption/decryption
├── logger/ # Logging subsystem
│ └── Logger.c # Error logging functions
├── utils/ # Networking utilities
│ ├── TcpClientUtility.c # Client socket creation and connection
│ ├── TcpServerUtility.c # Server socket creation and listening
│ ├── SocketUtility.c # Non-blocking socket configuration
│ ├── AddressUtility.c # Socket address printing
│ ├── Compressor.c # zlib compression/decompression
│ └── Utils.c # HTTP header generation
├── includes/ # Header files (public APIs)
│ ├── packet.h # Packet structure and flags
│ ├── utils.h # Utility function declarations
│ ├── crypt.h # Cryptography API and key definition
│ └── logger.h # Logging function declarations
└── tests/ # Test executables
└── test.c # Integration test for encoding/decoding

Core Systems

1. Client System (client/Client.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8090) for local connections
    • Spawns a new pthread for each accepted connection
    • Each thread establishes connection to PROXY_HOST:PROXY_PORT (167.71.189.187:8080)
    • Bidirectionally forwards data with custom protocol encoding
    • Uses select() for non-blocking I/O multiplexing

2. Server System (server/Server.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8080) for incoming xhttp_c connections
    • Spawns pthread per client connection
    • Establishes outbound connection to PROXY_HOST:PROXY_PORT (localhost:3128)
    • Decodes incoming packets and forwards raw data to upstream proxy
    • Encodes upstream responses back into packet format

3. Packet Protocol Layer (includes/packet.h, Encoder/Encoder.c)

  • Key Structure: struct Packet
    structPacket {
    uint32_tmsgLength; // Length of message payloaduint32_tstructSize; // Size of Packet structureuint8_tflag; // Protocol flags (compression, request/response, etc.)uint8_tmessage[BUFSIZ*3]; // Actual payload (max ~24KB)
    };
  • Encoding Pipeline: Packet → Serialize → Compress (zlib) → Encrypt (AES-GCM) → Frame (40-byte header)
  • Key Functions:
    • BufferEncode(): Serializes, compresses, encrypts packet
    • BufferDecode(): Decrypts, decompresses, deserializes packet
    • FrameToSocket(): Adds 40-byte header and sends to socket
    • FrameFromSocket(): Receives framed data and extracts payload

4. Cryptography System (crypt/AES.c, includes/crypt.h)

  • Algorithm: AES-256 GCM (authenticated encryption)
  • Key Management: Static key AES_CRYPT_KEY hardcoded in includes/crypt.h
  • Key Parameters:
    • Key size: 32 bytes (256 bits)
    • IV size: 12 bytes (96 bits, randomly generated per operation)
    • Auth tag size: 16 bytes
  • Functions:
    • aes_gcm_encrypt(): Encrypts plaintext, returns ciphertext with IV prepended
    • aes_gcm_decrypt(): Decrypts ciphertext, verifies authentication tag

5. Compression System (utils/Compressor.c)

  • Library: zlib
  • Configuration: Z_BEST_COMPRESSION level
  • Functions:
    • zlib_compress_dynamic(): Dynamically allocates compressed buffer
    • zlib_decompress_dynamic(): Dynamically allocates decompressed buffer

6. Network Utilities (utils/)

  • TCP Client: CreateClientSocket() - Establishes outbound connections
  • TCP Server: CreateServerSocket() - Creates listening sockets, AcceptTCPConnection() - Accepts clients
  • Socket Configuration: set_nonblocking_socket() - Enables non-blocking I/O
  • Options Set: SO_REUSEPORT, TCP_NODELAY

7. Logging System (logger/Logger.c, includes/logger.h)

  • Non-fatal: LogErrorWithReason() - Logs error, continues execution
  • Fatal (custom): LogErrorWithReasonX() - Logs error, calls exit(EXIT_FAILURE)
  • Fatal (system): LogSystemError() - Uses perror(), calls exit(EXIT_FAILURE)
  • All output goes to stdout

Threading Model

Both client and server use identical concurrency patterns:

  1. Main Thread: Runs accept() loop in select() for new connections
  2. Worker Threads: Spawned via pthread_create() and immediately detached with pthread_detach()
  3. Per-Thread Resources: Each thread manages two sockets (local + remote) with select() multiplexing
  4. Lifecycle: Threads self-terminate when either socket closes; no coordination with main thread

Data Flow

Client → Server Direction:

Local App → [Raw TCP Data] → Client.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket (40-byte header) → Network → Server.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Proxy

Server → Client Direction:

Proxy Response → Server.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket → Network → Client.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Local App

Build Targets

  • xhttp_c: Client executable (links all utilities + client/Client.c)
  • xhttp_s: Server executable (links all utilities + server/Server.c)
  • test_c: Test executable for encoding/decoding verification

External Dependencies

  • ZLIB: Data compression (zlib_compress_dynamic, zlib_decompress_dynamic)
  • OpenSSL::Crypto: AES-GCM cryptographic operations
  • OpenSSL::SSL: TLS/SSL support (linked but usage not visible in main code)
  • POSIX Threads: Multi-threading (pthread_create, pthread_detach)
  • POSIX Sockets: Network I/O (socket, bind, listen, accept, connect, select)

Configuration

Client Configuration (client/Client.c):

#defineDEF_LOCAL_PORT "8090" // Local listening port
#definePROXY_HOST "167.71.189.187" // Remote server IP
#definePROXY_PORT "8080" // Remote server port

Server Configuration (server/Server.c):

#defineDEF_LOCAL_PORT "8080" // Server listening port
#definePROXY_HOST "localhost" // Upstream proxy host
#definePROXY_PORT "3128" // Upstream proxy port (Squid default)

Glossary of Codebase-Specific Terms

Core Architecture Terms

  1. xhttp_c: Client executable that accepts local connections and tunnels them through encrypted protocol to xhttp_s. Built from client/Client.c. Listens on port 8090.

  2. xhttp_s: Server executable that receives encrypted connections from xhttp_c and forwards to upstream proxy. Built from server/Server.c. Listens on port 8080.

  3. Packet: Core data structure (struct Packet in includes/packet.h) containing msgLength, structSize, flag, and message[BUFSIZ*3]. Represents encapsulated application data.

  4. handle_client_thread: Function in both Client.c and Server.c that manages bidirectional data forwarding for a single connection. Each runs in a detached pthread.

  5. DEF_LOCAL_PORT: Port configuration macro. "8090" for client, "8080" for server. Defined in respective main files.

  6. PROXY_HOST/PROXY_PORT: Destination configuration. Client: 167.71.189.187:8080 (xhttp_s). Server: localhost:3128 (Squid proxy).

Protocol and Encoding

  1. BufferEncode: Function in Encoder/Encoder.c that serializes Packet, compresses with zlib, encrypts with AES-GCM. Returns uint8_t* buffer.

  2. BufferDecode: Function in Encoder/Encoder.c that reverses BufferEncode: decrypts, decompresses, deserializes into Packet structure.

  3. FrameToSocket: Function in Encoder/Encoder.c that prepends 40-byte header to data and writes to socket. Used for protocol framing.

  4. FrameFromSocket: Function in Encoder/Encoder.c that reads framed data from socket, skipping 40-byte header. Returns payload bytes.

  5. HEADER_SIZE: Constant defined as 40 in Encoder/Encoder.c. Size of HTTP-like header prepended to all transmitted packets.

  6. msgLength: Field in struct Packet storing length of actual message payload. Used for variable-length message handling.

  7. structSize: Field in struct Packet storing sizeof(struct Packet). Enables version compatibility checks or dynamic structure handling.

  8. flag: Single-byte field in struct Packet for protocol flags (COMPRESSION_FLAG, IS_REQUEST_FLAG, etc.). Defined in includes/packet.h.

Packet Flags

  1. COMPRESSION_FLAG: Value 0x0100 in includes/packet.h. Indicates packet payload is compressed. Set during encoding pipeline.

  2. IS_REQUEST_FLAG: Value 0x0500. Marks packet as client request. Used for protocol-level distinction between request/response.

  3. IS_RESPONSE_FLAG: Value 0x0300. Marks packet as server response. Complementary to IS_REQUEST_FLAG.

  4. CONTINUATION_FLAG: Value 0x0200. Indicates packet is part of multi-packet message sequence. For handling large payloads.

  5. IS_CHUNK_FLAG: Value 0x0400. Denotes packet contains data chunk, possibly for streaming or progressive transfer.

Cryptography

  1. AES_CRYPT_KEY: Static string constant in includes/crypt.h containing hardcoded 256-bit encryption key. Used by all AES operations.

  2. aes_gcm_encrypt: Function in crypt/AES.c that encrypts plaintext using AES-256 GCM. Generates random IV, prepends to ciphertext.

  3. aes_gcm_decrypt: Function in crypt/AES.c that decrypts ciphertext, extracts IV, verifies authentication tag. Returns -1 on tag mismatch.

  4. AES_KEY_SIZE: Constant 32 bytes (256 bits) in crypt/AES.c. Defines AES key length.

  5. AES_IV_SIZE: Constant 12 bytes (96 bits) in crypt/AES.c. Initialization vector size for GCM mode.

  6. TAG_SIZE: Constant 16 bytes in crypt/AES.c. Authentication tag size for GCM authenticated encryption.

Compression

  1. zlib_compress_dynamic: Function in utils/Compressor.c that compresses buffer using zlib Z_BEST_COMPRESSION. Dynamically allocates output.

  2. zlib_decompress_dynamic: Function in utils/Compressor.c that decompresses zlib buffer. Dynamically resizes output as needed.

  3. Z_BEST_COMPRESSION: zlib constant used in compression initialization. Maximizes compression ratio at cost of CPU.

Networking Utilities

  1. CreateClientSocket: Function in utils/TcpClientUtility.c that resolves hostname, creates socket, sets SO_REUSEPORT/TCP_NODELAY, connects.

  2. CreateServerSocket: Function in utils/TcpServerUtility.c that creates, binds, and sets socket to listen with MAX_CONNECTED_SOCKS backlog.

  3. AcceptTCPConnection: Function in utils/TcpServerUtility.c that monitors server socket with select() and accepts new client connections.

  4. set_nonblocking_socket: Function in utils/SocketUtility.c that uses fcntl() to set O_NONBLOCK flag on socket descriptor.

  5. MAX_CONNECTED_SOCKS: Constant 10 in utils/TcpServerUtility.c. Backlog parameter for listen() call, limits pending connection queue.

  6. STREAM_BUF_SIZE: Macro BUFSIZ * 3 in includes/utils.h. Size of I/O buffers (~24KB on most systems). Used for socket read/write.

  7. printSocketAddress: Function in utils/AddressUtility.c that formats sockaddr to human-readable IP:port string. Used for logging.

  8. generate_http_header: Function in utils/Utils.c that creates 40-byte HTTP-like header string. Used to disguise packets.

Logging

  1. LogErrorWithReason: Function in logger/Logger.c for non-fatal error logging. Outputs to stdout, continues execution.

  2. LogErrorWithReasonX: Function in logger/Logger.c for fatal errors. Logs to stdout, calls exit(EXIT_FAILURE). 'X' suffix means "exit".

  3. LogSystemError: Function in logger/Logger.c for system call failures. Uses perror(), then exits. For errno-based errors.

Threading and I/O

  1. serverSock: Global int in Client.c/Server.c. File descriptor for main listening socket created by CreateServerSocket().

  2. clntSock: Local variable in thread functions. File descriptor for accepted client connection from AcceptTCPConnection().

  3. proxySocket: Local variable in handle_client_thread. File descriptor for outbound connection to next hop (xhttp_s or Squid).

  4. client_buf/proxy_buf: Local buffers of STREAM_BUF_SIZE in thread functions. Used for reading data from respective sockets.

  5. fd_set: Standard type used with select() to monitor multiple socket descriptors. Declared as read_fd_set in thread loops.

  6. cleanup_handler: Signal handler function in Client.c/Server.c. Registered for SIGINT/SIGTERM to call cleanup() on shutdown.

Build System

  1. CMakePresets.json: File defining CMake configuration presets for build, test, configure stages. Standardizes development environments.

  2. XHTTP: Project namespace/prefix. Appears in header guards (XHTTP_PACKET_H, XHTTP_UTILS_H) and system identifier.

  3. temporal_buffer: Local variable in Encoder.c encoding/decoding functions. Intermediate buffer between compression and encryption stages.

  4. HTTP_HEADER_TEMPLATE: String constant in includes/packet.h: "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n". Template for generate_http_header().

  5. MIN_CONTENT_LENGTH/MAX_CONTENT_LENGTH: Constants 100/999 in includes/packet.h. Constraints for HTTP header content-length field.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Overview

XHTTP is a tunneling proxy system that establishes encrypted TCP connections between a local client and a remote server through a custom protocol. The system consists of two executables:

  • xhttp_c (Client): Runs on the local machine, listening on port 8090 for incoming connections from local applications (browsers, HTTP clients, etc.)
  • xhttp_s (Server): Runs on a remote machine, listening on port 8080 for connections from xhttp_c clients and forwarding traffic to an upstream proxy (default: localhost:3128)

Purpose: XHTTP enables secure, compressed communication through potentially restrictive networks by:

  1. Encapsulating traffic in a custom packet protocol
  2. Compressing data using zlib for bandwidth efficiency
  3. Encrypting traffic with AES-256 GCM for confidentiality and integrity
  4. Disguising encrypted packets with HTTP-like headers for potential firewall/proxy traversal

Users: Developers or network administrators who need to tunnel TCP traffic through monitored or restricted networks while maintaining security and optimizing bandwidth.

Use Case Example: A local application connects to localhost:8090 → xhttp_c encrypts and forwards to remote server at 167.71.189.187:8080 → xhttp_s decrypts and forwards to squid proxy at localhost:3128 → reaches final destination.


Project Organization

Build System Architecture

The project uses CMake as its build system, configured in CMakeLists.txt:

xhttp/
├── CMakeLists.txt # Defines build targets and dependencies
├── CMakePresets.json # CMake configuration presets
├── client/ # Client executable source
│ └── Client.c # Main client entry point and threading logic
├── server/ # Server executable source
│ └── Server.c # Main server entry point and threading logic
├── Encoder/ # Packet encoding/decoding
│ └── Encoder.c # BufferEncode/Decode, compression, encryption
├── crypt/ # Cryptography implementations
│ └── AES.c # AES-256 GCM encryption/decryption
├── logger/ # Logging subsystem
│ └── Logger.c # Error logging functions
├── utils/ # Networking utilities
│ ├── TcpClientUtility.c # Client socket creation and connection
│ ├── TcpServerUtility.c # Server socket creation and listening
│ ├── SocketUtility.c # Non-blocking socket configuration
│ ├── AddressUtility.c # Socket address printing
│ ├── Compressor.c # zlib compression/decompression
│ └── Utils.c # HTTP header generation
├── includes/ # Header files (public APIs)
│ ├── packet.h # Packet structure and flags
│ ├── utils.h # Utility function declarations
│ ├── crypt.h # Cryptography API and key definition
│ └── logger.h # Logging function declarations
└── tests/ # Test executables
└── test.c # Integration test for encoding/decoding

Core Systems

1. Client System (client/Client.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8090) for local connections
    • Spawns a new pthread for each accepted connection
    • Each thread establishes connection to PROXY_HOST:PROXY_PORT (167.71.189.187:8080)
    • Bidirectionally forwards data with custom protocol encoding
    • Uses select() for non-blocking I/O multiplexing

2. Server System (server/Server.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8080) for incoming xhttp_c connections
    • Spawns pthread per client connection
    • Establishes outbound connection to PROXY_HOST:PROXY_PORT (localhost:3128)
    • Decodes incoming packets and forwards raw data to upstream proxy
    • Encodes upstream responses back into packet format

3. Packet Protocol Layer (includes/packet.h, Encoder/Encoder.c)

  • Key Structure: struct Packet
    structPacket {
    uint32_tmsgLength; // Length of message payloaduint32_tstructSize; // Size of Packet structureuint8_tflag; // Protocol flags (compression, request/response, etc.)uint8_tmessage[BUFSIZ*3]; // Actual payload (max ~24KB)
    };
  • Encoding Pipeline: Packet → Serialize → Compress (zlib) → Encrypt (AES-GCM) → Frame (40-byte header)
  • Key Functions:
    • BufferEncode(): Serializes, compresses, encrypts packet
    • BufferDecode(): Decrypts, decompresses, deserializes packet
    • FrameToSocket(): Adds 40-byte header and sends to socket
    • FrameFromSocket(): Receives framed data and extracts payload

4. Cryptography System (crypt/AES.c, includes/crypt.h)

  • Algorithm: AES-256 GCM (authenticated encryption)
  • Key Management: Static key AES_CRYPT_KEY hardcoded in includes/crypt.h
  • Key Parameters:
    • Key size: 32 bytes (256 bits)
    • IV size: 12 bytes (96 bits, randomly generated per operation)
    • Auth tag size: 16 bytes
  • Functions:
    • aes_gcm_encrypt(): Encrypts plaintext, returns ciphertext with IV prepended
    • aes_gcm_decrypt(): Decrypts ciphertext, verifies authentication tag

5. Compression System (utils/Compressor.c)

  • Library: zlib
  • Configuration: Z_BEST_COMPRESSION level
  • Functions:
    • zlib_compress_dynamic(): Dynamically allocates compressed buffer
    • zlib_decompress_dynamic(): Dynamically allocates decompressed buffer

6. Network Utilities (utils/)

  • TCP Client: CreateClientSocket() - Establishes outbound connections
  • TCP Server: CreateServerSocket() - Creates listening sockets, AcceptTCPConnection() - Accepts clients
  • Socket Configuration: set_nonblocking_socket() - Enables non-blocking I/O
  • Options Set: SO_REUSEPORT, TCP_NODELAY

7. Logging System (logger/Logger.c, includes/logger.h)

  • Non-fatal: LogErrorWithReason() - Logs error, continues execution
  • Fatal (custom): LogErrorWithReasonX() - Logs error, calls exit(EXIT_FAILURE)
  • Fatal (system): LogSystemError() - Uses perror(), calls exit(EXIT_FAILURE)
  • All output goes to stdout

Threading Model

Both client and server use identical concurrency patterns:

  1. Main Thread: Runs accept() loop in select() for new connections
  2. Worker Threads: Spawned via pthread_create() and immediately detached with pthread_detach()
  3. Per-Thread Resources: Each thread manages two sockets (local + remote) with select() multiplexing
  4. Lifecycle: Threads self-terminate when either socket closes; no coordination with main thread

Data Flow

Client → Server Direction:

Local App → [Raw TCP Data] → Client.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket (40-byte header) → Network → Server.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Proxy

Server → Client Direction:

Proxy Response → Server.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket → Network → Client.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Local App

Build Targets

  • xhttp_c: Client executable (links all utilities + client/Client.c)
  • xhttp_s: Server executable (links all utilities + server/Server.c)
  • test_c: Test executable for encoding/decoding verification

External Dependencies

  • ZLIB: Data compression (zlib_compress_dynamic, zlib_decompress_dynamic)
  • OpenSSL::Crypto: AES-GCM cryptographic operations
  • OpenSSL::SSL: TLS/SSL support (linked but usage not visible in main code)
  • POSIX Threads: Multi-threading (pthread_create, pthread_detach)
  • POSIX Sockets: Network I/O (socket, bind, listen, accept, connect, select)

Configuration

Client Configuration (client/Client.c):

#defineDEF_LOCAL_PORT "8090" // Local listening port
#definePROXY_HOST "167.71.189.187" // Remote server IP
#definePROXY_PORT "8080" // Remote server port

Server Configuration (server/Server.c):

#defineDEF_LOCAL_PORT "8080" // Server listening port
#definePROXY_HOST "localhost" // Upstream proxy host
#definePROXY_PORT "3128" // Upstream proxy port (Squid default)

Glossary of Codebase-Specific Terms

Core Architecture Terms

  1. xhttp_c: Client executable that accepts local connections and tunnels them through encrypted protocol to xhttp_s. Built from client/Client.c. Listens on port 8090.

  2. xhttp_s: Server executable that receives encrypted connections from xhttp_c and forwards to upstream proxy. Built from server/Server.c. Listens on port 8080.

  3. Packet: Core data structure (struct Packet in includes/packet.h) containing msgLength, structSize, flag, and message[BUFSIZ*3]. Represents encapsulated application data.

  4. handle_client_thread: Function in both Client.c and Server.c that manages bidirectional data forwarding for a single connection. Each runs in a detached pthread.

  5. DEF_LOCAL_PORT: Port configuration macro. "8090" for client, "8080" for server. Defined in respective main files.

  6. PROXY_HOST/PROXY_PORT: Destination configuration. Client: 167.71.189.187:8080 (xhttp_s). Server: localhost:3128 (Squid proxy).

Protocol and Encoding

  1. BufferEncode: Function in Encoder/Encoder.c that serializes Packet, compresses with zlib, encrypts with AES-GCM. Returns uint8_t* buffer.

  2. BufferDecode: Function in Encoder/Encoder.c that reverses BufferEncode: decrypts, decompresses, deserializes into Packet structure.

  3. FrameToSocket: Function in Encoder/Encoder.c that prepends 40-byte header to data and writes to socket. Used for protocol framing.

  4. FrameFromSocket: Function in Encoder/Encoder.c that reads framed data from socket, skipping 40-byte header. Returns payload bytes.

  5. HEADER_SIZE: Constant defined as 40 in Encoder/Encoder.c. Size of HTTP-like header prepended to all transmitted packets.

  6. msgLength: Field in struct Packet storing length of actual message payload. Used for variable-length message handling.

  7. structSize: Field in struct Packet storing sizeof(struct Packet). Enables version compatibility checks or dynamic structure handling.

  8. flag: Single-byte field in struct Packet for protocol flags (COMPRESSION_FLAG, IS_REQUEST_FLAG, etc.). Defined in includes/packet.h.

Packet Flags

  1. COMPRESSION_FLAG: Value 0x0100 in includes/packet.h. Indicates packet payload is compressed. Set during encoding pipeline.

  2. IS_REQUEST_FLAG: Value 0x0500. Marks packet as client request. Used for protocol-level distinction between request/response.

  3. IS_RESPONSE_FLAG: Value 0x0300. Marks packet as server response. Complementary to IS_REQUEST_FLAG.

  4. CONTINUATION_FLAG: Value 0x0200. Indicates packet is part of multi-packet message sequence. For handling large payloads.

  5. IS_CHUNK_FLAG: Value 0x0400. Denotes packet contains data chunk, possibly for streaming or progressive transfer.

Cryptography

  1. AES_CRYPT_KEY: Static string constant in includes/crypt.h containing hardcoded 256-bit encryption key. Used by all AES operations.

  2. aes_gcm_encrypt: Function in crypt/AES.c that encrypts plaintext using AES-256 GCM. Generates random IV, prepends to ciphertext.

  3. aes_gcm_decrypt: Function in crypt/AES.c that decrypts ciphertext, extracts IV, verifies authentication tag. Returns -1 on tag mismatch.

  4. AES_KEY_SIZE: Constant 32 bytes (256 bits) in crypt/AES.c. Defines AES key length.

  5. AES_IV_SIZE: Constant 12 bytes (96 bits) in crypt/AES.c. Initialization vector size for GCM mode.

  6. TAG_SIZE: Constant 16 bytes in crypt/AES.c. Authentication tag size for GCM authenticated encryption.

Compression

  1. zlib_compress_dynamic: Function in utils/Compressor.c that compresses buffer using zlib Z_BEST_COMPRESSION. Dynamically allocates output.

  2. zlib_decompress_dynamic: Function in utils/Compressor.c that decompresses zlib buffer. Dynamically resizes output as needed.

  3. Z_BEST_COMPRESSION: zlib constant used in compression initialization. Maximizes compression ratio at cost of CPU.

Networking Utilities

  1. CreateClientSocket: Function in utils/TcpClientUtility.c that resolves hostname, creates socket, sets SO_REUSEPORT/TCP_NODELAY, connects.

  2. CreateServerSocket: Function in utils/TcpServerUtility.c that creates, binds, and sets socket to listen with MAX_CONNECTED_SOCKS backlog.

  3. AcceptTCPConnection: Function in utils/TcpServerUtility.c that monitors server socket with select() and accepts new client connections.

  4. set_nonblocking_socket: Function in utils/SocketUtility.c that uses fcntl() to set O_NONBLOCK flag on socket descriptor.

  5. MAX_CONNECTED_SOCKS: Constant 10 in utils/TcpServerUtility.c. Backlog parameter for listen() call, limits pending connection queue.

  6. STREAM_BUF_SIZE: Macro BUFSIZ * 3 in includes/utils.h. Size of I/O buffers (~24KB on most systems). Used for socket read/write.

  7. printSocketAddress: Function in utils/AddressUtility.c that formats sockaddr to human-readable IP:port string. Used for logging.

  8. generate_http_header: Function in utils/Utils.c that creates 40-byte HTTP-like header string. Used to disguise packets.

Logging

  1. LogErrorWithReason: Function in logger/Logger.c for non-fatal error logging. Outputs to stdout, continues execution.

  2. LogErrorWithReasonX: Function in logger/Logger.c for fatal errors. Logs to stdout, calls exit(EXIT_FAILURE). 'X' suffix means "exit".

  3. LogSystemError: Function in logger/Logger.c for system call failures. Uses perror(), then exits. For errno-based errors.

Threading and I/O

  1. serverSock: Global int in Client.c/Server.c. File descriptor for main listening socket created by CreateServerSocket().

  2. clntSock: Local variable in thread functions. File descriptor for accepted client connection from AcceptTCPConnection().

  3. proxySocket: Local variable in handle_client_thread. File descriptor for outbound connection to next hop (xhttp_s or Squid).

  4. client_buf/proxy_buf: Local buffers of STREAM_BUF_SIZE in thread functions. Used for reading data from respective sockets.

  5. fd_set: Standard type used with select() to monitor multiple socket descriptors. Declared as read_fd_set in thread loops.

  6. cleanup_handler: Signal handler function in Client.c/Server.c. Registered for SIGINT/SIGTERM to call cleanup() on shutdown.

Build System

  1. CMakePresets.json: File defining CMake configuration presets for build, test, configure stages. Standardizes development environments.

  2. XHTTP: Project namespace/prefix. Appears in header guards (XHTTP_PACKET_H, XHTTP_UTILS_H) and system identifier.

  3. temporal_buffer: Local variable in Encoder.c encoding/decoding functions. Intermediate buffer between compression and encryption stages.

  4. HTTP_HEADER_TEMPLATE: String constant in includes/packet.h: "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n". Template for generate_http_header().

  5. MIN_CONTENT_LENGTH/MAX_CONTENT_LENGTH: Constants 100/999 in includes/packet.h. Constraints for HTTP header content-length field.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Overview

XHTTP is a tunneling proxy system that establishes encrypted TCP connections between a local client and a remote server through a custom protocol. The system consists of two executables:

  • xhttp_c (Client): Runs on the local machine, listening on port 8090 for incoming connections from local applications (browsers, HTTP clients, etc.)
  • xhttp_s (Server): Runs on a remote machine, listening on port 8080 for connections from xhttp_c clients and forwarding traffic to an upstream proxy (default: localhost:3128)

Purpose: XHTTP enables secure, compressed communication through potentially restrictive networks by:

  1. Encapsulating traffic in a custom packet protocol
  2. Compressing data using zlib for bandwidth efficiency
  3. Encrypting traffic with AES-256 GCM for confidentiality and integrity
  4. Disguising encrypted packets with HTTP-like headers for potential firewall/proxy traversal

Users: Developers or network administrators who need to tunnel TCP traffic through monitored or restricted networks while maintaining security and optimizing bandwidth.

Use Case Example: A local application connects to localhost:8090 → xhttp_c encrypts and forwards to remote server at 167.71.189.187:8080 → xhttp_s decrypts and forwards to squid proxy at localhost:3128 → reaches final destination.


Project Organization

Build System Architecture

The project uses CMake as its build system, configured in CMakeLists.txt:

xhttp/
├── CMakeLists.txt # Defines build targets and dependencies
├── CMakePresets.json # CMake configuration presets
├── client/ # Client executable source
│ └── Client.c # Main client entry point and threading logic
├── server/ # Server executable source
│ └── Server.c # Main server entry point and threading logic
├── Encoder/ # Packet encoding/decoding
│ └── Encoder.c # BufferEncode/Decode, compression, encryption
├── crypt/ # Cryptography implementations
│ └── AES.c # AES-256 GCM encryption/decryption
├── logger/ # Logging subsystem
│ └── Logger.c # Error logging functions
├── utils/ # Networking utilities
│ ├── TcpClientUtility.c # Client socket creation and connection
│ ├── TcpServerUtility.c # Server socket creation and listening
│ ├── SocketUtility.c # Non-blocking socket configuration
│ ├── AddressUtility.c # Socket address printing
│ ├── Compressor.c # zlib compression/decompression
│ └── Utils.c # HTTP header generation
├── includes/ # Header files (public APIs)
│ ├── packet.h # Packet structure and flags
│ ├── utils.h # Utility function declarations
│ ├── crypt.h # Cryptography API and key definition
│ └── logger.h # Logging function declarations
└── tests/ # Test executables
└── test.c # Integration test for encoding/decoding

Core Systems

1. Client System (client/Client.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8090) for local connections
    • Spawns a new pthread for each accepted connection
    • Each thread establishes connection to PROXY_HOST:PROXY_PORT (167.71.189.187:8080)
    • Bidirectionally forwards data with custom protocol encoding
    • Uses select() for non-blocking I/O multiplexing

2. Server System (server/Server.c)

  • Entry Point: main() function
  • Core Function: handle_client_thread(void *args)
  • Responsibilities:
    • Listens on DEF_LOCAL_PORT (8080) for incoming xhttp_c connections
    • Spawns pthread per client connection
    • Establishes outbound connection to PROXY_HOST:PROXY_PORT (localhost:3128)
    • Decodes incoming packets and forwards raw data to upstream proxy
    • Encodes upstream responses back into packet format

3. Packet Protocol Layer (includes/packet.h, Encoder/Encoder.c)

  • Key Structure: struct Packet
    structPacket {
    uint32_tmsgLength; // Length of message payloaduint32_tstructSize; // Size of Packet structureuint8_tflag; // Protocol flags (compression, request/response, etc.)uint8_tmessage[BUFSIZ*3]; // Actual payload (max ~24KB)
    };
  • Encoding Pipeline: Packet → Serialize → Compress (zlib) → Encrypt (AES-GCM) → Frame (40-byte header)
  • Key Functions:
    • BufferEncode(): Serializes, compresses, encrypts packet
    • BufferDecode(): Decrypts, decompresses, deserializes packet
    • FrameToSocket(): Adds 40-byte header and sends to socket
    • FrameFromSocket(): Receives framed data and extracts payload

4. Cryptography System (crypt/AES.c, includes/crypt.h)

  • Algorithm: AES-256 GCM (authenticated encryption)
  • Key Management: Static key AES_CRYPT_KEY hardcoded in includes/crypt.h
  • Key Parameters:
    • Key size: 32 bytes (256 bits)
    • IV size: 12 bytes (96 bits, randomly generated per operation)
    • Auth tag size: 16 bytes
  • Functions:
    • aes_gcm_encrypt(): Encrypts plaintext, returns ciphertext with IV prepended
    • aes_gcm_decrypt(): Decrypts ciphertext, verifies authentication tag

5. Compression System (utils/Compressor.c)

  • Library: zlib
  • Configuration: Z_BEST_COMPRESSION level
  • Functions:
    • zlib_compress_dynamic(): Dynamically allocates compressed buffer
    • zlib_decompress_dynamic(): Dynamically allocates decompressed buffer

6. Network Utilities (utils/)

  • TCP Client: CreateClientSocket() - Establishes outbound connections
  • TCP Server: CreateServerSocket() - Creates listening sockets, AcceptTCPConnection() - Accepts clients
  • Socket Configuration: set_nonblocking_socket() - Enables non-blocking I/O
  • Options Set: SO_REUSEPORT, TCP_NODELAY

7. Logging System (logger/Logger.c, includes/logger.h)

  • Non-fatal: LogErrorWithReason() - Logs error, continues execution
  • Fatal (custom): LogErrorWithReasonX() - Logs error, calls exit(EXIT_FAILURE)
  • Fatal (system): LogSystemError() - Uses perror(), calls exit(EXIT_FAILURE)
  • All output goes to stdout

Threading Model

Both client and server use identical concurrency patterns:

  1. Main Thread: Runs accept() loop in select() for new connections
  2. Worker Threads: Spawned via pthread_create() and immediately detached with pthread_detach()
  3. Per-Thread Resources: Each thread manages two sockets (local + remote) with select() multiplexing
  4. Lifecycle: Threads self-terminate when either socket closes; no coordination with main thread

Data Flow

Client → Server Direction:

Local App → [Raw TCP Data] → Client.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket (40-byte header) → Network → Server.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Proxy

Server → Client Direction:

Proxy Response → Server.c → Create Packet → BufferEncode → Compress → Encrypt → FrameToSocket → Network → Client.c → FrameFromSocket → Decrypt → Decompress → BufferDecode → Extract message → Forward to Local App

Build Targets

  • xhttp_c: Client executable (links all utilities + client/Client.c)
  • xhttp_s: Server executable (links all utilities + server/Server.c)
  • test_c: Test executable for encoding/decoding verification

External Dependencies

  • ZLIB: Data compression (zlib_compress_dynamic, zlib_decompress_dynamic)
  • OpenSSL::Crypto: AES-GCM cryptographic operations
  • OpenSSL::SSL: TLS/SSL support (linked but usage not visible in main code)
  • POSIX Threads: Multi-threading (pthread_create, pthread_detach)
  • POSIX Sockets: Network I/O (socket, bind, listen, accept, connect, select)

Configuration

Client Configuration (client/Client.c):

#defineDEF_LOCAL_PORT "8090" // Local listening port
#definePROXY_HOST "167.71.189.187" // Remote server IP
#definePROXY_PORT "8080" // Remote server port

Server Configuration (server/Server.c):

#defineDEF_LOCAL_PORT "8080" // Server listening port
#definePROXY_HOST "localhost" // Upstream proxy host
#definePROXY_PORT "3128" // Upstream proxy port (Squid default)

Glossary of Codebase-Specific Terms

Core Architecture Terms

  1. xhttp_c: Client executable that accepts local connections and tunnels them through encrypted protocol to xhttp_s. Built from client/Client.c. Listens on port 8090.

  2. xhttp_s: Server executable that receives encrypted connections from xhttp_c and forwards to upstream proxy. Built from server/Server.c. Listens on port 8080.

  3. Packet: Core data structure (struct Packet in includes/packet.h) containing msgLength, structSize, flag, and message[BUFSIZ*3]. Represents encapsulated application data.

  4. handle_client_thread: Function in both Client.c and Server.c that manages bidirectional data forwarding for a single connection. Each runs in a detached pthread.

  5. DEF_LOCAL_PORT: Port configuration macro. "8090" for client, "8080" for server. Defined in respective main files.

  6. PROXY_HOST/PROXY_PORT: Destination configuration. Client: 167.71.189.187:8080 (xhttp_s). Server: localhost:3128 (Squid proxy).

Protocol and Encoding

  1. BufferEncode: Function in Encoder/Encoder.c that serializes Packet, compresses with zlib, encrypts with AES-GCM. Returns uint8_t* buffer.

  2. BufferDecode: Function in Encoder/Encoder.c that reverses BufferEncode: decrypts, decompresses, deserializes into Packet structure.

  3. FrameToSocket: Function in Encoder/Encoder.c that prepends 40-byte header to data and writes to socket. Used for protocol framing.

  4. FrameFromSocket: Function in Encoder/Encoder.c that reads framed data from socket, skipping 40-byte header. Returns payload bytes.

  5. HEADER_SIZE: Constant defined as 40 in Encoder/Encoder.c. Size of HTTP-like header prepended to all transmitted packets.

  6. msgLength: Field in struct Packet storing length of actual message payload. Used for variable-length message handling.

  7. structSize: Field in struct Packet storing sizeof(struct Packet). Enables version compatibility checks or dynamic structure handling.

  8. flag: Single-byte field in struct Packet for protocol flags (COMPRESSION_FLAG, IS_REQUEST_FLAG, etc.). Defined in includes/packet.h.

Packet Flags

  1. COMPRESSION_FLAG: Value 0x0100 in includes/packet.h. Indicates packet payload is compressed. Set during encoding pipeline.

  2. IS_REQUEST_FLAG: Value 0x0500. Marks packet as client request. Used for protocol-level distinction between request/response.

  3. IS_RESPONSE_FLAG: Value 0x0300. Marks packet as server response. Complementary to IS_REQUEST_FLAG.

  4. CONTINUATION_FLAG: Value 0x0200. Indicates packet is part of multi-packet message sequence. For handling large payloads.

  5. IS_CHUNK_FLAG: Value 0x0400. Denotes packet contains data chunk, possibly for streaming or progressive transfer.

Cryptography

  1. AES_CRYPT_KEY: Static string constant in includes/crypt.h containing hardcoded 256-bit encryption key. Used by all AES operations.

  2. aes_gcm_encrypt: Function in crypt/AES.c that encrypts plaintext using AES-256 GCM. Generates random IV, prepends to ciphertext.

  3. aes_gcm_decrypt: Function in crypt/AES.c that decrypts ciphertext, extracts IV, verifies authentication tag. Returns -1 on tag mismatch.

  4. AES_KEY_SIZE: Constant 32 bytes (256 bits) in crypt/AES.c. Defines AES key length.

  5. AES_IV_SIZE: Constant 12 bytes (96 bits) in crypt/AES.c. Initialization vector size for GCM mode.

  6. TAG_SIZE: Constant 16 bytes in crypt/AES.c. Authentication tag size for GCM authenticated encryption.

Compression

  1. zlib_compress_dynamic: Function in utils/Compressor.c that compresses buffer using zlib Z_BEST_COMPRESSION. Dynamically allocates output.

  2. zlib_decompress_dynamic: Function in utils/Compressor.c that decompresses zlib buffer. Dynamically resizes output as needed.

  3. Z_BEST_COMPRESSION: zlib constant used in compression initialization. Maximizes compression ratio at cost of CPU.

Networking Utilities

  1. CreateClientSocket: Function in utils/TcpClientUtility.c that resolves hostname, creates socket, sets SO_REUSEPORT/TCP_NODELAY, connects.

  2. CreateServerSocket: Function in utils/TcpServerUtility.c that creates, binds, and sets socket to listen with MAX_CONNECTED_SOCKS backlog.

  3. AcceptTCPConnection: Function in utils/TcpServerUtility.c that monitors server socket with select() and accepts new client connections.

  4. set_nonblocking_socket: Function in utils/SocketUtility.c that uses fcntl() to set O_NONBLOCK flag on socket descriptor.

  5. MAX_CONNECTED_SOCKS: Constant 10 in utils/TcpServerUtility.c. Backlog parameter for listen() call, limits pending connection queue.

  6. STREAM_BUF_SIZE: Macro BUFSIZ * 3 in includes/utils.h. Size of I/O buffers (~24KB on most systems). Used for socket read/write.

  7. printSocketAddress: Function in utils/AddressUtility.c that formats sockaddr to human-readable IP:port string. Used for logging.

  8. generate_http_header: Function in utils/Utils.c that creates 40-byte HTTP-like header string. Used to disguise packets.

Logging

  1. LogErrorWithReason: Function in logger/Logger.c for non-fatal error logging. Outputs to stdout, continues execution.

  2. LogErrorWithReasonX: Function in logger/Logger.c for fatal errors. Logs to stdout, calls exit(EXIT_FAILURE). 'X' suffix means "exit".

  3. LogSystemError: Function in logger/Logger.c for system call failures. Uses perror(), then exits. For errno-based errors.

Threading and I/O

  1. serverSock: Global int in Client.c/Server.c. File descriptor for main listening socket created by CreateServerSocket().

  2. clntSock: Local variable in thread functions. File descriptor for accepted client connection from AcceptTCPConnection().

  3. proxySocket: Local variable in handle_client_thread. File descriptor for outbound connection to next hop (xhttp_s or Squid).

  4. client_buf/proxy_buf: Local buffers of STREAM_BUF_SIZE in thread functions. Used for reading data from respective sockets.

  5. fd_set: Standard type used with select() to monitor multiple socket descriptors. Declared as read_fd_set in thread loops.

  6. cleanup_handler: Signal handler function in Client.c/Server.c. Registered for SIGINT/SIGTERM to call cleanup() on shutdown.

Build System

  1. CMakePresets.json: File defining CMake configuration presets for build, test, configure stages. Standardizes development environments.

  2. XHTTP: Project namespace/prefix. Appears in header guards (XHTTP_PACKET_H, XHTTP_UTILS_H) and system identifier.

  3. temporal_buffer: Local variable in Encoder.c encoding/decoding functions. Intermediate buffer between compression and encryption stages.

  4. HTTP_HEADER_TEMPLATE: String constant in includes/packet.h: "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n". Template for generate_http_header().

  5. MIN_CONTENT_LENGTH/MAX_CONTENT_LENGTH: Constants 100/999 in includes/packet.h. Constraints for HTTP header content-length field.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages