Example #1
0
func getConfigDir() string {
	d, e := homedir.Dir()
	if e != nil {
		logrus.Fatalf("config.go: failed to get home dir: error=%v", e)
	}
	return path.Join(d, ".otsimo")
}
Example #2
0
func TestDefaultKeys(t *testing.T) {
	util.AppFs = afero.NewMemMapFs()

	// Don't pull in keys from the host OS. Setting this environment variable
	// is safe because it won't affect the parent shell.
	os.Setenv("SSH_AUTH_SOCK", "")

	dir, err := homedir.Dir()
	if err != nil {
		t.Errorf("Failed to get homedir: %q", err.Error())
		return
	}

	sshDir := filepath.Join(dir, ".ssh")
	if err := util.AppFs.MkdirAll(sshDir, 0600); err != nil {
		t.Errorf("Failed to create SSH directory: %q", err.Error())
		return
	}

	for _, key := range []string{"id_rsa", "id_dsa", "ignored"} {
		if err := writeRandomKey(filepath.Join(sshDir, key)); err != nil {
			t.Errorf("Failed to write key: %q", err.Error())
			return
		}
	}

	signers := defaultSigners()
	if len(signers) != 2 {
		t.Errorf("Expected two default signers, but got %v", signers)
	}
}
Example #3
0
func parseConfig() *viper.Viper {
	if verbose {
		logrus.SetLevel(logrus.DebugLevel)
		logrus.SetOutput(os.Stderr)
	}

	// Get home directory for current user
	homeDir, err := homedir.Dir()
	if err != nil {
		fatalf("Cannot get current user home directory: %v", err)
	}
	if homeDir == "" {
		fatalf("Cannot get current user home directory")
	}

	// By default our trust directory (where keys are stored) is in ~/.notary/
	mainViper.SetDefault("trust_dir", filepath.Join(homeDir, filepath.Dir(configDir)))

	// If there was a commandline configFile set, we parse that.
	// If there wasn't we attempt to find it on the default location ~/.notary/config
	if configFile != "" {
		configFileExt = strings.TrimPrefix(filepath.Ext(configFile), ".")
		configFileName = strings.TrimSuffix(filepath.Base(configFile), filepath.Ext(configFile))
		configPath = filepath.Dir(configFile)
	} else {
		configPath = filepath.Join(homeDir, filepath.Dir(configDir))
	}

	// Setup the configuration details into viper
	mainViper.SetConfigName(configFileName)
	mainViper.SetConfigType(configFileExt)
	mainViper.AddConfigPath(configPath)

	// Find and read the config file
	err = mainViper.ReadInConfig()
	if err != nil {
		logrus.Debugf("Configuration file not found, using defaults")
		// If we were passed in a configFile via -c, bail if it doesn't exist,
		// otherwise ignore it: we can use the defaults
		if configFile != "" || !os.IsNotExist(err) {
			fatalf("error opening config file %v", err)
		}
	}

	// At this point we either have the default value or the one set by the config.
	// Either way, the command-line flag has precedence and overwrites the value
	if trustDir != "" {
		mainViper.Set("trust_dir", trustDir)
	}

	// Expands all the possible ~/ that have been given, either through -d or config
	// If there is no error, use it, if not, attempt to use whatever the user gave us
	expandedTrustDir, err := homedir.Expand(mainViper.GetString("trust_dir"))
	if err == nil {
		mainViper.Set("trust_dir", expandedTrustDir)
	}
	logrus.Debugf("Using the following trust directory: %s", mainViper.GetString("trust_dir"))

	return mainViper
}
Example #4
0
// Opens/creates a config file for the specified appName.
// The path to config file is ~/.config/appName/config.ini.
func New(appName string) (g *GlobalConf, err error) {
	hmdr, err := homedir.Dir()
	if err != nil {
		return
	}

	// Create config file's directory.
	dirPath := path.Join(hmdr, ".config", appName)
	if err = os.MkdirAll(dirPath, 0755); err != nil {
		return
	}
	// Touch a config file if it doesn't exit.
	filePath := path.Join(dirPath, defaultConfigFileName)
	if _, err = os.Stat(filePath); err != nil {
		if !os.IsNotExist(err) {
			return
		}
		// create file
		if err = ioutil.WriteFile(filePath, []byte{}, 0644); err != nil {
			return
		}
	}
	opts := Options{Filename: filePath}
	return NewWithOptions(&opts)
}
Example #5
0
func GetLocalShell() (*sh.Shell, error) {
	apiAddress := os.Getenv("IPFS_API")
	if apiAddress != "" {
		// IPFS_API takes priority.
		return sh.NewShell(apiAddress), nil
	}

	apiFilePath := ""
	ipath := os.Getenv("IPFS_PATH")
	if ipath != "" {
		apiFilePath = filepath.Join(ipath, "api")
	}
	home, err := hd.Dir() // Get home directory
	if err == nil {
		apiFilePath = filepath.Join(home, ".ipfs", "api")
	}

	// Read the file (hopefully) containing the location of an ipfs daemon
	apiFileContent, err := ioutil.ReadFile(apiFilePath)
	if err != nil {
		return nil, err
	}

	multiAddr := strings.Trim(string(apiFileContent), "\n\t ")
	apiAddress, err = multiaddrToNormal(multiAddr)
	if err != nil {
		return nil, err
	}
	return sh.NewShell(apiAddress), nil
}
Example #6
0
func getHomeDir() string {
	home, err := home.Dir()
	if err != nil {
		log.WithField("err", err).Fatal("failed to deterine a home directory")
	}
	return home
}
Example #7
0
func init() {
	currentHomeDir, err := homedir.Dir()
	if err != nil {
		os.Stderr.WriteString(fmt.Sprintf("Cannot fetch your home directory: %v", err))
		os.Exit(1)
	}
	homeDir = currentHomeDir
}
Example #8
0
File: api.go Project: NetSys/quilt
func vagrantDir() (string, error) {
	dir, err := homedir.Dir()
	if err != nil {
		return "", err
	}
	vagrantDir := dir + "/.vagrant/"
	return vagrantDir, nil
}
Example #9
0
func TestGetBucketsDirPath(t *testing.T) {
	actual, err := getBucketsDirPath()
	if err != nil {
		t.Errorf("occurred error when get bucket directory path: %v", err)
	}

	home, _ := homedir.Dir()
	expected := filepath.Join(home, ".honoka", "buckets")
	if actual != expected {
		t.Errorf("actual does not match expected. actual: %s , expected: %s", actual, expected)
	}
}
Example #10
0
// HomeDir is the home directory for the user. Light wrapper on the homedir lib.
func HomeDir() (string, error) {
	homish, err := homedir.Dir()
	if err != nil {
		return "", fmt.Errorf("Unable to acquire home directory: %v", err)
	}

	home, err := homedir.Expand(homish)
	if err != nil {
		return "", fmt.Errorf("Unable to expand home directory: %v", err)
	}

	return home, nil
}
Example #11
0
func parseConfig() {
	if verbose {
		logrus.SetLevel(logrus.DebugLevel)
		logrus.SetOutput(os.Stderr)
	}

	if trustDir == "" {
		// Get home directory for current user
		homeDir, err := homedir.Dir()
		if err != nil {
			fatalf("cannot get current user home directory: %v", err)
		}
		if homeDir == "" {
			fatalf("cannot get current user home directory")
		}
		trustDir = filepath.Join(homeDir, filepath.Dir(configDir))

		logrus.Debugf("no trust directory provided, using default: %s", trustDir)
	} else {
		logrus.Debugf("trust directory provided: %s", trustDir)
	}

	// If there was a commandline configFile set, we parse that.
	// If there wasn't we attempt to find it on the default location ~/.notary/config
	if configFile != "" {
		configFileExt = strings.TrimPrefix(filepath.Ext(configFile), ".")
		configFileName = strings.TrimSuffix(filepath.Base(configFile), filepath.Ext(configFile))
		configPath = filepath.Dir(configFile)
	} else {
		configPath = trustDir
	}

	// Setup the configuration details into viper
	mainViper.SetConfigName(configFileName)
	mainViper.SetConfigType(configFileExt)
	mainViper.AddConfigPath(configPath)

	// Find and read the config file
	err := mainViper.ReadInConfig()
	if err != nil {
		logrus.Debugf("configuration file not found, using defaults")
		// Ignore if the configuration file doesn't exist, we can use the defaults
		if !os.IsNotExist(err) {
			fatalf("fatal error config file: %v", err)
		}
	}
}
Example #12
0
func init() {
	stdcli.RegisterCommand(cli.Command{
		Name:        "login",
		Description: "log into your convox rack",
		Usage:       "[hostname]",
		Action:      cmdLogin,
		Flags: []cli.Flag{
			cli.StringFlag{
				Name:  "password, p",
				Usage: "Password to use for authentication. If not specified, prompt for password.",
			},
		},
	})

	home, err := homedir.Dir()

	if err != nil {
		stdcli.Error(err)
		return
	}

	ConfigRoot = filepath.Join(home, ".convox")

	if root := os.Getenv("CONVOX_CONFIG"); root != "" {
		ConfigRoot = root
	}

	stat, err := os.Stat(ConfigRoot)

	if err != nil && !os.IsNotExist(err) {
		stdcli.Error(err)
		return
	}

	if stat != nil && !stat.IsDir() {
		err := upgradeConfig()

		if err != nil {
			stdcli.Error(err)
			return
		}
	}
}
Example #13
0
func saveRuntimeInfo() {

	homeDir, _ := home.Dir()
	parentPath := path.Join(homeDir, ".logk")

	_, err := os.Stat(parentPath)
	if err != nil {
		os.Mkdir(parentPath, 0777)
	}

	file, err := os.OpenFile(path.Join(parentPath, "runtimeinfo"), os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	for k, v := range runtimeInfo {
		file.Write([]byte(fmt.Sprintf("%s %d\n", k, v)))
	}
}
Example #14
0
func CompatLoad() (*CompatConfigFile, error) {
	dockerCfg := cliconfig.NewConfigFile(filepath.Join(cliconfig.ConfigDir(), cliconfig.ConfigFileName))
	configFile := CompatConfigFile{
		dockerCfg,
		dockerCfg.Filename(),
	}

	// Try .docker/config.json first
	if _, err := os.Stat(configFile.filename); err == nil {
		file, err := os.Open(configFile.filename)
		if err != nil {
			return &configFile, err
		}
		defer file.Close()
		err = configFile.LoadFromReader(file)
		return &configFile, err
	} else if !os.IsNotExist(err) {
		return &configFile, err
	}

	// Try the old .dockercfg
	homeDir, _ := homedir.Dir()
	configFile.filename = filepath.Join(homeDir, ".dockercfg")
	if _, err := os.Stat(configFile.filename); err != nil {
		return &configFile, nil //missing file is not an error
	}
	file, err := os.Open(configFile.filename)
	if err != nil {
		return &configFile, err
	}
	defer file.Close()
	err = configFile.LegacyLoadFromReader(file)
	if err != nil {
		return &configFile, err
	}

	return &configFile, nil
}
Example #15
0
func recoverRuntimeInfo() {
	homeDir, _ := home.Dir()
	file, err := os.OpenFile(path.Join(homeDir, ".logk", "runtimeinfo"), os.O_RDONLY, 0666)
	if err != nil {
		return
	}

	defer file.Close()
	buf := bufio.NewReader(file)

	for {
		line, err := buf.ReadString('\n')

		if err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}

		var f string
		var p int64
		fmt.Sscanf(line, "%s %d", &f, &p)

		stat, err := os.Stat(f)

		if err != nil {
			p = int64(0)
		} else {
			if stat.Size() < p {
				p = 0
			}
		}

		runtimeInfo[f] = p
	}
}
Example #16
0
func newDockerClient(host string) (*docker.Client, error) {
	var err error
	var newClient *docker.Client
	dockerCertPath := os.Getenv("DOCKER_CERT_PATH")

	homeDir, _ := homedir.Dir()
	dockerConfigDir := path.Join(homeDir, ".docker")

	_, err = os.Stat(path.Join(dockerConfigDir, "cert.pem"))
	certExists := err == nil

	_, err = os.Stat(path.Join(dockerConfigDir, "ca.pem"))
	caExists := err == nil

	_, err = os.Stat(path.Join(dockerConfigDir, "key.pem"))
	keyExists := err == nil

	if dockerCertPath == "" && certExists && caExists && keyExists {
		dockerCertPath = dockerConfigDir
	}

	if dockerCertPath != "" {
		cert := path.Join(dockerCertPath, "cert.pem")
		key := path.Join(dockerCertPath, "key.pem")
		ca := path.Join(dockerCertPath, "ca.pem")

		newClient, err = docker.NewTLSClient(host, cert, key, ca)
	} else {
		newClient, err = docker.NewClient(host)
	}

	if err != nil {
		return nil, err
	}
	return newClient, err
}
Example #17
0
func (n *notaryCommander) parseConfig() (*viper.Viper, error) {
	n.setVerbosityLevel()

	// Get home directory for current user
	homeDir, err := homedir.Dir()
	if err != nil {
		return nil, fmt.Errorf("cannot get current user home directory: %v", err)
	}
	if homeDir == "" {
		return nil, fmt.Errorf("cannot get current user home directory")
	}

	config := viper.New()

	// By default our trust directory (where keys are stored) is in ~/.notary/
	defaultTrustDir := filepath.Join(homeDir, filepath.Dir(configDir))

	// If there was a commandline configFile set, we parse that.
	// If there wasn't we attempt to find it on the default location ~/.notary/config.json
	if n.configFile != "" {
		config.SetConfigFile(n.configFile)
	} else {
		config.SetConfigFile(filepath.Join(defaultTrustDir, "config.json"))
	}

	// Setup the configuration details into viper
	config.SetDefault("trust_dir", defaultTrustDir)
	config.SetDefault("remote_server", map[string]string{"url": defaultServerURL})

	// Find and read the config file
	if err := config.ReadInConfig(); err != nil {
		logrus.Debugf("Configuration file not found, using defaults")

		// If we were passed in a configFile via command linen flags, bail if it doesn't exist,
		// otherwise ignore it: we can use the defaults
		if n.configFile != "" || !os.IsNotExist(err) {
			return nil, fmt.Errorf("error opening config file: %v", err)
		}
	}

	// At this point we either have the default value or the one set by the config.
	// Either way, some command-line flags have precedence and overwrites the value
	if n.trustDir != "" {
		config.Set("trust_dir", pathRelativeToCwd(n.trustDir))
	}
	if n.tlsCAFile != "" {
		config.Set("remote_server.root_ca", pathRelativeToCwd(n.tlsCAFile))
	}
	if n.tlsCertFile != "" {
		config.Set("remote_server.tls_client_cert", pathRelativeToCwd(n.tlsCertFile))
	}
	if n.tlsKeyFile != "" {
		config.Set("remote_server.tls_client_key", pathRelativeToCwd(n.tlsKeyFile))
	}
	if n.remoteTrustServer != "" {
		config.Set("remote_server.url", n.remoteTrustServer)
	}

	// Expands all the possible ~/ that have been given, either through -d or config
	// If there is no error, use it, if not, just attempt to use whatever the user gave us
	expandedTrustDir, err := homedir.Expand(config.GetString("trust_dir"))
	if err == nil {
		config.Set("trust_dir", expandedTrustDir)
	}
	logrus.Debugf("Using the following trust directory: %s", config.GetString("trust_dir"))

	return config, nil
}
Example #18
0
func LoadAWSCredentials(profileName string) (aws.Auth, aws.Region, error) {
	if profileName == "" {
		if p := os.Getenv("AWS_DEFAULT_PROFILE"); p != "" {
			profileName = p
		} else {
			profileName = AWSDefaultProfileName
		}
	}

	var awsAuth aws.Auth
	var awsRegion aws.Region

	// load from File (~/.aws/config, ~/.aws/credentials)
	configFile := os.Getenv("AWS_CONFIG_FILE")
	if configFile == "" {
		if dir, err := homedir.Dir(); err == nil {
			configFile = filepath.Join(dir, ".aws", "config")
		}
	}

	dir, _ := filepath.Split(configFile)
	_profile := AWSDefaultProfileName
	if profileName != AWSDefaultProfileName {
		_profile = "profile " + profileName
	}
	auth, region, _ := loadAWSConfigFile(configFile, _profile)
	if isValidAuth(auth) {
		awsAuth = auth
	}
	if isValidRegion(region) {
		awsRegion = region
	}

	credFile := filepath.Join(dir, "credentials")
	auth, region, _ = loadAWSConfigFile(credFile, profileName)
	if isValidAuth(auth) {
		awsAuth = auth
	}
	if isValidRegion(region) {
		awsRegion = region
	}

	// Override by environment valiable
	if region := os.Getenv("AWS_DEFAULT_REGION"); region != "" {
		awsRegion = aws.GetRegion(region)
	}
	if os.Getenv("AWS_ACCESS_KEY_ID") != "" && os.Getenv("AWS_SECRET_ACCESS_KEY") != "" {
		if auth, _ := aws.EnvAuth(); isValidAuth(auth) {
			awsAuth = auth
		}
	}
	if isValidAuth(awsAuth) && isValidRegion(awsRegion) {
		return awsAuth, awsRegion, nil
	}

	// Otherwise, use IAM Role
	cred, err := aws.GetInstanceCredentials()
	if err == nil {
		exptdate, err := time.Parse("2006-01-02T15:04:05Z", cred.Expiration)
		if err == nil {
			auth := aws.NewAuth(cred.AccessKeyId, cred.SecretAccessKey, cred.Token, exptdate)
			awsAuth = *auth
		}
	}
	if isValidAuth(awsAuth) && isValidRegion(awsRegion) {
		return awsAuth, awsRegion, nil
	}

	return awsAuth, awsRegion, errors.New("cannot detect valid credentials or region")
}