Skip to content

Commit

Permalink
Adds strip-wildcards
Browse files Browse the repository at this point in the history
  • Loading branch information
tomnomnom committed Oct 22, 2019
1 parent 8a3fac3 commit ab2c68b
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
2 changes: 2 additions & 0 deletions strip-wildcards/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
testdata
strip-wildcards
80 changes: 80 additions & 0 deletions strip-wildcards/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package main

import (
"bufio"
"bytes"
"fmt"
"math/rand"
"net"
"os"
"strings"
"time"
)

var globalRandString string

func init() {
rand.Seed(time.Now().UnixNano())
globalRandString = randString(16)
}

func main() {
sc := bufio.NewScanner(os.Stdin)
r := &resolver{cache: make(map[string]bool)}

for sc.Scan() {
name := strings.ToLower(sc.Text())

if !r.containsWildcard(name) {
fmt.Println(name)
}
}
}

type resolver struct {
cache map[string]bool
}

func (r *resolver) isWildcard(name string) bool {
if r.cache[name] {
return true
}

check := fmt.Sprintf("%s.%s", globalRandString, name)
_, err := net.LookupHost(check)
r.cache[name] = err == nil
return err == nil
}

func (r *resolver) containsWildcard(name string) bool {

parts := strings.Split(name, ".")

// Given one.two.target.com
// Start from the right hand side, check:
// $rand.com
// $rand.target.com
// $rand.two.target.com
// Do not check $rand.one.two.target.com otherwise
// we'd just be resolving every line of input which
// is what we're trying to avoid doing.
for i := len(parts) - 1; i > 1; i-- {
candidate := strings.Join(parts[i-1:len(parts)], ".")
if r.isWildcard(candidate) {
return true
}
}

return false
}

func randString(length int) string {
chars := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
out := bytes.Buffer{}

for i := 0; i < length; i++ {
out.WriteByte(chars[rand.Intn(len(chars))])
}

return out.String()
}

0 comments on commit ab2c68b

Please sign in to comment.