// Gateway デフォルトゲートウェイアドレス
199305
func (s *Server) Gateway() string {
	if len(s.Interfaces) == 0 || s.Interfaces[0].Switch == nil {
		return ""
	}
	if s.Interfaces[0].Switch.UserSubnet != nil {
		return s.Interfaces[0].Switch.UserSubnet.DefaultRoute
	}
	return s.Interfaces[0].Switch.Subnet.DefaultRoute
}
798213
func hexGatewayToAddr(gateway []rune) (string, error) {
	// gateway address is encoded in reverse order in hex
	if len(gateway) != 8 {
		return "", errors.New("invalid gateway length")
	}

	var octets [4]uint8
	for i, hexOctet := range [4]string{
		string(gateway[6:8]), // first octet of IP Address
		string(gateway[4:6]), // second octet
		string(gateway[2:4]), // third octet
		string(gateway[0:2]), // last octet
	} {
		octet, err := strconv.ParseUint(hexOctet, 16, 8)
		if err != nil {
			return "", err
		}

		octets[i] = uint8(octet)
	}

	return fmt.Sprintf("%v.%v.%v.%v", octets[0], octets[1], octets[2], octets[3]), nil
}
580585
func nasGatewayMain(ctx *cli.Context) {
	// Validate gateway arguments.
	if !ctx.Args().Present() || ctx.Args().First() == "help" {
		cli.ShowCommandHelpAndExit(ctx, nasBackend, 1)
	}

	minio.StartGateway(ctx, &NAS{ctx.Args().First()})
}
643116
func (s *VolumeInfo) SetGatewayARN(v string) *VolumeInfo {
	s.GatewayARN = &v
	return s
}
790407
func (s *FileShareInfo) SetGatewayARN(v string) *FileShareInfo {
	s.GatewayARN = &v
	return s
}
588899
func (s *Server) getAllGatewayConnections(conns map[uint64]*client) {
	gw := s.gateway
	gw.RLock()
	for _, c := range gw.out {
		c.mu.Lock()
		cid := c.cid
		c.mu.Unlock()
		conns[cid] = c
	}
	for cid, c := range gw.in {
		conns[cid] = c
	}
	gw.RUnlock()
}
1126928
func (o *Enterprise) NSGateways(info *bambou.FetchingInfo) (NSGatewaysList, *bambou.Error) {

	var list NSGatewaysList
	err := bambou.CurrentSession().FetchChildren(o, NSGatewayIdentity, &list, info)
	return list, err
}
1011784
func (a *Account) StreamGateways() (*GatewayStream, error) {
	body, err := a.gets(a.auth, "/api/v2/gateways")
	if err != nil {
		return nil, err
	}

	stream := &GatewayStream{
		decoder: json.NewDecoder(body),
		body:    body,
	}

	// parse the first array bracket
	_, err = stream.decoder.Token()
	if err != nil {
		return nil, err
	}

	return stream, err
}
575536
func MigrateGatewayStats(p *redis.Pool, db sqlx.Queryer) error {
	log.Info("migrating gateway stats")

	var row struct {
		GatewayID           lorawan.EUI64               `db:"gateway_id"`
		Timestamp           time.Time                   `db:"timestamp"`
		Interval            storage.AggregationInterval `db:"interval"`
		RXPacketsReceived   int                         `db:"rx_packets_received"`
		RXPacketsReceivedOK int                         `db:"rx_packets_received_ok"`
		TXPacketsReceived   int                         `db:"tx_packets_received"`
		TXPacketsEmitted    int                         `db:"tx_packets_emitted"`
	}

	rows, err := db.Queryx(`
		select
			gateway_id,
			timestamp,
			interval,
			rx_packets_received,
			rx_packets_received_ok,
			tx_packets_received,
			tx_packets_emitted
		from
			gateway_stats
		where
			(interval = 'MINUTE' and timestamp >= (now() - interval '65 minutes')) or
			(interval = 'HOUR' and timestamp >= (now() - interval '25 hours')) or
			(interval = 'DAY' and timestamp >= (now() - interval '32 days')) or
			(interval = 'MONTH' and timestamp >= (now() - interval '13 months'))
	`)
	if err != nil {
		return errors.Wrap(err, "select error")
	}
	defer rows.Close()

	for rows.Next() {
		if err := rows.StructScan(&row); err != nil {
			return errors.Wrap(err, "scan error")
		}

		switch row.Interval {
		case storage.AggregationMinute, storage.AggregationHour, storage.AggregationDay, storage.AggregationMonth:
			err = storage.SaveMetricsForInterval(p, row.Interval, "gw:"+row.GatewayID.String(), storage.MetricsRecord{
				Time: row.Timestamp,
				Metrics: map[string]float64{
					"rx_count":    float64(row.RXPacketsReceived),
					"rx_ok_count": float64(row.RXPacketsReceivedOK),
					"tx_count":    float64(row.TXPacketsReceived),
					"tx_ok_count": float64(row.TXPacketsEmitted),
				},
			})
			if err != nil {
				return errors.Wrap(err, "save metrics error")
			}
		}
	}

	log.Info("gateway stats migrated")
	return nil
}
525834
func GatewayTimeout(w http.ResponseWriter, response interface{}) {
	Respond(w, http.StatusGatewayTimeout, response)
}
933380
func StartGateway(ctx *cli.Context, gw Gateway) {
	if gw == nil {
		logger.FatalIf(errUnexpected, "Gateway implementation not initialized")
	}

	// Disable logging until gateway initialization is complete, any
	// error during initialization will be shown as a fatal message
	logger.Disable = true

	// Validate if we have access, secret set through environment.
	gatewayName := gw.Name()
	if ctx.Args().First() == "help" {
		cli.ShowCommandHelpAndExit(ctx, gatewayName, 1)
	}

	// Handle common command args.
	handleCommonCmdArgs(ctx)

	// Get port to listen on from gateway address
	globalMinioHost, globalMinioPort = mustSplitHostPort(globalCLIContext.Addr)

	// On macOS, if a process already listens on LOCALIPADDR:PORT, net.Listen() falls back
	// to IPv6 address ie minio will start listening on IPv6 address whereas another
	// (non-)minio process is listening on IPv4 of given port.
	// To avoid this error situation we check for port availability.
	logger.FatalIf(checkPortAvailability(globalMinioPort), "Unable to start the gateway")

	// Check and load TLS certificates.
	var err error
	globalPublicCerts, globalTLSCerts, globalIsSSL, err = getTLSConfig()
	logger.FatalIf(err, "Invalid TLS certificate file")

	// Check and load Root CAs.
	globalRootCAs, err = getRootCAs(globalCertsCADir.Get())
	logger.FatalIf(err, "Failed to read root CAs (%v)", err)

	// Handle common env vars.
	handleCommonEnvVars()

	// Handle gateway specific env
	handleGatewayEnvVars()

	// Validate if we have access, secret set through environment.
	if !globalIsEnvCreds {
		logger.Fatal(uiErrEnvCredentialsMissingGateway(nil), "Unable to start gateway")
	}

	// Set system resources to maximum.
	logger.LogIf(context.Background(), setMaxResources())

	initNSLock(false) // Enable local namespace lock.

	router := mux.NewRouter().SkipClean(true)

	if globalEtcdClient != nil {
		// Enable STS router if etcd is enabled.
		registerSTSRouter(router)
	}

	enableConfigOps := globalEtcdClient != nil && gatewayName == "nas"
	enableIAMOps := globalEtcdClient != nil

	// Enable IAM admin APIs if etcd is enabled, if not just enable basic
	// operations such as profiling, server info etc.
	registerAdminRouter(router, enableConfigOps, enableIAMOps)

	// Add healthcheck router
	registerHealthCheckRouter(router)

	// Add server metrics router
	registerMetricsRouter(router)

	// Register web router when its enabled.
	if globalIsBrowserEnabled {
		logger.FatalIf(registerWebRouter(router), "Unable to configure web browser")
	}

	// Currently only NAS and S3 gateway support encryption headers.
	encryptionEnabled := gatewayName == "s3" || gatewayName == "nas"

	// Add API router.
	registerAPIRouter(router, encryptionEnabled)

	var getCert certs.GetCertificateFunc
	if globalTLSCerts != nil {
		getCert = globalTLSCerts.GetCertificate
	}

	globalHTTPServer = xhttp.NewServer([]string{globalCLIContext.Addr}, criticalErrorHandler{registerHandlers(router, globalHandlers...)}, getCert)
	globalHTTPServer.UpdateBytesReadFunc = globalConnStats.incInputBytes
	globalHTTPServer.UpdateBytesWrittenFunc = globalConnStats.incOutputBytes
	go func() {
		globalHTTPServerErrorCh <- globalHTTPServer.Start()
	}()

	signal.Notify(globalOSSignalCh, os.Interrupt, syscall.SIGTERM)

	// !!! Do not move this block !!!
	// For all gateways, the config needs to be loaded from env
	// prior to initializing the gateway layer
	{
		// Initialize server config.
		srvCfg := newServerConfig()

		// Override any values from ENVs.
		srvCfg.loadFromEnvs()

		// Load values to cached global values.
		srvCfg.loadToCachedConfigs()

		// hold the mutex lock before a new config is assigned.
		globalServerConfigMu.Lock()
		globalServerConfig = srvCfg
		globalServerConfigMu.Unlock()
	}

	newObject, err := gw.NewGatewayLayer(globalServerConfig.GetCredential())
	if err != nil {
		// Stop watching for any certificate changes.
		globalTLSCerts.Stop()

		globalHTTPServer.Shutdown()
		logger.FatalIf(err, "Unable to initialize gateway backend")
	}

	if enableConfigOps {
		// Create a new config system.
		globalConfigSys = NewConfigSys()

		// Load globalServerConfig from etcd
		logger.LogIf(context.Background(), globalConfigSys.Init(newObject))
	}

	// Load logger subsystem
	loadLoggers()

	// This is only to uniquely identify each gateway deployments.
	globalDeploymentID = os.Getenv("MINIO_GATEWAY_DEPLOYMENT_ID")

	var cacheConfig = globalServerConfig.GetCacheConfig()
	if len(cacheConfig.Drives) > 0 {
		var err error
		// initialize the new disk cache objects.
		globalCacheObjectAPI, err = newServerCacheObjects(cacheConfig)
		logger.FatalIf(err, "Unable to initialize disk caching")
	}

	// Re-enable logging
	logger.Disable = false

	// Create new IAM system.
	globalIAMSys = NewIAMSys()
	if enableIAMOps {
		// Initialize IAM sys.
		logger.LogIf(context.Background(), globalIAMSys.Init(newObject))
	}

	// Create new policy system.
	globalPolicySys = NewPolicySys()

	// Initialize policy system.
	go globalPolicySys.Init(newObject)

	// Create new notification system.
	globalNotificationSys = NewNotificationSys(globalServerConfig, globalEndpoints)
	if globalEtcdClient != nil && newObject.IsNotificationSupported() {
		logger.LogIf(context.Background(), globalNotificationSys.Init(newObject))
	}

	// Encryption support checks in gateway mode.
	{

		if (globalAutoEncryption || GlobalKMS != nil) && !newObject.IsEncryptionSupported() {
			logger.Fatal(errInvalidArgument,
				"Encryption support is requested but (%s) gateway does not support encryption", gw.Name())
		}

		if GlobalGatewaySSE.IsSet() && GlobalKMS == nil {
			logger.Fatal(uiErrInvalidGWSSEEnvValue(nil).Msg("MINIO_GATEWAY_SSE set but KMS is not configured"),
				"Unable to start gateway with SSE")
		}
	}

	// Once endpoints are finalized, initialize the new object api.
	globalObjLayerMutex.Lock()
	globalObjectAPI = newObject
	globalObjLayerMutex.Unlock()

	// Prints the formatted startup message once object layer is initialized.
	if !globalCLIContext.Quiet {
		mode := globalMinioModeGatewayPrefix + gatewayName
		// Check update mode.
		checkUpdate(mode)

		// Print a warning message if gateway is not ready for production before the startup banner.
		if !gw.Production() {
			logger.StartupMessage(colorYellow("               *** Warning: Not Ready for Production ***"))
		}

		// Print gateway startup message.
		printGatewayStartupMessage(getAPIEndpoints(), gatewayName)
	}

	// Set uptime time after object layer has initialized.
	globalBootTime = UTCNow()

	handleSignals()
}
781247
func (e deviceGatewayEdge) To() graph.Node {
	return simple.Node(eui64Int64(e.gatewayID))
}
294942
func (c *client) sendGatewayConnect() {
	tlsRequired := c.gw.cfg.TLSConfig != nil
	url := c.gw.connectURL
	c.gw.connectURL = nil
	var user, pass string
	if userInfo := url.User; userInfo != nil {
		user = userInfo.Username()
		pass, _ = userInfo.Password()
	}
	cinfo := connectInfo{
		Verbose:  false,
		Pedantic: false,
		User:     user,
		Pass:     pass,
		TLS:      tlsRequired,
		Name:     c.srv.info.ID,
		Gateway:  c.srv.getGatewayName(),
	}
	b, err := json.Marshal(cinfo)
	if err != nil {
		panic(err)
	}
	c.sendProto([]byte(fmt.Sprintf(ConProto, b)), true)
}
624208
func (sb *sandbox) getGatewayEndpoint() *endpoint {
	for _, ep := range sb.getConnectedEndpoints() {
		if ep.getNetwork().Type() == "null" || ep.getNetwork().Type() == "host" {
			continue
		}
		if len(ep.Gateway()) != 0 {
			return ep
		}
	}
	return nil
}
888707
func (s *SetLocalConsolePasswordOutput) SetGatewayARN(v string) *SetLocalConsolePasswordOutput {
	s.GatewayARN = &v
	return s
}
534430
func (a *Account) ListGateways() (gateways []Gateway, err error) {
	err = a.get(a.auth, "/api/v2/gateways", &gateways)
	return gateways, err
}
767900
func (o *RedundancyGroup) Gateways(info *bambou.FetchingInfo) (GatewaysList, *bambou.Error) {

	var list GatewaysList
	err := bambou.CurrentSession().FetchChildren(o, GatewayIdentity, &list, info)
	return list, err
}