You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
7.1 KiB
7.1 KiB
AGENTS.md - uTun Development Guide
This file contains essential information for AI coding agents working in the uTun codebase.
📋 Quick Reference
Repository: uTun - Secure VPN tunnel with ETCP protocol
Language: C (C99)
Build System: GNU Autotools (autoconf/automake)
Cryptography: TinyCrypt (AES-CCM, ECC)
🔧 Build Commands
Full Build
./autogen.sh # Generate configure script (if needed)
./configure # Configure build
make # Build everything
make install # Install (requires sudo)
Partial Builds
cd lib && make # Build only the library
cd src && make # Build only the main program
cd tests && make # Build only tests
Clean Build
make clean # Clean object files
make distclean # Clean everything including configure files
🧪 Test Commands
Run All Tests
make check # Run all tests via automake
Run Specific Test
cd tests/ && ./test_etcp_crypto # ETCP crypto test
cd tests/ && ./test_etcp_simple # Simple ETCP test
cd tests/ && ./test_ecc_encrypt # ECC encryption test
Run Single Test with Debug Info
cd tests/
gcc -I../src -I../lib -I../tinycrypt/lib/include \
-o my_test test_file.c ../src/*.c ../lib/*.c ../tinycrypt/lib/source/*.c
./my_test
💻 Code Style Guidelines
Naming Conventions
- Functions:
snake_case-etcp_connection_create(),sc_encrypt() - Types:
struct snake_caseortypedef:struct secure_channel,sc_context_t - Macros:
UPPER_CASE-SC_PRIVKEY_SIZE,DEBUG_ERROR() - Constants:
UPPER_CASE-SC_OK,SC_ERR_CRYPTO - Global Variables: Avoid where possible, use
staticfor file scope
Formatting
- Indentation: 4 spaces, no tabs
- Braces: Same line for functions, new line for control structures:
int function(void) { if (condition) { do_something(); } } - Comments: Primary language is Russian for business logic, English for API docs
- Line Length: Aim for 80-100 characters
Include Order
// 1. System headers
#include <stdlib.h>
#include <string.h>
// 2. Library headers
#include "../lib/ll_queue.h"
// 3. Local headers
#include "etcp.h"
Error Handling
- Use custom error codes defined in headers (e.g.,
SC_ERR_INVALID_ARG) - Return negative values for errors, 0 for success
- Use DEBUG macros for logging:
DEBUG_ERROR(DEBUG_CATEGORY_ETCP, "Failed to initialize: %s", err); DEBUG_INFO(DEBUG_CATEGORY_CONNECTION, "Socket created on port %d", port);
🔐 Cryptography Guidelines
Using Secure Channel (secure_channel.h)
// 1. Initialize context
struct SC_MYKEYS my_keys;
// ... fill keys ...
sc_context_t ctx;
sc_init_ctx(&ctx, &my_keys);
// 2. Set peer public key (for key exchange)
sc_set_peer_public_key(&ctx, peer_public_key, 0); // 0 = binary format
// 3. Ready for encrypt/decrypt
sc_encrypt(&ctx, plaintext, plaintext_len, ciphertext, &ciphertext_len);
sc_decrypt(&ctx, ciphertext, ciphertext_len, plaintext, &plaintext_len);
Important Notes
- Nonce size: Must be exactly 13 bytes for CCM mode (
SC_NONCE_SIZE = 13) - Session key: 16 bytes for AES-128 (
SC_SESSION_KEY_SIZE = 16) - Tag size: 8 bytes for authentication (
SC_TAG_SIZE = 8) - Error codes: Check return values, negative = error
🏗️ Architecture
Directory Structure
├── lib/ # Core libraries (uasync, ll_queue, memory pools)
├── src/ # Main source code
│ ├── utun.c # Main program entry
│ ├── etcp*.c # ETCP protocol implementation
│ ├── secure_channel.c # Cryptography
│ └── tun_if.c # TUN/TAP interface
├── tests/ # Test programs
├── tinycrypt/ # TinyCrypt crypto library
└── net_emulator/ # Network emulator
Key Components
- UASYNC: Asynchronous event loop for sockets and timers
- LL_QUEUE: Lock-free lockstep queue for packet handling
- Memory Pool: Fast allocation for network packets
- ETCP: Extended TCP protocol with crypto and reliability
- Secure Channel: AES-CCM encryption with ECC key exchange
🐛 Debugging Tips
Enable Debug Output
// In source files, define debug before including headers
#define DEBUG_CATEGORY_YOUR_MODULE 1
Common Build Issues
- Missing headers: Check include paths in Makefile.am
- Undefined references: Ensure source files are listed in Makefile.am
- Link errors: Check function declarations match definitions
Testing Crypto
cd tests/
./test_etcp_crypto # Should show all tests passing
cd tests/
./working_crypto_test # Standalone crypto test
📦 Dependencies
Build Dependencies
- autoconf, automake, libtool
- gcc with C99 support
- pthread library
- OpenSSL/crypto library (for SHA256)
Runtime Dependencies
- TUN/TAP interface support (Linux kernel module)
- libcrypto (usually installed by default)
- Proper network configuration for testing
📝 Git Conventions
- Commit Messages: Use imperative mood, concise (50-72 chars)
- Language: Mix of English (technical) and Russian (business logic)
- Branching: Use feature branches, merge to master via pull request
- Tags: Version tags follow vX.Y.Z format
Example commits:
Fix: Added uasync_t typedef for compilation
Crypto: Fixed CCM nonce size to 13 bytes, all crypto tests passing
🚀 Quick Start for New Features
- Add new source file to
src/Makefile.amunderutun_SOURCES - Add test file to
tests/Makefile.amundercheck_PROGRAMS - Use existing patterns from similar modules
- Run
make checkafter changes - Commit with descriptive message in appropriate language
Важные дополнения:
- если в процессе исправлений-доработок возникла нестыковка которая требует сеньезных доработок, остановить и подробно расскажи об этом.
- sed для редактирования исходников - запрещено пользоваться!
- Проверяй на дублирование кода - не сделано ли это уже в другом месте.
- Не делай функций-посредников: лучше сразу вызывать target функцию без вложенных вызовов.
- Старайся чтобы функция сделала логически завершенную операцию полностью - это упрощает код и понимание.
- нельзя ничего восстанавливать из репозитория не прашивая
- Когда пишешь код всегда загружай в контекст и мысленно разберись как работают все функции/струтуры, назначение переменных которые используешь.
Last updated: 2025-01-20 - After full crypto implementation and testing