> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/sammwyy/mikuMikuBeam/llms.txt
> Use this file to discover all available pages before exploring further.

# Proxy Package

> Proxy loading, parsing, and filtering utilities

The `proxy` package provides utilities for loading proxies from files, parsing user agent lists, and filtering proxies by attack method.

## Package Overview

```go theme={null}
import "github.com/sammwyy/mikumikubeam/internal/proxy"
```

This package handles:

* Loading proxies from text files with various formats
* Parsing authentication credentials
* Loading user agent lists
* Filtering proxies by protocol compatibility

## Functions

### LoadProxies

```go theme={null}
func LoadProxies(path string) ([]engine.Proxy, error)
```

Loads and parses proxies from a text file. Supports multiple formats and protocols.

**Parameters:**

<ParamField name="path" type="string">
  Path to the proxy list file
</ParamField>

**Returns:**

<ResponseField name="proxies" type="[]engine.Proxy">
  Parsed proxy list
</ResponseField>

<ResponseField name="error" type="error">
  Error if file cannot be read or parsed
</ResponseField>

**Supported Formats:**

<CodeGroup>
  ```txt Basic Format theme={null}
  host:port
  192.168.1.100:8080
  example.com:3128
  ```

  ```txt With Protocol theme={null}
  http://host:port
  https://host:port
  socks4://host:port
  socks5://host:port
  ```

  ```txt With Authentication theme={null}
  username:password@host:port
  http://user:pass@host:port
  socks5://admin:secret@192.168.1.1:1080
  ```

  ```txt With Comments theme={null}
  # Production proxies
  http://proxy1.example.com:8080
  http://proxy2.example.com:8080

  # Staging proxies
  http://proxy-staging.example.com:3128
  ```
</CodeGroup>

**Parsing Rules:**

<AccordionGroup>
  <Accordion title="Protocol Detection">
    * Default protocol: `http`
    * Explicit protocol: `http://`, `https://`, `socks4://`, `socks5://`
    * Protocol prefix is removed from the host string
  </Accordion>

  <Accordion title="Authentication Extraction">
    * Regex pattern: `^([^:]+):([^@]+)@(.+)$`
    * Format: `username:password@host:port`
    * Username and password stored in `Proxy.Username` and `Proxy.Password`
    * Credentials removed from host string after extraction
  </Accordion>

  <Accordion title="Port Parsing">
    * Default port: `8080`
    * Custom port: parsed from `host:port` format
    * Invalid port numbers fall back to `8080`
  </Accordion>

  <Accordion title="Comments and Blank Lines">
    * Lines starting with `#` are ignored
    * Empty lines and whitespace-only lines are skipped
    * Leading/trailing whitespace is trimmed from all lines
  </Accordion>
</AccordionGroup>

**Example:**

```go theme={null}
proxies, err := proxy.LoadProxies("proxies.txt")
if err != nil {
    log.Fatalf("Failed to load proxies: %v", err)
}

fmt.Printf("Loaded %d proxies\n", len(proxies))
for _, p := range proxies {
    fmt.Printf("%s://%s:%d\n", p.Protocol, p.Host, p.Port)
    if p.Username != "" {
        fmt.Printf("  Auth: %s:%s\n", p.Username, p.Password)
    }
}
```

**Output:**

```
Loaded 3 proxies
http://192.168.1.100:8080
socks5://proxy.example.com:1080
  Auth: admin:secret
https://secure-proxy.com:443
```

### LoadUserAgents

```go theme={null}
func LoadUserAgents(path string) ([]string, error)
```

Loads user agent strings from a text file (one per line).

**Parameters:**

<ParamField name="path" type="string">
  Path to the user agent list file
</ParamField>

**Returns:**

<ResponseField name="userAgents" type="[]string">
  List of user agent strings
</ResponseField>

<ResponseField name="error" type="error">
  Error if file cannot be read
</ResponseField>

**File Format:**

```txt user-agents.txt theme={null}
# Desktop browsers
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36

# Mobile browsers
Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1
Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36
```

**Processing:**

* Splits file by newlines
* Trims whitespace from each line
* Skips empty lines
* Skips lines starting with `#` (comments)

**Example:**

```go theme={null}
userAgents, err := proxy.LoadUserAgents("user-agents.txt")
if err != nil {
    log.Fatalf("Failed to load user agents: %v", err)
}

fmt.Printf("Loaded %d user agents\n", len(userAgents))

// Randomly select a user agent
import "math/rand"
ua := userAgents[rand.Intn(len(userAgents))]
fmt.Printf("Selected: %s\n", ua)
```

### FilterByMethod

```go theme={null}
func FilterByMethod(proxies []engine.Proxy, method engine.AttackKind) []engine.Proxy
```

Filters proxies to only those compatible with the given attack method.

**Parameters:**

<ParamField name="proxies" type="[]engine.Proxy">
  Full list of loaded proxies
</ParamField>

<ParamField name="method" type="engine.AttackKind">
  Attack method to filter for
</ParamField>

**Returns:**

<ResponseField name="filtered" type="[]engine.Proxy">
  Proxies compatible with the specified method
</ResponseField>

**Compatibility Matrix:**

| Attack Method       | http | https | socks4 | socks5 |
| ------------------- | ---- | ----- | ------ | ------ |
| **http\_flood**     | ✅    | ✅     | ✅      | ✅      |
| **http\_bypass**    | ✅    | ✅     | ✅      | ✅      |
| **http\_slowloris** | ❌    | ❌     | ✅      | ✅      |
| **tcp\_flood**      | ❌    | ❌     | ✅      | ✅      |
| **minecraft\_ping** | ❌    | ❌     | ✅      | ✅      |

<Note>
  **Why SOCKS-only for some attacks?**

  HTTP/HTTPS proxies work at the application layer and can only forward HTTP requests. Attacks like Slowloris, TCP flood, and Minecraft ping require raw TCP connections, which only SOCKS proxies support.
</Note>

**Example:**

```go theme={null}
allProxies, _ := proxy.LoadProxies("proxies.txt")

// Filter for HTTP flood (all protocols work)
httpProxies := proxy.FilterByMethod(allProxies, engine.AttackHTTPFlood)
fmt.Printf("HTTP Flood: %d proxies\n", len(httpProxies))

// Filter for Slowloris (SOCKS only)
slowlorisProxies := proxy.FilterByMethod(allProxies, engine.AttackHTTPSlowloris)
fmt.Printf("Slowloris: %d proxies\n", len(slowlorisProxies))

// Filter for TCP flood (SOCKS only)
tcpProxies := proxy.FilterByMethod(allProxies, engine.AttackTCPFlood)
fmt.Printf("TCP Flood: %d proxies\n", len(tcpProxies))
```

**Output:**

```
HTTP Flood: 150 proxies
Slowloris: 45 proxies
TCP Flood: 45 proxies
```

## Complete Usage Example

```go theme={null}
package main

import (
    "context"
    "log"
    "time"
    
    "github.com/sammwyy/mikumikubeam/internal/engine"
    "github.com/sammwyy/mikumikubeam/internal/proxy"
    "github.com/sammwyy/mikumikubeam/internal/attacks/http"
    targetpkg "github.com/sammwyy/mikumikubeam/pkg/target"
)

func main() {
    // 1. Load proxies from file
    allProxies, err := proxy.LoadProxies("proxies.txt")
    if err != nil {
        log.Fatalf("Failed to load proxies: %v", err)
    }
    log.Printf("Loaded %d proxies", len(allProxies))
    
    // 2. Load user agents
    userAgents, err := proxy.LoadUserAgents("user-agents.txt")
    if err != nil {
        log.Fatalf("Failed to load user agents: %v", err)
    }
    log.Printf("Loaded %d user agents", len(userAgents))
    
    // 3. Choose attack method
    attackMethod := engine.AttackHTTPFlood
    
    // 4. Filter proxies by method
    filteredProxies := proxy.FilterByMethod(allProxies, attackMethod)
    log.Printf("Filtered to %d proxies for %s", len(filteredProxies), attackMethod)
    
    // 5. Parse target
    targetNode, err := targetpkg.Parse("https://example.com")
    if err != nil {
        log.Fatalf("Invalid target: %v", err)
    }
    
    // 6. Setup engine
    registry := engine.NewRegistry()
    registry.Register(engine.AttackHTTPFlood, http.NewFloodWorker())
    eng := engine.NewEngine(*registry)
    
    // 7. Start attack
    params := engine.AttackParams{
        Target:      "https://example.com",
        TargetNode:  targetNode,
        Duration:    60 * time.Second,
        PacketDelay: 10 * time.Millisecond,
        PacketSize:  1024,
        Method:      attackMethod,
        Threads:     16,
        Verbose:     true,
    }
    
    ctx := context.Background()
    statsCh, err := eng.Start("attack-1", ctx, params, filteredProxies, userAgents)
    if err != nil {
        log.Fatalf("Failed to start attack: %v", err)
    }
    
    // 8. Monitor stats
    for stat := range statsCh {
        log.Printf("PPS: %d | Total: %d | Proxies: %d",
            stat.PacketsPerS, stat.TotalPackets, stat.Proxies)
        if stat.Log != "" {
            log.Printf("  %s", stat.Log)
        }
    }
    
    log.Println("Attack completed")
}
```

## Proxy File Best Practices

<AccordionGroup>
  <Accordion title="Organize by Type">
    Use comments to organize proxies by protocol, region, or purpose:

    ```txt theme={null}
    # HTTP Proxies - US East
    http://us-east-1.proxy.com:8080
    http://us-east-2.proxy.com:8080

    # SOCKS5 Proxies - EU
    socks5://eu-proxy-1.com:1080
    socks5://eu-proxy-2.com:1080

    # Premium Proxies (authenticated)
    http://user:pass@premium-proxy.com:3128
    ```
  </Accordion>

  <Accordion title="Test Proxy Validity">
    Regularly validate proxies before use:

    ```go theme={null}
    func validateProxies(proxies []engine.Proxy) []engine.Proxy {
        valid := []engine.Proxy{}
        for _, p := range proxies {
            if testProxy(p) {
                valid = append(valid, p)
            }
        }
        return valid
    }
    ```
  </Accordion>

  <Accordion title="Separate by Attack Type">
    Maintain separate files for different attack requirements:

    ```
    proxies/
    ├── http-proxies.txt      # For HTTP flood/bypass
    ├── socks-proxies.txt     # For Slowloris/TCP/Minecraft
    └── all-proxies.txt       # Master list
    ```
  </Accordion>

  <Accordion title="Document Credentials Securely">
    Store authenticated proxies in separate, secured files:

    ```txt premium-proxies.txt theme={null}
    # Premium SOCKS5 - Provider A
    socks5://account1:token123@premium-a.com:1080
    socks5://account2:token456@premium-a.com:1080
    ```

    Ensure proper file permissions:

    ```bash theme={null}
    chmod 600 premium-proxies.txt
    ```
  </Accordion>
</AccordionGroup>

## Error Handling

### File Not Found

```go theme={null}
proxies, err := proxy.LoadProxies("missing.txt")
if err != nil {
    if os.IsNotExist(err) {
        log.Fatal("Proxy file not found")
    }
    log.Fatalf("Error loading proxies: %v", err)
}
```

### Empty Proxy List

```go theme={null}
proxies, _ := proxy.LoadProxies("proxies.txt")
if len(proxies) == 0 {
    log.Fatal("No valid proxies found in file")
}

filtered := proxy.FilterByMethod(proxies, engine.AttackHTTPSlowloris)
if len(filtered) == 0 {
    log.Fatal("No SOCKS proxies available for Slowloris attack")
}
```

### Malformed Lines

```go theme={null}
// LoadProxies silently skips malformed lines
// To track skipped lines, implement custom parsing:

func loadProxiesWithValidation(path string) ([]engine.Proxy, []error) {
    file, _ := os.Open(path)
    defer file.Close()
    
    var proxies []engine.Proxy
    var errors []error
    
    scanner := bufio.NewScanner(file)
    lineNum := 0
    for scanner.Scan() {
        lineNum++
        line := strings.TrimSpace(scanner.Text())
        
        // Skip comments and empty lines
        if line == "" || strings.HasPrefix(line, "#") {
            continue
        }
        
        proxy, err := parseProxy(line)
        if err != nil {
            errors = append(errors, fmt.Errorf("line %d: %w", lineNum, err))
            continue
        }
        proxies = append(proxies, proxy)
    }
    
    return proxies, errors
}
```

## See Also

* [Engine Package](/api/engine) - Using proxies in attacks
* [AttackWorker Interface](/api/attack-workers) - How workers use proxies
