Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Torcontrol Laravel Package

dunglas/php-torcontrol

PHP TorControl is a lightweight library to control a Tor server via the Tor Control Protocol. Connect over TCP/SSL/UNIX sockets, authenticate via null/password/cookie, send commands (e.g., NEWNYM), and handle multi-line replies. Composer install.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation Add the package via Composer:

    composer require dunglas/php-torcontrol
    

    Ensure your composer.json autoloads PSR-4 compliant classes.

  2. Basic Connection Initialize the client with Tor server credentials (e.g., localhost:9051 with password auth):

    use TorControl\TorControl;
    
    $torControl = new TorControl([
        'hostname' => 'localhost',
        'port'     => 9051,
        'password' => 'your_secure_password',
        'authmethod' => TorControl::AUTH_PASSWORD, // 1
    ]);
    $torControl->connect();
    $torControl->authenticate();
    
  3. First Use Case: Rotate Identity Execute a command to renew a Tor circuit (e.g., for anonymity):

    $response = $torControl->executeCommand('SIGNAL NEWNYM');
    dd($response); // Inspect reply code/message
    

Where to Look First

  • Tor Control Protocol Spec – Reference for valid commands (e.g., GETINFO, SETCONF).
  • TorControl Class Docs – Check method signatures (e.g., executeCommand(), quit()).
  • Unit TestsTest files demonstrate edge cases (e.g., multi-line replies).

Implementation Patterns

Core Workflows

  1. Connection Management

    • Reusable Connection: Store $torControl in a service container (e.g., Laravel’s bind()) for app-wide access.
      $app->bind(TorControl::class, function ($app) {
          return new TorControl(['hostname' => config('tor.host'), 'port' => 9051, 'authmethod' => 1]);
      });
      
    • Connection Pooling: For high-frequency commands, reuse the connection instead of reconnecting per request.
  2. Command Execution

    • Idempotent Commands: Cache responses for read-only queries (e.g., GETINFO status/networkstatus).
      $cacheKey = 'tor_network_status';
      $response = Cache::remember($cacheKey, now()->addHours(1), function () use ($torControl) {
          return $torControl->executeCommand('GETINFO status/networkstatus');
      });
      
    • Error Handling: Wrap commands in try-catch to handle Tor server errors (e.g., 552 for invalid commands).
      try {
          $torControl->executeCommand('INVALID_COMMAND');
      } catch (\TorControl\Exception\TorControlException $e) {
          Log::error("Tor error: {$e->getMessage()}");
      }
      
  3. Authentication

    • Cookie File Auth: For production, use cookie-based auth (more secure than passwords):
      $torControl = new TorControl([
          'hostname' => 'localhost',
          'port'     => 9051,
          'cookie_file' => '/var/lib/tor/control_auth_cookie',
          'authmethod' => TorControl::AUTH_COOKIE, // 2
      ]);
      
    • Null Auth: If Tor is configured for ControlListenAddress without auth, use:
      $torControl = new TorControl(['hostname' => 'localhost', 'port' => 9051, 'authmethod' => 0]);
      
  4. Configuration Management

    • Dynamic Tor Settings: Use SETCONF to adjust runtime settings (e.g., circuit timeout):
      $torControl->executeCommand('SETCONF CircuitBuildTimeout=30');
      

Integration Tips

  • Laravel Service Providers: Encapsulate Tor logic in a provider to manage lifecycle:
    public function register() {
        $this->app->singleton(TorControl::class, function ($app) {
            $config = config('tor');
            return new TorControl($config['connection']);
        });
    }
    
  • Artisan Commands: Create CLI tools for Tor admin tasks (e.g., php artisan tor:newnym):
    $this->call('tor:newnym', [
        '--circuit' => 'general',
    ]);
    
  • Event Listeners: React to Tor events (e.g., circuit changes) via NOTICE commands:
    $torControl->executeCommand('SETEVENTS CIRC');
    

Gotchas and Tips

Pitfalls

  1. Multi-Line Replies

    • Issue: Commands like GETINFO may return multi-line responses. The library handles this, but ensure you inspect $response[0]['lines'] for verbose output.
    • Fix: Always check count($response) for multiple replies.
  2. Authentication Failures

    • Issue: Silent failures if authenticate() is called without valid credentials.
    • Fix: Verify auth method and credentials before connecting:
      if (!$torControl->authenticate()) {
          throw new \RuntimeException("Tor authentication failed");
      }
      
  3. Socket Timeouts

    • Issue: Long-running commands (e.g., GETINFO) may time out if Tor is overloaded.
    • Fix: Increase PHP socket timeout:
      $torControl->setSocketTimeout(30); // Default is 10 seconds
      
  4. Deprecated Auth Methods

    • Issue: AUTH_NULL (0) may be disabled in newer Tor versions.
    • Fix: Use AUTH_COOKIE (2) or AUTH_PASSWORD (1) explicitly.
  5. UNIX Socket Paths

    • Issue: Incorrect paths (e.g., /var/run/tor/control.sock) cause connection failures.
    • Fix: Validate paths exist and permissions are set (chmod 600 for cookie files).

Debugging

  • Enable Verbose Logging Set TorControl to debug mode to log raw commands/responses:
    $torControl->setDebug(true);
    
  • Check Tor Logs Monitor /var/log/tor/log for errors like Failed to parse/validate config.

Extension Points

  1. Custom Commands Extend the library by creating a wrapper class:

    class TorService {
        protected $torControl;
    
        public function __construct(TorControl $torControl) {
            $this->torControl = $torControl;
        }
    
        public function renewIdentity() {
            return $this->torControl->executeCommand('SIGNAL NEWNYM');
        }
    }
    
  2. Event Handling Parse NOTICE events for real-time monitoring:

    $events = $torControl->executeCommand('GETEVENTS CIRC');
    foreach ($events[0]['lines'] as $event) {
        Log::info("Tor event: $event");
    }
    
  3. Configuration Validation Validate Tor config before connecting (e.g., check ControlPort is enabled):

    $status = $torControl->executeCommand('GETINFO status');
    if (!isset($status[0]['lines']['ControlPort'])) {
        throw new \RuntimeException("Tor ControlPort not enabled");
    }
    

Tips

  • Use GETINFO for Status Checks Query Tor’s status before executing commands:
    $status = $torControl->executeCommand('GETINFO status');
    if ($status[0]['code'] !== 250) {
        // Handle error
    }
    
  • Leverage SETCONF for Runtime Tweaks Adjust settings dynamically (e.g., EntryNodes for path control):
    $torControl->executeCommand('SETCONF EntryNodes={us}');
    
  • Test with AUTH_NULL Locally Simplify development by disabling auth in torrc:
    ControlPort 9051
    ControlListenAddress 127.0.0.1
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
aimeos/prisma
besmartand-pro/php-quality-config
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views