Tizen_4.0 base
[platform/upstream/docker-engine.git] / vendor / golang.org / x / oauth2 / internal / oauth2.go
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package internal contains support packages for oauth2 package.
6 package internal
7
8 import (
9         "bufio"
10         "crypto/rsa"
11         "crypto/x509"
12         "encoding/pem"
13         "errors"
14         "fmt"
15         "io"
16         "strings"
17 )
18
19 // ParseKey converts the binary contents of a private key file
20 // to an *rsa.PrivateKey. It detects whether the private key is in a
21 // PEM container or not. If so, it extracts the the private key
22 // from PEM container before conversion. It only supports PEM
23 // containers with no passphrase.
24 func ParseKey(key []byte) (*rsa.PrivateKey, error) {
25         block, _ := pem.Decode(key)
26         if block != nil {
27                 key = block.Bytes
28         }
29         parsedKey, err := x509.ParsePKCS8PrivateKey(key)
30         if err != nil {
31                 parsedKey, err = x509.ParsePKCS1PrivateKey(key)
32                 if err != nil {
33                         return nil, fmt.Errorf("private key should be a PEM or plain PKSC1 or PKCS8; parse error: %v", err)
34                 }
35         }
36         parsed, ok := parsedKey.(*rsa.PrivateKey)
37         if !ok {
38                 return nil, errors.New("private key is invalid")
39         }
40         return parsed, nil
41 }
42
43 func ParseINI(ini io.Reader) (map[string]map[string]string, error) {
44         result := map[string]map[string]string{
45                 "": map[string]string{}, // root section
46         }
47         scanner := bufio.NewScanner(ini)
48         currentSection := ""
49         for scanner.Scan() {
50                 line := strings.TrimSpace(scanner.Text())
51                 if strings.HasPrefix(line, ";") {
52                         // comment.
53                         continue
54                 }
55                 if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
56                         currentSection = strings.TrimSpace(line[1 : len(line)-1])
57                         result[currentSection] = map[string]string{}
58                         continue
59                 }
60                 parts := strings.SplitN(line, "=", 2)
61                 if len(parts) == 2 && parts[0] != "" {
62                         result[currentSection][strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
63                 }
64         }
65         if err := scanner.Err(); err != nil {
66                 return nil, fmt.Errorf("error scanning ini: %v", err)
67         }
68         return result, nil
69 }
70
71 func CondVal(v string) []string {
72         if v == "" {
73                 return nil
74         }
75         return []string{v}
76 }