Esempio n. 1
0
File: config.go Progetto: vil1/gerra
func init() {
	var errors Errors
	basePath := os.Args[0]
	configPath = basePath[0:strings.LastIndex(basePath, "/")]
	if cfg, err := conf.ReadConfigFile(configPath + "/hooks.conf"); err == nil {
		if User, err = cfg.GetString("jira", "user"); err != nil {
			errors = append(errors, err)
		}
		if Pwd, err = cfg.GetString("jira", "password"); err != nil {
			errors = append(errors, err)
		}
		if JiraBaseUrl, err = cfg.GetString("jira", "baseUrl"); err != nil {
			errors = append(errors, err)
		}
		if Host, err = cfg.GetString("gerrit", "host"); err != nil {
			errors = append(errors, err)
		}
		if Port, err = cfg.GetString("gerrit", "port"); err != nil {
			errors = append(errors, err)
		}
		if len(errors) > 0 {
			panic(errors)
		}
	} else {
		panic(err)
	}
	var err error
	if LogFile, err = os.OpenFile(configPath+"/hooks.log", os.O_APPEND|os.O_WRONLY, 0600); err == nil {
		log.SetOutput(LogFile)
		log.SetFlags(log.LstdFlags | log.Lshortfile)
	} else {
		panic(err)
	}
}
Esempio n. 2
0
func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	config_file := flag.String("conf", "default.conf", "Config file to use")
	flag.BoolVar(&DEBUG, "debug", false, "Enable debug output")
	flag.Parse()

	c, err := conf.ReadConfigFile(*config_file)
	if err != nil {
		log.Fatal("Error parsing config file: ", err)
	}

	LISTEN = getString(c, "", "listen")
	HTTP_HOST_HEADER = getString(c, "", "header")
	SPOOL_DIR = filepath.Clean(getString(c, "", "spool_dir"))
	PREFIX = getString(c, "", "file_prefix")
	PREFIX_TMP = getString(c, "", "tmpfile_prefix")

	if !isDir(SPOOL_DIR) {
		log.Fatalf("Spool directory %s does not exist or is not a directory", SPOOL_DIR)
	}

	// routing configuration
	http.HandleFunc("/", Handler)

	log.Print("Start listening on ", LISTEN, " spool=", SPOOL_DIR)
	log.Fatal(http.ListenAndServe(LISTEN, nil))
}
Esempio n. 3
0
func readConf(filename string) error {
	c, err := conf.ReadConfigFile(filename)
	if err != nil {
		return err
	}
	var err_psql, err_serv_port, err_log_file, err_tls_mode, err_verbose_mode error
	info_connect_bdd, err_psql = c.GetString("default", "db-uri")
	server_port, err_serv_port = c.GetInt("default", "server-port")
	log_file, err_log_file = c.GetString("default", "log-file")
	tls_mode, err_tls_mode = c.GetBool("default", "tls")
	verbose_mode, err_verbose_mode = c.GetBool("default", "verbose")

	// default value if not in the config file
	if err_psql != nil {
		info_connect_bdd = "postgres://*****:*****@127.0.0.1:5432/kanban"
	}
	if err_serv_port != nil {
		server_port = 9658
	}
	if err_log_file != nil {
		log_file = "kanban.log"
	}
	if err_tls_mode != nil {
		tls_mode = false
	}
	if err_verbose_mode != nil {
		verbose_mode = false
	}
	return nil
}
Esempio n. 4
0
func NewContester(configFile string, gData *platform.GlobalData) (*Contester, error) {
	config, err := conf.ReadConfigFile(configFile)
	if err != nil {
		return nil, err
	}

	var result Contester

	result.InvokerId = getHostname()
	result.Env = getLocalEnvironment()
	result.ServerAddress, err = config.GetString("default", "server")
	if err != nil {
		return nil, err
	}
	result.Platform = PLATFORM_ID
	result.Disks = PLATFORM_DISKS
	result.ProgramFiles = PLATFORM_PFILES
	result.PathSeparator = string(os.PathSeparator)
	result.GData = gData

	result.Storage = storage.NewStorage()

	result.Sandboxes, err = configureSandboxes(config)
	if err != nil {
		return nil, err
	}

	return &result, nil
}
Esempio n. 5
0
func (this *Configurator) LoadConfig() *Config {
	var configFileName string
	flag.StringVar(&configFileName, "config", "hpfeed.conf", "path to config file")
	flag.Parse()

	config := Config{}
	configFile, err := conf.ReadConfigFile(configFileName)
	helper.HandleFatalError("loading config file failed (-config= forgotten):", err)

	config.Updateinterval, err = configFile.GetInt("", "updateinterval")
	helper.HandleFatalError("updateinterval", err)
	config.ListenPort, err = configFile.GetInt("", "listenPort")
	helper.HandleFatalError("listenPort", err)
	config.ListenPath, err = configFile.GetString("", "listenPath")
	helper.HandleFatalError("listenPath", err)
	config.Dbhost, err = configFile.GetString("", "dbhost")
	helper.HandleFatalError("dbhost", err)
	config.Dbport, err = configFile.GetString("", "dbport")
	helper.HandleFatalError("dbport", err)
	config.Dbname, err = configFile.GetString("", "dbname")
	helper.HandleFatalError("dbname", err)
	config.Dbuser, err = configFile.GetString("", "dbuser")
	helper.HandleFatalError("dbuser", err)
	config.Dbpassword, err = configFile.GetString("", "dbpassword")
	helper.HandleFatalError("dbpassword", err)
	config.ForumUser, err = configFile.GetString("", "forumUser")
	helper.HandleFatalError("forumUser", err)
	config.ForumPasswd, err = configFile.GetString("", "forumPasswd")
	helper.HandleFatalError("forumPasswd", err)
	return &config
}
Esempio n. 6
0
func getSocketFromArgs(args []string) (string, error) {
	const config_usage = "Config File to use"
	userHomeDir := "~"

	u, err := user.Current()
	if err == nil {
		userHomeDir = u.HomeDir
	}

	flags := flag.NewFlagSet("stop", flag.ExitOnError)
	flags.StringVar(&globals.configFileName, "config", path.Join(userHomeDir, ".asink", "config"), config_usage)
	flags.StringVar(&globals.configFileName, "c", path.Join(userHomeDir, ".asink", "config"), config_usage+" (shorthand)")
	flags.Parse(args)

	config, err := conf.ReadConfigFile(globals.configFileName)
	if err != nil {
		return "", err
	}

	rpcSock, err := config.GetString("local", "socket")
	if err != nil {
		return "", errors.New("Error reading local.socket from config file at " + globals.configFileName)
	}

	return rpcSock, nil
}
Esempio n. 7
0
func init() {
	var err error
	// reading config file

	c, err := conf.ReadConfigFile("Gopfile")
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	user, err = c.GetString("", "username")
	pass, err = c.GetString("", "password")
	hostname, err = c.GetString("", "hostname")
	repository, err = c.GetString("", "repository")
	path, err = c.GetString("", "path")
	releases = path + "/releases"
	shared = path + "/shared"
	utils = path + "/utils"

	keep_releases, err = c.GetString("", "keep_releases")

	//just log whichever we get; let the user re-run the program to see all errors... for now
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}
}
Esempio n. 8
0
func ReadConfigFile(fname string) (c *ConfigFile, err error) {
	corg, err := conf.ReadConfigFile(fname)

	if err != nil {
		return nil, err
	}
	return &ConfigFile{*corg}, nil
}
Esempio n. 9
0
//ranges through config file and checks all expressions.
// prints result messages to stdout
func (c *checker) CheckAll() ([]CheckResult, error) {
	result := []CheckResult{}
	cnf, err := conf.ReadConfigFile(c.configFile)
	if err != nil {
		return nil, err
	}
	for _, section := range cnf.GetSections() {
		if section == "default" {
			continue
		}
		expr, _ := cnf.GetString(section, "expr")
		_, r, err := types.Eval(expr, c.pkg, c.sc)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			continue
		}
		cr := &CheckResult{
			Name: section,
		}
		var m string
		if exact.BoolVal(r) {
			m, err = cnf.GetString(section, "true")
			if err != nil {
				continue
			}
		} else {
			m, err = cnf.GetString(section, "false")
			if err != nil {
				continue
			}
		}
		val, err := cnf.GetString(section, "val")
		if err == nil {
			t, v, err := types.Eval(val, c.pkg, c.sc)
			if err == nil {
				if types.Identical(t, types.Typ[types.UntypedFloat]) || types.Identical(t, types.Typ[types.Float64]) {
					x, _ := exact.Float64Val(v)
					cr.Value = x
				}
			}
		}
		owner, err := cnf.GetString(section, "owner")
		if err == nil {
			cr.Owner = owner
		} else {
			cr.Owner = "unknown"
		}

		_, msg, err := types.Eval(m, c.pkg, c.sc)
		if err != nil {
			cr.Message = m
		} else {
			cr.Message = exact.StringVal(msg)
		}
		result = append(result, *cr)
	}
	return result, nil
}
Esempio n. 10
0
// create connection to mysql database here
// when an error is encountered, still return database so that the logger may be used
func New(user, password, config string) (MysqlDB, error) {

	dsn := map[string]string{"dbname": "information_schema"}
	creds := map[string]string{"root": "/root/.my.cnf", "nrpe": "/etc/my_nrpe.cnf"}

	database := &mysqlDB{
		Logger: log.New(os.Stderr, "LOG: ", log.Lshortfile),
	}

	if user == "" {
		user = DEFAULT_MYSQL_USER
		dsn["user"] = DEFAULT_MYSQL_USER
	} else {
		dsn["user"] = user
	}
	if password != "" {
		dsn["password"] = password
	}
	//	socket_file := "/var/lib/mysql/mysql.sock"
	//	if _, err := os.Stat(socket_file); err == nil {
	//		dsn["unix_socket"] = socket_file
	//	}

	//Parse ini file to get password
	ini_file := creds[user]
	if config != "" {
		ini_file = config
	}
	_, err := os.Stat(ini_file)
	if err != nil {
		fmt.Println(err)
		return database, errors.New("'" + ini_file + "' does not exist")
	}
	// read ini file to get password
	c, err := conf.ReadConfigFile(ini_file)
	if err != nil {
		return database, err
	}
	pw, err := c.GetString("client", "password")
	dsn["password"] = strings.Trim(pw, " \"")
	database.dsnString = makeDsn(dsn)

	//make connection to db
	db, err := sql.Open("mysql", database.dsnString)
	if err != nil {
		return database, err
	}
	database.db = db

	//ping db to verify connection
	err = database.db.Ping()
	if err != nil {
		return database, err
	}
	fmt.Println("connected to " + user + " @ " + dsn["dbname"])
	return database, nil
}
Esempio n. 11
0
func NewShellSource(sess *dbus.Connection, x *xdg.XDG) *ShellSource {
	ss := &ShellSource{
		sess_conn: sess,
		Xdg:       x,
	}
	for _, dir := range []string{
		"/usr/share/gnome-shell/search-providers",
		"/usr/local/share/gnoem-shell/search-providers",
	} {

		srcs, err := ioutil.ReadDir(dir)
		//utils.FailMeMaybe(err)
		if err != nil {
			continue
		}
		for _, file := range srcs {
			cfg, err := conf.ReadConfigFile(dir + "/" + file.Name())
			utils.FailMeMaybe(err)

			SSP := "Shell Search Provider"

			objPath, err := cfg.GetString(SSP, "ObjectPath")
			if err != nil {
				continue
			}

			busName, err := cfg.GetString(SSP, "BusName")
			if err != nil {
				continue
			}

			var name, icon string

			name, err = cfg.GetString(SSP, "Name")
			if err != nil {
				did, err := cfg.GetString(SSP, "DesktopId")
				if err == nil {
					name, icon = getName(did)
				}
			}

			if icon == "" {
				if tmp, err := cfg.GetString(SSP, "Icon"); err == nil {
					icon = tmp
				}
			}

			searcher := gs_search.New(sess.Object(busName, dbus.ObjectPath(objPath)))
			searcher.Name = name
			searcher.Icon = icon

			ss.searchers = append(ss.searchers, searcher)
		}
	}

	return ss
}
Esempio n. 12
0
File: front.go Progetto: v-sh/gotwit
func main() {
	flag.Parse()
	var err error
	mainConf, err = conf.ReadConfigFile(confFileName)

	if err != nil {
		log.Panicf("Error reading config file: err %s", err)
	}
	httpServe.Run(mainConf)
}
Esempio n. 13
0
func initHost() string {
	c, err := conf.ReadConfigFile("./tohva-test.conf")
	if err == nil {
		h, err := c.GetString("database", "host")
		if err == nil {
			return h
		}
	}
	return "localhost"
}
Esempio n. 14
0
func readSlashCreateConfig() {
	if _, err := os.Stat(*configFilePath); os.IsNotExist(err) {
		config.WriteConfigFile(*configFilePath, 0600, configHeader)
	} else {
		config, err = conf.ReadConfigFile(*configFilePath)
		if err != nil {
			log.Fatal("Error with ReadConfigFile:", err)
		}
	}
}
Esempio n. 15
0
func OpenConfig(filename string) (c *conf.ConfigFile, err error) {
	if filename == "" {
		filename = defaultConfigFilePath
	}
	c, err = conf.ReadConfigFile(filename)
	if err != nil {
		return nil, err
	}
	return
}
Esempio n. 16
0
File: conf.go Progetto: rif/gocmd
func main() {
	c, err := conf.ReadConfigFile("something.config")
	if err != nil {
		log.Panic("cannot open config file: ", err)
	}
	log.Print(c.GetString("default", "host"))        // return something.com
	log.Print(c.GetInt("default", "port"))           // return 443
	log.Print(c.GetBool("default", "active"))        // return true
	log.Print(c.GetBool("default", "compression"))   // return false
	log.Print(c.GetBool("default", "compression"))   // returns false
	log.Print(c.GetBool("service-1", "compression")) // returns true
	log.Print(c.GetBool("service-2", "compression")) // returns GetError
}
Esempio n. 17
0
func Load() *conf.ConfigFile {
	if config != nil {
		return config
	}

	path := ConfFile()

	config1, err := conf.ReadConfigFile(path)
	if err != nil {
		log.Println("Error reading config; writing out default")

		os.MkdirAll(ConfDir(), 0700)

		file, err := os.OpenFile(path,
			os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
		if err != nil {
			log.Fatalln("Could not create config file:", err)
		}

		_, err = file.WriteString(defaultConfig)
		if err != nil {
			log.Fatalln("Write error:", err)
		}

		err = file.Close()
		if err != nil {
			log.Fatalln("Error on close:", err)
		}

		config1, err = conf.ReadConfigFile(path)
		if err != nil {
			log.Fatalln("Could not read new default config file:", err)
		}
	}

	config = config1
	return config
}
Esempio n. 18
0
func init() {

	// command line options
	var confFile string
	flag.StringVar(&confFile, "config", "/etc/toris/toris.conf", "The configuration file")

	flag.BoolVar(&ShowModules, "module-list", false, "Print the list of loaded modules and exits")

	flag.Parse()

	// read the configuration file
	config, err := conf.ReadConfigFile(confFile)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	// initializes the database connection
	dbHost, _ := config.GetString("database", "host")
	dbPort, _ := config.GetInt("database", "port")
	dbName, _ := config.GetString("database", "name")
	adminName, _ := config.GetString("database", "admin_name")
	adminPwd, _ := config.GetString("database", "admin_password")

	couch := tohva.CreateCouchClient(dbHost, dbPort)

	// the secret token for secure cookies
	secretToken, _ := config.GetString("sessions", "secret")

	Context = Toris{
		map[string]InstalledModule{},
		config,
		&couch,
		dbName,
		adminName,
		adminPwd,
		sessions.NewCookieStore([]byte(secretToken))}

	// start all the modules
	for _, m := range Context.modules {
		log.Println("Starting module " + m.module.Name())
	}

}
Esempio n. 19
0
func configDeleteHandler(writer http.ResponseWriter, request *http.Request) {
	readSlashCreateConfig()
	if config.RemoveSection(request.FormValue("DeleteName")) {
		err := config.WriteConfigFile(*configFilePath, 0600, configHeader)
		if err != nil {
			log.Fatalf("Error with WriteConfigFile: %s", err)
		}
		dmns, err := conf.ReadConfigFile(*configFilePath)
		if err != nil {
			log.Fatalf("Error with ReadConfigFile: %s", err)
		} else {
			config = dmns
			setupDaemonsFromConfig()
			http.Redirect(writer, request, "/config", http.StatusFound)
		}
	} else {
		log.Fatal(writer, "Error with RemoveSection!")
	}
}
Esempio n. 20
0
func (xdg *XDG) LoadApplication(path string) (*Application, error) {
	cfg, err := conf.ReadConfigFile(path)
	if err != nil {
		return nil, err
	}

	app := &Application{}

	DE := "Desktop Entry"

	app.Exec, err = cfg.GetRawString(DE, "Exec")
	if err != nil {
		return nil, err
	}

	app.Icon, err = cfg.GetRawString(DE, "Icon")
	if err != nil {
		app.Icon = ""
	}

	app.Name, err = cfg.GetRawString(DE, "Name")
	if err != nil {
		return nil, err
	}

	app.Type, err = cfg.GetRawString(DE, "Type")
	if err != nil {
		return nil, err
	}

	app.NoDisplay, err = cfg.GetBool(DE, "NoDisplay")
	if err != nil {
		app.NoDisplay = false
	}

	app.cfg = cfg
	app.xdg = xdg

	return app, nil
}
Esempio n. 21
0
func MergeConfig() {
	if Configfile == "" {
		return
	}
	config, err := conf.ReadConfigFile(Configfile)
	if err != nil {
		log.Fatal(err)
		return
	}
	getdef := func(key, default_value string) string {
		value, err := config.GetString("ums", key)
		if err == nil && value != "" {
			return value
		}
		return default_value
	}
	Account.Email = getdef("Email", Account.Email)
	Account.Password = getdef("Password", Account.Password)
	Account.Host = getdef("Host", Account.Host)
	// Port is also a string, because we also accept sth. like pop3s here
	Account.Port = getdef("Port", Account.Port)
}
Esempio n. 22
0
func configCreateHandler(writer http.ResponseWriter, request *http.Request) {
	readSlashCreateConfig()
	// AddSection and AddOption return boolean
	if config.AddSection(request.FormValue("Name")) {
		if config.AddOption(request.FormValue("Name"), "sshUserString", request.FormValue("sshUserName")) {
			if config.AddOption(request.FormValue("Name"), "serverAddrString", request.FormValue("serverAddress")) {
				if config.AddOption(request.FormValue("Name"), "daemonAddrString", request.FormValue("daemonAddress")) {
					err := config.WriteConfigFile(*configFilePath, 0600, configHeader)
					if err != nil {
						log.Fatalf("Error with WriteConfigFile: %s", err)
					}
				}
				dmns, err := conf.ReadConfigFile(*configFilePath)
				if err != nil {
					log.Fatalf("Error with ReadConfigFile: %s", err)
				} else {
					config = dmns
					setupDaemonsFromConfig()
					http.Redirect(writer, request, "/config", http.StatusFound)
				}
			}
		}
	}
}
Esempio n. 23
0
func getName(did string) (string, string) {
	for _, dir := range []string{
		"/usr/share/applications",
		"/usr/local/share/applications",
		os.Getenv("HOME") + "/.local/share/applications",
	} {
		cfg, err := conf.ReadConfigFile(dir + "/" + did)
		if err == nil {
			name, err := cfg.GetString("Desktop Entry", "Name")
			if err != nil {
				return strings.Split(did, ".")[0], ""
			}

			icon, err := cfg.GetString("Desktop Entry", "Icon")
			if err != nil {
				return strings.Split(did, ".")[0], ""
			}

			return name, icon
		}
	}

	return strings.Split(did, ".")[0], ""
}
Esempio n. 24
0
func main() {
	pid := sigar.ProcExe{}
	pid.Get(os.Getpid())
	base := path.Dir(pid.Name)
	config, err := conf.ReadConfigFile(base + "/watchdog.conf")
	hostname, err := config.GetString("", "hostname")
	dbuser, err := config.GetString("mongo", "username")
	dbpass, err := config.GetString("mongo", "password")
	dbhost, err := config.GetString("mongo", "host")
	dbname, err := config.GetString("mongo", "database")
	fslist := sigar.FileSystemList{}
	cpulist := sigar.CpuList{}
	load := sigar.LoadAverage{}
	uptime := sigar.Uptime{}
	mem := sigar.Mem{}
	swap := sigar.Swap{}
	plist := sigar.ProcList{}
	fslist.Get()
	cpulist.Get()
	load.Get()
	uptime.Get()
	mem.Get()
	swap.Get()
	plist.Get()
	h := &ProcList{}
	g := &Swap{
		Total: swap.Total,
		Free:  swap.Free,
		Used:  swap.Used,
	}
	f := &Mem{
		Used:       mem.Used,
		ActualFree: mem.ActualFree,
		ActualUsed: mem.ActualUsed,
		Total:      mem.Total,
		Free:       mem.Free,
	}
	e := &Uptime{
		Length: uptime.Length,
	}
	d := &LoadAverage{
		One:     load.One,
		Five:    load.Five,
		Fifteen: load.Fifteen,
	}
	c := &CPUS{}
	b := &DF{}
	a := &Application{
		Hostname:    hostname,
		Time:        time.Now().UTC(),
		DF:          b,
		CPU:         c,
		LoadAverage: d,
		Uptime:      e,
		Mem:         f,
		Swap:        g,
		ProcList:    h,
	}
	for _, fs := range fslist.List {
		dir_name := fs.DirName
		usage := sigar.FileSystemUsage{}
		usage.Get(dir_name)
		b.Data = append(b.Data, &FileSystem{
			FileSystem: fs.DevName,
			Size:       usage.Total,
			Used:       usage.Used,
			Avail:      usage.Avail,
			Percent:    usage.UsePercent(),
			Mounted:    dir_name,
		})
	}

	for _, cpu := range cpulist.List {
		c.Data = append(c.Data, &CpuStat{
			ID:      cpu.Name,
			User:    cpu.User,
			Nice:    cpu.Nice,
			Sys:     cpu.Sys,
			Idle:    cpu.Idle,
			Wait:    cpu.Wait,
			IRQ:     cpu.Irq,
			SoftIRQ: cpu.SoftIrq,
			Stolen:  cpu.Stolen,
		})
	}

	for _, proc := range plist.List {
		pr := sigar.ProcState{}
		pm := sigar.ProcMem{}
		pt := sigar.ProcTime{}
		pa := sigar.ProcArgs{}
		pe := sigar.ProcExe{}
		pr.Get(proc)
		pm.Get(proc)
		pt.Get(proc)
		pa.Get(proc)
		pe.Get(proc)
		procm := &ProcMem{
			Size:        pm.Size,
			Resident:    pm.Resident,
			Share:       pm.Share,
			MinorFaults: pm.MinorFaults,
			MajorFaults: pm.MajorFaults,
			PageFaults:  pm.PageFaults,
		}
		proct := &ProcTime{
			StartTime: pt.StartTime,
			Sys:       pt.Sys,
			Total:     pt.Total,
			User:      pt.User,
		}
		proca := &ProcArgs{
			Arguements: pa.List,
		}
		proce := &ProcExe{
			Name: pe.Name,
			Cwd:  pe.Cwd,
			Root: pe.Root,
		}

		h.List = append(h.List, &ProcState{
			Pid:       proc,
			Name:      pr.Name,
			State:     pr.State,
			Ppid:      pr.Ppid,
			Tty:       pr.Tty,
			Priority:  pr.Priority,
			Nice:      pr.Nice,
			Processor: pr.Processor,
			Memory:    procm,
			Time:      proct,
			Args:      proca,
			Exe:       proce,
		})
	}
	//fmt.Printf("%#v", v)
	session, err := mgo.Dial(dbuser + ":" + dbpass + "@" + dbhost + "/" + dbname)
	if err != nil {
		panic(err)
	}
	defer session.Close()
	db := session.DB(dbname).C(hostname)
	err = db.Insert(a)
	if err != nil {
		panic(err)
	}
	if err != nil {
		fmt.Printf("error: %v\n", err)
	}
}
Esempio n. 25
0
func StartClient(args []string) {
	const config_usage = "Config File to use"
	userHomeDir := "~"

	u, err := user.Current()
	if err == nil {
		userHomeDir = u.HomeDir
	}

	flags := flag.NewFlagSet("start", flag.ExitOnError)
	flags.StringVar(&globals.configFileName, "config", path.Join(userHomeDir, ".asink", "config"), config_usage)
	flags.StringVar(&globals.configFileName, "c", path.Join(userHomeDir, ".asink", "config"), config_usage+" (shorthand)")
	flags.Parse(args)

	//make sure config file's permissions are read-write only for the current user
	if !util.FileExistsAndHasPermissions(globals.configFileName, 384 /*0b110000000*/) {
		fmt.Println("Error: Either the file at " + globals.configFileName + " doesn't exist, or it doesn't have permissions such that the current user is the only one allowed to read and write.")
		return
	}

	config, err := conf.ReadConfigFile(globals.configFileName)
	if err != nil {
		fmt.Println(err)
		fmt.Println("Error reading config file at ", globals.configFileName, ". Does it exist?")
		return
	}

	globals.storage, err = GetStorage(config)
	if err != nil {
		fmt.Println(err)
		return
	}

	globals.syncDir, err = config.GetString("local", "syncdir")
	globals.cacheDir, err = config.GetString("local", "cachedir")
	globals.tmpDir, err = config.GetString("local", "tmpdir")
	globals.rpcSock, err = config.GetString("local", "socket") //TODO make sure this exists

	//make sure all the necessary directories exist
	err = util.EnsureDirExists(globals.syncDir)
	if err != nil {
		panic(err)
	}
	err = util.EnsureDirExists(globals.cacheDir)
	if err != nil {
		panic(err)
	}
	err = util.EnsureDirExists(globals.tmpDir)
	if err != nil {
		panic(err)
	}

	//TODO check errors on server settings
	globals.server, err = config.GetString("server", "host")
	globals.port, err = config.GetInt("server", "port")
	globals.username, err = config.GetString("server", "username")
	globals.password, err = config.GetString("server", "password")

	//TODO check errors on encryption settings
	globals.encrypted, err = config.GetBool("encryption", "enabled")
	if globals.encrypted {
		globals.key, err = config.GetString("encryption", "key")
	}

	globals.db, err = GetAndInitDB(config)
	if err != nil {
		panic(err)
	}

	//spawn goroutine to handle locking file paths
	go PathLocker(globals.db)

	//spawn goroutines to handle local events
	go SendEvents(&globals)
	localFileUpdates := make(chan *asink.Event)
	initialWalkComplete := make(chan int)
	go StartWatching(globals.syncDir, localFileUpdates, initialWalkComplete)

	//spawn goroutines to receive remote events
	remoteFileUpdates := make(chan *asink.Event)
	go GetEvents(&globals, remoteFileUpdates)

	rpcTornDown := make(chan int)
	go StartRPC(globals.rpcSock, rpcTornDown)
	defer func() { <-rpcTornDown }()

	//make chan with which to wait for exit
	exitChan := make(chan int)
	asink.WaitOnExitChan(exitChan)

	//create all the contexts
	startupContext := NewStartupContext(&globals, localFileUpdates, remoteFileUpdates, initialWalkComplete, exitChan)
	normalContext := NewNormalContext(&globals, localFileUpdates, remoteFileUpdates, exitChan)

	//begin running contexts
	err = startupContext.Run()
	if err != nil && ErrorRequiresExit(err) {
		fmt.Println(err)
		if !ErrorWasExit(err) {
			asink.Exit(1)
		}
		return
	}

	err = normalContext.Run()
	if err != nil {
		fmt.Println(err)
		if !ErrorWasExit(err) {
			asink.Exit(1)
		}
	}
}
Esempio n. 26
0
func main() {
	// give us as much parallelism as possible
	runtime.GOMAXPROCS(runtime.NumCPU())

	devMode := flag.Bool("dev", false, "run on port 8080, rather than 8443")
	flag.Parse()

	conf, err := conf.ReadConfigFile("config")
	if err != nil {
		log.Printf("reading config failed: %s\n", err)
		return
	}
	key, err := conf.GetString("", "key")
	if err != nil {
		log.Printf("reading config.key failed: %s", err)
		return
	}
	name, err := conf.GetString("", "cookie-name")
	if err != nil {
		log.Printf("reading config.cookie-name failed: %s", err)
		return
	}
	musicDir, err := conf.GetString("", "music-dir")
	if err != nil {
		log.Printf("reading config.models-dir failed: %s", err)
		return
	}
	if musicDir[:2] == "~/" {
		musicDir = path.Join(os.Getenv("HOME"), musicDir[2:])
	}

	log.Printf("using music in %s\n", musicDir)

	rootHandler := seshcookie.NewSessionHandler(
		&AuthHandler{
			http.FileServer(http.Dir("./static")),
			&authorizer{musicDir},
			&decider{},
		},
		key,
		nil)
	rootHandler.CookieName = name

	http.Handle("/", rootHandler)
	http.Handle("/err/", http.FileServer(http.Dir("./err")))
	http.Handle("/music/", http.StripPrefix("/music",
		http.FileServer(http.Dir(musicDir))))
	http.HandleFunc("/api/", proxyToCnote)
	http.HandleFunc("/pkg/", proxyToGodoc)
	http.HandleFunc("/doc/", proxyToGodoc)

	watch, err := NewDirwatch(musicDir)
	if err != nil {
		log.Printf("NewDirwatch: %r\n", err)
		return
	}
	_ = watch

	if *devMode {
		err = http.ListenAndServe(
			"127.0.0.1:8080",
			nil)
	} else {
		go func() {
			mux := http.NewServeMux()
			mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
				http.Redirect(rw, r, "https://lightswitchrave.net/", 302)
			})
			http.ListenAndServe(":8080", mux)
		}()
		// if we're serving over https, set the secure flag
		// for cookies
		seshcookie.Session.Secure = true
		err = http.ListenAndServeTLS(
			":8443",
			"/home/bpowers/.tls/certchain.pem",
			"/home/bpowers/.tls/boosd.org_key.pem",
			nil)
	}
	if err != nil {
		log.Printf("ListenAndServe:", err)
	}
}
Esempio n. 27
0
func (a *S3Account) Load(file string) {
	c, _ := conf.ReadConfigFile(file)
	a.Host_base, _ = c.GetString("default", "host_base")
	a.access_key, _ = c.GetString("default", "access_key")
	a.secret_key, _ = c.GetString("default", "secret_key")
}
Esempio n. 28
0
File: crud.go Progetto: cyc115/rter
// Generic Create handler
func Create(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)

	user, permissions := auth.Challenge(w, r, true)

	if (user == nil || permissions < 1) && vars["datatype"] != "users" { // Allow anyone to create users for now
		http.Error(w, "Please Login", http.StatusUnauthorized)
		return
	}

	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-PINGOTHER")

	var val interface{} // Generic container for the new object

	// Build a URI like representation of the datatype
	types := []string{vars["datatype"]}

	if childtype, ok := vars["childtype"]; ok {
		types = append(types, childtype)
	}

	// Switch based on that URI like representation and instantiate something in the generic container
	switch strings.Join(types, "/") {
	case "items":
		val = new(data.Item)
	case "items/comments":
		val = new(data.ItemComment)
	case "items/geolocations":
		val = new(data.Geolocation)
	case "users":
		val = new(data.User)
	case "roles":
		val = new(data.Role)
	case "taxonomy":
		val = new(data.Term)
	default:
		http.NotFound(w, r)
		return
	}

	// Perform the JSON decode
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&val)

	if err != nil {
		log.Println(err)
		http.Error(w, "Malformed json.", http.StatusBadRequest)
		return
	}

	// Perform post decode actions, setting automated field, validate values, exectute hooks, etc ...
	switch v := val.(type) {
	case *data.Item:
		v.Author = user.Username
	case *data.ItemComment:
		v.ItemID, err = strconv.ParseInt(vars["key"], 10, 64)
		v.Author = user.Username
	case *data.Geolocation:
		v.ItemID, err = strconv.ParseInt(vars["key"], 10, 64)
	case *data.User:
		err := v.Validate()
		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		v.HashAndSalt()
		v.Role = "public" // TODO: Temporary while anyone can sign up maybe this will change?
	case *data.Term:
		v.Author = user.Username
	}

	if err != nil {
		log.Println(err)
		http.Error(w, "Malformed key in URI", http.StatusBadRequest)
		return
	}

	// Perform the DB insert
	err = storage.Insert(val)

	if err != nil {
		log.Println(err)
		var errorMsg string
		switch dbErr := err.(type) {
		case *storage.StorageError:
			switch dbErr.Code() {
			case 1062:
				switch val.(type) {
				case *data.User:
					errorMsg = "User already exists"
				default:
					errorMsg = "Database entry already exists"
				}
			default:
				errorMsg = "Database error (" + dbErr.Error() + ")"
			}
		default:
			errorMsg = "Insert Database error, likely due to malformed request"
		}
		http.Error(w, errorMsg, http.StatusInternalServerError)
		return
	}

	// Exectute post insert hooks, etc ...
	switch v := val.(type) {
	case *data.Item:
		if v.Type == "streaming-video-v1" {
			c, err := conf.ReadConfigFile("rter.config")
			if err != nil {
				log.Println(err)
				return
			}
			baseUrl, err := c.GetString("videoserver", "base-url")
			if err != nil {
				log.Println(err)
				return
			}
			v.UploadURI = baseUrl + "/v1/ingest/" + strconv.FormatInt(v.ID, 10)
			v.ThumbnailURI = baseUrl + "/v1/videos/" + strconv.FormatInt(v.ID, 10) + "/thumb/000000001.jpg"
			v.ContentURI = baseUrl + "/v1/videos/" + strconv.FormatInt(v.ID, 10)

			host, _, err := net.SplitHostPort(r.RemoteAddr)

			if err != nil {
				log.Println(err)
				http.Error(w, "Problem building streaming tokens, not remote addresse available.", http.StatusBadRequest)
				return
			}

			t, err := token.GenerateToken(v.UploadURI, host, time.Duration(3600)*time.Second, "1122AABBCCDDEEFF")

			if err != nil {
				log.Println(err)
				http.Error(w, "Problem building streaming tokens, likely due to malformed request.", http.StatusInternalServerError)
				return
			}

			v.Token = t

			err = storage.Update(v) //FIXME: This is awful, but probably not workaroundable?

			if err != nil {
				log.Println(err)
				http.Error(w, "Update Database error, likely due to malformed request.", http.StatusInternalServerError)
				return
			}
		}
	}

	w.Header().Set("Content-Type", "application/json") // Header are important when GZIP is enabled
	w.WriteHeader(http.StatusCreated)

	// Return the object we've inserted in the database.
	encoder := json.NewEncoder(w)
	err = encoder.Encode(val)

	if err != nil {
		log.Println(err)
	}
}
Esempio n. 29
0
func (xdg *XDG) readIndex(theme string) error {
	foundValid := false

	for _, dir := range XDG_THEME_DIRS {
		// fmt.Printf("Reading %s/%s\n", dir, theme)

		cfg, err := conf.ReadConfigFile(dir + "/" + theme + "/index.theme")
		if err != nil {
			// fmt.Printf("%s does not have the file we are looking for.\n", dir)
			continue
		}

		foundValid = true

		var it iconTheme

		if it.name, err = cfg.GetString("Icon Theme", "Name"); err != nil {
			// fmt.Printf("Invalid Theme ( Missing Name ) %s\n", theme)
			return fmt.Errorf("Invalid theme %s (Missing: Name)", theme)
		}

		if it.desc, err = cfg.GetString("Icon Theme", "Comment"); err != nil {
			// fmt.Printf("Invalid Theme ( Missing Comment ) %s\n", theme)
			return fmt.Errorf("Invalid theme %s (Missing: Comment)", theme)
		}

		var dirs string

		if dirs, err = cfg.GetString("Icon Theme", "Directories"); err != nil {
			//fmt.Printf("Invalid theme ( Missing Directories ) %s\n", theme)
			return fmt.Errorf("Invalid theme %s (Missing: Directories)", theme)
		}

		for _, d := range strings.Split(dirs, ",") {
			var id iconDir

			var tmp string

			if id.iconSize, err = cfg.GetInt(d, "Size"); err != nil {
				return fmt.Errorf("Invalid theme %s (Missing: Size)", theme)
			}

			if tmp, err = cfg.GetString(d, "Type"); err != nil {
				id.iconType = iconThreshold
			} else {
				if tmp == "Threshold" {
					id.iconType = iconThreshold
				} else if tmp == "Scalable" {
					id.iconType = iconScalable
				} else if tmp == "Fixed" {
					id.iconType = iconFixed
				} else {
					return fmt.Errorf("Invalid theme %s (Invalid IT: %s)", theme, tmp)
				}
			}

			if id.iconType == iconThreshold {
				var tmpInt int

				if tmpInt, err = cfg.GetInt(d, "Threshold"); err != nil {
					tmpInt = 2
				}

				id.iconMinSize = id.iconSize - tmpInt
				id.iconMaxSize = id.iconSize + tmpInt
			} else if id.iconType == iconScalable {
				if id.iconMinSize, err = cfg.GetInt(d, "MinSize"); err != nil {
					id.iconMinSize = id.iconSize
				}
				if id.iconMaxSize, err = cfg.GetInt(d, "MaxSize"); err != nil {
					id.iconMaxSize = id.iconSize
				}
			} else if id.iconType == iconFixed {
				id.iconMinSize = id.iconSize
				id.iconMaxSize = id.iconSize
			}

			id.dirName = dir + "/" + theme + "/" + d

			it.dirs = append(it.dirs, id)
		}

		xdg.iconTheme = append(xdg.iconTheme, it)
	}

	if !foundValid {
		return fmt.Errorf("No such theme: %s", theme)
	}

	return nil
}
Esempio n. 30
0
File: gapp.go Progetto: armen/gapp
func Init(configFile string, externalFuncMap template.FuncMap) {

	var err error

	Config, err = conf.ReadConfigFile(configFile)
	if err != nil {
		log.Fatal(err)
	}

	goMaxProcs, err := Config.GetInt("default", "go-max-procs")
	if err != nil {
		goMaxProcs = 3
	}

	AppRoot, err = Config.GetString("default", "app-root")
	if err != nil {
		AppRoot = os.Getenv("PWD")
	}

	Hostname, err = Config.GetString("default", "hostname")
	if err != nil {
		Hostname = "localhost:8080"
	}

	Host, err := Config.GetString("default", "host")
	if err != nil {
		Host = "localhost"
	}

	Port, err := Config.GetString("default", "port")
	if err != nil {
		Port = "9980"
	}

	secrets, err := Config.GetString("session", "secrets")
	if err != nil {
		log.Fatal(err)
	}

	redisMaxIdle, err := Config.GetInt("redis", "max-idle")
	if err != nil {
		redisMaxIdle = 20
	}

	redisIdleTimeout, err := Config.GetInt("redis", "idle-timeout")
	if err != nil {
		redisIdleTimeout = 240
	}

	build, err := ioutil.ReadFile(path.Join(AppRoot, "conf", "BUILD"))
	if err != nil {
		log.Fatalf("%s - Please make sure BUILD file is created with \"make assets\"", err)
	}
	BuildId = string(bytes.TrimSpace(build))

	RedisPool = &redis.Pool{
		MaxIdle:     redisMaxIdle,
		IdleTimeout: time.Duration(redisIdleTimeout) * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", ":6379")
			if err != nil {
				return nil, err
			}
			return c, err
		},
	}

	// Default funcMap is merged with external funcMap
	funcMap := template.FuncMap{
		"user":         NewUser,
		"humanizeTime": utils.HumanizeTime,
	}

	for funcName, function := range externalFuncMap {
		funcMap[funcName] = function
	}

	runtime.GOMAXPROCS(goMaxProcs)
	DocRoot = path.Join(AppRoot, "templates")
	Address = net.JoinHostPort(Host, Port)
	sessionStore = sessions.NewRedisStore(RedisPool, bytes.Fields([]byte(secrets))...)
	Templates = template.Must(template.New("gapp").Funcs(funcMap).ParseGlob(path.Join(DocRoot, "*.html")))
}