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