Example #1
0
func (t *TorrentSession) fetchTrackerInfo(event string) {
	m, si := t.m, t.si
	log.Println("Stats: Uploaded", si.Uploaded, "Downloaded", si.Downloaded, "Left", si.Left)
	// A single concatenation would brake compilation for ARM.
	url := m.Announce + "?" +
		"info_hash=" + http.URLEscape(m.InfoHash) +
		"&peer_id=" + si.PeerId +
		"&port=" + strconv.Itoa(si.Port)
	url += "&uploaded=" + strconv.Itoa64(si.Uploaded) +
		"&downloaded=" + strconv.Itoa64(si.Downloaded) +
		"&left=" + strconv.Itoa64(si.Left) +
		"&compact=1"
	if event != "" {
		url += "&event=" + event
	}
	ch := t.trackerInfoChan
	go func() {
		ti, err := getTrackerInfo(url)
		if ti == nil || err != nil {
			log.Println("Could not fetch tracker info:", err)
		} else {
			ch <- ti
		}
	}()
}
Example #2
0
File: gg.go Project: zbq/gg
func SendFile(file *os.File, fileLen int64) bool {
	var laddr = &net.TCPAddr{}
	var raddr = &net.TCPAddr{IP: Server.Nets[0].IP, Port: Server.Port}
	conn, err := net.DialTCP("tcp4", laddr, raddr)
	if err != nil {
		return false
	}
	conn.SetTimeout(2 * SECOND)
	defer conn.Close()

	pkt := make([]byte, MAX_TCP_PKT)
	if !responseServerAuth(conn, pkt) {
		return false
	}

	contentLen := int64(0)
	if fileLen%int64(Cipher.BlockSize()) == 0 {
		contentLen = fileLen
	} else {
		contentLen = (fileLen/int64(Cipher.BlockSize()) + 1) * int64(Cipher.BlockSize())
	}

	pktlen := 0
	pktlen += pktAddHeader(pkt[pktlen:], PACKET_TYPE_TAG, PACKET_TYPE_SEND_FILE)
	pktlen += pktAddHeader(pkt[pktlen:], USERNAME_TAG, Self.Name)
	pktlen += pktAddHeader(pkt[pktlen:], HOSTNAME_TAG, Self.Hostname)
	pktlen += pktAddHeader(pkt[pktlen:], FILE_NAME_TAG, filepath.Base(file.Name()))
	pktlen += pktAddHeader(pkt[pktlen:], CONTENT_LEN_TAG, strconv.Itoa64(contentLen))
	pktlen += pktAddHeader(pkt[pktlen:], PADDING_LEN_TAG, strconv.Itoa64(contentLen-fileLen))
	pktlen += pktAddHeaderEndMark(pkt[pktlen:])

	if writeBuf(conn, pkt[:pktlen]) != pktlen {
		return false
	}
	encrypter := NewCBCEncrypter()
	for {
		if fileLen < int64(cap(pkt)) {
			pkt = pkt[:fileLen]
		} else {
			pkt = pkt[:cap(pkt)]
		}
		if n, _ := fullRead(file, pkt); n != len(pkt) {
			return false
		}
		fileLen -= int64(len(pkt))
		if len(pkt)%Cipher.BlockSize() != 0 {
			//at file end
			n := (len(pkt)/Cipher.BlockSize() + 1) * Cipher.BlockSize()
			pkt = pkt[:n]
		}
		encrypter.CryptBlocks(pkt, pkt)
		if writeBuf(conn, pkt) != len(pkt) {
			return false
		}
		if fileLen <= 0 {
			break
		}
	}
	return true
}
Example #3
0
// Encode writes the Image m to w in PNG format. Any Image may be encoded, but
// images that are not image.NRGBA might be encoded lossily.
func Encode(w io.Writer, m image.Image) os.Error {
	// Obviously, negative widths and heights are invalid. Furthermore, the PNG
	// spec section 11.2.2 says that zero is invalid. Excessively large images are
	// also rejected.
	mw, mh := int64(m.Width()), int64(m.Height())
	if mw <= 0 || mh <= 0 || mw >= 1<<32 || mh >= 1<<32 {
		return FormatError("invalid image size: " + strconv.Itoa64(mw) + "x" + strconv.Itoa64(mw))
	}

	var e encoder
	e.w = w
	e.m = m
	e.colorType = uint8(ctTrueColorAlpha)
	pal, _ := m.(*image.Paletted)
	if pal != nil {
		e.colorType = ctPaletted
	} else if opaque(m) {
		e.colorType = ctTrueColor
	}

	_, e.err = io.WriteString(w, pngHeader)
	e.writeIHDR()
	if pal != nil {
		e.writePLTE(pal.Palette)
	}
	e.writeIDATs()
	e.writeIEND()
	return e.err
}
Example #4
0
func main() {
	/*	list, _ := ioutil.ReadDir("/Users/sunfmin/Developments/perapera/templates/videos")

		for _, f := range list {
			fmt.Println(f.Name)
		}
	*/
	ts := templateset.MustBuildFromDirectory("./templates/videos", nil)

	fmt.Println(ts)

	ch := make(chan int, 10)
	ch <- 1
	ch <- 2
	fmt.Println(len(ch))
	fmt.Println(cap(ch))

	fmt.Println(([]int)("Hi Felix"))
	fmt.Println(string([]int{70, 101, 108, 105, 120}))
	fmt.Println(string(1212))
	fmt.Println(strconv.Itoa64(121212312312))
	fmt.Println(strconv.Itoa64(121))

	fmt.Println(MyString("hello cool"))

	fmt.Println(12 << 1)

	fmt.Println(os.Stdout)

	f, _ := os.Open("perapera.go")
	var buf [48]byte

	fmt.Println(buf)

	f.Read(buf[0:32])

	/*	fmt.Println(string([]byte{'1', '2'}))*/
	fmt.Println(string([]byte{112, 97}))
	fmt.Println(string(buf[0:]))

	fmt.Println(cap(buf[0:12]))
	fmt.Println(len(buf[0:12]))

	fmt.Println(os.Stdout)

	fmt.Println(buf)

	a := [...]float64{7.0, 8.5, 9.1, 10, 12}

	fmt.Println(a)

	fmt.Println(&T{"hi"})

	fmt.Println(&[]int{1, 2})

	x := Sum(&[]float64{7.0, 8.5, 9.1, 10, 202})
	fmt.Println(x)
}
Example #5
0
func createSessionId(username string) string {
	hm := hmac.NewSHA1([]byte(ServerSecret))
	hm.Write([]byte(username))
	hm.Write([]byte(strconv.Itoa64(sessionIdCounter)))
	hm.Write([]byte(strconv.Itoa64(time.Seconds())))
	sessionIdCounter++
	hex := fmt.Sprintf("%02x", hm.Sum())
	return hex
}
Example #6
0
func (c *Consumer) baseParams(consumerKey string, additionalParams map[string]string) *OrderedParams {
	params := NewOrderedParams()
	params.Add(VERSION_PARAM, OAUTH_VERSION)
	params.Add(SIGNATURE_METHOD_PARAM, SIGNATURE_METHOD)
	params.Add(TIMESTAMP_PARAM, strconv.Itoa64(c.clock.Seconds()))
	params.Add(NONCE_PARAM, strconv.Itoa64(c.nonceGenerator.Int63()))
	params.Add(CONSUMER_KEY_PARAM, consumerKey)
	for key, value := range additionalParams {
		params.Add(key, value)
	}
	return params
}
Example #7
0
func (p *YahooContactService) UpdateContactOnExternalService(client oauth2_client.OAuth2Client, originalContact, contact interface{}) (interface{}, string, os.Error) {
	if contact == nil {
		return nil, "", nil
	}
	if originalContact == nil {
		return p.CreateContactOnExternalService(client, contact)
	}
	originalYContact := originalContact.(*yahoo.Contact)
	yContact := contact.(*yahoo.Contact)
	err := yahoo.UpdateContact(client, "", strconv.Itoa64(originalYContact.Id), yContact)
	return yContact, strconv.Itoa64(yContact.Id), err
}
Example #8
0
func module(f string) (string, os.Error) {
	i, err := os.Stat(f)
	if err != nil {
		return "", err
	}

	m := "$" + f + "-" + strconv.Uitoa64(i.Dev) + "-" +
		strconv.Uitoa64(i.Ino) + "-" + strconv.Itoa64(i.Blocks) + "-" +
		strconv.Itoa64(i.Mtime_ns)

	return m, nil
}
Example #9
0
// Redis LRANGE command.
func (c *syncClient) Lrange(arg0 string, arg1 int64, arg2 int64) (result [][]byte, err Error) {
	arg0bytes := []byte(arg0)
	arg1bytes := []byte(strconv.Itoa64(arg1))
	arg2bytes := []byte(strconv.Itoa64(arg2))

	var resp Response
	resp, err = c.conn.ServiceRequest(&LRANGE, [][]byte{arg0bytes, arg1bytes, arg2bytes})
	if err == nil {
		result = resp.GetMultiBulkData()
	}
	return result, err

}
Example #10
0
// Redis LRANGE command.
func (c *asyncClient) Lrange(arg0 string, arg1 int64, arg2 int64) (result FutureBytesArray, err Error) {
	arg0bytes := []byte(arg0)
	arg1bytes := []byte(strconv.Itoa64(arg1))
	arg2bytes := []byte(strconv.Itoa64(arg2))

	var resp *PendingResponse
	resp, err = c.conn.QueueRequest(&LRANGE, [][]byte{arg0bytes, arg1bytes, arg2bytes})
	if err == nil {
		result = resp.future.(FutureBytesArray)
	}
	return result, err

}
Example #11
0
// Encode writes the Image m to w in PNG format. Any Image may be encoded, but
// images that are not image.NRGBA might be encoded lossily.
func Encode(w io.Writer, m image.Image) os.Error {
	// Obviously, negative widths and heights are invalid. Furthermore, the PNG
	// spec section 11.2.2 says that zero is invalid. Excessively large images are
	// also rejected.
	mw, mh := int64(m.Bounds().Dx()), int64(m.Bounds().Dy())
	if mw <= 0 || mh <= 0 || mw >= 1<<32 || mh >= 1<<32 {
		return FormatError("invalid image size: " + strconv.Itoa64(mw) + "x" + strconv.Itoa64(mw))
	}

	var e encoder
	e.w = w
	e.m = m

	var pal color.Palette
	// cbP8 encoding needs PalettedImage's ColorIndexAt method.
	if _, ok := m.(image.PalettedImage); ok {
		pal, _ = m.ColorModel().(color.Palette)
	}
	if pal != nil {
		e.cb = cbP8
	} else {
		switch m.ColorModel() {
		case color.GrayModel:
			e.cb = cbG8
		case color.Gray16Model:
			e.cb = cbG16
		case color.RGBAModel, color.NRGBAModel, color.AlphaModel:
			if opaque(m) {
				e.cb = cbTC8
			} else {
				e.cb = cbTCA8
			}
		default:
			if opaque(m) {
				e.cb = cbTC16
			} else {
				e.cb = cbTCA16
			}
		}
	}

	_, e.err = io.WriteString(w, pngHeader)
	e.writeIHDR()
	if pal != nil {
		e.writePLTE(pal)
		e.maybeWritetRNS(pal)
	}
	e.writeIDATs()
	e.writeIEND()
	return e.err
}
Example #12
0
func formatReflectValue(x reflect.Value) (string, os.Error) {
	/*
	   if !x.CanSet() {
	       return "", ErrorCantSet
	   }
	*/
	var (
		errc os.Error
		kind = x.Kind()
		//vintstr   string
	)
	switch kind {
	// Format pointers to standard types.
	case reflect.String:
		return x.Interface().(string), nil
	case reflect.Int:
		return strconv.Itoa(x.Interface().(int)), nil
	case reflect.Int8:
		return strconv.Itoa64(int64(x.Interface().(int8))), nil
	case reflect.Int16:
		return strconv.Itoa64(int64(x.Interface().(int16))), nil
	case reflect.Int32:
		return strconv.Itoa64(int64(x.Interface().(int32))), nil
	case reflect.Int64:
		return strconv.Itoa64(x.Interface().(int64)), nil
	case reflect.Uint:
		return strconv.Uitoa(x.Interface().(uint)), nil
	case reflect.Uint8:
		return strconv.Uitoa64(uint64(x.Interface().(uint8))), nil
	case reflect.Uint16:
		return strconv.Uitoa64(uint64(x.Interface().(uint16))), nil
	case reflect.Uint32:
		return strconv.Uitoa64(uint64(x.Interface().(uint32))), nil
	case reflect.Uint64:
		return strconv.Uitoa64(x.Interface().(uint64)), nil
	case reflect.Float32:
		return strconv.Ftoa32(x.Interface().(float32), FloatFmt, FloatPrec), nil
	case reflect.Float64:
		return strconv.Ftoa64(x.Interface().(float64), FloatFmt, FloatPrec), nil
	case reflect.Complex64:
		fallthrough
	case reflect.Complex128:
		errc = ErrorUnimplemented
	case reflect.Bool:
		return strconv.Btoa(x.Interface().(bool)), nil
	default:
		errc = ErrorFieldType
	}
	return "", errc
}
Example #13
0
func (c *AuthClient) MakeRequest(url string, additional_params map[string]string, token_secret string, protected bool) (r *http.Response, finalURL string, err os.Error) {

	log.Stderrf("make_request:url:%s:", url);
	for k,v := range additional_params {
		log.Stderrf("make_request:%s:%s:", k, v);
	}

	params := make(map[string]string);
	params["oauth_consumer_key"] = c.consumer_key;
	params["oauth_signature_method"] = "HMAC-SHA1";
	params["oauth_timestamp"] =  strconv.Itoa64(time.Seconds());
	params["oauth_nonce"] = strconv.Itoa64(rand.Int63());
	params["oauth_version"] = "1.0";

	//if token != "" {
	//	params["oauth_token"] = token;
	//}
	//else {
	//	params["oauth_callback"] = c.callback_url;
	//}

	// typically: oauth_token, oauth_callback, and/or oauth_verifier
	for k,v := range additional_params {
		params[k] = v;
	}

	for k,v := range params {
		log.Stderrf("param:%s:%s:", k, v);
	}

	m := BuildMessage(url, params);

	key := c.consumer_secret + "&" + token_secret;
	log.Stderrf("key:%s", key);

	digest_str := Digest(key, m);
	params["oauth_signature"] = digest_str;
	log.Stderrf("digest_str:%s", digest_str);

	sparams := urllib.Urlencode(params);
	log.Stderrf("sparams:%s", sparams);

	rurl := strings.Join([]string{url,sparams}, "?");

	log.Stderrf("make_request:rurl:%s", rurl);

	// TODO: no easy way to add header for Authorization:OAuth when protected...?
	return http.Get(rurl);
}
Example #14
0
func LoadPost(ctx *web.Context, val string) {
	username := ctx.Params["username"]
	password := ctx.Params["password"]

	salt := strconv.Itoa64(time.Nanoseconds()) + username

	var h hash.Hash = sha256.New()
	h.Write([]byte(password + salt))

	s, _err := conn.Prepare("INSERT INTO users VALUES(NULL, ?, ?, ?)")
	utils.ReportErr(_err)

	s.Exec(username, string(h.Sum()), salt)
	s.Finalize()
	conn.Close()
	sidebar := utils.Loadmustache("admin.mustache", &map[string]string{})

	//TESTING, REMOVE LATER
	script := "<script type=\"text/javascript\" src=\"../inc/adminref.js\"></script>"
	content := "Welcome to the admin panel, use the control box on your right to control the site content"
	//ENDTESTING

	mapping := map[string]string{"css": "../inc/site.css",
		"title":   "Proggin: Admin panel",
		"sidebar": sidebar,
		"content": content,
		"script":  script}

	output := utils.Loadmustache("frame.mustache", &mapping)
	ctx.WriteString(output)
}
Example #15
0
func SetSecureCookie(rw http.ResponseWriter, name, val, path string, timeout int64) {
	var buf bytes.Buffer

	e := base64.NewEncoder(base64.StdEncoding, &buf)
	e.Write([]byte(val))
	e.Close()

	ts := strconv.Itoa64(time.Seconds())
	data := strings.Join([]string{buf.String(), ts, getCookieSig(buf.Bytes(), ts)}, "|")

	var cookie string

	// Timeout of -1 is a special case that omits the entire 'expires' bit.
	// This is used for cookies which expire as soon as a user's session ends.
	if timeout != -1 {
		t := time.UTC()
		t = time.SecondsToUTC(t.Seconds() + timeout)
		ts = t.Format(time.RFC1123)
		ts = ts[0:len(ts)-3] + "GMT"
		cookie = fmt.Sprintf("%s=%s; expires=%s; path=%s", name, data, ts, path)
	} else {
		cookie = fmt.Sprintf("%s=%s; path=%s", name, data, path)
	}

	if context.Config().Secure {
		cookie += "; secure"
	}

	rw.SetHeader("Set-Cookie", cookie)
}
Example #16
0
func main() {
	f, err := os.OpenFile("./file.exe", os.O_RDWR, 0666) //其实这里的 O_RDWR应该是 O_RDWR|O_CREATE,也就是文件不存在的情况下就建一个空文件,但是因为windows下还有BUG,如果使用这个O_CREATE,就会直接清空文件,所以这里就不用了这个标志,你自己事先建立好文件。
	if err != nil {
		panic(err)
	}
	stat, err := f.Stat() //获取文件状态
	if err != nil {
		panic(err)
	}
	f.Seek(stat.Size(), 0) //把文件指针指到文件末,当然你说为何不直接用 O_APPEND 模式打开,没错是可以。我这里只是试验。
	url := "http://dl.google.com/chrome/install/696.57/chrome_installer.exe"
	var req http.Request
	req.Method = "GET"
	//req.UserAgent = UA
	req.Close = true
	req.URL, err = http.ParseURL(url)
	if err != nil {
		panic(err)
	}
	header := http.Header{}
	header.Set("Range", "bytes="+strconv.Itoa64(stat.Size)+"-")
	req.Header = header
	resp, err := http.DefaultClient.Do(&req)
	if err != nil {
		panic(err)
	}
	written, err := io.Copy(f, resp.Body)
	if err != nil {
		panic(err)
	}
	println("written: ", written)
}
Example #17
0
func AsString(v interface{}) (string, os.Error) {
	switch value := v.(type) {
	default:
		return "", os.NewError(fmt.Sprintf("unexpected type: %T", value))
	case int:
		return strconv.Itoa(value), nil
	case int8:
		return strconv.Itoa(int(value)), nil
	case int16:
		return strconv.Itoa(int(value)), nil
	case int32:
		return strconv.Itoa(int(value)), nil
	case int64:
		return strconv.Itoa64(value), nil
	case uint:
		return strconv.Uitoa(value), nil
	case uint8:
		return strconv.Uitoa(uint(value)), nil
	case uint16:
		return strconv.Uitoa(uint(value)), nil
	case uint32:
		return strconv.Uitoa(uint(value)), nil
	case uint64:
		return strconv.Uitoa64(value), nil
	case float32:
		return strconv.Ftoa32(value, 'g', -1), nil
	case float64:
		return strconv.Ftoa64(value, 'g', -1), nil
	case string:
		return value, nil
	}
	panic(fmt.Sprintf("unsupported type: %s", reflect.ValueOf(v).Type().Name()))
}
Example #18
0
// any to string
func atos(i interface{}) (s string) {
	switch t := i.(type) {
	case int64:
		s = strconv.Itoa64(t)
	case uint64:
		s = strconv.Uitoa64(t)
	case float32:
		s = strconv.Ftoa32(t, 'f', -1)
	case float64:
		s = strconv.Ftoa64(t, 'f', -1)
	case []byte:
		s = string(t)
	case Date:
		return t.String()
	case Time:
		return t.String()
	case DateTime:
		return t.String()
	case string:
		return t
	default:
		panic("Not a string or compatible type")
	}
	return
}
Example #19
0
func enc(val reflect.Value, typ reflect.Type, buffer *bytes.Buffer, req bool) (encoded bool, err os.Error) {
	switch typ.(type) {
	case *reflect.PtrType:
		// log.Println("pointer")
		pt := typ.(*reflect.PtrType).Elem()
		pv := reflect.Indirect(val)
		// log.Println("Type is: ", pt.Name())
		if pv == nil {
			if !req {
				return false, nil
			} else {
				return false, os.NewError("Required field is nil")
			}
		}
		return enc(pv, pt, buffer, req)
	case *reflect.BoolType:
		if val.(*reflect.BoolValue).Get() {
			buffer.WriteString("true")
		} else {
			buffer.WriteString("false")
		}
	case *reflect.IntType:
		buffer.WriteString(strconv.Itoa64(val.(*reflect.IntValue).Get()))
	case *reflect.UintType:
		buffer.WriteString(strconv.Uitoa64(val.(*reflect.UintValue).Get()))
	case *reflect.StringType:
		buffer.WriteString("\"")
		// TODO: encode
		buffer.WriteString(val.(*reflect.StringValue).Get())
		buffer.WriteString("\"")
	case *reflect.FloatType:
		buffer.WriteString(strconv.Ftoa64(val.(*reflect.FloatValue).Get(), 'e', -1))
	case *reflect.StructType:
		enc_struct(val.(*reflect.StructValue), typ.(*reflect.StructType), buffer)
	case *reflect.SliceType:
		st := typ.(*reflect.SliceType).Elem()
		sv := val.(*reflect.SliceValue)
		if sv.IsNil() {
			if req {
				return false, os.NewError("Required field is nil")
			} else {
				return false, nil
			}
		}
		buffer.WriteString("[")
		for i := 0; i < sv.Len(); i++ {
			if i > 0 {
				buffer.WriteString(",")
			}
			_, err := enc(sv.Elem(i), st, buffer, true)
			if err != nil {
				return false, err
			}
		}
		buffer.WriteString("]")
	default:
		return false, os.NewError("Unsupported type")
	}
	return true, nil
}
Example #20
0
func Crawl(pool *mgo.Session, du *DigestwUser, tl *TwTimeLine, resolveURL bool, done chan<- int) {
	defer func() { done <- 0 }()
	sess := pool.New()
	defer sess.Close()
	sa := NewStatsAll(du.TwUser.Screen_Name, sess)
	var sid, first, last int64
	for k, v := range *tl {
		tmpTime, _ := time.Parse(time.RubyDate, v.Created_at)
		tmpSec := tmpTime.Seconds()
		if du.UTC_Offset != nil {
			tmpSec += *du.UTC_Offset
			v.Created_at = time.SecondsToUTC(tmpSec).Format(time.RubyDate)
		}
		if k == 0 {
			sid = v.Id
			last = tmpSec
		}
		addStats(sa, &v, resolveURL)
		if k == (len(*tl) - 1) {
			first = tmpSec
		}
		//log.Printf("id:%d", v.Id)
	}
	sa.Foreach(update)
	// decide to the next execution time
	du.SinceId = strconv.Itoa64(sid)
	du.NextSeconds = time.Seconds() + (last - first)
	if _, err := du.Upsert(sess); err != nil {
		log.Print(err)
	}
}
Example #21
0
func (stream *CommandStream) WriteQuery(body string, timeoutSeconds int64, toAddress string) os.Error {
	command := make([]string, 4)
	command[0] = queryCommandStr
	command[1] = strconv.Itoa(len(body))
	command[2] = strconv.Itoa64(timeoutSeconds)
	command[3] = toAddress

	err := stream.WriteCommand(command)
	if err != nil {
		return err
	}

	if len(body) > 0 {
		_, err = io.WriteString(stream.writer, body)
		if err != nil {
			return err
		}

		_, err = io.WriteString(stream.writer, "\r\n")
		if err != nil {
			return err
		}
	}

	return nil
}
Example #22
0
func TestSession(t *testing.T) {
	st := store.New()
	defer close(st.Ops)
	fp := &test.FakeProposer{Store: st}
	go Clean(st, fp)

	ch := make(chan store.Event, 100)
	go func(c <-chan store.Event) {
		for e := range c {
			ch <- e
		}
		close(ch)
	}(st.Watch("/session/*"))

	// check-in with less than a nanosecond to live
	body := strconv.Itoa64(time.Nanoseconds() + 1)
	fp.Propose(store.MustEncodeSet("/session/a", body, store.Clobber))

	// Throw away the set
	assert.T(t, (<-ch).IsSet())

	ev := <-ch
	assert.T(t, ev.IsDel())
	assert.Equal(t, "/session/a", ev.Path)
}
Example #23
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
}
Example #24
0
func (memc *Memcache) store(cmd string, key string, value []byte, flags int, exptime int64) os.Error {
	if memc == nil || memc.conn == nil {
		return ConnectionError
	}
	l := len(value)
	s := cmd + " " + key + " " + strconv.Itoa(flags) + " " + strconv.Itoa64(exptime) + " " + strconv.Itoa(l) + "\r\n"
	writer := bufio.NewWriter(memc.conn)
	_, err := writer.WriteString(s)
	if err != nil {
		return err
	}
	_, err = writer.Write(value)
	if err != nil {
		return err
	}
	_, err = writer.WriteString("\r\n")
	if err != nil {
		return err
	}
	err = writer.Flush()
	if err != nil {
		return err
	}
	reader := bufio.NewReader(memc.conn)
	line, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	if line != "STORED\r\n" {
		WriteError := os.NewError("memcache: " + strings.TrimSpace(line))
		return WriteError
	}
	return nil
}
Example #25
0
func (n *Network) Pass() os.Error {
	t := strconv.Itoa64(time.Nanoseconds())
	myreplies := []string{"ERR_NEEDMOREPARAMS", "ERR_ALREADYREGISTRED"}
	var err os.Error
	repch := make(chan *IrcMessage)
	for _, rep := range myreplies {
		if err := n.Listen.RegListener(replies[rep], t, repch); err != nil {
			err = os.NewError(fmt.Sprintf("Couldn't authenticate with password, exiting: %s", err.String()))
		}
	}
	ticker := time.NewTicker(timeout(n.lag))
	defer func(myreplies []string, t string, tick *time.Ticker) {
		for _, rep := range myreplies {
			n.Listen.DelListener(replies[rep], t)
		}
		tick.Stop()
		return
	}(myreplies, t, ticker)
	n.queueOut <- &IrcMessage{"", "PASS", []string{n.password}}
	select {
	case msg := <-repch:
		if msg.Cmd == replies["ERR_NEEDMOREPARAMS"] {
			err = os.NewError(fmt.Sprintf("Need more parameters for password: %s", msg.String()))
		}
		break
	case <-ticker.C:
		break
	}
	return err
}
Example #26
0
func (b bulk) repr() string {
	if b.isNil {
		return "$-1\r\n"
	}
	return "$" + strconv.Itoa64(int64(len(b.bulk))) + "\r\n" +
		b.bulk + "\r\n"
}
Example #27
0
func gdate() string {
	now := time.LocalTime()
	now.Hour = 24
	now.Minute = 60
	now.Second = 60
	var ny time.Time
	ny.Year = now.Year
	ny.Month = 1
	ny.Day = 1
	ny.Hour = 0
	ny.Minute = 0
	ny.Second = 0
	ny.Zone = "CST"
	day := (now.Seconds() - ny.Seconds()) / 86400
	return strconv.Itoa64(day) + ", " + strconv.Itoa64(now.Year)
}
Example #28
0
// CleanDir removes binary files under rundir in case they were not
// accessed for more than CleanFileDelay nanoseconds.  A last-cleaned
// marker file is created so that the next verification is only done
// after CleanFileDelay nanoseconds.
func CleanDir(rundir string, now int64) os.Error {
	cleanedfile := filepath.Join(rundir, "last-cleaned")
	if info, err := os.Stat(cleanedfile); err == nil && info.Mtime_ns > now-CleanFileDelay {
		// It's been cleaned recently.
		return nil
	}
	f, err := os.Create(cleanedfile)
	if err != nil {
		return err
	}
	_, err = f.Write([]byte(strconv.Itoa64(now)))
	f.Close()
	if err != nil {
		return err
	}

	// Look for expired files.
	d, err := os.Open(rundir)
	if err != nil {
		return err
	}
	infos, err := d.Readdir(-1)
	expired := now - CleanFileDelay
	for _, info := range infos {
		if info.Atime_ns < expired {
			os.Remove(filepath.Join(rundir, info.Name))
		}
	}
	return nil
}
Example #29
0
func serveFile(ctx *Context, name string) {
	f, err := os.Open(name, os.O_RDONLY, 0)

	if err != nil {
		ctx.Abort(404, "Invalid file")
		return
	}

	defer f.Close()

	info, _ := f.Stat()
	size := strconv.Itoa64(info.Size)
	mtime := strconv.Itoa64(info.Mtime_ns)

	//set content-length
	ctx.SetHeader("Content-Length", size, true)

	//set the last-modified header
	lm := time.SecondsToLocalTime(info.Mtime_ns / 1e9)
	ctx.SetHeader("Last-Modified", webTime(lm), true)

	//generate a simple etag with heuristic MD5(filename, size, lastmod)
	etagparts := []string{name, size, mtime}
	etag := fmt.Sprintf(`"%s"`, getmd5(strings.Join(etagparts, "|")))
	ctx.SetHeader("ETag", etag, true)

	ext := path.Ext(name)
	if ctype := mime.TypeByExtension(ext); ctype != "" {
		ctx.SetHeader("Content-Type", ctype, true)
	} else {
		// read first chunk to decide between utf-8 text and binary
		buf := make([]byte, 1024)
		n, _ := io.ReadFull(f, buf)
		b := buf[0:n]
		if isText(b) {
			ctx.SetHeader("Content-Type", "text-plain; charset=utf-8", true)
		} else {
			ctx.SetHeader("Content-Type", "application/octet-stream", true) // generic binary
		}
		if ctx.Request.Method != "HEAD" {
			ctx.Write(b)
		}
	}
	if ctx.Request.Method != "HEAD" {
		io.Copy(ctx, f)
	}
}
Example #30
0
func valueToString(v reflect.Value) (string, os.Error) {
	if v == nil {
		return "null", nil
	}

	switch v := v.(type) {
	case *reflect.PtrValue:
		return valueToString(reflect.Indirect(v))
	case *reflect.InterfaceValue:
		return valueToString(v.Elem())
	case *reflect.BoolValue:
		x := v.Get()
		if x {
			return "true", nil
		} else {
			return "false", nil
		}

	case *reflect.IntValue:
		return strconv.Itoa(v.Get()), nil
	case *reflect.Int8Value:
		return strconv.Itoa(int(v.Get())), nil
	case *reflect.Int16Value:
		return strconv.Itoa(int(v.Get())), nil
	case *reflect.Int32Value:
		return strconv.Itoa(int(v.Get())), nil
	case *reflect.Int64Value:
		return strconv.Itoa64(v.Get()), nil

	case *reflect.UintValue:
		return strconv.Uitoa(v.Get()), nil
	case *reflect.Uint8Value:
		return strconv.Uitoa(uint(v.Get())), nil
	case *reflect.Uint16Value:
		return strconv.Uitoa(uint(v.Get())), nil
	case *reflect.Uint32Value:
		return strconv.Uitoa(uint(v.Get())), nil
	case *reflect.Uint64Value:
		return strconv.Uitoa64(v.Get()), nil
	case *reflect.UintptrValue:
		return strconv.Uitoa64(uint64(v.Get())), nil

	case *reflect.FloatValue:
		return strconv.Ftoa(v.Get(), 'g', -1), nil
	case *reflect.Float32Value:
		return strconv.Ftoa32(v.Get(), 'g', -1), nil
	case *reflect.Float64Value:
		return strconv.Ftoa64(v.Get(), 'g', -1), nil

	case *reflect.StringValue:
		return v.Get(), nil
	case *reflect.SliceValue:
		typ := v.Type().(*reflect.SliceType)
		if _, ok := typ.Elem().(*reflect.Uint8Type); ok {
			return string(v.Interface().([]byte)), nil
		}
	}
	return "", os.NewError("Unsupported type")
}