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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
11,100
square/certigo
starttls/psql/notify.go
Unlisten
func (l *Listener) Unlisten(channel string) error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } // Similarly to LISTEN, this is not an error in Postgres, but it seems // useful to distinguish from the normal conditions. _, exists := l.channels[channel] if !exists { return ErrChannelNotOpen } if l.cn != nil { // Similarly to Listen (see comment in that function), the caller // should only be bothered with an error if it came from the backend as // a response to our query. gotResponse, err := l.cn.Unlisten(channel) if gotResponse && err != nil { return err } } // Don't bother waiting for resync if there's no connection. delete(l.channels, channel) return nil }
go
func (l *Listener) Unlisten(channel string) error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } // Similarly to LISTEN, this is not an error in Postgres, but it seems // useful to distinguish from the normal conditions. _, exists := l.channels[channel] if !exists { return ErrChannelNotOpen } if l.cn != nil { // Similarly to Listen (see comment in that function), the caller // should only be bothered with an error if it came from the backend as // a response to our query. gotResponse, err := l.cn.Unlisten(channel) if gotResponse && err != nil { return err } } // Don't bother waiting for resync if there's no connection. delete(l.channels, channel) return nil }
[ "func", "(", "l", "*", "Listener", ")", "Unlisten", "(", "channel", "string", ")", "error", "{", "l", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "l", ".", "isClosed", "{", "return", "errListenerClosed", "\n", "}", "\n\n", "// Similarly to LISTEN, this is not an error in Postgres, but it seems", "// useful to distinguish from the normal conditions.", "_", ",", "exists", ":=", "l", ".", "channels", "[", "channel", "]", "\n", "if", "!", "exists", "{", "return", "ErrChannelNotOpen", "\n", "}", "\n\n", "if", "l", ".", "cn", "!=", "nil", "{", "// Similarly to Listen (see comment in that function), the caller", "// should only be bothered with an error if it came from the backend as", "// a response to our query.", "gotResponse", ",", "err", ":=", "l", ".", "cn", ".", "Unlisten", "(", "channel", ")", "\n", "if", "gotResponse", "&&", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Don't bother waiting for resync if there's no connection.", "delete", "(", "l", ".", "channels", ",", "channel", ")", "\n", "return", "nil", "\n", "}" ]
// Unlisten removes a channel from the Listener's channel list. Returns // ErrChannelNotOpen if the Listener is not listening on the specified channel. // Returns immediately with no error if there is no connection. Note that you // might still get notifications for this channel even after Unlisten has // returned. // // The channel name is case-sensitive.
[ "Unlisten", "removes", "a", "channel", "from", "the", "Listener", "s", "channel", "list", ".", "Returns", "ErrChannelNotOpen", "if", "the", "Listener", "is", "not", "listening", "on", "the", "specified", "channel", ".", "Returns", "immediately", "with", "no", "error", "if", "there", "is", "no", "connection", ".", "Note", "that", "you", "might", "still", "get", "notifications", "for", "this", "channel", "even", "after", "Unlisten", "has", "returned", ".", "The", "channel", "name", "is", "case", "-", "sensitive", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/notify.go#L529-L557
11,101
square/certigo
starttls/psql/notify.go
UnlistenAll
func (l *Listener) UnlistenAll() error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } if l.cn != nil { // Similarly to Listen (see comment in that function), the caller // should only be bothered with an error if it came from the backend as // a response to our query. gotResponse, err := l.cn.UnlistenAll() if gotResponse && err != nil { return err } } // Don't bother waiting for resync if there's no connection. l.channels = make(map[string]struct{}) return nil }
go
func (l *Listener) UnlistenAll() error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } if l.cn != nil { // Similarly to Listen (see comment in that function), the caller // should only be bothered with an error if it came from the backend as // a response to our query. gotResponse, err := l.cn.UnlistenAll() if gotResponse && err != nil { return err } } // Don't bother waiting for resync if there's no connection. l.channels = make(map[string]struct{}) return nil }
[ "func", "(", "l", "*", "Listener", ")", "UnlistenAll", "(", ")", "error", "{", "l", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "l", ".", "isClosed", "{", "return", "errListenerClosed", "\n", "}", "\n\n", "if", "l", ".", "cn", "!=", "nil", "{", "// Similarly to Listen (see comment in that function), the caller", "// should only be bothered with an error if it came from the backend as", "// a response to our query.", "gotResponse", ",", "err", ":=", "l", ".", "cn", ".", "UnlistenAll", "(", ")", "\n", "if", "gotResponse", "&&", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Don't bother waiting for resync if there's no connection.", "l", ".", "channels", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "return", "nil", "\n", "}" ]
// UnlistenAll removes all channels from the Listener's channel list. Returns // immediately with no error if there is no connection. Note that you might // still get notifications for any of the deleted channels even after // UnlistenAll has returned.
[ "UnlistenAll", "removes", "all", "channels", "from", "the", "Listener", "s", "channel", "list", ".", "Returns", "immediately", "with", "no", "error", "if", "there", "is", "no", "connection", ".", "Note", "that", "you", "might", "still", "get", "notifications", "for", "any", "of", "the", "deleted", "channels", "even", "after", "UnlistenAll", "has", "returned", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/notify.go#L563-L584
11,102
square/certigo
starttls/psql/notify.go
Ping
func (l *Listener) Ping() error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } if l.cn == nil { return errors.New("no connection") } return l.cn.Ping() }
go
func (l *Listener) Ping() error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } if l.cn == nil { return errors.New("no connection") } return l.cn.Ping() }
[ "func", "(", "l", "*", "Listener", ")", "Ping", "(", ")", "error", "{", "l", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "l", ".", "isClosed", "{", "return", "errListenerClosed", "\n", "}", "\n", "if", "l", ".", "cn", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "l", ".", "cn", ".", "Ping", "(", ")", "\n", "}" ]
// Ping the remote server to make sure it's alive. Non-nil return value means // that there is no active connection.
[ "Ping", "the", "remote", "server", "to", "make", "sure", "it", "s", "alive", ".", "Non", "-", "nil", "return", "value", "means", "that", "there", "is", "no", "active", "connection", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/notify.go#L588-L600
11,103
square/certigo
starttls/psql/notify.go
resync
func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error { doneChan := make(chan error) go func() { for channel := range l.channels { // If we got a response, return that error to our caller as it's // going to be more descriptive than cn.Err(). gotResponse, err := cn.Listen(channel) if gotResponse && err != nil { doneChan <- err return } // If we couldn't reach the server, wait for notificationChan to // close and then return the error message from the connection, as // per ListenerConn's interface. if err != nil { for _ = range notificationChan { } doneChan <- cn.Err() return } } doneChan <- nil }() // Ignore notifications while synchronization is going on to avoid // deadlocks. We have to send a nil notification over Notify anyway as // we can't possibly know which notifications (if any) were lost while // the connection was down, so there's no reason to try and process // these messages at all. for { select { case _, ok := <-notificationChan: if !ok { notificationChan = nil } case err := <-doneChan: return err } } }
go
func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error { doneChan := make(chan error) go func() { for channel := range l.channels { // If we got a response, return that error to our caller as it's // going to be more descriptive than cn.Err(). gotResponse, err := cn.Listen(channel) if gotResponse && err != nil { doneChan <- err return } // If we couldn't reach the server, wait for notificationChan to // close and then return the error message from the connection, as // per ListenerConn's interface. if err != nil { for _ = range notificationChan { } doneChan <- cn.Err() return } } doneChan <- nil }() // Ignore notifications while synchronization is going on to avoid // deadlocks. We have to send a nil notification over Notify anyway as // we can't possibly know which notifications (if any) were lost while // the connection was down, so there's no reason to try and process // these messages at all. for { select { case _, ok := <-notificationChan: if !ok { notificationChan = nil } case err := <-doneChan: return err } } }
[ "func", "(", "l", "*", "Listener", ")", "resync", "(", "cn", "*", "ListenerConn", ",", "notificationChan", "<-", "chan", "*", "Notification", ")", "error", "{", "doneChan", ":=", "make", "(", "chan", "error", ")", "\n", "go", "func", "(", ")", "{", "for", "channel", ":=", "range", "l", ".", "channels", "{", "// If we got a response, return that error to our caller as it's", "// going to be more descriptive than cn.Err().", "gotResponse", ",", "err", ":=", "cn", ".", "Listen", "(", "channel", ")", "\n", "if", "gotResponse", "&&", "err", "!=", "nil", "{", "doneChan", "<-", "err", "\n", "return", "\n", "}", "\n\n", "// If we couldn't reach the server, wait for notificationChan to", "// close and then return the error message from the connection, as", "// per ListenerConn's interface.", "if", "err", "!=", "nil", "{", "for", "_", "=", "range", "notificationChan", "{", "}", "\n", "doneChan", "<-", "cn", ".", "Err", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "doneChan", "<-", "nil", "\n", "}", "(", ")", "\n\n", "// Ignore notifications while synchronization is going on to avoid", "// deadlocks. We have to send a nil notification over Notify anyway as", "// we can't possibly know which notifications (if any) were lost while", "// the connection was down, so there's no reason to try and process", "// these messages at all.", "for", "{", "select", "{", "case", "_", ",", "ok", ":=", "<-", "notificationChan", ":", "if", "!", "ok", "{", "notificationChan", "=", "nil", "\n", "}", "\n\n", "case", "err", ":=", "<-", "doneChan", ":", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// Synchronize the list of channels we want to be listening on with the server // after the connection has been established.
[ "Synchronize", "the", "list", "of", "channels", "we", "want", "to", "be", "listening", "on", "with", "the", "server", "after", "the", "connection", "has", "been", "established", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/notify.go#L626-L667
11,104
square/certigo
starttls/psql/notify.go
closed
func (l *Listener) closed() bool { l.lock.Lock() defer l.lock.Unlock() return l.isClosed }
go
func (l *Listener) closed() bool { l.lock.Lock() defer l.lock.Unlock() return l.isClosed }
[ "func", "(", "l", "*", "Listener", ")", "closed", "(", ")", "bool", "{", "l", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "return", "l", ".", "isClosed", "\n", "}" ]
// caller should NOT be holding l.lock
[ "caller", "should", "NOT", "be", "holding", "l", ".", "lock" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/notify.go#L670-L675
11,105
square/certigo
starttls/psql/notify.go
Close
func (l *Listener) Close() error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } if l.cn != nil { l.cn.Close() } l.isClosed = true return nil }
go
func (l *Listener) Close() error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } if l.cn != nil { l.cn.Close() } l.isClosed = true return nil }
[ "func", "(", "l", "*", "Listener", ")", "Close", "(", ")", "error", "{", "l", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "l", ".", "isClosed", "{", "return", "errListenerClosed", "\n", "}", "\n\n", "if", "l", ".", "cn", "!=", "nil", "{", "l", ".", "cn", ".", "Close", "(", ")", "\n", "}", "\n", "l", ".", "isClosed", "=", "true", "\n\n", "return", "nil", "\n", "}" ]
// Close disconnects the Listener from the database and shuts it down. // Subsequent calls to its methods will return an error. Close returns an // error if the connection has already been closed.
[ "Close", "disconnects", "the", "Listener", "from", "the", "database", "and", "shuts", "it", "down", ".", "Subsequent", "calls", "to", "its", "methods", "will", "return", "an", "error", ".", "Close", "returns", "an", "error", "if", "the", "connection", "has", "already", "been", "closed", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/notify.go#L703-L717
11,106
square/certigo
starttls/psql/encode.go
appendEncodedText
func appendEncodedText(parameterStatus *parameterStatus, buf []byte, x interface{}) []byte { switch v := x.(type) { case int64: return strconv.AppendInt(buf, v, 10) case float64: return strconv.AppendFloat(buf, v, 'f', -1, 64) case []byte: encodedBytea := encodeBytea(parameterStatus.serverVersion, v) return appendEscapedText(buf, string(encodedBytea)) case string: return appendEscapedText(buf, v) case bool: return strconv.AppendBool(buf, v) case time.Time: return append(buf, formatTs(v)...) case nil: return append(buf, "\\N"...) default: errorf("encode: unknown type for %T", v) } panic("not reached") }
go
func appendEncodedText(parameterStatus *parameterStatus, buf []byte, x interface{}) []byte { switch v := x.(type) { case int64: return strconv.AppendInt(buf, v, 10) case float64: return strconv.AppendFloat(buf, v, 'f', -1, 64) case []byte: encodedBytea := encodeBytea(parameterStatus.serverVersion, v) return appendEscapedText(buf, string(encodedBytea)) case string: return appendEscapedText(buf, v) case bool: return strconv.AppendBool(buf, v) case time.Time: return append(buf, formatTs(v)...) case nil: return append(buf, "\\N"...) default: errorf("encode: unknown type for %T", v) } panic("not reached") }
[ "func", "appendEncodedText", "(", "parameterStatus", "*", "parameterStatus", ",", "buf", "[", "]", "byte", ",", "x", "interface", "{", "}", ")", "[", "]", "byte", "{", "switch", "v", ":=", "x", ".", "(", "type", ")", "{", "case", "int64", ":", "return", "strconv", ".", "AppendInt", "(", "buf", ",", "v", ",", "10", ")", "\n", "case", "float64", ":", "return", "strconv", ".", "AppendFloat", "(", "buf", ",", "v", ",", "'f'", ",", "-", "1", ",", "64", ")", "\n", "case", "[", "]", "byte", ":", "encodedBytea", ":=", "encodeBytea", "(", "parameterStatus", ".", "serverVersion", ",", "v", ")", "\n", "return", "appendEscapedText", "(", "buf", ",", "string", "(", "encodedBytea", ")", ")", "\n", "case", "string", ":", "return", "appendEscapedText", "(", "buf", ",", "v", ")", "\n", "case", "bool", ":", "return", "strconv", ".", "AppendBool", "(", "buf", ",", "v", ")", "\n", "case", "time", ".", "Time", ":", "return", "append", "(", "buf", ",", "formatTs", "(", "v", ")", "...", ")", "\n", "case", "nil", ":", "return", "append", "(", "buf", ",", "\"", "\\\\", "\"", "...", ")", "\n", "default", ":", "errorf", "(", "\"", "\"", ",", "v", ")", "\n", "}", "\n\n", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// appendEncodedText encodes item in text format as required by COPY // and appends to buf
[ "appendEncodedText", "encodes", "item", "in", "text", "format", "as", "required", "by", "COPY", "and", "appends", "to", "buf" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/encode.go#L136-L158
11,107
square/certigo
starttls/psql/encode.go
getLocation
func (c *locationCache) getLocation(offset int) *time.Location { c.lock.Lock() defer c.lock.Unlock() location, ok := c.cache[offset] if !ok { location = time.FixedZone("", offset) c.cache[offset] = location } return location }
go
func (c *locationCache) getLocation(offset int) *time.Location { c.lock.Lock() defer c.lock.Unlock() location, ok := c.cache[offset] if !ok { location = time.FixedZone("", offset) c.cache[offset] = location } return location }
[ "func", "(", "c", "*", "locationCache", ")", "getLocation", "(", "offset", "int", ")", "*", "time", ".", "Location", "{", "c", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "location", ",", "ok", ":=", "c", ".", "cache", "[", "offset", "]", "\n", "if", "!", "ok", "{", "location", "=", "time", ".", "FixedZone", "(", "\"", "\"", ",", "offset", ")", "\n", "c", ".", "cache", "[", "offset", "]", "=", "location", "\n", "}", "\n\n", "return", "location", "\n", "}" ]
// Returns the cached timezone for the specified offset, creating and caching // it if necessary.
[ "Returns", "the", "cached", "timezone", "for", "the", "specified", "offset", "creating", "and", "caching", "it", "if", "necessary", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/encode.go#L268-L279
11,108
square/certigo
starttls/psql/encode.go
formatTs
func formatTs(t time.Time) []byte { if infinityTsEnabled { // t <= -infinity : ! (t > -infinity) if !t.After(infinityTsNegative) { return []byte("-infinity") } // t >= infinity : ! (!t < infinity) if !t.Before(infinityTsPositive) { return []byte("infinity") } } return FormatTimestamp(t) }
go
func formatTs(t time.Time) []byte { if infinityTsEnabled { // t <= -infinity : ! (t > -infinity) if !t.After(infinityTsNegative) { return []byte("-infinity") } // t >= infinity : ! (!t < infinity) if !t.Before(infinityTsPositive) { return []byte("infinity") } } return FormatTimestamp(t) }
[ "func", "formatTs", "(", "t", "time", ".", "Time", ")", "[", "]", "byte", "{", "if", "infinityTsEnabled", "{", "// t <= -infinity : ! (t > -infinity)", "if", "!", "t", ".", "After", "(", "infinityTsNegative", ")", "{", "return", "[", "]", "byte", "(", "\"", "\"", ")", "\n", "}", "\n", "// t >= infinity : ! (!t < infinity)", "if", "!", "t", ".", "Before", "(", "infinityTsPositive", ")", "{", "return", "[", "]", "byte", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "FormatTimestamp", "(", "t", ")", "\n", "}" ]
// formatTs formats t into a format postgres understands.
[ "formatTs", "formats", "t", "into", "a", "format", "postgres", "understands", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/encode.go#L455-L467
11,109
square/certigo
starttls/psql/encode.go
FormatTimestamp
func FormatTimestamp(t time.Time) []byte { // Need to send dates before 0001 A.D. with " BC" suffix, instead of the // minus sign preferred by Go. // Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on bc := false if t.Year() <= 0 { // flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11" t = t.AddDate((-t.Year())*2+1, 0, 0) bc = true } b := []byte(t.Format("2006-01-02 15:04:05.999999999Z07:00")) _, offset := t.Zone() offset = offset % 60 if offset != 0 { // RFC3339Nano already printed the minus sign if offset < 0 { offset = -offset } b = append(b, ':') if offset < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(offset), 10) } if bc { b = append(b, " BC"...) } return b }
go
func FormatTimestamp(t time.Time) []byte { // Need to send dates before 0001 A.D. with " BC" suffix, instead of the // minus sign preferred by Go. // Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on bc := false if t.Year() <= 0 { // flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11" t = t.AddDate((-t.Year())*2+1, 0, 0) bc = true } b := []byte(t.Format("2006-01-02 15:04:05.999999999Z07:00")) _, offset := t.Zone() offset = offset % 60 if offset != 0 { // RFC3339Nano already printed the minus sign if offset < 0 { offset = -offset } b = append(b, ':') if offset < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(offset), 10) } if bc { b = append(b, " BC"...) } return b }
[ "func", "FormatTimestamp", "(", "t", "time", ".", "Time", ")", "[", "]", "byte", "{", "// Need to send dates before 0001 A.D. with \" BC\" suffix, instead of the", "// minus sign preferred by Go.", "// Beware, \"0000\" in ISO is \"1 BC\", \"-0001\" is \"2 BC\" and so on", "bc", ":=", "false", "\n", "if", "t", ".", "Year", "(", ")", "<=", "0", "{", "// flip year sign, and add 1, e.g: \"0\" will be \"1\", and \"-10\" will be \"11\"", "t", "=", "t", ".", "AddDate", "(", "(", "-", "t", ".", "Year", "(", ")", ")", "*", "2", "+", "1", ",", "0", ",", "0", ")", "\n", "bc", "=", "true", "\n", "}", "\n", "b", ":=", "[", "]", "byte", "(", "t", ".", "Format", "(", "\"", "\"", ")", ")", "\n\n", "_", ",", "offset", ":=", "t", ".", "Zone", "(", ")", "\n", "offset", "=", "offset", "%", "60", "\n", "if", "offset", "!=", "0", "{", "// RFC3339Nano already printed the minus sign", "if", "offset", "<", "0", "{", "offset", "=", "-", "offset", "\n", "}", "\n\n", "b", "=", "append", "(", "b", ",", "':'", ")", "\n", "if", "offset", "<", "10", "{", "b", "=", "append", "(", "b", ",", "'0'", ")", "\n", "}", "\n", "b", "=", "strconv", ".", "AppendInt", "(", "b", ",", "int64", "(", "offset", ")", ",", "10", ")", "\n", "}", "\n\n", "if", "bc", "{", "b", "=", "append", "(", "b", ",", "\"", "\"", "...", ")", "\n", "}", "\n", "return", "b", "\n", "}" ]
// FormatTimestamp formats t into Postgres' text format for timestamps.
[ "FormatTimestamp", "formats", "t", "into", "Postgres", "text", "format", "for", "timestamps", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/encode.go#L470-L501
11,110
square/certigo
starttls/psql/encode.go
parseBytea
func parseBytea(s []byte) (result []byte, err error) { if len(s) >= 2 && bytes.Equal(s[:2], []byte("\\x")) { // bytea_output = hex s = s[2:] // trim off leading "\\x" result = make([]byte, hex.DecodedLen(len(s))) _, err := hex.Decode(result, s) if err != nil { return nil, err } } else { // bytea_output = escape for len(s) > 0 { if s[0] == '\\' { // escaped '\\' if len(s) >= 2 && s[1] == '\\' { result = append(result, '\\') s = s[2:] continue } // '\\' followed by an octal number if len(s) < 4 { return nil, fmt.Errorf("invalid bytea sequence %v", s) } r, err := strconv.ParseInt(string(s[1:4]), 8, 9) if err != nil { return nil, fmt.Errorf("could not parse bytea value: %s", err.Error()) } result = append(result, byte(r)) s = s[4:] } else { // We hit an unescaped, raw byte. Try to read in as many as // possible in one go. i := bytes.IndexByte(s, '\\') if i == -1 { result = append(result, s...) break } result = append(result, s[:i]...) s = s[i:] } } } return result, nil }
go
func parseBytea(s []byte) (result []byte, err error) { if len(s) >= 2 && bytes.Equal(s[:2], []byte("\\x")) { // bytea_output = hex s = s[2:] // trim off leading "\\x" result = make([]byte, hex.DecodedLen(len(s))) _, err := hex.Decode(result, s) if err != nil { return nil, err } } else { // bytea_output = escape for len(s) > 0 { if s[0] == '\\' { // escaped '\\' if len(s) >= 2 && s[1] == '\\' { result = append(result, '\\') s = s[2:] continue } // '\\' followed by an octal number if len(s) < 4 { return nil, fmt.Errorf("invalid bytea sequence %v", s) } r, err := strconv.ParseInt(string(s[1:4]), 8, 9) if err != nil { return nil, fmt.Errorf("could not parse bytea value: %s", err.Error()) } result = append(result, byte(r)) s = s[4:] } else { // We hit an unescaped, raw byte. Try to read in as many as // possible in one go. i := bytes.IndexByte(s, '\\') if i == -1 { result = append(result, s...) break } result = append(result, s[:i]...) s = s[i:] } } } return result, nil }
[ "func", "parseBytea", "(", "s", "[", "]", "byte", ")", "(", "result", "[", "]", "byte", ",", "err", "error", ")", "{", "if", "len", "(", "s", ")", ">=", "2", "&&", "bytes", ".", "Equal", "(", "s", "[", ":", "2", "]", ",", "[", "]", "byte", "(", "\"", "\\\\", "\"", ")", ")", "{", "// bytea_output = hex", "s", "=", "s", "[", "2", ":", "]", "// trim off leading \"\\\\x\"", "\n", "result", "=", "make", "(", "[", "]", "byte", ",", "hex", ".", "DecodedLen", "(", "len", "(", "s", ")", ")", ")", "\n", "_", ",", "err", ":=", "hex", ".", "Decode", "(", "result", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "// bytea_output = escape", "for", "len", "(", "s", ")", ">", "0", "{", "if", "s", "[", "0", "]", "==", "'\\\\'", "{", "// escaped '\\\\'", "if", "len", "(", "s", ")", ">=", "2", "&&", "s", "[", "1", "]", "==", "'\\\\'", "{", "result", "=", "append", "(", "result", ",", "'\\\\'", ")", "\n", "s", "=", "s", "[", "2", ":", "]", "\n", "continue", "\n", "}", "\n\n", "// '\\\\' followed by an octal number", "if", "len", "(", "s", ")", "<", "4", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "r", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "string", "(", "s", "[", "1", ":", "4", "]", ")", ",", "8", ",", "9", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "byte", "(", "r", ")", ")", "\n", "s", "=", "s", "[", "4", ":", "]", "\n", "}", "else", "{", "// We hit an unescaped, raw byte. Try to read in as many as", "// possible in one go.", "i", ":=", "bytes", ".", "IndexByte", "(", "s", ",", "'\\\\'", ")", "\n", "if", "i", "==", "-", "1", "{", "result", "=", "append", "(", "result", ",", "s", "...", ")", "\n", "break", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "s", "[", ":", "i", "]", "...", ")", "\n", "s", "=", "s", "[", "i", ":", "]", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// Parse a bytea value received from the server. Both "hex" and the legacy // "escape" format are supported.
[ "Parse", "a", "bytea", "value", "received", "from", "the", "server", ".", "Both", "hex", "and", "the", "legacy", "escape", "format", "are", "supported", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/encode.go#L505-L550
11,111
square/certigo
starttls/ldap/bind.go
NewSimpleBindRequest
func NewSimpleBindRequest(username string, password string, controls []Control) *SimpleBindRequest { return &SimpleBindRequest{ Username: username, Password: password, Controls: controls, } }
go
func NewSimpleBindRequest(username string, password string, controls []Control) *SimpleBindRequest { return &SimpleBindRequest{ Username: username, Password: password, Controls: controls, } }
[ "func", "NewSimpleBindRequest", "(", "username", "string", ",", "password", "string", ",", "controls", "[", "]", "Control", ")", "*", "SimpleBindRequest", "{", "return", "&", "SimpleBindRequest", "{", "Username", ":", "username", ",", "Password", ":", "password", ",", "Controls", ":", "controls", ",", "}", "\n", "}" ]
// NewSimpleBindRequest returns a bind request
[ "NewSimpleBindRequest", "returns", "a", "bind", "request" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/bind.go#L29-L35
11,112
square/certigo
starttls/ldap/bind.go
SimpleBind
func (l *Conn) SimpleBind(simpleBindRequest *SimpleBindRequest) (*SimpleBindResult, error) { packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID")) encodedBindRequest := simpleBindRequest.encode() packet.AppendChild(encodedBindRequest) if l.Debug { ber.PrintPacket(packet) } msgCtx, err := l.sendMessage(packet) if err != nil { return nil, err } defer l.finishMessage(msgCtx) packetResponse, ok := <-msgCtx.responses if !ok { return nil, NewError(ErrorNetwork, errors.New("ldap: response channel closed")) } packet, err = packetResponse.ReadPacket() l.Debug.Printf("%d: got response %p", msgCtx.id, packet) if err != nil { return nil, err } if l.Debug { if err := addLDAPDescriptions(packet); err != nil { return nil, err } ber.PrintPacket(packet) } result := &SimpleBindResult{ Controls: make([]Control, 0), } if len(packet.Children) == 3 { for _, child := range packet.Children[2].Children { result.Controls = append(result.Controls, DecodeControl(child)) } } resultCode, resultDescription := getLDAPResultCode(packet) if resultCode != 0 { return result, NewError(resultCode, errors.New(resultDescription)) } return result, nil }
go
func (l *Conn) SimpleBind(simpleBindRequest *SimpleBindRequest) (*SimpleBindResult, error) { packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID")) encodedBindRequest := simpleBindRequest.encode() packet.AppendChild(encodedBindRequest) if l.Debug { ber.PrintPacket(packet) } msgCtx, err := l.sendMessage(packet) if err != nil { return nil, err } defer l.finishMessage(msgCtx) packetResponse, ok := <-msgCtx.responses if !ok { return nil, NewError(ErrorNetwork, errors.New("ldap: response channel closed")) } packet, err = packetResponse.ReadPacket() l.Debug.Printf("%d: got response %p", msgCtx.id, packet) if err != nil { return nil, err } if l.Debug { if err := addLDAPDescriptions(packet); err != nil { return nil, err } ber.PrintPacket(packet) } result := &SimpleBindResult{ Controls: make([]Control, 0), } if len(packet.Children) == 3 { for _, child := range packet.Children[2].Children { result.Controls = append(result.Controls, DecodeControl(child)) } } resultCode, resultDescription := getLDAPResultCode(packet) if resultCode != 0 { return result, NewError(resultCode, errors.New(resultDescription)) } return result, nil }
[ "func", "(", "l", "*", "Conn", ")", "SimpleBind", "(", "simpleBindRequest", "*", "SimpleBindRequest", ")", "(", "*", "SimpleBindResult", ",", "error", ")", "{", "packet", ":=", "ber", ".", "Encode", "(", "ber", ".", "ClassUniversal", ",", "ber", ".", "TypeConstructed", ",", "ber", ".", "TagSequence", ",", "nil", ",", "\"", "\"", ")", "\n", "packet", ".", "AppendChild", "(", "ber", ".", "NewInteger", "(", "ber", ".", "ClassUniversal", ",", "ber", ".", "TypePrimitive", ",", "ber", ".", "TagInteger", ",", "l", ".", "nextMessageID", "(", ")", ",", "\"", "\"", ")", ")", "\n", "encodedBindRequest", ":=", "simpleBindRequest", ".", "encode", "(", ")", "\n", "packet", ".", "AppendChild", "(", "encodedBindRequest", ")", "\n\n", "if", "l", ".", "Debug", "{", "ber", ".", "PrintPacket", "(", "packet", ")", "\n", "}", "\n\n", "msgCtx", ",", "err", ":=", "l", ".", "sendMessage", "(", "packet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "l", ".", "finishMessage", "(", "msgCtx", ")", "\n\n", "packetResponse", ",", "ok", ":=", "<-", "msgCtx", ".", "responses", "\n", "if", "!", "ok", "{", "return", "nil", ",", "NewError", "(", "ErrorNetwork", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "packet", ",", "err", "=", "packetResponse", ".", "ReadPacket", "(", ")", "\n", "l", ".", "Debug", ".", "Printf", "(", "\"", "\"", ",", "msgCtx", ".", "id", ",", "packet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "l", ".", "Debug", "{", "if", "err", ":=", "addLDAPDescriptions", "(", "packet", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ber", ".", "PrintPacket", "(", "packet", ")", "\n", "}", "\n\n", "result", ":=", "&", "SimpleBindResult", "{", "Controls", ":", "make", "(", "[", "]", "Control", ",", "0", ")", ",", "}", "\n\n", "if", "len", "(", "packet", ".", "Children", ")", "==", "3", "{", "for", "_", ",", "child", ":=", "range", "packet", ".", "Children", "[", "2", "]", ".", "Children", "{", "result", ".", "Controls", "=", "append", "(", "result", ".", "Controls", ",", "DecodeControl", "(", "child", ")", ")", "\n", "}", "\n", "}", "\n\n", "resultCode", ",", "resultDescription", ":=", "getLDAPResultCode", "(", "packet", ")", "\n", "if", "resultCode", "!=", "0", "{", "return", "result", ",", "NewError", "(", "resultCode", ",", "errors", ".", "New", "(", "resultDescription", ")", ")", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// SimpleBind performs the simple bind operation defined in the given request
[ "SimpleBind", "performs", "the", "simple", "bind", "operation", "defined", "in", "the", "given", "request" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/bind.go#L49-L98
11,113
square/certigo
starttls/ldap/bind.go
Bind
func (l *Conn) Bind(username, password string) error { packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID")) bindRequest := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request") bindRequest.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version")) bindRequest.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, username, "User Name")) bindRequest.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, password, "Password")) packet.AppendChild(bindRequest) if l.Debug { ber.PrintPacket(packet) } msgCtx, err := l.sendMessage(packet) if err != nil { return err } defer l.finishMessage(msgCtx) packetResponse, ok := <-msgCtx.responses if !ok { return NewError(ErrorNetwork, errors.New("ldap: response channel closed")) } packet, err = packetResponse.ReadPacket() l.Debug.Printf("%d: got response %p", msgCtx.id, packet) if err != nil { return err } if l.Debug { if err := addLDAPDescriptions(packet); err != nil { return err } ber.PrintPacket(packet) } resultCode, resultDescription := getLDAPResultCode(packet) if resultCode != 0 { return NewError(resultCode, errors.New(resultDescription)) } return nil }
go
func (l *Conn) Bind(username, password string) error { packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID")) bindRequest := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request") bindRequest.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version")) bindRequest.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, username, "User Name")) bindRequest.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, password, "Password")) packet.AppendChild(bindRequest) if l.Debug { ber.PrintPacket(packet) } msgCtx, err := l.sendMessage(packet) if err != nil { return err } defer l.finishMessage(msgCtx) packetResponse, ok := <-msgCtx.responses if !ok { return NewError(ErrorNetwork, errors.New("ldap: response channel closed")) } packet, err = packetResponse.ReadPacket() l.Debug.Printf("%d: got response %p", msgCtx.id, packet) if err != nil { return err } if l.Debug { if err := addLDAPDescriptions(packet); err != nil { return err } ber.PrintPacket(packet) } resultCode, resultDescription := getLDAPResultCode(packet) if resultCode != 0 { return NewError(resultCode, errors.New(resultDescription)) } return nil }
[ "func", "(", "l", "*", "Conn", ")", "Bind", "(", "username", ",", "password", "string", ")", "error", "{", "packet", ":=", "ber", ".", "Encode", "(", "ber", ".", "ClassUniversal", ",", "ber", ".", "TypeConstructed", ",", "ber", ".", "TagSequence", ",", "nil", ",", "\"", "\"", ")", "\n", "packet", ".", "AppendChild", "(", "ber", ".", "NewInteger", "(", "ber", ".", "ClassUniversal", ",", "ber", ".", "TypePrimitive", ",", "ber", ".", "TagInteger", ",", "l", ".", "nextMessageID", "(", ")", ",", "\"", "\"", ")", ")", "\n", "bindRequest", ":=", "ber", ".", "Encode", "(", "ber", ".", "ClassApplication", ",", "ber", ".", "TypeConstructed", ",", "ApplicationBindRequest", ",", "nil", ",", "\"", "\"", ")", "\n", "bindRequest", ".", "AppendChild", "(", "ber", ".", "NewInteger", "(", "ber", ".", "ClassUniversal", ",", "ber", ".", "TypePrimitive", ",", "ber", ".", "TagInteger", ",", "3", ",", "\"", "\"", ")", ")", "\n", "bindRequest", ".", "AppendChild", "(", "ber", ".", "NewString", "(", "ber", ".", "ClassUniversal", ",", "ber", ".", "TypePrimitive", ",", "ber", ".", "TagOctetString", ",", "username", ",", "\"", "\"", ")", ")", "\n", "bindRequest", ".", "AppendChild", "(", "ber", ".", "NewString", "(", "ber", ".", "ClassContext", ",", "ber", ".", "TypePrimitive", ",", "0", ",", "password", ",", "\"", "\"", ")", ")", "\n", "packet", ".", "AppendChild", "(", "bindRequest", ")", "\n\n", "if", "l", ".", "Debug", "{", "ber", ".", "PrintPacket", "(", "packet", ")", "\n", "}", "\n\n", "msgCtx", ",", "err", ":=", "l", ".", "sendMessage", "(", "packet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "l", ".", "finishMessage", "(", "msgCtx", ")", "\n\n", "packetResponse", ",", "ok", ":=", "<-", "msgCtx", ".", "responses", "\n", "if", "!", "ok", "{", "return", "NewError", "(", "ErrorNetwork", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "packet", ",", "err", "=", "packetResponse", ".", "ReadPacket", "(", ")", "\n", "l", ".", "Debug", ".", "Printf", "(", "\"", "\"", ",", "msgCtx", ".", "id", ",", "packet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "l", ".", "Debug", "{", "if", "err", ":=", "addLDAPDescriptions", "(", "packet", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ber", ".", "PrintPacket", "(", "packet", ")", "\n", "}", "\n\n", "resultCode", ",", "resultDescription", ":=", "getLDAPResultCode", "(", "packet", ")", "\n", "if", "resultCode", "!=", "0", "{", "return", "NewError", "(", "resultCode", ",", "errors", ".", "New", "(", "resultDescription", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Bind performs a bind with the given username and password
[ "Bind", "performs", "a", "bind", "with", "the", "given", "username", "and", "password" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/bind.go#L101-L143
11,114
square/certigo
starttls/ldap/error.go
NewError
func NewError(resultCode uint8, err error) error { return &Error{ResultCode: resultCode, Err: err} }
go
func NewError(resultCode uint8, err error) error { return &Error{ResultCode: resultCode, Err: err} }
[ "func", "NewError", "(", "resultCode", "uint8", ",", "err", "error", ")", "error", "{", "return", "&", "Error", "{", "ResultCode", ":", "resultCode", ",", "Err", ":", "err", "}", "\n", "}" ]
// NewError creates an LDAP error with the given code and underlying error
[ "NewError", "creates", "an", "LDAP", "error", "with", "the", "given", "code", "and", "underlying", "error" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/error.go#L139-L141
11,115
square/certigo
starttls/ldap/error.go
IsErrorWithCode
func IsErrorWithCode(err error, desiredResultCode uint8) bool { if err == nil { return false } serverError, ok := err.(*Error) if !ok { return false } return serverError.ResultCode == desiredResultCode }
go
func IsErrorWithCode(err error, desiredResultCode uint8) bool { if err == nil { return false } serverError, ok := err.(*Error) if !ok { return false } return serverError.ResultCode == desiredResultCode }
[ "func", "IsErrorWithCode", "(", "err", "error", ",", "desiredResultCode", "uint8", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "serverError", ",", "ok", ":=", "err", ".", "(", "*", "Error", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "return", "serverError", ".", "ResultCode", "==", "desiredResultCode", "\n", "}" ]
// IsErrorWithCode returns true if the given error is an LDAP error with the given result code
[ "IsErrorWithCode", "returns", "true", "if", "the", "given", "error", "is", "an", "LDAP", "error", "with", "the", "given", "result", "code" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/error.go#L144-L155
11,116
square/certigo
starttls/ldap/filter.go
CompileFilter
func CompileFilter(filter string) (*ber.Packet, error) { if len(filter) == 0 || filter[0] != '(' { return nil, NewError(ErrorFilterCompile, errors.New("ldap: filter does not start with an '('")) } packet, pos, err := compileFilter(filter, 1) if err != nil { return nil, err } if pos != len(filter) { return nil, NewError(ErrorFilterCompile, errors.New("ldap: finished compiling filter with extra at end: "+fmt.Sprint(filter[pos:]))) } return packet, nil }
go
func CompileFilter(filter string) (*ber.Packet, error) { if len(filter) == 0 || filter[0] != '(' { return nil, NewError(ErrorFilterCompile, errors.New("ldap: filter does not start with an '('")) } packet, pos, err := compileFilter(filter, 1) if err != nil { return nil, err } if pos != len(filter) { return nil, NewError(ErrorFilterCompile, errors.New("ldap: finished compiling filter with extra at end: "+fmt.Sprint(filter[pos:]))) } return packet, nil }
[ "func", "CompileFilter", "(", "filter", "string", ")", "(", "*", "ber", ".", "Packet", ",", "error", ")", "{", "if", "len", "(", "filter", ")", "==", "0", "||", "filter", "[", "0", "]", "!=", "'('", "{", "return", "nil", ",", "NewError", "(", "ErrorFilterCompile", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "packet", ",", "pos", ",", "err", ":=", "compileFilter", "(", "filter", ",", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "pos", "!=", "len", "(", "filter", ")", "{", "return", "nil", ",", "NewError", "(", "ErrorFilterCompile", ",", "errors", ".", "New", "(", "\"", "\"", "+", "fmt", ".", "Sprint", "(", "filter", "[", "pos", ":", "]", ")", ")", ")", "\n", "}", "\n", "return", "packet", ",", "nil", "\n", "}" ]
// CompileFilter converts a string representation of a filter into a BER-encoded packet
[ "CompileFilter", "converts", "a", "string", "representation", "of", "a", "filter", "into", "a", "BER", "-", "encoded", "packet" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/filter.go#L77-L89
11,117
square/certigo
starttls/ldap/filter.go
escapedStringToEncodedBytes
func escapedStringToEncodedBytes(escapedString string) (string, error) { var buffer bytes.Buffer i := 0 for i < len(escapedString) { currentRune, currentWidth := utf8.DecodeRuneInString(escapedString[i:]) if currentRune == utf8.RuneError { return "", NewError(ErrorFilterCompile, fmt.Errorf("ldap: error reading rune at position %d", i)) } // Check for escaped hex characters and convert them to their literal value for transport. if currentRune == '\\' { // http://tools.ietf.org/search/rfc4515 // \ (%x5C) is not a valid character unless it is followed by two HEX characters due to not // being a member of UTF1SUBSET. if i+2 > len(escapedString) { return "", NewError(ErrorFilterCompile, errors.New("ldap: missing characters for escape in filter")) } escByte, decodeErr := hexpac.DecodeString(escapedString[i+1 : i+3]) if decodeErr != nil { return "", NewError(ErrorFilterCompile, errors.New("ldap: invalid characters for escape in filter")) } buffer.WriteByte(escByte[0]) i += 2 // +1 from end of loop, so 3 total for \xx. } else { buffer.WriteRune(currentRune) } i += currentWidth } return buffer.String(), nil }
go
func escapedStringToEncodedBytes(escapedString string) (string, error) { var buffer bytes.Buffer i := 0 for i < len(escapedString) { currentRune, currentWidth := utf8.DecodeRuneInString(escapedString[i:]) if currentRune == utf8.RuneError { return "", NewError(ErrorFilterCompile, fmt.Errorf("ldap: error reading rune at position %d", i)) } // Check for escaped hex characters and convert them to their literal value for transport. if currentRune == '\\' { // http://tools.ietf.org/search/rfc4515 // \ (%x5C) is not a valid character unless it is followed by two HEX characters due to not // being a member of UTF1SUBSET. if i+2 > len(escapedString) { return "", NewError(ErrorFilterCompile, errors.New("ldap: missing characters for escape in filter")) } escByte, decodeErr := hexpac.DecodeString(escapedString[i+1 : i+3]) if decodeErr != nil { return "", NewError(ErrorFilterCompile, errors.New("ldap: invalid characters for escape in filter")) } buffer.WriteByte(escByte[0]) i += 2 // +1 from end of loop, so 3 total for \xx. } else { buffer.WriteRune(currentRune) } i += currentWidth } return buffer.String(), nil }
[ "func", "escapedStringToEncodedBytes", "(", "escapedString", "string", ")", "(", "string", ",", "error", ")", "{", "var", "buffer", "bytes", ".", "Buffer", "\n", "i", ":=", "0", "\n", "for", "i", "<", "len", "(", "escapedString", ")", "{", "currentRune", ",", "currentWidth", ":=", "utf8", ".", "DecodeRuneInString", "(", "escapedString", "[", "i", ":", "]", ")", "\n", "if", "currentRune", "==", "utf8", ".", "RuneError", "{", "return", "\"", "\"", ",", "NewError", "(", "ErrorFilterCompile", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "i", ")", ")", "\n", "}", "\n\n", "// Check for escaped hex characters and convert them to their literal value for transport.", "if", "currentRune", "==", "'\\\\'", "{", "// http://tools.ietf.org/search/rfc4515", "// \\ (%x5C) is not a valid character unless it is followed by two HEX characters due to not", "// being a member of UTF1SUBSET.", "if", "i", "+", "2", ">", "len", "(", "escapedString", ")", "{", "return", "\"", "\"", ",", "NewError", "(", "ErrorFilterCompile", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "escByte", ",", "decodeErr", ":=", "hexpac", ".", "DecodeString", "(", "escapedString", "[", "i", "+", "1", ":", "i", "+", "3", "]", ")", "\n", "if", "decodeErr", "!=", "nil", "{", "return", "\"", "\"", ",", "NewError", "(", "ErrorFilterCompile", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "buffer", ".", "WriteByte", "(", "escByte", "[", "0", "]", ")", "\n", "i", "+=", "2", "// +1 from end of loop, so 3 total for \\xx.", "\n", "}", "else", "{", "buffer", ".", "WriteRune", "(", "currentRune", ")", "\n", "}", "\n\n", "i", "+=", "currentWidth", "\n", "}", "\n", "return", "buffer", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// Convert from "ABC\xx\xx\xx" form to literal bytes for transport
[ "Convert", "from", "ABC", "\\", "xx", "\\", "xx", "\\", "xx", "form", "to", "literal", "bytes", "for", "transport" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/filter.go#L436-L466
11,118
square/certigo
starttls/ldap/del.go
NewDelRequest
func NewDelRequest(DN string, Controls []Control) *DelRequest { return &DelRequest{ DN: DN, Controls: Controls, } }
go
func NewDelRequest(DN string, Controls []Control) *DelRequest { return &DelRequest{ DN: DN, Controls: Controls, } }
[ "func", "NewDelRequest", "(", "DN", "string", ",", "Controls", "[", "]", "Control", ")", "*", "DelRequest", "{", "return", "&", "DelRequest", "{", "DN", ":", "DN", ",", "Controls", ":", "Controls", ",", "}", "\n", "}" ]
// NewDelRequest creates a delete request for the given DN and controls
[ "NewDelRequest", "creates", "a", "delete", "request", "for", "the", "given", "DN", "and", "controls" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/del.go#L30-L36
11,119
square/certigo
starttls/ldap/del.go
Del
func (l *Conn) Del(delRequest *DelRequest) error { packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID")) packet.AppendChild(delRequest.encode()) if delRequest.Controls != nil { packet.AppendChild(encodeControls(delRequest.Controls)) } l.Debug.PrintPacket(packet) msgCtx, err := l.sendMessage(packet) if err != nil { return err } defer l.finishMessage(msgCtx) l.Debug.Printf("%d: waiting for response", msgCtx.id) packetResponse, ok := <-msgCtx.responses if !ok { return NewError(ErrorNetwork, errors.New("ldap: response channel closed")) } packet, err = packetResponse.ReadPacket() l.Debug.Printf("%d: got response %p", msgCtx.id, packet) if err != nil { return err } if l.Debug { if err := addLDAPDescriptions(packet); err != nil { return err } ber.PrintPacket(packet) } if packet.Children[1].Tag == ApplicationDelResponse { resultCode, resultDescription := getLDAPResultCode(packet) if resultCode != 0 { return NewError(resultCode, errors.New(resultDescription)) } } else { log.Printf("Unexpected Response: %d", packet.Children[1].Tag) } l.Debug.Printf("%d: returning", msgCtx.id) return nil }
go
func (l *Conn) Del(delRequest *DelRequest) error { packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID")) packet.AppendChild(delRequest.encode()) if delRequest.Controls != nil { packet.AppendChild(encodeControls(delRequest.Controls)) } l.Debug.PrintPacket(packet) msgCtx, err := l.sendMessage(packet) if err != nil { return err } defer l.finishMessage(msgCtx) l.Debug.Printf("%d: waiting for response", msgCtx.id) packetResponse, ok := <-msgCtx.responses if !ok { return NewError(ErrorNetwork, errors.New("ldap: response channel closed")) } packet, err = packetResponse.ReadPacket() l.Debug.Printf("%d: got response %p", msgCtx.id, packet) if err != nil { return err } if l.Debug { if err := addLDAPDescriptions(packet); err != nil { return err } ber.PrintPacket(packet) } if packet.Children[1].Tag == ApplicationDelResponse { resultCode, resultDescription := getLDAPResultCode(packet) if resultCode != 0 { return NewError(resultCode, errors.New(resultDescription)) } } else { log.Printf("Unexpected Response: %d", packet.Children[1].Tag) } l.Debug.Printf("%d: returning", msgCtx.id) return nil }
[ "func", "(", "l", "*", "Conn", ")", "Del", "(", "delRequest", "*", "DelRequest", ")", "error", "{", "packet", ":=", "ber", ".", "Encode", "(", "ber", ".", "ClassUniversal", ",", "ber", ".", "TypeConstructed", ",", "ber", ".", "TagSequence", ",", "nil", ",", "\"", "\"", ")", "\n", "packet", ".", "AppendChild", "(", "ber", ".", "NewInteger", "(", "ber", ".", "ClassUniversal", ",", "ber", ".", "TypePrimitive", ",", "ber", ".", "TagInteger", ",", "l", ".", "nextMessageID", "(", ")", ",", "\"", "\"", ")", ")", "\n", "packet", ".", "AppendChild", "(", "delRequest", ".", "encode", "(", ")", ")", "\n", "if", "delRequest", ".", "Controls", "!=", "nil", "{", "packet", ".", "AppendChild", "(", "encodeControls", "(", "delRequest", ".", "Controls", ")", ")", "\n", "}", "\n\n", "l", ".", "Debug", ".", "PrintPacket", "(", "packet", ")", "\n\n", "msgCtx", ",", "err", ":=", "l", ".", "sendMessage", "(", "packet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "l", ".", "finishMessage", "(", "msgCtx", ")", "\n\n", "l", ".", "Debug", ".", "Printf", "(", "\"", "\"", ",", "msgCtx", ".", "id", ")", "\n", "packetResponse", ",", "ok", ":=", "<-", "msgCtx", ".", "responses", "\n", "if", "!", "ok", "{", "return", "NewError", "(", "ErrorNetwork", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "packet", ",", "err", "=", "packetResponse", ".", "ReadPacket", "(", ")", "\n", "l", ".", "Debug", ".", "Printf", "(", "\"", "\"", ",", "msgCtx", ".", "id", ",", "packet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "l", ".", "Debug", "{", "if", "err", ":=", "addLDAPDescriptions", "(", "packet", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ber", ".", "PrintPacket", "(", "packet", ")", "\n", "}", "\n\n", "if", "packet", ".", "Children", "[", "1", "]", ".", "Tag", "==", "ApplicationDelResponse", "{", "resultCode", ",", "resultDescription", ":=", "getLDAPResultCode", "(", "packet", ")", "\n", "if", "resultCode", "!=", "0", "{", "return", "NewError", "(", "resultCode", ",", "errors", ".", "New", "(", "resultDescription", ")", ")", "\n", "}", "\n", "}", "else", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "packet", ".", "Children", "[", "1", "]", ".", "Tag", ")", "\n", "}", "\n\n", "l", ".", "Debug", ".", "Printf", "(", "\"", "\"", ",", "msgCtx", ".", "id", ")", "\n", "return", "nil", "\n", "}" ]
// Del executes the given delete request
[ "Del", "executes", "the", "given", "delete", "request" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/del.go#L39-L84
11,120
square/certigo
starttls/psql/ssl_permissions.go
sslCertificatePermissions
func sslCertificatePermissions(cert, key os.FileInfo) { kmode := key.Mode() if kmode != kmode&0600 { panic(ErrSSLKeyHasWorldPermissions) } }
go
func sslCertificatePermissions(cert, key os.FileInfo) { kmode := key.Mode() if kmode != kmode&0600 { panic(ErrSSLKeyHasWorldPermissions) } }
[ "func", "sslCertificatePermissions", "(", "cert", ",", "key", "os", ".", "FileInfo", ")", "{", "kmode", ":=", "key", ".", "Mode", "(", ")", "\n", "if", "kmode", "!=", "kmode", "&", "0600", "{", "panic", "(", "ErrSSLKeyHasWorldPermissions", ")", "\n", "}", "\n", "}" ]
// sslCertificatePermissions checks the permissions on user-supplied certificate // files. The key file should have very little access. // // libpq does not check key file permissions on Windows.
[ "sslCertificatePermissions", "checks", "the", "permissions", "on", "user", "-", "supplied", "certificate", "files", ".", "The", "key", "file", "should", "have", "very", "little", "access", ".", "libpq", "does", "not", "check", "key", "file", "permissions", "on", "Windows", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/ssl_permissions.go#L11-L16
11,121
square/certigo
lib/encoder.go
hexify
func hexify(arr []byte) string { var hexed bytes.Buffer for i := 0; i < len(arr); i++ { hexed.WriteString(strings.ToUpper(hex.EncodeToString(arr[i : i+1]))) if i < len(arr)-1 { hexed.WriteString(":") } } return hexed.String() }
go
func hexify(arr []byte) string { var hexed bytes.Buffer for i := 0; i < len(arr); i++ { hexed.WriteString(strings.ToUpper(hex.EncodeToString(arr[i : i+1]))) if i < len(arr)-1 { hexed.WriteString(":") } } return hexed.String() }
[ "func", "hexify", "(", "arr", "[", "]", "byte", ")", "string", "{", "var", "hexed", "bytes", ".", "Buffer", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "arr", ")", ";", "i", "++", "{", "hexed", ".", "WriteString", "(", "strings", ".", "ToUpper", "(", "hex", ".", "EncodeToString", "(", "arr", "[", "i", ":", "i", "+", "1", "]", ")", ")", ")", "\n", "if", "i", "<", "len", "(", "arr", ")", "-", "1", "{", "hexed", ".", "WriteString", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "hexed", ".", "String", "(", ")", "\n", "}" ]
// hexify returns a colon separated, hexadecimal representation // of a given byte array.
[ "hexify", "returns", "a", "colon", "separated", "hexadecimal", "representation", "of", "a", "given", "byte", "array", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/encoder.go#L323-L332
11,122
square/certigo
lib/encoder.go
decodeKey
func decodeKey(publicKey interface{}) (string, int) { switch publicKey.(type) { case *dsa.PublicKey: return "DSA", publicKey.(*dsa.PublicKey).P.BitLen() case *ecdsa.PublicKey: return "ECDSA", publicKey.(*ecdsa.PublicKey).Curve.Params().BitSize case *rsa.PublicKey: return "RSA", publicKey.(*rsa.PublicKey).N.BitLen() default: return "", 0 } }
go
func decodeKey(publicKey interface{}) (string, int) { switch publicKey.(type) { case *dsa.PublicKey: return "DSA", publicKey.(*dsa.PublicKey).P.BitLen() case *ecdsa.PublicKey: return "ECDSA", publicKey.(*ecdsa.PublicKey).Curve.Params().BitSize case *rsa.PublicKey: return "RSA", publicKey.(*rsa.PublicKey).N.BitLen() default: return "", 0 } }
[ "func", "decodeKey", "(", "publicKey", "interface", "{", "}", ")", "(", "string", ",", "int", ")", "{", "switch", "publicKey", ".", "(", "type", ")", "{", "case", "*", "dsa", ".", "PublicKey", ":", "return", "\"", "\"", ",", "publicKey", ".", "(", "*", "dsa", ".", "PublicKey", ")", ".", "P", ".", "BitLen", "(", ")", "\n", "case", "*", "ecdsa", ".", "PublicKey", ":", "return", "\"", "\"", ",", "publicKey", ".", "(", "*", "ecdsa", ".", "PublicKey", ")", ".", "Curve", ".", "Params", "(", ")", ".", "BitSize", "\n", "case", "*", "rsa", ".", "PublicKey", ":", "return", "\"", "\"", ",", "publicKey", ".", "(", "*", "rsa", ".", "PublicKey", ")", ".", "N", ".", "BitLen", "(", ")", "\n", "default", ":", "return", "\"", "\"", ",", "0", "\n", "}", "\n", "}" ]
// decodeKey returns the algorithm and key size for a public key.
[ "decodeKey", "returns", "the", "algorithm", "and", "key", "size", "for", "a", "public", "key", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/encoder.go#L364-L375
11,123
square/certigo
lib/encoder.go
certWarnings
func certWarnings(cert *x509.Certificate, uriNames []string) (warnings []string) { if cert.SerialNumber.Sign() != 1 { warnings = append(warnings, "Serial number in cert appears to be zero/negative") } if cert.SerialNumber.BitLen() > 160 { warnings = append(warnings, "Serial number too long; should be 20 bytes or less") } if cert.KeyUsage&x509.KeyUsageCertSign != 0 && !cert.IsCA { warnings = append(warnings, "Key usage 'cert sign' is set, but is not a CA cert") } if cert.KeyUsage&x509.KeyUsageCertSign == 0 && cert.IsCA { warnings = append(warnings, "Certificate is a CA cert, but key usage 'cert sign' missing") } if cert.Version < 2 { warnings = append(warnings, fmt.Sprintf("Certificate is not in X509v3 format (version is %d)", cert.Version+1)) } if len(cert.DNSNames) == 0 && len(cert.IPAddresses) == 0 && len(uriNames) == 0 && !cert.IsCA { warnings = append(warnings, fmt.Sprintf("Certificate doesn't have any valid DNS/URI names or IP addresses set")) } if len(cert.UnhandledCriticalExtensions) > 0 { warnings = append(warnings, "Certificate has unhandled critical extensions") } warnings = append(warnings, algWarnings(cert)...) return }
go
func certWarnings(cert *x509.Certificate, uriNames []string) (warnings []string) { if cert.SerialNumber.Sign() != 1 { warnings = append(warnings, "Serial number in cert appears to be zero/negative") } if cert.SerialNumber.BitLen() > 160 { warnings = append(warnings, "Serial number too long; should be 20 bytes or less") } if cert.KeyUsage&x509.KeyUsageCertSign != 0 && !cert.IsCA { warnings = append(warnings, "Key usage 'cert sign' is set, but is not a CA cert") } if cert.KeyUsage&x509.KeyUsageCertSign == 0 && cert.IsCA { warnings = append(warnings, "Certificate is a CA cert, but key usage 'cert sign' missing") } if cert.Version < 2 { warnings = append(warnings, fmt.Sprintf("Certificate is not in X509v3 format (version is %d)", cert.Version+1)) } if len(cert.DNSNames) == 0 && len(cert.IPAddresses) == 0 && len(uriNames) == 0 && !cert.IsCA { warnings = append(warnings, fmt.Sprintf("Certificate doesn't have any valid DNS/URI names or IP addresses set")) } if len(cert.UnhandledCriticalExtensions) > 0 { warnings = append(warnings, "Certificate has unhandled critical extensions") } warnings = append(warnings, algWarnings(cert)...) return }
[ "func", "certWarnings", "(", "cert", "*", "x509", ".", "Certificate", ",", "uriNames", "[", "]", "string", ")", "(", "warnings", "[", "]", "string", ")", "{", "if", "cert", ".", "SerialNumber", ".", "Sign", "(", ")", "!=", "1", "{", "warnings", "=", "append", "(", "warnings", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "cert", ".", "SerialNumber", ".", "BitLen", "(", ")", ">", "160", "{", "warnings", "=", "append", "(", "warnings", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "cert", ".", "KeyUsage", "&", "x509", ".", "KeyUsageCertSign", "!=", "0", "&&", "!", "cert", ".", "IsCA", "{", "warnings", "=", "append", "(", "warnings", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "cert", ".", "KeyUsage", "&", "x509", ".", "KeyUsageCertSign", "==", "0", "&&", "cert", ".", "IsCA", "{", "warnings", "=", "append", "(", "warnings", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "cert", ".", "Version", "<", "2", "{", "warnings", "=", "append", "(", "warnings", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cert", ".", "Version", "+", "1", ")", ")", "\n", "}", "\n\n", "if", "len", "(", "cert", ".", "DNSNames", ")", "==", "0", "&&", "len", "(", "cert", ".", "IPAddresses", ")", "==", "0", "&&", "len", "(", "uriNames", ")", "==", "0", "&&", "!", "cert", ".", "IsCA", "{", "warnings", "=", "append", "(", "warnings", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "if", "len", "(", "cert", ".", "UnhandledCriticalExtensions", ")", ">", "0", "{", "warnings", "=", "append", "(", "warnings", ",", "\"", "\"", ")", "\n", "}", "\n\n", "warnings", "=", "append", "(", "warnings", ",", "algWarnings", "(", "cert", ")", "...", ")", "\n\n", "return", "\n", "}" ]
// certWarnings prints a list of warnings to show common mistakes in certs.
[ "certWarnings", "prints", "a", "list", "of", "warnings", "to", "show", "common", "mistakes", "in", "certs", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/encoder.go#L378-L410
11,124
square/certigo
lib/encoder.go
algWarnings
func algWarnings(cert *x509.Certificate) (warnings []string) { alg, size := decodeKey(cert.PublicKey) if (alg == "RSA" || alg == "DSA") && size < 2048 { warnings = append(warnings, fmt.Sprintf("Size of %s key should be at least 2048 bits", alg)) } if alg == "ECDSA" && size < 224 { warnings = append(warnings, fmt.Sprintf("Size of %s key should be at least 224 bits", alg)) } for _, alg := range badSignatureAlgorithms { if cert.SignatureAlgorithm == alg { warnings = append(warnings, fmt.Sprintf("Signed with %s, which is an outdated signature algorithm", algString(alg))) } } if alg == "RSA" { key := cert.PublicKey.(*rsa.PublicKey) if key.E < 3 { warnings = append(warnings, "Public key exponent in RSA key is less than 3") } if key.N.Sign() != 1 { warnings = append(warnings, "Public key modulus in RSA key appears to be zero/negative") } } return }
go
func algWarnings(cert *x509.Certificate) (warnings []string) { alg, size := decodeKey(cert.PublicKey) if (alg == "RSA" || alg == "DSA") && size < 2048 { warnings = append(warnings, fmt.Sprintf("Size of %s key should be at least 2048 bits", alg)) } if alg == "ECDSA" && size < 224 { warnings = append(warnings, fmt.Sprintf("Size of %s key should be at least 224 bits", alg)) } for _, alg := range badSignatureAlgorithms { if cert.SignatureAlgorithm == alg { warnings = append(warnings, fmt.Sprintf("Signed with %s, which is an outdated signature algorithm", algString(alg))) } } if alg == "RSA" { key := cert.PublicKey.(*rsa.PublicKey) if key.E < 3 { warnings = append(warnings, "Public key exponent in RSA key is less than 3") } if key.N.Sign() != 1 { warnings = append(warnings, "Public key modulus in RSA key appears to be zero/negative") } } return }
[ "func", "algWarnings", "(", "cert", "*", "x509", ".", "Certificate", ")", "(", "warnings", "[", "]", "string", ")", "{", "alg", ",", "size", ":=", "decodeKey", "(", "cert", ".", "PublicKey", ")", "\n", "if", "(", "alg", "==", "\"", "\"", "||", "alg", "==", "\"", "\"", ")", "&&", "size", "<", "2048", "{", "warnings", "=", "append", "(", "warnings", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "alg", ")", ")", "\n", "}", "\n", "if", "alg", "==", "\"", "\"", "&&", "size", "<", "224", "{", "warnings", "=", "append", "(", "warnings", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "alg", ")", ")", "\n", "}", "\n\n", "for", "_", ",", "alg", ":=", "range", "badSignatureAlgorithms", "{", "if", "cert", ".", "SignatureAlgorithm", "==", "alg", "{", "warnings", "=", "append", "(", "warnings", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "algString", "(", "alg", ")", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "alg", "==", "\"", "\"", "{", "key", ":=", "cert", ".", "PublicKey", ".", "(", "*", "rsa", ".", "PublicKey", ")", "\n", "if", "key", ".", "E", "<", "3", "{", "warnings", "=", "append", "(", "warnings", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "key", ".", "N", ".", "Sign", "(", ")", "!=", "1", "{", "warnings", "=", "append", "(", "warnings", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// algWarnings checks key sizes, signature algorithms.
[ "algWarnings", "checks", "key", "sizes", "signature", "algorithms", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/encoder.go#L413-L439
11,125
square/certigo
starttls/psql/ssl.go
ssl
func ssl(o values) func(net.Conn) net.Conn { verifyCaOnly := false tlsConf := tls.Config{} switch mode := o.Get("sslmode"); mode { // "require" is the default. case "", "require": // We must skip TLS's own verification since it requires full // verification since Go 1.3. tlsConf.InsecureSkipVerify = true // From http://www.postgresql.org/docs/current/static/libpq-ssl.html: // Note: For backwards compatibility with earlier versions of PostgreSQL, if a // root CA file exists, the behavior of sslmode=require will be the same as // that of verify-ca, meaning the server certificate is validated against the // CA. Relying on this behavior is discouraged, and applications that need // certificate validation should always use verify-ca or verify-full. if _, err := os.Stat(o.Get("sslrootcert")); err == nil { verifyCaOnly = true } else { o.Set("sslrootcert", "") } case "verify-ca": // We must skip TLS's own verification since it requires full // verification since Go 1.3. tlsConf.InsecureSkipVerify = true verifyCaOnly = true case "verify-full": tlsConf.ServerName = o.Get("host") case "disable": return nil default: errorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode) } sslClientCertificates(&tlsConf, o) sslCertificateAuthority(&tlsConf, o) sslRenegotiation(&tlsConf) return func(conn net.Conn) net.Conn { client := tls.Client(conn, &tlsConf) if verifyCaOnly { sslVerifyCertificateAuthority(client, &tlsConf) } return client } }
go
func ssl(o values) func(net.Conn) net.Conn { verifyCaOnly := false tlsConf := tls.Config{} switch mode := o.Get("sslmode"); mode { // "require" is the default. case "", "require": // We must skip TLS's own verification since it requires full // verification since Go 1.3. tlsConf.InsecureSkipVerify = true // From http://www.postgresql.org/docs/current/static/libpq-ssl.html: // Note: For backwards compatibility with earlier versions of PostgreSQL, if a // root CA file exists, the behavior of sslmode=require will be the same as // that of verify-ca, meaning the server certificate is validated against the // CA. Relying on this behavior is discouraged, and applications that need // certificate validation should always use verify-ca or verify-full. if _, err := os.Stat(o.Get("sslrootcert")); err == nil { verifyCaOnly = true } else { o.Set("sslrootcert", "") } case "verify-ca": // We must skip TLS's own verification since it requires full // verification since Go 1.3. tlsConf.InsecureSkipVerify = true verifyCaOnly = true case "verify-full": tlsConf.ServerName = o.Get("host") case "disable": return nil default: errorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode) } sslClientCertificates(&tlsConf, o) sslCertificateAuthority(&tlsConf, o) sslRenegotiation(&tlsConf) return func(conn net.Conn) net.Conn { client := tls.Client(conn, &tlsConf) if verifyCaOnly { sslVerifyCertificateAuthority(client, &tlsConf) } return client } }
[ "func", "ssl", "(", "o", "values", ")", "func", "(", "net", ".", "Conn", ")", "net", ".", "Conn", "{", "verifyCaOnly", ":=", "false", "\n", "tlsConf", ":=", "tls", ".", "Config", "{", "}", "\n", "switch", "mode", ":=", "o", ".", "Get", "(", "\"", "\"", ")", ";", "mode", "{", "// \"require\" is the default.", "case", "\"", "\"", ",", "\"", "\"", ":", "// We must skip TLS's own verification since it requires full", "// verification since Go 1.3.", "tlsConf", ".", "InsecureSkipVerify", "=", "true", "\n\n", "// From http://www.postgresql.org/docs/current/static/libpq-ssl.html:", "// Note: For backwards compatibility with earlier versions of PostgreSQL, if a", "// root CA file exists, the behavior of sslmode=require will be the same as", "// that of verify-ca, meaning the server certificate is validated against the", "// CA. Relying on this behavior is discouraged, and applications that need", "// certificate validation should always use verify-ca or verify-full.", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "o", ".", "Get", "(", "\"", "\"", ")", ")", ";", "err", "==", "nil", "{", "verifyCaOnly", "=", "true", "\n", "}", "else", "{", "o", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "case", "\"", "\"", ":", "// We must skip TLS's own verification since it requires full", "// verification since Go 1.3.", "tlsConf", ".", "InsecureSkipVerify", "=", "true", "\n", "verifyCaOnly", "=", "true", "\n", "case", "\"", "\"", ":", "tlsConf", ".", "ServerName", "=", "o", ".", "Get", "(", "\"", "\"", ")", "\n", "case", "\"", "\"", ":", "return", "nil", "\n", "default", ":", "errorf", "(", "`unsupported sslmode %q; only \"require\" (default), \"verify-full\", \"verify-ca\", and \"disable\" supported`", ",", "mode", ")", "\n", "}", "\n\n", "sslClientCertificates", "(", "&", "tlsConf", ",", "o", ")", "\n", "sslCertificateAuthority", "(", "&", "tlsConf", ",", "o", ")", "\n", "sslRenegotiation", "(", "&", "tlsConf", ")", "\n\n", "return", "func", "(", "conn", "net", ".", "Conn", ")", "net", ".", "Conn", "{", "client", ":=", "tls", ".", "Client", "(", "conn", ",", "&", "tlsConf", ")", "\n", "if", "verifyCaOnly", "{", "sslVerifyCertificateAuthority", "(", "client", ",", "&", "tlsConf", ")", "\n", "}", "\n", "return", "client", "\n", "}", "\n", "}" ]
// ssl generates a function to upgrade a net.Conn based on the "sslmode" and // related settings. The function is nil when no upgrade should take place.
[ "ssl", "generates", "a", "function", "to", "upgrade", "a", "net", ".", "Conn", "based", "on", "the", "sslmode", "and", "related", "settings", ".", "The", "function", "is", "nil", "when", "no", "upgrade", "should", "take", "place", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/ssl.go#L15-L60
11,126
square/certigo
starttls/psql/ssl.go
sslClientCertificates
func sslClientCertificates(tlsConf *tls.Config, o values) { sslkey := o.Get("sslkey") sslcert := o.Get("sslcert") var cinfo, kinfo os.FileInfo var err error if sslcert != "" && sslkey != "" { // Check that both files exist. Note that we don't do any more extensive // checks than this (such as checking that the paths aren't directories); // LoadX509KeyPair() will take care of the rest. cinfo, err = os.Stat(sslcert) if err != nil { panic(err) } kinfo, err = os.Stat(sslkey) if err != nil { panic(err) } } else { // Automatically find certificates from ~/.postgresql sslcert, sslkey, cinfo, kinfo = sslHomeCertificates() if cinfo == nil || kinfo == nil { // No certificates to load return } } // The files must also have the correct permissions sslCertificatePermissions(cinfo, kinfo) cert, err := tls.LoadX509KeyPair(sslcert, sslkey) if err != nil { panic(err) } tlsConf.Certificates = []tls.Certificate{cert} }
go
func sslClientCertificates(tlsConf *tls.Config, o values) { sslkey := o.Get("sslkey") sslcert := o.Get("sslcert") var cinfo, kinfo os.FileInfo var err error if sslcert != "" && sslkey != "" { // Check that both files exist. Note that we don't do any more extensive // checks than this (such as checking that the paths aren't directories); // LoadX509KeyPair() will take care of the rest. cinfo, err = os.Stat(sslcert) if err != nil { panic(err) } kinfo, err = os.Stat(sslkey) if err != nil { panic(err) } } else { // Automatically find certificates from ~/.postgresql sslcert, sslkey, cinfo, kinfo = sslHomeCertificates() if cinfo == nil || kinfo == nil { // No certificates to load return } } // The files must also have the correct permissions sslCertificatePermissions(cinfo, kinfo) cert, err := tls.LoadX509KeyPair(sslcert, sslkey) if err != nil { panic(err) } tlsConf.Certificates = []tls.Certificate{cert} }
[ "func", "sslClientCertificates", "(", "tlsConf", "*", "tls", ".", "Config", ",", "o", "values", ")", "{", "sslkey", ":=", "o", ".", "Get", "(", "\"", "\"", ")", "\n", "sslcert", ":=", "o", ".", "Get", "(", "\"", "\"", ")", "\n\n", "var", "cinfo", ",", "kinfo", "os", ".", "FileInfo", "\n", "var", "err", "error", "\n\n", "if", "sslcert", "!=", "\"", "\"", "&&", "sslkey", "!=", "\"", "\"", "{", "// Check that both files exist. Note that we don't do any more extensive", "// checks than this (such as checking that the paths aren't directories);", "// LoadX509KeyPair() will take care of the rest.", "cinfo", ",", "err", "=", "os", ".", "Stat", "(", "sslcert", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "kinfo", ",", "err", "=", "os", ".", "Stat", "(", "sslkey", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "// Automatically find certificates from ~/.postgresql", "sslcert", ",", "sslkey", ",", "cinfo", ",", "kinfo", "=", "sslHomeCertificates", "(", ")", "\n\n", "if", "cinfo", "==", "nil", "||", "kinfo", "==", "nil", "{", "// No certificates to load", "return", "\n", "}", "\n", "}", "\n\n", "// The files must also have the correct permissions", "sslCertificatePermissions", "(", "cinfo", ",", "kinfo", ")", "\n\n", "cert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "sslcert", ",", "sslkey", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "tlsConf", ".", "Certificates", "=", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", "\n", "}" ]
// sslClientCertificates adds the certificate specified in the "sslcert" and // "sslkey" settings, or if they aren't set, from the .postgresql directory // in the user's home directory. The configured files must exist and have // the correct permissions.
[ "sslClientCertificates", "adds", "the", "certificate", "specified", "in", "the", "sslcert", "and", "sslkey", "settings", "or", "if", "they", "aren", "t", "set", "from", "the", ".", "postgresql", "directory", "in", "the", "user", "s", "home", "directory", ".", "The", "configured", "files", "must", "exist", "and", "have", "the", "correct", "permissions", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/ssl.go#L66-L104
11,127
square/certigo
starttls/psql/ssl.go
sslCertificateAuthority
func sslCertificateAuthority(tlsConf *tls.Config, o values) { if sslrootcert := o.Get("sslrootcert"); sslrootcert != "" { tlsConf.RootCAs = x509.NewCertPool() cert, err := ioutil.ReadFile(sslrootcert) if err != nil { panic(err) } ok := tlsConf.RootCAs.AppendCertsFromPEM(cert) if !ok { errorf("couldn't parse pem in sslrootcert") } } }
go
func sslCertificateAuthority(tlsConf *tls.Config, o values) { if sslrootcert := o.Get("sslrootcert"); sslrootcert != "" { tlsConf.RootCAs = x509.NewCertPool() cert, err := ioutil.ReadFile(sslrootcert) if err != nil { panic(err) } ok := tlsConf.RootCAs.AppendCertsFromPEM(cert) if !ok { errorf("couldn't parse pem in sslrootcert") } } }
[ "func", "sslCertificateAuthority", "(", "tlsConf", "*", "tls", ".", "Config", ",", "o", "values", ")", "{", "if", "sslrootcert", ":=", "o", ".", "Get", "(", "\"", "\"", ")", ";", "sslrootcert", "!=", "\"", "\"", "{", "tlsConf", ".", "RootCAs", "=", "x509", ".", "NewCertPool", "(", ")", "\n\n", "cert", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "sslrootcert", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "ok", ":=", "tlsConf", ".", "RootCAs", ".", "AppendCertsFromPEM", "(", "cert", ")", "\n", "if", "!", "ok", "{", "errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// sslCertificateAuthority adds the RootCA specified in the "sslrootcert" setting.
[ "sslCertificateAuthority", "adds", "the", "RootCA", "specified", "in", "the", "sslrootcert", "setting", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/ssl.go#L107-L121
11,128
square/certigo
starttls/psql/ssl.go
sslHomeCertificates
func sslHomeCertificates() (cert, key string, cinfo, kinfo os.FileInfo) { user, err := user.Current() if err != nil { // user.Current() might fail when cross-compiling. We have to ignore the // error and continue without client certificates, since we wouldn't know // from where to load them. return } cert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt") key = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key") cinfo, err = os.Stat(cert) if err != nil { cinfo = nil } kinfo, err = os.Stat(key) if err != nil { kinfo = nil } return }
go
func sslHomeCertificates() (cert, key string, cinfo, kinfo os.FileInfo) { user, err := user.Current() if err != nil { // user.Current() might fail when cross-compiling. We have to ignore the // error and continue without client certificates, since we wouldn't know // from where to load them. return } cert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt") key = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key") cinfo, err = os.Stat(cert) if err != nil { cinfo = nil } kinfo, err = os.Stat(key) if err != nil { kinfo = nil } return }
[ "func", "sslHomeCertificates", "(", ")", "(", "cert", ",", "key", "string", ",", "cinfo", ",", "kinfo", "os", ".", "FileInfo", ")", "{", "user", ",", "err", ":=", "user", ".", "Current", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "// user.Current() might fail when cross-compiling. We have to ignore the", "// error and continue without client certificates, since we wouldn't know", "// from where to load them.", "return", "\n", "}", "\n\n", "cert", "=", "filepath", ".", "Join", "(", "user", ".", "HomeDir", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "key", "=", "filepath", ".", "Join", "(", "user", ".", "HomeDir", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "cinfo", ",", "err", "=", "os", ".", "Stat", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "cinfo", "=", "nil", "\n", "}", "\n\n", "kinfo", ",", "err", "=", "os", ".", "Stat", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "kinfo", "=", "nil", "\n", "}", "\n\n", "return", "\n", "}" ]
// sslHomeCertificates returns the path and stats of certificates in the current // user's home directory.
[ "sslHomeCertificates", "returns", "the", "path", "and", "stats", "of", "certificates", "in", "the", "current", "user", "s", "home", "directory", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/ssl.go#L125-L149
11,129
square/certigo
starttls/psql/ssl.go
sslVerifyCertificateAuthority
func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) { err := client.Handshake() if err != nil { panic(err) } certs := client.ConnectionState().PeerCertificates opts := x509.VerifyOptions{ DNSName: client.ConnectionState().ServerName, Intermediates: x509.NewCertPool(), Roots: tlsConf.RootCAs, } for i, cert := range certs { if i == 0 { continue } opts.Intermediates.AddCert(cert) } _, err = certs[0].Verify(opts) if err != nil { panic(err) } }
go
func sslVerifyCertificateAuthority(client *tls.Conn, tlsConf *tls.Config) { err := client.Handshake() if err != nil { panic(err) } certs := client.ConnectionState().PeerCertificates opts := x509.VerifyOptions{ DNSName: client.ConnectionState().ServerName, Intermediates: x509.NewCertPool(), Roots: tlsConf.RootCAs, } for i, cert := range certs { if i == 0 { continue } opts.Intermediates.AddCert(cert) } _, err = certs[0].Verify(opts) if err != nil { panic(err) } }
[ "func", "sslVerifyCertificateAuthority", "(", "client", "*", "tls", ".", "Conn", ",", "tlsConf", "*", "tls", ".", "Config", ")", "{", "err", ":=", "client", ".", "Handshake", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "certs", ":=", "client", ".", "ConnectionState", "(", ")", ".", "PeerCertificates", "\n", "opts", ":=", "x509", ".", "VerifyOptions", "{", "DNSName", ":", "client", ".", "ConnectionState", "(", ")", ".", "ServerName", ",", "Intermediates", ":", "x509", ".", "NewCertPool", "(", ")", ",", "Roots", ":", "tlsConf", ".", "RootCAs", ",", "}", "\n", "for", "i", ",", "cert", ":=", "range", "certs", "{", "if", "i", "==", "0", "{", "continue", "\n", "}", "\n", "opts", ".", "Intermediates", ".", "AddCert", "(", "cert", ")", "\n", "}", "\n", "_", ",", "err", "=", "certs", "[", "0", "]", ".", "Verify", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}" ]
// sslVerifyCertificateAuthority carries out a TLS handshake to the server and // verifies the presented certificate against the CA, i.e. the one specified in // sslrootcert or the system CA if sslrootcert was not specified.
[ "sslVerifyCertificateAuthority", "carries", "out", "a", "TLS", "handshake", "to", "the", "server", "and", "verifies", "the", "presented", "certificate", "against", "the", "CA", "i", ".", "e", ".", "the", "one", "specified", "in", "sslrootcert", "or", "the", "system", "CA", "if", "sslrootcert", "was", "not", "specified", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/ssl.go#L154-L175
11,130
square/certigo
starttls/ldap/ldap.go
addLDAPDescriptions
func addLDAPDescriptions(packet *ber.Packet) (err error) { defer func() { if r := recover(); r != nil { err = NewError(ErrorDebugging, errors.New("ldap: cannot process packet to add descriptions")) } }() packet.Description = "LDAP Response" packet.Children[0].Description = "Message ID" application := uint8(packet.Children[1].Tag) packet.Children[1].Description = ApplicationMap[application] switch application { case ApplicationBindRequest: addRequestDescriptions(packet) case ApplicationBindResponse: addDefaultLDAPResponseDescriptions(packet) case ApplicationUnbindRequest: addRequestDescriptions(packet) case ApplicationSearchRequest: addRequestDescriptions(packet) case ApplicationSearchResultEntry: packet.Children[1].Children[0].Description = "Object Name" packet.Children[1].Children[1].Description = "Attributes" for _, child := range packet.Children[1].Children[1].Children { child.Description = "Attribute" child.Children[0].Description = "Attribute Name" child.Children[1].Description = "Attribute Values" for _, grandchild := range child.Children[1].Children { grandchild.Description = "Attribute Value" } } if len(packet.Children) == 3 { addControlDescriptions(packet.Children[2]) } case ApplicationSearchResultDone: addDefaultLDAPResponseDescriptions(packet) case ApplicationModifyRequest: addRequestDescriptions(packet) case ApplicationModifyResponse: case ApplicationAddRequest: addRequestDescriptions(packet) case ApplicationAddResponse: case ApplicationDelRequest: addRequestDescriptions(packet) case ApplicationDelResponse: case ApplicationModifyDNRequest: addRequestDescriptions(packet) case ApplicationModifyDNResponse: case ApplicationCompareRequest: addRequestDescriptions(packet) case ApplicationCompareResponse: case ApplicationAbandonRequest: addRequestDescriptions(packet) case ApplicationSearchResultReference: case ApplicationExtendedRequest: addRequestDescriptions(packet) case ApplicationExtendedResponse: } return nil }
go
func addLDAPDescriptions(packet *ber.Packet) (err error) { defer func() { if r := recover(); r != nil { err = NewError(ErrorDebugging, errors.New("ldap: cannot process packet to add descriptions")) } }() packet.Description = "LDAP Response" packet.Children[0].Description = "Message ID" application := uint8(packet.Children[1].Tag) packet.Children[1].Description = ApplicationMap[application] switch application { case ApplicationBindRequest: addRequestDescriptions(packet) case ApplicationBindResponse: addDefaultLDAPResponseDescriptions(packet) case ApplicationUnbindRequest: addRequestDescriptions(packet) case ApplicationSearchRequest: addRequestDescriptions(packet) case ApplicationSearchResultEntry: packet.Children[1].Children[0].Description = "Object Name" packet.Children[1].Children[1].Description = "Attributes" for _, child := range packet.Children[1].Children[1].Children { child.Description = "Attribute" child.Children[0].Description = "Attribute Name" child.Children[1].Description = "Attribute Values" for _, grandchild := range child.Children[1].Children { grandchild.Description = "Attribute Value" } } if len(packet.Children) == 3 { addControlDescriptions(packet.Children[2]) } case ApplicationSearchResultDone: addDefaultLDAPResponseDescriptions(packet) case ApplicationModifyRequest: addRequestDescriptions(packet) case ApplicationModifyResponse: case ApplicationAddRequest: addRequestDescriptions(packet) case ApplicationAddResponse: case ApplicationDelRequest: addRequestDescriptions(packet) case ApplicationDelResponse: case ApplicationModifyDNRequest: addRequestDescriptions(packet) case ApplicationModifyDNResponse: case ApplicationCompareRequest: addRequestDescriptions(packet) case ApplicationCompareResponse: case ApplicationAbandonRequest: addRequestDescriptions(packet) case ApplicationSearchResultReference: case ApplicationExtendedRequest: addRequestDescriptions(packet) case ApplicationExtendedResponse: } return nil }
[ "func", "addLDAPDescriptions", "(", "packet", "*", "ber", ".", "Packet", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "err", "=", "NewError", "(", "ErrorDebugging", ",", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "packet", ".", "Description", "=", "\"", "\"", "\n", "packet", ".", "Children", "[", "0", "]", ".", "Description", "=", "\"", "\"", "\n\n", "application", ":=", "uint8", "(", "packet", ".", "Children", "[", "1", "]", ".", "Tag", ")", "\n", "packet", ".", "Children", "[", "1", "]", ".", "Description", "=", "ApplicationMap", "[", "application", "]", "\n\n", "switch", "application", "{", "case", "ApplicationBindRequest", ":", "addRequestDescriptions", "(", "packet", ")", "\n", "case", "ApplicationBindResponse", ":", "addDefaultLDAPResponseDescriptions", "(", "packet", ")", "\n", "case", "ApplicationUnbindRequest", ":", "addRequestDescriptions", "(", "packet", ")", "\n", "case", "ApplicationSearchRequest", ":", "addRequestDescriptions", "(", "packet", ")", "\n", "case", "ApplicationSearchResultEntry", ":", "packet", ".", "Children", "[", "1", "]", ".", "Children", "[", "0", "]", ".", "Description", "=", "\"", "\"", "\n", "packet", ".", "Children", "[", "1", "]", ".", "Children", "[", "1", "]", ".", "Description", "=", "\"", "\"", "\n", "for", "_", ",", "child", ":=", "range", "packet", ".", "Children", "[", "1", "]", ".", "Children", "[", "1", "]", ".", "Children", "{", "child", ".", "Description", "=", "\"", "\"", "\n", "child", ".", "Children", "[", "0", "]", ".", "Description", "=", "\"", "\"", "\n", "child", ".", "Children", "[", "1", "]", ".", "Description", "=", "\"", "\"", "\n", "for", "_", ",", "grandchild", ":=", "range", "child", ".", "Children", "[", "1", "]", ".", "Children", "{", "grandchild", ".", "Description", "=", "\"", "\"", "\n", "}", "\n", "}", "\n", "if", "len", "(", "packet", ".", "Children", ")", "==", "3", "{", "addControlDescriptions", "(", "packet", ".", "Children", "[", "2", "]", ")", "\n", "}", "\n", "case", "ApplicationSearchResultDone", ":", "addDefaultLDAPResponseDescriptions", "(", "packet", ")", "\n", "case", "ApplicationModifyRequest", ":", "addRequestDescriptions", "(", "packet", ")", "\n", "case", "ApplicationModifyResponse", ":", "case", "ApplicationAddRequest", ":", "addRequestDescriptions", "(", "packet", ")", "\n", "case", "ApplicationAddResponse", ":", "case", "ApplicationDelRequest", ":", "addRequestDescriptions", "(", "packet", ")", "\n", "case", "ApplicationDelResponse", ":", "case", "ApplicationModifyDNRequest", ":", "addRequestDescriptions", "(", "packet", ")", "\n", "case", "ApplicationModifyDNResponse", ":", "case", "ApplicationCompareRequest", ":", "addRequestDescriptions", "(", "packet", ")", "\n", "case", "ApplicationCompareResponse", ":", "case", "ApplicationAbandonRequest", ":", "addRequestDescriptions", "(", "packet", ")", "\n", "case", "ApplicationSearchResultReference", ":", "case", "ApplicationExtendedRequest", ":", "addRequestDescriptions", "(", "packet", ")", "\n", "case", "ApplicationExtendedResponse", ":", "}", "\n\n", "return", "nil", "\n", "}" ]
// Adds descriptions to an LDAP Response packet for debugging
[ "Adds", "descriptions", "to", "an", "LDAP", "Response", "packet", "for", "debugging" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/ldap.go#L90-L151
11,131
square/certigo
starttls/ldap/ldap.go
DebugBinaryFile
func DebugBinaryFile(fileName string) error { file, err := ioutil.ReadFile(fileName) if err != nil { return NewError(ErrorDebugging, err) } ber.PrintBytes(os.Stdout, file, "") packet := ber.DecodePacket(file) addLDAPDescriptions(packet) ber.PrintPacket(packet) return nil }
go
func DebugBinaryFile(fileName string) error { file, err := ioutil.ReadFile(fileName) if err != nil { return NewError(ErrorDebugging, err) } ber.PrintBytes(os.Stdout, file, "") packet := ber.DecodePacket(file) addLDAPDescriptions(packet) ber.PrintPacket(packet) return nil }
[ "func", "DebugBinaryFile", "(", "fileName", "string", ")", "error", "{", "file", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "fileName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NewError", "(", "ErrorDebugging", ",", "err", ")", "\n", "}", "\n", "ber", ".", "PrintBytes", "(", "os", ".", "Stdout", ",", "file", ",", "\"", "\"", ")", "\n", "packet", ":=", "ber", ".", "DecodePacket", "(", "file", ")", "\n", "addLDAPDescriptions", "(", "packet", ")", "\n", "ber", ".", "PrintPacket", "(", "packet", ")", "\n\n", "return", "nil", "\n", "}" ]
// DebugBinaryFile reads and prints packets from the given filename
[ "DebugBinaryFile", "reads", "and", "prints", "packets", "from", "the", "given", "filename" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/ldap.go#L274-L285
11,132
square/certigo
jceks/jceks.go
readBytes
func readBytes(r io.Reader) ([]byte, error) { length, err := readInt32(r) if err != nil { return nil, err } buf := make([]byte, length) _, err = io.ReadFull(r, buf) if err != nil { return nil, err } return buf, nil }
go
func readBytes(r io.Reader) ([]byte, error) { length, err := readInt32(r) if err != nil { return nil, err } buf := make([]byte, length) _, err = io.ReadFull(r, buf) if err != nil { return nil, err } return buf, nil }
[ "func", "readBytes", "(", "r", "io", ".", "Reader", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "length", ",", "err", ":=", "readInt32", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "length", ")", "\n", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "r", ",", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ",", "nil", "\n", "}" ]
// readBytes reads a byte array from the reader. The encoding provides // a 4-byte prefix indicating the number of bytes which follow.
[ "readBytes", "reads", "a", "byte", "array", "from", "the", "reader", ".", "The", "encoding", "provides", "a", "4", "-", "byte", "prefix", "indicating", "the", "number", "of", "bytes", "which", "follow", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/jceks/jceks.go#L169-L180
11,133
square/certigo
jceks/jceks.go
getPreKeyedHash
func getPreKeyedHash(password []byte) hash.Hash { md := sha1.New() buf := make([]byte, len(password)*2) for i := 0; i < len(password); i++ { buf[i*2+1] = password[i] } md.Write(buf) // Yes, "Mighty Aphrodite" is a constant used by this method. md.Write([]byte("Mighty Aphrodite")) return md }
go
func getPreKeyedHash(password []byte) hash.Hash { md := sha1.New() buf := make([]byte, len(password)*2) for i := 0; i < len(password); i++ { buf[i*2+1] = password[i] } md.Write(buf) // Yes, "Mighty Aphrodite" is a constant used by this method. md.Write([]byte("Mighty Aphrodite")) return md }
[ "func", "getPreKeyedHash", "(", "password", "[", "]", "byte", ")", "hash", ".", "Hash", "{", "md", ":=", "sha1", ".", "New", "(", ")", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "password", ")", "*", "2", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "password", ")", ";", "i", "++", "{", "buf", "[", "i", "*", "2", "+", "1", "]", "=", "password", "[", "i", "]", "\n", "}", "\n", "md", ".", "Write", "(", "buf", ")", "\n", "// Yes, \"Mighty Aphrodite\" is a constant used by this method.", "md", ".", "Write", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", "\n", "return", "md", "\n", "}" ]
// Returns a SHA1 hash which has been pre-keyed with the specified // password according to the JCEKS algorithm.
[ "Returns", "a", "SHA1", "hash", "which", "has", "been", "pre", "-", "keyed", "with", "the", "specified", "password", "according", "to", "the", "JCEKS", "algorithm", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/jceks/jceks.go#L207-L217
11,134
square/certigo
jceks/jceks.go
Parse
func (ks *KeyStore) Parse(r io.Reader, password []byte) error { var md hash.Hash if password != nil { md = getPreKeyedHash(password) r = io.TeeReader(r, md) } version, err := parseHeader(r) if err != nil { return err } if version != jceksVersion { return fmt.Errorf("unexpected version: %d != %d", version, jceksVersion) } count, err := readInt32(r) if err != nil { return err } for i := 0; i < int(count); i++ { tag, err := readInt32(r) if err != nil { return err } switch tag { case 1: // Private-key entry err := ks.parsePrivateKey(r) if err != nil { return err } case 2: // Trusted-cert entry err := ks.parseTrustedCert(r) if err != nil { return err } case 3: // Secret-key entry return fmt.Errorf("unimplemented: Secret-key") default: return fmt.Errorf("unimplemented tag: %d", tag) } } if md != nil { computed := md.Sum([]byte{}) actual := make([]byte, len(computed)) _, err := io.ReadFull(r, actual) if err != nil { return err } if subtle.ConstantTimeCompare(computed, actual) != 1 { return fmt.Errorf("keystore was tampered with or password was incorrect") } } return nil }
go
func (ks *KeyStore) Parse(r io.Reader, password []byte) error { var md hash.Hash if password != nil { md = getPreKeyedHash(password) r = io.TeeReader(r, md) } version, err := parseHeader(r) if err != nil { return err } if version != jceksVersion { return fmt.Errorf("unexpected version: %d != %d", version, jceksVersion) } count, err := readInt32(r) if err != nil { return err } for i := 0; i < int(count); i++ { tag, err := readInt32(r) if err != nil { return err } switch tag { case 1: // Private-key entry err := ks.parsePrivateKey(r) if err != nil { return err } case 2: // Trusted-cert entry err := ks.parseTrustedCert(r) if err != nil { return err } case 3: // Secret-key entry return fmt.Errorf("unimplemented: Secret-key") default: return fmt.Errorf("unimplemented tag: %d", tag) } } if md != nil { computed := md.Sum([]byte{}) actual := make([]byte, len(computed)) _, err := io.ReadFull(r, actual) if err != nil { return err } if subtle.ConstantTimeCompare(computed, actual) != 1 { return fmt.Errorf("keystore was tampered with or password was incorrect") } } return nil }
[ "func", "(", "ks", "*", "KeyStore", ")", "Parse", "(", "r", "io", ".", "Reader", ",", "password", "[", "]", "byte", ")", "error", "{", "var", "md", "hash", ".", "Hash", "\n", "if", "password", "!=", "nil", "{", "md", "=", "getPreKeyedHash", "(", "password", ")", "\n", "r", "=", "io", ".", "TeeReader", "(", "r", ",", "md", ")", "\n", "}", "\n\n", "version", ",", "err", ":=", "parseHeader", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "version", "!=", "jceksVersion", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "version", ",", "jceksVersion", ")", "\n", "}", "\n\n", "count", ",", "err", ":=", "readInt32", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "count", ")", ";", "i", "++", "{", "tag", ",", "err", ":=", "readInt32", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "switch", "tag", "{", "case", "1", ":", "// Private-key entry", "err", ":=", "ks", ".", "parsePrivateKey", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "2", ":", "// Trusted-cert entry", "err", ":=", "ks", ".", "parseTrustedCert", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "3", ":", "// Secret-key entry", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tag", ")", "\n", "}", "\n", "}", "\n\n", "if", "md", "!=", "nil", "{", "computed", ":=", "md", ".", "Sum", "(", "[", "]", "byte", "{", "}", ")", "\n", "actual", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "computed", ")", ")", "\n", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "actual", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "subtle", ".", "ConstantTimeCompare", "(", "computed", ",", "actual", ")", "!=", "1", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Parse parses the key store from the specified reader.
[ "Parse", "parses", "the", "key", "store", "from", "the", "specified", "reader", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/jceks/jceks.go#L308-L366
11,135
square/certigo
jceks/jceks.go
GetPrivateKeyAndCerts
func (ks *KeyStore) GetPrivateKeyAndCerts(alias string, password []byte) ( key crypto.PrivateKey, certs []*x509.Certificate, err error) { entry := ks.entries[alias] if entry == nil { return } switch t := entry.(type) { case *privateKeyEntry: if len(t.certs) < 1 { return nil, nil, fmt.Errorf("key has no certificates") } key, err = t.Recover(password) if err == nil { certs = t.certs return } } return }
go
func (ks *KeyStore) GetPrivateKeyAndCerts(alias string, password []byte) ( key crypto.PrivateKey, certs []*x509.Certificate, err error) { entry := ks.entries[alias] if entry == nil { return } switch t := entry.(type) { case *privateKeyEntry: if len(t.certs) < 1 { return nil, nil, fmt.Errorf("key has no certificates") } key, err = t.Recover(password) if err == nil { certs = t.certs return } } return }
[ "func", "(", "ks", "*", "KeyStore", ")", "GetPrivateKeyAndCerts", "(", "alias", "string", ",", "password", "[", "]", "byte", ")", "(", "key", "crypto", ".", "PrivateKey", ",", "certs", "[", "]", "*", "x509", ".", "Certificate", ",", "err", "error", ")", "{", "entry", ":=", "ks", ".", "entries", "[", "alias", "]", "\n", "if", "entry", "==", "nil", "{", "return", "\n", "}", "\n", "switch", "t", ":=", "entry", ".", "(", "type", ")", "{", "case", "*", "privateKeyEntry", ":", "if", "len", "(", "t", ".", "certs", ")", "<", "1", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "key", ",", "err", "=", "t", ".", "Recover", "(", "password", ")", "\n", "if", "err", "==", "nil", "{", "certs", "=", "t", ".", "certs", "\n", "return", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// GetPrivateKeyAndCerts retrieves the specified private key. Returns // nil if the private key does not exist or alias points to a non // private key entry.
[ "GetPrivateKeyAndCerts", "retrieves", "the", "specified", "private", "key", ".", "Returns", "nil", "if", "the", "private", "key", "does", "not", "exist", "or", "alias", "points", "to", "a", "non", "private", "key", "entry", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/jceks/jceks.go#L371-L390
11,136
square/certigo
jceks/jceks.go
GetCert
func (ks *KeyStore) GetCert(alias string) (*x509.Certificate, error) { entry := ks.entries[alias] if entry == nil { return nil, nil } switch t := entry.(type) { case *trustedCertEntry: return t.cert, nil } return nil, nil }
go
func (ks *KeyStore) GetCert(alias string) (*x509.Certificate, error) { entry := ks.entries[alias] if entry == nil { return nil, nil } switch t := entry.(type) { case *trustedCertEntry: return t.cert, nil } return nil, nil }
[ "func", "(", "ks", "*", "KeyStore", ")", "GetCert", "(", "alias", "string", ")", "(", "*", "x509", ".", "Certificate", ",", "error", ")", "{", "entry", ":=", "ks", ".", "entries", "[", "alias", "]", "\n", "if", "entry", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "switch", "t", ":=", "entry", ".", "(", "type", ")", "{", "case", "*", "trustedCertEntry", ":", "return", "t", ".", "cert", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// GetCert retrieves the specified certificate. Returns nil if the // certificate does not exist or alias points to a non certificate // entry.
[ "GetCert", "retrieves", "the", "specified", "certificate", ".", "Returns", "nil", "if", "the", "certificate", "does", "not", "exist", "or", "alias", "points", "to", "a", "non", "certificate", "entry", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/jceks/jceks.go#L395-L405
11,137
square/certigo
jceks/jceks.go
ListPrivateKeys
func (ks *KeyStore) ListPrivateKeys() []string { var r []string for k, v := range ks.entries { if _, ok := v.(*privateKeyEntry); ok { r = append(r, k) } } return r }
go
func (ks *KeyStore) ListPrivateKeys() []string { var r []string for k, v := range ks.entries { if _, ok := v.(*privateKeyEntry); ok { r = append(r, k) } } return r }
[ "func", "(", "ks", "*", "KeyStore", ")", "ListPrivateKeys", "(", ")", "[", "]", "string", "{", "var", "r", "[", "]", "string", "\n", "for", "k", ",", "v", ":=", "range", "ks", ".", "entries", "{", "if", "_", ",", "ok", ":=", "v", ".", "(", "*", "privateKeyEntry", ")", ";", "ok", "{", "r", "=", "append", "(", "r", ",", "k", ")", "\n", "}", "\n", "}", "\n", "return", "r", "\n", "}" ]
// ListPrivateKeys lists the names of the private keys stored in the key store.
[ "ListPrivateKeys", "lists", "the", "names", "of", "the", "private", "keys", "stored", "in", "the", "key", "store", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/jceks/jceks.go#L408-L416
11,138
square/certigo
jceks/jceks.go
ListCerts
func (ks *KeyStore) ListCerts() []string { var r []string for k, v := range ks.entries { if _, ok := v.(*trustedCertEntry); ok { r = append(r, k) } } return r }
go
func (ks *KeyStore) ListCerts() []string { var r []string for k, v := range ks.entries { if _, ok := v.(*trustedCertEntry); ok { r = append(r, k) } } return r }
[ "func", "(", "ks", "*", "KeyStore", ")", "ListCerts", "(", ")", "[", "]", "string", "{", "var", "r", "[", "]", "string", "\n", "for", "k", ",", "v", ":=", "range", "ks", ".", "entries", "{", "if", "_", ",", "ok", ":=", "v", ".", "(", "*", "trustedCertEntry", ")", ";", "ok", "{", "r", "=", "append", "(", "r", ",", "k", ")", "\n", "}", "\n", "}", "\n", "return", "r", "\n", "}" ]
// ListCerts lists the names of the certs stored in the key store.
[ "ListCerts", "lists", "the", "names", "of", "the", "certs", "stored", "in", "the", "key", "store", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/jceks/jceks.go#L419-L427
11,139
square/certigo
jceks/jceks.go
LoadFromFile
func LoadFromFile(filename string, password []byte) (*KeyStore, error) { file, err := os.Open(filename) if err != nil { return nil, err } defer file.Close() return LoadFromReader(file, password) }
go
func LoadFromFile(filename string, password []byte) (*KeyStore, error) { file, err := os.Open(filename) if err != nil { return nil, err } defer file.Close() return LoadFromReader(file, password) }
[ "func", "LoadFromFile", "(", "filename", "string", ",", "password", "[", "]", "byte", ")", "(", "*", "KeyStore", ",", "error", ")", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n\n", "return", "LoadFromReader", "(", "file", ",", "password", ")", "\n", "}" ]
// LoadFromFile loads the key store from the specified file.
[ "LoadFromFile", "loads", "the", "key", "store", "from", "the", "specified", "file", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/jceks/jceks.go#L439-L447
11,140
square/certigo
jceks/jceks.go
LoadFromReader
func LoadFromReader(reader io.Reader, password []byte) (*KeyStore, error) { ks := &KeyStore{ entries: make(map[string]interface{}), } err := ks.Parse(reader, password) if err != nil { return nil, err } return ks, err }
go
func LoadFromReader(reader io.Reader, password []byte) (*KeyStore, error) { ks := &KeyStore{ entries: make(map[string]interface{}), } err := ks.Parse(reader, password) if err != nil { return nil, err } return ks, err }
[ "func", "LoadFromReader", "(", "reader", "io", ".", "Reader", ",", "password", "[", "]", "byte", ")", "(", "*", "KeyStore", ",", "error", ")", "{", "ks", ":=", "&", "KeyStore", "{", "entries", ":", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ",", "}", "\n", "err", ":=", "ks", ".", "Parse", "(", "reader", ",", "password", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ks", ",", "err", "\n", "}" ]
// LoadFromReader loads the key store from the specified file.
[ "LoadFromReader", "loads", "the", "key", "store", "from", "the", "specified", "file", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/jceks/jceks.go#L450-L459
11,141
square/certigo
starttls/psql/conn_go18.go
QueryContext
func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { list := make([]driver.Value, len(args)) for i, nv := range args { list[i] = nv.Value } var closed chan<- struct{} if ctx.Done() != nil { closed = watchCancel(ctx, cn.cancel) } r, err := cn.query(query, list) if err != nil { return nil, err } r.closed = closed return r, nil }
go
func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { list := make([]driver.Value, len(args)) for i, nv := range args { list[i] = nv.Value } var closed chan<- struct{} if ctx.Done() != nil { closed = watchCancel(ctx, cn.cancel) } r, err := cn.query(query, list) if err != nil { return nil, err } r.closed = closed return r, nil }
[ "func", "(", "cn", "*", "conn", ")", "QueryContext", "(", "ctx", "context", ".", "Context", ",", "query", "string", ",", "args", "[", "]", "driver", ".", "NamedValue", ")", "(", "driver", ".", "Rows", ",", "error", ")", "{", "list", ":=", "make", "(", "[", "]", "driver", ".", "Value", ",", "len", "(", "args", ")", ")", "\n", "for", "i", ",", "nv", ":=", "range", "args", "{", "list", "[", "i", "]", "=", "nv", ".", "Value", "\n", "}", "\n", "var", "closed", "chan", "<-", "struct", "{", "}", "\n", "if", "ctx", ".", "Done", "(", ")", "!=", "nil", "{", "closed", "=", "watchCancel", "(", "ctx", ",", "cn", ".", "cancel", ")", "\n", "}", "\n", "r", ",", "err", ":=", "cn", ".", "query", "(", "query", ",", "list", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "r", ".", "closed", "=", "closed", "\n", "return", "r", ",", "nil", "\n", "}" ]
// Implement the "QueryerContext" interface
[ "Implement", "the", "QueryerContext", "interface" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/conn_go18.go#L12-L27
11,142
square/certigo
starttls/psql/conn_go18.go
ExecContext
func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { list := make([]driver.Value, len(args)) for i, nv := range args { list[i] = nv.Value } if ctx.Done() != nil { closed := watchCancel(ctx, cn.cancel) defer close(closed) } return cn.Exec(query, list) }
go
func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { list := make([]driver.Value, len(args)) for i, nv := range args { list[i] = nv.Value } if ctx.Done() != nil { closed := watchCancel(ctx, cn.cancel) defer close(closed) } return cn.Exec(query, list) }
[ "func", "(", "cn", "*", "conn", ")", "ExecContext", "(", "ctx", "context", ".", "Context", ",", "query", "string", ",", "args", "[", "]", "driver", ".", "NamedValue", ")", "(", "driver", ".", "Result", ",", "error", ")", "{", "list", ":=", "make", "(", "[", "]", "driver", ".", "Value", ",", "len", "(", "args", ")", ")", "\n", "for", "i", ",", "nv", ":=", "range", "args", "{", "list", "[", "i", "]", "=", "nv", ".", "Value", "\n", "}", "\n\n", "if", "ctx", ".", "Done", "(", ")", "!=", "nil", "{", "closed", ":=", "watchCancel", "(", "ctx", ",", "cn", ".", "cancel", ")", "\n", "defer", "close", "(", "closed", ")", "\n", "}", "\n\n", "return", "cn", ".", "Exec", "(", "query", ",", "list", ")", "\n", "}" ]
// Implement the "ExecerContext" interface
[ "Implement", "the", "ExecerContext", "interface" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/conn_go18.go#L30-L42
11,143
square/certigo
starttls/psql/conn_go18.go
BeginTx
func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { if opts.Isolation != 0 { return nil, errors.New("isolation levels not supported") } if opts.ReadOnly { return nil, errors.New("read-only transactions not supported") } tx, err := cn.Begin() if err != nil { return nil, err } if ctx.Done() != nil { cn.txnClosed = watchCancel(ctx, cn.cancel) } return tx, nil }
go
func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { if opts.Isolation != 0 { return nil, errors.New("isolation levels not supported") } if opts.ReadOnly { return nil, errors.New("read-only transactions not supported") } tx, err := cn.Begin() if err != nil { return nil, err } if ctx.Done() != nil { cn.txnClosed = watchCancel(ctx, cn.cancel) } return tx, nil }
[ "func", "(", "cn", "*", "conn", ")", "BeginTx", "(", "ctx", "context", ".", "Context", ",", "opts", "driver", ".", "TxOptions", ")", "(", "driver", ".", "Tx", ",", "error", ")", "{", "if", "opts", ".", "Isolation", "!=", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "opts", ".", "ReadOnly", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "tx", ",", "err", ":=", "cn", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "ctx", ".", "Done", "(", ")", "!=", "nil", "{", "cn", ".", "txnClosed", "=", "watchCancel", "(", "ctx", ",", "cn", ".", "cancel", ")", "\n", "}", "\n", "return", "tx", ",", "nil", "\n", "}" ]
// Implement the "ConnBeginTx" interface
[ "Implement", "the", "ConnBeginTx", "interface" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/psql/conn_go18.go#L45-L60
11,144
square/certigo
starttls/ldap/debug.go
Printf
func (debug debugging) Printf(format string, args ...interface{}) { if debug { log.Printf(format, args...) } }
go
func (debug debugging) Printf(format string, args ...interface{}) { if debug { log.Printf(format, args...) } }
[ "func", "(", "debug", "debugging", ")", "Printf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "debug", "{", "log", ".", "Printf", "(", "format", ",", "args", "...", ")", "\n", "}", "\n", "}" ]
// Printf writes debug output
[ "Printf", "writes", "debug", "output" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/debug.go#L14-L18
11,145
square/certigo
lib/tls.go
EncodeTLSInfoToText
func EncodeTLSInfoToText(tcs *tls.ConnectionState, cri *tls.CertificateRequestInfo) string { version := lookup(tlsVersions, tcs.Version) cipher := lookup(cipherSuites, tcs.CipherSuite) description := TLSDescription{ Version: tlscolor(version), Cipher: tlscolor(explainCipher(cipher)), } tlsInfoContext := tlsInfoContext{ Conn: &description, } if cri != nil { criDesc, err := EncodeCRIToObject(cri) if err == nil { tlsInfoContext.CRI = criDesc.(*CertificateRequestInfo) } } funcMap := sprig.TxtFuncMap() extras := template.FuncMap{ "printCommonName": PrintCommonName, "printShortName": PrintShortName, "greenify": greenify, } for k, v := range extras { funcMap[k] = v } t := template.New("TLS template").Funcs(funcMap) t, err := t.Parse(tlsLayout) if err != nil { // Should never happen panic(err) } var buffer bytes.Buffer w := bufio.NewWriter(&buffer) err = t.Execute(w, tlsInfoContext) if err != nil { // Should never happen panic(err) } w.Flush() return string(buffer.Bytes()) }
go
func EncodeTLSInfoToText(tcs *tls.ConnectionState, cri *tls.CertificateRequestInfo) string { version := lookup(tlsVersions, tcs.Version) cipher := lookup(cipherSuites, tcs.CipherSuite) description := TLSDescription{ Version: tlscolor(version), Cipher: tlscolor(explainCipher(cipher)), } tlsInfoContext := tlsInfoContext{ Conn: &description, } if cri != nil { criDesc, err := EncodeCRIToObject(cri) if err == nil { tlsInfoContext.CRI = criDesc.(*CertificateRequestInfo) } } funcMap := sprig.TxtFuncMap() extras := template.FuncMap{ "printCommonName": PrintCommonName, "printShortName": PrintShortName, "greenify": greenify, } for k, v := range extras { funcMap[k] = v } t := template.New("TLS template").Funcs(funcMap) t, err := t.Parse(tlsLayout) if err != nil { // Should never happen panic(err) } var buffer bytes.Buffer w := bufio.NewWriter(&buffer) err = t.Execute(w, tlsInfoContext) if err != nil { // Should never happen panic(err) } w.Flush() return string(buffer.Bytes()) }
[ "func", "EncodeTLSInfoToText", "(", "tcs", "*", "tls", ".", "ConnectionState", ",", "cri", "*", "tls", ".", "CertificateRequestInfo", ")", "string", "{", "version", ":=", "lookup", "(", "tlsVersions", ",", "tcs", ".", "Version", ")", "\n", "cipher", ":=", "lookup", "(", "cipherSuites", ",", "tcs", ".", "CipherSuite", ")", "\n", "description", ":=", "TLSDescription", "{", "Version", ":", "tlscolor", "(", "version", ")", ",", "Cipher", ":", "tlscolor", "(", "explainCipher", "(", "cipher", ")", ")", ",", "}", "\n", "tlsInfoContext", ":=", "tlsInfoContext", "{", "Conn", ":", "&", "description", ",", "}", "\n", "if", "cri", "!=", "nil", "{", "criDesc", ",", "err", ":=", "EncodeCRIToObject", "(", "cri", ")", "\n", "if", "err", "==", "nil", "{", "tlsInfoContext", ".", "CRI", "=", "criDesc", ".", "(", "*", "CertificateRequestInfo", ")", "\n", "}", "\n", "}", "\n\n", "funcMap", ":=", "sprig", ".", "TxtFuncMap", "(", ")", "\n", "extras", ":=", "template", ".", "FuncMap", "{", "\"", "\"", ":", "PrintCommonName", ",", "\"", "\"", ":", "PrintShortName", ",", "\"", "\"", ":", "greenify", ",", "}", "\n", "for", "k", ",", "v", ":=", "range", "extras", "{", "funcMap", "[", "k", "]", "=", "v", "\n", "}", "\n\n", "t", ":=", "template", ".", "New", "(", "\"", "\"", ")", ".", "Funcs", "(", "funcMap", ")", "\n", "t", ",", "err", ":=", "t", ".", "Parse", "(", "tlsLayout", ")", "\n", "if", "err", "!=", "nil", "{", "// Should never happen", "panic", "(", "err", ")", "\n", "}", "\n", "var", "buffer", "bytes", ".", "Buffer", "\n", "w", ":=", "bufio", ".", "NewWriter", "(", "&", "buffer", ")", "\n", "err", "=", "t", ".", "Execute", "(", "w", ",", "tlsInfoContext", ")", "\n", "if", "err", "!=", "nil", "{", "// Should never happen", "panic", "(", "err", ")", "\n", "}", "\n", "w", ".", "Flush", "(", ")", "\n", "return", "string", "(", "buffer", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// EncodeTLSInfoToText returns a human readable string, suitable for certigo console output.
[ "EncodeTLSInfoToText", "returns", "a", "human", "readable", "string", "suitable", "for", "certigo", "console", "output", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/tls.go#L57-L99
11,146
square/certigo
lib/tls.go
EncodeTLSToObject
func EncodeTLSToObject(t *tls.ConnectionState) interface{} { version := lookup(tlsVersions, t.Version) cipher := lookup(cipherSuites, t.CipherSuite) return &TLSDescription{ version.Slug, cipher.Slug, } }
go
func EncodeTLSToObject(t *tls.ConnectionState) interface{} { version := lookup(tlsVersions, t.Version) cipher := lookup(cipherSuites, t.CipherSuite) return &TLSDescription{ version.Slug, cipher.Slug, } }
[ "func", "EncodeTLSToObject", "(", "t", "*", "tls", ".", "ConnectionState", ")", "interface", "{", "}", "{", "version", ":=", "lookup", "(", "tlsVersions", ",", "t", ".", "Version", ")", "\n", "cipher", ":=", "lookup", "(", "cipherSuites", ",", "t", ".", "CipherSuite", ")", "\n", "return", "&", "TLSDescription", "{", "version", ".", "Slug", ",", "cipher", ".", "Slug", ",", "}", "\n", "}" ]
// EncodeTLSToObject returns a JSON-marshallable description of a TLS connection
[ "EncodeTLSToObject", "returns", "a", "JSON", "-", "marshallable", "description", "of", "a", "TLS", "connection" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/tls.go#L102-L109
11,147
square/certigo
lib/tls.go
EncodeCRIToObject
func EncodeCRIToObject(cri *tls.CertificateRequestInfo) (interface{}, error) { out := &CertificateRequestInfo{} for _, ca := range cri.AcceptableCAs { subject, err := parseRawSubject(ca) if err != nil { return nil, err } out.AcceptableCAs = append(out.AcceptableCAs, simplePKIXName{subject, nil}) } for _, scheme := range cri.SignatureSchemes { desc, ok := signatureSchemeStrings[scheme] if !ok { desc = fmt.Sprintf("Unknown(0x%x)", scheme) } out.SignatureSchemes = append(out.SignatureSchemes, desc) } return out, nil }
go
func EncodeCRIToObject(cri *tls.CertificateRequestInfo) (interface{}, error) { out := &CertificateRequestInfo{} for _, ca := range cri.AcceptableCAs { subject, err := parseRawSubject(ca) if err != nil { return nil, err } out.AcceptableCAs = append(out.AcceptableCAs, simplePKIXName{subject, nil}) } for _, scheme := range cri.SignatureSchemes { desc, ok := signatureSchemeStrings[scheme] if !ok { desc = fmt.Sprintf("Unknown(0x%x)", scheme) } out.SignatureSchemes = append(out.SignatureSchemes, desc) } return out, nil }
[ "func", "EncodeCRIToObject", "(", "cri", "*", "tls", ".", "CertificateRequestInfo", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "out", ":=", "&", "CertificateRequestInfo", "{", "}", "\n", "for", "_", ",", "ca", ":=", "range", "cri", ".", "AcceptableCAs", "{", "subject", ",", "err", ":=", "parseRawSubject", "(", "ca", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "out", ".", "AcceptableCAs", "=", "append", "(", "out", ".", "AcceptableCAs", ",", "simplePKIXName", "{", "subject", ",", "nil", "}", ")", "\n", "}", "\n", "for", "_", ",", "scheme", ":=", "range", "cri", ".", "SignatureSchemes", "{", "desc", ",", "ok", ":=", "signatureSchemeStrings", "[", "scheme", "]", "\n", "if", "!", "ok", "{", "desc", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "scheme", ")", "\n", "}", "\n", "out", ".", "SignatureSchemes", "=", "append", "(", "out", ".", "SignatureSchemes", ",", "desc", ")", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// EncodeCRIToObject returns a JSON-marshallable representation of a CertificateRequestInfo object.
[ "EncodeCRIToObject", "returns", "a", "JSON", "-", "marshallable", "representation", "of", "a", "CertificateRequestInfo", "object", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/tls.go#L112-L129
11,148
square/certigo
lib/tls.go
lookup
func lookup(descriptions map[uint16]description, what uint16) description { v, ok := descriptions[what] if !ok { unknown := fmt.Sprintf("UNKNOWN_%x", what) return description{unknown, unknown, 0} } return v }
go
func lookup(descriptions map[uint16]description, what uint16) description { v, ok := descriptions[what] if !ok { unknown := fmt.Sprintf("UNKNOWN_%x", what) return description{unknown, unknown, 0} } return v }
[ "func", "lookup", "(", "descriptions", "map", "[", "uint16", "]", "description", ",", "what", "uint16", ")", "description", "{", "v", ",", "ok", ":=", "descriptions", "[", "what", "]", "\n", "if", "!", "ok", "{", "unknown", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "what", ")", "\n", "return", "description", "{", "unknown", ",", "unknown", ",", "0", "}", "\n", "}", "\n", "return", "v", "\n", "}" ]
// Just a map lookup with a default
[ "Just", "a", "map", "lookup", "with", "a", "default" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/tls.go#L132-L139
11,149
square/certigo
lib/tls.go
explainCipher
func explainCipher(d description) description { kexAndCipher := strings.Split(d.Slug, "_WITH_") d.Name = fmt.Sprintf("%s key exchange, %s cipher", kexAndCipher[0][len("TLS_"):], kexAndCipher[1]) return d }
go
func explainCipher(d description) description { kexAndCipher := strings.Split(d.Slug, "_WITH_") d.Name = fmt.Sprintf("%s key exchange, %s cipher", kexAndCipher[0][len("TLS_"):], kexAndCipher[1]) return d }
[ "func", "explainCipher", "(", "d", "description", ")", "description", "{", "kexAndCipher", ":=", "strings", ".", "Split", "(", "d", ".", "Slug", ",", "\"", "\"", ")", "\n", "d", ".", "Name", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "kexAndCipher", "[", "0", "]", "[", "len", "(", "\"", "\"", ")", ":", "]", ",", "kexAndCipher", "[", "1", "]", ")", "\n", "return", "d", "\n", "}" ]
// Fill in a human readable name, extracted from the slug
[ "Fill", "in", "a", "human", "readable", "name", "extracted", "from", "the", "slug" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/tls.go#L180-L184
11,150
square/certigo
starttls/ldap/control.go
FindControl
func FindControl(controls []Control, controlType string) Control { for _, c := range controls { if c.GetControlType() == controlType { return c } } return nil }
go
func FindControl(controls []Control, controlType string) Control { for _, c := range controls { if c.GetControlType() == controlType { return c } } return nil }
[ "func", "FindControl", "(", "controls", "[", "]", "Control", ",", "controlType", "string", ")", "Control", "{", "for", "_", ",", "c", ":=", "range", "controls", "{", "if", "c", ".", "GetControlType", "(", ")", "==", "controlType", "{", "return", "c", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FindControl returns the first control of the given type in the list, or nil
[ "FindControl", "returns", "the", "first", "control", "of", "the", "given", "type", "in", "the", "list", "or", "nil" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/control.go#L246-L253
11,151
square/certigo
starttls/ldap/control.go
NewControlString
func NewControlString(controlType string, criticality bool, controlValue string) *ControlString { return &ControlString{ ControlType: controlType, Criticality: criticality, ControlValue: controlValue, } }
go
func NewControlString(controlType string, criticality bool, controlValue string) *ControlString { return &ControlString{ ControlType: controlType, Criticality: criticality, ControlValue: controlValue, } }
[ "func", "NewControlString", "(", "controlType", "string", ",", "criticality", "bool", ",", "controlValue", "string", ")", "*", "ControlString", "{", "return", "&", "ControlString", "{", "ControlType", ":", "controlType", ",", "Criticality", ":", "criticality", ",", "ControlValue", ":", "controlValue", ",", "}", "\n", "}" ]
// NewControlString returns a generic control
[ "NewControlString", "returns", "a", "generic", "control" ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/starttls/ldap/control.go#L392-L398
11,152
square/certigo
lib/certs.go
readCertsFromStream
func readCertsFromStream(reader io.Reader, filename string, format string, password func(string) string, callback func(*pem.Block)) error { headers := map[string]string{} if filename != "" && filename != os.Stdin.Name() { headers[fileHeader] = filename } switch strings.TrimSpace(format) { case "PEM": scanner := pemScanner(reader) for scanner.Scan() { block, _ := pem.Decode(scanner.Bytes()) block.Headers = mergeHeaders(block.Headers, headers) callback(block) } return nil case "DER": data, err := ioutil.ReadAll(reader) if err != nil { return fmt.Errorf("unable to read input: %s\n", err) } x509Certs, err0 := x509.ParseCertificates(data) if err0 == nil { for _, cert := range x509Certs { callback(EncodeX509ToPEM(cert, headers)) } return nil } p7bBlocks, err1 := pkcs7.ParseSignedData(data) if err1 == nil { for _, block := range p7bBlocks { callback(pkcs7ToPem(block, headers)) } return nil } return fmt.Errorf("unable to parse certificates from DER data\n* X.509 parser gave: %s\n* PKCS7 parser gave: %s\n", err0, err1) case "PKCS12": data, err := ioutil.ReadAll(reader) if err != nil { return fmt.Errorf("unable to read input: %s\n", err) } blocks, err := pkcs12.ToPEM(data, password("")) if err != nil || len(blocks) == 0 { return fmt.Errorf("keystore appears to be empty or password was incorrect\n") } for _, block := range blocks { block.Headers = mergeHeaders(block.Headers, headers) callback(block) } return nil case "JCEKS": keyStore, err := jceks.LoadFromReader(reader, []byte(password(""))) if err != nil { return fmt.Errorf("unable to parse keystore: %s\n", err) } for _, alias := range keyStore.ListCerts() { cert, _ := keyStore.GetCert(alias) callback(EncodeX509ToPEM(cert, mergeHeaders(headers, map[string]string{nameHeader: alias}))) } for _, alias := range keyStore.ListPrivateKeys() { key, certs, err := keyStore.GetPrivateKeyAndCerts(alias, []byte(password(alias))) if err != nil { return fmt.Errorf("unable to parse keystore: %s\n", err) } block, err := keyToPem(key, mergeHeaders(headers, map[string]string{nameHeader: alias})) if err != nil { return fmt.Errorf("problem reading key: %s\n", err) } callback(block) for _, cert := range certs { callback(EncodeX509ToPEM(cert, mergeHeaders(headers, map[string]string{nameHeader: alias}))) } } return nil } return fmt.Errorf("unknown file type '%s'\n", format) }
go
func readCertsFromStream(reader io.Reader, filename string, format string, password func(string) string, callback func(*pem.Block)) error { headers := map[string]string{} if filename != "" && filename != os.Stdin.Name() { headers[fileHeader] = filename } switch strings.TrimSpace(format) { case "PEM": scanner := pemScanner(reader) for scanner.Scan() { block, _ := pem.Decode(scanner.Bytes()) block.Headers = mergeHeaders(block.Headers, headers) callback(block) } return nil case "DER": data, err := ioutil.ReadAll(reader) if err != nil { return fmt.Errorf("unable to read input: %s\n", err) } x509Certs, err0 := x509.ParseCertificates(data) if err0 == nil { for _, cert := range x509Certs { callback(EncodeX509ToPEM(cert, headers)) } return nil } p7bBlocks, err1 := pkcs7.ParseSignedData(data) if err1 == nil { for _, block := range p7bBlocks { callback(pkcs7ToPem(block, headers)) } return nil } return fmt.Errorf("unable to parse certificates from DER data\n* X.509 parser gave: %s\n* PKCS7 parser gave: %s\n", err0, err1) case "PKCS12": data, err := ioutil.ReadAll(reader) if err != nil { return fmt.Errorf("unable to read input: %s\n", err) } blocks, err := pkcs12.ToPEM(data, password("")) if err != nil || len(blocks) == 0 { return fmt.Errorf("keystore appears to be empty or password was incorrect\n") } for _, block := range blocks { block.Headers = mergeHeaders(block.Headers, headers) callback(block) } return nil case "JCEKS": keyStore, err := jceks.LoadFromReader(reader, []byte(password(""))) if err != nil { return fmt.Errorf("unable to parse keystore: %s\n", err) } for _, alias := range keyStore.ListCerts() { cert, _ := keyStore.GetCert(alias) callback(EncodeX509ToPEM(cert, mergeHeaders(headers, map[string]string{nameHeader: alias}))) } for _, alias := range keyStore.ListPrivateKeys() { key, certs, err := keyStore.GetPrivateKeyAndCerts(alias, []byte(password(alias))) if err != nil { return fmt.Errorf("unable to parse keystore: %s\n", err) } block, err := keyToPem(key, mergeHeaders(headers, map[string]string{nameHeader: alias})) if err != nil { return fmt.Errorf("problem reading key: %s\n", err) } callback(block) for _, cert := range certs { callback(EncodeX509ToPEM(cert, mergeHeaders(headers, map[string]string{nameHeader: alias}))) } } return nil } return fmt.Errorf("unknown file type '%s'\n", format) }
[ "func", "readCertsFromStream", "(", "reader", "io", ".", "Reader", ",", "filename", "string", ",", "format", "string", ",", "password", "func", "(", "string", ")", "string", ",", "callback", "func", "(", "*", "pem", ".", "Block", ")", ")", "error", "{", "headers", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "if", "filename", "!=", "\"", "\"", "&&", "filename", "!=", "os", ".", "Stdin", ".", "Name", "(", ")", "{", "headers", "[", "fileHeader", "]", "=", "filename", "\n", "}", "\n\n", "switch", "strings", ".", "TrimSpace", "(", "format", ")", "{", "case", "\"", "\"", ":", "scanner", ":=", "pemScanner", "(", "reader", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "block", ",", "_", ":=", "pem", ".", "Decode", "(", "scanner", ".", "Bytes", "(", ")", ")", "\n", "block", ".", "Headers", "=", "mergeHeaders", "(", "block", ".", "Headers", ",", "headers", ")", "\n", "callback", "(", "block", ")", "\n", "}", "\n", "return", "nil", "\n", "case", "\"", "\"", ":", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "x509Certs", ",", "err0", ":=", "x509", ".", "ParseCertificates", "(", "data", ")", "\n", "if", "err0", "==", "nil", "{", "for", "_", ",", "cert", ":=", "range", "x509Certs", "{", "callback", "(", "EncodeX509ToPEM", "(", "cert", ",", "headers", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "p7bBlocks", ",", "err1", ":=", "pkcs7", ".", "ParseSignedData", "(", "data", ")", "\n", "if", "err1", "==", "nil", "{", "for", "_", ",", "block", ":=", "range", "p7bBlocks", "{", "callback", "(", "pkcs7ToPem", "(", "block", ",", "headers", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "err0", ",", "err1", ")", "\n", "case", "\"", "\"", ":", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "blocks", ",", "err", ":=", "pkcs12", ".", "ToPEM", "(", "data", ",", "password", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "blocks", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "for", "_", ",", "block", ":=", "range", "blocks", "{", "block", ".", "Headers", "=", "mergeHeaders", "(", "block", ".", "Headers", ",", "headers", ")", "\n", "callback", "(", "block", ")", "\n", "}", "\n", "return", "nil", "\n", "case", "\"", "\"", ":", "keyStore", ",", "err", ":=", "jceks", ".", "LoadFromReader", "(", "reader", ",", "[", "]", "byte", "(", "password", "(", "\"", "\"", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "alias", ":=", "range", "keyStore", ".", "ListCerts", "(", ")", "{", "cert", ",", "_", ":=", "keyStore", ".", "GetCert", "(", "alias", ")", "\n", "callback", "(", "EncodeX509ToPEM", "(", "cert", ",", "mergeHeaders", "(", "headers", ",", "map", "[", "string", "]", "string", "{", "nameHeader", ":", "alias", "}", ")", ")", ")", "\n", "}", "\n", "for", "_", ",", "alias", ":=", "range", "keyStore", ".", "ListPrivateKeys", "(", ")", "{", "key", ",", "certs", ",", "err", ":=", "keyStore", ".", "GetPrivateKeyAndCerts", "(", "alias", ",", "[", "]", "byte", "(", "password", "(", "alias", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "block", ",", "err", ":=", "keyToPem", "(", "key", ",", "mergeHeaders", "(", "headers", ",", "map", "[", "string", "]", "string", "{", "nameHeader", ":", "alias", "}", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "callback", "(", "block", ")", "\n", "for", "_", ",", "cert", ":=", "range", "certs", "{", "callback", "(", "EncodeX509ToPEM", "(", "cert", ",", "mergeHeaders", "(", "headers", ",", "map", "[", "string", "]", "string", "{", "nameHeader", ":", "alias", "}", ")", ")", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "format", ")", "\n", "}" ]
// readCertsFromStream takes some input and converts it to PEM blocks.
[ "readCertsFromStream", "takes", "some", "input", "and", "converts", "it", "to", "PEM", "blocks", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/certs.go#L191-L266
11,153
square/certigo
lib/certs.go
EncodeX509ToPEM
func EncodeX509ToPEM(cert *x509.Certificate, headers map[string]string) *pem.Block { return &pem.Block{ Type: "CERTIFICATE", Bytes: cert.Raw, Headers: headers, } }
go
func EncodeX509ToPEM(cert *x509.Certificate, headers map[string]string) *pem.Block { return &pem.Block{ Type: "CERTIFICATE", Bytes: cert.Raw, Headers: headers, } }
[ "func", "EncodeX509ToPEM", "(", "cert", "*", "x509", ".", "Certificate", ",", "headers", "map", "[", "string", "]", "string", ")", "*", "pem", ".", "Block", "{", "return", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "cert", ".", "Raw", ",", "Headers", ":", "headers", ",", "}", "\n", "}" ]
// EncodeX509ToPEM converts an X.509 certificate into a PEM block for output.
[ "EncodeX509ToPEM", "converts", "an", "X", ".", "509", "certificate", "into", "a", "PEM", "block", "for", "output", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/certs.go#L280-L286
11,154
square/certigo
lib/certs.go
pkcs7ToPem
func pkcs7ToPem(block *pkcs7.SignedDataEnvelope, headers map[string]string) *pem.Block { return &pem.Block{ Type: "PKCS7", Bytes: block.Raw, Headers: headers, } }
go
func pkcs7ToPem(block *pkcs7.SignedDataEnvelope, headers map[string]string) *pem.Block { return &pem.Block{ Type: "PKCS7", Bytes: block.Raw, Headers: headers, } }
[ "func", "pkcs7ToPem", "(", "block", "*", "pkcs7", ".", "SignedDataEnvelope", ",", "headers", "map", "[", "string", "]", "string", ")", "*", "pem", ".", "Block", "{", "return", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "block", ".", "Raw", ",", "Headers", ":", "headers", ",", "}", "\n", "}" ]
// Convert a PKCS7 envelope into a PEM block for output.
[ "Convert", "a", "PKCS7", "envelope", "into", "a", "PEM", "block", "for", "output", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/certs.go#L289-L295
11,155
square/certigo
lib/certs.go
keyToPem
func keyToPem(key crypto.PrivateKey, headers map[string]string) (*pem.Block, error) { switch k := key.(type) { case *rsa.PrivateKey: return &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k), Headers: headers, }, nil case *ecdsa.PrivateKey: raw, err := x509.MarshalECPrivateKey(k) if err != nil { return nil, fmt.Errorf("error marshaling key: %s\n", reflect.TypeOf(key)) } return &pem.Block{ Type: "EC PRIVATE KEY", Bytes: raw, Headers: headers, }, nil } return nil, fmt.Errorf("unknown key type: %s\n", reflect.TypeOf(key)) }
go
func keyToPem(key crypto.PrivateKey, headers map[string]string) (*pem.Block, error) { switch k := key.(type) { case *rsa.PrivateKey: return &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k), Headers: headers, }, nil case *ecdsa.PrivateKey: raw, err := x509.MarshalECPrivateKey(k) if err != nil { return nil, fmt.Errorf("error marshaling key: %s\n", reflect.TypeOf(key)) } return &pem.Block{ Type: "EC PRIVATE KEY", Bytes: raw, Headers: headers, }, nil } return nil, fmt.Errorf("unknown key type: %s\n", reflect.TypeOf(key)) }
[ "func", "keyToPem", "(", "key", "crypto", ".", "PrivateKey", ",", "headers", "map", "[", "string", "]", "string", ")", "(", "*", "pem", ".", "Block", ",", "error", ")", "{", "switch", "k", ":=", "key", ".", "(", "type", ")", "{", "case", "*", "rsa", ".", "PrivateKey", ":", "return", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "x509", ".", "MarshalPKCS1PrivateKey", "(", "k", ")", ",", "Headers", ":", "headers", ",", "}", ",", "nil", "\n", "case", "*", "ecdsa", ".", "PrivateKey", ":", "raw", ",", "err", ":=", "x509", ".", "MarshalECPrivateKey", "(", "k", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "reflect", ".", "TypeOf", "(", "key", ")", ")", "\n", "}", "\n", "return", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "raw", ",", "Headers", ":", "headers", ",", "}", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "reflect", ".", "TypeOf", "(", "key", ")", ")", "\n", "}" ]
// Convert a key into one or more PEM blocks for output.
[ "Convert", "a", "key", "into", "one", "or", "more", "PEM", "blocks", "for", "output", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/certs.go#L298-L318
11,156
square/certigo
lib/certs.go
pemScanner
func pemScanner(reader io.Reader) *bufio.Scanner { scanner := bufio.NewScanner(reader) scanner.Split(func(data []byte, atEOF bool) (int, []byte, error) { block, rest := pem.Decode(data) if block != nil { size := len(data) - len(rest) return size, data[:size], nil } return 0, nil, nil }) return scanner }
go
func pemScanner(reader io.Reader) *bufio.Scanner { scanner := bufio.NewScanner(reader) scanner.Split(func(data []byte, atEOF bool) (int, []byte, error) { block, rest := pem.Decode(data) if block != nil { size := len(data) - len(rest) return size, data[:size], nil } return 0, nil, nil }) return scanner }
[ "func", "pemScanner", "(", "reader", "io", ".", "Reader", ")", "*", "bufio", ".", "Scanner", "{", "scanner", ":=", "bufio", ".", "NewScanner", "(", "reader", ")", "\n\n", "scanner", ".", "Split", "(", "func", "(", "data", "[", "]", "byte", ",", "atEOF", "bool", ")", "(", "int", ",", "[", "]", "byte", ",", "error", ")", "{", "block", ",", "rest", ":=", "pem", ".", "Decode", "(", "data", ")", "\n", "if", "block", "!=", "nil", "{", "size", ":=", "len", "(", "data", ")", "-", "len", "(", "rest", ")", "\n", "return", "size", ",", "data", "[", ":", "size", "]", ",", "nil", "\n", "}", "\n\n", "return", "0", ",", "nil", ",", "nil", "\n", "}", ")", "\n\n", "return", "scanner", "\n", "}" ]
// pemScanner will return a bufio.Scanner that splits the input // from the given reader into PEM blocks.
[ "pemScanner", "will", "return", "a", "bufio", ".", "Scanner", "that", "splits", "the", "input", "from", "the", "given", "reader", "into", "PEM", "blocks", "." ]
9ce8f40ef6de69064855a1ebe32e97360ca75c9c
https://github.com/square/certigo/blob/9ce8f40ef6de69064855a1ebe32e97360ca75c9c/lib/certs.go#L364-L378
11,157
ungerik/go3d
mat2/mat2.go
TransformVec2
func (mat *T) TransformVec2(v *vec2.T) { // Use intermediate variables to not alter further computations. x := mat[0][0]*v[0] + mat[1][0]*v[1] v[1] = mat[0][1]*v[0] + mat[1][1]*v[1] v[0] = x }
go
func (mat *T) TransformVec2(v *vec2.T) { // Use intermediate variables to not alter further computations. x := mat[0][0]*v[0] + mat[1][0]*v[1] v[1] = mat[0][1]*v[0] + mat[1][1]*v[1] v[0] = x }
[ "func", "(", "mat", "*", "T", ")", "TransformVec2", "(", "v", "*", "vec2", ".", "T", ")", "{", "// Use intermediate variables to not alter further computations.", "x", ":=", "mat", "[", "0", "]", "[", "0", "]", "*", "v", "[", "0", "]", "+", "mat", "[", "1", "]", "[", "0", "]", "*", "v", "[", "1", "]", "\n", "v", "[", "1", "]", "=", "mat", "[", "0", "]", "[", "1", "]", "*", "v", "[", "0", "]", "+", "mat", "[", "1", "]", "[", "1", "]", "*", "v", "[", "1", "]", "\n", "v", "[", "0", "]", "=", "x", "\n", "}" ]
// TransformVec2 multiplies v with mat and saves the result in v.
[ "TransformVec2", "multiplies", "v", "with", "mat", "and", "saves", "the", "result", "in", "v", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat2/mat2.go#L135-L140
11,158
ungerik/go3d
mat2/mat2.go
Transpose
func (mat *T) Transpose() *T { temp := mat[0][1] mat[0][1] = mat[1][0] mat[1][0] = temp return mat }
go
func (mat *T) Transpose() *T { temp := mat[0][1] mat[0][1] = mat[1][0] mat[1][0] = temp return mat }
[ "func", "(", "mat", "*", "T", ")", "Transpose", "(", ")", "*", "T", "{", "temp", ":=", "mat", "[", "0", "]", "[", "1", "]", "\n", "mat", "[", "0", "]", "[", "1", "]", "=", "mat", "[", "1", "]", "[", "0", "]", "\n", "mat", "[", "1", "]", "[", "0", "]", "=", "temp", "\n", "return", "mat", "\n", "}" ]
// Transpose transposes the matrix.
[ "Transpose", "transposes", "the", "matrix", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat2/mat2.go#L143-L148
11,159
ungerik/go3d
vec4/vec4.go
Scale
func (vec *T) Scale(f float32) *T { vec[0] *= f vec[1] *= f vec[2] *= f return vec }
go
func (vec *T) Scale(f float32) *T { vec[0] *= f vec[1] *= f vec[2] *= f return vec }
[ "func", "(", "vec", "*", "T", ")", "Scale", "(", "f", "float32", ")", "*", "T", "{", "vec", "[", "0", "]", "*=", "f", "\n", "vec", "[", "1", "]", "*=", "f", "\n", "vec", "[", "2", "]", "*=", "f", "\n", "return", "vec", "\n", "}" ]
// Scale multiplies the first 3 element of the vector by f and returns vec.
[ "Scale", "multiplies", "the", "first", "3", "element", "of", "the", "vector", "by", "f", "and", "returns", "vec", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec4/vec4.go#L668-L673
11,160
ungerik/go3d
vec4/vec4.go
Invert
func (vec *T) Invert() *T { vec[0] = -vec[0] vec[1] = -vec[1] vec[2] = -vec[2] return vec }
go
func (vec *T) Invert() *T { vec[0] = -vec[0] vec[1] = -vec[1] vec[2] = -vec[2] return vec }
[ "func", "(", "vec", "*", "T", ")", "Invert", "(", ")", "*", "T", "{", "vec", "[", "0", "]", "=", "-", "vec", "[", "0", "]", "\n", "vec", "[", "1", "]", "=", "-", "vec", "[", "1", "]", "\n", "vec", "[", "2", "]", "=", "-", "vec", "[", "2", "]", "\n", "return", "vec", "\n", "}" ]
// Invert inverts the vector.
[ "Invert", "inverts", "the", "vector", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec4/vec4.go#L681-L686
11,161
ungerik/go3d
vec4/vec4.go
Vec3
func (vec *T) Vec3() vec3.T { return vec3.T{vec[0], vec[1], vec[2]} }
go
func (vec *T) Vec3() vec3.T { return vec3.T{vec[0], vec[1], vec[2]} }
[ "func", "(", "vec", "*", "T", ")", "Vec3", "(", ")", "vec3", ".", "T", "{", "return", "vec3", ".", "T", "{", "vec", "[", "0", "]", ",", "vec", "[", "1", "]", ",", "vec", "[", "2", "]", "}", "\n", "}" ]
// Vec3 returns a vec3.T with the first three components of the vector. // See also Vec3DividedByW
[ "Vec3", "returns", "a", "vec3", ".", "T", "with", "the", "first", "three", "components", "of", "the", "vector", ".", "See", "also", "Vec3DividedByW" ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec4/vec4.go#L742-L744
11,162
ungerik/go3d
vec4/vec4.go
AssignVec3
func (vec *T) AssignVec3(v *vec3.T) *T { vec[0] = v[0] vec[1] = v[1] vec[2] = v[2] vec[3] = 1 return vec }
go
func (vec *T) AssignVec3(v *vec3.T) *T { vec[0] = v[0] vec[1] = v[1] vec[2] = v[2] vec[3] = 1 return vec }
[ "func", "(", "vec", "*", "T", ")", "AssignVec3", "(", "v", "*", "vec3", ".", "T", ")", "*", "T", "{", "vec", "[", "0", "]", "=", "v", "[", "0", "]", "\n", "vec", "[", "1", "]", "=", "v", "[", "1", "]", "\n", "vec", "[", "2", "]", "=", "v", "[", "2", "]", "\n", "vec", "[", "3", "]", "=", "1", "\n", "return", "vec", "\n", "}" ]
// AssignVec3 assigns v to the first three components and sets the fourth to 1.
[ "AssignVec3", "assigns", "v", "to", "the", "first", "three", "components", "and", "sets", "the", "fourth", "to", "1", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec4/vec4.go#L747-L753
11,163
ungerik/go3d
vec4/vec4.go
Dot4
func Dot4(a, b *T) float32 { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + a[3]*b[3] }
go
func Dot4(a, b *T) float32 { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + a[3]*b[3] }
[ "func", "Dot4", "(", "a", ",", "b", "*", "T", ")", "float32", "{", "return", "a", "[", "0", "]", "*", "b", "[", "0", "]", "+", "a", "[", "1", "]", "*", "b", "[", "1", "]", "+", "a", "[", "2", "]", "*", "b", "[", "2", "]", "+", "a", "[", "3", "]", "*", "b", "[", "3", "]", "\n", "}" ]
// Dot4 returns the 4 element dot product of two vectors.
[ "Dot4", "returns", "the", "4", "element", "dot", "product", "of", "two", "vectors", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec4/vec4.go#L817-L819
11,164
ungerik/go3d
vec4/vec4.go
Angle
func Angle(a, b *T) float32 { v := Dot(a, b) / (a.Length() * b.Length()) // prevent NaN if v > 1. { v = v - 2 } else if v < -1. { v = v + 2 } return math.Acos(v) }
go
func Angle(a, b *T) float32 { v := Dot(a, b) / (a.Length() * b.Length()) // prevent NaN if v > 1. { v = v - 2 } else if v < -1. { v = v + 2 } return math.Acos(v) }
[ "func", "Angle", "(", "a", ",", "b", "*", "T", ")", "float32", "{", "v", ":=", "Dot", "(", "a", ",", "b", ")", "/", "(", "a", ".", "Length", "(", ")", "*", "b", ".", "Length", "(", ")", ")", "\n", "// prevent NaN", "if", "v", ">", "1.", "{", "v", "=", "v", "-", "2", "\n", "}", "else", "if", "v", "<", "-", "1.", "{", "v", "=", "v", "+", "2", "\n", "}", "\n", "return", "math", ".", "Acos", "(", "v", ")", "\n", "}" ]
// Angle returns the angle between two vectors.
[ "Angle", "returns", "the", "angle", "between", "two", "vectors", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec4/vec4.go#L830-L839
11,165
ungerik/go3d
vec4/vec4.go
Clamp
func (vec *T) Clamp(min, max *T) *T { for i := range vec { if vec[i] < min[i] { vec[i] = min[i] } else if vec[i] > max[i] { vec[i] = max[i] } } return vec }
go
func (vec *T) Clamp(min, max *T) *T { for i := range vec { if vec[i] < min[i] { vec[i] = min[i] } else if vec[i] > max[i] { vec[i] = max[i] } } return vec }
[ "func", "(", "vec", "*", "T", ")", "Clamp", "(", "min", ",", "max", "*", "T", ")", "*", "T", "{", "for", "i", ":=", "range", "vec", "{", "if", "vec", "[", "i", "]", "<", "min", "[", "i", "]", "{", "vec", "[", "i", "]", "=", "min", "[", "i", "]", "\n", "}", "else", "if", "vec", "[", "i", "]", ">", "max", "[", "i", "]", "{", "vec", "[", "i", "]", "=", "max", "[", "i", "]", "\n", "}", "\n", "}", "\n", "return", "vec", "\n", "}" ]
// Clamp clamps the vector's components to be in the range of min to max.
[ "Clamp", "clamps", "the", "vector", "s", "components", "to", "be", "in", "the", "range", "of", "min", "to", "max", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec4/vec4.go#L853-L862
11,166
ungerik/go3d
vec4/vec4.go
Clamped
func (vec *T) Clamped(min, max *T) T { result := *vec result.Clamp(min, max) return result }
go
func (vec *T) Clamped(min, max *T) T { result := *vec result.Clamp(min, max) return result }
[ "func", "(", "vec", "*", "T", ")", "Clamped", "(", "min", ",", "max", "*", "T", ")", "T", "{", "result", ":=", "*", "vec", "\n", "result", ".", "Clamp", "(", "min", ",", "max", ")", "\n", "return", "result", "\n", "}" ]
// Clamped returns a copy of the vector with the components clamped to be in the range of min to max.
[ "Clamped", "returns", "a", "copy", "of", "the", "vector", "with", "the", "components", "clamped", "to", "be", "in", "the", "range", "of", "min", "to", "max", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec4/vec4.go#L865-L869
11,167
ungerik/go3d
vec2/rect.go
ContainsPoint
func (rect *Rect) ContainsPoint(p *T) bool { return p[0] >= rect.Min[0] && p[0] <= rect.Max[0] && p[1] >= rect.Min[1] && p[1] <= rect.Max[1] }
go
func (rect *Rect) ContainsPoint(p *T) bool { return p[0] >= rect.Min[0] && p[0] <= rect.Max[0] && p[1] >= rect.Min[1] && p[1] <= rect.Max[1] }
[ "func", "(", "rect", "*", "Rect", ")", "ContainsPoint", "(", "p", "*", "T", ")", "bool", "{", "return", "p", "[", "0", "]", ">=", "rect", ".", "Min", "[", "0", "]", "&&", "p", "[", "0", "]", "<=", "rect", ".", "Max", "[", "0", "]", "&&", "p", "[", "1", "]", ">=", "rect", ".", "Min", "[", "1", "]", "&&", "p", "[", "1", "]", "<=", "rect", ".", "Max", "[", "1", "]", "\n", "}" ]
// ContainsPoint returns if a point is contained within the rectangle.
[ "ContainsPoint", "returns", "if", "a", "point", "is", "contained", "within", "the", "rectangle", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec2/rect.go#L25-L28
11,168
ungerik/go3d
float64/vec4/vec4.go
Scaled
func (vec *T) Scaled(f float64) T { return T{vec[0] * f, vec[1] * f, vec[2] * f, vec[3]} }
go
func (vec *T) Scaled(f float64) T { return T{vec[0] * f, vec[1] * f, vec[2] * f, vec[3]} }
[ "func", "(", "vec", "*", "T", ")", "Scaled", "(", "f", "float64", ")", "T", "{", "return", "T", "{", "vec", "[", "0", "]", "*", "f", ",", "vec", "[", "1", "]", "*", "f", ",", "vec", "[", "2", "]", "*", "f", ",", "vec", "[", "3", "]", "}", "\n", "}" ]
// Scaled returns a copy of vec with the first 3 elements multiplies by f.
[ "Scaled", "returns", "a", "copy", "of", "vec", "with", "the", "first", "3", "elements", "multiplies", "by", "f", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/vec4/vec4.go#L676-L678
11,169
ungerik/go3d
float64/vec4/vec4.go
Dot4
func Dot4(a, b *T) float64 { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + a[3]*b[3] }
go
func Dot4(a, b *T) float64 { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + a[3]*b[3] }
[ "func", "Dot4", "(", "a", ",", "b", "*", "T", ")", "float64", "{", "return", "a", "[", "0", "]", "*", "b", "[", "0", "]", "+", "a", "[", "1", "]", "*", "b", "[", "1", "]", "+", "a", "[", "2", "]", "*", "b", "[", "2", "]", "+", "a", "[", "3", "]", "*", "b", "[", "3", "]", "\n", "}" ]
// Dot4 returns the 4 element vdot product of two vectors.
[ "Dot4", "returns", "the", "4", "element", "vdot", "product", "of", "two", "vectors", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/vec4/vec4.go#L816-L818
11,170
ungerik/go3d
vec2/vec2.go
RotateAroundPoint
func (vec *T) RotateAroundPoint(point *T, angle float32) *T { return vec.Sub(point).Rotate(angle).Add(point) }
go
func (vec *T) RotateAroundPoint(point *T, angle float32) *T { return vec.Sub(point).Rotate(angle).Add(point) }
[ "func", "(", "vec", "*", "T", ")", "RotateAroundPoint", "(", "point", "*", "T", ",", "angle", "float32", ")", "*", "T", "{", "return", "vec", ".", "Sub", "(", "point", ")", ".", "Rotate", "(", "angle", ")", ".", "Add", "(", "point", ")", "\n", "}" ]
// RotateAroundPoint rotates the vector counter-clockwise around a point.
[ "RotateAroundPoint", "rotates", "the", "vector", "counter", "-", "clockwise", "around", "a", "point", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec2/vec2.go#L167-L169
11,171
ungerik/go3d
vec2/vec2.go
IsLeftWinding
func IsLeftWinding(a, b *T) bool { ab := b.Rotated(-a.Angle()) return ab.Angle() > 0 }
go
func IsLeftWinding(a, b *T) bool { ab := b.Rotated(-a.Angle()) return ab.Angle() > 0 }
[ "func", "IsLeftWinding", "(", "a", ",", "b", "*", "T", ")", "bool", "{", "ab", ":=", "b", ".", "Rotated", "(", "-", "a", ".", "Angle", "(", ")", ")", "\n", "return", "ab", ".", "Angle", "(", ")", ">", "0", "\n", "}" ]
// IsLeftWinding returns if the angle from a to b is left winding.
[ "IsLeftWinding", "returns", "if", "the", "angle", "from", "a", "to", "b", "is", "left", "winding", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec2/vec2.go#L233-L236
11,172
ungerik/go3d
vec2/vec2.go
IsRightWinding
func IsRightWinding(a, b *T) bool { ab := b.Rotated(-a.Angle()) return ab.Angle() < 0 }
go
func IsRightWinding(a, b *T) bool { ab := b.Rotated(-a.Angle()) return ab.Angle() < 0 }
[ "func", "IsRightWinding", "(", "a", ",", "b", "*", "T", ")", "bool", "{", "ab", ":=", "b", ".", "Rotated", "(", "-", "a", ".", "Angle", "(", ")", ")", "\n", "return", "ab", ".", "Angle", "(", ")", "<", "0", "\n", "}" ]
// IsRightWinding returns if the angle from a to b is right winding.
[ "IsRightWinding", "returns", "if", "the", "angle", "from", "a", "to", "b", "is", "right", "winding", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec2/vec2.go#L239-L242
11,173
ungerik/go3d
quaternion/quaternion.go
Normalize
func (quat *T) Normalize() *T { norm := quat.Norm() if norm != 1 && norm != 0 { ool := 1 / math.Sqrt(norm) quat[0] *= ool quat[1] *= ool quat[2] *= ool quat[3] *= ool } return quat }
go
func (quat *T) Normalize() *T { norm := quat.Norm() if norm != 1 && norm != 0 { ool := 1 / math.Sqrt(norm) quat[0] *= ool quat[1] *= ool quat[2] *= ool quat[3] *= ool } return quat }
[ "func", "(", "quat", "*", "T", ")", "Normalize", "(", ")", "*", "T", "{", "norm", ":=", "quat", ".", "Norm", "(", ")", "\n", "if", "norm", "!=", "1", "&&", "norm", "!=", "0", "{", "ool", ":=", "1", "/", "math", ".", "Sqrt", "(", "norm", ")", "\n", "quat", "[", "0", "]", "*=", "ool", "\n", "quat", "[", "1", "]", "*=", "ool", "\n", "quat", "[", "2", "]", "*=", "ool", "\n", "quat", "[", "3", "]", "*=", "ool", "\n", "}", "\n", "return", "quat", "\n", "}" ]
// Normalize normalizes to a unit quaternation.
[ "Normalize", "normalizes", "to", "a", "unit", "quaternation", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/quaternion/quaternion.go#L104-L114
11,174
ungerik/go3d
quaternion/quaternion.go
Normalized
func (quat *T) Normalized() T { norm := quat.Norm() if norm != 1 && norm != 0 { ool := 1 / math.Sqrt(norm) return T{ quat[0] * ool, quat[1] * ool, quat[2] * ool, quat[3] * ool, } } else { return *quat } }
go
func (quat *T) Normalized() T { norm := quat.Norm() if norm != 1 && norm != 0 { ool := 1 / math.Sqrt(norm) return T{ quat[0] * ool, quat[1] * ool, quat[2] * ool, quat[3] * ool, } } else { return *quat } }
[ "func", "(", "quat", "*", "T", ")", "Normalized", "(", ")", "T", "{", "norm", ":=", "quat", ".", "Norm", "(", ")", "\n", "if", "norm", "!=", "1", "&&", "norm", "!=", "0", "{", "ool", ":=", "1", "/", "math", ".", "Sqrt", "(", "norm", ")", "\n", "return", "T", "{", "quat", "[", "0", "]", "*", "ool", ",", "quat", "[", "1", "]", "*", "ool", ",", "quat", "[", "2", "]", "*", "ool", ",", "quat", "[", "3", "]", "*", "ool", ",", "}", "\n", "}", "else", "{", "return", "*", "quat", "\n", "}", "\n", "}" ]
// Normalized returns a copy normalized to a unit quaternation.
[ "Normalized", "returns", "a", "copy", "normalized", "to", "a", "unit", "quaternation", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/quaternion/quaternion.go#L117-L130
11,175
ungerik/go3d
quaternion/quaternion.go
Negate
func (quat *T) Negate() *T { quat[0] = -quat[0] quat[1] = -quat[1] quat[2] = -quat[2] quat[3] = -quat[3] return quat }
go
func (quat *T) Negate() *T { quat[0] = -quat[0] quat[1] = -quat[1] quat[2] = -quat[2] quat[3] = -quat[3] return quat }
[ "func", "(", "quat", "*", "T", ")", "Negate", "(", ")", "*", "T", "{", "quat", "[", "0", "]", "=", "-", "quat", "[", "0", "]", "\n", "quat", "[", "1", "]", "=", "-", "quat", "[", "1", "]", "\n", "quat", "[", "2", "]", "=", "-", "quat", "[", "2", "]", "\n", "quat", "[", "3", "]", "=", "-", "quat", "[", "3", "]", "\n", "return", "quat", "\n", "}" ]
// Negate negates the quaternion.
[ "Negate", "negates", "the", "quaternion", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/quaternion/quaternion.go#L133-L139
11,176
ungerik/go3d
quaternion/quaternion.go
Invert
func (quat *T) Invert() *T { quat[0] = -quat[0] quat[1] = -quat[1] quat[2] = -quat[2] return quat }
go
func (quat *T) Invert() *T { quat[0] = -quat[0] quat[1] = -quat[1] quat[2] = -quat[2] return quat }
[ "func", "(", "quat", "*", "T", ")", "Invert", "(", ")", "*", "T", "{", "quat", "[", "0", "]", "=", "-", "quat", "[", "0", "]", "\n", "quat", "[", "1", "]", "=", "-", "quat", "[", "1", "]", "\n", "quat", "[", "2", "]", "=", "-", "quat", "[", "2", "]", "\n", "return", "quat", "\n", "}" ]
// Invert inverts the quaterion.
[ "Invert", "inverts", "the", "quaterion", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/quaternion/quaternion.go#L147-L152
11,177
ungerik/go3d
quaternion/quaternion.go
RotateVec3
func (quat *T) RotateVec3(v *vec3.T) { qv := T{v[0], v[1], v[2], 0} inv := quat.Inverted() q := Mul3(quat, &qv, &inv) v[0] = q[0] v[1] = q[1] v[2] = q[2] }
go
func (quat *T) RotateVec3(v *vec3.T) { qv := T{v[0], v[1], v[2], 0} inv := quat.Inverted() q := Mul3(quat, &qv, &inv) v[0] = q[0] v[1] = q[1] v[2] = q[2] }
[ "func", "(", "quat", "*", "T", ")", "RotateVec3", "(", "v", "*", "vec3", ".", "T", ")", "{", "qv", ":=", "T", "{", "v", "[", "0", "]", ",", "v", "[", "1", "]", ",", "v", "[", "2", "]", ",", "0", "}", "\n", "inv", ":=", "quat", ".", "Inverted", "(", ")", "\n", "q", ":=", "Mul3", "(", "quat", ",", "&", "qv", ",", "&", "inv", ")", "\n", "v", "[", "0", "]", "=", "q", "[", "0", "]", "\n", "v", "[", "1", "]", "=", "q", "[", "1", "]", "\n", "v", "[", "2", "]", "=", "q", "[", "2", "]", "\n", "}" ]
// RotateVec3 rotates v by the rotation represented by the quaternion.
[ "RotateVec3", "rotates", "v", "by", "the", "rotation", "represented", "by", "the", "quaternion", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/quaternion/quaternion.go#L183-L190
11,178
ungerik/go3d
quaternion/quaternion.go
Dot
func Dot(a, b *T) float32 { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + a[3]*b[3] }
go
func Dot(a, b *T) float32 { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + a[3]*b[3] }
[ "func", "Dot", "(", "a", ",", "b", "*", "T", ")", "float32", "{", "return", "a", "[", "0", "]", "*", "b", "[", "0", "]", "+", "a", "[", "1", "]", "*", "b", "[", "1", "]", "+", "a", "[", "2", "]", "*", "b", "[", "2", "]", "+", "a", "[", "3", "]", "*", "b", "[", "3", "]", "\n", "}" ]
// Dot returns the dot product of two quaternions.
[ "Dot", "returns", "the", "dot", "product", "of", "two", "quaternions", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/quaternion/quaternion.go#L201-L203
11,179
ungerik/go3d
quaternion/quaternion.go
Mul
func Mul(a, b *T) T { q := T{ a[3]*b[0] + a[0]*b[3] + a[1]*b[2] - a[2]*b[1], a[3]*b[1] + a[1]*b[3] + a[2]*b[0] - a[0]*b[2], a[3]*b[2] + a[2]*b[3] + a[0]*b[1] - a[1]*b[0], a[3]*b[3] - a[0]*b[0] - a[1]*b[1] - a[2]*b[2], } return q.Normalized() }
go
func Mul(a, b *T) T { q := T{ a[3]*b[0] + a[0]*b[3] + a[1]*b[2] - a[2]*b[1], a[3]*b[1] + a[1]*b[3] + a[2]*b[0] - a[0]*b[2], a[3]*b[2] + a[2]*b[3] + a[0]*b[1] - a[1]*b[0], a[3]*b[3] - a[0]*b[0] - a[1]*b[1] - a[2]*b[2], } return q.Normalized() }
[ "func", "Mul", "(", "a", ",", "b", "*", "T", ")", "T", "{", "q", ":=", "T", "{", "a", "[", "3", "]", "*", "b", "[", "0", "]", "+", "a", "[", "0", "]", "*", "b", "[", "3", "]", "+", "a", "[", "1", "]", "*", "b", "[", "2", "]", "-", "a", "[", "2", "]", "*", "b", "[", "1", "]", ",", "a", "[", "3", "]", "*", "b", "[", "1", "]", "+", "a", "[", "1", "]", "*", "b", "[", "3", "]", "+", "a", "[", "2", "]", "*", "b", "[", "0", "]", "-", "a", "[", "0", "]", "*", "b", "[", "2", "]", ",", "a", "[", "3", "]", "*", "b", "[", "2", "]", "+", "a", "[", "2", "]", "*", "b", "[", "3", "]", "+", "a", "[", "0", "]", "*", "b", "[", "1", "]", "-", "a", "[", "1", "]", "*", "b", "[", "0", "]", ",", "a", "[", "3", "]", "*", "b", "[", "3", "]", "-", "a", "[", "0", "]", "*", "b", "[", "0", "]", "-", "a", "[", "1", "]", "*", "b", "[", "1", "]", "-", "a", "[", "2", "]", "*", "b", "[", "2", "]", ",", "}", "\n", "return", "q", ".", "Normalized", "(", ")", "\n", "}" ]
// Mul multiplies two quaternions.
[ "Mul", "multiplies", "two", "quaternions", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/quaternion/quaternion.go#L206-L214
11,180
ungerik/go3d
quaternion/quaternion.go
Mul3
func Mul3(a, b, c *T) T { q := Mul(a, b) return Mul(&q, c) }
go
func Mul3(a, b, c *T) T { q := Mul(a, b) return Mul(&q, c) }
[ "func", "Mul3", "(", "a", ",", "b", ",", "c", "*", "T", ")", "T", "{", "q", ":=", "Mul", "(", "a", ",", "b", ")", "\n", "return", "Mul", "(", "&", "q", ",", "c", ")", "\n", "}" ]
// Mul3 multiplies three quaternions.
[ "Mul3", "multiplies", "three", "quaternions", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/quaternion/quaternion.go#L217-L220
11,181
ungerik/go3d
quaternion/quaternion.go
Mul4
func Mul4(a, b, c, d *T) T { q := Mul(a, b) q = Mul(&q, c) return Mul(&q, d) }
go
func Mul4(a, b, c, d *T) T { q := Mul(a, b) q = Mul(&q, c) return Mul(&q, d) }
[ "func", "Mul4", "(", "a", ",", "b", ",", "c", ",", "d", "*", "T", ")", "T", "{", "q", ":=", "Mul", "(", "a", ",", "b", ")", "\n", "q", "=", "Mul", "(", "&", "q", ",", "c", ")", "\n", "return", "Mul", "(", "&", "q", ",", "d", ")", "\n", "}" ]
// Mul4 multiplies four quaternions.
[ "Mul4", "multiplies", "four", "quaternions", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/quaternion/quaternion.go#L223-L227
11,182
ungerik/go3d
quaternion/quaternion.go
Vec3Diff
func Vec3Diff(a, b *vec3.T) T { cr := vec3.Cross(a, b) sr := math.Sqrt(2 * (1 + vec3.Dot(a, b))) oosr := 1 / sr q := T{cr[0] * oosr, cr[1] * oosr, cr[2] * oosr, sr * 0.5} return q.Normalized() }
go
func Vec3Diff(a, b *vec3.T) T { cr := vec3.Cross(a, b) sr := math.Sqrt(2 * (1 + vec3.Dot(a, b))) oosr := 1 / sr q := T{cr[0] * oosr, cr[1] * oosr, cr[2] * oosr, sr * 0.5} return q.Normalized() }
[ "func", "Vec3Diff", "(", "a", ",", "b", "*", "vec3", ".", "T", ")", "T", "{", "cr", ":=", "vec3", ".", "Cross", "(", "a", ",", "b", ")", "\n", "sr", ":=", "math", ".", "Sqrt", "(", "2", "*", "(", "1", "+", "vec3", ".", "Dot", "(", "a", ",", "b", ")", ")", ")", "\n", "oosr", ":=", "1", "/", "sr", "\n\n", "q", ":=", "T", "{", "cr", "[", "0", "]", "*", "oosr", ",", "cr", "[", "1", "]", "*", "oosr", ",", "cr", "[", "2", "]", "*", "oosr", ",", "sr", "*", "0.5", "}", "\n", "return", "q", ".", "Normalized", "(", ")", "\n", "}" ]
// Vec3Diff returns the rotation quaternion between two vectors.
[ "Vec3Diff", "returns", "the", "rotation", "quaternion", "between", "two", "vectors", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/quaternion/quaternion.go#L249-L256
11,183
ungerik/go3d
float64/vec2/rect.go
NewRect
func NewRect(a, b *T) (rect Rect) { rect.Min = Min(a, b) rect.Max = Max(a, b) return rect }
go
func NewRect(a, b *T) (rect Rect) { rect.Min = Min(a, b) rect.Max = Max(a, b) return rect }
[ "func", "NewRect", "(", "a", ",", "b", "*", "T", ")", "(", "rect", "Rect", ")", "{", "rect", ".", "Min", "=", "Min", "(", "a", ",", "b", ")", "\n", "rect", ".", "Max", "=", "Max", "(", "a", ",", "b", ")", "\n", "return", "rect", "\n", "}" ]
// NewRect creates a Rect from two points.
[ "NewRect", "creates", "a", "Rect", "from", "two", "points", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/vec2/rect.go#L14-L18
11,184
ungerik/go3d
float64/vec2/rect.go
Area
func (rect *Rect) Area() float64 { return (rect.Max[0] - rect.Min[0]) * (rect.Max[1] - rect.Min[1]) }
go
func (rect *Rect) Area() float64 { return (rect.Max[0] - rect.Min[0]) * (rect.Max[1] - rect.Min[1]) }
[ "func", "(", "rect", "*", "Rect", ")", "Area", "(", ")", "float64", "{", "return", "(", "rect", ".", "Max", "[", "0", "]", "-", "rect", ".", "Min", "[", "0", "]", ")", "*", "(", "rect", ".", "Max", "[", "1", "]", "-", "rect", ".", "Min", "[", "1", "]", ")", "\n", "}" ]
// Area calculates the area of the rectangle.
[ "Area", "calculates", "the", "area", "of", "the", "rectangle", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/vec2/rect.go#L46-L48
11,185
ungerik/go3d
float64/vec2/rect.go
Joined
func Joined(a, b *Rect) (rect Rect) { rect.Min = Min(&a.Min, &b.Min) rect.Max = Max(&a.Max, &b.Max) return rect }
go
func Joined(a, b *Rect) (rect Rect) { rect.Min = Min(&a.Min, &b.Min) rect.Max = Max(&a.Max, &b.Max) return rect }
[ "func", "Joined", "(", "a", ",", "b", "*", "Rect", ")", "(", "rect", "Rect", ")", "{", "rect", ".", "Min", "=", "Min", "(", "&", "a", ".", "Min", ",", "&", "b", ".", "Min", ")", "\n", "rect", ".", "Max", "=", "Max", "(", "&", "a", ".", "Max", ",", "&", "b", ".", "Max", ")", "\n", "return", "rect", "\n", "}" ]
// Joined returns the minimal rectangle containing both a and b.
[ "Joined", "returns", "the", "minimal", "rectangle", "containing", "both", "a", "and", "b", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/vec2/rect.go#L65-L69
11,186
ungerik/go3d
float64/quaternion/quaternion.go
FromAxisAngle
func FromAxisAngle(axis *vec3.T, angle float64) T { angle *= 0.5 sin := math.Sin(angle) q := T{axis[0] * sin, axis[1] * sin, axis[2] * sin, math.Cos(angle)} return q.Normalized() }
go
func FromAxisAngle(axis *vec3.T, angle float64) T { angle *= 0.5 sin := math.Sin(angle) q := T{axis[0] * sin, axis[1] * sin, axis[2] * sin, math.Cos(angle)} return q.Normalized() }
[ "func", "FromAxisAngle", "(", "axis", "*", "vec3", ".", "T", ",", "angle", "float64", ")", "T", "{", "angle", "*=", "0.5", "\n", "sin", ":=", "math", ".", "Sin", "(", "angle", ")", "\n", "q", ":=", "T", "{", "axis", "[", "0", "]", "*", "sin", ",", "axis", "[", "1", "]", "*", "sin", ",", "axis", "[", "2", "]", "*", "sin", ",", "math", ".", "Cos", "(", "angle", ")", "}", "\n", "return", "q", ".", "Normalized", "(", ")", "\n", "}" ]
// FromAxisAngle returns a quaternion representing a rotation around and axis.
[ "FromAxisAngle", "returns", "a", "quaternion", "representing", "a", "rotation", "around", "and", "axis", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/quaternion/quaternion.go#L25-L30
11,187
ungerik/go3d
float64/quaternion/quaternion.go
FromEulerAngles
func FromEulerAngles(yHead, xPitch, zRoll float64) T { qy := FromYAxisAngle(yHead) qx := FromXAxisAngle(xPitch) qz := FromZAxisAngle(zRoll) return Mul3(&qy, &qx, &qz) }
go
func FromEulerAngles(yHead, xPitch, zRoll float64) T { qy := FromYAxisAngle(yHead) qx := FromXAxisAngle(xPitch) qz := FromZAxisAngle(zRoll) return Mul3(&qy, &qx, &qz) }
[ "func", "FromEulerAngles", "(", "yHead", ",", "xPitch", ",", "zRoll", "float64", ")", "T", "{", "qy", ":=", "FromYAxisAngle", "(", "yHead", ")", "\n", "qx", ":=", "FromXAxisAngle", "(", "xPitch", ")", "\n", "qz", ":=", "FromZAxisAngle", "(", "zRoll", ")", "\n", "return", "Mul3", "(", "&", "qy", ",", "&", "qx", ",", "&", "qz", ")", "\n", "}" ]
// FromEulerAngles returns a quaternion representing Euler angle rotations.
[ "FromEulerAngles", "returns", "a", "quaternion", "representing", "Euler", "angle", "rotations", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/quaternion/quaternion.go#L51-L56
11,188
ungerik/go3d
float64/quaternion/quaternion.go
AxisAngle
func (quat *T) AxisAngle() (axis vec3.T, angle float64) { cos := quat[3] sin := math.Sqrt(1 - cos*cos) angle = math.Acos(cos) var ooSin float64 if math.Abs(sin) < 0.0005 { ooSin = 1 } else { ooSin = 1 / sin } axis[0] = quat[0] * ooSin axis[1] = quat[1] * ooSin axis[2] = quat[2] * ooSin return axis, angle }
go
func (quat *T) AxisAngle() (axis vec3.T, angle float64) { cos := quat[3] sin := math.Sqrt(1 - cos*cos) angle = math.Acos(cos) var ooSin float64 if math.Abs(sin) < 0.0005 { ooSin = 1 } else { ooSin = 1 / sin } axis[0] = quat[0] * ooSin axis[1] = quat[1] * ooSin axis[2] = quat[2] * ooSin return axis, angle }
[ "func", "(", "quat", "*", "T", ")", "AxisAngle", "(", ")", "(", "axis", "vec3", ".", "T", ",", "angle", "float64", ")", "{", "cos", ":=", "quat", "[", "3", "]", "\n", "sin", ":=", "math", ".", "Sqrt", "(", "1", "-", "cos", "*", "cos", ")", "\n", "angle", "=", "math", ".", "Acos", "(", "cos", ")", "\n\n", "var", "ooSin", "float64", "\n", "if", "math", ".", "Abs", "(", "sin", ")", "<", "0.0005", "{", "ooSin", "=", "1", "\n", "}", "else", "{", "ooSin", "=", "1", "/", "sin", "\n", "}", "\n", "axis", "[", "0", "]", "=", "quat", "[", "0", "]", "*", "ooSin", "\n", "axis", "[", "1", "]", "=", "quat", "[", "1", "]", "*", "ooSin", "\n", "axis", "[", "2", "]", "=", "quat", "[", "2", "]", "*", "ooSin", "\n\n", "return", "axis", ",", "angle", "\n", "}" ]
// AxisAngle extracts the rotation in form of an axis and a rotation angle.
[ "AxisAngle", "extracts", "the", "rotation", "in", "form", "of", "an", "axis", "and", "a", "rotation", "angle", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/quaternion/quaternion.go#L80-L96
11,189
ungerik/go3d
mat3/mat3.go
ScaleVec2
func (mat *T) ScaleVec2(s *vec2.T) *T { mat[0][0] *= s[0] mat[1][1] *= s[1] return mat }
go
func (mat *T) ScaleVec2(s *vec2.T) *T { mat[0][0] *= s[0] mat[1][1] *= s[1] return mat }
[ "func", "(", "mat", "*", "T", ")", "ScaleVec2", "(", "s", "*", "vec2", ".", "T", ")", "*", "T", "{", "mat", "[", "0", "]", "[", "0", "]", "*=", "s", "[", "0", "]", "\n", "mat", "[", "1", "]", "[", "1", "]", "*=", "s", "[", "1", "]", "\n", "return", "mat", "\n", "}" ]
// ScaleVec2 multiplies the 2D scaling diagonal of the matrix by s.
[ "ScaleVec2", "multiplies", "the", "2D", "scaling", "diagonal", "of", "the", "matrix", "by", "s", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat3/mat3.go#L122-L126
11,190
ungerik/go3d
mat3/mat3.go
SetTranslation
func (mat *T) SetTranslation(v *vec2.T) *T { mat[2][0] = v[0] mat[2][1] = v[1] return mat }
go
func (mat *T) SetTranslation(v *vec2.T) *T { mat[2][0] = v[0] mat[2][1] = v[1] return mat }
[ "func", "(", "mat", "*", "T", ")", "SetTranslation", "(", "v", "*", "vec2", ".", "T", ")", "*", "T", "{", "mat", "[", "2", "]", "[", "0", "]", "=", "v", "[", "0", "]", "\n", "mat", "[", "2", "]", "[", "1", "]", "=", "v", "[", "1", "]", "\n", "return", "mat", "\n", "}" ]
// SetTranslation sets the 2D translation elements of the matrix.
[ "SetTranslation", "sets", "the", "2D", "translation", "elements", "of", "the", "matrix", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat3/mat3.go#L129-L133
11,191
ungerik/go3d
mat3/mat3.go
Translate
func (mat *T) Translate(v *vec2.T) *T { mat[2][0] += v[0] mat[2][1] += v[1] return mat }
go
func (mat *T) Translate(v *vec2.T) *T { mat[2][0] += v[0] mat[2][1] += v[1] return mat }
[ "func", "(", "mat", "*", "T", ")", "Translate", "(", "v", "*", "vec2", ".", "T", ")", "*", "T", "{", "mat", "[", "2", "]", "[", "0", "]", "+=", "v", "[", "0", "]", "\n", "mat", "[", "2", "]", "[", "1", "]", "+=", "v", "[", "1", "]", "\n", "return", "mat", "\n", "}" ]
// Translate adds v to the 2D translation part of the matrix.
[ "Translate", "adds", "v", "to", "the", "2D", "translation", "part", "of", "the", "matrix", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat3/mat3.go#L136-L140
11,192
ungerik/go3d
mat3/mat3.go
TransformVec3
func (mat *T) TransformVec3(v *vec3.T) { // Use intermediate variables to not alter further computations. x := mat[0][0]*v[0] + mat[1][0]*v[1] + mat[2][0]*v[2] y := mat[0][1]*v[0] + mat[1][1]*v[1] + mat[2][1]*v[2] v[2] = mat[0][2]*v[0] + mat[1][2]*v[1] + mat[2][2]*v[2] v[0] = x v[1] = y }
go
func (mat *T) TransformVec3(v *vec3.T) { // Use intermediate variables to not alter further computations. x := mat[0][0]*v[0] + mat[1][0]*v[1] + mat[2][0]*v[2] y := mat[0][1]*v[0] + mat[1][1]*v[1] + mat[2][1]*v[2] v[2] = mat[0][2]*v[0] + mat[1][2]*v[1] + mat[2][2]*v[2] v[0] = x v[1] = y }
[ "func", "(", "mat", "*", "T", ")", "TransformVec3", "(", "v", "*", "vec3", ".", "T", ")", "{", "// Use intermediate variables to not alter further computations.", "x", ":=", "mat", "[", "0", "]", "[", "0", "]", "*", "v", "[", "0", "]", "+", "mat", "[", "1", "]", "[", "0", "]", "*", "v", "[", "1", "]", "+", "mat", "[", "2", "]", "[", "0", "]", "*", "v", "[", "2", "]", "\n", "y", ":=", "mat", "[", "0", "]", "[", "1", "]", "*", "v", "[", "0", "]", "+", "mat", "[", "1", "]", "[", "1", "]", "*", "v", "[", "1", "]", "+", "mat", "[", "2", "]", "[", "1", "]", "*", "v", "[", "2", "]", "\n", "v", "[", "2", "]", "=", "mat", "[", "0", "]", "[", "2", "]", "*", "v", "[", "0", "]", "+", "mat", "[", "1", "]", "[", "2", "]", "*", "v", "[", "1", "]", "+", "mat", "[", "2", "]", "[", "2", "]", "*", "v", "[", "2", "]", "\n", "v", "[", "0", "]", "=", "x", "\n", "v", "[", "1", "]", "=", "y", "\n", "}" ]
// TransformVec3 multiplies v with mat and saves the result in v.
[ "TransformVec3", "multiplies", "v", "with", "mat", "and", "saves", "the", "result", "in", "v", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat3/mat3.go#L187-L194
11,193
ungerik/go3d
mat3/mat3.go
Quaternion
func (mat *T) Quaternion() quaternion.T { tr := mat.Trace() s := math.Sqrt(tr + 1) w := s * 0.5 s = 0.5 / s q := quaternion.T{ (mat[1][2] - mat[2][1]) * s, (mat[2][0] - mat[0][2]) * s, (mat[0][1] - mat[1][0]) * s, w, } return q.Normalized() }
go
func (mat *T) Quaternion() quaternion.T { tr := mat.Trace() s := math.Sqrt(tr + 1) w := s * 0.5 s = 0.5 / s q := quaternion.T{ (mat[1][2] - mat[2][1]) * s, (mat[2][0] - mat[0][2]) * s, (mat[0][1] - mat[1][0]) * s, w, } return q.Normalized() }
[ "func", "(", "mat", "*", "T", ")", "Quaternion", "(", ")", "quaternion", ".", "T", "{", "tr", ":=", "mat", ".", "Trace", "(", ")", "\n\n", "s", ":=", "math", ".", "Sqrt", "(", "tr", "+", "1", ")", "\n", "w", ":=", "s", "*", "0.5", "\n", "s", "=", "0.5", "/", "s", "\n\n", "q", ":=", "quaternion", ".", "T", "{", "(", "mat", "[", "1", "]", "[", "2", "]", "-", "mat", "[", "2", "]", "[", "1", "]", ")", "*", "s", ",", "(", "mat", "[", "2", "]", "[", "0", "]", "-", "mat", "[", "0", "]", "[", "2", "]", ")", "*", "s", ",", "(", "mat", "[", "0", "]", "[", "1", "]", "-", "mat", "[", "1", "]", "[", "0", "]", ")", "*", "s", ",", "w", ",", "}", "\n", "return", "q", ".", "Normalized", "(", ")", "\n", "}" ]
// Quaternion extracts a quaternion from the rotation part of the matrix.
[ "Quaternion", "extracts", "a", "quaternion", "from", "the", "rotation", "part", "of", "the", "matrix", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat3/mat3.go#L197-L211
11,194
ungerik/go3d
mat3/mat3.go
AssignQuaternion
func (mat *T) AssignQuaternion(q *quaternion.T) *T { xx := q[0] * q[0] * 2 yy := q[1] * q[1] * 2 zz := q[2] * q[2] * 2 xy := q[0] * q[1] * 2 xz := q[0] * q[2] * 2 yz := q[1] * q[2] * 2 wx := q[3] * q[0] * 2 wy := q[3] * q[1] * 2 wz := q[3] * q[2] * 2 mat[0][0] = 1 - (yy + zz) mat[1][0] = xy - wz mat[2][0] = xz + wy mat[0][1] = xy + wz mat[1][1] = 1 - (xx + zz) mat[2][1] = yz - wx mat[0][2] = xz - wy mat[1][2] = yz + wx mat[2][2] = 1 - (xx + yy) return mat }
go
func (mat *T) AssignQuaternion(q *quaternion.T) *T { xx := q[0] * q[0] * 2 yy := q[1] * q[1] * 2 zz := q[2] * q[2] * 2 xy := q[0] * q[1] * 2 xz := q[0] * q[2] * 2 yz := q[1] * q[2] * 2 wx := q[3] * q[0] * 2 wy := q[3] * q[1] * 2 wz := q[3] * q[2] * 2 mat[0][0] = 1 - (yy + zz) mat[1][0] = xy - wz mat[2][0] = xz + wy mat[0][1] = xy + wz mat[1][1] = 1 - (xx + zz) mat[2][1] = yz - wx mat[0][2] = xz - wy mat[1][2] = yz + wx mat[2][2] = 1 - (xx + yy) return mat }
[ "func", "(", "mat", "*", "T", ")", "AssignQuaternion", "(", "q", "*", "quaternion", ".", "T", ")", "*", "T", "{", "xx", ":=", "q", "[", "0", "]", "*", "q", "[", "0", "]", "*", "2", "\n", "yy", ":=", "q", "[", "1", "]", "*", "q", "[", "1", "]", "*", "2", "\n", "zz", ":=", "q", "[", "2", "]", "*", "q", "[", "2", "]", "*", "2", "\n", "xy", ":=", "q", "[", "0", "]", "*", "q", "[", "1", "]", "*", "2", "\n", "xz", ":=", "q", "[", "0", "]", "*", "q", "[", "2", "]", "*", "2", "\n", "yz", ":=", "q", "[", "1", "]", "*", "q", "[", "2", "]", "*", "2", "\n", "wx", ":=", "q", "[", "3", "]", "*", "q", "[", "0", "]", "*", "2", "\n", "wy", ":=", "q", "[", "3", "]", "*", "q", "[", "1", "]", "*", "2", "\n", "wz", ":=", "q", "[", "3", "]", "*", "q", "[", "2", "]", "*", "2", "\n\n", "mat", "[", "0", "]", "[", "0", "]", "=", "1", "-", "(", "yy", "+", "zz", ")", "\n", "mat", "[", "1", "]", "[", "0", "]", "=", "xy", "-", "wz", "\n", "mat", "[", "2", "]", "[", "0", "]", "=", "xz", "+", "wy", "\n\n", "mat", "[", "0", "]", "[", "1", "]", "=", "xy", "+", "wz", "\n", "mat", "[", "1", "]", "[", "1", "]", "=", "1", "-", "(", "xx", "+", "zz", ")", "\n", "mat", "[", "2", "]", "[", "1", "]", "=", "yz", "-", "wx", "\n\n", "mat", "[", "0", "]", "[", "2", "]", "=", "xz", "-", "wy", "\n", "mat", "[", "1", "]", "[", "2", "]", "=", "yz", "+", "wx", "\n", "mat", "[", "2", "]", "[", "2", "]", "=", "1", "-", "(", "xx", "+", "yy", ")", "\n\n", "return", "mat", "\n", "}" ]
// AssignQuaternion assigns a quaternion to the rotations part of the matrix and sets the other elements to their ident value.
[ "AssignQuaternion", "assigns", "a", "quaternion", "to", "the", "rotations", "part", "of", "the", "matrix", "and", "sets", "the", "other", "elements", "to", "their", "ident", "value", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat3/mat3.go#L214-L238
11,195
ungerik/go3d
mat3/mat3.go
AssignCoordinateSystem
func (mat *T) AssignCoordinateSystem(x, y, z *vec3.T) *T { mat[0][0] = x[0] mat[1][0] = x[1] mat[2][0] = x[2] mat[0][1] = y[0] mat[1][1] = y[1] mat[2][1] = y[2] mat[0][2] = z[0] mat[1][2] = z[1] mat[2][2] = z[2] return mat }
go
func (mat *T) AssignCoordinateSystem(x, y, z *vec3.T) *T { mat[0][0] = x[0] mat[1][0] = x[1] mat[2][0] = x[2] mat[0][1] = y[0] mat[1][1] = y[1] mat[2][1] = y[2] mat[0][2] = z[0] mat[1][2] = z[1] mat[2][2] = z[2] return mat }
[ "func", "(", "mat", "*", "T", ")", "AssignCoordinateSystem", "(", "x", ",", "y", ",", "z", "*", "vec3", ".", "T", ")", "*", "T", "{", "mat", "[", "0", "]", "[", "0", "]", "=", "x", "[", "0", "]", "\n", "mat", "[", "1", "]", "[", "0", "]", "=", "x", "[", "1", "]", "\n", "mat", "[", "2", "]", "[", "0", "]", "=", "x", "[", "2", "]", "\n\n", "mat", "[", "0", "]", "[", "1", "]", "=", "y", "[", "0", "]", "\n", "mat", "[", "1", "]", "[", "1", "]", "=", "y", "[", "1", "]", "\n", "mat", "[", "2", "]", "[", "1", "]", "=", "y", "[", "2", "]", "\n\n", "mat", "[", "0", "]", "[", "2", "]", "=", "z", "[", "0", "]", "\n", "mat", "[", "1", "]", "[", "2", "]", "=", "z", "[", "1", "]", "\n", "mat", "[", "2", "]", "[", "2", "]", "=", "z", "[", "2", "]", "\n\n", "return", "mat", "\n", "}" ]
// AssignCoordinateSystem assigns the rotation of a orthogonal coordinates system to the rotation part of the matrix and sets the remaining elements to their ident value.
[ "AssignCoordinateSystem", "assigns", "the", "rotation", "of", "a", "orthogonal", "coordinates", "system", "to", "the", "rotation", "part", "of", "the", "matrix", "and", "sets", "the", "remaining", "elements", "to", "their", "ident", "value", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat3/mat3.go#L301-L315
11,196
ungerik/go3d
float64/vec2/vec2.go
Scale
func (vec *T) Scale(f float64) *T { vec[0] *= f vec[1] *= f return vec }
go
func (vec *T) Scale(f float64) *T { vec[0] *= f vec[1] *= f return vec }
[ "func", "(", "vec", "*", "T", ")", "Scale", "(", "f", "float64", ")", "*", "T", "{", "vec", "[", "0", "]", "*=", "f", "\n", "vec", "[", "1", "]", "*=", "f", "\n", "return", "vec", "\n", "}" ]
// Scale multiplies all element of the vector by f and returns vec.
[ "Scale", "multiplies", "all", "element", "of", "the", "vector", "by", "f", "and", "returns", "vec", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/vec2/vec2.go#L90-L94
11,197
ungerik/go3d
float64/vec2/vec2.go
Rotated
func (vec *T) Rotated(angle float64) T { sinus := math.Sin(angle) cosinus := math.Cos(angle) return T{ vec[0]*cosinus - vec[1]*sinus, vec[0]*sinus + vec[1]*cosinus, } }
go
func (vec *T) Rotated(angle float64) T { sinus := math.Sin(angle) cosinus := math.Cos(angle) return T{ vec[0]*cosinus - vec[1]*sinus, vec[0]*sinus + vec[1]*cosinus, } }
[ "func", "(", "vec", "*", "T", ")", "Rotated", "(", "angle", "float64", ")", "T", "{", "sinus", ":=", "math", ".", "Sin", "(", "angle", ")", "\n", "cosinus", ":=", "math", ".", "Cos", "(", "angle", ")", "\n", "return", "T", "{", "vec", "[", "0", "]", "*", "cosinus", "-", "vec", "[", "1", "]", "*", "sinus", ",", "vec", "[", "0", "]", "*", "sinus", "+", "vec", "[", "1", "]", "*", "cosinus", ",", "}", "\n", "}" ]
// Rotated returns a counter-clockwise rotated copy of the vector.
[ "Rotated", "returns", "a", "counter", "-", "clockwise", "rotated", "copy", "of", "the", "vector", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/vec2/vec2.go#L157-L164
11,198
ungerik/go3d
float64/mat3/mat3.go
AssignEulerRotation
func (mat *T) AssignEulerRotation(yHead, xPitch, zRoll float64) *T { sinH := math.Sin(yHead) cosH := math.Cos(yHead) sinP := math.Sin(xPitch) cosP := math.Cos(xPitch) sinR := math.Sin(zRoll) cosR := math.Cos(zRoll) mat[0][0] = cosR*cosH - sinR*sinP*sinH mat[1][0] = -sinR * cosP mat[2][0] = cosR*sinH + sinR*sinP*cosH mat[0][1] = sinR*cosH + cosR*sinP*sinH mat[1][1] = cosR * cosP mat[2][1] = sinR*sinH - cosR*sinP*cosH mat[0][2] = -cosP * sinH mat[1][2] = sinP mat[2][2] = cosP * cosH return mat }
go
func (mat *T) AssignEulerRotation(yHead, xPitch, zRoll float64) *T { sinH := math.Sin(yHead) cosH := math.Cos(yHead) sinP := math.Sin(xPitch) cosP := math.Cos(xPitch) sinR := math.Sin(zRoll) cosR := math.Cos(zRoll) mat[0][0] = cosR*cosH - sinR*sinP*sinH mat[1][0] = -sinR * cosP mat[2][0] = cosR*sinH + sinR*sinP*cosH mat[0][1] = sinR*cosH + cosR*sinP*sinH mat[1][1] = cosR * cosP mat[2][1] = sinR*sinH - cosR*sinP*cosH mat[0][2] = -cosP * sinH mat[1][2] = sinP mat[2][2] = cosP * cosH return mat }
[ "func", "(", "mat", "*", "T", ")", "AssignEulerRotation", "(", "yHead", ",", "xPitch", ",", "zRoll", "float64", ")", "*", "T", "{", "sinH", ":=", "math", ".", "Sin", "(", "yHead", ")", "\n", "cosH", ":=", "math", ".", "Cos", "(", "yHead", ")", "\n", "sinP", ":=", "math", ".", "Sin", "(", "xPitch", ")", "\n", "cosP", ":=", "math", ".", "Cos", "(", "xPitch", ")", "\n", "sinR", ":=", "math", ".", "Sin", "(", "zRoll", ")", "\n", "cosR", ":=", "math", ".", "Cos", "(", "zRoll", ")", "\n\n", "mat", "[", "0", "]", "[", "0", "]", "=", "cosR", "*", "cosH", "-", "sinR", "*", "sinP", "*", "sinH", "\n", "mat", "[", "1", "]", "[", "0", "]", "=", "-", "sinR", "*", "cosP", "\n", "mat", "[", "2", "]", "[", "0", "]", "=", "cosR", "*", "sinH", "+", "sinR", "*", "sinP", "*", "cosH", "\n\n", "mat", "[", "0", "]", "[", "1", "]", "=", "sinR", "*", "cosH", "+", "cosR", "*", "sinP", "*", "sinH", "\n", "mat", "[", "1", "]", "[", "1", "]", "=", "cosR", "*", "cosP", "\n", "mat", "[", "2", "]", "[", "1", "]", "=", "sinR", "*", "sinH", "-", "cosR", "*", "sinP", "*", "cosH", "\n\n", "mat", "[", "0", "]", "[", "2", "]", "=", "-", "cosP", "*", "sinH", "\n", "mat", "[", "1", "]", "[", "2", "]", "=", "sinP", "\n", "mat", "[", "2", "]", "[", "2", "]", "=", "cosP", "*", "cosH", "\n\n", "return", "mat", "\n", "}" ]
// AssignEulerRotation assigns Euler angle rotations to the rotation part of the matrix and sets the remaining elements to their ident value.
[ "AssignEulerRotation", "assigns", "Euler", "angle", "rotations", "to", "the", "rotation", "part", "of", "the", "matrix", "and", "sets", "the", "remaining", "elements", "to", "their", "ident", "value", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/mat3/mat3.go#L318-L339
11,199
ungerik/go3d
float64/mat3/mat3.go
ExtractEulerAngles
func (mat *T) ExtractEulerAngles() (yHead, xPitch, zRoll float64) { xPitch = math.Asin(mat[1][2]) f12 := math.Abs(mat[1][2]) if f12 > (1.0-0.0001) && f12 < (1.0+0.0001) { // f12 == 1.0 yHead = 0.0 zRoll = math.Atan2(mat[0][1], mat[0][0]) } else { yHead = math.Atan2(-mat[0][2], mat[2][2]) zRoll = math.Atan2(-mat[1][0], mat[1][1]) } return yHead, xPitch, zRoll }
go
func (mat *T) ExtractEulerAngles() (yHead, xPitch, zRoll float64) { xPitch = math.Asin(mat[1][2]) f12 := math.Abs(mat[1][2]) if f12 > (1.0-0.0001) && f12 < (1.0+0.0001) { // f12 == 1.0 yHead = 0.0 zRoll = math.Atan2(mat[0][1], mat[0][0]) } else { yHead = math.Atan2(-mat[0][2], mat[2][2]) zRoll = math.Atan2(-mat[1][0], mat[1][1]) } return yHead, xPitch, zRoll }
[ "func", "(", "mat", "*", "T", ")", "ExtractEulerAngles", "(", ")", "(", "yHead", ",", "xPitch", ",", "zRoll", "float64", ")", "{", "xPitch", "=", "math", ".", "Asin", "(", "mat", "[", "1", "]", "[", "2", "]", ")", "\n", "f12", ":=", "math", ".", "Abs", "(", "mat", "[", "1", "]", "[", "2", "]", ")", "\n", "if", "f12", ">", "(", "1.0", "-", "0.0001", ")", "&&", "f12", "<", "(", "1.0", "+", "0.0001", ")", "{", "// f12 == 1.0", "yHead", "=", "0.0", "\n", "zRoll", "=", "math", ".", "Atan2", "(", "mat", "[", "0", "]", "[", "1", "]", ",", "mat", "[", "0", "]", "[", "0", "]", ")", "\n", "}", "else", "{", "yHead", "=", "math", ".", "Atan2", "(", "-", "mat", "[", "0", "]", "[", "2", "]", ",", "mat", "[", "2", "]", "[", "2", "]", ")", "\n", "zRoll", "=", "math", ".", "Atan2", "(", "-", "mat", "[", "1", "]", "[", "0", "]", ",", "mat", "[", "1", "]", "[", "1", "]", ")", "\n", "}", "\n", "return", "yHead", ",", "xPitch", ",", "zRoll", "\n", "}" ]
// ExtractEulerAngles extracts the rotation part of the matrix as Euler angle rotation values.
[ "ExtractEulerAngles", "extracts", "the", "rotation", "part", "of", "the", "matrix", "as", "Euler", "angle", "rotation", "values", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/mat3/mat3.go#L342-L353