func (api *privetAPI) accesstoken(w http.ResponseWriter, r *http.Request) {
	log.Debugf("Received /accesstoken request: %+v", r)
	if ok := api.checkRequest(w, r, "GET"); !ok {
		return
	}

	user := r.Form.Get("user")
	if len(user) == 0 {
		writeError(w, "invalid_params", "user parameter expected")
		return
	}

	responseBody, httpStatusCode, err := api.getProximityToken(api.gcpID, user)
	if err != nil {
		log.Errorf("Failed to get proximity token: %s", err)
	}

	if responseBody == nil || len(responseBody) == 0 {
		log.Warning("Cloud returned empty response body")
		writeError(w, "server_error", "Check connector logs")
		return
	}

	var response struct {
		Success        bool                   `json:"success"`
		Message        string                 `json:"message"`
		ErrorCode      int                    `json:"errorCode"`
		ProximityToken map[string]interface{} `json:"proximity_token"`
	}
	if err = json.Unmarshal(responseBody, &response); err != nil {
		log.Errorf("Failed to unmarshal ticket from cloud: %s", err)
		writeError(w, "server_error", "Check connector logs")
		return
	}

	if response.Success {
		token, err := json.MarshalIndent(response.ProximityToken, "", "  ")
		if err != nil {
			log.Errorf("Failed to marshal something that was just unmarshalled: %s", err)
			writeError(w, "server_error", "Check connector logs")
		} else {
			w.Write(token)
		}
		return
	}

	if response.ErrorCode != 0 {
		e := privetError{
			Error:          "server_error",
			Description:    response.Message,
			ServerAPI:      "/proximitytoken",
			ServerCode:     response.ErrorCode,
			ServerHTTPCode: httpStatusCode,
		}.json()
		w.Write(e)
		return
	}

	writeError(w, "server_error", "Check connector logs")
}
// getWithRetry calls get() and retries on HTTP failure
// (response code != 200).
func getWithRetry(hc *http.Client, url string) (*http.Response, error) {
	backoff := lib.Backoff{}
	for {
		response, err := get(hc, url)
		if response != nil && response.StatusCode == http.StatusOK {
			return response, err
		}

		p, retryAgain := backoff.Pause()
		if !retryAgain {
			log.Debugf("HTTP error %s, retry timeout hit", err, p)
			return response, err
		}
		log.Debugf("HTTP error %s, retrying after %s", err, p)
		time.Sleep(p)
	}
}
// postWithRetry calls post() and retries on HTTP failure
// (response code != 200).
func postWithRetry(hc *http.Client, url string, form url.Values) ([]byte, uint, int, error) {
	backoff := lib.Backoff{}
	for {
		responseBody, gcpErrorCode, httpStatusCode, err := post(hc, url, form)
		if responseBody != nil && httpStatusCode == http.StatusOK {
			return responseBody, gcpErrorCode, httpStatusCode, err
		}

		p, retryAgain := backoff.Pause()
		if !retryAgain {
			log.Debugf("HTTP error %s, retry timeout hit", err, p)
			return responseBody, gcpErrorCode, httpStatusCode, err
		}
		log.Debugf("HTTP error %s, retrying after %s", err, p)
		time.Sleep(p)
	}
}
func (api *privetAPI) jobstate(w http.ResponseWriter, r *http.Request) {
	log.Debugf("Received /jobstate request: %+v", r)
	if ok := api.checkRequest(w, r, "GET"); !ok {
		return
	}

	jobID := r.Form.Get("job_id")
	jobState, exists := api.jc.jobState(jobID)
	if !exists {
		writeError(w, "invalid_print_job", "")
		return
	}

	w.Write(jobState)
}
func (api *privetAPI) createjob(w http.ResponseWriter, r *http.Request) {
	log.Debugf("Received /createjob request: %+v", r)
	if ok := api.checkRequest(w, r, "POST"); !ok {
		return
	}

	requestBody, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Warningf("Failed to read request body: %s", err)
		writeError(w, "invalid_ticket", "Check connector logs")
		return
	}

	var ticket cdd.CloudJobTicket
	if err = json.Unmarshal(requestBody, &ticket); err != nil {
		log.Warningf("Failed to read request body: %s", err)
		writeError(w, "invalid_ticket", "Check connector logs")
		return
	}

	printer, exists := api.getPrinter(api.name)
	if !exists {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	if printer.State.State == cdd.CloudDeviceStateStopped {
		writeError(w, "printer_error", "Printer is stopped")
		return
	}

	jobID, expiresIn := api.jc.createJob(&ticket)
	var response struct {
		JobID     string `json:"job_id"`
		ExpiresIn int32  `json:"expires_in"`
	}
	response.JobID = jobID
	response.ExpiresIn = expiresIn
	j, err := json.MarshalIndent(response, "", "  ")
	if err != nil {
		api.jc.deleteJob(jobID)
		log.Errorf("Failed to marrshal createJob response: %s", err)
		w.WriteHeader(http.StatusInternalServerError)
	} else {
		w.Write(j)
	}
}
// listenNotifications handles the messages found on the channels.
func (pm *PrinterManager) listenNotifications(jobs <-chan *lib.Job, xmppMessages <-chan xmpp.PrinterNotification) {
	go func() {
		for {
			select {
			case <-pm.quit:
				return

			case job := <-jobs:
				log.DebugJobf(job.JobID, "Received job: %+v", job)
				go pm.printJob(job.NativePrinterName, job.Filename, job.Title, job.User, job.JobID, job.Ticket, job.UpdateJob)

			case notification := <-xmppMessages:
				log.Debugf("Received XMPP message: %+v", notification)
				if notification.Type == xmpp.PrinterNewJobs {
					if p, exists := pm.printers.GetByGCPID(notification.GCPID); exists {
						go pm.gcp.HandleJobs(&p, func() { pm.incrementJobsProcessed(false) })
					}
				}
			}
		}
	}()
}
func (api *privetAPI) capabilities(w http.ResponseWriter, r *http.Request) {
	log.Debugf("Received /capabilities request: %+v", r)
	if ok := api.checkRequest(w, r, "GET"); !ok {
		return
	}

	printer, exists := api.getPrinter(api.name)
	if !exists {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	capabilities := cdd.CloudDeviceDescription{
		Version: "1.0",
		Printer: printer.Description,
	}
	j, err := json.MarshalIndent(capabilities, "", "  ")
	if err != nil {
		log.Errorf("Failed to marshal capabilities response: %s", err)
		w.WriteHeader(http.StatusInternalServerError)
	} else {
		w.Write(j)
	}
}
func (t *tee) Write(p []byte) (int, error) {
	n, err := t.w.Write(p)
	log.Debugf("XMPP wrote %d %s", n, p[0:n])
	return n, err
}
func (t *tee) Read(p []byte) (int, error) {
	n, err := t.r.Read(p)
	log.Debugf("XMPP read %d %s", n, p[0:n])
	return n, err
}
func (service *service) Execute(args []string, r <-chan svc.ChangeRequest, s chan<- svc.Status) (bool, uint32) {
	if service.interactive {
		if err := log.Start(true); err != nil {
			fmt.Fprintf(os.Stderr, "Failed to start event log: %s\n", err)
			return false, 1
		}
	} else {
		if err := log.Start(false); err != nil {
			fmt.Fprintf(os.Stderr, "Failed to start event log: %s\n", err)
			return false, 1
		}
	}
	defer log.Stop()

	config, configFilename, err := lib.GetConfig(service.context)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to read config file: %s\n", err)
		return false, 1
	}

	logLevel, ok := log.LevelFromString(config.LogLevel)
	if !ok {
		fmt.Fprintf(os.Stderr, "Log level %s is not recognized\n", config.LogLevel)
		return false, 1
	}
	log.SetLevel(logLevel)

	if configFilename == "" {
		log.Info("No config file was found, so using defaults")
	} else {
		log.Infof("Using config file %s", configFilename)
	}
	completeConfig, _ := json.MarshalIndent(config, "", " ")
	log.Debugf("Config: %s", string(completeConfig))

	log.Info(lib.FullName)

	if !config.CloudPrintingEnable && !config.LocalPrintingEnable {
		log.Fatal("Cannot run connector with both local_printing_enable and cloud_printing_enable set to false")
		return false, 1
	} else if config.LocalPrintingEnable {
		log.Fatal("Local printing has not been implemented in this version of the Windows connector.")
		return false, 1
	}

	jobs := make(chan *lib.Job, 10)
	xmppNotifications := make(chan xmpp.PrinterNotification, 5)

	var g *gcp.GoogleCloudPrint
	var x *xmpp.XMPP
	if config.CloudPrintingEnable {
		xmppPingTimeout, err := time.ParseDuration(config.XMPPPingTimeout)
		if err != nil {
			log.Fatalf("Failed to parse xmpp ping timeout: %s", err)
			return false, 1
		}
		xmppPingInterval, err := time.ParseDuration(config.XMPPPingInterval)
		if err != nil {
			log.Fatalf("Failed to parse xmpp ping interval default: %s", err)
			return false, 1
		}

		g, err = gcp.NewGoogleCloudPrint(config.GCPBaseURL, config.RobotRefreshToken,
			config.UserRefreshToken, config.ProxyName, config.GCPOAuthClientID,
			config.GCPOAuthClientSecret, config.GCPOAuthAuthURL, config.GCPOAuthTokenURL,
			config.GCPMaxConcurrentDownloads, jobs)
		if err != nil {
			log.Fatal(err)
			return false, 1
		}

		x, err = xmpp.NewXMPP(config.XMPPJID, config.ProxyName, config.XMPPServer, config.XMPPPort,
			xmppPingTimeout, xmppPingInterval, g.GetRobotAccessToken, xmppNotifications)
		if err != nil {
			log.Fatal(err)
			return false, 1
		}
		defer x.Quit()
	}

	ws, err := winspool.NewWinSpool(*config.PrefixJobIDToJobTitle, config.DisplayNamePrefix, config.PrinterBlacklist, config.PrinterWhitelist)
	if err != nil {
		log.Fatal(err)
		return false, 1
	}

	nativePrinterPollInterval, err := time.ParseDuration(config.NativePrinterPollInterval)
	if err != nil {
		log.Fatalf("Failed to parse printer poll interval: %s", err)
		return false, 1
	}
	pm, err := manager.NewPrinterManager(ws, g, nil, nativePrinterPollInterval,
		config.NativeJobQueueSize, *config.CUPSJobFullUsername, config.ShareScope, jobs, xmppNotifications)
	if err != nil {
		log.Fatal(err)
		return false, 1
	}
	defer pm.Quit()

	if config.CloudPrintingEnable {
		if config.LocalPrintingEnable {
			log.Infof("Ready to rock as proxy '%s' and in local mode", config.ProxyName)
		} else {
			log.Infof("Ready to rock as proxy '%s'", config.ProxyName)
		}
	} else {
		log.Info("Ready to rock in local-only mode")
	}

	s <- runningStatus
	for {
		request := <-r
		switch request.Cmd {
		case svc.Interrogate:
			s <- runningStatus

		case svc.Stop:
			s <- stoppingStatus
			log.Info("Shutting down")
			time.AfterFunc(time.Second*30, func() {
				log.Fatal("Failed to stop quickly; stopping forcefully")
				os.Exit(1)
			})

			return false, 0

		default:
			log.Errorf("Received unsupported service command from service control manager: %d", request.Cmd)
		}
	}
}
func (api *privetAPI) submitdoc(w http.ResponseWriter, r *http.Request) {
	log.Debugf("Received /submitdoc request: %+v", r)
	if ok := api.checkRequest(w, r, "POST"); !ok {
		return
	}

	file, err := ioutil.TempFile("", "cloud-print-connector-privet-")
	if err != nil {
		log.Errorf("Failed to create file for new Privet job: %s", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer file.Close()

	jobSize, err := io.Copy(file, r.Body)
	if err != nil {
		log.Errorf("Failed to copy new print job file: %s", err)
		w.WriteHeader(http.StatusInternalServerError)
		os.Remove(file.Name())
		return
	}
	if length, err := strconv.ParseInt(r.Header.Get("Content-Length"), 10, 64); err != nil || length != jobSize {
		writeError(w, "invalid_params", "Content-Length header doesn't match length of content")
		os.Remove(file.Name())
		return
	}

	jobType := r.Header.Get("Content-Type")
	if jobType == "" {
		writeError(w, "invalid_document_type", "Content-Type header is missing")
		os.Remove(file.Name())
		return
	}

	printer, exists := api.getPrinter(api.name)
	if !exists {
		w.WriteHeader(http.StatusInternalServerError)
		os.Remove(file.Name())
		return
	}
	if printer.State.State == cdd.CloudDeviceStateStopped {
		writeError(w, "printer_error", "Printer is stopped")
		os.Remove(file.Name())
		return
	}

	jobName := r.Form.Get("job_name")
	userName := r.Form.Get("user_name")
	jobID := r.Form.Get("job_id")
	var expiresIn int32
	var ticket *cdd.CloudJobTicket
	if jobID == "" {
		jobID, expiresIn = api.jc.createJob(nil)
	} else {
		var ok bool
		if expiresIn, ticket, ok = api.jc.getJobExpiresIn(jobID); !ok {
			pe := privetError{
				Error:   "invalid_print_job",
				Timeout: 5,
			}.json()
			w.Write(pe)
			os.Remove(file.Name())
			return
		}
	}

	api.jobs <- &lib.Job{
		NativePrinterName: api.name,
		Filename:          file.Name(),
		Title:             jobName,
		User:              userName,
		JobID:             jobID,
		Ticket:            ticket,
		UpdateJob:         api.jc.updateJob,
	}

	var response struct {
		JobID     string `json:"job_id"`
		ExpiresIn int32  `json:"expires_in"`
		JobType   string `json:"job_type"`
		JobSize   int64  `json:"job_size"`
		JobName   string `json:"job_name,omitempty"`
	}

	response.JobID = jobID
	response.ExpiresIn = expiresIn
	response.JobType = jobType
	response.JobSize = jobSize
	response.JobName = jobName
	j, err := json.MarshalIndent(response, "", "  ")
	if err != nil {
		log.ErrorJobf(jobID, "Failed to marshal submitdoc response: %s", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Write(j)
}
func (api *privetAPI) info(w http.ResponseWriter, r *http.Request) {
	log.Debugf("Received /info request: %+v", r)
	if r.Method != "GET" {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	if _, exists := r.Header["X-Privet-Token"]; !exists {
		w.WriteHeader(http.StatusBadRequest)
		writeError(w, "invalid_x_privet_token",
			"X-Privet-Token request header is missing or invalid")
		return
	}

	printer, exists := api.getPrinter(api.name)
	if !exists {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	var s cdd.CloudConnectionStateType
	if api.online {
		s = cdd.CloudConnectionStateOnline
	} else {
		s = cdd.CloudConnectionStateOffline
	}
	state := cdd.CloudDeviceState{
		Version:              "1.0",
		CloudConnectionState: &s,
		Printer:              printer.State,
	}

	var connectionState string
	var supportedAPIs []string
	if api.online {
		connectionState = "online"
		supportedAPIs = supportedAPIsOnline
	} else {
		connectionState = "offline"
		supportedAPIs = supportedAPIsOffline
	}

	response := infoResponse{
		Version:         "1.0",
		Name:            printer.DefaultDisplayName,
		URL:             api.gcpBaseURL,
		Type:            []string{"printer"},
		ID:              printer.GCPID,
		DeviceState:     strings.ToLower(string(printer.State.State)),
		ConnectionState: connectionState,
		Manufacturer:    printer.Manufacturer,
		Model:           printer.Model,
		SerialNumber:    printer.UUID,
		Firmware:        printer.ConnectorVersion,
		Uptime:          uint(time.Since(api.startTime).Seconds()),
		SetupURL:        printer.SetupURL,
		SupportURL:      printer.SupportURL,
		UpdateURL:       printer.UpdateURL,
		XPrivetToken:    api.xsrf.newToken(),
		API:             supportedAPIs,
		SemanticState:   state,
	}

	j, err := json.MarshalIndent(response, "", "  ")
	if err != nil {
		log.Errorf("Failed to marshal Privet info: %s", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Write(j)
}
func connector(context *cli.Context) int {
	config, configFilename, err := lib.GetConfig(context)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to read config file: %s", err)
		return 1
	}

	logToJournal := *config.LogToJournal && journal.Enabled()
	logToConsole := context.Bool("log-to-console")

	if logToJournal {
		log.SetJournalEnabled(true)
		if logToConsole {
			log.SetWriter(os.Stderr)
		} else {
			log.SetWriter(ioutil.Discard)
		}
	} else {
		logFileMaxBytes := config.LogFileMaxMegabytes * 1024 * 1024
		var logWriter io.Writer
		logWriter, err = log.NewLogRoller(config.LogFileName, logFileMaxBytes, config.LogMaxFiles)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to start log roller: %s", err)
			return 1
		}

		if logToConsole {
			logWriter = io.MultiWriter(logWriter, os.Stderr)
		}
		log.SetWriter(logWriter)
	}

	logLevel, ok := log.LevelFromString(config.LogLevel)
	if !ok {
		fmt.Fprintf(os.Stderr, "Log level %s is not recognized", config.LogLevel)
		return 1
	}
	log.SetLevel(logLevel)

	if configFilename == "" {
		log.Info("No config file was found, so using defaults")
	} else {
		log.Infof("Using config file %s", configFilename)
	}
	completeConfig, _ := json.MarshalIndent(config, "", " ")
	log.Debugf("Config: %s", string(completeConfig))

	log.Info(lib.FullName)
	fmt.Println(lib.FullName)

	if !config.CloudPrintingEnable && !config.LocalPrintingEnable {
		log.Fatal("Cannot run connector with both local_printing_enable and cloud_printing_enable set to false")
		return 1
	}

	if _, err := os.Stat(config.MonitorSocketFilename); !os.IsNotExist(err) {
		if err != nil {
			log.Fatalf("Failed to stat monitor socket: %s", err)
		} else {
			log.Fatalf(
				"A connector is already running, or the monitoring socket %s wasn't cleaned up properly",
				config.MonitorSocketFilename)
		}
		return 1
	}

	jobs := make(chan *lib.Job, 10)
	xmppNotifications := make(chan xmpp.PrinterNotification, 5)

	var g *gcp.GoogleCloudPrint
	var x *xmpp.XMPP
	if config.CloudPrintingEnable {
		xmppPingTimeout, err := time.ParseDuration(config.XMPPPingTimeout)
		if err != nil {
			log.Fatalf("Failed to parse xmpp ping timeout: %s", err)
			return 1
		}
		xmppPingInterval, err := time.ParseDuration(config.XMPPPingInterval)
		if err != nil {
			log.Fatalf("Failed to parse xmpp ping interval default: %s", err)
			return 1
		}

		g, err = gcp.NewGoogleCloudPrint(config.GCPBaseURL, config.RobotRefreshToken,
			config.UserRefreshToken, config.ProxyName, config.GCPOAuthClientID,
			config.GCPOAuthClientSecret, config.GCPOAuthAuthURL, config.GCPOAuthTokenURL,
			config.GCPMaxConcurrentDownloads, jobs)
		if err != nil {
			log.Fatal(err)
			return 1
		}

		x, err = xmpp.NewXMPP(config.XMPPJID, config.ProxyName, config.XMPPServer, config.XMPPPort,
			xmppPingTimeout, xmppPingInterval, g.GetRobotAccessToken, xmppNotifications)
		if err != nil {
			log.Fatal(err)
			return 1
		}
		defer x.Quit()
	}

	cupsConnectTimeout, err := time.ParseDuration(config.CUPSConnectTimeout)
	if err != nil {
		log.Fatalf("Failed to parse CUPS connect timeout: %s", err)
		return 1
	}
	c, err := cups.NewCUPS(*config.CUPSCopyPrinterInfoToDisplayName, *config.PrefixJobIDToJobTitle,
		config.DisplayNamePrefix, config.CUPSPrinterAttributes, config.CUPSMaxConnections,
		cupsConnectTimeout, config.PrinterBlacklist, config.PrinterWhitelist, *config.CUPSIgnoreRawPrinters,
		*config.CUPSIgnoreClassPrinters)
	if err != nil {
		log.Fatal(err)
		return 1
	}
	defer c.Quit()

	var priv *privet.Privet
	if config.LocalPrintingEnable {
		if g == nil {
			priv, err = privet.NewPrivet(jobs, config.LocalPortLow, config.LocalPortHigh, config.GCPBaseURL, nil)
		} else {
			priv, err = privet.NewPrivet(jobs, config.LocalPortLow, config.LocalPortHigh, config.GCPBaseURL, g.ProximityToken)
		}
		if err != nil {
			log.Fatal(err)
			return 1
		}
		defer priv.Quit()
	}

	nativePrinterPollInterval, err := time.ParseDuration(config.NativePrinterPollInterval)
	if err != nil {
		log.Fatalf("Failed to parse CUPS printer poll interval: %s", err)
		return 1
	}
	pm, err := manager.NewPrinterManager(c, g, priv, nativePrinterPollInterval,
		config.NativeJobQueueSize, *config.CUPSJobFullUsername, config.ShareScope,
		jobs, xmppNotifications)
	if err != nil {
		log.Fatal(err)
		return 1
	}
	defer pm.Quit()

	m, err := monitor.NewMonitor(c, g, priv, pm, config.MonitorSocketFilename)
	if err != nil {
		log.Fatal(err)
		return 1
	}
	defer m.Quit()

	if config.CloudPrintingEnable {
		if config.LocalPrintingEnable {
			log.Infof("Ready to rock as proxy '%s' and in local mode", config.ProxyName)
			fmt.Printf("Ready to rock as proxy '%s' and in local mode\n", config.ProxyName)
		} else {
			log.Infof("Ready to rock as proxy '%s'", config.ProxyName)
			fmt.Printf("Ready to rock as proxy '%s'\n", config.ProxyName)
		}
	} else {
		log.Info("Ready to rock in local-only mode")
		fmt.Println("Ready to rock in local-only mode")
	}

	waitIndefinitely()

	log.Info("Shutting down")
	fmt.Println("")
	fmt.Println("Shutting down")

	return 0
}