smartdns/readme.plan2.md

211 lines
6.3 KiB
Markdown
Raw Normal View History

# DNS Server Manual Socket Handling Implementation Plan
Command to reread CLAUDE.md: `cat /home/philkunz/.claude/CLAUDE.md`
## Overview
Enable manual socket handling for the DNSServer class to allow external socket management instead of internal socket creation and binding. This enables advanced use cases like socket pooling, custom networking layers, and integration with existing socket infrastructures.
## Current Implementation Analysis
- DNSServer currently creates and manages its own UDP (`dgram.Socket`) and HTTPS (`https.Server`) sockets
- Socket creation happens in `start()` method at lines ~728-752 in `ts_server/classes.dnsserver.ts`
- No mechanism exists to inject pre-created sockets
- Socket lifecycle is tightly coupled with server lifecycle
## Implementation Plan
### 1. Update IDnsServerOptions Interface
- Add optional `udpSocket?: dgram.Socket` property
- Add optional `httpsServer?: https.Server` property
- Add optional `manualMode?: boolean` flag to indicate manual socket handling
- Maintain backwards compatibility with existing automatic socket creation
### 2. Modify DnsServer Constructor
- Accept pre-created sockets in options
- Store references to manual sockets
- Set internal flags to track manual vs automatic mode
### 3. Update start() Method Logic
- Skip socket creation if manual sockets provided
- Validate manual sockets are in correct state
- Attach event listeners to provided sockets
- Support hybrid mode (UDP manual, HTTPS automatic, or vice versa)
### 4. Update stop() Method Logic
- For manual sockets: only remove event listeners, don't close sockets
- For automatic sockets: close sockets as current behavior
- Provide clear separation of lifecycle management
### 5. Add Socket Validation
- Verify provided UDP socket is correct type (udp4/udp6)
- Ensure HTTPS server is properly configured
- Validate socket state (not already listening, etc.)
### 6. Error Handling & Events
- Emit events for socket errors without stopping server
- Allow graceful handling of external socket failures
- Provide clear error messages for socket state issues
## Benefits
- **Socket Pooling**: Share sockets across multiple DNS server instances
- **Custom Networking**: Integration with custom network stacks
- **Performance**: Reuse existing socket infrastructure
- **Advanced Configuration**: Fine-grained control over socket options
- **Testing**: Easier mocking and testing with provided sockets
- **Container Integration**: Better integration with orchestration platforms
## Example Usage After Implementation
### Manual UDP Socket with Automatic HTTPS
```typescript
import * as dgram from 'dgram';
import { DnsServer } from '@push.rocks/smartdns/server';
// Create and configure UDP socket externally
const udpSocket = dgram.createSocket('udp4');
udpSocket.bind(53, '0.0.0.0');
const dnsServer = new DnsServer({
// Manual UDP socket
udpSocket: udpSocket,
manualMode: true,
// Automatic HTTPS server
httpsPort: 443,
httpsKey: cert.key,
httpsCert: cert.cert,
dnssecZone: 'example.com'
});
await dnsServer.start(); // Won't create new UDP socket
```
### Fully Manual Mode
```typescript
import * as https from 'https';
import * as dgram from 'dgram';
// Create both sockets externally
const udpSocket = dgram.createSocket('udp4');
const httpsServer = https.createServer({ key: cert.key, cert: cert.cert });
udpSocket.bind(53, '0.0.0.0');
httpsServer.listen(443, '0.0.0.0');
const dnsServer = new DnsServer({
udpSocket: udpSocket,
httpsServer: httpsServer,
manualMode: true,
dnssecZone: 'example.com'
});
await dnsServer.start(); // Only attaches handlers, no socket creation
```
### Socket Pooling Example
```typescript
// Shared socket pool
const socketPool = {
udp: dgram.createSocket('udp4'),
https: https.createServer(sslOptions)
};
// Multiple DNS servers sharing sockets
const server1 = new DnsServer({
udpSocket: socketPool.udp,
httpsServer: socketPool.https,
manualMode: true,
dnssecZone: 'zone1.com'
});
const server2 = new DnsServer({
udpSocket: socketPool.udp,
httpsServer: socketPool.https,
manualMode: true,
dnssecZone: 'zone2.com'
});
```
## Implementation Details
### New Interface Properties
```typescript
export interface IDnsServerOptions {
// Existing properties...
httpsKey: string;
httpsCert: string;
httpsPort: number;
udpPort: number;
dnssecZone: string;
udpBindInterface?: string;
httpsBindInterface?: string;
// New manual socket properties
udpSocket?: plugins.dgram.Socket;
httpsServer?: plugins.https.Server;
manualMode?: boolean;
}
```
### Modified Constructor Logic
```typescript
constructor(private options: IDnsServerOptions) {
// Existing DNSSEC initialization...
// Handle manual sockets
if (options.manualMode) {
if (options.udpSocket) {
this.udpServer = options.udpSocket;
}
if (options.httpsServer) {
this.httpsServer = options.httpsServer;
}
}
}
```
### Updated start() Method
```typescript
public async start(): Promise<void> {
// Manual socket mode handling
if (this.options.manualMode) {
await this.startManualMode();
} else {
await this.startAutomaticMode();
}
}
private async startManualMode(): Promise<void> {
if (this.udpServer) {
this.attachUdpHandlers();
}
if (this.httpsServer) {
this.attachHttpsHandlers();
}
}
```
## Files to Modify
1. `ts_server/classes.dnsserver.ts` - Core implementation
2. `test/test.server.ts` - Add manual socket tests
3. `readme.md` - Documentation updates with examples
## Testing Strategy
- Unit tests for manual socket validation
- Integration tests for mixed manual/automatic mode
- Socket lifecycle tests (start/stop behavior)
- Error handling tests for invalid socket states
- Performance tests comparing manual vs automatic modes
## Migration Path
- Feature is completely backwards compatible
- Existing code continues to work unchanged
- New `manualMode` flag clearly indicates intent
- Gradual adoption possible (UDP manual, HTTPS automatic, etc.)
## Security Considerations
- Validate provided sockets are properly configured
- Ensure manual sockets have appropriate permissions
- Document security implications of socket sharing
- Provide guidance on proper socket isolation
This enhancement enables advanced DNS server deployments while maintaining full backwards compatibility with existing implementations.