id
stringlengths
2
7
text
stringlengths
17
51.2k
title
stringclasses
1 value
c6100
if n := hs.Lookup(hash); n > 0 { h = hash[:n] tds = append(tds, td) } } db.ml.RUnlock() return h, tds }
c6101
} db.tfl, db.err, db.last = nil, err, time.Time{} db.ml.Unlock() }
c6102
> 2*(db.config.UpdatePeriod+jitter) { return true } return false }
c6103
nil { db.readyCh = make(chan struct{}) } db.err = errStale }
c6104
db.ml.Unlock() if db.err != nil { close(db.readyCh) } db.err = nil }
c6105
} db.ml.RLock() for td, hs := range db.tfl { phs := db.tfu[td] phs.Hashes = hs.Export() db.tfu[td] = phs } db.ml.RUnlock() }
c6106
phs.Hashes = nil // Clear hashes to keep memory usage low db.tfu[td] = phs } db.ml.Lock() wasBad := db.err != nil db.tfl, db.last = tfl, last db.ml.Unlock() if wasBad { db.clearError() db.log.Printf("database is now healthy") } }
c6107
if zerr := gz.Close(); err == nil { err = zerr } }() encoder := gob.NewEncoder(gz) if err = encoder.Encode(db); err != nil { return err } return nil }
c6108
}() decoder := gob.NewDecoder(gz) if err = decoder.Decode(&db); err != nil { return db, err } for _, dv := range db.Table { if !bytes.Equal(dv.SHA256, dv.Hashes.SHA256()) { return db, errors.New("safebrowsing: threat list SHA256 mismatch") } } return db, nil }
c6109
phs.Hashes { if h != "" { compactHashes = append(compactHashes, h) } } phs.Hashes = compactHashes } for _, addition := range m.Additions { hashes, err := decodeHashes(addition) if err != nil { return err } phs.Hashes = append(phs.Hashes, hashes...) } // Hashes must be sorte...
c6110
return mime, errors.New("invalid interchange format") } switch req.Header.Get("Content-Type") { case mimeJSON: if err := jsonpb.Unmarshal(req.Body, pbReq); err != nil { return mime, err } case mimeProto: body, err := ioutil.ReadAll(req.Body) if err != nil { return mime, err } if err := proto.U...
c6111
:= m.Marshal(&b, pbResp); err != nil { return err } if _, err := resp.Write(b.Bytes()); err != nil { return err } default: return errors.New("invalid interchange format") } return nil }
c6112
errStr}) if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) return } resp.Header().Set("Content-Type", mimeJSON) resp.Write(buf) }
c6113
threats[0] { if tmpl, ok := threatTemplate[threat.ThreatType]; ok { t, err = parseTemplates(fs, t, tmpl, "/interstitial.html") if err != nil { http.Error(resp, err.Error(), http.StatusInternalServerError) return } err = t.Execute(resp, map[string]interface{}{ "Threat": threat, "Url": p...
c6114
_, p := range patterns { hashes[hashFromPattern(p)] = p } return hashes, nil }
c6115
[]string for _, h := range hosts { for _, p := range paths { patterns = append(patterns, h+p) } } return patterns, nil }
c6116
case 'a' <= c && c <= 'f': return true case 'A' <= c && c <= 'F': return true } return false }
c6117
reasons, 0x80 is not considered a Unicode character. if c > 0x80 { return true } } return false }
c6118
b.WriteString(fmt.Sprintf("%%%02x", c)) } else { b.WriteByte(c) } } return b.String() }
c6119
s = s[3:] } else { b.WriteByte(s[0]) s = s[1:] } } return b.String() }
c6120
s, nil } s = t } return "", errors.New("safebrowsing: unescaping is too recursive") }
c6121
return "", err } return escape(u), nil }
c6122
} } // Remove the port if it is there. host = portRegexp.ReplaceAllString(host, "") // Convert internationalized hostnames to IDNA. u := unescape(host) if isUnicode(u) { host, err = idna.ToASCII(u) if err != nil { return "", err } } // Remove any superfluous '.' characters in the hostname. host =...
c6123
} parsedURL.Scheme, rest = getScheme(rest) rest, parsedURL.RawQuery = split(rest, "?", true) // Add HTTP as scheme if none. var hostish string if !strings.HasPrefix(rest, "//") && parsedURL.Scheme != "" { return nil, errors.New("safebrowsing: invalid path") } if parsedURL.Scheme == "" { parsedURL.Scheme = ...
c6124
significantly // slower on the server side to check some extra hashes. Also the client // does not need to keep a database of TLDs. const maxHostComponents = 7 host, err := canonicalHost(urlStr) if err != nil { return nil, err } // handle IPv4 and IPv6 addresses. ip := net.ParseIP(strings.Trim(host, "[]")) ...
c6125
1; i < numComponents; i++ { paths = append(paths, "/"+strings.Join(pathComponents[:i], "/")+"/") } if path != "/" { paths = append(paths, path) } if len(parsedURL.RawQuery) > 0 { paths = append(paths, path+"?"+parsedURL.RawQuery) } return paths, nil }
c6126
:= sha256.New() hash.Write([]byte(pattern)) return hashPrefix(hash.Sum(nil)) }
c6127
strings.HasPrefix(string(h), string(other)) }
c6128
len(h) >= minHashPrefixLength && len(h) <= maxHashPrefixLength }
c6129
return hashes, nil case pb.CompressionType_RICE: values, err := decodeRiceIntegers(input.GetRiceHashes()) if err != nil { return nil, err } hashes := make([]hashPrefix, 0, len(values)) var buf [4]byte for _, h := range values { binary.LittleEndian.PutUint32(buf[:], h) hashes = append(hashes, has...
c6130
case pb.CompressionType_RICE: values, err := decodeRiceIntegers(input.GetRiceIndices()) if err != nil { return nil, err } indices := make([]int32, 0, len(values)) for _, v := range values { indices = append(indices, int32(v)) } return indices, nil default: return nil, errors.New("safebrowsing: ...
c6131
< int(rice.NumEntries); i++ { delta, err := rd.ReadValue() if err != nil { return nil, err } values = append(values, values[i]+delta) } if br.BitsRemaining() >= 8 { return nil, errors.New("safebrowsing: unconsumed rice encoded data") } return values, nil }
c6132
m != 1; m >>= 1 { n-- } return n }
c6133
c.RequestTimeout = DefaultRequestTimeout } if c.compressionTypes == nil { c.compressionTypes = []pb.CompressionType{pb.CompressionType_RAW, pb.CompressionType_RICE} } return true }
c6134
// If database file is provided, use that to initialize. if !sb.db.Init(&sb.config, sb.log) { ctx, cancel := context.WithTimeout(context.Background(), sb.config.RequestTimeout) delay, _ = sb.db.Update(ctx, sb.api) cancel() } else { if age := sb.db.SinceLastUpdate(); age < sb.config.UpdatePeriod { delay =...
c6135
QueriesFail: atomic.LoadInt64(&sb.stats.QueriesFail), DatabaseUpdateLag: sb.db.UpdateLag(), } return stats, sb.db.Status() }
c6136
case <-ctx.Done(): return ctx.Err() case <-sb.done: return errClosed } }
c6137
atomic.StoreUint32(&sb.closed, 1) close(sb.done) } return nil }
c6138
return err } defer httpResp.Body.Close() if httpResp.StatusCode != 200 { return fmt.Errorf("safebrowsing: unexpected server response code: %d", httpResp.StatusCode) } body, err := ioutil.ReadAll(httpResp.Body) if err != nil { return err } return proto.Unmarshal(body, resp) }
c6139
:= new(pb.FetchThreatListUpdatesResponse) return resp, a.doRequest(ctx, fetchUpdatePath, req, resp) }
c6140
:= new(pb.FindFullHashesResponse) return resp, a.doRequest(ctx, findHashPath, req, resp) }
c6141
}{ EmbeddedJSONAttachment: (*EmbeddedJSONAttachment)(a), Duration: a.Duration.Seconds(), }) }
c6142
return err } if raw.Duration > 0 { nsec := int64(raw.Duration * float64(time.Second)) raw.EmbeddedJSONAttachment.Duration = time.Duration(nsec) } return nil }
c6143
{ return "", err } return string(data), nil }
c6144
feed.Author = &JSONAuthor{ Name: f.Author.Name, } } for _, e := range f.Items { feed.Items = append(feed.Items, newJSONItem(e)) } return feed }
c6145
i.Content} } if i.Source != nil { item.Source = i.Source.Href } // Define a closure if i.Enclosure != nil && i.Enclosure.Type != "" && i.Enclosure.Length != "" { item.Enclosure = &RssEnclosure{Url: i.Enclosure.Url, Type: i.Enclosure.Type, Length: i.Enclosure.Length} } if i.Author != nil { item.Author = ...
c6146
r.Title, Link: r.Link.Href, Description: r.Description, ManagingEditor: author, PubDate: pub, LastBuildDate: build, Copyright: r.Copyright, Image: image, } for _, i := range r.Items { channel.Items = append(channel.Items, newRssItem(i)) } return channel }
c6147
append(f.Items, item) }
c6148
if !t.IsZero() { return t.Format(format) } } return "" }
c6149
:= &Atom{f} return ToXML(a) }
c6150
WriteXML(&Atom{f}, w) }
c6151
:= &Rss{f} return ToXML(r) }
c6152
WriteXML(&Rss{f}, w) }
c6153
:= &JSON{f} return j.ToJSON() }
c6154
:= j.JSONFeed() e := json.NewEncoder(w) e.SetIndent("", " ") return e.Encode(feed) }
c6155
j int) bool { return less(f.Items[i], f.Items[j]) } sort.SliceStable(f.Items, lessFunc) }
c6156
!= nil { panic(err) } u[8] = (u[8] | 0x80) & 0xBf u[6] = (u[6] | 0x40) & 0x4f return u }
c6157
= &AtomAuthor{AtomPerson: AtomPerson{Name: a.Author.Name, Email: a.Author.Email}} } for _, e := range a.Items { feed.Entries = append(feed.Entries, newAtomEntry(e)) } return feed }
c6158
return unsafe.Pointer(uintptr(p) + x) }
c6159
if ver == "go1.5" || strings.HasPrefix(ver, "go1.5.") { loadGo15Types() } else if ver == "go1.6" || strings.HasPrefix(ver, "go1.6.") { loadGo15Types() } else { loadGo17Types() } }
c6160
return Type2(types[typeName]) }
c6161
pkgTypes := packages[pkgPath] if pkgTypes == nil { return nil } return Type2(pkgTypes[name]) }
c6162
if err != nil { return nil, err } return withBuffer(opts, &DynamicLargeObjectCreateFile{ largeObjectCreateFile: *lo, }), nil }
c6163
error) { opts.Flags = os.O_TRUNC | os.O_CREATE return c.DynamicLargeObjectCreateFile(opts) }
c6164
{ return c.LargeObjectDelete(container, path) }
c6165
} segmentContainer, segmentPath := parseFullPath(headers["X-Object-Manifest"]) if err := c.createDLOManifest(dstContainer, dstObjectName, segmentContainer+"/"+segmentPath, info.ContentType); err != nil { return err } if err := c.ObjectDelete(srcContainer, srcObjectName); err != nil { return err } return ...
c6166
"", contentType, headers) if err != nil { return err } if err := manifest.Close(); err != nil { return err } return nil }
c6167
return &v2Auth{ // Guess as to whether using API key or // password it will try both eventually so // this is just an optimization. useApiKey: len(c.ApiKey) >= 32, }, nil case 3: return &v3Auth{}, nil } return nil, newErrorf(500, "Auth Version %d not supported", AuthVersion) }
c6168
err != nil { return nil, err } req.Header.Set("User-Agent", c.UserAgent) req.Header.Set("X-Auth-Key", c.ApiKey) req.Header.Set("X-Auth-User", c.UserName) return req, nil }
c6169
error { auth.Headers = resp.Header return nil }
c6170
} newUrl.Host = "snet-" + newUrl.Host storageUrl = newUrl.String() } return storageUrl }
c6171
v2.Auth.Tenant = c.Tenant v2.Auth.TenantId = c.TenantId v2i = v2 } else { // Rackspace special with API Key v2 := v2AuthRequestRackspace{} v2.Auth.ApiKeyCredentials.UserName = c.UserName v2.Auth.ApiKeyCredentials.ApiKey = c.ApiKey v2.Auth.Tenant = c.Tenant v2.Auth.TenantId = c.TenantId v2i = v2 } ...
c6172
need to toggle useApiKey any more if err == nil { auth.useApiKeyOk = true } return err }
c6173
EndpointTypePublic: return endpoint.PublicUrl case EndpointTypeAdmin: return endpoint.AdminUrl default: return "" } } } } } return "" }
c6174
return time.Time{} // return Zero if not parsed } return t }
c6175
*timeoutReader { return &timeoutReader{ reader: reader, timeout: timeout, cancel: cancel, } }
c6176
timeout, reader: reader, timer: timer, chunkSize: watchdogChunkSize, } }
c6177
lo, err := c.largeObjectCreate(opts) if err != nil { return nil, err } return withBuffer(opts, &StaticLargeObjectCreateFile{ largeObjectCreateFile: *lo, }), nil }
c6178
error) { opts.Flags = os.O_TRUNC | os.O_CREATE return c.StaticLargeObjectCreateFile(opts) }
c6179
{ return SLONotSupported } return c.LargeObjectDelete(container, path) }
c6180
safe for copying) headers = headers.ObjectMetadata().ObjectHeaders() if err := c.createSLOManifest(dstContainer, dstObjectName, info.ContentType, container, segments, headers); err != nil { return err } if err := c.ObjectDelete(srcContainer, srcObjectName); err != nil { return err } return nil }
c6181
sloSegments[i].Etag = segment.Hash sloSegments[i].Size = segment.Bytes } content, err := json.Marshal(sloSegments) if err != nil { return err } values := url.Values{} values.Set("multipart-manifest", "put") if _, err := c.objectPut(container, path, bytes.NewBuffer(content), false, "", contentType, h, va...
c6182
not exist on the authenticated platform") } return c.cdnUrl, nil } if c.Authenticated() { _, err = p.OnReAuth() if err != nil { return nil, nil, err } } return c.Connection.Call(c.cdnUrl, p) }
c6183
err := c.manage(swift.RequestOpts{ Container: container, Operation: "PUT", ErrorMap: swift.ContainerErrorMap, NoResponse: true, Headers: h, }) return err }
c6184
tr, ok := transport.(interface { CancelRequest(*http.Request) }); ok { tr.CancelRequest(req) } }
c6185
d time.Duration) { t.Reset(d) }
c6186
segmentPath = gopath.Dir(segments[0].Name) } } else { if err = c.ObjectMove(opts.Container, opts.ObjectName, opts.Container, getSegment(segmentPath, 1)); err != nil { return nil, err } segments = append(segments, info) } } } else if err != ObjectNotFound { return nil, err } // segmen...
c6187
for i, obj := range objects { filenames[i] = obj[0] + "/" + obj[1] } _, err = c.doBulkDelete(filenames) // Don't fail on ObjectNotFound because eventual consistency // makes this situation normal. if err != nil && err != Forbidden && err != ObjectNotFound { return err } } else { for _, obj := ran...
c6188
fmt.Errorf("invalid value for whence") } if file.filePos < 0 { return -1, fmt.Errorf("negative offset") } return file.filePos, nil }
c6189
if writeSegmentIdx < len(file.segments) { file.segments[writeSegmentIdx] = *newSegment } else { file.segments = append(file.segments, *newSegment) } offset += n writeSegmentIdx++ relativeFilePos = 0 } file.filePos += int64(sizeToWrite) file.currentLength = 0 for _, obj := range file.segments { ...
c6190
for key, value := range h { if strings.HasPrefix(key, metaPrefix) { metaKey := strings.ToLower(key[len(metaPrefix):]) m[metaKey] = value } } return m }
c6191
result[split:] decimals = strings.TrimRight(decimals, "0") if decimals != "" { result += "." result += decimals } return result }
c6192
} else if len(s) > 0 { // Make sure empty string produces an error s += zeros } return strconv.ParseInt(s, 10, 64) }
c6193
{ return &Error{ StatusCode: StatusCode, Text: Text, } }
c6194
newError(StatusCode, fmt.Sprintf(Text, Parameters...)) }
c6195
cerr := rd.Close() if err != nil && *err == nil { *err = cerr } }
c6196
> 299 { drainAndClose(resp.Body, nil) return newErrorf(resp.StatusCode, "HTTP Error: %d: %s", resp.StatusCode, resp.Status) } return nil }
c6197
return r.resp, r.err case <-timer.C: // Kill the connection on timeout so we don't leak sockets or goroutines cancelRequest(c.Transport, req) return nil, TimeoutError } panic("unreachable") // For Go 1.0 }
c6198
linux's default open files limit (1024). MaxIdleConnsPerHost: 512, } SetExpectContinueTimeout(t, 5*time.Second) c.Transport = t } if c.client == nil { c.client = &http.Client{ // CheckRedirect: redirectPolicyFunc, Transport: c.Transport, } } }
c6199
c.authLock.Unlock() return c.authenticate() }