Browse Source

add dyndns api

.newmind 10 months ago
parent
commit
1a4fe5eafa
1 changed files with 47 additions and 9 deletions
  1. 47 9
      main.go

+ 47 - 9
main.go

@@ -39,6 +39,8 @@ func main() {
 	}
 
 	http.HandleFunc("/update", handleUpdate)
+	http.HandleFunc("/v3/update", handleUpdateDyndns)
+	http.HandleFunc("/nic/update", handleUpdateDyndns)
 	log.Println("Server started on :8085")
 	log.Fatal(http.ListenAndServe(":8085", nil))
 }
@@ -61,10 +63,50 @@ func handleUpdate(w http.ResponseWriter, r *http.Request) {
 		req.IP = r.URL.Query().Get("ip")
 	}
 
-	if req.FQDN == "" || req.Key == "" {
-		http.Error(w, "FQDN and Key are required", http.StatusBadRequest)
+	err := update(r, req)
+	if err != nil {
+		http.Error(w, "Failed DNS Update: "+err.Error() , http.StatusInternalServerError)
 		return
 	}
+	w.WriteHeader(http.StatusOK)
+	fmt.Fprintln(w, "DNS update successful")
+}
+
+func handleUpdateDyndns(w http.ResponseWriter, r *http.Request) {
+	if r.Method != http.MethodGet {
+		http.Error(w, "Only GET methods are allowed", http.StatusMethodNotAllowed)
+		return
+	}
+	var req UpdateRequest
+
+	username, password, ok := r.BasicAuth()
+
+	if !ok {
+		http.Error(w, "User and Password required", http.StatusUnauthorized)
+		return
+	}
+	req.FQDN = r.URL.Query().Get("hostname")
+	req.IP = r.URL.Query().Get("myip")
+	req.Key = username+password
+
+
+
+	err := update(r, req)
+	if err != nil {
+		http.Error(w, "dnserr\n"+err.Error(), http.StatusInternalServerError)
+		return
+	}
+
+	w.WriteHeader(http.StatusOK)
+	fmt.Fprintln(w, "good")
+}
+
+
+func update(r *http.Request, req UpdateRequest) error {
+
+	if req.FQDN == "" || req.Key == "" {
+		return errors.New("FQDN and Key are required")
+	}
 
 	// Default to the requester's IP if IP is not provided
 	if req.IP == "" {
@@ -73,8 +115,7 @@ func handleUpdate(w http.ResponseWriter, r *http.Request) {
 	}
 
 	if net.ParseIP(req.IP) == nil {
-		http.Error(w, "Invalid IP address", http.StatusBadRequest)
-		return
+		return errors.New("Invalid IP address")
 	}
 
 	components := strings.Split(req.FQDN, ".")
@@ -85,12 +126,9 @@ func handleUpdate(w http.ResponseWriter, r *http.Request) {
 	err := updateDNS(zone, req.FQDN, req.Key, req.IP)
 	if err != nil {
 		log.Printf("Error updating DNS for %s: %v\n", req.FQDN, err)
-		w.WriteHeader(http.StatusInternalServerError)
-		fmt.Fprintf(w, "Failed to update DNS: %v\n", err)
-		return
+		return err
 	}
-	w.WriteHeader(http.StatusOK)
-	fmt.Fprintln(w, "DNS update successful")
+	return nil
 } 
 
 func getRequesterIP(r *http.Request) string {