Exemple #1
0
//phpHandler deals with PHP files. Warning, this blindly assumes there's a
//php-cgi file under the 'files' directory contained in the -root command
//argument. TODO.
func phpHandler(w http.ResponseWriter, req *http.Request, script string) {
	pwd := workingDirectory

	hostSplit := strings.Split(req.Host, ":")
	host := hostSplit[0]

	vHostFolder := path.Join(pwd, host)
	if ok, _ := fileIsDir(vHostFolder); ok {
		pwd = vHostFolder
	} else {
		pwd = path.Join(pwd, defaultVHost)
	}

	cgiHandler := cgi.Handler{
		Path: path.Join(workingDirectory, "files/php-cgi"), //TODO: Variable?
		Dir:  pwd,
		Root: pwd,
		//Args: []string{req.URL.Path},
		Env: []string{
			"REDIRECT_STATUS=200",
			//original, working for dummy files:
			//"SCRIPT_FILENAME=" + path.Join(pwd, script),
			//"SCRIPT_NAME=" + path.Join(pwd, script),

			"SCRIPT_FILENAME=" + path.Join(pwd, script), //Doit etre le OS ABSOLUTE php file path
			"SCRIPT_NAME=" + script,                     //Doit etre le WEB ABSOLUTE php file path
			"REQUEST_URI=" + req.RequestURI,
			"DOCUMENT_ROOT=" + pwd,
			"PHP_SELF=" + req.RequestURI, //PHP automagically appends PHP_SELF's value??
		},
	}
	errorLog(LOG_DEBUG, host, fmt.Sprintf("CGI Handler: %#v", cgiHandler))
	cgiHandler.ServeHTTP(w, req)
}
Exemple #2
0
func MapServer(bin, mapfile string, mapReq Request) ([]byte, error) {
	if !filepath.IsAbs(mapfile) {
		if wd, err := os.Getwd(); err == nil {
			mapfile = filepath.Join(wd, mapfile)
		}
	}

	q := url.Values{}
	q.Set("REQUEST", "GetMap")
	q.Set("SERVICE", "WMS")
	q.Set("VERSION", "1.1.1")
	q.Set("STYLES", "")
	q.Set("LAYERS", "map")
	q.Set("MAP", mapfile)

	q.Set("BBOX", fmt.Sprintf("%f,%f,%f,%f", mapReq.BBOX[0], mapReq.BBOX[1], mapReq.BBOX[2], mapReq.BBOX[3]))
	q.Set("WIDTH", fmt.Sprintf("%d", mapReq.Width))
	q.Set("HEIGHT", fmt.Sprintf("%d", mapReq.Height))
	q.Set("SRS", fmt.Sprintf("EPSG:%d", mapReq.EPSGCode))
	q.Set("FORMAT", mapReq.Format)

	if !filepath.IsAbs(bin) {
		for _, path := range strings.Split(os.Getenv("PATH"), string(filepath.ListSeparator)) {
			if fi, _ := os.Stat(filepath.Join(path, bin)); fi != nil {
				bin = filepath.Join(path, bin)
				break
			}
		}
	}

	wd := filepath.Dir(mapfile)
	handler := cgi.Handler{
		Path: bin,
		Dir:  wd,
	}

	w := &httptest.ResponseRecorder{
		Body: bytes.NewBuffer(nil),
	}

	req, err := http.NewRequest("GET", "/?"+q.Encode(), nil)
	if err != nil {
		return nil, err
	}

	handler.ServeHTTP(w, req)

	if w.Code != 200 {
		return nil, fmt.Errorf("error while calling mapserv CGI (status %d): %v", w.Code, string(w.Body.Bytes()))
	}
	if ct := w.Header().Get("Content-type"); ct != "" && !strings.HasPrefix(ct, "image") {
		return nil, fmt.Errorf(" mapserv CGI did not return image (%v)\n%v", w.Header(), string(w.Body.Bytes()))
	}
	return w.Body.Bytes(), nil
}
Exemple #3
0
func (m *MapServer) Render(mapfile string, dst io.Writer, mapReq Request) error {
	if !filepath.IsAbs(mapfile) {
		if wd, err := os.Getwd(); err == nil {
			mapfile = filepath.Join(wd, mapfile)
		}
	}

	q := url.Values{}
	q.Set("REQUEST", "GetMap")
	q.Set("SERVICE", "WMS")
	q.Set("VERSION", "1.1.1")
	q.Set("STYLES", "")
	q.Set("LAYERS", "map")
	q.Set("MAP", mapfile)
	q.Set("TRANSPARENT", "false")

	q.Set("BBOX", fmt.Sprintf("%f,%f,%f,%f", mapReq.BBOX[0], mapReq.BBOX[1], mapReq.BBOX[2], mapReq.BBOX[3]))
	q.Set("WIDTH", fmt.Sprintf("%d", mapReq.Width))
	q.Set("HEIGHT", fmt.Sprintf("%d", mapReq.Height))
	q.Set("SRS", fmt.Sprintf("EPSG:%d", mapReq.EPSGCode))
	q.Set("FORMAT", mapReq.Format)

	if mapReq.ScaleFactor != 0 {
		// mapserver default resolution is 72 dpi
		q.Set("MAP.RESOLUTION", fmt.Sprintf("%d", int(72*mapReq.ScaleFactor)))
	}

	wd := filepath.Dir(mapfile)
	handler := cgi.Handler{
		Path: m.bin,
		Dir:  wd,
	}

	w := &responseRecorder{
		Body: dst,
	}

	req, err := http.NewRequest("GET", "/?"+q.Encode(), nil)
	if err != nil {
		return err
	}

	handler.ServeHTTP(w, req)

	if w.Code != 200 {
		return fmt.Errorf("error while calling mapserv CGI (status %d)", w.Code)
	}
	if ct := w.Header().Get("Content-type"); ct != "" && !strings.HasPrefix(ct, "image") {
		return fmt.Errorf(" mapserv CGI did not return image (%v)", w.Header())
	}
	return nil
}
Exemple #4
0
func (h *CgiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	var isCGI bool
	file := filepath.FromSlash(path)
	if len(file) > 0 && os.IsPathSeparator(file[len(file)-1]) {
		file = file[:len(file)-1]
	}
	ext := filepath.Ext(file)
	bin, isCGI := h.LangMap[ext]
	file = filepath.Join(h.Root, file)

	f, e := os.Stat(file)
	if e != nil || f.IsDir() {
		if len(h.DefaultApp) > 0 {
			file = h.DefaultApp
		}
		ext := filepath.Ext(file)
		bin, isCGI = h.LangMap[ext]
	}

	if isCGI {
		var cgih cgi.Handler
		if h.UseLangMap {
			cgih = cgi.Handler{
				Path: bin,
				Dir:  h.Root,
				Root: h.Root,
				Args: []string{file},
				Env:  []string{"SCRIPT_FILENAME=" + file},
			}
		} else {
			cgih = cgi.Handler{
				Path: file,
				Root: h.Root,
			}
		}
		cgih.ServeHTTP(w, r)
	} else {
		if (f != nil && f.IsDir()) || file == "" {
			tmp := filepath.Join(file, "index.html")
			f, e = os.Stat(tmp)
			if e == nil {
				file = tmp
			}
		}
		http.ServeFile(w, r, file)
	}
}
Exemple #5
0
func CgiHandler(config map[string]string) http.Handler {
	h := new(cgi.Handler)

	h.Path = mustGet(config, "path")
	h.Root = mustGet(config, "mount")
	h.Dir = tryGet(config, "dir", "")
	h.Args = getSlice(config, "args")
	h.Env = getSlice(config, "env")
	h.InheritEnv = getSlice(config, "inherit")

	h.PathLocationHandler = http.DefaultServeMux

	return h
}
Exemple #6
0
func (m Map) serveMap(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		//TODO: Check that this is the correct status code to useg
		log.Printf(buildCommonLogFormat(r, time.Now(), 404, 0))
		return
	}

	normalizeKeys(r.Form, strings.ToUpper)

	if r.Form.Get("REQUEST") == "" {
		r.Form.Set("REQUEST", "GetCapabilities")
	}

	if r.Form.Get("SERVICE") == "" {
		r.Form.Set("SERVICE", "WMS")
	}
	//Don't let the user set the mapfile.
	r.Form.Del("MAP")
	r.Form.Set("MAP", m.Mapfile(r.Form.Get("SRS")))

	//ESRI software sends an invalid value?
	//Force it to xml unless it's a valid value
	if invalidException(r.Form.Get("EXCEPTIONS")) {
		r.Form.Set("EXCEPTIONS", "xml")
	}

	queryString := "QUERY_STRING=" + r.Form.Encode()
	// env := append(config.Environment, queryString)
	handler := cgi.Handler{
		Path: config.Mapserv,
		Dir:  config.Directory,
		Env:  []string{queryString},
	}

	handler.ServeHTTP(w, r)

	//Should be able to say w.Header().Get("Status"), w.Header().Get("Length(?)")
	log.Println(buildCommonLogFormat(r, time.Now(), 200, 0))
}
Exemple #7
0
// serve http with php script(cgi mode)
func Cgi(w http.ResponseWriter, r *http.Request, phpBin string, scriptFileName string) {
	handler := new(cgi.Handler)
	handler.Path = phpBin
	handler.Env = append(handler.Env, "REDIRECT_STATUS=CGI")
	handler.Env = append(handler.Env, "SCRIPT_FILENAME="+scriptFileName)

	handler.ServeHTTP(w, r)
}
Exemple #8
0
//executablehandler deals with self-contained executable files, like go
//compiled files, shell scripts and other programs we don't have the control
//ultimately. YOU are basically held responsible for the content. We're just
//doing the mailman at this rate.
//TODO: Pass HTTP GET parameters
func executableHandler(w http.ResponseWriter, req *http.Request, bin string) {
	pwd := workingDirectory

	hostSplit := strings.Split(req.Host, ":")
	host := hostSplit[0]

	vHostFolder := path.Join(pwd, host)
	vHostDirExists, _ := fileIsDir(vHostFolder)
	if vHostDirExists == true {
		pwd = vHostFolder
	} else {
		pwd = path.Join(pwd, defaultVHost)
	}
	cgiHandler := cgi.Handler{
		//Path: path.Join(pwd, req.URL.Path),
		Path: path.Join(pwd, bin),
		Dir:  pwd,
		Root: pwd,
		//Args: []string{file},
		//Env:  []string{"SCRIPT_FILENAME=" + file},
	}
	cgiHandler.ServeHTTP(w, req)
}
Exemple #9
0
/** 调用CGI程序的Handler */
func handleCgi(out http.ResponseWriter, request *http.Request) {
	u := (*request).URL

	var hdl cgi.Handler
	hdl.Path = "./" + u.Path
	hdl.Root = "/cgi/"
	hdl.Dir = "."
	hdl.ServeHTTP(out, request)
}
Exemple #10
0
func bundleCgiHandler(writer http.ResponseWriter, req *http.Request, path string, pathSegs []string) bool {
	segments := strings.Split(req.URL.Path, "/")
	cgiProgram := segments[3]

	// This is to try to prevent someone from trying to execute arbitrary commands (e.g. ../../../bash)
	if strings.Index(cgiProgram, ".") != -1 {
		return false
	}

	// Check the bin directories of the gopaths to find a command that matches
	//  the command specified here.
	cmd := ""

	for _, srcDir := range srcDirs {
		c := filepath.Join(srcDir, "../bin/"+cgiProgram)
		_, err := os.Stat(c)
		if err == nil {
			cmd = c
			break
		}
	}

	if cmd != "" {
		logger.Printf("GODEV CGI CALL: %v\n", cmd)
		handler := cgi.Handler{}
		handler.Path = cmd
		handler.Args = []string{"-godev"}
		handler.Logger = logger
		handler.InheritEnv = []string{"PATH", "GOPATH"} // TODO Add GOCERTFILE, GOKEYFILE, ...
		handler.ServeHTTP(writer, req)
		return true
	} else {
		logger.Printf("GODEV CGI MISS: %v\n", cgiProgram)
	}

	return false
}
Exemple #11
0
// Serve a CGI application 'path', stripping 'prefix' from the URL being
// requested
func CGIServer(path, prefix string) Component {
	handler := new(cgi.Handler)
	handler.Path = path
	handler.Root = prefix
	return NewHandlerComponent(handler)
}