From f6d432dbfac5af069d670b472dac6f33b26cfba5 Mon Sep 17 00:00:00 2001 From: maride Date: Tue, 21 Aug 2018 22:41:03 +0200 Subject: Add container start/stop handlers --- src/http.go | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) (limited to 'src') diff --git a/src/http.go b/src/http.go index d06ef1b..287004f 100644 --- a/src/http.go +++ b/src/http.go @@ -32,6 +32,8 @@ func runHTTPServer() (error) { r.HandleFunc("/challenges", challengesHandler).Methods("GET") r.HandleFunc("/api/getChallenges", getChallengesHandler).Methods("GET") r.HandleFunc("/api/submitFlag", submitFlagHandler).Methods("POST") + r.HandleFunc("/api/startContainer", startContainerHandler).Methods("POST") + r.HandleFunc("/api/stopContainer", stopContainerHandler).Methods("POST") address := fmt.Sprintf(":%d", *port) return http.ListenAndServe(address, r) @@ -227,3 +229,56 @@ func submitFlagHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte(jsonAnswer)) } } + +// Starts the given container and return its IP address if successful +func startContainerHandler(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + challengeName := r.Form.Get("challengeName") + session, cookieNotFoundError := r.Cookie("session") + + errorString := "" + addressString := "" + + if cookieNotFoundError != nil || !isValidSession(session.Value) { + // either no session cookie found, or it contains an invalid session token. Redirect. + http.Redirect(w, r, "/login", http.StatusTemporaryRedirect) + } else { + // valid session token found, now search for the requested challenge + for _, challenge := range challenges { + if challenge.Name == challengeName { + // found challenge, start container + + cc, err := startChallengeContainer(challenge) + if err != nil { + log.Println(err.Error()) + errorString = "Server error." + } else { + addressString = cc.IP + } + break + } + } + + // inform our client + jsonAnswer, _ := json.Marshal(map[string]string{ + "error": errorString, + "address": addressString, + }) + w.Write([]byte(jsonAnswer)) + } +} + +// Stops the given container and returns if it stopped +func stopContainerHandler(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + challengeName := r.Form.Get("challengeName") + session, cookieNotFoundError := r.Cookie("session") + + if cookieNotFoundError != nil || !isValidSession(session.Value) { + // either no session cookie found, or it contains an invalid session token. Redirect. + http.Redirect(w, r, "/login", http.StatusTemporaryRedirect) + } else { + // valid session token found, now search for the requested challenge + stopChallengeContainer(challengeName) + } +} -- cgit 1.4.1