Пример #1
0
func main() {
	pflag.Parse()

	viper.SetConfigName("config")
	viper.AddConfigPath(".")

	if debug {
		logrus.SetLevel(logrus.DebugLevel)
	}

	if err := viper.ReadInConfig(); err != nil {
		logrus.Fatal(err)
	}

	nick := viper.GetString("twitch.nick")
	pass := viper.GetString("twitch.pass")
	channels := viper.GetStringSlice("twitch.join")
	dbFilename := viper.GetString("database.filename")
	superusers := viper.GetStringSlice("permissions.superusers")

	bot := bot.NewBot(nick, pass, channels, dbFilename, superusers)
	if err := bot.Start(); err != nil {
		logrus.Fatal(err)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	<-c
	fmt.Print("\r\r\b")

	if err := bot.Stop(); err != nil {
		logrus.Fatal(err)
	}
}
Пример #2
0
func ReadDir(path string) []os.FileInfo {
	wd := ""
	p := ""
	if viper.GetString("WorkingDir") != "" {
		wd = viper.GetString("WorkingDir")
	}
	if strings.Contains(path, "..") {
		jww.ERROR.Printf("Path %s contains parent directory marker", path)
		return nil
	}
	if filepath.IsAbs(path) {
		jww.ERROR.Printf("Path %s is an absolute path", path)
		return nil
	}

	p = filepath.Clean(path)
	p = filepath.Join(wd, p)

	list, err := ioutil.ReadDir(p)
	if err != nil {
		jww.ERROR.Printf("Failed to read Directory %s with error message %s", path, err)
		return nil
	}
	return list
}
Пример #3
0
func build(watches ...bool) error {

	// Hugo writes the output to memory instead of the disk
	// This is only used for benchmark testing. Cause the content is only visible
	// in memory
	if renderToMemory {
		hugofs.DestinationFS = new(afero.MemMapFs)
		// Rendering to memoryFS, publish to Root regardless of publishDir.
		viper.Set("PublishDir", "/")
	}

	if err := copyStatic(); err != nil {
		return fmt.Errorf("Error copying static files to %s: %s", helpers.AbsPathify(viper.GetString("PublishDir")), err)
	}
	watch := false
	if len(watches) > 0 && watches[0] {
		watch = true
	}
	if err := buildSite(buildWatch || watch); err != nil {
		return fmt.Errorf("Error building site: %s", err)
	}

	if buildWatch {
		jww.FEEDBACK.Println("Watching for changes in", helpers.AbsPathify(viper.GetString("ContentDir")))
		jww.FEEDBACK.Println("Press Ctrl+C to stop")
		utils.CheckErr(NewWatcher(0))
	}

	return nil
}
Пример #4
0
func copyStatic() error {
	staticDir := helpers.AbsPathify(viper.GetString("StaticDir")) + "/"
	if _, err := os.Stat(staticDir); os.IsNotExist(err) {
		jww.ERROR.Println("Unable to find Static Directory:", staticDir)
		return nil
	}

	publishDir := helpers.AbsPathify(viper.GetString("PublishDir")) + "/"

	syncer := fsync.NewSyncer()
	syncer.NoTimes = viper.GetBool("notimes")
	syncer.SrcFs = hugofs.SourceFs
	syncer.DestFs = hugofs.DestinationFS

	themeDir, err := helpers.GetThemeStaticDirPath()
	if err != nil {
		jww.ERROR.Println(err)
		return nil
	}

	if themeDir != "" {
		// Copy Static to Destination
		jww.INFO.Println("syncing from", themeDir, "to", publishDir)
		utils.CheckErr(syncer.Sync(publishDir, themeDir), fmt.Sprintf("Error copying static files of theme to %s", publishDir))
	}

	// Copy Static to Destination
	jww.INFO.Println("syncing from", staticDir, "to", publishDir)
	return syncer.Sync(publishDir, staticDir)
}
Пример #5
0
func loadConfig(filenamePath *string, filename *string) {
	log := logging.MustGetLogger("log")

	viper.SetConfigName(*filename)
	viper.AddConfigPath(*filenamePath)

	if err := viper.ReadInConfig(); err != nil {
		log.Critical("Unable to load config file:", err)
		os.Exit(1)
	}

	switch viper.GetString("logtype") {
	case "critical":
		logging.SetLevel(0, "")
	case "error":
		logging.SetLevel(1, "")
	case "warning":
		logging.SetLevel(2, "")
	case "notice":
		logging.SetLevel(3, "")
	case "info":
		logging.SetLevel(4, "")
	case "debug":
		logging.SetLevel(5, "")
		log.Debug("\"debug\" is selected")
	default:
		logging.SetLevel(2, "")
		//log.Debug("\"default\" is selected (warning)")
	}

	log.Debug("loadConfig func:")
	log.Debug("  path: %s", *filenamePath)
	log.Debug("  filename: %s", *filename)
	log.Debug("  logtype in file config is \"%s\"", viper.GetString("logtype"))
}
Пример #6
0
func main() {
	viper.SetConfigName("config")
	viper.AddConfigPath(".")
	err := viper.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	urls := viper.GetStringMapString("urls")
	username := viper.GetString("auth.username")
	password := viper.GetString("auth.password")

	for title, url := range urls {
		c := Checker{
			Title:    title,
			URL:      url,
			Username: username,
			Password: password,
		}

		go func() {
			for {
				if err := c.Check(); err != nil {
					log.Println(err)
				}
				time.Sleep(time.Second * 5)
			}
		}()
	}

	select {}
}
Пример #7
0
func FindArchetype(kind string) (outpath string) {
	search := []string{helpers.AbsPathify(viper.GetString("archetypeDir"))}

	if viper.GetString("theme") != "" {
		themeDir := path.Join(helpers.AbsPathify("themes/"+viper.GetString("theme")), "/archetypes/")
		if _, err := os.Stat(themeDir); os.IsNotExist(err) {
			jww.ERROR.Println("Unable to find archetypes directory for theme :", viper.GetString("theme"), "in", themeDir)
		} else {
			search = append(search, themeDir)
		}
	}

	for _, x := range search {
		// If the new content isn't in a subdirectory, kind == "".
		// Therefore it should be excluded otherwise `is a directory`
		// error will occur. github.com/spf13/hugo/issues/411
		var pathsToCheck []string

		if kind == "" {
			pathsToCheck = []string{"default.md", "default"}
		} else {
			pathsToCheck = []string{kind + ".md", kind, "default.md", "default"}
		}
		for _, p := range pathsToCheck {
			curpath := path.Join(x, p)
			jww.DEBUG.Println("checking", curpath, "for archetypes")
			if exists, _ := helpers.Exists(curpath); exists {
				jww.INFO.Println("curpath: " + curpath)
				return curpath
			}
		}
	}

	return ""
}
Пример #8
0
// ResetSystemUser reset password for a system user
func (*UsersController) ResetSystemUser(ctx *gin.Context) {
	var systemUserJSON resetSystemUserJSON
	ctx.Bind(&systemUserJSON)

	if !strings.HasPrefix(systemUserJSON.Username, "tat.system") {
		AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("Username does not begin with tat.system (%s), it's not possible to reset password for this user", systemUserJSON.Username))
		return
	}

	var systemUserToReset = models.User{}
	err := systemUserToReset.FindByUsername(systemUserJSON.Username)
	if err != nil {
		AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("user with username %s does not exist", systemUserJSON.Username))
		return
	}

	if !systemUserToReset.IsSystem {
		AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("user with username %s is not a system user", systemUserJSON.Username))
		return
	}

	newPassword, err := systemUserToReset.ResetSystemUserPassword()
	if err != nil {
		AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("Reset password for %s (system user) failed", systemUserJSON.Username))
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"message":  "Reset password successfull",
		"username": systemUserToReset.Username,
		"password": newPassword,
		"url":      fmt.Sprintf("%s://%s:%s%s", viper.GetString("exposed_scheme"), viper.GetString("exposed_host"), viper.GetString("exposed_port"), viper.GetString("exposed_path")),
	})
}
Пример #9
0
Файл: store.go Проект: ovh/tat
// getDbParameter gets value of tat parameter
// return values if not "" AND not "false"
// used by db_user, db_password and db_rs_tags
func getDbParameter(key string) string {
	value := ""
	if viper.GetString(key) != "" && viper.GetString(key) != "false" {
		value = viper.GetString(key)
	}
	return value
}
Пример #10
0
// Verify is called by user, after receive email to validate his account
func (u *UsersController) Verify(ctx *gin.Context) {
	var user = &models.User{}
	username, err := GetParam(ctx, "username")
	if err != nil {
		return
	}
	tokenVerify, err := GetParam(ctx, "tokenVerify")
	if err != nil {
		return
	}
	if username != "" && tokenVerify != "" {
		isNewUser, password, err := user.Verify(username, tokenVerify)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"info": fmt.Sprintf("Error on verify token for username %s %s", username, err.Error())})
		} else {
			ctx.JSON(http.StatusOK, gin.H{
				"message":  "Verification successfull",
				"username": username,
				"password": password,
				"url":      fmt.Sprintf("%s://%s:%s%s", viper.GetString("exposed_scheme"), viper.GetString("exposed_host"), viper.GetString("exposed_port"), viper.GetString("exposed_path")),
			})

			if isNewUser {
				go models.WSUser(&models.WSUserJSON{Action: "verify", Username: username})
			}
		}
	} else {
		ctx.JSON(http.StatusBadRequest, gin.H{"info": fmt.Sprintf("username %s or token empty", username)})
	}
}
Пример #11
0
// Convert a "normal" user to a "system" user
func (*UsersController) Convert(ctx *gin.Context) {
	var convertJSON convertUserJSON
	ctx.Bind(&convertJSON)

	if !strings.HasPrefix(convertJSON.Username, "tat.system") {
		AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("Username does not begin with tat.system (%s), it's not possible to convert this user", convertJSON.Username))
		return
	}

	var userToConvert = models.User{}
	err := userToConvert.FindByUsername(convertJSON.Username)
	if err != nil {
		AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("user with username %s does not exist", convertJSON.Username))
		return
	}

	if userToConvert.IsSystem {
		AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("user with username %s is already a system user", convertJSON.Username))
		return
	}

	newPassword, err := userToConvert.ConvertToSystem(utils.GetCtxUsername(ctx), convertJSON.CanWriteNotifications)
	if err != nil {
		AbortWithReturnError(ctx, http.StatusBadRequest, fmt.Errorf("Convert %s to system user failed", convertJSON.Username))
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"message":  "Verification successfull",
		"username": userToConvert.Username,
		"password": newPassword,
		"url":      fmt.Sprintf("%s://%s:%s%s", viper.GetString("exposed_scheme"), viper.GetString("exposed_host"), viper.GetString("exposed_port"), viper.GetString("exposed_path")),
	})
}
Пример #12
0
func setupLogging() {
	switch viper.GetString("log-level") {
	case "debug":
		log.SetLevel(log.DebugLevel)
	case "info":
		log.SetLevel(log.InfoLevel)
	case "warn":
		log.SetLevel(log.WarnLevel)
	case "error":
		log.SetLevel(log.ErrorLevel)
	case "fatal":
		log.SetLevel(log.FatalLevel)
	default:
		log.WithField("log-level", viper.GetString("log-level")).Warning("invalid log level. defaulting to info.")
		log.SetLevel(log.InfoLevel)
	}

	switch viper.GetString("log-format") {
	case "text":
		log.SetFormatter(new(log.TextFormatter))
	case "json":
		log.SetFormatter(new(log.JSONFormatter))
	default:
		log.WithField("log-format", viper.GetString("log-format")).Warning("invalid log format. defaulting to text.")
		log.SetFormatter(new(log.TextFormatter))
	}
}
Пример #13
0
func parseDefaultPygmentsOpts() (map[string]string, error) {

	options := make(map[string]string)
	err := parseOptions(options, viper.GetString("PygmentsOptions"))
	if err != nil {
		return nil, err
	}

	if viper.IsSet("PygmentsStyle") {
		options["style"] = viper.GetString("PygmentsStyle")
	}

	if viper.IsSet("PygmentsUseClasses") {
		if viper.GetBool("PygmentsUseClasses") {
			options["noclasses"] = "false"
		} else {
			options["noclasses"] = "true"
		}

	}

	if _, ok := options["encoding"]; !ok {
		options["encoding"] = "utf8"
	}

	return options, nil
}
Пример #14
0
Файл: initDB.go Проект: WnP/zut
func Initdb() *gorm.DB {
	log := logging.MustGetLogger("log")

	log.Debug("db path: %s", viper.GetString("db.path"))
	log.Debug("db filename: %s", viper.GetString("db.filename"))

	db, err := gorm.Open(
		"sqlite3",
		filepath.Join(
			viper.GetString("db.path"),
			viper.GetString("db.filename"),
		),
	)
	if err != nil {
		log.Critical("Unable to open db file: %s", err)
		os.Exit(1)
	}
	if viper.GetString("logtype") == "debug" {
		db.LogMode(viper.GetBool("debug"))
	}
	db.CreateTable(new(Temperature))
	db.DB().Ping()

	return &db
}
Пример #15
0
func copyStatic() error {
	publishDir := helpers.AbsPathify(viper.GetString("PublishDir")) + "/"

	// If root, remove the second '/'
	if publishDir == "//" {
		publishDir = "/"
	}

	syncer := fsync.NewSyncer()
	syncer.NoTimes = viper.GetBool("notimes")
	syncer.SrcFs = hugofs.SourceFs
	syncer.DestFs = hugofs.DestinationFS

	themeDir, err := helpers.GetThemeStaticDirPath()
	if err != nil {
		jww.ERROR.Println(err)
		return nil
	}

	// Copy the theme's static directory
	if themeDir != "" {
		jww.INFO.Println("syncing from", themeDir, "to", publishDir)
		utils.CheckErr(syncer.Sync(publishDir, themeDir), fmt.Sprintf("Error copying static files of theme to %s", publishDir))
	}

	// Copy the site's own static directory
	staticDir := helpers.AbsPathify(viper.GetString("StaticDir")) + "/"
	if _, err := os.Stat(staticDir); err == nil {
		jww.INFO.Println("syncing from", staticDir, "to", publishDir)
		return syncer.Sync(publishDir, staticDir)
	} else if os.IsNotExist(err) {
		jww.WARN.Println("Unable to find Static Directory:", staticDir)
	}
	return nil
}
Пример #16
0
func registerChaincodeSupport(chainname chaincode.ChainName, grpcServer *grpc.Server,
	secHelper crypto.Peer) {

	//get user mode
	userRunsCC := false
	if viper.GetString("chaincode.mode") == chaincode.DevModeUserRunsChaincode {
		userRunsCC = true
	}

	//get chaincode startup timeout
	tOut, err := strconv.Atoi(viper.GetString("chaincode.startuptimeout"))
	if err != nil { //what went wrong ?
		fmt.Printf("could not retrive timeout var...setting to 5secs\n")
		tOut = 5000
	}
	ccStartupTimeout := time.Duration(tOut) * time.Millisecond

	ccSrv := chaincode.NewChaincodeSupport(chainname, peer.GetPeerEndpoint, userRunsCC,
		ccStartupTimeout, secHelper)

	//Now that chaincode is initialized, register all system chaincodes.
	system_chaincode.RegisterSysCCs()

	pb.RegisterChaincodeSupportServer(grpcServer, ccSrv)
}
Пример #17
0
//newEventsClientConnectionWithAddress Returns a new grpc.ClientConn to the configured local PEER.
func newEventsClientConnectionWithAddress(peerAddress string) (*grpc.ClientConn, error) {
	var opts []grpc.DialOption
	if peer.TLSEnabled() {
		var sn string
		if viper.GetString("peer.tls.serverhostoverride") != "" {
			sn = viper.GetString("peer.tls.serverhostoverride")
		}
		var creds credentials.TransportAuthenticator
		if viper.GetString("peer.tls.cert.file") != "" {
			var err error
			creds, err = credentials.NewClientTLSFromFile(viper.GetString("peer.tls.cert.file"), sn)
			if err != nil {
				grpclog.Fatalf("Failed to create TLS credentials %v", err)
			}
		} else {
			creds = credentials.NewClientTLSFromCert(nil, sn)
		}
		opts = append(opts, grpc.WithTransportCredentials(creds))
	}
	opts = append(opts, grpc.WithTimeout(defaultTimeout))
	opts = append(opts, grpc.WithBlock())
	opts = append(opts, grpc.WithInsecure())

	return grpc.Dial(peerAddress, opts...)
}
Пример #18
0
//this should be called exactly once and the result cached
//NOTE- this crypto func might rightly belong in a crypto package
//and universally accessed
func getSecHelper() (crypto.Peer, error) {
	var secHelper crypto.Peer
	var err error
	once.Do(func() {
		if core.SecurityEnabled() {
			enrollID := viper.GetString("security.enrollID")
			enrollSecret := viper.GetString("security.enrollSecret")
			if peer.ValidatorEnabled() {
				logger.Debugf("Registering validator with enroll ID: %s", enrollID)
				if err = crypto.RegisterValidator(enrollID, nil, enrollID, enrollSecret); nil != err {
					return
				}
				logger.Debugf("Initializing validator with enroll ID: %s", enrollID)
				secHelper, err = crypto.InitValidator(enrollID, nil)
				if nil != err {
					return
				}
			} else {
				logger.Debugf("Registering non-validator with enroll ID: %s", enrollID)
				if err = crypto.RegisterPeer(enrollID, nil, enrollID, enrollSecret); nil != err {
					return
				}
				logger.Debugf("Initializing non-validator with enroll ID: %s", enrollID)
				secHelper, err = crypto.InitPeer(enrollID, nil)
				if nil != err {
					return
				}
			}
		}
	})
	return secHelper, err
}
Пример #19
0
func (s *Site) initializeSiteInfo() {
	params := viper.GetStringMap("Params")

	permalinks := make(PermalinkOverrides)
	for k, v := range viper.GetStringMapString("Permalinks") {
		permalinks[k] = PathPattern(v)
	}

	s.Info = SiteInfo{
		BaseURL:               template.URL(helpers.SanitizeURLKeepTrailingSlash(viper.GetString("BaseURL"))),
		Title:                 viper.GetString("Title"),
		Author:                viper.GetStringMap("author"),
		Social:                viper.GetStringMapString("social"),
		LanguageCode:          viper.GetString("languagecode"),
		Copyright:             viper.GetString("copyright"),
		DisqusShortname:       viper.GetString("DisqusShortname"),
		BuildDrafts:           viper.GetBool("BuildDrafts"),
		canonifyURLs:          viper.GetBool("CanonifyURLs"),
		preserveTaxonomyNames: viper.GetBool("PreserveTaxonomyNames"),
		Pages:      &s.Pages,
		Menus:      &s.Menus,
		Params:     params,
		Permalinks: permalinks,
		Data:       &s.Data,
	}
}
Пример #20
0
func signResponse(w http.ResponseWriter, username string) {
	// @TODO: Store the username in the cookie (in cleartext) so it can be used afterwards
	cookieMaxAge := time.Duration(viper.GetInt("cookiemaxage")) * time.Hour

	expiration := fmt.Sprintf("%v", int(time.Now().Unix())+int(cookieMaxAge.Seconds()))
	mac := hmac.New(sha1.New, []byte(viper.GetString("cookiesecret")))
	mac.Write([]byte(expiration))
	hash := fmt.Sprintf("%x", mac.Sum(nil))
	value := fmt.Sprintf("%v:%v", expiration, hash)

	cookieContent := fmt.Sprintf("%v=%v", "mycookie", value)
	expire := time.Now().Add(cookieMaxAge)
	cookie := http.Cookie{"mycookie",
		value,
		"/",
		viper.GetString("domain"),
		expire,
		expire.Format(time.UnixDate),
		int(cookieMaxAge.Seconds()),
		secureCookie,
		true,
		cookieContent,
		[]string{cookieContent},
	}
	http.SetCookie(w, &cookie)
}
Пример #21
0
func serve(port int) {
	jww.FEEDBACK.Println("Serving pages from " + helpers.AbsPathify(viper.GetString("PublishDir")))

	httpFs := &afero.HttpFs{SourceFs: hugofs.DestinationFS}
	fileserver := http.FileServer(httpFs.Dir(helpers.AbsPathify(viper.GetString("PublishDir"))))

	u, err := url.Parse(viper.GetString("BaseUrl"))
	if err != nil {
		jww.ERROR.Fatalf("Invalid BaseUrl: %s", err)
	}
	if u.Path == "" || u.Path == "/" {
		http.Handle("/", fileserver)
	} else {
		http.Handle(u.Path, http.StripPrefix(u.Path, fileserver))
	}

	u.Scheme = "http"
	jww.FEEDBACK.Printf("Web Server is available at %s\n", u.String())
	fmt.Println("Press Ctrl+C to stop")

	err = http.ListenAndServe(":"+strconv.Itoa(port), nil)
	if err != nil {
		jww.ERROR.Printf("Error: %s\n", err.Error())
		os.Exit(1)
	}
}
Пример #22
0
func run(cmd *cobra.Command, args []string) {
	// Message hub
	hub := NewHub()
	go hub.Run()

	// Websocket Service
	ws := NewWSService(hub)

	// Connect to STOMP
	addr := fmt.Sprintf("%v:%v", viper.GetString("addr"), viper.GetString("port"))
	sub, err := feed(addr, viper.GetString("user"), viper.GetString("key"))
	if err != nil {
		panic(err)
	}

	// Get messages
	go func() {
		for {
			msg := <-sub.C

			if err := msg.Conn.Ack(msg); err != nil {
				fmt.Println("Faild to ACK Message")
			}

			fmt.Println("-----------------------------")
			if msg.Body != nil {
				fmt.Println(string(msg.Body[:]))
				Process(msg.Body, hub)
			}
			fmt.Println("-----------------------------")
		}
	}()

	http.ListenAndServe(":5000", ws)
}
Пример #23
0
// setRomanaRootURL sanitizes rootURL and rootPort and also
// sets baseURL which is needed to connect to other romana
// services.
func setRomanaRootURL() {
	// Variables used for configuration and flags.
	var baseURL string
	var rootURL string
	var rootPort string

	// Add port details to rootURL else try localhost
	// if nothing is given on command line or config.
	rootURL = config.GetString("RootURL")
	rootPort = config.GetString("RootPort")
	if rootPort == "" {
		re, _ := regexp.Compile(`:\d+/?`)
		port := re.FindString(rootURL)
		port = strings.TrimPrefix(port, ":")
		port = strings.TrimSuffix(port, "/")
		if port != "" {
			rootPort = port
		} else {
			rootPort = "9600"
		}
	}
	config.Set("RootPort", rootPort)
	if rootURL != "" {
		baseURL = strings.TrimSuffix(rootURL, "/")
		baseURL = strings.TrimSuffix(baseURL, ":9600")
		baseURL = strings.TrimSuffix(baseURL, ":"+rootPort)
	} else {
		baseURL = "http://localhost"
	}
	config.Set("BaseURL", baseURL)
	rootURL = baseURL + ":" + rootPort + "/"
	config.Set("RootURL", rootURL)
}
Пример #24
0
func initInjector(cmd *cobra.Command, args []string) {
	db, err := sqlx.Connect("postgres", viper.GetString("postgres-url"))
	if err != nil {
		fail(err)
	}

	mustProvide(inject.Object{Value: &drivers.DB})
	mustProvide(inject.Object{Value: &drivers.Horizon})
	mustProvide(inject.Object{Value: &uis.Console})
	mustProvide(inject.Object{Value: &drivers.Editor})
	mustProvide(inject.Object{Value: &drivers.HTTP})
	mustProvide(inject.Object{Value: db})
	mustProvide(inject.Object{
		Name:  "postgres-url",
		Value: viper.GetString("postgres-url"),
	})
	mustProvide(inject.Object{
		Name:  "horizon-url",
		Value: viper.GetString("horizon-url"),
	})

	if err := injector.Populate(); err != nil {
		fail(err)
	}
}
Пример #25
0
func startTLSCA(t *testing.T) {
	LogInit(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr, os.Stdout)

	eca_s = NewECA()
	tlsca_s = NewTLSCA(eca_s)

	var opts []grpc.ServerOption
	creds, err := credentials.NewServerTLSFromFile(viper.GetString("server.tls.certfile"), viper.GetString("server.tls.keyfile"))
	if err != nil {
		t.Logf("Failed creating credentials for TLS-CA service: %s", err)
		t.Fail()
	}

	opts = []grpc.ServerOption{grpc.Creds(creds)}

	srv = grpc.NewServer(opts...)

	eca_s.Start(srv)
	tlsca_s.Start(srv)

	sock, err := net.Listen("tcp", viper.GetString("server.port"))
	if err != nil {
		t.Logf("Failed to start TLS-CA service: %s", err)
		t.Fail()
	}

	srv.Serve(sock)
}
Пример #26
0
// Init initializes the crypto layer. It load from viper the security level
// and the logging setting.
func Init() (err error) {
	// Init log
	log.ExtraCalldepth++

	level, err := logging.LogLevel(viper.GetString("logging.crypto"))
	if err == nil {
		// No error, use the setting
		logging.SetLevel(level, "crypto")
		log.Info("Log level recognized '%s', set to %s", viper.GetString("logging.crypto"),
			logging.GetLevel("crypto"))
	} else {
		log.Warning("Log level not recognized '%s', defaulting to %s: %s", viper.GetString("logging.crypto"),
			logging.GetLevel("crypto"), err)
	}

	// Init security level

	securityLevel := 256
	if viper.IsSet("security.level") {
		ovveride := viper.GetInt("security.level")
		if ovveride != 0 {
			securityLevel = ovveride
		}
	}
	log.Debug("Working at security level [%d]", securityLevel)
	if err = conf.InitSecurityLevel(securityLevel); err != nil {
		log.Debug("Failed setting security level: [%s]", err)

		return
	}

	return
}
Пример #27
0
func createEventHubServer() (net.Listener, *grpc.Server, error) {
	var lis net.Listener
	var grpcServer *grpc.Server
	var err error
	if viper.GetBool("peer.validator.enabled") {
		lis, err = net.Listen("tcp", viper.GetString("peer.validator.events.address"))
		if err != nil {
			return nil, nil, fmt.Errorf("failed to listen: %v", err)
		}

		//TODO - do we need different SSL material for events ?
		var opts []grpc.ServerOption
		if viper.GetBool("peer.tls.enabled") {
			creds, err := credentials.NewServerTLSFromFile(viper.GetString("peer.tls.cert.file"), viper.GetString("peer.tls.key.file"))
			if err != nil {
				return nil, nil, fmt.Errorf("Failed to generate credentials %v", err)
			}
			opts = []grpc.ServerOption{grpc.Creds(creds)}
		}

		grpcServer = grpc.NewServer(opts...)
		ehServer := producer.NewOpenchainEventsServer(uint(viper.GetInt("peer.validator.events.buffersize")), viper.GetInt("peer.validator.events.timeout"))
		pb.RegisterOpenchainEventsServer(grpcServer, ehServer)
	}
	return lis, grpcServer, err
}
Пример #28
0
func startPKI() {
	var opts []grpc.ServerOption
	if viper.GetBool("peer.pki.tls.enabled") {
		// TLS configuration
		creds, err := credentials.NewServerTLSFromFile(
			filepath.Join(viper.GetString("server.rootpath"), "tlsca.cert"),
			filepath.Join(viper.GetString("server.rootpath"), "tlsca.priv"),
		)
		if err != nil {
			panic("Failed creating credentials for OBC-CA: " + err.Error())
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}

	fmt.Printf("open socket...\n")
	sockp, err := net.Listen("tcp", viper.GetString("server.port"))
	if err != nil {
		panic("Cannot open port: " + err.Error())
	}
	fmt.Printf("open socket...done\n")

	server = grpc.NewServer(opts...)

	eca.Start(server)
	tca.Start(server)
	tlsca.Start(server)

	fmt.Printf("start serving...\n")
	server.Serve(sockp)
}
Пример #29
0
func serve(port int) {
	jww.FEEDBACK.Println("Serving pages from " + helpers.AbsPathify(viper.GetString("PublishDir")))

	httpFs := &afero.HttpFs{SourceFs: hugofs.DestinationFS}
	fs := filesOnlyFs{httpFs.Dir(helpers.AbsPathify(viper.GetString("PublishDir")))}
	fileserver := http.FileServer(fs)

	// We're only interested in the path
	u, err := url.Parse(viper.GetString("BaseURL"))
	if err != nil {
		jww.ERROR.Fatalf("Invalid BaseURL: %s", err)
	}
	if u.Path == "" || u.Path == "/" {
		http.Handle("/", fileserver)
	} else {
		http.Handle(u.Path, http.StripPrefix(u.Path, fileserver))
	}

	u.Scheme = "http"
	jww.FEEDBACK.Printf("Web Server is available at %s (bind address %s)\n", u.String(), serverInterface)
	fmt.Println("Press Ctrl+C to stop")

	endpoint := net.JoinHostPort(serverInterface, strconv.Itoa(port))
	err = http.ListenAndServe(endpoint, nil)
	if err != nil {
		jww.ERROR.Printf("Error: %s\n", err.Error())
		os.Exit(1)
	}
}
Пример #30
0
func newPeerClientConnection() (*grpc.ClientConn, error) {
	var opts []grpc.DialOption
	if viper.GetBool("peer.tls.enabled") {
		var sn string
		if viper.GetString("peer.tls.serverhostoverride") != "" {
			sn = viper.GetString("peer.tls.serverhostoverride")
		}
		var creds credentials.TransportAuthenticator
		if viper.GetString("peer.tls.cert.file") != "" {
			var err error
			creds, err = credentials.NewClientTLSFromFile(viper.GetString("peer.tls.cert.file"), sn)
			if err != nil {
				grpclog.Fatalf("Failed to create TLS credentials %v", err)
			}
		} else {
			creds = credentials.NewClientTLSFromCert(nil, sn)
		}
		opts = append(opts, grpc.WithTransportCredentials(creds))
	}
	opts = append(opts, grpc.WithTimeout(1*time.Second))
	opts = append(opts, grpc.WithBlock())
	opts = append(opts, grpc.WithInsecure())
	conn, err := grpc.Dial(getPeerAddress(), opts...)
	if err != nil {
		return nil, err
	}
	return conn, err
}