id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
153,400
rook/operator-kit
sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/myproject_client.go
NewForConfigOrDie
func NewForConfigOrDie(c *rest.Config) *MyprojectV1alpha1Client { client, err := NewForConfig(c) if err != nil { panic(err) } return client }
go
func NewForConfigOrDie(c *rest.Config) *MyprojectV1alpha1Client { client, err := NewForConfig(c) if err != nil { panic(err) } return client }
[ "func", "NewForConfigOrDie", "(", "c", "*", "rest", ".", "Config", ")", "*", "MyprojectV1alpha1Client", "{", "client", ",", "err", ":=", "NewForConfig", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "client", "\n", "}" ]
// NewForConfigOrDie creates a new MyprojectV1alpha1Client for the given config and // panics if there is an error in the config.
[ "NewForConfigOrDie", "creates", "a", "new", "MyprojectV1alpha1Client", "for", "the", "given", "config", "and", "panics", "if", "there", "is", "an", "error", "in", "the", "config", "." ]
e7b2e1264fff5f1dc9d506089af2399621b5a0c1
https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/myproject_client.go#L57-L63
153,401
rook/operator-kit
watcher.go
NewWatcher
func NewWatcher(resource CustomResource, namespace string, handlers cache.ResourceEventHandlerFuncs, client rest.Interface) *ResourceWatcher { return &ResourceWatcher{ resource: resource, namespace: namespace, resourceEventHandlers: handlers, client: client, } }
go
func NewWatcher(resource CustomResource, namespace string, handlers cache.ResourceEventHandlerFuncs, client rest.Interface) *ResourceWatcher { return &ResourceWatcher{ resource: resource, namespace: namespace, resourceEventHandlers: handlers, client: client, } }
[ "func", "NewWatcher", "(", "resource", "CustomResource", ",", "namespace", "string", ",", "handlers", "cache", ".", "ResourceEventHandlerFuncs", ",", "client", "rest", ".", "Interface", ")", "*", "ResourceWatcher", "{", "return", "&", "ResourceWatcher", "{", "resource", ":", "resource", ",", "namespace", ":", "namespace", ",", "resourceEventHandlers", ":", "handlers", ",", "client", ":", "client", ",", "}", "\n", "}" ]
// NewWatcher creates an instance of a custom resource watcher for the given resource
[ "NewWatcher", "creates", "an", "instance", "of", "a", "custom", "resource", "watcher", "for", "the", "given", "resource" ]
e7b2e1264fff5f1dc9d506089af2399621b5a0c1
https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/watcher.go#L44-L51
153,402
rook/operator-kit
resource.go
CreateCustomResources
func CreateCustomResources(context Context, resources []CustomResource) error { var lastErr error for _, resource := range resources { if err := createCRD(context, resource); err != nil { lastErr = err } } for _, resource := range resources { if err := waitForCRDInit(context, resource); err != nil { lastErr = err } } return lastErr }
go
func CreateCustomResources(context Context, resources []CustomResource) error { var lastErr error for _, resource := range resources { if err := createCRD(context, resource); err != nil { lastErr = err } } for _, resource := range resources { if err := waitForCRDInit(context, resource); err != nil { lastErr = err } } return lastErr }
[ "func", "CreateCustomResources", "(", "context", "Context", ",", "resources", "[", "]", "CustomResource", ")", "error", "{", "var", "lastErr", "error", "\n", "for", "_", ",", "resource", ":=", "range", "resources", "{", "if", "err", ":=", "createCRD", "(", "context", ",", "resource", ")", ";", "err", "!=", "nil", "{", "lastErr", "=", "err", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "resource", ":=", "range", "resources", "{", "if", "err", ":=", "waitForCRDInit", "(", "context", ",", "resource", ")", ";", "err", "!=", "nil", "{", "lastErr", "=", "err", "\n", "}", "\n", "}", "\n\n", "return", "lastErr", "\n", "}" ]
// CreateCustomResources creates the given custom resources and waits for them to initialize // The resource is of kind CRD if the Kubernetes server is 1.7.0 and above. // The resource is of kind TPR if the Kubernetes server is below 1.7.0.
[ "CreateCustomResources", "creates", "the", "given", "custom", "resources", "and", "waits", "for", "them", "to", "initialize", "The", "resource", "is", "of", "kind", "CRD", "if", "the", "Kubernetes", "server", "is", "1", ".", "7", ".", "0", "and", "above", ".", "The", "resource", "is", "of", "kind", "TPR", "if", "the", "Kubernetes", "server", "is", "below", "1", ".", "7", ".", "0", "." ]
e7b2e1264fff5f1dc9d506089af2399621b5a0c1
https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/resource.go#L70-L86
153,403
rook/operator-kit
client.go
NewHTTPClient
func NewHTTPClient(group, version string, schemeBuilder runtime.SchemeBuilder) (rest.Interface, *runtime.Scheme, error) { config, err := rest.InClusterConfig() if err != nil { return nil, nil, err } return NewHTTPClientFromConfig(group, version, schemeBuilder, config) }
go
func NewHTTPClient(group, version string, schemeBuilder runtime.SchemeBuilder) (rest.Interface, *runtime.Scheme, error) { config, err := rest.InClusterConfig() if err != nil { return nil, nil, err } return NewHTTPClientFromConfig(group, version, schemeBuilder, config) }
[ "func", "NewHTTPClient", "(", "group", ",", "version", "string", ",", "schemeBuilder", "runtime", ".", "SchemeBuilder", ")", "(", "rest", ".", "Interface", ",", "*", "runtime", ".", "Scheme", ",", "error", ")", "{", "config", ",", "err", ":=", "rest", ".", "InClusterConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "return", "NewHTTPClientFromConfig", "(", "group", ",", "version", ",", "schemeBuilder", ",", "config", ")", "\n", "}" ]
// NewHTTPClient creates a Kubernetes client to interact with API extensions for Custom Resources
[ "NewHTTPClient", "creates", "a", "Kubernetes", "client", "to", "interact", "with", "API", "extensions", "for", "Custom", "Resources" ]
e7b2e1264fff5f1dc9d506089af2399621b5a0c1
https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/client.go#L32-L39
153,404
rook/operator-kit
sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/sample.go
NewSampleInformer
func NewSampleInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFilteredSampleInformer(client, namespace, resyncPeriod, indexers, nil) }
go
func NewSampleInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFilteredSampleInformer(client, namespace, resyncPeriod, indexers, nil) }
[ "func", "NewSampleInformer", "(", "client", "versioned", ".", "Interface", ",", "namespace", "string", ",", "resyncPeriod", "time", ".", "Duration", ",", "indexers", "cache", ".", "Indexers", ")", "cache", ".", "SharedIndexInformer", "{", "return", "NewFilteredSampleInformer", "(", "client", ",", "namespace", ",", "resyncPeriod", ",", "indexers", ",", "nil", ")", "\n", "}" ]
// NewSampleInformer constructs a new informer for Sample type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server.
[ "NewSampleInformer", "constructs", "a", "new", "informer", "for", "Sample", "type", ".", "Always", "prefer", "using", "an", "informer", "factory", "to", "get", "a", "shared", "informer", "instead", "of", "getting", "an", "independent", "one", ".", "This", "reduces", "memory", "footprint", "and", "number", "of", "connections", "to", "the", "server", "." ]
e7b2e1264fff5f1dc9d506089af2399621b5a0c1
https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/sample.go#L50-L52
153,405
rook/operator-kit
sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/sample.go
NewFilteredSampleInformer
func NewFilteredSampleInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.MyprojectV1alpha1().Samples(namespace).List(options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.MyprojectV1alpha1().Samples(namespace).Watch(options) }, }, &myprojectv1alpha1.Sample{}, resyncPeriod, indexers, ) }
go
func NewFilteredSampleInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.MyprojectV1alpha1().Samples(namespace).List(options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.MyprojectV1alpha1().Samples(namespace).Watch(options) }, }, &myprojectv1alpha1.Sample{}, resyncPeriod, indexers, ) }
[ "func", "NewFilteredSampleInformer", "(", "client", "versioned", ".", "Interface", ",", "namespace", "string", ",", "resyncPeriod", "time", ".", "Duration", ",", "indexers", "cache", ".", "Indexers", ",", "tweakListOptions", "internalinterfaces", ".", "TweakListOptionsFunc", ")", "cache", ".", "SharedIndexInformer", "{", "return", "cache", ".", "NewSharedIndexInformer", "(", "&", "cache", ".", "ListWatch", "{", "ListFunc", ":", "func", "(", "options", "v1", ".", "ListOptions", ")", "(", "runtime", ".", "Object", ",", "error", ")", "{", "if", "tweakListOptions", "!=", "nil", "{", "tweakListOptions", "(", "&", "options", ")", "\n", "}", "\n", "return", "client", ".", "MyprojectV1alpha1", "(", ")", ".", "Samples", "(", "namespace", ")", ".", "List", "(", "options", ")", "\n", "}", ",", "WatchFunc", ":", "func", "(", "options", "v1", ".", "ListOptions", ")", "(", "watch", ".", "Interface", ",", "error", ")", "{", "if", "tweakListOptions", "!=", "nil", "{", "tweakListOptions", "(", "&", "options", ")", "\n", "}", "\n", "return", "client", ".", "MyprojectV1alpha1", "(", ")", ".", "Samples", "(", "namespace", ")", ".", "Watch", "(", "options", ")", "\n", "}", ",", "}", ",", "&", "myprojectv1alpha1", ".", "Sample", "{", "}", ",", "resyncPeriod", ",", "indexers", ",", ")", "\n", "}" ]
// NewFilteredSampleInformer constructs a new informer for Sample type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server.
[ "NewFilteredSampleInformer", "constructs", "a", "new", "informer", "for", "Sample", "type", ".", "Always", "prefer", "using", "an", "informer", "factory", "to", "get", "a", "shared", "informer", "instead", "of", "getting", "an", "independent", "one", ".", "This", "reduces", "memory", "footprint", "and", "number", "of", "connections", "to", "the", "server", "." ]
e7b2e1264fff5f1dc9d506089af2399621b5a0c1
https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/sample.go#L57-L77
153,406
rook/operator-kit
sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/interface.go
Samples
func (v *version) Samples() SampleInformer { return &sampleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} }
go
func (v *version) Samples() SampleInformer { return &sampleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} }
[ "func", "(", "v", "*", "version", ")", "Samples", "(", ")", "SampleInformer", "{", "return", "&", "sampleInformer", "{", "factory", ":", "v", ".", "factory", ",", "namespace", ":", "v", ".", "namespace", ",", "tweakListOptions", ":", "v", ".", "tweakListOptions", "}", "\n", "}" ]
// Samples returns a SampleInformer.
[ "Samples", "returns", "a", "SampleInformer", "." ]
e7b2e1264fff5f1dc9d506089af2399621b5a0c1
https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/interface.go#L43-L45
153,407
mcuadros/go-syslog
internal/syslogparser/rfc5424/rfc5424.go
parseYear
func parseYear(buff []byte, cursor *int, l int) (int, error) { yearLen := 4 if *cursor+yearLen > l { return 0, syslogparser.ErrEOL } // XXX : we do not check for a valid year (ie. 1999, 2013 etc) // XXX : we only checks the format is correct sub := string(buff[*cursor : *cursor+yearLen]) *cursor += yearLen year, err := strconv.Atoi(sub) if err != nil { return 0, ErrYearInvalid } return year, nil }
go
func parseYear(buff []byte, cursor *int, l int) (int, error) { yearLen := 4 if *cursor+yearLen > l { return 0, syslogparser.ErrEOL } // XXX : we do not check for a valid year (ie. 1999, 2013 etc) // XXX : we only checks the format is correct sub := string(buff[*cursor : *cursor+yearLen]) *cursor += yearLen year, err := strconv.Atoi(sub) if err != nil { return 0, ErrYearInvalid } return year, nil }
[ "func", "parseYear", "(", "buff", "[", "]", "byte", ",", "cursor", "*", "int", ",", "l", "int", ")", "(", "int", ",", "error", ")", "{", "yearLen", ":=", "4", "\n\n", "if", "*", "cursor", "+", "yearLen", ">", "l", "{", "return", "0", ",", "syslogparser", ".", "ErrEOL", "\n", "}", "\n\n", "// XXX : we do not check for a valid year (ie. 1999, 2013 etc)", "// XXX : we only checks the format is correct", "sub", ":=", "string", "(", "buff", "[", "*", "cursor", ":", "*", "cursor", "+", "yearLen", "]", ")", "\n\n", "*", "cursor", "+=", "yearLen", "\n\n", "year", ",", "err", ":=", "strconv", ".", "Atoi", "(", "sub", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "ErrYearInvalid", "\n", "}", "\n\n", "return", "year", ",", "nil", "\n", "}" ]
// DATE-FULLYEAR = 4DIGIT
[ "DATE", "-", "FULLYEAR", "=", "4DIGIT" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L307-L326
153,408
mcuadros/go-syslog
internal/syslogparser/rfc5424/rfc5424.go
parseMonth
func parseMonth(buff []byte, cursor *int, l int) (int, error) { return syslogparser.Parse2Digits(buff, cursor, l, 1, 12, ErrMonthInvalid) }
go
func parseMonth(buff []byte, cursor *int, l int) (int, error) { return syslogparser.Parse2Digits(buff, cursor, l, 1, 12, ErrMonthInvalid) }
[ "func", "parseMonth", "(", "buff", "[", "]", "byte", ",", "cursor", "*", "int", ",", "l", "int", ")", "(", "int", ",", "error", ")", "{", "return", "syslogparser", ".", "Parse2Digits", "(", "buff", ",", "cursor", ",", "l", ",", "1", ",", "12", ",", "ErrMonthInvalid", ")", "\n", "}" ]
// DATE-MONTH = 2DIGIT ; 01-12
[ "DATE", "-", "MONTH", "=", "2DIGIT", ";", "01", "-", "12" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L329-L331
153,409
mcuadros/go-syslog
internal/syslogparser/rfc5424/rfc5424.go
parseFullTime
func parseFullTime(buff []byte, cursor *int, l int) (fullTime, error) { var loc = new(time.Location) var ft fullTime pt, err := parsePartialTime(buff, cursor, l) if err != nil { return ft, err } loc, err = parseTimeOffset(buff, cursor, l) if err != nil { return ft, err } ft = fullTime{ pt: pt, loc: loc, } return ft, nil }
go
func parseFullTime(buff []byte, cursor *int, l int) (fullTime, error) { var loc = new(time.Location) var ft fullTime pt, err := parsePartialTime(buff, cursor, l) if err != nil { return ft, err } loc, err = parseTimeOffset(buff, cursor, l) if err != nil { return ft, err } ft = fullTime{ pt: pt, loc: loc, } return ft, nil }
[ "func", "parseFullTime", "(", "buff", "[", "]", "byte", ",", "cursor", "*", "int", ",", "l", "int", ")", "(", "fullTime", ",", "error", ")", "{", "var", "loc", "=", "new", "(", "time", ".", "Location", ")", "\n", "var", "ft", "fullTime", "\n\n", "pt", ",", "err", ":=", "parsePartialTime", "(", "buff", ",", "cursor", ",", "l", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ft", ",", "err", "\n", "}", "\n\n", "loc", ",", "err", "=", "parseTimeOffset", "(", "buff", ",", "cursor", ",", "l", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ft", ",", "err", "\n", "}", "\n\n", "ft", "=", "fullTime", "{", "pt", ":", "pt", ",", "loc", ":", "loc", ",", "}", "\n\n", "return", "ft", ",", "nil", "\n", "}" ]
// FULL-TIME = PARTIAL-TIME TIME-OFFSET
[ "FULL", "-", "TIME", "=", "PARTIAL", "-", "TIME", "TIME", "-", "OFFSET" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L343-L363
153,410
mcuadros/go-syslog
internal/syslogparser/rfc5424/rfc5424.go
parseHour
func parseHour(buff []byte, cursor *int, l int) (int, error) { return syslogparser.Parse2Digits(buff, cursor, l, 0, 23, ErrHourInvalid) }
go
func parseHour(buff []byte, cursor *int, l int) (int, error) { return syslogparser.Parse2Digits(buff, cursor, l, 0, 23, ErrHourInvalid) }
[ "func", "parseHour", "(", "buff", "[", "]", "byte", ",", "cursor", "*", "int", ",", "l", "int", ")", "(", "int", ",", "error", ")", "{", "return", "syslogparser", ".", "Parse2Digits", "(", "buff", ",", "cursor", ",", "l", ",", "0", ",", "23", ",", "ErrHourInvalid", ")", "\n", "}" ]
// TIME-HOUR = 2DIGIT ; 00-23
[ "TIME", "-", "HOUR", "=", "2DIGIT", ";", "00", "-", "23" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L411-L413
153,411
mcuadros/go-syslog
internal/syslogparser/rfc5424/rfc5424.go
parseMinute
func parseMinute(buff []byte, cursor *int, l int) (int, error) { return syslogparser.Parse2Digits(buff, cursor, l, 0, 59, ErrMinuteInvalid) }
go
func parseMinute(buff []byte, cursor *int, l int) (int, error) { return syslogparser.Parse2Digits(buff, cursor, l, 0, 59, ErrMinuteInvalid) }
[ "func", "parseMinute", "(", "buff", "[", "]", "byte", ",", "cursor", "*", "int", ",", "l", "int", ")", "(", "int", ",", "error", ")", "{", "return", "syslogparser", ".", "Parse2Digits", "(", "buff", ",", "cursor", ",", "l", ",", "0", ",", "59", ",", "ErrMinuteInvalid", ")", "\n", "}" ]
// TIME-MINUTE = 2DIGIT ; 00-59
[ "TIME", "-", "MINUTE", "=", "2DIGIT", ";", "00", "-", "59" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L416-L418
153,412
mcuadros/go-syslog
internal/syslogparser/rfc5424/rfc5424.go
parseSecond
func parseSecond(buff []byte, cursor *int, l int) (int, error) { return syslogparser.Parse2Digits(buff, cursor, l, 0, 59, ErrSecondInvalid) }
go
func parseSecond(buff []byte, cursor *int, l int) (int, error) { return syslogparser.Parse2Digits(buff, cursor, l, 0, 59, ErrSecondInvalid) }
[ "func", "parseSecond", "(", "buff", "[", "]", "byte", ",", "cursor", "*", "int", ",", "l", "int", ")", "(", "int", ",", "error", ")", "{", "return", "syslogparser", ".", "Parse2Digits", "(", "buff", ",", "cursor", ",", "l", ",", "0", ",", "59", ",", "ErrSecondInvalid", ")", "\n", "}" ]
// TIME-SECOND = 2DIGIT ; 00-59
[ "TIME", "-", "SECOND", "=", "2DIGIT", ";", "00", "-", "59" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L421-L423
153,413
mcuadros/go-syslog
handler.go
NewChannelHandler
func NewChannelHandler(channel LogPartsChannel) *ChannelHandler { handler := new(ChannelHandler) handler.SetChannel(channel) return handler }
go
func NewChannelHandler(channel LogPartsChannel) *ChannelHandler { handler := new(ChannelHandler) handler.SetChannel(channel) return handler }
[ "func", "NewChannelHandler", "(", "channel", "LogPartsChannel", ")", "*", "ChannelHandler", "{", "handler", ":=", "new", "(", "ChannelHandler", ")", "\n", "handler", ".", "SetChannel", "(", "channel", ")", "\n\n", "return", "handler", "\n", "}" ]
//NewChannelHandler returns a new ChannelHandler
[ "NewChannelHandler", "returns", "a", "new", "ChannelHandler" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/handler.go#L20-L25
153,414
mcuadros/go-syslog
handler.go
Handle
func (h *ChannelHandler) Handle(logParts format.LogParts, messageLength int64, err error) { h.channel <- logParts }
go
func (h *ChannelHandler) Handle(logParts format.LogParts, messageLength int64, err error) { h.channel <- logParts }
[ "func", "(", "h", "*", "ChannelHandler", ")", "Handle", "(", "logParts", "format", ".", "LogParts", ",", "messageLength", "int64", ",", "err", "error", ")", "{", "h", ".", "channel", "<-", "logParts", "\n", "}" ]
//Syslog entry receiver
[ "Syslog", "entry", "receiver" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/handler.go#L33-L35
153,415
mcuadros/go-syslog
server.go
NewServer
func NewServer() *Server { return &Server{tlsPeerNameFunc: defaultTlsPeerName, datagramPool: sync.Pool{ New: func() interface{} { return make([]byte, 65536) }, }} }
go
func NewServer() *Server { return &Server{tlsPeerNameFunc: defaultTlsPeerName, datagramPool: sync.Pool{ New: func() interface{} { return make([]byte, 65536) }, }} }
[ "func", "NewServer", "(", ")", "*", "Server", "{", "return", "&", "Server", "{", "tlsPeerNameFunc", ":", "defaultTlsPeerName", ",", "datagramPool", ":", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "return", "make", "(", "[", "]", "byte", ",", "65536", ")", "\n", "}", ",", "}", "}", "\n", "}" ]
//NewServer returns a new Server
[ "NewServer", "returns", "a", "new", "Server" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L46-L52
153,416
mcuadros/go-syslog
server.go
defaultTlsPeerName
func defaultTlsPeerName(tlsConn *tls.Conn) (tlsPeer string, ok bool) { state := tlsConn.ConnectionState() if len(state.PeerCertificates) <= 0 { return "", false } cn := state.PeerCertificates[0].Subject.CommonName return cn, true }
go
func defaultTlsPeerName(tlsConn *tls.Conn) (tlsPeer string, ok bool) { state := tlsConn.ConnectionState() if len(state.PeerCertificates) <= 0 { return "", false } cn := state.PeerCertificates[0].Subject.CommonName return cn, true }
[ "func", "defaultTlsPeerName", "(", "tlsConn", "*", "tls", ".", "Conn", ")", "(", "tlsPeer", "string", ",", "ok", "bool", ")", "{", "state", ":=", "tlsConn", ".", "ConnectionState", "(", ")", "\n", "if", "len", "(", "state", ".", "PeerCertificates", ")", "<=", "0", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "cn", ":=", "state", ".", "PeerCertificates", "[", "0", "]", ".", "Subject", ".", "CommonName", "\n", "return", "cn", ",", "true", "\n", "}" ]
// Default TLS peer name function - returns the CN of the certificate
[ "Default", "TLS", "peer", "name", "function", "-", "returns", "the", "CN", "of", "the", "certificate" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L75-L82
153,417
mcuadros/go-syslog
server.go
ListenUDP
func (s *Server) ListenUDP(addr string) error { udpAddr, err := net.ResolveUDPAddr("udp", addr) if err != nil { return err } connection, err := net.ListenUDP("udp", udpAddr) if err != nil { return err } connection.SetReadBuffer(datagramReadBufferSize) s.connections = append(s.connections, connection) return nil }
go
func (s *Server) ListenUDP(addr string) error { udpAddr, err := net.ResolveUDPAddr("udp", addr) if err != nil { return err } connection, err := net.ListenUDP("udp", udpAddr) if err != nil { return err } connection.SetReadBuffer(datagramReadBufferSize) s.connections = append(s.connections, connection) return nil }
[ "func", "(", "s", "*", "Server", ")", "ListenUDP", "(", "addr", "string", ")", "error", "{", "udpAddr", ",", "err", ":=", "net", ".", "ResolveUDPAddr", "(", "\"", "\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "connection", ",", "err", ":=", "net", ".", "ListenUDP", "(", "\"", "\"", ",", "udpAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "connection", ".", "SetReadBuffer", "(", "datagramReadBufferSize", ")", "\n\n", "s", ".", "connections", "=", "append", "(", "s", ".", "connections", ",", "connection", ")", "\n", "return", "nil", "\n", "}" ]
//Configure the server for listen on an UDP addr
[ "Configure", "the", "server", "for", "listen", "on", "an", "UDP", "addr" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L85-L99
153,418
mcuadros/go-syslog
server.go
ListenUnixgram
func (s *Server) ListenUnixgram(addr string) error { unixAddr, err := net.ResolveUnixAddr("unixgram", addr) if err != nil { return err } connection, err := net.ListenUnixgram("unixgram", unixAddr) if err != nil { return err } connection.SetReadBuffer(datagramReadBufferSize) s.connections = append(s.connections, connection) return nil }
go
func (s *Server) ListenUnixgram(addr string) error { unixAddr, err := net.ResolveUnixAddr("unixgram", addr) if err != nil { return err } connection, err := net.ListenUnixgram("unixgram", unixAddr) if err != nil { return err } connection.SetReadBuffer(datagramReadBufferSize) s.connections = append(s.connections, connection) return nil }
[ "func", "(", "s", "*", "Server", ")", "ListenUnixgram", "(", "addr", "string", ")", "error", "{", "unixAddr", ",", "err", ":=", "net", ".", "ResolveUnixAddr", "(", "\"", "\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "connection", ",", "err", ":=", "net", ".", "ListenUnixgram", "(", "\"", "\"", ",", "unixAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "connection", ".", "SetReadBuffer", "(", "datagramReadBufferSize", ")", "\n\n", "s", ".", "connections", "=", "append", "(", "s", ".", "connections", ",", "connection", ")", "\n", "return", "nil", "\n", "}" ]
//Configure the server for listen on an unix socket
[ "Configure", "the", "server", "for", "listen", "on", "an", "unix", "socket" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L102-L116
153,419
mcuadros/go-syslog
server.go
ListenTCP
func (s *Server) ListenTCP(addr string) error { tcpAddr, err := net.ResolveTCPAddr("tcp", addr) if err != nil { return err } listener, err := net.ListenTCP("tcp", tcpAddr) if err != nil { return err } s.doneTcp = make(chan bool) s.listeners = append(s.listeners, listener) return nil }
go
func (s *Server) ListenTCP(addr string) error { tcpAddr, err := net.ResolveTCPAddr("tcp", addr) if err != nil { return err } listener, err := net.ListenTCP("tcp", tcpAddr) if err != nil { return err } s.doneTcp = make(chan bool) s.listeners = append(s.listeners, listener) return nil }
[ "func", "(", "s", "*", "Server", ")", "ListenTCP", "(", "addr", "string", ")", "error", "{", "tcpAddr", ",", "err", ":=", "net", ".", "ResolveTCPAddr", "(", "\"", "\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "listener", ",", "err", ":=", "net", ".", "ListenTCP", "(", "\"", "\"", ",", "tcpAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "doneTcp", "=", "make", "(", "chan", "bool", ")", "\n", "s", ".", "listeners", "=", "append", "(", "s", ".", "listeners", ",", "listener", ")", "\n", "return", "nil", "\n", "}" ]
//Configure the server for listen on a TCP addr
[ "Configure", "the", "server", "for", "listen", "on", "a", "TCP", "addr" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L119-L133
153,420
mcuadros/go-syslog
server.go
ListenTCPTLS
func (s *Server) ListenTCPTLS(addr string, config *tls.Config) error { listener, err := tls.Listen("tcp", addr, config) if err != nil { return err } s.doneTcp = make(chan bool) s.listeners = append(s.listeners, listener) return nil }
go
func (s *Server) ListenTCPTLS(addr string, config *tls.Config) error { listener, err := tls.Listen("tcp", addr, config) if err != nil { return err } s.doneTcp = make(chan bool) s.listeners = append(s.listeners, listener) return nil }
[ "func", "(", "s", "*", "Server", ")", "ListenTCPTLS", "(", "addr", "string", ",", "config", "*", "tls", ".", "Config", ")", "error", "{", "listener", ",", "err", ":=", "tls", ".", "Listen", "(", "\"", "\"", ",", "addr", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "s", ".", "doneTcp", "=", "make", "(", "chan", "bool", ")", "\n", "s", ".", "listeners", "=", "append", "(", "s", ".", "listeners", ",", "listener", ")", "\n", "return", "nil", "\n", "}" ]
//Configure the server for listen on a TCP addr for TLS
[ "Configure", "the", "server", "for", "listen", "on", "a", "TCP", "addr", "for", "TLS" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L136-L145
153,421
mcuadros/go-syslog
server.go
Boot
func (s *Server) Boot() error { if s.format == nil { return errors.New("please set a valid format") } if s.handler == nil { return errors.New("please set a valid handler") } for _, listener := range s.listeners { s.goAcceptConnection(listener) } if len(s.connections) > 0 { s.goParseDatagrams() } for _, connection := range s.connections { s.goReceiveDatagrams(connection) } return nil }
go
func (s *Server) Boot() error { if s.format == nil { return errors.New("please set a valid format") } if s.handler == nil { return errors.New("please set a valid handler") } for _, listener := range s.listeners { s.goAcceptConnection(listener) } if len(s.connections) > 0 { s.goParseDatagrams() } for _, connection := range s.connections { s.goReceiveDatagrams(connection) } return nil }
[ "func", "(", "s", "*", "Server", ")", "Boot", "(", ")", "error", "{", "if", "s", ".", "format", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "s", ".", "handler", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "_", ",", "listener", ":=", "range", "s", ".", "listeners", "{", "s", ".", "goAcceptConnection", "(", "listener", ")", "\n", "}", "\n\n", "if", "len", "(", "s", ".", "connections", ")", ">", "0", "{", "s", ".", "goParseDatagrams", "(", ")", "\n", "}", "\n\n", "for", "_", ",", "connection", ":=", "range", "s", ".", "connections", "{", "s", ".", "goReceiveDatagrams", "(", "connection", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
//Starts the server, all the go routines goes to live
[ "Starts", "the", "server", "all", "the", "go", "routines", "goes", "to", "live" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L148-L170
153,422
mcuadros/go-syslog
server.go
Kill
func (s *Server) Kill() error { for _, connection := range s.connections { err := connection.Close() if err != nil { return err } } for _, listener := range s.listeners { err := listener.Close() if err != nil { return err } } // Only need to close channel once to broadcast to all waiting if s.doneTcp != nil { close(s.doneTcp) } if s.datagramChannel != nil { close(s.datagramChannel) } return nil }
go
func (s *Server) Kill() error { for _, connection := range s.connections { err := connection.Close() if err != nil { return err } } for _, listener := range s.listeners { err := listener.Close() if err != nil { return err } } // Only need to close channel once to broadcast to all waiting if s.doneTcp != nil { close(s.doneTcp) } if s.datagramChannel != nil { close(s.datagramChannel) } return nil }
[ "func", "(", "s", "*", "Server", ")", "Kill", "(", ")", "error", "{", "for", "_", ",", "connection", ":=", "range", "s", ".", "connections", "{", "err", ":=", "connection", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "listener", ":=", "range", "s", ".", "listeners", "{", "err", ":=", "listener", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "// Only need to close channel once to broadcast to all waiting", "if", "s", ".", "doneTcp", "!=", "nil", "{", "close", "(", "s", ".", "doneTcp", ")", "\n", "}", "\n", "if", "s", ".", "datagramChannel", "!=", "nil", "{", "close", "(", "s", ".", "datagramChannel", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
//Kill the server
[ "Kill", "the", "server" ]
a127d826d6c27489d377b3c080bd256d8f8093a6
https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L279-L301
153,423
cavaliercoder/grab
client.go
NewClient
func NewClient() *Client { return &Client{ UserAgent: "grab", HTTPClient: &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, }, } }
go
func NewClient() *Client { return &Client{ UserAgent: "grab", HTTPClient: &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, }, } }
[ "func", "NewClient", "(", ")", "*", "Client", "{", "return", "&", "Client", "{", "UserAgent", ":", "\"", "\"", ",", "HTTPClient", ":", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "}", ",", "}", ",", "}", "\n", "}" ]
// NewClient returns a new file download Client, using default configuration.
[ "NewClient", "returns", "a", "new", "file", "download", "Client", "using", "default", "configuration", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L37-L46
153,424
cavaliercoder/grab
client.go
DoChannel
func (c *Client) DoChannel(reqch <-chan *Request, respch chan<- *Response) { // TODO: enable cancelling of batch jobs for req := range reqch { resp := c.Do(req) respch <- resp <-resp.Done } }
go
func (c *Client) DoChannel(reqch <-chan *Request, respch chan<- *Response) { // TODO: enable cancelling of batch jobs for req := range reqch { resp := c.Do(req) respch <- resp <-resp.Done } }
[ "func", "(", "c", "*", "Client", ")", "DoChannel", "(", "reqch", "<-", "chan", "*", "Request", ",", "respch", "chan", "<-", "*", "Response", ")", "{", "// TODO: enable cancelling of batch jobs", "for", "req", ":=", "range", "reqch", "{", "resp", ":=", "c", ".", "Do", "(", "req", ")", "\n", "respch", "<-", "resp", "\n", "<-", "resp", ".", "Done", "\n", "}", "\n", "}" ]
// DoChannel executes all requests sent through the given Request channel, one // at a time, until it is closed by another goroutine. The caller is blocked // until the Request channel is closed and all transfers have completed. All // responses are sent through the given Response channel as soon as they are // received from the remote servers and can be used to track the progress of // each download. // // Slow Response receivers will cause a worker to block and therefore delay the // start of the transfer for an already initiated connection - potentially // causing a server timeout. It is the caller's responsibility to ensure a // sufficient buffer size is used for the Response channel to prevent this. // // If an error occurs during any of the file transfers it will be accessible via // the associated Response.Err function.
[ "DoChannel", "executes", "all", "requests", "sent", "through", "the", "given", "Request", "channel", "one", "at", "a", "time", "until", "it", "is", "closed", "by", "another", "goroutine", ".", "The", "caller", "is", "blocked", "until", "the", "Request", "channel", "is", "closed", "and", "all", "transfers", "have", "completed", ".", "All", "responses", "are", "sent", "through", "the", "given", "Response", "channel", "as", "soon", "as", "they", "are", "received", "from", "the", "remote", "servers", "and", "can", "be", "used", "to", "track", "the", "progress", "of", "each", "download", ".", "Slow", "Response", "receivers", "will", "cause", "a", "worker", "to", "block", "and", "therefore", "delay", "the", "start", "of", "the", "transfer", "for", "an", "already", "initiated", "connection", "-", "potentially", "causing", "a", "server", "timeout", ".", "It", "is", "the", "caller", "s", "responsibility", "to", "ensure", "a", "sufficient", "buffer", "size", "is", "used", "for", "the", "Response", "channel", "to", "prevent", "this", ".", "If", "an", "error", "occurs", "during", "any", "of", "the", "file", "transfers", "it", "will", "be", "accessible", "via", "the", "associated", "Response", ".", "Err", "function", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L106-L113
153,425
cavaliercoder/grab
client.go
DoBatch
func (c *Client) DoBatch(workers int, requests ...*Request) <-chan *Response { if workers < 1 { workers = len(requests) } reqch := make(chan *Request, len(requests)) respch := make(chan *Response, len(requests)) wg := sync.WaitGroup{} for i := 0; i < workers; i++ { wg.Add(1) go func() { c.DoChannel(reqch, respch) wg.Done() }() } // queue requests go func() { for _, req := range requests { reqch <- req } close(reqch) wg.Wait() close(respch) }() return respch }
go
func (c *Client) DoBatch(workers int, requests ...*Request) <-chan *Response { if workers < 1 { workers = len(requests) } reqch := make(chan *Request, len(requests)) respch := make(chan *Response, len(requests)) wg := sync.WaitGroup{} for i := 0; i < workers; i++ { wg.Add(1) go func() { c.DoChannel(reqch, respch) wg.Done() }() } // queue requests go func() { for _, req := range requests { reqch <- req } close(reqch) wg.Wait() close(respch) }() return respch }
[ "func", "(", "c", "*", "Client", ")", "DoBatch", "(", "workers", "int", ",", "requests", "...", "*", "Request", ")", "<-", "chan", "*", "Response", "{", "if", "workers", "<", "1", "{", "workers", "=", "len", "(", "requests", ")", "\n", "}", "\n", "reqch", ":=", "make", "(", "chan", "*", "Request", ",", "len", "(", "requests", ")", ")", "\n", "respch", ":=", "make", "(", "chan", "*", "Response", ",", "len", "(", "requests", ")", ")", "\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "workers", ";", "i", "++", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "c", ".", "DoChannel", "(", "reqch", ",", "respch", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n", "}", "\n\n", "// queue requests", "go", "func", "(", ")", "{", "for", "_", ",", "req", ":=", "range", "requests", "{", "reqch", "<-", "req", "\n", "}", "\n", "close", "(", "reqch", ")", "\n", "wg", ".", "Wait", "(", ")", "\n", "close", "(", "respch", ")", "\n", "}", "(", ")", "\n", "return", "respch", "\n", "}" ]
// DoBatch executes all the given requests using the given number of concurrent // workers. Control is passed back to the caller as soon as the workers are // initiated. // // If the requested number of workers is less than one, a worker will be created // for every request. I.e. all requests will be executed concurrently. // // If an error occurs during any of the file transfers it will be accessible via // call to the associated Response.Err. // // The returned Response channel is closed only after all of the given Requests // have completed, successfully or otherwise.
[ "DoBatch", "executes", "all", "the", "given", "requests", "using", "the", "given", "number", "of", "concurrent", "workers", ".", "Control", "is", "passed", "back", "to", "the", "caller", "as", "soon", "as", "the", "workers", "are", "initiated", ".", "If", "the", "requested", "number", "of", "workers", "is", "less", "than", "one", "a", "worker", "will", "be", "created", "for", "every", "request", ".", "I", ".", "e", ".", "all", "requests", "will", "be", "executed", "concurrently", ".", "If", "an", "error", "occurs", "during", "any", "of", "the", "file", "transfers", "it", "will", "be", "accessible", "via", "call", "to", "the", "associated", "Response", ".", "Err", ".", "The", "returned", "Response", "channel", "is", "closed", "only", "after", "all", "of", "the", "given", "Requests", "have", "completed", "successfully", "or", "otherwise", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L127-L152
153,426
cavaliercoder/grab
client.go
run
func (c *Client) run(resp *Response, f stateFunc) { for { select { case <-resp.ctx.Done(): if resp.IsComplete() { return } resp.err = resp.ctx.Err() f = c.closeResponse default: // keep working } if f = f(resp); f == nil { return } } }
go
func (c *Client) run(resp *Response, f stateFunc) { for { select { case <-resp.ctx.Done(): if resp.IsComplete() { return } resp.err = resp.ctx.Err() f = c.closeResponse default: // keep working } if f = f(resp); f == nil { return } } }
[ "func", "(", "c", "*", "Client", ")", "run", "(", "resp", "*", "Response", ",", "f", "stateFunc", ")", "{", "for", "{", "select", "{", "case", "<-", "resp", ".", "ctx", ".", "Done", "(", ")", ":", "if", "resp", ".", "IsComplete", "(", ")", "{", "return", "\n", "}", "\n", "resp", ".", "err", "=", "resp", ".", "ctx", ".", "Err", "(", ")", "\n", "f", "=", "c", ".", "closeResponse", "\n\n", "default", ":", "// keep working", "}", "\n", "if", "f", "=", "f", "(", "resp", ")", ";", "f", "==", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// run calls the given stateFunc function and all subsequent returned stateFuncs // until a stateFunc returns nil or the Response.ctx is canceled. Each stateFunc // should mutate the state of the given Response until it has completed // downloading or failed.
[ "run", "calls", "the", "given", "stateFunc", "function", "and", "all", "subsequent", "returned", "stateFuncs", "until", "a", "stateFunc", "returns", "nil", "or", "the", "Response", ".", "ctx", "is", "canceled", ".", "Each", "stateFunc", "should", "mutate", "the", "state", "of", "the", "given", "Response", "until", "it", "has", "completed", "downloading", "or", "failed", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L162-L179
153,427
cavaliercoder/grab
client.go
statFileInfo
func (c *Client) statFileInfo(resp *Response) stateFunc { if resp.Filename == "" { return c.headRequest } fi, err := os.Stat(resp.Filename) if err != nil { if os.IsNotExist(err) { return c.headRequest } resp.err = err return c.closeResponse } if fi.IsDir() { resp.Filename = "" return c.headRequest } resp.fi = fi return c.validateLocal }
go
func (c *Client) statFileInfo(resp *Response) stateFunc { if resp.Filename == "" { return c.headRequest } fi, err := os.Stat(resp.Filename) if err != nil { if os.IsNotExist(err) { return c.headRequest } resp.err = err return c.closeResponse } if fi.IsDir() { resp.Filename = "" return c.headRequest } resp.fi = fi return c.validateLocal }
[ "func", "(", "c", "*", "Client", ")", "statFileInfo", "(", "resp", "*", "Response", ")", "stateFunc", "{", "if", "resp", ".", "Filename", "==", "\"", "\"", "{", "return", "c", ".", "headRequest", "\n", "}", "\n", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "resp", ".", "Filename", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "c", ".", "headRequest", "\n", "}", "\n", "resp", ".", "err", "=", "err", "\n", "return", "c", ".", "closeResponse", "\n", "}", "\n", "if", "fi", ".", "IsDir", "(", ")", "{", "resp", ".", "Filename", "=", "\"", "\"", "\n", "return", "c", ".", "headRequest", "\n", "}", "\n", "resp", ".", "fi", "=", "fi", "\n", "return", "c", ".", "validateLocal", "\n", "}" ]
// statFileInfo retrieves FileInfo for any local file matching // Response.Filename. // // If the file does not exist, is a directory, or its name is unknown the next // stateFunc is headRequest. // // If the file exists, Response.fi is set and the next stateFunc is // validateLocal. // // If an error occurs, the next stateFunc is closeResponse.
[ "statFileInfo", "retrieves", "FileInfo", "for", "any", "local", "file", "matching", "Response", ".", "Filename", ".", "If", "the", "file", "does", "not", "exist", "is", "a", "directory", "or", "its", "name", "is", "unknown", "the", "next", "stateFunc", "is", "headRequest", ".", "If", "the", "file", "exists", "Response", ".", "fi", "is", "set", "and", "the", "next", "stateFunc", "is", "validateLocal", ".", "If", "an", "error", "occurs", "the", "next", "stateFunc", "is", "closeResponse", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L191-L209
153,428
cavaliercoder/grab
client.go
validateLocal
func (c *Client) validateLocal(resp *Response) stateFunc { if resp.Request.SkipExisting { resp.err = ErrFileExists return c.closeResponse } // determine expected file size size := resp.Request.Size if size == 0 && resp.HTTPResponse != nil { size = resp.HTTPResponse.ContentLength } if size == 0 { return c.headRequest } if size == resp.fi.Size() { resp.DidResume = true resp.bytesResumed = resp.fi.Size() return c.checksumFile } if resp.Request.NoResume { return c.getRequest } if size < resp.fi.Size() { resp.err = ErrBadLength return c.closeResponse } if resp.CanResume { resp.Request.HTTPRequest.Header.Set( "Range", fmt.Sprintf("bytes=%d-", resp.fi.Size())) resp.DidResume = true resp.bytesResumed = resp.fi.Size() return c.getRequest } return c.headRequest }
go
func (c *Client) validateLocal(resp *Response) stateFunc { if resp.Request.SkipExisting { resp.err = ErrFileExists return c.closeResponse } // determine expected file size size := resp.Request.Size if size == 0 && resp.HTTPResponse != nil { size = resp.HTTPResponse.ContentLength } if size == 0 { return c.headRequest } if size == resp.fi.Size() { resp.DidResume = true resp.bytesResumed = resp.fi.Size() return c.checksumFile } if resp.Request.NoResume { return c.getRequest } if size < resp.fi.Size() { resp.err = ErrBadLength return c.closeResponse } if resp.CanResume { resp.Request.HTTPRequest.Header.Set( "Range", fmt.Sprintf("bytes=%d-", resp.fi.Size())) resp.DidResume = true resp.bytesResumed = resp.fi.Size() return c.getRequest } return c.headRequest }
[ "func", "(", "c", "*", "Client", ")", "validateLocal", "(", "resp", "*", "Response", ")", "stateFunc", "{", "if", "resp", ".", "Request", ".", "SkipExisting", "{", "resp", ".", "err", "=", "ErrFileExists", "\n", "return", "c", ".", "closeResponse", "\n", "}", "\n\n", "// determine expected file size", "size", ":=", "resp", ".", "Request", ".", "Size", "\n", "if", "size", "==", "0", "&&", "resp", ".", "HTTPResponse", "!=", "nil", "{", "size", "=", "resp", ".", "HTTPResponse", ".", "ContentLength", "\n", "}", "\n", "if", "size", "==", "0", "{", "return", "c", ".", "headRequest", "\n", "}", "\n\n", "if", "size", "==", "resp", ".", "fi", ".", "Size", "(", ")", "{", "resp", ".", "DidResume", "=", "true", "\n", "resp", ".", "bytesResumed", "=", "resp", ".", "fi", ".", "Size", "(", ")", "\n", "return", "c", ".", "checksumFile", "\n", "}", "\n\n", "if", "resp", ".", "Request", ".", "NoResume", "{", "return", "c", ".", "getRequest", "\n", "}", "\n\n", "if", "size", "<", "resp", ".", "fi", ".", "Size", "(", ")", "{", "resp", ".", "err", "=", "ErrBadLength", "\n", "return", "c", ".", "closeResponse", "\n", "}", "\n\n", "if", "resp", ".", "CanResume", "{", "resp", ".", "Request", ".", "HTTPRequest", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "resp", ".", "fi", ".", "Size", "(", ")", ")", ")", "\n", "resp", ".", "DidResume", "=", "true", "\n", "resp", ".", "bytesResumed", "=", "resp", ".", "fi", ".", "Size", "(", ")", "\n", "return", "c", ".", "getRequest", "\n", "}", "\n", "return", "c", ".", "headRequest", "\n", "}" ]
// validateLocal compares a local copy of the downloaded file to the remote // file. // // An error is returned if the local file is larger than the remote file, or // Request.SkipExisting is true. // // If the existing file matches the length of the remote file, the next // stateFunc is checksumFile. // // If the local file is smaller than the remote file and the remote server is // known to support ranged requests, the next stateFunc is getRequest.
[ "validateLocal", "compares", "a", "local", "copy", "of", "the", "downloaded", "file", "to", "the", "remote", "file", ".", "An", "error", "is", "returned", "if", "the", "local", "file", "is", "larger", "than", "the", "remote", "file", "or", "Request", ".", "SkipExisting", "is", "true", ".", "If", "the", "existing", "file", "matches", "the", "length", "of", "the", "remote", "file", "the", "next", "stateFunc", "is", "checksumFile", ".", "If", "the", "local", "file", "is", "smaller", "than", "the", "remote", "file", "and", "the", "remote", "server", "is", "known", "to", "support", "ranged", "requests", "the", "next", "stateFunc", "is", "getRequest", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L222-L261
153,429
cavaliercoder/grab
client.go
doHTTPRequest
func (c *Client) doHTTPRequest(req *http.Request) (*http.Response, error) { if c.UserAgent != "" && req.Header.Get("User-Agent") == "" { req.Header.Set("User-Agent", c.UserAgent) } return c.HTTPClient.Do(req) }
go
func (c *Client) doHTTPRequest(req *http.Request) (*http.Response, error) { if c.UserAgent != "" && req.Header.Get("User-Agent") == "" { req.Header.Set("User-Agent", c.UserAgent) } return c.HTTPClient.Do(req) }
[ "func", "(", "c", "*", "Client", ")", "doHTTPRequest", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "if", "c", ".", "UserAgent", "!=", "\"", "\"", "&&", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "==", "\"", "\"", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "c", ".", "UserAgent", ")", "\n", "}", "\n", "return", "c", ".", "HTTPClient", ".", "Do", "(", "req", ")", "\n", "}" ]
// doHTTPRequest sends a HTTP Request and returns the response
[ "doHTTPRequest", "sends", "a", "HTTP", "Request", "and", "returns", "the", "response" ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L293-L298
153,430
cavaliercoder/grab
client.go
openWriter
func (c *Client) openWriter(resp *Response) stateFunc { if !resp.Request.NoCreateDirectories { resp.err = mkdirp(resp.Filename) if resp.err != nil { return c.closeResponse } } // compute write flags flag := os.O_CREATE | os.O_WRONLY if resp.fi != nil { if resp.DidResume { flag = os.O_APPEND | os.O_WRONLY } else { flag = os.O_TRUNC | os.O_WRONLY } } // open file f, err := os.OpenFile(resp.Filename, flag, 0644) if err != nil { resp.err = err return c.closeResponse } resp.writer = f // seek to start or end whence := os.SEEK_SET if resp.bytesResumed > 0 { whence = os.SEEK_END } _, resp.err = f.Seek(0, whence) if resp.err != nil { return c.closeResponse } // init transfer if resp.bufferSize < 1 { resp.bufferSize = 32 * 1024 } b := make([]byte, resp.bufferSize) resp.transfer = newTransfer( resp.Request.Context(), resp.Request.RateLimiter, resp.writer, resp.HTTPResponse.Body, b) // next step is copyFile, but this will be called later in another goroutine return nil }
go
func (c *Client) openWriter(resp *Response) stateFunc { if !resp.Request.NoCreateDirectories { resp.err = mkdirp(resp.Filename) if resp.err != nil { return c.closeResponse } } // compute write flags flag := os.O_CREATE | os.O_WRONLY if resp.fi != nil { if resp.DidResume { flag = os.O_APPEND | os.O_WRONLY } else { flag = os.O_TRUNC | os.O_WRONLY } } // open file f, err := os.OpenFile(resp.Filename, flag, 0644) if err != nil { resp.err = err return c.closeResponse } resp.writer = f // seek to start or end whence := os.SEEK_SET if resp.bytesResumed > 0 { whence = os.SEEK_END } _, resp.err = f.Seek(0, whence) if resp.err != nil { return c.closeResponse } // init transfer if resp.bufferSize < 1 { resp.bufferSize = 32 * 1024 } b := make([]byte, resp.bufferSize) resp.transfer = newTransfer( resp.Request.Context(), resp.Request.RateLimiter, resp.writer, resp.HTTPResponse.Body, b) // next step is copyFile, but this will be called later in another goroutine return nil }
[ "func", "(", "c", "*", "Client", ")", "openWriter", "(", "resp", "*", "Response", ")", "stateFunc", "{", "if", "!", "resp", ".", "Request", ".", "NoCreateDirectories", "{", "resp", ".", "err", "=", "mkdirp", "(", "resp", ".", "Filename", ")", "\n", "if", "resp", ".", "err", "!=", "nil", "{", "return", "c", ".", "closeResponse", "\n", "}", "\n", "}", "\n\n", "// compute write flags", "flag", ":=", "os", ".", "O_CREATE", "|", "os", ".", "O_WRONLY", "\n", "if", "resp", ".", "fi", "!=", "nil", "{", "if", "resp", ".", "DidResume", "{", "flag", "=", "os", ".", "O_APPEND", "|", "os", ".", "O_WRONLY", "\n", "}", "else", "{", "flag", "=", "os", ".", "O_TRUNC", "|", "os", ".", "O_WRONLY", "\n", "}", "\n", "}", "\n\n", "// open file", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "resp", ".", "Filename", ",", "flag", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "resp", ".", "err", "=", "err", "\n", "return", "c", ".", "closeResponse", "\n", "}", "\n", "resp", ".", "writer", "=", "f", "\n\n", "// seek to start or end", "whence", ":=", "os", ".", "SEEK_SET", "\n", "if", "resp", ".", "bytesResumed", ">", "0", "{", "whence", "=", "os", ".", "SEEK_END", "\n", "}", "\n", "_", ",", "resp", ".", "err", "=", "f", ".", "Seek", "(", "0", ",", "whence", ")", "\n", "if", "resp", ".", "err", "!=", "nil", "{", "return", "c", ".", "closeResponse", "\n", "}", "\n\n", "// init transfer", "if", "resp", ".", "bufferSize", "<", "1", "{", "resp", ".", "bufferSize", "=", "32", "*", "1024", "\n", "}", "\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "resp", ".", "bufferSize", ")", "\n", "resp", ".", "transfer", "=", "newTransfer", "(", "resp", ".", "Request", ".", "Context", "(", ")", ",", "resp", ".", "Request", ".", "RateLimiter", ",", "resp", ".", "writer", ",", "resp", ".", "HTTPResponse", ".", "Body", ",", "b", ")", "\n\n", "// next step is copyFile, but this will be called later in another goroutine", "return", "nil", "\n", "}" ]
// openWriter opens the destination file for writing and seeks to the location // from whence the file transfer will resume. // // Requires that Response.Filename and resp.DidResume are already be set.
[ "openWriter", "opens", "the", "destination", "file", "for", "writing", "and", "seeks", "to", "the", "location", "from", "whence", "the", "file", "transfer", "will", "resume", ".", "Requires", "that", "Response", ".", "Filename", "and", "resp", ".", "DidResume", "are", "already", "be", "set", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L387-L437
153,431
cavaliercoder/grab
client.go
closeResponse
func (c *Client) closeResponse(resp *Response) stateFunc { if resp.IsComplete() { panic("response already closed") } resp.fi = nil closeWriter(resp) resp.closeResponseBody() resp.End = time.Now() close(resp.Done) if resp.cancel != nil { resp.cancel() } return nil }
go
func (c *Client) closeResponse(resp *Response) stateFunc { if resp.IsComplete() { panic("response already closed") } resp.fi = nil closeWriter(resp) resp.closeResponseBody() resp.End = time.Now() close(resp.Done) if resp.cancel != nil { resp.cancel() } return nil }
[ "func", "(", "c", "*", "Client", ")", "closeResponse", "(", "resp", "*", "Response", ")", "stateFunc", "{", "if", "resp", ".", "IsComplete", "(", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "resp", ".", "fi", "=", "nil", "\n", "closeWriter", "(", "resp", ")", "\n", "resp", ".", "closeResponseBody", "(", ")", "\n\n", "resp", ".", "End", "=", "time", ".", "Now", "(", ")", "\n", "close", "(", "resp", ".", "Done", ")", "\n", "if", "resp", ".", "cancel", "!=", "nil", "{", "resp", ".", "cancel", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// close finalizes the Response
[ "close", "finalizes", "the", "Response" ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L489-L505
153,432
cavaliercoder/grab
response.go
Progress
func (c *Response) Progress() float64 { if c.Size == 0 { return 0 } return float64(c.BytesComplete()) / float64(c.Size) }
go
func (c *Response) Progress() float64 { if c.Size == 0 { return 0 } return float64(c.BytesComplete()) / float64(c.Size) }
[ "func", "(", "c", "*", "Response", ")", "Progress", "(", ")", "float64", "{", "if", "c", ".", "Size", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "float64", "(", "c", ".", "BytesComplete", "(", ")", ")", "/", "float64", "(", "c", ".", "Size", ")", "\n", "}" ]
// Progress returns the ratio of total bytes that have been downloaded. Multiply // the returned value by 100 to return the percentage completed.
[ "Progress", "returns", "the", "ratio", "of", "total", "bytes", "that", "have", "been", "downloaded", ".", "Multiply", "the", "returned", "value", "by", "100", "to", "return", "the", "percentage", "completed", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/response.go#L141-L146
153,433
cavaliercoder/grab
response.go
Duration
func (c *Response) Duration() time.Duration { if c.IsComplete() { return c.End.Sub(c.Start) } return time.Now().Sub(c.Start) }
go
func (c *Response) Duration() time.Duration { if c.IsComplete() { return c.End.Sub(c.Start) } return time.Now().Sub(c.Start) }
[ "func", "(", "c", "*", "Response", ")", "Duration", "(", ")", "time", ".", "Duration", "{", "if", "c", ".", "IsComplete", "(", ")", "{", "return", "c", ".", "End", ".", "Sub", "(", "c", ".", "Start", ")", "\n", "}", "\n\n", "return", "time", ".", "Now", "(", ")", ".", "Sub", "(", "c", ".", "Start", ")", "\n", "}" ]
// Duration returns the duration of a file transfer. If the transfer is in // process, the duration will be between now and the start of the transfer. If // the transfer is complete, the duration will be between the start and end of // the completed transfer process.
[ "Duration", "returns", "the", "duration", "of", "a", "file", "transfer", ".", "If", "the", "transfer", "is", "in", "process", "the", "duration", "will", "be", "between", "now", "and", "the", "start", "of", "the", "transfer", ".", "If", "the", "transfer", "is", "complete", "the", "duration", "will", "be", "between", "the", "start", "and", "end", "of", "the", "completed", "transfer", "process", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/response.go#L152-L158
153,434
cavaliercoder/grab
response.go
ETA
func (c *Response) ETA() time.Time { if c.IsComplete() { return c.End } bt := c.BytesComplete() bps := c.transfer.BPS() if bps == 0 { return time.Time{} } secs := float64(c.Size-bt) / bps return time.Now().Add(time.Duration(secs) * time.Second) }
go
func (c *Response) ETA() time.Time { if c.IsComplete() { return c.End } bt := c.BytesComplete() bps := c.transfer.BPS() if bps == 0 { return time.Time{} } secs := float64(c.Size-bt) / bps return time.Now().Add(time.Duration(secs) * time.Second) }
[ "func", "(", "c", "*", "Response", ")", "ETA", "(", ")", "time", ".", "Time", "{", "if", "c", ".", "IsComplete", "(", ")", "{", "return", "c", ".", "End", "\n", "}", "\n", "bt", ":=", "c", ".", "BytesComplete", "(", ")", "\n", "bps", ":=", "c", ".", "transfer", ".", "BPS", "(", ")", "\n", "if", "bps", "==", "0", "{", "return", "time", ".", "Time", "{", "}", "\n", "}", "\n", "secs", ":=", "float64", "(", "c", ".", "Size", "-", "bt", ")", "/", "bps", "\n", "return", "time", ".", "Now", "(", ")", ".", "Add", "(", "time", ".", "Duration", "(", "secs", ")", "*", "time", ".", "Second", ")", "\n", "}" ]
// ETA returns the estimated time at which the the download will complete, given // the current BytesPerSecond. If the transfer has already completed, the actual // end time will be returned.
[ "ETA", "returns", "the", "estimated", "time", "at", "which", "the", "the", "download", "will", "complete", "given", "the", "current", "BytesPerSecond", ".", "If", "the", "transfer", "has", "already", "completed", "the", "actual", "end", "time", "will", "be", "returned", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/response.go#L163-L174
153,435
cavaliercoder/grab
bps/bps.go
Watch
func Watch(ctx context.Context, g Gauge, f SampleFunc, interval time.Duration) { g.Sample(time.Now(), f()) t := time.NewTicker(interval) defer t.Stop() for { select { case <-ctx.Done(): return case now := <-t.C: g.Sample(now, f()) } } }
go
func Watch(ctx context.Context, g Gauge, f SampleFunc, interval time.Duration) { g.Sample(time.Now(), f()) t := time.NewTicker(interval) defer t.Stop() for { select { case <-ctx.Done(): return case now := <-t.C: g.Sample(now, f()) } } }
[ "func", "Watch", "(", "ctx", "context", ".", "Context", ",", "g", "Gauge", ",", "f", "SampleFunc", ",", "interval", "time", ".", "Duration", ")", "{", "g", ".", "Sample", "(", "time", ".", "Now", "(", ")", ",", "f", "(", ")", ")", "\n", "t", ":=", "time", ".", "NewTicker", "(", "interval", ")", "\n", "defer", "t", ".", "Stop", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "case", "now", ":=", "<-", "t", ".", "C", ":", "g", ".", "Sample", "(", "now", ",", "f", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Watch will periodically call the given SampleFunc to sample the progress of // a monitored stream and update the given gauge. SampleFunc should return the // total number of bytes transferred by the stream since it started. // // Watch is a blocking call and should typically be called in a new goroutine. // To prevent the goroutine from leaking, make sure to cancel the given context // once the stream is completed or canceled.
[ "Watch", "will", "periodically", "call", "the", "given", "SampleFunc", "to", "sample", "the", "progress", "of", "a", "monitored", "stream", "and", "update", "the", "given", "gauge", ".", "SampleFunc", "should", "return", "the", "total", "number", "of", "bytes", "transferred", "by", "the", "stream", "since", "it", "started", ".", "Watch", "is", "a", "blocking", "call", "and", "should", "typically", "be", "called", "in", "a", "new", "goroutine", ".", "To", "prevent", "the", "goroutine", "from", "leaking", "make", "sure", "to", "cancel", "the", "given", "context", "once", "the", "stream", "is", "completed", "or", "canceled", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/bps/bps.go#L42-L54
153,436
cavaliercoder/grab
util.go
setLastModified
func setLastModified(resp *http.Response, filename string) error { // https://tools.ietf.org/html/rfc7232#section-2.2 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified header := resp.Header.Get("Last-Modified") if header == "" { return nil } lastmod, err := time.Parse(http.TimeFormat, header) if err != nil { return nil } return os.Chtimes(filename, lastmod, lastmod) }
go
func setLastModified(resp *http.Response, filename string) error { // https://tools.ietf.org/html/rfc7232#section-2.2 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified header := resp.Header.Get("Last-Modified") if header == "" { return nil } lastmod, err := time.Parse(http.TimeFormat, header) if err != nil { return nil } return os.Chtimes(filename, lastmod, lastmod) }
[ "func", "setLastModified", "(", "resp", "*", "http", ".", "Response", ",", "filename", "string", ")", "error", "{", "// https://tools.ietf.org/html/rfc7232#section-2.2", "// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified", "header", ":=", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "header", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "lastmod", ",", "err", ":=", "time", ".", "Parse", "(", "http", ".", "TimeFormat", ",", "header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "os", ".", "Chtimes", "(", "filename", ",", "lastmod", ",", "lastmod", ")", "\n", "}" ]
// setLastModified sets the last modified timestamp of a local file according to // the Last-Modified header returned by a remote server.
[ "setLastModified", "sets", "the", "last", "modified", "timestamp", "of", "a", "local", "file", "according", "to", "the", "Last", "-", "Modified", "header", "returned", "by", "a", "remote", "server", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/util.go#L18-L30
153,437
cavaliercoder/grab
util.go
mkdirp
func mkdirp(path string) error { dir := filepath.Dir(path) if fi, err := os.Stat(dir); err != nil { if !os.IsNotExist(err) { return fmt.Errorf("error checking destination directory: %v", err) } if err := os.MkdirAll(dir, 0755); err != nil { return fmt.Errorf("error creating destination directory: %v", err) } } else if !fi.IsDir() { panic("destination path is not directory") } return nil }
go
func mkdirp(path string) error { dir := filepath.Dir(path) if fi, err := os.Stat(dir); err != nil { if !os.IsNotExist(err) { return fmt.Errorf("error checking destination directory: %v", err) } if err := os.MkdirAll(dir, 0755); err != nil { return fmt.Errorf("error creating destination directory: %v", err) } } else if !fi.IsDir() { panic("destination path is not directory") } return nil }
[ "func", "mkdirp", "(", "path", "string", ")", "error", "{", "dir", ":=", "filepath", ".", "Dir", "(", "path", ")", "\n", "if", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "dir", ")", ";", "err", "!=", "nil", "{", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "dir", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "else", "if", "!", "fi", ".", "IsDir", "(", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// mkdirp creates all missing parent directories for the destination file path.
[ "mkdirp", "creates", "all", "missing", "parent", "directories", "for", "the", "destination", "file", "path", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/util.go#L33-L46
153,438
cavaliercoder/grab
util.go
guessFilename
func guessFilename(resp *http.Response) (string, error) { filename := resp.Request.URL.Path if cd := resp.Header.Get("Content-Disposition"); cd != "" { if _, params, err := mime.ParseMediaType(cd); err == nil { filename = params["filename"] } } // sanitize if filename == "" || strings.HasSuffix(filename, "/") || strings.Contains(filename, "\x00") { return "", ErrNoFilename } filename = filepath.Base(path.Clean("/" + filename)) if filename == "" || filename == "." || filename == "/" { return "", ErrNoFilename } return filename, nil }
go
func guessFilename(resp *http.Response) (string, error) { filename := resp.Request.URL.Path if cd := resp.Header.Get("Content-Disposition"); cd != "" { if _, params, err := mime.ParseMediaType(cd); err == nil { filename = params["filename"] } } // sanitize if filename == "" || strings.HasSuffix(filename, "/") || strings.Contains(filename, "\x00") { return "", ErrNoFilename } filename = filepath.Base(path.Clean("/" + filename)) if filename == "" || filename == "." || filename == "/" { return "", ErrNoFilename } return filename, nil }
[ "func", "guessFilename", "(", "resp", "*", "http", ".", "Response", ")", "(", "string", ",", "error", ")", "{", "filename", ":=", "resp", ".", "Request", ".", "URL", ".", "Path", "\n", "if", "cd", ":=", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ";", "cd", "!=", "\"", "\"", "{", "if", "_", ",", "params", ",", "err", ":=", "mime", ".", "ParseMediaType", "(", "cd", ")", ";", "err", "==", "nil", "{", "filename", "=", "params", "[", "\"", "\"", "]", "\n", "}", "\n", "}", "\n\n", "// sanitize", "if", "filename", "==", "\"", "\"", "||", "strings", ".", "HasSuffix", "(", "filename", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "filename", ",", "\"", "\\x00", "\"", ")", "{", "return", "\"", "\"", ",", "ErrNoFilename", "\n", "}", "\n\n", "filename", "=", "filepath", ".", "Base", "(", "path", ".", "Clean", "(", "\"", "\"", "+", "filename", ")", ")", "\n", "if", "filename", "==", "\"", "\"", "||", "filename", "==", "\"", "\"", "||", "filename", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "ErrNoFilename", "\n", "}", "\n\n", "return", "filename", ",", "nil", "\n", "}" ]
// guessFilename returns a filename for the given http.Response. If none can be // determined ErrNoFilename is returned.
[ "guessFilename", "returns", "a", "filename", "for", "the", "given", "http", ".", "Response", ".", "If", "none", "can", "be", "determined", "ErrNoFilename", "is", "returned", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/util.go#L50-L69
153,439
cavaliercoder/grab
util.go
checksum
func checksum(ctx context.Context, filename string, h hash.Hash) (b []byte, err error) { var f *os.File f, err = os.Open(filename) if err != nil { return } defer func() { err = f.Close() }() t := newTransfer(ctx, nil, h, f, nil) if _, err = t.copy(); err != nil { return } b = h.Sum(nil) return }
go
func checksum(ctx context.Context, filename string, h hash.Hash) (b []byte, err error) { var f *os.File f, err = os.Open(filename) if err != nil { return } defer func() { err = f.Close() }() t := newTransfer(ctx, nil, h, f, nil) if _, err = t.copy(); err != nil { return } b = h.Sum(nil) return }
[ "func", "checksum", "(", "ctx", "context", ".", "Context", ",", "filename", "string", ",", "h", "hash", ".", "Hash", ")", "(", "b", "[", "]", "byte", ",", "err", "error", ")", "{", "var", "f", "*", "os", ".", "File", "\n", "f", ",", "err", "=", "os", ".", "Open", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "defer", "func", "(", ")", "{", "err", "=", "f", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n\n", "t", ":=", "newTransfer", "(", "ctx", ",", "nil", ",", "h", ",", "f", ",", "nil", ")", "\n", "if", "_", ",", "err", "=", "t", ".", "copy", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "b", "=", "h", ".", "Sum", "(", "nil", ")", "\n", "return", "\n", "}" ]
// checksum returns a hash of the given file, using the given hash algorithm.
[ "checksum", "returns", "a", "hash", "of", "the", "given", "file", "using", "the", "given", "hash", "algorithm", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/util.go#L72-L89
153,440
cavaliercoder/grab
grabui/console_client.go
refresh
func (c *ConsoleClient) refresh() { // clear lines for incomplete downloads if c.inProgress > 0 { fmt.Printf("\033[%dA\033[K", c.inProgress) } // print newly completed downloads for i, resp := range c.responses { if resp != nil && resp.IsComplete() { if resp.Err() != nil { c.failed++ fmt.Fprintf(os.Stderr, "Error downloading %s: %v\n", resp.Request.URL(), resp.Err()) } else { c.succeeded++ fmt.Printf("Finished %s %s / %s (%d%%)\n", resp.Filename, byteString(resp.BytesComplete()), byteString(resp.Size), int(100*resp.Progress())) } c.responses[i] = nil } } // print progress for incomplete downloads c.inProgress = 0 for _, resp := range c.responses { if resp != nil { fmt.Printf("Downloading %s %s / %s (%d%%) - %s ETA: %s \033[K\n", resp.Filename, byteString(resp.BytesComplete()), byteString(resp.Size), int(100*resp.Progress()), bpsString(resp.BytesPerSecond()), etaString(resp.ETA())) c.inProgress++ } } }
go
func (c *ConsoleClient) refresh() { // clear lines for incomplete downloads if c.inProgress > 0 { fmt.Printf("\033[%dA\033[K", c.inProgress) } // print newly completed downloads for i, resp := range c.responses { if resp != nil && resp.IsComplete() { if resp.Err() != nil { c.failed++ fmt.Fprintf(os.Stderr, "Error downloading %s: %v\n", resp.Request.URL(), resp.Err()) } else { c.succeeded++ fmt.Printf("Finished %s %s / %s (%d%%)\n", resp.Filename, byteString(resp.BytesComplete()), byteString(resp.Size), int(100*resp.Progress())) } c.responses[i] = nil } } // print progress for incomplete downloads c.inProgress = 0 for _, resp := range c.responses { if resp != nil { fmt.Printf("Downloading %s %s / %s (%d%%) - %s ETA: %s \033[K\n", resp.Filename, byteString(resp.BytesComplete()), byteString(resp.Size), int(100*resp.Progress()), bpsString(resp.BytesPerSecond()), etaString(resp.ETA())) c.inProgress++ } } }
[ "func", "(", "c", "*", "ConsoleClient", ")", "refresh", "(", ")", "{", "// clear lines for incomplete downloads", "if", "c", ".", "inProgress", ">", "0", "{", "fmt", ".", "Printf", "(", "\"", "\\033", "\\033", "\"", ",", "c", ".", "inProgress", ")", "\n", "}", "\n\n", "// print newly completed downloads", "for", "i", ",", "resp", ":=", "range", "c", ".", "responses", "{", "if", "resp", "!=", "nil", "&&", "resp", ".", "IsComplete", "(", ")", "{", "if", "resp", ".", "Err", "(", ")", "!=", "nil", "{", "c", ".", "failed", "++", "\n", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "resp", ".", "Request", ".", "URL", "(", ")", ",", "resp", ".", "Err", "(", ")", ")", "\n", "}", "else", "{", "c", ".", "succeeded", "++", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "resp", ".", "Filename", ",", "byteString", "(", "resp", ".", "BytesComplete", "(", ")", ")", ",", "byteString", "(", "resp", ".", "Size", ")", ",", "int", "(", "100", "*", "resp", ".", "Progress", "(", ")", ")", ")", "\n", "}", "\n", "c", ".", "responses", "[", "i", "]", "=", "nil", "\n", "}", "\n", "}", "\n\n", "// print progress for incomplete downloads", "c", ".", "inProgress", "=", "0", "\n", "for", "_", ",", "resp", ":=", "range", "c", ".", "responses", "{", "if", "resp", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\033", "\\n", "\"", ",", "resp", ".", "Filename", ",", "byteString", "(", "resp", ".", "BytesComplete", "(", ")", ")", ",", "byteString", "(", "resp", ".", "Size", ")", ",", "int", "(", "100", "*", "resp", ".", "Progress", "(", ")", ")", ",", "bpsString", "(", "resp", ".", "BytesPerSecond", "(", ")", ")", ",", "etaString", "(", "resp", ".", "ETA", "(", ")", ")", ")", "\n", "c", ".", "inProgress", "++", "\n", "}", "\n", "}", "\n", "}" ]
// refresh prints the progress of all downloads to the terminal
[ "refresh", "prints", "the", "progress", "of", "all", "downloads", "to", "the", "terminal" ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/grabui/console_client.go#L86-L126
153,441
cavaliercoder/grab
request.go
NewRequest
func NewRequest(dst, urlStr string) (*Request, error) { if dst == "" { dst = "." } req, err := http.NewRequest("GET", urlStr, nil) if err != nil { return nil, err } return &Request{ HTTPRequest: req, Filename: dst, }, nil }
go
func NewRequest(dst, urlStr string) (*Request, error) { if dst == "" { dst = "." } req, err := http.NewRequest("GET", urlStr, nil) if err != nil { return nil, err } return &Request{ HTTPRequest: req, Filename: dst, }, nil }
[ "func", "NewRequest", "(", "dst", ",", "urlStr", "string", ")", "(", "*", "Request", ",", "error", ")", "{", "if", "dst", "==", "\"", "\"", "{", "dst", "=", "\"", "\"", "\n", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "urlStr", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Request", "{", "HTTPRequest", ":", "req", ",", "Filename", ":", "dst", ",", "}", ",", "nil", "\n", "}" ]
// NewRequest returns a new file transfer Request suitable for use with // Client.Do.
[ "NewRequest", "returns", "a", "new", "file", "transfer", "Request", "suitable", "for", "use", "with", "Client", ".", "Do", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/request.go#L108-L120
153,442
cavaliercoder/grab
request.go
WithContext
func (r *Request) WithContext(ctx context.Context) *Request { if ctx == nil { panic("nil context") } r2 := new(Request) *r2 = *r r2.ctx = ctx r2.HTTPRequest = r2.HTTPRequest.WithContext(ctx) return r2 }
go
func (r *Request) WithContext(ctx context.Context) *Request { if ctx == nil { panic("nil context") } r2 := new(Request) *r2 = *r r2.ctx = ctx r2.HTTPRequest = r2.HTTPRequest.WithContext(ctx) return r2 }
[ "func", "(", "r", "*", "Request", ")", "WithContext", "(", "ctx", "context", ".", "Context", ")", "*", "Request", "{", "if", "ctx", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "r2", ":=", "new", "(", "Request", ")", "\n", "*", "r2", "=", "*", "r", "\n", "r2", ".", "ctx", "=", "ctx", "\n", "r2", ".", "HTTPRequest", "=", "r2", ".", "HTTPRequest", ".", "WithContext", "(", "ctx", ")", "\n", "return", "r2", "\n", "}" ]
// WithContext returns a shallow copy of r with its context changed // to ctx. The provided ctx must be non-nil.
[ "WithContext", "returns", "a", "shallow", "copy", "of", "r", "with", "its", "context", "changed", "to", "ctx", ".", "The", "provided", "ctx", "must", "be", "non", "-", "nil", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/request.go#L139-L148
153,443
cavaliercoder/grab
request.go
SetChecksum
func (r *Request) SetChecksum(h hash.Hash, sum []byte, deleteOnError bool) { r.hash = h r.checksum = sum r.deleteOnError = deleteOnError }
go
func (r *Request) SetChecksum(h hash.Hash, sum []byte, deleteOnError bool) { r.hash = h r.checksum = sum r.deleteOnError = deleteOnError }
[ "func", "(", "r", "*", "Request", ")", "SetChecksum", "(", "h", "hash", ".", "Hash", ",", "sum", "[", "]", "byte", ",", "deleteOnError", "bool", ")", "{", "r", ".", "hash", "=", "h", "\n", "r", ".", "checksum", "=", "sum", "\n", "r", ".", "deleteOnError", "=", "deleteOnError", "\n", "}" ]
// SetChecksum sets the desired hashing algorithm and checksum value to validate // a downloaded file. Once the download is complete, the given hashing algorithm // will be used to compute the actual checksum of the downloaded file. If the // checksums do not match, an error will be returned by the associated // Response.Err method. // // If deleteOnError is true, the downloaded file will be deleted automatically // if it fails checksum validation. // // To prevent corruption of the computed checksum, the given hash must not be // used by any other request or goroutines. // // To disable checksum validation, call SetChecksum with a nil hash.
[ "SetChecksum", "sets", "the", "desired", "hashing", "algorithm", "and", "checksum", "value", "to", "validate", "a", "downloaded", "file", ".", "Once", "the", "download", "is", "complete", "the", "given", "hashing", "algorithm", "will", "be", "used", "to", "compute", "the", "actual", "checksum", "of", "the", "downloaded", "file", ".", "If", "the", "checksums", "do", "not", "match", "an", "error", "will", "be", "returned", "by", "the", "associated", "Response", ".", "Err", "method", ".", "If", "deleteOnError", "is", "true", "the", "downloaded", "file", "will", "be", "deleted", "automatically", "if", "it", "fails", "checksum", "validation", ".", "To", "prevent", "corruption", "of", "the", "computed", "checksum", "the", "given", "hash", "must", "not", "be", "used", "by", "any", "other", "request", "or", "goroutines", ".", "To", "disable", "checksum", "validation", "call", "SetChecksum", "with", "a", "nil", "hash", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/request.go#L168-L172
153,444
cavaliercoder/grab
transfer.go
copy
func (c *transfer) copy() (written int64, err error) { // maintain a bps gauge in another goroutine ctx, cancel := context.WithCancel(c.ctx) defer cancel() go bps.Watch(ctx, c.gauge, c.N, time.Second) // start the transfer if c.b == nil { c.b = make([]byte, 32*1024) } for { select { case <-c.ctx.Done(): err = c.ctx.Err() return default: // keep working } nr, er := c.r.Read(c.b) if nr > 0 { nw, ew := c.w.Write(c.b[0:nr]) if nw > 0 { written += int64(nw) atomic.StoreInt64(&c.n, written) } if ew != nil { err = ew break } if nr != nw { err = io.ErrShortWrite break } // wait for rate limiter if c.lim != nil { err = c.lim.WaitN(c.ctx, nr) if err != nil { return } } } if er != nil { if er != io.EOF { err = er } break } } return written, err }
go
func (c *transfer) copy() (written int64, err error) { // maintain a bps gauge in another goroutine ctx, cancel := context.WithCancel(c.ctx) defer cancel() go bps.Watch(ctx, c.gauge, c.N, time.Second) // start the transfer if c.b == nil { c.b = make([]byte, 32*1024) } for { select { case <-c.ctx.Done(): err = c.ctx.Err() return default: // keep working } nr, er := c.r.Read(c.b) if nr > 0 { nw, ew := c.w.Write(c.b[0:nr]) if nw > 0 { written += int64(nw) atomic.StoreInt64(&c.n, written) } if ew != nil { err = ew break } if nr != nw { err = io.ErrShortWrite break } // wait for rate limiter if c.lim != nil { err = c.lim.WaitN(c.ctx, nr) if err != nil { return } } } if er != nil { if er != io.EOF { err = er } break } } return written, err }
[ "func", "(", "c", "*", "transfer", ")", "copy", "(", ")", "(", "written", "int64", ",", "err", "error", ")", "{", "// maintain a bps gauge in another goroutine", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "c", ".", "ctx", ")", "\n", "defer", "cancel", "(", ")", "\n", "go", "bps", ".", "Watch", "(", "ctx", ",", "c", ".", "gauge", ",", "c", ".", "N", ",", "time", ".", "Second", ")", "\n\n", "// start the transfer", "if", "c", ".", "b", "==", "nil", "{", "c", ".", "b", "=", "make", "(", "[", "]", "byte", ",", "32", "*", "1024", ")", "\n", "}", "\n", "for", "{", "select", "{", "case", "<-", "c", ".", "ctx", ".", "Done", "(", ")", ":", "err", "=", "c", ".", "ctx", ".", "Err", "(", ")", "\n", "return", "\n", "default", ":", "// keep working", "}", "\n", "nr", ",", "er", ":=", "c", ".", "r", ".", "Read", "(", "c", ".", "b", ")", "\n", "if", "nr", ">", "0", "{", "nw", ",", "ew", ":=", "c", ".", "w", ".", "Write", "(", "c", ".", "b", "[", "0", ":", "nr", "]", ")", "\n", "if", "nw", ">", "0", "{", "written", "+=", "int64", "(", "nw", ")", "\n", "atomic", ".", "StoreInt64", "(", "&", "c", ".", "n", ",", "written", ")", "\n", "}", "\n", "if", "ew", "!=", "nil", "{", "err", "=", "ew", "\n", "break", "\n", "}", "\n", "if", "nr", "!=", "nw", "{", "err", "=", "io", ".", "ErrShortWrite", "\n", "break", "\n", "}", "\n", "// wait for rate limiter", "if", "c", ".", "lim", "!=", "nil", "{", "err", "=", "c", ".", "lim", ".", "WaitN", "(", "c", ".", "ctx", ",", "nr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "er", "!=", "nil", "{", "if", "er", "!=", "io", ".", "EOF", "{", "err", "=", "er", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "written", ",", "err", "\n", "}" ]
// copy behaves similarly to io.CopyBuffer except that it checks for cancelation // of the given context.Context, reports progress in a thread-safe manner and // tracks the transfer rate.
[ "copy", "behaves", "similarly", "to", "io", ".", "CopyBuffer", "except", "that", "it", "checks", "for", "cancelation", "of", "the", "given", "context", ".", "Context", "reports", "progress", "in", "a", "thread", "-", "safe", "manner", "and", "tracks", "the", "transfer", "rate", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/transfer.go#L36-L85
153,445
cavaliercoder/grab
transfer.go
N
func (c *transfer) N() (n int64) { if c == nil { return 0 } n = atomic.LoadInt64(&c.n) return }
go
func (c *transfer) N() (n int64) { if c == nil { return 0 } n = atomic.LoadInt64(&c.n) return }
[ "func", "(", "c", "*", "transfer", ")", "N", "(", ")", "(", "n", "int64", ")", "{", "if", "c", "==", "nil", "{", "return", "0", "\n", "}", "\n", "n", "=", "atomic", ".", "LoadInt64", "(", "&", "c", ".", "n", ")", "\n", "return", "\n", "}" ]
// N returns the number of bytes transferred.
[ "N", "returns", "the", "number", "of", "bytes", "transferred", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/transfer.go#L88-L94
153,446
cavaliercoder/grab
transfer.go
BPS
func (c *transfer) BPS() (bps float64) { if c == nil || c.gauge == nil { return 0 } return c.gauge.BPS() }
go
func (c *transfer) BPS() (bps float64) { if c == nil || c.gauge == nil { return 0 } return c.gauge.BPS() }
[ "func", "(", "c", "*", "transfer", ")", "BPS", "(", ")", "(", "bps", "float64", ")", "{", "if", "c", "==", "nil", "||", "c", ".", "gauge", "==", "nil", "{", "return", "0", "\n", "}", "\n", "return", "c", ".", "gauge", ".", "BPS", "(", ")", "\n", "}" ]
// BPS returns the current bytes per second transfer rate using a simple moving // average.
[ "BPS", "returns", "the", "current", "bytes", "per", "second", "transfer", "rate", "using", "a", "simple", "moving", "average", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/transfer.go#L98-L103
153,447
cavaliercoder/grab
grab.go
GetBatch
func GetBatch(workers int, dst string, urlStrs ...string) (<-chan *Response, error) { fi, err := os.Stat(dst) if err != nil { return nil, err } if !fi.IsDir() { return nil, fmt.Errorf("destination is not a directory") } reqs := make([]*Request, len(urlStrs)) for i := 0; i < len(urlStrs); i++ { req, err := NewRequest(dst, urlStrs[i]) if err != nil { return nil, err } reqs[i] = req } ch := DefaultClient.DoBatch(workers, reqs...) return ch, nil }
go
func GetBatch(workers int, dst string, urlStrs ...string) (<-chan *Response, error) { fi, err := os.Stat(dst) if err != nil { return nil, err } if !fi.IsDir() { return nil, fmt.Errorf("destination is not a directory") } reqs := make([]*Request, len(urlStrs)) for i := 0; i < len(urlStrs); i++ { req, err := NewRequest(dst, urlStrs[i]) if err != nil { return nil, err } reqs[i] = req } ch := DefaultClient.DoBatch(workers, reqs...) return ch, nil }
[ "func", "GetBatch", "(", "workers", "int", ",", "dst", "string", ",", "urlStrs", "...", "string", ")", "(", "<-", "chan", "*", "Response", ",", "error", ")", "{", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "dst", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "fi", ".", "IsDir", "(", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "reqs", ":=", "make", "(", "[", "]", "*", "Request", ",", "len", "(", "urlStrs", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "urlStrs", ")", ";", "i", "++", "{", "req", ",", "err", ":=", "NewRequest", "(", "dst", ",", "urlStrs", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "reqs", "[", "i", "]", "=", "req", "\n", "}", "\n\n", "ch", ":=", "DefaultClient", ".", "DoBatch", "(", "workers", ",", "reqs", "...", ")", "\n", "return", "ch", ",", "nil", "\n", "}" ]
// GetBatch sends multiple HTTP requests and downloads the content of the // requested URLs to the given destination directory using the given number of // concurrent worker goroutines. // // The Response for each requested URL is sent through the returned Response // channel, as soon as a worker receives a response from the remote server. The // Response can then be used to track the progress of the download while it is // in progress. // // The returned Response channel will be closed by Grab, only once all downloads // have completed or failed. // // If an error occurs during any download, it will be available via call to the // associated Response.Err. // // For control over HTTP client headers, redirect policy, and other settings, // create a Client instead.
[ "GetBatch", "sends", "multiple", "HTTP", "requests", "and", "downloads", "the", "content", "of", "the", "requested", "URLs", "to", "the", "given", "destination", "directory", "using", "the", "given", "number", "of", "concurrent", "worker", "goroutines", ".", "The", "Response", "for", "each", "requested", "URL", "is", "sent", "through", "the", "returned", "Response", "channel", "as", "soon", "as", "a", "worker", "receives", "a", "response", "from", "the", "remote", "server", ".", "The", "Response", "can", "then", "be", "used", "to", "track", "the", "progress", "of", "the", "download", "while", "it", "is", "in", "progress", ".", "The", "returned", "Response", "channel", "will", "be", "closed", "by", "Grab", "only", "once", "all", "downloads", "have", "completed", "or", "failed", ".", "If", "an", "error", "occurs", "during", "any", "download", "it", "will", "be", "available", "via", "call", "to", "the", "associated", "Response", ".", "Err", ".", "For", "control", "over", "HTTP", "client", "headers", "redirect", "policy", "and", "other", "settings", "create", "a", "Client", "instead", "." ]
a224b4097c01f213344b657c2886cd429d891812
https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/grab.go#L44-L64
153,448
opentracing-contrib/go-stdlib
nethttp/server.go
OperationNameFunc
func OperationNameFunc(f func(r *http.Request) string) MWOption { return func(options *mwOptions) { options.opNameFunc = f } }
go
func OperationNameFunc(f func(r *http.Request) string) MWOption { return func(options *mwOptions) { options.opNameFunc = f } }
[ "func", "OperationNameFunc", "(", "f", "func", "(", "r", "*", "http", ".", "Request", ")", "string", ")", "MWOption", "{", "return", "func", "(", "options", "*", "mwOptions", ")", "{", "options", ".", "opNameFunc", "=", "f", "\n", "}", "\n", "}" ]
// OperationNameFunc returns a MWOption that uses given function f // to generate operation name for each server-side span.
[ "OperationNameFunc", "returns", "a", "MWOption", "that", "uses", "given", "function", "f", "to", "generate", "operation", "name", "for", "each", "server", "-", "side", "span", "." ]
3020fec0e66bdb65fd42cb346cb65d58deb92e0d
https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/server.go#L26-L30
153,449
opentracing-contrib/go-stdlib
nethttp/server.go
MWSpanFilter
func MWSpanFilter(f func(r *http.Request) bool) MWOption { return func(options *mwOptions) { options.spanFilter = f } }
go
func MWSpanFilter(f func(r *http.Request) bool) MWOption { return func(options *mwOptions) { options.spanFilter = f } }
[ "func", "MWSpanFilter", "(", "f", "func", "(", "r", "*", "http", ".", "Request", ")", "bool", ")", "MWOption", "{", "return", "func", "(", "options", "*", "mwOptions", ")", "{", "options", ".", "spanFilter", "=", "f", "\n", "}", "\n", "}" ]
// MWSpanFilter returns a MWOption that filters requests from creating a span // for the server-side span. // Span won't be created if it returns false.
[ "MWSpanFilter", "returns", "a", "MWOption", "that", "filters", "requests", "from", "creating", "a", "span", "for", "the", "server", "-", "side", "span", ".", "Span", "won", "t", "be", "created", "if", "it", "returns", "false", "." ]
3020fec0e66bdb65fd42cb346cb65d58deb92e0d
https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/server.go#L43-L47
153,450
opentracing-contrib/go-stdlib
nethttp/server.go
MWSpanObserver
func MWSpanObserver(f func(span opentracing.Span, r *http.Request)) MWOption { return func(options *mwOptions) { options.spanObserver = f } }
go
func MWSpanObserver(f func(span opentracing.Span, r *http.Request)) MWOption { return func(options *mwOptions) { options.spanObserver = f } }
[ "func", "MWSpanObserver", "(", "f", "func", "(", "span", "opentracing", ".", "Span", ",", "r", "*", "http", ".", "Request", ")", ")", "MWOption", "{", "return", "func", "(", "options", "*", "mwOptions", ")", "{", "options", ".", "spanObserver", "=", "f", "\n", "}", "\n", "}" ]
// MWSpanObserver returns a MWOption that observe the span // for the server-side span.
[ "MWSpanObserver", "returns", "a", "MWOption", "that", "observe", "the", "span", "for", "the", "server", "-", "side", "span", "." ]
3020fec0e66bdb65fd42cb346cb65d58deb92e0d
https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/server.go#L51-L55
153,451
opentracing-contrib/go-stdlib
nethttp/server.go
MWURLTagFunc
func MWURLTagFunc(f func(u *url.URL) string) MWOption { return func(options *mwOptions) { options.urlTagFunc = f } }
go
func MWURLTagFunc(f func(u *url.URL) string) MWOption { return func(options *mwOptions) { options.urlTagFunc = f } }
[ "func", "MWURLTagFunc", "(", "f", "func", "(", "u", "*", "url", ".", "URL", ")", "string", ")", "MWOption", "{", "return", "func", "(", "options", "*", "mwOptions", ")", "{", "options", ".", "urlTagFunc", "=", "f", "\n", "}", "\n", "}" ]
// MWURLTagFunc returns a MWOption that uses given function f // to set the span's http.url tag. Can be used to change the default // http.url tag, eg to redact sensitive information.
[ "MWURLTagFunc", "returns", "a", "MWOption", "that", "uses", "given", "function", "f", "to", "set", "the", "span", "s", "http", ".", "url", "tag", ".", "Can", "be", "used", "to", "change", "the", "default", "http", ".", "url", "tag", "eg", "to", "redact", "sensitive", "information", "." ]
3020fec0e66bdb65fd42cb346cb65d58deb92e0d
https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/server.go#L60-L64
153,452
opentracing-contrib/go-stdlib
nethttp/client.go
ClientSpanObserver
func ClientSpanObserver(f func(span opentracing.Span, r *http.Request)) ClientOption { return func(options *clientOptions) { options.spanObserver = f } }
go
func ClientSpanObserver(f func(span opentracing.Span, r *http.Request)) ClientOption { return func(options *clientOptions) { options.spanObserver = f } }
[ "func", "ClientSpanObserver", "(", "f", "func", "(", "span", "opentracing", ".", "Span", ",", "r", "*", "http", ".", "Request", ")", ")", "ClientOption", "{", "return", "func", "(", "options", "*", "clientOptions", ")", "{", "options", ".", "spanObserver", "=", "f", "\n", "}", "\n", "}" ]
// ClientSpanObserver returns a ClientOption that observes the span // for the client-side span.
[ "ClientSpanObserver", "returns", "a", "ClientOption", "that", "observes", "the", "span", "for", "the", "client", "-", "side", "span", "." ]
3020fec0e66bdb65fd42cb346cb65d58deb92e0d
https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/client.go#L69-L73
153,453
opentracing-contrib/go-stdlib
nethttp/client.go
TracerFromRequest
func TracerFromRequest(req *http.Request) *Tracer { tr, ok := req.Context().Value(keyTracer).(*Tracer) if !ok { return nil } return tr }
go
func TracerFromRequest(req *http.Request) *Tracer { tr, ok := req.Context().Value(keyTracer).(*Tracer) if !ok { return nil } return tr }
[ "func", "TracerFromRequest", "(", "req", "*", "http", ".", "Request", ")", "*", "Tracer", "{", "tr", ",", "ok", ":=", "req", ".", "Context", "(", ")", ".", "Value", "(", "keyTracer", ")", ".", "(", "*", "Tracer", ")", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "return", "tr", "\n", "}" ]
// TracerFromRequest retrieves the Tracer from the request. If the request does // not have a Tracer it will return nil.
[ "TracerFromRequest", "retrieves", "the", "Tracer", "from", "the", "request", ".", "If", "the", "request", "does", "not", "have", "a", "Tracer", "it", "will", "return", "nil", "." ]
3020fec0e66bdb65fd42cb346cb65d58deb92e0d
https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/client.go#L129-L135
153,454
bitrise-io/bitrise
cli/trigger_check.go
getWorkflowIDByParamsInCompatibleMode
func getWorkflowIDByParamsInCompatibleMode(triggerMap models.TriggerMapModel, params RunAndTriggerParamsModel, isPullRequestMode bool) (string, error) { if params.TriggerPattern != "" { params = migratePatternToParams(params, isPullRequestMode) } return getWorkflowIDByParams(triggerMap, params) }
go
func getWorkflowIDByParamsInCompatibleMode(triggerMap models.TriggerMapModel, params RunAndTriggerParamsModel, isPullRequestMode bool) (string, error) { if params.TriggerPattern != "" { params = migratePatternToParams(params, isPullRequestMode) } return getWorkflowIDByParams(triggerMap, params) }
[ "func", "getWorkflowIDByParamsInCompatibleMode", "(", "triggerMap", "models", ".", "TriggerMapModel", ",", "params", "RunAndTriggerParamsModel", ",", "isPullRequestMode", "bool", ")", "(", "string", ",", "error", ")", "{", "if", "params", ".", "TriggerPattern", "!=", "\"", "\"", "{", "params", "=", "migratePatternToParams", "(", "params", ",", "isPullRequestMode", ")", "\n", "}", "\n\n", "return", "getWorkflowIDByParams", "(", "triggerMap", ",", "params", ")", "\n", "}" ]
// migrates deprecated params.TriggerPattern to params.PushBranch or params.PRSourceBranch based on isPullRequestMode // and returns the triggered workflow id
[ "migrates", "deprecated", "params", ".", "TriggerPattern", "to", "params", ".", "PushBranch", "or", "params", ".", "PRSourceBranch", "based", "on", "isPullRequestMode", "and", "returns", "the", "triggered", "workflow", "id" ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/cli/trigger_check.go#L77-L83
153,455
bitrise-io/bitrise
tools/timeoutcmd/timeoutcmd.go
New
func New(dir, name string, args ...string) Command { c := Command{ cmd: exec.Command(name, args...), } c.cmd.Dir = dir return c }
go
func New(dir, name string, args ...string) Command { c := Command{ cmd: exec.Command(name, args...), } c.cmd.Dir = dir return c }
[ "func", "New", "(", "dir", ",", "name", "string", ",", "args", "...", "string", ")", "Command", "{", "c", ":=", "Command", "{", "cmd", ":", "exec", ".", "Command", "(", "name", ",", "args", "...", ")", ",", "}", "\n", "c", ".", "cmd", ".", "Dir", "=", "dir", "\n", "return", "c", "\n", "}" ]
// New creates a command model.
[ "New", "creates", "a", "command", "model", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/timeoutcmd/timeoutcmd.go#L22-L28
153,456
bitrise-io/bitrise
tools/timeoutcmd/timeoutcmd.go
AppendEnv
func (c *Command) AppendEnv(env string) { if c.cmd.Env != nil { c.cmd.Env = append(c.cmd.Env, env) return } c.cmd.Env = append(os.Environ(), env) }
go
func (c *Command) AppendEnv(env string) { if c.cmd.Env != nil { c.cmd.Env = append(c.cmd.Env, env) return } c.cmd.Env = append(os.Environ(), env) }
[ "func", "(", "c", "*", "Command", ")", "AppendEnv", "(", "env", "string", ")", "{", "if", "c", ".", "cmd", ".", "Env", "!=", "nil", "{", "c", ".", "cmd", ".", "Env", "=", "append", "(", "c", ".", "cmd", ".", "Env", ",", "env", ")", "\n", "return", "\n", "}", "\n", "c", ".", "cmd", ".", "Env", "=", "append", "(", "os", ".", "Environ", "(", ")", ",", "env", ")", "\n", "}" ]
// AppendEnv appends and env to the command's env list.
[ "AppendEnv", "appends", "and", "env", "to", "the", "command", "s", "env", "list", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/timeoutcmd/timeoutcmd.go#L36-L42
153,457
bitrise-io/bitrise
tools/timeoutcmd/timeoutcmd.go
SetStandardIO
func (c *Command) SetStandardIO(in io.Reader, out, err io.Writer) { c.cmd.Stdin, c.cmd.Stdout, c.cmd.Stderr = in, out, err }
go
func (c *Command) SetStandardIO(in io.Reader, out, err io.Writer) { c.cmd.Stdin, c.cmd.Stdout, c.cmd.Stderr = in, out, err }
[ "func", "(", "c", "*", "Command", ")", "SetStandardIO", "(", "in", "io", ".", "Reader", ",", "out", ",", "err", "io", ".", "Writer", ")", "{", "c", ".", "cmd", ".", "Stdin", ",", "c", ".", "cmd", ".", "Stdout", ",", "c", ".", "cmd", ".", "Stderr", "=", "in", ",", "out", ",", "err", "\n", "}" ]
// SetStandardIO sets the input and outputs of the command.
[ "SetStandardIO", "sets", "the", "input", "and", "outputs", "of", "the", "command", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/timeoutcmd/timeoutcmd.go#L45-L47
153,458
bitrise-io/bitrise
tools/timeoutcmd/timeoutcmd.go
Start
func (c *Command) Start() error { // setting up notification for signals so we can have // separated logic to end the process interruptChan := make(chan os.Signal) signal.Notify(interruptChan, os.Interrupt, os.Kill) var interrupted bool go func() { <-interruptChan interrupted = true }() // start the process if err := c.cmd.Start(); err != nil { return err } // Wait for the process to finish done := make(chan error, 1) go func() { done <- c.cmd.Wait() }() // or kill it after a timeout (whichever happens first) var timeoutChan <-chan time.Time if c.timeout > 0 { timeoutChan = time.After(c.timeout) } // exiting the method for the two supported cases: finish/error or timeout select { case <-timeoutChan: if err := c.cmd.Process.Kill(); err != nil { log.Warnf("Failed to kill process: %s", err) } return fmt.Errorf("timed out") case err := <-done: if interrupted { os.Exit(ExitStatus(err)) } return err } }
go
func (c *Command) Start() error { // setting up notification for signals so we can have // separated logic to end the process interruptChan := make(chan os.Signal) signal.Notify(interruptChan, os.Interrupt, os.Kill) var interrupted bool go func() { <-interruptChan interrupted = true }() // start the process if err := c.cmd.Start(); err != nil { return err } // Wait for the process to finish done := make(chan error, 1) go func() { done <- c.cmd.Wait() }() // or kill it after a timeout (whichever happens first) var timeoutChan <-chan time.Time if c.timeout > 0 { timeoutChan = time.After(c.timeout) } // exiting the method for the two supported cases: finish/error or timeout select { case <-timeoutChan: if err := c.cmd.Process.Kill(); err != nil { log.Warnf("Failed to kill process: %s", err) } return fmt.Errorf("timed out") case err := <-done: if interrupted { os.Exit(ExitStatus(err)) } return err } }
[ "func", "(", "c", "*", "Command", ")", "Start", "(", ")", "error", "{", "// setting up notification for signals so we can have", "// separated logic to end the process", "interruptChan", ":=", "make", "(", "chan", "os", ".", "Signal", ")", "\n", "signal", ".", "Notify", "(", "interruptChan", ",", "os", ".", "Interrupt", ",", "os", ".", "Kill", ")", "\n", "var", "interrupted", "bool", "\n", "go", "func", "(", ")", "{", "<-", "interruptChan", "\n", "interrupted", "=", "true", "\n", "}", "(", ")", "\n\n", "// start the process", "if", "err", ":=", "c", ".", "cmd", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Wait for the process to finish", "done", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "done", "<-", "c", ".", "cmd", ".", "Wait", "(", ")", "\n", "}", "(", ")", "\n\n", "// or kill it after a timeout (whichever happens first)", "var", "timeoutChan", "<-", "chan", "time", ".", "Time", "\n", "if", "c", ".", "timeout", ">", "0", "{", "timeoutChan", "=", "time", ".", "After", "(", "c", ".", "timeout", ")", "\n", "}", "\n\n", "// exiting the method for the two supported cases: finish/error or timeout", "select", "{", "case", "<-", "timeoutChan", ":", "if", "err", ":=", "c", ".", "cmd", ".", "Process", ".", "Kill", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "err", ":=", "<-", "done", ":", "if", "interrupted", "{", "os", ".", "Exit", "(", "ExitStatus", "(", "err", ")", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}" ]
// Start starts the command run.
[ "Start", "starts", "the", "command", "run", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/timeoutcmd/timeoutcmd.go#L50-L91
153,459
bitrise-io/bitrise
tools/timeoutcmd/timeoutcmd.go
ExitStatus
func ExitStatus(err error) int { if err == nil { return 0 } code := 1 if exiterr, ok := err.(*exec.ExitError); ok { if waitStatus, ok := exiterr.Sys().(syscall.WaitStatus); ok { code = waitStatus.ExitStatus() } } return code }
go
func ExitStatus(err error) int { if err == nil { return 0 } code := 1 if exiterr, ok := err.(*exec.ExitError); ok { if waitStatus, ok := exiterr.Sys().(syscall.WaitStatus); ok { code = waitStatus.ExitStatus() } } return code }
[ "func", "ExitStatus", "(", "err", "error", ")", "int", "{", "if", "err", "==", "nil", "{", "return", "0", "\n", "}", "\n\n", "code", ":=", "1", "\n", "if", "exiterr", ",", "ok", ":=", "err", ".", "(", "*", "exec", ".", "ExitError", ")", ";", "ok", "{", "if", "waitStatus", ",", "ok", ":=", "exiterr", ".", "Sys", "(", ")", ".", "(", "syscall", ".", "WaitStatus", ")", ";", "ok", "{", "code", "=", "waitStatus", ".", "ExitStatus", "(", ")", "\n", "}", "\n", "}", "\n", "return", "code", "\n", "}" ]
// ExitStatus returns the error's exit status // if the error is an exec.ExitError // if the error is nil it return 0 // otherwise returns 1.
[ "ExitStatus", "returns", "the", "error", "s", "exit", "status", "if", "the", "error", "is", "an", "exec", ".", "ExitError", "if", "the", "error", "is", "nil", "it", "return", "0", "otherwise", "returns", "1", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/timeoutcmd/timeoutcmd.go#L97-L109
153,460
bitrise-io/bitrise
tools/filterwriter/range.go
allRanges
func allRanges(b, pattern []byte) (ranges []matchRange) { i := 0 for { sub := b[i:len(b)] idx := bytes.Index(sub, pattern) if idx == -1 { return } ranges = append(ranges, matchRange{first: idx + i, last: idx + i + len(pattern)}) i += idx + 1 if i > len(b)-1 { return } } }
go
func allRanges(b, pattern []byte) (ranges []matchRange) { i := 0 for { sub := b[i:len(b)] idx := bytes.Index(sub, pattern) if idx == -1 { return } ranges = append(ranges, matchRange{first: idx + i, last: idx + i + len(pattern)}) i += idx + 1 if i > len(b)-1 { return } } }
[ "func", "allRanges", "(", "b", ",", "pattern", "[", "]", "byte", ")", "(", "ranges", "[", "]", "matchRange", ")", "{", "i", ":=", "0", "\n", "for", "{", "sub", ":=", "b", "[", "i", ":", "len", "(", "b", ")", "]", "\n", "idx", ":=", "bytes", ".", "Index", "(", "sub", ",", "pattern", ")", "\n", "if", "idx", "==", "-", "1", "{", "return", "\n", "}", "\n\n", "ranges", "=", "append", "(", "ranges", ",", "matchRange", "{", "first", ":", "idx", "+", "i", ",", "last", ":", "idx", "+", "i", "+", "len", "(", "pattern", ")", "}", ")", "\n\n", "i", "+=", "idx", "+", "1", "\n", "if", "i", ">", "len", "(", "b", ")", "-", "1", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// allRanges returns every indexes of instance of pattern in b, or nil if pattern is not present in b.
[ "allRanges", "returns", "every", "indexes", "of", "instance", "of", "pattern", "in", "b", "or", "nil", "if", "pattern", "is", "not", "present", "in", "b", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/range.go#L11-L27
153,461
bitrise-io/bitrise
tools/filterwriter/range.go
mergeAllRanges
func mergeAllRanges(r []matchRange) []matchRange { sort.Slice(r, func(i, j int) bool { return r[i].first < r[j].first }) for i := 0; i < len(r)-1; i++ { for i+1 < len(r) && r[i+1].first <= r[i].last { if r[i+1].last > r[i].last { r[i].last = r[i+1].last } r = append(r[:i+1], r[i+2:]...) } } return r }
go
func mergeAllRanges(r []matchRange) []matchRange { sort.Slice(r, func(i, j int) bool { return r[i].first < r[j].first }) for i := 0; i < len(r)-1; i++ { for i+1 < len(r) && r[i+1].first <= r[i].last { if r[i+1].last > r[i].last { r[i].last = r[i+1].last } r = append(r[:i+1], r[i+2:]...) } } return r }
[ "func", "mergeAllRanges", "(", "r", "[", "]", "matchRange", ")", "[", "]", "matchRange", "{", "sort", ".", "Slice", "(", "r", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "r", "[", "i", "]", ".", "first", "<", "r", "[", "j", "]", ".", "first", "}", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "r", ")", "-", "1", ";", "i", "++", "{", "for", "i", "+", "1", "<", "len", "(", "r", ")", "&&", "r", "[", "i", "+", "1", "]", ".", "first", "<=", "r", "[", "i", "]", ".", "last", "{", "if", "r", "[", "i", "+", "1", "]", ".", "last", ">", "r", "[", "i", "]", ".", "last", "{", "r", "[", "i", "]", ".", "last", "=", "r", "[", "i", "+", "1", "]", ".", "last", "\n", "}", "\n", "r", "=", "append", "(", "r", "[", ":", "i", "+", "1", "]", ",", "r", "[", "i", "+", "2", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n", "return", "r", "\n", "}" ]
// mergeAllRanges merges every overlapping ranges in r.
[ "mergeAllRanges", "merges", "every", "overlapping", "ranges", "in", "r", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/range.go#L30-L41
153,462
bitrise-io/bitrise
tools/filterwriter/filterwriter.go
Write
func (w *Writer) Write(p []byte) (int, error) { defer func() { w.mux.Unlock() }() w.mux.Lock() // previous bytes may not ended with newline data := append(w.chunk, p...) lastLines, chunk := splitAfterNewline(data) w.chunk = chunk if len(chunk) > 0 { // we have remaining bytes, do not swallow them if w.timer != nil { w.timer.Stop() w.timer.C = nil } w.timer = time.AfterFunc(100*time.Millisecond, func() { if _, err := w.Flush(); err != nil { log.Errorf("Failed to print last lines: %s", err) } }) } if len(lastLines) == 0 { // it is necessary to return the count of incoming bytes return len(p), nil } for _, line := range lastLines { lines := append(w.store, line) matchMap, partialMatchIndexes := w.matchSecrets(lines) var linesToPrint [][]byte linesToPrint, w.store = w.matchLines(lines, partialMatchIndexes) if linesToPrint == nil { continue } redactedLines := w.redact(linesToPrint, matchMap) redactedBytes := bytes.Join(redactedLines, nil) if c, err := w.writer.Write(redactedBytes); err != nil { return c, err } } // it is necessary to return the count of incoming bytes // to let the exec.Command work properly return len(p), nil }
go
func (w *Writer) Write(p []byte) (int, error) { defer func() { w.mux.Unlock() }() w.mux.Lock() // previous bytes may not ended with newline data := append(w.chunk, p...) lastLines, chunk := splitAfterNewline(data) w.chunk = chunk if len(chunk) > 0 { // we have remaining bytes, do not swallow them if w.timer != nil { w.timer.Stop() w.timer.C = nil } w.timer = time.AfterFunc(100*time.Millisecond, func() { if _, err := w.Flush(); err != nil { log.Errorf("Failed to print last lines: %s", err) } }) } if len(lastLines) == 0 { // it is necessary to return the count of incoming bytes return len(p), nil } for _, line := range lastLines { lines := append(w.store, line) matchMap, partialMatchIndexes := w.matchSecrets(lines) var linesToPrint [][]byte linesToPrint, w.store = w.matchLines(lines, partialMatchIndexes) if linesToPrint == nil { continue } redactedLines := w.redact(linesToPrint, matchMap) redactedBytes := bytes.Join(redactedLines, nil) if c, err := w.writer.Write(redactedBytes); err != nil { return c, err } } // it is necessary to return the count of incoming bytes // to let the exec.Command work properly return len(p), nil }
[ "func", "(", "w", "*", "Writer", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "defer", "func", "(", ")", "{", "w", ".", "mux", ".", "Unlock", "(", ")", "\n", "}", "(", ")", "\n", "w", ".", "mux", ".", "Lock", "(", ")", "\n\n", "// previous bytes may not ended with newline", "data", ":=", "append", "(", "w", ".", "chunk", ",", "p", "...", ")", "\n\n", "lastLines", ",", "chunk", ":=", "splitAfterNewline", "(", "data", ")", "\n", "w", ".", "chunk", "=", "chunk", "\n", "if", "len", "(", "chunk", ")", ">", "0", "{", "// we have remaining bytes, do not swallow them", "if", "w", ".", "timer", "!=", "nil", "{", "w", ".", "timer", ".", "Stop", "(", ")", "\n", "w", ".", "timer", ".", "C", "=", "nil", "\n", "}", "\n", "w", ".", "timer", "=", "time", ".", "AfterFunc", "(", "100", "*", "time", ".", "Millisecond", ",", "func", "(", ")", "{", "if", "_", ",", "err", ":=", "w", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", ")", "\n", "}", "\n\n", "if", "len", "(", "lastLines", ")", "==", "0", "{", "// it is necessary to return the count of incoming bytes", "return", "len", "(", "p", ")", ",", "nil", "\n", "}", "\n\n", "for", "_", ",", "line", ":=", "range", "lastLines", "{", "lines", ":=", "append", "(", "w", ".", "store", ",", "line", ")", "\n", "matchMap", ",", "partialMatchIndexes", ":=", "w", ".", "matchSecrets", "(", "lines", ")", "\n\n", "var", "linesToPrint", "[", "]", "[", "]", "byte", "\n", "linesToPrint", ",", "w", ".", "store", "=", "w", ".", "matchLines", "(", "lines", ",", "partialMatchIndexes", ")", "\n", "if", "linesToPrint", "==", "nil", "{", "continue", "\n", "}", "\n\n", "redactedLines", ":=", "w", ".", "redact", "(", "linesToPrint", ",", "matchMap", ")", "\n", "redactedBytes", ":=", "bytes", ".", "Join", "(", "redactedLines", ",", "nil", ")", "\n", "if", "c", ",", "err", ":=", "w", ".", "writer", ".", "Write", "(", "redactedBytes", ")", ";", "err", "!=", "nil", "{", "return", "c", ",", "err", "\n", "}", "\n", "}", "\n\n", "// it is necessary to return the count of incoming bytes", "// to let the exec.Command work properly", "return", "len", "(", "p", ")", ",", "nil", "\n", "}" ]
// Write implements io.Writer interface. // Splits p into lines, the lines are matched against the secrets, // this determines which lines can be redacted and written into the buffer. // There are may lines which needs to be stored, since they are partial matching to a secret. // Since we do not know which is the last call of Write we need to call Flush // on buffer to write the remaining lines.
[ "Write", "implements", "io", ".", "Writer", "interface", ".", "Splits", "p", "into", "lines", "the", "lines", "are", "matched", "against", "the", "secrets", "this", "determines", "which", "lines", "can", "be", "redacted", "and", "written", "into", "the", "buffer", ".", "There", "are", "may", "lines", "which", "needs", "to", "be", "stored", "since", "they", "are", "partial", "matching", "to", "a", "secret", ".", "Since", "we", "do", "not", "know", "which", "is", "the", "last", "call", "of", "Write", "we", "need", "to", "call", "Flush", "on", "buffer", "to", "write", "the", "remaining", "lines", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L43-L92
153,463
bitrise-io/bitrise
tools/filterwriter/filterwriter.go
Flush
func (w *Writer) Flush() (int, error) { defer func() { w.mux.Unlock() }() w.mux.Lock() if len(w.chunk) > 0 { // lines are containing newline, chunk may not chunk := w.chunk w.chunk = nil w.store = append(w.store, chunk) } // we only need to care about the full matches in the remaining lines // (no more lines were come, why care about the partial matches?) matchMap, _ := w.matchSecrets(w.store) redactedLines := w.redact(w.store, matchMap) w.store = nil return w.writer.Write(bytes.Join(redactedLines, nil)) }
go
func (w *Writer) Flush() (int, error) { defer func() { w.mux.Unlock() }() w.mux.Lock() if len(w.chunk) > 0 { // lines are containing newline, chunk may not chunk := w.chunk w.chunk = nil w.store = append(w.store, chunk) } // we only need to care about the full matches in the remaining lines // (no more lines were come, why care about the partial matches?) matchMap, _ := w.matchSecrets(w.store) redactedLines := w.redact(w.store, matchMap) w.store = nil return w.writer.Write(bytes.Join(redactedLines, nil)) }
[ "func", "(", "w", "*", "Writer", ")", "Flush", "(", ")", "(", "int", ",", "error", ")", "{", "defer", "func", "(", ")", "{", "w", ".", "mux", ".", "Unlock", "(", ")", "\n", "}", "(", ")", "\n", "w", ".", "mux", ".", "Lock", "(", ")", "\n\n", "if", "len", "(", "w", ".", "chunk", ")", ">", "0", "{", "// lines are containing newline, chunk may not", "chunk", ":=", "w", ".", "chunk", "\n", "w", ".", "chunk", "=", "nil", "\n", "w", ".", "store", "=", "append", "(", "w", ".", "store", ",", "chunk", ")", "\n", "}", "\n\n", "// we only need to care about the full matches in the remaining lines", "// (no more lines were come, why care about the partial matches?)", "matchMap", ",", "_", ":=", "w", ".", "matchSecrets", "(", "w", ".", "store", ")", "\n", "redactedLines", ":=", "w", ".", "redact", "(", "w", ".", "store", ",", "matchMap", ")", "\n", "w", ".", "store", "=", "nil", "\n\n", "return", "w", ".", "writer", ".", "Write", "(", "bytes", ".", "Join", "(", "redactedLines", ",", "nil", ")", ")", "\n", "}" ]
// Flush writes the remaining bytes.
[ "Flush", "writes", "the", "remaining", "bytes", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L95-L115
153,464
bitrise-io/bitrise
tools/filterwriter/filterwriter.go
linesToKeepRange
func (w *Writer) linesToKeepRange(partialMatchIndexes map[int]bool) int { first := -1 for lineIdx := range partialMatchIndexes { if first == -1 { first = lineIdx continue } if first > lineIdx { first = lineIdx } } return first }
go
func (w *Writer) linesToKeepRange(partialMatchIndexes map[int]bool) int { first := -1 for lineIdx := range partialMatchIndexes { if first == -1 { first = lineIdx continue } if first > lineIdx { first = lineIdx } } return first }
[ "func", "(", "w", "*", "Writer", ")", "linesToKeepRange", "(", "partialMatchIndexes", "map", "[", "int", "]", "bool", ")", "int", "{", "first", ":=", "-", "1", "\n\n", "for", "lineIdx", ":=", "range", "partialMatchIndexes", "{", "if", "first", "==", "-", "1", "{", "first", "=", "lineIdx", "\n", "continue", "\n", "}", "\n\n", "if", "first", ">", "lineIdx", "{", "first", "=", "lineIdx", "\n", "}", "\n", "}", "\n\n", "return", "first", "\n", "}" ]
// linesToKeepRange returns the first line index needs to be observed // since they contain partially matching secrets.
[ "linesToKeepRange", "returns", "the", "first", "line", "index", "needs", "to", "be", "observed", "since", "they", "contain", "partially", "matching", "secrets", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L190-L205
153,465
bitrise-io/bitrise
tools/filterwriter/filterwriter.go
matchLines
func (w *Writer) matchLines(lines [][]byte, partialMatchIndexes map[int]bool) ([][]byte, [][]byte) { first := w.linesToKeepRange(partialMatchIndexes) switch first { case -1: // no lines needs to be kept return lines, nil case 0: // partial match is always longer then the lines return nil, lines default: return lines[:first], lines[first:] } }
go
func (w *Writer) matchLines(lines [][]byte, partialMatchIndexes map[int]bool) ([][]byte, [][]byte) { first := w.linesToKeepRange(partialMatchIndexes) switch first { case -1: // no lines needs to be kept return lines, nil case 0: // partial match is always longer then the lines return nil, lines default: return lines[:first], lines[first:] } }
[ "func", "(", "w", "*", "Writer", ")", "matchLines", "(", "lines", "[", "]", "[", "]", "byte", ",", "partialMatchIndexes", "map", "[", "int", "]", "bool", ")", "(", "[", "]", "[", "]", "byte", ",", "[", "]", "[", "]", "byte", ")", "{", "first", ":=", "w", ".", "linesToKeepRange", "(", "partialMatchIndexes", ")", "\n", "switch", "first", "{", "case", "-", "1", ":", "// no lines needs to be kept", "return", "lines", ",", "nil", "\n", "case", "0", ":", "// partial match is always longer then the lines", "return", "nil", ",", "lines", "\n", "default", ":", "return", "lines", "[", ":", "first", "]", ",", "lines", "[", "first", ":", "]", "\n", "}", "\n", "}" ]
// matchLines return which lines can be printed and which should be kept for further observing.
[ "matchLines", "return", "which", "lines", "can", "be", "printed", "and", "which", "should", "be", "kept", "for", "further", "observing", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L208-L220
153,466
bitrise-io/bitrise
tools/filterwriter/filterwriter.go
secretLinesToRedact
func (w *Writer) secretLinesToRedact(lineIdxToRedact int, matchMap map[int][]int) [][]byte { // which line is which secrets first matching line secretIdxsByLine := make(map[int][]int) for secretIdx, lineIndexes := range matchMap { for _, lineIdx := range lineIndexes { secretIdxsByLine[lineIdx] = append(secretIdxsByLine[lineIdx], secretIdx) } } var secretChunks [][]byte for firstMatchingLineIdx, secretIndexes := range secretIdxsByLine { if lineIdxToRedact < firstMatchingLineIdx { continue } for _, secretIdx := range secretIndexes { secret := w.secrets[secretIdx] if lineIdxToRedact > firstMatchingLineIdx+len(secret)-1 { continue } secretLineIdx := lineIdxToRedact - firstMatchingLineIdx secretChunks = append(secretChunks, secret[secretLineIdx]) } } sort.Slice(secretChunks, func(i, j int) bool { return len(secretChunks[i]) < len(secretChunks[j]) }) return secretChunks }
go
func (w *Writer) secretLinesToRedact(lineIdxToRedact int, matchMap map[int][]int) [][]byte { // which line is which secrets first matching line secretIdxsByLine := make(map[int][]int) for secretIdx, lineIndexes := range matchMap { for _, lineIdx := range lineIndexes { secretIdxsByLine[lineIdx] = append(secretIdxsByLine[lineIdx], secretIdx) } } var secretChunks [][]byte for firstMatchingLineIdx, secretIndexes := range secretIdxsByLine { if lineIdxToRedact < firstMatchingLineIdx { continue } for _, secretIdx := range secretIndexes { secret := w.secrets[secretIdx] if lineIdxToRedact > firstMatchingLineIdx+len(secret)-1 { continue } secretLineIdx := lineIdxToRedact - firstMatchingLineIdx secretChunks = append(secretChunks, secret[secretLineIdx]) } } sort.Slice(secretChunks, func(i, j int) bool { return len(secretChunks[i]) < len(secretChunks[j]) }) return secretChunks }
[ "func", "(", "w", "*", "Writer", ")", "secretLinesToRedact", "(", "lineIdxToRedact", "int", ",", "matchMap", "map", "[", "int", "]", "[", "]", "int", ")", "[", "]", "[", "]", "byte", "{", "// which line is which secrets first matching line", "secretIdxsByLine", ":=", "make", "(", "map", "[", "int", "]", "[", "]", "int", ")", "\n", "for", "secretIdx", ",", "lineIndexes", ":=", "range", "matchMap", "{", "for", "_", ",", "lineIdx", ":=", "range", "lineIndexes", "{", "secretIdxsByLine", "[", "lineIdx", "]", "=", "append", "(", "secretIdxsByLine", "[", "lineIdx", "]", ",", "secretIdx", ")", "\n", "}", "\n", "}", "\n\n", "var", "secretChunks", "[", "]", "[", "]", "byte", "\n", "for", "firstMatchingLineIdx", ",", "secretIndexes", ":=", "range", "secretIdxsByLine", "{", "if", "lineIdxToRedact", "<", "firstMatchingLineIdx", "{", "continue", "\n", "}", "\n\n", "for", "_", ",", "secretIdx", ":=", "range", "secretIndexes", "{", "secret", ":=", "w", ".", "secrets", "[", "secretIdx", "]", "\n\n", "if", "lineIdxToRedact", ">", "firstMatchingLineIdx", "+", "len", "(", "secret", ")", "-", "1", "{", "continue", "\n", "}", "\n\n", "secretLineIdx", ":=", "lineIdxToRedact", "-", "firstMatchingLineIdx", "\n", "secretChunks", "=", "append", "(", "secretChunks", ",", "secret", "[", "secretLineIdx", "]", ")", "\n", "}", "\n", "}", "\n\n", "sort", ".", "Slice", "(", "secretChunks", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "len", "(", "secretChunks", "[", "i", "]", ")", "<", "len", "(", "secretChunks", "[", "j", "]", ")", "}", ")", "\n", "return", "secretChunks", "\n", "}" ]
// secretLinesToRedact returns which secret lines should be redacted
[ "secretLinesToRedact", "returns", "which", "secret", "lines", "should", "be", "redacted" ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L223-L252
153,467
bitrise-io/bitrise
tools/filterwriter/filterwriter.go
redact
func redact(line []byte, ranges []matchRange) []byte { var offset int // the offset of ranges generated by replacing x bytes by the RedactStr for _, r := range ranges { length := r.last - r.first first := r.first + offset last := first + length toRedact := line[first:last] redactStr := RedactStr if bytes.HasSuffix(toRedact, []byte("\n")) { // if string to redact ends with newline redact message should also redactStr += "\n" } newLine := append([]byte{}, line[:first]...) newLine = append(newLine, redactStr...) newLine = append(newLine, line[last:]...) offset += len(redactStr) - length line = newLine } return line }
go
func redact(line []byte, ranges []matchRange) []byte { var offset int // the offset of ranges generated by replacing x bytes by the RedactStr for _, r := range ranges { length := r.last - r.first first := r.first + offset last := first + length toRedact := line[first:last] redactStr := RedactStr if bytes.HasSuffix(toRedact, []byte("\n")) { // if string to redact ends with newline redact message should also redactStr += "\n" } newLine := append([]byte{}, line[:first]...) newLine = append(newLine, redactStr...) newLine = append(newLine, line[last:]...) offset += len(redactStr) - length line = newLine } return line }
[ "func", "redact", "(", "line", "[", "]", "byte", ",", "ranges", "[", "]", "matchRange", ")", "[", "]", "byte", "{", "var", "offset", "int", "// the offset of ranges generated by replacing x bytes by the RedactStr", "\n", "for", "_", ",", "r", ":=", "range", "ranges", "{", "length", ":=", "r", ".", "last", "-", "r", ".", "first", "\n", "first", ":=", "r", ".", "first", "+", "offset", "\n", "last", ":=", "first", "+", "length", "\n\n", "toRedact", ":=", "line", "[", "first", ":", "last", "]", "\n", "redactStr", ":=", "RedactStr", "\n", "if", "bytes", ".", "HasSuffix", "(", "toRedact", ",", "[", "]", "byte", "(", "\"", "\\n", "\"", ")", ")", "{", "// if string to redact ends with newline redact message should also", "redactStr", "+=", "\"", "\\n", "\"", "\n", "}", "\n\n", "newLine", ":=", "append", "(", "[", "]", "byte", "{", "}", ",", "line", "[", ":", "first", "]", "...", ")", "\n", "newLine", "=", "append", "(", "newLine", ",", "redactStr", "...", ")", "\n", "newLine", "=", "append", "(", "newLine", ",", "line", "[", "last", ":", "]", "...", ")", "\n\n", "offset", "+=", "len", "(", "redactStr", ")", "-", "length", "\n\n", "line", "=", "newLine", "\n", "}", "\n", "return", "line", "\n", "}" ]
// redact hides the given ranges in the given line.
[ "redact", "hides", "the", "given", "ranges", "in", "the", "given", "line", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L255-L278
153,468
bitrise-io/bitrise
tools/filterwriter/filterwriter.go
redact
func (w *Writer) redact(lines [][]byte, matchMap map[int][]int) [][]byte { secretIdxsByLine := map[int][]int{} for secretIdx, lineIndexes := range matchMap { for _, lineIdx := range lineIndexes { secretIdxsByLine[lineIdx] = append(secretIdxsByLine[lineIdx], secretIdx) } } for i, line := range lines { linesToRedact := w.secretLinesToRedact(i, matchMap) if linesToRedact == nil { continue } var ranges []matchRange for _, lineToRedact := range linesToRedact { ranges = append(ranges, allRanges(line, lineToRedact)...) } lines[i] = redact(line, mergeAllRanges(ranges)) } return lines }
go
func (w *Writer) redact(lines [][]byte, matchMap map[int][]int) [][]byte { secretIdxsByLine := map[int][]int{} for secretIdx, lineIndexes := range matchMap { for _, lineIdx := range lineIndexes { secretIdxsByLine[lineIdx] = append(secretIdxsByLine[lineIdx], secretIdx) } } for i, line := range lines { linesToRedact := w.secretLinesToRedact(i, matchMap) if linesToRedact == nil { continue } var ranges []matchRange for _, lineToRedact := range linesToRedact { ranges = append(ranges, allRanges(line, lineToRedact)...) } lines[i] = redact(line, mergeAllRanges(ranges)) } return lines }
[ "func", "(", "w", "*", "Writer", ")", "redact", "(", "lines", "[", "]", "[", "]", "byte", ",", "matchMap", "map", "[", "int", "]", "[", "]", "int", ")", "[", "]", "[", "]", "byte", "{", "secretIdxsByLine", ":=", "map", "[", "int", "]", "[", "]", "int", "{", "}", "\n", "for", "secretIdx", ",", "lineIndexes", ":=", "range", "matchMap", "{", "for", "_", ",", "lineIdx", ":=", "range", "lineIndexes", "{", "secretIdxsByLine", "[", "lineIdx", "]", "=", "append", "(", "secretIdxsByLine", "[", "lineIdx", "]", ",", "secretIdx", ")", "\n", "}", "\n", "}", "\n\n", "for", "i", ",", "line", ":=", "range", "lines", "{", "linesToRedact", ":=", "w", ".", "secretLinesToRedact", "(", "i", ",", "matchMap", ")", "\n", "if", "linesToRedact", "==", "nil", "{", "continue", "\n", "}", "\n\n", "var", "ranges", "[", "]", "matchRange", "\n", "for", "_", ",", "lineToRedact", ":=", "range", "linesToRedact", "{", "ranges", "=", "append", "(", "ranges", ",", "allRanges", "(", "line", ",", "lineToRedact", ")", "...", ")", "\n", "}", "\n\n", "lines", "[", "i", "]", "=", "redact", "(", "line", ",", "mergeAllRanges", "(", "ranges", ")", ")", "\n", "}", "\n\n", "return", "lines", "\n", "}" ]
// redact hides the given secrets in the given lines.
[ "redact", "hides", "the", "given", "secrets", "in", "the", "given", "lines", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L281-L304
153,469
bitrise-io/bitrise
tools/filterwriter/filterwriter.go
secretsByteList
func secretsByteList(secrets []string) [][][]byte { var s [][][]byte for _, secret := range secrets { lines, lastLine := splitAfterNewline([]byte(secret)) if lines == nil && lastLine == nil { continue } var secretLines [][]byte if lines != nil { secretLines = append(secretLines, lines...) } if lastLine != nil { secretLines = append(secretLines, lastLine) } s = append(s, secretLines) } return s }
go
func secretsByteList(secrets []string) [][][]byte { var s [][][]byte for _, secret := range secrets { lines, lastLine := splitAfterNewline([]byte(secret)) if lines == nil && lastLine == nil { continue } var secretLines [][]byte if lines != nil { secretLines = append(secretLines, lines...) } if lastLine != nil { secretLines = append(secretLines, lastLine) } s = append(s, secretLines) } return s }
[ "func", "secretsByteList", "(", "secrets", "[", "]", "string", ")", "[", "]", "[", "]", "[", "]", "byte", "{", "var", "s", "[", "]", "[", "]", "[", "]", "byte", "\n", "for", "_", ",", "secret", ":=", "range", "secrets", "{", "lines", ",", "lastLine", ":=", "splitAfterNewline", "(", "[", "]", "byte", "(", "secret", ")", ")", "\n", "if", "lines", "==", "nil", "&&", "lastLine", "==", "nil", "{", "continue", "\n", "}", "\n\n", "var", "secretLines", "[", "]", "[", "]", "byte", "\n", "if", "lines", "!=", "nil", "{", "secretLines", "=", "append", "(", "secretLines", ",", "lines", "...", ")", "\n", "}", "\n", "if", "lastLine", "!=", "nil", "{", "secretLines", "=", "append", "(", "secretLines", ",", "lastLine", ")", "\n", "}", "\n", "s", "=", "append", "(", "s", ",", "secretLines", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// secretsByteList returns the list of secret byte lines.
[ "secretsByteList", "returns", "the", "list", "of", "secret", "byte", "lines", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L307-L325
153,470
bitrise-io/bitrise
tools/filterwriter/filterwriter.go
splitAfterNewline
func splitAfterNewline(p []byte) ([][]byte, []byte) { chunk := p var lines [][]byte for len(chunk) > 0 { idx := bytes.Index(chunk, newLine) if idx == -1 { return lines, chunk } lines = append(lines, chunk[:idx+1]) if idx == len(chunk)-1 { chunk = nil break } chunk = chunk[idx+1:] } return lines, chunk }
go
func splitAfterNewline(p []byte) ([][]byte, []byte) { chunk := p var lines [][]byte for len(chunk) > 0 { idx := bytes.Index(chunk, newLine) if idx == -1 { return lines, chunk } lines = append(lines, chunk[:idx+1]) if idx == len(chunk)-1 { chunk = nil break } chunk = chunk[idx+1:] } return lines, chunk }
[ "func", "splitAfterNewline", "(", "p", "[", "]", "byte", ")", "(", "[", "]", "[", "]", "byte", ",", "[", "]", "byte", ")", "{", "chunk", ":=", "p", "\n", "var", "lines", "[", "]", "[", "]", "byte", "\n\n", "for", "len", "(", "chunk", ")", ">", "0", "{", "idx", ":=", "bytes", ".", "Index", "(", "chunk", ",", "newLine", ")", "\n", "if", "idx", "==", "-", "1", "{", "return", "lines", ",", "chunk", "\n", "}", "\n\n", "lines", "=", "append", "(", "lines", ",", "chunk", "[", ":", "idx", "+", "1", "]", ")", "\n\n", "if", "idx", "==", "len", "(", "chunk", ")", "-", "1", "{", "chunk", "=", "nil", "\n", "break", "\n", "}", "\n\n", "chunk", "=", "chunk", "[", "idx", "+", "1", ":", "]", "\n", "}", "\n\n", "return", "lines", ",", "chunk", "\n", "}" ]
// splitAfterNewline splits p after "\n", the split is assigned to lines // if last line has no "\n" it is assigned to the chunk. // If p is nil both lines and chunk is set to nil.
[ "splitAfterNewline", "splits", "p", "after", "\\", "n", "the", "split", "is", "assigned", "to", "lines", "if", "last", "line", "has", "no", "\\", "n", "it", "is", "assigned", "to", "the", "chunk", ".", "If", "p", "is", "nil", "both", "lines", "and", "chunk", "is", "set", "to", "nil", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L330-L351
153,471
bitrise-io/bitrise
plugins/install.go
isSourceURIChanged
func isSourceURIChanged(installed, new string) bool { if urlsForOrg := func(org string) []string { return []string{ "https://github.com/" + org + "/bitrise-plugins-init.git", "https://github.com/" + org + "/bitrise-plugins-step.git", "https://github.com/" + org + "/bitrise-plugins-analytics.git", } }; (installed == new) || (sliceutil.IsStringInSlice(installed, urlsForOrg("bitrise-core")) && sliceutil.IsStringInSlice(new, urlsForOrg("bitrise-io"))) { return false } return true }
go
func isSourceURIChanged(installed, new string) bool { if urlsForOrg := func(org string) []string { return []string{ "https://github.com/" + org + "/bitrise-plugins-init.git", "https://github.com/" + org + "/bitrise-plugins-step.git", "https://github.com/" + org + "/bitrise-plugins-analytics.git", } }; (installed == new) || (sliceutil.IsStringInSlice(installed, urlsForOrg("bitrise-core")) && sliceutil.IsStringInSlice(new, urlsForOrg("bitrise-io"))) { return false } return true }
[ "func", "isSourceURIChanged", "(", "installed", ",", "new", "string", ")", "bool", "{", "if", "urlsForOrg", ":=", "func", "(", "org", "string", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "\"", "\"", "+", "org", "+", "\"", "\"", ",", "\"", "\"", "+", "org", "+", "\"", "\"", ",", "\"", "\"", "+", "org", "+", "\"", "\"", ",", "}", "\n", "}", ";", "(", "installed", "==", "new", ")", "||", "(", "sliceutil", ".", "IsStringInSlice", "(", "installed", ",", "urlsForOrg", "(", "\"", "\"", ")", ")", "&&", "sliceutil", ".", "IsStringInSlice", "(", "new", ",", "urlsForOrg", "(", "\"", "\"", ")", ")", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// plugins from bitrise-core to bitrise-io GitHub org have been moved // so it is better to not to detect this as a different plugin source
[ "plugins", "from", "bitrise", "-", "core", "to", "bitrise", "-", "io", "GitHub", "org", "have", "been", "moved", "so", "it", "is", "better", "to", "not", "to", "detect", "this", "as", "a", "different", "plugin", "source" ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/plugins/install.go#L103-L115
153,472
bitrise-io/bitrise
tools/tools.go
EnvmanRun
func EnvmanRun(envstorePth, workDirPth string, cmdArgs []string, timeout time.Duration, secrets []envmanModels.EnvironmentItemModel) (int, error) { logLevel := log.GetLevel().String() args := []string{"--loglevel", logLevel, "--path", envstorePth, "run"} args = append(args, cmdArgs...) var outWriter io.Writer var errWriter io.Writer if !configs.IsSecretFiltering { outWriter = os.Stdout errWriter = os.Stderr } else { var secretValues []string for _, secret := range secrets { key, value, err := secret.GetKeyValuePair() if err != nil || len(value) < 1 || IsBuiltInFlagTypeKey(key) { continue } secretValues = append(secretValues, value) } outWriter = filterwriter.New(secretValues, os.Stdout) errWriter = outWriter } cmd := timeoutcmd.New(workDirPth, "envman", args...) cmd.SetStandardIO(os.Stdin, outWriter, errWriter) cmd.SetTimeout(timeout) cmd.AppendEnv("PWD=" + workDirPth) err := cmd.Start() // flush the writer anyway if the process is finished if configs.IsSecretFiltering { _, ferr := (outWriter.(*filterwriter.Writer)).Flush() if ferr != nil { return 1, ferr } } return timeoutcmd.ExitStatus(err), err }
go
func EnvmanRun(envstorePth, workDirPth string, cmdArgs []string, timeout time.Duration, secrets []envmanModels.EnvironmentItemModel) (int, error) { logLevel := log.GetLevel().String() args := []string{"--loglevel", logLevel, "--path", envstorePth, "run"} args = append(args, cmdArgs...) var outWriter io.Writer var errWriter io.Writer if !configs.IsSecretFiltering { outWriter = os.Stdout errWriter = os.Stderr } else { var secretValues []string for _, secret := range secrets { key, value, err := secret.GetKeyValuePair() if err != nil || len(value) < 1 || IsBuiltInFlagTypeKey(key) { continue } secretValues = append(secretValues, value) } outWriter = filterwriter.New(secretValues, os.Stdout) errWriter = outWriter } cmd := timeoutcmd.New(workDirPth, "envman", args...) cmd.SetStandardIO(os.Stdin, outWriter, errWriter) cmd.SetTimeout(timeout) cmd.AppendEnv("PWD=" + workDirPth) err := cmd.Start() // flush the writer anyway if the process is finished if configs.IsSecretFiltering { _, ferr := (outWriter.(*filterwriter.Writer)).Flush() if ferr != nil { return 1, ferr } } return timeoutcmd.ExitStatus(err), err }
[ "func", "EnvmanRun", "(", "envstorePth", ",", "workDirPth", "string", ",", "cmdArgs", "[", "]", "string", ",", "timeout", "time", ".", "Duration", ",", "secrets", "[", "]", "envmanModels", ".", "EnvironmentItemModel", ")", "(", "int", ",", "error", ")", "{", "logLevel", ":=", "log", ".", "GetLevel", "(", ")", ".", "String", "(", ")", "\n", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "logLevel", ",", "\"", "\"", ",", "envstorePth", ",", "\"", "\"", "}", "\n", "args", "=", "append", "(", "args", ",", "cmdArgs", "...", ")", "\n\n", "var", "outWriter", "io", ".", "Writer", "\n", "var", "errWriter", "io", ".", "Writer", "\n\n", "if", "!", "configs", ".", "IsSecretFiltering", "{", "outWriter", "=", "os", ".", "Stdout", "\n", "errWriter", "=", "os", ".", "Stderr", "\n", "}", "else", "{", "var", "secretValues", "[", "]", "string", "\n", "for", "_", ",", "secret", ":=", "range", "secrets", "{", "key", ",", "value", ",", "err", ":=", "secret", ".", "GetKeyValuePair", "(", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "value", ")", "<", "1", "||", "IsBuiltInFlagTypeKey", "(", "key", ")", "{", "continue", "\n", "}", "\n", "secretValues", "=", "append", "(", "secretValues", ",", "value", ")", "\n", "}", "\n\n", "outWriter", "=", "filterwriter", ".", "New", "(", "secretValues", ",", "os", ".", "Stdout", ")", "\n", "errWriter", "=", "outWriter", "\n", "}", "\n\n", "cmd", ":=", "timeoutcmd", ".", "New", "(", "workDirPth", ",", "\"", "\"", ",", "args", "...", ")", "\n", "cmd", ".", "SetStandardIO", "(", "os", ".", "Stdin", ",", "outWriter", ",", "errWriter", ")", "\n", "cmd", ".", "SetTimeout", "(", "timeout", ")", "\n", "cmd", ".", "AppendEnv", "(", "\"", "\"", "+", "workDirPth", ")", "\n\n", "err", ":=", "cmd", ".", "Start", "(", ")", "\n\n", "// flush the writer anyway if the process is finished", "if", "configs", ".", "IsSecretFiltering", "{", "_", ",", "ferr", ":=", "(", "outWriter", ".", "(", "*", "filterwriter", ".", "Writer", ")", ")", ".", "Flush", "(", ")", "\n", "if", "ferr", "!=", "nil", "{", "return", "1", ",", "ferr", "\n", "}", "\n", "}", "\n\n", "return", "timeoutcmd", ".", "ExitStatus", "(", "err", ")", ",", "err", "\n", "}" ]
// EnvmanRun runs a command through envman.
[ "EnvmanRun", "runs", "a", "command", "through", "envman", "." ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/tools.go#L342-L383
153,473
bitrise-io/bitrise
tools/tools.go
IsBuiltInFlagTypeKey
func IsBuiltInFlagTypeKey(env string) bool { switch string(env) { case configs.IsSecretFilteringKey, configs.CIModeEnvKey, configs.PRModeEnvKey, configs.DebugModeEnvKey, configs.LogLevelEnvKey, configs.PullRequestIDEnvKey: return true default: return false } }
go
func IsBuiltInFlagTypeKey(env string) bool { switch string(env) { case configs.IsSecretFilteringKey, configs.CIModeEnvKey, configs.PRModeEnvKey, configs.DebugModeEnvKey, configs.LogLevelEnvKey, configs.PullRequestIDEnvKey: return true default: return false } }
[ "func", "IsBuiltInFlagTypeKey", "(", "env", "string", ")", "bool", "{", "switch", "string", "(", "env", ")", "{", "case", "configs", ".", "IsSecretFilteringKey", ",", "configs", ".", "CIModeEnvKey", ",", "configs", ".", "PRModeEnvKey", ",", "configs", ".", "DebugModeEnvKey", ",", "configs", ".", "LogLevelEnvKey", ",", "configs", ".", "PullRequestIDEnvKey", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsBuiltInFlagTypeKey returns true if the env key is a built-in flag type env key
[ "IsBuiltInFlagTypeKey", "returns", "true", "if", "the", "env", "key", "is", "a", "built", "-", "in", "flag", "type", "env", "key" ]
2ec917b478fe766c026ba3e78954db0f6b3954d4
https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/tools.go#L432-L444
153,474
mozilla/tls-observatory
database/certificate.go
UpdateCertificateRank
func (db *DB) UpdateCertificateRank(id, rank int64) error { _, err := db.Exec("UPDATE certificates SET cisco_umbrella_rank=$1 WHERE id=$2", rank, id) return err }
go
func (db *DB) UpdateCertificateRank(id, rank int64) error { _, err := db.Exec("UPDATE certificates SET cisco_umbrella_rank=$1 WHERE id=$2", rank, id) return err }
[ "func", "(", "db", "*", "DB", ")", "UpdateCertificateRank", "(", "id", ",", "rank", "int64", ")", "error", "{", "_", ",", "err", ":=", "db", ".", "Exec", "(", "\"", "\"", ",", "rank", ",", "id", ")", "\n", "return", "err", "\n", "}" ]
// UpdateCertificateRank updates the rank integer of the input certificate.
[ "UpdateCertificateRank", "updates", "the", "rank", "integer", "of", "the", "input", "certificate", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L350-L353
153,475
mozilla/tls-observatory
database/certificate.go
UpdateCertLastSeen
func (db *DB) UpdateCertLastSeen(cert *certificate.Certificate) error { _, err := db.Exec("UPDATE certificates SET last_seen=$1 WHERE sha1_fingerprint=$2", cert.LastSeenTimestamp, cert.Hashes.SHA1) return err }
go
func (db *DB) UpdateCertLastSeen(cert *certificate.Certificate) error { _, err := db.Exec("UPDATE certificates SET last_seen=$1 WHERE sha1_fingerprint=$2", cert.LastSeenTimestamp, cert.Hashes.SHA1) return err }
[ "func", "(", "db", "*", "DB", ")", "UpdateCertLastSeen", "(", "cert", "*", "certificate", ".", "Certificate", ")", "error", "{", "_", ",", "err", ":=", "db", ".", "Exec", "(", "\"", "\"", ",", "cert", ".", "LastSeenTimestamp", ",", "cert", ".", "Hashes", ".", "SHA1", ")", "\n", "return", "err", "\n", "}" ]
// UpdateCertLastSeen updates the last_seen timestamp of the input certificate. // Outputs an error if it occurs.
[ "UpdateCertLastSeen", "updates", "the", "last_seen", "timestamp", "of", "the", "input", "certificate", ".", "Outputs", "an", "error", "if", "it", "occurs", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L357-L361
153,476
mozilla/tls-observatory
database/certificate.go
UpdateCertLastSeenByID
func (db *DB) UpdateCertLastSeenByID(id int64) error { _, err := db.Exec("UPDATE certificates SET last_seen=$1 WHERE id=$2", time.Now(), id) return err }
go
func (db *DB) UpdateCertLastSeenByID(id int64) error { _, err := db.Exec("UPDATE certificates SET last_seen=$1 WHERE id=$2", time.Now(), id) return err }
[ "func", "(", "db", "*", "DB", ")", "UpdateCertLastSeenByID", "(", "id", "int64", ")", "error", "{", "_", ",", "err", ":=", "db", ".", "Exec", "(", "\"", "\"", ",", "time", ".", "Now", "(", ")", ",", "id", ")", "\n", "return", "err", "\n", "}" ]
// UpdateCertLastSeenWithID updates the last_seen timestamp of the certificate with the given id. // Outputs an error if it occurs.
[ "UpdateCertLastSeenWithID", "updates", "the", "last_seen", "timestamp", "of", "the", "certificate", "with", "the", "given", "id", ".", "Outputs", "an", "error", "if", "it", "occurs", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L365-L368
153,477
mozilla/tls-observatory
database/certificate.go
RemoveCACertFromTruststore
func (db *DB) RemoveCACertFromTruststore(trustedCerts []string, tsName string) error { if len(trustedCerts) == 0 { return errors.New("Cannot work with empty list of trusted certs") } tsVariable := "" switch tsName { case certificate.Ubuntu_TS_name: tsVariable = "in_ubuntu_root_store" case certificate.Mozilla_TS_name: tsVariable = "in_mozilla_root_store" case certificate.Microsoft_TS_name: tsVariable = "in_microsoft_root_store" case certificate.Apple_TS_name: tsVariable = "in_apple_root_store" case certificate.Android_TS_name: tsVariable = "in_android_root_store" default: return errors.New(fmt.Sprintf("Cannot update DB, %s does not represent a valid truststore name.", tsName)) } var fps string for _, fp := range trustedCerts { if len(fps) > 1 { fps += "," } fps += "'" + fp + "'" } q := fmt.Sprintf(`UPDATE certificates SET %s='false', last_seen=NOW() WHERE %s='true' AND sha256_fingerprint NOT IN (%s)`, tsVariable, tsVariable, fps) _, err := db.Exec(q) return err }
go
func (db *DB) RemoveCACertFromTruststore(trustedCerts []string, tsName string) error { if len(trustedCerts) == 0 { return errors.New("Cannot work with empty list of trusted certs") } tsVariable := "" switch tsName { case certificate.Ubuntu_TS_name: tsVariable = "in_ubuntu_root_store" case certificate.Mozilla_TS_name: tsVariable = "in_mozilla_root_store" case certificate.Microsoft_TS_name: tsVariable = "in_microsoft_root_store" case certificate.Apple_TS_name: tsVariable = "in_apple_root_store" case certificate.Android_TS_name: tsVariable = "in_android_root_store" default: return errors.New(fmt.Sprintf("Cannot update DB, %s does not represent a valid truststore name.", tsName)) } var fps string for _, fp := range trustedCerts { if len(fps) > 1 { fps += "," } fps += "'" + fp + "'" } q := fmt.Sprintf(`UPDATE certificates SET %s='false', last_seen=NOW() WHERE %s='true' AND sha256_fingerprint NOT IN (%s)`, tsVariable, tsVariable, fps) _, err := db.Exec(q) return err }
[ "func", "(", "db", "*", "DB", ")", "RemoveCACertFromTruststore", "(", "trustedCerts", "[", "]", "string", ",", "tsName", "string", ")", "error", "{", "if", "len", "(", "trustedCerts", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "tsVariable", ":=", "\"", "\"", "\n", "switch", "tsName", "{", "case", "certificate", ".", "Ubuntu_TS_name", ":", "tsVariable", "=", "\"", "\"", "\n", "case", "certificate", ".", "Mozilla_TS_name", ":", "tsVariable", "=", "\"", "\"", "\n", "case", "certificate", ".", "Microsoft_TS_name", ":", "tsVariable", "=", "\"", "\"", "\n", "case", "certificate", ".", "Apple_TS_name", ":", "tsVariable", "=", "\"", "\"", "\n", "case", "certificate", ".", "Android_TS_name", ":", "tsVariable", "=", "\"", "\"", "\n", "default", ":", "return", "errors", ".", "New", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "tsName", ")", ")", "\n", "}", "\n", "var", "fps", "string", "\n", "for", "_", ",", "fp", ":=", "range", "trustedCerts", "{", "if", "len", "(", "fps", ")", ">", "1", "{", "fps", "+=", "\"", "\"", "\n", "}", "\n", "fps", "+=", "\"", "\"", "+", "fp", "+", "\"", "\"", "\n", "}", "\n", "q", ":=", "fmt", ".", "Sprintf", "(", "`UPDATE certificates SET %s='false', last_seen=NOW() WHERE %s='true' AND sha256_fingerprint NOT IN (%s)`", ",", "tsVariable", ",", "tsVariable", ",", "fps", ")", "\n", "_", ",", "err", ":=", "db", ".", "Exec", "(", "q", ")", "\n", "return", "err", "\n", "}" ]
// RemoveCACertFromTruststore takes a list of hashes from certs trusted by a given truststore and disables // the trust of all certs not listed but trusted in DB
[ "RemoveCACertFromTruststore", "takes", "a", "list", "of", "hashes", "from", "certs", "trusted", "by", "a", "given", "truststore", "and", "disables", "the", "trust", "of", "all", "certs", "not", "listed", "but", "trusted", "in", "DB" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L402-L432
153,478
mozilla/tls-observatory
database/certificate.go
GetCertIDBySHA1Fingerprint
func (db *DB) GetCertIDBySHA1Fingerprint(sha1 string) (id int64, err error) { id = -1 err = db.QueryRow(`SELECT id FROM certificates WHERE sha1_fingerprint=upper($1) ORDER BY id ASC LIMIT 1`, sha1).Scan(&id) if err == sql.ErrNoRows { return -1, nil } return }
go
func (db *DB) GetCertIDBySHA1Fingerprint(sha1 string) (id int64, err error) { id = -1 err = db.QueryRow(`SELECT id FROM certificates WHERE sha1_fingerprint=upper($1) ORDER BY id ASC LIMIT 1`, sha1).Scan(&id) if err == sql.ErrNoRows { return -1, nil } return }
[ "func", "(", "db", "*", "DB", ")", "GetCertIDBySHA1Fingerprint", "(", "sha1", "string", ")", "(", "id", "int64", ",", "err", "error", ")", "{", "id", "=", "-", "1", "\n", "err", "=", "db", ".", "QueryRow", "(", "`SELECT id\n\t\t\t\t FROM certificates\n\t\t\t\t WHERE sha1_fingerprint=upper($1)\n\t\t\t\t ORDER BY id ASC LIMIT 1`", ",", "sha1", ")", ".", "Scan", "(", "&", "id", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "-", "1", ",", "nil", "\n", "}", "\n", "return", "\n", "}" ]
// GetCertIDWithSHA1Fingerprint fetches the database id of the certificate with the given SHA1 fingerprint. // Returns the mentioned id and any errors that happen. // It wraps the sql.ErrNoRows error in order to avoid passing not existing row errors to upper levels. // In that case it returns -1 with no error.
[ "GetCertIDWithSHA1Fingerprint", "fetches", "the", "database", "id", "of", "the", "certificate", "with", "the", "given", "SHA1", "fingerprint", ".", "Returns", "the", "mentioned", "id", "and", "any", "errors", "that", "happen", ".", "It", "wraps", "the", "sql", ".", "ErrNoRows", "error", "in", "order", "to", "avoid", "passing", "not", "existing", "row", "errors", "to", "upper", "levels", ".", "In", "that", "case", "it", "returns", "-", "1", "with", "no", "error", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L438-L449
153,479
mozilla/tls-observatory
database/certificate.go
GetCertIDBySHA256Fingerprint
func (db *DB) GetCertIDBySHA256Fingerprint(sha256 string) (id int64, err error) { id = -1 err = db.QueryRow(`SELECT id FROM certificates WHERE sha256_fingerprint=upper($1) ORDER BY id ASC LIMIT 1`, strings.ToUpper(sha256)).Scan(&id) if err == sql.ErrNoRows { return -1, nil } return }
go
func (db *DB) GetCertIDBySHA256Fingerprint(sha256 string) (id int64, err error) { id = -1 err = db.QueryRow(`SELECT id FROM certificates WHERE sha256_fingerprint=upper($1) ORDER BY id ASC LIMIT 1`, strings.ToUpper(sha256)).Scan(&id) if err == sql.ErrNoRows { return -1, nil } return }
[ "func", "(", "db", "*", "DB", ")", "GetCertIDBySHA256Fingerprint", "(", "sha256", "string", ")", "(", "id", "int64", ",", "err", "error", ")", "{", "id", "=", "-", "1", "\n", "err", "=", "db", ".", "QueryRow", "(", "`SELECT id\n\t\t\t\t FROM certificates\n\t\t\t\t WHERE sha256_fingerprint=upper($1)\n\t\t\t\t ORDER BY id ASC LIMIT 1`", ",", "strings", ".", "ToUpper", "(", "sha256", ")", ")", ".", "Scan", "(", "&", "id", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "-", "1", ",", "nil", "\n", "}", "\n", "return", "\n", "}" ]
// GetCertIDWithSHA256Fingerprint fetches the database id of the certificate with the given SHA256 fingerprint. // Returns the mentioned id and any errors that happen. // It wraps the sql.ErrNoRows error in order to avoid passing not existing row errors to upper levels. // In that case it returns -1 with no error.
[ "GetCertIDWithSHA256Fingerprint", "fetches", "the", "database", "id", "of", "the", "certificate", "with", "the", "given", "SHA256", "fingerprint", ".", "Returns", "the", "mentioned", "id", "and", "any", "errors", "that", "happen", ".", "It", "wraps", "the", "sql", ".", "ErrNoRows", "error", "in", "order", "to", "avoid", "passing", "not", "existing", "row", "errors", "to", "upper", "levels", ".", "In", "that", "case", "it", "returns", "-", "1", "with", "no", "error", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L455-L466
153,480
mozilla/tls-observatory
database/certificate.go
GetCertIDFromTrust
func (db *DB) GetCertIDFromTrust(trustID int64) (id int64, err error) { id = -1 err = db.QueryRow("SELECT cert_id FROM trust WHERE id=$1", trustID).Scan(&id) if err == sql.ErrNoRows { return -1, nil } return }
go
func (db *DB) GetCertIDFromTrust(trustID int64) (id int64, err error) { id = -1 err = db.QueryRow("SELECT cert_id FROM trust WHERE id=$1", trustID).Scan(&id) if err == sql.ErrNoRows { return -1, nil } return }
[ "func", "(", "db", "*", "DB", ")", "GetCertIDFromTrust", "(", "trustID", "int64", ")", "(", "id", "int64", ",", "err", "error", ")", "{", "id", "=", "-", "1", "\n", "err", "=", "db", ".", "QueryRow", "(", "\"", "\"", ",", "trustID", ")", ".", "Scan", "(", "&", "id", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "-", "1", ",", "nil", "\n", "}", "\n", "return", "\n", "}" ]
// GetCertIDFromTrust fetches the database id of the certificate in the trust relation with the given id. // Returns the mentioned id and any errors that happen. // It wraps the sql.ErrNoRows error in order to avoid passing not existing row errors to upper levels. // In that case it returns -1 with no error.
[ "GetCertIDFromTrust", "fetches", "the", "database", "id", "of", "the", "certificate", "in", "the", "trust", "relation", "with", "the", "given", "id", ".", "Returns", "the", "mentioned", "id", "and", "any", "errors", "that", "happen", ".", "It", "wraps", "the", "sql", ".", "ErrNoRows", "error", "in", "order", "to", "avoid", "passing", "not", "existing", "row", "errors", "to", "upper", "levels", ".", "In", "that", "case", "it", "returns", "-", "1", "with", "no", "error", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L472-L479
153,481
mozilla/tls-observatory
database/certificate.go
GetCertByID
func (db *DB) GetCertByID(certID int64) (*certificate.Certificate, error) { row := db.QueryRow(`SELECT `+strings.Join(allCertificateColumns, ", ")+` FROM certificates WHERE id=$1`, certID) cert, err := db.scanCert(row) return &cert, err }
go
func (db *DB) GetCertByID(certID int64) (*certificate.Certificate, error) { row := db.QueryRow(`SELECT `+strings.Join(allCertificateColumns, ", ")+` FROM certificates WHERE id=$1`, certID) cert, err := db.scanCert(row) return &cert, err }
[ "func", "(", "db", "*", "DB", ")", "GetCertByID", "(", "certID", "int64", ")", "(", "*", "certificate", ".", "Certificate", ",", "error", ")", "{", "row", ":=", "db", ".", "QueryRow", "(", "`SELECT `", "+", "strings", ".", "Join", "(", "allCertificateColumns", ",", "\"", "\"", ")", "+", "`\n\t\tFROM certificates WHERE id=$1`", ",", "certID", ")", "\n", "cert", ",", "err", ":=", "db", ".", "scanCert", "(", "row", ")", "\n", "return", "&", "cert", ",", "err", "\n\n", "}" ]
// GetCertByID fetches a certain certificate from the database. // It returns a pointer to a Certificate struct and any errors that occur.
[ "GetCertByID", "fetches", "a", "certain", "certificate", "from", "the", "database", ".", "It", "returns", "a", "pointer", "to", "a", "Certificate", "struct", "and", "any", "errors", "that", "occur", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L580-L586
153,482
mozilla/tls-observatory
database/certificate.go
GetEECountForIssuerByID
func (db *DB) GetEECountForIssuerByID(certID int64) (count int64, err error) { count = -1 err = db.QueryRow(` WITH RECURSIVE issued_by(cert_id, issuer_id) AS ( SELECT DISTINCT cert_id, issuer_id FROM trust WHERE issuer_id = $1 AND cert_id != issuer_id UNION ALL SELECT trust.cert_id, trust.issuer_id FROM trust JOIN issued_by ON (trust.issuer_id = issued_by.cert_id) ) SELECT count(id) FROM certificates WHERE id IN ( SELECT DISTINCT cert_id FROM issued_by ) AND is_ca = false AND not_valid_after > NOW() AND not_valid_before < NOW()`, certID).Scan(&count) return }
go
func (db *DB) GetEECountForIssuerByID(certID int64) (count int64, err error) { count = -1 err = db.QueryRow(` WITH RECURSIVE issued_by(cert_id, issuer_id) AS ( SELECT DISTINCT cert_id, issuer_id FROM trust WHERE issuer_id = $1 AND cert_id != issuer_id UNION ALL SELECT trust.cert_id, trust.issuer_id FROM trust JOIN issued_by ON (trust.issuer_id = issued_by.cert_id) ) SELECT count(id) FROM certificates WHERE id IN ( SELECT DISTINCT cert_id FROM issued_by ) AND is_ca = false AND not_valid_after > NOW() AND not_valid_before < NOW()`, certID).Scan(&count) return }
[ "func", "(", "db", "*", "DB", ")", "GetEECountForIssuerByID", "(", "certID", "int64", ")", "(", "count", "int64", ",", "err", "error", ")", "{", "count", "=", "-", "1", "\n", "err", "=", "db", ".", "QueryRow", "(", "`\nWITH RECURSIVE issued_by(cert_id, issuer_id) AS (\n\tSELECT DISTINCT cert_id, issuer_id\n\tFROM trust\n\tWHERE issuer_id = $1\n\tAND cert_id != issuer_id\n\tUNION ALL\n\t\tSELECT trust.cert_id, trust.issuer_id\n\t\tFROM trust\n\t\tJOIN issued_by\n\t\tON (trust.issuer_id = issued_by.cert_id)\n)\nSELECT count(id) FROM certificates WHERE id IN (\n\tSELECT DISTINCT cert_id FROM issued_by\n) AND is_ca = false\nAND not_valid_after > NOW()\nAND not_valid_before < NOW()`", ",", "certID", ")", ".", "Scan", "(", "&", "count", ")", "\n", "return", "\n", "}" ]
// GetEECountForIssuerByID gets the count of valid end entity certificates in the // database that chain to the certificate with the specified ID
[ "GetEECountForIssuerByID", "gets", "the", "count", "of", "valid", "end", "entity", "certificates", "in", "the", "database", "that", "chain", "to", "the", "certificate", "with", "the", "specified", "ID" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L619-L639
153,483
mozilla/tls-observatory
database/certificate.go
GetCertBySHA1Fingerprint
func (db *DB) GetCertBySHA1Fingerprint(sha1 string) (*certificate.Certificate, error) { var id int64 = -1 cert := &certificate.Certificate{} err := db.QueryRow(`SELECT id FROM certificates WHERE sha1_fingerprint=$1`, sha1).Scan(&id) if err == sql.ErrNoRows { return cert, err } return db.GetCertByID(id) }
go
func (db *DB) GetCertBySHA1Fingerprint(sha1 string) (*certificate.Certificate, error) { var id int64 = -1 cert := &certificate.Certificate{} err := db.QueryRow(`SELECT id FROM certificates WHERE sha1_fingerprint=$1`, sha1).Scan(&id) if err == sql.ErrNoRows { return cert, err } return db.GetCertByID(id) }
[ "func", "(", "db", "*", "DB", ")", "GetCertBySHA1Fingerprint", "(", "sha1", "string", ")", "(", "*", "certificate", ".", "Certificate", ",", "error", ")", "{", "var", "id", "int64", "=", "-", "1", "\n", "cert", ":=", "&", "certificate", ".", "Certificate", "{", "}", "\n", "err", ":=", "db", ".", "QueryRow", "(", "`SELECT id FROM certificates WHERE sha1_fingerprint=$1`", ",", "sha1", ")", ".", "Scan", "(", "&", "id", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "cert", ",", "err", "\n", "}", "\n", "return", "db", ".", "GetCertByID", "(", "id", ")", "\n", "}" ]
// GetCertBySHA1Fingerprint fetches a certain certificate from the database. // It returns a pointer to a Certificate struct and any errors that occur.
[ "GetCertBySHA1Fingerprint", "fetches", "a", "certain", "certificate", "from", "the", "database", ".", "It", "returns", "a", "pointer", "to", "a", "Certificate", "struct", "and", "any", "errors", "that", "occur", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L643-L651
153,484
mozilla/tls-observatory
database/certificate.go
GetCACertsBySubject
func (db *DB) GetCACertsBySubject(subject certificate.Subject) (certs []*certificate.Certificate, err error) { // we must remove the ID before looking for the cert in database subject.ID = 0 subjectJson, err := json.Marshal(subject) if err != nil { return } rows, err := db.Query(`SELECT `+strings.Join(allCertificateColumns, ", ")+` FROM certificates WHERE is_ca='true' AND subject=$1`, subjectJson) if rows != nil { defer rows.Close() } if err == sql.ErrNoRows { return } if err != nil && err != sql.ErrNoRows { err = fmt.Errorf("Error while getting certificates by subject: '%v'", err) return } for rows.Next() { var ( cert certificate.Certificate ) cert, err = db.scanCert(rows) if err != nil { return } certs = append(certs, &cert) } if err := rows.Err(); err != nil { err = fmt.Errorf("Failed to complete database query: '%v'", err) } return }
go
func (db *DB) GetCACertsBySubject(subject certificate.Subject) (certs []*certificate.Certificate, err error) { // we must remove the ID before looking for the cert in database subject.ID = 0 subjectJson, err := json.Marshal(subject) if err != nil { return } rows, err := db.Query(`SELECT `+strings.Join(allCertificateColumns, ", ")+` FROM certificates WHERE is_ca='true' AND subject=$1`, subjectJson) if rows != nil { defer rows.Close() } if err == sql.ErrNoRows { return } if err != nil && err != sql.ErrNoRows { err = fmt.Errorf("Error while getting certificates by subject: '%v'", err) return } for rows.Next() { var ( cert certificate.Certificate ) cert, err = db.scanCert(rows) if err != nil { return } certs = append(certs, &cert) } if err := rows.Err(); err != nil { err = fmt.Errorf("Failed to complete database query: '%v'", err) } return }
[ "func", "(", "db", "*", "DB", ")", "GetCACertsBySubject", "(", "subject", "certificate", ".", "Subject", ")", "(", "certs", "[", "]", "*", "certificate", ".", "Certificate", ",", "err", "error", ")", "{", "// we must remove the ID before looking for the cert in database", "subject", ".", "ID", "=", "0", "\n", "subjectJson", ",", "err", ":=", "json", ".", "Marshal", "(", "subject", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "rows", ",", "err", ":=", "db", ".", "Query", "(", "`SELECT `", "+", "strings", ".", "Join", "(", "allCertificateColumns", ",", "\"", "\"", ")", "+", "`\n FROM certificates WHERE is_ca='true' AND subject=$1`", ",", "subjectJson", ")", "\n", "if", "rows", "!=", "nil", "{", "defer", "rows", ".", "Close", "(", ")", "\n", "}", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "\n", "}", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "sql", ".", "ErrNoRows", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "for", "rows", ".", "Next", "(", ")", "{", "var", "(", "cert", "certificate", ".", "Certificate", "\n", ")", "\n", "cert", ",", "err", "=", "db", ".", "scanCert", "(", "rows", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "certs", "=", "append", "(", "certs", ",", "&", "cert", ")", "\n", "}", "\n", "if", "err", ":=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}" ]
// GetCACertsBySubject returns a list of CA certificates that match a given subject
[ "GetCACertsBySubject", "returns", "a", "list", "of", "CA", "certificates", "that", "match", "a", "given", "subject" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L654-L687
153,485
mozilla/tls-observatory
database/certificate.go
GetCertPaths
func (db *DB) GetCertPaths(cert *certificate.Certificate) (paths certificate.Paths, err error) { // check if we have a path in the cache if paths, ok := db.paths.Get(cert.Issuer.String()); ok { // the end-entity in the cache is likely another cert, so replace // it with the current one newpaths := paths.(certificate.Paths) newpaths.Cert = cert return newpaths, nil } // nothing in the cache, go to the database, recursively var ancestors []string paths, err = db.getCertPaths(cert, ancestors) if err != nil { return } // add the path into the cache db.paths.Add(cert.Issuer.String(), paths) return }
go
func (db *DB) GetCertPaths(cert *certificate.Certificate) (paths certificate.Paths, err error) { // check if we have a path in the cache if paths, ok := db.paths.Get(cert.Issuer.String()); ok { // the end-entity in the cache is likely another cert, so replace // it with the current one newpaths := paths.(certificate.Paths) newpaths.Cert = cert return newpaths, nil } // nothing in the cache, go to the database, recursively var ancestors []string paths, err = db.getCertPaths(cert, ancestors) if err != nil { return } // add the path into the cache db.paths.Add(cert.Issuer.String(), paths) return }
[ "func", "(", "db", "*", "DB", ")", "GetCertPaths", "(", "cert", "*", "certificate", ".", "Certificate", ")", "(", "paths", "certificate", ".", "Paths", ",", "err", "error", ")", "{", "// check if we have a path in the cache", "if", "paths", ",", "ok", ":=", "db", ".", "paths", ".", "Get", "(", "cert", ".", "Issuer", ".", "String", "(", ")", ")", ";", "ok", "{", "// the end-entity in the cache is likely another cert, so replace", "// it with the current one", "newpaths", ":=", "paths", ".", "(", "certificate", ".", "Paths", ")", "\n", "newpaths", ".", "Cert", "=", "cert", "\n", "return", "newpaths", ",", "nil", "\n", "}", "\n", "// nothing in the cache, go to the database, recursively", "var", "ancestors", "[", "]", "string", "\n", "paths", ",", "err", "=", "db", ".", "getCertPaths", "(", "cert", ",", "ancestors", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "// add the path into the cache", "db", ".", "paths", ".", "Add", "(", "cert", ".", "Issuer", ".", "String", "(", ")", ",", "paths", ")", "\n", "return", "\n", "}" ]
// GetCertPaths returns the various certificates paths from the current cert to roots. // It takes a certificate as argument that will be used as the start of the path.
[ "GetCertPaths", "returns", "the", "various", "certificates", "paths", "from", "the", "current", "cert", "to", "roots", ".", "It", "takes", "a", "certificate", "as", "argument", "that", "will", "be", "used", "as", "the", "start", "of", "the", "path", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L819-L837
153,486
mozilla/tls-observatory
database/certificate.go
IsTrustValid
func (db *DB) IsTrustValid(id int64) (bool, error) { row := db.QueryRow(`SELECT trusted_ubuntu OR trusted_mozilla OR trusted_microsoft OR trusted_apple OR trusted_android FROM trust WHERE id=$1`, id) isValid := false err := row.Scan(&isValid) return isValid, err }
go
func (db *DB) IsTrustValid(id int64) (bool, error) { row := db.QueryRow(`SELECT trusted_ubuntu OR trusted_mozilla OR trusted_microsoft OR trusted_apple OR trusted_android FROM trust WHERE id=$1`, id) isValid := false err := row.Scan(&isValid) return isValid, err }
[ "func", "(", "db", "*", "DB", ")", "IsTrustValid", "(", "id", "int64", ")", "(", "bool", ",", "error", ")", "{", "row", ":=", "db", ".", "QueryRow", "(", "`SELECT trusted_ubuntu OR\n\t\t\t\t trusted_mozilla OR\n\t\t\t\t trusted_microsoft OR\n\t\t\t\t trusted_apple OR\n\t\t\t\t trusted_android\n\t\t\t FROM trust WHERE id=$1`", ",", "id", ")", "\n", "isValid", ":=", "false", "\n", "err", ":=", "row", ".", "Scan", "(", "&", "isValid", ")", "\n", "return", "isValid", ",", "err", "\n", "}" ]
// IsTrustValid returns the validity of the trust relationship for the given id. // It returns a "valid" if any of the per truststore valitities is valid // It returns a boolean that represent if trust is valid or not.
[ "IsTrustValid", "returns", "the", "validity", "of", "the", "trust", "relationship", "for", "the", "given", "id", ".", "It", "returns", "a", "valid", "if", "any", "of", "the", "per", "truststore", "valitities", "is", "valid", "It", "returns", "a", "boolean", "that", "represent", "if", "trust", "is", "valid", "or", "not", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/certificate.go#L896-L906
153,487
mozilla/tls-observatory
worker/symantecDistrust/symantecDistrust.go
evalPaths
func evalPaths(paths certificate.Paths) (distrust bool, reasons []string) { // assume distrust and change that if we find a trusted path distrust = true x509Cert, _ := paths.Cert.ToX509() spkihash := certificate.SPKISHA256(x509Cert) if evalBlacklist(spkihash) { reason := fmt.Sprintf("path uses a blacklisted cert: %s (id=%d)", paths.Cert.Subject.String(), paths.Cert.ID) if !alreadyPresent(reason, reasons) { reasons = append(reasons, reason) } return } if len(paths.Parents) == 0 { // if is not directly distrusted and doesn't have any parent, set distrust to false distrust = false return } for _, parent := range paths.Parents { theirDistrust, theirReasons := evalPaths(parent) for _, theirReason := range theirReasons { if !alreadyPresent(theirReason, reasons) { reasons = append(reasons, theirReason) } } if theirDistrust { // if the parent is distrusted, check if the current cert is whitelisted, // and if so, override the distrust decision if evalWhitelist(spkihash) { distrust = false reason := fmt.Sprintf("whitelisted intermediate %s (id=%d) override blacklisting of %d", paths.Cert.Subject.String(), paths.Cert.ID, parent.Cert.ID) if !alreadyPresent(reason, reasons) { reasons = append(reasons, reason) } } } else { // when the parent is a root that is not blacklisted, but it isn't trusted by mozilla, // then flag the chain as distrusted anyway if parent.Cert.CA && len(parent.Parents) == 0 && !parent.Cert.ValidationInfo["Mozilla"].IsValid { reason := fmt.Sprintf("path uses a root not trusted by Mozilla: %s (id=%d)", parent.Cert.Subject.String(), parent.Cert.ID) if !alreadyPresent(reason, reasons) { reasons = append(reasons, reason) } } else { distrust = false } } } return }
go
func evalPaths(paths certificate.Paths) (distrust bool, reasons []string) { // assume distrust and change that if we find a trusted path distrust = true x509Cert, _ := paths.Cert.ToX509() spkihash := certificate.SPKISHA256(x509Cert) if evalBlacklist(spkihash) { reason := fmt.Sprintf("path uses a blacklisted cert: %s (id=%d)", paths.Cert.Subject.String(), paths.Cert.ID) if !alreadyPresent(reason, reasons) { reasons = append(reasons, reason) } return } if len(paths.Parents) == 0 { // if is not directly distrusted and doesn't have any parent, set distrust to false distrust = false return } for _, parent := range paths.Parents { theirDistrust, theirReasons := evalPaths(parent) for _, theirReason := range theirReasons { if !alreadyPresent(theirReason, reasons) { reasons = append(reasons, theirReason) } } if theirDistrust { // if the parent is distrusted, check if the current cert is whitelisted, // and if so, override the distrust decision if evalWhitelist(spkihash) { distrust = false reason := fmt.Sprintf("whitelisted intermediate %s (id=%d) override blacklisting of %d", paths.Cert.Subject.String(), paths.Cert.ID, parent.Cert.ID) if !alreadyPresent(reason, reasons) { reasons = append(reasons, reason) } } } else { // when the parent is a root that is not blacklisted, but it isn't trusted by mozilla, // then flag the chain as distrusted anyway if parent.Cert.CA && len(parent.Parents) == 0 && !parent.Cert.ValidationInfo["Mozilla"].IsValid { reason := fmt.Sprintf("path uses a root not trusted by Mozilla: %s (id=%d)", parent.Cert.Subject.String(), parent.Cert.ID) if !alreadyPresent(reason, reasons) { reasons = append(reasons, reason) } } else { distrust = false } } } return }
[ "func", "evalPaths", "(", "paths", "certificate", ".", "Paths", ")", "(", "distrust", "bool", ",", "reasons", "[", "]", "string", ")", "{", "// assume distrust and change that if we find a trusted path", "distrust", "=", "true", "\n", "x509Cert", ",", "_", ":=", "paths", ".", "Cert", ".", "ToX509", "(", ")", "\n", "spkihash", ":=", "certificate", ".", "SPKISHA256", "(", "x509Cert", ")", "\n", "if", "evalBlacklist", "(", "spkihash", ")", "{", "reason", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "paths", ".", "Cert", ".", "Subject", ".", "String", "(", ")", ",", "paths", ".", "Cert", ".", "ID", ")", "\n", "if", "!", "alreadyPresent", "(", "reason", ",", "reasons", ")", "{", "reasons", "=", "append", "(", "reasons", ",", "reason", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "if", "len", "(", "paths", ".", "Parents", ")", "==", "0", "{", "// if is not directly distrusted and doesn't have any parent, set distrust to false", "distrust", "=", "false", "\n", "return", "\n", "}", "\n", "for", "_", ",", "parent", ":=", "range", "paths", ".", "Parents", "{", "theirDistrust", ",", "theirReasons", ":=", "evalPaths", "(", "parent", ")", "\n", "for", "_", ",", "theirReason", ":=", "range", "theirReasons", "{", "if", "!", "alreadyPresent", "(", "theirReason", ",", "reasons", ")", "{", "reasons", "=", "append", "(", "reasons", ",", "theirReason", ")", "\n", "}", "\n", "}", "\n", "if", "theirDistrust", "{", "// if the parent is distrusted, check if the current cert is whitelisted,", "// and if so, override the distrust decision", "if", "evalWhitelist", "(", "spkihash", ")", "{", "distrust", "=", "false", "\n", "reason", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "paths", ".", "Cert", ".", "Subject", ".", "String", "(", ")", ",", "paths", ".", "Cert", ".", "ID", ",", "parent", ".", "Cert", ".", "ID", ")", "\n", "if", "!", "alreadyPresent", "(", "reason", ",", "reasons", ")", "{", "reasons", "=", "append", "(", "reasons", ",", "reason", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "// when the parent is a root that is not blacklisted, but it isn't trusted by mozilla,", "// then flag the chain as distrusted anyway", "if", "parent", ".", "Cert", ".", "CA", "&&", "len", "(", "parent", ".", "Parents", ")", "==", "0", "&&", "!", "parent", ".", "Cert", ".", "ValidationInfo", "[", "\"", "\"", "]", ".", "IsValid", "{", "reason", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "parent", ".", "Cert", ".", "Subject", ".", "String", "(", ")", ",", "parent", ".", "Cert", ".", "ID", ")", "\n", "if", "!", "alreadyPresent", "(", "reason", ",", "reasons", ")", "{", "reasons", "=", "append", "(", "reasons", ",", "reason", ")", "\n", "}", "\n", "}", "else", "{", "distrust", "=", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// evalPaths recursively processes certificate paths and checks each entity // against the list of blacklisted symantec certs
[ "evalPaths", "recursively", "processes", "certificate", "paths", "and", "checks", "each", "entity", "against", "the", "list", "of", "blacklisted", "symantec", "certs" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/worker/symantecDistrust/symantecDistrust.go#L215-L265
153,488
mozilla/tls-observatory
worker/symantecDistrust/symantecDistrust.go
evalBlacklist
func evalBlacklist(spkihash string) bool { for _, blacklisted := range blacklist { if strings.ToUpper(spkihash) == strings.ToUpper(blacklisted) { return true } } return false }
go
func evalBlacklist(spkihash string) bool { for _, blacklisted := range blacklist { if strings.ToUpper(spkihash) == strings.ToUpper(blacklisted) { return true } } return false }
[ "func", "evalBlacklist", "(", "spkihash", "string", ")", "bool", "{", "for", "_", ",", "blacklisted", ":=", "range", "blacklist", "{", "if", "strings", ".", "ToUpper", "(", "spkihash", ")", "==", "strings", ".", "ToUpper", "(", "blacklisted", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// check if the SPKI hash of a cert is blacklisted
[ "check", "if", "the", "SPKI", "hash", "of", "a", "cert", "is", "blacklisted" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/worker/symantecDistrust/symantecDistrust.go#L268-L275
153,489
mozilla/tls-observatory
worker/symantecDistrust/symantecDistrust.go
evalWhitelist
func evalWhitelist(spkihash string) bool { for _, whitelisted := range whitelist { if strings.ToUpper(spkihash) == strings.ToUpper(whitelisted) { return true } } return false }
go
func evalWhitelist(spkihash string) bool { for _, whitelisted := range whitelist { if strings.ToUpper(spkihash) == strings.ToUpper(whitelisted) { return true } } return false }
[ "func", "evalWhitelist", "(", "spkihash", "string", ")", "bool", "{", "for", "_", ",", "whitelisted", ":=", "range", "whitelist", "{", "if", "strings", ".", "ToUpper", "(", "spkihash", ")", "==", "strings", ".", "ToUpper", "(", "whitelisted", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// check if the SPKI hash of a cert matches the ones in the whitelist. // here we use the spki because CAs might create more certs from those whitelisted keys
[ "check", "if", "the", "SPKI", "hash", "of", "a", "cert", "matches", "the", "ones", "in", "the", "whitelist", ".", "here", "we", "use", "the", "spki", "because", "CAs", "might", "create", "more", "certs", "from", "those", "whitelisted", "keys" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/worker/symantecDistrust/symantecDistrust.go#L279-L286
153,490
mozilla/tls-observatory
worker/mozillaGradingWorker/keyexchangeGrading.go
gradeKeyX
func gradeKeyX(connInfo connection.Stored) (categoryResults, error) { res := categoryResults{} best := float64(0) worst := float64(15360) for _, cs := range connInfo.CipherSuite { pubkeylength := getBitsForPubKey(cs) bits := pubkeylength // if we do not have a Kx algorithm the public key length is enough if cs.PFS != "None" { kxlength := getBitsForKeyExchange(cs.PFS) bits = math.Min(pubkeylength, kxlength) } if bits < worst { worst = bits } if bits > best { best = bits } } res.Grade = getKxScoreFromBits((best + worst) / 2) return res, nil }
go
func gradeKeyX(connInfo connection.Stored) (categoryResults, error) { res := categoryResults{} best := float64(0) worst := float64(15360) for _, cs := range connInfo.CipherSuite { pubkeylength := getBitsForPubKey(cs) bits := pubkeylength // if we do not have a Kx algorithm the public key length is enough if cs.PFS != "None" { kxlength := getBitsForKeyExchange(cs.PFS) bits = math.Min(pubkeylength, kxlength) } if bits < worst { worst = bits } if bits > best { best = bits } } res.Grade = getKxScoreFromBits((best + worst) / 2) return res, nil }
[ "func", "gradeKeyX", "(", "connInfo", "connection", ".", "Stored", ")", "(", "categoryResults", ",", "error", ")", "{", "res", ":=", "categoryResults", "{", "}", "\n\n", "best", ":=", "float64", "(", "0", ")", "\n", "worst", ":=", "float64", "(", "15360", ")", "\n\n", "for", "_", ",", "cs", ":=", "range", "connInfo", ".", "CipherSuite", "{", "pubkeylength", ":=", "getBitsForPubKey", "(", "cs", ")", "\n\n", "bits", ":=", "pubkeylength", "\n\n", "// if we do not have a Kx algorithm the public key length is enough", "if", "cs", ".", "PFS", "!=", "\"", "\"", "{", "kxlength", ":=", "getBitsForKeyExchange", "(", "cs", ".", "PFS", ")", "\n", "bits", "=", "math", ".", "Min", "(", "pubkeylength", ",", "kxlength", ")", "\n", "}", "\n\n", "if", "bits", "<", "worst", "{", "worst", "=", "bits", "\n", "}", "\n", "if", "bits", ">", "best", "{", "best", "=", "bits", "\n", "}", "\n", "}", "\n\n", "res", ".", "Grade", "=", "getKxScoreFromBits", "(", "(", "best", "+", "worst", ")", "/", "2", ")", "\n\n", "return", "res", ",", "nil", "\n", "}" ]
//gradeKeyX uses the simple SSLLabs method to grade the key Exchange characteristics //of the connection
[ "gradeKeyX", "uses", "the", "simple", "SSLLabs", "method", "to", "grade", "the", "key", "Exchange", "characteristics", "of", "the", "connection" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/worker/mozillaGradingWorker/keyexchangeGrading.go#L24-L53
153,491
mozilla/tls-observatory
certificate/certificate.go
GetBooleanValidity
func (c Certificate) GetBooleanValidity() (trusted_ubuntu, trusted_mozilla, trusted_microsoft, trusted_apple, trusted_android bool) { //check Ubuntu validation info valInfo, ok := c.ValidationInfo[Ubuntu_TS_name] if !ok { trusted_ubuntu = false } else { trusted_ubuntu = valInfo.IsValid } //check Mozilla validation info valInfo, ok = c.ValidationInfo[Mozilla_TS_name] if !ok { trusted_mozilla = false } else { trusted_mozilla = valInfo.IsValid } //check Microsoft validation info valInfo, ok = c.ValidationInfo[Microsoft_TS_name] if !ok { trusted_microsoft = false } else { trusted_microsoft = valInfo.IsValid } //check Apple validation info valInfo, ok = c.ValidationInfo[Apple_TS_name] if !ok { trusted_apple = false } else { trusted_apple = valInfo.IsValid } //check Android validation info valInfo, ok = c.ValidationInfo[Android_TS_name] if !ok { trusted_android = false } else { trusted_android = valInfo.IsValid } return }
go
func (c Certificate) GetBooleanValidity() (trusted_ubuntu, trusted_mozilla, trusted_microsoft, trusted_apple, trusted_android bool) { //check Ubuntu validation info valInfo, ok := c.ValidationInfo[Ubuntu_TS_name] if !ok { trusted_ubuntu = false } else { trusted_ubuntu = valInfo.IsValid } //check Mozilla validation info valInfo, ok = c.ValidationInfo[Mozilla_TS_name] if !ok { trusted_mozilla = false } else { trusted_mozilla = valInfo.IsValid } //check Microsoft validation info valInfo, ok = c.ValidationInfo[Microsoft_TS_name] if !ok { trusted_microsoft = false } else { trusted_microsoft = valInfo.IsValid } //check Apple validation info valInfo, ok = c.ValidationInfo[Apple_TS_name] if !ok { trusted_apple = false } else { trusted_apple = valInfo.IsValid } //check Android validation info valInfo, ok = c.ValidationInfo[Android_TS_name] if !ok { trusted_android = false } else { trusted_android = valInfo.IsValid } return }
[ "func", "(", "c", "Certificate", ")", "GetBooleanValidity", "(", ")", "(", "trusted_ubuntu", ",", "trusted_mozilla", ",", "trusted_microsoft", ",", "trusted_apple", ",", "trusted_android", "bool", ")", "{", "//check Ubuntu validation info", "valInfo", ",", "ok", ":=", "c", ".", "ValidationInfo", "[", "Ubuntu_TS_name", "]", "\n\n", "if", "!", "ok", "{", "trusted_ubuntu", "=", "false", "\n", "}", "else", "{", "trusted_ubuntu", "=", "valInfo", ".", "IsValid", "\n", "}", "\n\n", "//check Mozilla validation info", "valInfo", ",", "ok", "=", "c", ".", "ValidationInfo", "[", "Mozilla_TS_name", "]", "\n\n", "if", "!", "ok", "{", "trusted_mozilla", "=", "false", "\n", "}", "else", "{", "trusted_mozilla", "=", "valInfo", ".", "IsValid", "\n", "}", "\n\n", "//check Microsoft validation info", "valInfo", ",", "ok", "=", "c", ".", "ValidationInfo", "[", "Microsoft_TS_name", "]", "\n\n", "if", "!", "ok", "{", "trusted_microsoft", "=", "false", "\n", "}", "else", "{", "trusted_microsoft", "=", "valInfo", ".", "IsValid", "\n", "}", "\n\n", "//check Apple validation info", "valInfo", ",", "ok", "=", "c", ".", "ValidationInfo", "[", "Apple_TS_name", "]", "\n\n", "if", "!", "ok", "{", "trusted_apple", "=", "false", "\n", "}", "else", "{", "trusted_apple", "=", "valInfo", ".", "IsValid", "\n", "}", "\n\n", "//check Android validation info", "valInfo", ",", "ok", "=", "c", ".", "ValidationInfo", "[", "Android_TS_name", "]", "\n\n", "if", "!", "ok", "{", "trusted_android", "=", "false", "\n", "}", "else", "{", "trusted_android", "=", "valInfo", ".", "IsValid", "\n", "}", "\n", "return", "\n", "}" ]
//GetBooleanValidity converts the validation info map to DB booleans
[ "GetBooleanValidity", "converts", "the", "validation", "info", "map", "to", "DB", "booleans" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/certificate/certificate.go#L256-L303
153,492
mozilla/tls-observatory
certificate/certificate.go
GetValidityMap
func GetValidityMap(trusted_ubuntu, trusted_mozilla, trusted_microsoft, trusted_apple, trusted_android bool) map[string]ValidationInfo { vUbuntu := ValidationInfo{IsValid: trusted_ubuntu} vMozilla := ValidationInfo{IsValid: trusted_mozilla} vMicrosoft := ValidationInfo{IsValid: trusted_microsoft} vApple := ValidationInfo{IsValid: trusted_apple} vAndroid := ValidationInfo{IsValid: trusted_android} m := make(map[string]ValidationInfo) m[Ubuntu_TS_name] = vUbuntu m[Mozilla_TS_name] = vMozilla m[Microsoft_TS_name] = vMicrosoft m[Apple_TS_name] = vApple m[Android_TS_name] = vAndroid return m }
go
func GetValidityMap(trusted_ubuntu, trusted_mozilla, trusted_microsoft, trusted_apple, trusted_android bool) map[string]ValidationInfo { vUbuntu := ValidationInfo{IsValid: trusted_ubuntu} vMozilla := ValidationInfo{IsValid: trusted_mozilla} vMicrosoft := ValidationInfo{IsValid: trusted_microsoft} vApple := ValidationInfo{IsValid: trusted_apple} vAndroid := ValidationInfo{IsValid: trusted_android} m := make(map[string]ValidationInfo) m[Ubuntu_TS_name] = vUbuntu m[Mozilla_TS_name] = vMozilla m[Microsoft_TS_name] = vMicrosoft m[Apple_TS_name] = vApple m[Android_TS_name] = vAndroid return m }
[ "func", "GetValidityMap", "(", "trusted_ubuntu", ",", "trusted_mozilla", ",", "trusted_microsoft", ",", "trusted_apple", ",", "trusted_android", "bool", ")", "map", "[", "string", "]", "ValidationInfo", "{", "vUbuntu", ":=", "ValidationInfo", "{", "IsValid", ":", "trusted_ubuntu", "}", "\n", "vMozilla", ":=", "ValidationInfo", "{", "IsValid", ":", "trusted_mozilla", "}", "\n", "vMicrosoft", ":=", "ValidationInfo", "{", "IsValid", ":", "trusted_microsoft", "}", "\n", "vApple", ":=", "ValidationInfo", "{", "IsValid", ":", "trusted_apple", "}", "\n", "vAndroid", ":=", "ValidationInfo", "{", "IsValid", ":", "trusted_android", "}", "\n\n", "m", ":=", "make", "(", "map", "[", "string", "]", "ValidationInfo", ")", "\n\n", "m", "[", "Ubuntu_TS_name", "]", "=", "vUbuntu", "\n", "m", "[", "Mozilla_TS_name", "]", "=", "vMozilla", "\n", "m", "[", "Microsoft_TS_name", "]", "=", "vMicrosoft", "\n", "m", "[", "Apple_TS_name", "]", "=", "vApple", "\n", "m", "[", "Android_TS_name", "]", "=", "vAndroid", "\n\n", "return", "m", "\n\n", "}" ]
// GetValidityMap converts boolean validity variables to a validity map.
[ "GetValidityMap", "converts", "boolean", "validity", "variables", "to", "a", "validity", "map", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/certificate/certificate.go#L306-L324
153,493
mozilla/tls-observatory
certificate/certificate.go
CertToStored
func CertToStored(cert *x509.Certificate, parentSignature, domain, ip string, TSName string, valInfo *ValidationInfo) Certificate { var ( err error stored = Certificate{} ) // initialize []string to never store them as null stored.ParentSignature = make([]string, 0) stored.IPs = make([]string, 0) stored.Version = cert.Version // If there's an error, we just store the zero value ("") serial, _ := GetHexASN1Serial(cert) stored.Serial = serial stored.SignatureAlgorithm = SignatureAlgorithm[cert.SignatureAlgorithm] stored.Key, err = getPublicKeyInfo(cert) if err != nil { log.Printf("Failed to retrieve public key information: %v. Continuing anyway.", err) } stored.Issuer.Country = cert.Issuer.Country stored.Issuer.Organisation = cert.Issuer.Organization stored.Issuer.OrgUnit = cert.Issuer.OrganizationalUnit stored.Issuer.CommonName = cert.Issuer.CommonName stored.Subject.Country = cert.Subject.Country stored.Subject.Organisation = cert.Subject.Organization stored.Subject.OrgUnit = cert.Subject.OrganizationalUnit stored.Subject.CommonName = cert.Subject.CommonName stored.Validity.NotBefore = cert.NotBefore.UTC() stored.Validity.NotAfter = cert.NotAfter.UTC() stored.X509v3Extensions = getCertExtensions(cert) stored.MozillaPolicyV2_5 = getMozillaPolicyV2_5(cert) //below check tries to hack around the basic constraints extension //not being available in versions < 3. //Only the IsCa variable is set, as setting X509v3BasicConstraints //messes up the validation procedure. if cert.Version < 3 { stored.CA = cert.IsCA } else { if cert.BasicConstraintsValid { stored.X509v3BasicConstraints = "Critical" stored.CA = cert.IsCA } else { stored.X509v3BasicConstraints = "" stored.CA = false } } t := time.Now().UTC() stored.FirstSeenTimestamp = t stored.LastSeenTimestamp = t stored.ParentSignature = append(stored.ParentSignature, parentSignature) if !cert.IsCA { stored.ScanTarget = domain stored.IPs = append(stored.IPs, ip) } stored.ValidationInfo = make(map[string]ValidationInfo) stored.ValidationInfo[TSName] = *valInfo stored.Hashes.MD5 = MD5Hash(cert.Raw) stored.Hashes.SHA1 = SHA1Hash(cert.Raw) stored.Hashes.SHA256 = SHA256Hash(cert.Raw) stored.Hashes.SPKISHA256 = SPKISHA256(cert) stored.Hashes.SubjectSPKISHA256 = SubjectSPKISHA256(cert) stored.Hashes.PKPSHA256 = PKPSHA256Hash(cert) stored.Raw = base64.StdEncoding.EncodeToString(cert.Raw) stored.CiscoUmbrellaRank = Default_Cisco_Umbrella_Rank return stored }
go
func CertToStored(cert *x509.Certificate, parentSignature, domain, ip string, TSName string, valInfo *ValidationInfo) Certificate { var ( err error stored = Certificate{} ) // initialize []string to never store them as null stored.ParentSignature = make([]string, 0) stored.IPs = make([]string, 0) stored.Version = cert.Version // If there's an error, we just store the zero value ("") serial, _ := GetHexASN1Serial(cert) stored.Serial = serial stored.SignatureAlgorithm = SignatureAlgorithm[cert.SignatureAlgorithm] stored.Key, err = getPublicKeyInfo(cert) if err != nil { log.Printf("Failed to retrieve public key information: %v. Continuing anyway.", err) } stored.Issuer.Country = cert.Issuer.Country stored.Issuer.Organisation = cert.Issuer.Organization stored.Issuer.OrgUnit = cert.Issuer.OrganizationalUnit stored.Issuer.CommonName = cert.Issuer.CommonName stored.Subject.Country = cert.Subject.Country stored.Subject.Organisation = cert.Subject.Organization stored.Subject.OrgUnit = cert.Subject.OrganizationalUnit stored.Subject.CommonName = cert.Subject.CommonName stored.Validity.NotBefore = cert.NotBefore.UTC() stored.Validity.NotAfter = cert.NotAfter.UTC() stored.X509v3Extensions = getCertExtensions(cert) stored.MozillaPolicyV2_5 = getMozillaPolicyV2_5(cert) //below check tries to hack around the basic constraints extension //not being available in versions < 3. //Only the IsCa variable is set, as setting X509v3BasicConstraints //messes up the validation procedure. if cert.Version < 3 { stored.CA = cert.IsCA } else { if cert.BasicConstraintsValid { stored.X509v3BasicConstraints = "Critical" stored.CA = cert.IsCA } else { stored.X509v3BasicConstraints = "" stored.CA = false } } t := time.Now().UTC() stored.FirstSeenTimestamp = t stored.LastSeenTimestamp = t stored.ParentSignature = append(stored.ParentSignature, parentSignature) if !cert.IsCA { stored.ScanTarget = domain stored.IPs = append(stored.IPs, ip) } stored.ValidationInfo = make(map[string]ValidationInfo) stored.ValidationInfo[TSName] = *valInfo stored.Hashes.MD5 = MD5Hash(cert.Raw) stored.Hashes.SHA1 = SHA1Hash(cert.Raw) stored.Hashes.SHA256 = SHA256Hash(cert.Raw) stored.Hashes.SPKISHA256 = SPKISHA256(cert) stored.Hashes.SubjectSPKISHA256 = SubjectSPKISHA256(cert) stored.Hashes.PKPSHA256 = PKPSHA256Hash(cert) stored.Raw = base64.StdEncoding.EncodeToString(cert.Raw) stored.CiscoUmbrellaRank = Default_Cisco_Umbrella_Rank return stored }
[ "func", "CertToStored", "(", "cert", "*", "x509", ".", "Certificate", ",", "parentSignature", ",", "domain", ",", "ip", "string", ",", "TSName", "string", ",", "valInfo", "*", "ValidationInfo", ")", "Certificate", "{", "var", "(", "err", "error", "\n", "stored", "=", "Certificate", "{", "}", "\n", ")", "\n", "// initialize []string to never store them as null", "stored", ".", "ParentSignature", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "stored", ".", "IPs", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n\n", "stored", ".", "Version", "=", "cert", ".", "Version", "\n\n", "// If there's an error, we just store the zero value (\"\")", "serial", ",", "_", ":=", "GetHexASN1Serial", "(", "cert", ")", "\n", "stored", ".", "Serial", "=", "serial", "\n\n", "stored", ".", "SignatureAlgorithm", "=", "SignatureAlgorithm", "[", "cert", ".", "SignatureAlgorithm", "]", "\n\n", "stored", ".", "Key", ",", "err", "=", "getPublicKeyInfo", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "stored", ".", "Issuer", ".", "Country", "=", "cert", ".", "Issuer", ".", "Country", "\n", "stored", ".", "Issuer", ".", "Organisation", "=", "cert", ".", "Issuer", ".", "Organization", "\n", "stored", ".", "Issuer", ".", "OrgUnit", "=", "cert", ".", "Issuer", ".", "OrganizationalUnit", "\n", "stored", ".", "Issuer", ".", "CommonName", "=", "cert", ".", "Issuer", ".", "CommonName", "\n\n", "stored", ".", "Subject", ".", "Country", "=", "cert", ".", "Subject", ".", "Country", "\n", "stored", ".", "Subject", ".", "Organisation", "=", "cert", ".", "Subject", ".", "Organization", "\n", "stored", ".", "Subject", ".", "OrgUnit", "=", "cert", ".", "Subject", ".", "OrganizationalUnit", "\n", "stored", ".", "Subject", ".", "CommonName", "=", "cert", ".", "Subject", ".", "CommonName", "\n\n", "stored", ".", "Validity", ".", "NotBefore", "=", "cert", ".", "NotBefore", ".", "UTC", "(", ")", "\n", "stored", ".", "Validity", ".", "NotAfter", "=", "cert", ".", "NotAfter", ".", "UTC", "(", ")", "\n\n", "stored", ".", "X509v3Extensions", "=", "getCertExtensions", "(", "cert", ")", "\n\n", "stored", ".", "MozillaPolicyV2_5", "=", "getMozillaPolicyV2_5", "(", "cert", ")", "\n\n", "//below check tries to hack around the basic constraints extension", "//not being available in versions < 3.", "//Only the IsCa variable is set, as setting X509v3BasicConstraints", "//messes up the validation procedure.", "if", "cert", ".", "Version", "<", "3", "{", "stored", ".", "CA", "=", "cert", ".", "IsCA", "\n", "}", "else", "{", "if", "cert", ".", "BasicConstraintsValid", "{", "stored", ".", "X509v3BasicConstraints", "=", "\"", "\"", "\n", "stored", ".", "CA", "=", "cert", ".", "IsCA", "\n", "}", "else", "{", "stored", ".", "X509v3BasicConstraints", "=", "\"", "\"", "\n", "stored", ".", "CA", "=", "false", "\n", "}", "\n", "}", "\n\n", "t", ":=", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", "\n\n", "stored", ".", "FirstSeenTimestamp", "=", "t", "\n", "stored", ".", "LastSeenTimestamp", "=", "t", "\n\n", "stored", ".", "ParentSignature", "=", "append", "(", "stored", ".", "ParentSignature", ",", "parentSignature", ")", "\n\n", "if", "!", "cert", ".", "IsCA", "{", "stored", ".", "ScanTarget", "=", "domain", "\n", "stored", ".", "IPs", "=", "append", "(", "stored", ".", "IPs", ",", "ip", ")", "\n", "}", "\n\n", "stored", ".", "ValidationInfo", "=", "make", "(", "map", "[", "string", "]", "ValidationInfo", ")", "\n", "stored", ".", "ValidationInfo", "[", "TSName", "]", "=", "*", "valInfo", "\n\n", "stored", ".", "Hashes", ".", "MD5", "=", "MD5Hash", "(", "cert", ".", "Raw", ")", "\n", "stored", ".", "Hashes", ".", "SHA1", "=", "SHA1Hash", "(", "cert", ".", "Raw", ")", "\n", "stored", ".", "Hashes", ".", "SHA256", "=", "SHA256Hash", "(", "cert", ".", "Raw", ")", "\n", "stored", ".", "Hashes", ".", "SPKISHA256", "=", "SPKISHA256", "(", "cert", ")", "\n", "stored", ".", "Hashes", ".", "SubjectSPKISHA256", "=", "SubjectSPKISHA256", "(", "cert", ")", "\n", "stored", ".", "Hashes", ".", "PKPSHA256", "=", "PKPSHA256Hash", "(", "cert", ")", "\n\n", "stored", ".", "Raw", "=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "cert", ".", "Raw", ")", "\n", "stored", ".", "CiscoUmbrellaRank", "=", "Default_Cisco_Umbrella_Rank", "\n\n", "return", "stored", "\n", "}" ]
//certtoStored returns a Certificate struct created from a X509.Certificate
[ "certtoStored", "returns", "a", "Certificate", "struct", "created", "from", "a", "X509", ".", "Certificate" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/certificate/certificate.go#L509-L590
153,494
mozilla/tls-observatory
certificate/certificate.go
printRawCertExtensions
func printRawCertExtensions(cert *x509.Certificate) { for i, extension := range cert.Extensions { var numbers string for num, num2 := range extension.Id { numbers = numbers + " " + "[" + strconv.Itoa(num) + " " + strconv.Itoa(num2) + "]" } fmt.Println("//", strconv.Itoa(i), ": {", numbers, "}", string(extension.Value)) } }
go
func printRawCertExtensions(cert *x509.Certificate) { for i, extension := range cert.Extensions { var numbers string for num, num2 := range extension.Id { numbers = numbers + " " + "[" + strconv.Itoa(num) + " " + strconv.Itoa(num2) + "]" } fmt.Println("//", strconv.Itoa(i), ": {", numbers, "}", string(extension.Value)) } }
[ "func", "printRawCertExtensions", "(", "cert", "*", "x509", ".", "Certificate", ")", "{", "for", "i", ",", "extension", ":=", "range", "cert", ".", "Extensions", "{", "var", "numbers", "string", "\n", "for", "num", ",", "num2", ":=", "range", "extension", ".", "Id", "{", "numbers", "=", "numbers", "+", "\"", "\"", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "num", ")", "+", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "num2", ")", "+", "\"", "\"", "\n\n", "}", "\n", "fmt", ".", "Println", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "i", ")", ",", "\"", "\"", ",", "numbers", ",", "\"", "\"", ",", "string", "(", "extension", ".", "Value", ")", ")", "\n", "}", "\n\n", "}" ]
//printRawCertExtensions Print raw extension info //for debugging purposes
[ "printRawCertExtensions", "Print", "raw", "extension", "info", "for", "debugging", "purposes" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/certificate/certificate.go#L603-L616
153,495
mozilla/tls-observatory
certificate/certificate.go
IsSelfSigned
func (c Certificate) IsSelfSigned() bool { if c.Subject.CommonName != c.Issuer.CommonName || len(c.Subject.Organisation) != len(c.Issuer.Organisation) || len(c.Subject.OrgUnit) != len(c.Issuer.OrgUnit) || len(c.Subject.Country) != len(c.Issuer.Country) { return false } for i, _ := range c.Subject.Organisation { if c.Subject.Organisation[i] != c.Issuer.Organisation[i] { return false } } for i, _ := range c.Subject.OrgUnit { if c.Subject.OrgUnit[i] != c.Issuer.OrgUnit[i] { return false } } for i, _ := range c.Subject.Country { if c.Subject.Country[i] != c.Issuer.Country[i] { return false } } return true }
go
func (c Certificate) IsSelfSigned() bool { if c.Subject.CommonName != c.Issuer.CommonName || len(c.Subject.Organisation) != len(c.Issuer.Organisation) || len(c.Subject.OrgUnit) != len(c.Issuer.OrgUnit) || len(c.Subject.Country) != len(c.Issuer.Country) { return false } for i, _ := range c.Subject.Organisation { if c.Subject.Organisation[i] != c.Issuer.Organisation[i] { return false } } for i, _ := range c.Subject.OrgUnit { if c.Subject.OrgUnit[i] != c.Issuer.OrgUnit[i] { return false } } for i, _ := range c.Subject.Country { if c.Subject.Country[i] != c.Issuer.Country[i] { return false } } return true }
[ "func", "(", "c", "Certificate", ")", "IsSelfSigned", "(", ")", "bool", "{", "if", "c", ".", "Subject", ".", "CommonName", "!=", "c", ".", "Issuer", ".", "CommonName", "||", "len", "(", "c", ".", "Subject", ".", "Organisation", ")", "!=", "len", "(", "c", ".", "Issuer", ".", "Organisation", ")", "||", "len", "(", "c", ".", "Subject", ".", "OrgUnit", ")", "!=", "len", "(", "c", ".", "Issuer", ".", "OrgUnit", ")", "||", "len", "(", "c", ".", "Subject", ".", "Country", ")", "!=", "len", "(", "c", ".", "Issuer", ".", "Country", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ",", "_", ":=", "range", "c", ".", "Subject", ".", "Organisation", "{", "if", "c", ".", "Subject", ".", "Organisation", "[", "i", "]", "!=", "c", ".", "Issuer", ".", "Organisation", "[", "i", "]", "{", "return", "false", "\n", "}", "\n", "}", "\n", "for", "i", ",", "_", ":=", "range", "c", ".", "Subject", ".", "OrgUnit", "{", "if", "c", ".", "Subject", ".", "OrgUnit", "[", "i", "]", "!=", "c", ".", "Issuer", ".", "OrgUnit", "[", "i", "]", "{", "return", "false", "\n", "}", "\n", "}", "\n", "for", "i", ",", "_", ":=", "range", "c", ".", "Subject", ".", "Country", "{", "if", "c", ".", "Subject", ".", "Country", "[", "i", "]", "!=", "c", ".", "Issuer", ".", "Country", "[", "i", "]", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsSelfSigned return true if the subject and issuer fields of a certificate // are identical
[ "IsSelfSigned", "return", "true", "if", "the", "subject", "and", "issuer", "fields", "of", "a", "certificate", "are", "identical" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/certificate/certificate.go#L639-L662
153,496
mozilla/tls-observatory
database/messaging.go
RegisterScanListener
func (db *DB) RegisterScanListener(dbname, user, password, hostport, sslmode string) <-chan int64 { log := logger.GetLogger() reportProblem := func(ev pq.ListenerEventType, err error) { if err != nil { log.WithFields(logrus.Fields{ "error": err.Error(), }).Error("Listener Error") } } listenerChan := make(chan int64) listenerName := "scan_listener" userPass := url.UserPassword(user, password) url := fmt.Sprintf("postgres://%s@%s/%s?sslmode=%s", userPass.String(), hostport, dbname, sslmode) go func() { listener := pq.NewListener(url, 100*time.Millisecond, 10*time.Second, reportProblem) err := listener.Listen(listenerName) if err != nil { log.WithFields(logrus.Fields{ "listener": listenerName, "error": err.Error(), }).Error("could not listen for notification") close(listenerChan) return } for m := range listener.Notify { sid := m.Extra if !db.acquireScan(sid) { // skip this scan if we didn't acquire it continue } // scan was acquired, inform the scanner to launch it id, err := strconv.ParseInt(string(sid), 10, 64) if err != nil { log.WithFields(logrus.Fields{ "scan_id": sid, "error": err.Error(), }).Error("could not decode acquired notification") } listenerChan <- id log.WithFields(logrus.Fields{ "scan_id": id, }).Debug("Acquired notification.") } }() // Launch a goroutine that relaunches scans that have not yet been processed go func() { for { // don't requeue scans more than 3 times _, err := db.Exec(`UPDATE scans SET ack = false, timestamp = NOW() WHERE completion_perc = 0 AND attempts < 3 AND ack = true AND timestamp < NOW() - INTERVAL '10 minute'`) if err != nil { log.WithFields(logrus.Fields{ "error": err, }).Error("Could not run zero completion update query") } _, err = db.Exec(fmt.Sprintf(`SELECT pg_notify('%s', ''||id ) FROM scans WHERE ack=false ORDER BY id ASC LIMIT 1000`, listenerName)) if err != nil { log.WithFields(logrus.Fields{ "error": err, }).Error("Could not run unacknowledged scans periodic check.") } time.Sleep(3 * time.Minute) } }() return listenerChan }
go
func (db *DB) RegisterScanListener(dbname, user, password, hostport, sslmode string) <-chan int64 { log := logger.GetLogger() reportProblem := func(ev pq.ListenerEventType, err error) { if err != nil { log.WithFields(logrus.Fields{ "error": err.Error(), }).Error("Listener Error") } } listenerChan := make(chan int64) listenerName := "scan_listener" userPass := url.UserPassword(user, password) url := fmt.Sprintf("postgres://%s@%s/%s?sslmode=%s", userPass.String(), hostport, dbname, sslmode) go func() { listener := pq.NewListener(url, 100*time.Millisecond, 10*time.Second, reportProblem) err := listener.Listen(listenerName) if err != nil { log.WithFields(logrus.Fields{ "listener": listenerName, "error": err.Error(), }).Error("could not listen for notification") close(listenerChan) return } for m := range listener.Notify { sid := m.Extra if !db.acquireScan(sid) { // skip this scan if we didn't acquire it continue } // scan was acquired, inform the scanner to launch it id, err := strconv.ParseInt(string(sid), 10, 64) if err != nil { log.WithFields(logrus.Fields{ "scan_id": sid, "error": err.Error(), }).Error("could not decode acquired notification") } listenerChan <- id log.WithFields(logrus.Fields{ "scan_id": id, }).Debug("Acquired notification.") } }() // Launch a goroutine that relaunches scans that have not yet been processed go func() { for { // don't requeue scans more than 3 times _, err := db.Exec(`UPDATE scans SET ack = false, timestamp = NOW() WHERE completion_perc = 0 AND attempts < 3 AND ack = true AND timestamp < NOW() - INTERVAL '10 minute'`) if err != nil { log.WithFields(logrus.Fields{ "error": err, }).Error("Could not run zero completion update query") } _, err = db.Exec(fmt.Sprintf(`SELECT pg_notify('%s', ''||id ) FROM scans WHERE ack=false ORDER BY id ASC LIMIT 1000`, listenerName)) if err != nil { log.WithFields(logrus.Fields{ "error": err, }).Error("Could not run unacknowledged scans periodic check.") } time.Sleep(3 * time.Minute) } }() return listenerChan }
[ "func", "(", "db", "*", "DB", ")", "RegisterScanListener", "(", "dbname", ",", "user", ",", "password", ",", "hostport", ",", "sslmode", "string", ")", "<-", "chan", "int64", "{", "log", ":=", "logger", ".", "GetLogger", "(", ")", "\n\n", "reportProblem", ":=", "func", "(", "ev", "pq", ".", "ListenerEventType", ",", "err", "error", ")", "{", "if", "err", "!=", "nil", "{", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "err", ".", "Error", "(", ")", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "listenerChan", ":=", "make", "(", "chan", "int64", ")", "\n", "listenerName", ":=", "\"", "\"", "\n\n", "userPass", ":=", "url", ".", "UserPassword", "(", "user", ",", "password", ")", "\n", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "userPass", ".", "String", "(", ")", ",", "hostport", ",", "dbname", ",", "sslmode", ")", "\n", "go", "func", "(", ")", "{", "listener", ":=", "pq", ".", "NewListener", "(", "url", ",", "100", "*", "time", ".", "Millisecond", ",", "10", "*", "time", ".", "Second", ",", "reportProblem", ")", "\n", "err", ":=", "listener", ".", "Listen", "(", "listenerName", ")", "\n\n", "if", "err", "!=", "nil", "{", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "listenerName", ",", "\"", "\"", ":", "err", ".", "Error", "(", ")", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "close", "(", "listenerChan", ")", "\n", "return", "\n", "}", "\n\n", "for", "m", ":=", "range", "listener", ".", "Notify", "{", "sid", ":=", "m", ".", "Extra", "\n", "if", "!", "db", ".", "acquireScan", "(", "sid", ")", "{", "// skip this scan if we didn't acquire it", "continue", "\n", "}", "\n", "// scan was acquired, inform the scanner to launch it", "id", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "string", "(", "sid", ")", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "sid", ",", "\"", "\"", ":", "err", ".", "Error", "(", ")", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "listenerChan", "<-", "id", "\n", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "id", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "}", "\n\n", "}", "(", ")", "\n\n", "// Launch a goroutine that relaunches scans that have not yet been processed", "go", "func", "(", ")", "{", "for", "{", "// don't requeue scans more than 3 times", "_", ",", "err", ":=", "db", ".", "Exec", "(", "`UPDATE scans SET ack = false, timestamp = NOW()\n\t\t\t\t WHERE completion_perc = 0 AND attempts < 3 AND ack = true\n\t\t\t\t\t\t AND timestamp < NOW() - INTERVAL '10 minute'`", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "err", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "_", ",", "err", "=", "db", ".", "Exec", "(", "fmt", ".", "Sprintf", "(", "`SELECT pg_notify('%s', ''||id )\n\t\t\t\t\t\t FROM scans\n\t\t\t\t\t\t WHERE ack=false\n\t\t\t\t\t\t ORDER BY id ASC\n\t\t\t\t\t\t LIMIT 1000`", ",", "listenerName", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "err", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "time", ".", "Sleep", "(", "3", "*", "time", ".", "Minute", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "listenerChan", "\n", "}" ]
// RegisterScanListener "subscribes" to the notifications published to the scan_listener notifier. // It has as input the usual db attributes and returns an int64 channel which can be consumed // for newly created scan id's.
[ "RegisterScanListener", "subscribes", "to", "the", "notifications", "published", "to", "the", "scan_listener", "notifier", ".", "It", "has", "as", "input", "the", "usual", "db", "attributes", "and", "returns", "an", "int64", "channel", "which", "can", "be", "consumed", "for", "newly", "created", "scan", "id", "s", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/messaging.go#L18-L98
153,497
mozilla/tls-observatory
database/messaging.go
acquireScan
func (db *DB) acquireScan(id string) bool { tx, err := db.Begin() if err != nil { return false } // `ack` is a mutex in the database that each scanner will try to select // for update. if a scanner succeeds, it will return true, otherwise it // will return false. row := tx.QueryRow("SELECT ack FROM scans WHERE id=$1 FOR UPDATE", id) ack := false err = row.Scan(&ack) if err != nil { tx.Rollback() return false } if ack { // if ack was true in db, that means another job already acked this // scan so we drop the lock and return false tx.Rollback() return false } // otherwise, ack is false and we acquire it to run the scan // if anything fails along the way, we drop the lock by rolling back _, err = tx.Exec("UPDATE scans SET ack=true WHERE id=$1", id) if err != nil { tx.Rollback() return false } err = tx.Commit() if err != nil { tx.Rollback() return false } return true }
go
func (db *DB) acquireScan(id string) bool { tx, err := db.Begin() if err != nil { return false } // `ack` is a mutex in the database that each scanner will try to select // for update. if a scanner succeeds, it will return true, otherwise it // will return false. row := tx.QueryRow("SELECT ack FROM scans WHERE id=$1 FOR UPDATE", id) ack := false err = row.Scan(&ack) if err != nil { tx.Rollback() return false } if ack { // if ack was true in db, that means another job already acked this // scan so we drop the lock and return false tx.Rollback() return false } // otherwise, ack is false and we acquire it to run the scan // if anything fails along the way, we drop the lock by rolling back _, err = tx.Exec("UPDATE scans SET ack=true WHERE id=$1", id) if err != nil { tx.Rollback() return false } err = tx.Commit() if err != nil { tx.Rollback() return false } return true }
[ "func", "(", "db", "*", "DB", ")", "acquireScan", "(", "id", "string", ")", "bool", "{", "tx", ",", "err", ":=", "db", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "// `ack` is a mutex in the database that each scanner will try to select", "// for update. if a scanner succeeds, it will return true, otherwise it", "// will return false.", "row", ":=", "tx", ".", "QueryRow", "(", "\"", "\"", ",", "id", ")", "\n", "ack", ":=", "false", "\n", "err", "=", "row", ".", "Scan", "(", "&", "ack", ")", "\n", "if", "err", "!=", "nil", "{", "tx", ".", "Rollback", "(", ")", "\n", "return", "false", "\n", "}", "\n", "if", "ack", "{", "// if ack was true in db, that means another job already acked this", "// scan so we drop the lock and return false", "tx", ".", "Rollback", "(", ")", "\n", "return", "false", "\n", "}", "\n", "// otherwise, ack is false and we acquire it to run the scan", "// if anything fails along the way, we drop the lock by rolling back", "_", ",", "err", "=", "tx", ".", "Exec", "(", "\"", "\"", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "tx", ".", "Rollback", "(", ")", "\n", "return", "false", "\n", "}", "\n", "err", "=", "tx", ".", "Commit", "(", ")", "\n", "if", "err", "!=", "nil", "{", "tx", ".", "Rollback", "(", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// acquireScan provides a way to limit to one the number of scanners // evaluating a given target, but setting a `ack` boolean to true when a // scanner picks up a scan
[ "acquireScan", "provides", "a", "way", "to", "limit", "to", "one", "the", "number", "of", "scanners", "evaluating", "a", "given", "target", "but", "setting", "a", "ack", "boolean", "to", "true", "when", "a", "scanner", "picks", "up", "a", "scan" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/messaging.go#L103-L137
153,498
mozilla/tls-observatory
database/stats.go
CountTableEntries
func (db *DB) CountTableEntries() (scans, trusts, analyses, certificates int64, err error) { err = db.QueryRow(`SELECT reltuples::INTEGER FROM pg_class WHERE relname='scans'`).Scan(&scans) if err != nil { return } err = db.QueryRow(`SELECT reltuples::INTEGER FROM pg_class WHERE relname='trust'`).Scan(&trusts) if err != nil { return } err = db.QueryRow(`SELECT reltuples::INTEGER FROM pg_class WHERE relname='analysis'`).Scan(&analyses) if err != nil { return } err = db.QueryRow(`SELECT reltuples::INTEGER FROM pg_class WHERE relname='certificates'`).Scan(&certificates) if err != nil { return } return }
go
func (db *DB) CountTableEntries() (scans, trusts, analyses, certificates int64, err error) { err = db.QueryRow(`SELECT reltuples::INTEGER FROM pg_class WHERE relname='scans'`).Scan(&scans) if err != nil { return } err = db.QueryRow(`SELECT reltuples::INTEGER FROM pg_class WHERE relname='trust'`).Scan(&trusts) if err != nil { return } err = db.QueryRow(`SELECT reltuples::INTEGER FROM pg_class WHERE relname='analysis'`).Scan(&analyses) if err != nil { return } err = db.QueryRow(`SELECT reltuples::INTEGER FROM pg_class WHERE relname='certificates'`).Scan(&certificates) if err != nil { return } return }
[ "func", "(", "db", "*", "DB", ")", "CountTableEntries", "(", ")", "(", "scans", ",", "trusts", ",", "analyses", ",", "certificates", "int64", ",", "err", "error", ")", "{", "err", "=", "db", ".", "QueryRow", "(", "`SELECT reltuples::INTEGER FROM pg_class WHERE relname='scans'`", ")", ".", "Scan", "(", "&", "scans", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "db", ".", "QueryRow", "(", "`SELECT reltuples::INTEGER FROM pg_class WHERE relname='trust'`", ")", ".", "Scan", "(", "&", "trusts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "db", ".", "QueryRow", "(", "`SELECT reltuples::INTEGER FROM pg_class WHERE relname='analysis'`", ")", ".", "Scan", "(", "&", "analyses", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "db", ".", "QueryRow", "(", "`SELECT reltuples::INTEGER FROM pg_class WHERE relname='certificates'`", ")", ".", "Scan", "(", "&", "certificates", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "\n", "}" ]
// CountTableEntries returns the estimated count of scans, trusts relationships, analyses // and certificates stored in database. The count uses Postgres' own stats counter and is // not guaranteed to be fully accurate.
[ "CountTableEntries", "returns", "the", "estimated", "count", "of", "scans", "trusts", "relationships", "analyses", "and", "certificates", "stored", "in", "database", ".", "The", "count", "uses", "Postgres", "own", "stats", "counter", "and", "is", "not", "guaranteed", "to", "be", "fully", "accurate", "." ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/stats.go#L43-L61
153,499
mozilla/tls-observatory
database/stats.go
CountPendingScans
func (db *DB) CountPendingScans() (count int64, err error) { err = db.QueryRow(`SELECT COUNT(*) FROM scans WHERE completion_perc = 0 AND attempts < 3 AND ack = false`).Scan(&count) return }
go
func (db *DB) CountPendingScans() (count int64, err error) { err = db.QueryRow(`SELECT COUNT(*) FROM scans WHERE completion_perc = 0 AND attempts < 3 AND ack = false`).Scan(&count) return }
[ "func", "(", "db", "*", "DB", ")", "CountPendingScans", "(", ")", "(", "count", "int64", ",", "err", "error", ")", "{", "err", "=", "db", ".", "QueryRow", "(", "`SELECT COUNT(*) FROM scans\n\t\t\t\t WHERE completion_perc = 0\n\t\t\t\t AND attempts < 3 AND ack = false`", ")", ".", "Scan", "(", "&", "count", ")", "\n", "return", "\n", "}" ]
// CountPendingScans returns the total number of scans that are pending in the queue
[ "CountPendingScans", "returns", "the", "total", "number", "of", "scans", "that", "are", "pending", "in", "the", "queue" ]
a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c
https://github.com/mozilla/tls-observatory/blob/a3c1b6cfecfd7a0cf8f64c6bdc2b1e1d6a87e06c/database/stats.go#L64-L69