// ocspServerMain is the command line entry point to the OCSP responder.
// It sets up a new HTTP server that responds to OCSP requests.
766818
func ocspServerMain(args []string, c cli.Config) error {
	var src ocsp.Source
	// serve doesn't support arguments.
	if len(args) > 0 {
		return errors.New("argument is provided but not defined; please refer to the usage by flag -h")
	}

	if c.Responses != "" {
		s, err := ocsp.NewSourceFromFile(c.Responses)
		if err != nil {
			return errors.New("unable to read response file")
		}
		src = s
	} else if c.DBConfigFile != "" {
		s, err := ocsp.NewSourceFromDB(c.DBConfigFile)
		if err != nil {
			return errors.New("unable to read configuration file")
		}
		src = s
	} else {
		return errors.New(
			"no response file or db-config provided, please set the one of these using either -responses or -db-config flags",
		)
	}

	log.Info("Registering OCSP responder handler")
	http.Handle(c.Path, ocsp.NewResponder(src, nil))

	addr := fmt.Sprintf("%s:%d", c.Address, c.Port)
	log.Info("Now listening on ", addr)
	return http.ListenAndServe(addr, nil)
}
682278
func main() {
	var svcPath, svcImportPath string
	flag.StringVar(&svcPath, "path", "service",
		"The `path` to generate service clients in to.",
	)
	flag.StringVar(&svcImportPath, "svc-import-path",
		"github.com/aws/aws-sdk-go/service",
		"The Go `import path` to generate client to be under.",
	)
	flag.Usage = usage
	flag.Parse()

	if len(os.Getenv("AWS_SDK_CODEGEN_DEBUG")) != 0 {
		api.LogDebug(os.Stdout)
	}

	// Make sure all paths are based on platform's pathing not Unix
	globs := flag.Args()
	for i, g := range globs {
		globs[i] = filepath.FromSlash(g)
	}
	svcPath = filepath.FromSlash(svcPath)

	modelPaths, err := api.ExpandModelGlobPath(globs...)
	if err != nil {
		fmt.Fprintln(os.Stderr, "failed to glob file pattern", err)
		os.Exit(1)
	}
	modelPaths, _ = api.TrimModelServiceVersions(modelPaths)

	apis, err := api.LoadAPIs(modelPaths, svcImportPath)
	if err != nil {
		fmt.Fprintln(os.Stderr, "failed to load API models", err)
		os.Exit(1)
	}
	if len(apis) == 0 {
		fmt.Fprintf(os.Stderr, "expected to load models, but found none")
		os.Exit(1)
	}

	if v := os.Getenv("SERVICES"); len(v) != 0 {
		svcs := strings.Split(v, ",")
		for pkgName, a := range apis {
			var found bool
			for _, include := range svcs {
				if a.PackageName() == include {
					found = true
					break
				}
			}
			if !found {
				delete(apis, pkgName)
			}
		}
	}

	var wg sync.WaitGroup
	servicePaths := map[string]struct{}{}
	for _, a := range apis {
		if _, ok := excludeServices[a.PackageName()]; ok {
			continue
		}

		// Create the output path for the model.
		pkgDir := filepath.Join(svcPath, a.PackageName())
		os.MkdirAll(filepath.Join(pkgDir, a.InterfacePackageName()), 0775)

		if _, ok := servicePaths[pkgDir]; ok {
			fmt.Fprintf(os.Stderr,
				"attempted to generate a client into %s twice. Second model package, %v\n",
				pkgDir, a.PackageName())
			os.Exit(1)
		}
		servicePaths[pkgDir] = struct{}{}

		g := &generateInfo{
			API:        a,
			PackageDir: pkgDir,
		}

		wg.Add(1)
		go func() {
			defer wg.Done()
			writeServiceFiles(g, pkgDir)
		}()
	}

	wg.Wait()
}
1183519
func main() {
	var l server.ListenConst

	if useDomainSocket {
		l = server.UnixListener(sockPath)
	} else {
		l = server.TCPListener(port)
	}

	protocols := []protocol.Components{binprot.Components, textprot.Components}

	var o orcas.OrcaConst
	var h2 handlers.HandlerConst
	var h1 handlers.HandlerConst

	// Choose the proper L1 handler
	if l1inmem {
		h1 = inmem.New
	} else if chunked {
		h1 = memcached.Chunked(l1sock)
	} else if l1batched {
		h1 = memcached.Batched(l1sock, batchOpts)
	} else {
		h1 = memcached.Regular(l1sock)
	}

	if l2enabled {
		o = orcas.L1L2
		h2 = memcached.Regular(l2sock)
	} else {
		o = orcas.L1Only
		h2 = handlers.NilHandler
	}

	// Add the locking wrapper if requested. The locking wrapper can either allow mutltiple readers
	// or not, with the same difference in semantics between a sync.Mutex and a sync.RWMutex. If
	// chunking is enabled, we want to ensure that stricter locking is enabled, since concurrent
	// sets into L1 with chunking can collide and cause data corruption.
	var lockset uint32
	if locked {
		if chunked || !multiReader {
			o, lockset = orcas.Locked(o, false, uint8(concurrency))
		} else {
			o, lockset = orcas.Locked(o, true, uint8(concurrency))
		}
	}

	go server.ListenAndServe(l, protocols, server.Default, o, h1, h2)

	if l2enabled {
		// If L2 is enabled, start the batch L1 / L2 orchestrator
		l = server.TCPListener(batchPort)
		o := orcas.L1L2Batch

		if locked {
			o = orcas.LockedWithExisting(o, lockset)
		}

		go server.ListenAndServe(l, protocols, server.Default, o, h1, h2)
	}

	// Block forever
	wg := sync.WaitGroup{}
	wg.Add(1)
	wg.Wait()
}
488311
func main() {

	swaggerSpec, err := loads.Embedded(restapi.SwaggerJSON, restapi.FlatSwaggerJSON)
	if err != nil {
		log.Fatalln(err)
	}

	var server *restapi.Server // make sure init is called

	flag.Usage = func() {
		fmt.Fprint(os.Stderr, "Usage:\n")
		fmt.Fprint(os.Stderr, "  todo-list-server [OPTIONS]\n\n")

		title := "Simple To Do List API"
		fmt.Fprint(os.Stderr, title+"\n\n")
		desc := swaggerSpec.Spec().Info.Description
		if desc != "" {
			fmt.Fprintf(os.Stderr, desc+"\n\n")
		}
		fmt.Fprintln(os.Stderr, flag.CommandLine.FlagUsages())
	}
	// parse the CLI flags
	flag.Parse()

	api := operations.NewTodoListAPI(swaggerSpec)
	// get server with flag values filled out
	server = restapi.NewServer(api)

	defer server.Shutdown()

	server.ConfigureAPI()
	if err := server.Serve(); err != nil {
		log.Fatalln(err)
	}

}
468618
func (s *Server) setupRpcServer(server *rpc.Server, ctx *RPCContext) {
	// Add the static endpoints to the RPC server.
	if s.staticEndpoints.Status == nil {
		// Initialize the list just once
		s.staticEndpoints.ACL = &ACL{srv: s, logger: s.logger.Named("acl")}
		s.staticEndpoints.Alloc = &Alloc{srv: s, logger: s.logger.Named("alloc")}
		s.staticEndpoints.Eval = &Eval{srv: s, logger: s.logger.Named("eval")}
		s.staticEndpoints.Job = &Job{srv: s, logger: s.logger.Named("job")}
		s.staticEndpoints.Node = &Node{srv: s, logger: s.logger.Named("client")} // Add but don't register
		s.staticEndpoints.Deployment = &Deployment{srv: s, logger: s.logger.Named("deployment")}
		s.staticEndpoints.Operator = &Operator{srv: s, logger: s.logger.Named("operator")}
		s.staticEndpoints.Periodic = &Periodic{srv: s, logger: s.logger.Named("periodic")}
		s.staticEndpoints.Plan = &Plan{srv: s, logger: s.logger.Named("plan")}
		s.staticEndpoints.Region = &Region{srv: s, logger: s.logger.Named("region")}
		s.staticEndpoints.Status = &Status{srv: s, logger: s.logger.Named("status")}
		s.staticEndpoints.System = &System{srv: s, logger: s.logger.Named("system")}
		s.staticEndpoints.Search = &Search{srv: s, logger: s.logger.Named("search")}
		s.staticEndpoints.Enterprise = NewEnterpriseEndpoints(s)

		// Client endpoints
		s.staticEndpoints.ClientStats = &ClientStats{srv: s, logger: s.logger.Named("client_stats")}
		s.staticEndpoints.ClientAllocations = &ClientAllocations{srv: s, logger: s.logger.Named("client_allocs")}

		// Streaming endpoints
		s.staticEndpoints.FileSystem = &FileSystem{srv: s, logger: s.logger.Named("client_fs")}
		s.staticEndpoints.FileSystem.register()
	}

	// Register the static handlers
	server.Register(s.staticEndpoints.ACL)
	server.Register(s.staticEndpoints.Alloc)
	server.Register(s.staticEndpoints.Eval)
	server.Register(s.staticEndpoints.Job)
	server.Register(s.staticEndpoints.Deployment)
	server.Register(s.staticEndpoints.Operator)
	server.Register(s.staticEndpoints.Periodic)
	server.Register(s.staticEndpoints.Plan)
	server.Register(s.staticEndpoints.Region)
	server.Register(s.staticEndpoints.Status)
	server.Register(s.staticEndpoints.System)
	server.Register(s.staticEndpoints.Search)
	s.staticEndpoints.Enterprise.Register(server)
	server.Register(s.staticEndpoints.ClientStats)
	server.Register(s.staticEndpoints.ClientAllocations)
	server.Register(s.staticEndpoints.FileSystem)

	// Create new dynamic endpoints and add them to the RPC server.
	node := &Node{srv: s, ctx: ctx, logger: s.logger.Named("client")}

	// Register the dynamic endpoints
	server.Register(node)
}
1183147
func (p *ProxyLBCertificates) ParseServerCertificate() (*x509.Certificate, error) {
	cert, e := p.parseCertificate(p.ServerCertificate)
	if e != nil {
		return nil, e
	}
	return cert, nil
}
1064717
func (o Middleware) PublisherMsgInterceptor(serviceName string, next pubsub.PublishHandler) pubsub.PublishHandler {
	return func(ctx context.Context, topic string, m *pubsub.Msg) (err error) {
		defer func() {
			if r := recover(); r != nil {
				err = recoverFrom(r, "pubsub: publish error", o.RecoveryHandlerFunc)
			}
		}()
		err = next(ctx, topic, m)
		return
	}
}
532482
func main() {
	var addr, conf string
	flag.StringVar(&addr, "a", "127.0.0.1:9876", "`address` of server")
	flag.StringVar(&conf, "f", "server.json", "config `file` to use")
	flag.Parse()

	var id = new(core.Identity)
	data, err := ioutil.ReadFile(conf)
	if err != nil {
		exlib.Err(1, err, "reading config file")
	}

	err = json.Unmarshal(data, id)
	if err != nil {
		exlib.Err(1, err, "parsing config file")
	}

	tr, err := transport.New(exlib.Before, id)
	if err != nil {
		exlib.Err(1, err, "creating transport")
	}

	l, err := transport.Listen(addr, tr)
	if err != nil {
		exlib.Err(1, err, "setting up listener")
	}

	var errChan = make(chan error, 0)
	go func(ec <-chan error) {
		for {
			err, ok := <-ec
			if !ok {
				log.Warning("error channel closed, future errors will not be reported")
				break
			}
			log.Errorf("auto update error: %v", err)
		}
	}(errChan)

	log.Info("setting up auto-update")
	go l.AutoUpdate(nil, errChan)

	log.Info("listening on ", addr)
	exlib.Warn(serve(l), "serving listener")
}
258674
func main() {
	if len(os.Args) == 2 && strings.ToLower(os.Args[1]) == "server" {
		ServerLoop()
	} else if len(os.Args) == 2 && strings.ToLower(os.Args[1]) == "client" {
		ClientLoop()
	} else {
		fmt.Println("wsserver [server|client]")
	}
}
622352
func ocsprefreshMain(args []string, c cli.Config) error {
	if c.DBConfigFile == "" {
		return errors.New("need DB config file (provide with -db-config)")
	}

	if c.ResponderFile == "" {
		return errors.New("need responder certificate (provide with -responder)")
	}

	if c.ResponderKeyFile == "" {
		return errors.New("need responder key (provide with -responder-key)")
	}

	if c.CAFile == "" {
		return errors.New("need CA certificate (provide with -ca)")
	}

	s, err := SignerFromConfig(c)
	if err != nil {
		log.Critical("Unable to create OCSP signer: ", err)
		return err
	}

	db, err := dbconf.DBFromConfig(c.DBConfigFile)
	if err != nil {
		return err
	}

	dbAccessor := sql.NewAccessor(db)
	certs, err := dbAccessor.GetUnexpiredCertificates()
	if err != nil {
		return err
	}

	// Set an expiry timestamp for all certificates refreshed in this batch
	ocspExpiry := time.Now().Add(c.Interval)
	for _, certRecord := range certs {
		cert, err := helpers.ParseCertificatePEM([]byte(certRecord.PEM))
		if err != nil {
			log.Critical("Unable to parse certificate: ", err)
			return err
		}

		req := ocsp.SignRequest{
			Certificate: cert,
			Status:      certRecord.Status,
		}

		if certRecord.Status == "revoked" {
			req.Reason = int(certRecord.Reason)
			req.RevokedAt = certRecord.RevokedAt
		}

		resp, err := s.Sign(req)
		if err != nil {
			log.Critical("Unable to sign OCSP response: ", err)
			return err
		}

		err = dbAccessor.UpsertOCSP(cert.SerialNumber.String(), hex.EncodeToString(cert.AuthorityKeyId), string(resp), ocspExpiry)
		if err != nil {
			log.Critical("Unable to save OCSP response: ", err)
			return err
		}
	}

	return nil
}
1284372
func main() {
	// Set up a connection to the server.
	cr, err := credentials.NewClientTLSFromFile("./testdata/out/GearTest.crt", "127.0.0.1")
	if err != nil {
		log.Fatalf("credentials error: %v", err)
	}
	conn, err := grpc.Dial("127.0.0.1:3000", grpc.WithTransportCredentials(cr))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c := pb.NewGreeterClient(conn)

	for i := 0; i < 10; i++ {
		r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: strconv.Itoa(i)})
		if err != nil {
			log.Fatalf("could not greet: %v", err)
		}
		log.Printf("Greeting: %s", r.Message)
	}

	// bench(c)
}
743038
func signerMain(args []string, c cli.Config) (err error) {
	if c.CSRFile == "" {
		c.CSRFile, args, err = cli.PopFirstArgument(args)
		if err != nil {
			return
		}
	}

	var subjectData *signer.Subject
	if len(args) > 0 {
		var subjectFile string
		subjectFile, args, err = cli.PopFirstArgument(args)
		if err != nil {
			return
		}
		if len(args) > 0 {
			return errors.New("too many arguments are provided, please check with usage")
		}

		var subjectJSON []byte
		subjectJSON, err = ioutil.ReadFile(subjectFile)
		if err != nil {
			return
		}

		subjectData = new(signer.Subject)
		err = json.Unmarshal(subjectJSON, subjectData)
		if err != nil {
			return
		}
	}

	csr, err := cli.ReadStdin(c.CSRFile)
	if err != nil {
		return
	}

	// Remote can be forced on the command line or in the config
	if c.Remote == "" && c.CFG == nil {
		if c.CAFile == "" {
			log.Error("need CA certificate (provide one with -ca)")
			return
		}

		if c.CAKeyFile == "" {
			log.Error("need CA key (provide one with -ca-key)")
			return
		}
	}

	s, err := SignerFromConfig(c)
	if err != nil {
		return
	}

	req := signer.SignRequest{
		Hosts:   signer.SplitHosts(c.Hostname),
		Request: string(csr),
		Subject: subjectData,
		Profile: c.Profile,
		Label:   c.Label,
	}
	cert, err := s.Sign(req)
	if err != nil {
		return
	}
	cli.PrintCert(nil, csr, cert)
	return
}
436375
func gcsGatewayMain(ctx *cli.Context) {
	projectID := ctx.Args().First()
	if projectID == "" && os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") == "" {
		logger.LogIf(context.Background(), errGCSProjectIDNotFound)
		cli.ShowCommandHelpAndExit(ctx, "gcs", 1)
	}
	if projectID != "" && !isValidGCSProjectIDFormat(projectID) {
		reqInfo := (&logger.ReqInfo{}).AppendTags("projectID", ctx.Args().First())
		contxt := logger.SetReqInfo(context.Background(), reqInfo)
		logger.LogIf(contxt, errGCSInvalidProjectID)
		cli.ShowCommandHelpAndExit(ctx, "gcs", 1)
	}

	minio.StartGateway(ctx, &GCS{projectID})
}
277939
func initGossipService(policyMgr policies.ChannelPolicyManagerGetter, metricsProvider metrics.Provider,
	peerServer *comm.GRPCServer, serializedIdentity []byte, peerAddr string) error {
	var certs *gossipcommon.TLSCertificates
	if peerServer.TLSEnabled() {
		serverCert := peerServer.ServerCertificate()
		clientCert, err := peer.GetClientCertificate()
		if err != nil {
			return errors.Wrap(err, "failed obtaining client certificates")
		}
		certs = &gossipcommon.TLSCertificates{}
		certs.TLSServerCert.Store(&serverCert)
		certs.TLSClientCert.Store(&clientCert)
	}

	messageCryptoService := peergossip.NewMCS(
		policyMgr,
		localmsp.NewSigner(),
		mgmt.NewDeserializersManager(),
	)
	secAdv := peergossip.NewSecurityAdvisor(mgmt.NewDeserializersManager())
	bootstrap := viper.GetStringSlice("peer.gossip.bootstrap")

	return service.InitGossipService(
		serializedIdentity,
		metricsProvider,
		peerAddr,
		peerServer.Server(),
		certs,
		messageCryptoService,
		secAdv,
		secureDialOpts,
		bootstrap...,
	)
}
1184978
func main() {
	opts := CliOptions{}
	_, err := flags.Parse(&opts)
	if err != nil {
		log.Fatal(err)
	}
	err = config.LoadDotEnvFirst(opts.EnvFile, os.Getenv("ENV_PATH"), "./.env")
	if err != nil {
		log.Fatal(err)
	}
	rcCfg, err := NewRingCentralConfigEnv()
	if err != nil {
		log.Fatal(err)
	}

	fmtutil.PrintJSON(opts)
	fmtutil.PrintJSON(rcCfg)

	apiClient, err := ru.NewApiClientPassword(
		rcCfg.ApplicationCredentials(),
		rcCfg.PasswordCredentials())
	if err != nil {
		log.Fatal(err)
	}

	httpClient := apiClient.HTTPClient()

	if 1 == 0 {
		sendFaxRaw(opts, httpClient)
	}

	if 1 == 1 {
		fmt.Println(opts.Files[0])

		file, err := os.Open(opts.Files[0])
		if err != nil {
			log.Fatal(err)
		}

		params := rc.SendFaxMessageOpts{}
		if len(opts.CoverPageText) > 0 {
			//params.FaxResolution = optional.NewString("High")
			params.CoverPageText = optional.NewString(opts.CoverPageText)
		}
		fmtutil.PrintJSON(opts)
		if 1 == 1 {
			params.Attachment = optional.NewInterface(file)
		}
		info, resp, err := apiClient.MessagesApi.SendFaxMessage(
			context.Background(),
			"~",
			"~",
			opts.To,
			&params)

		if err != nil {
			panic(err)
		} else if resp.StatusCode > 299 {
			panic(fmt.Errorf("API Status %v", resp.StatusCode))
		}
		fmtutil.PrintJSON(info)
	}

	fmt.Println("DONE")
}
1352841
func (n *NIC) primaryEndpoint(protocol tcpip.NetworkProtocolNumber) *referencedNetworkEndpoint {
	n.mu.RLock()
	defer n.mu.RUnlock()

	list := n.primary[protocol]
	if list == nil {
		return nil
	}

	for e := list.Front(); e != nil; e = e.Next() {
		r := e.(*referencedNetworkEndpoint)
		// TODO(crawshaw): allow broadcast address when SO_BROADCAST is set.
		switch r.ep.ID().LocalAddress {
		case header.IPv4Broadcast, header.IPv4Any:
			continue
		}
		if r.tryIncRef() {
			return r
		}
	}

	return nil
}
228581
func (mr *MockRPCServerMockRecorder) StartServer(ctx, protocol, path, handler interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartServer", reflect.TypeOf((*MockRPCServer)(nil).StartServer), ctx, protocol, path, handler)
}