Example #1
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	tagflag.Parse(&flags)
	var clientConfig torrent.Config
	if flags.Mmap {
		clientConfig.DefaultStorage = storage.NewMMap("")
	}
	if flags.Addr != nil {
		clientConfig.ListenAddr = flags.Addr.String()
	}

	client, err := torrent.NewClient(&clientConfig)
	if err != nil {
		log.Fatalf("error creating client: %s", err)
	}
	defer client.Close()
	// Write status on the root path on the default HTTP muxer. This will be
	// bound to localhost somewhere if GOPPROF is set, thanks to the envpprof
	// import.
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		client.WriteStatus(w)
	})
	uiprogress.Start()
	addTorrents(client)
	if client.WaitAll() {
		log.Print("downloaded ALL the torrents")
	} else {
		log.Fatal("y u no complete torrents?!")
	}
	if flags.Seed {
		select {}
	}
}
Example #2
0
func main() {
	tagflag.Parse(&flags)
	for _, filename := range flags.TorrentFiles {
		metainfo, err := metainfo.LoadFromFile(filename)
		if err != nil {
			log.Print(err)
			continue
		}
		info := &metainfo.Info.Info
		if flags.JustName {
			fmt.Printf("%s\n", metainfo.Info.Name)
			continue
		}
		d := map[string]interface{}{
			"Name":        info.Name,
			"NumPieces":   info.NumPieces(),
			"PieceLength": info.PieceLength,
		}
		if flags.PieceHashes {
			d["PieceHashes"] = func() (ret []string) {
				for i := range iter.N(info.NumPieces()) {
					ret = append(ret, hex.EncodeToString(info.Pieces[i*20:(i+1)*20]))
				}
				return
			}()
		}
		b, _ := json.MarshalIndent(d, "", "  ")
		os.Stdout.Write(b)
	}
	if !flags.JustName {
		os.Stdout.WriteString("\n")
	}
}
Example #3
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	tagflag.Parse(&opts, tagflag.SkipBadTypes())
	clientConfig := opts.Config
	if opts.Mmap {
		clientConfig.DefaultStorage = storage.NewMMap("")
	}

	client, err := torrent.NewClient(&clientConfig)
	if err != nil {
		log.Fatalf("error creating client: %s", err)
	}
	defer client.Close()
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		client.WriteStatus(w)
	})
	uiprogress.Start()
	addTorrents(client)
	if client.WaitAll() {
		log.Print("downloaded ALL the torrents")
	} else {
		log.Fatal("y u no complete torrents?!")
	}
	if opts.Seed {
		select {}
	}
}
Example #4
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	tagflag.Parse(&opts, tagflag.SkipBadTypes())
	clientConfig := opts.Config
	if opts.Mmap {
		clientConfig.TorrentDataOpener = func(info *metainfo.Info) torrent.Data {
			ret, err := mmap.TorrentData(info, "")
			if err != nil {
				log.Fatalf("error opening torrent data for %q: %s", info.Name, err)
			}
			return ret
		}
	}

	client, err := torrent.NewClient(&clientConfig)
	if err != nil {
		log.Fatalf("error creating client: %s", err)
	}
	defer client.Close()
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		client.WriteStatus(w)
	})
	uiprogress.Start()
	addTorrents(client)
	if client.WaitAll() {
		log.Print("downloaded ALL the torrents")
	} else {
		log.Fatal("y u no complete torrents?!")
	}
	if opts.Seed {
		select {}
	}
}
Example #5
0
func main() {
	log.SetFlags(log.Flags() | log.Lshortfile)
	tagflag.Parse(&args)
	env := gasp.NewStandardEnv()
	err := env.RunProject(args.ProjectDir)
	if err != nil {
		fmt.Fprint(os.Stderr, err)
		os.Exit(1)
	}
}
Example #6
0
func main() {
	tagflag.Parse(nil)

	mi, err := metainfo.Load(os.Stdin)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error reading metainfo from stdin: %s", err)
		os.Exit(1)
	}

	fmt.Fprintf(os.Stdout, "%s\n", mi.Magnet().String())
}
Example #7
0
func main() {
	tagflag.Parse(nil)
	l, err := iplist.NewFromReader(os.Stdin)
	if err != nil {
		missinggo.Fatal(err)
	}
	wb := bufio.NewWriter(os.Stdout)
	defer wb.Flush()
	err = l.WritePacked(wb)
	if err != nil {
		missinggo.Fatal(err)
	}
}
Example #8
0
func main() {
	var args struct {
		Files []string `arity:"+" type:"pos"`
	}
	tagflag.Parse(&args)
	for _, arg := range args.Files {
		mi, err := metainfo.LoadFromFile(arg)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%x: %s\n", mi.Info.Hash, arg)
	}
}
Example #9
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	var args = struct {
		Timeout time.Duration
		Nodes   []string `type:"pos" arity:"+" help:"nodes to ping e.g. router.bittorrent.com:6881"`
	}{
		Timeout: math.MaxInt64,
	}
	tagflag.Parse(&args)
	s, err := dht.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("dht server on %s", s.Addr())
	timeout := time.After(args.Timeout)
	pongChan := make(chan pong)
	startPings(s, pongChan, args.Nodes)
	numResp := receivePongs(pongChan, timeout, len(args.Nodes))
	fmt.Printf("%d/%d responses (%f%%)\n", numResp, len(args.Nodes), 100*float64(numResp)/float64(len(args.Nodes)))
}
Example #10
0
func main() {
	var args struct {
		M uint `help:"num bits"`
		K uint `help:"num hashing functions"`
	}
	tagflag.Parse(&args, tagflag.Description("adds lines from stdin to a bloom filter with the given configuration, and gives collision stats at EOF"))
	filter := bloom.New(args.M, args.K)
	scanner := bufio.NewScanner(os.Stdin)
	n := 0
	collisions := 0
	for scanner.Scan() {
		if filter.TestAndAdd(scanner.Bytes()) {
			collisions++
		}
		n++
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintf(os.Stderr, "error reading stdin: %s", err)
		os.Exit(1)
	}
	fmt.Printf("collisions %d/%d (%f)\n", collisions, n, float64(collisions)/float64(n)*100)
}
Example #11
0
func main() {
	log.SetFlags(log.Flags() | log.Lshortfile)
	tagflag.Parse(&args)
	tempName := filepath.Join(os.TempDir(), fmt.Sprintf("gasp.%d.go", os.Getpid()))
	f, err := os.OpenFile(tempName, os.O_EXCL|os.O_CREATE|os.O_WRONLY, 0600)
	if err != nil {
		log.Fatal(err)
	}
	err = writeBootstrap(f)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("wrote %q", f.Name())
	goLook, err := exec.LookPath("go")
	if err != nil {
		log.Fatal(err)
	}
	err = syscall.Exec(goLook, []string{"go", "run", f.Name(), args.ProjectDir}, os.Environ())
	if err != nil {
		fmt.Fprintf(os.Stderr, "error execing go run: %s\n", err)
		os.Exit(1)
	}
}
Example #12
0
func main() {
	log.SetFlags(log.Flags() | log.Lshortfile)
	var args struct {
		AnnounceList []string `name:"a" help:"extra announce-list tier entry"`
		tagflag.StartPos
		Root string
	}
	tagflag.Parse(&args, tagflag.Description("Creates a torrent metainfo for the file system rooted at ROOT, and outputs it to stdout."))
	mi := metainfo.MetaInfo{
		AnnounceList: builtinAnnounceList,
	}
	for _, a := range args.AnnounceList {
		mi.AnnounceList = append(mi.AnnounceList, []string{a})
	}
	mi.SetDefaults()
	err := mi.Info.BuildFromFilePath(args.Root)
	if err != nil {
		log.Fatal(err)
	}
	err = mi.Write(os.Stdout)
	if err != nil {
		log.Fatal(err)
	}
}
Example #13
0
func main() {
	log.SetFlags(log.Flags() | log.Lshortfile)
	args := struct {
		Capacity tagflag.Bytes `short:"c"`
		Addr     string
	}{
		Capacity: -1,
		Addr:     "localhost:2076",
	}
	tagflag.Parse(&args)
	root, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("cache root at %q", root)
	c, err = filecache.NewCache(root)
	if err != nil {
		log.Fatalf("error creating cache: %s", err)
	}
	if args.Capacity < 0 {
		log.Printf("no capacity set, no evictions will occur")
	} else {
		c.SetCapacity(args.Capacity.Int64())
		log.Printf("setting capacity to %s bytes", humanize.Comma(args.Capacity.Int64()))
	}
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		p := r.URL.Path[1:]
		switch r.Method {
		case "DELETE":
			log.Printf("%s %s", r.Method, r.RequestURI)
			handleDelete(w, p)
			return
		case "PUT", "PATCH", "POST":
			contentRange := r.Header.Get("Content-Range")
			firstByte := parseContentRangeFirstByte(contentRange)
			log.Printf("%s (%d-) %s", r.Method, firstByte, r.RequestURI)
			handleNewData(w, p, firstByte, r.Body)
			return
		}
		log.Printf("%s %s %s", r.Method, r.Header.Get("Range"), r.RequestURI)
		f, err := c.OpenFile(p, os.O_RDONLY)
		if os.IsNotExist(err) {
			http.NotFound(w, r)
			return
		}
		if err != nil {
			log.Printf("couldn't open requested file: %s", err)
			http.Error(w, "couldn't open file", http.StatusInternalServerError)
			return
		}
		defer func() {
			go f.Close()
		}()
		info, _ := f.Stat()
		w.Header().Set("Content-Range", fmt.Sprintf("*/%d", info.Size()))
		http.ServeContent(w, r, p, info.ModTime(), f)
	})
	http.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
		info := c.Info()
		fmt.Fprintf(w, "Capacity: %d\n", info.Capacity)
		fmt.Fprintf(w, "Current Size: %d\n", info.Filled)
		fmt.Fprintf(w, "Item Count: %d\n", info.NumItems)
	})
	http.HandleFunc("/lru", func(w http.ResponseWriter, r *http.Request) {
		c.WalkItems(func(item filecache.ItemInfo) {
			fmt.Fprintf(w, "%s\t%d\t%s\n", item.Accessed, item.Size, item.Path)
		})
	})
	cert, err := missinggo.NewSelfSignedCertificate()
	if err != nil {
		log.Fatal(err)
	}
	srv := http.Server{
		Addr: args.Addr,
		TLSConfig: &tls.Config{
			Certificates: []tls.Certificate{cert},
		},
	}
	log.Fatal(srv.ListenAndServeTLS("", ""))
}
Example #14
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	var opts struct {
		torrent.Config `name:"Client"`
		Mmap           bool           `help:"memory-map torrent data"`
		TestPeer       []*net.TCPAddr `short:"p" help:"addresses of some starting peers"`
		Torrent        []string       `type:"pos" arity:"+" help:"torrent file path or magnet uri"`
	}
	tagflag.Parse(&opts, tagflag.SkipBadTypes())
	clientConfig := opts.Config
	if opts.Mmap {
		clientConfig.TorrentDataOpener = func(info *metainfo.Info) torrent.Data {
			ret, err := mmap.TorrentData(info, "")
			if err != nil {
				log.Fatalf("error opening torrent data for %q: %s", info.Name, err)
			}
			return ret
		}
	}

	torrents := opts.Torrent
	if len(torrents) == 0 {
		fmt.Fprintf(os.Stderr, "no torrents specified\n")
		return
	}
	client, err := torrent.NewClient(&clientConfig)
	if err != nil {
		log.Fatalf("error creating client: %s", err)
	}
	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		client.WriteStatus(w)
	})
	defer client.Close()
	for _, arg := range torrents {
		t := func() torrent.Torrent {
			if strings.HasPrefix(arg, "magnet:") {
				t, err := client.AddMagnet(arg)
				if err != nil {
					log.Fatalf("error adding magnet: %s", err)
				}
				return t
			} else {
				metaInfo, err := metainfo.LoadFromFile(arg)
				if err != nil {
					fmt.Fprintf(os.Stderr, "error loading torrent file %q: %s\n", arg, err)
					os.Exit(1)
				}
				t, err := client.AddTorrent(metaInfo)
				if err != nil {
					log.Fatal(err)
				}
				return t
			}
		}()
		err := t.AddPeers(func() (ret []torrent.Peer) {
			for _, ta := range opts.TestPeer {
				ret = append(ret, torrent.Peer{
					IP:   ta.IP,
					Port: ta.Port,
				})
			}
			return
		}())
		if err != nil {
			log.Fatal(err)
		}
		go func() {
			<-t.GotInfo()
			t.DownloadAll()
		}()
	}
	done := make(chan struct{})
	go func() {
		defer close(done)
		if client.WaitAll() {
			log.Print("downloaded ALL the torrents")
		} else {
			log.Fatal("y u no complete torrents?!")
		}
	}()
	ticker := time.NewTicker(time.Second)
waitDone:
	for {
		select {
		case <-done:
			break waitDone
		case <-ticker.C:
			os.Stdout.WriteString(progressLine(client))
		}
	}
	if opts.Seed {
		select {}
	}
}