Exemplo n.º 1
0
func main() {
	// Define buttons and action function
	DashMacs["74:75:48:10:33:ec"] = ToggleWorkshopLights
	DashMacs["f0:27:2d:6d:aa:de"] = ToggleMovieLights
	DashMacs["74:75:48:68:5f:8c"] = ToggleComputerLights

	// Load config file
	var conf = flag.String("conf", "./go-dash-button.ini", "Configuration file required for button events.")
	flag.Parse()

	if *conf != "" {
		if _, err := os.Stat(*conf); os.IsNotExist(err) {
			log.Printf("Can't find config file at: %s", *conf)
			os.Exit(0)
		}

		var err error
		Config, err = ini.Load(*conf)
		if err != nil {
			log.Printf("Unable to parse config file.")
			os.Exit(0)
		}
	}

	// Kick it off!
	SnifferStart()
}
// loadProfiles loads from the file pointed to by shared credentials filename for profile.
// The credentials retrieved from the profile will be returned or error. Error will be
// returned if it fails to read from the file, or the data is invalid.
func loadProfile(filename, profile string) (Value, error) {
	config, err := ini.Load(filename)
	if err != nil {
		return Value{}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err)
	}
	iniProfile, err := config.GetSection(profile)
	if err != nil {
		return Value{}, awserr.New("SharedCredsLoad", "failed to get profile", err)
	}

	id, err := iniProfile.GetKey("aws_access_key_id")
	if err != nil {
		return Value{}, awserr.New("SharedCredsAccessKey",
			fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename),
			err)
	}

	secret, err := iniProfile.GetKey("aws_secret_access_key")
	if err != nil {
		return Value{}, awserr.New("SharedCredsSecret",
			fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename),
			nil)
	}

	// Default to empty string if not found
	token := iniProfile.Key("aws_session_token")

	return Value{
		AccessKeyID:     id.String(),
		SecretAccessKey: secret.String(),
		SessionToken:    token.String(),
	}, nil
}
Exemplo n.º 3
0
func GetMainServerConfig() (string, error) {
	if mainServer != "" {
		return mainServer, nil
	} else {
		cfg, err := ini.Load(utils.GetConfigFilePath())
		if err != nil {
			return "", err
		}

		if session, err := cfg.GetSection(MainServerSectionName); err == nil {
			ip, err := utils.GetConfigValue(session, MainServerIpKeyName)
			if err != nil {
				return "", err
			}
			port, err := utils.GetConfigValue(session, MainServerPortKeyName)
			if err != nil {
				return "", err
			}

			return fmt.Sprintf("%s:%s", ip, port), nil
		} else {
			return "", errors.New("Can not find MainServer configuration")
		}
	}
}
Exemplo n.º 4
0
func init() {
	conf, err := ini.Load("conf/app.conf")
	if err != nil {
		panic(err)
	}
	crypt_secret = conf.Section("").Key("crypt_secret").String()
}
Exemplo n.º 5
0
func Init() {
	cfgFile := getAbs("./settings/settings.ini")

	cfg := new(ini.File)
	cfg.BlockMode = false
	cfg, err := ini.Load(cfgFile)
	if err != nil {
		panic(err)
	}

	cfg.MapTo(&settingStruct)
	settingStruct.Log.File = filepath.Join(
		getAbs(settingStruct.Log.Path),
		time.Now().Format(settingStruct.Log.Format),
	)

	//map to global
	{
		Static = settingStruct.Static
		Server = settingStruct.Server
		Filesync = settingStruct.Filesync
		Template = settingStruct.Template
		DefaultVars = settingStruct.DefaultVars
		Admin = settingStruct.Admin
		Log = settingStruct.Log
	}

	FsCfgMgr = new(cfgMgr)
	FsCfgMgr.Init()

	go watch()
}
Exemplo n.º 6
0
func getAWSRegion() (string, error) {
	currentUser, err := user.Current()
	if err != nil {
		return "", err
	}

	cfgPath := fmt.Sprintf("%s/.aws/config", currentUser.HomeDir)
	cfg, err := ini.Load(cfgPath)

	if err != nil {
		return "", err
	}

	var sectionName string
	if profileName != "" {
		sectionName = fmt.Sprintf("profile %s", profileName)
	} else {
		sectionName = "default"
	}

	section := cfg.Section(sectionName)
	if err != nil || !section.HasKey("region") {
		return "", errors.New("Did not find AWS region from config file")
	}

	region := section.Key("region").String()

	return region, nil
}
Exemplo n.º 7
0
func init() {
	var err error
	cfg, err = ini.Load("config.ini")
	if err != nil {
		log.Println(err)
	}
}
Exemplo n.º 8
0
func readFile(path string) (*ini.File, error) {
	cfg, err := ini.Load(path)
	if err != nil {
		return nil, err
	}
	return cfg, nil
}
Exemplo n.º 9
0
func loadConfig() *ServerInfo {
	log.Println("Loading configuration from `config.ini`")

	serverConfig := new(ServerInfo)
	cfg, err := ini.Load("config.ini")
	if err != nil {
		log.Fatal("Couldn't load config file")
	}

	err = cfg.Section("Server").MapTo(serverConfig)
	if err != nil {
		log.Println("Couldn't map configuration!")
		log.Fatal(err)
	}

	now := time.Now()
	serverConfig.started = &now

	log.Println("Loading motd")
	readMotd(serverConfig, serverConfig.MotdPath)

	log.Println("Configuration fully loaded")
	return serverConfig

}
Exemplo n.º 10
0
func addModule(cmd *cobra.Command, args []string) {

	moduleName := args[0]
	modulePath := args[1]

	cfg, err := ini.Load(configPath)
	if err != nil {
		log.Fatal(err)
	}

	section, err := cfg.NewSection(moduleName)

	if err != nil {
		log.Fatal(err)
	}
	_, err = section.NewKey("path", modulePath)
	_, err = section.NewKey("comment", moduleComment)
	_, err = section.NewKey("read only", boolMapping[moduleReadOnly])
	_, err = section.NewKey("list", boolMapping[mouduleListable])
	_, err = section.NewKey("uid", moduleUid)
	_, err = section.NewKey("gid", moduleGid)
	_, err = section.NewKey("auth users", moduleAuthUser)
	_, err = section.NewKey("secrets files", moduleSecrets)

	cfg.SaveTo(configPath)
}
Exemplo n.º 11
0
func main() {

	// parse args
	_, err := flags.Parse(&opts)
	if err != nil {
		typ := err.(*flags.Error).Type
		if typ == flags.ErrHelp {
			os.Exit(0)
		} else {
			fmt.Println(err)
			os.Exit(1)
		}
	}

	// load from profile
	credentials_path := expandPath(opts.Filename)
	cfg, err := ini.Load(credentials_path)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	section, err := cfg.GetSection(opts.Positional.Profile)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// AWS_KEY
	key := section.Key("aws_access_key_id").String()
	// AWS_SECRET
	secret := section.Key("aws_secret_access_key").String()
	// AWS_KEYNAME
	keyname := section.Key("aws_keyname").String()
	// AWS_KEYPATH
	kp := section.Key("aws_keypath").String()
	keypath := expandPath(kp)

	// output
	out := ""
	out += fmt.Sprintf("export AWS_ACCESS_KEY_ID='%s'; ", key)
	out += fmt.Sprintf("export AWS_SECRET_ACCESS_KEY='%s'; ", secret)
	if len(keyname) > 0 {
		out += fmt.Sprintf("export AWS_KEYNAME='%s'; ", keyname)
	} else {
		out += "unset AWS_KEYNAME; "
	}
	if len(keypath) > 0 {
		out += fmt.Sprintf("export AWS_KEYPATH='%s'; ", keypath)
	} else {
		out += "unset AWS_KEYPATH; "
	}

	// verbose?
	if opts.Verbose {
		out += "env | grep AWS; "
	}

	fmt.Println(out)
}
Exemplo n.º 12
0
func NewIniConfig(file string) Configuration {
	config, err := ini.Load(file)
	if err != nil {
		log.Fatalf("could not read config file %s", err)
	}
	// Remove unused default section
	config.DeleteSection(ini.DEFAULT_SECTION)
	return &IniConfig{config: config}
}
Exemplo n.º 13
0
func LoadConfig(path string) error {

	if _, err := IsExists(path); err != nil {
		return fmt.Errorf("Unable to locate local configuration file. path: %s", path)
	}

	iniCfg, err := ini.Load(path)
	if err != nil || iniCfg == nil {
		return err
	}

	if sect, err := iniCfg.GetSection("MAIN"); sect == nil || err != nil {
		logLevel = "WARN"
	} else {
		if ok := sect.HasKey("log-level"); ok {
			logLevel = sect.Key("log-level").In("WARN", []string{"DEBUG", "INFO", "ERROR", "CRITICAL"})
		}

		if ok := sect.HasKey("req-doms"); ok {
			var doms []string
			reqdoms := strings.Split(sect.Key("req-doms").String(), ",")
			for _, dom := range reqdoms {
				dom = strings.TrimSpace(dom)
				doms = append(doms, dom)
			}

			if len(doms) <= 0 {
				return fmt.Errorf("Malformed req-doms in config file: %s", path)
			}
			reqDoms = doms
		}
	}

	if sect, err := iniCfg.GetSection("CACHE"); sect != nil && err == nil {
		if ok := sect.HasKey("cache-path"); ok {
			cachePath = sect.Key("cache-path").Validate(func(in string) string {
				if len(in) == 0 {
					return cachePath
				}
				return in
			})
		}
	}

	if sect, err := iniCfg.GetSection("DNS"); sect != nil && err == nil {
		if ok := sect.HasKey("cache-ttl"); ok {
			if v, err := sect.Key("cache-ttl").Int(); err == nil {
				cacheTTL = v
			}
		}
	}

	return nil
}
Exemplo n.º 14
0
func readConfig() {
	cfg, err := ini.Load("./qunar.ini")
	if err != nil {
		panic(err)
	}
	sec := cfg.Section("from_citys")
	fromCitys = sec.Keys()
	sec = cfg.Section("to_citys")
	toCitys = sec.Keys()
	max = cfg.Section("common").Key("max").MustInt(8)
}
Exemplo n.º 15
0
func delModule(cmd *cobra.Command, args []string) {

	moduleName := args[0]

	cfg, err := ini.Load(configPath)
	if err != nil {
		log.Fatal(err)
	}

	cfg.DeleteSection(moduleName)
	cfg.SaveTo(configPath)
}
Exemplo n.º 16
0
func getConfigValue(valueName string) (string, error) {
	cfg, err := ini.Load(utils.GetConfigFilePath())
	if err != nil {
		return "", err
	}

	if session, err := cfg.GetSection(""); err == nil {
		return utils.GetConfigValue(session, valueName)
	} else {
		return "", err
	}
}
Exemplo n.º 17
0
func InitConfig() Config {
	cfg, err := ini.Load("config.ini")
	cfg.BlockMode = false
	if err != nil {
		panic(err)
	}
	config := Config{}
	err = cfg.MapTo(&config)
	if err != nil {
		panic(err)
	}

	return config
}
Exemplo n.º 18
0
Arquivo: status.go Projeto: ibab/msg
func GetMaildirPath(key string) string {
	home := os.Getenv("HOME")
	cfg, err := ini.Load(home + "/.msgconfig")
	if err != nil {
		log.Fatal(err)
	}
	section, err := cfg.GetSection("mail")
	if err != nil {
		log.Fatal(err)
	}
	maildir, err := section.GetKey(key)
	if err != nil {
		log.Fatal(err)
	}
	return strings.Replace(maildir.String(), "~", home, -1)
}
Exemplo n.º 19
0
func DetectConfig(specifiedFile string) (*ConfigMan, error) {
	var paths []string
	if specifiedFile == NULL {
		paths = []string{CONFIG_NAME} // cwd
		var ef, home string
		var err error
		// same path with exe
		ef, err = osext.ExecutableFolder()
		if err == nil {
			paths = append(paths, filepath.Join(ef, CONFIG_NAME))
		}
		// home
		if u, err := user.Current(); err == nil {
			home = u.HomeDir
		} else {
			home = os.Getenv("HOME")
		}
		if home != NULL {
			paths = append(paths, filepath.Join(home, CONFIG_NAME))
		}
		// etc
		if runtime.GOOS != "windows" {
			paths = append(paths, "/etc/deblocus/"+CONFIG_NAME)
		}
	} else {
		paths = []string{specifiedFile}
	}

	var file *string
	for _, f := range paths {
		if f != NULL && !IsNotExist(f) {
			file = &f
			break
		}
	}
	if file == nil {
		msg := fmt.Sprintf("Not found `%s` in [ %s ]\n", CONFIG_NAME, strings.Join(paths, "; "))
		msg += "Create config in typical path or specify it with option `--config/-c`."
		return nil, errors.New(msg)
	}

	iniInstance, err := ini.Load(*file)
	return &ConfigMan{
		filepath:    *file,
		iniInstance: iniInstance,
	}, err
}
Exemplo n.º 20
0
func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.Parse()

	var (
		err error
	)
	if cfg, err = ini.Load(*confpath); err != nil {
		panic(err)
	}

	if cfg.Section("PPROF").Key("UsePprof").MustBool(false) {
		go func() {
			log.Println(http.ListenAndServe(cfg.Section("PPROF").Key("PprofAddr").MustString(":6063"), nil))
		}()
	}
}
Exemplo n.º 21
0
func (this *INIFile) Load() (map[string]string, error) {
	settings := map[string]string{}

	file, err := ini.Load(this.path)
	if err != nil {
		return nil, err
	}

	for _, section := range file.Sections() {
		for _, key := range section.Keys() {
			token := fmt.Sprintf("%s.%s", section.Name(), key.Name())
			settings[token] = key.String()
		}
	}

	return settings, nil
}
Exemplo n.º 22
0
// InitConfig initializes configuration file
func InitConfig(filepath string, section string) Config {
	var (
		c               Config
		requiredOptions = []string{"host", "client_token", "client_secret", "access_token"}
		missing         []string
	)

	// Check if filepath is empty
	if filepath == "" {
		filepath = "~/.edgerc"
	}

	// Check if section is empty
	if section == "" {
		section = "default"
	}

	// Tilde seems to be not working when passing ~/.edgerc as file
	// Takes current user and use home dir instead

	path, err := tilde.Expand(filepath)

	if err != nil {
		log.Panicf("Fatal could not find home dir from user: %s \n", err)
	}

	edgerc, err := ini.Load(path)
	if err != nil {
		log.Panicf("Fatal error config file: %s \n", err)
	}
	edgerc.Section(section).MapTo(&c)
	for _, opt := range requiredOptions {
		if !(edgerc.Section(section).HasKey(opt)) {
			missing = append(missing, opt)
		}
	}
	if len(missing) > 0 {
		log.Panicf("Fatal missing required options: %s \n", missing)
	}
	if c.MaxBody == 0 {
		c.MaxBody = 131072
	}
	return c
}
Exemplo n.º 23
0
func checkConfigFile() error {
	usr, err := user.Current()
	if err != nil {
		return err
	}

	cfg, err := ini.Load(path.Join(usr.HomeDir, CONFIG_FILENAME))
	if err != nil {
		return err
	}

	CONSUMER_KEY = cfg.Section("").Key("CONSUMER_KEY").String()
	CONSUMER_SECRET = cfg.Section("").Key("CONSUMER_SECRET").String()

	ACCESS_TOKEN = cfg.Section("").Key("ACCESS_TOKEN").String()
	ACCESS_TOKEN_SECRET = cfg.Section("").Key("ACCESS_TOKEN_SECRET").String()

	return isConfigurationComplete()
}
Exemplo n.º 24
0
// Loads the primary configuration file and maps it into a Config type.
func parseConfigINI(cfgPathAbs string) (*Config, error) {
	var err error
	var cfg *Config = new(Config)
	var iniCfg *ini.File

	// loading the INI file contents into local struct
	if iniCfg, err = ini.Load(cfgPathAbs); err != nil {
		log.Fatalln("[Config] Errors on parsing INI file:", err)
		return nil, err
	}

	// mapping configuration into local struct
	if err = iniCfg.MapTo(cfg); err != nil {
		log.Fatalln("[Config] Errors on mapping INI:", err)
		return nil, err
	}

	return cfg, nil
}
Exemplo n.º 25
0
// Store function updates the shared credentials with the specified values:
// * If the shared credentials file does not exist, it will be created. Any parent directories will also be created.
// * If the section to update does not exist, it will be created.
func Store(accessKeyID, secretAccessKey, sessionToken, profile string) error {
	if profile == "" {
		profile = defaultProfile
	}

	credPath, err := filename()
	if err != nil {
		return err
	}

	// check if file exists, if not create it
	if !fileutil.Exists(credPath) {
		err := createFile(credPath)
		if err != nil {
			return awserr.New("SharedCredentialsStore", "failed to create shared credentials file", err)
		}
	}

	config, err := ini.Load(credPath)
	if err != nil {
		return awserr.New("SharedCredentialsStore", "failed to load shared credentials file", err)
	}

	iniProfile := config.Section(profile)
	if err != nil {
		return awserr.New("SharedCredentialsStore", "failed to get profile", err)
	}

	// Default to empty string if not found
	iniProfile.Key(awsAccessKeyID).SetValue(accessKeyID)

	iniProfile.Key(awsSecretAccessKey).SetValue(secretAccessKey)

	iniProfile.Key(awsSessionToken).SetValue(sessionToken)

	err = config.SaveTo(credPath)
	if err != nil {
		return awserr.New("SharedCredentialsStore", "failed to save profile", err)
	}

	return nil
}
Exemplo n.º 26
0
func GetProcessNames() ([]string, error) {
	if processNames != "" {
		return strings.Split(processNames, ","), nil
	} else {
		cfg, err := ini.Load(utils.GetConfigFilePath())
		if err != nil {
			return make([]string, 0), err
		}

		if session, err := cfg.GetSection(SystemSectionName); err == nil {
			processStr, err := utils.GetConfigValue(session, SystemConcernedProcesses)
			if err != nil {
				return make([]string, 0), err
			}
			return strings.Split(processStr, ","), nil
		} else {
			return make([]string, 0), err
		}
	}
}
Exemplo n.º 27
0
// LoadEndpoints returns and Endpoints struct by reading them from a file or from defaults
func LoadEndpoints(filename string, section string) Endpoints {
	config, err := ini.Load(filename)

	appManagerURL := "https://application.api.kumoru.io"
	if os.Getenv("APPLICATION_MANAGER_URL") != "" {
		appManagerURL = os.Getenv("APPLICATION_MANAGER_URL")
	}

	authManagerURL := "https://authorization.api.kumoru.io"
	if os.Getenv("AUTHORIZATION_MANAGER_URL") != "" {
		authManagerURL = os.Getenv("AUTHORIZATION_MANAGER_URL")
	}

	locationManagerURL := "https://location.api.kumoru.io"
	if os.Getenv("LOCATION_MANAGER_URL") != "" {
		locationManagerURL = os.Getenv("LOCATION_MANAGER_URL")
	}

	if err != nil {
		return Endpoints{
			Application:   appManagerURL,
			Authorization: authManagerURL,
			Location:      locationManagerURL,
		}
	}

	iniEndpoints, err := config.GetSection(section)
	if err != nil {
		return Endpoints{
			Application:   appManagerURL,
			Authorization: authManagerURL,
			Location:      locationManagerURL,
		}
	}

	return Endpoints{
		Application:   iniEndpoints.Key("kumoru_application_api").String(),
		Authorization: iniEndpoints.Key("kumoru_authorization_api").String(),
		Location:      iniEndpoints.Key("kumoru_location_api").String(),
	}
}
Exemplo n.º 28
0
func loadSharedConfigIniFiles(filenames []string) ([]sharedConfigFile, error) {
	files := make([]sharedConfigFile, 0, len(filenames))

	for _, filename := range filenames {
		if _, err := os.Stat(filename); os.IsNotExist(err) {
			// Trim files from the list that don't exist.
			continue
		}

		f, err := ini.Load(filename)
		if err != nil {
			return nil, SharedConfigLoadError{Filename: filename}
		}

		files = append(files, sharedConfigFile{
			Filename: filename, IniData: f,
		})
	}

	return files, nil
}
Exemplo n.º 29
0
func main() {

	var (
		configFilepath = kingpin.Arg("config-file", "Configuration filepath").Default("/etc/metrology/metrology.conf").String()
	)

	kingpin.Version("0.0.1")
	kingpin.Parse()

	cfg, err := ini.Load(*configFilepath)

	if err != nil {
		panic(err)
	}

	metricAgentEndpoint := cfg.Section("agent").Key("metric-agent-endpoint").String()
	metricPublicationEndpoint := cfg.Section("agent").Key("metric-publication-endpoint").String()

	meteringAgent := agent.CreateAgent(metricAgentEndpoint, metricPublicationEndpoint)
	meteringAgent.Run()
}
func TestSharedCredentialsStoreDefaultProfile(t *testing.T) {
	// Test setup
	os.Clearenv()
	credFilePath := exampleCredFilePath()
	setupTest(credFilePath)

	// Test
	os.Setenv("AWS_SHARED_CREDENTIALS_FILE", credFilePath)

	err1 := Store(accessKey, accessSecretKey, token, "")
	assert.Nil(t, err1, "Expect no error saving profile")

	config, err2 := ini.Load(credFilePath)
	assert.Nil(t, err2, "Expect no error loading file")

	iniProfile := config.Section(defaultProfile)

	assert.Equal(t, accessKey, iniProfile.Key(awsAccessKeyID).Value(), "Expect access key ID to match")
	assert.Equal(t, accessSecretKey, iniProfile.Key(awsSecretAccessKey).Value(), "Expect secret access key to match")
	assert.Equal(t, token, iniProfile.Key(awsSessionToken).Value(), "Expect session token to match")
}