main.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package main
  7. import (
  8. "context"
  9. "crypto/tls"
  10. "errors"
  11. "flag"
  12. "fmt"
  13. "net/url"
  14. "os"
  15. "time"
  16. _ "github.com/syncthing/syncthing/lib/automaxprocs"
  17. "github.com/syncthing/syncthing/lib/config"
  18. "github.com/syncthing/syncthing/lib/discover"
  19. "github.com/syncthing/syncthing/lib/events"
  20. "github.com/syncthing/syncthing/lib/protocol"
  21. )
  22. var timeout = 5 * time.Second
  23. func main() {
  24. var server string
  25. flag.StringVar(&server, "server", "", "Announce server (blank for default set)")
  26. flag.DurationVar(&timeout, "timeout", timeout, "Query timeout")
  27. flag.Usage = usage
  28. flag.Parse()
  29. if flag.NArg() != 1 {
  30. flag.Usage()
  31. os.Exit(64)
  32. }
  33. id, err := protocol.DeviceIDFromString(flag.Args()[0])
  34. if err != nil {
  35. fmt.Println(err)
  36. os.Exit(1)
  37. }
  38. if server != "" {
  39. checkServers(id, server)
  40. } else {
  41. checkServers(id, config.DefaultDiscoveryServers...)
  42. }
  43. }
  44. type checkResult struct {
  45. server string
  46. addresses []string
  47. error
  48. }
  49. func checkServers(deviceID protocol.DeviceID, servers ...string) {
  50. t0 := time.Now()
  51. resc := make(chan checkResult)
  52. for _, srv := range servers {
  53. srv := srv
  54. go func() {
  55. res := checkServer(deviceID, srv)
  56. res.server = srv
  57. resc <- res
  58. }()
  59. }
  60. for range servers {
  61. res := <-resc
  62. u, _ := url.Parse(res.server)
  63. fmt.Printf("%s (%v):\n", u.Host, time.Since(t0))
  64. if res.error != nil {
  65. fmt.Println(" " + res.error.Error())
  66. }
  67. for _, addr := range res.addresses {
  68. fmt.Println(" address:", addr)
  69. }
  70. }
  71. }
  72. func checkServer(deviceID protocol.DeviceID, server string) checkResult {
  73. disco, err := discover.NewGlobal(server, tls.Certificate{}, nil, events.NoopLogger, nil)
  74. if err != nil {
  75. return checkResult{error: err}
  76. }
  77. res := make(chan checkResult, 1)
  78. time.AfterFunc(timeout, func() {
  79. res <- checkResult{error: errors.New("timeout")}
  80. })
  81. go func() {
  82. addresses, err := disco.Lookup(context.Background(), deviceID)
  83. res <- checkResult{addresses: addresses, error: err}
  84. }()
  85. return <-res
  86. }
  87. func usage() {
  88. fmt.Printf("Usage:\n\t%s [options] <device ID>\n\nOptions:\n", os.Args[0])
  89. flag.PrintDefaults()
  90. }