func getHostPatternLists() map[string]clientconfig.HostsFile { conf := clientconfig.Get() lists := make(map[string]clientconfig.HostsFile) lists["blocked"] = conf.BlockedHosts lists["direct"] = conf.DirectHosts lists["blocked-central"] = conf.BlockedHostsCentral return lists }
func GetNotifications(w rest.ResponseWriter, r *rest.Request) { if UITEST { GetNotificationsUITest(w, r) return } var notifications []Notification conf := clientconfig.Get() // if setup is not done it is the only notification if !conf.Settings.Local.UserSetup() { notifications = append(notifications, Notification{ Level: "info", Title: "setup_required_title", Message: "setup_required_firstrun_message", Actions: []NotificationAction{ {"action_continue", "/setup-guide/"}, }, }) notifications = prepareNotifications(notifications) w.WriteJson(notifications) return } // put the global status of alkasir first if service.TransportOk() { notifications = append(notifications, Notification{ Level: "success", Title: "status_title", Message: "status_ok_message", }) notifications = append(notifications, Notification{ Level: "info", Title: "suggest_this_title", Message: "suggest_this_message", Actions: []NotificationAction{ {"action_continue", "/suggestions/"}, {"action_help", "/docs/__/report-url"}, }, }) } if !service.TransportOk() { notifications = append(notifications, Notification{ Level: "danger", Title: "status_title", Message: "transport_error_message", Actions: []NotificationAction{ {"action_help", "/docs/__/index"}, }, }) } notifications = prepareNotifications(notifications) w.WriteJson(notifications) }
func GetDebug(w rest.ResponseWriter, r *rest.Request) { response := debugexport.NewDebugResposne(VERSION, clientconfig.Get()) if r.URL.Query().Get("inbrowser") != "true" { w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=alkasir-debuginfo\"%s.txt\"", response.Header.ID)) } _ = w.WriteJson(response) }
func GetUserSettings(w rest.ResponseWriter, r *rest.Request) { conf := clientconfig.Get() response := UserSettings{ Language: conf.Settings.Local.Language, LanguageOptions: LanguageOptions, CountryCode: conf.Settings.Local.CountryCode, ClientAutoUpdate: conf.Settings.Local.ClientAutoUpdate, BlocklistAutoUpdate: conf.Settings.Local.BlocklistAutoUpdate, } w.WriteJson(response) }
func GetConnections(w rest.ResponseWriter, r *rest.Request) { conf := clientconfig.Get() var cSettings []ConnectionSetting connections := conf.Settings.Connections for _, v := range connections { cSettings = append(cSettings, ConnectionSetting{ ID: v.ID, Disabled: v.Disabled, Protected: v.Protected, Name: v.DisplayName(), }) } w.WriteJson(cSettings) }
// JSON api function func GetStatusSummary(w rest.ResponseWriter, r *rest.Request) { conf := clientconfig.Get() version := VERSION if version == "" { version = "development version" } summary := &StatusSummary{ AlkasirVersion: version, CountryCode: conf.Settings.Local.CountryCode, TransportOk: service.TransportOk(), LastBlocklistChange: lastBlocklistChange, BrowserOk: true, CentralOk: true, } w.WriteJson(summary) return }
// Fetch and list all host patterns func GetAllHostPatterns(w rest.ResponseWriter, r *rest.Request) { conf := clientconfig.Get() items := make([]HostPatternListItem, 0) for _, value := range conf.BlockedHosts.Hosts { items = append(items, toHostPatternListItem(value, "blocked")) } for _, value := range conf.DirectHosts.Hosts { items = append(items, toHostPatternListItem(value, "direct")) } for _, value := range conf.BlockedHostsCentral.Hosts { items = append(items, toHostPatternListItem(value, "blocked-central")) } w.WriteJson(items) return }
func PostBrowsercodeToClipboard(w rest.ResponseWriter, r *rest.Request) { conf := clientconfig.Get() ak := conf.Settings.Local.ClientAuthKey addr := conf.Settings.Local.ClientBindAddr bc := browsercode.BrowserCode{Key: ak} err := bc.SetHostport(addr) if err != nil { apiutils.WriteRestError(w, apierrors.NewInternalError(err)) return } err = bc.CopyToClipboard() if err != nil { apiutils.WriteRestError(w, apierrors.NewInternalError(err)) return } w.WriteJson(true) }
// Init does precondition check if the application can/should be started. // Init will return an error message with reason for exit printed. func Run() { if debugEnabled { log.Println("ALKASIR_DEBUG ENABLED!") err := os.Setenv("ALKASIR_DEBUG", "1") if err != nil { log.Fatal(err) } } if hotEnabled { log.Println("ALKASIR_HOT ENABLED!") err := os.Setenv("ALKASIR_HOT", "1") if err != nil { log.Fatal(err) } } // the darwin systray does not exit the main loop if runtime.GOOS != "darwin" { uiRunning.Add(1) } err := ui.Run(func() { Atexit(ui.Done) // start the getpublic ip updater. go func() { _ = shared.GetPublicIPAddr() }() if debugEnabled { go func() { err := http.ListenAndServe( fmt.Sprintf("localhost:%d", debugPort), nil) if err != nil { panic(err) } }() } // wipe user data if wipeData { settingsdir := clientconfig.ConfigPath() if settingsdir == "" { log.Println("[wipe] Configdir not set") os.Exit(1) } settingsfile := clientconfig.ConfigPath("settings.json") if _, err := os.Stat(settingsfile); os.IsNotExist(err) { log.Println("[wipe] No settings.json in configdir, will NOT wipe data") os.Exit(1) } log.Println("Wiping all user data") if err := os.RemoveAll(settingsdir); err != nil { log.Println(err) } } // Prepare logging logdir := clientconfig.ConfigPath("log") err := os.MkdirAll(logdir, 0775) if err != nil { log.Println("Could not create logging directory") os.Exit(1) } err = flag.Set("log_dir", logdir) if err != nil { panic(err) } lg.SetSrcHighlight("alkasir/cmd", "alkasir/pkg") lg.CopyStandardLogTo("INFO") // Start init if VERSION != "" { lg.Infoln("Alkasir v" + VERSION) } else { lg.Warningln("Alkasir dev version (VERSION not set)") } lg.V(1).Info("Log v-level:", lg.Verbosity()) _, err = clientconfig.Read() if err != nil { lg.Infoln("Could not read config") exit() } lg.V(30).Infoln("settings", clientconfig.Get().Settings) if saveChromeExt { err := saveChromeExtension() if err != nil { lg.Fatal(err) } } { configChanged, err := clientconfig.UpgradeConfig() if err != nil { lg.Fatalln("Could not upgrade config", err) } clientconfig.Update(func(conf *clientconfig.Config) error { if clientAuthKeyFlag != "" { lg.Warningln("Overriding generated authKey with", clientAuthKeyFlag) conf.Settings.Local.ClientAuthKey = clientAuthKeyFlag configChanged = true } if bindAddrFlag != "" { lg.Warningln("Overriding configured bindAddr with", bindAddrFlag) conf.Settings.Local.ClientBindAddr = bindAddrFlag configChanged = true } if centralAddrFlag != "" { lg.Warningln("Overriding central server addr with", centralAddrFlag) conf.Settings.Local.CentralAddr = centralAddrFlag configChanged = true } return nil }) if configChanged { if err := clientconfig.Write(); err != nil { lg.Warning(err) } } } conf := clientconfig.Get() loadTranslations(LanguageOptions...) if err := ui.Language(conf.Settings.Local.Language); err != nil { lg.Warningln(err) } go func() { select { case <-sigIntC: exit() case <-ui.Actions.Quit: exit() } }() for _, e := range []error{ mime.AddExtensionType(".json", "application/json"), mime.AddExtensionType(".js", "application/javascript"), mime.AddExtensionType(".css", "text/css"), mime.AddExtensionType(".md", "text/plain"), } { if e != nil { lg.Warning(e) } } err = startInternalHTTPServer(conf.Settings.Local.ClientAuthKey) if err != nil { lg.Fatal("could not start internal http services") } // Connect the default transport service.UpdateConnections(conf.Settings.Connections) service.UpdateTransports(conf.Settings.Transports) go service.StartConnectionManager(conf.Settings.Local.ClientAuthKey) // TODO: async pac.UpdateDirectList(conf.DirectHosts.Hosts) pac.UpdateBlockedList(conf.BlockedHostsCentral.Hosts, conf.BlockedHosts.Hosts) lastBlocklistChange = time.Now() go StartBlocklistUpgrader() if upgradeDiffsBaseURL != "" { lg.V(19).Infoln("upgradeDiffsBaseURL is ", upgradeDiffsBaseURL) go StartBinaryUpgradeChecker(upgradeDiffsBaseURL) } else { lg.Warningln("empty upgradeDiffsBaseURL, disabling upgrade checks") } lg.V(5).Info("Alkasir has started") }) // the darwin systray does not exit the main loop if runtime.GOOS != "darwin" { uiRunning.Done() } lg.Infoln("ui.Run ended") if err != nil { log.Println("client.Run error:", err) } }
// SubmitSuggestion initiates the comminication with Central for a Submission // session. func SubmitSuggestion(w rest.ResponseWriter, r *rest.Request) { // // TODO This is the response that must be forwarded from central/api and parsed by client and passed on to the browser. // apiutils.WriteRestError(w, // apierrors.NewInvalid("object", "suggestion", // fielderrors.ValidationErrorList{ // fielderrors.NewFieldValueNotSupported("URL", "...", []string{})})) // return ID := r.PathParam("id") suggestion, ok := client.GetSuggestion(ID) if !ok { apiutils.WriteRestError(w, apierrors.NewNotFound("suggestion", ID)) return } wanip := shared.GetPublicIPAddr() if wanip == nil { lg.Warning("could not resolve public ip addr") } conf := clientconfig.Get() restclient, err := NewRestClient() if err != nil { apiutils.WriteRestError(w, apierrors.NewInternalError(err)) return } tokenResp, err := suggestion.RequestToken( restclient, wanip, conf.Settings.Local.CountryCode) if err != nil { if apiutils.IsNetError(err) { apiutils.WriteRestError(w, apierrors.NewServerTimeout("alkasir-central", "request-submission-token", 0)) } else { apiutils.WriteRestError(w, apierrors.NewInternalError(err)) } return } n, err := suggestion.SendSamples(restclient) if err != nil { lg.Warningln("error sending samples", err.Error()) } lg.V(5).Infof("sent %d samples", n) // continue sending samples if future measuremetns are expected to come prepared, err := suggestion.Prepared() if err != nil { lg.Errorln(err) } else if !prepared { lg.V(5).Infof("all samples not collected, will try to send the rest when they are done") go func(s client.Suggestion) { start := time.Now() t := time.NewTicker(30 * time.Second) defer t.Stop() submitSamples: for range t.C { if time.Now().After(start.Add(15 * time.Minute)) { lg.Errorln("Stopping trying to send additional samples") return } prepared, err := suggestion.Prepared() if err != nil { lg.Errorln(err) return } if prepared { restclient, err := NewRestClient() if err != nil { continue submitSamples } n, err := suggestion.SendSamples(restclient) lg.V(5).Infof("sent %d samples", n) if err != nil { lg.Warningln("error sending samples", err.Error()) continue submitSamples } return } } }(suggestion) } u, err := url.Parse(suggestion.URL) if err != nil { lg.Errorln(err) } else { err := clientconfig.Update(func(conf *clientconfig.Config) error { conf.BlockedHosts.Add(u.Host) lastBlocklistChange = time.Now() pac.UpdateBlockedList(conf.BlockedHostsCentral.Hosts, conf.BlockedHosts.Hosts) return nil }) if err != nil { lg.Errorln(err) } } w.WriteJson(tokenResp) }