DEV Community

llocustjr-web
llocustjr-web

Posted on

Telnet

Here is a PowerShell script (mud_telnet_scanner.ps1) that mirrors the Sawlties / πEve MUD-style Telnet loop, German Unicode transliteration/normalization (Ä/ä, Ö/ö, Ü/ü, ß), and URL/compound-token scanning (PrimePiElifiLukeKerryLocustJunior) alongside your existing 21-character [Ηi]^2...[/Ηi]^2 frame codec and factor-tree helpers.

mud_telnet_scanner.ps1

#Requires -Version 5.1
<#
.SYNOPSIS
    PowerShell MUD-style TCP/Telnet room simulator with German Unicode
    substitution, URL/compound-token scanning (e.g., PrimePiElifiLukeKerryLocustJunior),
    and PiEve 21-char [Hi]^2 frame helpers.
.EXAMPLE
    .\mud_telnet_scanner.ps1 -BindAddress "127.0.0.1" -Port 2323 -RoomLabel "Melania"
    .\mud_telnet_scanner.ps1 -ScanTarget "PrimePiElifiLukeKerryLocustJunior"
#>
[CmdletBinding()]
param(
    [string]$BindAddress = "127.0.0.1",

    [ValidateRange(1, 65535)]
    [int]$Port = 2323,

    [string]$RoomLabel = "Melania",

    [ValidateSet("Η", "H")]
    [string]$Marker = "Η",

    [AllowEmptyString()]
    [string]$ScanTarget = ""
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$script:FrameLength = 21
$script:FrameRegex = [regex]'(?s)\[(Η|H)i\]\^2([01]{8})\[/\1i\]\^2'

$script:GermanMap = @{
    [char]0x00C4 = "AE"  # Ä
    [char]0x00D6 = "OE"  # Ö
    [char]0x00DC = "UE"  # Ü
    [char]0x00E4 = "ae"  # ä
    [char]0x00F6 = "oe"  # ö
    [char]0x00FC = "ue"  # ü
    [char]0x00DF = "ss"  # ß
}

function Invoke-GermanUnicodeSubstitution {
    param(
        [AllowEmptyString()]
        [string]$InputText
    )
    if ([string]::IsNullOrEmpty($InputText)) {
        return ""
    }
    $nfc = $InputText.Normalize([System.Text.NormalizationForm]::FormC)
    $sb = [System.Text.StringBuilder]::new($nfc.Length)
    foreach ($ch in $nfc.ToCharArray()) {
        if ($script:GermanMap.ContainsKey($ch)) {
            [void]$sb.Append($script:GermanMap[$ch])
        }
        else {
            [void]$sb.Append($ch)
        }
    }
    return $sb.ToString()
}

function Invoke-AtbashChar {
    param([char]$Char)
    $code = [int]$Char
    if ($code -ge 97 -and $code -le 122) {
        return [char](122 - ($code - 97))
    }
    if ($code -ge 65 -and $code -le 90) {
        return [char](90 - ($code - 65))
    }
    return $Char
}

function Invoke-AtbashText {
    param(
        [AllowEmptyString()]
        [string]$InputText
    )
    if ([string]::IsNullOrEmpty($InputText)) {
        return ""
    }
    $sb = [System.Text.StringBuilder]::new($InputText.Length)
    foreach ($ch in $InputText.ToCharArray()) {
        [void]$sb.Append((Invoke-AtbashChar -Char $ch))
    }
    return $sb.ToString()
}

function ConvertTo-AtbashHi2 {
    param(
        [AllowEmptyString()]
        [string]$PlainText,
        [ValidateSet("Η", "H")]
        [string]$FrameMarker = "Η"
    )
    if ([string]::IsNullOrEmpty($PlainText)) {
        return ""
    }
    $reflected = Invoke-AtbashText -InputText $PlainText
    $utf8Bytes = [System.Text.Encoding]::UTF8.GetBytes($reflected)
    $sb = [System.Text.StringBuilder]::new($utf8Bytes.Length * $script:FrameLength)
    foreach ($b in $utf8Bytes) {
        $bits = [Convert]::ToString($b, 2).PadLeft(8, '0')
        [void]$sb.Append(("[{0}i]^2{1}[/{0}i]^2" -f $FrameMarker, $bits))
    }
    return $sb.ToString()
}

function ConvertFrom-AtbashHi2 {
    param(
        [AllowEmptyString()]
        [string]$Stream
    )
    if ($null -eq $Stream) {
        return ""
    }
    $cleaned = $Stream.Trim()
    if ([string]::IsNullOrEmpty($cleaned)) {
        return ""
    }

    $matches = $script:FrameRegex.Matches($cleaned)
    if ($matches.Count -eq 0) {
        throw "No valid binary frames found in stream."
    }

    $cursor = 0
    $byteList = [System.Collections.Generic.List[byte]]::new($matches.Count)
    foreach ($m in $matches) {
        if ($m.Index -ne $cursor -or $m.Length -ne $script:FrameLength) {
            throw "Corrupted, truncated, or mismatched frames detected."
        }
        $byteList.Add([Convert]::ToByte($m.Groups[2].Value, 2))
        $cursor = $m.Index + $m.Length
    }

    if ($cursor -ne $cleaned.Length) {
        throw "Trailing or unframed data detected."
    }

    $decodedReflected = [System.Text.Encoding]::UTF8.GetString($byteList.ToArray())
    return (Invoke-AtbashText -InputText $decodedReflected)
}

function Invoke-TargetScan {
    param([string]$RawTarget)
    $substituted = Invoke-GermanUnicodeSubstitution -InputText $RawTarget
    $candidateUri = if ($substituted -match '^[a-zA-Z][a-zA-Z0-9+.-]*://') {
        $substituted
    }
    else {
        "https://$substituted"
    }

    $hostOrSlug = $substituted
    try {
        $uri = [System.Uri]$candidateUri
        if (-not [string]::IsNullOrWhiteSpace($uri.Host)) {
            $hostOrSlug = $uri.Host
        }
    }
    catch {
        $hostOrSlug = $substituted
    }

    $segments = [regex]::Matches($substituted, '[A-Z][a-z0-9]*|[0-9]+|[^A-Za-z0-9\s]+') |
        ForEach-Object { $_.Value }

    $encoded = ConvertTo-AtbashHi2 -PlainText $substituted -FrameMarker $Marker
    $roundTripOk = ((ConvertFrom-AtbashHi2 -Stream $encoded) -eq $substituted)

    return [PSCustomObject]@{
        Raw             = $RawTarget
        GermanSub       = $substituted
        HostOrSlug      = $hostOrSlug
        Segments        = @($segments)
        RoundTripOk     = $roundTripOk
        EncodedLength   = $encoded.Length
        EncodedStream   = $encoded
    }
}

if (-not [string]::IsNullOrWhiteSpace($ScanTarget)) {
    $res = Invoke-TargetScan -RawTarget $ScanTarget
    Write-Output "Raw:           $($res.Raw)"
    Write-Output "German-sub:    $($res.GermanSub)"
    Write-Output "Host/Slug:     $($res.HostOrSlug)"
    Write-Output "Segments:      $($res.Segments -join ', ')"
    Write-Output "Round-trip OK: $($res.RoundTripOk)"
    Write-Output "Encoded chars: $($res.EncodedLength)"
    Write-Output "Encoded:       $($res.EncodedStream)"
    return
}

$endpoint = [System.Net.IPEndPoint]::new([System.Net.IPAddress]::Parse($BindAddress), $Port)
$listener = [System.Net.Sockets.TcpListener]::new($endpoint)
$listener.Start()
Write-Host "MUD Telnet listener running on ${BindAddress}:${Port} [room=$RoomLabel]"

try {
    while ($true) {
        $client = $listener.AcceptTcpClient()
        try {
            $stream = $client.GetStream()
            $reader = [System.IO.StreamReader]::new($stream, [System.Text.Encoding]::UTF8)
            $writer = [System.IO.StreamWriter]::new($stream, [System.Text.Encoding]::UTF8)
            $writer.AutoFlush = $true
            $writer.NewLine = "`r`n"

            $writer.WriteLine("=== Sawlties MUD Telnet [$RoomLabel] ===")
            $writer.WriteLine("Commands: look | scan <url_or_token> | say <msg> | quit")

            while ($client.Connected) {
                $writer.Write("[$RoomLabel]> ")
                $line = $reader.ReadLine()
                if ($null -eq $line) {
                    break
                }

                $cleanLine = (Invoke-GermanUnicodeSubstitution -InputText $line).Trim()
                if ([string]::IsNullOrWhiteSpace($cleanLine)) {
                    continue
                }

                $parts = $cleanLine -split '\s+', 2
                $cmd = $parts[0].ToLowerInvariant()
                $rest = if ($parts.Count -gt 1) { $parts[1] } else { "" }

                switch ($cmd) {
                    { $_ -in @("quit", "exit") } {
                        $writer.WriteLine("Disconnected.")
                        $client.Close()
                        break
                    }
                    "look" {
                        $writer.WriteLine("You stand in the [$RoomLabel] chamber. Try: scan PrimePiElifiLukeKerryLocustJunior")
                    }
                    "scan" {
                        $target = if ([string]::IsNullOrWhiteSpace($rest)) { "PrimePiElifiLukeKerryLocustJunior" } else { $rest.Trim() }
                        $info = Invoke-TargetScan -RawTarget $target
                        $writer.WriteLine("Scanned: $($info.Raw)")
                        $writer.WriteLine("German-sub: $($info.GermanSub)")
                        $writer.WriteLine("Segments: $($info.Segments -join ', ')")
                        $writer.WriteLine("Round-trip OK: $($info.RoundTripOk)")
                    }
                    "say" {
                        $writer.WriteLine("[$RoomLabel} echo]: $rest")
                    }
                    default {
                        $writer.WriteLine("Unknown command '$cmd'. Type 'look', 'scan <target>', or 'quit'.")
                    }
                }
            }
        }
        finally {
            if ($null -ne $client) {
                $client.Dispose()
            }
        }
    }
}
finally {
    $listener.Stop()
}

Enter fullscreen mode Exit fullscreen mode

How to Use It

  • One-shot scan without opening a socket:
.\mud_telnet_scanner.ps1 -ScanTarget "PrimePiElifiLukeKerryLocustJunior"

Enter fullscreen mode Exit fullscreen mode
  • Local MUD Telnet room loop (bound to 127.0.0.1):
.\mud_telnet_scanner.ps1 -BindAddress "127.0.0.1" -Port 2323 -RoomLabel "Melania"

Enter fullscreen mode Exit fullscreen mode

Then connect locally with telnet 127.0.0.1 2323 (or Test-NetConnection 127.0.0.1 -Port 2323) and run look, scan PrimePiElifiLukeKerryLocustJunior, say hello, or quit.

Would you like to dot-source this into `pieve_suite.ps1 so Get-Sha256Hex, Get-TokenMetadataMatches, and Get-FactorTree are also accessible inside scan` commands?

Top comments (0)