func Send(c *http.Conn, req *http.Request) {
	query_params, _ := http.ParseQuery(req.URL.RawQuery)
	arg_game, ok_game := query_params["game"]
	arg_msg, ok_msg := query_params["msg"]
	if !ok_game {
		c.Write([]byte("Game parameter not set"))
		return
	}
	if !ok_msg {
		c.Write([]byte("Msg parameter not set"))
		return
	}
	game := arg_game[0]
	msg := arg_msg[0]
	params := strings.Split(game, ",", 2)
	if len(params) != 2 {
		c.Write([]byte("Malformed game parameter"))
		return
	}
	game_id, player_id := params[0], params[1]
	game_instance := room.Find(game_id)
	if room == nil {
		c.Write([]byte("Game not found"))
		return
	}
	result := game_instance.Send(player_id, msg)
	c.Write([]byte(result))
}
Beispiel #2
0
// Generates the canonical string-to-sign for (most) AWS services.
// You shouldn't need to use this directly.
func Canonicalize(req *http.Request) (out string, err os.Error) {
	fv, err := http.ParseQuery(req.URL.RawQuery)
	if err == nil {
		out = strings.Join([]string{req.Method, req.Host, req.URL.Path, SortedEscape(fv)}, "\n")
	}
	return
}
Beispiel #3
0
// Generates the canonical string-to-sign for S3 services.
// You shouldn't need to use this directly unless you're pre-signing URL's.
func CanonicalizeS3(req *http.Request) (out string, err os.Error) {
	fv, err := http.ParseQuery(req.URL.RawQuery)
	if err == nil || len(fv["Expires"]) != 1 {
		out = strings.Join([]string{req.Method, req.Header.Get("Content-Md5"), req.Header.Get("Content-Type"), fv["Expires"][0], req.URL.Path}, "\n")
	}
	return
}
Beispiel #4
0
func InsertTweet(w http.ResponseWriter, r *http.Request) {
	query, _ := http.ParseQuery(r.URL.RawQuery)
	signature := Sign([]byte(query["message"][0]))
	tweet := &Tweet{Name: query["name"][0], Message: query["message"][0], Timestamp: query["date"][0], Sig: signature}
	TweetWrite <- tweet
	w.Write([]byte(`"looks good"`))
}
Beispiel #5
0
// Used exclusively by S3 to the best of my knowledge...
func (self *Signer) SignRequestV1(req *http.Request, canon func(*http.Request) (string, os.Error), exp int64) (err os.Error) {
	qstring, err := http.ParseQuery(req.URL.RawQuery)

	if err != nil {
		return
	}

	if exp > 0 {
		qstring["Expires"] = []string{strconv.Itoa64(time.Seconds() + exp)}
	} else {
		qstring["Timestamp"] = []string{time.UTC().Format(ISO8601TimestampFormat)}
	}
	qstring["Signature"] = nil, false
	qstring["AWSAccessKeyId"] = []string{self.AccessKey}

	req.URL.RawQuery = http.Values(qstring).Encode()

	can, err := canon(req)
	if err != nil {
		return
	}

	var sig []byte
	sig, err = self.SignEncoded(crypto.SHA1, can, base64.StdEncoding)

	if err == nil {
		req.URL.RawQuery += "&" + http.Values{"Signature": []string{string(sig)}}.Encode()
	}

	return
}
Beispiel #6
0
// DialUri connects to one of the doozer servers given in `uri`. If `uri`
// contains a secret key, then DialUri will call `Access` with the secret.
func DialUri(uri string) (*Conn, os.Error) {
	if !strings.HasPrefix(uri, uriPrefix) {
		return nil, ErrInvalidUri
	}

	q := uri[len(uriPrefix):]
	p, err := http.ParseQuery(q)
	if err != nil {
		return nil, err
	}

	addrs, ok := p["ca"]
	if !ok {
		return nil, ErrInvalidUri
	}

	c, err := Dial(addrs[rand.Int()%len(addrs)])
	if err != nil {
		return nil, err
	}

	secret, ok := p["sk"]
	if ok {
		err = c.Access(secret[0])
		if err != nil {
			c.Close()
			return nil, err
		}
	}

	return c, nil
}
Beispiel #7
0
// Parse query string: /path?q=val1&id=val2
func getParams(r *http.Request) map[string]string {
	params := make(map[string]string)
	p, _ := http.ParseQuery(r.URL.RawQuery)
	for k, v := range p {
		params[k] = v[0]
	}
	return params
}
Beispiel #8
0
func (self *DummyDriver) Connect(url *http.URL) (Connection, os.Error) {
	conn := new(DummyConnection)
	conn.host = url.Host
	conn.userinfo = url.RawUserinfo
	conn.db = url.Path[1:]
	options, err := http.ParseQuery(url.RawQuery)
	if err != nil {
		return nil, err
	}
	conn.options = options
	return conn, nil
}
Beispiel #9
0
func camliMode(req *http.Request) string {
	// TODO-GO: this is too hard to get at the GET Query args on a
	// POST request.
	m, err := http.ParseQuery(req.URL.RawQuery)
	if err != nil {
		return ""
	}
	if mode, ok := m["camli.mode"]; ok && len(mode) > 0 {
		return mode[0]
	}
	return ""
}
Beispiel #10
0
func Connect(c *http.Conn, req *http.Request) {
	query_params, _ := http.ParseQuery(req.URL.RawQuery)
	arg_owner, ok_owner := query_params["owner"]
	if ok_owner {
		fmt.Println("Connect owner=", arg_owner)
		owner := arg_owner[0]
		owner_id := room.Connect(owner)
		fmt.Println("Connected as ", owner_id)
		c.Write([]byte(owner_id))
	} else {
		c.Write([]byte("Parameters not specified correctly"))
	}
}
Beispiel #11
0
func Wait(c *http.Conn, req *http.Request) {
	query_params, _ := http.ParseQuery(req.URL.RawQuery)
	arg_owner_id, ok_owner_id := query_params["owner_id"]
	if ok_owner_id {
		fmt.Println("Create owner_id=", arg_owner_id)
		owner_id := arg_owner_id[0]
		game_id := room.Wait(owner_id)
		fmt.Println("Create ", game_id)
		c.Write([]byte(game_id))
	} else {
		c.Write([]byte("Parameters not specified correctly"))
	}
}
Beispiel #12
0
func handler(w http.ResponseWriter, r *http.Request) {
	error := func(msg string) {
		w.WriteHeader(400)
		w.Write([]byte(msg))
	}

	query, _ := http.ParseQuery(r.URL.RawQuery)

	url, ok_url := query["url"]
	bot, ok_bot := query["agent"]
	if !ok_url || !ok_bot {
		error("Required parameters: url, agent")
		return
	}

	log.Printf("Handling request for %s, agent: %s\n", url, bot)

	uri, err := http.ParseURL(url[0])
	if err != nil {
		error("Invalid URL: " + err.String())
		return
	}

	robotsUri := "http://" + uri.Host + "/robots.txt"
	cached, ok := cache[robotsUri]
	if ok {
		log.Println("Found robots.txt data in cache for: ", robotsUri)

		testAgent(uri.Path, bot[0], cached, w)
		return
	}

	resp, _, err := http.Get(robotsUri)
	if err != nil {
		error("Cannot fetch robots.txt: " + err.String())
		return
	}

	log.Printf("\tfetched robots.txt: %s, status code: %s \n", robotsUri, resp.StatusCode)

	body, _ := ioutil.ReadAll(resp.Body)
	robots, err := robotstxt.FromResponse(resp.StatusCode, string(body), true)
	if err != nil {
		error("Cannot parse robots file: " + err.String())
		return
	}

	// cache for future requests
	testAgent(uri.Path, bot[0], robots, w)
	cache[robotsUri] = robots
}
Beispiel #13
0
// Returns a new request composed of the original http.Request structure
func NewRequest(r *ResponseWriter, httpreq *http.Request) *Request {
	req := new(Request)
	req.Request = httpreq

	// try to parse the URL
	params, err := http.ParseQuery(httpreq.URL.RawQuery)
	if err != nil {
		log.Error("API: Couldn't parse GET parameters: %s\n", err)
		r.ReturnError("Parameters error")
		return nil
	}
	req.Params = params

	return req
}
Beispiel #14
0
func static(req *http.Request) (*page, os.Error) {
	var p page
	filename := ""
	query, _ := http.ParseQuery(req.URL.RawQuery)
	q, ok := query["file"]
	if ok {
		filename = q[0]
	} else {
		return nil, os.NewError("Failed to parse the query string")
	}
	p.filedir = staticDir

	p.filename = filename
	return &p, nil
}
Beispiel #15
0
func (o *OAuthClient) GetAccessToken(requestToken *RequestToken, OAuthVerifier string) (*AccessToken, os.Error) {
	if requestToken == nil || requestToken.OAuthToken == "" || requestToken.OAuthTokenSecret == "" {
		return nil, os.NewError("Invalid Request token")
	}

	nonce := getNonce(40)
	params := map[string]string{
		"oauth_nonce":            nonce,
		"oauth_token":            requestToken.OAuthToken,
		"oauth_verifier":         OAuthVerifier,
		"oauth_signature_method": "HMAC-SHA1",
		"oauth_timestamp":        strconv.Itoa64(time.Seconds()),
		"oauth_consumer_key":     o.ConsumerKey,
		"oauth_version":          "1.0",
	}

	base := signatureBase("POST", requestTokenUrl.Raw, params)
	signature := signRequest(base, o.ConsumerSecret, requestToken.OAuthTokenSecret)
	params["oauth_signature"] = URLEscape(signature)

	authBuf := bytes.NewBufferString("OAuth ")
	i := 0
	for k, v := range params {
		authBuf.WriteString(fmt.Sprintf("%s=%q", k, v))
		if i < len(params)-1 {
			authBuf.WriteString(", ")
		}
		i++
	}
	request := httplib.Post(accessTokenUrl.Raw)
	request.Header("Authorization", authBuf.String())
	request.Body("")
	resp, err := request.AsString()
	tokens, err := http.ParseQuery(resp)
	if err != nil {
		return nil, err
	}

	at := AccessToken{
		OAuthTokenSecret: tokens["oauth_token_secret"][0],
		OAuthToken:       tokens["oauth_token"][0],
		UserId:           tokens["user_id"][0],
		ScreenName:       tokens["screen_name"][0],
	}
	return &at, nil

}
Beispiel #16
0
func parseTokenAndSecret(data string) (string, string, os.Error) {
	parts, err := http.ParseQuery(data)
	if err != nil {
		return "", "", err
	}

	if len(parts[TOKEN_PARAM]) < 1 {
		return "", "", os.NewError("Missing " + TOKEN_PARAM + " in response. " +
			"Full response body: '" + data + "'")
	}
	if len(parts[TOKEN_SECRET_PARAM]) < 1 {
		return "", "", os.NewError("Missing " + TOKEN_SECRET_PARAM + " in response." +
			"Full response body: '" + data + "'")
	}

	return parts[TOKEN_PARAM][0], parts[TOKEN_SECRET_PARAM][0], nil
}
Beispiel #17
0
func download(req *http.Request) (*page, os.Error) {
	var p page
	filename := ""
	query, _ := http.ParseQuery(req.URL.RawQuery)
	q, ok := query["file"]
	if ok {
		filename = q[0]
	} else {
		return nil, os.NewError("failed to parse query string")
	}
	if filename == "style.css" {
		p.filedir = tmplDir
	} else {
		p.filedir = filesDir
	}
	p.filename = filename
	return &p, nil
}
Beispiel #18
0
// The V2 denotes amazon signing version 2, not version 2 of this particular function...
// V2 is used by all services but S3;
// Note, some services vary in their exact implementation of escaping w/r/t signatures,
// so it is recommended you use this function.
//
// Final note: if exp is set to 0, a Timestamp will be used, otherwise an expiration.
func (self *Signer) SignRequestV2(req *http.Request, canon func(*http.Request) (string, os.Error), api_ver string, exp int64) (err os.Error) {
	// log.Printf("Signing request...")

	qstring, err := http.ParseQuery(req.URL.RawQuery)
	if err != nil {
		return
	}
	qstring["SignatureVersion"] = []string{DEFAULT_SIGNATURE_VERSION}
	if _, ok := qstring["SignatureMethod"]; !ok || len(qstring["SignatureMethod"]) == 0 {
		qstring["SignatureMethod"] = []string{DEFAULT_SIGNATURE_METHOD}
	}
	qstring["Version"] = []string{api_ver}

	if exp > 0 {
		qstring["Expires"] = []string{strconv.Itoa64(time.Seconds() + exp)}
	} else {
		qstring["Timestamp"] = []string{time.UTC().Format(ISO8601TimestampFormat)}
	}
	qstring["Signature"] = nil, false
	qstring["AWSAccessKeyId"] = []string{self.AccessKey}

	var sig []byte
	req.URL.RawQuery = http.Values(qstring).Encode()
	can, err := canon(req)
	if err != nil {
		return
	}
	//log.Printf("String-to-sign: '%s'", can)

	switch qstring["SignatureMethod"][0] {
	case "HmacSHA256":
		sig, err = self.SignEncoded(crypto.SHA256, can, base64.StdEncoding)
	case "HmacSHA1":
		sig, err = self.SignEncoded(crypto.SHA1, can, base64.StdEncoding)
	default:
		err = os.NewError("Unknown SignatureMethod:" + req.Form.Get("SignatureMethod"))
	}

	if err == nil {
		req.URL.RawQuery += "&" + http.Values{"Signature": []string{string(sig)}}.Encode()
	}

	return
}
Beispiel #19
0
func (self *UserNode) get(req *GetRequest) {
	docuri := req.URI.(DocumentURI)

	// Request is aimed at this document?
	if req.RawQuery != "" && len(docuri.NameSeq) == self.level {
		// Parse the query
		query, err := http.ParseQuery(req.RawQuery)
		if err != nil {
			log.Println("Failed parsing query")
			makeErrorResponse(req.Response, "Failed parsing query")
			req.FinishSignal <- false
			return
		}
		kind, ok := query["kind"]
		if !ok || (kind != nil && len(kind) != 1) {
			log.Println("Missing kind in query or malformed kind")
			makeErrorResponse(req.Response, "Failed parsing query")
			req.FinishSignal <- false
			return
		}
		switch kind[0] {
		case "friends":
			// TODO
			reply := []byte("{\"friends\":[{\"displayName\":\"Torben\", \"userid\":\"weis@localhost\"}, {\"displayName\":\"Tux\", \"userid\":\"tux@localhost\"},{\"displayName\":\"Konqi\", \"userid\":\"konqi@localhost\"}]}")
			req.Response.SetHeader("Content-Type", "application/json")
			_, err = req.Response.Write(reply)
			if err != nil {
				log.Println("Failed writing HTTP response")
				req.FinishSignal <- false
				return
			}
		default:
			log.Println("Unknown kind in query or malformed kind")
			makeErrorResponse(req.Response, "Failed parsing query")
			req.FinishSignal <- false
			return
		}
		req.FinishSignal <- true
		return
	} else {
		// Forward request to the default implementation
		self.DocumentNode.get(req)
	}
}
Beispiel #20
0
func Handler(c http.ResponseWriter, r *http.Request) {
	host := r.Host
	s := session.Get(c, r)
	query, _ := http.ParseQuery(r.URL.RawQuery)
	continueURLS := query["continue-url"]
	continueURL := ""
	if len(continueURLS) >= 1 {
		continueURL = continueURLS[0]
	}
	if len(continueURL) == 0 {
		continueURL = "/"
	}
	fmt.Println(continueURL)
	s.Set("openid-continue-url", continueURL)
	fmt.Println(s.Get("openid-name-first"))
	url := "https://www.google.com/accounts/o8/ud"
	var urlParams = map[string]string{
		"openid.ns":                "http://specs.openid.net/auth/2.0",
		"openid.claimed_id":        "http://specs.openid.net/auth/2.0/identifier_select",
		"openid.identity":          "http://specs.openid.net/auth/2.0/identifier_select",
		"openid.return_to":         "http://" + host + "/openid/auth",
		"openid.realm":             "http://" + host,
		"openid.mode":              "checkid_setup",
		"openid.ns.ui":             "http://specs.openid.net/extensions/ui/1.0",
		"openid.ns.ext1":           "http://openid.net/srv/ax/1.0",
		"openid.ext1.mode":         "fetch_request",
		"openid.ext1.type.email":   "http://axschema.org/contact/email",
		"openid.ext1.type.first":   "http://axschema.org/namePerson/first",
		"openid.ext1.type.last":    "http://axschema.org/namePerson/last",
		"openid.ext1.type.country": "http://axschema.org/contact/country/home",
		"openid.ext1.type.lang":    "http://axschema.org/pref/language",
		"openid.ext1.required":     "email,first,last,country,lang",
		"openid.ns.oauth":          "http://specs.openid.net/extensions/oauth/1.0",
		"openid.oauth.consumer":    host,
		"openid.oauth.scope":       "http://picasaweb.google.com/data/"}
	queryURL := "?"
	for name, value := range urlParams {
		queryURL += http.URLEscape(name) + "=" + http.URLEscape(value) + "&"
	}
	queryURL = queryURL[0 : len(queryURL)-1]
	fmt.Println(queryURL)
	http.Redirect(c, r, url+queryURL, 307)
}
Beispiel #21
0
func YouTuber(conn *irc.Conn, channel string) {
	AutoJoin(conn, channel)
	conn.AddHandler("PRIVMSG", func(c *irc.Conn, l *irc.Line) {
		if l.Args[0] != channel {
			return
		}
		m := l.Args[1]
		url := youtubeRe.FindStringSubmatch(m)
		if url == nil {
			return
		}
		q, _ := http.ParseQuery(url[1])
		key, found := q["v"]
		if !found {
			return
		}
		printMetadataForKey(c, channel, key[0])
	})
}
Beispiel #22
0
func (o *OAuthClient) GetRequestToken(callback string) *RequestToken {
	nonce := getNonce(40)
	params := map[string]string{
		"oauth_nonce":            nonce,
		"oauth_callback":         URLEscape(callback),
		"oauth_signature_method": "HMAC-SHA1",
		"oauth_timestamp":        strconv.Itoa64(time.Seconds()),
		"oauth_consumer_key":     o.ConsumerKey,
		"oauth_version":          "1.0",
	}

	base := signatureBase("POST", requestTokenUrl.Raw, params)
	signature := signRequest(base, o.ConsumerSecret, "")
	params["oauth_signature"] = URLEscape(signature)

	authBuf := bytes.NewBufferString("OAuth ")
	i := 0
	for k, v := range params {
		authBuf.WriteString(fmt.Sprintf("%s=%q", k, v))
		if i < len(params)-1 {
			authBuf.WriteString(", ")
		}
		i++
	}
	request := httplib.Post(requestTokenUrl.Raw)
	request.Header("Authorization", authBuf.String())
	request.Body("")
	resp, err := request.AsString()
	tokens, err := http.ParseQuery(resp)
	if err != nil {
		println(err.String())
	}

	confirmed, _ := strconv.Atob(tokens["oauth_callback_confirmed"][0])
	rt := RequestToken{
		OAuthTokenSecret:       tokens["oauth_token_secret"][0],
		OAuthToken:             tokens["oauth_token"][0],
		OAuthCallbackConfirmed: confirmed,
	}
	return &rt
}
Beispiel #23
0
func (frontend *Frontend) ServeHTTP(conn http.ResponseWriter, req *http.Request) {

	originalHost := req.Host

	// Redirect all requests to the "official" public host if the Host header
	// doesn't match.
	if !frontend.isValidHost(originalHost) {
		conn.Header().Set("Location", frontend.RedirectURL)
		conn.WriteHeader(http.StatusMovedPermanently)
		conn.Write(frontend.RedirectHTML)
		frontend.Log(HTTPS_REDIRECT, http.StatusMovedPermanently, originalHost, req)
		return
	}

	// Return the HTTP 503 error page if we're in maintenance mode.
	if frontend.MaintenanceMode {
		headers := conn.Header()
		headers.Set("Content-Type", "text/html; charset=utf-8")
		headers.Set("Content-Length", frontend.Error503Length)
		conn.WriteHeader(http.StatusServiceUnavailable)
		conn.Write(frontend.Error503)
		frontend.Log(HTTPS_MAINTENANCE, http.StatusServiceUnavailable, originalHost, req)
		return
	}

	reqPath := req.URL.Path

	// Handle requests for any files exposed within the static directory.
	if staticFile, ok := frontend.StaticFiles[reqPath]; ok {
		expires := time.SecondsToUTC(time.Seconds() + frontend.StaticMaxAge)
		headers := conn.Header()
		headers.Set("Expires", expires.Format(http.TimeFormat))
		headers.Set("Cache-Control", frontend.StaticCache)
		headers.Set("Etag", staticFile.ETag)
		if req.Header.Get("If-None-Match") == staticFile.ETag {
			conn.WriteHeader(http.StatusNotModified)
			frontend.Log(HTTPS_STATIC, http.StatusNotModified, originalHost, req)
			return
		}
		// Special case /.well-known/oauth.json?callback= requests.
		if reqPath == "/.well-known/oauth.json" && req.URL.RawQuery != "" {
			query, err := http.ParseQuery(req.URL.RawQuery)
			if err != nil {
				logging.Error("Error parsing oauth.json query string %q: %s",
					req.URL.RawQuery, err)
				frontend.ServeError400(conn, originalHost, req)
				return
			}
			if callbackList, found := query["callback"]; found {
				callback := callbackList[0]
				if callback != "" {
					respLen := len(callback) + len(staticFile.Content) + 2
					headers.Set("Content-Type", "text/javascript")
					headers.Set("Content-Length", fmt.Sprintf("%d", respLen))
					conn.WriteHeader(http.StatusOK)
					conn.Write([]byte(callback))
					conn.Write([]byte{'('})
					conn.Write(staticFile.Content)
					conn.Write([]byte{')'})
					frontend.Log(HTTPS_STATIC, http.StatusOK, originalHost, req)
					return
				}
			}
		}
		headers.Set("Content-Type", staticFile.Mimetype)
		headers.Set("Content-Length", staticFile.Size)
		conn.WriteHeader(http.StatusOK)
		conn.Write(staticFile.Content)
		frontend.Log(HTTPS_STATIC, http.StatusOK, originalHost, req)
		return
	}

	if frontend.LiveMode {

		// Handle WebSocket requests.
		if strings.HasPrefix(reqPath, frontend.WebsocketPrefix) {
			websocket.Handler(frontend.getWebSocketHandler()).ServeHTTP(conn, req)
			return
		}

		// Handle long-polling Comet requests.
		if strings.HasPrefix(reqPath, frontend.CometPrefix) {
			query, err := http.ParseQuery(req.URL.RawQuery)
			if err != nil {
				logging.Error("Error parsing Comet query string %q: %s",
					req.URL.RawQuery, err)
				frontend.ServeError400(conn, originalHost, req)
				return
			}
			queryReq, found := query["q"]
			if !found {
				frontend.ServeError400(conn, originalHost, req)
				return
			}
			response, status := getLiveItems(queryReq[0])
			headers := conn.Header()
			headers.Set("Content-Type", "application/json")
			headers.Set("Content-Length", fmt.Sprintf("%d", len(response)))
			conn.WriteHeader(status)
			conn.Write(response)
			frontend.Log(HTTPS_COMET, status, originalHost, req)
			return
		}

	}

	// Open a connection to the upstream server.
	upstreamConn, err := net.Dial("tcp", frontend.upstreamAddr)
	if err != nil {
		logging.Error("Couldn't connect to upstream: %s", err)
		frontend.ServeError502(conn, originalHost, req)
		return
	}

	var clientIP string
	var upstream net.Conn

	splitPoint := strings.LastIndex(req.RemoteAddr, ":")
	if splitPoint == -1 {
		clientIP = req.RemoteAddr
	} else {
		clientIP = req.RemoteAddr[0:splitPoint]
	}

	if frontend.upstreamTLS {
		upstream = tls.Client(upstreamConn, tlsconf.Config)
		defer upstream.Close()
	} else {
		upstream = upstreamConn
	}

	// Modify the request Host: and User-Agent: headers.
	req.Host = frontend.upstreamHost
	req.Header.Set(
		"User-Agent",
		fmt.Sprintf("%s, %s, %s", req.UserAgent(), clientIP, originalHost))

	// Send the request to the upstream server.
	err = req.Write(upstream)
	if err != nil {
		logging.Error("Error writing to the upstream server: %s", err)
		frontend.ServeError502(conn, originalHost, req)
		return
	}

	// Parse the response from upstream.
	resp, err := http.ReadResponse(bufio.NewReader(upstream), req)
	if err != nil {
		logging.Error("Error parsing response from upstream: %s", err)
		frontend.ServeError502(conn, originalHost, req)
		return
	}

	defer resp.Body.Close()

	// Get the original request header.
	headers := conn.Header()

	// Set a variable to hold the X-Live header value if present.
	var liveLength int

	if frontend.LiveMode {
		xLive := resp.Header.Get("X-Live")
		if xLive != "" {
			// If the X-Live header was set, parse it into an int.
			liveLength, err = strconv.Atoi(xLive)
			if err != nil {
				logging.Error("Error converting X-Live header value %q: %s", xLive, err)
				frontend.ServeError500(conn, originalHost, req)
				return
			}
			resp.Header.Del("X-Live")
		}
	}

	var body []byte

	if liveLength > 0 {

		var gzipSet bool
		var respBody io.ReadCloser

		// Check Content-Encoding to see if upstream sent gzipped content.
		if resp.Header.Get("Content-Encoding") == "gzip" {
			gzipSet = true
			respBody, err = gzip.NewReader(resp.Body)
			if err != nil {
				logging.Error("Error reading gzipped response from upstream: %s", err)
				frontend.ServeError500(conn, originalHost, req)
				return
			}
			defer respBody.Close()
		} else {
			respBody = resp.Body
		}

		// Read the X-Live content from the response body.
		liveMessage := make([]byte, liveLength)
		n, err := respBody.Read(liveMessage)
		if n != liveLength || err != nil {
			logging.Error("Error reading X-Live response from upstream: %s", err)
			frontend.ServeError500(conn, originalHost, req)
			return
		}

		// Read the response to send back to the original request.
		body, err = ioutil.ReadAll(respBody)
		if err != nil {
			logging.Error("Error reading non X-Live response from upstream: %s", err)
			frontend.ServeError500(conn, originalHost, req)
			return
		}

		// Re-encode the response if it had been gzipped by upstream.
		if gzipSet {
			buffer := &bytes.Buffer{}
			encoder, err := gzip.NewWriter(buffer)
			if err != nil {
				logging.Error("Error creating a new gzip Writer: %s", err)
				frontend.ServeError500(conn, originalHost, req)
				return
			}
			n, err = encoder.Write(body)
			if n != len(body) || err != nil {
				logging.Error("Error writing to the gzip Writer: %s", err)
				frontend.ServeError500(conn, originalHost, req)
				return
			}
			err = encoder.Close()
			if err != nil {
				logging.Error("Error finalising the write to the gzip Writer: %s", err)
				frontend.ServeError500(conn, originalHost, req)
				return
			}
			body = buffer.Bytes()
		}

		resp.Header.Set("Content-Length", fmt.Sprintf("%d", len(body)))
		liveChannel <- liveMessage

	} else {
		// Read the full response body.
		body, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			logging.Error("Error reading response from upstream: %s", err)
			frontend.ServeError502(conn, originalHost, req)
			return
		}
	}

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

	// Write the response body back to the initial connection.
	conn.WriteHeader(resp.StatusCode)
	conn.Write(body)
	frontend.Log(HTTPS_UPSTREAM, resp.StatusCode, originalHost, req)

}
Beispiel #24
0
func (self *WaveletNode) get(req *GetRequest) {
	docuri := req.URI.(DocumentURI)

	// Request is not aimed at this document?
	if len(docuri.NameSeq) != self.level {
		makeErrorResponse(req.Response, "Document "+docuri.NameSeq[self.level]+" does not exist")
		req.FinishSignal <- false
		return
	}
	log.Println("Wavelet is handling a get: ", req.URI)

	// Is a special history requested?
	if req.RawQuery != "" {
		// Parse the query
		query, err := http.ParseQuery(req.RawQuery)
		if err != nil {
			log.Println("Failed parsing query")
			makeErrorResponse(req.Response, "Failed parsing query")
			req.FinishSignal <- false
			return
		}
		_v1, ok := query["v1"]
		if !ok || len(_v1) != 1 {
			log.Println("Expected v1 in query string")
			makeErrorResponse(req.Response, "Expected v1 in query string")
			req.FinishSignal <- false
			return
		}
		v1, err := strconv.Atoi(_v1[0])
		if err != nil {
			log.Println("Malformed query")
			makeErrorResponse(req.Response, "Expected v1 in query string")
			req.FinishSignal <- false
			return
		}
		v1hash, ok := query["v1hash"]
		if !ok || len(v1hash) != 1 {
			log.Println("Expected v1hash in query string")
			makeErrorResponse(req.Response, "Expected v1hash in query string")
			req.FinishSignal <- false
			return
		}
		_v2, ok := query["v2"]
		if !ok || len(_v2) != 1 {
			log.Println("Expected v2 in query string")
			makeErrorResponse(req.Response, "Expected v2 in query string")
			req.FinishSignal <- false
			return
		}
		v2, err := strconv.Atoi(_v2[0])
		if err != nil {
			log.Println("Malformed query")
			makeErrorResponse(req.Response, "Expected v1 in query string")
			req.FinishSignal <- false
			return
		}
		v2hash, ok := query["v1hash"]
		if !ok || len(v2hash) != 1 {
			log.Println("Expected v2hash in query string")
			makeErrorResponse(req.Response, "Expected v2hash in query string")
			req.FinishSignal <- false
			return
		}
		_limit, ok := query["limit"]
		if ok && len(_limit) != 1 {
			log.Println("Double limit in query string")
			makeErrorResponse(req.Response, "Double limit in query string")
			req.FinishSignal <- false
			return
		}
		limit, err := strconv.Atoi(_limit[0])
		if err != nil {
			log.Println("Malformed query")
			makeErrorResponse(req.Response, "Expected v1 in query string")
			req.FinishSignal <- false
			return
		}
		// Retrieve the history
		log.Println(v1, v2, limit, v1hash, v2hash)
		/* TODO
		  result, err := self.history.Range(int64(v1), v1hash[0], int64(v2), v2hash[0], int64(limit))
		  if err != nil {
			log.Println("Failed retrieving history ", err)
			makeErrorResponse(req.Response, "Failed retrieving history")
			req.FinishSignal <- false
			return
		  }
		  // Send the result by HTTP
		  req.Response.SetHeader("Content-Type", "application/protobuf")
		  _, err = req.Response.Write( []byte(result) )
		  if err != nil {
			log.Println("Failed writing HTTP response")
			req.FinishSignal <- false
			return
		  } */
		req.FinishSignal <- true
		return
	}

	makeErrorResponse(req.Response, "Snapshots are not implemented")
	req.FinishSignal <- false
}
Beispiel #25
0
func AddFriend(w http.ResponseWriter, r *http.Request) {
	query, _ := http.ParseQuery(r.URL.RawQuery)
	mod := query["mod"][0]
	username := query["username"][0]
	WriteFriend(mod, username)
}
Beispiel #26
0
func (self *DocumentNode) get(req *GetRequest) {
	docuri := req.URI.(DocumentURI)

	// Request is aimed at this document?
	if len(docuri.NameSeq) == self.level {
		// Is a special history requested?
		if req.RawQuery != "" {
			// Parse the query
			query, err := http.ParseQuery(req.RawQuery)
			if err != nil {
				log.Println("Failed parsing query")
				makeErrorResponse(req.Response, "Failed parsing query")
				req.FinishSignal <- false
				return
			}
			_v1, ok := query["v1"]
			if !ok || len(_v1) != 1 {
				log.Println("Expected v1 in query string")
				makeErrorResponse(req.Response, "Expected v1 in query string")
				req.FinishSignal <- false
				return
			}
			v1, err := strconv.Atoi(_v1[0])
			if err != nil {
				log.Println("Malformed query")
				makeErrorResponse(req.Response, "Expected v1 in query string")
				req.FinishSignal <- false
				return
			}
			v1hash, ok := query["v1hash"]
			if !ok || len(v1hash) != 1 {
				log.Println("Expected v1hash in query string")
				makeErrorResponse(req.Response, "Expected v1hash in query string")
				req.FinishSignal <- false
				return
			}
			_v2, ok := query["v2"]
			if !ok || len(_v2) != 1 {
				log.Println("Expected v2 in query string")
				makeErrorResponse(req.Response, "Expected v2 in query string")
				req.FinishSignal <- false
				return
			}
			v2, err := strconv.Atoi(_v2[0])
			if err != nil {
				log.Println("Malformed query")
				makeErrorResponse(req.Response, "Expected v1 in query string")
				req.FinishSignal <- false
				return
			}
			v2hash, ok := query["v1hash"]
			if !ok || len(v2hash) != 1 {
				log.Println("Expected v2hash in query string")
				makeErrorResponse(req.Response, "Expected v2hash in query string")
				req.FinishSignal <- false
				return
			}
			_limit, ok := query["limit"]
			if ok && len(_limit) != 1 {
				log.Println("Double limit in query string")
				makeErrorResponse(req.Response, "Double limit in query string")
				req.FinishSignal <- false
				return
			}
			limit, err := strconv.Atoi(_limit[0])
			if err != nil {
				log.Println("Malformed query")
				makeErrorResponse(req.Response, "Expected v1 in query string")
				req.FinishSignal <- false
				return
			}
			// Retrieve the history
			result, err := self.history.Range(int64(v1), v1hash[0], int64(v2), v2hash[0], int64(limit))
			if err != nil {
				log.Println("Failed retrieving history ", err)
				makeErrorResponse(req.Response, "Failed retrieving history")
				req.FinishSignal <- false
				return
			}
			// Send the result by HTTP
			req.Response.SetHeader("Content-Type", "application/json")
			_, err = req.Response.Write([]byte(result))
			if err != nil {
				log.Println("Failed writing HTTP response")
				req.FinishSignal <- false
				return
			}
			req.FinishSignal <- true
			return
		}

		json, err := json.Marshal(self.doc)
		if err != nil {
			panic("Failed marshaling to json")
		}
		req.Response.SetHeader("Content-Type", "application/json")
		_, err = req.Response.Write(json)
		if err != nil {
			log.Println("Failed writing HTTP response")
			req.FinishSignal <- false
			return
		}
		fmt.Println("Document is getting itself with req %v", req)
		req.FinishSignal <- true
		return
	}

	// Request is aimed at a child document
	doc, ok := self.children[docuri.NameSeq[self.level]]
	if !ok {
		doc = self.loadDocument(docuri.NameSeq[self.level])
	}
	if doc == nil {
		makeErrorResponse(req.Response, "Document "+docuri.NameSeq[self.level]+" does not exist")
		req.FinishSignal <- false
		return
	}
	doc.Get(req)
}