tor-dam

tor distributed announce mechanism (not a dht)
git clone https://git.parazyd.org/tor-dam
Log | Files | Refs | README | LICENSE

helpers.go (1992B)


      1 package main
      2 
      3 /*
      4  * Copyright (c) 2017-2021 Ivan Jelincic <parazyd@dyne.org>
      5  *
      6  * This file is part of tor-dam
      7  *
      8  * This program is free software: you can redistribute it and/or modify
      9  * it under the terms of the GNU Affero General Public License as published by
     10  * the Free Software Foundation, either version 3 of the License, or
     11  * (at your option) any later version.
     12  *
     13  * This program is distributed in the hope that it will be useful,
     14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     16  * GNU Affero General Public License for more details.
     17  *
     18  * You should have received a copy of the GNU Affero General Public License
     19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
     20  */
     21 
     22 import (
     23 	"bytes"
     24 	"compress/gzip"
     25 	"crypto/rand"
     26 	"encoding/base64"
     27 	"fmt"
     28 	"math/big"
     29 	"strings"
     30 )
     31 
     32 func genRandomASCII(length int) (string, error) {
     33 	var res string
     34 	for {
     35 		if len(res) == length {
     36 			return res, nil
     37 		}
     38 		num, err := rand.Int(rand.Reader, big.NewInt(int64(127)))
     39 		if err != nil {
     40 			return "", err
     41 		}
     42 		n := num.Int64()
     43 		if n > 32 && n < 127 {
     44 			res += fmt.Sprint(n)
     45 		}
     46 	}
     47 }
     48 
     49 func gzipEncode(data []byte) (string, error) {
     50 	var b bytes.Buffer
     51 	gz := gzip.NewWriter(&b)
     52 	if _, err := gz.Write(data); err != nil {
     53 		return "", err
     54 	}
     55 	if err := gz.Flush(); err != nil {
     56 		return "", err
     57 	}
     58 	if err := gz.Close(); err != nil {
     59 		return "", err
     60 	}
     61 
     62 	return base64.StdEncoding.EncodeToString(b.Bytes()), nil
     63 }
     64 
     65 func stringInSlice(str string, slice []string) bool {
     66 	for _, i := range slice {
     67 		if str == i {
     68 			return true
     69 		}
     70 	}
     71 	return false
     72 }
     73 
     74 func parseDirs(sl []string, data []byte) []string {
     75 	dirstr := string(data)
     76 	_dirs := strings.Split(dirstr, "\n")
     77 	for _, i := range _dirs {
     78 		if strings.HasPrefix(i, "DIR:") {
     79 			t := strings.Split(i, "DIR:")
     80 			if !stringInSlice(t[1], sl) {
     81 				if validateOnionAddress(t[1]) {
     82 					sl = append(sl, t[1])
     83 				}
     84 			}
     85 		}
     86 	}
     87 	return sl
     88 }