github.com/olivere/camlistore@v0.0.0-20140121221811-1b7ac2da0199/cmd/camput/init.go (about)

     1  /*
     2  Copyright 2011 Google Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package main
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"flag"
    23  	"fmt"
    24  	"log"
    25  	"os"
    26  	"os/exec"
    27  
    28  	"camlistore.org/pkg/blob"
    29  	"camlistore.org/pkg/cmdmain"
    30  	"camlistore.org/pkg/jsonsign"
    31  	"camlistore.org/pkg/osutil"
    32  	"camlistore.org/pkg/types/clientconfig"
    33  )
    34  
    35  type initCmd struct {
    36  	newKey   bool
    37  	gpgkey   string
    38  	noconfig bool
    39  }
    40  
    41  func init() {
    42  	cmdmain.RegisterCommand("init", func(flags *flag.FlagSet) cmdmain.CommandRunner {
    43  		cmd := new(initCmd)
    44  		flags.BoolVar(&cmd.newKey, "newkey", false, "Automatically generate a new identity in a new secret ring.")
    45  		flags.StringVar(&cmd.gpgkey, "gpgkey", "", "GPG key to use for signing (overrides $GPGKEY environment)")
    46  		flags.BoolVar(&cmd.noconfig, "noconfig", false, "Stop after creating the public key blob, and do not try and create a config file.")
    47  		return cmd
    48  	})
    49  }
    50  
    51  func (c *initCmd) Describe() string {
    52  	return "Initialize the camput configuration file. With no option, it tries to use the GPG key found in the default identity secret ring."
    53  }
    54  
    55  func (c *initCmd) Usage() {
    56  	fmt.Fprintf(cmdmain.Stderr, "Usage: camput init [opts]")
    57  }
    58  
    59  func (c *initCmd) Examples() []string {
    60  	return []string{
    61  		"",
    62  		"--gpgkey=XXXXX",
    63  		"--newkey Creates a new identity",
    64  	}
    65  }
    66  
    67  // keyId returns the current keyId. It checks, in this order,
    68  // the --gpgkey flag, the GPGKEY env var, and the default
    69  // identity secret ring.
    70  func (c *initCmd) keyId(secRing string) (string, error) {
    71  	if k := c.gpgkey; k != "" {
    72  		return k, nil
    73  	}
    74  	if k := os.Getenv("GPGKEY"); k != "" {
    75  		return k, nil
    76  	}
    77  
    78  	k, err := jsonsign.KeyIdFromRing(secRing)
    79  	if err != nil {
    80  		log.Printf("No suitable gpg key was found in %v: %v", secRing, err)
    81  	} else {
    82  		if k != "" {
    83  			log.Printf("Re-using identity with keyId %q found in file %s", k, secRing)
    84  			return k, nil
    85  		}
    86  	}
    87  
    88  	// TODO: run and parse gpg --list-secret-keys and see if there's just one and suggest that?  Or show
    89  	// a list of them?
    90  	return "", errors.New("Initialization requires your public GPG key.\nYou can set --gpgkey=<pubid> or set $GPGKEY in your environment. Run gpg --list-secret-keys to find their key IDs.\nOr you can create a new secret ring and key with 'camput init --newkey'.")
    91  }
    92  
    93  func (c *initCmd) getPublicKeyArmoredFromFile(secretRingFileName, keyId string) (b []byte, err error) {
    94  	entity, err := jsonsign.EntityFromSecring(keyId, secretRingFileName)
    95  	if err == nil {
    96  		pubArmor, err := jsonsign.ArmoredPublicKey(entity)
    97  		if err == nil {
    98  			return []byte(pubArmor), nil
    99  		}
   100  	}
   101  	b, err = exec.Command("gpg", "--export", "--armor", keyId).Output()
   102  	if err != nil {
   103  		return nil, fmt.Errorf("Error running gpg to export public key %q: %v", keyId, err)
   104  	}
   105  	if len(b) == 0 {
   106  		return nil, fmt.Errorf("gpg export of public key %q was empty.", keyId)
   107  	}
   108  	return b, nil
   109  }
   110  
   111  func (c *initCmd) getPublicKeyArmored(keyId string) (b []byte, err error) {
   112  	file := osutil.IdentitySecretRing()
   113  	b, err = c.getPublicKeyArmoredFromFile(file, keyId)
   114  	if err != nil {
   115  		return nil, fmt.Errorf("failed to export armored public key ID %q from %v: %v", keyId, file, err)
   116  	}
   117  	return b, nil
   118  }
   119  
   120  func (c *initCmd) RunCommand(args []string) error {
   121  	if len(args) > 0 {
   122  		return cmdmain.ErrUsage
   123  	}
   124  
   125  	if c.newKey && c.gpgkey != "" {
   126  		log.Fatal("--newkey and --gpgkey are mutually exclusive")
   127  	}
   128  
   129  	var keyId string
   130  	var err error
   131  	secRing := osutil.IdentitySecretRing()
   132  	if c.newKey {
   133  		keyId, err = jsonsign.GenerateNewSecRing(secRing)
   134  		if err != nil {
   135  			return err
   136  		}
   137  	} else {
   138  		keyId, err = c.keyId(secRing)
   139  		if err != nil {
   140  			return err
   141  		}
   142  	}
   143  
   144  	pubArmor, err := c.getPublicKeyArmored(keyId)
   145  	if err != nil {
   146  		return err
   147  	}
   148  
   149  	bref := blob.SHA1FromString(string(pubArmor))
   150  
   151  	log.Printf("Your Camlistore identity (your GPG public key's blobref) is: %s", bref.String())
   152  
   153  	if c.noconfig {
   154  		return nil
   155  	}
   156  
   157  	configFilePath := osutil.UserClientConfigPath()
   158  	_, err = os.Stat(configFilePath)
   159  	if err == nil {
   160  		log.Fatalf("Config file %q already exists; quitting without touching it.", configFilePath)
   161  	}
   162  
   163  	if f, err := os.OpenFile(configFilePath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600); err == nil {
   164  		defer f.Close()
   165  		m := &clientconfig.Config{
   166  			Servers: map[string]*clientconfig.Server{
   167  				"localhost": {
   168  					Server:    "http://localhost:3179",
   169  					IsDefault: true,
   170  					Auth:      "localhost",
   171  				},
   172  			},
   173  			Identity:     keyId,
   174  			IgnoredFiles: []string{".DS_Store"},
   175  		}
   176  
   177  		jsonBytes, err := json.MarshalIndent(m, "", "  ")
   178  		if err != nil {
   179  			log.Fatalf("JSON serialization error: %v", err)
   180  		}
   181  		_, err = f.Write(jsonBytes)
   182  		if err != nil {
   183  			log.Fatalf("Error writing to %q: %v", configFilePath, err)
   184  		}
   185  		log.Printf("Wrote %q; modify as necessary.", configFilePath)
   186  	}
   187  	return nil
   188  }