Esempio n. 1
0
static void
_connect (GtkCupsRequest *request)
{
  request->poll_state = GTK_CUPS_HTTP_IDLE;
  request->bytes_received = 0;

  if (request->http == NULL)
    {
      request->http = httpConnectEncrypt (request->server, 
                                          ippPort (), 
                                          cupsEncryption ());

      if (request->http == NULL)
        request->attempts++;

      if (request->http)
        httpBlocking (request->http, 0);
        
      request->own_http = TRUE;
    }
  else
    {
      request->attempts = 0;
      request->state++;

      /* we always write to the socket after we get
         the connection */
      request->poll_state = GTK_CUPS_HTTP_WRITE;
    }
}
Esempio n. 2
0
///////////////////////////////////////////////////////////////////////////////////////////
//
// CS     : PUBLIC gint getPrinterStatus(gchar *pDestName, gchar *pStatus, gint bufSize)
// IN     : gchar *pDestName : Printer name.
//          gint bufSize : Size of output buffer.
// OUT    : gchar *pStatus : Printer status string.
// RETURN : ID_ERR_NO_ERROR : No error.
//          ID_ERR_CUPS_API_FAILED : Error occured in CUPS API.
//
PUBLIC gint getPrinterStatus(gchar *pDestName, gchar *pStatus, gint bufSize)
{
/*** Parameters start ***/
	http_t			*pHTTP;						// Pointer to HTTP connection.
	ipp_t			*pRequest,					// Pointer to CUPS IPP request.
					*pResponse;					// Pointer to CUPS IPP response.
	ipp_attribute_t	*pAttribute;				// Pointer to CUPS attributes.
	cups_lang_t		*pLanguage;					// Pointer to language.
	gchar			printerURI[HTTP_MAX_URI];	// Printer URI.
	gchar			serverName[HTTP_MAX_URI];	// CUPS server name.
	gint			retVal = ID_ERR_NO_ERROR;	// Return value.
/*** Parameters end ***/

	// Initialize buffer.
	memset(printerURI, 0, sizeof(printerURI));
	memset(serverName, 0, sizeof(serverName));

	// Get printer URI and CUPS server name.
	retVal = getPrinterURI(pDestName, printerURI, serverName, HTTP_MAX_URI);
	if (retVal == ID_ERR_NO_ERROR) {
		// CUPS http connect.
		if ((pHTTP = httpConnectEncrypt(serverName, ippPort(), cupsEncryption())) == NULL) {
			retVal = ID_ERR_CUPS_API_FAILED;
		}
		else {
			pRequest = ippNew();

			ippSetOperation(pRequest, IPP_GET_PRINTER_ATTRIBUTES);
			ippSetRequestId(pRequest, 1);

			pLanguage = bjcupsLangDefault();		// cupsLangDefault() -> bjcupsLangDefault() for cups-1.1.19

			ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, cupsLangEncoding(pLanguage));
			ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, pLanguage->language);
			ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printerURI);

			if ((pResponse = cupsDoRequest(pHTTP, pRequest, "/")) != NULL) {
				if (ippGetStatusCode(pResponse) > IPP_OK_CONFLICT) {
					retVal = ID_ERR_CUPS_API_FAILED;
				}
				else {
					pAttribute = ippFindAttribute(pResponse, "printer-state-message", IPP_TAG_TEXT);
					if (pAttribute != NULL) {
						strncpy(pStatus, ippGetString(pAttribute, 0, NULL), bufSize);
					}
				}
				ippDelete(pResponse);
			}
			else {
				retVal = ID_ERR_CUPS_API_FAILED;
			}

			cupsLangFree(pLanguage);
			httpClose(pHTTP);
		}
	}

	return(retVal);
}// End getPrinterStatus
Esempio n. 3
0
papi_status_t
service_connect(service_t *svc, char *service_name)
{
	papi_status_t result = PAPI_OK;
	int port = 631;

	if (svc == NULL)
		return (PAPI_BAD_ARGUMENT);

	if (svc->connection != NULL)	/* alread connected ? */
		return (PAPI_OK);

	if (svc->uri == NULL)
		uri_from_string(service_name, &svc->uri);

	if ((service_name != NULL) && (svc->uri == NULL)) {
		/*
		 * a name was supplied and it's not in URI form, we will
		 * try to use a "default" IPP service under the assumption
		 * that this is most likely a short-form printer name from
		 * from a papiPrinter*() or papiJob*() call and not from a
		 * papiServiceCreate() call.
		 */
		if ((service_name = getenv("PAPI_SERVICE_URI")) == NULL) {
			char *cups;

			if ((cups = getenv("CUPS_SERVER")) != NULL) {
				char buf[BUFSIZ];

				snprintf(buf, sizeof (buf),
					"ipp://%s/printers/", cups);
				service_name = strdup(buf);
			}
		}
		if (service_name == NULL)
			service_name = DEFAULT_IPP_SERVICE_URI;

		uri_from_string(service_name, &svc->uri);
	}

	if (svc->uri == NULL)
		return (PAPI_NOT_POSSIBLE);

	if (svc->uri->port != NULL)
		port = strtol(svc->uri->port, NULL, 10);

	svc->connection = httpConnectEncrypt(svc->uri->host, port,
					http_encryption_type(svc->encryption));
	if (svc->connection == NULL) {
		if (svc->uri != NULL) {
			uri_free(svc->uri);
			svc->uri = NULL;
		}
		result = PAPI_SERVICE_UNAVAILABLE;
	} else if (service_name != NULL)
		svc->name = strdup(service_name);

	return (result);
}
Esempio n. 4
0
static rdpPrintJob* printer_cups_create_printjob(rdpPrinter* printer, UINT32 id)
{
	rdpCupsPrinter* cups_printer = (rdpCupsPrinter*) printer;
	rdpCupsPrintJob* cups_printjob;

	if (cups_printer->printjob != NULL)
		return NULL;

	cups_printjob = (rdpCupsPrintJob*) malloc(sizeof(rdpCupsPrintJob));
	ZeroMemory(cups_printjob, sizeof(rdpCupsPrintJob));

	cups_printjob->printjob.id = id;
	cups_printjob->printjob.printer = printer;

	cups_printjob->printjob.Write = printer_cups_write_printjob;
	cups_printjob->printjob.Close = printer_cups_close_printjob;

#ifndef _CUPS_API_1_4

	cups_printjob->printjob_object = _strdup(tmpnam(NULL));

#else
	{
		char buf[100];

		cups_printjob->printjob_object = httpConnectEncrypt(cupsServer(), ippPort(), HTTP_ENCRYPT_IF_REQUESTED);

		if (cups_printjob->printjob_object == NULL)
		{
			DEBUG_WARN("httpConnectEncrypt: %s", cupsLastErrorString());
			free(cups_printjob);
			return NULL;
		}

		printer_cups_get_printjob_name(buf, sizeof(buf));
		cups_printjob->printjob_id = cupsCreateJob((http_t*) cups_printjob->printjob_object,
			printer->name, buf, 0, NULL);

		if (cups_printjob->printjob_id == 0)
		{
			DEBUG_WARN("cupsCreateJob: %s", cupsLastErrorString());
			httpClose((http_t*) cups_printjob->printjob_object);
			free(cups_printjob);
			return NULL;
		}

		cupsStartDocument((http_t*) cups_printjob->printjob_object,
			printer->name, cups_printjob->printjob_id, buf, CUPS_FORMAT_AUTO, 1);
	}

#endif

	cups_printer->printjob = cups_printjob;
	
	return (rdpPrintJob*)cups_printjob;
}
Esempio n. 5
0
uint32
printer_hw_create(IRP * irp, const char * path)
{
	PRINTER_DEVICE_INFO * info;

	info = (PRINTER_DEVICE_INFO *) irp->dev->info;

	/* Server's print queue will ensure no two print jobs will be sent to the same printer.
	   However, we still want to do a simple locking just to ensure we are safe. */
	if (info->printjob_object)
	{
		return RD_STATUS_DEVICE_BUSY;
	}

#ifndef _CUPS_API_1_4

	info->printjob_id++;
	info->printjob_object = strdup(tmpnam(NULL));

#else
	{
		char buf[100];

		info->printjob_object = httpConnectEncrypt(cupsServer(), ippPort(), HTTP_ENCRYPT_IF_REQUESTED);
		if (info->printjob_object == NULL)
		{
			LLOGLN(0, ("printer_hw_create: httpConnectEncrypt: %s", cupsLastErrorString()));
			return RD_STATUS_DEVICE_BUSY;
		}

		printer_hw_get_printjob_name(buf, sizeof(buf));
		info->printjob_id = cupsCreateJob((http_t *) info->printjob_object,
			info->printer_name, buf,
			0, NULL);

		if (info->printjob_id == 0)
		{
			LLOGLN(0, ("printer_hw_create: cupsCreateJob: %s", cupsLastErrorString()));
			httpClose((http_t *) info->printjob_object);
			info->printjob_object = NULL;
			/* Should get the right return code based on printer status */
			return RD_STATUS_DEVICE_BUSY;
		}
		cupsStartDocument((http_t *) info->printjob_object,
			info->printer_name, info->printjob_id, buf,
			CUPS_FORMAT_POSTSCRIPT, 1);
	}

#endif

	LLOGLN(10, ("printe_hw_create: %s id=%d", info->printer_name, info->printjob_id));
	irp->fileID = info->printjob_id;

	return RD_STATUS_SUCCESS;
}
Esempio n. 6
0
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line args */
     char *argv[])			/* I - Command-line arguments */
{
    int		i,			/* Looping var */
            num_settings;		/* Number of settings */
    cups_option_t	*settings;		/* Settings */
    http_t	*http;			/* Connection to server */


    /*
     * Connect to the server using the defaults...
     */

    http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption());

    /*
     * Set the current configuration if we have anything on the command-line...
     */

    if (argc > 1)
    {
        for (i = 1, num_settings = 0, settings = NULL; i < argc; i ++)
            num_settings = cupsParseOptions(argv[i], num_settings, &settings);

        if (cupsAdminSetServerSettings(http, num_settings, settings))
        {
            puts("New server settings:");
            cupsFreeOptions(num_settings, settings);
        }
        else
        {
            printf("Server settings not changed: %s\n", cupsLastErrorString());
            return (1);
        }
    }
    else
        puts("Current server settings:");

    /*
     * Get the current configuration...
     */

    if (cupsAdminGetServerSettings(http, &num_settings, &settings))
    {
        show_settings(num_settings, settings);
        cupsFreeOptions(num_settings, settings);
        return (0);
    }
    else
    {
        printf("    %s\n", cupsLastErrorString());
        return (1);
    }
}
Esempio n. 7
0
static http_t *cups_connect(TALLOC_CTX *frame)
{
	http_t *http = NULL;
	char *server = NULL, *p = NULL;
	int port;
	int timeout = lp_cups_connection_timeout();
	size_t size;

	if (lp_cups_server(talloc_tos()) != NULL && strlen(lp_cups_server(talloc_tos())) > 0) {
		if (!push_utf8_talloc(frame, &server, lp_cups_server(talloc_tos()), &size)) {
			return NULL;
		}
	} else {
		server = talloc_strdup(frame,cupsServer());
	}
	if (!server) {
		return NULL;
	}

	p = strchr(server, ':');
	if (p) {
		port = atoi(p+1);
		*p = '\0';
	} else {
		port = ippPort();
	}

	DEBUG(10, ("connecting to cups server %s:%d\n",
		   server, port));

	gotalarm = 0;

	if (timeout) {
                CatchSignal(SIGALRM, gotalarm_sig);
                alarm(timeout);
        }

#ifdef HAVE_HTTPCONNECTENCRYPT
	http = httpConnectEncrypt(server, port, lp_cups_encrypt());
#else
	http = httpConnect(server, port);
#endif


	CatchSignal(SIGALRM, SIG_IGN);
        alarm(0);

	if (http == NULL) {
		DEBUG(0,("Unable to connect to CUPS server %s:%d - %s\n",
			 server, port, strerror(errno)));
	}

	return http;
}
Esempio n. 8
0
///////////////////////////////////////////////////////////////////////////////////////////
//
// CS     : PRIVATE gint checkPrinterState(gchar *pDestName, gchar *pURI, gchar *pServerName)
// IN     : gchar *pDestName : Printer name.
//          gchar *pURI : Printer URI.
//          gchar *pServerName : CUPS server name.
// OUT    : None.
// RETURN : ID_ERR_NO_ERROR : No error.
//          ID_ERR_UNKNOWN_PRINTER : No printer registerd in CUPS.
//          ID_ERR_CUPS_API_FAILED : Error occured in CUPS API.
//
PRIVATE gint checkPrinterState(gchar *pDestName, gchar *pURI, gchar *pServerName)
{
/*** Parameters start ***/
	http_t			*pHTTP;								// Pointer to HTTP connection.
	ipp_t			*pRequest,							// Pointer to CUPS IPP request.
					*pResponse;							// Pointer to CUPS IPP response.
	ipp_attribute_t	*pAttribute;						// Pointer to CUPS attributes.
	cups_lang_t		*pLanguage;							// Pointer to language.
	ipp_pstate_t	printerState = IPP_PRINTER_STOPPED;	// Pointer to printer state.
	gint			retVal = ID_ERR_UNKNOWN_PRINTER;	// Return value.
/*** Parameters end ***/

	// CUPS http connect.
	if ((pHTTP = httpConnectEncrypt(pServerName, ippPort(), cupsEncryption())) == NULL) {
		retVal = ID_ERR_CUPS_API_FAILED;
	}
	else {
		pRequest = ippNew();

		ippSetOperation(pRequest, IPP_GET_PRINTER_ATTRIBUTES);
		ippSetRequestId(pRequest, 1);

		pLanguage = bjcupsLangDefault();			// cupsLangDefault() -> bjcupsLangDefault() for cups-1.1.19

		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, cupsLangEncoding(pLanguage));
		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, pLanguage->language);
		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, pURI);

		if ((pResponse = cupsDoRequest(pHTTP, pRequest, "/")) != NULL) {
			if (ippGetStatusCode(pResponse) > IPP_OK_CONFLICT) {
				retVal = ID_ERR_CUPS_API_FAILED;
			}
			else {
				if ((pAttribute = ippFindAttribute(pResponse, "printer-state", IPP_TAG_ENUM)) != NULL) {
					printerState = (ipp_state_t) ippGetInteger(pAttribute, 0);
				}
			}

			ippDelete(pResponse);
		}
		else {
			retVal = ID_ERR_CUPS_API_FAILED;
		}

		cupsLangFree(pLanguage);
		httpClose(pHTTP);
	}

	if (printerState == IPP_PRINTER_IDLE || printerState == IPP_PRINTER_PROCESSING) {
		retVal = ID_ERR_NO_ERROR;
	}

	return(retVal);
}// End checkPrinterState
Esempio n. 9
0
http_t * oyGetCUPSConnection()
{
  if(!cups_http_)
  {
    httpInitialize();
    /* Open access to printer(s) installed on system. */
    cups_http_ = httpConnectEncrypt ( cupsServer(),
                                      ippPort(),
                                      cupsEncryption());
  }
  return cups_http_;
}
Esempio n. 10
0
static void
connection_test_thread (GTask        *task,
                        gpointer      source_object,
                        gpointer      task_data,
                        GCancellable *cancellable)
{
  http_t *http;

  http = httpConnectEncrypt (cupsServer (), ippPort (), cupsEncryption ());
  g_task_return_boolean (task, http != NULL);

  httpClose (http);
}
Esempio n. 11
0
static int GetCupsPrinters(char ***printer)
{
   http_t *http=NULL;     /* HTTP object */
   ipp_t *request=NULL;  /* IPP request object */
   ipp_t *response=NULL; /* IPP response object */
   ipp_attribute_t *attr;     /* Current IPP attribute */
   int cnt=0;

   /* Connect to the HTTP server */
   if ((http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption())) == NULL)
      goto bugout;

   /* Assemble the IPP request */
   request = ippNew();

   ippSetOperation( request, CUPS_GET_PRINTERS );
   ippSetRequestId( request, 1 );

   ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, "utf-8");
   ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, "en");
   ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", NULL, "device-uri");

   /* Send the request and get a response. */
   if ((response = cupsDoRequest(http, request, "/")) == NULL)
      goto bugout;

   for (attr = ippFirstAttribute ( response ); attr != NULL; attr = ippNextAttribute( response ))
   {
      /* Skip leading attributes until we hit a printer. */
      while (attr != NULL && ippGetGroupTag( attr ) != IPP_TAG_PRINTER)
         attr = ippNextAttribute( response );

      if (attr == NULL)
         break;

      while (attr != NULL && ippGetGroupTag( attr ) == IPP_TAG_PRINTER)
      {
         if (strcmp(ippGetName( attr ), "device-uri") == 0 && ippGetValueTag( attr ) == IPP_TAG_URI && AddCupsList(ippGetString( attr, 0, NULL ), printer) == 0)
            cnt++;
         attr = ippNextAttribute( response );
      }

      if (attr == NULL)
         break;
   }

   ippDelete(response);

 bugout:
   return cnt;
}
Esempio n. 12
0
static http_t *				/* O - New HTTP connection */
connect_server(const char *command,	/* I - Command name */
               http_t     *http)	/* I - Current HTTP connection */
{
  if (!http)
  {
    http = httpConnectEncrypt(cupsServer(), ippPort(),
	                      cupsEncryption());

    if (http == NULL)
    {
      _cupsLangPrintf(stderr, _("%s: Unable to connect to server."), command);
      exit(1);
    }
  }

  return (http);
}
Esempio n. 13
0
static int				/* O - 1 on success, 0 on failure */
cups_get_printer_uri(
    http_t     *http,			/* I - HTTP connection */
    const char *name,			/* I - Name of printer or class */
    char       *host,			/* I - Hostname buffer */
    int        hostsize,		/* I - Size of hostname buffer */
    int        *port,			/* O - Port number */
    char       *resource,		/* I - Resource buffer */
    int        resourcesize,		/* I - Size of resource buffer */
    int        depth)			/* I - Depth of query */
{
    int		i;			/* Looping var */
    int		http_port;		/* Port number */
    http_t	*http2;			/* Alternate HTTP connection */
    ipp_t		*request,		/* IPP request */
                *response;		/* IPP response */
    ipp_attribute_t *attr;		/* Current attribute */
    char		uri[HTTP_MAX_URI],	/* printer-uri attribute */
                scheme[HTTP_MAX_URI],	/* Scheme name */
                username[HTTP_MAX_URI],	/* Username:password */
                classname[255],		/* Temporary class name */
                http_hostname[HTTP_MAX_HOST];
    /* Hostname associated with connection */
    static const char * const requested_attrs[] =
    {   /* Requested attributes */
        "printer-uri-supported",
        "printer-type",
        "member-uris"
    };


    DEBUG_printf(("cups_get_printer_uri(http=%p, name=\"%s\", host=%p, "
                  "hostsize=%d, resource=%p, resourcesize=%d, depth=%d)\n",
                  http, name ? name : "(null)", host, hostsize,
                  resource, resourcesize, depth));

    /*
     * Setup the printer URI...
     */

    if (httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
                         "localhost", 0, "/printers/%s", name) != HTTP_URI_OK)
    {
        _cupsSetError(IPP_INTERNAL_ERROR, "Unable to create printer-uri!");

        *host     = '\0';
        *resource = '\0';

        return (0);
    }

    DEBUG_printf(("cups_get_printer_uri: printer-uri=\"%s\"\n", uri));

    /*
     * Get the hostname and port number we are connected to...
     */

    httpGetHostname(http, http_hostname, sizeof(http_hostname));

#ifdef AF_INET6
    if (http->hostaddr->addr.sa_family == AF_INET6)
        http_port = ntohs(http->hostaddr->ipv6.sin6_port);
    else
#endif /* AF_INET6 */
        if (http->hostaddr->addr.sa_family == AF_INET)
            http_port = ntohs(http->hostaddr->ipv4.sin_port);
        else
            http_port = ippPort();

    /*
     * Build an IPP_GET_PRINTER_ATTRIBUTES request, which requires the following
     * attributes:
     *
     *    attributes-charset
     *    attributes-natural-language
     *    printer-uri
     *    requested-attributes
     */

    request = ippNewRequest(IPP_GET_PRINTER_ATTRIBUTES);

    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
                 NULL, uri);

    ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                  "requested-attributes",
                  sizeof(requested_attrs) / sizeof(requested_attrs[0]),
                  NULL, requested_attrs);

    /*
     * Do the request and get back a response...
     */

    if ((response = cupsDoRequest(http, request, "/")) != NULL)
    {
        if ((attr = ippFindAttribute(response, "member-uris", IPP_TAG_URI)) != NULL)
        {
            /*
             * Get the first actual printer name in the class...
             */

            for (i = 0; i < attr->num_values; i ++)
            {
                httpSeparateURI(HTTP_URI_CODING_ALL, attr->values[i].string.text,
                                scheme, sizeof(scheme), username, sizeof(username),
                                host, hostsize, port, resource, resourcesize);
                if (!strncmp(resource, "/printers/", 10))
                {
                    /*
                     * Found a printer!
                     */

                    ippDelete(response);

                    return (1);
                }
            }

            /*
             * No printers in this class - try recursively looking for a printer,
             * but not more than 3 levels deep...
             */

            if (depth < 3)
            {
                for (i = 0; i < attr->num_values; i ++)
                {
                    httpSeparateURI(HTTP_URI_CODING_ALL, attr->values[i].string.text,
                                    scheme, sizeof(scheme), username, sizeof(username),
                                    host, hostsize, port, resource, resourcesize);
                    if (!strncmp(resource, "/classes/", 9))
                    {
                        /*
                         * Found a class!  Connect to the right server...
                         */

                        if (!strcasecmp(http_hostname, host) && *port == http_port)
                            http2 = http;
                        else if ((http2 = httpConnectEncrypt(host, *port,
                                                             cupsEncryption())) == NULL)
                        {
                            DEBUG_puts("Unable to connect to server!");

                            continue;
                        }

                        /*
                        * Look up printers on that server...
                        */

                        strlcpy(classname, resource + 9, sizeof(classname));

                        cups_get_printer_uri(http2, classname, host, hostsize, port,
                                             resource, resourcesize, depth + 1);

                        /*
                        * Close the connection as needed...
                        */

                        if (http2 != http)
                            httpClose(http2);

                        if (*host)
                            return (1);
                    }
                }
            }
        }
        else if ((attr = ippFindAttribute(response, "printer-uri-supported",
                                          IPP_TAG_URI)) != NULL)
        {
            httpSeparateURI(HTTP_URI_CODING_ALL, attr->values[0].string.text,
                            scheme, sizeof(scheme), username, sizeof(username),
                            host, hostsize, port, resource, resourcesize);
            ippDelete(response);

            if (!strncmp(resource, "/classes/", 9))
            {
                _cupsSetError(IPP_INTERNAL_ERROR, _("No printer-uri found for class!"));

                *host     = '\0';
                *resource = '\0';

                return (0);
            }

            return (1);
        }

        ippDelete(response);
    }

    if (cupsLastError() != IPP_NOT_FOUND)
        _cupsSetError(IPP_INTERNAL_ERROR, _("No printer-uri found!"));

    *host     = '\0';
    *resource = '\0';

    return (0);
}
Esempio n. 14
0
static char *				/* I - Printer name or NULL */
cups_connect(const char *name,		/* I - Destination (printer[@host]) */
             char       *printer,	/* O - Printer name [HTTP_MAX_URI] */
             char       *hostname)	/* O - Hostname [HTTP_MAX_URI] */
{
    char	hostbuf[HTTP_MAX_URI],		/* Name of host */
            http_hostname[HTTP_MAX_HOST];	/* Hostname associated with connection */
    _cups_globals_t  *cg = _cupsGlobals();/* Pointer to library globals */


    DEBUG_printf(("cups_connect(\"%s\", %p, %p)\n", name, printer, hostname));

    if (name == NULL)
    {
        _cupsSetError(IPP_BAD_REQUEST, NULL);

        return (NULL);
    }

    /*
     * All jobs are now queued to cupsServer() to avoid hostname
     * resolution problems and to ensure that the user sees all
     * locally queued jobs locally.
     */

    strlcpy(hostbuf, cupsServer(), sizeof(hostbuf));

    httpGetHostname(cg->http, http_hostname, sizeof(http_hostname));

    if (hostname != NULL)
        strlcpy(hostname, hostbuf, HTTP_MAX_URI);
    else
        hostname = hostbuf;

    if (printer != NULL)
        strlcpy(printer, name, HTTP_MAX_URI);
    else
        printer = (char *)name;

    if (cg->http != NULL)
    {
        if (!strcasecmp(http_hostname, hostname))
            return (printer);

        httpClose(cg->http);
    }

    DEBUG_printf(("connecting to %s on port %d...\n", hostname, ippPort()));

    if ((cg->http = httpConnectEncrypt(hostname, ippPort(),
                                       cupsEncryption())) == NULL)
    {
        DEBUG_puts("Unable to connect to server!");

        _cupsSetError(IPP_SERVICE_UNAVAILABLE, strerror(errno));

        return (NULL);
    }
    else
        return (printer);
}
Esempio n. 15
0
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line arguments */
     char *argv[])			/* I - Command-line arguments */
{
  http_t	*http;			/* HTTP connection to server */
  int		i;			/* Looping var */
  int		job_id;			/* Job ID */
  int		num_dests;		/* Number of destinations */
  cups_dest_t	*dests;			/* Destinations */
  char		*dest,			/* Destination printer */
		*job,			/* Job ID pointer */
		*user;			/* Cancel jobs for a user */
  int		purge;			/* Purge or cancel jobs? */
  char		uri[1024];		/* Printer or job URI */
  ipp_t		*request;		/* IPP request */
  ipp_t		*response;		/* IPP response */
  ipp_op_t	op;			/* Operation */


  _cupsSetLocale(argv);

 /*
  * Setup to cancel individual print jobs...
  */

  op        = IPP_CANCEL_JOB;
  purge     = 0;
  dest      = NULL;
  user      = NULL;
  http      = NULL;
  num_dests = 0;
  dests     = NULL;


 /*
  * Process command-line arguments...
  */

  for (i = 1; i < argc; i ++)
    if (argv[i][0] == '-' && argv[i][1])
      switch (argv[i][1])
      {
        case 'E' : /* Encrypt */
#ifdef HAVE_SSL
	    cupsSetEncryption(HTTP_ENCRYPT_REQUIRED);

	    if (http)
	      httpEncryption(http, HTTP_ENCRYPT_REQUIRED);
#else
            _cupsLangPrintf(stderr,
	                    _("%s: Sorry, no encryption support compiled in!\n"),
	                    argv[0]);
#endif /* HAVE_SSL */
	    break;

        case 'U' : /* Username */
	    if (argv[i][2] != '\0')
	      cupsSetUser(argv[i] + 2);
	    else
	    {
	      i ++;
	      if (i >= argc)
	      {
	        _cupsLangPrintf(stderr,
		                _("%s: Error - expected username after "
				  "\'-U\' option!\n"),
		        	argv[0]);
	        return (1);
	      }

              cupsSetUser(argv[i]);
	    }
	    break;
	    
        case 'a' : /* Cancel all jobs */
	    purge = 1;
	    op    = IPP_PURGE_JOBS;
	    break;

        case 'h' : /* Connect to host */
	    if (http != NULL)
	    {
	      httpClose(http);
	      http = NULL;
	    }

	    if (argv[i][2] != '\0')
              cupsSetServer(argv[i] + 2);
	    else
	    {
	      i ++;

	      if (i >= argc)
	      {
	        _cupsLangPrintf(stderr,
		        	_("%s: Error - expected hostname after "
			          "\'-h\' option!\n"),
				argv[0]);
		return (1);
              }
	      else
                cupsSetServer(argv[i]);
	    }
	    break;

        case 'u' : /* Username */
	    op = IPP_PURGE_JOBS;

	    if (argv[i][2] != '\0')
	      user = argv[i] + 2;
	    else
	    {
	      i ++;

	      if (i >= argc)
	      {
	        _cupsLangPrintf(stderr,
		        	_("%s: Error - expected username after "
			          "\'-u\' option!\n"),
				argv[0]);
		return (1);
              }
	      else
		user = argv[i];
	    }
	    break;

	default :
	    _cupsLangPrintf(stderr,
	                    _("%s: Error - unknown option \'%c\'!\n"),
			    argv[0], argv[i][1]);
	    return (1);
      }
    else
    {
     /*
      * Cancel a job or printer...
      */

      if (num_dests == 0)
        num_dests = cupsGetDests(&dests);

      if (!strcmp(argv[i], "-"))
      {
       /*
        * Delete the current job...
	*/

        dest   = "";
	job_id = 0;
      }
      else if (cupsGetDest(argv[i], NULL, num_dests, dests) != NULL)
      {
       /*
        * Delete the current job on the named destination...
	*/

        dest   = argv[i];
	job_id = 0;
      }
      else if ((job = strrchr(argv[i], '-')) != NULL && isdigit(job[1] & 255))
      {
       /*
        * Delete the specified job ID.
	*/

        dest   = NULL;
	op     = IPP_CANCEL_JOB;
        job_id = atoi(job + 1);
      }
      else if (isdigit(argv[i][0] & 255))
      {
       /*
        * Delete the specified job ID.
	*/

        dest   = NULL;
	op     = IPP_CANCEL_JOB;
        job_id = atoi(argv[i]);
      }
      else
      {
       /*
        * Bad printer name!
	*/

        _cupsLangPrintf(stderr,
	                _("%s: Error - unknown destination \"%s\"!\n"),
			argv[0], argv[i]);
	return (1);
      }

     /*
      * For Solaris LP compatibility, ignore a destination name after
      * cancelling a specific job ID...
      */

      if (job_id && (i + 1) < argc &&
          cupsGetDest(argv[i + 1], NULL, num_dests, dests) != NULL)
        i ++;

     /*
      * Open a connection to the server...
      */

      if (http == NULL)
	if ((http = httpConnectEncrypt(cupsServer(), ippPort(),
	                               cupsEncryption())) == NULL)
	{
	  _cupsLangPrintf(stderr,
	                  _("%s: Unable to contact server!\n"),
			  argv[0]);
	  return (1);
	}

     /*
      * Build an IPP request, which requires the following
      * attributes:
      *
      *    attributes-charset
      *    attributes-natural-language
      *    printer-uri + job-id *or* job-uri
      *    [requesting-user-name]
      */

      request = ippNewRequest(op);

      if (dest)
      {
	httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
	                 "localhost", 0, "/printers/%s", dest);
	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI,
	             "printer-uri", NULL, uri);
	ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id",
	              job_id);
      }
      else
      {
        sprintf(uri, "ipp://localhost/jobs/%d", job_id);
	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL,
	             uri);
      }

      if (user)
      {
	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                     "requesting-user-name", NULL, user);
	ippAddBoolean(request, IPP_TAG_OPERATION, "my-jobs", 1);
      }
      else
	ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                     "requesting-user-name", NULL, cupsUser());

      if (op == IPP_PURGE_JOBS)
	ippAddBoolean(request, IPP_TAG_OPERATION, "purge-jobs", purge);

     /*
      * Do the request and get back a response...
      */

      if (op == IPP_PURGE_JOBS && (!user || strcasecmp(user, cupsUser())))
        response = cupsDoRequest(http, request, "/admin/");
      else
        response = cupsDoRequest(http, request, "/jobs/");

      if (response == NULL ||
          response->request.status.status_code > IPP_OK_CONFLICT)
      {
	_cupsLangPrintf(stderr, _("%s: %s failed: %s\n"), argv[0],
	        	op == IPP_PURGE_JOBS ? "purge-jobs" : "cancel-job",
        		cupsLastErrorString());

	if (response)
	  ippDelete(response);

	return (1);
      }

      ippDelete(response);
    }

  if (num_dests == 0 && op == IPP_PURGE_JOBS)
  {
   /*
    * Open a connection to the server...
    */

    if (http == NULL)
      if ((http = httpConnectEncrypt(cupsServer(), ippPort(),
	                             cupsEncryption())) == NULL)
      {
	_cupsLangPrintf(stderr, _("%s: Unable to contact server!\n"),
	                argv[0]);
	return (1);
      }

   /*
    * Build an IPP request, which requires the following
    * attributes:
    *
    *    attributes-charset
    *    attributes-natural-language
    *    printer-uri + job-id *or* job-uri
    *    [requesting-user-name]
    */

    request = ippNewRequest(op);

    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI,
	         "printer-uri", NULL, "ipp://localhost/printers/");

    if (user)
    {
      ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                   "requesting-user-name", NULL, user);
      ippAddBoolean(request, IPP_TAG_OPERATION, "my-jobs", 1);
    }
    else
      ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                   "requesting-user-name", NULL, cupsUser());

    ippAddBoolean(request, IPP_TAG_OPERATION, "purge-jobs", purge);

   /*
    * Do the request and get back a response...
    */

    response = cupsDoRequest(http, request, "/admin/");

    if (response == NULL ||
        response->request.status.status_code > IPP_OK_CONFLICT)
    {
      _cupsLangPrintf(stderr, _("%s: %s failed: %s\n"), argv[0],
		      op == IPP_PURGE_JOBS ? "purge-jobs" : "cancel-job",
        	      cupsLastErrorString());

      if (response)
	ippDelete(response);

      return (1);
    }

    ippDelete(response);
  }

  return (0);
}
Esempio n. 16
0
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line arguments */
     char *argv[])			/* I - Command-line arguments */
{
  const char	*printer;		/* Printer name */
  const char	*user;			/* Username */
  http_t	*http;			/* Connection to the server */
  ipp_t		*request,		/* IPP request */
		*response;		/* IPP response */
  ipp_attribute_t *attr;		/* IPP attribute */
  const char	*op;			/* Operation to perform, if any */
  static const char *def_attrs[] =	/* Attributes for default printer */
		{
		  "printer-name",
		  "printer-uri-supported"
		};


 /*
  * Get any form variables...
  */

  cgiInitialize();

  op = cgiGetVariable("OP");

 /*
  * Set the web interface section...
  */

  cgiSetVariable("SECTION", "printers");
  cgiSetVariable("REFRESH_PAGE", "");

 /*
  * See if we are displaying a printer or all printers...
  */

  if ((printer = getenv("PATH_INFO")) != NULL)
  {
    printer ++;

    if (!*printer)
      printer = NULL;

    if (printer)
      cgiSetVariable("PRINTER_NAME", printer);
  }

 /*
  * See who is logged in...
  */

  user = getenv("REMOTE_USER");

 /*
  * Connect to the HTTP server...
  */

  http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption());

 /*
  * Get the default printer...
  */

  if (!op || !cgiIsPOST())
  {
   /*
    * Get the default destination...
    */

    request = ippNewRequest(CUPS_GET_DEFAULT);

    ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
                  "requested-attributes",
		  sizeof(def_attrs) / sizeof(def_attrs[0]), NULL, def_attrs);

    if ((response = cupsDoRequest(http, request, "/")) != NULL)
    {
      if ((attr = ippFindAttribute(response, "printer-name", IPP_TAG_NAME)) != NULL)
        cgiSetVariable("DEFAULT_NAME", attr->values[0].string.text);

      if ((attr = ippFindAttribute(response, "printer-uri-supported", IPP_TAG_URI)) != NULL)
      {
	char	url[HTTP_MAX_URI];	/* New URL */


        cgiSetVariable("DEFAULT_URI",
	               cgiRewriteURL(attr->values[0].string.text,
		                     url, sizeof(url), NULL));
      }

      ippDelete(response);
    }

   /*
    * See if we need to show a list of printers or the status of a
    * single printer...
    */

    if (!printer)
      show_all_printers(http, user);
    else
      show_printer(http, printer);
  }
  else if (printer)
  {
    if (!*op)
    {
      const char *server_port = getenv("SERVER_PORT");
					/* Port number string */
      int	port = atoi(server_port ? server_port : "0");
      					/* Port number */
      char	uri[1024];		/* URL */

      httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri),
		       getenv("HTTPS") ? "https" : "http", NULL,
		       getenv("SERVER_NAME"), port, "/printers/%s", printer);

      printf("Location: %s\n\n", uri);
    }
    else if (!strcmp(op, "start-printer"))
      do_printer_op(http, printer, IPP_RESUME_PRINTER,
                    cgiText(_("Resume Printer")));
    else if (!strcmp(op, "stop-printer"))
      do_printer_op(http, printer, IPP_PAUSE_PRINTER,
                    cgiText(_("Pause Printer")));
    else if (!strcmp(op, "accept-jobs"))
      do_printer_op(http, printer, CUPS_ACCEPT_JOBS, cgiText(_("Accept Jobs")));
    else if (!strcmp(op, "reject-jobs"))
      do_printer_op(http, printer, CUPS_REJECT_JOBS, cgiText(_("Reject Jobs")));
    else if (!strcmp(op, "purge-jobs"))
      do_printer_op(http, printer, IPP_PURGE_JOBS, cgiText(_("Purge Jobs")));
    else if (!_cups_strcasecmp(op, "print-self-test-page"))
      cgiPrintCommand(http, printer, "PrintSelfTestPage",
                      cgiText(_("Print Self-Test Page")));
    else if (!_cups_strcasecmp(op, "clean-print-heads"))
      cgiPrintCommand(http, printer, "Clean all",
                      cgiText(_("Clean Print Heads")));
    else if (!_cups_strcasecmp(op, "print-test-page"))
      cgiPrintTestPage(http, printer);
    else if (!_cups_strcasecmp(op, "move-jobs"))
      cgiMoveJobs(http, printer, 0);
    else
    {
     /*
      * Unknown/bad operation...
      */

      cgiStartHTML(printer);
      cgiCopyTemplateLang("error-op.tmpl");
      cgiEndHTML();
    }
  }
  else
  {
   /*
    * Unknown/bad operation...
    */

    cgiStartHTML(cgiText(_("Printers")));
    cgiCopyTemplateLang("error-op.tmpl");
    cgiEndHTML();
  }

 /*
  * Close the HTTP server connection...
  */

  httpClose(http);

 /*
  * Return with no errors...
  */

  return (0);
}
Esempio n. 17
0
static int				/* O - Command status */
recv_print_job(
    const char    *queue,		/* I - Printer name */
    int           num_defaults,		/* I - Number of default options */
    cups_option_t *defaults)		/* I - Default options */
{
  http_t	*http;			/* HTTP connection */
  int		i;			/* Looping var */
  int		status;			/* Command status */
  int		fd;			/* Temporary file */
  FILE		*fp;			/* File pointer */
  char		filename[1024];		/* Temporary filename */
  ssize_t	bytes;			/* Bytes received */
  size_t	total;			/* Total bytes */
  char		line[256],		/* Line from file/stdin */
		command,		/* Command from line */
		*count,			/* Number of bytes */
		*name;			/* Name of file */
  const char	*job_sheets;		/* Job sheets */
  int		num_data;		/* Number of data files */
  char		control[1024],		/* Control filename */
		data[100][256],		/* Data files */
		temp[100][1024];	/* Temporary files */
  char		user[1024],		/* User name */
		title[1024],		/* Job title */
		docname[1024],		/* Document name */
		dest[256];		/* Printer/class queue */
  int		accepting,		/* printer-is-accepting */
		shared,			/* printer-is-shared */
		num_options;		/* Number of options */
  cups_option_t	*options;		/* Options */
  int		id;			/* Job ID */
  int		docnumber,		/* Current document number */
		doccount;		/* Count of documents */


 /*
  * Connect to the server...
  */

  http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption());
  if (!http)
  {
    syslog(LOG_ERR, "Unable to connect to server: %s", strerror(errno));

    putchar(1);

    return (1);
  }

 /*
  * See if the printer is available...
  */

  num_options = get_printer(http, queue, dest, sizeof(dest), &options,
                            &accepting, &shared, NULL);

  if (num_options < 0 || !accepting || !shared)
  {
    if (dest[0])
      syslog(LOG_INFO, "Rejecting job because \"%s\" is not %s", dest,
             !accepting ? "accepting jobs" : "shared");
    else
      syslog(LOG_ERR, "Unable to get printer information for \"%s\"", queue);

    httpClose(http);

    putchar(1);

    return (1);
  }

  putchar(0);				/* OK so far... */

 /*
  * Read the request...
  */

  status   = 0;
  num_data = 0;
  fd       = -1;

  control[0] = '\0';

  while (smart_gets(line, sizeof(line), stdin) != NULL)
  {
    if (strlen(line) < 2)
    {
      status = 1;
      break;
    }

    command = line[0];
    count   = line + 1;

    for (name = count + 1; *name && !isspace(*name & 255); name ++);
    while (isspace(*name & 255))
      *name++ = '\0';

    switch (command)
    {
      default :
      case 0x01 : /* Abort */
          status = 1;
	  break;

      case 0x02 : /* Receive control file */
          if (strlen(name) < 2)
	  {
	    syslog(LOG_ERR, "Bad control file name \"%s\"", name);
	    putchar(1);
	    status = 1;
	    break;
	  }

          if (control[0])
	  {
	   /*
	    * Append to the existing control file - the LPD spec is
	    * not entirely clear, but at least the OS/2 LPD code sends
	    * multiple control files per connection...
	    */

	    if ((fd = open(control, O_WRONLY)) < 0)
	    {
	      syslog(LOG_ERR,
	             "Unable to append to temporary control file \"%s\" - %s",
        	     control, strerror(errno));
	      putchar(1);
	      status = 1;
	      break;
	    }

	    lseek(fd, 0, SEEK_END);
          }
	  else
	  {
	    if ((fd = cupsTempFd(control, sizeof(control))) < 0)
	    {
	      syslog(LOG_ERR, "Unable to open temporary control file \"%s\" - %s",
        	     control, strerror(errno));
	      putchar(1);
	      status = 1;
	      break;
	    }

	    strlcpy(filename, control, sizeof(filename));
	  }
	  break;

      case 0x03 : /* Receive data file */
          if (strlen(name) < 2)
	  {
	    syslog(LOG_ERR, "Bad data file name \"%s\"", name);
	    putchar(1);
	    status = 1;
	    break;
	  }

          if (num_data >= (int)(sizeof(data) / sizeof(data[0])))
	  {
	   /*
	    * Too many data files...
	    */

	    syslog(LOG_ERR, "Too many data files (%d)", num_data);
	    putchar(1);
	    status = 1;
	    break;
	  }

	  strlcpy(data[num_data], name, sizeof(data[0]));

          if ((fd = cupsTempFd(temp[num_data], sizeof(temp[0]))) < 0)
	  {
	    syslog(LOG_ERR, "Unable to open temporary data file \"%s\" - %s",
        	   temp[num_data], strerror(errno));
	    putchar(1);
	    status = 1;
	    break;
	  }

	  strlcpy(filename, temp[num_data], sizeof(filename));

          num_data ++;
	  break;
    }

    putchar(status);

    if (status)
      break;

   /*
    * Copy the data or control file from the client...
    */

    for (total = (size_t)strtoll(count, NULL, 10); total > 0; total -= (size_t)bytes)
    {
      if (total > sizeof(line))
        bytes = (ssize_t)sizeof(line);
      else
        bytes = (ssize_t)total;

      if ((bytes = (ssize_t)fread(line, 1, (size_t)bytes, stdin)) > 0)
        bytes = write(fd, line, (size_t)bytes);

      if (bytes < 1)
      {
	syslog(LOG_ERR, "Error while reading file - %s",
               strerror(errno));
        status = 1;
	break;
      }
    }

   /*
    * Read trailing nul...
    */

    if (!status)
    {
      if (fread(line, 1, 1, stdin) < 1)
      {
        status = 1;
	syslog(LOG_ERR, "Error while reading trailing nul - %s",
               strerror(errno));
      }
      else if (line[0])
      {
        status = 1;
	syslog(LOG_ERR, "Trailing character after file is not nul (%02X)!",
	       line[0]);
      }
    }

   /*
    * Close the file and send an acknowledgement...
    */

    close(fd);

    putchar(status);

    if (status)
      break;
  }

  if (!status)
  {
   /*
    * Process the control file and print stuff...
    */

    if ((fp = fopen(control, "rb")) == NULL)
      status = 1;
    else
    {
     /*
      * Copy the default options...
      */

      for (i = 0; i < num_defaults; i ++)
	num_options = cupsAddOption(defaults[i].name,
		                    defaults[i].value,
		                    num_options, &options);

     /*
      * Grab the job information...
      */

      title[0]   = '\0';
      user[0]    = '\0';
      docname[0] = '\0';
      doccount   = 0;

      while (smart_gets(line, sizeof(line), fp) != NULL)
      {
       /*
        * Process control lines...
	*/

	switch (line[0])
	{
	  case 'J' : /* Job name */
	      strlcpy(title, line + 1, sizeof(title));
	      break;

          case 'N' : /* Document name */
              strlcpy(docname, line + 1, sizeof(docname));
              break;

	  case 'P' : /* User identification */
	      strlcpy(user, line + 1, sizeof(user));
	      break;

	  case 'L' : /* Print banner page */
	     /*
	      * If a banner was requested and it's not overridden by a
	      * command line option and the destination's default is none
	      * then add the standard banner...
	      */

	      if (cupsGetOption("job-sheets", num_defaults, defaults) == NULL &&
        	  ((job_sheets = cupsGetOption("job-sheets", num_options,
					       options)) == NULL ||
        	   !strcmp(job_sheets, "none,none")))
	      {
		num_options = cupsAddOption("job-sheets", "standard",
		                	    num_options, &options);
	      }
	      break;

	  case 'c' : /* Plot CIF file */
	  case 'd' : /* Print DVI file */
	  case 'f' : /* Print formatted file */
	  case 'g' : /* Plot file */
	  case 'l' : /* Print file leaving control characters (raw) */
	  case 'n' : /* Print ditroff output file */
	  case 'o' : /* Print PostScript output file */
	  case 'p' : /* Print file with 'pr' format (prettyprint) */
	  case 'r' : /* File to print with FORTRAN carriage control */
	  case 't' : /* Print troff output file */
	  case 'v' : /* Print raster file */
	      doccount ++;

	      if (line[0] == 'l' &&
	          !cupsGetOption("document-format", num_options, options))
		num_options = cupsAddOption("raw", "", num_options, &options);

              if (line[0] == 'p')
		num_options = cupsAddOption("prettyprint", "", num_options,
		                	    &options);
              break;
	}

	if (status)
	  break;
      }

     /*
      * Check that we have a username...
      */

      if (!user[0])
      {
	syslog(LOG_WARNING, "No username specified by client! "
		            "Using \"anonymous\"...");
	strlcpy(user, "anonymous", sizeof(user));
      }

     /*
      * Create the job...
      */

      if ((id = create_job(http, dest, title, docname, user, num_options,
                           options)) < 0)
        status = 1;
      else
      {
       /*
	* Then print the job files...
	*/

	rewind(fp);

	docname[0] = '\0';
	docnumber  = 0;

	while (smart_gets(line, sizeof(line), fp) != NULL)
	{
	 /*
          * Process control lines...
	  */

	  switch (line[0])
	  {
	    case 'N' : /* Document name */
		strlcpy(docname, line + 1, sizeof(docname));
		break;

	    case 'c' : /* Plot CIF file */
	    case 'd' : /* Print DVI file */
	    case 'f' : /* Print formatted file */
	    case 'g' : /* Plot file */
	    case 'l' : /* Print file leaving control characters (raw) */
	    case 'n' : /* Print ditroff output file */
	    case 'o' : /* Print PostScript output file */
	    case 'p' : /* Print file with 'pr' format (prettyprint) */
	    case 'r' : /* File to print with FORTRAN carriage control */
	    case 't' : /* Print troff output file */
	    case 'v' : /* Print raster file */
               /*
		* Figure out which file we are printing...
		*/

		for (i = 0; i < num_data; i ++)
	          if (!strcmp(data[i], line + 1))
		    break;

        	if (i >= num_data)
		{
	          status = 1;
		  break;
		}

               /*
		* Send the print file...
		*/

        	docnumber ++;

        	if (print_file(http, id, temp[i], docname, user,
		               cupsGetOption("document-format", num_options,
			                     options),
	                       docnumber == doccount))
                  status = 1;
		else
	          status = 0;

		break;
	  }

	  if (status)
	    break;
	}
      }

      fclose(fp);
    }
  }

  cupsFreeOptions(num_options, options);

  httpClose(http);

 /*
  * Clean up all temporary files and return...
  */

  unlink(control);

  for (i = 0; i < num_data; i ++)
    unlink(temp[i]);

  return (status);
}
Esempio n. 18
0
static int				/* O - Command status */
send_state(const char *queue,		/* I - Destination */
           const char *list,		/* I - Job or user */
	   int        longstatus)	/* I - List of jobs or users */
{
  int		id;			/* Job ID from list */
  http_t	*http;			/* HTTP server connection */
  ipp_t		*request,		/* IPP Request */
		*response;		/* IPP Response */
  ipp_attribute_t *attr;		/* Current attribute */
  ipp_pstate_t	state;			/* Printer state */
  const char	*jobdest,		/* Pointer into job-printer-uri */
		*jobuser,		/* Pointer to job-originating-user-name */
		*jobname;		/* Pointer to job-name */
  ipp_jstate_t	jobstate;		/* job-state */
  int		jobid,			/* job-id */
		jobsize,		/* job-k-octets */
		jobcount,		/* Number of jobs */
		jobcopies,		/* Number of copies */
		rank;			/* Rank of job */
  char		rankstr[255];		/* Rank string */
  char		namestr[1024];		/* Job name string */
  char		uri[HTTP_MAX_URI];	/* Printer URI */
  char		dest[256];		/* Printer/class queue */
  static const char * const ranks[10] =	/* Ranking strings */
		{
		  "th",
		  "st",
		  "nd",
		  "rd",
		  "th",
		  "th",
		  "th",
		  "th",
		  "th",
		  "th"
		};
  static const char * const requested[] =
		{			/* Requested attributes */
		  "job-id",
		  "job-k-octets",
		  "job-state",
		  "job-printer-uri",
		  "job-originating-user-name",
		  "job-name",
		  "copies"
		};


 /*
  * Try connecting to the local server...
  */

  if ((http = httpConnectEncrypt(cupsServer(), ippPort(),
                                 cupsEncryption())) == NULL)
  {
    syslog(LOG_ERR, "Unable to connect to server %s: %s", cupsServer(),
           strerror(errno));
    printf("Unable to connect to server %s: %s", cupsServer(), strerror(errno));
    return (1);
  }

 /*
  * Get the actual destination name and printer state...
  */

  if (get_printer(http, queue, dest, sizeof(dest), NULL, NULL, NULL, &state))
  {
    syslog(LOG_ERR, "Unable to get printer %s: %s", queue,
           cupsLastErrorString());
    printf("Unable to get printer %s: %s", queue, cupsLastErrorString());
    return (1);
  }

 /*
  * Show the queue state...
  */

  switch (state)
  {
    case IPP_PRINTER_IDLE :
        printf("%s is ready\n", dest);
	break;
    case IPP_PRINTER_PROCESSING :
        printf("%s is ready and printing\n", dest);
	break;
    case IPP_PRINTER_STOPPED :
        printf("%s is not ready\n", dest);
	break;
  }

 /*
  * Build an IPP_GET_JOBS or IPP_GET_JOB_ATTRIBUTES request, which requires
  * the following attributes:
  *
  *    attributes-charset
  *    attributes-natural-language
  *    job-uri or printer-uri
  */

  id = atoi(list);

  request = ippNewRequest(id ? IPP_GET_JOB_ATTRIBUTES : IPP_GET_JOBS);

  httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
                   "localhost", 0, "/printers/%s", dest);

  ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
               NULL, uri);

  if (id)
    ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id", id);
  else
  {
    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                 "requesting-user-name", NULL, list);
    ippAddBoolean(request, IPP_TAG_OPERATION, "my-jobs", 1);
  }

  ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
                "requested-attributes",
	        sizeof(requested) / sizeof(requested[0]),
		NULL, requested);

 /*
  * Do the request and get back a response...
  */

  jobcount = 0;
  response = cupsDoRequest(http, request, "/");

  if (cupsLastError() > IPP_OK_CONFLICT)
  {
    printf("get-jobs failed: %s\n", cupsLastErrorString());
    ippDelete(response);
    return (1);
  }

 /*
  * Loop through the job list and display them...
  */

  for (attr = response->attrs, rank = 1; attr; attr = attr->next)
  {
   /*
    * Skip leading attributes until we hit a job...
    */

    while (attr && (attr->group_tag != IPP_TAG_JOB || !attr->name))
      attr = attr->next;

    if (!attr)
      break;

   /*
    * Pull the needed attributes from this job...
    */

    jobid     = 0;
    jobsize   = 0;
    jobstate  = IPP_JOB_PENDING;
    jobname   = "untitled";
    jobuser   = NULL;
    jobdest   = NULL;
    jobcopies = 1;

    while (attr && attr->group_tag == IPP_TAG_JOB)
    {
      if (!strcmp(attr->name, "job-id") &&
	  attr->value_tag == IPP_TAG_INTEGER)
	jobid = attr->values[0].integer;

      if (!strcmp(attr->name, "job-k-octets") &&
	  attr->value_tag == IPP_TAG_INTEGER)
	jobsize = attr->values[0].integer;

      if (!strcmp(attr->name, "job-state") &&
	  attr->value_tag == IPP_TAG_ENUM)
	jobstate = (ipp_jstate_t)attr->values[0].integer;

      if (!strcmp(attr->name, "job-printer-uri") &&
	  attr->value_tag == IPP_TAG_URI)
	if ((jobdest = strrchr(attr->values[0].string.text, '/')) != NULL)
	  jobdest ++;

      if (!strcmp(attr->name, "job-originating-user-name") &&
	  attr->value_tag == IPP_TAG_NAME)
	jobuser = attr->values[0].string.text;

      if (!strcmp(attr->name, "job-name") &&
	  attr->value_tag == IPP_TAG_NAME)
	jobname = attr->values[0].string.text;

      if (!strcmp(attr->name, "copies") &&
	  attr->value_tag == IPP_TAG_INTEGER)
	jobcopies = attr->values[0].integer;

      attr = attr->next;
    }

   /*
    * See if we have everything needed...
    */

    if (!jobdest || !jobid)
    {
      if (!attr)
	break;
      else
        continue;
    }

    if (!longstatus && jobcount == 0)
      puts("Rank    Owner   Job     File(s)                         Total Size");

    jobcount ++;

   /*
    * Display the job...
    */

    if (jobstate == IPP_JOB_PROCESSING)
      strlcpy(rankstr, "active", sizeof(rankstr));
    else
    {
      snprintf(rankstr, sizeof(rankstr), "%d%s", rank, ranks[rank % 10]);
      rank ++;
    }

    if (longstatus)
    {
      puts("");

      if (jobcopies > 1)
	snprintf(namestr, sizeof(namestr), "%d copies of %s", jobcopies,
	         jobname);
      else
	strlcpy(namestr, jobname, sizeof(namestr));

      printf("%s: %-33.33s [job %d localhost]\n", jobuser, rankstr, jobid);
      printf("        %-39.39s %.0f bytes\n", namestr, 1024.0 * jobsize);
    }
    else
      printf("%-7s %-7.7s %-7d %-31.31s %.0f bytes\n", rankstr, jobuser,
	     jobid, jobname, 1024.0 * jobsize);

    if (!attr)
      break;
  }

  ippDelete(response);

  if (jobcount == 0)
    puts("no entries");

  httpClose(http);

  return (0);
}
Esempio n. 19
0
static int				/* O - Command status */
remove_jobs(const char *dest,		/* I - Destination */
            const char *agent,		/* I - User agent */
	    const char *list)		/* I - List of jobs or users */
{
  int		id;			/* Job ID */
  http_t	*http;			/* HTTP server connection */
  ipp_t		*request;		/* IPP Request */
  char		uri[HTTP_MAX_URI];	/* Job URI */


  (void)dest;	/* Suppress compiler warnings... */

 /*
  * Try connecting to the local server...
  */

  if ((http = httpConnectEncrypt(cupsServer(), ippPort(),
                                 cupsEncryption())) == NULL)
  {
    syslog(LOG_ERR, "Unable to connect to server %s: %s", cupsServer(),
           strerror(errno));
    return (1);
  }

 /*
  * Loop for each job...
  */

  while ((id = atoi(list)) > 0)
  {
   /*
    * Skip job ID in list...
    */

    while (isdigit(*list & 255))
      list ++;
    while (isspace(*list & 255))
      list ++;

   /*
    * Build an IPP_CANCEL_JOB request, which requires the following
    * attributes:
    *
    *    attributes-charset
    *    attributes-natural-language
    *    job-uri
    *    requesting-user-name
    */

    request = ippNewRequest(IPP_CANCEL_JOB);

    sprintf(uri, "ipp://localhost/jobs/%d", id);
    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri);

    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                 "requesting-user-name", NULL, agent);

   /*
    * Do the request and get back a response...
    */

    ippDelete(cupsDoRequest(http, request, "/jobs"));

    if (cupsLastError() > IPP_OK_CONFLICT)
    {
      syslog(LOG_WARNING, "Cancel of job ID %d failed: %s\n", id,
             cupsLastErrorString());
      httpClose(http);
      return (1);
    }
    else
      syslog(LOG_INFO, "Job ID %d canceled", id);
  }

  httpClose(http);

  return (0);
}
Esempio n. 20
0
static void
cups_create_localizations(
    http_t       *http,			/* I - Connection to destination */
    cups_dinfo_t *dinfo)		/* I - Destination informations */
{
  http_t		*http2;		/* Connection for strings file */
  http_status_t		status;		/* Request status */
  ipp_attribute_t	*attr;		/* "printer-strings-uri" attribute */
  char			scheme[32],	/* URI scheme */
  			userpass[256],	/* Username/password info */
  			hostname[256],	/* Hostname */
  			resource[1024],	/* Resource */
  			http_hostname[256],
  					/* Hostname of connection */
			tempfile[1024];	/* Temporary filename */
  int			port;		/* Port number */
  http_encryption_t	encryption;	/* Encryption to use */
  cups_file_t		*temp;		/* Temporary file */


 /*
  * Create an empty message catalog...
  */

  dinfo->localizations = _cupsMessageNew(NULL);

 /*
  * See if there are any localizations...
  */

  if ((attr = ippFindAttribute(dinfo->attrs, "printer-strings-uri",
                               IPP_TAG_URI)) == NULL)
  {
   /*
    * Nope...
    */

    DEBUG_puts("4cups_create_localizations: No printer-strings-uri (uri) "
               "value.");
    return;				/* Nope */
  }

 /*
  * Pull apart the URI and determine whether we need to try a different
  * server...
  */

  if (httpSeparateURI(HTTP_URI_CODING_ALL, attr->values[0].string.text,
                      scheme, sizeof(scheme), userpass, sizeof(userpass),
                      hostname, sizeof(hostname), &port, resource,
                      sizeof(resource)) < HTTP_URI_OK)
  {
    DEBUG_printf(("4cups_create_localizations: Bad printer-strings-uri value "
                  "\"%s\".", attr->values[0].string.text));
    return;
  }

  httpGetHostname(http, http_hostname, sizeof(http_hostname));

  if (!_cups_strcasecmp(http_hostname, hostname) &&
      port == _httpAddrPort(http->hostaddr))
  {
   /*
    * Use the same connection...
    */

    http2 = http;
  }
  else
  {
   /*
    * Connect to the alternate host...
    */

    if (!strcmp(scheme, "https"))
      encryption = HTTP_ENCRYPT_ALWAYS;
    else
      encryption = HTTP_ENCRYPT_IF_REQUESTED;

    if ((http2 = httpConnectEncrypt(hostname, port, encryption)) == NULL)
    {
      DEBUG_printf(("4cups_create_localizations: Unable to connect to "
                    "%s:%d: %s", hostname, port, cupsLastErrorString()));
      return;
    }
  }

 /*
  * Get a temporary file...
  */

  if ((temp = cupsTempFile2(tempfile, sizeof(tempfile))) == NULL)
  {
    DEBUG_printf(("4cups_create_localizations: Unable to create temporary "
                  "file: %s", cupsLastErrorString()));
    if (http2 != http)
      httpClose(http2);
    return;
  }

  status = cupsGetFd(http2, resource, cupsFileNumber(temp));

  DEBUG_printf(("4cups_create_localizations: GET %s = %s", resource,
                httpStatus(status)));

  if (status == HTTP_OK)
  {
   /*
    * Got the file, read it...
    */

    char		buffer[8192],	/* Message buffer */
    			*id,		/* ID string */
    			*str;		/* Translated message */
    _cups_message_t	*m;		/* Current message */

    lseek(cupsFileNumber(temp), 0, SEEK_SET);

    while (cups_read_strings(temp, buffer, sizeof(buffer), &id, &str))
    {
      if ((m = malloc(sizeof(_cups_message_t))) == NULL)
        break;

      m->id  = strdup(id);
      m->str = strdup(str);

      if (m->id && m->str)
        cupsArrayAdd(dinfo->localizations, m);
      else
      {
        if (m->id)
          free(m->id);

        if (m->str)
          free(m->str);

        free(m);
        break;
      }
    }
  }

  DEBUG_printf(("4cups_create_localizations: %d messages loaded.",
                cupsArrayCount(dinfo->localizations)));

 /*
  * Cleanup...
  */

  unlink(tempfile);
  cupsFileClose(temp);

  if (http2 != http)
    httpClose(http2);
}
Esempio n. 21
0
///////////////////////////////////////////////////////////////////////////////////////////
//
// CS     : PRIVATE gint getPrinterURI(gchar *pDestName, gchar *pURI, gchar *pServerName, gint bufSize)
// IN     : gchar *pDestName : Printer name.
//          gint bufSize : Size of output buffer.
// OUT    : gchar *pURI : Printer URI.
//          gchar *pServerName : Server name.
// RETURN : ID_ERR_NO_ERROR : No error.
//          ID_ERR_CUPS_API_FAILED : Error occured in CUPS API.
//
PRIVATE gint getPrinterURI(gchar *pDestName, gchar *pURI, gchar *pServerName, gint bufSize)
{
/*** Parameters start ***/
	http_t			*pHTTP;						// Pointer to HTTP connection.
	ipp_t			*pRequest,					// Pointer to CUPS IPP request.
					*pResponse;					// Pointer to CUPS IPP response.
	ipp_attribute_t	*pAttribute;				// Pointer to CUPS attributes.
	cups_lang_t		*pLanguage;					// Pointer to language.
	gchar			*pPrinter = NULL;			// Pointer to printer name.
	gchar			*pUri = NULL;				// Pointer to printer uri.
	gchar			*pTemp = NULL;				// Temporary pointer.
	gint			i;							// Counter.
	gint			retVal = ID_ERR_NO_ERROR;	// Return value.
	const char		*attributes[] = {			// Attributes name set.
						"printer-name",
						"printer-uri-supported",
					};
/*** Parameters end ***/

	// CUPS http connect.
	if ((pHTTP = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption())) == NULL) {
		retVal = ID_ERR_CUPS_API_FAILED;
	}
	else {
		pRequest = ippNew();

		ippSetOperation(pRequest, CUPS_GET_PRINTERS);
		ippSetRequestId(pRequest, 1);

		pLanguage = bjcupsLangDefault();	// cupsLangDefault() -> bjcupsLangDefault() for cups-1.1.19

		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, cupsLangEncoding(pLanguage));
		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, pLanguage->language);
		ippAddStrings(pRequest, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", sizeof(attributes) / sizeof(attributes[0]), NULL, attributes);

		if ((pResponse = cupsDoRequest(pHTTP, pRequest, "/")) != NULL) {
			if (ippGetStatusCode(pResponse) > IPP_OK_CONFLICT) {
				retVal = ID_ERR_CUPS_API_FAILED;
			}
			else {
				pAttribute = ippFirstAttribute(pResponse);

				while (pAttribute != NULL) {
					while (pAttribute != NULL && ippGetGroupTag(pAttribute) != IPP_TAG_PRINTER) {
						pAttribute = bjcups_ippNextAttribute(pRequest, pAttribute);
					}
					if (pAttribute == NULL) {
						break;
					}

					while (pAttribute != NULL && ippGetGroupTag(pAttribute) == IPP_TAG_PRINTER) {
						if (strcmp(ippGetName(pAttribute), "printer-name") == 0 && ippGetValueTag(pAttribute) == IPP_TAG_NAME) {
							pPrinter = ippGetString(pAttribute, 0, NULL);
						}
						if (strcmp(ippGetName(pAttribute), "printer-uri-supported") == 0 && ippGetValueTag(pAttribute) == IPP_TAG_URI) {
							pUri = ippGetString(pAttribute, 0, NULL);
						}
						pAttribute = bjcups_ippNextAttribute(pRequest, pAttribute);
					}

					// Tora 020418: Compare two printer names ignoring the character case.
					if (strcasecmp(pDestName, pPrinter) == 0) {
						strncpy(pURI, pUri, bufSize);

						pTemp = strstr(pURI, "//");
						pTemp += 2;
						for (i = 0; *pTemp != '/' && *pTemp != ':'; i++, pTemp++) {
							pServerName[i] = *pTemp;
						}

						break;
					}

					if (pAttribute != NULL)
						 pAttribute = bjcups_ippNextAttribute(pRequest, pAttribute);
				}
			}

			ippDelete(pResponse);
		}
		else {
			retVal = ID_ERR_CUPS_API_FAILED;
		}

		cupsLangFree(pLanguage);
		httpClose(pHTTP);
	}

	if (pURI[0] == '\0') {
		snprintf(pURI, bufSize, "ipp://localhost/printers/%s", pDestName);
	}
	if (pServerName[0] == '\0') {
		strncpy(pServerName, "localhost", strlen("localhost"));
	}

	return(retVal);
}// End getPrinterURI
Esempio n. 22
0
///////////////////////////////////////////////////////////////////////////////////////////
//
// CS     : PRIVATE gint getJobID(gchar *pDestName, gchar *pURI, gchar *pServerName, gint *pJobID)
// IN     : gchar *pDestName : Printer name.
//          gchar *pURI : Printer URI.
//          gchar *pServerName : CUPS server name.
// OUT    : gint *pJobID : Job ID.
// RETURN : ID_ERR_NO_ERROR : No error.
//          ID_ERR_CUPS_API_FAILED : Error occured in CUPS API.
//
PRIVATE gint getJobID(gchar *pDestName, gchar *pURI, gchar *pServerName, gint *pJobID)
{
/*** Parameters start ***/
	http_t			*pHTTP;									// Pointer to HTTP connection.
	ipp_t			*pRequest,								// Pointer to CUPS IPP request.
					*pResponse;								// Pointer to CUPS IPP response.
	ipp_attribute_t	*pAttribute;							// Pointer to CUPS attributes.
	cups_lang_t		*pLanguage;								// Pointer to language.
	ipp_jstate_t	jobState = 0;							// Job state.
	gint			jobID = 0;								// Job ID.
	gchar			*pJobUserName = NULL;					// User name of print job.
	uid_t			userID;									// User ID.
	struct passwd	*pPasswd;								// Pointer to password structure.
	gint			retVal = ID_ERR_PRINT_JOB_NOT_EXIST;	// Return value.
/*** Parameters end ***/

	// Get login name.
	userID = getuid();
	pPasswd = getpwuid(userID);

	// CUPS http connect.
	if ((pHTTP = httpConnectEncrypt(pServerName, ippPort(), cupsEncryption())) == NULL) {
		retVal = ID_ERR_CUPS_API_FAILED;
	}
	else {
		pRequest = ippNew();

		ippSetOperation(pRequest, IPP_GET_JOBS);
		ippSetRequestId(pRequest, 1);

		pLanguage = bjcupsLangDefault();	// cupsLangDefault() -> bjcupsLangDefault() for cups-1.1.19

		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, cupsLangEncoding(pLanguage));
		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, pLanguage->language);
		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, pURI);
		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());

		if ((pResponse = cupsDoRequest(pHTTP, pRequest, "/")) != NULL) {
            int statusCode = ippGetStatusCode(pResponse);
			if (statusCode > IPP_OK_CONFLICT) {
				retVal = ID_ERR_CUPS_API_FAILED;
			}
			else {
				pAttribute = ippFirstAttribute(pResponse);

				while (pAttribute != NULL) {
					while (pAttribute != NULL && ippGetGroupTag(pAttribute) != IPP_TAG_JOB) {
						pAttribute = bjcups_ippNextAttribute(pResponse, pAttribute);
					}
					if (pAttribute == NULL) {
						break;
					}

					while (pAttribute != NULL && ippGetGroupTag(pAttribute) == IPP_TAG_JOB) {
						if (strcmp(ippGetName(pAttribute), "job-id") == 0 && ippGetValueTag(pAttribute) == IPP_TAG_INTEGER) {
							jobID = ippGetInteger(pAttribute, 0);
						}
						if (strcmp(ippGetName(pAttribute), "job-uri") == 0 && ippGetValueTag(pAttribute) == IPP_TAG_URI) {
							pJobUserName=getJobState(pDestName,ippGetString(pAttribute, 0, NULL),pServerName,&jobState,pJobUserName);
						}
						pAttribute = bjcups_ippNextAttribute(pRequest, pAttribute);
					}
					if (jobState == IPP_JOB_PROCESSING) {
						if (pJobUserName != NULL) {
							if (strcmp(pPasswd->pw_name, pJobUserName) == 0) {
								retVal = ID_ERR_NO_ERROR;
							}
							else if (pJobUserName[0] == '\0') {
								retVal = ID_ERR_NO_ERROR;
							}
						}
						break;
					}

					if (pAttribute != NULL)
						pAttribute = bjcups_ippNextAttribute(pRequest, pAttribute);
				}
			}

			ippDelete(pResponse);
		}
		else {
			retVal = ID_ERR_CUPS_API_FAILED;
		}

		cupsLangFree(pLanguage);
		httpClose(pHTTP);
	}

	if (retVal == ID_ERR_NO_ERROR && pJobID != NULL) {
		*pJobID = jobID;
	}

	return(retVal);
}// End getJobID
Esempio n. 23
0
static mxml_node_t *			/* O - XML file or NULL */
load_xml(const char *reg_file)		/* I - Filename or URL */
{
  mxml_node_t		*xml;		/* XML file */
  char			scheme[256],	/* Scheme */
			userpass[256],	/* Username and password */
			hostname[256],	/* Hostname */
			resource[1024],	/* Resource path */
			filename[1024];	/* Temporary file */
  int			port,		/* Port number */
			fd;		/* File descriptor */


  if (httpSeparateURI(HTTP_URI_CODING_ALL, reg_file, scheme, sizeof(scheme),
                      userpass, sizeof(userpass), hostname, sizeof(hostname),
                      &port, resource, sizeof(resource)) < HTTP_URI_OK)
  {
    fprintf(stderr, "xmltotest: Bad URI or filename \"%s\".\n", reg_file);
    return (NULL);
  }

  if (!strcmp(scheme, "file"))
  {
   /*
    * Local file...
    */

    if ((fd = open(resource, O_RDONLY)) < 0)
    {
      fprintf(stderr, "xmltotest: Unable to open \"%s\": %s\n", resource,
              strerror(errno));
      return (NULL);
    }

    filename[0] = '\0';
  }
  else if (strcmp(scheme, "http") && strcmp(scheme, "https"))
  {
    fprintf(stderr, "xmltotest: Unsupported URI scheme \"%s\".\n", scheme);
    return (NULL);
  }
  else
  {
    http_t		*http;		/* HTTP connection */
    http_encryption_t	encryption;	/* Encryption to use */
    http_status_t	status;		/* Status of HTTP GET */

    if (!strcmp(scheme, "https") || port == 443)
      encryption = HTTP_ENCRYPT_ALWAYS;
    else
      encryption = HTTP_ENCRYPT_IF_REQUESTED;

    if ((http = httpConnectEncrypt(hostname, port, encryption)) == NULL)
    {
      fprintf(stderr, "xmltotest: Unable to connect to \"%s\": %s\n", hostname,
              cupsLastErrorString());
      return (NULL);
    }

    if ((fd = cupsTempFd(filename, sizeof(filename))) < 0)
    {
      fprintf(stderr, "xmltotest: Unable to create temporary file: %s\n",
              strerror(errno));
      httpClose(http);
      return (NULL);
    }

    status = cupsGetFd(http, resource, fd);
    httpClose(http);

    if (status != HTTP_OK)
    {
      fprintf(stderr, "mxmltotest: Unable to get \"%s\": %d\n", reg_file,
              status);
      close(fd);
      unlink(filename);
      return (NULL);
    }

    lseek(fd, 0, SEEK_SET);
  }

 /*
  * Load the XML file...
  */

  xml = mxmlLoadFd(NULL, fd, MXML_OPAQUE_CALLBACK);

  close(fd);

  if (filename[0])
    unlink(filename);

  return (xml);
}
Esempio n. 24
0
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line args */
     char *argv[])			/* I - Command-line arguments */
{
  int		i,			/* Looping var */
		num_settings;		/* Number of settings */
  cups_option_t	*settings;		/* Settings */
  const char	*opt;			/* Current option character */
  http_t	*http;			/* Connection to server */


 /*
  * Process the command-line...
  */

  _cupsSetLocale(argv);

  num_settings = 0;
  settings     = NULL;

  for (i = 1; i < argc; i ++)
  {
    if (!strcmp(argv[i], "--help"))
      usage(NULL);
    else if (argv[i][0] == '-')
    {
      if (argv[i][1] == '-')
      {
        if (!strcmp(argv[i], "--debug-logging"))
	  num_settings = cupsAddOption(CUPS_SERVER_DEBUG_LOGGING, "1",
	                               num_settings, &settings);
        else if (!strcmp(argv[i], "--no-debug-logging"))
	  num_settings = cupsAddOption(CUPS_SERVER_DEBUG_LOGGING, "0",
	                               num_settings, &settings);
        else if (!strcmp(argv[i], "--remote-admin"))
	  num_settings = cupsAddOption(CUPS_SERVER_REMOTE_ADMIN, "1",
	                               num_settings, &settings);
        else if (!strcmp(argv[i], "--no-remote-admin"))
	  num_settings = cupsAddOption(CUPS_SERVER_REMOTE_ADMIN, "0",
	                               num_settings, &settings);
        else if (!strcmp(argv[i], "--remote-any"))
	  num_settings = cupsAddOption(CUPS_SERVER_REMOTE_ANY, "1",
	                               num_settings, &settings);
        else if (!strcmp(argv[i], "--no-remote-any"))
	  num_settings = cupsAddOption(CUPS_SERVER_REMOTE_ANY, "0",
	                               num_settings, &settings);
        else if (!strcmp(argv[i], "--share-printers"))
	  num_settings = cupsAddOption(CUPS_SERVER_SHARE_PRINTERS, "1",
	                               num_settings, &settings);
        else if (!strcmp(argv[i], "--no-share-printers"))
	  num_settings = cupsAddOption(CUPS_SERVER_SHARE_PRINTERS, "0",
	                               num_settings, &settings);
        else if (!strcmp(argv[i], "--user-cancel-any"))
	  num_settings = cupsAddOption(CUPS_SERVER_USER_CANCEL_ANY, "1",
	                               num_settings, &settings);
        else if (!strcmp(argv[i], "--no-user-cancel-any"))
	  num_settings = cupsAddOption(CUPS_SERVER_USER_CANCEL_ANY, "0",
	                               num_settings, &settings);
        else
	  usage(argv[i]);
      }
      else
      {
        for (opt = argv[i] + 1; *opt; opt ++)
	  switch (*opt)
	  {
	    case 'E' :
	        cupsSetEncryption(HTTP_ENCRYPT_REQUIRED);
	        break;

	    case 'U' :
	        i ++;
		if (i >= argc)
		  usage(NULL);

                cupsSetUser(argv[i]);
	        break;

	    case 'h' :
	        i ++;
		if (i >= argc)
		  usage(NULL);

                cupsSetServer(argv[i]);
	        break;

	    default :
	        usage(opt);
		break;
	  }
      }
    }
    else if (strchr(argv[i], '='))
      num_settings = cupsParseOptions(argv[i], num_settings, &settings);
    else
      usage(argv[i]);
  }

  if (cupsGetOption("Listen", num_settings, settings) ||
      cupsGetOption("Port", num_settings, settings))
  {
    _cupsLangPuts(stderr, _("cupsctl: Cannot set Listen or Port directly."));
    return (1);
  }

 /*
  * Connect to the server using the defaults...
  */

  if ((http = httpConnectEncrypt(cupsServer(), ippPort(),
                                 cupsEncryption())) == NULL)
  {
    _cupsLangPrintf(stderr, _("cupsctl: Unable to connect to server: %s"),
                    strerror(errno));
    return (1);
  }

 /*
  * Set the current configuration if we have anything on the command-line...
  */

  if (num_settings > 0)
  {
    if (!cupsAdminSetServerSettings(http, num_settings, settings))
    {
      _cupsLangPrintf(stderr, "cupsctl: %s", cupsLastErrorString());
      return (1);
    }
  }
  else if (!cupsAdminGetServerSettings(http, &num_settings, &settings))
  {
    _cupsLangPrintf(stderr, "cupsctl: %s", cupsLastErrorString());
    return (1);
  }
  else
  {
    for (i = 0; i < num_settings; i ++)
      _cupsLangPrintf(stdout, "%s=%s", settings[i].name, settings[i].value);
  }

  cupsFreeOptions(num_settings, settings);
  return (0);
}
Esempio n. 25
0
const char *				/* O - Filename for PPD file */
cupsGetPPD2(http_t     *http,		/* I - HTTP connection */
            const char *name)		/* I - Printer name */
{
    int		http_port;		/* Port number */
    char		http_hostname[HTTP_MAX_HOST];
    /* Hostname associated with connection */
    http_t	*http2;			/* Alternate HTTP connection */
    int		fd;			/* PPD file */
    char		localhost[HTTP_MAX_URI],/* Local hostname */
                hostname[HTTP_MAX_URI],	/* Hostname */
                resource[HTTP_MAX_URI];	/* Resource name */
    int		port;			/* Port number */
    http_status_t	status;			/* HTTP status from server */
    _cups_globals_t *cg = _cupsGlobals();	/* Pointer to library globals */


    /*
     * Range check input...
     */

    DEBUG_printf(("cupsGetPPD2(http=%p, name=\"%s\")\n", http,
                  name ? name : "(null)"));

    if (!http || !name)
    {
        if (!http)
            _cupsSetError(IPP_INTERNAL_ERROR, "No HTTP connection!");
        else
            _cupsSetError(IPP_INTERNAL_ERROR, "No printer name!");

        return (NULL);
    }

    /*
     * Try finding a printer URI for this printer...
     */

    if (!cups_get_printer_uri(http, name, hostname, sizeof(hostname), &port,
                              resource, sizeof(resource), 0))
        return (NULL);

    DEBUG_printf(("cupsGetPPD3: Printer hostname=\"%s\", port=%d\n", hostname, port));

    /*
     * Remap local hostname to localhost...
     */

    httpGetHostname(NULL, localhost, sizeof(localhost));

    DEBUG_printf(("Local hostname=\"%s\"\n", localhost));

    if (!strcasecmp(localhost, hostname))
        strcpy(hostname, "localhost");

    /*
     * Get the hostname and port number we are connected to...
     */

    httpGetHostname(http, http_hostname, sizeof(http_hostname));

#ifdef AF_INET6
    if (http->hostaddr->addr.sa_family == AF_INET6)
        http_port = ntohs(http->hostaddr->ipv6.sin6_port);
    else
#endif /* AF_INET6 */
        if (http->hostaddr->addr.sa_family == AF_INET)
            http_port = ntohs(http->hostaddr->ipv4.sin_port);
        else
            http_port = ippPort();

    DEBUG_printf(("Connection hostname=\"%s\", port=%d\n", http_hostname,
                  http_port));

    /*
     * Reconnect to the correct server as needed...
     */

    if (!strcasecmp(http_hostname, hostname) && port == http_port)
        http2 = http;
    else if ((http2 = httpConnectEncrypt(hostname, port,
                                         cupsEncryption())) == NULL)
    {
        DEBUG_puts("Unable to connect to server!");

        return (NULL);
    }

    /*
     * Get a temp file...
     */

    if ((fd = cupsTempFd(cg->ppd_filename, sizeof(cg->ppd_filename))) < 0)
    {
        /*
         * Can't open file; close the server connection and return NULL...
         */

        _cupsSetError(IPP_INTERNAL_ERROR, strerror(errno));

        if (http2 != http)
            httpClose(http2);

        return (NULL);
    }

    /*
     * And send a request to the HTTP server...
     */

    strlcat(resource, ".ppd", sizeof(resource));

    status = cupsGetFd(http2, resource, fd);

    close(fd);

    /*
     * See if we actually got the file or an error...
     */

    if (status != HTTP_OK)
    {
        switch (status)
        {
        case HTTP_NOT_FOUND :
            _cupsSetError(IPP_NOT_FOUND, httpStatus(status));
            break;

        case HTTP_UNAUTHORIZED :
            _cupsSetError(IPP_NOT_AUTHORIZED, httpStatus(status));
            break;

        default :
            DEBUG_printf(("HTTP error %d mapped to IPP_SERVICE_UNAVAILABLE!\n",
                          status));
            _cupsSetError(IPP_SERVICE_UNAVAILABLE, httpStatus(status));
            break;
        }

        unlink(cg->ppd_filename);

        return (NULL);
    }

    if (http2 != http)
        httpClose(http2);

    /*
     * Return the PPD file...
     */

    return (cg->ppd_filename);
}
Esempio n. 26
0
int
main(int  argc,				/* I - Number of command-line arguments */
     char *argv[])			/* I - Command-line arguments */
{
  int		i;			/* Looping var */
  const char	*uri;			/* URI to use */
  int		num_events;		/* Number of events */
  const char	*events[100];		/* Events */
  int		subscription_id,	/* notify-subscription-id */
		sequence_number,	/* notify-sequence-number */
		interval;		/* Interval between polls */
  http_t	*http;			/* HTTP connection */
  ipp_t		*request,		/* IPP request */
		*response;		/* IPP response */
  ipp_attribute_t *attr;		/* Current attribute */
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
  struct sigaction action;		/* Actions for POSIX signals */
#endif /* HAVE_SIGACTION && !HAVE_SIGSET */


 /*
  * Parse command-line...
  */

  num_events = 0;
  uri        = NULL;

  for (i = 1; i < argc; i ++)
    if (!strcmp(argv[i], "-E"))
      cupsSetEncryption(HTTP_ENCRYPT_REQUIRED);
    else if (!strcmp(argv[i], "-e"))
    {
      i ++;
      if (i >= argc || num_events >= 100)
        usage();

      events[num_events] = argv[i];
      num_events ++;
    }
    else if (!strcmp(argv[i], "-h"))
    {
      i ++;
      if (i >= argc)
        usage();

      cupsSetServer(argv[i]);
    }
    else if (uri || strncmp(argv[i], "ipp://", 6))
      usage();
    else
      uri = argv[i];

  if (!uri)
    usage();

  if (num_events == 0)
  {
    events[0]  = "all";
    num_events = 1;
  }

 /*
  * Connect to the server...
  */

  if ((http = httpConnectEncrypt(cupsServer(), ippPort(),
                                 cupsEncryption())) == NULL)
  {
    perror(cupsServer());
    return (1);
  }

 /*
  * Catch CTRL-C and SIGTERM...
  */

#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
  sigset(SIGINT, sigterm_handler);
  sigset(SIGTERM, sigterm_handler);
#elif defined(HAVE_SIGACTION)
  memset(&action, 0, sizeof(action));

  sigemptyset(&action.sa_mask);
  action.sa_handler = sigterm_handler;
  sigaction(SIGINT, &action, NULL);
  sigaction(SIGTERM, &action, NULL);
#else
  signal(SIGINT, sigterm_handler);
  signal(SIGTERM, sigterm_handler);
#endif /* HAVE_SIGSET */

 /*
  * Create the subscription...
  */

  if (strstr(uri, "/jobs/"))
  {
    request = ippNewRequest(IPP_CREATE_JOB_SUBSCRIPTION);
    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri);
  }
  else
  {
    request = ippNewRequest(IPP_CREATE_PRINTER_SUBSCRIPTION);
    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL,
                 uri);
  }

  ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
               NULL, cupsUser());

  ippAddStrings(request, IPP_TAG_SUBSCRIPTION, IPP_TAG_KEYWORD, "notify-events",
                num_events, NULL, events);
  ippAddString(request, IPP_TAG_SUBSCRIPTION, IPP_TAG_KEYWORD,
               "notify-pull-method", NULL, "ippget");

  response = cupsDoRequest(http, request, uri);
  if (cupsLastError() >= IPP_BAD_REQUEST)
  {
    fprintf(stderr, "Create-%s-Subscription: %s\n",
            strstr(uri, "/jobs") ? "Job" : "Printer", cupsLastErrorString());
    ippDelete(response);
    httpClose(http);
    return (1);
  }

  if ((attr = ippFindAttribute(response, "notify-subscription-id",
                               IPP_TAG_INTEGER)) == NULL)
  {
    fputs("ERROR: No notify-subscription-id in response!\n", stderr);
    ippDelete(response);
    httpClose(http);
    return (1);
  }

  subscription_id = attr->values[0].integer;

  printf("Create-%s-Subscription: notify-subscription-id=%d\n",
         strstr(uri, "/jobs/") ? "Job" : "Printer", subscription_id);

  ippDelete(response);

 /*
  * Monitor for events...
  */

  sequence_number = 0;

  while (!terminate)
  {
   /*
    * Get the current events...
    */

    printf("\nGet-Notifications(%d,%d):", subscription_id, sequence_number);
    fflush(stdout);

    request = ippNewRequest(IPP_GET_NOTIFICATIONS);

    if (strstr(uri, "/jobs/"))
      ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri);
    else
      ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL,
                   uri);

    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                 "requesting-user-name", NULL, cupsUser());

    ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER,
                  "notify-subscription-ids", subscription_id);
    if (sequence_number)
      ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER,
                    "notify-sequence-numbers", sequence_number + 1);

    response = cupsDoRequest(http, request, uri);

    printf(" %s\n", ippErrorString(cupsLastError()));

    if (cupsLastError() >= IPP_BAD_REQUEST)
      fprintf(stderr, "Get-Notifications: %s\n", cupsLastErrorString());
    else if (response)
    {
      print_attributes(response, 0);

      for (attr = ippFindAttribute(response, "notify-sequence-number",
                                   IPP_TAG_INTEGER);
           attr;
	   attr = ippFindNextAttribute(response, "notify-sequence-number",
	                               IPP_TAG_INTEGER))
        if (attr->values[0].integer > sequence_number)
	  sequence_number = attr->values[0].integer;
    }

    if ((attr = ippFindAttribute(response, "notify-get-interval",
                                 IPP_TAG_INTEGER)) != NULL &&
        attr->values[0].integer > 0)
      interval = attr->values[0].integer;
    else
      interval = 5;

    ippDelete(response);
    sleep(interval);
  }

 /*
  * Cancel the subscription...
  */

  printf("\nCancel-Subscription:");
  fflush(stdout);

  request = ippNewRequest(IPP_CANCEL_SUBSCRIPTION);

  if (strstr(uri, "/jobs/"))
    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri);
  else
    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL,
                 uri);

  ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
               NULL, cupsUser());

  ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER,
                "notify-subscription-id", subscription_id);

  ippDelete(cupsDoRequest(http, request, uri));

  printf(" %s\n", ippErrorString(cupsLastError()));

  if (cupsLastError() >= IPP_BAD_REQUEST)
    fprintf(stderr, "Cancel-Subscription: %s\n", cupsLastErrorString());

 /*
  * Close the connection and return...
  */

  httpClose(http);

  return (0);
}
Esempio n. 27
0
GtkCupsRequest *
gtk_cups_request_new_with_username (http_t             *connection,
                                    GtkCupsRequestType  req_type, 
                                    gint                operation_id,
                                    GIOChannel         *data_io,
                                    const char         *server,
                                    const char         *resource,
                                    const char         *username)
{
  GtkCupsRequest *request;
  cups_lang_t *language;
  
  request = g_new0 (GtkCupsRequest, 1);
  request->result = g_new0 (GtkCupsResult, 1);

  request->result->error_msg = NULL;
  request->result->ipp_response = NULL;

  request->result->is_error = FALSE;
  request->result->is_ipp_response = FALSE;

  request->type = req_type;
  request->state = GTK_CUPS_REQUEST_START;

  request->password_state = GTK_CUPS_PASSWORD_NONE;

   if (server)
    request->server = g_strdup (server);
  else
    request->server = g_strdup (cupsServer ());


  if (resource)
    request->resource = g_strdup (resource);
  else
    request->resource = g_strdup ("/");
 
  if (connection != NULL)
    {
      request->http = connection;
      request->own_http = FALSE;
    }
  else
    {
      request->http = NULL;
      request->http = httpConnectEncrypt (request->server, 
                                          ippPort (), 
                                          cupsEncryption ());

      if (request->http)
        httpBlocking (request->http, 0);
        
      request->own_http = TRUE;
    }

  request->last_status = HTTP_CONTINUE;

  request->attempts = 0;
  request->data_io = data_io;

  request->ipp_request = ippNew ();
  ippSetOperation (request->ipp_request, operation_id);
  ippSetRequestId (request->ipp_request, 1);

  language = cupsLangDefault ();

  gtk_cups_request_ipp_add_string (request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
                                   "attributes-charset", 
                                   NULL, "utf-8");
	
  gtk_cups_request_ipp_add_string (request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
                                   "attributes-natural-language", 
                                   NULL, language->language);

  if (username != NULL)
    gtk_cups_request_ipp_add_string (request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                                     "requesting-user-name",
                                     NULL, username);
  else
    gtk_cups_request_ipp_add_string (request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                                     "requesting-user-name",
                                     NULL, cupsUser ());

  request->auth_info_required = NULL;
  request->auth_info = NULL;
  request->need_auth_info = FALSE;

  cupsLangFree (language);

  return request;
}
Esempio n. 28
0
///////////////////////////////////////////////////////////////////////////////////////////
//
// CS     : PUBLIC gint removeJob(gchar *pDestName)
// IN     : gchar *pDestName : Printer name.
// OUT    : None.
// RETURN : ID_ERR_NO_ERROR : No error.
//          ID_ERR_CUPS_API_FAILED : Error occured in CUPS API.
//
PUBLIC gint removeJob(gchar *pDestName)
{
/*** Parameters start ***/
	http_t			*pHTTP;						// Pointer to HTTP connection.
	ipp_t			*pRequest,					// Pointer to CUPS IPP request.
					*pResponse;					// Pointer to CUPS IPP response.
	cups_lang_t		*pLanguage;					// Pointer to language.
	gchar			printerURI[HTTP_MAX_URI];	// Printer URI.
	gchar			serverName[HTTP_MAX_URI];	// CUPS server name.
	gint			jobID = 0;					// Job ID.
	gint			retVal = ID_ERR_NO_ERROR;	// Return value.
/*** Parameters end ***/

	// Initialize buffer.
	memset(printerURI, 0, sizeof(printerURI));
	memset(serverName, 0, sizeof(serverName));

	// Get printer URI and CUPS server name.
	retVal = getPrinterURI(pDestName, printerURI, serverName, HTTP_MAX_URI);
	if (retVal == ID_ERR_NO_ERROR) {
		retVal = getJobID(pDestName, printerURI, serverName, &jobID);
		if (retVal == ID_ERR_PRINT_JOB_NOT_EXIST) {
			retVal = ID_ERR_NO_ERROR;
		}

		if (retVal == ID_ERR_NO_ERROR) {
			// CUPS http connect.
			if ((pHTTP = httpConnectEncrypt(serverName, ippPort(), cupsEncryption())) == NULL) {
				retVal = ID_ERR_CUPS_API_FAILED;
			}
			else {
				pRequest = ippNew();

				ippSetOperation(pRequest, IPP_CANCEL_JOB);
				ippSetRequestId(pRequest, 1);

				pLanguage = bjcupsLangDefault();		// cupsLangDefault() -> bjcupsLangDefault() for cups-1.1.19

				ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, cupsLangEncoding(pLanguage));
				ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, pLanguage->language);
				ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printerURI);
				ippAddInteger(pRequest, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id", jobID);
				ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());

				if ((pResponse = cupsDoRequest(pHTTP, pRequest, "/jobs/")) != NULL) {
					if (ippGetStatusCode(pResponse) > IPP_OK_CONFLICT) {
						retVal = ID_ERR_CUPS_API_FAILED;
					}
					ippDelete(pResponse);
				}
				else {
					retVal = ID_ERR_CUPS_API_FAILED;
				}

				cupsLangFree(pLanguage);
				httpClose(pHTTP);
			}
		}
	}

	return(retVal);
}// End removeJob
Esempio n. 29
0
static int				/* O - Exit status */
do_test(const char        *server,	/* I - Server to use */
        http_encryption_t encryption,	/* I - Encryption to use */
	int               requests,	/* I - Number of requests to send */
	int               verbose)	/* I - Verbose output? */
{
  int		i;			/* Looping var */
  http_t	*http;			/* Connection to server */
  ipp_t		*request,		/* IPP Request */
		*response;		/* IPP Response */
  cups_lang_t	*language;		/* Default language */
  struct timeval start,			/* Start time */
		end;			/* End time */
  double	elapsed;		/* Elapsed time */
  static ipp_op_t ops[4] =		/* Operations to test... */
		{
		  IPP_PRINT_JOB,
		  CUPS_GET_PRINTERS,
		  CUPS_GET_CLASSES,
		  IPP_GET_JOBS
		};


 /*
  * Connect to the server...
  */

  http = httpConnectEncrypt(server, ippPort(), encryption);

  if (http == NULL)
  {
    perror("testspeed: unable to connect to server");
    return (1);
  }

  language = cupsLangDefault();

 /*
  * Do multiple requests...
  */

  for (elapsed = 0.0, i = 0; i < requests; i ++)
  {
    if (verbose && (i % 10) == 0)
      printf("testspeed(%d): %d%% complete...\n", (int)getpid(),
             i * 100 / requests);

   /*
    * Build a request which requires the following attributes:
    *
    *    attributes-charset
    *    attributes-natural-language
    *
    * In addition, IPP_GET_JOBS needs a printer-uri attribute.
    */

    request = ippNew();

    request->request.op.operation_id = ops[i & 3];
    request->request.op.request_id   = 1;

    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_CHARSET,
        	 "attributes-charset", NULL, cupsLangEncoding(language));

    ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE,
        	 "attributes-natural-language", NULL, language->language);

    gettimeofday(&start, NULL);

    switch (request->request.op.operation_id)
    {
      case IPP_GET_JOBS :
	  ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
                       NULL, "ipp://localhost/printers/");

      default :
	  response = cupsDoRequest(http, request, "/");
          break;

      case IPP_PRINT_JOB :
	  ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
                       NULL, "ipp://localhost/printers/test");
	  response = cupsDoFileRequest(http, request, "/printers/test",
	                               "../data/testprint.ps");
          break;
    }

    gettimeofday(&end, NULL);

    if (response != NULL)
      ippDelete(response);

    elapsed += (end.tv_sec - start.tv_sec) +
               0.000001 * (end.tv_usec - start.tv_usec);
  }

  cupsLangFree(language);
  httpClose(http);

  printf("testspeed(%d): %d requests in %.1fs (%.3fs/r, %.1fr/s)\n",
         (int)getpid(), i, elapsed, elapsed / i, i / elapsed);

  return (0);
}
Esempio n. 30
0
PRIVATE gchar * getJobState(gchar *pDestName, const gchar *pURI, gchar *pServerName, ipp_jstate_t *pJobState, gchar *pJobUserName)
{
/*** Parameters start ***/
	http_t			*pHTTP;									// Pointer to HTTP connection.
	ipp_t			*pRequest,								// Pointer to CUPS IPP request.
					*pResponse;								// Pointer to CUPS IPP response.
	ipp_attribute_t	*pAttribute;							// Pointer to CUPS attributes.
	cups_lang_t		*pLanguage;								// Pointer to language.
//	ipp_jstate_t	jobState = 0;							// Job state.
//	gint			jobID = 0;								// Job ID.
//	gchar			*pJobUserName = NULL;					// User name of print job.
	uid_t			userID;									// User ID.
	struct passwd	*pPasswd;								// Pointer to password structure.
	gint			retVal = ID_ERR_PRINT_JOB_NOT_EXIST;	// Return value.
/*** Parameters end ***/

	// Get login name.
	userID = getuid();
	pPasswd = getpwuid(userID);

	// CUPS http connect.
	if ((pHTTP = httpConnectEncrypt(pServerName, ippPort(), cupsEncryption())) == NULL) {
		retVal = ID_ERR_CUPS_API_FAILED;
	}
	else {
		pRequest = ippNew();

		ippSetOperation(pRequest, IPP_GET_JOB_ATTRIBUTES);
		ippSetRequestId(pRequest, 1);

		pLanguage = bjcupsLangDefault();	// cupsLangDefault() -> bjcupsLangDefault() for cups-1.1.19

		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_CHARSET, "attributes-charset", NULL, cupsLangEncoding(pLanguage));
		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "attributes-natural-language", NULL, pLanguage->language);
		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, pURI);
		ippAddString(pRequest, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, pPasswd->pw_name);

		if ((pResponse = cupsDoRequest(pHTTP, pRequest, "/")) != NULL) {
			if (ippGetStatusCode(pResponse) > IPP_OK_CONFLICT) {
				retVal = ID_ERR_CUPS_API_FAILED;
			}
			else {
				pAttribute = ippFirstAttribute(pResponse);

				while (pAttribute != NULL) {
					while (pAttribute != NULL && ippGetGroupTag(pAttribute) != IPP_TAG_JOB) {
						pAttribute = bjcups_ippNextAttribute(pResponse, pAttribute);
					}
					if (pAttribute == NULL) {
						break;
					}

					while (pAttribute != NULL && ippGetGroupTag(pAttribute) == IPP_TAG_JOB) {
						if (strcmp(ippGetName(pAttribute), "job-state") == 0 && ippGetValueTag(pAttribute) == IPP_TAG_ENUM) {
							*pJobState = (ipp_jstate_t)ippGetInteger(pAttribute, 0);
						}
						if (strcmp(ippGetName(pAttribute), "job-originating-user-name") == 0 && ippGetValueTag(pAttribute) == IPP_TAG_NAME) {
							//pJobUserName = pAttribute->values[0].string.text;
							pJobUserName=malloc(20*sizeof(gchar));
							strncpy(pJobUserName,ippGetString(pAttribute, 0, NULL), 19);
							pJobUserName[19]='\0';

						}
						pAttribute = bjcups_ippNextAttribute(pResponse, pAttribute);
					}
					if (pAttribute != NULL)
						pAttribute = bjcups_ippNextAttribute(pResponse, pAttribute);
				}
			}

			ippDelete(pResponse);
		}
		else {
			retVal = ID_ERR_CUPS_API_FAILED;
		}

		cupsLangFree(pLanguage);
		httpClose(pHTTP);
	}


	return(pJobUserName);
}// End getJobState