Ejemplo n.º 1
0
func serveError502(conn *http.Conn, host string) {
	conn.WriteHeader(http.StatusBadGateway)
	conn.SetHeader(contentType, textHTML)
	conn.SetHeader(contentLength, error502Length)
	conn.Write(error502)
	logRequest(http.StatusBadGateway, host, conn)
}
Ejemplo n.º 2
0
func (set *TileServer) ServeHTTP(conn *http.Conn, req *http.Request) {
	req.ParseForm()
	var x, y, zoom int
	x, err := strconv.Atoi(req.Form["x"][0])
	if err == nil {
		y, err = strconv.Atoi(req.Form["y"][0])
	}
	if err == nil {
		zoom, err = strconv.Atoi(req.Form["z"][0])
	}

	if err != nil {
		fmt.Println("Err:", err.String())
		conn.WriteHeader(404)
		return
	}

	tile := set.GetTile(x, y, zoom)
	if tile == nil {
		fmt.Println("No tile at", x, y, zoom)
		conn.WriteHeader(404)
		return
	}
	conn.Write(tile)
}
Ejemplo n.º 3
0
func add(c *http.Conn, req *http.Request) {
	if req.Method == "POST" && len(strings.TrimSpace(req.FormValue("code"))) > 0 {
		paste := savePaste(req.FormValue("code"), req.FormValue("private") != "")
		c.SetHeader("Location", "/view/"+paste)
		c.WriteHeader(http.StatusFound)
	} else {
		c.Write(strings.Bytes("No code submitted.\n"))
	}
}
Ejemplo n.º 4
0
Archivo: views.go Proyecto: tung/goblog
// url: /blog/entry/add
func AddEntry(c *http.Conn, req *http.Request) {
	req.ParseForm();
	heading, body := req.FormValue("heading"), req.FormValue("body");
	if len(heading) > 0 && len(body) > 0 {
		blog.AddEntry(heading, body)
	}
	c.SetHeader("Location", "/blog");
	c.WriteHeader(http.StatusFound);
}
Ejemplo n.º 5
0
func (proxy *Proxy) ServeHTTP(conn *http.Conn, req *http.Request) {

	// Open a connection to the Hub.
	hubconn, err := net.Dial("tcp", "", remoteAddr)
	if err != nil {
		if debugMode {
			fmt.Printf("Couldn't connect to remote %s: %v\n", remoteHost, err)
		}
		return
	}

	hub := tls.Client(hubconn, tlsconf.Config)
	defer hub.Close()

	// Modify the request Host: header.
	req.Host = remoteHost

	// Send the request to the Hub.
	err = req.Write(hub)
	if err != nil {
		if debugMode {
			fmt.Printf("Error writing to the hub: %v\n", err)
		}
		return
	}

	// Parse the response from the Hub.
	resp, err := http.ReadResponse(bufio.NewReader(hub), req.Method)
	if err != nil {
		if debugMode {
			fmt.Printf("Error parsing response from the hub: %v\n", err)
		}
		return
	}

	// Set the received headers back to the initial connection.
	for k, v := range resp.Header {
		conn.SetHeader(k, v)
	}

	// Read the full response body.
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		if debugMode {
			fmt.Printf("Error reading response from the hub: %v\n", err)
		}
		resp.Body.Close()
		return
	}

	// Write the response body back to the initial connection.
	resp.Body.Close()
	conn.WriteHeader(resp.StatusCode)
	conn.Write(body)

}
Ejemplo n.º 6
0
func (s *Swif) handleError(code int, c *http.Conn) {
	switch code {
	case http.StatusBadRequest:
		c.WriteHeader(code)
		io.WriteString(c, "Invalid Request")
	default:
		c.WriteHeader(http.StatusBadRequest)
		io.WriteString(c, "Invalid Request")
	}
}
Ejemplo n.º 7
0
Archivo: views.go Proyecto: tung/goblog
// url: /blog/comment/add
func AddComment(c *http.Conn, req *http.Request) {
	req.ParseForm();
	entryIDString, text := req.FormValue("entry_id"), req.FormValue("text");
	if len(entryIDString) > 0 && len(text) > 0 {
		if entryID, parseErr := strconv.Atoi(entryIDString); parseErr == nil {
			if foundEntry := blog.FindEntry(entryID); foundEntry != nil {
				foundEntry.AddComment(text);
			}
		}
	}
	c.SetHeader("Location", "/blog/entry/" + entryIDString);
	c.WriteHeader(http.StatusFound);
}
Ejemplo n.º 8
0
func FileServer(c *http.Conn, req *http.Request) {
	c.SetHeader("content-type", "text/plain; charset=utf-8")
	pathVar.Add(req.URL.Path, 1)
	path := *webroot + req.URL.Path // TODO: insecure: use os.CleanName
	f, err := os.Open(path, os.O_RDONLY, 0)
	if err != nil {
		c.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(c, "open %s: %v\n", path, err)
		return
	}
	n, _ := io.Copy(c, f)
	fmt.Fprintf(c, "[%d bytes]\n", n)
	f.Close()
}
Ejemplo n.º 9
0
func serveHTTP(c *http.Conn, req *http.Request) {
	if req.Method != "CONNECT" {
		c.SetHeader("Content-Type", "text/plain; charset=utf-8")
		c.WriteHeader(http.StatusMethodNotAllowed)
		io.WriteString(c, "405 must CONNECT to "+rpcPath+"\n")
		return
	}
	conn, _, err := c.Hijack()
	if err != nil {
		log.Stderr("rpc hijacking ", c.RemoteAddr, ": ", err.String())
		return
	}
	io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n")
	server.input(conn)
}
Ejemplo n.º 10
0
Archivo: views.go Proyecto: tung/goblog
// url: /blog
func Index(c *http.Conn, req *http.Request) {
	revEntries := blog.EntriesReversed();
	frontPageEntries := make([]frontPageEntry, len(revEntries));
	for i, e := range revEntries {
		frontPageEntries[i].Entry = e;
		frontPageEntries[i].CommentCount = e.Comments.Len();
	}

	if tmpl, err := loadTemplate("index.html"); err == nil {
		tmpl.Execute(frontPageEntries, c);
	} else {
		c.SetHeader("Content-Type", "text/plain; charset=utf-8");
		c.WriteHeader(http.StatusInternalServerError);
		io.WriteString(c, "500 internal server error\n");
	}
}
Ejemplo n.º 11
0
func (redirector *Redirector) ServeHTTP(conn *http.Conn, req *http.Request) {

	var url string
	if len(req.URL.RawQuery) > 0 {
		url = fmt.Sprintf(redirectURLQuery, redirector.url, req.URL.Path, req.URL.RawQuery)
	} else {
		url = fmt.Sprintf(redirectURL, redirector.url, req.URL.Path)
	}

	if len(url) == 0 {
		url = "/"
	}

	conn.SetHeader("Location", url)
	conn.WriteHeader(http.StatusMovedPermanently)
	fmt.Fprintf(conn, redirectHTML, url)
	logRequest(http.StatusMovedPermanently, req.Host, conn)

}
Ejemplo n.º 12
0
Archivo: web.go Proyecto: tjweir/web.go
func httpHandler(c *http.Conn, req *http.Request) {
	path := req.URL.Path

	//try to serve a static file
	if strings.HasPrefix(path, "/static/") {
		staticFile := path[8:]
		if len(staticFile) > 0 {
			http.ServeFile(c, req, "static/"+staticFile)
			return
		}
	}

	req.ParseForm()
	resp := routeHandler((*Request)(req))
	c.WriteHeader(resp.StatusCode)
	if resp.Body != nil {
		body, _ := ioutil.ReadAll(resp.Body)
		c.Write(body)
	}
}
Ejemplo n.º 13
0
func ServeTestHTTP(conn *http.Conn, req *http.Request) {
	req.Close = true
	if api_key, ok := req.Header["Authorization"]; !ok || api_key != API_KEY {
		text := []byte(ERROR_CODES[http.StatusUnauthorized])
		conn.SetHeader("Content-Type", "text/html;charset=ISO-8859-1")
		conn.SetHeader("Cache-Control", "must-revalidate,no-cache,no-store")
		conn.SetHeader("Content-Length", strconv.Itoa(len(text)))
		conn.WriteHeader(http.StatusUnauthorized)
		conn.Write(text)
		conn.Flush()
		return
	}
	if text, ok := URL_MAPPINGS[req.URL.Path]; ok {
		conn.SetHeader("Content-Type", "application/xml;charset=UTF-8")
		conn.SetHeader("Transfer-Encoding", "chunked")
		// for some reason, api.rapleaf.com does not send Content-Length
		// when sending stored data
		conn.WriteHeader(http.StatusOK)
		conn.Write([]byte(text))
		conn.Flush()
		return
	}
	text := []byte(ERROR_CODES[http.StatusNotFound])
	conn.SetHeader("Content-Type", "text/html;charset=ISO-8859-1")
	conn.SetHeader("Cache-Control", "must-revalidate,no-cache,no-store")
	conn.SetHeader("Content-Length", strconv.Itoa(len(text)))
	conn.WriteHeader(http.StatusNotFound)
	conn.Write(text)
	conn.Flush()
	return
}
Ejemplo n.º 14
0
Archivo: views.go Proyecto: tung/goblog
// url: /blog/entry/(\d+)
//   1: ID of blog post to show.
func Entry(c *http.Conn, req *http.Request) {
	idString := req.URL.String();
	idString = idString[len("/blog/entry/"):len(idString)];
	if entryID, parseErr := strconv.Atoi(idString); parseErr == nil {
		if foundEntry := blog.FindEntry(entryID); foundEntry != nil {
			var entry singlePageEntry;
			entry.Entry = foundEntry;
			entry.Comments = foundEntry.Comments.Data();
			entry.CommentCount = len(entry.Comments);

			if tmpl, err := loadTemplate("entry.html"); err == nil {
				tmpl.Execute(entry, c);
			} else {
				c.SetHeader("Content-Type", "text/plain; charset=utf-8");
				c.WriteHeader(http.StatusInternalServerError);
				io.WriteString(c, "500 internal server error\n");
			}
		} else {
			c.SetHeader("Content-Type", "text/plain; charset=utf-8");
			c.WriteHeader(http.StatusNotFound);
			io.WriteString(c, "404 not found\n");
		}
	} else {
		c.SetHeader("Content-Type", "text/plain; charset=utf-8");
		c.WriteHeader(http.StatusInternalServerError);
		io.WriteString(c, "500 internal server error\n");
	}
}
Ejemplo n.º 15
0
// ServeHTTP implements the http.Handler interface for a Web Socket.
func (f Draft75Handler) ServeHTTP(c *http.Conn, req *http.Request) {
	if req.Method != "GET" || req.Proto != "HTTP/1.1" {
		c.WriteHeader(http.StatusBadRequest)
		io.WriteString(c, "Unexpected request")
		return
	}
	if req.Header["Upgrade"] != "WebSocket" {
		c.WriteHeader(http.StatusBadRequest)
		io.WriteString(c, "missing Upgrade: WebSocket header")
		return
	}
	if req.Header["Connection"] != "Upgrade" {
		c.WriteHeader(http.StatusBadRequest)
		io.WriteString(c, "missing Connection: Upgrade header")
		return
	}
	origin, found := req.Header["Origin"]
	if !found {
		c.WriteHeader(http.StatusBadRequest)
		io.WriteString(c, "missing Origin header")
		return
	}

	rwc, buf, err := c.Hijack()
	if err != nil {
		panic("Hijack failed: " + err.String())
		return
	}
	defer rwc.Close()
	location := "ws://" + req.Host + req.URL.RawPath

	// TODO(ukai): verify origin,location,protocol.

	buf.WriteString("HTTP/1.1 101 Web Socket Protocol Handshake\r\n")
	buf.WriteString("Upgrade: WebSocket\r\n")
	buf.WriteString("Connection: Upgrade\r\n")
	buf.WriteString("WebSocket-Origin: " + origin + "\r\n")
	buf.WriteString("WebSocket-Location: " + location + "\r\n")
	protocol, found := req.Header["Websocket-Protocol"]
	// canonical header key of WebSocket-Protocol.
	if found {
		buf.WriteString("WebSocket-Protocol: " + protocol + "\r\n")
	}
	buf.WriteString("\r\n")
	if err := buf.Flush(); err != nil {
		return
	}
	ws := newConn(origin, location, protocol, buf, rwc)
	f(ws)
}
Ejemplo n.º 16
0
// ServeHTTP implements the http.Handler interface for a Web Socket.
func (f Handler) ServeHTTP(c *http.Conn, req *http.Request) {
	if req.Method != "GET" || req.Proto != "HTTP/1.1" ||
		req.Header["Upgrade"] != "WebSocket" ||
		req.Header["Connection"] != "Upgrade" {
		c.WriteHeader(http.StatusNotFound)
		io.WriteString(c, "must use websocket to connect here")
		return
	}
	rwc, buf, err := c.Hijack()
	if err != nil {
		panic("Hijack failed: ", err.String())
		return
	}
	defer rwc.Close()
	origin := req.Header["Origin"]
	location := "ws://" + req.Host + req.URL.Path

	// TODO(ukai): verify origin,location,protocol.

	buf.WriteString("HTTP/1.1 101 Web Socket Protocol Handshake\r\n")
	buf.WriteString("Upgrade: WebSocket\r\n")
	buf.WriteString("Connection: Upgrade\r\n")
	buf.WriteString("WebSocket-Origin: " + origin + "\r\n")
	buf.WriteString("WebSocket-Location: " + location + "\r\n")
	protocol := ""
	// canonical header key of WebSocket-Protocol.
	if protocol, found := req.Header["Websocket-Protocol"]; found {
		buf.WriteString("WebSocket-Protocol: " + protocol + "\r\n")
	}
	buf.WriteString("\r\n")
	if err := buf.Flush(); err != nil {
		return
	}
	ws := newConn(origin, location, protocol, buf, rwc)
	f(ws)
}
func HandleGarage(conn *http.Conn, req *http.Request) {
	timeString := req.FormValue("t")
	requestTime, err := strconv.Atoi64(timeString)
	if len(timeString) == 0 || err != nil {
		conn.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(conn, "Missing/bogus 't' query parameter.")
		return
	}

	if requestTime < time.Seconds()-60 {
		conn.WriteHeader(http.StatusForbidden)
		fmt.Fprintf(conn, "Request too old.")
		return
	}

	key := req.FormValue("key")
	if len(key) == 0 {
		conn.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(conn, "Missing 'key' query parameter.")
		return
	}

	secretHasher := hmac.NewSHA1([]byte(sharedSecret))
	fmt.Fprint(secretHasher, timeString)
	expectedHash := fmt.Sprintf("%40x", secretHasher.Sum())

	if key != expectedHash {
		conn.WriteHeader(http.StatusForbidden)
		fmt.Fprintf(conn, "Signature fail.")
		return
	}

	fmt.Println("Opening garage door...")

	cmd, err := exec.Run(
		*heyUPath,
		[]string{"heyu", "on", *x10Unit},
		os.Environ(),
		"/",
		exec.DevNull,         // stdin
		exec.DevNull,         // stdout
		exec.MergeWithStdout) // stderr
	if err != nil {
		GarageOpenError(conn, err)
		return
	}

	fmt.Printf("Started heyu with pid %v\n", cmd.Pid)
	waitmsg, err := cmd.Wait(0)
	if err != nil {
		GarageOpenError(conn, err)
		return
	}
	fmt.Printf("WaitMsg: %v\n", waitmsg)

	if waitmsg.WaitStatus != 0 {
		conn.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(conn, "x10 command returned error opening garage: %v", err)
		return
	}

	fmt.Fprint(conn, "Opened.")
	fmt.Printf("Garage opened at %v from %v\n",
		time.LocalTime(),
		conn.RemoteAddr)

}
Ejemplo n.º 18
0
func (frontend *Frontend) ServeHTTP(conn *http.Conn, req *http.Request) {

	if frontend.enforceHost && req.Host != frontend.officialHost {
		conn.SetHeader("Location", frontend.officialRedirectURL)
		conn.WriteHeader(http.StatusMovedPermanently)
		conn.Write(frontend.officialRedirectHTML)
		logRequest(http.StatusMovedPermanently, req.Host, conn)
		return
	}

	originalHost := req.Host

	// Open a connection to the App Engine server.
	gaeConn, err := net.Dial("tcp", "", frontend.gaeAddr)
	if err != nil {
		if debugMode {
			fmt.Printf("Couldn't connect to remote %s: %v\n", frontend.gaeHost, err)
		}
		serveError502(conn, originalHost)
		return
	}

	var gae net.Conn

	if frontend.gaeTLS {
		gae = tls.Client(gaeConn, tlsconf.Config)
		defer gae.Close()
	} else {
		gae = gaeConn
	}

	// Modify the request Host: header.
	req.Host = frontend.gaeHost

	// Send the request to the App Engine server.
	err = req.Write(gae)
	if err != nil {
		if debugMode {
			fmt.Printf("Error writing to App Engine: %v\n", err)
		}
		serveError502(conn, originalHost)
		return
	}

	// Parse the response from App Engine.
	resp, err := http.ReadResponse(bufio.NewReader(gae), req.Method)
	if err != nil {
		if debugMode {
			fmt.Printf("Error parsing response from App Engine: %v\n", err)
		}
		serveError502(conn, originalHost)
		return
	}

	// Read the full response body.
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		if debugMode {
			fmt.Printf("Error reading response from App Engine: %v\n", err)
		}
		serveError502(conn, originalHost)
		resp.Body.Close()
		return
	}

	// Set the received headers back to the initial connection.
	for k, v := range resp.Header {
		conn.SetHeader(k, v)
	}

	// Write the response body back to the initial connection.
	resp.Body.Close()
	conn.WriteHeader(resp.StatusCode)
	conn.Write(body)

	logRequest(resp.StatusCode, originalHost, conn)

}
func GarageOpenError(conn *http.Conn, err os.Error) {
	fmt.Println("Error opening garage: ", err)
	conn.WriteHeader(http.StatusInternalServerError)
	fmt.Fprintf(conn, "Error opening garage: %v", err)
}
Ejemplo n.º 20
0
func Logger(c *http.Conn, req *http.Request) {
	log.Stdout(req.URL.Raw)
	c.WriteHeader(404)
	c.Write([]byte("oops"))
}