• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* sane - Scanner Access Now Easy.
2 
3    Copyright (C) 2019 Touboul Nathane
4    Copyright (C) 2019 Thierry HUCHARD <thierry@ordissimo.com>
5 
6    This file is part of the SANE package.
7 
8    SANE is free software; you can redistribute it and/or modify it under
9    the terms of the GNU General Public License as published by the Free
10    Software Foundation; either version 3 of the License, or (at your
11    option) any later version.
12 
13    SANE is distributed in the hope that it will be useful, but WITHOUT
14    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16    for more details.
17 
18    You should have received a copy of the GNU General Public License
19    along with sane; see the file COPYING.
20    If not, see <https://www.gnu.org/licenses/>.
21 
22    This file implements a SANE backend for eSCL scanners.  */
23 
24 #include "escl.h"
25 
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 
30 #include <setjmp.h>
31 
32 #include "../include/sane/saneopts.h"
33 #include "../include/sane/sanei.h"
34 #include "../include/sane/sanei_backend.h"
35 #include "../include/sane/sanei_config.h"
36 
37 
38 #ifndef SANE_NAME_SHARPEN
39 # define SANE_NAME_SHARPEN "sharpen"
40 # define SANE_TITLE_SHARPEN SANE_I18N("Sharpen")
41 # define SANE_DESC_SHARPEN SANE_I18N("Set sharpen value.")
42 #endif
43 
44 #ifndef SANE_NAME_THRESHOLD
45 # define SANE_NAME_THRESHOLD "threshold"
46 #endif
47 #ifndef SANE_TITLE_THRESHOLD
48 # define SANE_TITLE_THRESHOLD SANE_I18N("Threshold")
49 #endif
50 #ifndef SANE_DESC_THRESHOLD
51 # define SANE_DESC_THRESHOLD \
52     SANE_I18N("Set threshold for line-art scans.")
53 #endif
54 
55 #define min(A,B) (((A)<(B)) ? (A) : (B))
56 #define max(A,B) (((A)>(B)) ? (A) : (B))
57 #define IS_ACTIVE(OPTION) (((handler->opt[OPTION].cap) & SANE_CAP_INACTIVE) == 0)
58 #define INPUT_BUFFER_SIZE 4096
59 
60 static const SANE_Device **devlist = NULL;
61 static ESCL_Device *list_devices_primary = NULL;
62 static int num_devices = 0;
63 
64 #ifdef CURL_SSLVERSION_MAX_DEFAULT
65 static int proto_tls[] = {
66         CURL_SSLVERSION_MAX_DEFAULT,
67    #ifdef CURL_SSLVERSION_MAX_TLSv1_3
68         CURL_SSLVERSION_MAX_TLSv1_3,
69    #endif
70    #ifdef CURL_SSLVERSION_MAX_TLSv1_2
71         CURL_SSLVERSION_MAX_TLSv1_2,
72    #endif
73    #ifdef CURL_SSLVERSION_MAX_TLSv1_1
74         CURL_SSLVERSION_MAX_TLSv1_1,
75    #endif
76    #ifdef CURL_SSLVERSION_MAX_TLSv1_0
77         CURL_SSLVERSION_MAX_TLSv1_0,
78    #endif
79         -1
80 };
81 #endif
82 
83 
84 typedef struct Handled {
85     struct Handled *next;
86     ESCL_Device *device;
87     char *result;
88     ESCL_ScanParam param;
89     SANE_Option_Descriptor opt[NUM_OPTIONS];
90     Option_Value val[NUM_OPTIONS];
91     capabilities_t *scanner;
92     SANE_Range x_range1;
93     SANE_Range x_range2;
94     SANE_Range y_range1;
95     SANE_Range y_range2;
96     SANE_Range brightness_range;
97     SANE_Range contrast_range;
98     SANE_Range sharpen_range;
99     SANE_Range thresold_range;
100     SANE_Bool cancel;
101     SANE_Bool write_scan_data;
102     SANE_Bool decompress_scan_data;
103     SANE_Bool end_read;
104     SANE_Parameters ps;
105 } escl_sane_t;
106 
107 static ESCL_Device *
escl_free_device(ESCL_Device * current)108 escl_free_device(ESCL_Device *current)
109 {
110     if (!current) return NULL;
111     free((void*)current->ip_address);
112     free((void*)current->model_name);
113     free((void*)current->type);
114     free((void*)current->is);
115     free((void*)current->uuid);
116     free((void*)current->unix_socket);
117     curl_slist_free_all(current->hack);
118     free(current);
119     return NULL;
120 }
121 
122 
123 #ifdef CURL_SSLVERSION_MAX_DEFAULT
124 static int
escl_tls_protocol_supported(char * url,int proto)125 escl_tls_protocol_supported(char *url, int proto)
126 {
127    CURLcode res = CURLE_UNSUPPORTED_PROTOCOL;
128    CURL *curl = curl_easy_init();
129    if(curl) {
130       curl_easy_setopt(curl, CURLOPT_URL, url);
131 
132       /* ask libcurl to use TLS version 1.0 or later */
133       curl_easy_setopt(curl, CURLOPT_SSLVERSION, proto);
134       curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
135       curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
136       curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
137       curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L);
138       /* Perform the request */
139       res = curl_easy_perform(curl);
140       curl_easy_cleanup(curl);
141    }
142    return res;
143 }
144 
145 static int
escl_is_tls(char * url,char * type)146 escl_is_tls(char * url, char *type)
147 {
148     int tls_version = 0;
149     if(!strcmp(type, "_uscans._tcp") ||
150        !strcmp(type, "https"))
151       {
152          while(proto_tls[tls_version] != -1)
153           {
154                 if (escl_tls_protocol_supported(url, proto_tls[tls_version]) == CURLE_OK)
155                 {
156                         DBG(10, "curl tls compatible (%d)\n", proto_tls[tls_version]);
157                         break;
158                 }
159                 tls_version++;
160           }
161          if (proto_tls[tls_version] < 1)
162             return 0;
163       }
164       return proto_tls[tls_version];
165 }
166 #else
167 static int
escl_is_tls(char * url,char * type)168 escl_is_tls(char * url, char *type)
169 {
170     (void)url;
171     (void)type;
172     return 0;
173 }
174 #endif
175 
176 void
escl_free_handler(escl_sane_t * handler)177 escl_free_handler(escl_sane_t *handler)
178 {
179     if (handler == NULL)
180         return;
181 
182     escl_free_device(handler->device);
183     free(handler);
184 }
185 
186 SANE_Status escl_parse_name(SANE_String_Const name, ESCL_Device *device);
187 
188 static SANE_Status
escl_check_and_add_device(ESCL_Device * current)189 escl_check_and_add_device(ESCL_Device *current)
190 {
191     if(!current) {
192       DBG (10, "ESCL_Device *current us null.\n");
193       return (SANE_STATUS_NO_MEM);
194     }
195     if (!current->ip_address) {
196       DBG (10, "Ip Address allocation failure.\n");
197       return (SANE_STATUS_NO_MEM);
198     }
199     if (current->port_nb == 0) {
200       DBG (10, "No port defined.\n");
201       return (SANE_STATUS_NO_MEM);
202     }
203     if (!current->model_name) {
204       DBG (10, "Modele Name allocation failure.\n");
205       return (SANE_STATUS_NO_MEM);
206     }
207     if (!current->type) {
208       DBG (10, "Scanner Type allocation failure.\n");
209       return (SANE_STATUS_NO_MEM);
210     }
211     if (!current->is) {
212       DBG (10, "Scanner Is allocation failure.\n");
213       return (SANE_STATUS_NO_MEM);
214     }
215     ++num_devices;
216     current->next = list_devices_primary;
217     list_devices_primary = current;
218     return (SANE_STATUS_GOOD);
219 }
220 
221 /**
222  * \fn static SANE_Status escl_add_in_list(ESCL_Device *current)
223  * \brief Function that adds all the element needed to my list :
224  *        the port number, the model name, the ip address, and the type of url (http/https).
225  *        Moreover, this function counts the number of devices found.
226  *
227  * \return SANE_STATUS_GOOD if everything is OK.
228  */
229 static SANE_Status
escl_add_in_list(ESCL_Device * current)230 escl_add_in_list(ESCL_Device *current)
231 {
232     if(!current) {
233       DBG (10, "ESCL_Device *current us null.\n");
234       return (SANE_STATUS_NO_MEM);
235     }
236 
237     if (SANE_STATUS_GOOD ==
238         escl_check_and_add_device(current)) {
239         list_devices_primary = current;
240         return (SANE_STATUS_GOOD);
241     }
242     current = escl_free_device(current);
243     return (SANE_STATUS_NO_MEM);
244 }
245 
246 /**
247  * \fn SANE_Status escl_device_add(int port_nb, const char *model_name, char *ip_address, char *type)
248  * \brief Function that browses my list ('for' loop) and returns the "escl_add_in_list" function to
249  *        adds all the element needed to my list :
250  *        the port number, the model name, the ip address and the type of the url (http / https).
251  *
252  * \return escl_add_in_list(current)
253  */
254 SANE_Status
escl_device_add(int port_nb,const char * model_name,char * ip_address,const char * is,const char * uuid,char * type)255 escl_device_add(int port_nb,
256                 const char *model_name,
257                 char *ip_address,
258                 const char *is,
259                 const char *uuid,
260                 char *type)
261 {
262     char tmp[PATH_MAX] = { 0 };
263     char *model = NULL;
264     char url_port[512] = { 0 };
265     int tls_version = 0;
266     ESCL_Device *current = NULL;
267     DBG (10, "escl_device_add\n");
268     snprintf(url_port, sizeof(url_port), "https://%s:%d", ip_address, port_nb);
269     tls_version = escl_is_tls(url_port, type);
270 
271     for (current = list_devices_primary; current; current = current->next) {
272 	if ((strcmp(current->ip_address, ip_address) == 0) ||
273             (uuid && current->uuid && !strcmp(current->uuid, uuid)))
274            {
275 	      if (strcmp(current->type, type))
276                 {
277                   if(!strcmp(type, "_uscans._tcp") ||
278                      !strcmp(type, "https"))
279                     {
280                        free (current->type);
281                        current->type = strdup(type);
282                        if (strcmp(current->ip_address, ip_address)) {
283                            free (current->ip_address);
284                            current->ip_address = strdup(ip_address);
285                        }
286                        current->port_nb = port_nb;
287                        current->https = SANE_TRUE;
288                        current->tls = tls_version;
289                     }
290 	          return (SANE_STATUS_GOOD);
291                 }
292               else if (current->port_nb == port_nb)
293 	        return (SANE_STATUS_GOOD);
294            }
295     }
296     current = (ESCL_Device*)calloc(1, sizeof(*current));
297     if (current == NULL) {
298        DBG (10, "New device allocation failure.\n");
299        return (SANE_STATUS_NO_MEM);
300     }
301     current->port_nb = port_nb;
302 
303     if (strcmp(type, "_uscan._tcp") != 0 && strcmp(type, "http") != 0) {
304         snprintf(tmp, sizeof(tmp), "%s SSL", model_name);
305         current->https = SANE_TRUE;
306     } else {
307         current->https = SANE_FALSE;
308     }
309     current->tls = tls_version;
310     model = (char*)(tmp[0] != 0 ? tmp : model_name);
311     current->model_name = strdup(model);
312     current->ip_address = strdup(ip_address);
313     memset(tmp, 0, PATH_MAX);
314     snprintf(tmp, sizeof(tmp), "%s scanner", (is ? is : "flatbed or ADF"));
315     current->is = strdup(tmp);
316     current->type = strdup(type);
317     if (uuid)
318        current->uuid = strdup(uuid);
319     return escl_add_in_list(current);
320 }
321 
322 /**
323  * \fn static inline size_t max_string_size(const SANE_String_Const strings[])
324  * \brief Function that browses the string ('for' loop) and counts the number of character in the string.
325  *        --> this allows to know the maximum size of the string.
326  *
327  * \return max_size + 1 (the size max)
328  */
329 static inline size_t
max_string_size(const SANE_String_Const strings[])330 max_string_size(const SANE_String_Const strings[])
331 {
332     size_t max_size = 0;
333     int i = 0;
334 
335     for (i = 0; strings[i]; ++i) {
336 	size_t size = strlen (strings[i]);
337 	if (size > max_size)
338 	    max_size = size;
339     }
340     return (max_size + 1);
341 }
342 
343 static char *
get_vendor(char * search)344 get_vendor(char *search)
345 {
346 	if(strcasestr(search, "Epson"))
347 		return strdup("Epson");
348 	else if(strcasestr(search, "Fujitsu"))
349 		return strdup("Fujitsu");
350 	else if(strcasestr(search, "HP"))
351 		return strdup("HP");
352 	else if(strcasestr(search, "Canon"))
353 		return strdup("Canon");
354 	else if(strcasestr(search, "Lexmark"))
355 		return strdup("Lexmark");
356 	else if(strcasestr(search, "Samsung"))
357 		return strdup("Samsung");
358 	else if(strcasestr(search, "Xerox"))
359 		return strdup("Xerox");
360 	else if(strcasestr(search, "OKI"))
361 		return strdup("OKI");
362 	else if(strcasestr(search, "Hewlett Packard"))
363 		return strdup("Hewlett Packard");
364 	else if(strcasestr(search, "IBM"))
365 		return strdup("IBM");
366 	else if(strcasestr(search, "Mustek"))
367 		return strdup("Mustek");
368 	else if(strcasestr(search, "Ricoh"))
369 		return strdup("Ricoh");
370 	else if(strcasestr(search, "Sharp"))
371 		return strdup("Sharp");
372 	else if(strcasestr(search, "UMAX"))
373 		return strdup("UMAX");
374 	else if(strcasestr(search, "PINT"))
375 		return strdup("PINT");
376 	else if(strcasestr(search, "Brother"))
377 		return strdup("Brother");
378 	return NULL;
379 }
380 
381 /**
382  * \fn static SANE_Device *convertFromESCLDev(ESCL_Device *cdev)
383  * \brief Function that checks if the url of the received scanner is secured or not (http / https).
384  *        --> if the url is not secured, our own url will be composed like "http://'ip':'port'".
385  *        --> else, our own url will be composed like "https://'ip':'port'".
386  *        AND, it's in this function that we gather all the information of the url (that were in our list) :
387  *        the model_name, the port, the ip, and the type of url.
388  *        SO, leaving this function, we have in memory the complete url.
389  *
390  * \return sdev (structure that contains the elements of the url)
391  */
392 static SANE_Device *
convertFromESCLDev(ESCL_Device * cdev)393 convertFromESCLDev(ESCL_Device *cdev)
394 {
395     char *tmp;
396     int len, lv = 0;
397     char unix_path[PATH_MAX+7] = { 0 };
398     SANE_Device *sdev = (SANE_Device*) calloc(1, sizeof(SANE_Device));
399     if (!sdev) {
400        DBG (10, "Sane_Device allocation failure.\n");
401        return NULL;
402     }
403 
404     if (cdev->unix_socket && strlen(cdev->unix_socket)) {
405         snprintf(unix_path, sizeof(unix_path), "unix:%s:", cdev->unix_socket);
406     }
407     len = snprintf(NULL, 0, "%shttp%s://%s:%d",
408              unix_path, cdev->https ? "s" : "", cdev->ip_address, cdev->port_nb);
409     len++;
410     tmp = (char *)malloc(len);
411     if (!tmp) {
412         DBG (10, "Name allocation failure.\n");
413         goto freedev;
414     }
415     snprintf(tmp, len, "%shttp%s://%s:%d",
416              unix_path, cdev->https ? "s" : "", cdev->ip_address, cdev->port_nb);
417     sdev->name = tmp;
418 
419     DBG( 1, "Escl add device : %s\n", tmp);
420     sdev->vendor = get_vendor(cdev->model_name);
421 
422     if (!sdev->vendor)
423        sdev->vendor = strdup("ESCL");
424     else
425        lv = strlen(sdev->vendor) + 1;
426     if (!sdev->vendor) {
427        DBG (10, "Vendor allocation failure.\n");
428        goto freemodel;
429     }
430     sdev->model = strdup(lv + cdev->model_name);
431     if (!sdev->model) {
432        DBG (10, "Model allocation failure.\n");
433        goto freename;
434     }
435     sdev->type = strdup(cdev->is);
436     if (!sdev->type) {
437        DBG (10, "Scanner Type allocation failure.\n");
438        goto freevendor;
439     }
440     return (sdev);
441 freevendor:
442     free((void*)sdev->vendor);
443 freemodel:
444     free((void*)sdev->model);
445 freename:
446     free((void*)sdev->name);
447 freedev:
448     free((void*)sdev);
449     return NULL;
450 }
451 
452 /**
453  * \fn SANE_Status sane_init(SANE_Int *version_code, SANE_Auth_Callback authorize)
454  * \brief Function that's called before any other SANE function ; it's the first SANE function called.
455  *        --> this function checks the SANE config. and can check the authentication of the user if
456  *        'authorize' value is more than SANE_TRUE.
457  *        In this case, it will be necessary to define an authentication method.
458  *
459  * \return SANE_STATUS_GOOD (everything is OK)
460  */
461 SANE_Status
sane_init(SANE_Int * version_code,SANE_Auth_Callback __sane_unused__ authorize)462 sane_init(SANE_Int *version_code, SANE_Auth_Callback __sane_unused__ authorize)
463 {
464     DBG_INIT();
465     DBG (10, "escl sane_init\n");
466     SANE_Status status = SANE_STATUS_GOOD;
467     curl_global_init(CURL_GLOBAL_ALL);
468     if (version_code != NULL)
469 	*version_code = SANE_VERSION_CODE(1, 0, 0);
470     if (status != SANE_STATUS_GOOD)
471 	return (status);
472     return (SANE_STATUS_GOOD);
473 }
474 
475 /**
476  * \fn void sane_exit(void)
477  * \brief Function that must be called to terminate use of a backend.
478  *        This function will first close all device handles that still might be open.
479  *        --> by freeing all the elements of my list.
480  *        After this function, no function other than 'sane_init' may be called.
481  */
482 void
sane_exit(void)483 sane_exit(void)
484 {
485     DBG (10, "escl sane_exit\n");
486     ESCL_Device *next = NULL;
487 
488     while (list_devices_primary != NULL) {
489 	next = list_devices_primary->next;
490 	free(list_devices_primary);
491 	list_devices_primary = next;
492     }
493     if (devlist)
494 	free (devlist);
495     list_devices_primary = NULL;
496     devlist = NULL;
497     curl_global_cleanup();
498 }
499 
500 /**
501  * \fn static SANE_Status attach_one_config(SANEI_Config *config, const char *line)
502  * \brief Function that implements a configuration file to the user :
503  *        if the user can't detect some devices, he will be able to force their detection with this config' file to use them.
504  *        Thus, this function parses the config' file to use the device of the user with the information below :
505  *        the type of protocol (http/https), the ip, the port number, and the model name.
506  *
507  * \return escl_add_in_list(escl_device) if the parsing worked, SANE_STATUS_GOOD otherwise.
508  */
509 static SANE_Status
attach_one_config(SANEI_Config __sane_unused__ * config,const char * line,void __sane_unused__ * data)510 attach_one_config(SANEI_Config __sane_unused__ *config, const char *line,
511 		  void __sane_unused__ *data)
512 {
513     int port = 0;
514     SANE_Status status;
515     static ESCL_Device *escl_device = NULL;
516     if (*line == '#') return SANE_STATUS_GOOD;
517     if (!strncmp(line, "pdfblacklist", 12)) return SANE_STATUS_GOOD;
518     if (strncmp(line, "device", 6) == 0) {
519         char *name_str = NULL;
520         char *opt_model = NULL;
521         char *opt_hack = NULL;
522 
523         line = sanei_config_get_string(line + 6, &name_str);
524         DBG (10, "New Escl_Device URL [%s].\n", (name_str ? name_str : "VIDE"));
525         if (!name_str || !*name_str) {
526             DBG (1, "Escl_Device URL missing.\n");
527             return SANE_STATUS_INVAL;
528         }
529         if (*line) {
530             line = sanei_config_get_string(line, &opt_model);
531             DBG (10, "New Escl_Device model [%s].\n", opt_model);
532         }
533         if (*line) {
534             line = sanei_config_get_string(line, &opt_hack);
535             DBG (10, "New Escl_Device hack [%s].\n", opt_hack);
536         }
537 
538         escl_free_device(escl_device);
539         escl_device = (ESCL_Device*)calloc(1, sizeof(ESCL_Device));
540         if (!escl_device) {
541            DBG (10, "New Escl_Device allocation failure.\n");
542            free(name_str);
543            return (SANE_STATUS_NO_MEM);
544         }
545         status = escl_parse_name(name_str, escl_device);
546         free(name_str);
547         if (status != SANE_STATUS_GOOD) {
548             escl_free_device(escl_device);
549             escl_device = NULL;
550             return status;
551         }
552         escl_device->model_name = opt_model ? opt_model : strdup("Unknown model");
553         escl_device->is = strdup("flatbed or ADF scanner");
554         escl_device->uuid = NULL;
555     }
556 
557     if (strncmp(line, "[device]", 8) == 0) {
558 	escl_device = escl_free_device(escl_device);
559 	escl_device = (ESCL_Device*)calloc(1, sizeof(ESCL_Device));
560 	if (!escl_device) {
561 	   DBG (10, "New Escl_Device allocation failure.");
562 	   return (SANE_STATUS_NO_MEM);
563 	}
564     }
565     else if (strncmp(line, "ip", 2) == 0) {
566 	const char *ip_space = sanei_config_skip_whitespace(line + 2);
567 	DBG (10, "New Escl_Device IP [%s].", (ip_space ? ip_space : "VIDE"));
568 	if (escl_device != NULL && ip_space != NULL) {
569 	    DBG (10, "New Escl_Device IP Affected.");
570 	    escl_device->ip_address = strdup(ip_space);
571 	}
572     }
573     else if (sscanf(line, "port %i", &port) == 1 && port != 0) {
574 	DBG (10, "New Escl_Device PORT [%d].", port);
575 	if (escl_device != NULL) {
576 	    DBG (10, "New Escl_Device PORT Affected.");
577 	    escl_device->port_nb = port;
578 	}
579     }
580     else if (strncmp(line, "model", 5) == 0) {
581 	const char *model_space = sanei_config_skip_whitespace(line + 5);
582 	DBG (10, "New Escl_Device MODEL [%s].", (model_space ? model_space : "VIDE"));
583 	if (escl_device != NULL && model_space != NULL) {
584 	    DBG (10, "New Escl_Device MODEL Affected.");
585 	    escl_device->model_name = strdup(model_space);
586 	}
587     }
588     else if (strncmp(line, "type", 4) == 0) {
589 	const char *type_space = sanei_config_skip_whitespace(line + 4);
590 	DBG (10, "New Escl_Device TYPE [%s].", (type_space ? type_space : "VIDE"));
591 	if (escl_device != NULL && type_space != NULL) {
592 	    DBG (10, "New Escl_Device TYPE Affected.");
593 	    escl_device->type = strdup(type_space);
594 	}
595     }
596     escl_device->is = strdup("flatbed or ADF scanner");
597     escl_device->uuid = NULL;
598     char url_port[512] = { 0 };
599     snprintf(url_port, sizeof(url_port), "https://%s:%d", escl_device->ip_address, escl_device->port_nb);
600     escl_device->tls = escl_is_tls(url_port, escl_device->type);
601     status = escl_check_and_add_device(escl_device);
602     if (status == SANE_STATUS_GOOD)
603        escl_device = NULL;
604     return status;
605 }
606 
607 /**
608  * \fn SANE_Status sane_get_devices(const SANE_Device ***device_list, SANE_Bool local_only)
609  * \brief Function that searches for connected devices and places them in our 'device_list'. ('for' loop)
610  *        If the attribute 'local_only' is worth SANE_FALSE, we only returns the connected devices locally.
611  *
612  * \return SANE_STATUS_GOOD if devlist != NULL ; SANE_STATUS_NO_MEM otherwise.
613  */
614 SANE_Status
sane_get_devices(const SANE_Device *** device_list,SANE_Bool local_only)615 sane_get_devices(const SANE_Device ***device_list, SANE_Bool local_only)
616 {
617     if (local_only)             /* eSCL is a network-only protocol */
618 	return (device_list ? SANE_STATUS_GOOD : SANE_STATUS_INVAL);
619 
620     DBG (10, "escl sane_get_devices\n");
621     ESCL_Device *dev = NULL;
622     static const SANE_Device **devlist = 0;
623     SANE_Status status;
624 
625     if (device_list == NULL)
626 	return (SANE_STATUS_INVAL);
627     status = sanei_configure_attach(ESCL_CONFIG_FILE, NULL,
628 				    attach_one_config, NULL);
629     if (status != SANE_STATUS_GOOD)
630 	return (status);
631     escl_devices(&status);
632     if (status != SANE_STATUS_GOOD)
633 	return (status);
634     if (devlist)
635 	free(devlist);
636     devlist = (const SANE_Device **) calloc (num_devices + 1, sizeof (devlist[0]));
637     if (devlist == NULL)
638 	return (SANE_STATUS_NO_MEM);
639     int i = 0;
640     for (dev = list_devices_primary; i < num_devices; dev = dev->next) {
641 	SANE_Device *s_dev = convertFromESCLDev(dev);
642 	devlist[i] = s_dev;
643 	i++;
644     }
645     devlist[i] = 0;
646     *device_list = devlist;
647     return (devlist) ? SANE_STATUS_GOOD : SANE_STATUS_NO_MEM;
648 }
649 
650 /* Returns the length of the longest string, including the terminating
651  * character. */
652 static size_t
_source_size_max(SANE_String_Const * sources)653 _source_size_max (SANE_String_Const * sources)
654 {
655   size_t size = 0;
656 
657   while(*sources)
658    {
659       size_t t = strlen (*sources) + 1;
660       if (t > size)
661           size = t;
662       sources++;
663    }
664   return size;
665 }
666 
667 static int
_get_resolution(escl_sane_t * handler,int resol)668 _get_resolution(escl_sane_t *handler, int resol)
669 {
670     int x = 1;
671     int n = handler->scanner->caps[handler->scanner->source].SupportedResolutions[0] + 1;
672     int old = -1;
673     for (; x < n; x++) {
674       DBG(10, "SEARCH RESOLUTION [ %d | %d]\n", resol, (int)handler->scanner->caps[handler->scanner->source].SupportedResolutions[x]);
675       if (resol == handler->scanner->caps[handler->scanner->source].SupportedResolutions[x])
676          return resol;
677       else if (resol < handler->scanner->caps[handler->scanner->source].SupportedResolutions[x])
678       {
679           if (old == -1)
680              return handler->scanner->caps[handler->scanner->source].SupportedResolutions[1];
681           else
682              return old;
683       }
684       else
685           old = handler->scanner->caps[handler->scanner->source].SupportedResolutions[x];
686     }
687     return old;
688 }
689 
690 
691 /**
692  * \fn static SANE_Status init_options(SANE_String_Const name, escl_sane_t *s)
693  * \brief Function thzt initializes all the needed options of the received scanner
694  *        (the resolution / the color / the margins) thanks to the information received with
695  *        the 'escl_capabilities' function, called just before.
696  *
697  * \return status (if everything is OK, status = SANE_STATUS_GOOD)
698  */
699 static SANE_Status
init_options_small(SANE_String_Const name_source,escl_sane_t * s)700 init_options_small(SANE_String_Const name_source, escl_sane_t *s)
701 {
702     int found = 0;
703     DBG (10, "escl init_options\n");
704 
705     SANE_Status status = SANE_STATUS_GOOD;
706     if (!s->scanner) return SANE_STATUS_INVAL;
707     if (name_source) {
708 	   int source = s->scanner->source;
709 	   if (!strcmp(name_source, SANE_I18N ("ADF Duplex")))
710 	       s->scanner->source = ADFDUPLEX;
711 	   else if (!strncmp(name_source, "A", 1) ||
712 	            !strcmp(name_source, SANE_I18N ("ADF")))
713 	       s->scanner->source = ADFSIMPLEX;
714 	   else
715 	       s->scanner->source = PLATEN;
716 	   if (source == s->scanner->source) return status;
717            s->scanner->caps[s->scanner->source].default_color =
718                 strdup(s->scanner->caps[source].default_color);
719            s->scanner->caps[s->scanner->source].default_resolution =
720                 _get_resolution(s, s->scanner->caps[source].default_resolution);
721     }
722     if (s->scanner->caps[s->scanner->source].ColorModes == NULL) {
723         if (s->scanner->caps[PLATEN].ColorModes)
724             s->scanner->source = PLATEN;
725         else if (s->scanner->caps[ADFSIMPLEX].ColorModes)
726             s->scanner->source = ADFSIMPLEX;
727         else if (s->scanner->caps[ADFDUPLEX].ColorModes)
728             s->scanner->source = ADFDUPLEX;
729         else
730             return SANE_STATUS_INVAL;
731     }
732     if (s->scanner->source == PLATEN) {
733         DBG (10, "SOURCE PLATEN.\n");
734     }
735     else if (s->scanner->source == ADFDUPLEX) {
736         DBG (10, "SOURCE ADFDUPLEX.\n");
737     }
738     else if (s->scanner->source == ADFSIMPLEX) {
739         DBG (10, "SOURCE ADFSIMPLEX.\n");
740     }
741     s->x_range1.min = 0;
742     s->x_range1.max =
743 	    PIXEL_TO_MM((s->scanner->caps[s->scanner->source].MaxWidth -
744 		         s->scanner->caps[s->scanner->source].MinWidth),
745 			300.0);
746     s->x_range1.quant = 0;
747     s->x_range2.min = PIXEL_TO_MM(s->scanner->caps[s->scanner->source].MinWidth, 300.0);
748     s->x_range2.max = PIXEL_TO_MM(s->scanner->caps[s->scanner->source].MaxWidth, 300.0);
749     s->x_range2.quant = 0;
750     s->y_range1.min = 0;
751     s->y_range1.max =
752 	    PIXEL_TO_MM((s->scanner->caps[s->scanner->source].MaxHeight -
753 	                 s->scanner->caps[s->scanner->source].MinHeight),
754 			300.0);
755     s->y_range1.quant = 0;
756     s->y_range2.min = PIXEL_TO_MM(s->scanner->caps[s->scanner->source].MinHeight, 300.0);
757     s->y_range2.max = PIXEL_TO_MM(s->scanner->caps[s->scanner->source].MaxHeight, 300.0);
758     s->y_range2.quant = 0;
759 
760     s->opt[OPT_MODE].constraint.string_list = s->scanner->caps[s->scanner->source].ColorModes;
761     if (s->val[OPT_MODE].s)
762         free(s->val[OPT_MODE].s);
763     s->val[OPT_MODE].s = NULL;
764 
765     if (s->scanner->caps[s->scanner->source].default_color) {
766         int x = 0;
767         if (!strcmp(s->scanner->caps[s->scanner->source].default_color, "Grayscale8"))
768            s->val[OPT_MODE].s = (char *)strdup(SANE_VALUE_SCAN_MODE_GRAY);
769         else if (!strcmp(s->scanner->caps[s->scanner->source].default_color, "BlackAndWhite1"))
770            s->val[OPT_MODE].s = (char *)strdup(SANE_VALUE_SCAN_MODE_LINEART);
771         else
772            s->val[OPT_MODE].s = (char *)strdup(SANE_VALUE_SCAN_MODE_COLOR);
773         for (x = 0; s->scanner->caps[s->scanner->source].ColorModes[x]; x++) {
774             if (s->scanner->caps[s->scanner->source].ColorModes[x] &&
775               !strcasecmp(s->scanner->caps[s->scanner->source].ColorModes[x], s->val[OPT_MODE].s)) {
776               found = 1;
777               break;
778             }
779         }
780     }
781     if (!s->scanner->caps[s->scanner->source].default_color || found == 0) {
782         if (s->scanner->caps[s->scanner->source].default_color)
783            free(s->scanner->caps[s->scanner->source].default_color);
784         s->val[OPT_MODE].s = strdup(s->scanner->caps[s->scanner->source].ColorModes[0]);
785         if (!strcasecmp(s->val[OPT_MODE].s, SANE_VALUE_SCAN_MODE_GRAY))
786             s->scanner->caps[s->scanner->source].default_color = strdup("Grayscale8");
787         else if (!strcasecmp(s->val[OPT_MODE].s, SANE_VALUE_SCAN_MODE_LINEART))
788             s->scanner->caps[s->scanner->source].default_color = strdup("BlackAndWhite1");
789         else
790             s->scanner->caps[s->scanner->source].default_color = strdup("RGB24");
791     }
792     if (!s->val[OPT_MODE].s) {
793        DBG (10, "Color Mode Default allocation failure.\n");
794        return (SANE_STATUS_NO_MEM);
795     }
796     if (!s->scanner->caps[s->scanner->source].default_color) {
797        DBG (10, "Color Mode Default allocation failure.\n");
798        return (SANE_STATUS_NO_MEM);
799     }
800     s->val[OPT_RESOLUTION].w = s->scanner->caps[s->scanner->source].default_resolution;
801     s->opt[OPT_TL_X].constraint.range = &s->x_range1;
802     s->opt[OPT_TL_Y].constraint.range = &s->y_range1;
803     s->opt[OPT_BR_X].constraint.range = &s->x_range2;
804     s->opt[OPT_BR_Y].constraint.range = &s->y_range2;
805 
806     if (s->val[OPT_SCAN_SOURCE].s)
807       free (s->val[OPT_SCAN_SOURCE].s);
808     s->val[OPT_SCAN_SOURCE].s = strdup (s->scanner->Sources[s->scanner->source]);
809 
810     return (SANE_STATUS_GOOD);
811 }
812 
813 /**
814  * \fn static SANE_Status init_options(SANE_String_Const name, escl_sane_t *s)
815  * \brief Function thzt initializes all the needed options of the received scanner
816  *        (the resolution / the color / the margins) thanks to the information received with
817  *        the 'escl_capabilities' function, called just before.
818  *
819  * \return status (if everything is OK, status = SANE_STATUS_GOOD)
820  */
821 static SANE_Status
init_options(SANE_String_Const name_source,escl_sane_t * s)822 init_options(SANE_String_Const name_source, escl_sane_t *s)
823 {
824     DBG (10, "escl init_options\n");
825 
826     SANE_Status status = SANE_STATUS_GOOD;
827     int i = 0;
828     if (!s->scanner) return SANE_STATUS_INVAL;
829     if (name_source) {
830 	   int source = s->scanner->source;
831 	   DBG (10, "escl init_options name [%s]\n", name_source);
832 	   if (!strcmp(name_source, SANE_I18N ("ADF Duplex")))
833 	       s->scanner->source = ADFDUPLEX;
834 	   else if (!strncmp(name_source, "A", 1) ||
835 	            !strcmp(name_source, SANE_I18N ("ADF")))
836 	       s->scanner->source = ADFSIMPLEX;
837 	   else
838 	       s->scanner->source = PLATEN;
839 	   if (source == s->scanner->source) return status;
840     }
841     if (s->scanner->caps[s->scanner->source].ColorModes == NULL) {
842         if (s->scanner->caps[PLATEN].ColorModes)
843             s->scanner->source = PLATEN;
844         else if (s->scanner->caps[ADFSIMPLEX].ColorModes)
845             s->scanner->source = ADFSIMPLEX;
846         else if (s->scanner->caps[ADFDUPLEX].ColorModes)
847             s->scanner->source = ADFDUPLEX;
848         else
849             return SANE_STATUS_INVAL;
850     }
851     if (s->scanner->source == PLATEN) {
852         DBG (10, "SOURCE PLATEN.\n");
853     }
854     else if (s->scanner->source == ADFDUPLEX) {
855         DBG (10, "SOURCE ADFDUPLEX.\n");
856     }
857     else if (s->scanner->source == ADFSIMPLEX) {
858         DBG (10, "SOURCE ADFSIMPLEX.\n");
859     }
860     memset (s->opt, 0, sizeof (s->opt));
861     memset (s->val, 0, sizeof (s->val));
862     for (i = 0; i < NUM_OPTIONS; ++i) {
863 	   s->opt[i].size = sizeof (SANE_Word);
864 	   s->opt[i].cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
865     }
866     s->x_range1.min = 0;
867     s->x_range1.max =
868 	    PIXEL_TO_MM((s->scanner->caps[s->scanner->source].MaxWidth -
869 		         s->scanner->caps[s->scanner->source].MinWidth),
870 			300.0);
871     s->x_range1.quant = 0;
872     s->x_range2.min = PIXEL_TO_MM(s->scanner->caps[s->scanner->source].MinWidth, 300.0);
873     s->x_range2.max = PIXEL_TO_MM(s->scanner->caps[s->scanner->source].MaxWidth, 300.0);
874     s->x_range2.quant = 0;
875     s->y_range1.min = 0;
876     s->y_range1.max =
877 	    PIXEL_TO_MM((s->scanner->caps[s->scanner->source].MaxHeight -
878 	                 s->scanner->caps[s->scanner->source].MinHeight),
879 			300.0);
880     s->y_range1.quant = 0;
881     s->y_range2.min = PIXEL_TO_MM(s->scanner->caps[s->scanner->source].MinHeight, 300.0);
882     s->y_range2.max = PIXEL_TO_MM(s->scanner->caps[s->scanner->source].MaxHeight, 300.0);
883     s->y_range2.quant = 0;
884     s->opt[OPT_NUM_OPTS].title = SANE_TITLE_NUM_OPTIONS;
885     s->opt[OPT_NUM_OPTS].desc = SANE_DESC_NUM_OPTIONS;
886     s->opt[OPT_NUM_OPTS].type = SANE_TYPE_INT;
887     s->opt[OPT_NUM_OPTS].cap = SANE_CAP_SOFT_DETECT;
888     s->val[OPT_NUM_OPTS].w = NUM_OPTIONS;
889 
890     s->opt[OPT_MODE_GROUP].title = SANE_TITLE_SCAN_MODE;
891     s->opt[OPT_MODE_GROUP].desc = "";
892     s->opt[OPT_MODE_GROUP].type = SANE_TYPE_GROUP;
893     s->opt[OPT_MODE_GROUP].cap = 0;
894     s->opt[OPT_MODE_GROUP].size = 0;
895     s->opt[OPT_MODE_GROUP].constraint_type = SANE_CONSTRAINT_NONE;
896 
897     s->opt[OPT_MODE].name = SANE_NAME_SCAN_MODE;
898     s->opt[OPT_MODE].title = SANE_TITLE_SCAN_MODE;
899     s->opt[OPT_MODE].desc = SANE_DESC_SCAN_MODE;
900     s->opt[OPT_MODE].type = SANE_TYPE_STRING;
901     s->opt[OPT_MODE].unit = SANE_UNIT_NONE;
902     s->opt[OPT_MODE].constraint_type = SANE_CONSTRAINT_STRING_LIST;
903     s->opt[OPT_MODE].constraint.string_list = s->scanner->caps[s->scanner->source].ColorModes;
904     if (s->scanner->caps[s->scanner->source].default_color) {
905         if (!strcasecmp(s->scanner->caps[s->scanner->source].default_color, "Grayscale8"))
906            s->val[OPT_MODE].s = (char *)strdup(SANE_VALUE_SCAN_MODE_GRAY);
907         else if (!strcasecmp(s->scanner->caps[s->scanner->source].default_color, "BlackAndWhite1"))
908            s->val[OPT_MODE].s = (char *)strdup(SANE_VALUE_SCAN_MODE_LINEART);
909         else
910            s->val[OPT_MODE].s = (char *)strdup(SANE_VALUE_SCAN_MODE_COLOR);
911     }
912     else {
913         s->val[OPT_MODE].s = (char *)strdup(s->scanner->caps[s->scanner->source].ColorModes[0]);
914         if (!strcasecmp(s->val[OPT_MODE].s, SANE_VALUE_SCAN_MODE_GRAY)) {
915            s->scanner->caps[s->scanner->source].default_color = strdup("Grayscale8");
916         }
917         else if (!strcasecmp(s->val[OPT_MODE].s, SANE_VALUE_SCAN_MODE_LINEART)) {
918            s->scanner->caps[s->scanner->source].default_color =
919                 strdup("BlackAndWhite1");
920         }
921         else {
922            s->scanner->caps[s->scanner->source].default_color =
923                strdup("RGB24");
924        }
925     }
926     if (!s->val[OPT_MODE].s) {
927        DBG (10, "Color Mode Default allocation failure.\n");
928        return (SANE_STATUS_NO_MEM);
929     }
930     DBG (10, "++ Color Mode Default allocation [%s].\n", s->scanner->caps[s->scanner->source].default_color);
931     s->opt[OPT_MODE].size = max_string_size(s->scanner->caps[s->scanner->source].ColorModes);
932     if (!s->scanner->caps[s->scanner->source].default_color) {
933        DBG (10, "Color Mode Default allocation failure.\n");
934        return (SANE_STATUS_NO_MEM);
935     }
936     DBG (10, "Color Mode Default allocation (%s).\n", s->scanner->caps[s->scanner->source].default_color);
937 
938     s->opt[OPT_RESOLUTION].name = SANE_NAME_SCAN_RESOLUTION;
939     s->opt[OPT_RESOLUTION].title = SANE_TITLE_SCAN_RESOLUTION;
940     s->opt[OPT_RESOLUTION].desc = SANE_DESC_SCAN_RESOLUTION;
941     s->opt[OPT_RESOLUTION].type = SANE_TYPE_INT;
942     s->opt[OPT_RESOLUTION].unit = SANE_UNIT_DPI;
943     s->opt[OPT_RESOLUTION].constraint_type = SANE_CONSTRAINT_WORD_LIST;
944     s->opt[OPT_RESOLUTION].constraint.word_list = s->scanner->caps[s->scanner->source].SupportedResolutions;
945     s->val[OPT_RESOLUTION].w = s->scanner->caps[s->scanner->source].SupportedResolutions[1];
946     s->scanner->caps[s->scanner->source].default_resolution = s->scanner->caps[s->scanner->source].SupportedResolutions[1];
947 
948     s->opt[OPT_PREVIEW].name = SANE_NAME_PREVIEW;
949     s->opt[OPT_PREVIEW].title = SANE_TITLE_PREVIEW;
950     s->opt[OPT_PREVIEW].desc = SANE_DESC_PREVIEW;
951     s->opt[OPT_PREVIEW].cap = SANE_CAP_SOFT_DETECT | SANE_CAP_SOFT_SELECT;
952     s->opt[OPT_PREVIEW].type = SANE_TYPE_BOOL;
953     s->val[OPT_PREVIEW].w = SANE_FALSE;
954 
955     s->opt[OPT_GRAY_PREVIEW].name = SANE_NAME_GRAY_PREVIEW;
956     s->opt[OPT_GRAY_PREVIEW].title = SANE_TITLE_GRAY_PREVIEW;
957     s->opt[OPT_GRAY_PREVIEW].desc = SANE_DESC_GRAY_PREVIEW;
958     s->opt[OPT_GRAY_PREVIEW].type = SANE_TYPE_BOOL;
959     s->val[OPT_GRAY_PREVIEW].w = SANE_FALSE;
960 
961     s->opt[OPT_GEOMETRY_GROUP].title = SANE_TITLE_GEOMETRY;
962     s->opt[OPT_GEOMETRY_GROUP].desc = SANE_DESC_GEOMETRY;
963     s->opt[OPT_GEOMETRY_GROUP].type = SANE_TYPE_GROUP;
964     s->opt[OPT_GEOMETRY_GROUP].cap = SANE_CAP_ADVANCED;
965     s->opt[OPT_GEOMETRY_GROUP].size = 0;
966     s->opt[OPT_GEOMETRY_GROUP].constraint_type = SANE_CONSTRAINT_NONE;
967 
968     s->opt[OPT_TL_X].name = SANE_NAME_SCAN_TL_X;
969     s->opt[OPT_TL_X].title = SANE_TITLE_SCAN_TL_X;
970     s->opt[OPT_TL_X].desc = SANE_DESC_SCAN_TL_X;
971     s->opt[OPT_TL_X].type = SANE_TYPE_FIXED;
972     s->opt[OPT_TL_X].size = sizeof(SANE_Fixed);
973     s->opt[OPT_TL_X].cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
974     s->opt[OPT_TL_X].unit = SANE_UNIT_MM;
975     s->opt[OPT_TL_X].constraint_type = SANE_CONSTRAINT_RANGE;
976     s->opt[OPT_TL_X].constraint.range = &s->x_range1;
977     s->val[OPT_TL_X].w = s->x_range1.min;
978 
979     s->opt[OPT_TL_Y].name = SANE_NAME_SCAN_TL_Y;
980     s->opt[OPT_TL_Y].title = SANE_TITLE_SCAN_TL_Y;
981     s->opt[OPT_TL_Y].desc = SANE_DESC_SCAN_TL_Y;
982     s->opt[OPT_TL_Y].type = SANE_TYPE_FIXED;
983     s->opt[OPT_TL_Y].size = sizeof(SANE_Fixed);
984     s->opt[OPT_TL_Y].cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
985     s->opt[OPT_TL_Y].unit = SANE_UNIT_MM;
986     s->opt[OPT_TL_Y].constraint_type = SANE_CONSTRAINT_RANGE;
987     s->opt[OPT_TL_Y].constraint.range = &s->y_range1;
988     s->val[OPT_TL_Y].w = s->y_range1.min;
989 
990     s->opt[OPT_BR_X].name = SANE_NAME_SCAN_BR_X;
991     s->opt[OPT_BR_X].title = SANE_TITLE_SCAN_BR_X;
992     s->opt[OPT_BR_X].desc = SANE_DESC_SCAN_BR_X;
993     s->opt[OPT_BR_X].type = SANE_TYPE_FIXED;
994     s->opt[OPT_BR_X].size = sizeof(SANE_Fixed);
995     s->opt[OPT_BR_X].cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
996     s->opt[OPT_BR_X].unit = SANE_UNIT_MM;
997     s->opt[OPT_BR_X].constraint_type = SANE_CONSTRAINT_RANGE;
998     s->opt[OPT_BR_X].constraint.range = &s->x_range2;
999     s->val[OPT_BR_X].w = s->x_range2.max;
1000 
1001     s->opt[OPT_BR_Y].name = SANE_NAME_SCAN_BR_Y;
1002     s->opt[OPT_BR_Y].title = SANE_TITLE_SCAN_BR_Y;
1003     s->opt[OPT_BR_Y].desc = SANE_DESC_SCAN_BR_Y;
1004     s->opt[OPT_BR_Y].type = SANE_TYPE_FIXED;
1005     s->opt[OPT_BR_Y].size = sizeof(SANE_Fixed);
1006     s->opt[OPT_BR_Y].cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
1007     s->opt[OPT_BR_Y].unit = SANE_UNIT_MM;
1008     s->opt[OPT_BR_Y].constraint_type = SANE_CONSTRAINT_RANGE;
1009     s->opt[OPT_BR_Y].constraint.range = &s->y_range2;
1010     s->val[OPT_BR_Y].w = s->y_range2.max;
1011 
1012 	/* OPT_SCAN_SOURCE */
1013     s->opt[OPT_SCAN_SOURCE].name = SANE_NAME_SCAN_SOURCE;
1014     s->opt[OPT_SCAN_SOURCE].title = SANE_TITLE_SCAN_SOURCE;
1015     s->opt[OPT_SCAN_SOURCE].desc = SANE_DESC_SCAN_SOURCE;
1016     s->opt[OPT_SCAN_SOURCE].type = SANE_TYPE_STRING;
1017     s->opt[OPT_SCAN_SOURCE].size = _source_size_max(s->scanner->Sources);
1018     s->opt[OPT_SCAN_SOURCE].cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
1019     s->opt[OPT_SCAN_SOURCE].constraint_type = SANE_CONSTRAINT_STRING_LIST;
1020     s->opt[OPT_SCAN_SOURCE].constraint.string_list = s->scanner->Sources;
1021     if (s->val[OPT_SCAN_SOURCE].s)
1022        free (s->val[OPT_SCAN_SOURCE].s);
1023     s->val[OPT_SCAN_SOURCE].s = strdup (s->scanner->Sources[s->scanner->source]);
1024 
1025     /* "Enhancement" group: */
1026     s->opt[OPT_ENHANCEMENT_GROUP].title = SANE_I18N ("Enhancement");
1027     s->opt[OPT_ENHANCEMENT_GROUP].desc = "";    /* not valid for a group */
1028     s->opt[OPT_ENHANCEMENT_GROUP].type = SANE_TYPE_GROUP;
1029     s->opt[OPT_ENHANCEMENT_GROUP].cap = SANE_CAP_ADVANCED;
1030     s->opt[OPT_ENHANCEMENT_GROUP].size = 0;
1031     s->opt[OPT_ENHANCEMENT_GROUP].constraint_type = SANE_CONSTRAINT_NONE;
1032 
1033 
1034     s->opt[OPT_BRIGHTNESS].name = SANE_NAME_BRIGHTNESS;
1035     s->opt[OPT_BRIGHTNESS].title = SANE_TITLE_BRIGHTNESS;
1036     s->opt[OPT_BRIGHTNESS].desc = SANE_DESC_BRIGHTNESS;
1037     s->opt[OPT_BRIGHTNESS].type = SANE_TYPE_INT;
1038     s->opt[OPT_BRIGHTNESS].unit = SANE_UNIT_NONE;
1039     s->opt[OPT_BRIGHTNESS].constraint_type = SANE_CONSTRAINT_RANGE;
1040     if (s->scanner->brightness) {
1041        s->opt[OPT_BRIGHTNESS].constraint.range = &s->brightness_range;
1042        s->val[OPT_BRIGHTNESS].w = s->scanner->brightness->value;
1043        s->brightness_range.quant=1;
1044        s->brightness_range.min=s->scanner->brightness->min;
1045        s->brightness_range.max=s->scanner->brightness->max;
1046     }
1047     else{
1048       SANE_Range range = { 0, 255, 0 };
1049       s->opt[OPT_BRIGHTNESS].constraint.range = &range;
1050       s->val[OPT_BRIGHTNESS].w = 0;
1051       s->opt[OPT_BRIGHTNESS].cap |= SANE_CAP_INACTIVE;
1052     }
1053     s->opt[OPT_CONTRAST].name = SANE_NAME_CONTRAST;
1054     s->opt[OPT_CONTRAST].title = SANE_TITLE_CONTRAST;
1055     s->opt[OPT_CONTRAST].desc = SANE_DESC_CONTRAST;
1056     s->opt[OPT_CONTRAST].type = SANE_TYPE_INT;
1057     s->opt[OPT_CONTRAST].unit = SANE_UNIT_NONE;
1058     s->opt[OPT_CONTRAST].constraint_type = SANE_CONSTRAINT_RANGE;
1059     if (s->scanner->contrast) {
1060        s->opt[OPT_CONTRAST].constraint.range = &s->contrast_range;
1061        s->val[OPT_CONTRAST].w = s->scanner->contrast->value;
1062        s->contrast_range.quant=1;
1063        s->contrast_range.min=s->scanner->contrast->min;
1064        s->contrast_range.max=s->scanner->contrast->max;
1065     }
1066     else{
1067       SANE_Range range = { 0, 255, 0 };
1068       s->opt[OPT_CONTRAST].constraint.range = &range;
1069       s->val[OPT_CONTRAST].w = 0;
1070       s->opt[OPT_CONTRAST].cap |= SANE_CAP_INACTIVE;
1071     }
1072     s->opt[OPT_SHARPEN].name = SANE_NAME_SHARPEN;
1073     s->opt[OPT_SHARPEN].title = SANE_TITLE_SHARPEN;
1074     s->opt[OPT_SHARPEN].desc = SANE_DESC_SHARPEN;
1075     s->opt[OPT_SHARPEN].type = SANE_TYPE_INT;
1076     s->opt[OPT_SHARPEN].unit = SANE_UNIT_NONE;
1077     s->opt[OPT_SHARPEN].constraint_type = SANE_CONSTRAINT_RANGE;
1078     if (s->scanner->sharpen) {
1079        s->opt[OPT_SHARPEN].constraint.range = &s->sharpen_range;
1080        s->val[OPT_SHARPEN].w = s->scanner->sharpen->value;
1081        s->sharpen_range.quant=1;
1082        s->sharpen_range.min=s->scanner->sharpen->min;
1083        s->sharpen_range.max=s->scanner->sharpen->max;
1084     }
1085     else{
1086       SANE_Range range = { 0, 255, 0 };
1087       s->opt[OPT_SHARPEN].constraint.range = &range;
1088       s->val[OPT_SHARPEN].w = 0;
1089       s->opt[OPT_SHARPEN].cap |= SANE_CAP_INACTIVE;
1090     }
1091     /*threshold*/
1092     s->opt[OPT_THRESHOLD].name = SANE_NAME_THRESHOLD;
1093     s->opt[OPT_THRESHOLD].title = SANE_TITLE_THRESHOLD;
1094     s->opt[OPT_THRESHOLD].desc = SANE_DESC_THRESHOLD;
1095     s->opt[OPT_THRESHOLD].type = SANE_TYPE_INT;
1096     s->opt[OPT_THRESHOLD].unit = SANE_UNIT_NONE;
1097     s->opt[OPT_THRESHOLD].constraint_type = SANE_CONSTRAINT_RANGE;
1098     if (s->scanner->threshold) {
1099       s->opt[OPT_THRESHOLD].constraint.range = &s->thresold_range;
1100       s->val[OPT_THRESHOLD].w = s->scanner->threshold->value;
1101       s->thresold_range.quant=1;
1102       s->thresold_range.min= s->scanner->threshold->min;
1103       s->thresold_range.max=s->scanner->threshold->max;
1104     }
1105     else{
1106       SANE_Range range = { 0, 255, 0 };
1107       s->opt[OPT_THRESHOLD].constraint.range = &range;
1108       s->val[OPT_THRESHOLD].w = 0;
1109       s->opt[OPT_THRESHOLD].cap |= SANE_CAP_INACTIVE;
1110     }
1111     if (!strcasecmp(s->val[OPT_MODE].s, SANE_VALUE_SCAN_MODE_LINEART)) {
1112        if (s->scanner->threshold)
1113        	  s->opt[OPT_THRESHOLD].cap  &= ~SANE_CAP_INACTIVE;
1114        if (s->scanner->brightness)
1115        	  s->opt[OPT_BRIGHTNESS].cap |= SANE_CAP_INACTIVE;
1116        if (s->scanner->contrast)
1117        	  s->opt[OPT_CONTRAST].cap |= SANE_CAP_INACTIVE;
1118        if (s->scanner->sharpen)
1119           s->opt[OPT_SHARPEN].cap |= SANE_CAP_INACTIVE;
1120     }
1121     else {
1122        if (s->scanner->threshold)
1123        	  s->opt[OPT_THRESHOLD].cap  |= SANE_CAP_INACTIVE;
1124        if (s->scanner->brightness)
1125           s->opt[OPT_BRIGHTNESS].cap &= ~SANE_CAP_INACTIVE;
1126        if (s->scanner->contrast)
1127           s->opt[OPT_CONTRAST].cap   &= ~SANE_CAP_INACTIVE;
1128        if (s->scanner->sharpen)
1129           s->opt[OPT_SHARPEN].cap   &= ~SANE_CAP_INACTIVE;
1130     }
1131     return (status);
1132 }
1133 
1134 SANE_Status
escl_parse_name(SANE_String_Const name,ESCL_Device * device)1135 escl_parse_name(SANE_String_Const name, ESCL_Device *device)
1136 {
1137     SANE_String_Const host = NULL;
1138     SANE_String_Const port_str = NULL;
1139     DBG(10, "escl_parse_name\n");
1140     if (name == NULL || device == NULL) {
1141         return SANE_STATUS_INVAL;
1142     }
1143 
1144     if (strncmp(name, "unix:", 5) == 0) {
1145         SANE_String_Const socket = name + 5;
1146         name = strchr(socket, ':');
1147         if (name == NULL)
1148             return SANE_STATUS_INVAL;
1149         device->unix_socket = strndup(socket, name - socket);
1150         name++;
1151     }
1152 
1153     if (strncmp(name, "https://", 8) == 0) {
1154         device->https = SANE_TRUE;
1155         device->type = strdup("https");
1156         host = name + 8;
1157     } else if (strncmp(name, "http://", 7) == 0) {
1158         device->https = SANE_FALSE;
1159         device->type = strdup("http");
1160         host = name + 7;
1161     } else {
1162         DBG(1, "Unknown URL scheme in %s", name);
1163         return SANE_STATUS_INVAL;
1164     }
1165 
1166     port_str = strchr(host, ':');
1167     if (port_str == NULL) {
1168         DBG(1, "Port missing from URL: %s", name);
1169         return SANE_STATUS_INVAL;
1170     }
1171     port_str++;
1172     device->port_nb = atoi(port_str);
1173     if (device->port_nb < 1 || device->port_nb > 65535) {
1174         DBG(1, "Invalid port number in URL: %s", name);
1175         return SANE_STATUS_INVAL;
1176     }
1177 
1178     device->ip_address = strndup(host, port_str - host - 1);
1179     return SANE_STATUS_GOOD;
1180 }
1181 
1182 static void
_get_hack(SANE_String_Const name,ESCL_Device * device)1183 _get_hack(SANE_String_Const name, ESCL_Device *device)
1184 {
1185   FILE *fp;
1186   SANE_Char line[PATH_MAX];
1187   DBG (3, "_get_hack: start\n");
1188   if (device->model_name &&
1189       (strcasestr(device->model_name, "LaserJet FlowMFP M578") ||
1190        strcasestr(device->model_name, "LaserJet MFP M630"))) {
1191        device->hack = curl_slist_append(NULL, "Host: localhost");
1192        DBG (3, "_get_hack: finish\n");
1193        return;
1194   }
1195 
1196   /* open configuration file */
1197   fp = sanei_config_open (ESCL_CONFIG_FILE);
1198   if (!fp)
1199     {
1200       DBG (2, "_get_hack: couldn't access %s\n", ESCL_CONFIG_FILE);
1201       DBG (3, "_get_hack: exit\n");
1202     }
1203 
1204   /* loop reading the configuration file, all line beginning by "option " are
1205    * parsed for value to store in configuration structure, other line are
1206    * used are device to try to attach
1207    */
1208   while (sanei_config_read (line, PATH_MAX, fp))
1209     {
1210        if (strstr(line, name)) {
1211           DBG (3, "_get_hack: idevice found\n");
1212 	  if (strstr(line, "hack=localhost")) {
1213               DBG (3, "_get_hack: device found\n");
1214 	      device->hack = curl_slist_append(NULL, "Host: localhost");
1215 	  }
1216 	  goto finish_hack;
1217        }
1218     }
1219 finish_hack:
1220   DBG (3, "_get_hack: finish\n");
1221   fclose(fp);
1222 }
1223 
1224 static char*
_get_blacklist_pdf(void)1225 _get_blacklist_pdf(void)
1226 {
1227   FILE *fp;
1228   char *blacklist = NULL;
1229   SANE_Char line[PATH_MAX];
1230 
1231   /* open configuration file */
1232   fp = sanei_config_open (ESCL_CONFIG_FILE);
1233   if (!fp)
1234     {
1235       DBG (2, "_get_blacklit: couldn't access %s\n", ESCL_CONFIG_FILE);
1236       DBG (3, "_get_blacklist: exit\n");
1237     }
1238 
1239   /* loop reading the configuration file, all line beginning by "option " are
1240    * parsed for value to store in configuration structure, other line are
1241    * used are device to try to attach
1242    */
1243   while (sanei_config_read (line, PATH_MAX, fp))
1244     {
1245        if (!strncmp(line, "pdfblacklist", 12)) {
1246           blacklist = strdup(line);
1247 	  goto finish_;
1248        }
1249     }
1250 finish_:
1251   DBG (3, "_get_blacklist_pdf: finish\n");
1252   fclose(fp);
1253   return blacklist;
1254 }
1255 
1256 
1257 /**
1258  * \fn SANE_Status sane_open(SANE_String_Const name, SANE_Handle *h)
1259  * \brief Function that establishes a connection with the device named by 'name',
1260  *        and returns a 'handler' using 'SANE_Handle *h', representing it.
1261  *        Thus, it's this function that calls the 'escl_status' function firstly,
1262  *        then the 'escl_capabilities' function, and, after, the 'init_options' function.
1263  *
1264  * \return status (if everything is OK, status = SANE_STATUS_GOOD, otherwise, SANE_STATUS_NO_MEM/SANE_STATUS_INVAL)
1265  */
1266 SANE_Status
sane_open(SANE_String_Const name,SANE_Handle * h)1267 sane_open(SANE_String_Const name, SANE_Handle *h)
1268 {
1269     char *blacklist = NULL;
1270     DBG (10, "escl sane_open\n");
1271     SANE_Status status;
1272     escl_sane_t *handler = NULL;
1273 
1274     if (name == NULL)
1275         return (SANE_STATUS_INVAL);
1276 
1277     ESCL_Device *device = calloc(1, sizeof(ESCL_Device));
1278     if (device == NULL) {
1279         DBG (10, "Handle device allocation failure.\n");
1280         return SANE_STATUS_NO_MEM;
1281     }
1282     status = escl_parse_name(name, device);
1283     if (status != SANE_STATUS_GOOD) {
1284         escl_free_device(device);
1285         return status;
1286     }
1287 
1288     handler = (escl_sane_t *)calloc(1, sizeof(escl_sane_t));
1289     if (handler == NULL) {
1290         escl_free_device(device);
1291         return (SANE_STATUS_NO_MEM);
1292     }
1293     handler->device = device;  // Handler owns device now.
1294     blacklist = _get_blacklist_pdf();
1295     handler->scanner = escl_capabilities(device, blacklist, &status);
1296     if (status != SANE_STATUS_GOOD) {
1297         escl_free_handler(handler);
1298         return (status);
1299     }
1300     _get_hack(name, device);
1301 
1302     status = init_options(NULL, handler);
1303     if (status != SANE_STATUS_GOOD) {
1304         escl_free_handler(handler);
1305         return (status);
1306     }
1307     handler->ps.depth = 8;
1308     handler->ps.last_frame = SANE_TRUE;
1309     handler->ps.format = SANE_FRAME_RGB;
1310     handler->ps.pixels_per_line = MM_TO_PIXEL(handler->val[OPT_BR_X].w, 300.0);
1311     handler->ps.lines = MM_TO_PIXEL(handler->val[OPT_BR_Y].w, 300.0);
1312     handler->ps.bytes_per_line = handler->ps.pixels_per_line * 3;
1313     status = sane_get_parameters(handler, 0);
1314     if (status != SANE_STATUS_GOOD) {
1315         escl_free_handler(handler);
1316         return (status);
1317     }
1318     handler->cancel = SANE_FALSE;
1319     handler->write_scan_data = SANE_FALSE;
1320     handler->decompress_scan_data = SANE_FALSE;
1321     handler->end_read = SANE_FALSE;
1322     *h = handler;
1323     return (status);
1324 }
1325 
1326 /**
1327  * \fn void sane_cancel(SANE_Handle h)
1328  * \brief Function that's used to, immediately or as quickly as possible, cancel the currently
1329  *        pending operation of the device represented by 'SANE_Handle h'.
1330  *        This functions calls the 'escl_scanner' functions, that resets the scan operations.
1331  */
1332 void
sane_cancel(SANE_Handle h)1333 sane_cancel(SANE_Handle h)
1334 {
1335     DBG (10, "escl sane_cancel\n");
1336     escl_sane_t *handler = h;
1337     if (handler->scanner->tmp)
1338     {
1339       fclose(handler->scanner->tmp);
1340       handler->scanner->tmp = NULL;
1341     }
1342     handler->scanner->work = SANE_FALSE;
1343     handler->cancel = SANE_TRUE;
1344     escl_scanner(handler->device, handler->scanner->scanJob, handler->result);
1345     free(handler->result);
1346     handler->result = NULL;
1347     free(handler->scanner->scanJob);
1348     handler->scanner->scanJob = NULL;
1349 }
1350 
1351 /**
1352  * \fn void sane_close(SANE_Handle h)
1353  * \brief Function that closes the communication with the device represented by 'SANE_Handle h'.
1354  *        This function must release the resources that were allocated to the opening of 'h'.
1355  */
1356 void
sane_close(SANE_Handle h)1357 sane_close(SANE_Handle h)
1358 {
1359     DBG (10, "escl sane_close\n");
1360     if (h != NULL) {
1361         escl_free_handler(h);
1362         h = NULL;
1363     }
1364 }
1365 
1366 /**
1367  * \fn const SANE_Option_Descriptor *sane_get_option_descriptor(SANE_Handle h, SANE_Int n)
1368  * \brief Function that retrieves a descriptor from the n number option of the scanner
1369  *        represented by 'h'.
1370  *        The descriptor remains valid until the machine is closed.
1371  *
1372  * \return s->opt + n
1373  */
1374 const SANE_Option_Descriptor *
sane_get_option_descriptor(SANE_Handle h,SANE_Int n)1375 sane_get_option_descriptor(SANE_Handle h, SANE_Int n)
1376 {
1377     DBG (10, "escl sane_get_option_descriptor\n");
1378     escl_sane_t *s = h;
1379 
1380     if ((unsigned) n >= NUM_OPTIONS || n < 0)
1381 	return (0);
1382     return (&s->opt[n]);
1383 }
1384 
1385 /**
1386  * \fn SANE_Status sane_control_option(SANE_Handle h, SANE_Int n, SANE_Action a, void *v, SANE_Int *i)
1387  * \brief Function that defines the actions to perform for the 'n' option of the machine,
1388  *        represented by 'h', if the action is 'a'.
1389  *        There are 3 types of possible actions :
1390  *        --> SANE_ACTION_GET_VALUE: 'v' must be used to provide the value of the option.
1391  *        --> SANE_ACTION_SET_VALUE: The option must take the 'v' value.
1392  *        --> SANE_ACTION_SET_AUTO: The backend or machine must affect the option with an appropriate value.
1393  *        Moreover, the parameter 'i' is used to provide additional information about the state of
1394  *        'n' option if SANE_ACTION_SET_VALUE has been performed.
1395  *
1396  * \return SANE_STATUS_GOOD if everything is OK, otherwise, SANE_STATUS_NO_MEM/SANE_STATUS_INVAL
1397  */
1398 SANE_Status
sane_control_option(SANE_Handle h,SANE_Int n,SANE_Action a,void * v,SANE_Int * i)1399 sane_control_option(SANE_Handle h, SANE_Int n, SANE_Action a, void *v, SANE_Int *i)
1400 {
1401     DBG (10, "escl sane_control_option\n");
1402     escl_sane_t *handler = h;
1403 
1404     if (i)
1405 	*i = 0;
1406     if (n >= NUM_OPTIONS || n < 0)
1407 	return (SANE_STATUS_INVAL);
1408     if (a == SANE_ACTION_GET_VALUE) {
1409 	switch (n) {
1410 	case OPT_TL_X:
1411 	case OPT_TL_Y:
1412 	case OPT_BR_X:
1413 	case OPT_BR_Y:
1414 	case OPT_NUM_OPTS:
1415 	case OPT_PREVIEW:
1416 	case OPT_GRAY_PREVIEW:
1417 	case OPT_RESOLUTION:
1418         case OPT_BRIGHTNESS:
1419         case OPT_CONTRAST:
1420         case OPT_SHARPEN:
1421 	    *(SANE_Word *) v = handler->val[n].w;
1422 	    break;
1423 	case OPT_SCAN_SOURCE:
1424 	case OPT_MODE:
1425 	    strcpy (v, handler->val[n].s);
1426 	    break;
1427 	case OPT_MODE_GROUP:
1428 	default:
1429 	    break;
1430 	}
1431 	return (SANE_STATUS_GOOD);
1432     }
1433     if (a == SANE_ACTION_SET_VALUE) {
1434 	switch (n) {
1435 	case OPT_TL_X:
1436 	case OPT_TL_Y:
1437 	case OPT_BR_X:
1438 	case OPT_BR_Y:
1439 	case OPT_NUM_OPTS:
1440 	case OPT_PREVIEW:
1441 	case OPT_GRAY_PREVIEW:
1442         case OPT_BRIGHTNESS:
1443         case OPT_CONTRAST:
1444         case OPT_SHARPEN:
1445 	    handler->val[n].w = *(SANE_Word *) v;
1446 	    if (i)
1447 		*i |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS | SANE_INFO_INEXACT;
1448 	    break;
1449 	case OPT_SCAN_SOURCE:
1450 	    DBG(10, "SET OPT_SCAN_SOURCE(%s)\n", (SANE_String_Const)v);
1451 	    init_options_small((SANE_String_Const)v, handler);
1452 	    if (i)
1453 		*i |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS | SANE_INFO_INEXACT;
1454 	    break;
1455 	case OPT_MODE:
1456 	    if (handler->val[n].s)
1457 		free (handler->val[n].s);
1458 	    handler->val[n].s = strdup (v);
1459 	    if (!handler->val[n].s) {
1460 	      DBG (10, "OPT_MODE allocation failure.\n");
1461 	      return (SANE_STATUS_NO_MEM);
1462 	    }
1463 	    DBG(10, "SET OPT_MODE(%s)\n", (SANE_String_Const)v);
1464 
1465             if (!strcasecmp(handler->val[n].s, SANE_VALUE_SCAN_MODE_GRAY)) {
1466               handler->scanner->caps[handler->scanner->source].default_color = strdup("Grayscale8");
1467 	    DBG(10, "SET OPT_MODE(Grayscale8)\n");
1468             }
1469             else if (!strcasecmp(handler->val[n].s, SANE_VALUE_SCAN_MODE_LINEART)) {
1470               handler->scanner->caps[handler->scanner->source].default_color =
1471                  strdup("BlackAndWhite1");
1472 	    DBG(10, "SET OPT_MODE(BlackAndWhite1)\n");
1473             }
1474             else {
1475               handler->scanner->caps[handler->scanner->source].default_color =
1476                  strdup("RGB24");
1477 	         DBG(10, "SET OPT_MODE(RGB24)\n");
1478             }
1479             DBG (10, "Color Mode allocation (%s).\n", handler->scanner->caps[handler->scanner->source].default_color);
1480 	    if (i)
1481 		*i |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS | SANE_INFO_INEXACT;
1482             if (handler->scanner->brightness)
1483                 handler->opt[OPT_BRIGHTNESS].cap |= SANE_CAP_INACTIVE;
1484             if (handler->scanner->contrast)
1485                 handler->opt[OPT_CONTRAST].cap   |= SANE_CAP_INACTIVE;
1486             if (handler->scanner->threshold)
1487                 handler->opt[OPT_THRESHOLD].cap  |= SANE_CAP_INACTIVE;
1488             if (handler->scanner->sharpen)
1489                 handler->opt[OPT_SHARPEN].cap  |= SANE_CAP_INACTIVE;
1490             if (!strcasecmp(handler->val[n].s, SANE_VALUE_SCAN_MODE_LINEART)) {
1491                if (handler->scanner->threshold)
1492                   handler->opt[OPT_THRESHOLD].cap  &= ~SANE_CAP_INACTIVE;
1493             }
1494             else {
1495                if (handler->scanner->brightness)
1496                   handler->opt[OPT_BRIGHTNESS].cap &= ~SANE_CAP_INACTIVE;
1497                if (handler->scanner->contrast)
1498                   handler->opt[OPT_CONTRAST].cap   &= ~SANE_CAP_INACTIVE;
1499                if (handler->scanner->sharpen)
1500                   handler->opt[OPT_SHARPEN].cap   &= ~SANE_CAP_INACTIVE;
1501             }
1502 	    break;
1503 	case OPT_RESOLUTION:
1504             handler->val[n].w = _get_resolution(handler, (int)(*(SANE_Word *) v));
1505 	    handler->scanner->caps[handler->scanner->source].default_resolution = handler->val[n].w;
1506 	    if (i)
1507 		*i |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS | SANE_INFO_INEXACT;
1508 	    break;
1509 	default:
1510 	    break;
1511 	}
1512     }
1513     return (SANE_STATUS_GOOD);
1514 }
1515 
1516 static SANE_Bool
_go_next_page(SANE_Status status,SANE_Status job)1517 _go_next_page(SANE_Status status,
1518               SANE_Status job)
1519 {
1520    // Thank's Alexander Pevzner (pzz@apevzner.com)
1521    SANE_Status st = SANE_STATUS_NO_DOCS;
1522    switch (status) {
1523       case SANE_STATUS_GOOD:
1524       case SANE_STATUS_UNSUPPORTED:
1525       case SANE_STATUS_DEVICE_BUSY: {
1526          DBG(10, "eSCL : Test next page\n");
1527          if (job != SANE_STATUS_GOOD) {
1528             DBG(10, "eSCL : Go next page\n");
1529             st = SANE_STATUS_GOOD;
1530          }
1531          break;
1532       }
1533       default:
1534          DBG(10, "eSCL : No next page\n");
1535    }
1536    return st;
1537 }
1538 
1539 /**
1540  * \fn SANE_Status sane_start(SANE_Handle h)
1541  * \brief Function that initiates acquisition of an image from the device represented by handle 'h'.
1542  *        This function calls the "escl_newjob" function and the "escl_scan" function.
1543  *
1544  * \return status (if everything is OK, status = SANE_STATUS_GOOD, otherwise, SANE_STATUS_NO_MEM/SANE_STATUS_INVAL)
1545  */
1546 SANE_Status
sane_start(SANE_Handle h)1547 sane_start(SANE_Handle h)
1548 {
1549     DBG (10, "escl sane_start\n");
1550     SANE_Status status = SANE_STATUS_GOOD;
1551     escl_sane_t *handler = h;
1552     int w = 0;
1553     int he = 0;
1554     int bps = 0;
1555 
1556     if (handler->device == NULL) {
1557         DBG(1, "Missing handler device.\n");
1558         return (SANE_STATUS_INVAL);
1559     }
1560     handler->cancel = SANE_FALSE;
1561     handler->write_scan_data = SANE_FALSE;
1562     handler->decompress_scan_data = SANE_FALSE;
1563     handler->end_read = SANE_FALSE;
1564     if (handler->scanner->work == SANE_FALSE) {
1565        SANE_Status st = escl_status(handler->device,
1566                                     handler->scanner->source,
1567                                     NULL,
1568                                     NULL);
1569        if (st != SANE_STATUS_GOOD)
1570           return st;
1571        if (handler->val[OPT_PREVIEW].w == SANE_TRUE)
1572        {
1573           int i = 0, val = 9999;
1574 
1575           if(handler->scanner->caps[handler->scanner->source].default_color)
1576              free(handler->scanner->caps[handler->scanner->source].default_color);
1577 
1578           if (handler->val[OPT_GRAY_PREVIEW].w == SANE_TRUE ||
1579 	      !strcasecmp(handler->val[OPT_MODE].s, SANE_VALUE_SCAN_MODE_GRAY))
1580 	     handler->scanner->caps[handler->scanner->source].default_color =
1581 	          strdup("Grayscale8");
1582           else
1583 	     handler->scanner->caps[handler->scanner->source].default_color =
1584 	          strdup("RGB24");
1585           if (!handler->scanner->caps[handler->scanner->source].default_color) {
1586 	     DBG (10, "Default Color allocation failure.\n");
1587 	     return (SANE_STATUS_NO_MEM);
1588 	  }
1589           for (i = 1; i < handler->scanner->caps[handler->scanner->source].SupportedResolutionsSize; i++)
1590           {
1591 	     if (val > handler->scanner->caps[handler->scanner->source].SupportedResolutions[i])
1592 	         val = handler->scanner->caps[handler->scanner->source].SupportedResolutions[i];
1593           }
1594           handler->scanner->caps[handler->scanner->source].default_resolution = val;
1595        }
1596        else
1597        {
1598           handler->scanner->caps[handler->scanner->source].default_resolution =
1599 	     handler->val[OPT_RESOLUTION].w;
1600           if (!handler->scanner->caps[handler->scanner->source].default_color) {
1601              if (!strcasecmp(handler->val[OPT_MODE].s, SANE_VALUE_SCAN_MODE_GRAY))
1602 	        handler->scanner->caps[handler->scanner->source].default_color = strdup("Grayscale8");
1603              else if (!strcasecmp(handler->val[OPT_MODE].s, SANE_VALUE_SCAN_MODE_LINEART))
1604 	        handler->scanner->caps[handler->scanner->source].default_color =
1605 	            strdup("BlackAndWhite1");
1606              else
1607 	        handler->scanner->caps[handler->scanner->source].default_color =
1608 	            strdup("RGB24");
1609           }
1610        }
1611        DBG (10, "Before newjob Color Mode allocation (%s).\n", handler->scanner->caps[handler->scanner->source].default_color);
1612        handler->scanner->caps[handler->scanner->source].height =
1613             MM_TO_PIXEL(handler->val[OPT_BR_Y].w, 300.0);
1614        handler->scanner->caps[handler->scanner->source].width =
1615             MM_TO_PIXEL(handler->val[OPT_BR_X].w, 300.0);;
1616        if (handler->x_range1.min == handler->val[OPT_TL_X].w)
1617            handler->scanner->caps[handler->scanner->source].pos_x = 0;
1618        else
1619            handler->scanner->caps[handler->scanner->source].pos_x =
1620                MM_TO_PIXEL((handler->val[OPT_TL_X].w - handler->x_range1.min),
1621                300.0);
1622        if (handler->y_range1.min == handler->val[OPT_TL_X].w)
1623            handler->scanner->caps[handler->scanner->source].pos_y = 0;
1624        else
1625            handler->scanner->caps[handler->scanner->source].pos_y =
1626                MM_TO_PIXEL((handler->val[OPT_TL_Y].w - handler->y_range1.min),
1627                300.0);
1628        DBG(10, "Calculate Size Image [%dx%d|%dx%d]\n",
1629 	        handler->scanner->caps[handler->scanner->source].pos_x,
1630 	        handler->scanner->caps[handler->scanner->source].pos_y,
1631 	        handler->scanner->caps[handler->scanner->source].width,
1632 	        handler->scanner->caps[handler->scanner->source].height);
1633        if (!handler->scanner->caps[handler->scanner->source].default_color) {
1634           DBG (10, "Default Color allocation failure.\n");
1635           return (SANE_STATUS_NO_MEM);
1636        }
1637 
1638        if (handler->scanner->threshold) {
1639           DBG(10, "Have Thresold\n");
1640           if (IS_ACTIVE(OPT_THRESHOLD)) {
1641             DBG(10, "Use Thresold [%d]\n", handler->val[OPT_THRESHOLD].w);
1642             handler->scanner->val_threshold = handler->val[OPT_THRESHOLD].w;
1643             handler->scanner->use_threshold = 1;
1644          }
1645          else  {
1646             DBG(10, "Not use Thresold\n");
1647             handler->scanner->use_threshold = 0;
1648          }
1649        }
1650        else
1651           DBG(10, "Don't have Thresold\n");
1652 
1653        if (handler->scanner->sharpen) {
1654           DBG(10, "Have Sharpen\n");
1655            if (IS_ACTIVE(OPT_SHARPEN)) {
1656              DBG(10, "Use Sharpen [%d]\n", handler->val[OPT_SHARPEN].w);
1657              handler->scanner->val_sharpen = handler->val[OPT_SHARPEN].w;
1658              handler->scanner->use_sharpen = 1;
1659           }
1660          else  {
1661             DBG(10, "Not use Sharpen\n");
1662             handler->scanner->use_sharpen = 0;
1663          }
1664        }
1665        else
1666           DBG(10, "Don't have Sharpen\n");
1667 
1668        if (handler->scanner->contrast) {
1669           DBG(10, "Have Contrast\n");
1670           if (IS_ACTIVE(OPT_CONTRAST)) {
1671              DBG(10, "Use Contrast [%d]\n", handler->val[OPT_CONTRAST].w);
1672              handler->scanner->val_contrast = handler->val[OPT_CONTRAST].w;
1673              handler->scanner->use_contrast = 1;
1674           }
1675           else  {
1676              DBG(10, "Not use Contrast\n");
1677              handler->scanner->use_contrast = 0;
1678           }
1679        }
1680        else
1681           DBG(10, "Don't have Contrast\n");
1682 
1683        if (handler->scanner->brightness) {
1684           DBG(10, "Have Brightness\n");
1685           if (IS_ACTIVE(OPT_BRIGHTNESS)) {
1686              DBG(10, "Use Brightness [%d]\n", handler->val[OPT_BRIGHTNESS].w);
1687              handler->scanner->val_brightness = handler->val[OPT_BRIGHTNESS].w;
1688              handler->scanner->use_brightness = 1;
1689           }
1690           else  {
1691              DBG(10, "Not use Brightness\n");
1692              handler->scanner->use_brightness = 0;
1693           }
1694        }
1695        else
1696           DBG(10, "Don't have Brightness\n");
1697 
1698        handler->result = escl_newjob(handler->scanner, handler->device, &status);
1699        if (status != SANE_STATUS_GOOD)
1700           return (status);
1701     }
1702     else
1703     {
1704        SANE_Status job = SANE_STATUS_UNSUPPORTED;
1705        SANE_Status st = escl_status(handler->device,
1706                                        handler->scanner->source,
1707                                        handler->result,
1708                                        &job);
1709        DBG(10, "eSCL : command returned status %s\n", sane_strstatus(st));
1710        if (_go_next_page(st, job) != SANE_STATUS_GOOD)
1711        {
1712          handler->scanner->work = SANE_FALSE;
1713          return SANE_STATUS_NO_DOCS;
1714        }
1715     }
1716     status = escl_scan(handler->scanner, handler->device, handler->scanner->scanJob, handler->result);
1717     if (status != SANE_STATUS_GOOD)
1718        return (status);
1719     if (!strcmp(handler->scanner->caps[handler->scanner->source].default_format, "image/jpeg"))
1720     {
1721        status = get_JPEG_data(handler->scanner, &w, &he, &bps);
1722     }
1723     else if (!strcmp(handler->scanner->caps[handler->scanner->source].default_format, "image/png"))
1724     {
1725        status = get_PNG_data(handler->scanner, &w, &he, &bps);
1726     }
1727     else if (!strcmp(handler->scanner->caps[handler->scanner->source].default_format, "image/tiff"))
1728     {
1729        status = get_TIFF_data(handler->scanner, &w, &he, &bps);
1730     }
1731     else if (!strcmp(handler->scanner->caps[handler->scanner->source].default_format, "application/pdf"))
1732     {
1733        status = get_PDF_data(handler->scanner, &w, &he, &bps);
1734     }
1735     else {
1736        DBG(10, "Unknown image format\n");
1737        return SANE_STATUS_INVAL;
1738     }
1739 
1740     DBG(10, "2-Size Image (%ld)[%dx%d|%dx%d]\n", handler->scanner->img_size, 0, 0, w, he);
1741 
1742     if (status != SANE_STATUS_GOOD)
1743        return (status);
1744     handler->ps.depth = 8;
1745     handler->ps.pixels_per_line = w;
1746     handler->ps.lines = he;
1747     handler->ps.bytes_per_line = w * bps;
1748     handler->ps.last_frame = SANE_TRUE;
1749     handler->ps.format = SANE_FRAME_RGB;
1750     handler->scanner->work = SANE_FALSE;
1751 //    DBG(10, "NEXT Frame [%s]\n", (handler->ps.last_frame ? "Non" : "Oui"));
1752     DBG(10, "Real Size Image [%dx%d|%dx%d]\n", 0, 0, w, he);
1753     return (status);
1754 }
1755 
1756 /**
1757  * \fn SANE_Status sane_get_parameters(SANE_Handle h, SANE_Parameters *p)
1758  * \brief Function that retrieves the device parameters represented by 'h' and stores them in 'p'.
1759  *        This function is normally used after "sane_start".
1760  *        It's in this function that we choose to assign the default color. (Color or Monochrome)
1761  *
1762  * \return status (if everything is OK, status = SANE_STATUS_GOOD, otherwise, SANE_STATUS_NO_MEM/SANE_STATUS_INVAL)
1763  */
1764 SANE_Status
sane_get_parameters(SANE_Handle h,SANE_Parameters * p)1765 sane_get_parameters(SANE_Handle h, SANE_Parameters *p)
1766 {
1767     DBG (10, "escl sane_get_parameters\n");
1768     SANE_Status status = SANE_STATUS_GOOD;
1769     escl_sane_t *handler = h;
1770 
1771     if (status != SANE_STATUS_GOOD)
1772         return (status);
1773     if (p != NULL) {
1774         p->depth = 8;
1775         p->last_frame = handler->ps.last_frame;
1776         p->format = SANE_FRAME_RGB;
1777         p->pixels_per_line = handler->ps.pixels_per_line;
1778         p->lines = handler->ps.lines;
1779         p->bytes_per_line = handler->ps.bytes_per_line;
1780     }
1781     return (status);
1782 }
1783 
1784 
1785 /**
1786  * \fn SANE_Status sane_read(SANE_Handle h, SANE_Byte *buf, SANE_Int maxlen, SANE_Int *len)
1787  * \brief Function that's used to read image data from the device represented by handle 'h'.
1788  *        The argument 'buf' is a pointer to a memory area that is at least 'maxlen' bytes long.
1789  *        The number of bytes returned is stored in '*len'.
1790  *        --> When the call succeeds, the number of bytes returned can be anywhere in the range from 0 to 'maxlen' bytes.
1791  *
1792  * \return SANE_STATUS_GOOD (if everything is OK, otherwise, SANE_STATUS_NO_MEM/SANE_STATUS_INVAL)
1793  */
1794 SANE_Status
sane_read(SANE_Handle h,SANE_Byte * buf,SANE_Int maxlen,SANE_Int * len)1795 sane_read(SANE_Handle h, SANE_Byte *buf, SANE_Int maxlen, SANE_Int *len)
1796 {
1797     DBG (10, "escl sane_read\n");
1798     escl_sane_t *handler = h;
1799     SANE_Status status = SANE_STATUS_GOOD;
1800     long readbyte;
1801 
1802     if (!handler | !buf | !len)
1803         return (SANE_STATUS_INVAL);
1804 
1805     if (handler->cancel)
1806         return (SANE_STATUS_CANCELLED);
1807     if (!handler->write_scan_data)
1808         handler->write_scan_data = SANE_TRUE;
1809     if (!handler->decompress_scan_data) {
1810         if (status != SANE_STATUS_GOOD)
1811             return (status);
1812         handler->decompress_scan_data = SANE_TRUE;
1813     }
1814     if (handler->scanner->img_data == NULL)
1815         return (SANE_STATUS_INVAL);
1816     if (!handler->end_read) {
1817         readbyte = min((handler->scanner->img_size - handler->scanner->img_read), maxlen);
1818         memcpy(buf, handler->scanner->img_data + handler->scanner->img_read, readbyte);
1819         handler->scanner->img_read = handler->scanner->img_read + readbyte;
1820         *len = readbyte;
1821         if (handler->scanner->img_read == handler->scanner->img_size)
1822             handler->end_read = SANE_TRUE;
1823         else if (handler->scanner->img_read > handler->scanner->img_size) {
1824             *len = 0;
1825             handler->end_read = SANE_TRUE;
1826             free(handler->scanner->img_data);
1827             handler->scanner->img_data = NULL;
1828             return (SANE_STATUS_INVAL);
1829         }
1830     }
1831     else {
1832         SANE_Status job = SANE_STATUS_UNSUPPORTED;
1833         *len = 0;
1834         free(handler->scanner->img_data);
1835         handler->scanner->img_data = NULL;
1836         if (handler->scanner->source != PLATEN) {
1837 	      SANE_Bool next_page = SANE_FALSE;
1838           SANE_Status st = escl_status(handler->device,
1839                                        handler->scanner->source,
1840                                        handler->result,
1841                                        &job);
1842           DBG(10, "eSCL : command returned status %s\n", sane_strstatus(st));
1843           if (_go_next_page(st, job) == SANE_STATUS_GOOD)
1844 	     next_page = SANE_TRUE;
1845           handler->scanner->work = SANE_TRUE;
1846           handler->ps.last_frame = !next_page;
1847         }
1848         return SANE_STATUS_EOF;
1849     }
1850     return (SANE_STATUS_GOOD);
1851 }
1852 
1853 SANE_Status
sane_get_select_fd(SANE_Handle __sane_unused__ h,SANE_Int __sane_unused__ * fd)1854 sane_get_select_fd(SANE_Handle __sane_unused__ h, SANE_Int __sane_unused__ *fd)
1855 {
1856     return (SANE_STATUS_UNSUPPORTED);
1857 }
1858 
1859 SANE_Status
sane_set_io_mode(SANE_Handle __sane_unused__ handle,SANE_Bool __sane_unused__ non_blocking)1860 sane_set_io_mode(SANE_Handle __sane_unused__ handle, SANE_Bool __sane_unused__ non_blocking)
1861 {
1862     return (SANE_STATUS_UNSUPPORTED);
1863 }
1864 
1865 /**
1866  * \fn void escl_curl_url(CURL *handle, const ESCL_Device *device, SANE_String_Const path)
1867  * \brief Uses the device info in 'device' and the path from 'path' to construct
1868  *        a full URL.  Sets this URL and any necessary connection options into
1869  *        'handle'.
1870  */
1871 void
escl_curl_url(CURL * handle,const ESCL_Device * device,SANE_String_Const path)1872 escl_curl_url(CURL *handle, const ESCL_Device *device, SANE_String_Const path)
1873 {
1874     int url_len;
1875     char *url;
1876 
1877     url_len = snprintf(NULL, 0, "%s://%s:%d%s",
1878                        (device->https ? "https" : "http"), device->ip_address,
1879                        device->port_nb, path);
1880     url_len++;
1881     url = (char *)malloc(url_len);
1882     snprintf(url, url_len, "%s://%s:%d%s",
1883              (device->https ? "https" : "http"), device->ip_address,
1884              device->port_nb, path);
1885 
1886     DBG( 1, "escl_curl_url: URL: %s\n", url );
1887     curl_easy_setopt(handle, CURLOPT_URL, url);
1888     free(url);
1889     DBG( 1, "Before use hack\n");
1890     if (device->hack) {
1891         DBG( 1, "Use hack\n");
1892         curl_easy_setopt(handle, CURLOPT_HTTPHEADER, device->hack);
1893     }
1894     DBG( 1, "After use hack\n");
1895     if (device->https) {
1896         DBG( 1, "Ignoring safety certificates, use https\n");
1897         curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L);
1898         curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 0L);
1899         if (device->tls > 0)
1900            curl_easy_setopt(handle, CURLOPT_SSLVERSION, device->tls);
1901     }
1902     if (device->unix_socket != NULL) {
1903         DBG( 1, "Using local socket %s\n", device->unix_socket );
1904         curl_easy_setopt(handle, CURLOPT_UNIX_SOCKET_PATH,
1905                          device->unix_socket);
1906     }
1907 }
1908