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 = httpConnect2(cupsServer(), ippPort(), NULL, AF_UNSPEC, cupsEncryption(), 1, 30000, NULL); /* * 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); } }
CupsOptions CupsGetOpt::load_document(Document& doc, int argc, char *argv[]) { // Extract non-CUPS cmd-line parameters typedef DocumentSettings DS; // use gs dithering as default for the cups-filter doc.put(EngraveSettings::DITHERING, EngraveSettings::FLOYD_STEINBERG); doc.put(DocumentSettings::LOAD_ENGRAVING, true); int c; while ((c = getopt(argc, argv, "x")) != -1) { switch (c) { case ':': print_usage(argv[0]); break; case '?': print_usage(argv[0]); break; } } /** FIXME: free of cwd impairs logger??? char *cwd = getwd(NULL); LOG_DEBUG(cwd); free(cwd); */ // Now, only standard CUPS parameters should be left int cupsargs = argc - optind; if (cupsargs < 5 || cupsargs > 6) { print_usage(argv[0]); } for (int i = optind; i < argc; i++) { LOG_DEBUG(argv[i]); } // FIXME: Register a signal handler to support cancelling of jobs string jobid = argv[optind]; string user = argv[optind + 1]; string title = argv[optind + 2]; string copies = argv[optind + 3]; string options = argv[optind + 4]; string filename = (cupsargs == 6) ? argv[optind + 5] : NULL; doc.put(DS::USER, user); doc.put(DS::TITLE, title); // Handle CUPS options cups_option_t *cups_options; size_t numCupsOptions = cupsParseOptions(options.c_str(), 0, &cups_options); CupsOptions cupsOpts = CupsOptions::parseSettings(doc.settings(), cups_options, numCupsOptions); doc.load(filename); return cupsOpts; }
/* * Ouverture et fermeture du fichier PPD * Opening or closing PPD file */ bool PPDFile::open(const char *file, const char *version, const char *useropts) { const char *fileVersion; cups_option_t *options; int nr; // Check if a PPD file was previously opened if (_ppd) { ERRORMSG(_("Internal warning: a PPD file was previously opened. Please " "close it before opening a new one.")); close(); } // Open the PPD file _ppd = ppdOpenFile(file); if (!_ppd) { ERRORMSG(_("Cannot open PPD file %s"), file); return false; } // Mark the default values and the user options ppdMarkDefaults(_ppd); nr = cupsParseOptions(useropts, 0, &options); cupsMarkOptions(_ppd, nr, options); cupsFreeOptions(nr, options); // Check if the PPD version is compatible with this filter fileVersion = get("FileVersion"); if (!fileVersion) { ERRORMSG(_("No FileVersion found in the PPD file: invalid " "PPD file")); ppdClose(_ppd); _ppd = NULL; return false; } if (strcmp(fileVersion, version)) { ERRORMSG(_("Invalid PPD file version: %s but the PPD file " "is designed for SpliX V. %s"), version, fileVersion); ppdClose(_ppd); _ppd = NULL; return false; } return true; }
int initializeCupsOptions(job_data_t *job, ppd_file_t **ppd, const char *argv[]) { char ls[64]; job->job_id = atoi(argv[1]); job->user = argv[2]; job->title = argv[3]; job->num_options = cupsParseOptions(argv[5], 0, &(job->options)); if ((*ppd = ppdOpenFile(getenv("PPD"))) != NULL) { ppdMarkDefaults(*ppd); cupsMarkOptions(*ppd, job->num_options, job->options); } else { l10nGetString("Unable to open PPD file", ls, sizeof(ls)); fprintf(stderr, "ERROR: %s: %s\n", ls, strerror(errno)); return 1; } return 0; }
static void read_config_options(const char *lpoptions) { int i; int num_options; cups_option_t *options; cups_option_t *option; num_options = cupsParseOptions(lpoptions, 0, &options); for (i = 0, option = options; i < num_options; i ++, option ++) { /* replace all _ by " " in value */ int j; for (j=0; option->value[j]!= '\0'; j++) { if (option->value[j] == '_') { option->value[j] = ' '; } } _assign_value(SEC_LPOPT, option->name, option->value); } return; }
int /* O - Exit code */ main(int argc, /* I - Number of command-line args */ char *argv[]) /* I - Command-line arguments */ { int i; /* Looping var */ int request_id; /* Request ID */ int timeout; /* Timeout in seconds */ const char *server_bin; /* CUPS_SERVERBIN environment variable */ char filename[1024]; /* Backend directory filename */ cups_dir_t *dir; /* Directory pointer */ cups_dentry_t *dent; /* Directory entry */ double current_time, /* Current time */ end_time; /* Ending time */ int num_options; /* Number of options */ cups_option_t *options; /* Options */ cups_array_t *requested, /* requested-attributes values */ *exclude, /* exclude-schemes values */ *include; /* include-schemes values */ #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET) struct sigaction action; /* Actions for POSIX signals */ #endif /* HAVE_SIGACTION && !HAVE_SIGSET */ setbuf(stderr, NULL); /* * Check the command-line... */ if (argc != 6) { fputs("Usage: cups-deviced request-id limit timeout user-id options\n", stderr); return (1); } request_id = atoi(argv[1]); if (request_id < 1) { fprintf(stderr, "ERROR: [cups-deviced] Bad request ID %d!\n", request_id); return (1); } device_limit = atoi(argv[2]); if (device_limit < 0) { fprintf(stderr, "ERROR: [cups-deviced] Bad limit %d!\n", device_limit); return (1); } timeout = atoi(argv[3]); if (timeout < 1) { fprintf(stderr, "ERROR: [cups-deviced] Bad timeout %d!\n", timeout); return (1); } normal_user = atoi(argv[4]); if (normal_user <= 0) { fprintf(stderr, "ERROR: [cups-deviced] Bad user %d!\n", normal_user); return (1); } num_options = cupsParseOptions(argv[5], 0, &options); requested = cupsdCreateStringsArray(cupsGetOption("requested-attributes", num_options, options)); exclude = cupsdCreateStringsArray(cupsGetOption("exclude-schemes", num_options, options)); include = cupsdCreateStringsArray(cupsGetOption("include-schemes", num_options, options)); if (!requested || cupsArrayFind(requested, "all") != NULL) { send_class = send_info = send_make_and_model = send_uri = send_id = send_location = 1; } else { send_class = cupsArrayFind(requested, "device-class") != NULL; send_info = cupsArrayFind(requested, "device-info") != NULL; send_make_and_model = cupsArrayFind(requested, "device-make-and-model") != NULL; send_uri = cupsArrayFind(requested, "device-uri") != NULL; send_id = cupsArrayFind(requested, "device-id") != NULL; send_location = cupsArrayFind(requested, "device-location") != NULL; } /* * Listen to child signals... */ #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */ sigset(SIGCHLD, sigchld_handler); #elif defined(HAVE_SIGACTION) memset(&action, 0, sizeof(action)); sigemptyset(&action.sa_mask); sigaddset(&action.sa_mask, SIGCHLD); action.sa_handler = sigchld_handler; sigaction(SIGCHLD, &action, NULL); #else signal(SIGCLD, sigchld_handler); /* No, SIGCLD isn't a typo... */ #endif /* HAVE_SIGSET */ /* * Try opening the backend directory... */ if ((server_bin = getenv("CUPS_SERVERBIN")) == NULL) server_bin = CUPS_SERVERBIN; snprintf(filename, sizeof(filename), "%s/backend", server_bin); if ((dir = cupsDirOpen(filename)) == NULL) { fprintf(stderr, "ERROR: [cups-deviced] Unable to open backend directory " "\"%s\": %s", filename, strerror(errno)); return (1); } /* * Setup the devices array... */ devices = cupsArrayNew((cups_array_func_t)compare_devices, NULL); /* * Loop through all of the device backends... */ while ((dent = cupsDirRead(dir)) != NULL) { /* * Skip entries that are not executable files... */ if (!S_ISREG(dent->fileinfo.st_mode) || !isalnum(dent->filename[0] & 255) || (dent->fileinfo.st_mode & (S_IRUSR | S_IXUSR)) != (S_IRUSR | S_IXUSR)) continue; /* * Skip excluded or not included backends... */ if (cupsArrayFind(exclude, dent->filename) || (include && !cupsArrayFind(include, dent->filename))) continue; /* * Backends without permissions for normal users run as root, * all others run as the unprivileged user... */ start_backend(dent->filename, !(dent->fileinfo.st_mode & (S_IRWXG | S_IRWXO))); } cupsDirClose(dir); /* * Collect devices... */ if (getenv("SOFTWARE")) puts("Content-Type: application/ipp\n"); cupsdSendIPPHeader(IPP_OK, request_id); cupsdSendIPPGroup(IPP_TAG_OPERATION); cupsdSendIPPString(IPP_TAG_CHARSET, "attributes-charset", "utf-8"); cupsdSendIPPString(IPP_TAG_LANGUAGE, "attributes-natural-language", "en-US"); end_time = get_current_time() + timeout; while (active_backends > 0 && (current_time = get_current_time()) < end_time) { /* * Collect the output from the backends... */ timeout = (int)(1000 * (end_time - current_time)); if (poll(backend_fds, num_backends, timeout) > 0) { for (i = 0; i < num_backends; i ++) if (backend_fds[i].revents && backends[i].pipe) { cups_file_t *bpipe = backends[i].pipe; /* Copy of pipe for backend... */ do { if (get_device(backends + i)) { backend_fds[i].fd = 0; backend_fds[i].events = 0; break; } } while (bpipe->ptr && memchr(bpipe->ptr, '\n', bpipe->end - bpipe->ptr)); } } /* * Get exit status from children... */ if (dead_children) process_children(); } cupsdSendIPPTrailer(); /* * Terminate any remaining backends and exit... */ if (active_backends > 0) { for (i = 0; i < num_backends; i ++) if (backends[i].pid) kill(backends[i].pid, SIGTERM); } return (0); }
int main(int argc, /* I - Number of command-line arguments */ char *argv[]) /* I - Command-line arguments */ { int i; /* Looping var */ http_t *http; /* Connection to server */ char *printer, /* Destination printer */ *pclass, /* Printer class name */ *val; /* Pointer to allow/deny value */ int num_options; /* Number of options */ cups_option_t *options; /* Options */ char *file; /* New PPD file/interface script */ _cupsSetLocale(argv); http = NULL; printer = NULL; num_options = 0; options = NULL; file = NULL; for (i = 1; i < argc; i ++) if (argv[i][0] == '-') switch (argv[i][1]) { case 'c' : /* Add printer to class */ if (!http) { http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption()); if (http == NULL) { _cupsLangPrintf(stderr, _("lpadmin: Unable to connect to server: %s"), strerror(errno)); return (1); } } if (printer == NULL) { _cupsLangPuts(stderr, _("lpadmin: Unable to add a printer to the class:\n" " You must specify a printer name " "first.")); return (1); } if (argv[i][2]) pclass = argv[i] + 2; else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected class name after \"-c\" " "option.")); return (1); } pclass = argv[i]; } if (!validate_name(pclass)) { _cupsLangPuts(stderr, _("lpadmin: Class name can only contain printable " "characters.")); return (1); } if (add_printer_to_class(http, printer, pclass)) return (1); break; case 'd' : /* Set as default destination */ if (!http) { http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption()); if (http == NULL) { _cupsLangPrintf(stderr, _("lpadmin: Unable to connect to server: %s"), strerror(errno)); return (1); } } if (argv[i][2]) printer = argv[i] + 2; else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected printer name after \"-d\" " "option.")); return (1); } printer = argv[i]; } if (!validate_name(printer)) { _cupsLangPuts(stderr, _("lpadmin: Printer name can only contain " "printable characters.")); return (1); } if (default_printer(http, printer)) return (1); i = argc; break; case 'h' : /* Connect to host */ if (http) { httpClose(http); http = NULL; } if (argv[i][2] != '\0') cupsSetServer(argv[i] + 2); else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected hostname after \"-h\" " "option.")); return (1); } cupsSetServer(argv[i]); } break; case 'i' : /* Use the specified interface script */ if (argv[i][2]) file = argv[i] + 2; else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected interface after \"-i\" " "option.")); return (1); } file = argv[i]; } break; case 'E' : /* Enable the printer */ if (printer == NULL) { #ifdef HAVE_SSL cupsSetEncryption(HTTP_ENCRYPT_REQUIRED); if (http) httpEncryption(http, HTTP_ENCRYPT_REQUIRED); #else _cupsLangPrintf(stderr, _("%s: Sorry, no encryption support."), argv[0]); #endif /* HAVE_SSL */ break; } if (!http) { http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption()); if (http == NULL) { _cupsLangPrintf(stderr, _("lpadmin: Unable to connect to server: %s"), strerror(errno)); return (1); } } if (enable_printer(http, printer)) return (1); break; case 'm' : /* Use the specified standard script/PPD file */ if (argv[i][2]) num_options = cupsAddOption("ppd-name", argv[i] + 2, num_options, &options); else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected model after \"-m\" " "option.")); return (1); } num_options = cupsAddOption("ppd-name", argv[i], num_options, &options); } break; case 'o' : /* Set option */ if (argv[i][2]) num_options = cupsParseOptions(argv[i] + 2, num_options, &options); else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected name=value after \"-o\" " "option.")); return (1); } num_options = cupsParseOptions(argv[i], num_options, &options); } break; case 'p' : /* Add/modify a printer */ if (argv[i][2]) printer = argv[i] + 2; else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected printer after \"-p\" " "option.")); return (1); } printer = argv[i]; } if (!validate_name(printer)) { _cupsLangPuts(stderr, _("lpadmin: Printer name can only contain " "printable characters.")); return (1); } break; case 'r' : /* Remove printer from class */ if (!http) { http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption()); if (http == NULL) { _cupsLangPrintf(stderr, _("lpadmin: Unable to connect to server: %s"), strerror(errno)); return (1); } } if (printer == NULL) { _cupsLangPuts(stderr, _("lpadmin: Unable to remove a printer from the " "class:\n" " You must specify a printer name " "first.")); return (1); } if (argv[i][2]) pclass = argv[i] + 2; else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected class after \"-r\" " "option.")); return (1); } pclass = argv[i]; } if (!validate_name(pclass)) { _cupsLangPuts(stderr, _("lpadmin: Class name can only contain printable " "characters.")); return (1); } if (delete_printer_from_class(http, printer, pclass)) return (1); break; case 'R' : /* Remove option */ if (!http) { http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption()); if (http == NULL) { _cupsLangPrintf(stderr, _("lpadmin: Unable to connect to server: %s"), strerror(errno)); return (1); } } if (printer == NULL) { _cupsLangPuts(stderr, _("lpadmin: Unable to delete option:\n" " You must specify a printer name " "first.")); return (1); } if (argv[i][2]) val = argv[i] + 2; else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected name after \"-R\" " "option.")); return (1); } val = argv[i]; } if (delete_printer_option(http, printer, val)) return (1); 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."), argv[0]); return (1); } cupsSetUser(argv[i]); } break; case 'u' : /* Allow/deny users */ if (argv[i][2]) val = argv[i] + 2; else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected allow/deny:userlist after " "\"-u\" option.")); return (1); } val = argv[i]; } if (!_cups_strncasecmp(val, "allow:", 6)) num_options = cupsAddOption("requesting-user-name-allowed", val + 6, num_options, &options); else if (!_cups_strncasecmp(val, "deny:", 5)) num_options = cupsAddOption("requesting-user-name-denied", val + 5, num_options, &options); else { _cupsLangPrintf(stderr, _("lpadmin: Unknown allow/deny option \"%s\"."), val); return (1); } break; case 'v' : /* Set the device-uri attribute */ if (argv[i][2]) num_options = cupsAddOption("device-uri", argv[i] + 2, num_options, &options); else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected device URI after \"-v\" " "option.")); return (1); } num_options = cupsAddOption("device-uri", argv[i], num_options, &options); } break; case 'x' : /* Delete a printer */ if (!http) { http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption()); if (http == NULL) { _cupsLangPrintf(stderr, _("lpadmin: Unable to connect to server: %s"), strerror(errno)); return (1); } } if (argv[i][2]) printer = argv[i] + 2; else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected printer or class after " "\"-x\" option.")); return (1); } printer = argv[i]; } if (!validate_name(printer)) { _cupsLangPuts(stderr, _("lpadmin: Printer name can only contain " "printable characters.")); return (1); } if (delete_printer(http, printer)) return (1); i = argc; break; case 'D' : /* Set the printer-info attribute */ if (argv[i][2]) num_options = cupsAddOption("printer-info", argv[i] + 2, num_options, &options); else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected description after " "\"-D\" option.")); return (1); } num_options = cupsAddOption("printer-info", argv[i], num_options, &options); } break; case 'I' : /* Set the supported file types (ignored) */ i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected file type(s) after \"-I\" " "option.")); return (1); } _cupsLangPuts(stderr, _("lpadmin: Warning - content type list ignored.")); break; case 'L' : /* Set the printer-location attribute */ if (argv[i][2]) num_options = cupsAddOption("printer-location", argv[i] + 2, num_options, &options); else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected location after \"-L\" " "option.")); return (1); } num_options = cupsAddOption("printer-location", argv[i], num_options, &options); } break; case 'P' : /* Use the specified PPD file */ if (argv[i][2]) file = argv[i] + 2; else { i ++; if (i >= argc) { _cupsLangPuts(stderr, _("lpadmin: Expected PPD after \"-P\" option.")); return (1); } file = argv[i]; } break; default : _cupsLangPrintf(stderr, _("lpadmin: Unknown option \"%c\"."), argv[i][1]); return (1); } else { _cupsLangPrintf(stderr, _("lpadmin: Unknown argument \"%s\"."), argv[i]); return (1); } /* * Set options as needed... */ if (num_options || file) { if (!http) { http = httpConnectEncrypt(cupsServer(), ippPort(), cupsEncryption()); if (http == NULL) { _cupsLangPrintf(stderr, _("lpadmin: Unable to connect to server: %s"), strerror(errno)); return (1); } } if (printer == NULL) { _cupsLangPuts(stderr, _("lpadmin: Unable to set the printer options:\n" " You must specify a printer name first.")); return (1); } if (set_printer_options(http, printer, num_options, options, file)) return (1); } if (printer == NULL) { _cupsLangPuts(stdout, _("Usage:\n" "\n" " lpadmin [-h server] -d destination\n" " lpadmin [-h server] -x destination\n" " lpadmin [-h server] -p printer [-c add-class] " "[-i interface] [-m model]\n" " [-r remove-class] [-v device] " "[-D description]\n" " [-P ppd-file] [-o name=value]\n" " [-u allow:user,user] " "[-u deny:user,user]")); } if (http) httpClose(http); return (0); }
int main(int argc, char *argv[]) { cups_option_t *p_cups_opt = NULL; int num_opt = 0; ParamList *p_ps_param = NULL; BufList *p_ps_data = NULL; char *p_data_buf; int ifd = 0; int fds[2]; struct sigaction sigact; char *cmd_buf = NULL; char product[256]; #ifdef DEBUG_SLEEP sleep(30); #endif setbuf(stderr, NULL); fprintf(stderr, "DEBUG: pstocanonbj start.\n"); memset(&sigact, 0, sizeof(sigact)); sigact.sa_handler = sigterm_handler; if( sigaction(SIGTERM, &sigact, NULL) ) { fputs("ERROR: pstocanonbj can't register signal hander.\n", stderr); return 1; } if( argc < 6 || argc > 7 ) { fputs("ERROR: pstocanonbj illegal parameter number.\n", stderr); return 1; } if( argv[5] != NULL ) { num_opt = cupsParseOptions(argv[5], 0, &p_cups_opt); if( num_opt < 0 ) { fputs("ERROR: illegal option.\n", stderr); return 1; } } if( argc == 7 ) { if( (ifd = open(argv[6], O_RDONLY)) == -1 ) { fputs("ERROR: can't open file.\n", stderr); return 1; } } #ifdef DEBUG_IN_PS g_in_log_fd = open("/tmp/debug_in_log.ps", O_WRONLY); #endif p_ps_param = get_ps_params(ifd, &p_ps_data); if( (cmd_buf = make_cmd_param(p_cups_opt, num_opt, p_ps_param, product, 256)) == NULL ) { fputs("ERROR: can't make parameter.\n", stderr); goto error_return; } if( g_signal_received ) goto error_return; if( (p_data_buf = (char*)malloc(DATA_BUF_SIZE)) != NULL ) { #ifdef DEBUG_PS int log_fd = open("/tmp/debug_data_log.ps", O_WRONLY); #endif // Execute extended filter. g_filter_pid = exec_filter(cmd_buf, 1, fds); // Write retained PS header and data. buflist_write(p_ps_data, fds[1]); #ifdef DEBUG_PS buflist_write(p_ps_data, log_fd); #endif // Write remaining PS data. while( !g_signal_received ) { int read_bytes = read(ifd, p_data_buf, DATA_BUF_SIZE); if( read_bytes > 0 ) { int write_bytes; char *p_data = p_data_buf; #ifdef DEBUG_PS write(log_fd, p_data_buf, read_bytes); #endif #ifdef DEBUG_IN_PS if( g_in_log_fd > 0 ) write(g_in_log_fd, p_data_buf, read_bytes); #endif do { write_bytes = write(fds[1], p_data, read_bytes); if( write_bytes < 0 ) { if( errno == EINTR ) continue; fprintf(stderr, "ERROR: pstocanonbj write error,%d.\n", errno); goto error_exit; } read_bytes -= write_bytes; p_data += write_bytes; } while( !g_signal_received && read_bytes > 0 ); } else if( read_bytes < 0 ) { if( errno == EINTR ) continue; fprintf(stderr, "ERROR: pstocanonbj read error,%d.\n", errno); goto error_exit; } else break; } free(p_data_buf); #ifdef DEBUG_PS if( log_fd != -1 ) close(log_fd); #endif } #ifdef DEBUG_IN_PS if( g_in_log_fd > 0 ) close(g_in_log_fd); #endif free(cmd_buf); if( p_ps_param != NULL ) param_list_free(p_ps_param); if( p_ps_data != NULL ) buflist_destroy(p_ps_data); if( ifd != 0 ) close(ifd); close(fds[1]); if( g_filter_pid != -1 ) waitpid(g_filter_pid, NULL, 0); return 0; error_exit: if( p_data_buf != NULL ) free(p_data_buf); error_return: free(cmd_buf); if( p_ps_param != NULL ) param_list_free(p_ps_param); if( p_ps_data != NULL ) buflist_destroy(p_ps_data); if( ifd != 0 ) close(ifd); return 1; }
static int check_options( FILE** fp, short *is_setregi, int *utilbyte, char* tmp_file, char* option , short *is_direct) { cups_option_t *p_opt = NULL; int num_opt = 0; int i,result = 0; short regi_flag=0; short direct_flag=0; int cmdlen = 0; int bscc_id = 0; if( (num_opt = cupsParseOptions(option, 0, &p_opt)) > 0 ){ for( i=0; i< num_opt; i++ ){ /* bscc */ if( strcmp( p_opt[i].name, REGI_OPTION)== 0){ bscc_id = atoi(p_opt[i].value); regi_flag = 1; } else if( strcmp( p_opt[i].name, UTIL_OPTION)== 0 ){ cmdlen = atoi(p_opt[i].value); *utilbyte = cmdlen; } /* Ver.3.20 */ else if( strcmp( p_opt[i].name, DIRECT_OPTION)== 0 ){ direct_flag = 1; } } } if( regi_flag ){ char model_name[MODEL_NAME_STR_LEN] ; char bscc_file[256]; char bscc_buf[256]; char cmd_buf[512]; int r_size,total_size; FILE* tmp_fp = NULL; sprintf( tmp_file, "/tmp/CNBjBackend%d", getpid()); // if( (tmp_fp =fopen( tmp_file, "w")) == NULL ) if( (tmp_fp =fopen( tmp_file, "w+b")) == NULL ){ /* Ver.2.90 */ fprintf(stderr,"CNBjBackend open_error\n"); goto open_error; } total_size = cmdlen; while( total_size > 0 ){ r_size = fread( cmd_buf, 1,total_size,(FILE*)(*fp) ); fwrite( cmd_buf, r_size, 1, tmp_fp); total_size -= r_size; } fseek( tmp_fp, 0, SEEK_SET ); r_size = fread( bscc_buf, 1, 256, (FILE*)(*fp) ); fprintf(stderr,"bscc_buf r_size=%d\n",r_size); /* bscc file */ get_model_name( model_name ); sprintf( bscc_file, "%scif%s.bscc", BSCCFILEPATH, model_name ); //sprintf( bscc_file, "%sbjfilter%s.bscc", BSCCFILEPATH, model_name ); if( write_to_bsccfile( bscc_file, bscc_buf, bscc_id ) ) result = -1; *fp = tmp_fp; } *is_setregi = regi_flag; *is_direct = direct_flag; /* Ver.3.20 */ cupsFreeOptions( num_opt, p_opt ); return result; open_error: cupsFreeOptions( num_opt, p_opt ); return -1; }
static int /* O - Number of options or -1 on error */ get_printer(http_t *http, /* I - HTTP connection */ const char *name, /* I - Printer name from request */ char *dest, /* I - Destination buffer */ size_t destsize, /* I - Size of destination buffer */ cups_option_t **options, /* O - Printer options */ int *accepting, /* O - printer-is-accepting-jobs value */ int *shared, /* O - printer-is-shared value */ ipp_pstate_t *state) /* O - printer-state value */ { int num_options; /* Number of options */ cups_file_t *fp; /* lpoptions file */ char line[1024], /* Line from lpoptions file */ *value, /* Pointer to value on line */ *optptr; /* Pointer to options on line */ int linenum; /* Line number in file */ const char *cups_serverroot; /* CUPS_SERVERROOT env var */ ipp_t *request; /* IPP request */ ipp_t *response; /* IPP response */ ipp_attribute_t *attr; /* IPP attribute */ char uri[HTTP_MAX_URI]; /* Printer URI */ static const char * const requested[] = { /* Requested attributes */ "printer-info", "printer-is-accepting-jobs", "printer-is-shared", "printer-name", "printer-state" }; /* * Initialize everything... */ if (accepting) *accepting = 0; if (shared) *shared = 0; if (state) *state = IPP_PRINTER_STOPPED; if (options) *options = NULL; /* * See if the name is a queue name optionally with an instance name. */ strlcpy(dest, name, destsize); if ((value = strchr(dest, '/')) != NULL) *value = '\0'; /* * Setup the Get-Printer-Attributes request... */ request = ippNewRequest(IPP_GET_PRINTER_ATTRIBUTES); 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); ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", (int)(sizeof(requested) / sizeof(requested[0])), NULL, requested); /* * Do the request... */ response = cupsDoRequest(http, request, "/"); if (!response || cupsLastError() > IPP_OK_CONFLICT) { /* * If we can't find the printer by name, look up the printer-name * using the printer-info values... */ ipp_attribute_t *accepting_attr,/* printer-is-accepting-jobs */ *info_attr, /* printer-info */ *name_attr, /* printer-name */ *shared_attr, /* printer-is-shared */ *state_attr; /* printer-state */ ippDelete(response); /* * Setup the CUPS-Get-Printers request... */ request = ippNewRequest(CUPS_GET_PRINTERS); ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", (int)(sizeof(requested) / sizeof(requested[0])), NULL, requested); /* * Do the request... */ response = cupsDoRequest(http, request, "/"); if (!response || cupsLastError() > IPP_OK_CONFLICT) { syslog(LOG_ERR, "Unable to get list of printers - %s", cupsLastErrorString()); ippDelete(response); return (-1); } /* * Scan the response for printers... */ *dest = '\0'; attr = response->attrs; while (attr) { /* * Skip to the next printer... */ while (attr && attr->group_tag != IPP_TAG_PRINTER) attr = attr->next; if (!attr) break; /* * Get all of the attributes for the current printer... */ accepting_attr = NULL; info_attr = NULL; name_attr = NULL; shared_attr = NULL; state_attr = NULL; while (attr && attr->group_tag == IPP_TAG_PRINTER) { if (!strcmp(attr->name, "printer-is-accepting-jobs") && attr->value_tag == IPP_TAG_BOOLEAN) accepting_attr = attr; else if (!strcmp(attr->name, "printer-info") && attr->value_tag == IPP_TAG_TEXT) info_attr = attr; else if (!strcmp(attr->name, "printer-name") && attr->value_tag == IPP_TAG_NAME) name_attr = attr; else if (!strcmp(attr->name, "printer-is-shared") && attr->value_tag == IPP_TAG_BOOLEAN) shared_attr = attr; else if (!strcmp(attr->name, "printer-state") && attr->value_tag == IPP_TAG_ENUM) state_attr = attr; attr = attr->next; } if (info_attr && name_attr && !_cups_strcasecmp(name, info_attr->values[0].string.text)) { /* * Found a match, use this one! */ strlcpy(dest, name_attr->values[0].string.text, destsize); if (accepting && accepting_attr) *accepting = accepting_attr->values[0].boolean; if (shared && shared_attr) *shared = shared_attr->values[0].boolean; if (state && state_attr) *state = (ipp_pstate_t)state_attr->values[0].integer; break; } } ippDelete(response); if (!*dest) { syslog(LOG_ERR, "Unable to find \"%s\" in list of printers!", name); return (-1); } name = dest; } else { /* * Get values from the response... */ if (accepting) { if ((attr = ippFindAttribute(response, "printer-is-accepting-jobs", IPP_TAG_BOOLEAN)) == NULL) syslog(LOG_ERR, "No printer-is-accepting-jobs attribute found in " "response from server!"); else *accepting = attr->values[0].boolean; } if (shared) { if ((attr = ippFindAttribute(response, "printer-is-shared", IPP_TAG_BOOLEAN)) == NULL) { syslog(LOG_ERR, "No printer-is-shared attribute found in " "response from server!"); *shared = 1; } else *shared = attr->values[0].boolean; } if (state) { if ((attr = ippFindAttribute(response, "printer-state", IPP_TAG_ENUM)) == NULL) syslog(LOG_ERR, "No printer-state attribute found in " "response from server!"); else *state = (ipp_pstate_t)attr->values[0].integer; } ippDelete(response); } /* * Next look for the printer in the lpoptions file... */ num_options = 0; if (options && shared && accepting) { if ((cups_serverroot = getenv("CUPS_SERVERROOT")) == NULL) cups_serverroot = CUPS_SERVERROOT; snprintf(line, sizeof(line), "%s/lpoptions", cups_serverroot); if ((fp = cupsFileOpen(line, "r")) != NULL) { linenum = 0; while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum)) { /* * Make sure we have "Dest name options" or "Default name options"... */ if ((_cups_strcasecmp(line, "Dest") && _cups_strcasecmp(line, "Default")) || !value) continue; /* * Separate destination name from options... */ for (optptr = value; *optptr && !isspace(*optptr & 255); optptr ++); while (*optptr == ' ') *optptr++ = '\0'; /* * If this is our destination, parse the options and break out of * the loop - we're done! */ if (!_cups_strcasecmp(value, name)) { num_options = cupsParseOptions(optptr, num_options, options); break; } } cupsFileClose(fp); } } else if (options) *options = NULL; /* * Return the number of options for this destination... */ return (num_options); }
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); }
int /* O - Exit status */ main(int argc, /* I - Number of command-line args */ char *argv[]) /* I - Command-line arguments */ { int errors; /* Number of errors */ const char *ext; /* Filename extension */ if (argc == 1) { errors = do_ps_tests(); errors += do_raster_tests(CUPS_RASTER_WRITE); errors += do_raster_tests(CUPS_RASTER_WRITE_COMPRESSED); errors += do_raster_tests(CUPS_RASTER_WRITE_PWG); } else { int i; /* Looping var */ int num_options; /* Number of options */ cups_option_t *options; /* Options */ for (errors = 0, num_options = 0, options = NULL, i = 1; i < argc; i ++) { if (argv[i][0] == '-') { if (argv[i][1] == 'o') { if (argv[i][2]) num_options = cupsParseOptions(argv[i] + 2, num_options, &options); else { i ++; if (i < argc) num_options = cupsParseOptions(argv[i], num_options, &options); else { puts("Usage: testraster [-o name=value ...] [filename.ppd ...]"); puts(" testraster [filename.ras ...]"); return (1); } } } else { puts("Usage: testraster [-o name=value ...] [filename.ppd ...]"); puts(" testraster [filename.ras ...]"); return (1); } } else if ((ext = strrchr(argv[i], '.')) != NULL) { if (!strcmp(ext, ".ppd")) errors += do_ppd_tests(argv[i], num_options, options); else errors += do_ras_file(argv[i]); } else { puts("Usage: testraster [-o name=value ...] [filename.ppd ...]"); puts(" testraster [filename.ras ...]"); return (1); } } cupsFreeOptions(num_options, options); } return (errors); }
int /* O - Exit status */ main(int argc, /* I - Number of command-line args */ char *argv[]) /* I - Command-line arguments */ { int fd; /* Raster file */ cups_raster_t *inras, /* Input raster stream */ *outras; /* Output raster stream */ cups_page_header2_t inheader, /* Input raster page header */ outheader; /* Output raster page header */ int y; /* Current line */ unsigned char *line; /* Line buffer */ int page = 0, /* Current page */ page_width, /* Actual page width */ page_height, /* Actual page height */ page_top, /* Top margin */ page_bottom, /* Bottom margin */ page_left, /* Left margin */ linesize, /* Bytes per line */ lineoffset; /* Offset into line */ unsigned char white; /* White pixel */ ppd_file_t *ppd; /* PPD file */ ppd_attr_t *back; /* cupsBackSize attribute */ _ppd_cache_t *cache; /* PPD cache */ _pwg_size_t *pwg_size; /* PWG media size */ _pwg_media_t *pwg_media; /* PWG media name */ int num_options; /* Number of options */ cups_option_t *options = NULL;/* Options */ const char *val; /* Option value */ if (argc < 6 || argc > 7) { puts("Usage: rastertopwg job user title copies options [filename]"); return (1); } else if (argc == 7) { if ((fd = open(argv[6], O_RDONLY)) < 0) { perror("ERROR: Unable to open print file"); return (1); } } else fd = 0; inras = cupsRasterOpen(fd, CUPS_RASTER_READ); outras = cupsRasterOpen(1, CUPS_RASTER_WRITE_PWG); ppd = ppdOpenFile(getenv("PPD")); back = ppdFindAttr(ppd, "cupsBackSide", NULL); num_options = cupsParseOptions(argv[5], 0, &options); ppdMarkDefaults(ppd); cupsMarkOptions(ppd, num_options, options); cache = ppd ? ppd->cache : NULL; while (cupsRasterReadHeader2(inras, &inheader)) { /* * Compute the real raster size... */ page ++; fprintf(stderr, "PAGE: %d %d\n", page, inheader.NumCopies); page_width = (int)(inheader.cupsPageSize[0] * inheader.HWResolution[0] / 72.0); page_height = (int)(inheader.cupsPageSize[1] * inheader.HWResolution[1] / 72.0); page_left = (int)(inheader.cupsImagingBBox[0] * inheader.HWResolution[0] / 72.0); page_bottom = (int)(inheader.cupsImagingBBox[1] * inheader.HWResolution[1] / 72.0); page_top = page_height - page_bottom - inheader.cupsHeight; linesize = (page_width * inheader.cupsBitsPerPixel + 7) / 8; lineoffset = page_left * inheader.cupsBitsPerPixel / 8; /* Round down */ switch (inheader.cupsColorSpace) { case CUPS_CSPACE_W : case CUPS_CSPACE_RGB : case CUPS_CSPACE_SW : case CUPS_CSPACE_SRGB : case CUPS_CSPACE_ADOBERGB : white = 255; break; case CUPS_CSPACE_K : case CUPS_CSPACE_CMYK : case CUPS_CSPACE_DEVICE1 : case CUPS_CSPACE_DEVICE2 : case CUPS_CSPACE_DEVICE3 : case CUPS_CSPACE_DEVICE4 : case CUPS_CSPACE_DEVICE5 : case CUPS_CSPACE_DEVICE6 : case CUPS_CSPACE_DEVICE7 : case CUPS_CSPACE_DEVICE8 : case CUPS_CSPACE_DEVICE9 : case CUPS_CSPACE_DEVICEA : case CUPS_CSPACE_DEVICEB : case CUPS_CSPACE_DEVICEC : case CUPS_CSPACE_DEVICED : case CUPS_CSPACE_DEVICEE : case CUPS_CSPACE_DEVICEF : white = 0; break; default : _cupsLangPrintFilter(stderr, "ERROR", _("Unsupported raster data.")); fprintf(stderr, "DEBUG: Unsupported cupsColorSpace %d on page %d.\n", inheader.cupsColorSpace, page); return (1); } if (inheader.cupsColorOrder != CUPS_ORDER_CHUNKED) { _cupsLangPrintFilter(stderr, "ERROR", _("Unsupported raster data.")); fprintf(stderr, "DEBUG: Unsupported cupsColorOrder %d on page %d.\n", inheader.cupsColorOrder, page); return (1); } if (inheader.cupsBitsPerPixel != 1 && inheader.cupsBitsPerColor != 8 && inheader.cupsBitsPerColor != 16) { _cupsLangPrintFilter(stderr, "ERROR", _("Unsupported raster data.")); fprintf(stderr, "DEBUG: Unsupported cupsBitsPerColor %d on page %d.\n", inheader.cupsBitsPerColor, page); return (1); } memcpy(&outheader, &inheader, sizeof(outheader)); outheader.cupsWidth = page_width; outheader.cupsHeight = page_height; outheader.cupsBytesPerLine = linesize; outheader.cupsInteger[14] = 0; /* VendorIdentifier */ outheader.cupsInteger[15] = 0; /* VendorLength */ if ((val = cupsGetOption("print-content-optimize", num_options, options)) != NULL) { if (!strcmp(val, "automatic")) strlcpy(outheader.OutputType, "Automatic", sizeof(outheader.OutputType)); else if (!strcmp(val, "graphics")) strlcpy(outheader.OutputType, "Graphics", sizeof(outheader.OutputType)); else if (!strcmp(val, "photo")) strlcpy(outheader.OutputType, "Photo", sizeof(outheader.OutputType)); else if (!strcmp(val, "text")) strlcpy(outheader.OutputType, "Text", sizeof(outheader.OutputType)); else if (!strcmp(val, "text-and-graphics")) strlcpy(outheader.OutputType, "TextAndGraphics", sizeof(outheader.OutputType)); else { fprintf(stderr, "DEBUG: Unsupported print-content-type \"%s\".\n", val); outheader.OutputType[0] = '\0'; } } if ((val = cupsGetOption("print-quality", num_options, options)) != NULL) { int quality = atoi(val); /* print-quality value */ if (quality >= IPP_QUALITY_DRAFT && quality <= IPP_QUALITY_HIGH) outheader.cupsInteger[8] = quality; else { fprintf(stderr, "DEBUG: Unsupported print-quality %d.\n", quality); outheader.cupsInteger[8] = 0; } } if ((val = cupsGetOption("print-rendering-intent", num_options, options)) != NULL) { if (!strcmp(val, "absolute")) strlcpy(outheader.cupsRenderingIntent, "Absolute", sizeof(outheader.cupsRenderingIntent)); else if (!strcmp(val, "automatic")) strlcpy(outheader.cupsRenderingIntent, "Automatic", sizeof(outheader.cupsRenderingIntent)); else if (!strcmp(val, "perceptual")) strlcpy(outheader.cupsRenderingIntent, "Perceptual", sizeof(outheader.cupsRenderingIntent)); else if (!strcmp(val, "relative")) strlcpy(outheader.cupsRenderingIntent, "Relative", sizeof(outheader.cupsRenderingIntent)); else if (!strcmp(val, "relative-bpc")) strlcpy(outheader.cupsRenderingIntent, "RelativeBpc", sizeof(outheader.cupsRenderingIntent)); else if (!strcmp(val, "saturation")) strlcpy(outheader.cupsRenderingIntent, "Saturation", sizeof(outheader.cupsRenderingIntent)); else { fprintf(stderr, "DEBUG: Unsupported print-rendering-intent \"%s\".\n", val); outheader.cupsRenderingIntent[0] = '\0'; } } if (inheader.cupsPageSizeName[0] && (pwg_size = _ppdCacheGetSize(cache, inheader.cupsPageSizeName)) != NULL) { strlcpy(outheader.cupsPageSizeName, pwg_size->map.pwg, sizeof(outheader.cupsPageSizeName)); } else { pwg_media = _pwgMediaForSize((int)(2540.0 * inheader.cupsPageSize[0] / 72.0), (int)(2540.0 * inheader.cupsPageSize[1] / 72.0)); if (pwg_media) strlcpy(outheader.cupsPageSizeName, pwg_media->pwg, sizeof(outheader.cupsPageSizeName)); else { fprintf(stderr, "DEBUG: Unsupported PageSize %.2fx%.2f.\n", inheader.cupsPageSize[0], inheader.cupsPageSize[1]); outheader.cupsPageSizeName[0] = '\0'; } } if (inheader.Duplex && !(page & 1) && back && _cups_strcasecmp(back->value, "Normal")) { if (_cups_strcasecmp(back->value, "Flipped")) { if (inheader.Tumble) { outheader.cupsInteger[1] = -1;/* CrossFeedTransform */ outheader.cupsInteger[2] = 1; /* FeedTransform */ outheader.cupsInteger[3] = page_width - page_left - inheader.cupsWidth; /* ImageBoxLeft */ outheader.cupsInteger[4] = page_top; /* ImageBoxTop */ outheader.cupsInteger[5] = page_width - page_left; /* ImageBoxRight */ outheader.cupsInteger[6] = page_height - page_bottom; /* ImageBoxBottom */ } else { outheader.cupsInteger[1] = 1; /* CrossFeedTransform */ outheader.cupsInteger[2] = -1;/* FeedTransform */ outheader.cupsInteger[3] = page_left; /* ImageBoxLeft */ outheader.cupsInteger[4] = page_bottom; /* ImageBoxTop */ outheader.cupsInteger[5] = page_left + inheader.cupsWidth; /* ImageBoxRight */ outheader.cupsInteger[6] = page_height - page_top; /* ImageBoxBottom */ } } else if (_cups_strcasecmp(back->value, "ManualTumble")) { if (inheader.Tumble) { outheader.cupsInteger[1] = -1;/* CrossFeedTransform */ outheader.cupsInteger[2] = -1;/* FeedTransform */ outheader.cupsInteger[3] = page_width - page_left - inheader.cupsWidth; /* ImageBoxLeft */ outheader.cupsInteger[4] = page_bottom; /* ImageBoxTop */ outheader.cupsInteger[5] = page_width - page_left; /* ImageBoxRight */ outheader.cupsInteger[6] = page_height - page_top; /* ImageBoxBottom */ } else { outheader.cupsInteger[1] = 1; /* CrossFeedTransform */ outheader.cupsInteger[2] = 1; /* FeedTransform */ outheader.cupsInteger[3] = page_left; /* ImageBoxLeft */ outheader.cupsInteger[4] = page_top; /* ImageBoxTop */ outheader.cupsInteger[5] = page_left + inheader.cupsWidth; /* ImageBoxRight */ outheader.cupsInteger[6] = page_height - page_bottom; /* ImageBoxBottom */ } } else if (_cups_strcasecmp(back->value, "Rotated")) { if (inheader.Tumble) { outheader.cupsInteger[1] = -1;/* CrossFeedTransform */ outheader.cupsInteger[2] = -1;/* FeedTransform */ outheader.cupsInteger[3] = page_width - page_left - inheader.cupsWidth; /* ImageBoxLeft */ outheader.cupsInteger[4] = page_bottom; /* ImageBoxTop */ outheader.cupsInteger[5] = page_width - page_left; /* ImageBoxRight */ outheader.cupsInteger[6] = page_height - page_top; /* ImageBoxBottom */ } else { outheader.cupsInteger[1] = 1; /* CrossFeedTransform */ outheader.cupsInteger[2] = 1; /* FeedTransform */ outheader.cupsInteger[3] = page_left; /* ImageBoxLeft */ outheader.cupsInteger[4] = page_top; /* ImageBoxTop */ outheader.cupsInteger[5] = page_left + inheader.cupsWidth; /* ImageBoxRight */ outheader.cupsInteger[6] = page_height - page_bottom; /* ImageBoxBottom */ } } else { /* * Unsupported value... */ fprintf(stderr, "DEBUG: Unsupported cupsBackSide \"%s\".\n", back->value); outheader.cupsInteger[1] = 1; /* CrossFeedTransform */ outheader.cupsInteger[2] = 1; /* FeedTransform */ outheader.cupsInteger[3] = page_left; /* ImageBoxLeft */ outheader.cupsInteger[4] = page_top; /* ImageBoxTop */ outheader.cupsInteger[5] = page_left + inheader.cupsWidth; /* ImageBoxRight */ outheader.cupsInteger[6] = page_height - page_bottom; /* ImageBoxBottom */ } } else { outheader.cupsInteger[1] = 1; /* CrossFeedTransform */ outheader.cupsInteger[2] = 1; /* FeedTransform */ outheader.cupsInteger[3] = page_left; /* ImageBoxLeft */ outheader.cupsInteger[4] = page_top; /* ImageBoxTop */ outheader.cupsInteger[5] = page_left + inheader.cupsWidth; /* ImageBoxRight */ outheader.cupsInteger[6] = page_height - page_bottom; /* ImageBoxBottom */ } if (!cupsRasterWriteHeader2(outras, &outheader)) { _cupsLangPrintFilter(stderr, "ERROR", _("Error sending raster data.")); fprintf(stderr, "DEBUG: Unable to write header for page %d.\n", page); return (1); } /* * Copy raster data... */ line = malloc(linesize); memset(line, white, linesize); for (y = page_top; y > 0; y --) if (!cupsRasterWritePixels(outras, line, outheader.cupsBytesPerLine)) { _cupsLangPrintFilter(stderr, "ERROR", _("Error sending raster data.")); fprintf(stderr, "DEBUG: Unable to write line %d for page %d.\n", page_top - y + 1, page); return (1); } for (y = inheader.cupsHeight; y > 0; y --) { cupsRasterReadPixels(inras, line + lineoffset, inheader.cupsBytesPerLine); if (!cupsRasterWritePixels(outras, line, outheader.cupsBytesPerLine)) { _cupsLangPrintFilter(stderr, "ERROR", _("Error sending raster data.")); fprintf(stderr, "DEBUG: Unable to write line %d for page %d.\n", inheader.cupsHeight - y + page_top + 1, page); return (1); } } memset(line, white, linesize); for (y = page_bottom; y > 0; y --) if (!cupsRasterWritePixels(outras, line, outheader.cupsBytesPerLine)) { _cupsLangPrintFilter(stderr, "ERROR", _("Error sending raster data.")); fprintf(stderr, "DEBUG: Unable to write line %d for page %d.\n", page_bottom - y + page_top + inheader.cupsHeight + 1, page); return (1); } free(line); } cupsRasterClose(inras); if (fd) close(fd); cupsRasterClose(outras); return (0); }
int /* O - Exit status */ main(int argc, /* I - Number of command-line arguments */ char *argv[]) /* I - Command-line arguments */ { int i; /* Looping var */ ppd_file_t *ppd; /* PPD file loaded from disk */ char line[256], /* Input buffer */ *ptr, /* Pointer into buffer */ *optr, /* Pointer to first option name */ *cptr; /* Pointer to first choice */ int num_options; /* Number of options */ cups_option_t *options; /* Options */ char *option, /* Current option */ *choice; /* Current choice */ if (argc != 2) { puts("Usage: testconflicts filename.ppd"); return (1); } if ((ppd = ppdOpenFile(argv[1])) == NULL) { ppd_status_t err; /* Last error in file */ int linenum; /* Line number in file */ err = ppdLastError(&linenum); printf("Unable to open PPD file \"%s\": %s on line %d\n", argv[1], ppdErrorString(err), linenum); return (1); } ppdMarkDefaults(ppd); option = NULL; choice = NULL; for (;;) { num_options = 0; options = NULL; if (!cupsResolveConflicts(ppd, option, choice, &num_options, &options)) puts("Unable to resolve conflicts!"); else if ((!option && num_options > 0) || (option && num_options > 1)) { fputs("Resolved conflicts with the following options:\n ", stdout); for (i = 0; i < num_options; i ++) if (!option || _cups_strcasecmp(option, options[i].name)) printf(" %s=%s", options[i].name, options[i].value); putchar('\n'); cupsFreeOptions(num_options, options); } if (option) { free(option); option = NULL; } if (choice) { free(choice); choice = NULL; } printf("\nNew Option(s): "); fflush(stdout); if (!fgets(line, sizeof(line), stdin) || line[0] == '\n') break; for (ptr = line; isspace(*ptr & 255); ptr ++); for (optr = ptr; *ptr && *ptr != '='; ptr ++); if (!*ptr) break; for (*ptr++ = '\0', cptr = ptr; *ptr && !isspace(*ptr & 255); ptr ++); if (!*ptr) break; *ptr++ = '\0'; option = strdup(optr); choice = strdup(cptr); num_options = cupsParseOptions(ptr, 0, &options); ppdMarkOption(ppd, option, choice); if (cupsMarkOptions(ppd, num_options, options)) puts("Options Conflict!"); cupsFreeOptions(num_options, options); } if (option) free(option); if (choice) free(choice); return (0); }
int /* O - Exit status */ main(int argc, /* I - Number of command-line args */ char *argv[]) /* I - Command-line arguments */ { int i; /* Looping vars */ const char *command, /* Command name */ *opt; /* Current option */ char *srctype, /* Source type */ *dsttype, /* Destination type */ super[MIME_MAX_SUPER], /* Super-type name */ type[MIME_MAX_TYPE]; /* Type name */ int compression; /* Compression of file */ int cost; /* Cost of filters */ mime_t *mime; /* MIME database */ char *infile, /* File to filter */ *outfile; /* File to create */ char cupsdconf[1024]; /* cupsd.conf file */ const char *server_root; /* CUPS_SERVERROOT environment variable */ mime_type_t *src, /* Source type */ *dst; /* Destination type */ cups_array_t *filters; /* Filters for the file */ int num_options; /* Number of options */ cups_option_t *options; /* Options */ const char *ppdfile; /* PPD file */ const char *title, /* Title string */ *user; /* Username */ int removeppd, /* Remove PPD file */ removeinfile; /* Remove input file */ int status; /* Execution status */ /* * Setup defaults... */ if ((command = strrchr(argv[0], '/')) != NULL) command ++; else command = argv[0]; mime = NULL; srctype = NULL; compression = 0; dsttype = "application/pdf"; infile = NULL; outfile = NULL; num_options = 0; options = NULL; ppdfile = NULL; title = NULL; user = cupsUser(); removeppd = 0; removeinfile = 0; if ((server_root = getenv("CUPS_SERVERROOT")) == NULL) server_root = CUPS_SERVERROOT; snprintf(cupsdconf, sizeof(cupsdconf), "%s/cupsd.conf", server_root); /* * Process command-line arguments... */ _cupsSetLocale(argv); for (i = 1; i < argc; i ++) if (argv[i][0] == '-') { for (opt = argv[i] + 1; *opt; opt ++) switch (*opt) { case '-' : /* Next argument is a filename... */ i ++; if (i < argc && !infile) infile = argv[i]; else usage(command, opt); break; case 'a' : /* Specify option... */ i ++; if (i < argc) num_options = cupsParseOptions(argv[i], num_options, &options); else usage(command, opt); break; case 'c' : /* Specify cupsd.conf file location... */ i ++; if (i < argc) { if (!strcmp(command, "convert")) num_options = cupsAddOption("copies", argv[i], num_options, &options); else strlcpy(cupsdconf, argv[i], sizeof(cupsdconf)); } else usage(command, opt); break; case 'D' : /* Delete input file after conversion */ removeinfile = 1; break; case 'f' : /* Specify input file... */ i ++; if (i < argc && !infile) infile = argv[i]; else usage(command, opt); break; case 'i' : /* Specify source MIME type... */ i ++; if (i < argc) { if (sscanf(argv[i], "%15[^/]/%255s", super, type) != 2) usage(command, opt); srctype = argv[i]; } else usage(command, opt); break; case 'j' : /* Specify destination MIME type... */ case 'm' : /* Specify destination MIME type... */ i ++; if (i < argc) { if (sscanf(argv[i], "%15[^/]/%255s", super, type) != 2) usage(command, opt); dsttype = argv[i]; } else usage(command, opt); break; case 'n' : /* Specify number of copies... */ i ++; if (i < argc) num_options = cupsAddOption("copies", argv[i], num_options, &options); else usage(command, opt); break; case 'o' : /* Specify option(s) or output filename */ i ++; if (i < argc) { if (!strcmp(command, "convert")) { if (outfile) usage(command, NULL); else outfile = argv[i]; } else num_options = cupsParseOptions(argv[i], num_options, &options); } else usage(command, opt); break; case 'p' : /* Specify PPD file... */ case 'P' : /* Specify PPD file... */ i ++; if (i < argc) ppdfile = argv[i]; else usage(command, opt); break; case 't' : /* Specify title... */ case 'J' : /* Specify title... */ i ++; if (i < argc) title = argv[i]; else usage(command, opt); break; case 'u' : /* Delete PPD file after conversion */ removeinfile = 1; break; case 'U' : /* Specify username... */ i ++; if (i < argc) user = argv[i]; else usage(command, opt); break; default : /* Something we don't understand... */ usage(command, opt); break; } } else if (!infile) { if (strcmp(command, "convert")) infile = argv[i]; else { _cupsLangPuts(stderr, _("convert: Use the -f option to specify a file to " "convert.\n")); usage(command, NULL); } } else { _cupsLangPuts(stderr, _("cupsfilter: Only one filename can be specified!\n")); usage(command, NULL); } if (!infile && !srctype) usage(command, NULL); if (!title) { if (!infile) title = "(stdin)"; else if ((title = strrchr(infile, '/')) != NULL) title ++; else title = infile; } /* * Load the cupsd.conf file and create the MIME database... */ if (read_cupsd_conf(cupsdconf)) return (1); if ((mime = mimeLoad(ServerRoot, Path)) == NULL) { _cupsLangPrintf(stderr, _("%s: Unable to read MIME database from \"%s\"!\n"), command, ServerRoot); return (1); } /* * Get the source and destination types... */ if (srctype) { sscanf(srctype, "%15[^/]/%255s", super, type); if ((src = mimeType(mime, super, type)) == NULL) { _cupsLangPrintf(stderr, _("%s: Unknown source MIME type %s/%s!\n"), command, super, type); return (1); } } else if ((src = mimeFileType(mime, infile, infile, &compression)) == NULL) { _cupsLangPrintf(stderr, _("%s: Unable to determine MIME type of \"%s\"!\n"), command, infile); return (1); } sscanf(dsttype, "%15[^/]/%255s", super, type); if ((dst = mimeType(mime, super, type)) == NULL) { _cupsLangPrintf(stderr, _("%s: Unknown destination MIME type %s/%s!\n"), command, super, type); return (1); } /* * Figure out how to filter the file... */ if (src == dst) { /* * Special case - no filtering needed... */ filters = cupsArrayNew(NULL, NULL); cupsArrayAdd(filters, &GZIPFilter); } else if ((filters = mimeFilter(mime, src, dst, &cost)) == NULL) { _cupsLangPrintf(stderr, _("%s: No filter to convert from %s/%s to %s/%s!\n"), command, src->super, src->type, dst->super, dst->type); return (1); } else if (compression) cupsArrayInsert(filters, &GZIPFilter); /* * Do it! */ status = exec_filters(filters, infile, outfile, ppdfile, !strcmp(command, "convert") ? "tofile" : "cupsfilter", user, title, num_options, options); /* * Remove files as needed, then exit... */ if (removeppd && ppdfile) unlink(ppdfile); if (removeinfile && infile) unlink(infile); return (status); }
int main(int argc, /* I - Number of command-line arguments */ char *argv[]) /* I - Command-line arguments */ { int i, j; /* Looping var */ int job_id; /* Job ID */ char ch; /* Option character */ char *printer, /* Destination printer or class */ *instance; /* Instance */ const char *title, /* Job title */ *val; /* Environment variable name */ int num_copies; /* Number of copies per file */ int num_files; /* Number of files to print */ const char *files[1000]; /* Files to print */ cups_dest_t *dest; /* Selected destination */ int num_options; /* Number of options */ cups_option_t *options; /* Options */ int deletefile; /* Delete file after print? */ char buffer[8192]; /* Copy buffer */ _cupsSetLocale(argv); deletefile = 0; printer = NULL; dest = NULL; num_options = 0; options = NULL; num_files = 0; title = NULL; for (i = 1; i < argc; i ++) if (argv[i][0] == '-') switch (ch = argv[i][1]) { case 'E' : /* Encrypt */ #ifdef HAVE_SSL cupsSetEncryption(HTTP_ENCRYPT_REQUIRED); #else _cupsLangPrintf(stderr, _("%s: Sorry, no encryption support."), 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."), argv[0]); return (1); } cupsSetUser(argv[i]); } break; case 'H' : /* Connect to host */ if (argv[i][2] != '\0') cupsSetServer(argv[i] + 2); else { i ++; if (i >= argc) { _cupsLangPrintf(stderr, _("%s: Error - expected hostname after " "\"-H\" option."), argv[0]); return (1); } else cupsSetServer(argv[i]); } break; case '1' : /* TROFF font set 1 */ case '2' : /* TROFF font set 2 */ case '3' : /* TROFF font set 3 */ case '4' : /* TROFF font set 4 */ case 'i' : /* indent */ case 'w' : /* width */ if (argv[i][2] == '\0') { i ++; if (i >= argc) { _cupsLangPrintf(stderr, _("%s: Error - expected value after \"-%c\" " "option."), argv[0], ch); return (1); } } case 'c' : /* CIFPLOT */ case 'd' : /* DVI */ case 'f' : /* FORTRAN */ case 'g' : /* plot */ case 'n' : /* Ditroff */ case 't' : /* Troff */ case 'v' : /* Raster image */ _cupsLangPrintf(stderr, _("%s: Warning - \"%c\" format modifier not " "supported - output may not be correct."), argv[0], ch); break; case 'o' : /* Option */ if (argv[i][2] != '\0') num_options = cupsParseOptions(argv[i] + 2, num_options, &options); else { i ++; if (i >= argc) { _cupsLangPrintf(stderr, _("%s: Error - expected option=value after " "\"-o\" option."), argv[0]); return (1); } num_options = cupsParseOptions(argv[i], num_options, &options); } break; case 'l' : /* Literal/raw */ num_options = cupsAddOption("raw", "true", num_options, &options); break; case 'p' : /* Prettyprint */ num_options = cupsAddOption("prettyprint", "true", num_options, &options); break; case 'h' : /* Suppress burst page */ num_options = cupsAddOption("job-sheets", "none", num_options, &options); break; case 's' : /* Don't use symlinks */ break; case 'm' : /* Mail on completion */ { char email[1024]; /* EMail address */ snprintf(email, sizeof(email), "mailto:%s@%s", cupsUser(), httpGetHostname(NULL, buffer, sizeof(buffer))); num_options = cupsAddOption("notify-recipient-uri", email, num_options, &options); } break; case 'q' : /* Queue file but don't print */ num_options = cupsAddOption("job-hold-until", "indefinite", num_options, &options); break; case 'r' : /* Remove file after printing */ deletefile = 1; break; case 'P' : /* Destination printer or class */ if (argv[i][2] != '\0') printer = argv[i] + 2; else { i ++; if (i >= argc) { _cupsLangPrintf(stderr, _("%s: Error - expected destination after " "\"-P\" option."), argv[0]); return (1); } printer = argv[i]; } if ((instance = strrchr(printer, '/')) != NULL) *instance++ = '\0'; if ((dest = cupsGetNamedDest(NULL, printer, instance)) != NULL) { for (j = 0; j < dest->num_options; j ++) if (cupsGetOption(dest->options[j].name, num_options, options) == NULL) num_options = cupsAddOption(dest->options[j].name, dest->options[j].value, num_options, &options); } break; case '#' : /* Number of copies */ if (argv[i][2] != '\0') num_copies = atoi(argv[i] + 2); else { i ++; if (i >= argc) { _cupsLangPrintf(stderr, _("%s: Error - expected copies after " "\"-#\" option."), argv[0]); return (1); } num_copies = atoi(argv[i]); } sprintf(buffer, "%d", num_copies); num_options = cupsAddOption("copies", buffer, num_options, &options); break; case 'C' : /* Class */ case 'J' : /* Job name */ case 'T' : /* Title */ if (argv[i][2] != '\0') title = argv[i] + 2; else { i ++; if (i >= argc) { _cupsLangPrintf(stderr, _("%s: Error - expected name after \"-%c\" " "option."), argv[0], ch); return (1); } title = argv[i]; } break; default : _cupsLangPrintf(stderr, _("%s: Error - unknown option \"%c\"."), argv[0], argv[i][1]); return (1); } else if (num_files < 1000) { /* * Print a file... */ if (access(argv[i], R_OK) != 0) { _cupsLangPrintf(stderr, _("%s: Error - unable to access \"%s\" - %s"), argv[0], argv[i], strerror(errno)); return (1); } files[num_files] = argv[i]; num_files ++; if (title == NULL) { if ((title = strrchr(argv[i], '/')) != NULL) title ++; else title = argv[i]; } } else _cupsLangPrintf(stderr, _("%s: Error - too many files - \"%s\"."), argv[0], argv[i]); /* * See if we have any files to print; if not, print from stdin... */ if (printer == NULL) { if ((dest = cupsGetNamedDest(NULL, NULL, NULL)) != NULL) { printer = dest->name; for (j = 0; j < dest->num_options; j ++) if (cupsGetOption(dest->options[j].name, num_options, options) == NULL) num_options = cupsAddOption(dest->options[j].name, dest->options[j].value, num_options, &options); } } if (printer == NULL) { val = NULL; if ((printer = getenv("LPDEST")) == NULL) { if ((printer = getenv("PRINTER")) != NULL) { if (!strcmp(printer, "lp")) printer = NULL; else val = "PRINTER"; } } else val = "LPDEST"; if (printer && !cupsGetNamedDest(NULL, printer, NULL)) _cupsLangPrintf(stderr, _("%s: Error - %s environment variable names " "non-existent destination \"%s\"."), argv[0], val, printer); else if (cupsLastError() == IPP_NOT_FOUND) _cupsLangPrintf(stderr, _("%s: Error - no default destination available."), argv[0]); else _cupsLangPrintf(stderr, _("%s: Error - scheduler not responding."), argv[0]); return (1); } if (num_files > 0) { job_id = cupsPrintFiles(printer, num_files, files, title, num_options, options); if (deletefile && job_id > 0) { /* * Delete print files after printing... */ for (i = 0; i < num_files; i ++) unlink(files[i]); } } else if ((job_id = cupsCreateJob(CUPS_HTTP_DEFAULT, printer, title ? title : "(stdin)", num_options, options)) > 0) { http_status_t status; /* Write status */ const char *format; /* Document format */ ssize_t bytes; /* Bytes read */ if (cupsGetOption("raw", num_options, options)) format = CUPS_FORMAT_RAW; else if ((format = cupsGetOption("document-format", num_options, options)) == NULL) format = CUPS_FORMAT_AUTO; status = cupsStartDocument(CUPS_HTTP_DEFAULT, printer, job_id, NULL, format, 1); while (status == HTTP_CONTINUE && (bytes = read(0, buffer, sizeof(buffer))) > 0) status = cupsWriteRequestData(CUPS_HTTP_DEFAULT, buffer, bytes); if (status != HTTP_CONTINUE) { _cupsLangPrintf(stderr, _("%s: Error - unable to queue from stdin - %s."), argv[0], httpStatus(status)); cupsFinishDocument(CUPS_HTTP_DEFAULT, printer); cupsCancelJob2(CUPS_HTTP_DEFAULT, printer, job_id, 0); return (1); } if (cupsFinishDocument(CUPS_HTTP_DEFAULT, printer) != IPP_OK) { _cupsLangPrintf(stderr, "%s: %s", argv[0], cupsLastErrorString()); cupsCancelJob2(CUPS_HTTP_DEFAULT, printer, job_id, 0); return (1); } } if (job_id < 1) { _cupsLangPrintf(stderr, "%s: %s", argv[0], cupsLastErrorString()); return (1); } return (0); }
int /* O - Exit status */ main(int argc, /* I - Number of command-line arguments */ char *argv[]) /* I - Command-line arguments */ { int i, j; /* Looping vars */ int changes; /* Did we make changes? */ int num_options; /* Number of options */ cups_option_t *options; /* Options */ int num_dests; /* Number of destinations */ cups_dest_t *dests; /* Destinations */ cups_dest_t *dest; /* Current destination */ char *opt, /* Option pointer */ *printer, /* Printer name */ *instance, /* Instance name */ *option; /* Current option */ _cupsSetLocale(argv); /* * Loop through the command-line arguments... */ dest = NULL; num_dests = 0; dests = NULL; num_options = 0; options = NULL; changes = 0; for (i = 1; i < argc; i ++) { if (!strcmp(argv[i], "--help")) usage(); else if (argv[i][0] == '-') { for (opt = argv[i] + 1; *opt; opt ++) { switch (*opt) { case 'd' : /* -d printer */ if (opt[1] != '\0') { printer = opt + 1; opt += strlen(opt) - 1; } else { i ++; if (i >= argc) usage(); printer = argv[i]; } if ((instance = strrchr(printer, '/')) != NULL) *instance++ = '\0'; if (num_dests == 0) num_dests = cupsGetDests(&dests); if (num_dests == 0 || !dests || (dest = cupsGetDest(printer, instance, num_dests, dests)) == NULL) { _cupsLangPuts(stderr, _("lpoptions: Unknown printer or class.")); return (1); } /* * Set the default destination... */ for (j = 0; j < num_dests; j ++) dests[j].is_default = 0; dest->is_default = 1; cupsSetDests(num_dests, dests); for (j = 0; j < dest->num_options; j ++) if (cupsGetOption(dest->options[j].name, num_options, options) == NULL) num_options = cupsAddOption(dest->options[j].name, dest->options[j].value, num_options, &options); break; case 'h' : /* -h server */ if (opt[1] != '\0') { cupsSetServer(opt + 1); opt += strlen(opt) - 1; } else { i ++; if (i >= argc) usage(); cupsSetServer(argv[i]); } break; case 'E' : /* Encrypt connection */ cupsSetEncryption(HTTP_ENCRYPT_REQUIRED); break; case 'l' : /* -l (list options) */ if (dest == NULL) { if (num_dests == 0) num_dests = cupsGetDests(&dests); if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) == NULL) dest = dests; } if (dest == NULL) _cupsLangPuts(stderr, _("lpoptions: No printers.")); else list_options(dest); changes = -1; break; case 'o' : /* -o option[=value] */ if (dest == NULL) { if (num_dests == 0) num_dests = cupsGetDests(&dests); if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) == NULL) dest = dests; if (dest == NULL) { _cupsLangPuts(stderr, _("lpoptions: No printers.")); return (1); } for (j = 0; j < dest->num_options; j ++) if (cupsGetOption(dest->options[j].name, num_options, options) == NULL) num_options = cupsAddOption(dest->options[j].name, dest->options[j].value, num_options, &options); } if (opt[1] != '\0') { num_options = cupsParseOptions(opt + 1, num_options, &options); opt += strlen(opt) - 1; } else { i ++; if (i >= argc) usage(); num_options = cupsParseOptions(argv[i], num_options, &options); } changes = 1; break; case 'p' : /* -p printer */ if (opt[1] != '\0') { printer = opt + 1; opt += strlen(opt) - 1; } else { i ++; if (i >= argc) usage(); printer = argv[i]; } if ((instance = strrchr(printer, '/')) != NULL) *instance++ = '\0'; if (num_dests == 0) num_dests = cupsGetDests(&dests); if ((dest = cupsGetDest(printer, instance, num_dests, dests)) == NULL) { num_dests = cupsAddDest(printer, instance, num_dests, &dests); dest = cupsGetDest(printer, instance, num_dests, dests); if (dest == NULL) { _cupsLangPrintf(stderr, _("lpoptions: Unable to add printer or instance: %s"), strerror(errno)); return (1); } } for (j = 0; j < dest->num_options; j ++) if (cupsGetOption(dest->options[j].name, num_options, options) == NULL) num_options = cupsAddOption(dest->options[j].name, dest->options[j].value, num_options, &options); break; case 'r' : /* -r option (remove) */ if (dest == NULL) { if (num_dests == 0) num_dests = cupsGetDests(&dests); if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) == NULL) dest = dests; if (dest == NULL) { _cupsLangPuts(stderr, _("lpoptions: No printers.")); return (1); } for (j = 0; j < dest->num_options; j ++) if (cupsGetOption(dest->options[j].name, num_options, options) == NULL) num_options = cupsAddOption(dest->options[j].name, dest->options[j].value, num_options, &options); } if (opt[1] != '\0') { option = opt + 1; opt += strlen(opt) - 1; } else { i ++; if (i >= argc) usage(); option = argv[i]; } num_options = cupsRemoveOption(option, num_options, &options); changes = 1; break; case 'x' : /* -x printer */ if (opt[1] != '\0') { printer = opt + 1; opt += strlen(opt) - 1; } else { i ++; if (i >= argc) usage(); printer = argv[i]; } if ((instance = strrchr(printer, '/')) != NULL) *instance++ = '\0'; if (num_dests == 0) num_dests = cupsGetDests(&dests); num_dests = cupsRemoveDest(printer, instance, num_dests, &dests); cupsSetDests(num_dests, dests); dest = NULL; changes = -1; break; default : usage(); } } } else { usage(); } } if (num_dests == 0) num_dests = cupsGetDests(&dests); if (dest == NULL) { if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) != NULL) { for (j = 0; j < dest->num_options; j ++) if (cupsGetOption(dest->options[j].name, num_options, options) == NULL) num_options = cupsAddOption(dest->options[j].name, dest->options[j].value, num_options, &options); } } if (dest == NULL) return (0); if (changes > 0) { /* * Set printer options... */ cupsFreeOptions(dest->num_options, dest->options); dest->num_options = num_options; dest->options = options; cupsSetDests(num_dests, dests); } else if (changes == 0) { char buffer[10240], /* String for options */ *ptr; /* Pointer into string */ num_options = dest->num_options; options = dest->options; for (i = 0, ptr = buffer; ptr < (buffer + sizeof(buffer) - 1) && i < num_options; i ++) { if (i) *ptr++ = ' '; if (!options[i].value[0]) strlcpy(ptr, options[i].name, sizeof(buffer) - (size_t)(ptr - buffer)); else if (strchr(options[i].value, ' ') != NULL || strchr(options[i].value, '\t') != NULL) snprintf(ptr, sizeof(buffer) - (size_t)(ptr - buffer), "%s=\'%s\'", options[i].name, options[i].value); else snprintf(ptr, sizeof(buffer) - (size_t)(ptr - buffer), "%s=%s", options[i].name, options[i].value); ptr += strlen(ptr); } _cupsLangPuts(stdout, buffer); } return (0); }
int /* O - Exit status */ TextMain(const char *name, /* I - Name of filter */ int argc, /* I - Number of command-line arguments */ char *argv[]) /* I - Command-line arguments */ { FILE *fp; /* Print file */ ppd_file_t *ppd; /* PPD file */ int i, /* Looping var */ ch, /* Current char from file */ lastch, /* Previous char from file */ attr, /* Current attribute */ line, /* Current line */ column, /* Current column */ page_column; /* Current page column */ int num_options; /* Number of print options */ cups_option_t *options; /* Print options */ const char *val; /* Option value */ char keyword[64], /* Keyword string */ *keyptr; /* Pointer into string */ int keycol; /* Column where keyword starts */ int ccomment; /* Inside a C-style comment? */ int cstring; /* Inside a C string */ /* * Make sure status messages are not buffered... */ setbuf(stderr, NULL); /* * Check command-line... */ if (argc < 6 || argc > 7) { fprintf(stderr, _("Usage: %s job-id user title copies options [file]\n"), name); return (1); } /* * If we have 7 arguments, print the file named on the command-line. * Otherwise, send stdin instead... */ if (argc == 6) fp = stdin; else { /* * Try to open the print file... */ if ((fp = fopen(argv[6], "rb")) == NULL) { perror("DEBUG: unable to open print file - "); return (1); } } /* * Process command-line options and write the prolog... */ options = NULL; num_options = cupsParseOptions(argv[5], 0, &options); if ((val = cupsGetOption("prettyprint", num_options, options)) != NULL && strcasecmp(val, "no") && strcasecmp(val, "off") && strcasecmp(val, "false")) { PageLeft = 72.0f; PageRight = PageWidth - 36.0f; PageBottom = PageBottom > 36.0f ? PageBottom : 36.0f; PageTop = PageLength - 36.0f; CharsPerInch = 12; LinesPerInch = 8; if ((val = getenv("CONTENT_TYPE")) == NULL) { PrettyPrint = PRETTY_PLAIN; NumKeywords = 0; Keywords = NULL; } else if (strcasecmp(val, "application/x-cshell") == 0) { PrettyPrint = PRETTY_SHELL; NumKeywords = sizeof(csh_keywords) / sizeof(csh_keywords[0]); Keywords = csh_keywords; } else if (strcasecmp(val, "application/x-csource") == 0) { PrettyPrint = PRETTY_CODE; NumKeywords = sizeof(code_keywords) / sizeof(code_keywords[0]); Keywords = code_keywords; } else if (strcasecmp(val, "application/x-perl") == 0) { PrettyPrint = PRETTY_PERL; NumKeywords = sizeof(perl_keywords) / sizeof(perl_keywords[0]); Keywords = perl_keywords; } else if (strcasecmp(val, "application/x-shell") == 0) { PrettyPrint = PRETTY_SHELL; NumKeywords = sizeof(sh_keywords) / sizeof(sh_keywords[0]); Keywords = sh_keywords; } else { PrettyPrint = PRETTY_PLAIN; NumKeywords = 0; Keywords = NULL; } } ppd = SetCommonOptions(num_options, options, 1); if ((val = cupsGetOption("wrap", num_options, options)) == NULL) WrapLines = 1; else WrapLines = !strcasecmp(val, "true") || !strcasecmp(val, "on") || !strcasecmp(val, "yes"); if ((val = cupsGetOption("columns", num_options, options)) != NULL) PageColumns = atoi(val); if ((val = cupsGetOption("cpi", num_options, options)) != NULL) CharsPerInch = atof(val); if ((val = cupsGetOption("lpi", num_options, options)) != NULL) LinesPerInch = atof(val); if (PrettyPrint) PageTop -= 216.0f / LinesPerInch; Copies = atoi(argv[4]); WriteProlog(argv[3], argv[2], getenv("CLASSIFICATION"), cupsGetOption("page-label", num_options, options), ppd); /* * Read text from the specified source and print it... */ lastch = 0; column = 0; line = 0; page_column = 0; attr = 0; keyptr = keyword; keycol = 0; ccomment = 0; cstring = 0; while ((ch = getutf8(fp)) >= 0) { /* * Control codes: * * BS Backspace (0x08) * HT Horizontal tab; next 8th column (0x09) * LF Line feed; forward full line (0x0a) * VT Vertical tab; reverse full line (0x0b) * FF Form feed (0x0c) * CR Carriage return (0x0d) * ESC 7 Reverse full line (0x1b 0x37) * ESC 8 Reverse half line (0x1b 0x38) * ESC 9 Forward half line (0x1b 0x39) */ switch (ch) { case 0x08 : /* BS - backspace for boldface & underline */ if (column > 0) column --; keyptr = keyword; keycol = column; break; case 0x09 : /* HT - tab to next 8th column */ if (PrettyPrint && keyptr > keyword) { *keyptr = '\0'; keyptr = keyword; if (bsearch(&keyptr, Keywords, NumKeywords, sizeof(char *), compare_keywords)) { /* * Put keywords in boldface... */ i = page_column * (ColumnWidth + ColumnGutter); while (keycol < column) { Page[line][keycol + i].attr |= ATTR_BOLD; keycol ++; } } } column = (column + 8) & ~7; if (column >= ColumnWidth && WrapLines) { /* Wrap text to margins */ line ++; column = 0; if (line >= SizeLines) { page_column ++; line = 0; if (page_column >= PageColumns) { WritePage(); page_column = 0; } } } keycol = column; attr &= ~ATTR_BOLD; break; case 0x0d : /* CR */ #ifndef __APPLE__ /* * All but MacOS/Darwin treat CR as was intended by ANSI * folks, namely to move to column 0/1. Some programs still * use this to do boldfacing and underlining... */ column = 0; break; #else /* * MacOS/Darwin still need to treat CR as a line ending. */ { int nextch; if ((nextch = getc(fp)) != 0x0a) ungetc(nextch, fp); else ch = nextch; } #endif /* !__APPLE__ */ case 0x0a : /* LF - output current line */ if (PrettyPrint && keyptr > keyword) { *keyptr = '\0'; keyptr = keyword; if (bsearch(&keyptr, Keywords, NumKeywords, sizeof(char *), compare_keywords)) { /* * Put keywords in boldface... */ i = page_column * (ColumnWidth + ColumnGutter); while (keycol < column) { Page[line][keycol + i].attr |= ATTR_BOLD; keycol ++; } } } line ++; column = 0; keycol = 0; if (!ccomment && !cstring) attr &= ~(ATTR_ITALIC | ATTR_BOLD | ATTR_RED | ATTR_GREEN | ATTR_BLUE); if (line >= SizeLines) { page_column ++; line = 0; if (page_column >= PageColumns) { WritePage(); page_column = 0; } } break; case 0x0b : /* VT - move up 1 line */ if (line > 0) line --; keyptr = keyword; keycol = column; if (!ccomment && !cstring) attr &= ~(ATTR_ITALIC | ATTR_BOLD | ATTR_RED | ATTR_GREEN | ATTR_BLUE); break; case 0x0c : /* FF - eject current page... */ if (PrettyPrint && keyptr > keyword) { *keyptr = '\0'; keyptr = keyword; if (bsearch(&keyptr, Keywords, NumKeywords, sizeof(char *), compare_keywords)) { /* * Put keywords in boldface... */ i = page_column * (ColumnWidth + ColumnGutter); while (keycol < column) { Page[line][keycol + i].attr |= ATTR_BOLD; keycol ++; } } } page_column ++; column = 0; keycol = 0; line = 0; if (!ccomment && !cstring) attr &= ~(ATTR_ITALIC | ATTR_BOLD | ATTR_RED | ATTR_GREEN | ATTR_BLUE); if (page_column >= PageColumns) { WritePage(); page_column = 0; } break; case 0x1b : /* Escape sequence */ ch = getutf8(fp); if (ch == '7') { /* * ESC 7 Reverse full line (0x1b 0x37) */ if (line > 0) line --; } else if (ch == '8') { /* * ESC 8 Reverse half line (0x1b 0x38) */ if ((attr & ATTR_RAISED) && line > 0) { attr &= ~ATTR_RAISED; line --; } else if (attr & ATTR_LOWERED) attr &= ~ATTR_LOWERED; else attr |= ATTR_RAISED; } else if (ch == '9') { /* * ESC 9 Forward half line (0x1b 0x39) */ if ((attr & ATTR_LOWERED) && line < (SizeLines - 1)) { attr &= ~ATTR_LOWERED; line ++; } else if (attr & ATTR_RAISED) attr &= ~ATTR_RAISED; else attr |= ATTR_LOWERED; } break; default : /* All others... */ if (ch < ' ') break; /* Ignore other control chars */ if (PrettyPrint > PRETTY_PLAIN) { /* * Do highlighting of C/C++ keywords, preprocessor commands, * and comments... */ if (ch == ' ' && (attr & ATTR_BOLD)) { /* * Stop bolding preprocessor command... */ attr &= ~ATTR_BOLD; } else if (!(isalnum(ch & 255) || ch == '_') && keyptr > keyword) { /* * Look for a keyword... */ *keyptr = '\0'; keyptr = keyword; if (!(attr & ATTR_ITALIC) && bsearch(&keyptr, Keywords, NumKeywords, sizeof(char *), compare_keywords)) { /* * Put keywords in boldface... */ i = page_column * (ColumnWidth + ColumnGutter); while (keycol < column) { Page[line][keycol + i].attr |= ATTR_BOLD; keycol ++; } } } else if ((isalnum(ch & 255) || ch == '_') && !ccomment && !cstring) { /* * Add characters to the current keyword (if they'll fit). */ if (keyptr == keyword) keycol = column; if (keyptr < (keyword + sizeof(keyword) - 1)) *keyptr++ = ch; } else if (ch == '\"' && lastch != '\\' && !ccomment && !cstring) { /* * Start a C string constant... */ cstring = -1; attr = ATTR_BLUE; } else if (ch == '*' && lastch == '/' && !cstring && PrettyPrint != PRETTY_SHELL) { /* * Start a C-style comment... */ ccomment = 1; attr = ATTR_ITALIC | ATTR_GREEN; } else if (ch == '/' && lastch == '/' && !cstring && PrettyPrint == PRETTY_CODE) { /* * Start a C++-style comment... */ attr = ATTR_ITALIC | ATTR_GREEN; } else if (ch == '#' && !cstring && PrettyPrint != PRETTY_CODE) { /* * Start a shell-style comment... */ attr = ATTR_ITALIC | ATTR_GREEN; } else if (ch == '#' && column == 0 && !ccomment && !cstring && PrettyPrint == PRETTY_CODE) { /* * Start a preprocessor command... */ attr = ATTR_BOLD | ATTR_RED; } } if (column >= ColumnWidth && WrapLines) { /* Wrap text to margins */ column = 0; line ++; if (line >= SizeLines) { page_column ++; line = 0; if (page_column >= PageColumns) { WritePage(); page_column = 0; } } } /* * Add text to the current column & line... */ if (column < ColumnWidth) { i = column + page_column * (ColumnWidth + ColumnGutter); if (PrettyPrint) Page[line][i].attr = attr; else if (ch == ' ' && Page[line][i].ch) ch = Page[line][i].ch; else if (ch == Page[line][i].ch) Page[line][i].attr |= ATTR_BOLD; else if (Page[line][i].ch == '_') Page[line][i].attr |= ATTR_UNDERLINE; else if (ch == '_') { Page[line][i].attr |= ATTR_UNDERLINE; if (Page[line][i].ch) ch = Page[line][i].ch; } else Page[line][i].attr = attr; Page[line][i].ch = ch; } if (PrettyPrint) { if ((ch == '{' || ch == '}') && !ccomment && !cstring && column < ColumnWidth) { /* * Highlight curley braces... */ Page[line][column].attr |= ATTR_BOLD; } else if ((ch == '/' || ch == '*') && lastch == '/' && column < ColumnWidth && PrettyPrint != PRETTY_SHELL) { /* * Highlight first comment character... */ Page[line][column - 1].attr = attr; } else if (ch == '\"' && lastch != '\\' && !ccomment && cstring > 0) { /* * End a C string constant... */ cstring = 0; attr &= ~ATTR_BLUE; } else if (ch == '/' && lastch == '*' && ccomment) { /* * End a C-style comment... */ ccomment = 0; attr &= ~(ATTR_ITALIC | ATTR_GREEN); } if (cstring < 0) cstring = 1; } column ++; break; } /* * Save this character for the next cycle. */ lastch = ch; } /* * Write any remaining page data... */ if (line > 0 || page_column > 0 || column > 0) WritePage(); /* * Write the epilog and return... */ WriteEpilogue(); if (ppd != NULL) ppdClose(ppd); return (0); }
/** * Main entry point for the program. * * @param argc The number of command line options passed to the program. * @param argv An array of strings where each string represents a command line * argument. * @return An integer where 0 represents successful termination, any other * value represents an error code. */ int main(int argc, char *argv[]) { // Make sure status messages are not buffered setbuf(stderr, NULL); if (argc < 6 || argc > 7) { fprintf(stderr, "ERROR: Usage: %s job-id user title copies options [file]\n", argv[0]); return 1; } fprintf(stderr, "DEBUG: Start debug output - passthroughfilter\n"); // Arguments debug output: fprintf(stderr, "DEBUG: "); for (int i=0;i<argc;i++) { // Don't print the option arg - these are parsed and output later if (i != 5) { fprintf(stderr, "%s ", argv[i]); } } fprintf(stderr, "\n"); // Env. variable debug output printEnv("CHARSET"); printEnv("CLASS"); printEnv("CONTENT_TYPE"); printEnv("CUPS_CACHEDIR"); printEnv("CUPS_DATADIR"); printEnv("CUPS_FILETYPE"); printEnv("CUPS_SERVERROOT"); printEnv("DEVICE_URI"); printEnv("FINAL_CONTENT_TYPE"); printEnv("LANG"); printEnv("PATH"); printEnv("PPD"); printEnv("PRINTER"); printEnv("RIP_CACHE"); printEnv("SOFTWARE"); printEnv("TZ"); printEnv("USER"); cups_option_t *options = NULL; int num_options = cupsParseOptions(argv[5], 0, &options); for (int i=0;i<num_options;i++) { fprintf(stderr, "DEBUG: %s: %s\n", options[i].name, options[i].value); } // FIXME: Register a signal handler to support cancelling of jobs cups_file_t *fp; if (argc == 6) { fp = cupsFileStdin(); } else { // Try to open the print file... if ((fp = cupsFileOpen(argv[6], "r")) == NULL) { perror("ERROR: unable to open print file - "); return 1; } } char buffer[8192]; int bytes; while ((bytes = cupsFileRead(fp, buffer, sizeof(buffer))) > 0) { fwrite(buffer, 1, bytes, stdout); } fprintf(stderr, "DEBUG: End debug output - passthroughfilter\n"); return 0; }
int /* O - Exit status */ imagetops_main(int argc, /* I - Number of command-line arguments */ char *argv[]) /* I - Command-line arguments */ { cups_image_t *img; /* Image to print */ float xprint, /* Printable area */ yprint, xinches, /* Total size in inches */ yinches; float xsize, /* Total size in points */ ysize, xsize2, ysize2; float aspect; /* Aspect ratio */ int xpages, /* # x pages */ ypages, /* # y pages */ xpage, /* Current x page */ ypage, /* Current y page */ page; /* Current page number */ int xc0, yc0, /* Corners of the page in image coords */ xc1, yc1; cups_ib_t *row; /* Current row */ int y; /* Current Y coordinate in image */ int colorspace; /* Output colorspace */ int out_offset, /* Offset into output buffer */ out_length; /* Length of output buffer */ ppd_file_t *ppd; /* PPD file */ ppd_choice_t *choice; /* PPD option choice */ int num_options; /* Number of print options */ cups_option_t *options; /* Print options */ const char *val; /* Option value */ int slowcollate; /* Collate copies the slow way */ float g; /* Gamma correction value */ float b; /* Brightness factor */ float zoom; /* Zoom facter */ int xppi, yppi; /* Pixels-per-inch */ int hue, sat; /* Hue and saturation adjustment */ int realcopies, /* Real copies being printed */ emit_jcl; /* Emit JCL? */ float left, top; /* Left and top of image */ char filename[1024]; /* Name of file to print */ time_t curtime; /* Current time */ struct tm *curtm; /* Current date */ char curdate[255]; /* Current date string */ int psFileMode = 0; //0:CREATE New ; 1: Append int outColorDevice = 1; //0 : monochrome print , 1:color print int count = 0,numFiles=1; int defout,outfd; /* * Make sure status messages are not buffered... */ int ii=0; for(;ii<argc;ii++) LOGI("imagetops : argv:%s",argv[ii]); fflush(stdout); Copies = 1; setbuf(stderr, NULL); /* * Ignore broken pipe signals... */ signal(SIGPIPE, SIG_IGN); /* * Process command-line options and write the prolog... */ zoom = 0.0; xppi = 0; yppi = 0; hue = 0; sat = 100; g = 1.0; b = 1.0; Copies = atoi(argv[4]); options = NULL; num_options = cupsParseOptions(argv[5], 0, &options); ppdFilePath = argv[6]; ContentType= argv[7]; psFilePath = argv[8]; outColorDevice = atoi(argv[9]); numFiles = argc - 10; LOGI("imagetops : numFiles=%d",numFiles); ppd = SetCommonOptions(num_options, options, 0); if ((val = cupsGetOption("multiple-document-handling", num_options, options)) != NULL) { /* * This IPP attribute is unnecessarily complicated... * * single-document, separate-documents-collated-copies, and * single-document-new-sheet all require collated copies. * * separate-documents-uncollated-copies allows for uncollated copies. */ Collate = _cups_strcasecmp(val, "separate-documents-uncollated-copies") != 0; } if ((val = cupsGetOption("Collate", num_options, options)) != NULL && _cups_strcasecmp(val, "True") == 0) Collate = 1; if ((val = cupsGetOption("gamma", num_options, options)) != NULL) { /* * Get gamma value from 1 to 10000... */ g = atoi(val) * 0.001f; if (g < 0.001f) g = 0.001f; else if (g > 10.0f) g = 10.0f; } if ((val = cupsGetOption("brightness", num_options, options)) != NULL) { /* * Get brightness value from 10 to 1000. */ b = atoi(val) * 0.01f; if (b < 0.1f) b = 0.1f; else if (b > 10.0f) b = 10.0f; } if ((val = cupsGetOption("scaling", num_options, options)) != NULL) zoom = atoi(val) * 0.01; else if ((val = cupsGetOption("fitplot", num_options, options)) != NULL && !_cups_strcasecmp(val, "true")) zoom = 1.0; else if ((val = cupsGetOption("fit-to-page", num_options, options)) != NULL && !_cups_strcasecmp(val, "true")) zoom = 1.0; if ((val = cupsGetOption("ppi", num_options, options)) != NULL) if (sscanf(val, "%dx%d", &xppi, &yppi) < 2) yppi = xppi; if ((val = cupsGetOption("position", num_options, options)) != NULL) { if (_cups_strcasecmp(val, "center") == 0) { XPosition = 0; YPosition = 0; } else if (_cups_strcasecmp(val, "top") == 0) { XPosition = 0; YPosition = 1; } else if (_cups_strcasecmp(val, "left") == 0) { XPosition = -1; YPosition = 0; } else if (_cups_strcasecmp(val, "right") == 0) { XPosition = 1; YPosition = 0; } else if (_cups_strcasecmp(val, "top-left") == 0) { XPosition = -1; YPosition = 1; } else if (_cups_strcasecmp(val, "top-right") == 0) { XPosition = 1; YPosition = 1; } else if (_cups_strcasecmp(val, "bottom") == 0) { XPosition = 0; YPosition = -1; } else if (_cups_strcasecmp(val, "bottom-left") == 0) { XPosition = -1; YPosition = -1; } else if (_cups_strcasecmp(val, "bottom-right") == 0) { XPosition = 1; YPosition = -1; } } if ((val = cupsGetOption("saturation", num_options, options)) != NULL) sat = atoi(val); if ((val = cupsGetOption("hue", num_options, options)) != NULL) hue = atoi(val); if ((choice = ppdFindMarkedChoice(ppd, "MirrorPrint")) != NULL) { val = choice->choice; choice->marked = 0; } else val = cupsGetOption("mirror", num_options, options); if (val && (!_cups_strcasecmp(val, "true") || !_cups_strcasecmp(val, "on") || !_cups_strcasecmp(val, "yes"))) Flip = 1; if ((val = cupsGetOption("emit-jcl", num_options, options)) != NULL && (!_cups_strcasecmp(val, "false") || !_cups_strcasecmp(val, "off") || !_cups_strcasecmp(val, "no") || !strcmp(val, "0"))) emit_jcl = 0; else emit_jcl = 1; LOGI("imagetops/Copies=%d , Collate=%d, gamma=%f, brightness=%f, zoom=%f",Copies,Collate,g,b,zoom); LOGI("imagetops/xppi=%d,yppi=%d,XPosition=%d,YPosition=%d,sat=%d,hue=%d,flip=%d,emit_jcl=%d",xppi,yppi,XPosition,YPosition,sat,hue,Flip,emit_jcl); /* * Open the input image to print... */ if(outColorDevice == 1) //added @ grv colorspace = CUPS_IMAGE_RGB_CMYK; else colorspace = CUPS_IMAGE_WHITE; LOGI("imagetops/ colorspace = %d",colorspace); for(count=0;count<numFiles;count++){ Copies = atoi(argv[4]); //do everything for both image files strlcpy(filename, argv[(10 + count)], sizeof(filename)); LOGI("imagetops : count=%d , filename=%s",count,filename); img = cupsImageOpen(filename, colorspace, CUPS_IMAGE_WHITE, sat, hue, NULL); if (img == NULL) { LOGI("imagetops:error:The print file could not be opened."); _cupsLangPrintFilter(stderr, "ERROR", _("The print file could not be opened.")); ppdClose(ppd); return (1); } colorspace = cupsImageGetColorSpace(img); LOGI("imagetops: cupsImageGetColorSpace finished : colorspace :%d",colorspace); /* * Scale as necessary... */ if (zoom == 0.0 && xppi == 0) { xppi = cupsImageGetXPPI(img); yppi = cupsImageGetYPPI(img); } LOGI("imagetops:xppi=%d",xppi); LOGI("imagetops:yppi=%d",yppi); if (yppi == 0) yppi = xppi; fprintf(stderr, "DEBUG: Before scaling: xppi=%d, yppi=%d, zoom=%.2f\n", xppi, yppi, zoom); if (xppi > 0) { /* * Scale the image as neccesary to match the desired pixels-per-inch. */ if (Orientation & 1) { xprint = (PageTop - PageBottom) / 72.0; yprint = (PageRight - PageLeft) / 72.0; } else { xprint = (PageRight - PageLeft) / 72.0; yprint = (PageTop - PageBottom) / 72.0; } fprintf(stderr, "DEBUG: Before scaling: xprint=%.1f, yprint=%.1f\n", xprint, yprint); xinches = (float)cupsImageGetWidth(img) / (float)xppi; yinches = (float)cupsImageGetHeight(img) / (float)yppi; fprintf(stderr, "DEBUG: Image size is %.1f x %.1f inches...\n", xinches, yinches); if ((val = cupsGetOption("natural-scaling", num_options, options)) != NULL) { xinches = xinches * atoi(val) / 100; yinches = yinches * atoi(val) / 100; } if (cupsGetOption("orientation-requested", num_options, options) == NULL && cupsGetOption("landscape", num_options, options) == NULL) { /* * Rotate the image if it will fit landscape but not portrait... */ fputs("DEBUG: Auto orientation...\n", stderr); LOGI("imagetops.c : Auto orientation..."); if ((xinches > xprint || yinches > yprint) && xinches <= yprint && yinches <= xprint) { /* * Rotate the image as needed... */ fputs("DEBUG: Using landscape orientation...\n", stderr); LOGI("imagetops.c : Auto orientation : Using landscape orientation"); Orientation = (Orientation + 1) & 3; xsize = yprint; yprint = xprint; xprint = xsize; } } }else{ /* * Scale percentage of page size... */ xprint = (PageRight - PageLeft) / 72.0; yprint = (PageTop - PageBottom) / 72.0; aspect = (float)cupsImageGetYPPI(img) / (float)cupsImageGetXPPI(img); fprintf(stderr, "DEBUG: Before scaling: xprint=%.1f, yprint=%.1f\n", xprint, yprint); fprintf(stderr, "DEBUG: cupsImageGetXPPI(img) = %d, cupsImageGetYPPI(img) = %d, aspect = %f\n", cupsImageGetXPPI(img), cupsImageGetYPPI(img), aspect); xsize = xprint * zoom; ysize = xsize * cupsImageGetHeight(img) / cupsImageGetWidth(img) / aspect; if (ysize > (yprint * zoom)) { ysize = yprint * zoom; xsize = ysize * cupsImageGetWidth(img) * aspect / cupsImageGetHeight(img); } xsize2 = yprint * zoom; ysize2 = xsize2 * cupsImageGetHeight(img) / cupsImageGetWidth(img) / aspect; if (ysize2 > (xprint * zoom)) { ysize2 = xprint * zoom; xsize2 = ysize2 * cupsImageGetWidth(img) * aspect / cupsImageGetHeight(img); } fprintf(stderr, "DEBUG: Portrait size is %.2f x %.2f inches\n", xsize, ysize); fprintf(stderr, "DEBUG: Landscape size is %.2f x %.2f inches\n", xsize2, ysize2); if (cupsGetOption("orientation-requested", num_options, options) == NULL && cupsGetOption("landscape", num_options, options) == NULL) { /* * Choose the rotation with the largest area, but prefer * portrait if they are equal... */ fputs("DEBUG: Auto orientation...\n", stderr); if ((xsize * ysize) < (xsize2 * xsize2)) { /* * Do landscape orientation... */ fputs("DEBUG: Using landscape orientation...\n", stderr); Orientation = 1; xinches = xsize2; yinches = ysize2; xprint = (PageTop - PageBottom) / 72.0; yprint = (PageRight - PageLeft) / 72.0; } else { /* * Do portrait orientation... */ fputs("DEBUG: Using portrait orientation...\n", stderr); Orientation = 0; xinches = xsize; yinches = ysize; } } else if (Orientation & 1) { fputs("DEBUG: Using landscape orientation...\n", stderr); xinches = xsize2; yinches = ysize2; xprint = (PageTop - PageBottom) / 72.0; yprint = (PageRight - PageLeft) / 72.0; } else { fputs("DEBUG: Using portrait orientation...\n", stderr); xinches = xsize; yinches = ysize; xprint = (PageRight - PageLeft) / 72.0; yprint = (PageTop - PageBottom) / 72.0; } } /* * Compute the number of pages to print and the size of the image on each * page... */ xpages = ceil(xinches / xprint); ypages = ceil(yinches / yprint); xprint = xinches / xpages; yprint = yinches / ypages; fprintf(stderr, "DEBUG: xpages = %dx%.2fin, ypages = %dx%.2fin\n",xpages, xprint, ypages, yprint); /* * Update the page size for custom sizes... */ if ((choice = ppdFindMarkedChoice(ppd, "PageSize")) != NULL && _cups_strcasecmp(choice->choice, "Custom") == 0) { float width, /* New width in points */ length; /* New length in points */ char s[255]; /* New custom page size... */ /* * Use the correct width and length for the current orientation... */ if (Orientation & 1) { width = yprint * 72.0; length = xprint * 72.0; } else { width = xprint * 72.0; length = yprint * 72.0; } /* * Add margins to page size... */ width += ppd->custom_margins[0] + ppd->custom_margins[2]; length += ppd->custom_margins[1] + ppd->custom_margins[3]; /* * Enforce minimums... */ if (width < ppd->custom_min[0]) width = ppd->custom_min[0]; if (length < ppd->custom_min[1]) length = ppd->custom_min[1]; fprintf(stderr, "DEBUG: Updated custom page size to %.2f x %.2f inches...\n",width / 72.0, length / 72.0); /* * Set the new custom size... */ sprintf(s, "Custom.%.0fx%.0f", width, length); ppdMarkOption(ppd, "PageSize", s); /* * Update page variables... */ PageWidth = width; PageLength = length; PageLeft = ppd->custom_margins[0]; PageRight = width - ppd->custom_margins[2]; PageBottom = ppd->custom_margins[1]; PageTop = length - ppd->custom_margins[3]; } /* * See if we need to collate, and if so how we need to do it... */ if (xpages == 1 && ypages == 1) Collate = 0; slowcollate = Collate && ppdFindOption(ppd, "Collate") == NULL; if (Copies > 1 && !slowcollate) { realcopies = Copies; Copies = 1; } else realcopies = 1; /* * Write any "exit server" options that have been selected... */ //Changes to create ps file -- start if(count == 0){//single side print defout = dup(1); outfd = open(psFilePath,O_RDWR | O_CREAT,S_IRWXU |S_IRWXG | S_IRWXO); dup2(outfd,1); } //Changes to create ps file -- end ppdEmit(ppd, stdout, PPD_ORDER_EXIT); /* * Write any JCL commands that are needed to print PostScript code... */ if (emit_jcl) ppdEmitJCL(ppd, stdout, atoi(argv[1]), argv[2], argv[3]); /* * Start sending the document with any commands needed... */ curtime = time(NULL); curtm = localtime(&curtime); ////////////////// if(count == 0){ puts("%!PS-Adobe-3.0"); printf("%%%%BoundingBox: %.0f %.0f %.0f %.0f\n", PageLeft, PageBottom,PageRight, PageTop); printf("%%%%LanguageLevel: %d\n", LanguageLevel); printf("%%%%Pages: %d\n", xpages * ypages * Copies * numFiles); puts("%%DocumentData: Clean7Bit"); puts("%%DocumentNeededResources: font Helvetica-Bold"); puts("%%Creator: imagetops/" CUPS_SVERSION); strftime(curdate, sizeof(curdate), "%c", curtm); printf("%%%%CreationDate: %s\n", curdate); WriteTextComment("Title", argv[3]); WriteTextComment("For", argv[2]); if (Orientation & 1) puts("%%Orientation: Landscape"); else puts("%%Orientation: Portrait"); puts("%%EndComments"); puts("%%BeginProlog"); if (ppd != NULL && ppd->patches != NULL) puts(ppd->patches); ppdEmit(ppd, stdout, PPD_ORDER_DOCUMENT); ppdEmit(ppd, stdout, PPD_ORDER_ANY); ppdEmit(ppd, stdout, PPD_ORDER_PROLOG); if (g != 1.0 || b != 1.0) printf("{ neg 1 add dup 0 lt { pop 1 } { %.3f exp neg 1 add } " "ifelse %.3f mul } bind settransfer\n", g, b); WriteCommon(); switch (Orientation) { case 0 : WriteLabelProlog(cupsGetOption("page-label", num_options, options), PageBottom, PageTop, PageWidth); break; case 1 : WriteLabelProlog(cupsGetOption("page-label", num_options, options), PageLeft, PageRight, PageLength); break; case 2 : WriteLabelProlog(cupsGetOption("page-label", num_options, options), PageLength - PageTop, PageLength - PageBottom, PageWidth); break; case 3 : WriteLabelProlog(cupsGetOption("page-label", num_options, options), PageWidth - PageRight, PageWidth - PageLeft,PageLength); break; } if (realcopies > 1) { if (ppd == NULL || ppd->language_level == 1) printf("/#copies %d def\n", realcopies); else printf("<</NumCopies %d>>setpagedevice\n", realcopies); } puts("%%EndProlog"); } /* * Output the pages... */ row = malloc(cupsImageGetWidth(img) * abs(colorspace) + 3); fprintf(stderr, "DEBUG: XPosition=%d, YPosition=%d, Orientation=%d\n",XPosition, YPosition, Orientation); fprintf(stderr, "DEBUG: xprint=%.0f, yprint=%.0f\n", xprint, yprint); fprintf(stderr, "DEBUG: PageLeft=%.0f, PageRight=%.0f, PageWidth=%.0f\n",PageLeft, PageRight, PageWidth); fprintf(stderr, "DEBUG: PageBottom=%.0f, PageTop=%.0f, PageLength=%.0f\n",PageBottom, PageTop, PageLength); switch (Orientation) { default : switch (XPosition) { case -1 : left = PageLeft; break; default : left = (PageRight + PageLeft - xprint * 72) / 2; break; case 1 : left = PageRight - xprint * 72; break; } switch (YPosition) { case -1 : top = PageBottom + yprint * 72; break; default : top = (PageTop + PageBottom + yprint * 72) / 2; break; case 1 : top = PageTop; break; } break; case 1 : switch (XPosition) { case -1 : left = PageBottom; break; default : left = (PageTop + PageBottom - xprint * 72) / 2; break; case 1 : left = PageTop - xprint * 72; break; } switch (YPosition) { case -1 : top = PageLeft + yprint * 72; break; default : top = (PageRight + PageLeft + yprint * 72) / 2; break; case 1 : top = PageRight; break; } break; case 2 : switch (XPosition) { case 1 : left = PageLeft; break; default : left = (PageRight + PageLeft - xprint * 72) / 2; break; case -1 : left = PageRight - xprint * 72; break; } switch (YPosition) { case 1 : top = PageBottom + yprint * 72; break; default : top = (PageTop + PageBottom + yprint * 72) / 2; break; case -1 : top = PageTop; break; } break; case 3 : switch (XPosition) { case 1 : left = PageBottom; break; default : left = (PageTop + PageBottom - xprint * 72) / 2; break; case -1 : left = PageTop - xprint * 72; break; } switch (YPosition) { case 1 : top = PageLeft + yprint * 72; break; default : top = (PageRight + PageLeft + yprint * 72) / 2; break; case -1 : top = PageRight; break; } break; } fprintf(stderr, "DEBUG: left=%.2f, top=%.2f\n", left, top); for (page = 1; Copies > 0; Copies --) for (xpage = 0; xpage < xpages; xpage ++) for (ypage = 0; ypage < ypages; ypage ++, page ++) { if (ppd && ppd->num_filters == 0) fprintf(stderr, "PAGE: %d %d\n", page, realcopies); _cupsLangPrintFilter(stderr, "INFO", _("Printing page %d."), page); printf("%%%%Page: %d %d\n", (page * (count+1)), (page*(count+1))); //TEST_TODO if(count>=1){ puts("%%BeginPageSetup"); if (Orientation & 1) puts("%%PageOrientation: Landscape"); else puts("%%PageOrientation: Portrait"); puts("%%EndPageSetup"); } ppdEmit(ppd, stdout, PPD_ORDER_PAGE); puts("gsave"); if (Flip) printf("%.0f 0 translate -1 1 scale\n", PageWidth); switch (Orientation) { case 1 : /* Landscape */ printf("%.0f 0 translate 90 rotate\n", PageWidth); break; case 2 : /* Reverse Portrait */ printf("%.0f %.0f translate 180 rotate\n", PageWidth, PageLength); break; case 3 : /* Reverse Landscape */ printf("0 %.0f translate -90 rotate\n", PageLength); break; } puts("gsave"); xc0 = cupsImageGetWidth(img) * xpage / xpages; xc1 = cupsImageGetWidth(img) * (xpage + 1) / xpages - 1; yc0 = cupsImageGetHeight(img) * ypage / ypages; yc1 = cupsImageGetHeight(img) * (ypage + 1) / ypages - 1; printf("%.1f %.1f translate\n", left, top); printf("%.3f %.3f scale\n\n",xprint * 72.0 / (xc1 - xc0 + 1),yprint * 72.0 / (yc1 - yc0 + 1)); if (LanguageLevel == 1) { printf("/picture %d string def\n", (xc1 - xc0 + 1) * abs(colorspace)); printf("%d %d 8[1 0 0 -1 0 1]", (xc1 - xc0 + 1), (yc1 - yc0 + 1)); if (colorspace == CUPS_IMAGE_WHITE) puts("{currentfile picture readhexstring pop} image"); else printf("{currentfile picture readhexstring pop} false %d colorimage\n",abs(colorspace)); for (y = yc0; y <= yc1; y ++) { cupsImageGetRow(img, xc0, y, xc1 - xc0 + 1, row); ps_hex(row, (xc1 - xc0 + 1) * abs(colorspace), y == yc1); } } else { switch (colorspace) { case CUPS_IMAGE_WHITE : puts("/DeviceGray setcolorspace"); break; case CUPS_IMAGE_RGB : puts("/DeviceRGB setcolorspace"); break; case CUPS_IMAGE_CMYK : puts("/DeviceCMYK setcolorspace"); break; } printf("<<" "/ImageType 1" "/Width %d" "/Height %d" "/BitsPerComponent 8", xc1 - xc0 + 1, yc1 - yc0 + 1); switch (colorspace) { case CUPS_IMAGE_WHITE : fputs("/Decode[0 1]", stdout); break; case CUPS_IMAGE_RGB : fputs("/Decode[0 1 0 1 0 1]", stdout); break; case CUPS_IMAGE_CMYK : fputs("/Decode[0 1 0 1 0 1 0 1]", stdout); break; } fputs("\n/DataSource currentfile/ASCII85Decode filter", stdout); if (((xc1 - xc0 + 1) / xprint) < 100.0) fputs("/Interpolate true", stdout); puts("/ImageMatrix[1 0 0 -1 0 1]>>image"); for (y = yc0, out_offset = 0; y <= yc1; y ++) { cupsImageGetRow(img, xc0, y, xc1 - xc0 + 1, row + out_offset); out_length = (xc1 - xc0 + 1) * abs(colorspace) + out_offset; out_offset = out_length & 3; ps_ascii85(row, out_length, y == yc1); if (out_offset > 0) memcpy(row, row + out_length - out_offset, out_offset); } } if(count==1){ puts("grestore"); WriteLabels(0); puts("grestore"); } puts("showpage"); puts("%%PageTrailer"); } } //end of big for loop puts("%%EOF"); /* * End the job with the appropriate JCL command or CTRL-D otherwise. */ if (emit_jcl) { if (ppd && ppd->jcl_end) ppdEmitJCLEnd(ppd, stdout); else putchar(0x04); } fflush(stdout); dup2(defout,1); close(outfd); close(defout); /* * Close files... */ LOGI("imagetops:Close files"); cupsImageClose(img); ppdClose(ppd); return (0); }
int /* O - Exit status */ main(int argc, /* I - Number of command-line arguments */ char *argv[]) /* I - Command-line arguments */ { http_t *http; /* Connection to destination */ cups_dest_t *dest = NULL; /* Destination */ cups_dinfo_t *dinfo; /* Destination info */ if (argc < 2) usage(NULL); if (!strcmp(argv[1], "--enum")) { int i; /* Looping var */ cups_ptype_t type = 0, /* Printer type filter */ mask = 0; /* Printer type mask */ for (i = 2; i < argc; i ++) { if (!strcmp(argv[i], "grayscale")) { type |= CUPS_PRINTER_BW; mask |= CUPS_PRINTER_BW; } else if (!strcmp(argv[i], "color")) { type |= CUPS_PRINTER_COLOR; mask |= CUPS_PRINTER_COLOR; } else if (!strcmp(argv[i], "duplex")) { type |= CUPS_PRINTER_DUPLEX; mask |= CUPS_PRINTER_DUPLEX; } else if (!strcmp(argv[i], "staple")) { type |= CUPS_PRINTER_STAPLE; mask |= CUPS_PRINTER_STAPLE; } else if (!strcmp(argv[i], "small")) { type |= CUPS_PRINTER_SMALL; mask |= CUPS_PRINTER_SMALL; } else if (!strcmp(argv[i], "medium")) { type |= CUPS_PRINTER_MEDIUM; mask |= CUPS_PRINTER_MEDIUM; } else if (!strcmp(argv[i], "large")) { type |= CUPS_PRINTER_LARGE; mask |= CUPS_PRINTER_LARGE; } else usage(argv[i]); } cupsEnumDests(CUPS_DEST_FLAGS_NONE, 5000, NULL, type, mask, enum_cb, NULL); return (0); } else if (!strncmp(argv[1], "ipp://", 6) || !strncmp(argv[1], "ipps://", 7)) dest = cupsGetDestWithURI(NULL, argv[1]); else dest = cupsGetNamedDest(CUPS_HTTP_DEFAULT, argv[1], NULL); if (!dest) { printf("testdest: Unable to get destination \"%s\": %s\n", argv[1], cupsLastErrorString()); return (1); } if ((http = cupsConnectDest(dest, CUPS_DEST_FLAGS_NONE, 30000, NULL, NULL, 0, NULL, NULL)) == NULL) { printf("testdest: Unable to connect to destination \"%s\": %s\n", argv[1], cupsLastErrorString()); return (1); } if ((dinfo = cupsCopyDestInfo(http, dest)) == NULL) { printf("testdest: Unable to get information for destination \"%s\": %s\n", argv[1], cupsLastErrorString()); return (1); } if (argc == 2 || (!strcmp(argv[2], "supported") && argc < 6)) { if (argc > 3) show_supported(http, dest, dinfo, argv[3], argv[4]); else if (argc > 2) show_supported(http, dest, dinfo, argv[3], NULL); else show_supported(http, dest, dinfo, NULL, NULL); } else if (!strcmp(argv[2], "conflicts") && argc > 3) { int i, /* Looping var */ num_options = 0;/* Number of options */ cups_option_t *options = NULL;/* Options */ for (i = 3; i < argc; i ++) num_options = cupsParseOptions(argv[i], num_options, &options); show_conflicts(http, dest, dinfo, num_options, options); } else if (!strcmp(argv[2], "default") && argc == 4) { show_default(http, dest, dinfo, argv[3]); } else if (!strcmp(argv[2], "localize") && argc < 6) { if (argc > 3) localize(http, dest, dinfo, argv[3], argv[4]); else if (argc > 2) localize(http, dest, dinfo, argv[3], NULL); else localize(http, dest, dinfo, NULL, NULL); } else if (!strcmp(argv[2], "media")) { int i; /* Looping var */ const char *name = NULL; /* Media name, if any */ unsigned flags = CUPS_MEDIA_FLAGS_DEFAULT; /* Media selection flags */ for (i = 3; i < argc; i ++) { if (!strcmp(argv[i], "borderless")) flags = CUPS_MEDIA_FLAGS_BORDERLESS; else if (!strcmp(argv[i], "duplex")) flags = CUPS_MEDIA_FLAGS_DUPLEX; else if (!strcmp(argv[i], "exact")) flags = CUPS_MEDIA_FLAGS_EXACT; else if (!strcmp(argv[i], "ready")) flags = CUPS_MEDIA_FLAGS_READY; else if (name) usage(argv[i]); else name = argv[i]; } show_media(http, dest, dinfo, flags, name); } else if (!strcmp(argv[2], "print") && argc > 3) { int i, /* Looping var */ num_options = 0;/* Number of options */ cups_option_t *options = NULL;/* Options */ for (i = 4; i < argc; i ++) num_options = cupsParseOptions(argv[i], num_options, &options); print_file(http, dest, dinfo, argv[3], num_options, options); } else usage(argv[2]); return (0); }
int /* O - Exit status */ main(int argc, /* I - Number of command-line args */ char *argv[]) /* I - Command-line arguments */ { int i, /* Looping vars */ list_filters = 0; /* Just list the filters? */ const char *command, /* Command name */ *opt, /* Current option */ *printer; /* Printer name */ mime_type_t *printer_type, /* Printer MIME type */ *prefilter_type; /* Printer prefilter MIME type */ char *srctype, /* Source type */ *dsttype, /* Destination type */ super[MIME_MAX_SUPER], /* Super-type name */ type[MIME_MAX_TYPE]; /* Type name */ int compression; /* Compression of file */ int cost; /* Cost of filters */ mime_t *mime; /* MIME database */ char mimedir[1024]; /* MIME directory */ char *infile, /* File to filter */ *outfile; /* File to create */ char cupsfilesconf[1024]; /* cups-files.conf file */ const char *server_root; /* CUPS_SERVERROOT environment variable */ mime_type_t *src, /* Source type */ *dst; /* Destination type */ cups_array_t *filters; /* Filters for the file */ int num_options; /* Number of options */ cups_option_t *options; /* Options */ const char *ppdfile; /* PPD file */ const char *title, /* Title string */ *user; /* Username */ int all_filters, /* Use all filters */ removeppd, /* Remove PPD file */ removeinfile; /* Remove input file */ int status; /* Execution status */ /* * Setup defaults... */ if ((command = strrchr(argv[0], '/')) != NULL) command ++; else command = argv[0]; printer = !strcmp(command, "convert") ? "tofile" : "cupsfilter"; mime = NULL; srctype = NULL; compression = 0; dsttype = "application/pdf"; infile = NULL; outfile = NULL; num_options = 0; options = NULL; ppdfile = NULL; title = NULL; user = cupsUser(); all_filters = 0; removeppd = 0; removeinfile = 0; if ((server_root = getenv("CUPS_SERVERROOT")) == NULL) server_root = CUPS_SERVERROOT; snprintf(cupsfilesconf, sizeof(cupsfilesconf), "%s/cups-files.conf", server_root); /* * Process command-line arguments... */ _cupsSetLocale(argv); for (i = 1; i < argc; i ++) { if (argv[i][0] == '-') { if (!strcmp(argv[i], "--list-filters")) { list_filters = 1; } else if (!strcmp(argv[i], "--")) { i ++; if (i < argc && !infile) infile = argv[i]; else usage(NULL); } else { for (opt = argv[i] + 1; *opt; opt ++) { switch (*opt) { case 'a' : /* Specify option... */ i ++; if (i < argc) num_options = cupsParseOptions(argv[i], num_options, &options); else usage(opt); break; case 'c' : /* Specify cups-files.conf file location... */ i ++; if (i < argc) { if (!strcmp(command, "convert")) num_options = cupsAddOption("copies", argv[i], num_options, &options); else strlcpy(cupsfilesconf, argv[i], sizeof(cupsfilesconf)); } else usage(opt); break; case 'd' : /* Specify the real printer name */ i ++; if (i < argc) printer = argv[i]; else usage(opt); break; case 'D' : /* Delete input file after conversion */ removeinfile = 1; break; case 'e' : /* Use every filter from the PPD file */ all_filters = 1; break; case 'f' : /* Specify input file... */ i ++; if (i < argc && !infile) infile = argv[i]; else usage(opt); break; case 'i' : /* Specify source MIME type... */ i ++; if (i < argc) { if (sscanf(argv[i], "%15[^/]/%255s", super, type) != 2) usage(opt); srctype = argv[i]; } else usage(opt); break; case 'j' : /* Get job file or specify destination MIME type... */ if (strcmp(command, "convert")) { i ++; if (i < argc) { get_job_file(argv[i]); infile = TempFile; } else usage(opt); break; } case 'm' : /* Specify destination MIME type... */ i ++; if (i < argc) { if (sscanf(argv[i], "%15[^/]/%255s", super, type) != 2) usage(opt); dsttype = argv[i]; } else usage(opt); break; case 'n' : /* Specify number of copies... */ i ++; if (i < argc) num_options = cupsAddOption("copies", argv[i], num_options, &options); else usage(opt); break; case 'o' : /* Specify option(s) or output filename */ i ++; if (i < argc) { if (!strcmp(command, "convert")) { if (outfile) usage(NULL); else outfile = argv[i]; } else num_options = cupsParseOptions(argv[i], num_options, &options); } else usage(opt); break; case 'p' : /* Specify PPD file... */ case 'P' : /* Specify PPD file... */ i ++; if (i < argc) ppdfile = argv[i]; else usage(opt); break; case 't' : /* Specify title... */ case 'J' : /* Specify title... */ i ++; if (i < argc) title = argv[i]; else usage(opt); break; case 'u' : /* Delete PPD file after conversion */ removeppd = 1; break; case 'U' : /* Specify username... */ i ++; if (i < argc) user = argv[i]; else usage(opt); break; default : /* Something we don't understand... */ usage(opt); break; } } } } else if (!infile) { if (strcmp(command, "convert")) infile = argv[i]; else usage(NULL); } else { _cupsLangPuts(stderr, _("cupsfilter: Only one filename can be specified.")); usage(NULL); } } if (!infile && !srctype) usage(NULL); if (!title) { if (!infile) title = "(stdin)"; else if ((title = strrchr(infile, '/')) != NULL) title ++; else title = infile; } /* * Load the cups-files.conf file and create the MIME database... */ if (read_cups_files_conf(cupsfilesconf)) return (1); snprintf(mimedir, sizeof(mimedir), "%s/mime", DataDir); mime = mimeLoadTypes(NULL, mimedir); mime = mimeLoadTypes(mime, ServerRoot); mime = mimeLoadFilters(mime, mimedir, Path); mime = mimeLoadFilters(mime, ServerRoot, Path); if (!mime) { _cupsLangPrintf(stderr, _("%s: Unable to read MIME database from \"%s\" or " "\"%s\"."), command, mimedir, ServerRoot); return (1); } prefilter_type = NULL; if (all_filters) printer_type = add_printer_filters(command, mime, printer, ppdfile, &prefilter_type); else printer_type = mimeType(mime, "application", "vnd.cups-postscript"); /* * Get the source and destination types... */ if (srctype) { /* sscanf return value already checked above */ sscanf(srctype, "%15[^/]/%255s", super, type); if ((src = mimeType(mime, super, type)) == NULL) { _cupsLangPrintf(stderr, _("%s: Unknown source MIME type %s/%s."), command, super, type); return (1); } } else if ((src = mimeFileType(mime, infile, infile, &compression)) == NULL) { _cupsLangPrintf(stderr, _("%s: Unable to determine MIME type of \"%s\"."), command, infile); return (1); } /* sscanf return value already checked above */ sscanf(dsttype, "%15[^/]/%255s", super, type); if (!_cups_strcasecmp(super, "printer")) dst = printer_type; else if ((dst = mimeType(mime, super, type)) == NULL) { _cupsLangPrintf(stderr, _("%s: Unknown destination MIME type %s/%s."), command, super, type); return (1); } /* * Figure out how to filter the file... */ if (src == dst) { /* * Special case - no filtering needed... */ filters = cupsArrayNew(NULL, NULL); cupsArrayAdd(filters, &GZIPFilter); GZIPFilter.src = src; GZIPFilter.dst = dst; } else if ((filters = mimeFilter(mime, src, dst, &cost)) == NULL) { _cupsLangPrintf(stderr, _("%s: No filter to convert from %s/%s to %s/%s."), command, src->super, src->type, dst->super, dst->type); return (1); } else if (compression) cupsArrayInsert(filters, &GZIPFilter); if (prefilter_type) { /* * Add pre-filters... */ mime_filter_t *filter, /* Current filter */ *prefilter; /* Current pre-filter */ cups_array_t *prefilters = cupsArrayNew(NULL, NULL); /* New filters array */ for (filter = (mime_filter_t *)cupsArrayFirst(filters); filter; filter = (mime_filter_t *)cupsArrayNext(filters)) { if ((prefilter = mimeFilterLookup(mime, filter->src, prefilter_type)) != NULL) cupsArrayAdd(prefilters, prefilter); cupsArrayAdd(prefilters, filter); } cupsArrayDelete(filters); filters = prefilters; } if (list_filters) { /* * List filters... */ mime_filter_t *filter; /* Current filter */ for (filter = (mime_filter_t *)cupsArrayFirst(filters); filter; filter = (mime_filter_t *)cupsArrayNext(filters)) if (strcmp(filter->filter, "-")) _cupsLangPuts(stdout, filter->filter); status = 0; } else { /* * Run filters... */ status = exec_filters(src, filters, infile, outfile, ppdfile, printer, user, title, num_options, options); } /* * Remove files as needed, then exit... */ if (TempFile[0]) unlink(TempFile); if (removeppd && ppdfile) unlink(ppdfile); if (removeinfile && infile) unlink(infile); return (status); }
int /* O - Exit status */ main(int argc, /* I - Number of command-line arguments */ char *argv[]) /* I - Command-line arguments */ { int fd; /* File descriptor */ cups_raster_t *ras; /* Raster stream for printing */ cups_page_header2_t header; /* Page header from file */ unsigned y; /* Current line */ ppd_file_t *ppd; /* PPD file */ int num_options; /* Number of options */ cups_option_t *options; /* Options */ #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET) struct sigaction action; /* Actions for POSIX signals */ #endif /* HAVE_SIGACTION && !HAVE_SIGSET */ /* * Make sure status messages are not buffered... */ setbuf(stderr, NULL); /* * Check command-line... */ if (argc < 6 || argc > 7) { /* * We don't have the correct number of arguments; write an error message * and return. */ _cupsLangPrintFilter(stderr, "ERROR", _("%s job-id user title copies options [file]"), "rastertolabel"); return (1); } /* * Open the page stream... */ if (argc == 7) { if ((fd = open(argv[6], O_RDONLY)) == -1) { _cupsLangPrintError("ERROR", _("Unable to open raster file")); sleep(1); return (1); } } else fd = 0; ras = cupsRasterOpen(fd, CUPS_RASTER_READ); /* * Register a signal handler to eject the current page if the * job is cancelled. */ Canceled = 0; #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */ sigset(SIGTERM, CancelJob); #elif defined(HAVE_SIGACTION) memset(&action, 0, sizeof(action)); sigemptyset(&action.sa_mask); action.sa_handler = CancelJob; sigaction(SIGTERM, &action, NULL); #else signal(SIGTERM, CancelJob); #endif /* HAVE_SIGSET */ /* * Open the PPD file and apply options... */ num_options = cupsParseOptions(argv[5], 0, &options); ppd = ppdOpenFile(getenv("PPD")); if (!ppd) { ppd_status_t status; /* PPD error */ int linenum; /* Line number */ _cupsLangPrintFilter(stderr, "ERROR", _("The PPD file could not be opened.")); status = ppdLastError(&linenum); fprintf(stderr, "DEBUG: %s on line %d.\n", ppdErrorString(status), linenum); return (1); } ppdMarkDefaults(ppd); cupsMarkOptions(ppd, num_options, options); /* * Initialize the print device... */ Setup(ppd); /* * Process pages as needed... */ Page = 0; while (cupsRasterReadHeader2(ras, &header)) { /* * Write a status message with the page number and number of copies. */ if (Canceled) break; Page ++; fprintf(stderr, "PAGE: %d 1\n", Page); _cupsLangPrintFilter(stderr, "INFO", _("Starting page %d."), Page); /* * Start the page... */ StartPage(ppd, &header); /* * Loop for each line on the page... */ for (y = 0; y < header.cupsHeight && !Canceled; y ++) { /* * Let the user know how far we have progressed... */ if (Canceled) break; if ((y & 15) == 0) { _cupsLangPrintFilter(stderr, "INFO", _("Printing page %d, %u%% complete."), Page, 100 * y / header.cupsHeight); fprintf(stderr, "ATTR: job-media-progress=%u\n", 100 * y / header.cupsHeight); } /* * Read a line of graphics... */ if (cupsRasterReadPixels(ras, Buffer, header.cupsBytesPerLine) < 1) break; /* * Write it to the printer... */ OutputLine(ppd, &header, y); } /* * Eject the page... */ _cupsLangPrintFilter(stderr, "INFO", _("Finished page %d."), Page); EndPage(ppd, &header); if (Canceled) break; } /* * Close the raster stream... */ cupsRasterClose(ras); if (fd != 0) close(fd); /* * Close the PPD file and free the options... */ ppdClose(ppd); cupsFreeOptions(num_options, options); /* * If no pages were printed, send an error message... */ if (Page == 0) { _cupsLangPrintFilter(stderr, "ERROR", _("No pages were found.")); return (1); } else return (0); }
void cupsEncodeOptions2( ipp_t *ipp, /* I - Request to add to */ int num_options, /* I - Number of options */ cups_option_t *options, /* I - Options */ ipp_tag_t group_tag) /* I - Group to encode */ { int i, j; /* Looping vars */ int count; /* Number of values */ char *s, /* Pointer into option value */ *val, /* Pointer to option value */ *copy, /* Copy of option value */ *sep, /* Option separator */ quote; /* Quote character */ ipp_attribute_t *attr; /* IPP attribute */ ipp_tag_t value_tag; /* IPP value tag */ cups_option_t *option; /* Current option */ ipp_t *collection; /* Collection value */ int num_cols; /* Number of collection values */ cups_option_t *cols; /* Collection values */ DEBUG_printf(("cupsEncodeOptions2(ipp=%p, num_options=%d, options=%p, " "group_tag=%x)", ipp, num_options, options, group_tag)); /* * Range check input... */ if (!ipp || num_options < 1 || !options) return; /* * Do special handling for the document-format/raw options... */ if (group_tag == IPP_TAG_OPERATION) { /* * Handle the document format stuff first... */ if ((val = (char *)cupsGetOption("document-format", num_options, options)) != NULL) ippAddString(ipp, IPP_TAG_OPERATION, IPP_TAG_MIMETYPE, "document-format", NULL, val); else if (cupsGetOption("raw", num_options, options)) ippAddString(ipp, IPP_TAG_OPERATION, IPP_TAG_MIMETYPE, "document-format", NULL, "application/vnd.cups-raw"); else ippAddString(ipp, IPP_TAG_OPERATION, IPP_TAG_MIMETYPE, "document-format", NULL, "application/octet-stream"); } /* * Then loop through the options... */ for (i = num_options, option = options; i > 0; i --, option ++) { _ipp_option_t *match; /* Matching attribute */ /* * Skip document format options that are handled above... */ if (!_cups_strcasecmp(option->name, "raw") || !_cups_strcasecmp(option->name, "document-format") || !option->name[0]) continue; /* * Figure out the proper value and group tags for this option... */ if ((match = _ippFindOption(option->name)) != NULL) { if (match->group_tag != group_tag) continue; value_tag = match->value_tag; } else { int namelen; /* Length of name */ namelen = (int)strlen(option->name); if (namelen < 9 || strcmp(option->name + namelen - 8, "-default")) { if (group_tag != IPP_TAG_JOB) continue; } else if (group_tag != IPP_TAG_PRINTER) continue; if (!_cups_strcasecmp(option->value, "true") || !_cups_strcasecmp(option->value, "false")) value_tag = IPP_TAG_BOOLEAN; else value_tag = IPP_TAG_NAME; } /* * Count the number of values... */ if (match && match->multivalue) { for (count = 1, sep = option->value, quote = 0; *sep; sep ++) { if (*sep == quote) quote = 0; else if (!quote && (*sep == '\'' || *sep == '\"')) { /* * Skip quoted option value... */ quote = *sep++; } else if (*sep == ',' && !quote) count ++; else if (*sep == '\\' && sep[1]) sep ++; } } else count = 1; DEBUG_printf(("2cupsEncodeOptions2: option=\"%s\", count=%d", option->name, count)); /* * Allocate memory for the attribute values... */ if ((attr = _ippAddAttr(ipp, count)) == NULL) { /* * Ran out of memory! */ DEBUG_puts("1cupsEncodeOptions2: Ran out of memory for attributes!"); return; } /* * Now figure out what type of value we have... */ attr->group_tag = group_tag; attr->value_tag = value_tag; /* * Copy the name over... */ attr->name = _cupsStrAlloc(option->name); if (count > 1) { /* * Make a copy of the value we can fiddle with... */ if ((copy = strdup(option->value)) == NULL) { /* * Ran out of memory! */ DEBUG_puts("1cupsEncodeOptions2: Ran out of memory for value copy!"); ippDeleteAttribute(ipp, attr); return; } val = copy; } else { /* * Since we have a single value, use the value directly... */ val = option->value; copy = NULL; } /* * Scan the value string for values... */ for (j = 0, sep = val; j < count; val = sep, j ++) { /* * Find the end of this value and mark it if needed... */ if (count > 1) { for (quote = 0; *sep; sep ++) { if (*sep == quote) { /* * Finish quoted value... */ quote = 0; } else if (!quote && (*sep == '\'' || *sep == '\"')) { /* * Handle quoted option value... */ quote = *sep; } else if (*sep == ',' && count > 1) break; else if (*sep == '\\' && sep[1]) { /* * Skip quoted character... */ sep ++; } } if (*sep == ',') *sep++ = '\0'; } /* * Copy the option value(s) over as needed by the type... */ switch (attr->value_tag) { case IPP_TAG_INTEGER : case IPP_TAG_ENUM : /* * Integer/enumeration value... */ attr->values[j].integer = strtol(val, &s, 10); DEBUG_printf(("2cupsEncodeOptions2: Added integer option value " "%d...", attr->values[j].integer)); break; case IPP_TAG_BOOLEAN : if (!_cups_strcasecmp(val, "true") || !_cups_strcasecmp(val, "on") || !_cups_strcasecmp(val, "yes")) { /* * Boolean value - true... */ attr->values[j].boolean = 1; DEBUG_puts("2cupsEncodeOptions2: Added boolean true value..."); } else { /* * Boolean value - false... */ attr->values[j].boolean = 0; DEBUG_puts("2cupsEncodeOptions2: Added boolean false value..."); } break; case IPP_TAG_RANGE : /* * Range... */ if (*val == '-') { attr->values[j].range.lower = 1; s = val; } else attr->values[j].range.lower = strtol(val, &s, 10); if (*s == '-') { if (s[1]) attr->values[j].range.upper = strtol(s + 1, NULL, 10); else attr->values[j].range.upper = 2147483647; } else attr->values[j].range.upper = attr->values[j].range.lower; DEBUG_printf(("2cupsEncodeOptions2: Added range option value " "%d-%d...", attr->values[j].range.lower, attr->values[j].range.upper)); break; case IPP_TAG_RESOLUTION : /* * Resolution... */ attr->values[j].resolution.xres = strtol(val, &s, 10); if (*s == 'x') attr->values[j].resolution.yres = strtol(s + 1, &s, 10); else attr->values[j].resolution.yres = attr->values[j].resolution.xres; if (!_cups_strcasecmp(s, "dpc")) attr->values[j].resolution.units = IPP_RES_PER_CM; else attr->values[j].resolution.units = IPP_RES_PER_INCH; DEBUG_printf(("2cupsEncodeOptions2: Added resolution option value " "%s...", val)); break; case IPP_TAG_STRING : /* * octet-string */ attr->values[j].unknown.length = (int)strlen(val); attr->values[j].unknown.data = strdup(val); DEBUG_printf(("2cupsEncodeOptions2: Added octet-string value " "\"%s\"...", (char *)attr->values[j].unknown.data)); break; case IPP_TAG_BEGIN_COLLECTION : /* * Collection value */ num_cols = cupsParseOptions(val, 0, &cols); if ((collection = ippNew()) == NULL) { cupsFreeOptions(num_cols, cols); if (copy) free(copy); ippDeleteAttribute(ipp, attr); return; } attr->values[j].collection = collection; cupsEncodeOptions2(collection, num_cols, cols, IPP_TAG_JOB); cupsFreeOptions(num_cols, cols); break; default : if ((attr->values[j].string.text = _cupsStrAlloc(val)) == NULL) { /* * Ran out of memory! */ DEBUG_puts("1cupsEncodeOptions2: Ran out of memory for string!"); if (copy) free(copy); ippDeleteAttribute(ipp, attr); return; } DEBUG_printf(("2cupsEncodeOptions2: Added string value \"%s\"...", val)); break; } } if (copy) free(copy); } }
int /* O - Exit status */ main(int argc, /* I - Number of command-line arguments (6 or 7) */ char *argv[]) /* I - Command-line arguments */ { const char *device_uri; /* Device URI */ char scheme[255], /* Scheme in URI */ hostname[1024], /* Hostname */ username[255], /* Username info */ resource[1024], /* Resource info (printer name) */ *options, /* Pointer to options */ *name, /* Name of option */ *value, /* Value of option */ sep, /* Separator character */ *filename, /* File to print */ title[256]; /* Title string */ int port; /* Port number */ char portname[256]; /* Port name (string) */ http_addrlist_t *addrlist; /* List of addresses for printer */ int snmp_enabled = 1; /* Is SNMP enabled? */ int snmp_fd; /* SNMP socket */ int fd; /* Print file */ int status; /* Status of LPD job */ int mode; /* Print mode */ int banner; /* Print banner page? */ int format; /* Print format */ int order; /* Order of control/data files */ int reserve; /* Reserve priviledged port? */ int sanitize_title; /* Sanitize title string? */ int manual_copies, /* Do manual copies? */ timeout, /* Timeout */ contimeout, /* Connection timeout */ copies; /* Number of copies */ ssize_t bytes = 0; /* Initial bytes read */ char buffer[16384]; /* Initial print buffer */ #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET) struct sigaction action; /* Actions for POSIX signals */ #endif /* HAVE_SIGACTION && !HAVE_SIGSET */ int num_jobopts; /* Number of job options */ cups_option_t *jobopts = NULL; /* Job options */ /* * Make sure status messages are not buffered... */ setbuf(stderr, NULL); /* * Ignore SIGPIPE and catch SIGTERM signals... */ #ifdef HAVE_SIGSET sigset(SIGPIPE, SIG_IGN); sigset(SIGTERM, sigterm_handler); #elif defined(HAVE_SIGACTION) memset(&action, 0, sizeof(action)); action.sa_handler = SIG_IGN; sigaction(SIGPIPE, &action, NULL); sigemptyset(&action.sa_mask); sigaddset(&action.sa_mask, SIGTERM); action.sa_handler = sigterm_handler; sigaction(SIGTERM, &action, NULL); #else signal(SIGPIPE, SIG_IGN); signal(SIGTERM, sigterm_handler); #endif /* HAVE_SIGSET */ /* * Check command-line... */ if (argc == 1) { printf("network lpd \"Unknown\" \"%s\"\n", _cupsLangString(cupsLangDefault(), _("LPD/LPR Host or Printer"))); return (CUPS_BACKEND_OK); } else if (argc < 6 || argc > 7) { _cupsLangPrintf(stderr, _("Usage: %s job-id user title copies options [file]"), argv[0]); return (CUPS_BACKEND_FAILED); } num_jobopts = cupsParseOptions(argv[5], 0, &jobopts); /* * Extract the hostname and printer name from the URI... */ while ((device_uri = cupsBackendDeviceURI(argv)) == NULL) { _cupsLangPrintFilter(stderr, "INFO", _("Unable to locate printer.")); sleep(10); if (getenv("CLASS") != NULL) return (CUPS_BACKEND_FAILED); } httpSeparateURI(HTTP_URI_CODING_ALL, device_uri, scheme, sizeof(scheme), username, sizeof(username), hostname, sizeof(hostname), &port, resource, sizeof(resource)); if (!port) port = 515; /* Default to port 515 */ if (!username[0]) { /* * If no username is in the device URI, then use the print job user... */ strlcpy(username, argv[2], sizeof(username)); } /* * See if there are any options... */ mode = MODE_STANDARD; banner = 0; format = 'l'; order = ORDER_CONTROL_DATA; reserve = RESERVE_ANY; manual_copies = 1; timeout = 300; contimeout = 7 * 24 * 60 * 60; #ifdef __APPLE__ /* * We want to pass UTF-8 characters by default, not re-map them (3071945) */ sanitize_title = 0; #else /* * Otherwise we want to re-map UTF-8 to "safe" characters by default... */ sanitize_title = 1; #endif /* __APPLE__ */ if ((options = strchr(resource, '?')) != NULL) { /* * Yup, terminate the device name string and move to the first * character of the options... */ *options++ = '\0'; /* * Parse options... */ while (*options) { /* * Get the name... */ name = options; while (*options && *options != '=' && *options != '+' && *options != '&') options ++; if ((sep = *options) != '\0') *options++ = '\0'; if (sep == '=') { /* * Get the value... */ value = options; while (*options && *options != '+' && *options != '&') options ++; if (*options) *options++ = '\0'; } else value = (char *)""; /* * Process the option... */ if (!_cups_strcasecmp(name, "banner")) { /* * Set the banner... */ banner = !value[0] || !_cups_strcasecmp(value, "on") || !_cups_strcasecmp(value, "yes") || !_cups_strcasecmp(value, "true"); } else if (!_cups_strcasecmp(name, "format") && value[0]) { /* * Set output format... */ if (strchr("cdfglnoprtv", value[0])) format = value[0]; else _cupsLangPrintFilter(stderr, "ERROR", _("Unknown format character: \"%c\"."), value[0]); } else if (!_cups_strcasecmp(name, "mode") && value[0]) { /* * Set control/data order... */ if (!_cups_strcasecmp(value, "standard")) mode = MODE_STANDARD; else if (!_cups_strcasecmp(value, "stream")) mode = MODE_STREAM; else _cupsLangPrintFilter(stderr, "ERROR", _("Unknown print mode: \"%s\"."), value); } else if (!_cups_strcasecmp(name, "order") && value[0]) { /* * Set control/data order... */ if (!_cups_strcasecmp(value, "control,data")) order = ORDER_CONTROL_DATA; else if (!_cups_strcasecmp(value, "data,control")) order = ORDER_DATA_CONTROL; else _cupsLangPrintFilter(stderr, "ERROR", _("Unknown file order: \"%s\"."), value); } else if (!_cups_strcasecmp(name, "reserve")) { /* * Set port reservation mode... */ if (!value[0] || !_cups_strcasecmp(value, "on") || !_cups_strcasecmp(value, "yes") || !_cups_strcasecmp(value, "true") || !_cups_strcasecmp(value, "rfc1179")) reserve = RESERVE_RFC1179; else if (!_cups_strcasecmp(value, "any")) reserve = RESERVE_ANY; else reserve = RESERVE_NONE; } else if (!_cups_strcasecmp(name, "manual_copies")) { /* * Set manual copies... */ manual_copies = !value[0] || !_cups_strcasecmp(value, "on") || !_cups_strcasecmp(value, "yes") || !_cups_strcasecmp(value, "true"); } else if (!_cups_strcasecmp(name, "sanitize_title")) { /* * Set sanitize title... */ sanitize_title = !value[0] || !_cups_strcasecmp(value, "on") || !_cups_strcasecmp(value, "yes") || !_cups_strcasecmp(value, "true"); } else if (!_cups_strcasecmp(name, "snmp")) { /* * Enable/disable SNMP stuff... */ snmp_enabled = !value[0] || !_cups_strcasecmp(value, "on") || _cups_strcasecmp(value, "yes") || _cups_strcasecmp(value, "true"); } else if (!_cups_strcasecmp(name, "timeout")) { /* * Set the timeout... */ if (atoi(value) > 0) timeout = atoi(value); } else if (!_cups_strcasecmp(name, "contimeout")) { /* * Set the connection timeout... */ if (atoi(value) > 0) contimeout = atoi(value); } } } if (mode == MODE_STREAM) order = ORDER_CONTROL_DATA; /* * Find the printer... */ snprintf(portname, sizeof(portname), "%d", port); fputs("STATE: +connecting-to-device\n", stderr); fprintf(stderr, "DEBUG: Looking up \"%s\"...\n", hostname); while ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portname)) == NULL) { _cupsLangPrintFilter(stderr, "INFO", _("Unable to locate printer \"%s\"."), hostname); sleep(10); if (getenv("CLASS") != NULL) { fputs("STATE: -connecting-to-device\n", stderr); exit(CUPS_BACKEND_FAILED); } } if (snmp_enabled) snmp_fd = _cupsSNMPOpen(addrlist->addr.addr.sa_family); else snmp_fd = -1; /* * Wait for data from the filter... */ if (argc == 6) { if (!backendWaitLoop(snmp_fd, &(addrlist->addr), 0, backendNetworkSideCB)) return (CUPS_BACKEND_OK); else if (mode == MODE_STANDARD && (bytes = read(0, buffer, sizeof(buffer))) <= 0) return (CUPS_BACKEND_OK); } /* * If we have 7 arguments, print the file named on the command-line. * Otherwise, copy stdin to a temporary file and print the temporary * file. */ if (argc == 6 && mode == MODE_STANDARD) { /* * Copy stdin to a temporary file... */ if ((fd = cupsTempFd(tmpfilename, sizeof(tmpfilename))) < 0) { perror("DEBUG: Unable to create temporary file"); return (CUPS_BACKEND_FAILED); } _cupsLangPrintFilter(stderr, "INFO", _("Copying print data.")); if (bytes > 0) write(fd, buffer, bytes); backendRunLoop(-1, fd, snmp_fd, &(addrlist->addr), 0, 0, backendNetworkSideCB); } else if (argc == 6) { /* * Stream from stdin... */ filename = NULL; fd = 0; } else { filename = argv[6]; fd = open(filename, O_RDONLY); if (fd == -1) { _cupsLangPrintError("ERROR", _("Unable to open print file")); return (CUPS_BACKEND_FAILED); } } /* * Sanitize the document title... */ strlcpy(title, argv[3], sizeof(title)); if (sanitize_title) { /* * Sanitize the title string so that we don't cause problems on * the remote end... */ char *ptr; for (ptr = title; *ptr; ptr ++) if (!isalnum(*ptr & 255) && !isspace(*ptr & 255)) *ptr = '_'; } /* * Queue the job... */ if (argc > 6) { if (manual_copies) { manual_copies = atoi(argv[4]); copies = 1; } else { manual_copies = 1; copies = atoi(argv[4]); } status = lpd_queue(hostname, addrlist, resource + 1, fd, snmp_fd, mode, username, title, copies, banner, format, order, reserve, manual_copies, timeout, contimeout, cupsGetOption("job-originating-host-name", num_jobopts, jobopts)); if (!status) fprintf(stderr, "PAGE: 1 %d\n", atoi(argv[4])); } else status = lpd_queue(hostname, addrlist, resource + 1, fd, snmp_fd, mode, username, title, 1, banner, format, order, reserve, 1, timeout, contimeout, cupsGetOption("job-originating-host-name", num_jobopts, jobopts)); /* * Remove the temporary file if necessary... */ if (tmpfilename[0]) unlink(tmpfilename); if (fd) close(fd); if (snmp_fd >= 0) _cupsSNMPClose(snmp_fd); /* * Return the queue status... */ return (status); }
static int cups_job_submit(int snum, struct printjob *pjob) { int ret; /* Return value */ http_t *http; /* HTTP connection to server */ ipp_t *request, /* IPP Request */ *response; /* IPP Response */ cups_lang_t *language; /* Default language */ char uri[HTTP_MAX_URI]; /* printer-uri attribute */ char *clientname; /* hostname of client for job-originating-host attribute */ pstring new_jobname; int num_options = 0; cups_option_t *options; DEBUG(5,("cups_job_submit(%d, %p (%d))\n", snum, pjob, pjob->sysjob)); /* * Make sure we don't ask for passwords... */ cupsSetPasswordCB(cups_passwd_cb); /* * Try to connect to the server... */ if ((http = httpConnect(cupsServer(), ippPort())) == NULL) { DEBUG(0,("Unable to connect to CUPS server %s - %s\n", cupsServer(), strerror(errno))); return (1); } /* * Build an IPP_PRINT_JOB request, which requires the following * attributes: * * attributes-charset * attributes-natural-language * printer-uri * requesting-user-name * [document-data] */ request = ippNew(); request->request.op.operation_id = IPP_PRINT_JOB; request->request.op.request_id = 1; language = cupsLangDefault(); 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); slprintf(uri, sizeof(uri) - 1, "ipp://localhost/printers/%s", PRINTERNAME(snum)); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, pjob->user); clientname = client_name(); if (strcmp(clientname, "UNKNOWN") == 0) { clientname = client_addr(); } ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "job-originating-host-name", NULL, clientname); pstr_sprintf(new_jobname,"%s%.8u %s", PRINT_SPOOL_PREFIX, (unsigned int)pjob->smbjob, pjob->jobname); ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "job-name", NULL, new_jobname); /* * add any options defined in smb.conf */ num_options = 0; options = NULL; num_options = cupsParseOptions(lp_cups_options(snum), num_options, &options); if ( num_options ) cupsEncodeOptions(request, num_options, options); /* * Do the request and get back a response... */ slprintf(uri, sizeof(uri) - 1, "/printers/%s", PRINTERNAME(snum)); ret = 1; if ((response = cupsDoFileRequest(http, request, uri, pjob->filename)) != NULL) { if (response->request.status.status_code >= IPP_OK_CONFLICT) DEBUG(0,("Unable to print file to %s - %s\n", PRINTERNAME(snum), ippErrorString(cupsLastError()))); else ret = 0; ippDelete(response); } else DEBUG(0,("Unable to print file to `%s' - %s\n", PRINTERNAME(snum), ippErrorString(cupsLastError()))); httpClose(http); if ( ret == 0 ) unlink(pjob->filename); /* else print_job_end will do it for us */ return (ret); }
int /* O - Exit status */ main(int argc, /* I - Number of command-line arguments */ char *argv[]) /* I - Command-line arguments */ { int i; /* Looping var */ int num_defaults; /* Number of default options */ cups_option_t *defaults; /* Default options */ char line[256], /* Command string */ command, /* Command code */ *dest, /* Pointer to destination */ *list, /* Pointer to list */ *agent, /* Pointer to user */ status; /* Status for client */ socklen_t hostlen; /* Size of client address */ http_addr_t hostaddr; /* Address of client */ char hostname[256], /* Name of client */ hostip[256], /* IP address */ *hostfamily; /* Address family */ int hostlookups; /* Do hostname lookups? */ #ifdef __APPLE__ vproc_transaction_t vtran = vproc_transaction_begin(NULL); #endif /* __APPLE__ */ /* * Don't buffer the output... */ setbuf(stdout, NULL); /* * Log things using the "cups-lpd" name... */ openlog("cups-lpd", LOG_PID, LOG_LPR); /* * Scan the command-line for options... */ num_defaults = 0; defaults = NULL; hostlookups = 1; for (i = 1; i < argc; i ++) if (argv[i][0] == '-') { switch (argv[i][1]) { case 'h' : /* -h hostname[:port] */ if (argv[i][2]) cupsSetServer(argv[i] + 2); else { i ++; if (i < argc) cupsSetServer(argv[i]); else syslog(LOG_WARNING, "Expected hostname string after -h option!"); } break; case 'o' : /* Option */ if (argv[i][2]) num_defaults = cupsParseOptions(argv[i] + 2, num_defaults, &defaults); else { i ++; if (i < argc) num_defaults = cupsParseOptions(argv[i], num_defaults, &defaults); else syslog(LOG_WARNING, "Expected option string after -o option!"); } break; case 'n' : /* Don't do hostname lookups */ hostlookups = 0; break; default : syslog(LOG_WARNING, "Unknown option \"%c\" ignored!", argv[i][1]); break; } } else syslog(LOG_WARNING, "Unknown command-line option \"%s\" ignored!", argv[i]); /* * Get the address of the client... */ hostlen = sizeof(hostaddr); if (getpeername(0, (struct sockaddr *)&hostaddr, &hostlen)) { syslog(LOG_WARNING, "Unable to get client address - %s", strerror(errno)); strlcpy(hostname, "unknown", sizeof(hostname)); } else { httpAddrString(&hostaddr, hostip, sizeof(hostip)); if (hostlookups) httpAddrLookup(&hostaddr, hostname, sizeof(hostname)); else strlcpy(hostname, hostip, sizeof(hostname)); #ifdef AF_INET6 if (hostaddr.addr.sa_family == AF_INET6) hostfamily = "IPv6"; else #endif /* AF_INET6 */ hostfamily = "IPv4"; syslog(LOG_INFO, "Connection from %s (%s %s)", hostname, hostfamily, hostip); } num_defaults = cupsAddOption("job-originating-host-name", hostname, num_defaults, &defaults); /* * RFC1179 specifies that only 1 daemon command can be received for * every connection. */ if (smart_gets(line, sizeof(line), stdin) == NULL) { /* * Unable to get command from client! Send an error status and return. */ syslog(LOG_ERR, "Unable to get command line from client!"); putchar(1); #ifdef __APPLE__ vproc_transaction_end(NULL, vtran); #endif /* __APPLE__ */ return (1); } /* * The first byte is the command byte. After that will be the queue name, * resource list, and/or user name. */ if ((command = line[0]) == '\0') dest = line; else dest = line + 1; if (command == 0x02) list = NULL; else { for (list = dest; *list && !isspace(*list & 255); list ++); while (isspace(*list & 255)) *list++ = '\0'; } /* * Do the command... */ switch (command) { default : /* Unknown command */ syslog(LOG_ERR, "Unknown LPD command 0x%02X!", command); syslog(LOG_ERR, "Command line = %s", line + 1); putchar(1); status = 1; break; case 0x01 : /* Print any waiting jobs */ syslog(LOG_INFO, "Print waiting jobs (no-op)"); putchar(0); status = 0; break; case 0x02 : /* Receive a printer job */ syslog(LOG_INFO, "Receive print job for %s", dest); /* recv_print_job() sends initial status byte */ status = (char)recv_print_job(dest, num_defaults, defaults); break; case 0x03 : /* Send queue state (short) */ syslog(LOG_INFO, "Send queue state (short) for %s %s", dest, list); /* no status byte for this command */ status = (char)send_state(dest, list, 0); break; case 0x04 : /* Send queue state (long) */ syslog(LOG_INFO, "Send queue state (long) for %s %s", dest, list); /* no status byte for this command */ status = (char)send_state(dest, list, 1); break; case 0x05 : /* Remove jobs */ if (list) { /* * Grab the agent and skip to the list of users and/or jobs. */ agent = list; for (; *list && !isspace(*list & 255); list ++); while (isspace(*list & 255)) *list++ = '\0'; syslog(LOG_INFO, "Remove jobs %s on %s by %s", list, dest, agent); status = (char)remove_jobs(dest, agent, list); } else status = 1; putchar(status); break; } syslog(LOG_INFO, "Closing connection"); closelog(); #ifdef __APPLE__ vproc_transaction_end(NULL, vtran); #endif /* __APPLE__ */ return (status); }
int /* O - Exit status */ main(int argc, /* I - Number of command-line arguments */ char *argv[]) /* I - Command-line arguments */ { int status = 0, /* Exit status */ num_options; /* Number of options */ cups_option_t *options; /* Options */ const char *value; /* Value of an option */ if (argc == 1) { /* * cupsParseOptions() */ fputs("cupsParseOptions: ", stdout); num_options = cupsParseOptions("foo=1234 " "bar=\"One Fish\",\"Two Fish\",\"Red Fish\"," "\"Blue Fish\" " "baz={param1=1 param2=2} " "foobar=FOO\\ BAR " "barfoo=barfoo " "barfoo=\"\'BAR FOO\'\"", 0, &options); if (num_options != 5) { printf("FAIL (num_options=%d, expected 5)\n", num_options); status ++; } else if ((value = cupsGetOption("foo", num_options, options)) == NULL || strcmp(value, "1234")) { printf("FAIL (foo=\"%s\", expected \"1234\")\n", value); status ++; } else if ((value = cupsGetOption("bar", num_options, options)) == NULL || strcmp(value, "One Fish,Two Fish,Red Fish,Blue Fish")) { printf("FAIL (bar=\"%s\", expected \"One Fish,Two Fish,Red Fish,Blue " "Fish\")\n", value); status ++; } else if ((value = cupsGetOption("baz", num_options, options)) == NULL || strcmp(value, "{param1=1 param2=2}")) { printf("FAIL (baz=\"%s\", expected \"{param1=1 param2=2}\")\n", value); status ++; } else if ((value = cupsGetOption("foobar", num_options, options)) == NULL || strcmp(value, "FOO BAR")) { printf("FAIL (foobar=\"%s\", expected \"FOO BAR\")\n", value); status ++; } else if ((value = cupsGetOption("barfoo", num_options, options)) == NULL || strcmp(value, "\'BAR FOO\'")) { printf("FAIL (barfoo=\"%s\", expected \"\'BAR FOO\'\")\n", value); status ++; } else puts("PASS"); } else { int i; /* Looping var */ cups_option_t *option; /* Current option */ num_options = cupsParseOptions(argv[1], 0, &options); for (i = 0, option = options; i < num_options; i ++, option ++) printf("options[%d].name=\"%s\", value=\"%s\"\n", i, option->name, option->value); } exit (status); }
static void ppd_mark_option(ppd_file_t *ppd, /* I - PPD file */ const char *option, /* I - Option name */ const char *choice) /* I - Choice name */ { int i, j; /* Looping vars */ ppd_option_t *o; /* Option pointer */ ppd_choice_t *c, /* Choice pointer */ *oldc, /* Old choice pointer */ key; /* Search key for choice */ struct lconv *loc; /* Locale data */ DEBUG_printf(("7ppd_mark_option(ppd=%p, option=\"%s\", choice=\"%s\")", ppd, option, choice)); /* * AP_D_InputSlot is the "default input slot" on MacOS X, and setting * it clears the regular InputSlot choices... */ if (!_cups_strcasecmp(option, "AP_D_InputSlot")) { cupsArraySave(ppd->options); if ((o = ppdFindOption(ppd, "InputSlot")) != NULL) { key.option = o; if ((oldc = (ppd_choice_t *)cupsArrayFind(ppd->marked, &key)) != NULL) { oldc->marked = 0; cupsArrayRemove(ppd->marked, oldc); } } cupsArrayRestore(ppd->options); } /* * Check for custom options... */ cupsArraySave(ppd->options); o = ppdFindOption(ppd, option); cupsArrayRestore(ppd->options); if (!o) return; loc = localeconv(); if (!_cups_strncasecmp(choice, "Custom.", 7)) { /* * Handle a custom option... */ if ((c = ppdFindChoice(o, "Custom")) == NULL) return; if (!_cups_strcasecmp(option, "PageSize")) { /* * Handle custom page sizes... */ ppdPageSize(ppd, choice); } else { /* * Handle other custom options... */ ppd_coption_t *coption; /* Custom option */ ppd_cparam_t *cparam; /* Custom parameter */ char *units; /* Custom points units */ if ((coption = ppdFindCustomOption(ppd, option)) != NULL) { if ((cparam = (ppd_cparam_t *)cupsArrayFirst(coption->params)) == NULL) return; switch (cparam->type) { case PPD_CUSTOM_CURVE : case PPD_CUSTOM_INVCURVE : case PPD_CUSTOM_REAL : cparam->current.custom_real = (float)_cupsStrScand(choice + 7, NULL, loc); break; case PPD_CUSTOM_POINTS : cparam->current.custom_points = (float)_cupsStrScand(choice + 7, &units, loc); if (units) { if (!_cups_strcasecmp(units, "cm")) cparam->current.custom_points *= 72.0f / 2.54f; else if (!_cups_strcasecmp(units, "mm")) cparam->current.custom_points *= 72.0f / 25.4f; else if (!_cups_strcasecmp(units, "m")) cparam->current.custom_points *= 72.0f / 0.0254f; else if (!_cups_strcasecmp(units, "in")) cparam->current.custom_points *= 72.0f; else if (!_cups_strcasecmp(units, "ft")) cparam->current.custom_points *= 12.0f * 72.0f; } break; case PPD_CUSTOM_INT : cparam->current.custom_int = atoi(choice + 7); break; case PPD_CUSTOM_PASSCODE : case PPD_CUSTOM_PASSWORD : case PPD_CUSTOM_STRING : if (cparam->current.custom_string) _cupsStrFree(cparam->current.custom_string); cparam->current.custom_string = _cupsStrAlloc(choice + 7); break; } } } /* * Make sure that we keep the option marked below... */ choice = "Custom"; } else if (choice[0] == '{') { /* * Handle multi-value custom options... */ ppd_coption_t *coption; /* Custom option */ ppd_cparam_t *cparam; /* Custom parameter */ char *units; /* Custom points units */ int num_vals; /* Number of values */ cups_option_t *vals, /* Values */ *val; /* Value */ if ((c = ppdFindChoice(o, "Custom")) == NULL) return; if ((coption = ppdFindCustomOption(ppd, option)) != NULL) { num_vals = cupsParseOptions(choice, 0, &vals); for (i = 0, val = vals; i < num_vals; i ++, val ++) { if ((cparam = ppdFindCustomParam(coption, val->name)) == NULL) continue; switch (cparam->type) { case PPD_CUSTOM_CURVE : case PPD_CUSTOM_INVCURVE : case PPD_CUSTOM_REAL : cparam->current.custom_real = (float)_cupsStrScand(val->value, NULL, loc); break; case PPD_CUSTOM_POINTS : cparam->current.custom_points = (float)_cupsStrScand(val->value, &units, loc); if (units) { if (!_cups_strcasecmp(units, "cm")) cparam->current.custom_points *= 72.0f / 2.54f; else if (!_cups_strcasecmp(units, "mm")) cparam->current.custom_points *= 72.0f / 25.4f; else if (!_cups_strcasecmp(units, "m")) cparam->current.custom_points *= 72.0f / 0.0254f; else if (!_cups_strcasecmp(units, "in")) cparam->current.custom_points *= 72.0f; else if (!_cups_strcasecmp(units, "ft")) cparam->current.custom_points *= 12.0f * 72.0f; } break; case PPD_CUSTOM_INT : cparam->current.custom_int = atoi(val->value); break; case PPD_CUSTOM_PASSCODE : case PPD_CUSTOM_PASSWORD : case PPD_CUSTOM_STRING : if (cparam->current.custom_string) _cupsStrFree(cparam->current.custom_string); cparam->current.custom_string = _cupsStrRetain(val->value); break; } } cupsFreeOptions(num_vals, vals); } } else { for (i = o->num_choices, c = o->choices; i > 0; i --, c ++) if (!_cups_strcasecmp(c->choice, choice)) break; if (!i) return; } /* * Option found; mark it and then handle unmarking any other options. */ if (o->ui != PPD_UI_PICKMANY) { /* * Unmark all other choices... */ if ((oldc = (ppd_choice_t *)cupsArrayFind(ppd->marked, c)) != NULL) { oldc->marked = 0; cupsArrayRemove(ppd->marked, oldc); } if (!_cups_strcasecmp(option, "PageSize") || !_cups_strcasecmp(option, "PageRegion")) { /* * Mark current page size... */ for (j = 0; j < ppd->num_sizes; j ++) ppd->sizes[j].marked = !_cups_strcasecmp(ppd->sizes[j].name, choice); /* * Unmark the current PageSize or PageRegion setting, as * appropriate... */ cupsArraySave(ppd->options); if (!_cups_strcasecmp(option, "PageSize")) { if ((o = ppdFindOption(ppd, "PageRegion")) != NULL) { key.option = o; if ((oldc = (ppd_choice_t *)cupsArrayFind(ppd->marked, &key)) != NULL) { oldc->marked = 0; cupsArrayRemove(ppd->marked, oldc); } } } else { if ((o = ppdFindOption(ppd, "PageSize")) != NULL) { key.option = o; if ((oldc = (ppd_choice_t *)cupsArrayFind(ppd->marked, &key)) != NULL) { oldc->marked = 0; cupsArrayRemove(ppd->marked, oldc); } } } cupsArrayRestore(ppd->options); } else if (!_cups_strcasecmp(option, "InputSlot")) { /* * Unmark ManualFeed option... */ cupsArraySave(ppd->options); if ((o = ppdFindOption(ppd, "ManualFeed")) != NULL) { key.option = o; if ((oldc = (ppd_choice_t *)cupsArrayFind(ppd->marked, &key)) != NULL) { oldc->marked = 0; cupsArrayRemove(ppd->marked, oldc); } } cupsArrayRestore(ppd->options); } else if (!_cups_strcasecmp(option, "ManualFeed") && !_cups_strcasecmp(choice, "True")) { /* * Unmark InputSlot option... */ cupsArraySave(ppd->options); if ((o = ppdFindOption(ppd, "InputSlot")) != NULL) { key.option = o; if ((oldc = (ppd_choice_t *)cupsArrayFind(ppd->marked, &key)) != NULL) { oldc->marked = 0; cupsArrayRemove(ppd->marked, oldc); } } cupsArrayRestore(ppd->options); } } c->marked = 1; cupsArrayAdd(ppd->marked, c); }
int /* O - Exit status */ main(int argc, /* I - Number of command-line args */ char *argv[]) /* I - Command-line arguments */ { int i; /* Looping var */ output_format_t output_format; /* Output format */ int fd = 0; /* Copy file descriptor */ char *filename, /* PDF file to convert */ tempfile[1024]; /* Temporary file */ char buffer[8192]; /* Copy buffer */ int bytes; /* Bytes copied */ int num_options; /* Number of options */ cups_option_t *options; /* Options */ const char *val; /* Option value */ char *argv_nt[8]; /* NULL-terminated array of the command line arguments */ int optbuflen; cups_array_t *filter_chain; /* Filter chain to execute */ int exit_status = 0; /* Exit status */ int color_printing; /* Do we print in color? */ char *filter, *p; #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET) struct sigaction action; /* Actions for POSIX signals */ #endif /* HAVE_SIGACTION && !HAVE_SIGSET */ static const char * const color_mode_option_names[] = { /* Possible names for a color mode option */ "pwg-raster-document-type", "PwgRasterDocumentType", "print-color-mode", "PrintColorMode", "color-space", "ColorSpace", "color-model", "ColorModel", NULL }; /* * Make sure status messages are not buffered... */ setbuf(stderr, NULL); /* * Ignore broken pipe signals... */ signal(SIGPIPE, SIG_IGN); /* * Make sure we have the right number of arguments for CUPS! */ if (argc < 6 || argc > 7) { fprintf(stderr, "Usage: %s job user title copies options [file]\n", argv[0]); return (1); } /* * Register a signal handler to cleanly cancel a job. */ #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */ sigset(SIGTERM, cancel_job); #elif defined(HAVE_SIGACTION) memset(&action, 0, sizeof(action)); sigemptyset(&action.sa_mask); action.sa_handler = cancel_job; sigaction(SIGTERM, &action, NULL); #else signal(SIGTERM, cancel_job); #endif /* HAVE_SIGSET */ /* * Copy stdin if needed... */ if (argc == 6) { /* * Copy stdin to a temp file... */ if ((fd = cupsTempFd(tempfile, sizeof(tempfile))) < 0) { perror("DEBUG: Unable to copy PDF file"); return (1); } fprintf(stderr, "DEBUG: sys5ippprinter - copying to temp print file \"%s\"\n", tempfile); while ((bytes = fread(buffer, 1, sizeof(buffer), stdin)) > 0) bytes = write(fd, buffer, bytes); close(fd); filename = tempfile; } else { /* * Use the filename on the command-line... */ filename = argv[6]; tempfile[0] = '\0'; } /* * Get the options from the fifth command line argument */ num_options = cupsParseOptions(argv[5], 0, &options); /* * Copy the command line arguments into a NULL-terminated array */ for (i = 0; i < 5; i++) argv_nt[i] = argv[i]; /* We copy the contents of argv[5] into a somewhat larger buffer so that we can manipulate it */ optbuflen = strlen(argv[5]) + 256; argv_nt[5] = calloc(optbuflen, sizeof(char)); strcpy(argv_nt[5], (const char*)argv[5]); argv_nt[6] = filename; argv_nt[7] = NULL; /* * Create filter chain */ filter_chain = cupsArrayNew(NULL, NULL); /* * Add the gziptoany filter if installed */ if (filter_present("gziptoany")) cupsArrayAdd(filter_chain, "gziptoany"); /* * If the rastertopdf filter is present and the input is in PWG Raster format * add the rastertopdf filter to the filter chain to support the PWG Raster * input. Same for JPEG input if imagetopdf is present. This way the PPD-less * auto-generated print queue emulates an IPP Everywhere printer, as PPDed * CUPS queues do. */ if (filter_present("rastertopdf") && (val = getenv("CONTENT_TYPE")) != NULL && strcasestr(val, "pwg-raster") != NULL) { cupsArrayAdd(filter_chain, "rastertopdf"); } else if (filter_present("imagetopdf") && (val = getenv("CONTENT_TYPE")) != NULL && strcasestr(val, "jpeg") != NULL) { cupsArrayAdd(filter_chain, "imagetopdf"); } /* * Check the presence of the pdftopdf filter and add it to the filter * chain if it is there */ if (filter_present("pdftopdf")) cupsArrayAdd(filter_chain, "pdftopdf"); /* * Select the output format: PDF, PostScript, PWG Raster, PCL-XL, and * PCL 5c/e * Add the needed filters to the filter chain */ if ((val = cupsGetOption("output-format", num_options, options)) != NULL) { if (strcasestr(val, "raster")) { output_format = PWGRASTER; /* PWG Raster output */ set_option_in_str(argv_nt[5], optbuflen, "MediaClass", NULL); set_option_in_str(argv_nt[5], optbuflen, "media-class", "PwgRaster"); if (filter_present("gstoraster") && access(CUPS_GHOSTSCRIPT, X_OK) == 0) cupsArrayAdd(filter_chain, "gstoraster"); else { fprintf(stderr, "DEBUG: Filter gstoraster or Ghostscript (%s) missing for \"output-format=%s\", using pdftoraster.\n", CUPS_GHOSTSCRIPT, val); if (filter_present("pdftoraster")) cupsArrayAdd(filter_chain, "pdftoraster"); else { fprintf(stderr, "ERROR: Filter pdftoraster missing for \"output-format=%s\"\n", val); exit_status = 1; goto error; } } } else if (strcasestr(val, "pdf")) output_format = PDF; else if (strcasestr(val, "postscript")) { output_format = POSTSCRIPT; if (filter_present("pdftops")) { cupsArrayAdd(filter_chain, "pdftops"); if (access(CUPS_GHOSTSCRIPT, X_OK) != 0) { fprintf(stderr, "DEBUG: Ghostscript (%s) missing for \"output-format=%s\", using Poppler's pdftops instead.\n", CUPS_GHOSTSCRIPT, val); set_option_in_str(argv_nt[5], optbuflen, "pdftops-renderer", "pdftops"); } else if (access(CUPS_POPPLER_PDFTOPS, X_OK) != 0) { fprintf(stderr, "DEBUG: Poppler's pdftops (%s) missing for \"output-format=%s\", using Ghostscript instead.\n", CUPS_POPPLER_PDFTOPS, val); set_option_in_str(argv_nt[5], optbuflen, "pdftops-renderer", "gs"); } else set_option_in_str(argv_nt[5], optbuflen, "pdftops-renderer", "hybrid"); } else { fprintf(stderr, "ERROR: Filter pdftops missing for \"output-format=%s\"\n", val); exit_status = 1; goto error; } } else if ((p = strcasestr(val, "pcl")) != NULL) { if (!strcasecmp(p, "pclxl")) { output_format = PCLXL; if (filter_present("gstopxl") && access(CUPS_GHOSTSCRIPT, X_OK) == 0) cupsArrayAdd(filter_chain, "gstopxl"); else { fprintf(stderr, "DEBUG: Filter gstopxl or Ghostscript (%s) missing for \"output-format=%s\", falling back to PCL 5c/e.\n", CUPS_GHOSTSCRIPT, val); output_format = PCL; } } else { output_format = PCL; } } else { fprintf(stderr, "ERROR: Invalid value for \"output-format\": \"%s\"\n", val); exit_status = 1; goto error; } } else { fprintf(stderr, "ERROR: Missing option \"output-format\".\n"); exit_status = 1; goto error; } if (output_format == PCL) { /* We need CUPS Raster as we want to use rastertopclx with unprintable margins */ set_option_in_str(argv_nt[5], optbuflen, "MediaClass", NULL); set_option_in_str(argv_nt[5], optbuflen, "media-class", ""); /* Does the client send info about margins? */ if (!get_option_in_str(argv_nt[5], "media-left-margin", 0) && !get_option_in_str(argv_nt[5], "media-right-margin", 0) && !get_option_in_str(argv_nt[5], "media-top-margin", 0) && !get_option_in_str(argv_nt[5], "media-bottom-margin", 0)) { /* Set default 12pt margins if there is no info about printer's unprintable margins (100th of mm units, 12.0 * 2540.0 / 72.0 = 423.33) */ set_option_in_str(argv_nt[5], optbuflen, "media-left-margin", "423.33"); set_option_in_str(argv_nt[5], optbuflen, "media-right-margin", "423.33"); set_option_in_str(argv_nt[5], optbuflen, "media-top-margin", "423.33"); set_option_in_str(argv_nt[5], optbuflen, "media-bottom-margin", "423.33"); } /* Check whether the job is requested to be printed in color and if so, set the color space to RGB as this is the best color printing support in PCL 5c */ color_printing = 0; for (i = 0; color_mode_option_names[i]; i ++) { p = get_option_in_str(argv_nt[5], color_mode_option_names[i], 1); if (p && (strcasestr(p, "RGB") || strcasestr(p, "CMY") || strcasestr(p, "color"))) { color_printing = 1; break; } } if (color_printing == 1) { /* Remove unneeded color mode options */ for (i = 0; color_mode_option_names[i]; i ++) set_option_in_str(argv_nt[5], optbuflen, color_mode_option_names[i], NULL); /* Set RGB as color mode */ set_option_in_str(argv_nt[5], optbuflen, "print-color-mode", "RGB"); } if (filter_present("gstoraster") && access(CUPS_GHOSTSCRIPT, X_OK) == 0) cupsArrayAdd(filter_chain, "gstoraster"); else { fprintf(stderr, "DEBUG: Filter gstoraster or Ghostscript (%s) missing for \"output-format=%s\", using pdftoraster.\n", CUPS_GHOSTSCRIPT, val); if (filter_present("pdftoraster")) cupsArrayAdd(filter_chain, "pdftoraster"); else { fprintf(stderr, "ERROR: Filter pdftoraster missing for \"output-format=%s\"\n", val); exit_status = 1; goto error; } } if (filter_present("rastertopclx")) cupsArrayAdd(filter_chain, "rastertopclx"); else { fprintf(stderr, "ERROR: Filter rastertopclx missing for \"output-format=%s\"\n", val); exit_status = 1; goto error; } } fprintf(stderr, "DEBUG: Printer supports output formats: %s\nDEBUG: Using following CUPS filter chain to convert input data to the %s format:", val, output_format == PDF ? "PDF" : (output_format == POSTSCRIPT ? "Postscript" : (output_format == PWGRASTER ? "PWG Raster" : (output_format == PCLXL ? "PCL XL" : (output_format == PCL ? "PCL 5c/e" : "unknown"))))); for (filter = (char *)cupsArrayFirst(filter_chain); filter; filter = (char *)cupsArrayNext(filter_chain)) fprintf(stderr, " %s", filter); fprintf(stderr, "\n"); /* * Execute the filter chain */ exit_status = exec_filters(filter_chain, (char **)argv_nt); /* * Cleanup and exit... */ error: if (tempfile[0]) unlink(tempfile); return (exit_status); }