func (i *Instances) ExportDel(sess, inst, method string, retval int) error { i.lck.Lock() defer i.lck.Unlock() s, found := i.Insts[sess] if !found { return e.New(ErrSessionNotFound) } in, found := s.Insts[inst] if !found { return e.New(ErrInstanceNotFound) } retvals, found := in.Export()[method] if !found { return e.New(ErrMethodNotFound) } _, found = retvals[retval] if !found { return e.New(ErrReturnValueNotFound) } delete(retvals, retval) if len(retvals) == 0 { delete(in.Export(), method) } return nil }
func NewMongoDb(rawurl, collection string, safe *mgo.Safe, entry Entry, timeout time.Duration) (Storer, error) { var err error m := &MongoDb{} err = chkData(entry) if err != nil { return nil, e.Forward(err) } m.tentry = reflect.TypeOf(entry) if m.tentry.Kind() != reflect.Ptr { m.tentry = reflect.PtrTo(m.tentry) } m.session, err = mgo.DialWithTimeout(rawurl, timeout) if err != nil { return nil, e.New(err) } parsed, err := url.Parse(rawurl) if err != nil { return nil, e.New(err) } if safe == nil { safe = &mgo.Safe{} } m.session.SetSafe(safe) m.dbname = strings.Trim(parsed.Path, "/") m.db = m.session.DB(m.dbname) m.collection = collection m.c = m.db.C(collection) return m, nil }
func (c *clone) Init(inst string) error { if c.Num <= 0 { return e.New("number of clones invalid") } if c.Session == nil { return e.New("nil Session") } if c.Num > c.MaxNum { return e.New("number of initial streams is greater than the maximun") } c.inst = inst c.once.Do(func() { c.conns = make([]connInst, 0, c.Num) log.ProtoLevel().Tag("gormethods", "client", "clone").Println("Init clones.") for i := 0; i < c.Num; i++ { conn, err := c.Session.NamedInstance(c.inst) if err != nil { log.ProtoLevel().Tag("gormethods", "client", "clone").Printf("New instance failed: %v.", err) continue } c.conns = append(c.conns, conn) } }) return nil }
func (i *Instances) Export(sess, inst string, exp *ToExport) error { i.lck.Lock() defer i.lck.Unlock() s, found := i.Insts[sess] if !found { return e.New(ErrSessionNotFound) } in, found := s.Insts[inst] if !found { return e.New(ErrInstanceNotFound) } m, ok := in.Instance().Type().MethodByName(exp.Method) if !ok { return e.New(ErrMethodNotFound) } if exp.RetvalPos >= m.Type.NumOut() { return e.New(ErrInvRetval) } retvals, found := in.Export()[exp.Method] if !found { retvals = make(map[int]*Export) in.Export()[exp.Method] = retvals } if exp.Export.Client == nil { return e.New(ErrInvClient) } retvals[exp.RetvalPos] = exp.Export return nil }
//NewMulti creates a MultiLog func NewMulti(vals ...interface{}) LogBackend { if len(vals)%2 != 0 { Fail(e.New("parameters must be in pair of LogBackend and Formatter")) return nil } l := len(vals) / 2 mp := make([]LogBackend, 0, l) for i := 0; i < len(vals); i += 2 { bak, ok := vals[i].(LogBackend) if !ok { Fail(e.New("not a LogBackend")) return nil } f, ok := vals[i+1].(Formatter) if !ok { Fail(e.New("not a Formatter")) return nil } bak.F(f) mp = append(mp, bak) } return &MultiLog{ mp: mp, } }
func (a *Server) bind() (conn *net.UDPConn, err error) { if !a.NotMulticast && a.iface.Flags&net.FlagMulticast == net.FlagMulticast { gaddr, err := a.groupAddr() if err != nil { return nil, e.Forward(err) } conn, err = net.ListenMulticastUDP(a.Proto(), a.iface, gaddr) if err != nil { return nil, e.New(err) } } else { server, err := net.ResolveUDPAddr(a.Proto(), ":"+a.Port) if err != nil { return nil, e.New(err) } conn, err = net.ListenUDP(a.Proto(), server) if err != nil { return nil, e.New(err) } } a.ipver(conn.LocalAddr()) _, a.Port, err = utilNet.SplitHostPort(conn.LocalAddr().String()) if err != nil { return nil, e.Forward(err) } return }
// Put inserts in the database the struct in v, v must have the fild _id and // the field _rev both strings. Like the TestStruct struct. func (c *Couch) Put(v interface{}) (id, rev string, err error) { data, err := json.Marshal(v) if err != nil { return "", "", e.Push(err, "can't serialize the data") } id = grepId(data) if id == "" { return "", "", e.New("document have no id") } code, resp, err := c.put(id, "", data) if err != nil && code == 409 { return "", "", e.Push(err, ErrDocConflict) } else if err != nil { return "", "", e.Push(err, "can't put the document") } if code == http.StatusCreated { ir := new(response) err := json.Unmarshal(resp, ir) if err != nil { return "", "", e.Push(e.Push(err, "can't desserialize returned data"), "can't put the document") } if !ir.Ok { return "", "", e.New("put failed") } return ir.Id, ir.Rev, nil } return "", "", e.Push(e.Push(err, e.New("received wrong response code, %v", code)), "can't put the document") }
// PingHttp connect a http or https server and try to // receive something. If the server return a code different // of 2xx, it will fail. Ignores insecure certificates. func PingHttp(url *url.URL) error { resp, err := httpClient.Get(url.String()) if e.Contains(err, "connection refused") { return e.Push(e.New(err), "get failed: connection refused") } else if err != nil { return e.Push(e.New(err), "get failed") } defer resp.Body.Close() buf := make([]byte, 4096) if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { n, err := resp.Body.Read(buf) if err != nil && err != io.EOF { return e.Forward(err) } buf = buf[:n] //status.Log(status.Protocol, "PingHttp status code is %v and received it from server: %v", resp.StatusCode, string(buf)) log.ProtoLevel().Printf("PingHttp status code is %v and received it from server: %v", resp.StatusCode, string(buf)) return e.New("returned status code %v, expected 2xx", resp.StatusCode) } _, err = resp.Body.Read(buf) if err != nil && err != io.EOF { return e.Forward(err) } return nil }
// TypeOf returns the type of val. If samething wrong occur return a error. // This functoin don't panic. func TypeOf(val reflect.Value) (t reflect.Type, err error) { defer func() { r := recover() if r != nil { switch v := r.(type) { case error: err = e.Forward(v) case string: if strings.Contains(v, "runtime error") { panic(r) } err = e.New(v) default: err = e.New("unable to type switch the recover data") } } }() t = val.Type() if t.Kind() == reflect.Interface { if val.Elem().IsValid() { t = val.Elem().Type() } else { err = e.New("invalid interface") } } return }
func (t *transaction) Put(key string, data interface{}) error { if !t.write { return e.New(ErrReadOnly) } if key == "" { return e.New(ErrInvKey) } t.m[key] = data idx := *t.idx defer func() { *t.idx = idx }() if len(idx) == 0 { idx = append(idx, key) return nil } i := searchString(idx, key) if i >= len(idx) || idx[i] != key { if i+1 > len(idx) { idx = append(idx, key) return nil } idx = append(idx[:i], append([]string{key}, idx[i:]...)...) } return nil }
// Delete deletes from database the id id with rev revision. // If rev is empty Delete deletes the last revision. func (c *Couch) Delete(id, rev string) (string, error) { if rev == "" { revision := new(idRev) err := c.Get(id, "", revision) if e.Equal(err, ErrCantGetDoc) { return "", e.Push(err, ErrDocDontExist) } else if err != nil { return "", e.Push(err, "not deleted") } rev = revision.Rev } rev = "rev=" + rev code, resp, err := c.delete(id, rev, nil) if err != nil && code == 404 { return "", e.Push(err, ErrDocDontExist) } else if err != nil { return "", e.Push(err, "not deleted") } if code != http.StatusOK && code != http.StatusAccepted { return "", e.New("can't delete the document, wrong code: %v", code) } dr := new(response) err = json.Unmarshal(resp, dr) if err != nil { return "", e.Push(e.Push(err, "can't desserialize returned data"), "can't put the document") } if !dr.Ok { return "", e.New("delete failed") } if dr.Id != id { return "", e.New("response with the wrong id") } return dr.Rev, nil }
func (c *client) do(method, path, params string, body []byte) (int, []byte, error) { url := utilUrl.Copy(c.url) url.Path += path url.RawQuery = params var buf io.Reader if len(body) > 0 { buf = bytes.NewBuffer(body) } req, err := http.NewRequest(method, url.String(), buf) if err != nil { return 0, nil, e.New("can't create request") } if c.url.User != nil { req.Header.Set("Authorization", authorizationHeader(url.User.String())) } req.Header.Set("Content-Type", "application/json") resp, err := HttpClient.Do(req) if err != nil { return 0, nil, e.Push(err, "can't put") } defer resp.Body.Close() if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { return resp.StatusCode, nil, e.New("wrong status code - %v: %v", resp.StatusCode, resp.Status) } var data []byte data, _ = ioutil.ReadAll(resp.Body) return resp.StatusCode, data, nil }
func (c *Constructors) Construct(name string, args ...interface{}) (reflect.Value, error) { c.lck.Lock() defer c.lck.Unlock() con, found := c.constructors[name] if !found { t, err := types.GetType(name) if err != nil { return reflect.Value{}, e.New(ErrTypeNotFound) } return types.Make(t), nil } vals := make([]reflect.Value, 0, len(args)) for _, arg := range args { vals = append(vals, reflect.ValueOf(arg)) } retvals := con.Call(vals) if len(retvals) != 2 { return reflect.Value{}, e.New(ErrInvReturn) } if retvals[1].Interface() != nil { err, ok := retvals[1].Interface().(error) if !ok { return reflect.Value{}, e.New(ErrInvReturn) } if err != nil { return reflect.Value{}, e.Forward(err) } } return retvals[0], nil }
func (i *Intface) getInt() error { if i.Interface != "" && i.iface == nil { ints, err := net.Interfaces() if err != nil { return e.New(err) } for _, in := range ints { if in.Name == i.Interface { i.iface = &in return nil } } return e.New("none interface with this name") } else if i.Interface == "" && i.iface == nil { ints, err := net.Interfaces() if err != nil { return e.New(err) } var intName string for _, in := range ints { if in.Flags&net.FlagMulticast == net.FlagMulticast || in.Flags&net.FlagBroadcast == net.FlagBroadcast || in.Flags&net.FlagBroadcast == net.FlagBroadcast { _, intName = getInterface(in) if intName == "" { continue } i.Interface = intName i.iface = &in break } } } return nil }
// NewStdFormatter crete a new formatter. func NewStdFormatter(delim, tmpl string, entry Entry, values map[string]interface{}, timeformat string) (Formatter, error) { if delim == "" { return nil, e.New("invalid delimitator") } if tmpl == "" { return nil, e.New("invalid template") } if entry == nil { return nil, e.New("invalid entry") } if values == nil { return nil, e.New("invalid values") } if timeformat == "" { timeformat = TimeDateFormat } return &StdFormatter{ Delim: []byte(delim), Tmpl: []byte(tmpl), E: entry, Map: values, Idx: mkindex(entry), TimeFormat: timeformat, }, nil }
func makeFunction(f *Func) (*Function, error) { var args []*Argument if len(f.Params.Arguments) >= 1 { args = f.Params.Arguments[0] } var results []*Argument if len(f.Params.Arguments) >= 2 { results = f.Params.Arguments[1] } found := -1 for i, r := range results { if r.Type == "error" { found = i } } if found >= 0 && found != len(results)-1 { return nil, e.New("one error must be the last result") } named := false for i, r := range results { if len(r.Names) > 0 && i == 0 { named = true } if len(r.Names) == 0 && named { return nil, e.New("all results must be named") } else if len(r.Names) > 0 && !named { return nil, e.New("all results must be unnamed") } if r.Type == "error" && len(r.Names) > 0 && r.Names[len(r.Names)-1] != "err" { return nil, e.New("last error must be named err") } } if !named { for i, r := range results { if r.Type == "error" { r.Names = []string{"err"} continue } r.Names = []string{fmt.Sprintf("arg%v", i)} } } for i, arg := range args { for j, name := range arg.Names { if name == "_" { arg.Names[j] = "param" + strconv.Itoa(i) + strconv.Itoa(j) } } } function := &Function{ Name: f.Name, RecvVar: f.Recv, RecvType: f.RecvType, Arguments: args, Results: results, ReturnErr: found >= 0, Comments: f.Comments, } return function, nil }
// Check if a tag is formed with the corrects characters func CheckTag(tag string) error { for _, v := range tag { if !u.IsLetter(v) && !unicode.IsDigit(v) && v != ' ' && v != '-' && v != '_' && v != '.' && v != '/' && v != ':' { return e.Push(e.New(ErrInvalidTagChar), e.New("the character '%v' is invalid", string([]byte{byte(v)}))) } } return nil }
func CheckDomain(domain string) error { for _, v := range domain { if !uni.IsLetter(v) && !unicode.IsDigit(v) && v != '.' { return e.Push(e.New("invalid domain name"), e.New("the character '%v' in redirect is invalid", string([]byte{byte(v)}))) } } return nil }
func CheckObjectName(name string) error { for _, v := range name { if !uni.IsLetter(v) && !unicode.IsDigit(v) && v != '-' && v != '_' && v != '*' && v != '{' && v != '}' && v != '/' && v != '.' && v != '[' && v != ']' { return e.Push(e.New(text.ErrInvCharacter), e.New("the character '%v' in object name is invalid", string([]byte{byte(v)}))) } } return nil }
// CheckHash the hash of a password. func CheckHash(name string) error { for _, v := range name { if !uni.IsLetter(v) && !unicode.IsDigit(v) && v != '-' && v != '_' && v != '.' && v != '=' { return e.Push(e.New(text.ErrInvCharacter), e.New("the character '%v' in instance name is invalid", string([]byte{byte(v)}))) } } return nil }
func lookupHost(host string, config *dns.ClientConfig) (addrs []string, err error) { if utilNet.IsValidIpv4(host) || utilNet.IsValidIpv6(host) { return []string{host}, nil } if host == "localhost" { return []string{"127.0.0.1", "::1"}, nil } c := new(dns.Client) c.DialTimeout = DialTimeout c.ReadTimeout = ReadTimeout c.WriteTimeout = WriteTimeout m := new(dns.Msg) m.SetQuestion(dns.Fqdn(host), dns.TypeA) var r *dns.Msg for i := 0; i < len(config.Servers); i++ { r, _, err = c.Exchange(m, config.Servers[i]+":"+config.Port) if err != nil { continue } err = nil } if err != nil { return nil, e.Forward(err) } if r.Rcode != dns.RcodeSuccess { return nil, e.New("can't resolve %v", host) } addrs = make([]string, 0, 10) for _, a := range r.Answer { if addr, ok := a.(*dns.A); ok { addrs = append(addrs, addr.A.String()) } } m.SetQuestion(dns.Fqdn(host), dns.TypeAAAA) for i := 0; i < len(config.Servers); i++ { r, _, err = c.Exchange(m, config.Servers[0]+":"+config.Port) if err != nil { continue } err = nil } if err != nil { return nil, e.Forward(err) } if r.Rcode != dns.RcodeSuccess { return nil, e.New("no success") } for _, a := range r.Answer { if addr, ok := a.(*dns.AAAA); ok { addrs = append(addrs, addr.AAAA.String()) } } return }
func (s StdFormatter) Format(entry Entry) (out []byte, err error) { val := reflect.Indirect(reflect.ValueOf(entry)) if val.Kind() != reflect.Struct { return nil, e.New("formater only accept entries that are structs ") } if val.Type() != reflect.Indirect(reflect.ValueOf(s.E)).Type() { return nil, e.New(ErrNotSupported) } out = make([]byte, len(s.Tmpl), len(s.Tmpl)*2) copy(out, s.Tmpl) for { start := bytes.Index(out, s.Delim) if start == -1 { break } var end int cut := out[start:] i := findCut(cut) if i > -1 { end = start + i } else { end = start + len(cut) } name := out[start+len(s.Delim) : end] var v string bname := string(name) fidx, found := s.Idx[bname] if found { fval := val.Field(fidx.I) v = scapeSep(stringfy(fval, s.TimeFormat), s.Delim) } else { inter, found := s.Map[bname] if !found { v = "" } else { fval := reflect.Indirect(reflect.ValueOf(inter)) v = scapeSep(stringfy(fval, s.TimeFormat), s.Delim) } } if v == "" { v = fidx.Def } vb := []byte(v) out = append(out[:start], append(vb, out[end:]...)...) } scape := scapemark(s.Delim) out = bytes.Replace(out, scape, s.Delim, -1) out = bytes.Replace(out, []byte{' ', ' '}, []byte{' '}, -1) return }
func delete(tx *bolt.Tx, hash, kw, kh []byte) error { bimg := tx.Bucket([]byte(images)) bhits := tx.Bucket([]byte(hits)) w := bimg.Get(hash) if w == nil { return e.New(ErrImageNotFound) } bw := tx.Bucket(append(hash, w...)) if bw == nil { return e.New(ErrImageNotFound) } h := bw.Get(kw) if h == nil { return e.New(ErrImageNotFound) } bh := tx.Bucket([]byte(string(hash) + string(w) + string(h))) if bh == nil { return e.New(ErrImageNotFound) } err := bh.Delete(kh) if err != nil { return e.Forward(err) } if bh.Stats().KeyN <= 0 { err = tx.DeleteBucket([]byte(string(hash) + string(w) + string(h))) if err != nil { return e.Forward(err) } err = bw.Delete(kw) if err != nil { return e.Forward(err) } if bw.Stats().KeyN <= 0 { err = tx.DeleteBucket(append(hash, w...)) if err != nil { return e.Forward(err) } err = bimg.Delete(hash) if err != nil { return e.Forward(err) } } } // BUG: FAULT ADDRS hitshash := append(hash, append(kw, kh...)...) err = bhits.Delete(hitshash) if err != nil { return e.Forward(err) } return nil }
func CheckEmail(email string) error { if len(email) < MinEmailLen || len(email) > MaxEmailLen { return e.New(ErrInvEmailLength) } if email != reMail.FindString(email) { return e.New(ErrInvEmailString) } return nil }
func PingImap(url *url.URL) error { if url.Scheme != "imap" && url.Scheme != "imaps" { return e.New("not an imap/imaps scheme") } c, err := dialImap(url.Host) if err != nil { return e.Push(err, ErrImapFailed) } defer c.Logout(30 * time.Second) if c.Caps["STARTTLS"] { _, err := c.StartTLS(tlsConfig) if err != nil { return e.Push(err, ErrImapFailed) } } if c.Caps["ID"] { _, err := c.ID("name", "goimap") if err != nil { return e.Push(err, ErrImapFailed) } } cmd, err := c.Noop() if err != nil { return e.Push(err, ErrImapFailed) } rsp, err := cmd.Result(imap.OK) if err != nil { return e.Push(err, ErrImapFailed) } //log.Println(rsp.Status, rsp.Info) if rsp.Status != imap.OK { return e.New(ErrImapFailed) } if url.User == nil { return nil } username := url.User.Username() pass, ok := url.User.Password() if username != "" && ok { cmd, err := c.Login(username, pass) if err != nil { return e.Push(err, ErrImapFailed) } rsp, err := cmd.Result(imap.OK) if err != nil { return e.Push(err, ErrImapFailed) } if rsp.Status != imap.OK { return e.New(ErrImapFailed) } } return nil }
func (d *Daemon) kill(num syscall.Signal) error { if d.pid == -1 { return e.New(ErrNoPid) } err := syscall.Kill(-d.pid, num) if err != nil { return e.New(err) } return nil }
func isOk(buf []byte) (bool, error) { if len(buf) < offcmd1 { return false, e.New("buffer is too small") } cmd, b := binary.Uvarint(buf[:offcmd1]) if b <= 0 { return false, e.New("invalid comand") } return ctrlCommands(cmd) == ok, nil }
// PingTCP try to connect a TCP port. func PingTCP(url *url.URL) error { conn, err := net.Dial("tcp", url.Host) if err != nil { return e.New(err) } err = conn.Close() if err != nil { return e.New(err) } return nil }
// Check the user password. Graphics character are allowed. See unicode.IsGraphic. func CheckPassword(pass string, min, max int) error { if len(pass) < min || len(pass) > max { return e.New(ErrInvalidPassLength) } for _, r := range pass { if !unicode.IsGraphic(r) { return e.New(ErrInvalidPassChar) } } return nil }
func CheckText(text string, min, max int) error { if len(text) < min || len(text) > max { return e.New(ErrInvNumberChars) } for _, v := range text { if !uni.IsLetter(v) && !unicode.IsDigit(v) && v != '\n' && v != ' ' && v != '`' && v != '~' && v != '!' && v != '@' && v != '#' && v != '$' && v != '%' && v != '^' && v != '&' && v != '*' && v != '(' && v != ')' && v != '_' && v != '-' && v != '+' && v != '=' && v != '{' && v != '}' && v != '[' && v != ']' && v != '|' && v != '\\' && v != ':' && v != ';' && v != '"' && v != '\'' && v != '?' && v != '/' && v != ',' && v != '.' { return e.Push(e.New(ErrInvCharacter), e.New("the character '%v' is invalid", string([]byte{byte(v)}))) } } return nil }