• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  * Copyright (C) 2016 Mopria Alliance, Inc.
4  * Copyright (C) 2013 Hewlett-Packard Development Company, L.P.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 #include "lib_wprint.h"
20 #include "cups.h"
21 #include "http-private.h"
22 #include "ipphelper.h"
23 #include "wprint_debug.h"
24 
25 #include "ipp_print.h"
26 #include "../plugins/media.h"
27 
28 #define TAG "ipphelper"
29 #define IPP_JOB_UNKNOWN ((ipp_jstate_t)(-1))
30 
31 const char *resource_extensions_arr[] = {
32         DEFAULT_IPP_URI_RESOURCE, "/"
33 };
34 
35 /*
36  * Get the IPP version of the given printer
37  */
38 static status_t determine_ipp_version(char *, http_t *);
39 
40 /*
41  * Tests IPP versions and sets it to the latest working version
42  */
43 static status_t test_and_set_ipp_version(char *, http_t *, int, int);
44 
45 /*
46  * Parses supported IPP versions from the IPP response and copies them into ippVersions
47  */
48 static void parse_IPPVersions(ipp_t *response, ipp_version_supported_t *ippVersions);
49 
50 /*
51  * Parses printer URIs from the IPP response and copies them into capabilities
52  */
53 static void parse_printerUris(ipp_t *response, printer_capabilities_t *capabilities);
54 
strnstr(const char * s,const char * needle,size_t len)55 static inline const char* strnstr(const char* s, const char* needle, size_t len) {
56     if (len <= 0) return NULL;
57 
58     const char c = *needle++;
59     const size_t needleLen = strlen(needle);
60     do {
61         do {
62             if (len <= (ssize_t)needleLen) return NULL;
63             --len;
64         } while (*s++ != c);
65     } while (memcmp(s, needle, needleLen) != 0);
66     s--;
67     return s;
68 }
69 
70 /*
71  * Known media sizes.
72  *
73  * A note on rounding: In some cases the Android-specified width (in mils) is rounded down.
74  * This causes artifacts in libjpeg-turbo when rendering to the correct width, so in these
75  * cases we override with a rounded-up value.
76  */
77 struct MediaSizeTableElement SupportedMediaSizes[SUPPORTED_MEDIA_SIZE_COUNT] = {
78         { US_LETTER, "LETTER", 8500, 11000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_letter_8.5x11in",
79           215900, 279400 },
80         { US_LEGAL, "LEGAL", 8500, 14000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_legal_8.5x14in",
81           215900, 355600 },
82         { LEDGER, "LEDGER", 11000, 17000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_ledger_11x17in",
83           279400, 431800 },
84         { INDEX_CARD_5X7, "5X7", 5000, 7000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_5x7_5x7in",
85           127000, 177800 },
86 
87         // Android system uses width of 11690
88         { ISO_A3, "A3", 11694, 16540, 297, 420, "iso_a3_297x420mm",
89           297000, 420000 },
90 
91         // Android system uses width of 8267
92         { ISO_A4, "A4", 8268, 11692, 210, 297, "iso_a4_210x297mm",
93           210000, 297000 },
94         { ISO_A5, "A5", 5830, 8270, 148, 210, "iso_a5_148x210mm",
95           148000, 210000 },
96 
97         // Android system uses width of 10118
98         { JIS_B4, "JIS B4", 10119, 14331, 257, 364, "jis_b4_257x364mm",
99           257000, 364000 },
100 
101         // Android system uses width of 7165
102         { JIS_B5, "JIS B5", 7167, 10118, 182, 257, "jis_b5_182x257mm",
103           182000, 257000 },
104         { US_GOVERNMENT_LETTER, "8x10", 8000, 10000, UNKNOWN_VALUE, UNKNOWN_VALUE,
105           "na_govt-letter_8x10in",203200, 254000 },
106         { INDEX_CARD_4X6, "4x6", 4000, 6000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_index-4x6_4x6in",
107           101600, 152400 },
108         { JPN_HAGAKI_PC, "JPOST", 3940, 5830, 100, 148, "jpn_hagaki_100x148mm",
109           100000, 148000 },
110         { PHOTO_89X119, "89X119", 3504, 4685, 89, 119, "om_dsc-photo_89x119mm",
111           89000, 119000 },
112         { CARD_54X86, "54X86", 2126, 3386, 54, 86, "om_card_54x86mm",
113           54000,  86000 },
114         { OE_PHOTO_L, "L", 3500, 5000, UNKNOWN_VALUE, UNKNOWN_VALUE, "oe_photo-l_3.5x5in",
115           88900, 127000 },
116 
117           // Large formats
118         { ISO_AND_JIS_A0, "A0", 33110, 46810, 841, 1189, "iso_a0_841x1189mm",
119           841000, 1189000},
120         { ISO_AND_JIS_A1, "A1", 23390, 33110, 594, 841, "iso_a1_594x841mm",
121           594000, 841000},
122         { ISO_AND_JIS_A2, "A2", 16540, 23390, 420, 594, "iso_a2_420x594mm",
123           420000, 594000},
124         { ARCH_A, "9X12", 9000, 12000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_arch-a_9x12in",
125           228600, 304800},
126         { ARCH_B, "12X18", 12000, 18000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_arch-b_12x18in",
127           304800, 457200},
128         { ARCH_C, "18x24", 18000, 24000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_arch-c_18x24in",
129           457200, 609600},
130         { ARCH_D, "24x36", 24000, 36000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_arch-d_24x36in",
131           609600, 914400},
132         { ARCH_E, "36x48", 36000, 48000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_arch-e_36x48in",
133           914400, 1219200},
134         { ARCH_E1, "30x42", 30000, 42000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_wide-format_30x42in",
135           762000, 1066800},
136         { C_SIZE, "AnsiC", 17000, 22000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_c_17x22in",
137           431800, 558800},
138         { D_SIZE, "AnsiD", 22000, 34000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_d_22x34in",
139           558800, 863600},
140         { E_SIZE, "AnsiE", 34000, 44000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_e_34x44in",
141           863600, 1117600},
142         { F_SIZE, "AnsiF", 28000, 40000, UNKNOWN_VALUE, UNKNOWN_VALUE, "asme_f_28x40in",
143           711200, 1016000},
144         { SUPER_B, "SuperB", 13000, 19000, UNKNOWN_VALUE, UNKNOWN_VALUE, "na_super-b_13x19in",
145           330200, 482600}
146 };
147 
148 typedef struct {
149     double Lower;
150     double Upper;
151 } media_dimension_mm_t;
152 
153 static const char *__request_ipp_version[] = {"ipp-versions-supported"};
154 
155 static int __ipp_version_major = 2;
156 static int __ipp_version_minor = 0;
157 
set_ipp_version(ipp_t * op_to_set,char * printer_uri,http_t * http,ipp_version_state use_existing_version)158 status_t set_ipp_version(ipp_t *op_to_set, char *printer_uri, http_t *http,
159         ipp_version_state use_existing_version) {
160     LOGD("set_ipp_version(): Enter %d", use_existing_version);
161     if (op_to_set == NULL) {
162         return ERROR;
163     }
164     switch (use_existing_version) {
165         case NEW_REQUEST_SEQUENCE:
166             __ipp_version_major = 2;
167             __ipp_version_minor = 0;
168             break;
169         case IPP_VERSION_RESOLVED:
170             break;
171         case IPP_VERSION_UNSUPPORTED:
172             if (determine_ipp_version(printer_uri, http) != 0) {
173                 return ERROR;
174             }
175             break;
176     }
177     ippSetVersion(op_to_set, __ipp_version_major, __ipp_version_minor);
178     LOGD("set_ipp_version(): Done");
179     return OK;
180 }
181 
determine_ipp_version(char * printer_uri,http_t * http)182 static status_t determine_ipp_version(char *printer_uri, http_t *http) {
183     LOGD("determine_ipp_version(): Enter printer_uri =  %s", printer_uri);
184 
185     if (http == NULL) {
186         LOGE("determine_ipp_version(): http is NULL cannot continue");
187         return ERROR;
188     }
189     if ((test_and_set_ipp_version(printer_uri, http, 1, 1) == OK)
190             || (test_and_set_ipp_version(printer_uri, http, 1, 0) == OK)
191             || (test_and_set_ipp_version(printer_uri, http, 2, 0) == OK)) {
192         LOGD("successfully set ipp version.");
193     } else {
194         LOGD("could not get ipp version using any known ipp version.");
195         return ERROR;
196     }
197     return OK;
198 }
199 
test_and_set_ipp_version(char * printer_uri,http_t * http,int major,int minor)200 static status_t test_and_set_ipp_version(char *printer_uri, http_t *http, int major, int minor) {
201     status_t return_value = ERROR;
202     int service_unavailable_retry_count = 0;
203     int bad_request_retry_count = 0;
204     ipp_t *request = NULL;
205     ipp_t *response;
206     ipp_version_supported_t ippVersions;
207     char http_resource[1024];
208     int op = IPP_GET_PRINTER_ATTRIBUTES;
209 
210     LOGD("test_and_set_ipp_version(): Enter %d - %d", major, minor);
211     memset(&ippVersions, 0, sizeof(ipp_version_supported_t));
212     getResourceFromURI(printer_uri, http_resource, 1024);
213     do {
214         request = ippNewRequest(op);
215         ippSetVersion(request, major, minor);
216         ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri);
217         ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes",
218                 sizeof(__request_ipp_version) / sizeof(__request_ipp_version[0]),
219                 NULL, __request_ipp_version);
220         if ((response = cupsDoRequest(http, request, http_resource)) == NULL) {
221             ipp_status_t ipp_status = cupsLastError();
222             LOGD("test_and_set_ipp_version:  response is null:  ipp_status %d %s",
223                     ipp_status, ippErrorString(ipp_status));
224             if (ipp_status == IPP_INTERNAL_ERROR) {
225                 LOGE("test_and_set_ipp_version: 1280 received, bailing...");
226                 break;
227             } else if ((ipp_status == IPP_SERVICE_UNAVAILABLE) &&
228                     (service_unavailable_retry_count < IPP_SERVICE_ERROR_MAX_RETRIES)) {
229                 LOGE("test_and_set_ipp_version: 1282 received, retrying %d of %d",
230                         service_unavailable_retry_count, IPP_SERVICE_ERROR_MAX_RETRIES);
231                 service_unavailable_retry_count++;
232                 continue;
233             } else if (ipp_status == IPP_BAD_REQUEST) {
234                 LOGE("test_and_set_ipp_version: IPP_Status of IPP_BAD_REQUEST "
235                         "received. retry (%d) of (%d)", bad_request_retry_count,
236                         IPP_BAD_REQUEST_MAX_RETRIES);
237                 if (bad_request_retry_count > IPP_BAD_REQUEST_MAX_RETRIES) {
238                     break;
239                 }
240                 bad_request_retry_count++;
241                 continue;
242             } else if (ipp_status == IPP_NOT_FOUND) {
243                 LOGE("test_and_set_ipp_version: IPP_Status of IPP_NOT_FOUND received");
244                 break;
245             }
246             return_value = ERROR;
247         } else {
248             ipp_status_t ipp_status = cupsLastError();
249             LOGD("ipp CUPS last ERROR: %d, %s", ipp_status, ippErrorString(ipp_status));
250             if (ipp_status == IPP_BAD_REQUEST) {
251                 LOGD("IPP_Status of IPP_BAD_REQUEST received. retry (%d) of (%d)",
252                         bad_request_retry_count, IPP_BAD_REQUEST_MAX_RETRIES);
253                 if (bad_request_retry_count > IPP_BAD_REQUEST_MAX_RETRIES) {
254                     break;
255                 }
256                 bad_request_retry_count++;
257                 ippDelete(response);
258                 continue;
259             }
260 
261             parse_IPPVersions(response, &ippVersions);
262             if (ippVersions.supportsIpp20) {
263                 __ipp_version_major = 2;
264                 __ipp_version_minor = 0;
265                 return_value = OK;
266                 LOGD("test_and_set_ipp_version(): ipp version set to %d,%d",
267                         __ipp_version_major, __ipp_version_minor);
268             } else if (ippVersions.supportsIpp11) {
269                 __ipp_version_major = 1;
270                 __ipp_version_minor = 1;
271                 return_value = OK;
272                 LOGD("test_and_set_ipp_version(): ipp version set to %d,%d",
273                         __ipp_version_major, __ipp_version_minor);
274             } else if (ippVersions.supportsIpp10) {
275                 __ipp_version_major = 1;
276                 __ipp_version_minor = 0;
277                 return_value = OK;
278                 LOGD("test_and_set_ipp_version(): ipp version set to %d,%d",
279                         __ipp_version_major, __ipp_version_minor);
280             } else {
281                 LOGD("test_and_set_ipp_version: ipp version not found");
282                 return_value = ERROR;
283             }
284         }
285         if (response != NULL) ippDelete(response);
286         break;
287     } while (1);
288     return return_value;
289 }
290 
get_PrinterState(http_t * http,char * printer_uri,printer_state_dyn_t * printer_state_dyn,ipp_pstate_t * printer_state)291 ipp_status_t get_PrinterState(http_t *http, char *printer_uri,
292         printer_state_dyn_t *printer_state_dyn, ipp_pstate_t *printer_state) {
293     LOGD("get_PrinterState(): Enter");
294 
295     // Requested printer attributes
296     static const char *pattrs[] = {"printer-make-and-model", "printer-state",
297             "printer-state-message", "printer-state-reasons"};
298 
299     ipp_t *request = NULL;
300     ipp_t *response = NULL;
301     ipp_status_t ipp_status = IPP_OK;
302     int op = IPP_GET_PRINTER_ATTRIBUTES;
303     char http_resource[1024];
304     getResourceFromURI(printer_uri, http_resource, 1024);
305 
306     if (printer_state_dyn == NULL) {
307         LOGE("get_PrinterState(): printer_state_dyn is null");
308         return ipp_status;
309     }
310 
311     if (printer_state) {
312         *printer_state = IPP_PRINTER_STOPPED;
313     } else {
314         LOGE("get_PrinterState(): printer_state is null");
315     }
316     request = ippNewRequest(op);
317 
318     ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri);
319 
320     ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes",
321             sizeof(pattrs) / sizeof(pattrs[0]), NULL, pattrs);
322 
323     if ((response = ipp_doCupsRequest(http, request, http_resource, printer_uri)) == NULL) {
324         ipp_status = cupsLastError();
325         LOGE("get_PrinterState(): response is null: ipp_status %d", ipp_status);
326         printer_state_dyn->printer_status = PRINT_STATUS_UNABLE_TO_CONNECT;
327         printer_state_dyn->printer_reasons[0] = PRINT_STATUS_UNABLE_TO_CONNECT;
328     } else {
329         ipp_status = cupsLastError();
330         LOGD("ipp CUPS last ERROR: %d, %s", ipp_status, ippErrorString(ipp_status));
331         get_PrinterStateReason(response, printer_state, printer_state_dyn);
332         LOGD("get_PrinterState(): printer_state_dyn->printer_status: %d",
333                 printer_state_dyn->printer_status);
334     }
335     LOGD("get_PrinterState(): exit http->fd %d, ipp_status %d, printer_state %d", http->fd,
336             ipp_status, printer_state_dyn->printer_status);
337 
338     ippDelete(request);
339     ippDelete(response);
340     return ipp_status;
341 }
342 
get_PrinterStateReason(ipp_t * response,ipp_pstate_t * printer_state,printer_state_dyn_t * printer_state_dyn)343 void get_PrinterStateReason(ipp_t *response, ipp_pstate_t *printer_state,
344         printer_state_dyn_t *printer_state_dyn) {
345     LOGD("get_PrinterStateReason(): Enter");
346     ipp_attribute_t *attrptr;
347     int reason_idx = 0;
348     int idx = 0;
349     ipp_pstate_t printer_ippstate = IPP_PRINTER_IDLE;
350 
351     if ((attrptr = ippFindAttribute(response, "printer-state", IPP_TAG_ENUM)) == NULL) {
352         LOGE("get_PrinterStateReason printer-state null");
353         printer_state_dyn->printer_status = PRINT_STATUS_UNABLE_TO_CONNECT;
354         printer_state_dyn->printer_reasons[0] = PRINT_STATUS_UNABLE_TO_CONNECT;
355     } else {
356         printer_ippstate = (ipp_pstate_t) ippGetInteger(attrptr, 0);
357         *printer_state = printer_ippstate;
358 
359         LOGD("get_PrinterStateReason printer-state: %d", printer_ippstate);
360         // set the printer_status; they may be modified based on the status reasons below.
361         switch (printer_ippstate) {
362             case IPP_PRINTER_IDLE:
363                 printer_state_dyn->printer_status = PRINT_STATUS_IDLE;
364                 break;
365             case IPP_PRINTER_PROCESSING:
366                 printer_state_dyn->printer_status = PRINT_STATUS_PRINTING;
367                 break;
368             case IPP_PRINTER_STOPPED:
369                 printer_state_dyn->printer_status = PRINT_STATUS_SVC_REQUEST;
370                 break;
371         }
372     }
373 
374     if ((attrptr = ippFindAttribute(response, "printer-state-reasons", IPP_TAG_KEYWORD)) == NULL) {
375         LOGE(" get_PrinterStateReason printer-state reason null");
376         printer_state_dyn->printer_status = PRINT_STATUS_UNABLE_TO_CONNECT;
377         printer_state_dyn->printer_reasons[0] = PRINT_STATUS_UNABLE_TO_CONNECT;
378     } else {
379         for (idx = 0; idx < ippGetCount(attrptr); idx++) {
380             // Per RFC2911 any of these can have -error, -warning, or -report appended to end
381             LOGD("get_PrinterStateReason printer-state-reason: %s",
382                     ippGetString(attrptr, idx, NULL));
383             if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_NONE,
384                     strlen(IPP_PRNT_STATE_NONE)) == 0) {
385                 switch (printer_ippstate) {
386                     case IPP_PRINTER_IDLE:
387                         printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_IDLE;
388                         break;
389                     case IPP_PRINTER_PROCESSING:
390                         printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_PRINTING;
391                         break;
392                     case IPP_PRINTER_STOPPED:
393                         // should this be PRINT_STATUS_SVC_REQUEST
394                         printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_UNKNOWN;
395                         break;
396                 }
397             } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_SPOOL_FULL,
398                     strlen(IPP_PRNT_STATE_SPOOL_FULL)) == 0) {
399                 switch (printer_ippstate) {
400                     case IPP_PRINTER_IDLE:
401                         printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_UNKNOWN;
402                         break;
403                     case IPP_PRINTER_PROCESSING:
404                         printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_PRINTING;
405                         break;
406                     case IPP_PRINTER_STOPPED:
407                         // should this be PRINT_STATUS_SVC_REQUEST
408                         printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_UNKNOWN;
409                         break;
410                 }
411             } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_MARKER_SUPPLY_LOW,
412                     strlen(IPP_PRNT_STATE_MARKER_SUPPLY_LOW)) == 0) {
413                 printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_LOW_ON_INK;
414             } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_TONER_LOW,
415                     strlen(IPP_PRNT_STATE_TONER_LOW)) == 0) {
416                 printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_LOW_ON_TONER;
417             } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_OTHER_WARN,
418                     strlen(IPP_PRNT_STATE_OTHER_WARN)) == 0) {
419                 printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_UNKNOWN;
420             } else {
421                 // check blocking cases
422                 if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_MEDIA_NEEDED,
423                         strlen(IPP_PRNT_STATE_MEDIA_NEEDED)) == 0) {
424                     printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_OUT_OF_PAPER;
425                 } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_MEDIA_EMPTY,
426                         strlen(IPP_PRNT_STATE_MEDIA_EMPTY)) == 0) {
427                     printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_OUT_OF_PAPER;
428                 } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_TONER_EMPTY,
429                         strlen(IPP_PRNT_STATE_TONER_EMPTY)) == 0) {
430                     printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_OUT_OF_TONER;
431                 } else if (strncmp(ippGetString(attrptr, idx, NULL),
432                         IPP_PRNT_STATE_MARKER_SUPPLY_EMPTY,
433                         strlen(IPP_PRNT_STATE_MARKER_SUPPLY_EMPTY)) == 0) {
434                     printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_OUT_OF_INK;
435                 } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_DOOR_OPEN,
436                         strlen(IPP_PRNT_STATE_DOOR_OPEN)) == 0) {
437                     printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_DOOR_OPEN;
438                 } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_COVER_OPEN,
439                         strlen(IPP_PRNT_STATE_COVER_OPEN)) == 0) {
440                     printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_DOOR_OPEN;
441                 } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_MEDIA_JAM,
442                         strlen(IPP_PRNT_STATE_MEDIA_JAM)) == 0) {
443                     printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_JAMMED;
444                 } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_SHUTDOWN,
445                         strlen(IPP_PRNT_SHUTDOWN)) == 0) {
446                     printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_SHUTTING_DOWN;
447                 } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_STATE_OTHER_ERR,
448                         strlen(IPP_PRNT_STATE_OTHER_ERR)) == 0) {
449                     printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_SVC_REQUEST;
450                 } else if (strncmp(ippGetString(attrptr, idx, NULL), IPP_PRNT_PAUSED,
451                         strlen(IPP_PRNT_PAUSED)) == 0) {
452                     printer_state_dyn->printer_reasons[reason_idx++] = PRINT_STATUS_UNKNOWN;
453                 }
454             }
455         }  // end of reasons loop
456     }
457 }
458 
set_jobStateDyn(ipp_t * response,ipp_jstate_t * job_state,job_state_dyn_t * job_state_dyn)459 void set_jobStateDyn(ipp_t *response,
460                     ipp_jstate_t *job_state,
461                     job_state_dyn_t *job_state_dyn) {
462     ipp_attribute_t *attr;
463     if ((attr = ippFindAttribute(response, "job-state", IPP_TAG_ENUM)) == NULL) {
464         LOGE("  job-state null");
465     } else {
466         *job_state = (ipp_jstate_t) ippGetInteger(attr, 0);
467     }
468 
469     switch (*job_state) {
470         case IPP_JOB_PENDING:
471             job_state_dyn->job_state = IPP_JOB_STATE_PENDING;
472             break;
473         case IPP_JOB_HELD:
474             job_state_dyn->job_state = IPP_JOB_STATE_PENDING_HELD;
475             break;
476         case IPP_JOB_PROCESSING:
477             job_state_dyn->job_state = IPP_JOB_STATE_PROCESSING;
478             break;
479         case IPP_JOB_STOPPED:
480             job_state_dyn->job_state = IPP_JOB_STATE_PROCESSING_STOPPED;
481             break;
482         case IPP_JOB_CANCELED:
483             job_state_dyn->job_state = IPP_JOB_STATE_CANCELED;
484             break;
485         case IPP_JOB_ABORTED:
486             job_state_dyn->job_state = IPP_JOB_STATE_ABORTED;
487             break;
488         case IPP_JOB_COMPLETED:
489             job_state_dyn->job_state = IPP_JOB_STATE_COMPLETED;
490             break;
491         default:
492             if (*job_state == IPP_JOB_UNKNOWN) {
493                 job_state_dyn->job_state = IPP_JOB_STATE_UNABLE_TO_CONNECT;
494             }
495             break;
496     }
497 }
498 
parse_jobStateReasons(ipp_t * response,job_state_dyn_t * job_state_dyn)499 void parse_jobStateReasons(ipp_t *response,
500                           job_state_dyn_t *job_state_dyn) {
501     ipp_attribute_t *attr;
502     if ((attr = ippFindAttribute(response, "job-state-reasons", IPP_TAG_KEYWORD)) == NULL) {
503         job_state_dyn->job_state = IPP_JOB_STATE_UNABLE_TO_CONNECT;
504         job_state_dyn->job_state_reasons[0] = IPP_JOB_STATE_REASON_UNABLE_TO_CONNECT;
505     } else {
506         int reasons_idx = 0;
507         for (int i = 0; i < ippGetCount(attr); i++) {
508             const char *text = ippGetString(attr, i, NULL);
509             LOGD("get_JobStatus: ipp job-state-reason(%d) : %s", i, text);
510             if (strcmp(text, "job-canceled-by-user") == 0) {
511                 job_state_dyn->job_state_reasons[reasons_idx++] =
512                         IPP_JOB_STATE_REASON_JOB_CANCELED_BY_USER;
513             } else if (strcmp(text, "job-canceled-at-device") == 0) {
514                 job_state_dyn->job_state_reasons[reasons_idx++] =
515                         IPP_JOB_STATE_REASON_JOB_CANCELED_AT_DEVICE;
516             } else if (strcmp(text, "aborted-by-system") == 0) {
517                 job_state_dyn->job_state_reasons[reasons_idx++] =
518                         IPP_JOB_STATE_REASON_ABORTED_BY_SYSTEM;
519             } else if (strcmp(text, "unsupported-compression") == 0) {
520                 job_state_dyn->job_state_reasons[reasons_idx++] =
521                         IPP_JOB_STATE_REASON_UNSUPPORTED_COMPRESSION;
522             } else if (strcmp(text, "compression-error") == 0) {
523                 job_state_dyn->job_state_reasons[reasons_idx++] =
524                         IPP_JOB_STATE_REASON_COMPRESSION_ERROR;
525             } else if (strcmp(text, "unsupported-document-format") == 0) {
526                 job_state_dyn->job_state_reasons[reasons_idx++] =
527                         IPP_JOB_STATE_REASON_UNSUPPORTED_DOCUMENT_FORMAT;
528             } else if (strcmp(text, "document-format-error") == 0) {
529                 job_state_dyn->job_state_reasons[reasons_idx++] =
530                         IPP_JOB_STATE_REASON_DOCUMENT_FORMAT_ERROR;
531             } else if (strcmp(text, "service-off-line") == 0) {
532                 job_state_dyn->job_state_reasons[reasons_idx++] =
533                         IPP_JOB_STATE_REASON_SERVICE_OFFLINE;
534             } else if (strcmp(text, "document-password-error") == 0) {
535                 job_state_dyn->job_state_reasons[reasons_idx++] =
536                         IPP_JOB_STATE_REASON_DOCUMENT_PASSWORD_ERROR;
537             } else if (strcmp(text, "document-permission-error") == 0) {
538                 job_state_dyn->job_state_reasons[reasons_idx++] =
539                         IPP_JOB_STATE_REASON_DOCUMENT_PERMISSION_ERROR;
540             } else if (strcmp(text, "document-security-error") == 0) {
541                 job_state_dyn->job_state_reasons[reasons_idx++] =
542                         IPP_JOB_STATE_REASON_DOCUMENT_SECURITY_ERROR;
543             } else if (strcmp(text, "document-unprintable-error") == 0) {
544                 job_state_dyn->job_state_reasons[reasons_idx++] =
545                         IPP_JOB_STATE_REASON_DOCUMENT_UNPRINTABLE_ERROR;
546             } else if (strcmp(text, "document-access-error") == 0) {
547                 job_state_dyn->job_state_reasons[reasons_idx++] =
548                         IPP_JOB_STATE_REASON_DOCUMENT_ACCESS_ERROR;
549             } else if (strcmp(text, "submission-interrupted") == 0) {
550                 job_state_dyn->job_state_reasons[reasons_idx++] =
551                         IPP_JOB_STATE_REASON_SUBMISSION_INTERRUPTED;
552             } else if (strcmp(text, "account-authorization-failed") == 0) {
553                 job_state_dyn->job_state_reasons[reasons_idx++] =
554                         IPP_JOB_STATE_REASON_AUTHORIZATION_FAILED;
555             } else if (strcmp(text, "account-closed") == 0) {
556                 job_state_dyn->job_state_reasons[reasons_idx++] =
557                         IPP_JOB_STATE_REASON_ACCOUNT_CLOSED;
558             } else if (strcmp(text, "account-info-needed") == 0) {
559                 job_state_dyn->job_state_reasons[reasons_idx++] =
560                         IPP_JOB_STATE_REASON_ACCOUNT_INFO_NEEDED;
561             } else if (strcmp(text, "account-limit-reached") == 0) {
562                 job_state_dyn->job_state_reasons[reasons_idx++] =
563                         IPP_JOB_STATE_REASON_ACCOUNT_LIMIT_REACHED;
564             }
565         }
566     }
567 }
568 
get_JobStatus(http_t * http,char * printer_uri,int job_id,job_state_dyn_t * job_state_dyn,ipp_jstate_t * job_state,const char * requesting_user)569 ipp_status_t get_JobStatus(http_t *http,
570               char *printer_uri,        /* I - URI buffer */
571               int job_id,
572               job_state_dyn_t *job_state_dyn,
573               ipp_jstate_t *job_state,
574               const char *requesting_user) {
575 
576     LOGD("get_JobStatus(): Enter");
577     static const char *const jattrs[] =
578             {            /* Job attributes we want */
579                     "job-id",
580                     "job-printer-uri",
581                     "job-name",
582                     "job-state",
583                     "job-state-reasons"
584             };
585     int service_unavailable_retry_count = 0;
586     int bad_request_retry_count = 0;
587     int op = IPP_GET_JOB_ATTRIBUTES;
588     ipp_t *request;  /* IPP request object */
589     ipp_t *response; /* IPP response object */
590     ipp_attribute_t *attr;     /* Current IPP attribute */
591     ipp_attribute_t *attrptr;        /* Attribute pointer */
592     ipp_status_t ipp_status = IPP_OK;        /* Status of IPP request */
593     ipp_version_state ipp_version_supported = IPP_VERSION_RESOLVED;
594     char http_resource[1024];
595     getResourceFromURI(printer_uri, http_resource, 1024);
596 
597     if (job_state_dyn == NULL) {
598         LOGE("get_JobStatus():   ERROR:  get_JobStatus entry: job_state_dyn is null");
599         return ipp_status;
600     }
601 
602     if (job_state != NULL) {
603         *job_state = IPP_JOB_UNKNOWN;
604     } else {
605         LOGE("  get_JobStatus: job_state is null");
606         // return error...
607         return ipp_status;
608     }
609 
610     LOGD(" get_JobStatus IPP_GET_JOB_ATTRIBUTES  http->fd %d", http->fd);
611     do {
612         ipp_status = IPP_OK; // reset ipp_status
613 
614         request = ippNewRequest(op);
615         if (set_ipp_version(request, printer_uri, http, ipp_version_supported) != 0) {
616             LOGE("get_JobStatus(): set_ipp_version!=0, version not set");
617             ipp_status = IPP_VERSION_NOT_SUPPORTED;
618             ippDelete(request);
619             break;
620         }
621 
622         ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri);
623         ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id", job_id);
624         ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
625                      NULL, requesting_user);
626         ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes",
627                       sizeof(jattrs) / sizeof(jattrs[0]), NULL, jattrs);
628 
629         for (attrptr = ippFirstAttribute(request); attrptr; attrptr = ippNextAttribute(request)) {
630             print_attr(attrptr);
631         }
632 
633         if ((response = cupsDoRequest(http, request, http_resource)) == NULL) {
634             job_state_dyn->job_state = IPP_JOB_STATE_UNABLE_TO_CONNECT;
635             job_state_dyn->job_state_reasons[0] = IPP_JOB_STATE_REASON_UNABLE_TO_CONNECT;
636             ipp_status = cupsLastError();
637             LOGE("  get_JobStatus:  response is null:  ipp_status %d", ipp_status);
638             if (ipp_status == IPP_INTERNAL_ERROR) {
639                 LOGE("get_JobStatus: 1280 received, bailing...");
640                 break;
641             }
642             if (ipp_status == IPP_SERVICE_UNAVAILABLE &&
643                 (service_unavailable_retry_count < IPP_SERVICE_ERROR_MAX_RETRIES)) {
644                 LOGE("1282 received, retrying %d of %d", service_unavailable_retry_count,
645                      IPP_SERVICE_ERROR_MAX_RETRIES);
646                 service_unavailable_retry_count++;
647                 continue;
648             }
649             if (ipp_status == IPP_BAD_REQUEST) {
650                 LOGE("IPP_Status of IPP_BAD_REQUEST received. retry (%d) of (%d)",
651                      bad_request_retry_count, IPP_BAD_REQUEST_MAX_RETRIES);
652                 bad_request_retry_count++;
653                 continue;
654             }
655             if (ipp_status == IPP_NOT_FOUND) {
656                 LOGE("IPP_Status of IPP_NOT_FOUND received. Switching resource path.");
657                 if (tryNextResourceExtension(printer_uri)) {
658                     getResourceFromURI(printer_uri, http_resource, 1024);
659                     continue;
660                 } else {
661                     LOGE("No more resource paths to try");
662                     break;
663                 }
664             }
665         } else {
666             ipp_status = cupsLastError();
667 
668             LOGD("ipp CUPS last ERROR: %d, %s", ipp_status, ippErrorString(ipp_status));
669             if (ipp_status == IPP_BAD_REQUEST) {
670                 LOGE("IPP_Status of IPP_BAD_REQUEST received. retry (%d) of (%d)",
671                      bad_request_retry_count, IPP_BAD_REQUEST_MAX_RETRIES);
672                 bad_request_retry_count++;
673                 ippDelete(response);
674                 continue;
675             }
676             if (ipp_status == IPP_VERSION_NOT_SUPPORTED) {
677                 ipp_version_supported = IPP_VERSION_UNSUPPORTED;
678                 ippDelete(response);
679                 continue;
680             }
681             LOGD("  get_JobStatus:  response!=null:  ipp_status %d", ipp_status);
682             for (attrptr = ippFirstAttribute(response);
683                     attrptr;
684                     attrptr = ippNextAttribute(response))
685                 print_attr(attrptr);
686         }
687 
688         set_jobStateDyn(response, job_state, job_state_dyn);
689         parse_jobStateReasons(response, job_state_dyn);
690 
691         if (response != NULL) ippDelete(response);
692 
693         break;
694     } while (bad_request_retry_count < IPP_BAD_REQUEST_MAX_RETRIES &&
695              service_unavailable_retry_count < IPP_SERVICE_ERROR_MAX_RETRIES);
696 
697     LOGD("  get_JobStatus exit  ipp_status %d, job_state %d", ipp_status, *job_state);
698 
699     return ipp_status;
700 }
701 
print_col(ipp_t * col)702 static void print_col(ipp_t *col) {
703     int i;
704     ipp_attribute_t *attr;
705 
706     LOGD("{");
707     for (attr = ippFirstAttribute(col); attr; attr = ippNextAttribute(col)) {
708         switch (ippGetValueTag(attr)) {
709             case IPP_TAG_INTEGER:
710             case IPP_TAG_ENUM:
711                 for (i = 0; i < ippGetCount(attr); i++) {
712                     LOGD("  %s(%s%s)= %d ", ippGetName(attr),
713                             ippGetCount(attr) > 1 ? "1setOf " : "",
714                             ippTagString(ippGetValueTag(attr)), ippGetInteger(attr, i));
715                 }
716                 break;
717             case IPP_TAG_BOOLEAN:
718                 for (i = 0; i < ippGetCount(attr); i++) {
719                     if (ippGetBoolean(attr, i)) {
720                         LOGD("  %s(%s%s)= true ", ippGetName(attr),
721                                 ippGetCount(attr) > 1 ? "1setOf " : "",
722                                 ippTagString(ippGetValueTag(attr)));
723                     } else {
724                         LOGD("  %s(%s%s)= false ", ippGetName(attr),
725                                 ippGetCount(attr) > 1 ? "1setOf " : "",
726                                 ippTagString(ippGetValueTag(attr)));
727                     }
728                 }
729                 break;
730             case IPP_TAG_NOVALUE:
731                 LOGD("  %s(%s%s)= novalue", ippGetName(attr),
732                         ippGetCount(attr) > 1 ? "1setOf " : "", ippTagString(ippGetValueTag(attr)));
733                 break;
734             case IPP_TAG_RANGE:
735                 for (i = 0; i < ippGetCount(attr); i++) {
736                     int lower, upper;
737                     lower = ippGetRange(attr, i, &upper);
738                     LOGD("  %s(%s%s)= %d-%d ", ippGetName(attr),
739                             ippGetCount(attr) > 1 ? "1setOf " : "",
740                             ippTagString(ippGetValueTag(attr)), lower, upper);
741                 }
742                 break;
743             case IPP_TAG_RESOLUTION:
744                 for (i = 0; i < ippGetCount(attr); i++) {
745                     ipp_res_t units;
746                     int xres, yres;
747                     xres = ippGetResolution(attr, i, &yres, &units);
748                     LOGD("  %s(%s%s)= %dx%d%s ", ippGetName(attr),
749                             ippGetCount(attr) > 1 ? "1setOf " : "",
750                             ippTagString(ippGetValueTag(attr)), xres, yres,
751                             units == IPP_RES_PER_INCH ? "dpi" : "dpc");
752                 }
753                 break;
754             case IPP_TAG_STRING:
755             case IPP_TAG_TEXT:
756             case IPP_TAG_NAME:
757             case IPP_TAG_KEYWORD:
758             case IPP_TAG_CHARSET:
759             case IPP_TAG_URI:
760             case IPP_TAG_MIMETYPE:
761             case IPP_TAG_LANGUAGE:
762                 for (i = 0; i < ippGetCount(attr); i++) {
763                     LOGD("  %s(%s%s)= \"%s\" ", ippGetName(attr),
764                             ippGetCount(attr) > 1 ? "1setOf " : "",
765                             ippTagString(ippGetValueTag(attr)), ippGetString(attr, i, NULL));
766                 }
767                 break;
768             case IPP_TAG_TEXTLANG:
769             case IPP_TAG_NAMELANG:
770                 for (i = 0; i < ippGetCount(attr); i++) {
771                     const char *charset;
772                     const char *text;
773                     text = ippGetString(attr, i, &charset);
774                     LOGD("  %s(%s%s)= \"%s\",%s ", ippGetName(attr),
775                             ippGetCount(attr) > 1 ? "1setOf " : "",
776                             ippTagString(ippGetValueTag(attr)), text, charset);
777                 }
778                 break;
779             case IPP_TAG_BEGIN_COLLECTION:
780                 for (i = 0; i < ippGetCount(attr); i++) {
781                     print_col(ippGetCollection(attr, i));
782                 }
783                 break;
784             default:
785                 break;
786         }
787     }
788     LOGD("}");
789 }
790 
print_attr(ipp_attribute_t * attr)791 void print_attr(ipp_attribute_t *attr) {
792     int i;
793 
794     if (ippGetName(attr) == NULL) {
795         return;
796     }
797 
798     switch (ippGetValueTag(attr)) {
799         case IPP_TAG_INTEGER:
800         case IPP_TAG_ENUM:
801             for (i = 0; i < ippGetCount(attr); i++) {
802                 LOGD("%s (%s%s) = %d ", ippGetName(attr), ippGetCount(attr) > 1 ? "1setOf " : "",
803                         ippTagString(ippGetValueTag(attr)), ippGetInteger(attr, i));
804             }
805             break;
806         case IPP_TAG_BOOLEAN:
807             for (i = 0; i < ippGetCount(attr); i++) {
808                 if (ippGetBoolean(attr, i)) {
809                     LOGD("%s (%s%s) = true ", ippGetName(attr),
810                             ippGetCount(attr) > 1 ? "1setOf " : "",
811                             ippTagString(ippGetValueTag(attr)));
812                 } else {
813                     LOGD("%s (%s%s) = false ", ippGetName(attr),
814                             ippGetCount(attr) > 1 ? "1setOf " : "",
815                             ippTagString(ippGetValueTag(attr)));
816                 }
817             }
818             break;
819         case IPP_TAG_NOVALUE:
820             LOGD("%s (%s%s) = novalue", ippGetName(attr),
821                     ippGetCount(attr) > 1 ? "1setOf " : "", ippTagString(ippGetValueTag(attr)));
822             break;
823         case IPP_TAG_RANGE:
824             for (i = 0; i < ippGetCount(attr); i++) {
825                 int lower, upper;
826                 lower = ippGetRange(attr, i, &upper);
827                 LOGD("%s (%s%s) = %d-%d ", ippGetName(attr), ippGetCount(attr) > 1 ? "1setOf " : "",
828                         ippTagString(ippGetValueTag(attr)), lower, upper);
829             }
830             break;
831         case IPP_TAG_RESOLUTION:
832             for (i = 0; i < ippGetCount(attr); i++) {
833                 ipp_res_t units;
834                 int xres, yres;
835                 xres = ippGetResolution(attr, i, &yres, &units);
836                 LOGD("%s (%s%s) = %dx%d%s ", ippGetName(attr),
837                         ippGetCount(attr) > 1 ? "1setOf " : "",
838                         ippTagString(ippGetValueTag(attr)), xres, yres,
839                         units == IPP_RES_PER_INCH ? "dpi" : "dpc");
840             }
841             break;
842         case IPP_TAG_STRING:
843         case IPP_TAG_TEXT:
844         case IPP_TAG_NAME:
845         case IPP_TAG_KEYWORD:
846         case IPP_TAG_CHARSET:
847         case IPP_TAG_URI:
848         case IPP_TAG_MIMETYPE:
849         case IPP_TAG_LANGUAGE:
850             for (i = 0; i < ippGetCount(attr); i++) {
851                 LOGD("%s (%s%s) = \"%s\" ", ippGetName(attr),
852                         ippGetCount(attr) > 1 ? "1setOf " : "",
853                         ippTagString(ippGetValueTag(attr)), ippGetString(attr, i, NULL));
854             }
855             break;
856         case IPP_TAG_TEXTLANG:
857         case IPP_TAG_NAMELANG:
858             for (i = 0; i < ippGetCount(attr); i++) {
859                 const char *charset;
860                 const char *text;
861                 text = ippGetString(attr, i, &charset);
862                 LOGD("%s (%s%s) = \"%s\",%s ", ippGetName(attr),
863                         ippGetCount(attr) > 1 ? "1setOf " : "",
864                         ippTagString(ippGetValueTag(attr)), text, charset);
865             }
866             break;
867 
868         case IPP_TAG_BEGIN_COLLECTION:
869             for (i = 0; i < ippGetCount(attr); i++) {
870                 LOGD("%s (%s%s): IPP_TAG_BEGIN_COLLECTION", ippGetName(attr),
871                         ippGetCount(attr) > 1 ? "1setOf " : "", ippTagString(ippGetValueTag(attr)));
872                 print_col(ippGetCollection(attr, i));
873             }
874             LOGD("%s (%s%s): IPP_TAG_END_COLLECTION", ippGetName(attr),
875                     ippGetCount(attr) > 1 ? "1setOf " : "", ippTagString(ippGetValueTag(attr)));
876             break;
877 
878         default:
879             break;
880     }
881 }
882 
parse_IPPVersions(ipp_t * response,ipp_version_supported_t * ippVersions)883 void parse_IPPVersions(ipp_t *response, ipp_version_supported_t *ippVersions) {
884     int i;
885     ipp_attribute_t *attrptr;
886     char ipp10[] = "1.0";
887     char ipp11[] = "1.1";
888     char ipp20[] = "2.0";
889     LOGD(" Entered IPPVersions");
890     if (ippVersions != NULL) {
891         memset(ippVersions, 0, sizeof(ipp_version_supported_t));
892         LOGD(" in get_supportedIPPVersions");
893         attrptr = ippFindAttribute(response, "ipp-versions-supported", IPP_TAG_KEYWORD);
894         if (attrptr != NULL) {
895             LOGD(" in get_supportedIPPVersions: %d", ippGetCount(attrptr));
896             for (i = 0; i < ippGetCount(attrptr); i++) {
897                 if (strcmp(ipp10, ippGetString(attrptr, i, NULL)) == 0) {
898                     ippVersions->supportsIpp10 = 1;
899                 } else if (strcmp(ipp11, ippGetString(attrptr, i, NULL)) == 0) {
900                     ippVersions->supportsIpp11 = 1;
901                 } else if (strcmp(ipp20, ippGetString(attrptr, i, NULL)) == 0) {
902                     ippVersions->supportsIpp20 = 1;
903                 } else {
904                     LOGD("found another ipp version. %s", ippGetString(attrptr, i, NULL));
905                 }
906             }
907         }
908     }
909 }
910 
mapDFMediaToIPPKeyword(media_size_t media_size)911 const char *mapDFMediaToIPPKeyword(media_size_t media_size) {
912     int i;
913     for (i = 0; i < SUPPORTED_MEDIA_SIZE_COUNT; i++) {
914         if (SupportedMediaSizes[i].media_size == (media_size_t) media_size) {
915             return (SupportedMediaSizes[i].PWGName);
916         }
917     }
918     return (SupportedMediaSizes[0].PWGName);
919 }
920 
ipp_find_media_size(const char * ipp_media_keyword,media_size_t * media_size)921 int ipp_find_media_size(const char *ipp_media_keyword, media_size_t *media_size) {
922     int i;
923     LOGD("ipp_find_media_size entry is %s", ipp_media_keyword);
924     for (i = 0; i < SUPPORTED_MEDIA_SIZE_COUNT; i++) {
925         if (strcmp(SupportedMediaSizes[i].PWGName, ipp_media_keyword) == 0) {
926             LOGD(" mediaArraySize: match string  %s  PT_size: %d",
927                     SupportedMediaSizes[i].PWGName, SupportedMediaSizes[i].media_size);
928             break;
929         }
930     }
931     if (i < SUPPORTED_MEDIA_SIZE_COUNT) {
932         *media_size = SupportedMediaSizes[i].media_size;
933         return i;
934     } else {
935         return -1;
936     }
937     return -1;
938 }
939 
getMediaSizeFromTag(const char * media_size_tag,media_size_t * media_size)940 static int getMediaSizeFromTag(const char *media_size_tag, media_size_t *media_size) {
941     int i;
942     LOGD("find media size from tag %s", media_size_tag);
943     for (i = 0; i < SUPPORTED_MEDIA_SIZE_COUNT; i++) {
944         if (strcmp(SupportedMediaSizes[i].PWGName, media_size_tag) == 0) {
945             LOGD("Media size match: pwg name %s", SupportedMediaSizes[i].PWGName);
946             *media_size = SupportedMediaSizes[i].media_size;
947             return i;
948         }
949     }
950     return -1;
951 }
952 
getMediaSizeNameFromDimens(unsigned int mediaColReadyWidth,unsigned int mediaColReadyHeight,media_size_t * media_size)953 static int getMediaSizeNameFromDimens(
954         unsigned int mediaColReadyWidth,
955         unsigned int mediaColReadyHeight,
956         media_size_t *media_size) {
957     int i;
958     for (i = 0; i < SUPPORTED_MEDIA_SIZE_COUNT; i++) {
959         if (SupportedMediaSizes[i].WidthInMicrometers / 10 == mediaColReadyWidth
960             && SupportedMediaSizes[i].HeightInMicrometers / 10 == mediaColReadyHeight) {
961             *media_size = SupportedMediaSizes[i].media_size;
962             return i;
963         }
964     }
965     return -1;
966 }
967 
addMediaIfNotDuplicate(int idx,int * sizes_idx,media_supported_t * media_supported,media_size_t media_size)968 static void addMediaIfNotDuplicate(
969         int idx,
970         int *sizes_idx,
971         media_supported_t *media_supported,
972         media_size_t media_size) {
973     if (idx >= 0) {
974         // Check if we've already added this media size to the supported list
975         bool isDuplicate = false;
976         for (int j = 0; j < (*sizes_idx); j++) {
977             if (media_supported->idxKeywordTranTable[j] == idx) {
978                 isDuplicate = true;
979                 break;
980             }
981         }
982         // Only add if it hasn't been added yet
983         if (!isDuplicate) {
984             media_supported->media_size[(*sizes_idx)] = media_size;
985             media_supported->idxKeywordTranTable[(*sizes_idx)] = idx;
986             (*sizes_idx)++;
987         }
988     }
989 }
990 
addRollSupportedSizes(unsigned int width,unsigned int minHeight,unsigned int maxHeight,media_supported_t * media_supported,int * sizesIdx)991 static void addRollSupportedSizes(
992         unsigned int width,
993         unsigned int minHeight,
994         unsigned int maxHeight,
995         media_supported_t *media_supported,
996         int *sizesIdx) {
997     // If a supported media size fits on the roll size, add it to the list
998     for (int i = 0; i < SUPPORTED_MEDIA_SIZE_COUNT; i++) {
999         if(SupportedMediaSizes[i].WidthInMicrometers / 10 <= width
1000             && SupportedMediaSizes[i].HeightInMicrometers / 10 >= minHeight
1001             && SupportedMediaSizes[i].HeightInMicrometers / 10 <= maxHeight) {
1002             addMediaIfNotDuplicate(i, sizesIdx, media_supported, SupportedMediaSizes[i].media_size);
1003         }
1004     }
1005 }
1006 
parse_getMediaSupported(ipp_t * response,media_supported_t * media_supported,printer_capabilities_t * capabilities)1007 void parse_getMediaSupported(
1008         ipp_t *response,
1009         media_supported_t *media_supported,
1010         printer_capabilities_t *capabilities) {
1011     int i;
1012     int sizes_idx = 0;
1013     LOGD(" Entered getMediaSupported");
1014 
1015     media_size_t media_sizeTemp;
1016     int idx = 0;
1017 
1018     // Check for media-col-ready first
1019     ipp_attribute_t *attrptr;
1020     if((attrptr =
1021         ippFindAttribute(response, "media-col-ready", IPP_TAG_BEGIN_COLLECTION)) != NULL) {
1022         LOGD("media-col-ready found");
1023         for (i = 0; i < ippGetCount(attrptr); i++) {
1024             ipp_t *collection = ippGetCollection(attrptr, i);
1025             ipp_attribute_t *attrptr2;
1026             media_ready_set_t mediaReadySet = {};
1027             int minHeight = 0, maxHeight = 0;
1028             for (attrptr2 = ippFirstAttribute(collection);
1029                  (attrptr2 != NULL);
1030                  attrptr2 = ippNextAttribute(collection)) {
1031                 if (strcmp("media-size", ippGetName(attrptr2)) == 0) {
1032                     ipp_t *collection_sec = ippGetCollection(attrptr2, 0);
1033                     ipp_attribute_t *attrptr3;
1034                     for (attrptr3 = ippFirstAttribute(collection_sec);
1035                          (attrptr3 != NULL);
1036                          attrptr3 = ippNextAttribute(collection_sec)) {
1037                         if (strcmp("x-dimension", ippGetName(attrptr3)) == 0) {
1038                             mediaReadySet.x_dimension = ippGetInteger(attrptr3, 0);
1039                         } else if (strcmp("y-dimension", ippGetName(attrptr3)) == 0) {
1040                             if (ippGetValueTag(attrptr3) == IPP_TAG_RANGE) {
1041                                 minHeight = ippGetRange(attrptr3, 0, &maxHeight);
1042                                 mediaReadySet.y_dimension = minHeight;
1043                             } else if (ippGetValueTag(attrptr3) == IPP_TAG_INTEGER) {
1044                                 mediaReadySet.y_dimension = ippGetInteger(attrptr3, 0);
1045                             }
1046                         }
1047                     }
1048                 } else if (strcmp("media-source", ippGetName(attrptr2)) == 0) {
1049                     memset(mediaReadySet.media_tray_tag, 0, MAX_STRING + 1);
1050                     strncpy(mediaReadySet.media_tray_tag,
1051                             ippGetString(attrptr2, 0, NULL), MAX_STRING);
1052                 }
1053             }
1054             if (minHeight > 0 && maxHeight > 0
1055                 && strstr(mediaReadySet.media_tray_tag, "roll") != NULL) {
1056                 // If the source is a roll, add supported sizes that would fit on the roll
1057                 addRollSupportedSizes(mediaReadySet.x_dimension, minHeight, maxHeight,
1058                                       media_supported, &sizes_idx);
1059             } else {
1060                 // Get the media size name from x and y dimensions
1061                 idx = getMediaSizeNameFromDimens(mediaReadySet.x_dimension,
1062                                                  mediaReadySet.y_dimension,
1063                                                  &media_sizeTemp);
1064                 addMediaIfNotDuplicate(idx, &sizes_idx, media_supported, media_sizeTemp);
1065             }
1066         }
1067     }
1068     // Check media-ready if no supported media was found in media-col-ready
1069     if (sizes_idx == 0
1070         && (attrptr = ippFindAttribute(response, "media-ready", IPP_TAG_KEYWORD)) != NULL) {
1071         LOGD("media-ready found");
1072         for (i = 0; i < ippGetCount(attrptr); i++) {
1073             char media_size_tag[MAX_STRING + 1];
1074             memset(media_size_tag, 0, MAX_STRING + 1);
1075             strncpy(media_size_tag,
1076                     ippGetString(attrptr, i, NULL), MAX_STRING);
1077             idx = getMediaSizeFromTag(media_size_tag, &media_sizeTemp);
1078             addMediaIfNotDuplicate(idx, &sizes_idx, media_supported, media_sizeTemp);
1079         }
1080     }
1081 
1082     // Set media ready size as default if we found any
1083     if (sizes_idx > 0) {
1084         strlcpy(capabilities->mediaDefault, mapDFMediaToIPPKeyword(media_supported->media_size[0]),
1085                     sizeof(capabilities->mediaDefault));
1086     }
1087 
1088     // Append media-supported. media is de-duplicated later in java
1089     if ((attrptr = ippFindAttribute(response, "media-supported", IPP_TAG_KEYWORD)) != NULL) {
1090         LOGD("media-supported  found; number of values %d", ippGetCount(attrptr));
1091         for (i = 0; i < ippGetCount(attrptr); i++) {
1092             idx = ipp_find_media_size(ippGetString(attrptr, i, NULL), &media_sizeTemp);
1093 
1094             // Modified since anytime the find media size returned 0 it could either mean
1095             // NOT found or na_letter.
1096             if (idx >= 0) {
1097                 media_supported->media_size[sizes_idx] = media_sizeTemp;
1098                 media_supported->idxKeywordTranTable[sizes_idx] = idx;
1099                 sizes_idx++;
1100             }
1101         }
1102     }
1103     if (sizes_idx == 0) {
1104         LOGD("No supported media found");
1105     }
1106 }
1107 
get_supportedPrinterResolutions(ipp_attribute_t * attrptr,printer_capabilities_t * capabilities)1108 static void get_supportedPrinterResolutions(ipp_attribute_t *attrptr,
1109         printer_capabilities_t *capabilities) {
1110     int idx = 0;
1111     int i;
1112     for (i = 0; i < ippGetCount(attrptr); i++) {
1113         ipp_res_t units;
1114         int xres, yres;
1115         xres = ippGetResolution(attrptr, i, &yres, &units);
1116         if (units == IPP_RES_PER_INCH) {
1117             if ((idx < MAX_RESOLUTIONS_SUPPORTED) && (xres == yres)) {
1118                 capabilities->supportedResolutions[idx] = xres;
1119                 idx++;
1120             }
1121         }
1122     }
1123     capabilities->numSupportedResolutions = idx;
1124 }
1125 
getResourceFromURI(const char * uri,char * resource,int resourcelen)1126 void getResourceFromURI(const char *uri, char *resource, int resourcelen) {
1127     char scheme[1024];
1128     char username[1024];
1129     char host[1024];
1130     int port;
1131     httpSeparateURI(0, uri, scheme, 1024, username, 1024, host, 1024, &port, resource, resourcelen);
1132 }
1133 
1134 /*
1135  * Add a new media type to a printer's collection of supported media types
1136  */
addMediaType(printer_capabilities_t * capabilities,media_type_t mediaType)1137 static void addMediaType(printer_capabilities_t *capabilities, media_type_t mediaType) {
1138     int index;
1139     for (index = 0; index < capabilities->numSupportedMediaTypes; index++) {
1140         // Skip if already present
1141         if (capabilities->supportedMediaTypes[index] == mediaType) return;
1142     }
1143 
1144     // Add if not found and not too many
1145     if (capabilities->numSupportedMediaTypes < MAX_MEDIA_TYPES_SUPPORTED) {
1146         capabilities->supportedMediaTypes[capabilities->numSupportedMediaTypes++] = mediaType;
1147     } else {
1148         LOGI("Hit MAX_MEDIA_TYPES_SUPPORTED while adding %d", mediaType);
1149     }
1150 }
1151 
parse_printerAttributes(ipp_t * response,printer_capabilities_t * capabilities)1152 void parse_printerAttributes(ipp_t *response, printer_capabilities_t *capabilities) {
1153     int i, j;
1154     ipp_attribute_t *attrptr;
1155 
1156     LOGD("Entered parse_printerAttributes");
1157 
1158     media_supported_t media_supported;
1159     for (i = 0; i <= PAGE_STATUS_MAX - 1; i++) {
1160         media_supported.media_size[i] = 0;
1161     }
1162     parse_getMediaSupported(response, &media_supported, capabilities);
1163 
1164     parse_printerUris(response, capabilities);
1165 
1166     LOGD("Media Supported: ");
1167     int idx = 0;
1168     capabilities->numSupportedMediaTypes = 0;
1169     for (i = 0; i <= PAGE_STATUS_MAX - 1; i++) {
1170         if (media_supported.media_size[i] != 0) {
1171             capabilities->supportedMediaSizes[capabilities->numSupportedMediaSizes++] =
1172                     media_supported.media_size[i];
1173             idx = media_supported.idxKeywordTranTable[i];
1174             LOGD(" i %d, \tPT_Size: %d  \tidx %d \tKeyword: %s", i, media_supported.media_size[i],
1175                     idx, SupportedMediaSizes[idx].PWGName);
1176         }
1177     }
1178 
1179     if ((attrptr = ippFindAttribute(response, "printer-dns-sd-name", IPP_TAG_NAME)) != NULL) {
1180         strlcpy(capabilities->name, ippGetString(attrptr, 0, NULL), sizeof(capabilities->name));
1181     }
1182 
1183     if (!capabilities->name[0]) {
1184         if ((attrptr = ippFindAttribute(response, "printer-info", IPP_TAG_TEXT)) != NULL) {
1185             strlcpy(capabilities->name, ippGetString(attrptr, 0, NULL), sizeof(capabilities->name));
1186         }
1187     }
1188 
1189     if (!capabilities->name[0]) {
1190         if ((attrptr = ippFindAttribute(response, "printer-name", IPP_TAG_TEXT)) != NULL) {
1191             strlcpy(capabilities->name, ippGetString(attrptr, 0, NULL), sizeof(capabilities->name));
1192         }
1193     }
1194 
1195     if ((attrptr = ippFindAttribute(response, "printer-make-and-model", IPP_TAG_TEXT)) != NULL) {
1196         strlcpy(capabilities->make, ippGetString(attrptr, 0, NULL), sizeof(capabilities->make));
1197     }
1198 
1199     if ((attrptr = ippFindAttribute(response, "printer-uuid", IPP_TAG_URI)) != NULL) {
1200         strlcpy(capabilities->uuid, ippGetString(attrptr, 0, NULL), sizeof(capabilities->uuid));
1201     }
1202 
1203     if ((attrptr = ippFindAttribute(response, "printer-location", IPP_TAG_TEXT)) != NULL) {
1204         strlcpy(capabilities->location, ippGetString(attrptr, 0, NULL),
1205                 sizeof(capabilities->location));
1206     }
1207 
1208     if ((attrptr = ippFindAttribute(response, "media-default", IPP_TAG_KEYWORD)) != NULL
1209          && strlen(capabilities->mediaDefault) <= 0) {
1210         strlcpy(capabilities->mediaDefault, ippGetString(attrptr, 0, NULL),
1211                 sizeof(capabilities->mediaDefault));
1212     }
1213 
1214     if ((attrptr = ippFindAttribute(response, "color-supported", IPP_TAG_BOOLEAN)) != NULL) {
1215         if (ippGetBoolean(attrptr, 0)) {
1216             capabilities->color = 1;
1217         }
1218     }
1219     if ((attrptr = ippFindAttribute(response, "copies-supported", IPP_TAG_RANGE)) != NULL) {
1220         int upper = 0;
1221         for (i = 0; i < ippGetCount(attrptr); i++) {
1222             ippGetRange(attrptr, i, &upper);
1223         }
1224         if (upper > 1) {
1225             capabilities->canCopy = 1;
1226         }
1227     }
1228     if ((attrptr = ippFindAttribute(response, "print-color-mode-supported", IPP_TAG_KEYWORD)) !=
1229             NULL) {
1230         for (i = 0; i < ippGetCount(attrptr); i++) {
1231             if (strcmp("color", ippGetString(attrptr, i, NULL)) == 0) {
1232                 capabilities->color = 1;
1233             }
1234         }
1235     }
1236     if ((attrptr = ippFindAttribute(response, "print-quality-supported", IPP_TAG_ENUM)) !=
1237             NULL) {
1238         for (i = 0; i < ippGetCount(attrptr) && capabilities->numSupportedQuality
1239                 < MAX_QUALITY_SUPPORTED; i++) {
1240             LOGD("print-quality-supported: %d", ippGetInteger(attrptr, i));
1241             capabilities->supportedQuality[capabilities->numSupportedQuality++] =
1242                 ippGetInteger(attrptr, i);
1243         }
1244     }
1245 
1246     char imagePCLm[] = "application/PCLm";
1247     char imagePWG[] = "image/pwg-raster";
1248     char imagePDF[] = "image/pdf";
1249     char applicationPDF[] = "application/pdf";
1250 
1251     if ((attrptr = ippFindAttribute(response, "document-format-supported", IPP_TAG_MIMETYPE))
1252             != NULL) {
1253         for (i = 0; i < ippGetCount(attrptr); i++) {
1254             if (strcmp(imagePDF, ippGetString(attrptr, i, NULL)) == 0) {
1255                 capabilities->canPrintPDF = 1;
1256             } else if (strcmp(applicationPDF, ippGetString(attrptr, i, NULL)) == 0) {
1257                 capabilities->canPrintPDF = 1;
1258             } else if (strcmp(imagePCLm, ippGetString(attrptr, i, NULL)) == 0) {
1259                 capabilities->canPrintPCLm = 1;
1260             } else if (strcmp(applicationPDF, ippGetString(attrptr, i, NULL)) == 0) {
1261                 capabilities->canPrintPDF = 1;
1262             } else if (strcmp(imagePWG, ippGetString(attrptr, i, NULL)) == 0) {
1263                 capabilities->canPrintPWG = 1;
1264             }
1265         }
1266     }
1267 
1268     if ((attrptr = ippFindAttribute(response, "sides-supported", IPP_TAG_KEYWORD)) != NULL) {
1269         for (i = 0; i < ippGetCount(attrptr); i++) {
1270             if (strcmp(IPP_SIDES_TWO_SIDED_SHORT_EDGE, ippGetString(attrptr, i, NULL)) == 0) {
1271                 capabilities->duplex = 1;
1272             } else if (strcmp(IPP_SIDES_TWO_SIDED_LONG_EDGE, ippGetString(attrptr, i, NULL)) == 0) {
1273                 capabilities->duplex = 1;
1274             }
1275         }
1276     }
1277 
1278     // Look up supported media types
1279     capabilities->numSupportedMediaTypes = 0;
1280     if (((attrptr = ippFindAttribute(response, "media-type-supported", IPP_TAG_KEYWORD)) != NULL)
1281             || ((attrptr = ippFindAttribute(response, "media-type-supported", IPP_TAG_NAME))
1282                     != NULL)) {
1283         for (i = 0; i < ippGetCount(attrptr); i++) {
1284             if (strcasestr(ippGetString(attrptr, i, NULL), "photographic-glossy")) {
1285                 addMediaType(capabilities, MEDIA_PHOTO_GLOSSY);
1286             } else if (strcasestr(ippGetString(attrptr, i, NULL), "photo")) {
1287                 addMediaType(capabilities, MEDIA_PHOTO);
1288             } else if (strcasestr(ippGetString(attrptr, i, NULL), "stationery")) {
1289                 addMediaType(capabilities, MEDIA_PLAIN);
1290             } else if (strcasestr(ippGetString(attrptr, i, NULL), "auto")) {
1291                 addMediaType(capabilities, MEDIA_AUTO);
1292             }
1293         }
1294     }
1295 
1296     if (capabilities->numSupportedMediaTypes == 0) {
1297         // If no recognized media types were found, fall back to all 3 just in case
1298         addMediaType(capabilities, MEDIA_PLAIN);
1299         addMediaType(capabilities, MEDIA_PHOTO);
1300         addMediaType(capabilities, MEDIA_PHOTO_GLOSSY);
1301     }
1302 
1303     capabilities->numSupportedResolutions = 0;
1304     // only appears that SMM supports the pclm-source-resolution-supported attribute
1305     // if that is not present, use the printer-resolution-supported attribute to determine
1306     // if 300DPI is supported
1307     if ((attrptr = ippFindAttribute(response, "pclm-source-resolution-supported",
1308             IPP_TAG_RESOLUTION)) != NULL) {
1309         get_supportedPrinterResolutions(attrptr, capabilities);
1310     } else if ((attrptr = ippFindAttribute(response, "printer-resolution-supported",
1311             IPP_TAG_RESOLUTION)) != NULL) {
1312         get_supportedPrinterResolutions(attrptr, capabilities);
1313     }
1314 
1315     char ipp10[] = "1.0";
1316     char ipp11[] = "1.1";
1317     char ipp20[] = "2.0";
1318 
1319     if ((attrptr = ippFindAttribute(response, "ipp-versions-supported", IPP_TAG_KEYWORD)) != NULL) {
1320         unsigned char supportsIpp20 = 0;
1321         unsigned char supportsIpp11 = 0;
1322         unsigned char supportsIpp10 = 0;
1323 
1324         for (i = 0; i < ippGetCount(attrptr); i++) {
1325             if (strcmp(ipp10, ippGetString(attrptr, i, NULL)) == 0) {
1326                 supportsIpp10 = 1;
1327             } else if (strcmp(ipp11, ippGetString(attrptr, i, NULL)) == 0) {
1328                 supportsIpp11 = 1;
1329             } else if (strcmp(ipp20, ippGetString(attrptr, i, NULL)) == 0) {
1330                 supportsIpp20 = 1;
1331             } else {
1332                 LOGD("found another ipp version. %s", ippGetString(attrptr, i, NULL));
1333             }
1334             if (supportsIpp20) {
1335                 capabilities->ippVersionMajor = 2;
1336                 capabilities->ippVersionMinor = 0;
1337             } else if (supportsIpp11) {
1338                 capabilities->ippVersionMajor = 1;
1339                 capabilities->ippVersionMinor = 1;
1340             } else if (supportsIpp10) {
1341                 capabilities->ippVersionMajor = 1;
1342                 capabilities->ippVersionMinor = 0;
1343             } else {
1344                 // default to 1.0
1345                 capabilities->ippVersionMajor = 1;
1346                 capabilities->ippVersionMinor = 0;
1347             }
1348         }
1349     }
1350 
1351     char epcl10[] = "1.0";
1352     if ((attrptr = ippFindAttribute(response, "epcl-version-supported", IPP_TAG_KEYWORD)) != NULL) {
1353         for (i = 0; i < ippGetCount(attrptr); i++) {
1354             LOGD("setting epcl_ipp_version (KEYWORD) %s", ippGetString(attrptr, i, NULL));
1355 
1356             // substring match because different devices implemented spec differently
1357             if (strstr(ippGetString(attrptr, i, NULL), epcl10) != NULL) {
1358                 LOGD("setting epcl_ipp_version = 1");
1359                 capabilities->ePclIppVersion = 1;
1360             }
1361         }
1362     }
1363 
1364     if ((attrptr = ippFindAttribute(response, "epcl-version-supported", IPP_TAG_TEXT)) != NULL) {
1365         for (i = 0; i < ippGetCount(attrptr); i++) {
1366             LOGD("setting epcl_ipp_verion (TEXT) %s", ippGetString(attrptr, i, NULL));
1367 
1368             // substring match because different devices implemented spec differently
1369             if (strstr(ippGetString(attrptr, i, NULL), epcl10) != NULL) {
1370                 LOGD("setting epcl_ipp_verion = 1");
1371                 capabilities->ePclIppVersion = 1;
1372             }
1373         }
1374     }
1375 
1376     if ((attrptr = ippFindAttribute(response, "media-col-default", IPP_TAG_BEGIN_COLLECTION)) !=
1377             NULL) {
1378         for (i = 0; i < ippGetCount(attrptr); i++) {
1379             LOGD("Gathering margins supported");
1380 
1381             ipp_t *collection = ippGetCollection(attrptr, i);
1382 
1383             for (j = 0, attrptr = ippFirstAttribute(collection);
1384                     (j < 4) && (attrptr != NULL); attrptr = ippNextAttribute(collection)) {
1385                 if (strcmp("media-top-margin", ippGetName(attrptr)) == 0) {
1386                     capabilities->printerTopMargin = ippGetInteger(attrptr, 0);
1387                 } else if (strcmp("media-bottom-margin", ippGetName(attrptr)) == 0) {
1388                     capabilities->printerBottomMargin = ippGetInteger(attrptr, 0);
1389                 } else if (strcmp("media-left-margin", ippGetName(attrptr)) == 0) {
1390                     capabilities->printerLeftMargin = ippGetInteger(attrptr, 0);
1391                 } else if (strcmp("media-right-margin", ippGetName(attrptr)) == 0) {
1392                     capabilities->printerRightMargin = ippGetInteger(attrptr, 0);
1393                 }
1394             }
1395         }
1396     }
1397 
1398     if ((attrptr = ippFindAttribute(response, "media-size-name", IPP_TAG_KEYWORD)) != NULL) {
1399         capabilities->isMediaSizeNameSupported = true;
1400     } else {
1401         capabilities->isMediaSizeNameSupported = false;
1402     }
1403 
1404     // is strip length supported? if so, stored in capabilities
1405     if ((attrptr = ippFindAttribute(response, "pclm-strip-height-preferred",
1406             IPP_TAG_INTEGER)) != NULL) {
1407         LOGD("pclm-strip-height-preferred=%d", ippGetInteger(attrptr, 0));
1408 
1409         // if the strip height is 0, the device wants us to send the entire page in one band
1410         // (according to ePCL spec). Since our code doesn't currently support generating an entire
1411         // page in one band, set the strip height to the default value every device *should* support
1412         // also, for some reason our code crashes when it attempts to generate strips at 512 or
1413         // above. Therefore, limiting the upper bound strip height to 256
1414         if (ippGetInteger(attrptr, 0) == 0 || ippGetInteger(attrptr, 0) > 256) {
1415             capabilities->stripHeight = STRIPE_HEIGHT;
1416         } else {
1417             capabilities->stripHeight = ippGetInteger(attrptr, 0);
1418         }
1419     } else {
1420         capabilities->stripHeight = STRIPE_HEIGHT;
1421     }
1422 
1423     // what is the preferred compression method - jpeg, flate, rle
1424     if ((attrptr = ippFindAttribute(response, "pclm-compression-method-preferred",
1425             IPP_TAG_KEYWORD)) != NULL) {
1426         LOGD("pclm-compression-method-preferred=%s", ippGetString(attrptr, 0, NULL));
1427     }
1428 
1429     // is device able to rotate back page for duplex jobs? (assume PCLM and PWG are similar)
1430     capabilities->canRotateDuplexBackPage = 0;
1431     if ((attrptr = ippFindAttribute(response, "pclm-raster-back-side", IPP_TAG_KEYWORD)) == NULL) {
1432         attrptr = ippFindAttribute(response, "pwg-raster-document-sheet-back", IPP_TAG_KEYWORD);
1433     }
1434     if (attrptr != NULL && strcmp(ippGetString(attrptr, 0, NULL), "rotated") != 0) {
1435         LOGD("Device can rotate back page for duplex jobs.");
1436         capabilities->canRotateDuplexBackPage = 1;
1437     }
1438 
1439     // look for full-bleed supported by looking for 0 on all margins
1440     bool topsupported = false, bottomsupported = false, rightsupported = false,
1441             leftsupported = false;
1442     if ((attrptr = ippFindAttribute(response, "media-top-margin-supported", IPP_TAG_INTEGER)) !=
1443             NULL) {
1444         for (i = 0; i < ippGetCount(attrptr); i++) {
1445             if (ippGetInteger(attrptr, i) == 0) {
1446                 LOGD("Top Margin Supported");
1447                 topsupported = true;
1448                 break;
1449             }
1450         }
1451     }
1452     if ((attrptr = ippFindAttribute(response, "media-bottom-margin-supported", IPP_TAG_INTEGER)) !=
1453             NULL) {
1454         for (i = 0; i < ippGetCount(attrptr); i++) {
1455             if (ippGetInteger(attrptr, i) == 0) {
1456                 LOGD("Bottom Margin Supported");
1457                 bottomsupported = true;
1458                 break;
1459             }
1460         }
1461     }
1462     if ((attrptr = ippFindAttribute(response, "media-right-margin-supported", IPP_TAG_INTEGER)) !=
1463             NULL) {
1464         for (i = 0; i < ippGetCount(attrptr); i++) {
1465             if (ippGetInteger(attrptr, i) == 0) {
1466                 LOGD("Right Margin Supported");
1467                 rightsupported = true;
1468                 break;
1469             }
1470         }
1471     }
1472     if ((attrptr = ippFindAttribute(response, "media-left-margin-supported", IPP_TAG_INTEGER)) !=
1473             NULL) {
1474         for (i = 0; i < ippGetCount(attrptr); i++) {
1475             if (ippGetInteger(attrptr, i) == 0) {
1476                 LOGD("Left Margin Supported");
1477                 leftsupported = true;
1478                 break;
1479             }
1480         }
1481     }
1482 
1483     if (topsupported && bottomsupported && rightsupported && leftsupported) {
1484         LOGD("full-bleed is supported");
1485         capabilities->borderless = 1;
1486     } else {
1487         LOGD("full-bleed is NOT supported");
1488     }
1489 
1490     if ((attrptr = ippFindAttribute(response, "printer-device-id", IPP_TAG_TEXT)) != NULL) {
1491         if (strstr(ippGetString(attrptr, 0, NULL), "PCL3GUI") != NULL) {
1492             capabilities->inkjet = 1;
1493         }
1494     } else if (capabilities->borderless == 1) {
1495         capabilities->inkjet = 1;
1496     }
1497 
1498     // determine if device prints pages face-down
1499     capabilities->faceDownTray = 1;
1500     if ((attrptr = ippFindAttribute(response, "output-bin-supported", IPP_TAG_KEYWORD)) != NULL) {
1501         if (strstr(ippGetString(attrptr, 0, NULL), "face-up") != NULL) {
1502             capabilities->faceDownTray = 0;
1503         }
1504     }
1505     if ((attrptr = ippFindAttribute(response, "printer-output-tray", IPP_TAG_STRING)) != NULL) {
1506         for (i = 0; i < ippGetCount(attrptr); i++) {
1507             int length = 0;
1508             const char *tray_str = ippGetOctetString(attrptr, i, &length);
1509             if (length > 0 && strnstr(tray_str, "faceUp", (size_t)length) != NULL) {
1510                 capabilities->faceDownTray = 0;
1511             }
1512         }
1513     }
1514 
1515     // Determine supported document format details
1516     if ((attrptr = ippFindAttribute(response, "document-format-details-supported",
1517             IPP_TAG_KEYWORD)) != NULL) {
1518         for (i = 0; i < ippGetCount(attrptr); i++) {
1519             if (strcmp("document-source-application-name", ippGetString(attrptr, i, NULL)) == 0) {
1520                 capabilities->docSourceAppName = 1;
1521             } else if (
1522                     strcmp("document-source-application-version", ippGetString(attrptr, i, NULL)) ==
1523                             0) {
1524                 capabilities->docSourceAppVersion = 1;
1525             } else if (strcmp("document-source-os-name", ippGetString(attrptr, i, NULL)) == 0) {
1526                 capabilities->docSourceOsName = 1;
1527             } else if (strcmp("document-source-os-version", ippGetString(attrptr, i, NULL)) == 0) {
1528                 capabilities->docSourceOsVersion = 1;
1529             }
1530         }
1531     }
1532     debuglist_printerCapabilities(capabilities);
1533 }
1534 
1535 // Used in parse_printerUris
1536 #define MAX_URIS 10
1537 typedef struct {
1538     const char *uri;
1539     int valid;
1540 } parsed_uri_t;
1541 
parse_printerUris(ipp_t * response,printer_capabilities_t * capabilities)1542 static void parse_printerUris(ipp_t *response, printer_capabilities_t *capabilities) {
1543     ipp_attribute_t *attrptr;
1544     int i;
1545     parsed_uri_t uris[MAX_URIS] = {0};
1546 
1547     if ((attrptr = ippFindAttribute(response, "printer-uri-supported", IPP_TAG_URI)) != NULL) {
1548         for (i = 0; i < MIN(ippGetCount(attrptr), MAX_URIS); i++) {
1549             uris[i].uri = ippGetString(attrptr, i, NULL);
1550             uris[i].valid = true;
1551         }
1552     }
1553 
1554     // If authentication is required by any URI, mark it invalid
1555     if ((attrptr = ippFindAttribute(response, "uri-authentication-supported", IPP_TAG_KEYWORD))
1556             != NULL) {
1557         for (i = 0; i < MIN(ippGetCount(attrptr), MAX_URIS); i++) {
1558             // Allow "none" and "requesting-user-name" only
1559             if (strcmp("none", ippGetString(attrptr, i, NULL)) != 0 &&
1560                     strcmp("requesting-user-name", ippGetString(attrptr, i, NULL)) != 0) {
1561                 LOGD("parse_printerUris %s invalid because auth=%s", uris[i].uri,
1562                         ippGetString(attrptr, i, NULL));
1563                 uris[i].valid = false;
1564             }
1565         }
1566     }
1567 
1568     // Find a valid URI and copy it into place.
1569     for (i = 0; i < MAX_URIS; i++) {
1570         // Copy if the URI is valid and we haven't yet discovered ipps
1571         if (uris[i].valid && strncmp(capabilities->printerUri, "ipps://", 7) != 0) {
1572             LOGD("parse_printerUris found %s", uris[i].uri);
1573             strlcpy(capabilities->printerUri, uris[i].uri, sizeof(capabilities->printerUri));
1574         }
1575     }
1576 }
1577 
debuglist_printerCapabilities(printer_capabilities_t * capabilities)1578 void debuglist_printerCapabilities(printer_capabilities_t *capabilities) {
1579     LOGD("printer make: %s", capabilities->make);
1580     LOGD("printer default media: %s", capabilities->mediaDefault);
1581     LOGD("canPrintPDF: %d", capabilities->canPrintPDF);
1582     LOGD("duplex: %d", capabilities->duplex);
1583     LOGD("canRotateDuplexBackPage: %d", capabilities->canRotateDuplexBackPage);
1584     LOGD("color: %d", capabilities->color);
1585     LOGD("canCopy: %d", capabilities->canCopy);
1586     LOGD("ippVersionMajor: %d", capabilities->ippVersionMajor);
1587     LOGD("ippVersionMinor: %d", capabilities->ippVersionMinor);
1588     LOGD("strip height: %d", capabilities->stripHeight);
1589     LOGD("faceDownTray: %d", capabilities->faceDownTray);
1590 }
1591 
debuglist_printerStatus(printer_state_dyn_t * printer_state_dyn)1592 void debuglist_printerStatus(printer_state_dyn_t *printer_state_dyn) {
1593     const char *decoded = "unknown";
1594     if (printer_state_dyn->printer_status == PRINT_STATUS_INITIALIZING) {
1595         decoded = "Initializing";
1596     } else if (printer_state_dyn->printer_status == PRINT_STATUS_SHUTTING_DOWN) {
1597         decoded = "Shutting Down";
1598     } else if (printer_state_dyn->printer_status == PRINT_STATUS_UNABLE_TO_CONNECT) {
1599         decoded = "Unable To Connect";
1600     } else if (printer_state_dyn->printer_status == PRINT_STATUS_UNKNOWN) {
1601         decoded = "Unknown";
1602     } else if (printer_state_dyn->printer_status == PRINT_STATUS_OFFLINE) {
1603         decoded = "Offline";
1604     } else if (printer_state_dyn->printer_status == PRINT_STATUS_IDLE) {
1605         decoded = "Idle";
1606     } else if (printer_state_dyn->printer_status == PRINT_STATUS_PRINTING) {
1607         decoded = "Printing";
1608     } else if (printer_state_dyn->printer_status == PRINT_STATUS_OUT_OF_PAPER) {
1609         decoded = "Out Of Paper";
1610     } else if (printer_state_dyn->printer_status == PRINT_STATUS_OUT_OF_INK) {
1611         decoded = "Out Of Ink";
1612     } else if (printer_state_dyn->printer_status == PRINT_STATUS_JAMMED) {
1613         decoded = "Jammed";
1614     } else if (printer_state_dyn->printer_status == PRINT_STATUS_DOOR_OPEN) {
1615         decoded = "Door Open";
1616     } else if (printer_state_dyn->printer_status == PRINT_STATUS_SVC_REQUEST) {
1617         decoded = "Service Request";
1618     }
1619     LOGD("printer status: %d (%s)", printer_state_dyn->printer_status, decoded);
1620 
1621     int idx = 0;
1622     for (idx = 0; idx < (PRINT_STATUS_MAX_STATE + 1); idx++) {
1623         if (PRINT_STATUS_MAX_STATE != printer_state_dyn->printer_reasons[idx]) {
1624             LOGD("printer_reasons (%d): %d", idx, printer_state_dyn->printer_reasons[idx]);
1625         }
1626     }
1627 }
1628 
1629 /*
1630  * Handle server certificate information.
1631  */
ipp_server_cert_cb(http_t * http,void * tls,cups_array_t * certs,void * user_data)1632 static int ipp_server_cert_cb(http_t *http, void *tls, cups_array_t *certs, void *user_data) {
1633     wprint_connect_info_t *connect_info = (wprint_connect_info_t *)user_data;
1634     int error = 0;
1635     if (connect_info->validate_certificate) {
1636         http_credential_t *credential = cupsArrayFirst(certs);
1637         if (credential) {
1638             LOGD("ipp_server_cert_cb: validate_certificate (len=%zu)", credential->datalen);
1639             error = connect_info->validate_certificate(connect_info, credential->data,
1640                                                        credential->datalen);
1641         }
1642     }
1643     return error;
1644 }
1645 
ipp_cups_connect(const wprint_connect_info_t * connect_info,char * printer_uri,unsigned int uriLength)1646 http_t *ipp_cups_connect(const wprint_connect_info_t *connect_info, char *printer_uri,
1647         unsigned int uriLength) {
1648     const char *uri_path;
1649     http_t *curl_http = NULL;
1650 
1651     cupsSetServerCertCB(ipp_server_cert_cb, (void *)connect_info);
1652 
1653     if ((connect_info->uri_path == NULL) || (strlen(connect_info->uri_path) == 0)) {
1654         uri_path = DEFAULT_IPP_URI_RESOURCE;
1655     } else {
1656         uri_path = connect_info->uri_path;
1657     }
1658 
1659     int ippPortNumber = ((connect_info->port_num == IPP_PORT) ? ippPort() : connect_info->port_num);
1660 
1661     if (strstr(connect_info->uri_scheme,IPPS_PREFIX) != NULL) {
1662         curl_http = httpConnect2(connect_info->printer_addr, ippPortNumber, NULL, AF_UNSPEC,
1663                 HTTP_ENCRYPTION_ALWAYS, 1, HTTP_TIMEOUT_MILLIS, NULL);
1664 
1665         // If ALWAYS doesn't work, fall back to REQUIRED
1666         if (curl_http == NULL) {
1667             curl_http = httpConnect2(connect_info->printer_addr, ippPortNumber, NULL, AF_UNSPEC,
1668                     HTTP_ENCRYPTION_REQUIRED, 1, HTTP_TIMEOUT_MILLIS, NULL);
1669         }
1670     } else {
1671         curl_http = httpConnect2(connect_info->printer_addr, ippPortNumber, NULL, AF_UNSPEC,
1672                 HTTP_ENCRYPTION_IF_REQUESTED, 1, HTTP_TIMEOUT_MILLIS, NULL);
1673     }
1674 
1675     httpSetTimeout(curl_http, (double)connect_info->timeout / 1000, NULL, 0);
1676     httpAssembleURIf(HTTP_URI_CODING_ALL, printer_uri, uriLength, connect_info->uri_scheme, NULL,
1677             connect_info->printer_addr, ippPortNumber, "%s", uri_path);
1678 
1679     if (curl_http == NULL) {
1680         LOGD("ipp_cups_connect failed addr=%s port=%d", connect_info->printer_addr, ippPortNumber);
1681     }
1682 
1683     cupsSetServerCertCB(NULL, NULL);
1684     return curl_http;
1685 }
1686 
1687 /*
1688  * Send a request using cupsSendRequest(). Loop if we get NULL or CONTINUE. Does not delete
1689  * the request.
1690  */
ippSendRequest(http_t * http,ipp_t * request,char * resource)1691 static ipp_t *ippSendRequest(http_t *http, ipp_t *request, char *resource) {
1692     ipp_t *response = NULL;
1693     http_status_t result;
1694     bool retry;
1695 
1696     do {
1697         retry = false;
1698         result = cupsSendRequest(http, request, resource, ippLength(request));
1699         if (result != HTTP_ERROR) {
1700             response = cupsGetResponse(http, resource);
1701             result = httpGetStatus(http);
1702         }
1703 
1704         if (result == HTTP_CONTINUE && response == NULL) {
1705             // We need to retry when this happens.
1706             LOGD("ippSendRequest: (Continue with NULL response) Retry");
1707             retry = true;
1708         } else if (result == HTTP_ERROR || result >= HTTP_BAD_REQUEST) {
1709             break;
1710         }
1711 
1712         if (http->state != HTTP_WAITING) {
1713             httpFlush(http);
1714         }
1715     } while (retry);
1716 
1717     return response;
1718 }
1719 
1720 /*
1721  * Call ippDoCupsIORequest, repeating if a failure occurs based on failure conditions, and
1722  * returning the response (or NULL if it failed).
1723  *
1724  * Does not free the request, and the caller must call ippDelete to free any valid response.
1725  */
ipp_doCupsRequest(http_t * http,ipp_t * request,char * http_resource,char * printer_uri)1726 ipp_t *ipp_doCupsRequest(http_t *http, ipp_t *request, char *http_resource, char *printer_uri) {
1727     ipp_status_t ipp_status;
1728     ipp_t *response = NULL;
1729     int service_unavailable_retry_count = 0;
1730     int bad_request_retry_count = 0;
1731     int internal_error_retry_count = 0;
1732     ipp_version_state ipp_version_supported = IPP_VERSION_RESOLVED;
1733 
1734     // Fail if any of these parameters are NULL
1735     if (http == NULL || request == NULL || http_resource == NULL || printer_uri == NULL) {
1736         return NULL;
1737     }
1738 
1739     do {
1740         // Give up immediately if wprint is done.
1741         if (!wprintIsRunning()) return NULL;
1742 
1743         // This is a no-op until we hit the error IPP_VERSION_NOT_SUPPORTED and retry.
1744         if (set_ipp_version(request, printer_uri, http, ipp_version_supported) != 0) {
1745             // We tried to find the correct IPP version by doing a series of get attribute
1746             // requests but they all failed... we give up.
1747             LOGE("ipp_doCupsRequest: set_ipp_version!=0, version not set");
1748             break;
1749         }
1750 
1751         response = ippSendRequest(http, request, http_resource);
1752         if (response == NULL) {
1753             ipp_status = cupsLastError();
1754             if (ipp_status == IPP_INTERNAL_ERROR || ipp_status == HTTP_ERROR) {
1755                 internal_error_retry_count++;
1756                 if (internal_error_retry_count > IPP_INTERNAL_ERROR_MAX_RETRIES) {
1757                     break;
1758                 }
1759 
1760                 LOGE("ipp_doCupsRequest: %s %d received, retry %d of %d",
1761                         printer_uri, ipp_status, internal_error_retry_count,
1762                         IPP_INTERNAL_ERROR_MAX_RETRIES);
1763                 continue;
1764             } else if (ipp_status == IPP_SERVICE_UNAVAILABLE) {
1765                 service_unavailable_retry_count++;
1766                 if (service_unavailable_retry_count > IPP_SERVICE_ERROR_MAX_RETRIES) {
1767                     break;
1768                 }
1769 
1770                 LOGE("ipp_doCupsRequest: %s IPP_SERVICE_UNAVAILABLE received, retrying %d of %d",
1771                         printer_uri, service_unavailable_retry_count,
1772                         IPP_SERVICE_ERROR_MAX_RETRIES);
1773                 continue;
1774             } else if (ipp_status == IPP_BAD_REQUEST) {
1775                 bad_request_retry_count++;
1776                 if (bad_request_retry_count > IPP_BAD_REQUEST_MAX_RETRIES) {
1777                     break;
1778                 }
1779 
1780                 LOGD("ipp_doCupsRequest: %s IPP_BAD_REQUEST received. retry (%d) of (%d)",
1781                         printer_uri, bad_request_retry_count, IPP_BAD_REQUEST_MAX_RETRIES);
1782                 continue;
1783             } else if (ipp_status == IPP_NOT_FOUND) {
1784                 LOGE("ipp_doCupsRequest: %s IPP_NOT_FOUND received.", printer_uri);
1785                 break;
1786             }
1787         } else {
1788             ipp_status = cupsLastError();
1789             if (ipp_status == IPP_BAD_REQUEST) {
1790                 bad_request_retry_count++;
1791                 LOGE("ipp_doCupsRequest: %s IPP_BAD_REQUEST received. retry (%d) of (%d)",
1792                         printer_uri, bad_request_retry_count, IPP_BAD_REQUEST_MAX_RETRIES);
1793                 if (bad_request_retry_count > IPP_BAD_REQUEST_MAX_RETRIES) {
1794                     break;
1795                 }
1796 
1797                 ippDelete(response);
1798                 response = NULL;
1799                 continue;
1800             } else if (ipp_status == IPP_VERSION_NOT_SUPPORTED) {
1801                 ipp_version_supported = IPP_VERSION_UNSUPPORTED;
1802                 ippDelete(response);
1803                 response = NULL;
1804                 continue;
1805             }
1806         }
1807         break;
1808     } while (1);
1809 
1810     return response;
1811 }
1812 
getJobId(http_t * http,char * http_resource,char * printer_uri,job_state_dyn_t * job_state_dyn,const char * requesting_user)1813 int getJobId(http_t *http,
1814               char *http_resource,
1815               char *printer_uri,        /* I - URI buffer */
1816               job_state_dyn_t *job_state_dyn,
1817               const char *requesting_user) {
1818     int job_id = -1;
1819     // Requested print job attributes
1820     static const char *jattrs[] = {"job-id"};
1821     ipp_t *request = NULL;  /* IPP request object */
1822     ipp_t *response = NULL; /* IPP response object */
1823 
1824     request = ippNewRequest(IPP_GET_JOBS);
1825 
1826     if (request != NULL) {
1827         ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printer_uri);
1828         ippAddBoolean(request, IPP_TAG_OPERATION, "my-jobs", 1);
1829         ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
1830                      NULL, requesting_user);
1831         ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes",
1832                       sizeof(jattrs) / sizeof(jattrs[0]), NULL, jattrs);
1833 
1834         if ((response = ipp_doCupsRequest(http, request, http_resource, printer_uri)) == NULL) {
1835             job_state_dyn->job_state = IPP_JOB_STATE_UNABLE_TO_CONNECT;
1836             job_state_dyn->job_state_reasons[0] = IPP_JOB_STATE_REASON_UNABLE_TO_CONNECT;
1837         } else {
1838             ipp_attribute_t *attr = ippFindAttribute(response, "job-id", IPP_TAG_INTEGER);
1839             if (attr != NULL) job_id = ippGetInteger(attr, 0);
1840         }
1841     }
1842 
1843     if (request != NULL) ippDelete(request);
1844     if (response != NULL) ippDelete(response);
1845 
1846     LOGD("getJobId() returning job-id: %d", job_id);
1847     return job_id;
1848 }
1849 
tryNextResourceExtension(char * printer_uri)1850 int tryNextResourceExtension(char *printer_uri) {
1851     char scheme[1024];
1852     char username[1024];
1853     char host[1024];
1854     char resource[1024];
1855     int port;
1856 
1857     httpSeparateURI(0, printer_uri, scheme, 1024, username, 1024, host, 1024,
1858                     &port, resource, 1024);
1859 
1860     int index;
1861     for (index = 0; index < ARRAY_SIZE(resource_extensions_arr); index++) {
1862         if (strcmp(resource_extensions_arr[index], resource) == 0) {
1863             break;
1864         }
1865     }
1866     if (index >= (ARRAY_SIZE(resource_extensions_arr) - 1)) {
1867         return 0;
1868     } else {
1869         httpAssembleURIf(HTTP_URI_CODING_ALL, printer_uri, 1024, scheme, NULL,
1870                          host, port, "%s", resource_extensions_arr[index + 1]);
1871         LOGD("next resource %s", printer_uri);
1872         return 1;
1873     }
1874 }
1875