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 <stdio.h>
20 #include <stdlib.h>
21 #include <sys/stat.h>
22 #include <fcntl.h>
23 
24 #ifndef _GNU_SOURCE
25 #define _GNU_SOURCE
26 #endif
27 #ifndef __USE_UNIX98
28 #define __USE_UNIX98
29 #endif
30 
31 #include <pthread.h>
32 
33 #include <semaphore.h>
34 #include <printer_capabilities_types.h>
35 
36 #include "ifc_print_job.h"
37 #include "wprint_debug.h"
38 #include "plugin_db.h"
39 
40 #include "ifc_status_monitor.h"
41 
42 #include "ippstatus_monitor.h"
43 #include "ippstatus_capabilities.h"
44 #include "ipp_print.h"
45 #include "ipphelper.h"
46 
47 #include "lib_printable_area.h"
48 #include "wprint_io_plugin.h"
49 #include "../plugins/media.h"
50 
51 #define TAG "lib_wprint"
52 
53 /* As expected by target devices */
54 #define USERAGENT_PREFIX "wPrintAndroid"
55 
56 #define USE_PWG_OVER_PCLM 0
57 
58 #if (USE_PWG_OVER_PCLM != 0)
59 #define _DEFAULT_PRINT_FORMAT  PRINT_FORMAT_PWG
60 #define _DEFAULT_PCL_TYPE      PCLPWG
61 #else // (USE_PWG_OVER_PCLM != 0)
62 #define _DEFAULT_PRINT_FORMAT  PRINT_FORMAT_PCLM
63 #define _DEFAULT_PCL_TYPE      PCLm
64 #endif // (USE_PWG_OVER_PCLM != 0)
65 
66 #define _MAX_SPOOLED_JOBS     100
67 #define _MAX_MSGS             (_MAX_SPOOLED_JOBS * 5)
68 
69 #define _MAX_PAGES_PER_JOB   1000
70 
71 #define MAX_IDLE_WAIT        (5 * 60)
72 
73 #define DEFAULT_RESOLUTION   (300)
74 
75 // When searching for a supported resolution this is the max resolution we will consider.
76 #define MAX_SUPPORTED_RESOLUTION (720)
77 
78 #define MAX_DONE_WAIT (5 * 60)
79 #define MAX_START_WAIT (45)
80 
81 #define IO_PORT_FILE   0
82 
83 /*
84  * The following macros allow for up to 8 bits (256) for spooled job id#s and
85  * 24 bits (16 million) of a running sequence number to provide a reasonably
86  * unique job handle
87  */
88 
89 // _ENCODE_HANDLE() is only called from _get_handle()
90 #define _ENCODE_HANDLE(X) ( (((++_running_number) & 0xffffff) << 8) | ((X) & 0xff) )
91 #define _DECODE_HANDLE(X) ((X) & 0xff)
92 
93 #undef snprintf
94 #undef vsnprintf
95 
96 typedef enum {
97     JOB_STATE_FREE, // queue element free
98     JOB_STATE_QUEUED, // job queued and waiting to be run
99     JOB_STATE_RUNNING, // job running (printing)
100     JOB_STATE_BLOCKED, // print job blocked due to printer stall/error
101     JOB_STATE_CANCEL_REQUEST, // print job cancelled by user,
102     JOB_STATE_CANCELLED, // print job cancelled by user, waiting to be freed
103     JOB_STATE_COMPLETED, // print job completed successfully, waiting to be freed
104     JOB_STATE_ERROR, // job could not be run due to error
105     JOB_STATE_CORRUPTED, // job could not be run due to error
106 
107     NUM_JOB_STATES
108 } _job_state_t;
109 
110 typedef enum {
111     TOP_MARGIN = 0,
112     LEFT_MARGIN,
113     RIGHT_MARGIN,
114     BOTTOM_MARGIN,
115 
116     NUM_PAGE_MARGINS
117 } _page_margins_t;
118 
119 typedef enum {
120     MSG_RUN_JOB, MSG_QUIT,
121 } wprint_msg_t;
122 
123 typedef struct {
124     wprint_msg_t id;
125     wJob_t job_id;
126 } _msg_t;
127 
128 /*
129  * Define an entry in the job queue
130  */
131 typedef struct {
132     wJob_t job_handle;
133     _job_state_t job_state;
134     unsigned int blocked_reasons;
135     wprint_status_cb_t cb_fn;
136     char *printer_addr;
137     port_t port_num;
138     wprint_plugin_t *plugin;
139     ifc_print_job_t *print_ifc;
140     char *mime_type;
141     char *pathname;
142     bool is_dir;
143     bool last_page_seen;
144     int num_pages;
145     msg_q_id pageQ;
146     msg_q_id saveQ;
147 
148     wprint_job_params_t job_params;
149     bool cancel_ok;
150     bool use_secure_uri;
151 
152     const ifc_status_monitor_t *status_ifc;
153     char debug_path[MAX_PATHNAME_LENGTH + 1];
154     char printer_uri[1024];
155     int job_debug_fd;
156     int page_debug_fd;
157 
158     /* A buffer of bytes containing the certificate received while setting up this job, if any. */
159     uint8 *certificate;
160     int certificate_len;
161 } _job_queue_t;
162 
163 /*
164  * An entry for queued pages
165  */
166 typedef struct {
167     int page_num;
168     bool pdf_page;
169     bool last_page;
170     bool corrupted;
171     char filename[MAX_PATHNAME_LENGTH + 1];
172     unsigned int top_margin;
173     unsigned int left_margin;
174     unsigned int right_margin;
175     unsigned int bottom_margin;
176 } _page_t;
177 
178 /*
179  * Entry for a registered plugin
180  */
181 typedef struct {
182     port_t port_num;
183     const wprint_io_plugin_t *io_plugin;
184 } _io_plugin_t;
185 
186 static _job_queue_t _job_queue[_MAX_SPOOLED_JOBS];
187 static msg_q_id _msgQ;
188 
189 static pthread_t _job_status_tid;
190 static pthread_t _job_tid;
191 
192 static pthread_mutex_t _q_lock;
193 static pthread_mutexattr_t _q_lock_attr;
194 
195 static sem_t _job_end_wait_sem;
196 static sem_t _job_start_wait_sem;
197 
198 static _io_plugin_t _io_plugins[2];
199 
200 char g_osName[MAX_ID_STRING_LENGTH + 1] = {0};
201 char g_appName[MAX_ID_STRING_LENGTH + 1] = {0};
202 char g_appVersion[MAX_ID_STRING_LENGTH + 1] = {0};
203 
204 /*
205  * Convert a pcl_t type to a human-readable string
206  */
getPCLTypeString(pcl_t pclenum)207 static char *getPCLTypeString(pcl_t pclenum) {
208     switch (pclenum) {
209         case PCLNONE:
210             return "PCL_NONE";
211         case PCLm:
212             return "PCLm";
213         case PCLJPEG:
214             return "PCL_JPEG";
215         case PCLPWG:
216             return "PWG-Raster";
217         default:
218             return "unkonwn PCL Type";
219     }
220 }
221 
222 /*
223  * Return a _job_queue_t item by its job_handle or NULL if not found.
224  */
_get_job_desc(wJob_t job_handle)225 static _job_queue_t *_get_job_desc(wJob_t job_handle) {
226     unsigned long index;
227     if (job_handle == WPRINT_BAD_JOB_HANDLE) {
228         return NULL;
229     }
230     index = _DECODE_HANDLE(job_handle);
231     if ((index < _MAX_SPOOLED_JOBS) && (_job_queue[index].job_handle == job_handle) &&
232             (_job_queue[index].job_state != JOB_STATE_FREE)) {
233         return (&_job_queue[index]);
234     } else {
235         return NULL;
236     }
237 }
238 
239 /*
240  * Functions below to fill out the _debug_stream_ifc interface
241  */
242 
_stream_dbg_end_job(wJob_t job_handle)243 static void _stream_dbg_end_job(wJob_t job_handle) {
244     _job_queue_t *jq = _get_job_desc(job_handle);
245     if (jq && (jq->job_debug_fd >= 0)) {
246         close(jq->job_debug_fd);
247         jq->job_debug_fd = -1;
248     }
249 }
250 
_stream_dbg_start_job(wJob_t job_handle,const char * ext)251 static void _stream_dbg_start_job(wJob_t job_handle, const char *ext) {
252     _stream_dbg_end_job(job_handle);
253     _job_queue_t *jq = _get_job_desc(job_handle);
254     if (jq && jq->debug_path[0]) {
255         char filename[MAX_PATHNAME_LENGTH + 1];
256         snprintf(filename, MAX_PATHNAME_LENGTH, "%s/jobstream.%s", jq->debug_path, ext);
257         filename[MAX_PATHNAME_LENGTH] = 0;
258         jq->job_debug_fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
259     }
260 }
261 
_stream_dbg_job_data(wJob_t job_handle,const unsigned char * buff,unsigned long nbytes)262 static void _stream_dbg_job_data(wJob_t job_handle, const unsigned char *buff,
263         unsigned long nbytes) {
264     _job_queue_t *jq = _get_job_desc(job_handle);
265     ssize_t bytes_written;
266     if (jq && (jq->job_debug_fd >= 0)) {
267         while (nbytes > 0) {
268             bytes_written = write(jq->job_debug_fd, buff, nbytes);
269             if (bytes_written < 0) {
270                 return;
271             }
272             nbytes -= bytes_written;
273             buff += bytes_written;
274         }
275     }
276 }
277 
_stream_dbg_end_page(wJob_t job_handle)278 static void _stream_dbg_end_page(wJob_t job_handle) {
279     _job_queue_t *jq = _get_job_desc(job_handle);
280     if (jq && (jq->page_debug_fd >= 0)) {
281         close(jq->page_debug_fd);
282         jq->page_debug_fd = -1;
283     }
284 }
285 
_stream_dbg_page_data(wJob_t job_handle,const unsigned char * buff,unsigned long nbytes)286 static void _stream_dbg_page_data(wJob_t job_handle, const unsigned char *buff,
287         unsigned long nbytes) {
288     _job_queue_t *jq = _get_job_desc(job_handle);
289     ssize_t bytes_written;
290     if (jq && (jq->page_debug_fd >= 0)) {
291         while (nbytes > 0) {
292             bytes_written = write(jq->page_debug_fd, buff, nbytes);
293             if (bytes_written < 0) {
294                 return;
295             }
296             nbytes -= bytes_written;
297             buff += bytes_written;
298         }
299     }
300 }
301 
302 #define PPM_IDENTIFIER "P6\n"
303 #define PPM_HEADER_LENGTH 128
304 
_stream_dbg_start_page(wJob_t job_handle,int page_number,int width,int height)305 static void _stream_dbg_start_page(wJob_t job_handle, int page_number, int width, int height) {
306     _stream_dbg_end_page(job_handle);
307     _job_queue_t *jq = _get_job_desc(job_handle);
308     if (jq && jq->debug_path[0]) {
309         union {
310             char filename[MAX_PATHNAME_LENGTH + 1];
311             char ppm_header[PPM_HEADER_LENGTH + 1];
312         } buff;
313         snprintf(buff.filename, MAX_PATHNAME_LENGTH, "%s/page%4.4d.ppm", jq->debug_path,
314                 page_number);
315         buff.filename[MAX_PATHNAME_LENGTH] = 0;
316         jq->page_debug_fd = open(buff.filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
317         int length = snprintf(buff.ppm_header, sizeof(buff.ppm_header), "%s\n#%*c\n%d %d\n%d\n",
318                 PPM_IDENTIFIER, 0, ' ', width, height, 255);
319         int padding = sizeof(buff.ppm_header) - length;
320         snprintf(buff.ppm_header, sizeof(buff.ppm_header), "%s\n#%*c\n%d %d\n%d\n",
321                 PPM_IDENTIFIER, padding, ' ', width, height, 255);
322         _stream_dbg_page_data(job_handle, (const unsigned char *) buff.ppm_header,
323                 PPM_HEADER_LENGTH);
324     }
325 }
326 
327 static const ifc_wprint_debug_stream_t _debug_stream_ifc = {
328         .debug_start_job = _stream_dbg_start_job, .debug_job_data = _stream_dbg_job_data,
329         .debug_end_job = _stream_dbg_end_job, .debug_start_page = _stream_dbg_start_page,
330         .debug_page_data = _stream_dbg_page_data, .debug_end_page = _stream_dbg_end_page
331 };
332 
333 /*
334  * Return the debug stream interface corresponding to the specified job handle
335  */
getDebugStreamIfc(wJob_t handle)336 const ifc_wprint_debug_stream_t *getDebugStreamIfc(wJob_t handle) {
337     _job_queue_t *jq = _get_job_desc(handle);
338     if (jq) {
339         return (jq->debug_path[0] == 0) ? NULL : &_debug_stream_ifc;
340     }
341     return NULL;
342 }
343 
344 const ifc_wprint_t _wprint_ifc = {
345         .msgQCreate = msgQCreate, .msgQDelete = msgQDelete,
346         .msgQSend = msgQSend, .msgQReceive = msgQReceive, .msgQNumMsgs = msgQNumMsgs,
347         .get_debug_stream_ifc = getDebugStreamIfc
348 };
349 
350 static pcl_t _default_pcl_type = _DEFAULT_PCL_TYPE;
351 
_printer_file_connect(const ifc_wprint_t * wprint_ifc)352 static const ifc_print_job_t *_printer_file_connect(const ifc_wprint_t *wprint_ifc) {
353     return printer_connect(IO_PORT_FILE);
354 }
355 
_get_caps_ifc(port_t port_num)356 static const ifc_printer_capabilities_t *_get_caps_ifc(port_t port_num) {
357     int i;
358     for (i = 0; i < ARRAY_SIZE(_io_plugins); i++) {
359         if (_io_plugins[i].port_num == port_num) {
360             if (_io_plugins[i].io_plugin == NULL) {
361                 return NULL;
362             }
363             if (_io_plugins[i].io_plugin->getCapsIFC == NULL) {
364                 return NULL;
365             } else {
366                 return (_io_plugins[i].io_plugin->getCapsIFC(&_wprint_ifc));
367             }
368         }
369     }
370     return NULL;
371 }
372 
_get_status_ifc(port_t port_num)373 static const ifc_status_monitor_t *_get_status_ifc(port_t port_num) {
374     int i;
375     for (i = 0; i < ARRAY_SIZE(_io_plugins); i++) {
376         if (_io_plugins[i].port_num == port_num) {
377             if (_io_plugins[i].io_plugin == NULL) {
378                 return NULL;
379             }
380             if (_io_plugins[i].io_plugin->getStatusIFC == NULL) {
381                 return NULL;
382             } else {
383                 return (_io_plugins[i].io_plugin->getStatusIFC(&_wprint_ifc));
384             }
385         }
386     }
387     return NULL;
388 }
389 
_get_print_ifc(port_t port_num)390 static const ifc_print_job_t *_get_print_ifc(port_t port_num) {
391     int i;
392     for (i = 0; i < ARRAY_SIZE(_io_plugins); i++) {
393         if (_io_plugins[i].port_num == port_num) {
394             if (_io_plugins[i].io_plugin == NULL) {
395                 return NULL;
396             }
397             if (_io_plugins[i].io_plugin->getPrintIFC == NULL) {
398                 return NULL;
399             } else {
400                 return (_io_plugins[i].io_plugin->getPrintIFC(&_wprint_ifc));
401             }
402         }
403     }
404     return NULL;
405 }
406 
407 /*
408  * Lock the semaphore for this module
409  */
_lock(void)410 static void _lock(void) {
411     pthread_mutex_lock(&_q_lock);
412 }
413 
414 /*
415  * Unlock the semaphore for this module
416  */
_unlock(void)417 static void _unlock(void) {
418     pthread_mutex_unlock(&_q_lock);
419 }
420 
_get_handle(void)421 static wJob_t _get_handle(void) {
422     static unsigned long _running_number = 0;
423     wJob_t job_handle = WPRINT_BAD_JOB_HANDLE;
424     int i, index, size;
425     char *ptr;
426 
427     for (i = 0; i < _MAX_SPOOLED_JOBS; i++) {
428         index = (i + _running_number) % _MAX_SPOOLED_JOBS;
429 
430         if (_job_queue[index].job_state == JOB_STATE_FREE) {
431             size = MAX_MIME_LENGTH + MAX_PRINTER_ADDR_LENGTH + MAX_PATHNAME_LENGTH + 4;
432             ptr = malloc(size);
433             if (ptr) {
434                 memset(&_job_queue[index], 0, sizeof(_job_queue_t));
435                 memset(ptr, 0, size);
436 
437                 _job_queue[index].job_debug_fd = -1;
438                 _job_queue[index].page_debug_fd = -1;
439                 _job_queue[index].printer_addr = ptr;
440 
441                 ptr += (MAX_PRINTER_ADDR_LENGTH + 1);
442                 _job_queue[index].mime_type = ptr;
443                 ptr += (MAX_MIME_LENGTH + 1);
444                 _job_queue[index].pathname = ptr;
445 
446                 _job_queue[index].job_state = JOB_STATE_QUEUED;
447                 _job_queue[index].job_handle = _ENCODE_HANDLE(index);
448 
449                 job_handle = _job_queue[index].job_handle;
450             }
451             break;
452         }
453     }
454     return job_handle;
455 }
456 
_recycle_handle(wJob_t job_handle)457 static int _recycle_handle(wJob_t job_handle) {
458     _job_queue_t *jq = _get_job_desc(job_handle);
459 
460     if (jq == NULL) {
461         return ERROR;
462     } else if ((jq->job_state == JOB_STATE_CANCELLED) || (jq->job_state == JOB_STATE_ERROR) ||
463             (jq->job_state == JOB_STATE_CORRUPTED) || (jq->job_state == JOB_STATE_COMPLETED)) {
464         if (jq->print_ifc != NULL) {
465             jq->print_ifc->destroy(jq->print_ifc);
466         }
467 
468         jq->print_ifc = NULL;
469         if (jq->status_ifc != NULL) {
470             jq->status_ifc->destroy(jq->status_ifc);
471         }
472         jq->status_ifc = NULL;
473         if (jq->job_params.useragent != NULL) {
474             free((void *) jq->job_params.useragent);
475         }
476         if (jq->job_params.certificate != NULL) {
477             free((void *) jq->job_params.certificate);
478         }
479         free(jq->printer_addr);
480         jq->job_state = JOB_STATE_FREE;
481         if (jq->job_debug_fd != -1) {
482             close(jq->job_debug_fd);
483         }
484         jq->job_debug_fd = -1;
485         if (jq->page_debug_fd != -1) {
486             close(jq->page_debug_fd);
487         }
488         jq->page_debug_fd = -1;
489         jq->debug_path[0] = 0;
490         if (jq->certificate) {
491             free(jq->certificate);
492             jq->certificate = NULL;
493         }
494         return OK;
495     } else {
496         return ERROR;
497     }
498 }
499 
500 /*
501  * Stops the job status thread if it exists
502  */
_stop_status_thread(_job_queue_t * jq)503 static int _stop_status_thread(_job_queue_t *jq) {
504     if (!pthread_equal(_job_status_tid, pthread_self()) && (jq && jq->status_ifc)) {
505         (jq->status_ifc->stop)(jq->status_ifc);
506         _unlock();
507         pthread_join(_job_status_tid, 0);
508         _lock();
509         _job_status_tid = pthread_self();
510         return OK;
511     } else {
512         return ERROR;
513     }
514 }
515 
516 /*
517  * Handles a new status message from the printer. Based on the status of wprint and the printer,
518  * this function will start/end a job, send another page, or return blocking errors.
519  */
_job_status_callback(const printer_state_dyn_t * new_status,const printer_state_dyn_t * old_status,void * param)520 static void _job_status_callback(const printer_state_dyn_t *new_status,
521         const printer_state_dyn_t *old_status, void *param) {
522     wprint_job_callback_params_t cb_param;
523     _job_queue_t *jq = (_job_queue_t *) param;
524     unsigned int i, blocked_reasons;
525     print_status_t statusnew, statusold;
526 
527     statusnew = new_status->printer_status & ~PRINTER_IDLE_BIT;
528     statusold = old_status->printer_status & ~PRINTER_IDLE_BIT;
529     cb_param.certificate = jq->certificate;
530     cb_param.certificate_len = jq->certificate_len;
531 
532     LOGD("_job_status_callback(): current printer state: %d", statusnew);
533     blocked_reasons = 0;
534     for (i = 0; i <= PRINT_STATUS_MAX_STATE; i++) {
535         if (new_status->printer_reasons[i] == PRINT_STATUS_MAX_STATE) {
536             break;
537         }
538         LOGD("_job_status_callback(): blocking reason %d: %d", i, new_status->printer_reasons[i]);
539         blocked_reasons |= (1 << new_status->printer_reasons[i]);
540     }
541 
542     switch (statusnew) {
543         case PRINT_STATUS_UNKNOWN:
544             if ((new_status->printer_reasons[0] == PRINT_STATUS_OFFLINE)
545                     || (new_status->printer_reasons[0] == PRINT_STATUS_UNKNOWN)) {
546                 sem_post(&_job_start_wait_sem);
547                 sem_post(&_job_end_wait_sem);
548                 _lock();
549                 if ((new_status->printer_reasons[0] == PRINT_STATUS_OFFLINE)
550                         && ((jq->print_ifc != NULL) && (jq->print_ifc->enable_timeout != NULL))) {
551                     jq->print_ifc->enable_timeout(jq->print_ifc, 1);
552                 }
553                 _unlock();
554             }
555             break;
556 
557         case PRINT_STATUS_IDLE:
558             if ((statusold > PRINT_STATUS_IDLE) || (statusold == PRINT_STATUS_CANCELLED)) {
559                 // Print is over but the job wasn't ended correctly
560                 if (jq->is_dir && !jq->last_page_seen) {
561                     wprintPage(jq->job_handle, jq->num_pages + 1, NULL, true, false, 0, 0, 0, 0);
562                 }
563                 sem_post(&_job_end_wait_sem);
564             }
565             break;
566 
567         case PRINT_STATUS_CANCELLED:
568             sem_post(&_job_start_wait_sem);
569             if ((jq->print_ifc != NULL) && (jq->print_ifc->enable_timeout != NULL)) {
570                 jq->print_ifc->enable_timeout(jq->print_ifc, 1);
571             }
572             if (statusold != PRINT_STATUS_CANCELLED) {
573                 LOGI("status requested job cancel");
574                 if (new_status->printer_reasons[0] == PRINT_STATUS_OFFLINE) {
575                     sem_post(&_job_start_wait_sem);
576                     sem_post(&_job_end_wait_sem);
577                     if ((jq->print_ifc != NULL) && (jq->print_ifc->enable_timeout != NULL)) {
578                         jq->print_ifc->enable_timeout(jq->print_ifc, 1);
579                     }
580                 }
581                 _lock();
582                 jq->job_params.cancelled = true;
583                 _unlock();
584             }
585             if (new_status->printer_reasons[0] == PRINT_STATUS_OFFLINE) {
586                 sem_post(&_job_start_wait_sem);
587                 sem_post(&_job_end_wait_sem);
588             }
589             break;
590 
591         case PRINT_STATUS_PRINTING:
592             sem_post(&_job_start_wait_sem);
593             _lock();
594             if ((jq->job_state != JOB_STATE_RUNNING) || (jq->blocked_reasons != blocked_reasons)) {
595                 jq->job_state = JOB_STATE_RUNNING;
596                 jq->blocked_reasons = blocked_reasons;
597                 if (jq->cb_fn) {
598                     cb_param.state = JOB_RUNNING;
599                     cb_param.blocked_reasons = jq->blocked_reasons;
600                     cb_param.job_done_result = OK;
601 
602                     jq->cb_fn(jq->job_handle, (void *) &cb_param);
603                 }
604             }
605             _unlock();
606             break;
607 
608         case PRINT_STATUS_UNABLE_TO_CONNECT:
609             sem_post(&_job_start_wait_sem);
610             _lock();
611             _stop_status_thread(jq);
612 
613             jq->blocked_reasons = blocked_reasons;
614             jq->job_params.cancelled = true;
615             jq->job_state = JOB_STATE_ERROR;
616             if (jq->cb_fn) {
617                 cb_param.state = JOB_DONE;
618                 cb_param.blocked_reasons = blocked_reasons;
619                 cb_param.job_done_result = ERROR;
620 
621                 jq->cb_fn(jq->job_handle, (void *) &cb_param);
622             }
623 
624             if (jq->print_ifc != NULL) {
625                 jq->print_ifc->destroy(jq->print_ifc);
626                 jq->print_ifc = NULL;
627             }
628 
629             if (jq->status_ifc != NULL) {
630                 jq->status_ifc->destroy(jq->status_ifc);
631                 jq->status_ifc = NULL;
632             }
633 
634             _unlock();
635             sem_post(&_job_end_wait_sem);
636             break;
637 
638         default:
639             // an error has occurred, report it back to the client
640             sem_post(&_job_start_wait_sem);
641             _lock();
642 
643             if ((jq->job_state != JOB_STATE_BLOCKED) || (jq->blocked_reasons != blocked_reasons)) {
644                 jq->job_state = JOB_STATE_BLOCKED;
645                 jq->blocked_reasons = blocked_reasons;
646                 if (jq->cb_fn) {
647                     cb_param.state = JOB_BLOCKED;
648                     cb_param.blocked_reasons = blocked_reasons;
649                     cb_param.job_done_result = OK;
650 
651                     jq->cb_fn(jq->job_handle, (void *) &cb_param);
652                 }
653             }
654             _unlock();
655             break;
656     }
657 }
658 
_job_status_thread(void * param)659 static void *_job_status_thread(void *param) {
660     _job_queue_t *jq = (_job_queue_t *) param;
661     (jq->status_ifc->start)(jq->status_ifc, _job_status_callback, param);
662     return NULL;
663 }
664 
_start_status_thread(_job_queue_t * jq)665 static int _start_status_thread(_job_queue_t *jq) {
666     sigset_t allsig, oldsig;
667     int result = ERROR;
668 
669     if ((jq == NULL) || (jq->status_ifc == NULL)) {
670         return result;
671     }
672 
673     result = OK;
674     sigfillset(&allsig);
675 #if CHECK_PTHREAD_SIGMASK_STATUS
676     result = pthread_sigmask(SIG_SETMASK, &allsig, &oldsig);
677 #else // else CHECK_PTHREAD_SIGMASK_STATUS
678     pthread_sigmask(SIG_SETMASK, &allsig, &oldsig);
679 #endif // CHECK_PTHREAD_SIGMASK_STATUS
680     if (result == OK) {
681         result = pthread_create(&_job_status_tid, 0, _job_status_thread, jq);
682         if ((result == ERROR) && (_job_status_tid != pthread_self())) {
683 #if USE_PTHREAD_CANCEL
684             pthread_cancel(_job_status_tid);
685 #else // else USE_PTHREAD_CANCEL
686             pthread_kill(_job_status_tid, SIGKILL);
687 #endif // USE_PTHREAD_CANCEL
688             _job_status_tid = pthread_self();
689         }
690     }
691 
692     if (result == OK) {
693         sched_yield();
694 #if CHECK_PTHREAD_SIGMASK_STATUS
695         result = pthread_sigmask(SIG_SETMASK, &oldsig, 0);
696 #else // else CHECK_PTHREAD_SIGMASK_STATUS
697         pthread_sigmask(SIG_SETMASK, &oldsig, 0);
698 #endif // CHECK_PTHREAD_SIGMASK_STATUS
699     }
700     return result;
701 }
702 
703 /*
704  * Return true unless the server gave an unexpected certificate
705  */
_is_certificate_allowed(_job_queue_t * jq)706 static bool _is_certificate_allowed(_job_queue_t *jq) {
707     int result = true;
708 
709     // Compare certificates if both are known
710     if (jq->job_params.certificate && jq->certificate) {
711         if (jq->job_params.certificate_len != jq->certificate_len) {
712             LOGD("_is_certificate_allowed: certificate length mismatch allowed=%d, received=%d",
713                 jq->job_params.certificate_len, jq->certificate_len);
714             result = false;
715         } else if (0 != memcmp(jq->job_params.certificate, jq->certificate, jq->certificate_len)) {
716             LOGD("_is_certificate_allowed: certificate content mismatch");
717             result = false;
718         } else {
719             LOGD("_is_certificate_allowed: certificate match, len=%d",
720                 jq->job_params.certificate_len);
721         }
722     }
723 
724     return result;
725 }
726 
727 /*
728  * Callback from lower layers containing certificate data, if any.
729  */
_validate_certificate(wprint_connect_info_t * connect_info,uint8 * data,int data_len)730 static int _validate_certificate(wprint_connect_info_t *connect_info, uint8 *data, int data_len) {
731     _job_queue_t *jq = connect_info->user;
732     LOGD("_validate_certificate: %s://%s:%d%s handling server cert len=%d for job %ld",
733         connect_info->uri_scheme, connect_info->printer_addr, connect_info->port_num,
734         connect_info->uri_path, data_len, jq->job_handle);
735 
736     // Free any old certificate we have and save new certificate data
737     if (jq->certificate) {
738         free(jq->certificate);
739         jq->certificate = NULL;
740     }
741     jq->certificate = (uint8 *)malloc(data_len);
742     int error = 0;
743     if (jq->certificate == NULL) {
744         LOGD("_validate_certificate: malloc failed");
745         error = -1;
746     } else {
747         memcpy(jq->certificate, data, data_len);
748         jq->certificate_len = data_len;
749         if (!_is_certificate_allowed(jq)) {
750             LOGD("_validate_certificate: received certificate disallowed.");
751             error = -1;
752         }
753     }
754     return error;
755 }
756 
757 /*
758  * Initialize the status interface (so we can use it to query for printer status.
759  */
_initialize_status_ifc(_job_queue_t * jq)760 static void _initialize_status_ifc(_job_queue_t *jq) {
761     wprint_connect_info_t connect_info;
762     connect_info.printer_addr = jq->printer_addr;
763     connect_info.uri_path = jq->printer_uri;
764     connect_info.port_num = jq->port_num;
765     if (jq->use_secure_uri) {
766         connect_info.uri_scheme = IPPS_PREFIX;
767         connect_info.user = jq;
768         connect_info.validate_certificate = _validate_certificate;
769     } else {
770         connect_info.uri_scheme = IPP_PREFIX;
771         connect_info.validate_certificate = NULL;
772     }
773     connect_info.timeout = DEFAULT_IPP_TIMEOUT;
774 
775     // Initialize the status interface with this connection info
776     jq->status_ifc->init(jq->status_ifc, &connect_info);
777 }
778 
779 /*
780  * Runs a print job. Contains logic for what to do given different printer statuses.
781  */
_job_thread(void * param)782 static void *_job_thread(void *param) {
783     wprint_job_callback_params_t cb_param = { 0 };
784     _msg_t msg;
785     wJob_t job_handle;
786     _job_queue_t *jq;
787     _page_t page;
788     int i;
789     status_t job_result;
790     int corrupted = 0;
791 
792     while (OK == msgQReceive(_msgQ, (char *) &msg, sizeof(msg), WAIT_FOREVER)) {
793         if (msg.id == MSG_RUN_JOB) {
794             LOGI("_job_thread(): Received message: MSG_RUN_JOB");
795         } else {
796             LOGI("_job_thread(): Received message: MSG_QUIT");
797         }
798 
799         if (msg.id == MSG_QUIT) {
800             break;
801         }
802 
803         job_handle = msg.job_id;
804 
805         //  check if this is a valid job_handle that is still active
806         _lock();
807 
808         jq = _get_job_desc(job_handle);
809 
810         //  set state to running and invoke the plugin, there is one
811         if (jq) {
812             if (jq->job_state != JOB_STATE_QUEUED) {
813                 _unlock();
814                 continue;
815             }
816             corrupted = 0;
817             job_result = OK;
818             jq->job_params.plugin_data = NULL;
819 
820             // clear out the semaphore just in case
821             while (sem_trywait(&_job_start_wait_sem) == OK) {
822             }
823             while (sem_trywait(&_job_end_wait_sem) == OK) {
824             }
825 
826             // initialize the status ifc
827             if (jq->status_ifc != NULL) {
828                 _initialize_status_ifc(jq);
829             }
830             // wait for the printer to be idle
831             if ((jq->status_ifc != NULL) && (jq->status_ifc->get_status != NULL)) {
832                 int retry = 0;
833                 bool idle = false;
834                 printer_state_dyn_t printer_state;
835                 while (!idle) {
836                     print_status_t status;
837                     jq->status_ifc->get_status(jq->status_ifc, &printer_state);
838                     status = printer_state.printer_status & ~PRINTER_IDLE_BIT;
839 
840                     // Pass along any certificate received in future callbacks
841                     cb_param.certificate = jq->certificate;
842                     cb_param.certificate_len = jq->certificate_len;
843 
844                     // Presume we found an idle state
845                     idle = true;
846                     if (status == PRINT_STATUS_IDLE) {
847                         printer_state.printer_status = PRINT_STATUS_IDLE;
848                         jq->blocked_reasons = 0;
849                     } else if (status == PRINT_STATUS_UNKNOWN
850                             && printer_state.printer_reasons[0] == PRINT_STATUS_UNKNOWN) {
851                         // no status available, break out and hope for the best
852                         printer_state.printer_status = PRINT_STATUS_IDLE;
853                     } else if ((status == PRINT_STATUS_UNKNOWN || status == PRINT_STATUS_SVC_REQUEST)
854                             && ((printer_state.printer_reasons[0] == PRINT_STATUS_UNABLE_TO_CONNECT)
855                                 || (printer_state.printer_reasons[0] == PRINT_STATUS_OFFLINE))) {
856                         if (_is_certificate_allowed(jq)) {
857                             LOGD("%s: Received an Unable to Connect message", __func__);
858                             jq->blocked_reasons = BLOCKED_REASON_UNABLE_TO_CONNECT;
859                         } else {
860                             LOGD("%s: Bad certificate", __func__);
861                             jq->blocked_reasons = BLOCKED_REASON_BAD_CERTIFICATE;
862                         }
863                     } else if (printer_state.printer_status & PRINTER_IDLE_BIT) {
864                         LOGD("%s: printer blocked but appears to be in an idle state. "
865                                 "Allowing job to proceed", __func__);
866                         printer_state.printer_status = PRINT_STATUS_IDLE;
867                     } else if (retry >= MAX_IDLE_WAIT) {
868                         jq->blocked_reasons |= BLOCKED_REASONS_PRINTER_BUSY;
869                     } else if (!jq->job_params.cancelled) {
870                         // Printer still appears busy, so stay in loop, notify, and poll again.
871                         idle = false;
872                         int blocked_reasons = 0;
873                         for (i = 0; i <= PRINT_STATUS_MAX_STATE; i++) {
874                             if (printer_state.printer_reasons[i] == PRINT_STATUS_MAX_STATE) {
875                                 break;
876                             }
877                             blocked_reasons |= (1 << printer_state.printer_reasons[i]);
878                         }
879                         if (blocked_reasons == 0) {
880                             blocked_reasons |= BLOCKED_REASONS_PRINTER_BUSY;
881                         }
882 
883                         if ((jq->job_state != JOB_STATE_BLOCKED)
884                                 || (jq->blocked_reasons != blocked_reasons)) {
885                             jq->job_state = JOB_STATE_BLOCKED;
886                             jq->blocked_reasons = blocked_reasons;
887                             if (jq->cb_fn) {
888                                 cb_param.state = JOB_BLOCKED;
889                                 cb_param.blocked_reasons = blocked_reasons;
890                                 cb_param.job_done_result = OK;
891 
892                                 jq->cb_fn(jq->job_handle, (void *) &cb_param);
893                             }
894                         }
895                         _unlock();
896                         sleep(1);
897                         _lock();
898                         retry++;
899                     }
900                 }
901 
902                 if (jq->job_params.cancelled) {
903                     job_result = CANCELLED;
904                 } else {
905                     job_result = (((printer_state.printer_status & ~PRINTER_IDLE_BIT) ==
906                             PRINT_STATUS_IDLE) ? OK : ERROR);
907                 }
908             }
909 
910             _job_status_tid = pthread_self();
911             if (job_result == OK) {
912                 if (jq->print_ifc) {
913                     job_result = jq->print_ifc->init(jq->print_ifc, jq->printer_addr,
914                             jq->port_num, jq->printer_uri, jq->use_secure_uri);
915                     if (job_result == ERROR) {
916                         jq->blocked_reasons = BLOCKED_REASON_UNABLE_TO_CONNECT;
917                     }
918                 }
919             }
920             if (job_result == OK) {
921                 _start_status_thread(jq);
922             }
923 
924             /*  call the plugin's start_job method, if no other job is running
925              use callback to notify the client */
926 
927             if ((job_result == OK) && jq->cb_fn) {
928                 cb_param.state = JOB_RUNNING;
929                 cb_param.blocked_reasons = 0;
930                 cb_param.job_done_result = OK;
931 
932                 jq->cb_fn(job_handle, (void *) &cb_param);
933             }
934 
935             jq->job_params.page_num = -1;
936             if (job_result == OK) {
937                 if (jq->print_ifc != NULL) {
938                     LOGD("_job_thread: Calling validate_job");
939                     if (jq->print_ifc->validate_job != NULL) {
940                         job_result = jq->print_ifc->validate_job(jq->print_ifc, &jq->job_params);
941                     }
942 
943                     /* PDF format plugin's start_job and end_job are to be called for each copy,
944                      * inside the for-loop for num_copies.
945                      */
946 
947                     // Do not call start_job unless validate_job returned OK
948                     if ((job_result == OK) && (jq->print_ifc->start_job != NULL) &&
949                             (strcmp(jq->job_params.print_format, PRINT_FORMAT_PDF) != 0)) {
950                         jq->print_ifc->start_job(jq->print_ifc, &jq->job_params);
951                     }
952                 }
953 
954                 // Do not call start_job unless validate_job returned OK
955                 if (job_result == OK && jq->plugin->start_job != NULL) {
956                     job_result = jq->plugin->start_job(job_handle, (void *) &_wprint_ifc,
957                             (void *) jq->print_ifc, &(jq->job_params));
958                 }
959             }
960 
961             if (job_result == OK) {
962                 jq->job_params.page_num = 0;
963             }
964 
965             // multi-page print job
966             if (jq->is_dir && (job_result == OK)) {
967                 int per_copy_page_num;
968                 for (i = 0; (i < jq->job_params.num_copies) &&
969                         ((job_result == OK) || (job_result == CORRUPT)) &&
970                         (!jq->job_params.cancelled); i++) {
971                     if ((i > 0) &&
972                             jq->job_params.copies_supported &&
973                             (strcmp(jq->job_params.print_format, PRINT_FORMAT_PDF) == 0)) {
974                         LOGD("_job_thread multi_page: breaking out copies supported");
975                         break;
976                     }
977                     bool pdf_printed = false;
978                     if (jq->print_ifc->start_job != NULL &&
979                             (strcmp(jq->job_params.print_format, PRINT_FORMAT_PDF) == 0)) {
980                         jq->print_ifc->start_job(jq->print_ifc, &jq->job_params);
981                     }
982 
983                     per_copy_page_num = 0;
984                     jq->job_state = JOB_STATE_RUNNING;
985 
986                     // while there is a page to print
987                     _unlock();
988 
989                     while (OK == msgQReceive(jq->pageQ, (char *) &page, sizeof(page),
990                             WAIT_FOREVER)) {
991                         _lock();
992 
993                         // check for any printing problems so far
994                         if (jq->print_ifc->check_status) {
995                             if (jq->print_ifc->check_status(jq->print_ifc) == ERROR) {
996                                 job_result = ERROR;
997                                 break;
998                             }
999                         }
1000 
1001                         /* take empty filename as cue to break out of the loop
1002                          * but we have to do last_page processing
1003                          */
1004 
1005                         // all copies are clubbed together as a single print job
1006                         if (page.last_page && ((i == jq->job_params.num_copies - 1) ||
1007                                 (jq->job_params.copies_supported &&
1008                                         strcmp(jq->job_params.print_format,
1009                                                 PRINT_FORMAT_PDF) == 0))) {
1010                             jq->job_params.last_page = page.last_page;
1011                         } else {
1012                             jq->job_params.last_page = false;
1013                         }
1014 
1015                         if (strlen(page.filename) > 0) {
1016                             per_copy_page_num++;
1017                             {
1018                                 jq->job_params.page_num++;
1019                             }
1020                             if (page.pdf_page) {
1021                                 jq->job_params.page_num = page.page_num;
1022                             } else {
1023                                 jq->job_params.page_num = per_copy_page_num;
1024                             }
1025 
1026                             // setup page margin information
1027                             jq->job_params.print_top_margin += page.top_margin;
1028                             jq->job_params.print_left_margin += page.left_margin;
1029                             jq->job_params.print_right_margin += page.right_margin;
1030                             jq->job_params.print_bottom_margin += page.bottom_margin;
1031 
1032                             jq->job_params.copy_num = (i + 1);
1033                             jq->job_params.copy_page_num = page.page_num;
1034                             jq->job_params.page_backside = !(per_copy_page_num & 0x1);
1035                             jq->job_params.page_corrupted = (page.corrupted ? 1 : 0);
1036                             jq->job_params.page_printing = true;
1037                             _unlock();
1038 
1039                             if (!page.corrupted) {
1040                                 LOGD("_job_thread(): page not corrupt, calling plugin's print_page"
1041                                         " function for page #%d", page.page_num);
1042                                 if (strcmp(jq->job_params.print_format, PRINT_FORMAT_PDF) != 0) {
1043                                     job_result = jq->plugin->print_page(&(jq->job_params),
1044                                             jq->mime_type,
1045                                             page.filename);
1046                                 } else if (!pdf_printed) {
1047                                     // for PDF plugin, print_page prints entire document,
1048                                     // so need to be called only once
1049                                     job_result = jq->plugin->print_page(&(jq->job_params),
1050                                             jq->mime_type,
1051                                             page.filename);
1052                                     pdf_printed = true;
1053                                 }
1054                             } else {
1055                                 LOGD("_job_thread(): page IS corrupt, printing blank page for "
1056                                         "page #%d", page.page_num);
1057                                 job_result = CORRUPT;
1058                                 if ((jq->job_params.duplex != DUPLEX_MODE_NONE) &&
1059                                         (jq->plugin->print_blank_page != NULL)) {
1060                                     jq->plugin->print_blank_page(job_handle, &(jq->job_params));
1061                                 }
1062                             }
1063                             _lock();
1064 
1065                             jq->job_params.print_top_margin -= page.top_margin;
1066                             jq->job_params.print_left_margin -= page.left_margin;
1067                             jq->job_params.print_right_margin -= page.right_margin;
1068                             jq->job_params.print_bottom_margin -= page.bottom_margin;
1069                             jq->job_params.page_printing = false;
1070 
1071                             // make sure we only count corrupted pages once
1072                             if (page.corrupted == false) {
1073                                 page.corrupted = ((job_result == CORRUPT) ? true : false);
1074                                 corrupted += (job_result == CORRUPT);
1075                             }
1076                         }
1077 
1078                         // make sure we always print an even number of pages in duplex jobs
1079                         if (page.last_page && (jq->job_params.duplex != DUPLEX_MODE_NONE)
1080                                 && !(jq->job_params.page_backside)
1081                                 && (jq->plugin->print_blank_page != NULL)) {
1082                             _unlock();
1083                             jq->plugin->print_blank_page(job_handle, &(jq->job_params));
1084                             _lock();
1085                         }
1086 
1087                         // if multiple copies are requested, save the contents of the pageQ message
1088                         if (jq->saveQ && !jq->job_params.cancelled && (job_result != ERROR)) {
1089                             job_result = msgQSend(jq->saveQ, (char *) &page,
1090                                     sizeof(page), NO_WAIT, MSG_Q_FIFO);
1091 
1092                             // swap pageQ and saveQ
1093                             if (page.last_page && !jq->job_params.last_page) {
1094                                 msg_q_id tmpQ = jq->pageQ;
1095                                 jq->pageQ = jq->saveQ;
1096                                 jq->saveQ = tmpQ;
1097 
1098                                 // defensive programming
1099                                 while (msgQNumMsgs(tmpQ) > 0) {
1100                                     msgQReceive(tmpQ, (char *) &page, sizeof(page), NO_WAIT);
1101                                     LOGE("pageQ inconsistencies, discarding page #%d, file %s",
1102                                             page.page_num, page.filename);
1103                                 }
1104                             }
1105                         }
1106 
1107                         if (page.last_page || jq->job_params.cancelled) {
1108                             // Leave the sempahore locked
1109                             break;
1110                         }
1111 
1112                         // unlock to go back to the top of the while loop
1113                         _unlock();
1114                     } // while there is another page
1115 
1116                     if ((strcmp(jq->job_params.print_format, PRINT_FORMAT_PDF) == 0) &&
1117                             (jq->print_ifc->end_job)) {
1118                         int end_job_result = jq->print_ifc->end_job(jq->print_ifc);
1119                         if (job_result == OK) {
1120                             if (end_job_result == ERROR) {
1121                                 job_result = ERROR;
1122                             } else if (end_job_result == CANCELLED) {
1123                                 job_result = CANCELLED;
1124                             }
1125                         }
1126                     }
1127                 } // for each copy of the job
1128             } else if (job_result == OK) {
1129                 // single page job
1130                 for (i = 0; ((i < jq->job_params.num_copies) && (job_result == OK)); i++) {
1131                     if ((i > 0) && jq->job_params.copies_supported &&
1132                             (strcmp(jq->job_params.print_format, PRINT_FORMAT_PDF) == 0)) {
1133                         LOGD("_job_thread single_page: breaking out copies supported");
1134                         break;
1135                     }
1136 
1137                     // check for any printing problems so far
1138                     if ((jq->print_ifc != NULL) && (jq->print_ifc->check_status)) {
1139                         if (jq->print_ifc->check_status(jq->print_ifc) == ERROR) {
1140                             job_result = ERROR;
1141                             break;
1142                         }
1143                     }
1144 
1145                     jq->job_state = JOB_STATE_RUNNING;
1146                     jq->job_params.page_num++;
1147                     jq->job_params.last_page = (i == (jq->job_params.num_copies - 1));
1148                     jq->job_params.copy_num = (i + 1);
1149                     jq->job_params.copy_page_num = 1;
1150                     jq->job_params.page_corrupted = (job_result == CORRUPT);
1151                     jq->job_params.page_printing = true;
1152 
1153                     _unlock();
1154                     job_result = jq->plugin->print_page(&(jq->job_params), jq->mime_type,
1155                             jq->pathname);
1156 
1157                     if ((jq->job_params.duplex != DUPLEX_MODE_NONE)
1158                             && (jq->plugin->print_blank_page != NULL)) {
1159                         jq->plugin->print_blank_page(job_handle,
1160                                 &(jq->job_params));
1161                     }
1162 
1163                     _lock();
1164                     jq->job_params.page_printing = false;
1165 
1166                     corrupted += (job_result == CORRUPT);
1167                 } // for each copy
1168             }
1169 
1170             // if we started the job end it
1171             if (jq->job_params.page_num >= 0) {
1172                 // if the job was cancelled without sending anything through, print a blank sheet
1173                 if ((jq->job_params.page_num == 0)
1174                         && (jq->plugin->print_blank_page != NULL)) {
1175                     jq->plugin->print_blank_page(job_handle, &(jq->job_params));
1176                 }
1177                 if (jq->plugin->end_job != NULL) {
1178                     jq->plugin->end_job(&(jq->job_params));
1179                 }
1180                 if ((jq->print_ifc != NULL) && (jq->print_ifc->end_job) &&
1181                         (strcmp(jq->job_params.print_format, PRINT_FORMAT_PDF) != 0)) {
1182                     int end_job_result = jq->print_ifc->end_job(jq->print_ifc);
1183                     if (job_result == OK) {
1184                         if (end_job_result == ERROR) {
1185                             job_result = ERROR;
1186                         } else if (end_job_result == CANCELLED) {
1187                             job_result = CANCELLED;
1188                         }
1189                     }
1190                 }
1191             }
1192 
1193             // if we started to print, wait for idle
1194             if ((jq->job_params.page_num > 0) && (jq->status_ifc != NULL)) {
1195                 int retry, result;
1196                 _unlock();
1197 
1198                 for (retry = 0, result = ERROR; ((result == ERROR) && (retry <= MAX_START_WAIT));
1199                         retry++) {
1200                     if (retry != 0) {
1201                         sleep(1);
1202                     }
1203                     result = sem_trywait(&_job_start_wait_sem);
1204                 }
1205 
1206                 if (result == OK) {
1207                     for (retry = 0, result = ERROR; ((result == ERROR) && (retry <= MAX_DONE_WAIT));
1208                             retry++) {
1209                         if (retry != 0) {
1210                             _lock();
1211                             if (jq->job_params.cancelled && !jq->cancel_ok) {
1212                                 /* The user tried to cancel and it either didn't go through
1213                                  * or the printer doesn't support cancel through an OID.
1214                                  * Either way it's pointless to sit here waiting for idle when
1215                                  * may never come, so we'll bail out early
1216                                  */
1217                                 retry = (MAX_DONE_WAIT + 1);
1218                             }
1219                             _unlock();
1220                             sleep(1);
1221                             if (retry == MAX_DONE_WAIT) {
1222                                 _lock();
1223                                 if (!jq->job_params.cancelled &&
1224                                         (jq->blocked_reasons
1225                                                 & (BLOCKED_REASON_OUT_OF_PAPER
1226                                                         | BLOCKED_REASON_JAMMED
1227                                                         | BLOCKED_REASON_DOOR_OPEN))) {
1228                                     retry = (MAX_DONE_WAIT - 1);
1229                                 }
1230                                 _unlock();
1231                             }
1232                         }
1233                         result = sem_trywait(&_job_end_wait_sem);
1234                     }
1235                 } else {
1236                     LOGD("_job_thread(): the job never started");
1237                 }
1238                 _lock();
1239             }
1240 
1241             // make sure page_num doesn't stay as a negative number
1242             jq->job_params.page_num = MAX(0, jq->job_params.page_num);
1243             _stop_status_thread(jq);
1244 
1245             if (corrupted != 0) {
1246                 job_result = CORRUPT;
1247             }
1248 
1249             LOGI("job_thread(): with job_state value: %d ", jq->job_state);
1250             if ((jq->job_state == JOB_STATE_COMPLETED) || (jq->job_state == JOB_STATE_ERROR)
1251                     || (jq->job_state == JOB_STATE_CANCELLED)
1252                     || (jq->job_state == JOB_STATE_CORRUPTED)
1253                     || (jq->job_state == JOB_STATE_FREE)) {
1254                 LOGI("_job_thread(): job finished early: do not send callback again");
1255             } else {
1256                 switch (job_result) {
1257                     case OK:
1258                         if (!jq->job_params.cancelled) {
1259                             jq->job_state = JOB_STATE_COMPLETED;
1260                             jq->blocked_reasons = 0;
1261                             break;
1262                         } else {
1263                             job_result = CANCELLED;
1264                         }
1265                     case CANCELLED:
1266                         jq->job_state = JOB_STATE_CANCELLED;
1267                         jq->blocked_reasons = BLOCKED_REASONS_CANCELLED;
1268                         if (!jq->cancel_ok) {
1269                             jq->blocked_reasons |= BLOCKED_REASON_PARTIAL_CANCEL;
1270                         }
1271                         break;
1272                     case CORRUPT:
1273                         LOGE("_job_thread(): %d file(s) in the job were corrupted", corrupted);
1274                         jq->job_state = JOB_STATE_CORRUPTED;
1275                         jq->blocked_reasons = 0;
1276                         break;
1277                     case ERROR:
1278                     default:
1279                         LOGE("_job_thread(): ERROR plugin->start_job(%ld): %s => %s", job_handle,
1280                                 jq->mime_type, jq->job_params.print_format);
1281                         job_result = ERROR;
1282                         jq->job_state = JOB_STATE_ERROR;
1283                         break;
1284                 } // job_result
1285 
1286                 // end of job callback
1287                 if (jq->cb_fn) {
1288                     cb_param.state = JOB_DONE;
1289                     cb_param.blocked_reasons = jq->blocked_reasons;
1290                     cb_param.job_done_result = job_result;
1291 
1292                     jq->cb_fn(job_handle, (void *) &cb_param);
1293                 }
1294 
1295                 if (jq->print_ifc != NULL) {
1296                     jq->print_ifc->destroy(jq->print_ifc);
1297                     jq->print_ifc = NULL;
1298                 }
1299 
1300                 if (jq->status_ifc != NULL) {
1301                     jq->status_ifc->destroy(jq->status_ifc);
1302                     jq->status_ifc = NULL;
1303                 }
1304             }
1305         } else {
1306             LOGI("_job_thread(): job %ld not in queue .. maybe cancelled", job_handle);
1307         }
1308 
1309         _unlock();
1310         LOGI("_job_thread(): job finished: %ld", job_handle);
1311     }
1312 
1313     sem_post(&_job_end_wait_sem);
1314     return NULL;
1315 }
1316 
1317 /*
1318  * Starts the wprint background job thread
1319  */
_start_thread(void)1320 static int _start_thread(void) {
1321     sigset_t allsig, oldsig;
1322     int result;
1323 
1324     _job_tid = pthread_self();
1325 
1326     result = OK;
1327     sigfillset(&allsig);
1328 #if CHECK_PTHREAD_SIGMASK_STATUS
1329     result = pthread_sigmask(SIG_SETMASK, &allsig, &oldsig);
1330 #else // else CHECK_PTHREAD_SIGMASK_STATUS
1331     pthread_sigmask(SIG_SETMASK, &allsig, &oldsig);
1332 #endif // CHECK_PTHREAD_SIGMASK_STATUS
1333     if (result == OK) {
1334         result = pthread_create(&_job_tid, 0, _job_thread, NULL);
1335         if ((result == ERROR) && (_job_tid != pthread_self())) {
1336 #if USE_PTHREAD_CANCEL
1337             pthread_cancel(_job_tid);
1338 #else // else USE_PTHREAD_CANCEL
1339             pthread_kill(_job_tid, SIGKILL);
1340 #endif // USE_PTHREAD_CANCEL
1341             _job_tid = pthread_self();
1342         }
1343     }
1344 
1345     if (result == OK) {
1346         sched_yield();
1347 #if CHECK_PTHREAD_SIGMASK_STATUS
1348         result = pthread_sigmask(SIG_SETMASK, &oldsig, 0);
1349 #else // else CHECK_PTHREAD_SIGMASK_STATUS
1350         pthread_sigmask(SIG_SETMASK, &oldsig, 0);
1351 #endif // CHECK_PTHREAD_SIGMASK_STATUS
1352     }
1353 
1354     return result;
1355 }
1356 
1357 /*
1358  * Waits for the job thread to reach a stopped state
1359  */
_stop_thread(void)1360 static int _stop_thread(void) {
1361     if (!pthread_equal(_job_tid, pthread_self())) {
1362         pthread_join(_job_tid, 0);
1363         _job_tid = pthread_self();
1364         return OK;
1365     } else {
1366         return ERROR;
1367     }
1368 }
1369 
1370 static const wprint_io_plugin_t _file_io_plugin = {
1371         .version = WPRINT_PLUGIN_VERSION(_INTERFACE_MINOR_VERSION),
1372         .port_num = PORT_FILE, .getCapsIFC = NULL, .getStatusIFC = NULL,
1373         .getPrintIFC = _printer_file_connect,};
1374 
1375 static const wprint_io_plugin_t _ipp_io_plugin = {
1376         .version = WPRINT_PLUGIN_VERSION(_INTERFACE_MINOR_VERSION),
1377         .port_num = PORT_IPP, .getCapsIFC = ipp_status_get_capabilities_ifc,
1378         .getStatusIFC = ipp_status_get_monitor_ifc, .getPrintIFC = ipp_get_print_ifc,};
1379 
_setup_io_plugins()1380 static void _setup_io_plugins() {
1381     _io_plugins[0].port_num = PORT_FILE;
1382     _io_plugins[0].io_plugin = &_file_io_plugin;
1383 
1384     _io_plugins[1].port_num = PORT_IPP;
1385     _io_plugins[1].io_plugin = &_ipp_io_plugin;
1386 }
1387 
1388 extern wprint_plugin_t *libwprintplugin_pcl_reg(void);
1389 
1390 extern wprint_plugin_t *libwprintplugin_pdf_reg(void);
1391 
_setup_print_plugins()1392 static void _setup_print_plugins() {
1393     plugin_reset();
1394     plugin_add(libwprintplugin_pcl_reg());
1395     plugin_add(libwprintplugin_pdf_reg());
1396 }
1397 
wprintIsRunning()1398 bool wprintIsRunning() {
1399     return _msgQ != 0;
1400 }
1401 
wprintInit(void)1402 int wprintInit(void) {
1403     int count = 0;
1404 
1405     _setup_print_plugins();
1406     _setup_io_plugins();
1407 
1408     _msgQ = msgQCreate(_MAX_MSGS, sizeof(_msg_t));
1409 
1410     if (!_msgQ) {
1411         LOGE("ERROR: cannot create msgQ");
1412         return ERROR;
1413     }
1414 
1415     sem_init(&_job_end_wait_sem, 0, 0);
1416     sem_init(&_job_start_wait_sem, 0, 0);
1417 
1418     signal(SIGPIPE, SIG_IGN); // avoid broken pipe process shutdowns
1419     pthread_mutexattr_settype(&_q_lock_attr, PTHREAD_MUTEX_RECURSIVE_NP);
1420     pthread_mutex_init(&_q_lock, &_q_lock_attr);
1421 
1422     if (_start_thread() != OK) {
1423         LOGE("could not start job thread");
1424         return ERROR;
1425     }
1426     return count;
1427 }
1428 
1429 static const printer_capabilities_t _default_cap = {.color = true, .borderless = true,
1430         .numSupportedMediaSizes = 0, .numSupportedMediaTrays = 0,
1431         .numSupportedMediaTypes = 0,};
1432 
1433 /*
1434  * Check if a media size is supported
1435  */
is_supported(media_size_t media_size)1436 static bool is_supported(media_size_t media_size) {
1437     int i;
1438     for (i = 0; i < SUPPORTED_MEDIA_SIZE_COUNT; i++) {
1439         if (SupportedMediaSizes[i].media_size == media_size) return true;
1440     }
1441     return false;
1442 }
1443 
1444 /*
1445  * Return true if the specified int array of the supplied length contains a value.
1446  */
int_array_contains(const int * array,int length,int value)1447 static bool int_array_contains(const int *array, int length, int value) {
1448     for (int i = 0; i < length; i++) {
1449         if (array[i] == value) return true;
1450     }
1451     return false;
1452 }
1453 
1454 /*
1455  * Checks printers reported media sizes and validates that wprint supports them
1456  */
_validate_supported_media_sizes(printer_capabilities_t * printer_cap)1457 static void _validate_supported_media_sizes(printer_capabilities_t *printer_cap) {
1458     if (printer_cap == NULL) return;
1459 
1460     if (printer_cap->numSupportedMediaSizes == 0) {
1461         unsigned int i = 0;
1462         printer_cap->supportedMediaSizes[i++] = ISO_A4;
1463         printer_cap->supportedMediaSizes[i++] = US_LETTER;
1464         printer_cap->supportedMediaSizes[i++] = INDEX_CARD_4X6;
1465         printer_cap->supportedMediaSizes[i++] = INDEX_CARD_5X7;
1466         printer_cap->numSupportedMediaSizes = i;
1467     } else {
1468         unsigned int read, write;
1469         for (read = write = 0; read < printer_cap->numSupportedMediaSizes; read++) {
1470             if (is_supported(printer_cap->supportedMediaSizes[read])) {
1471                 printer_cap->supportedMediaSizes[write++] =
1472                         printer_cap->supportedMediaSizes[read];
1473             }
1474         }
1475         printer_cap->numSupportedMediaSizes = write;
1476     }
1477 }
1478 
1479 /*
1480  * Checks printers numSupportedMediaTrays. If none, then add Auto.
1481  */
_validate_supported_media_trays(printer_capabilities_t * printer_cap)1482 static void _validate_supported_media_trays(printer_capabilities_t *printer_cap) {
1483     if (printer_cap == NULL) return;
1484 
1485     if (printer_cap->numSupportedMediaTrays == 0) {
1486         printer_cap->supportedMediaTrays[0] = TRAY_SRC_AUTO_SELECT;
1487         printer_cap->numSupportedMediaTrays = 1;
1488     }
1489 }
1490 
1491 /*
1492  * Add a printer's supported input formats to the capabilities struct
1493  */
_collect_supported_input_formats(printer_capabilities_t * printer_caps)1494 static void _collect_supported_input_formats(printer_capabilities_t *printer_caps) {
1495     unsigned long long input_formats = 0;
1496     plugin_get_passthru_input_formats(&input_formats);
1497 
1498     // remove things the printer can't support
1499     if (!printer_caps->canPrintPDF) {
1500         input_formats &= ~(1 << INPUT_MIME_TYPE_PDF);
1501     }
1502     if (!printer_caps->canPrintPCLm) {
1503         input_formats &= ~(1 << INPUT_MIME_TYPE_PCLM);
1504     }
1505     if (!printer_caps->canPrintPWG) {
1506         input_formats &= ~(1 << INPUT_MIME_TYPE_PWG);
1507     }
1508     printer_caps->supportedInputMimeTypes = input_formats;
1509 }
1510 
1511 /*
1512  * Check the print resolutions supported by the printer and verify that wprint supports them.
1513  * If nothing is found, the desired resolution is selected.
1514  */
_findCloseResolutionSupported(int desiredResolution,int maxResolution,const printer_capabilities_t * printer_cap)1515 static unsigned int _findCloseResolutionSupported(int desiredResolution, int maxResolution,
1516         const printer_capabilities_t *printer_cap) {
1517     int closeResolution = 0;
1518     int closeDifference = 0;
1519     unsigned int index = 0;
1520     for (index = 0; index < printer_cap->numSupportedResolutions; index++) {
1521         int resolution = printer_cap->supportedResolutions[index];
1522         if (resolution == desiredResolution) {
1523             // An exact match wins.. stop looking.
1524             return resolution;
1525         } else {
1526             int difference = abs(desiredResolution - resolution);
1527             if ((closeResolution == 0) || (difference < closeDifference)) {
1528                 if (resolution <= maxResolution) {
1529                     // We found a better match now.. record it but keep looking.
1530                     closeResolution = resolution;
1531                     closeDifference = difference;
1532                 }
1533             }
1534         }
1535     }
1536 
1537     // If we get here we did not find an exact match.
1538     if (closeResolution == 0) {
1539         // We did not find anything.. just pick the desired value.
1540         closeResolution = desiredResolution;
1541     }
1542     return closeResolution;
1543 }
1544 
wprintGetCapabilities(const wprint_connect_info_t * connect_info,printer_capabilities_t * printer_cap)1545 status_t wprintGetCapabilities(const wprint_connect_info_t *connect_info,
1546         printer_capabilities_t *printer_cap) {
1547     LOGD("wprintGetCapabilities: Enter");
1548     status_t result = ERROR;
1549     int index;
1550     int port_num = connect_info->port_num;
1551     const ifc_printer_capabilities_t *caps_ifc = NULL;
1552 
1553     memcpy(printer_cap, &_default_cap, sizeof(printer_capabilities_t));
1554 
1555     caps_ifc = _get_caps_ifc(((port_num == 0) ? PORT_FILE : PORT_IPP));
1556     LOGD("wprintGetCapabilities: after getting caps ifc: %p", caps_ifc);
1557     switch (port_num) {
1558         case PORT_FILE:
1559             printer_cap->duplex = 1;
1560             printer_cap->borderless = 1;
1561             printer_cap->canPrintPCLm = (_default_pcl_type == PCLm);
1562             printer_cap->canPrintPWG = (_default_pcl_type == PCLPWG);
1563             printer_cap->stripHeight = STRIPE_HEIGHT;
1564             result = OK;
1565             break;
1566         default:
1567             break;
1568     }
1569 
1570     if (caps_ifc != NULL) {
1571         caps_ifc->init(caps_ifc, connect_info);
1572         result = caps_ifc->get_capabilities(caps_ifc, printer_cap);
1573         caps_ifc->destroy(caps_ifc);
1574     }
1575 
1576     _validate_supported_media_sizes(printer_cap);
1577     _collect_supported_input_formats(printer_cap);
1578     _validate_supported_media_trays(printer_cap);
1579 
1580     printer_cap->isSupported = (printer_cap->canPrintPCLm || printer_cap->canPrintPDF ||
1581             printer_cap->canPrintPWG);
1582 
1583     if (result == OK) {
1584         LOGD("\tmake: %s", printer_cap->make);
1585         LOGD("\thas color: %d", printer_cap->color);
1586         LOGD("\tcan duplex: %d", printer_cap->duplex);
1587         LOGD("\tcan rotate back page: %d", printer_cap->canRotateDuplexBackPage);
1588         LOGD("\tcan print borderless: %d", printer_cap->borderless);
1589         LOGD("\tcan print pdf: %d", printer_cap->canPrintPDF);
1590         LOGD("\tcan print pclm: %d", printer_cap->canPrintPCLm);
1591         LOGD("\tcan print pwg: %d", printer_cap->canPrintPWG);
1592         LOGD("\tsource application name supported: %d", printer_cap->docSourceAppName);
1593         LOGD("\tsource application version supported: %d", printer_cap->docSourceAppVersion);
1594         LOGD("\tsource os name supported: %d", printer_cap->docSourceOsName);
1595         LOGD("\tsource os version supported: %d", printer_cap->docSourceOsVersion);
1596         LOGD("\tprinter supported: %d", printer_cap->isSupported);
1597         LOGD("\tstrip height: %d", printer_cap->stripHeight);
1598         LOGD("\tinkjet: %d", printer_cap->inkjet);
1599         LOGD("\tresolutions supported:");
1600         for (index = 0; index < printer_cap->numSupportedResolutions; index++) {
1601             LOGD("\t (%d dpi)", printer_cap->supportedResolutions[index]);
1602         }
1603     }
1604     LOGD("wprintGetCapabilities: Exit");
1605     return result;
1606 }
1607 
1608 /*
1609  * Returns a preferred print format supported by the printer
1610  */
_get_print_format(const char * mime_type,const wprint_job_params_t * job_params,const printer_capabilities_t * cap)1611 static char *_get_print_format(const char *mime_type, const wprint_job_params_t *job_params,
1612         const printer_capabilities_t *cap) {
1613     char *print_format = NULL;
1614 
1615     errno = OK;
1616 
1617     if (((strcmp(mime_type, MIME_TYPE_PDF) == 0) && cap->canPrintPDF)) {
1618         // For content type=photo and a printer that supports both PCLm and PDF,
1619         // prefer PCLm over PDF.
1620         if (job_params && (strcasecmp(job_params->docCategory, "photo") == 0) &&
1621                 cap->canPrintPCLm) {
1622             print_format = PRINT_FORMAT_PCLM;
1623             LOGI("_get_print_format(): print_format switched from PDF to PCLm");
1624         } else {
1625             print_format = PRINT_FORMAT_PDF;
1626         }
1627     } else if (cap->canPrintPCLm || cap->canPrintPDF) {
1628         // PCLm is a subset of PDF
1629         print_format = PRINT_FORMAT_PCLM;
1630 #if (USE_PWG_OVER_PCLM != 0)
1631         if (cap->canPrintPWG) {
1632             print_format = PRINT_FORMAT_PWG;
1633         }
1634 #endif // (USE_PWG_OVER_PCLM != 0)
1635     } else if (cap->canPrintPWG) {
1636         print_format = PRINT_FORMAT_PWG;
1637     } else {
1638         errno = EBADRQC;
1639     }
1640 
1641     if (print_format != NULL) {
1642         LOGI("\t_get_print_format(): print_format: %s", print_format);
1643     }
1644 
1645     return print_format;
1646 }
1647 
wprintGetDefaultJobParams(wprint_job_params_t * job_params)1648 status_t wprintGetDefaultJobParams(wprint_job_params_t *job_params) {
1649     status_t result = ERROR;
1650     static const wprint_job_params_t _default_job_params = {.print_format = _DEFAULT_PRINT_FORMAT,
1651             .pcl_type = _DEFAULT_PCL_TYPE, .media_size = US_LETTER, .media_type = MEDIA_PLAIN,
1652             .duplex = DUPLEX_MODE_NONE, .dry_time = DUPLEX_DRY_TIME_NORMAL,
1653             .color_space = COLOR_SPACE_COLOR, .media_tray = TRAY_SRC_AUTO_SELECT,
1654             .pixel_units = DEFAULT_RESOLUTION, .render_flags = 0, .num_copies =1,
1655             .borderless = false, .cancelled = false, .renderInReverseOrder = false,
1656             .ipp_1_0_supported = false, .ipp_2_0_supported = false, .epcl_ipp_supported = false,
1657             .strip_height = STRIPE_HEIGHT, .docCategory = {0},
1658             .copies_supported = false};
1659 
1660     if (job_params == NULL) return result;
1661 
1662     memcpy(job_params, &_default_job_params, sizeof(_default_job_params));
1663 
1664     return OK;
1665 }
1666 
wprintGetFinalJobParams(wprint_job_params_t * job_params,const printer_capabilities_t * printer_cap)1667 status_t wprintGetFinalJobParams(wprint_job_params_t *job_params,
1668         const printer_capabilities_t *printer_cap) {
1669     int i;
1670     status_t result = ERROR;
1671     float margins[NUM_PAGE_MARGINS];
1672 
1673     if (job_params == NULL) {
1674         return result;
1675     }
1676     result = OK;
1677 
1678     job_params->accepts_pclm = printer_cap->canPrintPCLm;
1679     job_params->accepts_pdf = printer_cap->canPrintPDF;
1680     job_params->media_default = printer_cap->mediaDefault;
1681 
1682     if (printer_cap->ePclIppVersion == 1) {
1683         job_params->epcl_ipp_supported = true;
1684     }
1685 
1686     if (printer_cap->canCopy) {
1687         job_params->copies_supported = true;
1688     }
1689 
1690     if (printer_cap->ippVersionMajor == 2) {
1691         job_params->ipp_1_0_supported = true;
1692         job_params->ipp_2_0_supported = true;
1693     } else if (printer_cap->ippVersionMajor == 1) {
1694         job_params->ipp_1_0_supported = true;
1695         job_params->ipp_2_0_supported = false;
1696     }
1697 
1698     if (!printer_cap->color) {
1699         job_params->color_space = COLOR_SPACE_MONO;
1700     }
1701 
1702     if (printer_cap->canPrintPCLm || printer_cap->canPrintPDF) {
1703         job_params->pcl_type = PCLm;
1704 #if (USE_PWG_OVER_PCLM != 0)
1705         if ( printer_cap->canPrintPWG) {
1706             job_params->pcl_type = PCLPWG;
1707         }
1708 #endif // (USE_PWG_OVER_PCLM != 0)
1709     } else if (printer_cap->canPrintPWG) {
1710         job_params->pcl_type = PCLPWG;
1711     }
1712 
1713     LOGD("wprintGetFinalJobParams: Using PCL Type %s", getPCLTypeString(job_params->pcl_type));
1714 
1715     // set strip height
1716     job_params->strip_height = printer_cap->stripHeight;
1717 
1718     // make sure the number of copies is valid
1719     if (job_params->num_copies <= 0) {
1720         job_params->num_copies = 1;
1721     }
1722 
1723     // If printing photo and HIGH quality is supported, specify it.
1724     if (strcasecmp(job_params->docCategory, "photo") == 0 && int_array_contains(
1725             printer_cap->supportedQuality, printer_cap->numSupportedQuality, IPP_QUALITY_HIGH)) {
1726         job_params->print_quality = IPP_QUALITY_HIGH;
1727     }
1728 
1729     // confirm that the media size is supported
1730     for (i = 0; i < printer_cap->numSupportedMediaSizes; i++) {
1731         if (job_params->media_size == printer_cap->supportedMediaSizes[i]) {
1732             break;
1733         }
1734     }
1735 
1736     if (i >= printer_cap->numSupportedMediaSizes) {
1737         job_params->media_size = ISO_A4;
1738         job_params->media_tray = TRAY_SRC_AUTO_SELECT;
1739     }
1740 
1741     // check that we support the media tray
1742     for (i = 0; i < printer_cap->numSupportedMediaTrays; i++) {
1743         if (job_params->media_tray == printer_cap->supportedMediaTrays[i]) {
1744             break;
1745         }
1746     }
1747 
1748     // media tray not supported, default to automatic
1749     if (i >= printer_cap->numSupportedMediaTrays) {
1750         job_params->media_tray = TRAY_SRC_AUTO_SELECT;
1751     }
1752 
1753     if (printer_cap->isMediaSizeNameSupported == true) {
1754         job_params->media_size_name = true;
1755     } else {
1756         job_params->media_size_name = false;
1757     }
1758 
1759     // verify borderless setting
1760     if ((job_params->borderless == true) && !printer_cap->borderless) {
1761         job_params->borderless = false;
1762     }
1763 
1764     // borderless and margins don't get along
1765     if (job_params->borderless &&
1766             ((job_params->job_top_margin > 0.0f) || (job_params->job_left_margin > 0.0f) ||
1767                     (job_params->job_right_margin > 0.0f)
1768                     || (job_params->job_bottom_margin > 0.0f))) {
1769         job_params->borderless = false;
1770     }
1771 
1772     // verify duplex setting
1773     if ((job_params->duplex != DUPLEX_MODE_NONE) && !printer_cap->duplex) {
1774         job_params->duplex = DUPLEX_MODE_NONE;
1775     }
1776 
1777     // borderless and duplex don't get along either
1778     if (job_params->borderless && (job_params->duplex != DUPLEX_MODE_NONE)) {
1779         job_params->duplex = DUPLEX_MODE_NONE;
1780     }
1781 
1782     if ((job_params->duplex == DUPLEX_MODE_BOOK)
1783             && !printer_cap->canRotateDuplexBackPage) {
1784         job_params->render_flags |= RENDER_FLAG_ROTATE_BACK_PAGE;
1785     }
1786 
1787     if (job_params->render_flags & RENDER_FLAG_ROTATE_BACK_PAGE) {
1788         LOGD("wprintGetFinalJobParams: Duplex is on and device needs back page rotated.");
1789     }
1790 
1791     if ((job_params->duplex == DUPLEX_MODE_NONE) && !printer_cap->faceDownTray) {
1792         job_params->renderInReverseOrder = true;
1793     } else {
1794         job_params->renderInReverseOrder = false;
1795     }
1796 
1797     if (job_params->render_flags & RENDER_FLAG_AUTO_SCALE) {
1798         job_params->render_flags |= AUTO_SCALE_RENDER_FLAGS;
1799     } else if (job_params->render_flags & RENDER_FLAG_AUTO_FIT) {
1800         job_params->render_flags |= AUTO_FIT_RENDER_FLAGS;
1801     }
1802 
1803     job_params->pixel_units = _findCloseResolutionSupported(DEFAULT_RESOLUTION,
1804             MAX_SUPPORTED_RESOLUTION, printer_cap);
1805 
1806     printable_area_get_default_margins(job_params, printer_cap, &margins[TOP_MARGIN],
1807             &margins[LEFT_MARGIN], &margins[RIGHT_MARGIN], &margins[BOTTOM_MARGIN]);
1808     printable_area_get(job_params, margins[TOP_MARGIN], margins[LEFT_MARGIN], margins[RIGHT_MARGIN],
1809             margins[BOTTOM_MARGIN]);
1810 
1811     job_params->accepts_app_name = printer_cap->docSourceAppName;
1812     job_params->accepts_app_version = printer_cap->docSourceAppVersion;
1813     job_params->accepts_os_name = printer_cap->docSourceOsName;
1814     job_params->accepts_os_version = printer_cap->docSourceOsVersion;
1815 
1816     return result;
1817 }
1818 
wprintStartJob(const char * printer_addr,port_t port_num,const wprint_job_params_t * job_params,const printer_capabilities_t * printer_cap,const char * mime_type,const char * pathname,wprint_status_cb_t cb_fn,const char * debugDir,const char * scheme)1819 wJob_t wprintStartJob(const char *printer_addr, port_t port_num,
1820         const wprint_job_params_t *job_params, const printer_capabilities_t *printer_cap,
1821         const char *mime_type, const char *pathname, wprint_status_cb_t cb_fn,
1822         const char *debugDir, const char *scheme) {
1823     wJob_t job_handle = WPRINT_BAD_JOB_HANDLE;
1824     _msg_t msg;
1825     struct stat stat_buf;
1826     bool is_dir = false;
1827     _job_queue_t *jq;
1828     wprint_plugin_t *plugin = NULL;
1829     char *print_format;
1830     ifc_print_job_t *print_ifc;
1831 
1832     if (mime_type == NULL) {
1833         errno = EINVAL;
1834         return job_handle;
1835     }
1836 
1837     print_format = _get_print_format(mime_type, job_params, printer_cap);
1838     if (print_format == NULL) return job_handle;
1839 
1840     // check to see if we have an appropriate plugin
1841     if (OK == stat(pathname, &stat_buf)) {
1842         if (S_ISDIR(stat_buf.st_mode)) {
1843             is_dir = true;
1844         } else if (stat_buf.st_size == 0) {
1845             errno = EBADF;
1846             return job_handle;
1847         }
1848     } else {
1849         errno = ENOENT;
1850         return job_handle;
1851     }
1852 
1853     // Make sure we have job_params
1854     if (job_params == NULL) {
1855         errno = ECOMM;
1856         return job_handle;
1857     }
1858 
1859     plugin = plugin_search(mime_type, print_format);
1860     _lock();
1861 
1862     if (plugin) {
1863         job_handle = _get_handle();
1864         if (job_handle == WPRINT_BAD_JOB_HANDLE) {
1865             errno = EAGAIN;
1866         }
1867     } else {
1868         errno = ENOSYS;
1869         LOGE("wprintStartJob(): ERROR: no plugin found for %s => %s", mime_type, print_format);
1870     }
1871 
1872     if (job_handle != WPRINT_BAD_JOB_HANDLE) {
1873         print_ifc = (ifc_print_job_t *) _get_print_ifc(((port_num == 0) ? PORT_FILE : PORT_IPP));
1874 
1875         // fill out the job queue record
1876         jq = _get_job_desc(job_handle);
1877         if (jq == NULL) {
1878             _recycle_handle(job_handle);
1879             job_handle = WPRINT_BAD_JOB_HANDLE;
1880             _unlock();
1881             return job_handle;
1882         }
1883 
1884         if (debugDir != NULL) {
1885             strncpy(jq->debug_path, debugDir, MAX_PATHNAME_LENGTH);
1886             jq->debug_path[MAX_PATHNAME_LENGTH] = 0;
1887         }
1888 
1889         strncpy(jq->printer_addr, printer_addr, MAX_PRINTER_ADDR_LENGTH);
1890         strncpy(jq->mime_type, mime_type, MAX_MIME_LENGTH);
1891         strncpy(jq->pathname, pathname, MAX_PATHNAME_LENGTH);
1892 
1893         jq->port_num = port_num;
1894         jq->cb_fn = cb_fn;
1895         jq->print_ifc = print_ifc;
1896         jq->cancel_ok = true; // assume cancel is ok
1897         jq->plugin = plugin;
1898         memcpy(jq->printer_uri, printer_cap->httpResource,
1899                 MIN(ARRAY_SIZE(printer_cap->httpResource), ARRAY_SIZE(jq->printer_uri)));
1900 
1901         jq->status_ifc = _get_status_ifc(((port_num == 0) ? PORT_FILE : PORT_IPP));
1902 
1903         memcpy((char *) &(jq->job_params), job_params, sizeof(wprint_job_params_t));
1904 
1905         jq->use_secure_uri = (strstr(scheme, IPPS_PREFIX) != NULL);
1906 
1907         size_t useragent_len = strlen(USERAGENT_PREFIX) + strlen(jq->job_params.docCategory) + 1;
1908         char *useragent = (char *) malloc(useragent_len);
1909         if (useragent != NULL) {
1910             snprintf(useragent, useragent_len, USERAGENT_PREFIX "%s", jq->job_params.docCategory);
1911             jq->job_params.useragent = useragent;
1912         }
1913 
1914         // Make a copy of the job_params certificate if it is present
1915         if (job_params->certificate) {
1916             jq->job_params.certificate = malloc(job_params->certificate_len);
1917             if (jq->job_params.certificate) {
1918                 memcpy(jq->job_params.certificate, job_params->certificate,
1919                         job_params->certificate_len);
1920             }
1921         }
1922 
1923         jq->job_params.page_num = 0;
1924         jq->job_params.print_format = print_format;
1925         if (strcmp(print_format, PRINT_FORMAT_PCLM) == 0) {
1926             if (printer_cap->canPrintPCLm || printer_cap->canPrintPDF) {
1927                 jq->job_params.pcl_type = PCLm;
1928             } else {
1929                 jq->job_params.pcl_type = PCLNONE;
1930             }
1931         }
1932 
1933         if (strcmp(print_format, PRINT_FORMAT_PWG) == 0) {
1934             if (printer_cap->canPrintPWG) {
1935                 jq->job_params.pcl_type = PCLPWG;
1936             } else {
1937                 jq->job_params.pcl_type = PCLNONE;
1938             }
1939         }
1940 
1941         // if the pathname is a directory, then this is a multi-page job with individual pages
1942         if (is_dir) {
1943             jq->is_dir = true;
1944             jq->num_pages = 0;
1945 
1946             // create a pageQ for queuing page information
1947             jq->pageQ = msgQCreate(_MAX_PAGES_PER_JOB, sizeof(_page_t));
1948 
1949             // create a secondary page Q for subsequently saving page data for copies #2 to n
1950             if (jq->job_params.num_copies > 1) {
1951                 jq->saveQ = msgQCreate(_MAX_PAGES_PER_JOB, sizeof(_page_t));
1952             }
1953         } else {
1954             jq->num_pages = 1;
1955         }
1956 
1957         // post a message with job_handle to the msgQ that is serviced by a thread
1958         msg.id = MSG_RUN_JOB;
1959         msg.job_id = job_handle;
1960 
1961         if (print_ifc && plugin && plugin->print_page &&
1962                 (msgQSend(_msgQ, (char *) &msg, sizeof(msg), NO_WAIT, MSG_Q_FIFO) == OK)) {
1963             errno = OK;
1964             LOGD("wprintStartJob(): print job %ld queued (%s => %s)", job_handle,
1965                     mime_type, print_format);
1966         } else {
1967             if (print_ifc == NULL) {
1968                 errno = EAFNOSUPPORT;
1969             } else if ((plugin == NULL) || (plugin->print_page == NULL)) {
1970                 errno = ELIBACC;
1971             } else {
1972                 errno = EBADMSG;
1973             }
1974 
1975             LOGE("wprintStartJob(): ERROR plugin->start_job(%ld) : %s => %s", job_handle,
1976                     mime_type, print_format);
1977             jq->job_state = JOB_STATE_ERROR;
1978             _recycle_handle(job_handle);
1979             job_handle = WPRINT_BAD_JOB_HANDLE;
1980         }
1981     }
1982     _unlock();
1983     return job_handle;
1984 }
1985 
wprintEndJob(wJob_t job_handle)1986 status_t wprintEndJob(wJob_t job_handle) {
1987     _page_t page;
1988     _job_queue_t *jq;
1989     status_t result = ERROR;
1990 
1991     _lock();
1992     jq = _get_job_desc(job_handle);
1993 
1994     if (jq) {
1995         // if the job is done and is to be freed, do it
1996         if ((jq->job_state == JOB_STATE_CANCELLED) || (jq->job_state == JOB_STATE_ERROR) ||
1997                 (jq->job_state == JOB_STATE_CORRUPTED) || (jq->job_state == JOB_STATE_COMPLETED)) {
1998             result = OK;
1999             if (jq->pageQ) {
2000                 while ((msgQNumMsgs(jq->pageQ) > 0)
2001                         && (msgQReceive(jq->pageQ, (char *) &page, sizeof(page),
2002                                 WAIT_FOREVER) == OK)) {
2003                 }
2004                 result |= msgQDelete(jq->pageQ);
2005                 jq->pageQ = NULL;
2006             }
2007 
2008             if (jq->saveQ) {
2009                 while ((msgQNumMsgs(jq->saveQ) > 0)
2010                         && (msgQReceive(jq->saveQ, (char *) &page, sizeof(page),
2011                                 WAIT_FOREVER) == OK)) {
2012                 }
2013                 result |= msgQDelete(jq->saveQ);
2014                 jq->saveQ = NULL;
2015             }
2016             _recycle_handle(job_handle);
2017         } else {
2018             LOGE("job %ld cannot be ended from state %d", job_handle, jq->job_state);
2019         }
2020     } else {
2021         LOGE("ERROR: wprintEndJob(%ld), job not found", job_handle);
2022     }
2023 
2024     _unlock();
2025     return result;
2026 }
2027 
wprintPage(wJob_t job_handle,int page_num,const char * filename,bool last_page,bool pdf_page,unsigned int top_margin,unsigned int left_margin,unsigned int right_margin,unsigned int bottom_margin)2028 status_t wprintPage(wJob_t job_handle, int page_num, const char *filename, bool last_page,
2029         bool pdf_page, unsigned int top_margin, unsigned int left_margin, unsigned int right_margin,
2030         unsigned int bottom_margin) {
2031     _job_queue_t *jq;
2032     _page_t page;
2033     status_t result = ERROR;
2034     struct stat stat_buf;
2035 
2036     _lock();
2037     jq = _get_job_desc(job_handle);
2038 
2039     // use empty string to indicate EOJ for an empty job
2040     if (!filename) {
2041         filename = "";
2042         last_page = true;
2043     } else if (OK == stat(filename, &stat_buf)) {
2044         if (!S_ISREG(stat_buf.st_mode) || (stat_buf.st_size == 0)) {
2045             _unlock();
2046             return result;
2047         }
2048     } else {
2049         _unlock();
2050         return result;
2051     }
2052 
2053     // must be setup as a multi-page job, page_num must be valid, and filename must fit
2054     if (jq && jq->is_dir && !(jq->last_page_seen) && (((strlen(filename) < MAX_PATHNAME_LENGTH)) ||
2055             (jq && (strcmp(filename, "") == 0) && last_page))) {
2056         memset(&page, 0, sizeof(page));
2057         page.page_num = page_num;
2058         page.corrupted = false;
2059         page.pdf_page = pdf_page;
2060         page.last_page = last_page;
2061         page.top_margin = top_margin;
2062         page.left_margin = left_margin;
2063         page.right_margin = right_margin;
2064         page.bottom_margin = bottom_margin;
2065 
2066         if ((strlen(filename) == 0) || strchr(filename, '/')) {
2067             // assume empty or complete pathname and use it as it is
2068             strncpy(page.filename, filename, MAX_PATHNAME_LENGTH);
2069         } else {
2070             // generate a complete pathname
2071             snprintf(page.filename, MAX_PATHNAME_LENGTH, "%s/%s", jq->pathname, filename);
2072         }
2073 
2074         if (last_page) {
2075             jq->last_page_seen = true;
2076         }
2077 
2078         result = msgQSend(jq->pageQ, (char *) &page, sizeof(page), NO_WAIT, MSG_Q_FIFO);
2079     }
2080 
2081     if (result == OK) {
2082         LOGD("wprintPage(%ld, %d, %s, %d)", job_handle, page_num, filename, last_page);
2083         if (!(last_page && (strcmp(filename, "") == 0))) {
2084             jq->num_pages++;
2085         }
2086     } else {
2087         LOGE("wprintPage(%ld, %d, %s, %d)", job_handle, page_num, filename, last_page);
2088     }
2089 
2090     _unlock();
2091     return result;
2092 }
2093 
wprintCancelJob(wJob_t job_handle)2094 status_t wprintCancelJob(wJob_t job_handle) {
2095     _job_queue_t *jq;
2096     status_t result;
2097 
2098     _lock();
2099 
2100     jq = _get_job_desc(job_handle);
2101 
2102     if (jq) {
2103         LOGI("received cancel request");
2104         // send a dummy page in case we're waiting on the msgQ page receive
2105         if ((jq->job_state == JOB_STATE_RUNNING) || (jq->job_state == JOB_STATE_BLOCKED)) {
2106             bool enableTimeout = true;
2107             jq->cancel_ok = true;
2108             jq->job_params.cancelled = true;
2109             wprintPage(job_handle, jq->num_pages + 1, NULL, true, false, 0, 0, 0, 0);
2110             if (jq->status_ifc) {
2111                 // are we blocked waiting for the job to start
2112                 if ((jq->job_state != JOB_STATE_BLOCKED) || (jq->job_params.page_num != 0)) {
2113                     errno = OK;
2114                     jq->cancel_ok = ((jq->status_ifc->cancel)(jq->status_ifc,
2115                             jq->job_params.job_originating_user_name) == 0);
2116                     if ((jq->cancel_ok == true) && (errno != OK)) {
2117                         enableTimeout = false;
2118                     }
2119                 }
2120             }
2121             if (!jq->cancel_ok) {
2122                 LOGE("CANCEL did not go through or is not supported for this device");
2123                 enableTimeout = true;
2124             }
2125             if (enableTimeout && (jq->print_ifc != NULL) &&
2126                     (jq->print_ifc->enable_timeout != NULL)) {
2127                 jq->print_ifc->enable_timeout(jq->print_ifc, 1);
2128             }
2129 
2130             errno = (jq->cancel_ok ? OK : ENOTSUP);
2131             jq->job_state = JOB_STATE_CANCEL_REQUEST;
2132             result = OK;
2133         } else if ((jq->job_state == JOB_STATE_CANCEL_REQUEST) ||
2134                 (jq->job_state == JOB_STATE_CANCELLED)) {
2135             result = OK;
2136             errno = (jq->cancel_ok ? OK : ENOTSUP);
2137         } else if (jq->job_state == JOB_STATE_QUEUED) {
2138             jq->job_params.cancelled = true;
2139             jq->job_state = JOB_STATE_CANCELLED;
2140 
2141             if (jq->cb_fn) {
2142                 wprint_job_callback_params_t cb_param;
2143                 cb_param.state = JOB_DONE;
2144                 cb_param.blocked_reasons = BLOCKED_REASONS_CANCELLED;
2145                 cb_param.job_done_result = CANCELLED;
2146                 cb_param.certificate = jq->certificate;
2147                 cb_param.certificate_len = jq->certificate_len;
2148 
2149                 jq->cb_fn(job_handle, (void *) &cb_param);
2150             }
2151 
2152             errno = OK;
2153             result = OK;
2154         } else {
2155             LOGE("job in other state");
2156             result = ERROR;
2157             errno = EBADRQC;
2158         }
2159     } else {
2160         LOGE("could not find job");
2161         result = ERROR;
2162         errno = EBADR;
2163     }
2164 
2165     _unlock();
2166 
2167     return result;
2168 }
2169 
wprintExit(void)2170 status_t wprintExit(void) {
2171     _msg_t msg;
2172 
2173     if (_msgQ) {
2174         //  toss the remaining messages in the msgQ
2175         while ((msgQNumMsgs(_msgQ) > 0) &&
2176                 (OK == msgQReceive(_msgQ, (char *) &msg, sizeof(msg), NO_WAIT))) {}
2177 
2178         // send a quit message
2179         msg.id = MSG_QUIT;
2180         msgQSend(_msgQ, (char *) &msg, sizeof(msg), NO_WAIT, MSG_Q_FIFO);
2181 
2182         // stop the job thread
2183         _stop_thread();
2184 
2185         // empty out the semaphore
2186         while (sem_trywait(&_job_end_wait_sem) == OK);
2187         while (sem_trywait(&_job_start_wait_sem) == OK);
2188 
2189         // receive any messages just in case
2190         while ((msgQNumMsgs(_msgQ) > 0)
2191                 && (OK == msgQReceive(_msgQ, (char *) &msg, sizeof(msg), NO_WAIT))) {}
2192 
2193         // delete the msgQ
2194         msgQDelete(_msgQ);
2195         _msgQ = NULL;
2196 
2197         sem_destroy(&_job_end_wait_sem);
2198         sem_destroy(&_job_start_wait_sem);
2199         pthread_mutex_destroy(&_q_lock);
2200     }
2201 
2202     return OK;
2203 }
2204 
wprintSetSourceInfo(const char * appName,const char * appVersion,const char * osName)2205 void wprintSetSourceInfo(const char *appName, const char *appVersion, const char *osName) {
2206     if (appName) {
2207         strncpy(g_appName, appName, (sizeof(g_appName) - 1));
2208     }
2209 
2210     if (appVersion) {
2211         strncpy(g_appVersion, appVersion, (sizeof(g_appVersion) - 1));
2212     }
2213 
2214     if (osName) {
2215         strncpy(g_osName, osName, (sizeof(g_osName) - 1));
2216     }
2217 
2218     LOGI("App Name: '%s', Version: '%s', OS: '%s'", g_appName, g_appVersion, g_osName);
2219 }
2220