package webapi import ( "errors" "fmt" "log" "net" "net/http" "net/url" "gitea.nehmer.net/torben/dyndns/service" ) func init() { router.HandleFunc("/update", handleUpdate) } func handleUpdate(w http.ResponseWriter, r *http.Request) { err := r.ParseForm() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } ur, err := createUpdateRequestFromForm(r.Form) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } uc, err := service.LoadConfigForUser(ur.UserName, ur.Password) if err != nil { if _, ok := err.(*service.UnauthorizedError); ok { http.Error(w, err.Error(), http.StatusUnauthorized) } else { http.Error(w, err.Error(), http.StatusInternalServerError) } log.Printf("Authorization failed: %v", err) return } ur.Config = uc // Start DEBUG Output log.Println("Final request") log.Println(ur.PrettyPrint()) for _, other := range uc.Others { log.Printf("Other %s, IID %v, merged: %v", other.Hostname, other.V6IID, other.ConvertIIDToAddress(ur.IPv6Net)) } log.Println("WebAPI Config:") log.Println(C.PrettyPrint()) log.Println("Service Config:") log.Println(service.C.PrettyPrint()) // End DEBUG Output if err := ur.Process(); err != nil { log.Printf("failed to process UpdateRequest: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) } w.Header().Set("Content-Type", "text/plain") fmt.Fprintln(w, "OK") } func createUpdateRequestFromForm(form url.Values) (*service.UpdateRequest, error) { ur := &service.UpdateRequest{} if form.Get("IPv4") != "" { if ur.IPv4 = net.ParseIP(form.Get("IPv4")); ur.IPv4 == nil { return nil, errors.New("could not parse IPv4 address") } } if form.Get("IPv6") != "" { if ur.IPv6 = net.ParseIP(form.Get("IPv6")); ur.IPv6 == nil { return nil, errors.New("could not parse IPv6 address") } } ur.UserName = form.Get("UserName") if ur.UserName == "" { return nil, errors.New("a UserName must be specified") } ur.Password = form.Get("Password") if ur.Password == "" { return nil, errors.New("a Password must be specified") } if ip6net := form.Get("IPv6Net"); ip6net != "" { _, ipnet, err := net.ParseCIDR(ip6net) if err != nil { return nil, errors.New("could not parse IPv6Net") } ur.IPv6Net = ipnet } return ur, nil }