1481dd
diff --git a/backend/Makefile b/backend/Makefile
1481dd
index 3038682..6642016 100644
1481dd
--- a/backend/Makefile
1481dd
+++ b/backend/Makefile
1481dd
@@ -28,6 +28,7 @@ include ../Makedefs
1481dd
 RBACKENDS =	\
1481dd
 		ipp \
1481dd
 		lpd \
1481dd
+		failover \
1481dd
 		$(DNSSD_BACKEND)
1481dd
 UBACKENDS =	\
1481dd
 		snmp \
1481dd
@@ -51,6 +52,7 @@ LIBOBJS	=	\
1481dd
 OBJS	=	\
1481dd
 		ipp.o \
1481dd
 		lpd.o \
1481dd
+		failover.o \
1481dd
 		dnssd.o \
1481dd
 		snmp.o \
1481dd
 		socket.o \
1481dd
@@ -275,6 +277,13 @@ lpd:	lpd.o ../cups/$(LIBCUPS) libbackend.a
1481dd
 	echo Linking $@...
1481dd
 	$(LD_CC) $(LDFLAGS) -o lpd lpd.o libbackend.a $(LIBS)
1481dd
 
1481dd
+#
1481dd
+# failover
1481dd
+#
1481dd
+
1481dd
+failover:	failover.o ../cups/$(LIBCUPS) libbackend.a
1481dd
+	echo Linking $@...
1481dd
+	$(LD_CC) $(LDFLAGS) -o failover failover.o libbackend.a $(LIBS)
1481dd
 
1481dd
 #
1481dd
 # snmp
1481dd
diff --git a/backend/failover.c b/backend/failover.c
1481dd
new file mode 100644
1481dd
index 0000000..9affd8f
1481dd
--- /dev/null
1481dd
+++ b/backend/failover.c
1481dd
@@ -0,0 +1,837 @@
1481dd
+/*
1481dd
+ * Failover Backend for the Common UNIX Printing System (CUPS).
1481dd
+ *
1481dd
+ * Copyright (c) 2014, Red Hat, Inc.
1481dd
+ * All rights reserved.
1481dd
+ *
1481dd
+ * Redistribution and use in source and binary forms, with or without
1481dd
+ * modification, are permitted provided that the following conditions
1481dd
+ * are met:
1481dd
+ *
1481dd
+ * * Redistributions of source code must retain the above copyright
1481dd
+ *   notice, this list of conditions and the following disclaimer.
1481dd
+ * * Redistributions in binary form must reproduce the above copyright
1481dd
+ *   notice, this list of conditions and the following disclaimer in the
1481dd
+ *   documentation and/or other materials provided with the distribution.
1481dd
+ * * Neither the name of Red Hat, Inc. nor the names of its contributors
1481dd
+ *   may be used to endorse or promote products derived from this software
1481dd
+ *   without specific prior written permission.
1481dd
+ *
1481dd
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1481dd
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1481dd
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
1481dd
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RED HAT,
1481dd
+ * INC.  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
1481dd
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
1481dd
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
1481dd
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
1481dd
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1481dd
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
1481dd
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
1481dd
+ * DAMAGE.
1481dd
+ *
1481dd
+ * Original version by Clark Hale, Red Hat, Inc.
1481dd
+ *
1481dd
+ * This backend presents a fake printer that will choose the first
1481dd
+ * available printer from a list of IPP URIs.
1481dd
+ *
1481dd
+ * Option failover contains a comma separated list of IPP URIs.  The
1481dd
+ * URIs are attempted in-order.
1481dd
+ *
1481dd
+ * Option failover-retries contains an integer that indicates how many
1481dd
+ * times to iterate through the failover list before completely
1481dd
+ * failing.
1481dd
+ *
1481dd
+ * Contents:
1481dd
+ *   main()                   - Checks each printer in a failover list, and
1481dd
+ *                              sends job data to the first available printer
1481dd
+ *   move_job()               - Sends and IPP Move-Job request
1481dd
+ *   check_printer()          - Checks a printer's attributes to see
1481dd
+ *                              if it's enabled and accepting jobs
1481dd
+ *   read_config()            - Read the backends configuration from
1481dd
+ *                              options
1481dd
+ *   get_printer_attributes() - Sends an IPP Get-Attributes request to
1481dd
+ *                              a URI
1481dd
+ *   sigterm_handler()        - Handle SIGTERM that cancels the job
1481dd
+ *   password_cb()            - Password call back used to disable password
1481dd
+ *                              prompt
1481dd
+ */
1481dd
+#include <stdlib.h>
1481dd
+#include <stdio.h>
1481dd
+#include <string.h>
1481dd
+#include <sys/wait.h>
1481dd
+#include <cups/http-private.h>
1481dd
+#include <cups/http.h>
1481dd
+#include "backend-private.h"
1481dd
+
1481dd
+/*
1481dd
+ * Return Values
1481dd
+ */
1481dd
+typedef enum fo_state_e
1481dd
+{
1481dd
+  FO_PRINTER_GOOD = 0,
1481dd
+  FO_PRINTER_BAD,
1481dd
+  FO_PRINTER_BUSY,
1481dd
+  FO_AUTH_REQUIRED
1481dd
+} fo_state_t;
1481dd
+
1481dd
+/*
1481dd
+ * Constants
1481dd
+ */
1481dd
+#define FAILOVER_DEFAULT_RETRIES        (3)
1481dd
+#define FAILOVER_PASSWORD_RETRIES_MAX   (3)
1481dd
+
1481dd
+/*
1481dd
+ * Local Functions
1481dd
+ */
1481dd
+static       int   check_printer(const char *device_uri);
1481dd
+static       int   read_config(cups_array_t *printer_array, int *retries,
1481dd
+                               const char *options);
1481dd
+static       int   get_printer_attributes(const char *device_uri,
1481dd
+                                          ipp_t **attributes);
1481dd
+static       int   move_job(int jobid, const char *dest);
1481dd
+static       void  sigterm_handler(int sig);
1481dd
+static const char *password_cb(const char *);
1481dd
+
1481dd
+/*
1481dd
+ * Global Variables
1481dd
+ */
1481dd
+static int         job_canceled = 0;     /* Job canceled */
1481dd
+static char       *password = NULL;      /* password for device */
1481dd
+static int         password_retries = 0;
1481dd
+static const char *auth_info_required = "none";
1481dd
+
1481dd
+/*
1481dd
+ * 'main()' - Checks each printer in a failover list, and
1481dd
+ *            sends job data to the first available printer
1481dd
+ * Usage:
1481dd
+ *    printer-uri job-id user title copies options [file]
1481dd
+ *
1481dd
+ *    The printer-uri option is not used, but it still required to fit
1481dd
+ *    to the backend(7) standards.
1481dd
+ */
1481dd
+int
1481dd
+main(int argc, char *argv[])
1481dd
+{
1481dd
+  const char   *selected_uri = NULL;      /* URI of selected printer     */
1481dd
+  const char   *tmp_device_uri;           /* Device URI to check         */
1481dd
+  cups_array_t *printer_array;            /* Array of available printers */
1481dd
+  int           printer_count = 0;        /* current printer array index */
1481dd
+  int           retry_max = 1;            /* maximum retries before exit */
1481dd
+  int           retry_count = 0;          /* current retry number        */
1481dd
+  int           auth_failed_count = 0;    /* auth failures per loop      */
1481dd
+  int           rc = CUPS_BACKEND_OK;
1481dd
+#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1481dd
+  struct        sigaction action;       /* Actions for POSIX signals */
1481dd
+#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1481dd
+
1481dd
+ /*
1481dd
+  * Check args
1481dd
+  */
1481dd
+  if (argc == 1)
1481dd
+  {
1481dd
+   /*
1481dd
+    * print out discovery data
1481dd
+    */
1481dd
+    char *backendName;
1481dd
+
1481dd
+    if ((backendName = strrchr(argv[0], '/')) != NULL)
1481dd
+      backendName++;
1481dd
+    else
1481dd
+      backendName = argv[0];
1481dd
+
1481dd
+    _cupsLangPrintf(stderr,"network %s \"Unknown\" \"%s (%s)\"\n",
1481dd
+                    backendName,
1481dd
+                    _cupsLangString(cupsLangDefault(), _("Failover Printer")),
1481dd
+                    backendName);
1481dd
+
1481dd
+    return (CUPS_BACKEND_OK);
1481dd
+  }
1481dd
+  else if (argc < 6)
1481dd
+  {
1481dd
+    _cupsLangPrintf(stderr,
1481dd
+                    _("Usage: %s job-id user title copies options [file]"),
1481dd
+                    argv[0]);
1481dd
+    return (CUPS_BACKEND_STOP);
1481dd
+  }
1481dd
+
1481dd
+  fprintf(stderr, "DEBUG: Failover backend starting up.\n");
1481dd
+
1481dd
+ /*
1481dd
+  * Don't buffer status messages
1481dd
+  */
1481dd
+  setbuf(stderr, NULL);
1481dd
+
1481dd
+ /*
1481dd
+  * Ignore SIGPIPE and catch SIGTERM signals...
1481dd
+  */
1481dd
+#ifdef HAVE_SIGSET
1481dd
+  sigset(SIGPIPE, SIG_IGN);
1481dd
+  sigset(SIGTERM, sigterm_handler);
1481dd
+#elif defined(HAVE_SIGACTION)
1481dd
+  memset(&action, 0, sizeof(action));
1481dd
+  action.sa_handler = SIG_IGN;
1481dd
+  sigaction(SIGPIPE, &action, NULL);
1481dd
+
1481dd
+  sigemptyset(&action.sa_mask);
1481dd
+  sigaddset(&action.sa_mask, SIGTERM);
1481dd
+  action.sa_handler = sigterm_handler;
1481dd
+  sigaction(SIGTERM, &action, NULL);
1481dd
+#else
1481dd
+  signal(SIGPIPE, SIG_IGN);
1481dd
+  signal(SIGTERM, sigterm_handler);
1481dd
+#endif /* HAVE_SIGSET */
1481dd
+
1481dd
+  printer_array = cupsArrayNew(NULL, NULL);
1481dd
+
1481dd
+ /*
1481dd
+  * Read Configuration
1481dd
+  */
1481dd
+  if ((rc = read_config(printer_array, &retry_max,
1481dd
+                        argv[5])) != CUPS_BACKEND_OK)
1481dd
+  {
1481dd
+    fprintf(stderr, "ERROR: Failed to read configuration options!\n");
1481dd
+    goto cleanup;
1481dd
+  }
1481dd
+
1481dd
+ /*
1481dd
+  * Main Retry Loop
1481dd
+  */
1481dd
+  for (retry_count = 0; retry_count < retry_max; retry_count++)
1481dd
+  {
1481dd
+    fprintf(stderr, "DEBUG: Retry loop #%d\n", retry_count + 1);
1481dd
+
1481dd
+   /*
1481dd
+    * Reset Counters
1481dd
+    */
1481dd
+    printer_count = 0;
1481dd
+    auth_failed_count = 0;
1481dd
+
1481dd
+    tmp_device_uri = (char *)cupsArrayFirst(printer_array);
1481dd
+
1481dd
+    do
1481dd
+    {
1481dd
+      if (job_canceled)
1481dd
+      {
1481dd
+        fprintf(stderr, "DEBUG: Job Canceled\n");
1481dd
+        goto cleanup;
1481dd
+      }
1481dd
+
1481dd
+      fprintf(stderr,"DEBUG: Checking printer #%d: %s\n",
1481dd
+              printer_count+1, tmp_device_uri);
1481dd
+
1481dd
+      rc = check_printer(tmp_device_uri);
1481dd
+
1481dd
+      // Printer is available and not busy.
1481dd
+      if ( rc == FO_PRINTER_GOOD )
1481dd
+      {
1481dd
+        selected_uri = tmp_device_uri;
1481dd
+        break;
1481dd
+      }
1481dd
+      // Printer is busy
1481dd
+      else if (rc == FO_PRINTER_BUSY)
1481dd
+      {
1481dd
+        fprintf(stderr, "DEBUG: Waiting for job to complete.\n");
1481dd
+        sleep(2);
1481dd
+        continue;
1481dd
+      }
1481dd
+      // Authorization is required to access the printer.
1481dd
+      else if (rc == FO_AUTH_REQUIRED)
1481dd
+      {
1481dd
+        auth_failed_count++;
1481dd
+        fprintf(stderr, "DEBUG: auth_failed_count = %d\n", auth_failed_count);
1481dd
+      }
1481dd
+      // Printer is stopped or not accepting jobs
1481dd
+      else
1481dd
+      {
1481dd
+        if (!printer_count)
1481dd
+          fprintf(stderr, "INFO: Primary Printer, %s, not available.  "
1481dd
+                  "Attempting Failovers...\n",
1481dd
+                  tmp_device_uri);
1481dd
+        else
1481dd
+          fprintf(stderr, "INFO: Failover Printer, %s, not available.  "
1481dd
+                  "Attempting Failovers..\n",
1481dd
+                  tmp_device_uri);
1481dd
+        printer_count++;
1481dd
+        tmp_device_uri = (char *)cupsArrayNext(printer_array);
1481dd
+      }
1481dd
+    } while (tmp_device_uri != NULL);
1481dd
+
1481dd
+    if (selected_uri && !printer_count)
1481dd
+      fprintf(stderr, "STATE: -primary-printer-failed\n");
1481dd
+    else
1481dd
+      fprintf(stderr, "STATE: +primary-printer-failed\n");
1481dd
+
1481dd
+    if (job_canceled)
1481dd
+    {
1481dd
+      fprintf(stderr, "DEBUG: Job Canceled\n");
1481dd
+      goto cleanup;
1481dd
+    }
1481dd
+
1481dd
+    if (!selected_uri && auth_failed_count == printer_count)
1481dd
+    {
1481dd
+      fprintf(stderr, "ERROR:  All failover printers failed with "
1481dd
+              "authorization issues.\n");
1481dd
+      rc = CUPS_BACKEND_AUTH_REQUIRED;
1481dd
+      fprintf(stderr, "ATTR: auth-info-required=%s\n", auth_info_required);
1481dd
+      goto cleanup;
1481dd
+    }
1481dd
+    else if (!selected_uri && retry_count + 1 < retry_max)
1481dd
+    {
1481dd
+      fprintf(stderr, "INFO: No suitable printer found...retrying...\n");
1481dd
+      sleep(2);
1481dd
+      continue;
1481dd
+    }
1481dd
+    else if (selected_uri)
1481dd
+    {
1481dd
+      fprintf(stderr, "DEBUG: Using printer, %s.\n", selected_uri);
1481dd
+      break;
1481dd
+    }
1481dd
+  }
1481dd
+
1481dd
+  if (!selected_uri)
1481dd
+  {
1481dd
+    fprintf(stderr, "ERROR: No suitable printer found.  Aborting print\n");
1481dd
+    rc = CUPS_BACKEND_FAILED;
1481dd
+    goto cleanup;
1481dd
+  }
1481dd
+
1481dd
+  rc = move_job(atoi(argv[1]), selected_uri);
1481dd
+
1481dd
+  if (job_canceled)
1481dd
+    rc = CUPS_BACKEND_OK;
1481dd
+
1481dd
+cleanup :
1481dd
+  if (job_canceled)
1481dd
+    rc = CUPS_BACKEND_OK;
1481dd
+
1481dd
+  tmp_device_uri = (char *)cupsArrayFirst(printer_array);
1481dd
+  do
1481dd
+  {
1481dd
+    free((void *)tmp_device_uri);
1481dd
+  } while ((tmp_device_uri = (char *)cupsArrayNext(printer_array)) != NULL);
1481dd
+
1481dd
+  cupsArrayDelete(printer_array);
1481dd
+  sleep(2);
1481dd
+  return (rc);
1481dd
+}
1481dd
+
1481dd
+/*
1481dd
+ * 'check_printer()' - Checks the status of a remote printer and returns
1481dd
+ *                     back a good/bad/busy status.
1481dd
+ */
1481dd
+int
1481dd
+check_printer(const char *device_uri)
1481dd
+{
1481dd
+  ipp_t           *attributes = NULL;     /* attributes for device_uri */
1481dd
+  ipp_attribute_t *tmp_attribute;         /* for examining attribs     */
1481dd
+  int              rc = FO_PRINTER_GOOD;  /* return code               */
1481dd
+  char            *reason;                /* printer state reason */
1481dd
+  int              i;
1481dd
+
1481dd
+  fprintf(stderr, "DEBUG: Checking printer %s\n",device_uri);
1481dd
+
1481dd
+  rc = get_printer_attributes(device_uri, &attributes);
1481dd
+  if ( rc != CUPS_BACKEND_OK )
1481dd
+  {
1481dd
+    fprintf(stderr, "DEBUG: Failed to get attributes from printer: %s\n",
1481dd
+            device_uri);
1481dd
+    if ( rc == CUPS_BACKEND_AUTH_REQUIRED )
1481dd
+      return (FO_AUTH_REQUIRED);
1481dd
+    else
1481dd
+      return (FO_PRINTER_BAD);
1481dd
+  }
1481dd
+
1481dd
+ /*
1481dd
+  * Check if printer is accepting jobs
1481dd
+  */
1481dd
+  if ((tmp_attribute = ippFindAttribute(attributes,
1481dd
+                                        "printer-is-accepting-jobs",
1481dd
+                                        IPP_TAG_BOOLEAN)) != NULL &&
1481dd
+      !tmp_attribute->values[0].boolean)
1481dd
+  {
1481dd
+    fprintf(stderr,
1481dd
+            "DEBUG: Printer, %s, is not accepting jobs.\n",
1481dd
+            device_uri);
1481dd
+
1481dd
+    rc = FO_PRINTER_BAD;
1481dd
+  }
1481dd
+
1481dd
+ /*
1481dd
+  * Check if printer is stopped or busy processing
1481dd
+  */
1481dd
+  if ((tmp_attribute = ippFindAttribute(attributes,
1481dd
+                                        "printer-state",
1481dd
+                                        IPP_TAG_ENUM)) != NULL)
1481dd
+  {
1481dd
+    // Printer Stopped
1481dd
+    if ( tmp_attribute->values[0].integer == IPP_PRINTER_STOPPED )
1481dd
+    {
1481dd
+      fprintf(stderr, "DEBUG: Printer, %s, stopped.\n", device_uri);
1481dd
+      rc = FO_PRINTER_BAD;
1481dd
+    }
1481dd
+    // Printer Busy
1481dd
+    else if ( tmp_attribute->values[0].integer == IPP_PRINTER_PROCESSING )
1481dd
+    {
1481dd
+      fprintf(stderr, "DEBUG: Printer %s is busy.\n", device_uri);
1481dd
+      rc = FO_PRINTER_BUSY;
1481dd
+    }
1481dd
+  }
1481dd
+
1481dd
+  /*
1481dd
+   * Parse through the printer-state-reasons
1481dd
+   */
1481dd
+  if ((tmp_attribute = ippFindAttribute(attributes, "printer-state-reasons",
1481dd
+                                        IPP_TAG_KEYWORD)) != NULL)
1481dd
+  {
1481dd
+    for (i = 0; i < tmp_attribute->num_values; i++)
1481dd
+    {
1481dd
+      reason = tmp_attribute->values[i].string.text;
1481dd
+      int len = strlen(reason);
1481dd
+
1481dd
+      if (len > 8 && !strcmp(reason + len - 8, "-warning"))
1481dd
+      {
1481dd
+        fprintf(stderr, "DEBUG: Printer Supply Warning, %s\n", reason);
1481dd
+        rc = FO_PRINTER_BAD;
1481dd
+      }
1481dd
+      else if (len > 6 && !strcmp(reason + len - 6, "-error"))
1481dd
+      {
1481dd
+        fprintf(stderr, "DEBUG: Printer Supply Error, %s\n", reason);
1481dd
+        rc = FO_PRINTER_BAD;
1481dd
+      }
1481dd
+    }
1481dd
+  }
1481dd
+
1481dd
+  return (rc);
1481dd
+}
1481dd
+
1481dd
+/*
1481dd
+ * 'read_config()' - Parses the failover and failover-retries options
1481dd
+ *
1481dd
+ */
1481dd
+static int
1481dd
+read_config(cups_array_t *printer_array, int *retries, const char *options)
1481dd
+{
1481dd
+
1481dd
+  const char    *tmp;                   /* temporary ptr                     */
1481dd
+  char          *tok_tmp;               /* temporary ptr for option  parsing */
1481dd
+  int            jobopts_count = 0;     /* number of options                 */
1481dd
+  cups_option_t *jobopts = NULL;        /* job options                       */
1481dd
+
1481dd
+
1481dd
+  fprintf(stderr, "DEBUG: Reading Configuration.\n");
1481dd
+  jobopts_count = cupsParseOptions(options, 0, &jobopts);
1481dd
+
1481dd
+  if (!jobopts_count)
1481dd
+  {
1481dd
+    fprintf(stderr,
1481dd
+            "ERROR: No job options!  Cannot find failover options!\n");
1481dd
+    return (CUPS_BACKEND_STOP);
1481dd
+  }
1481dd
+
1481dd
+ /*
1481dd
+  * Get attributes from the primary printer
1481dd
+  */
1481dd
+  fprintf(stderr, "DEBUG: Searching for failover option.\n");
1481dd
+
1481dd
+  if ((tmp = cupsGetOption("failover", jobopts_count, jobopts)) != NULL)
1481dd
+  {
1481dd
+    fprintf(stderr, "DEBUG: Failover option contents: %s.\n", tmp);
1481dd
+
1481dd
+    tok_tmp = strdup(tmp);
1481dd
+
1481dd
+    tmp = strtok(tok_tmp, ",");
1481dd
+    do
1481dd
+    {
1481dd
+      cupsArrayAdd(printer_array, strdup(tmp));
1481dd
+    } while ((tmp = strtok(NULL,",")) != NULL);
1481dd
+
1481dd
+    free(tok_tmp);
1481dd
+  }
1481dd
+  else
1481dd
+  {
1481dd
+   /*
1481dd
+    * The queue is misconfigured, so return back CUPS_BACKEND_STOP
1481dd
+    */
1481dd
+    fprintf(stderr, "ERROR: failover option not specified!\n");
1481dd
+    return (CUPS_BACKEND_STOP);
1481dd
+  }
1481dd
+
1481dd
+ /*
1481dd
+  * Get the failover-retries value, if it exists.
1481dd
+  */
1481dd
+  fprintf(stderr, "DEBUG: Searching for failover-retries option.\n");
1481dd
+
1481dd
+  if ((tmp = cupsGetOption("failover-retries",
1481dd
+                           jobopts_count, jobopts)) != NULL)
1481dd
+  {
1481dd
+    fprintf(stderr, "DEBUG: failover-retries option contents: %s.\n", tmp);
1481dd
+    *retries = atoi(tmp);
1481dd
+  }
1481dd
+  else
1481dd
+  {
1481dd
+    *retries = FAILOVER_DEFAULT_RETRIES;
1481dd
+    fprintf(stderr, "DEBUG: Failed to get failover-retries option\n");
1481dd
+    fprintf(stderr, "DEBUG: Defaulted to %d retries\n", *retries);
1481dd
+  }
1481dd
+
1481dd
+  return (CUPS_BACKEND_OK);
1481dd
+}
1481dd
+
1481dd
+/*
1481dd
+ * 'get_printer_attributes()' - Sends an IPP Get-Attributes request to
1481dd
+ *                              a URI
1481dd
+ */
1481dd
+int
1481dd
+get_printer_attributes(const char *device_uri, ipp_t **attributes)
1481dd
+{
1481dd
+  char               uri[HTTP_MAX_URI];         /* Updated URI without login */
1481dd
+  int                version;                   /* IPP version */
1481dd
+  char               scheme[256];               /* Scheme in URI */
1481dd
+  ipp_status_t       ipp_status;                /* Status of IPP request */
1481dd
+  char               hostname[1024];            /* Hostname */
1481dd
+  char               resource[1024];            /* Resource infoo */
1481dd
+  char               addrname[256];             /* Address name */
1481dd
+  int                port;                      /* IPP Port number */
1481dd
+  char               portname[255];             /* Port as string */
1481dd
+  http_t            *http;                      /* HTTP connection */
1481dd
+  ipp_t             *request;                   /* IPP request */
1481dd
+  int                rc = CUPS_BACKEND_OK;      /* Return Code */
1481dd
+  char               username[256];             /* Username for device URI */
1481dd
+  char              *option_ptr;                /* for parsing resource opts */
1481dd
+  const char * const pattrs[] =                 /* Printer attributes wanted */
1481dd
+    {
1481dd
+      "printer-is-accepting-jobs",
1481dd
+      "printer-state",
1481dd
+      "printer-state-reasons"
1481dd
+    };
1481dd
+
1481dd
+  if (job_canceled)
1481dd
+    return (CUPS_BACKEND_OK);
1481dd
+
1481dd
+  fprintf(stderr, "DEBUG: Getting Printer Attributes.\n");
1481dd
+  fprintf(stderr, "DEBUG: Device URL %s.\n", device_uri);
1481dd
+
1481dd
+ /*
1481dd
+  * Parse device_uri
1481dd
+  */
1481dd
+  if (httpSeparateURI(HTTP_URI_CODING_ALL, device_uri, scheme, sizeof(scheme),
1481dd
+                     username, sizeof(username), hostname, sizeof(hostname),
1481dd
+                     &port, resource, sizeof(resource)) != HTTP_URI_OK)
1481dd
+  {
1481dd
+    fprintf(stderr, "ERROR: Problem parsing device_uri, %s\n", device_uri);
1481dd
+    return (CUPS_BACKEND_STOP);
1481dd
+  }
1481dd
+
1481dd
+  if (!port)
1481dd
+    port = IPP_PORT;
1481dd
+
1481dd
+  sprintf(portname, "%d", port);
1481dd
+
1481dd
+  fprintf(stderr, "DEBUG: Getting Printer Attributes.\n");
1481dd
+
1481dd
+ /*
1481dd
+  * Configure password
1481dd
+  */
1481dd
+  cupsSetPasswordCB(password_cb);
1481dd
+
1481dd
+ /*
1481dd
+  * reset, in case a previous attempt for
1481dd
+  * another printer left residue
1481dd
+  */
1481dd
+  cupsSetUser(NULL);
1481dd
+  password = NULL;
1481dd
+  password_retries = 0;
1481dd
+
1481dd
+  if (*username)
1481dd
+  {
1481dd
+    if ((password = strchr(username, ':')) != NULL)
1481dd
+    {
1481dd
+      *password = '\0';
1481dd
+      password++;
1481dd
+    }
1481dd
+
1481dd
+    cupsSetUser(username);
1481dd
+  }
1481dd
+  else if (!getuid())
1481dd
+  {
1481dd
+    const char *username_env;
1481dd
+
1481dd
+    if ((username_env = getenv("AUTH_USERNAME")) != NULL)
1481dd
+    {
1481dd
+      cupsSetUser(username_env);
1481dd
+      password = getenv("AUTH_PASSWORD");
1481dd
+    }
1481dd
+  }
1481dd
+
1481dd
+ /*
1481dd
+  * Try connecting to the remote server...
1481dd
+  */
1481dd
+  fprintf(stderr, "DEBUG: Connecting to %s:%d\n", hostname, port);
1481dd
+  _cupsLangPuts(stderr, _("INFO: Connecting to printer...\n"));
1481dd
+
1481dd
+  http = httpConnectEncrypt(hostname, port, cupsEncryption());
1481dd
+
1481dd
+ /*
1481dd
+  * Deal the socket not being open.
1481dd
+  */
1481dd
+  if (!http)
1481dd
+  {
1481dd
+    int error = errno;          /* Connection error */
1481dd
+
1481dd
+    switch (error)
1481dd
+    {
1481dd
+    case EHOSTDOWN :
1481dd
+      _cupsLangPuts(stderr, _("WARNING: "
1481dd
+                              "The printer may not exist or "
1481dd
+                              "is unavailable at this time.\n"));
1481dd
+      break;
1481dd
+    case EHOSTUNREACH :
1481dd
+      _cupsLangPuts(stderr, _("WARNING: "
1481dd
+                              "The printer is unreachable at this "
1481dd
+                              "time.\n"));
1481dd
+      break;
1481dd
+    case ECONNREFUSED :
1481dd
+      _cupsLangPuts(stderr, _("WARNING: "
1481dd
+                              "Connection Refused.\n"));
1481dd
+      break;
1481dd
+    default :
1481dd
+      fprintf(stderr, "DEBUG: Connection error: %s\n", strerror(errno));
1481dd
+      break;
1481dd
+    }
1481dd
+
1481dd
+    rc = CUPS_BACKEND_FAILED;
1481dd
+    sleep(5);
1481dd
+    goto prt_available_cleanup;
1481dd
+  }
1481dd
+
1481dd
+
1481dd
+#ifdef AF_INET6
1481dd
+  if (http->hostaddr->addr.sa_family == AF_INET6)
1481dd
+    fprintf(stderr, "DEBUG: Connected to [%s]:%d (IPv6)...\n",
1481dd
+            httpAddrString(http->hostaddr, addrname, sizeof(addrname)),
1481dd
+            ntohs(http->hostaddr->ipv6.sin6_port));
1481dd
+  else
1481dd
+#endif /* AF_INET6 */
1481dd
+  if (http->hostaddr->addr.sa_family == AF_INET)
1481dd
+    fprintf(stderr, "DEBUG: Connected to %s:%d (IPv4)...\n",
1481dd
+            httpAddrString(http->hostaddr, addrname, sizeof(addrname)),
1481dd
+            ntohs(http->hostaddr->ipv4.sin_port));
1481dd
+
1481dd
+ /*
1481dd
+  * Search the resource string for options.
1481dd
+  * We only care about version, for the moment.
1481dd
+  */
1481dd
+  version = 11;
1481dd
+
1481dd
+  if ((option_ptr = strchr(resource, '?')) != NULL)
1481dd
+  {
1481dd
+    *option_ptr++ = '\0';
1481dd
+
1481dd
+    if ((option_ptr = strstr(option_ptr, "version="))!=NULL)
1481dd
+    {
1481dd
+      int   minor;       /* minor version from URI */
1481dd
+      int   major;       /* major version from URI */
1481dd
+      char *version_str; /* ipp version */
1481dd
+
1481dd
+      option_ptr += 8;
1481dd
+      version_str = option_ptr;
1481dd
+
1481dd
+      while (*option_ptr && *option_ptr != '&' && *option_ptr != '+')
1481dd
+        option_ptr++;
1481dd
+
1481dd
+      if (*option_ptr)
1481dd
+        *option_ptr = '\0';
1481dd
+
1481dd
+      sscanf(version_str, "%d.%d", &major, &minor);
1481dd
+
1481dd
+      version = (major * 10) + minor;
1481dd
+
1481dd
+      switch(version)
1481dd
+      {
1481dd
+      case 10 :
1481dd
+      case 11 :
1481dd
+      case 20 :
1481dd
+      case 21 :
1481dd
+        fprintf(stderr,
1481dd
+                "DEBUG: Set version to %d from URI\n",
1481dd
+                version);
1481dd
+        break;
1481dd
+      default :
1481dd
+        _cupsLangPrintf(stderr,
1481dd
+                        _("DEBUG: Invalid version, %d, from URI.  "
1481dd
+                          "Using default of 1.1 \n"),
1481dd
+                        version);
1481dd
+        version = 11;
1481dd
+      }
1481dd
+    }
1481dd
+  }
1481dd
+
1481dd
+
1481dd
+ /*
1481dd
+  * Build a URI for the printer.  We can't use the URI in argv[0]
1481dd
+  * because it might contain username:password information...
1481dd
+  */
1481dd
+  if (httpAssembleURI(HTTP_URI_CODING_ALL, uri, sizeof(uri), scheme, NULL,
1481dd
+                      hostname, port, resource) != HTTP_URI_OK)
1481dd
+  {
1481dd
+    fprintf(stderr, "ERROR: Problem assembling printer URI from host %s, "
1481dd
+            "port %d, resource %s\n", hostname, port, resource);
1481dd
+    return (CUPS_BACKEND_STOP);
1481dd
+  }
1481dd
+
1481dd
+ /*
1481dd
+  * Build the IPP request...
1481dd
+  */
1481dd
+  request = ippNewRequest(IPP_GET_PRINTER_ATTRIBUTES);
1481dd
+  request->request.op.version[0] = version / 10;
1481dd
+  request->request.op.version[1] = version % 10;
1481dd
+
1481dd
+  ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
1481dd
+               NULL, uri);
1481dd
+
1481dd
+  ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
1481dd
+                "requested-attributes", sizeof(pattrs) / sizeof(pattrs[0]),
1481dd
+                NULL, pattrs);
1481dd
+
1481dd
+ /*
1481dd
+  * Do the request...
1481dd
+  */
1481dd
+  fputs("DEBUG: Getting supported attributes...\n", stderr);
1481dd
+
1481dd
+  fprintf(stderr, "DEBUG: IPP Request Structure Built.\n");
1481dd
+
1481dd
+  *attributes = cupsDoRequest(http, request, resource);
1481dd
+  ipp_status = cupsLastError();
1481dd
+
1481dd
+  fprintf(stderr, "DEBUG: Get-Printer-Attributes: %s (%s)\n",
1481dd
+          ippErrorString(ipp_status), cupsLastErrorString());
1481dd
+
1481dd
+  if (ipp_status > IPP_OK_CONFLICT)
1481dd
+  {
1481dd
+    fprintf(stderr, "DEBUG: Get-Printer-Attributes returned %s.\n",
1481dd
+            ippErrorString(ipp_status));
1481dd
+    switch(ipp_status)
1481dd
+    {
1481dd
+    case IPP_FORBIDDEN :
1481dd
+    case IPP_NOT_AUTHORIZED :
1481dd
+      _cupsLangPuts(stderr, _("ERROR: Not Authorized.\n"));
1481dd
+      rc = CUPS_BACKEND_AUTH_REQUIRED;
1481dd
+      break;
1481dd
+    case IPP_PRINTER_BUSY :
1481dd
+    case IPP_SERVICE_UNAVAILABLE :
1481dd
+      _cupsLangPuts(stderr, _("ERROR: "
1481dd
+                              "The printer is not responding.\n"));
1481dd
+      rc = CUPS_BACKEND_FAILED;
1481dd
+      break;
1481dd
+    case IPP_BAD_REQUEST :
1481dd
+    case IPP_VERSION_NOT_SUPPORTED :
1481dd
+      fprintf(stderr, "ERROR: Destination does not support IPP version %d\n",
1481dd
+              version);
1481dd
+    case IPP_NOT_FOUND :
1481dd
+      _cupsLangPuts(stderr, _("ERROR: "
1481dd
+                              "The printer configuration is incorrect or the "
1481dd
+                              "printer no longer exists.\n"));
1481dd
+      rc = CUPS_BACKEND_STOP;
1481dd
+      break;
1481dd
+    default :
1481dd
+      rc = CUPS_BACKEND_FAILED;
1481dd
+    }
1481dd
+    goto prt_available_cleanup;
1481dd
+  }
1481dd
+
1481dd
+prt_available_cleanup :
1481dd
+  httpClose(http);
1481dd
+  return (rc);
1481dd
+}
1481dd
+
1481dd
+static int
1481dd
+move_job(int        jobid,              /* Job ID */
1481dd
+         const char *dest)              /* Destination ipp address */
1481dd
+{
1481dd
+  ipp_t *request;                       /* IPP Request */
1481dd
+  char  job_uri[HTTP_MAX_URI];          /* job-uri */
1481dd
+
1481dd
+  http_t* http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption());
1481dd
+
1481dd
+  if (!http)
1481dd
+  {
1481dd
+    _cupsLangPrintf(stderr,
1481dd
+                    _("failover: Unable to connect to server: %s\n"),
1481dd
+                    strerror(errno));
1481dd
+    return (CUPS_BACKEND_FAILED);
1481dd
+  }
1481dd
+
1481dd
+ /*
1481dd
+  * Build a CUPS_MOVE_JOB request, which requires the following
1481dd
+  * attributes:
1481dd
+  *
1481dd
+  *    job-uri/printer-uri
1481dd
+  *    job-printer-uri
1481dd
+  *    requesting-user-name
1481dd
+  */
1481dd
+
1481dd
+  request = ippNewRequest(CUPS_MOVE_JOB);
1481dd
+
1481dd
+  snprintf(job_uri, sizeof(job_uri), "ipp://localhost/jobs/%d", jobid);
1481dd
+  ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL,
1481dd
+               job_uri);
1481dd
+
1481dd
+  ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
1481dd
+               "requesting-user-name",
1481dd
+               NULL, cupsUser());
1481dd
+
1481dd
+  ippAddString(request, IPP_TAG_JOB, IPP_TAG_URI, "job-printer-uri",
1481dd
+               NULL, dest);
1481dd
+
1481dd
+ /*
1481dd
+  * Do the request and get back a response...
1481dd
+  */
1481dd
+
1481dd
+  ippDelete(cupsDoRequest(http, request, "/jobs"));
1481dd
+
1481dd
+  httpClose(http);
1481dd
+
1481dd
+  if (cupsLastError() > IPP_OK_CONFLICT)
1481dd
+  {
1481dd
+    _cupsLangPrintf(stderr, "failover: %s\n", cupsLastErrorString());
1481dd
+    return (CUPS_BACKEND_FAILED);
1481dd
+  }
1481dd
+  else
1481dd
+    return (CUPS_BACKEND_OK);
1481dd
+}
1481dd
+
1481dd
+/*
1481dd
+ * 'sigterm_handler()' - handles a sigterm, i.e. job canceled
1481dd
+ */
1481dd
+static void
1481dd
+sigterm_handler(int sig)
1481dd
+{
1481dd
+  if (!job_canceled)
1481dd
+  {
1481dd
+    write(2, "DEBUG: Got SIGTERM.\n", 20);
1481dd
+    job_canceled = 1;
1481dd
+  }
1481dd
+  else
1481dd
+  {
1481dd
+   /*
1481dd
+    * Job has already been canceled, so just exit
1481dd
+    */
1481dd
+    exit(1);
1481dd
+  }
1481dd
+}
1481dd
+
1481dd
+/*
1481dd
+ * 'password_cb()' - Disable the password prompt for cupsDoFileRequest().
1481dd
+ */
1481dd
+static const char *                     /* O - Password  */
1481dd
+password_cb(const char *prompt)         /* I - Prompt (not used) */
1481dd
+{
1481dd
+  auth_info_required = "username,password";
1481dd
+  password_retries++;
1481dd
+
1481dd
+  if(password_retries < FAILOVER_PASSWORD_RETRIES_MAX)
1481dd
+    return (password);
1481dd
+  else
1481dd
+    return (NULL);
1481dd
+}