1 /* SANE - Scanner Access Now Easy.
2 
3    Copyright (C) 2008  2012 by Louis Lagendijk
4 
5    This file is part of the SANE package.
6 
7    SANE is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11 
12    SANE is distributed in the hope that it will be useful, but WITHOUT
13    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
15    License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with sane; see the file COPYING.
19    If not, see <https://www.gnu.org/licenses/>.
20 
21    As a special exception, the authors of SANE give permission for
22    additional uses of the libraries contained in this release of SANE.
23 
24    The exception is that, if you link a SANE library with other files
25    to produce an executable, this does not by itself cause the
26    resulting executable to be covered by the GNU General Public
27    License.  Your use of that executable is in no way restricted on
28    account of linking the SANE library code into it.
29 
30    This exception does not, however, invalidate any other reasons why
31    the executable file might be covered by the GNU General Public
32    License.
33 
34    If you submit changes to SANE to the maintainers to be included in
35    a subsequent release, you agree by submitting the changes that
36    those changes may be distributed with this exception intact.
37 
38    If you write modifications of your own for SANE, it is your choice
39    whether to permit this exception to apply to your modifications.
40    If you do not wish that, delete this exception notice.
41 */
42 
43 #undef BACKEND_NAME
44 #define BACKEND_NAME bjnp
45 
46 #include  "../include/sane/config.h"
47 #include  "../include/sane/sane.h"
48 
49 /*
50  * Standard types etc
51  */
52 #ifdef HAVE_STDLIB_H
53 #include <stdlib.h>
54 #endif
55 #ifdef HAVE_STRING_H
56 #include <string.h>
57 #endif
58 #include <unistd.h>
59 #include <stdio.h>
60 #ifdef HAVE_STDINT_H
61 #include <stdint.h>
62 #endif
63 #ifdef HAVE_SYS_TYPES_H
64 #include <sys/types.h>
65 #endif
66 #ifdef HAVE_SYS_TIME_H
67 #include <sys/time.h>
68 #endif
69 #ifdef HAVE_LIMITS_H
70 #include <limits.h>
71 #endif
72 #ifdef HAVE_UNISTD_H
73 #include <unistd.h>
74 #endif
75 
76 /*
77  * networking stuff
78  */
79 #ifdef HAVE_SYS_SOCKET_H
80 #include <sys/socket.h>
81 #endif
82 #ifdef HAVE_NETINET_IN_H
83 #include <netinet/in.h>
84 #endif
85 #include <netinet/tcp.h>
86 #include <arpa/inet.h>
87 #include <netdb.h>
88 #include <net/if.h>
89 #ifdef HAVE_IFADDRS_H
90 #include <ifaddrs.h>
91 #endif
92 #ifdef HAVE_SYS_SELECT_H
93 #include <sys/select.h>
94 #endif
95 #ifdef HAVE_PWD_H
96 #include <pwd.h>
97 #endif
98 #include <errno.h>
99 #ifdef HAVE_FCNTL_H
100 #include <fcntl.h>
101 #endif
102 
103 #include "pixma_bjnp_private.h"
104 #include "pixma_bjnp.h"
105 /* #include "pixma_rename.h" */
106 #include "pixma.h"
107 #include "pixma_common.h"
108 
109 #ifndef SSIZE_MAX
110 # define SSIZE_MAX      LONG_MAX
111 #endif
112 #ifndef HOST_NAME_MAX
113 # ifdef _POSIX_HOST_NAME_MAX
114 #  define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
115 # else
116 #  define HOST_NAME_MAX 255
117 # endif
118 #endif
119 
120 /* static data */
121 static bjnp_device_t device[BJNP_NO_DEVICES];
122 static int bjnp_no_devices = 0;
123 
124 /*
125  * Private functions
126  */
127 
lookup_scanner(const char * makemodel,const struct pixma_config_t * const pixma_devices[])128 static const struct pixma_config_t *lookup_scanner(const char *makemodel,
129                                                    const struct pixma_config_t *const pixma_devices[])
130 {
131   int i;
132   const struct pixma_config_t *cfg;
133   char *match;
134 
135   for (i = 0; pixma_devices[i]; i++)
136     {
137       /* loop through the device classes (mp150, mp730 etc) */
138       for (cfg = pixma_devices[i]; cfg->name; cfg++)
139         {
140           /* loop through devices in class */
141           PDBG( bjnp_dbg( LOG_DEBUG3, "lookup_scanner: Checking for %s in %s\n", makemodel, cfg->model));
142           if ((match = strcasestr (makemodel, cfg->model)) != NULL)
143             {
144               /* possible match found, make sure it is not a partial match */
145               /* MP600 and MP600R are different models! */
146               /* some models contain ranges, so check for a '-' too */
147 
148               if ((match[strlen(cfg->model)] == ' ') ||
149                   (match[strlen(cfg->model)] == '\0') ||
150                   (match[strlen(cfg->model)] == '-'))
151                 {
152                   PDBG( bjnp_dbg (LOG_DEBUG, "lookup_scanner: Scanner model found: Name %s(%s) matches %s\n", cfg->model, cfg->name, makemodel));
153                   return cfg;
154                 }
155             }
156        }
157     }
158   PDBG( bjnp_dbg (LOG_DEBUG, "lookup_scanner: Scanner model %s not found, giving up!\n", makemodel));
159   return NULL;
160 }
161 
162 static void
u8tohex(char * string,const uint8_t * value,int len)163 u8tohex (char *string, const uint8_t *value, int len )
164 {
165   int i;
166   int x;
167   const char hdigit[16] =
168     { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
169     'e', 'f'
170   };
171   for (i = 0; i < len; i++)
172     {
173       x = value[i];
174       string[ 2 * i ] = hdigit[(x >> 4) & 0xf];
175       string[ 2 * i + 1] = hdigit[x & 0xf];
176     }
177   string[2 * len ] = '\0';
178 }
179 
180 static void
u32tohex(uint32_t x,char * str)181 u32tohex (uint32_t x, char *str)
182 {
183   uint8_t uint8[4];
184   uint8[0] = (uint8_t)(x >> 24);
185   uint8[1] = (uint8_t)(x >> 16);
186   uint8[2] = (uint8_t)(x >> 8);
187   uint8[3] = (uint8_t)x ;
188   u8tohex(str, uint8, 4);
189 }
190 
191 static void
bjnp_hexdump(int level,const void * d_,unsigned len)192 bjnp_hexdump (int level, const void *d_, unsigned len)
193 {
194   const uint8_t *d = (const uint8_t *) (d_);
195   unsigned ofs, c, plen;
196   char line[100];               /* actually only 1+8+1+8*3+1+8*3+1 = 61 bytes needed */
197 
198   if (level > DBG_LEVEL)
199     return;
200   if (level == DBG_LEVEL)
201     /* if debuglevel == exact match and buffer contains more than 3 lines, print 2 lines + .... */
202     plen = (len > 64) ? 32: len;
203   else
204     plen = len;
205   ofs = 0;
206   while (ofs < plen)
207     {
208       char *p;
209       line[0] = ' ';
210       u32tohex (ofs, line + 1);
211       line[9] = ':';
212       p = line + 10;
213       for (c = 0; c != 16 && (ofs + c) < plen; c++)
214         {
215           u8tohex (p, d + ofs + c, 1);
216           p[2] = ' ';
217           p += 3;
218           if (c == 7)
219             {
220               p[0] = ' ';
221               p++;
222             }
223         }
224       p[0] = '\0';
225       bjnp_dbg (level, "%s\n", line);
226       ofs += c;
227     }
228   if (len > plen)
229     bjnp_dbg(level, "......\n");
230 }
231 
sa_is_equal(const bjnp_sockaddr_t * sa1,const bjnp_sockaddr_t * sa2)232 static int sa_is_equal( const bjnp_sockaddr_t * sa1, const bjnp_sockaddr_t * sa2)
233 {
234   if ((sa1 == NULL) || (sa2 == NULL) )
235     return 0;
236 
237   if (sa1->addr.sa_family == sa2-> addr.sa_family)
238     {
239       if( sa1 -> addr.sa_family == AF_INET)
240         {
241           if ( (sa1->ipv4.sin_port == sa2->ipv4.sin_port) &&
242                (sa1->ipv4.sin_addr.s_addr == sa2->ipv4.sin_addr.s_addr))
243             {
244             return 1;
245             }
246         }
247 #ifdef ENABLE_IPV6
248       else if (sa1 -> addr.sa_family == AF_INET6 )
249         {
250           if ( (sa1-> ipv6.sin6_port == sa2->ipv6.sin6_port) &&
251               (memcmp(&(sa1->ipv6.sin6_addr), &(sa2->ipv6.sin6_addr), sizeof(struct in6_addr)) == 0))
252             {
253               return 1;
254             }
255         }
256 #endif
257     }
258     return 0;
259 }
260 
261 static int
sa_size(const bjnp_sockaddr_t * sa)262 sa_size( const bjnp_sockaddr_t *sa)
263 {
264   switch (sa -> addr.sa_family)
265     {
266       case AF_INET:
267         return (sizeof(struct sockaddr_in) );
268 #ifdef ENABLE_IPV6
269       case AF_INET6:
270         return (sizeof(struct sockaddr_in6) );
271 #endif
272       default:
273         /* should not occur */
274         return sizeof( bjnp_sockaddr_t );
275     }
276 }
277 
278 static int
get_protocol_family(const bjnp_sockaddr_t * sa)279 get_protocol_family( const bjnp_sockaddr_t *sa)
280 {
281   switch (sa -> addr.sa_family)
282     {
283       case AF_INET:
284         return PF_INET;
285         break;
286 #ifdef ENABLE_IPV6
287       case AF_INET6:
288         return PF_INET6;
289         break;
290 #endif
291       default:
292         /* should not occur */
293         return -1;
294     }
295 }
296 
297 static void
get_address_info(const bjnp_sockaddr_t * addr,char * addr_string,int * port)298 get_address_info ( const bjnp_sockaddr_t *addr, char * addr_string, int *port)
299 {
300   char tmp_addr[BJNP_HOST_MAX];
301   if ( addr->addr.sa_family == AF_INET)
302     {
303       inet_ntop( AF_INET, &(addr -> ipv4.sin_addr.s_addr), addr_string, BJNP_HOST_MAX);
304       *port = ntohs (addr->ipv4.sin_port);
305     }
306 #ifdef ENABLE_IPV6
307   else if (addr->addr.sa_family == AF_INET6)
308     {
309       inet_ntop( AF_INET6, addr -> ipv6.sin6_addr.s6_addr, tmp_addr, sizeof(tmp_addr) );
310 
311       if (IN6_IS_ADDR_LINKLOCAL( &(addr -> ipv6.sin6_addr) ) )
312           sprintf(addr_string, "[%s%%%d]", tmp_addr, addr -> ipv6.sin6_scope_id);
313 
314       *port = ntohs (addr->ipv6.sin6_port);
315     }
316 #endif
317   else
318     {
319       /* unknown address family, should not occur */
320       strcpy(addr_string, "Unknown address family");
321       *port = 0;
322     }
323 }
324 
325 static int
parse_IEEE1284_to_model(char * scanner_id,char * model)326 parse_IEEE1284_to_model (char *scanner_id, char *model)
327 {
328 /*
329  * parses the  IEEE1284  ID of the scanner to retrieve make and model
330  * of the scanner
331  * Returns: 0 = not found
332  *          1 = found, model is set
333  */
334 
335   char s[BJNP_IEEE1284_MAX];
336   char *tok;
337   char * model_str;
338 
339   strncpy (s, scanner_id, BJNP_IEEE1284_MAX);
340   s[BJNP_IEEE1284_MAX - 1] = '\0';
341   model[0] = '\0';
342 
343   tok = strtok (s, ";");
344   while (tok != NULL)
345     {
346       /* MDL contains make and model */
347 
348       if (strncmp (tok, "MDL:", strlen("MDL:")) == 0)
349 	{
350 	  model_str = tok + strlen("MDL:");
351 	  strncpy (model, model_str, BJNP_MODEL_MAX);
352 	  model[BJNP_MODEL_MAX -1] = '\0';
353 	  return 1;
354 	}
355       tok = strtok (NULL, ";");
356     }
357   return 0;
358 }
359 
360 static int
charTo2byte(char * d,const char * s,int len)361 charTo2byte (char *d, const char *s, int len)
362 {
363   /*
364    * copy ASCII string to UTF-16 unicode string
365    * len is length of destination buffer
366    * Returns: number of characters copied
367    */
368 
369   int done = 0;
370   int copied = 0;
371   int i;
372 
373   len = len / 2;
374   for (i = 0; i < len; i++)
375     {
376       d[2 * i] = '\0';
377       if (s[i] == '\0')
378 	{
379 	  done = 1;
380 	}
381       if (done == 0)
382 	{
383 	  d[2 * i + 1] = s[i];
384 	  copied++;
385 	}
386       else
387 	d[2 * i + 1] = '\0';
388     }
389   return copied;
390 }
391 
get_protocol_by_method(char * method)392 static bjnp_protocol_defs_t *get_protocol_by_method( char *method)
393 {
394   int i = 0;
395   while ( bjnp_protocol_defs[i].method_string != NULL)
396     {
397       if (strcmp(method, bjnp_protocol_defs[i].method_string) == 0)
398         {
399           return &bjnp_protocol_defs[i];
400         }
401       i++;
402     }
403   return NULL;
404 }
405 
get_protocol_by_proto_string(char * proto_string)406 static bjnp_protocol_defs_t *get_protocol_by_proto_string( char *proto_string)
407 {
408   int i = 0;
409   while ( bjnp_protocol_defs[i].proto_string != NULL)
410     {
411       if (strncmp(proto_string, bjnp_protocol_defs[i].proto_string, 4) == 0)
412         {
413           return &bjnp_protocol_defs[i];
414         }
415       i++;
416     }
417   return NULL;
418 }
419 
420 static char *
getusername(void)421 getusername (void)
422 {
423   static char noname[] = "sane_pixma";
424   struct passwd *pwdent;
425 
426 #ifdef HAVE_PWD_H
427   if (((pwdent = getpwuid (geteuid ())) != NULL) && (pwdent->pw_name != NULL))
428     return pwdent->pw_name;
429 #endif
430   return noname;
431 }
432 
433 
434 static char *
determine_scanner_serial(const char * hostname,const char * mac_address,char * serial)435 determine_scanner_serial (const char *hostname, const char * mac_address, char *serial)
436 {
437   char *dot;
438   char copy[BJNP_HOST_MAX];
439 
440   /* determine a "serial number" for the scanner */
441   /* if available we use the hostname or ipv4 address of the printer */
442   /* if we only have a literal ipv6 address, we use the mac-address */
443 
444   strcpy(copy, hostname);
445   if (strlen (copy) >= SERIAL_MAX)
446     {
447       /* make the string fit into the serial */
448       /* if this is a FQDN, not an ip-address, remove domain part of the name */
449       if ((dot = strchr (copy, '.')) != NULL)
450         {
451           *dot = '\0';
452         }
453     }
454   /* check if name is still to long. If so use the mac-address */
455   if (strlen(copy) >= SERIAL_MAX)
456     {
457       strcpy(copy, mac_address);
458     }
459   strcpy( serial, copy );
460   return serial;
461 }
462 
463 static int
split_uri(const char * devname,char * method,char * host,char * port,char * args)464 split_uri (const char *devname, char *method, char *host, char *port,
465 	   char *args)
466 {
467   char copy[1024];
468   char *start;
469   char next;
470   int i;
471 
472   strncpy (copy, devname, 1024);
473   copy[1023] = '\0';
474   start = copy;
475 
476 /*
477  * retrieve method
478  */
479   i = 0;
480   while ((start[i] != '\0') && (start[i] != ':'))
481     {
482       i++;
483     }
484 
485   if (((strncmp (start + i, "://", 3) != 0)) || (i > BJNP_METHOD_MAX -1 ))
486     {
487       PDBG (bjnp_dbg (LOG_NOTICE, "split_uri: ERROR - Can not find method in %s (offset %d)\n",
488 		       devname, i));
489       return -1;
490     }
491 
492   start[i] = '\0';
493   strcpy (method, start);
494   start = start + i + 3;
495 
496 /*
497  * retrieve host
498  */
499 
500   if (start[0] == '[')
501     {
502       /* literal IPv6 address */
503 
504       char *end_of_address = strchr(start, ']');
505 
506       if ( ( end_of_address == NULL) ||
507            ( (end_of_address[1] != ':') && (end_of_address[1] != '/' ) &&  (end_of_address[1] != '\0' )) ||
508            ( (end_of_address - start) >= BJNP_HOST_MAX ) )
509         {
510           PDBG (bjnp_dbg (LOG_NOTICE, "split_uri: ERROR - Can not find hostname or address in %s\n", devname));
511           return -1;
512         }
513       next = end_of_address[1];
514       *end_of_address = '\0';
515       strcpy(host, start + 1);
516       start = end_of_address + 2;
517     }
518   else
519     {
520       i = 0;
521       while ((start[i] != '\0') && (start[i] != '/') && (start[i] != ':'))
522         {
523           i++;
524         }
525       next = start[i];
526       start[i] = '\0';
527       if ((i == 0) || (i >= BJNP_HOST_MAX ) )
528         {
529           PDBG (bjnp_dbg (LOG_NOTICE, "split_uri: ERROR - Can not find hostname or address in %s\n", devname));
530           return -1;
531         }
532       strcpy (host, start);
533       start = start + i +1;
534     }
535 
536 
537 /*
538  * retrieve port number
539  */
540 
541   if (next != ':')
542     strcpy(port, "");
543   else
544     {
545       char *end_of_port = strchr(start, '/');
546       if (end_of_port == NULL)
547         {
548           next = '\0';
549         }
550       else
551         {
552           next = *end_of_port;
553           *end_of_port = '\0';
554         }
555       if ((strlen(start) == 0) || (strlen(start) >= BJNP_PORT_MAX ) )
556         {
557           PDBG (bjnp_dbg (LOG_NOTICE, "split_uri: ERROR - Can not find port in %s (have \"%s\")\n", devname, start));
558           return -1;
559         }
560       strcpy(port, start);
561       start = end_of_port + 1;
562     }
563 
564 /*
565  * Retrieve arguments
566  */
567 
568   if (next == '/')
569     {
570     i = strlen(start);
571     if ( i >= BJNP_ARGS_MAX)
572       {
573         PDBG (bjnp_dbg (LOG_NOTICE, "split_uri: ERROR - Argument string too long in %s\n", devname));
574       }
575     strcpy (args, start);
576     }
577   else
578     strcpy (args, "");
579   return 0;
580 }
581 
582 
583 
584 static void
set_cmd_from_string(char * protocol_string,struct BJNP_command * cmd,char cmd_code,int payload_len)585 set_cmd_from_string (char* protocol_string, struct BJNP_command *cmd, char cmd_code, int payload_len)
586 {
587   /*
588    * Set command buffer with command code, session_id and length of payload
589    * Returns: sequence number of command
590    */
591 
592   memcpy (cmd->BJNP_id, protocol_string, sizeof (cmd->BJNP_id));
593   cmd->dev_type = BJNP_CMD_SCAN;
594   cmd->cmd_code = cmd_code;
595   cmd->unknown1 = htons (0);
596 
597   /* device not yet opened, use 0 for serial and session) */
598   cmd->seq_no = htons (0);
599   cmd->session_id = htons (0);
600   cmd->payload_len = htonl (payload_len);
601 }
602 
603 static void
set_cmd_for_dev(int devno,struct BJNP_command * cmd,char cmd_code,int payload_len)604 set_cmd_for_dev (int devno, struct BJNP_command *cmd, char cmd_code, int payload_len)
605 {
606   /*
607    * Set command buffer with command code, session_id and length of payload
608    * Returns: sequence number of command
609    */
610 
611   memcpy(cmd->BJNP_id, device[devno].protocol_string, sizeof (cmd->BJNP_id));
612   cmd->dev_type = BJNP_CMD_SCAN;
613   cmd->cmd_code = cmd_code;
614   cmd->unknown1 = htons (0);
615   cmd->seq_no = htons (++(device[devno].serial));
616   cmd->session_id = (cmd_code == CMD_UDP_POLL ) ? 0 : htons (device[devno].session_id);
617   device[devno].last_cmd = cmd_code;
618   cmd->payload_len = htonl (payload_len);
619 }
620 
621 static int
bjnp_setup_udp_socket(const int dev_no)622 bjnp_setup_udp_socket ( const int dev_no )
623 {
624   /*
625    * Setup a udp socket for the given device
626    * Returns the socket or -1 in case of error
627    */
628 
629   int sockfd;
630   char addr_string[256];
631   int port;
632   bjnp_sockaddr_t * addr = device[dev_no].addr;
633 
634   get_address_info( addr, addr_string, &port);
635 
636   PDBG (bjnp_dbg (LOG_DEBUG, "setup_udp_socket: Setting up a UDP socket, dest: %s  port %d\n",
637 		   addr_string, port ) );
638 
639   if ((sockfd = socket (get_protocol_family( addr ), SOCK_DGRAM, IPPROTO_UDP)) == -1)
640     {
641       PDBG (bjnp_dbg
642 	    (LOG_CRIT, "setup_udp_socket: ERROR - can not open socket - %s\n",
643 	     strerror (errno)));
644       return -1;
645     }
646 
647   if (connect
648       (sockfd, &(device[dev_no].addr->addr), sa_size(device[dev_no].addr) )!= 0)
649     {
650       PDBG (bjnp_dbg
651 	    (LOG_CRIT, "setup_udp_socket: ERROR - connect failed- %s\n",
652 	     strerror (errno)));
653       close(sockfd);
654       return -1;
655     }
656   return sockfd;
657 }
658 
659 static int
udp_command(const int dev_no,char * command,int cmd_len,char * response,int resp_len)660 udp_command (const int dev_no, char *command, int cmd_len, char *response,
661 	     int resp_len)
662 {
663   /*
664    * send udp command to given device and receive the response`
665    * returns: the length of the response or -1
666    */
667   int sockfd;
668   struct timeval timeout;
669   int result;
670   int try, attempt;
671   int numbytes;
672   fd_set fdset;
673   struct BJNP_command *resp = (struct BJNP_command *) response;
674   struct BJNP_command *cmd = (struct BJNP_command *) command;
675 
676   if ( (sockfd = bjnp_setup_udp_socket(dev_no) ) == -1 )
677     {
678       PDBG (bjnp_dbg( LOG_CRIT, "udp_command: ERROR - Can not setup socket\n") );
679       return -1;
680     }
681 
682   for (try = 0; try < BJNP_UDP_RETRY_MAX; try++)
683     {
684       if ((numbytes = send (sockfd, command, cmd_len, 0)) != cmd_len)
685 	{
686 	  PDBG (bjnp_dbg
687 		(LOG_NOTICE, "udp_command: ERROR - Sent %d bytes, expected %d\n",
688 		 numbytes, cmd_len));
689 	  continue;
690 	}
691 
692       attempt = 0;
693 
694       /* wait for data to be received, ignore signals being received */
695       /* skip late udp responses (they have an incorrect sequence number */
696       do
697 	{
698 	  FD_ZERO (&fdset);
699 	  FD_SET (sockfd, &fdset);
700 
701 	  timeout.tv_sec = device[dev_no].bjnp_ip_timeout /1000;
702 	  timeout.tv_usec = device[dev_no].bjnp_ip_timeout %1000;
703 	}
704       while (((result =
705 	       select (sockfd + 1, &fdset, NULL, NULL, &timeout)) <= 0)
706 	     && (errno == EINTR) && (attempt++ < BJNP_MAX_SELECT_ATTEMPTS)
707              && resp-> seq_no != cmd->seq_no);
708 
709       if (result <= 0)
710 	{
711 	  PDBG (bjnp_dbg
712 		(LOG_NOTICE, "udp_command: ERROR - select failed: %s\n",
713 		 result == 0 ? "timed out" : strerror (errno)));
714 	  continue;
715 	}
716 
717       if ((numbytes = recv (sockfd, response, resp_len, 0)) == -1)
718 	{
719 	  PDBG (bjnp_dbg
720 		(LOG_NOTICE, "udp_command: ERROR - recv failed: %s",
721 		 strerror (errno)));
722 	  continue;
723 	}
724       close(sockfd);
725       return numbytes;
726     }
727 
728   /* no response even after retry */
729 
730   close(sockfd);
731   PDBG (bjnp_dbg
732         (LOG_CRIT, "udp_command: ERROR - no data received (timeout = %d)\n", device[dev_no].bjnp_ip_timeout ) );
733   return -1;
734 }
735 
736 static int
get_scanner_id(const int dev_no,char * model)737 get_scanner_id (const int dev_no, char *model)
738 {
739   /*
740    * get scanner identity
741    * Sets model (make and model)
742    * Return 0 on success, -1 in case of errors
743    */
744 
745   struct BJNP_command cmd;
746   struct IDENTITY *id;
747   char scanner_id[BJNP_IEEE1284_MAX];
748   int resp_len;
749   char resp_buf[BJNP_RESP_MAX];
750   int id_len;
751 
752   /* set defaults */
753 
754   strcpy (model, "Unidentified scanner");
755 
756   set_cmd_for_dev (dev_no, &cmd, CMD_UDP_GET_ID, 0);
757 
758   PDBG (bjnp_dbg (LOG_DEBUG2, "get_scanner_id: Get scanner identity\n"));
759   PDBG (bjnp_hexdump (LOG_DEBUG2, (char *) &cmd,
760 		       sizeof (struct BJNP_command)));
761 
762   if ( ( resp_len =  udp_command (dev_no, (char *) &cmd, sizeof (struct BJNP_command),
763 		 resp_buf, BJNP_RESP_MAX) ) < (int)sizeof(struct BJNP_command) )
764     {
765       PDBG (bjnp_dbg (LOG_DEBUG, "get_scanner_id: ERROR - Failed to retrieve scanner identity:\n"));
766       return -1;
767     }
768   PDBG (bjnp_dbg (LOG_DEBUG2, "get_scanner_id: scanner identity:\n"));
769   PDBG (bjnp_hexdump (LOG_DEBUG2, resp_buf, resp_len));
770 
771   id = (struct IDENTITY *) resp_buf;
772 
773   if (device[dev_no].protocol == PROTOCOL_BJNP)
774     {
775       id_len = MIN(ntohl( id-> cmd.payload_len ) - sizeof(id-> payload.bjnp.id_len), BJNP_IEEE1284_MAX);
776       strncpy(scanner_id, id->payload.bjnp.id, id_len);
777       scanner_id[id_len] = '\0';
778     }
779   else
780     {
781       id_len = MIN(ntohl( id-> cmd.payload_len ), BJNP_IEEE1284_MAX);
782       strncpy(scanner_id, id->payload.mfnp.id, id_len);
783       scanner_id[id_len] = '\0';
784     }
785   PDBG (bjnp_dbg (LOG_INFO, "get_scanner_id: Scanner identity string = %s - length = %d\n", scanner_id, id_len));
786 
787   /* get make&model from IEEE1284 id  */
788 
789   if (model != NULL)
790   {
791     parse_IEEE1284_to_model (scanner_id, model);
792     PDBG (bjnp_dbg (LOG_INFO, "get_scanner_id: Scanner model = %s\n", model));
793   }
794   return 0;
795 }
796 
797 static int
get_scanner_name(const bjnp_sockaddr_t * scanner_sa,char * host)798 get_scanner_name(const bjnp_sockaddr_t *scanner_sa, char *host)
799 {
800   /*
801    * Parse identify command responses to ip-address
802    * and hostname. Return qulity of the address
803    */
804 
805   struct addrinfo *results;
806   struct addrinfo *result;
807   char ip_address[BJNP_HOST_MAX];
808   int port;
809   int error;
810   int match = 0;
811   int level;
812   char service[64];
813 
814 #ifdef ENABLE_IPV6
815   if ( ( scanner_sa -> addr.sa_family == AF_INET6 ) &&
816        ( IN6_IS_ADDR_LINKLOCAL( &(scanner_sa -> ipv6.sin6_addr ) ) ) )
817     level = BJNP_ADDRESS_IS_LINK_LOCAL;
818   else
819 #endif
820     level = BJNP_ADDRESS_IS_GLOBAL;
821 
822   get_address_info( scanner_sa, ip_address, &port );
823 
824   /* do reverse name lookup, if hostname can not be found return ip-address */
825 
826   if( (error = getnameinfo( &(scanner_sa -> addr) , sa_size( scanner_sa),
827                   host, BJNP_HOST_MAX , NULL, 0, NI_NAMEREQD) ) != 0 )
828     {
829       PDBG (bjnp_dbg(LOG_INFO, "get_scanner_name: Name for %s not found : %s\n",
830                       ip_address, gai_strerror(error) ) );
831       strcpy(host, ip_address);
832       return level;
833     }
834   else
835     {
836       sprintf(service, "%d", port);
837       /* some buggy routers return rubbish if reverse lookup fails, so
838        * we do a forward lookup on the received name to see if the result matches */
839 
840       if (getaddrinfo(host , service, NULL, &results) == 0)
841         {
842           result = results;
843 
844           while (result != NULL)
845             {
846                if(sa_is_equal( scanner_sa, (bjnp_sockaddr_t *)result-> ai_addr))
847                  {
848                      /* found match, good */
849                      PDBG (bjnp_dbg (LOG_INFO,
850                               "get_scanner_name: Forward lookup for %s succeeded, using as hostname\n", host));
851                     match = 1;
852                     level = BJNP_ADDRESS_HAS_FQDN;
853                     break;
854                  }
855               result = result-> ai_next;
856             }
857           freeaddrinfo(results);
858 
859           if (match != 1)
860             {
861               PDBG (bjnp_dbg (LOG_INFO,
862                  "get_scanner_name: Forward lookup for %s succeeded, IP-address does not match, using IP-address %s instead\n",
863                  host, ip_address));
864               strcpy (host, ip_address);
865             }
866          }
867        else
868          {
869            /* forward lookup failed, use ip-address */
870            PDBG ( bjnp_dbg (LOG_INFO, "get_scanner_name: Forward lookup of %s failed, using IP-address", ip_address));
871            strcpy (host, ip_address);
872          }
873     }
874   return level;
875 }
876 
877 static int
get_port_from_sa(const bjnp_sockaddr_t scanner_sa)878 get_port_from_sa(const bjnp_sockaddr_t scanner_sa)
879 {
880 #ifdef ENABLE_IPV6
881   if ( scanner_sa.addr.sa_family == AF_INET6 )
882     {
883       return ntohs(scanner_sa.ipv6.sin6_port);
884     }
885   else
886 #endif
887   if ( scanner_sa.addr.sa_family == AF_INET )
888     {
889       return ntohs(scanner_sa.ipv4.sin_port);
890     }
891   return -1;
892 }
893 
create_broadcast_socket(const bjnp_sockaddr_t * local_addr)894 static int create_broadcast_socket( const bjnp_sockaddr_t * local_addr )
895 {
896   int sockfd = -1;
897   int broadcast = 1;
898   int ipv6_v6only = 1;
899 
900 
901  if ((sockfd = socket (local_addr-> addr.sa_family, SOCK_DGRAM, 0)) == -1)
902     {
903       PDBG (bjnp_dbg
904             (LOG_CRIT, "create_broadcast_socket: ERROR - can not open socket - %s",
905              strerror (errno)));
906       return -1;
907     }
908 
909   /* Set broadcast flag on socket */
910 
911   if (setsockopt
912       (sockfd, SOL_SOCKET, SO_BROADCAST, (const char *) &broadcast,
913        sizeof (broadcast)) != 0)
914     {
915       PDBG (bjnp_dbg
916             (LOG_CRIT,
917              "create_broadcast_socket: ERROR - setting socket option SO_BROADCAST failed - %s",
918              strerror (errno)));
919       close (sockfd);
920       return -1;
921     };
922 
923   /* For an IPv6 socket, bind to v6 only so a V6 socket can co-exist with a v4 socket */
924   if ( (local_addr -> addr.sa_family == AF_INET6) && ( setsockopt
925       (sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (const char *) &ipv6_v6only,
926        sizeof (ipv6_v6only)) != 0) )
927     {
928       PDBG (bjnp_dbg
929             (LOG_CRIT,
930              "create_broadcast_socket: ERROR - setting socket option IPV6_V6ONLY failed - %s",
931              strerror (errno)));
932       close (sockfd);
933       return -1;
934     };
935 
936   if (bind
937       (sockfd, &(local_addr->addr),
938        (socklen_t) sa_size( local_addr)) != 0)
939     {
940       PDBG (bjnp_dbg
941             (LOG_CRIT,
942              "create_broadcast_socket: ERROR - bind socket to local address failed - %s\n",
943              strerror (errno)));
944       close (sockfd);
945       return -1;
946     }
947   return sockfd;
948 }
949 
950 static int
prepare_socket(const char * if_name,const bjnp_sockaddr_t * local_sa,const bjnp_sockaddr_t * broadcast_sa,bjnp_sockaddr_t * dest_sa)951 prepare_socket(const char *if_name, const bjnp_sockaddr_t *local_sa,
952                const bjnp_sockaddr_t *broadcast_sa, bjnp_sockaddr_t * dest_sa)
953 {
954   /*
955    * Prepare a socket for broadcast or multicast
956    * Input:
957    * if_name: the name of the interface
958    * local_sa: local address to use
959    * broadcast_sa: broadcast address to use, if NULL we use all hosts
960    * dest_sa: (write) where to return destination address of broadcast
961    * returns: open socket or -1
962    */
963 
964   int socket = -1;
965   bjnp_sockaddr_t local_sa_copy;
966 
967   if ( local_sa == NULL )
968     {
969       PDBG (bjnp_dbg (LOG_DEBUG,
970                        "prepare_socket: %s is not a valid IPv4 interface, skipping...\n",
971                        if_name));
972       return -1;
973     }
974 
975   memset( &local_sa_copy, 0, sizeof(local_sa_copy) );
976   memcpy( &local_sa_copy, local_sa, sa_size(local_sa) );
977 
978   switch( local_sa_copy.addr.sa_family )
979     {
980       case AF_INET:
981         {
982           local_sa_copy.ipv4.sin_port = htons(BJNP_PORT_SCAN);
983 
984           if (local_sa_copy.ipv4.sin_addr.s_addr == htonl (INADDR_LOOPBACK) )
985             {
986               /* not a valid interface */
987 
988               PDBG (bjnp_dbg (LOG_DEBUG,
989                                "prepare_socket: %s is not a valid IPv4 interface, skipping...\n",
990 	                       if_name));
991               return -1;
992             }
993 
994 
995           /* send broadcasts to the broadcast address of the interface */
996 
997           memcpy(dest_sa, broadcast_sa, sa_size(dest_sa) );
998 
999 	  /* we fill port when we send the broadcast */
1000           dest_sa -> ipv4.sin_port = htons(0);
1001 
1002           if ( (socket = create_broadcast_socket( &local_sa_copy) ) != -1)
1003             {
1004                PDBG (bjnp_dbg (LOG_INFO, "prepare_socket: %s is IPv4 capable, sending broadcast, socket = %d\n",
1005                       if_name, socket));
1006             }
1007           else
1008             {
1009               PDBG (bjnp_dbg (LOG_INFO, "prepare_socket: ERROR - %s is IPv4 capable, but failed to create a socket.\n",
1010                     if_name));
1011               return -1;
1012             }
1013         }
1014         break;
1015 #ifdef ENABLE_IPV6
1016       case AF_INET6:
1017         {
1018           local_sa_copy.ipv6.sin6_port = htons(BJNP_PORT_SCAN);
1019 
1020           if (IN6_IS_ADDR_LOOPBACK( &(local_sa_copy.ipv6.sin6_addr) ) )
1021             {
1022               /* not a valid interface */
1023 
1024               PDBG (bjnp_dbg (LOG_DEBUG,
1025                                "prepare_socket: %s is not a valid IPv6 interface, skipping...\n",
1026 	                       if_name));
1027               return -1;
1028             }
1029           else
1030             {
1031               dest_sa -> ipv6.sin6_family = AF_INET6;
1032 
1033               /* We fill port when we send the broadcast */
1034               dest_sa -> ipv6.sin6_port = htons(0);
1035 
1036               inet_pton(AF_INET6, "ff02::1", dest_sa -> ipv6.sin6_addr.s6_addr);
1037               if ( (socket = create_broadcast_socket( &local_sa_copy ) ) != -1)
1038                 {
1039                    PDBG (bjnp_dbg (LOG_INFO, "prepare_socket: %s is IPv6 capable, sending broadcast, socket = %d\n",
1040                           if_name, socket));
1041                 }
1042               else
1043                 {
1044                   PDBG (bjnp_dbg (LOG_INFO, "prepare_socket: ERROR - %s is IPv6 capable, but failed to create a socket.\n",
1045                         if_name));
1046                   return -1;
1047                 }
1048             }
1049           }
1050           break;
1051 #endif
1052 
1053       default:
1054         socket = -1;
1055     }
1056   return socket;
1057 }
1058 
1059 static int
bjnp_send_broadcast(int sockfd,const bjnp_sockaddr_t * broadcast_addr,int port,struct BJNP_command cmd,int size)1060 bjnp_send_broadcast (int sockfd, const bjnp_sockaddr_t * broadcast_addr, int port,
1061                      struct BJNP_command cmd, int size)
1062 {
1063   int num_bytes;
1064   bjnp_sockaddr_t dest_addr;
1065 
1066   /* set address to send packet to broadcast address of interface, */
1067   /* with port set to the destination port */
1068 
1069   memcpy(&dest_addr,  broadcast_addr, sizeof(dest_addr));
1070   if( dest_addr.addr.sa_family == AF_INET)
1071     {
1072       dest_addr.ipv4.sin_port = htons(port);
1073     }
1074 #ifdef ENABLE_IPV6
1075   if( dest_addr.addr.sa_family == AF_INET6)
1076     {
1077       dest_addr.ipv6.sin6_port = htons(port);
1078     }
1079 #endif
1080 
1081   if ((num_bytes = sendto (sockfd, &cmd, size, 0,
1082 			  &(dest_addr.addr),
1083 			  sa_size( broadcast_addr)) ) != size)
1084     {
1085       PDBG (bjnp_dbg (LOG_INFO,
1086 		       "bjnp_send_broadcast: Socket: %d: ERROR - sent only %x = %d bytes of packet, error = %s\n",
1087 		       sockfd, num_bytes, num_bytes, strerror (errno)));
1088       /* not allowed, skip this interface */
1089 
1090       return -1;
1091     }
1092   return sockfd;
1093 }
1094 
1095 static void
bjnp_finish_job(int devno)1096 bjnp_finish_job (int devno)
1097 {
1098 /*
1099  * Signal end of scanjob to scanner
1100  */
1101 
1102   char resp_buf[BJNP_RESP_MAX];
1103   int resp_len;
1104   struct BJNP_command cmd;
1105 
1106   set_cmd_for_dev (devno, &cmd, CMD_UDP_CLOSE, 0);
1107 
1108   PDBG (bjnp_dbg (LOG_DEBUG2, "bjnp_finish_job: Finish scanjob\n"));
1109   PDBG (bjnp_hexdump
1110 	(LOG_DEBUG2, (char *) &cmd, sizeof (struct BJNP_command)));
1111   resp_len =
1112     udp_command (devno, (char *) &cmd, sizeof (struct BJNP_command), resp_buf,
1113 		 BJNP_RESP_MAX);
1114 
1115   if (resp_len != sizeof (struct BJNP_command))
1116     {
1117       PDBG (bjnp_dbg
1118 	    (LOG_INFO,
1119 	     "bjnp_finish_job: ERROR - Received %d characters on close scanjob command, expected %d\n",
1120 	     resp_len, (int) sizeof (struct BJNP_command)));
1121       return;
1122     }
1123   PDBG (bjnp_dbg (LOG_DEBUG2, "bjnp_finish_job: Finish scanjob response\n"));
1124   PDBG (bjnp_hexdump (LOG_DEBUG2, resp_buf, resp_len));
1125 
1126 }
1127 
1128 #ifdef PIXMA_BJNP_USE_STATUS
1129 static int
bjnp_poll_scanner(int devno,char type,char * hostname,char * user,SANE_Byte * status,int size)1130 bjnp_poll_scanner (int devno, char type,char *hostname, char *user, SANE_Byte *status, int size)
1131 {
1132 /*
1133  * send details of user to the scanner
1134  */
1135 
1136   char cmd_buf[BJNP_CMD_MAX];
1137   char resp_buf[BJNP_RESP_MAX];
1138   int resp_len;
1139   int len = 0;			/* payload length */
1140   int buf_len;			/* length of the whole command  buffer */
1141   struct POLL_DETAILS *poll;
1142   struct POLL_RESPONSE *response;
1143   char user_host[256];
1144   time_t t;
1145   int user_host_len;
1146 
1147   poll = (struct POLL_DETAILS *) cmd_buf;
1148   memset( poll, 0, sizeof( struct POLL_DETAILS));
1149   memset( &resp_buf, 0, sizeof( resp_buf) );
1150 
1151 
1152   /* create payload */
1153   poll->type = htons(type);
1154 
1155   user_host_len =  sizeof( poll -> extensions.type2.user_host);
1156   snprintf(user_host, (user_host_len /2) ,"%s  %s", user, hostname);
1157   user_host[ user_host_len /2 + 1] = '\0';
1158 
1159   switch( type) {
1160     case 0:
1161       len = 80;
1162       break;
1163     case 1:
1164       charTo2byte(poll->extensions.type1.user_host, user_host, user_host_len);
1165       len = 80;
1166       break;
1167     case 2:
1168       poll->extensions.type2.dialog = htonl(device[devno].dialog);
1169       charTo2byte(poll->extensions.type2.user_host, user_host, user_host_len);
1170       poll->extensions.type2.unknown_1 = htonl(0x14);
1171       poll->extensions.type2.unknown_2 = htonl(0x10);
1172       t = time (NULL);
1173       strftime (poll->extensions.type2.ascii_date,
1174                 sizeof (poll->extensions.type2.ascii_date),
1175                "%Y%m%d%H%M%S", localtime (&t));
1176       len = 116;
1177       break;
1178     case 5:
1179       poll->extensions.type5.dialog = htonl(device[devno].dialog);
1180       charTo2byte(poll->extensions.type5.user_host, user_host, user_host_len);
1181       poll->extensions.type5.unknown_1 = htonl(0x14);
1182       poll->extensions.type5.key = htonl(device[devno].status_key);
1183       len = 100;
1184       break;
1185     default:
1186       PDBG (bjnp_dbg (LOG_INFO, "bjnp_poll_scanner: unknown packet type: %d\n", type));
1187       return -1;
1188   };
1189   /* we can only now set the header as we now know the length of the payload */
1190   set_cmd_for_dev (devno, (struct BJNP_command *) cmd_buf, CMD_UDP_POLL,
1191 	   len);
1192 
1193   buf_len = len + sizeof(struct BJNP_command);
1194   PDBG (bjnp_dbg (LOG_DEBUG2, "bjnp_poll_scanner: Poll details (type %d)\n", type));
1195   PDBG (bjnp_hexdump (LOG_DEBUG2, cmd_buf,
1196 		       buf_len));
1197 
1198   resp_len = udp_command (devno, cmd_buf, buf_len,  resp_buf, BJNP_RESP_MAX);
1199 
1200   if (resp_len > 0)
1201     {
1202       PDBG (bjnp_dbg (LOG_DEBUG2, "bjnp_poll_scanner: Poll details response:\n"));
1203       PDBG (bjnp_hexdump (LOG_DEBUG2, resp_buf, resp_len));
1204       response = (struct POLL_RESPONSE *) resp_buf;
1205 
1206       device[devno].dialog = ntohl( response -> dialog );
1207 
1208       if ( response -> result[3] == 1 )
1209         {
1210           return BJNP_RESTART_POLL;
1211         }
1212       if ( (response -> result[2] & 0x80) != 0)
1213         {
1214           memcpy( status, response->status, size);
1215           PDBG( bjnp_dbg(LOG_INFO, "bjnp_poll_scanner: received button status!\n"));
1216 	  PDBG (bjnp_hexdump( LOG_DEBUG2, status, size ));
1217 	  device[devno].status_key = ntohl( response -> key );
1218           return  size;
1219         }
1220     }
1221   return 0;
1222 }
1223 #endif
1224 
1225 static void
bjnp_send_job_details(int devno,char * hostname,char * user,char * title)1226 bjnp_send_job_details (int devno, char *hostname, char *user, char *title)
1227 {
1228 /*
1229  * send details of scanjob to scanner
1230  */
1231 
1232   char cmd_buf[BJNP_CMD_MAX];
1233   char resp_buf[BJNP_RESP_MAX];
1234   int resp_len;
1235   struct JOB_DETAILS *job;
1236   struct BJNP_command *resp;
1237 
1238   /* send job details command */
1239 
1240   set_cmd_for_dev (devno, (struct BJNP_command *) cmd_buf, CMD_UDP_JOB_DETAILS,
1241 	   sizeof (*job) - sizeof (struct BJNP_command));
1242 
1243   /* create payload */
1244 
1245   job = (struct JOB_DETAILS *) (cmd_buf);
1246   charTo2byte (job->unknown, "", sizeof (job->unknown));
1247   charTo2byte (job->hostname, hostname, sizeof (job->hostname));
1248   charTo2byte (job->username, user, sizeof (job->username));
1249   charTo2byte (job->jobtitle, title, sizeof (job->jobtitle));
1250 
1251   PDBG (bjnp_dbg (LOG_DEBUG2, "bjnp_send_job_details: Job details\n"));
1252   PDBG (bjnp_hexdump (LOG_DEBUG2, cmd_buf,
1253 		       (sizeof (struct BJNP_command) + sizeof (*job))));
1254 
1255   resp_len = udp_command (devno, cmd_buf,
1256 			  sizeof (struct JOB_DETAILS), resp_buf,
1257 			  BJNP_RESP_MAX);
1258 
1259   if (resp_len > 0)
1260     {
1261       PDBG (bjnp_dbg (LOG_DEBUG2, "bjnp_send_job_details: Job details response:\n"));
1262       PDBG (bjnp_hexdump (LOG_DEBUG2, resp_buf, resp_len));
1263       resp = (struct BJNP_command *) resp_buf;
1264       device[devno].session_id = ntohs (resp->session_id);
1265     }
1266 }
1267 
1268 static int
bjnp_get_scanner_mac_address(int devno,char * mac_address)1269 bjnp_get_scanner_mac_address ( int devno, char *mac_address )
1270 {
1271 /*
1272  * send discover to scanner
1273  */
1274 
1275   char cmd_buf[BJNP_CMD_MAX];
1276   char resp_buf[BJNP_RESP_MAX];
1277   int resp_len;
1278   struct DISCOVER_RESPONSE *resp = (struct DISCOVER_RESPONSE * )&resp_buf;;
1279 
1280   /* send job details command */
1281 
1282   set_cmd_for_dev (devno, (struct BJNP_command *) cmd_buf, CMD_UDP_DISCOVER, 0);
1283   resp_len = udp_command (devno, cmd_buf,
1284 			  sizeof (struct BJNP_command), resp_buf,
1285 			  BJNP_RESP_MAX);
1286 
1287   if (resp_len > 0)
1288     {
1289       PDBG (bjnp_dbg (LOG_DEBUG2, "bjnp_get_scanner_mac_address: Discover response:\n"));
1290       PDBG (bjnp_hexdump (LOG_DEBUG2, resp_buf, resp_len));
1291       u8tohex( mac_address, resp -> mac_addr, sizeof( resp -> mac_addr ) );
1292       return 0;
1293     }
1294   return -1;
1295 }
1296 
1297 static int
bjnp_write(int devno,const SANE_Byte * buf,size_t count)1298 bjnp_write (int devno, const SANE_Byte * buf, size_t count)
1299 {
1300 /*
1301  * This function writes TCP data to the scanner.
1302  * Returns: number of bytes written to the scanner
1303  */
1304   int sent_bytes;
1305   int terrno;
1306   struct SCAN_BUF bjnp_buf;
1307 
1308   if (device[devno].scanner_data_left)
1309     {
1310       PDBG (bjnp_dbg
1311 	    (LOG_CRIT, "bjnp_write: ERROR - scanner data left = 0x%lx = %ld\n",
1312 	     (unsigned long) device[devno].scanner_data_left,
1313 	     (unsigned long) device[devno].scanner_data_left));
1314     }
1315   /* set BJNP command header */
1316 
1317   set_cmd_for_dev (devno, (struct BJNP_command *) &bjnp_buf, CMD_TCP_SEND, count);
1318   memcpy (bjnp_buf.scan_data, buf, count);
1319   PDBG (bjnp_dbg (LOG_DEBUG, "bjnp_write: sending 0x%lx = %ld bytes\n",
1320 		   (unsigned long) count, (unsigned long) count);
1321 	PDBG (bjnp_hexdump (LOG_DEBUG2, (char *) &bjnp_buf,
1322 			     sizeof (struct BJNP_command) + count)));
1323 
1324   if ((sent_bytes =
1325        send (device[devno].tcp_socket, &bjnp_buf,
1326 	     sizeof (struct BJNP_command) + count, 0)) <
1327       (ssize_t) (sizeof (struct BJNP_command) + count))
1328     {
1329       /* return result from write */
1330       terrno = errno;
1331       PDBG (bjnp_dbg (LOG_CRIT, "bjnp_write: ERROR - Could not send data!\n"));
1332       errno = terrno;
1333       return sent_bytes;
1334     }
1335   /* correct nr of bytes sent for length of command */
1336 
1337   else if (sent_bytes != (int) (sizeof (struct BJNP_command) + count))
1338     {
1339       errno = EIO;
1340       return -1;
1341     }
1342   return count;
1343 }
1344 
1345 static int
bjnp_send_read_request(int devno)1346 bjnp_send_read_request (int devno)
1347 {
1348 /*
1349  * This function reads responses from the scanner.
1350  * Returns: 0 on success, else -1
1351  *
1352  */
1353   int sent_bytes;
1354   int terrno;
1355   struct BJNP_command bjnp_buf;
1356 
1357   if (device[devno].scanner_data_left)
1358     PDBG (bjnp_dbg
1359 	  (LOG_CRIT,
1360 	   "bjnp_send_read_request: ERROR - scanner data left = 0x%lx = %ld\n",
1361 	   (unsigned long) device[devno].scanner_data_left,
1362 	   (unsigned long) device[devno].scanner_data_left));
1363 
1364   /* set BJNP command header */
1365 
1366   set_cmd_for_dev (devno, (struct BJNP_command *) &bjnp_buf, CMD_TCP_REQ, 0);
1367 
1368   PDBG (bjnp_dbg (LOG_DEBUG, "bjnp_send_read_req sending command\n"));
1369   PDBG (bjnp_hexdump (LOG_DEBUG2, (char *) &bjnp_buf,
1370 		       sizeof (struct BJNP_command)));
1371 
1372   if ((sent_bytes =
1373        send (device[devno].tcp_socket, &bjnp_buf, sizeof (struct BJNP_command),
1374 	     0)) < 0)
1375     {
1376       /* return result from write */
1377       terrno = errno;
1378       PDBG (bjnp_dbg
1379 	    (LOG_CRIT, "bjnp_send_read_request: ERROR - Could not send data!\n"));
1380       errno = terrno;
1381       return -1;
1382     }
1383   return 0;
1384 }
1385 
1386 static SANE_Status
bjnp_recv_header(int devno,size_t * payload_size)1387 bjnp_recv_header (int devno, size_t *payload_size )
1388 {
1389 /*
1390  * This function receives the response header to bjnp commands.
1391  * devno device number
1392  * size: return value for data size returned by scanner
1393  * Returns:
1394  * SANE_STATUS_IO_ERROR when any IO error occurs
1395  * SANE_STATUS_GOOD in case no errors were encountered
1396  */
1397   struct BJNP_command resp_buf;
1398   fd_set input;
1399   struct timeval timeout;
1400   int recv_bytes;
1401   int terrno;
1402   int result;
1403   int fd;
1404   int attempt;
1405 
1406   PDBG (bjnp_dbg
1407 	(LOG_DEBUG, "bjnp_recv_header: receiving response header\n") );
1408   fd = device[devno].tcp_socket;
1409 
1410   *payload_size = 0;
1411   attempt = 0;
1412   do
1413     {
1414       /* wait for data to be received, ignore signals being received */
1415       FD_ZERO (&input);
1416       FD_SET (fd, &input);
1417 
1418       timeout.tv_sec = device[devno].bjnp_ip_timeout /1000;
1419       timeout.tv_usec = device[devno].bjnp_ip_timeout %1000;
1420     }
1421   while ( ( (result = select (fd + 1, &input, NULL, NULL, &timeout)) <= 0) &&
1422 	 (errno == EINTR) && (attempt++ < BJNP_MAX_SELECT_ATTEMPTS));
1423 
1424   if (result < 0)
1425     {
1426       terrno = errno;
1427       PDBG (bjnp_dbg (LOG_CRIT,
1428 		       "bjnp_recv_header: ERROR - could not read response header (select): %s!\n",
1429 		       strerror (terrno)));
1430       errno = terrno;
1431       return SANE_STATUS_IO_ERROR;
1432     }
1433   else if (result == 0)
1434     {
1435       terrno = errno;
1436       PDBG (bjnp_dbg (LOG_CRIT,
1437 		"bjnp_recv_header: ERROR - could not read response header (select timed out after %d ms)!\n",
1438 		device[devno].bjnp_ip_timeout ) );
1439       errno = terrno;
1440       return SANE_STATUS_IO_ERROR;
1441     }
1442 
1443   /* get response header */
1444 
1445   if ((recv_bytes =
1446        recv (fd, (char *) &resp_buf,
1447 	     sizeof (struct BJNP_command),
1448 	     0)) != sizeof (struct BJNP_command))
1449     {
1450       terrno = errno;
1451       if (recv_bytes == 0)
1452         {
1453           PDBG (bjnp_dbg (LOG_CRIT,
1454           		"bjnp_recv_header: ERROR - (recv) Scanner closed the TCP-connection!\n"));
1455         } else {
1456           PDBG (bjnp_dbg (LOG_CRIT,
1457 	      	       "bjnp_recv_header: ERROR - (recv) could not read response header, received %d bytes!\n",
1458 		       recv_bytes));
1459           PDBG (bjnp_dbg
1460 	  		(LOG_CRIT, "bjnp_recv_header: ERROR - (recv) error: %s!\n",
1461 	     		strerror (terrno)));
1462         }
1463       errno = terrno;
1464       return SANE_STATUS_IO_ERROR;
1465     }
1466 
1467   if (resp_buf.cmd_code != device[devno].last_cmd)
1468     {
1469       PDBG (bjnp_dbg
1470 	    (LOG_CRIT,
1471 	     "bjnp_recv_header: ERROR - Received response has cmd code %d, expected %d\n",
1472 	     resp_buf.cmd_code, device[devno].last_cmd));
1473       return SANE_STATUS_IO_ERROR;
1474     }
1475 
1476   if (ntohs (resp_buf.seq_no) != (uint16_t) device[devno].serial)
1477     {
1478       PDBG (bjnp_dbg
1479 	    (LOG_CRIT,
1480 	     "bjnp_recv_header: ERROR - Received response has serial %d, expected %d\n",
1481 	     (int) ntohs (resp_buf.seq_no), (int) device[devno].serial));
1482       return SANE_STATUS_IO_ERROR;
1483     }
1484 
1485   /* got response header back, retrieve length of payload */
1486 
1487 
1488   *payload_size = ntohl (resp_buf.payload_len);
1489   PDBG (bjnp_dbg
1490 	(LOG_DEBUG, "bjnp_recv_header: TCP response header(payload data = %ld bytes):\n",
1491 	 *payload_size) );
1492   PDBG (bjnp_hexdump
1493 	(LOG_DEBUG2, (char *) &resp_buf, sizeof (struct BJNP_command)));
1494   return SANE_STATUS_GOOD;
1495 }
1496 
1497 static int
bjnp_init_device_structure(int dn,bjnp_sockaddr_t * sa,bjnp_protocol_defs_t * protocol_defs,int ip_timeout)1498 bjnp_init_device_structure(int dn, bjnp_sockaddr_t *sa, bjnp_protocol_defs_t *protocol_defs, int ip_timeout)
1499 {
1500   /* initialize device structure */
1501 
1502   char name[BJNP_HOST_MAX];
1503 
1504   device[dn].open = 0;
1505 #ifdef PIXMA_BJNP_USE_STATUS
1506   device[dn].polling_status = BJNP_POLL_STOPPED;
1507   device[dn].dialog = 0;
1508   device[dn].status_key = 0;
1509 #endif
1510   device[dn].protocol = protocol_defs->protocol_version;
1511   device[dn].protocol_string = protocol_defs->proto_string;
1512   device[dn].single_tcp_session = protocol_defs->single_tcp_session;
1513   device[dn].tcp_socket = -1;
1514 
1515   device[dn].addr = (bjnp_sockaddr_t *) malloc(sizeof ( bjnp_sockaddr_t) );
1516   memset( device[dn].addr, 0, sizeof( bjnp_sockaddr_t ) );
1517   memcpy(device[dn].addr, sa, sa_size((bjnp_sockaddr_t *)sa) );
1518   device[dn].address_level = get_scanner_name(sa, name);
1519   device[dn].session_id = 0;
1520   device[dn].serial = -1;
1521   device[dn].bjnp_ip_timeout = ip_timeout;
1522   device[dn].bjnp_scanner_timeout = 1000;
1523   device[dn].scanner_data_left = 0;
1524   device[dn].last_cmd = 0;
1525   device[dn].blocksize = BJNP_BLOCKSIZE_START;
1526   device[dn].last_block = 0;
1527   /* fill mac_address */
1528 
1529   if (bjnp_get_scanner_mac_address(dn, device[dn].mac_address) != 0 )
1530     {
1531       PDBG (bjnp_dbg
1532             (LOG_CRIT, "bjnp_init_device_structure: Cannot read mac address, skipping this scanner\n"  ) );
1533             device[dn].open = 0;
1534       return -1;
1535     }
1536   device[dn].open = 1;
1537   return 0;
1538 }
1539 
1540 static void
bjnp_free_device_structure(int dn)1541 bjnp_free_device_structure( int dn)
1542 {
1543   if (device[dn].addr != NULL)
1544     {
1545     free (device[dn].addr );
1546     device[dn].addr = NULL;
1547     }
1548   device[dn].open = 0;
1549 }
1550 
1551 static SANE_Status
bjnp_recv_data(int devno,SANE_Byte * buffer,size_t start_pos,size_t * len)1552 bjnp_recv_data (int devno, SANE_Byte * buffer, size_t start_pos, size_t * len)
1553 {
1554 /*
1555  * This function receives the payload data.
1556  * NOTE: len may not exceed SSIZE_MAX (as that is max for recv)
1557  *       len will be restricted to SSIZE_MAX to be sure
1558  * Returns: number of bytes of payload received from device
1559  */
1560 
1561   fd_set input;
1562   struct timeval timeout;
1563   ssize_t recv_bytes;
1564   int terrno;
1565   int result;
1566   int fd;
1567   int attempt;
1568 
1569   PDBG (bjnp_dbg
1570 	(LOG_DEBUG, "bjnp_recv_data: read response payload (0x%lx bytes max), buffer: 0x%lx, start_pos: 0x%lx\n",
1571 	 (long) *len, (long) buffer, (long) start_pos));
1572 
1573 
1574   if (*len == 0)
1575     {
1576       /* nothing to do */
1577       PDBG (bjnp_dbg
1578   	    (LOG_DEBUG, "bjnp_recv_data: Nothing to do (%ld bytes requested)\n",
1579 	     (long) *len));
1580       return SANE_STATUS_GOOD;
1581     }
1582   else if ( *len > SSIZE_MAX )
1583     {
1584       PDBG (bjnp_dbg
1585     	    (LOG_DEBUG, "bjnp_recv_data: WARNING - requested block size (%ld) exceeds maximum, setting to maximum %ld\n",
1586 	     (long)*len, SSIZE_MAX));
1587       *len = SSIZE_MAX;
1588     }
1589 
1590   fd = device[devno].tcp_socket;
1591   attempt = 0;
1592   do
1593     {
1594       /* wait for data to be received, retry on a signal being received */
1595       FD_ZERO (&input);
1596       FD_SET (fd, &input);
1597       timeout.tv_sec = device[devno].bjnp_ip_timeout /1000;
1598       timeout.tv_usec = device[devno].bjnp_ip_timeout %1000;
1599     }
1600   while (((result = select (fd + 1, &input, NULL, NULL, &timeout)) <= 0) &&
1601 	 (errno == EINTR) && (attempt++ < BJNP_MAX_SELECT_ATTEMPTS));
1602 
1603   if (result < 0)
1604     {
1605       terrno = errno;
1606       PDBG (bjnp_dbg (LOG_CRIT,
1607 		       "bjnp_recv_data: ERROR - could not read response payload (select failed): %s!\n",
1608 		       strerror (errno)));
1609       errno = terrno;
1610       *len = 0;
1611       return SANE_STATUS_IO_ERROR;
1612     }
1613   else if (result == 0)
1614     {
1615       terrno = errno;
1616       PDBG (bjnp_dbg (LOG_CRIT,
1617 		"bjnp_recv_data: ERROR - could not read response payload (select timed out after %d ms)!\n",
1618 		device[devno].bjnp_ip_timeout) );
1619       errno = terrno;
1620       *len = 0;
1621       return SANE_STATUS_IO_ERROR;
1622     }
1623 
1624   if ((recv_bytes = recv (fd, buffer + start_pos, *len, 0)) < 0)
1625     {
1626       terrno = errno;
1627       PDBG (bjnp_dbg (LOG_CRIT,
1628 		       "bjnp_recv_data: ERROR - could not read response payload (%ld + %ld = %ld) (recv): %s!\n",
1629 		       (long) buffer, (long) start_pos, (long) buffer + start_pos, strerror (errno)));
1630       errno = terrno;
1631       *len = 0;
1632       return SANE_STATUS_IO_ERROR;
1633     }
1634   PDBG (bjnp_dbg (LOG_DEBUG2, "bjnp_recv_data: Received TCP response payload (%ld bytes):\n",
1635 		   (unsigned long) recv_bytes));
1636   PDBG (bjnp_hexdump (LOG_DEBUG2, buffer, recv_bytes));
1637 
1638   *len = recv_bytes;
1639   return SANE_STATUS_GOOD;
1640 }
1641 
1642 static int
bjnp_open_tcp(int devno)1643 bjnp_open_tcp (int devno)
1644 {
1645   int sock;
1646   int val;
1647   char my_hostname[HOST_NAME_MAX];
1648   char pid_str[64];
1649   bjnp_sockaddr_t *addr = device[devno].addr;
1650   char host[BJNP_HOST_MAX];
1651   int port;
1652   int connect_timeout = BJNP_TIMEOUT_TCP_CONNECT;
1653 
1654   if (device[devno].tcp_socket != -1)
1655     {
1656       PDBG (bjnp_dbg( LOG_DEBUG, "bjnp_open_tcp: socket alreeady opened, nothing to do\n"));
1657       return 0;
1658     }
1659   get_address_info( addr, host, &port);
1660   PDBG (bjnp_dbg (LOG_DEBUG, "bjnp_open_tcp: Setting up a TCP socket, dest: %s  port %d\n",
1661 		   host, port ) );
1662 
1663   gethostname (my_hostname, HOST_NAME_MAX);
1664   my_hostname[HOST_NAME_MAX - 1] = '\0';
1665   sprintf (pid_str, "Process ID = %d", getpid ());
1666   bjnp_send_job_details (devno, my_hostname, getusername (), pid_str);
1667 
1668   if ((sock = socket (get_protocol_family( addr ) , SOCK_STREAM, 0)) < 0)
1669     {
1670       PDBG (bjnp_dbg (LOG_CRIT, "bjnp_open_tcp: ERROR - Can not create socket: %s\n",
1671 		       strerror (errno)));
1672       return -1;
1673     }
1674 
1675   val = 1;
1676   setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof (val));
1677 
1678 #if 0
1679   val = 1;
1680   setsockopt (sock, SOL_SOCKET, SO_REUSEPORT, &val, sizeof (val));
1681 
1682   val = 1;
1683 #endif
1684 
1685   /*
1686    * Using TCP_NODELAY improves responsiveness, especially on systems
1687    * with a slow loopback interface...
1688    */
1689 
1690   val = 1;
1691   setsockopt (sock, IPPROTO_TCP, TCP_NODELAY, &val, sizeof (val));
1692 
1693 /*
1694  * Close this socket when starting another process...
1695  */
1696 
1697   fcntl (sock, F_SETFD, FD_CLOEXEC);
1698 
1699   while (connect_timeout > 0)
1700     {
1701       if (connect
1702           (sock, &(addr->addr), sa_size(device[devno].addr)) == 0)
1703 	    {
1704               device[devno].tcp_socket = sock;
1705               PDBG( bjnp_dbg(LOG_INFO, "bjnp_open_tcp: created socket %d\n", sock));
1706               return 0;
1707 	    }
1708       PDBG (bjnp_dbg( LOG_INFO, "bjnp_open_tcp: INFO - Can not yet connect over TCP to scanner: %s, retrying\n",
1709                       strerror(errno)));
1710       usleep(BJNP_TCP_CONNECT_INTERVAL * BJNP_USLEEP_MS);
1711       connect_timeout = connect_timeout - BJNP_TCP_CONNECT_INTERVAL;
1712     }
1713   PDBG (bjnp_dbg
1714         (LOG_CRIT, "bjnp_open_tcp: ERROR - Can not connect to scanner, giving up!"));
1715   return -1;
1716 }
1717 
bjnp_close_tcp(int devno)1718 static void bjnp_close_tcp(int devno)
1719 {
1720   if ( device[devno].tcp_socket != -1)
1721     {
1722       PDBG( bjnp_dbg( LOG_INFO, "bjnp_close_tcp - closing tcp-socket %d\n", device[devno].tcp_socket));
1723       bjnp_finish_job (devno);
1724       close (device[devno].tcp_socket);
1725       device[devno].tcp_socket = -1;
1726     }
1727   else
1728     {
1729       PDBG( bjnp_dbg( LOG_INFO, "bjnp_close_tcp: socket not open, nothing to do.\n"));
1730     }
1731   device[devno].open = 0;
1732 }
1733 
1734 static BJNP_Status
bjnp_allocate_device(SANE_String_Const devname,SANE_Int * dn,char * resulting_host)1735 bjnp_allocate_device (SANE_String_Const devname,
1736                       SANE_Int * dn, char *resulting_host)
1737 {
1738   char method[BJNP_METHOD_MAX];
1739   char host[BJNP_HOST_MAX];
1740   char port[BJNP_PORT_MAX] = "";
1741   char args[BJNP_ARGS_MAX];
1742   bjnp_protocol_defs_t *protocol_defs;
1743   struct addrinfo *res, *cur;
1744   struct addrinfo hints;
1745   int result;
1746   int i;
1747   int ip_timeout = BJNP_TIMEOUT_DEFAULT;
1748 
1749   PDBG (bjnp_dbg (LOG_DEBUG, "bjnp_allocate_device(%s) %d\n", devname, bjnp_no_devices));
1750 
1751   if (split_uri (devname, method, host, port, args) != 0)
1752     {
1753       return BJNP_STATUS_INVAL;
1754     }
1755 
1756   if (strlen (args) > 0)
1757     {
1758       /* get device specific ip timeout if any */
1759 
1760       if (strncmp(args, "timeout=", strlen("timeout=")) == 0)
1761         {
1762           ip_timeout = atoi(args + strlen("timeout="));
1763         } else {
1764 		PDBG (bjnp_dbg
1765 	    		(LOG_CRIT,
1766 				"bjnp_allocate_device: ERROR - Unrecognized argument: %s\n",
1767 	     			devname));
1768 
1769       return BJNP_STATUS_INVAL;
1770         }
1771     }
1772   if ( (protocol_defs = get_protocol_by_method(method)) == NULL)
1773     {
1774       PDBG (bjnp_dbg
1775 		(LOG_CRIT, "bjnp_allocate_device: ERROR - URI %s contains invalid method: %s\n",
1776 		 devname, method));
1777       return BJNP_STATUS_INVAL;
1778     }
1779 
1780   if (strlen(port) == 0)
1781     {
1782       sprintf( port, "%d", protocol_defs->default_port );
1783     }
1784 
1785   hints.ai_flags = 0;
1786 #ifdef ENABLE_IPV6
1787   hints.ai_family = AF_UNSPEC;
1788 #else
1789   hints.ai_family = AF_INET;
1790 #endif
1791   hints.ai_socktype = SOCK_DGRAM;
1792   hints.ai_protocol = 0;
1793   hints.ai_addrlen = 0;
1794   hints.ai_addr = NULL;
1795   hints.ai_canonname = NULL;
1796   hints.ai_next = NULL;
1797 
1798   result = getaddrinfo (host, port, &hints, &res );
1799   if (result != 0 )
1800     {
1801       PDBG (bjnp_dbg (LOG_CRIT, "bjnp_allocate_device: ERROR - Cannot resolve host: %s port %s\n", host, port));
1802       return BJNP_STATUS_INVAL;
1803     }
1804 
1805   /* Check if a device number is already allocated to any of the scanner's addresses */
1806 
1807   cur = res;
1808   while( cur != NULL)
1809     {
1810       /* create a new device structure for this address */
1811 
1812       if (bjnp_no_devices == BJNP_NO_DEVICES)
1813         {
1814           PDBG (bjnp_dbg
1815     	    (LOG_CRIT,
1816     	     "bjnp_allocate_device: WARNING - Too many devices, ran out of device structures, cannot add %s\n",
1817     	     devname));
1818           freeaddrinfo(res);
1819           return BJNP_STATUS_INVAL;
1820         }
1821       if (bjnp_init_device_structure( bjnp_no_devices, (bjnp_sockaddr_t *)cur -> ai_addr,
1822                                       protocol_defs, ip_timeout) != 0)
1823         {
1824           /* giving up on this address, try next one if any */
1825           cur = cur->ai_next;
1826           continue;
1827         }
1828       for (i = 0; i < bjnp_no_devices; i++)
1829         {
1830 
1831           /* Check if found the scanner before, if so we use the best address
1832 	   * but still make sure the scanner is listed only once.
1833 	   * We check for matching addresses as wel as matching mac_addresses as
1834            * an IPv6 host can have multiple addresses */
1835 
1836           if ( strcmp( device[i].mac_address, device[bjnp_no_devices].mac_address ) == 0 )
1837             {
1838               if ( device[i].address_level < device[bjnp_no_devices].address_level )
1839                 {
1840                   /* use the new address instead as it is better */
1841                   free (device[i].addr);
1842                   device[i].addr = device[bjnp_no_devices].addr;
1843                   device[bjnp_no_devices].addr = NULL;
1844                   device[i].address_level = device[bjnp_no_devices].address_level;
1845                 }
1846 
1847 	      /* Leave timeout values unchanged, as they were probably specified by the user */
1848 
1849               freeaddrinfo(res);
1850               *dn = i;
1851               bjnp_free_device_structure( bjnp_no_devices);
1852               return BJNP_STATUS_ALREADY_ALLOCATED;
1853             }
1854         }
1855       cur = cur->ai_next;
1856     }
1857   freeaddrinfo(res);
1858 
1859   if (device[bjnp_no_devices].open == 0)
1860     {
1861       PDBG (bjnp_dbg(LOG_NOTICE, "bjnp_allocate_device: Cannot access scanner, skipping!"));
1862       return BJNP_STATUS_INVAL;
1863     }
1864 
1865   PDBG (bjnp_dbg (LOG_INFO, "bjnp_allocate_device: Scanner not yet in our list, added it: %s:%s\n", host, port));
1866 
1867   /* Commit new device structure */
1868 
1869   *dn = bjnp_no_devices;
1870   bjnp_no_devices++;
1871 
1872   /* return hostname if required */
1873 
1874   if (resulting_host != NULL)
1875     {
1876       strcpy (resulting_host, host);
1877     }
1878 
1879   return BJNP_STATUS_GOOD;
1880 }
1881 
add_scanner(SANE_Int * dev_no,const char * uri,SANE_Status (* attach_bjnp)(SANE_String_Const devname,SANE_String_Const serial,const struct pixma_config_t * cfg),const struct pixma_config_t * const pixma_devices[])1882 static void add_scanner(SANE_Int *dev_no,
1883                         const char *uri,
1884 			SANE_Status (*attach_bjnp)
1885 			              (SANE_String_Const devname,
1886 			               SANE_String_Const serial,
1887 			               const struct pixma_config_t *cfg),
1888                        const struct pixma_config_t *const pixma_devices[])
1889 
1890 {
1891   char scanner_host[BJNP_HOST_MAX];
1892   char serial[BJNP_SERIAL_MAX];
1893   char makemodel[BJNP_MODEL_MAX];
1894   const struct pixma_config_t *cfg = NULL;
1895 
1896   /* Allocate device structure for scanner */
1897   switch (bjnp_allocate_device (uri, dev_no, scanner_host))
1898     {
1899       case BJNP_STATUS_GOOD:
1900         if (get_scanner_id (*dev_no, makemodel) != 0)
1901           {
1902             PDBG (bjnp_dbg (LOG_CRIT, "add_scanner: ERROR - Cannot read scanner make & model: %s\n",
1903                              uri));
1904           }
1905         else
1906           {
1907             /*
1908              * fetch scanner configuration
1909              */
1910             if ((cfg = lookup_scanner(makemodel, pixma_devices)) == (struct pixma_config_t *)NULL)
1911               {
1912                  PDBG (bjnp_dbg (LOG_CRIT, "add_scanner: Scanner %s is not supported, model is unknown! Please report upstream\n", makemodel));
1913                  break;
1914               }
1915 
1916             /*
1917              * inform caller of found scanner
1918              */
1919 
1920              determine_scanner_serial (scanner_host, device[*dev_no].mac_address, serial);
1921 
1922              switch (attach_bjnp (uri, serial, cfg))
1923              {
1924                case SANE_STATUS_GOOD:
1925                  PDBG (bjnp_dbg (LOG_NOTICE, "add_scanner: New scanner added: %s, serial %s, mac address: %s.\n",
1926 	                         uri, serial, device[*dev_no].mac_address));
1927                  break;
1928                default:
1929                  PDBG (bjnp_dbg (LOG_CRIT, "add_scanner: unexpected error (out of memory?), adding %s\n", makemodel));
1930             }
1931           }
1932 
1933         break;
1934       case BJNP_STATUS_ALREADY_ALLOCATED:
1935         PDBG (bjnp_dbg (LOG_NOTICE, "add_scanner: Scanner at %s was added before, good!\n",
1936 	                 uri));
1937         break;
1938 
1939       case BJNP_STATUS_INVAL:
1940         PDBG (bjnp_dbg (LOG_NOTICE, "add_scanner: Scanner at %s can not be added\n",
1941 	                 uri));
1942         break;
1943     }
1944 }
1945 
add_timeout_to_uri(char * uri,int timeout,int max_len)1946 int add_timeout_to_uri(char *uri, int timeout, int max_len)
1947 {
1948   char method[BJNP_METHOD_MAX];
1949   char host[BJNP_HOST_MAX];
1950   char port_str[BJNP_PORT_MAX];
1951   char args[BJNP_HOST_MAX];
1952   int port;
1953   bjnp_protocol_defs_t *proto_struct;
1954 
1955   if (split_uri(uri, method, host, port_str, args ) != 0)
1956     {
1957       return -1;
1958     }
1959 
1960   port = atoi(port_str);
1961 
1962   if (port == 0)
1963     {
1964       proto_struct = get_protocol_by_method(method);
1965       if (proto_struct == NULL)
1966         {
1967           PDBG (bjnp_dbg (LOG_NOTICE, "uri: %s: Method %s cannot be recognized\n", uri,  method));
1968         }
1969       else
1970         {
1971           port = proto_struct-> default_port;
1972         }
1973     }
1974 
1975   /* add timeout value only if missing in URI */
1976 
1977   if (strstr(args, "timeout=") == NULL)
1978     {
1979       sprintf(args, "timeout=%d", timeout);
1980     }
1981 
1982   snprintf(uri, max_len -1, "%s://%s:%d/%s", method,host, port, args);
1983   uri[max_len - 1] = '\0';
1984   return 0;
1985 }
1986 
1987 /** Public functions **/
1988 
1989 /** Initialize sanei_bjnp.
1990  *
1991  * Call this before any other sanei_bjnp function.
1992  */
1993 extern void
sanei_bjnp_init(void)1994 sanei_bjnp_init (void)
1995 {
1996   DBG_INIT();
1997   bjnp_no_devices = 0;
1998 }
1999 
2000 /**
2001  * Find devices that implement the bjnp protocol
2002  *
2003  * The function attach is called for every device which has been found.
2004  *
2005  * @param attach attach function
2006  *
2007  * @return SANE_STATUS_GOOD - on success (even if no scanner was found)
2008  */
2009 extern SANE_Status
sanei_bjnp_find_devices(const char ** conf_devices,SANE_Status (* attach_bjnp)(SANE_String_Const devname,SANE_String_Const serial,const struct pixma_config_t * cfg),const struct pixma_config_t * const pixma_devices[])2010 sanei_bjnp_find_devices (const char **conf_devices,
2011 			 SANE_Status (*attach_bjnp)
2012 			     (SANE_String_Const devname,
2013 			      SANE_String_Const serial,
2014 			      const struct pixma_config_t *cfg),
2015 			 const struct pixma_config_t *const pixma_devices[])
2016 {
2017   int numbytes = 0;
2018   struct BJNP_command cmd;
2019   unsigned char resp_buf[2048];
2020   struct DISCOVER_RESPONSE *disc_resp = ( struct DISCOVER_RESPONSE *) & resp_buf;
2021   int socket_fd[BJNP_SOCK_MAX];
2022   int no_sockets;
2023   int i;
2024   int j;
2025   int attempt;
2026   int last_socketfd = 0;
2027   fd_set fdset;
2028   fd_set active_fdset;
2029   struct timeval timeout;
2030   char scanner_host[HOST_NAME_MAX];
2031   char uri[HOST_NAME_MAX + 32];
2032   int dev_no;
2033   int port;
2034   int auto_detect = 1;
2035   int timeout_default = BJNP_TIMEOUT_DEFAULT;
2036   bjnp_sockaddr_t broadcast_addr[BJNP_SOCK_MAX];
2037   bjnp_sockaddr_t scanner_sa;
2038   socklen_t socklen;
2039   bjnp_protocol_defs_t *protocol_defs;
2040 
2041   memset( broadcast_addr, 0, sizeof( broadcast_addr) );
2042   memset( &scanner_sa, 0 ,sizeof( scanner_sa ) );
2043   PDBG (bjnp_dbg (LOG_INFO, "sanei_bjnp_find_devices, pixma backend version: %d.%d.%d\n",
2044 	PIXMA_VERSION_MAJOR, PIXMA_VERSION_MINOR, PIXMA_VERSION_BUILD));
2045   bjnp_no_devices = 0;
2046 
2047   for (i=0; i < BJNP_SOCK_MAX; i++)
2048     {
2049       socket_fd[i] = -1;
2050     }
2051 
2052   /* parse config file */
2053 
2054   if (conf_devices[0] != NULL)
2055     {
2056       if (strcmp(conf_devices[0], "networking=no") == 0)
2057         {
2058           /* networking=no may only occur on the first non-commented line */
2059 
2060           PDBG (bjnp_dbg( LOG_DEBUG, "sanei_bjnp_find_devices: Networked scanner detection is disabled in configuration file.\n" ) );
2061           return SANE_STATUS_GOOD;
2062         }
2063       /* parse configuration file */
2064 
2065       for (i = 0; conf_devices[i] != NULL; i++)
2066         {
2067           if (strncmp(conf_devices[i], "bjnp-timeout=", strlen("bjnp-timeout="))== 0)
2068             {
2069 	      timeout_default = atoi(conf_devices[i] + strlen("bjnp-timeout=") );
2070 	      PDBG ( bjnp_dbg (LOG_DEBUG, "Set new default timeout value: %d ms.", timeout_default));
2071 	      continue;
2072 	    }
2073 	  else if (strncmp(conf_devices[i], "auto_detection=no", strlen("auto_detection=no"))== 0)
2074             {
2075               auto_detect = 0;
2076 	      PDBG ( bjnp_dbg (LOG_DEBUG, "sanei_bjnp_find_devices: auto detection of scanners disabled"));
2077 	      continue;
2078 	    }
2079 	  else
2080             {
2081               PDBG (bjnp_dbg (LOG_DEBUG, "sanei_bjnp_find_devices: Adding scanner from pixma.conf: %s\n", conf_devices[i]));
2082               memcpy(uri, conf_devices[i], sizeof(uri));
2083               add_timeout_to_uri(uri, timeout_default, sizeof(uri));
2084               add_scanner(&dev_no, uri, attach_bjnp, pixma_devices);
2085 	    }
2086         }
2087       PDBG (bjnp_dbg (LOG_DEBUG, "sanei_bjnp_find_devices: Added all specified scanners.\n"));
2088     }
2089   else
2090     {
2091       PDBG (bjnp_dbg( LOG_DEBUG, "sanei_bjnp_find_devices: Configuration file is empty, No devices specified.\n" ) );
2092     }
2093 
2094   if (auto_detect == 0)
2095     {
2096       return SANE_STATUS_GOOD;
2097     }
2098   /*
2099    * Send UDP DISCOVER to discover scanners and return the list of scanners found
2100    */
2101 
2102   PDBG (bjnp_dbg( LOG_DEBUG, "sanei_bjnp_find_devices: Start auto-detection.\n" ) );
2103   FD_ZERO (&fdset);
2104 
2105   no_sockets = 0;
2106 #ifdef HAVE_IFADDRS_H
2107   {
2108     struct ifaddrs *interfaces = NULL;
2109     struct ifaddrs *interface;
2110     getifaddrs (&interfaces);
2111 
2112     /* create a socket for each suitable interface */
2113 
2114     interface = interfaces;
2115     while ((no_sockets < BJNP_SOCK_MAX) && (interface != NULL))
2116       {
2117         if ( ! (interface -> ifa_flags & IFF_POINTOPOINT) &&
2118             ( (socket_fd[no_sockets] =
2119                       prepare_socket( interface -> ifa_name,
2120                                       (bjnp_sockaddr_t *) interface -> ifa_addr,
2121                                       (bjnp_sockaddr_t *) interface -> ifa_broadaddr,
2122                                       &broadcast_addr[no_sockets] ) ) != -1 ) )
2123           {
2124             /* track highest used socket for later use in select */
2125             if (socket_fd[no_sockets] > last_socketfd)
2126               {
2127                 last_socketfd = socket_fd[no_sockets];
2128               }
2129             FD_SET (socket_fd[no_sockets], &fdset);
2130             no_sockets++;
2131           }
2132         interface = interface->ifa_next;
2133       }
2134     freeifaddrs (interfaces);
2135   }
2136 #else
2137   /* we have no easy way to find interfaces with their broadcast addresses. */
2138   /* use global broadcast and all-hosts instead */
2139   {
2140     bjnp_sockaddr_t local;
2141     bjnp_sockaddr_t bc_addr;
2142 
2143     memset( &local, 0, sizeof( local) );
2144     local.ipv4.sin_family = AF_INET;
2145     local.ipv4.sin_addr.s_addr = htonl (INADDR_ANY);
2146 
2147     bc_addr.ipv4.sin_family = AF_INET;
2148     bc_addr.ipv4.sin_port = htons(0);
2149     bc_addr.ipv4.sin_addr.s_addr = htonl (INADDR_BROADCAST);
2150 
2151     socket_fd[no_sockets] = prepare_socket( "any_interface",
2152                                    &local,
2153                                    &bc_addr,
2154                                    &broadcast_addr[no_sockets] );
2155     if (socket_fd[no_sockets] >= 0)
2156       {
2157         FD_SET (socket_fd[no_sockets], &fdset);
2158         if (socket_fd[no_sockets] > last_socketfd)
2159           {
2160             last_socketfd = socket_fd[no_sockets];
2161           }
2162         no_sockets++;
2163       }
2164 #ifdef ENABLE_IPV6
2165     local.ipv6.sin6_family = AF_INET6;
2166     local.ipv6.sin6_addr = in6addr_any;
2167 
2168     socket_fd[no_sockets] = prepare_socket( "any_interface",
2169                                    &local,
2170                                    NULL,
2171                                    &broadcast_addr[no_sockets] );
2172     if (socket_fd[no_sockets] >= 0)
2173       {
2174         FD_SET (socket_fd[no_sockets], &fdset);
2175         if (socket_fd[no_sockets] > last_socketfd)
2176           {
2177             last_socketfd = socket_fd[no_sockets];
2178           }
2179         no_sockets++;
2180       }
2181 #endif
2182   }
2183 #endif
2184 
2185   /* send BJNP_MAX_BROADCAST_ATTEMPTS broadcasts on each prepared socket */
2186   for (attempt = 0; attempt < BJNP_MAX_BROADCAST_ATTEMPTS; attempt++)
2187     {
2188       for ( i=0; i < no_sockets; i++)
2189         {
2190 	  j = 0;
2191           while(bjnp_protocol_defs[j].protocol_version != PROTOCOL_NONE)
2192 	    {
2193 	      set_cmd_from_string (bjnp_protocol_defs[j].proto_string, &cmd, CMD_UDP_DISCOVER, 0);
2194               bjnp_send_broadcast ( socket_fd[i], &broadcast_addr[i],
2195                                     bjnp_protocol_defs[j].default_port, cmd, sizeof (cmd));
2196 	      j++;
2197 	    }
2198 	}
2199       /* wait for some time between broadcast packets */
2200       usleep (BJNP_BROADCAST_INTERVAL * BJNP_USLEEP_MS);
2201     }
2202 
2203   /* wait for a UDP response */
2204 
2205   timeout.tv_sec = 0;
2206   timeout.tv_usec = BJNP_BC_RESPONSE_TIMEOUT * BJNP_USLEEP_MS;
2207 
2208 
2209   active_fdset = fdset;
2210 
2211   while (select (last_socketfd + 1, &active_fdset, NULL, NULL, &timeout) > 0)
2212     {
2213       PDBG (bjnp_dbg (LOG_DEBUG, "sanei_bjnp_find_devices: Select returned, time left %d.%d....\n",
2214 		       (int) timeout.tv_sec, (int) timeout.tv_usec));
2215       for (i = 0; i < no_sockets; i++)
2216 	{
2217 	  if (FD_ISSET (socket_fd[i], &active_fdset))
2218 	    {
2219               socklen =  sizeof(scanner_sa);
2220 	      if ((numbytes =
2221 		   recvfrom (socket_fd[i], resp_buf, sizeof (resp_buf), 0,
2222                              &(scanner_sa.addr), &socklen ) ) == -1)
2223 		{
2224 		  PDBG (bjnp_dbg
2225 			(LOG_INFO, "sanei_find_devices: no data received"));
2226 		  break;
2227 		}
2228 	      else
2229 		{
2230 		  PDBG (bjnp_dbg (LOG_DEBUG2, "sanei_find_devices: Discover response:\n"));
2231 		  PDBG (bjnp_hexdump (LOG_DEBUG2, &resp_buf, numbytes));
2232 
2233 		  /* check if something sensible is returned */
2234 		  protocol_defs = get_protocol_by_proto_string(disc_resp-> response.BJNP_id);
2235 		  if ( (numbytes < (int)sizeof (struct BJNP_command)) ||
2236 		       (protocol_defs == NULL))
2237 		    {
2238 		      /* not a valid response, assume not a scanner  */
2239 
2240                       char bjnp_id[5];
2241                       strncpy(bjnp_id,  disc_resp-> response.BJNP_id, 4);
2242                       bjnp_id[4] = '\0';
2243                       PDBG (bjnp_dbg (LOG_INFO,
2244                         "sanei_find_devices: Invalid discover response! Length = %d, Id = %s\n",
2245                         numbytes, bjnp_id ) );
2246 		      break;
2247 		    }
2248                   if ( !(disc_resp -> response.dev_type & 0x80) )
2249                     {
2250                       /* not a response, a command from somebody else or */
2251                       /* a discover command that we generated */
2252                       break;
2253                     }
2254 		};
2255 
2256 	      port = get_port_from_sa(scanner_sa);
2257 	      /* scanner found, get IP-address or hostname */
2258               get_scanner_name( &scanner_sa, scanner_host);
2259 
2260 	      /* construct URI */
2261 	      sprintf (uri, "%s://%s:%d/timeout=%d", protocol_defs->method_string, scanner_host,
2262 		           port, timeout_default);
2263 
2264               add_scanner( &dev_no, uri, attach_bjnp, pixma_devices);
2265 
2266 	    }
2267 	}
2268       active_fdset = fdset;
2269       timeout.tv_sec = 0;
2270       timeout.tv_usec = BJNP_BC_RESPONSE_TIMEOUT * BJNP_USLEEP_MS;
2271     }
2272   PDBG (bjnp_dbg (LOG_DEBUG, "sanei_find_devices: scanner discovery finished...\n"));
2273 
2274   for (i = 0; i < no_sockets; i++)
2275     close (socket_fd[i]);
2276 
2277   return SANE_STATUS_GOOD;
2278 }
2279 
2280 /** Open a BJNP device.
2281  *
2282  * The device is opened by its name devname and the device number is
2283  * returned in dn on success.
2284  *
2285  * Device names consist of an URI
2286  * Where:
2287  * type = bjnp
2288  * hostname = resolvable name or IP-address
2289  * port = 8612 for a scanner
2290  * An example could look like this: bjnp://host.domain:8612
2291  *
2292  * @param devname name of the device to open
2293  * @param dn device number
2294  *
2295  * @return
2296  * - SANE_STATUS_GOOD - on success
2297  * - SANE_STATUS_ACCESS_DENIED - if the file couldn't be accessed due to
2298  *   permissions
2299  * - SANE_STATUS_INVAL - on every other error
2300  */
2301 
2302 extern SANE_Status
sanei_bjnp_open(SANE_String_Const devname,SANE_Int * dn)2303 sanei_bjnp_open (SANE_String_Const devname, SANE_Int * dn)
2304 {
2305   int result;
2306 
2307   PDBG (bjnp_dbg (LOG_INFO, "sanei_bjnp_open(%s, %d):\n", devname, *dn));
2308 
2309   result = bjnp_allocate_device (devname, dn, NULL);
2310   if ( (result != BJNP_STATUS_GOOD) && (result != BJNP_STATUS_ALREADY_ALLOCATED ) ) {
2311     return SANE_STATUS_INVAL;
2312   }
2313 
2314   if (device[*dn].single_tcp_session && bjnp_open_tcp (*dn) != 0)
2315     {
2316       PDBG (bjnp_dbg (LOG_INFO, "sanei_bjnp_opening TCP connection failed.\n\n"));
2317       return SANE_STATUS_INVAL;
2318     }
2319   PDBG (bjnp_dbg (LOG_INFO, "sanei_bjnp_open done.\n\n"));
2320   return SANE_STATUS_GOOD;
2321 }
2322 
2323 /** Close a BJNP device.
2324  *
2325  * @param dn device number
2326  */
2327 
2328 void
sanei_bjnp_close(SANE_Int dn)2329 sanei_bjnp_close (SANE_Int dn)
2330 {
2331   PDBG (bjnp_dbg (LOG_INFO, "sanei_bjnp_close(%d):\n", dn));
2332 
2333   bjnp_close_tcp( dn );
2334   PDBG (bjnp_dbg (LOG_INFO, "sanei_bjnp_close done.\n\n"));
2335 }
2336 
2337 /** Activate BJNP device connection
2338  *
2339  * @param dn device number
2340  */
2341 
2342 SANE_Status
sanei_bjnp_activate(SANE_Int dn)2343 sanei_bjnp_activate (SANE_Int dn)
2344 {
2345   PDBG (bjnp_dbg (LOG_INFO, "sanei_bjnp_activate (%d)\n", dn));
2346   if (!(device[dn].single_tcp_session) && bjnp_open_tcp (dn) != 0)
2347     {
2348       PDBG (bjnp_dbg (LOG_INFO, "sanei_bjnp_activate: open TCP connection failed.\n\n"));
2349       return SANE_STATUS_INVAL;
2350     }
2351   PDBG (bjnp_dbg (LOG_INFO, "sanei_bjnp_activate done.\n\n"));
2352   return SANE_STATUS_GOOD;
2353 }
2354 
2355 /** Deactivate BJNP device connection
2356  *
2357  * @paran dn device number
2358  */
2359 
2360 SANE_Status
sanei_bjnp_deactivate(SANE_Int dn)2361 sanei_bjnp_deactivate (SANE_Int dn)
2362 {
2363   PDBG (bjnp_dbg (LOG_INFO, "sanei_bjnp_deactivate (%d)\n", dn));
2364   if (!device[dn].single_tcp_session)
2365   {
2366     bjnp_close_tcp(dn);
2367   }
2368   PDBG (bjnp_dbg (LOG_INFO, "sanei_bjnp_deactivate done.\n\n"));
2369   return SANE_STATUS_GOOD;
2370 }
2371 
2372 /** Set the timeout for interrupt reads.
2373  *  we do not use it for bulk reads!
2374  * @param timeout the new timeout in ms
2375  */
2376 extern void
sanei_bjnp_set_timeout(SANE_Int devno,SANE_Int timeout)2377 sanei_bjnp_set_timeout (SANE_Int devno, SANE_Int timeout)
2378 {
2379   PDBG (bjnp_dbg (LOG_INFO, "bjnp_set_timeout to %d\n",
2380         timeout));
2381 
2382   device[devno].bjnp_scanner_timeout = timeout;
2383 }
2384 
2385 /** Initiate a bulk transfer read.
2386  *
2387  * Read up to size bytes from the device to buffer. After the read, size
2388  * contains the number of bytes actually read.
2389  *
2390  * @param dn device number
2391  * @param buffer buffer to store read data in
2392  * @param size size of the data
2393  *
2394  * @return
2395  * - SANE_STATUS_GOOD - on success
2396  * - SANE_STATUS_EOF - if zero bytes have been read
2397  * - SANE_STATUS_IO_ERROR - if an error occurred during the read
2398  * - SANE_STATUS_INVAL - on every other error
2399  *
2400  */
2401 
2402 extern SANE_Status
sanei_bjnp_read_bulk(SANE_Int dn,SANE_Byte * buffer,size_t * size)2403 sanei_bjnp_read_bulk (SANE_Int dn, SANE_Byte * buffer, size_t * size)
2404 {
2405   SANE_Status result;
2406   SANE_Status error;
2407   size_t recvd;
2408   size_t read_size;
2409   size_t read_size_max;
2410   size_t requested;
2411 
2412   PDBG (bjnp_dbg
2413 	(LOG_INFO, "bjnp_read_bulk(dn=%d, bufferptr=%lx, 0x%lx = %ld)\n", dn,
2414 	 (long) buffer, (unsigned long) *size, (unsigned long) *size));
2415 
2416   recvd = 0;
2417   requested = *size;
2418 
2419   PDBG (bjnp_dbg
2420 	(LOG_DEBUG, "bjnp_read_bulk: 0x%lx = %ld bytes available at start\n",
2421 	 (unsigned long) device[dn].scanner_data_left,
2422 	 (unsigned long) device[dn].scanner_data_left ) );
2423 
2424   while ( (recvd < requested) && !( device[dn].last_block && (device[dn].scanner_data_left == 0)) )
2425     {
2426       PDBG (bjnp_dbg
2427 	    (LOG_DEBUG,
2428 	     "bjnp_read_bulk: Already received 0x%lx = %ld bytes, backend requested 0x%lx = %ld bytes\n",
2429 	     (unsigned long) recvd, (unsigned long) recvd,
2430 	     (unsigned long) requested, (unsigned long)requested ));
2431 
2432       /* Check first if there is data in flight from the scanner */
2433 
2434       if (device[dn].scanner_data_left == 0)
2435         {
2436 	  /* There is no data in flight from the scanner, send new read request */
2437 
2438           PDBG (bjnp_dbg (LOG_DEBUG,
2439                           "bjnp_read_bulk: No (more) scanner data available, requesting more( blocksize = %ld = %lx\n",
2440                           (long int) device[dn].blocksize, (long int) device[dn].blocksize ));
2441 
2442           if ((error = bjnp_send_read_request (dn)) != SANE_STATUS_GOOD)
2443             {
2444               *size = recvd;
2445               return SANE_STATUS_IO_ERROR;
2446             }
2447           if ( ( error = bjnp_recv_header (dn, &(device[dn].scanner_data_left) )  ) != SANE_STATUS_GOOD)
2448             {
2449               *size = recvd;
2450               return SANE_STATUS_IO_ERROR;
2451             }
2452           /* correct blocksize if applicable */
2453 
2454           device[dn].blocksize = MAX (device[dn].blocksize, device[dn].scanner_data_left);
2455 
2456           if ( device[dn].scanner_data_left < device[dn].blocksize)
2457             {
2458               /* the scanner will not react at all to a read request, when no more data is available */
2459               /* we now determine end of data by comparing the payload size to the maximum blocksize */
2460               /* this block is shorter than blocksize, so after this block we are done */
2461 
2462               device[dn].last_block = 1;
2463             }
2464         }
2465 
2466       PDBG (bjnp_dbg (LOG_DEBUG, "bjnp_read_bulk: In flight: 0x%lx = %ld bytes available\n",
2467 		 (unsigned long) device[dn].scanner_data_left,
2468 		 (unsigned long) device[dn].scanner_data_left));
2469 
2470        /* read as many bytes as needed and available */
2471 
2472       read_size_max = MIN( device[dn].scanner_data_left, (requested - recvd) );
2473       read_size = read_size_max;
2474 
2475       PDBG (bjnp_dbg
2476 	    (LOG_DEBUG,
2477 	     "bjnp_read_bulk: Try to read 0x%lx = %ld (of max 0x%lx = %ld) bytes\n",
2478 	     (unsigned long) read_size_max,
2479 	     (unsigned long) read_size_max,
2480 	     (unsigned long) device[dn].scanner_data_left,
2481 	     (unsigned long) device[dn].scanner_data_left) );
2482 
2483       result = bjnp_recv_data (dn, buffer , recvd, &read_size);
2484       if (result != SANE_STATUS_GOOD)
2485 	{
2486 	  *size = recvd;
2487 	  return SANE_STATUS_IO_ERROR;
2488 	}
2489       PDBG (bjnp_dbg (LOG_DEBUG, "bjnp_read_bulk: Expected at most %ld bytes, received this time: %ld\n",
2490             read_size_max, read_size) );
2491 
2492       device[dn].scanner_data_left = device[dn].scanner_data_left - read_size;
2493       recvd = recvd + read_size;
2494     }
2495 
2496   PDBG (bjnp_dbg (LOG_DEBUG, "bjnp_read_bulk: %s: Returning %ld bytes, backend expects %ld\n",
2497         (recvd == *size)? "OK": "NOTICE",recvd, *size ) );
2498   *size = recvd;
2499   if ( *size == 0 )
2500     return SANE_STATUS_EOF;
2501   return SANE_STATUS_GOOD;
2502 }
2503 
2504 /** Initiate a bulk transfer write.
2505  *
2506  * Write up to size bytes from buffer to the device. After the write size
2507  * contains the number of bytes actually written.
2508  *
2509  * @param dn device number
2510  * @param buffer buffer to write to device
2511  * @param size size of the data
2512  *
2513  * @return
2514  * - SANE_STATUS_GOOD - on success
2515  * - SANE_STATUS_IO_ERROR - if an error occurred during the write
2516  * - SANE_STATUS_INVAL - on every other error
2517  */
2518 
2519 extern SANE_Status
sanei_bjnp_write_bulk(SANE_Int dn,const SANE_Byte * buffer,size_t * size)2520 sanei_bjnp_write_bulk (SANE_Int dn, const SANE_Byte * buffer, size_t * size)
2521 {
2522   ssize_t sent;
2523   size_t recvd;
2524   uint32_t buf;
2525   size_t payload_size;
2526 
2527   /* Write received data to scanner */
2528 
2529   sent = bjnp_write (dn, buffer, *size);
2530   if (sent < 0)
2531     return SANE_STATUS_IO_ERROR;
2532   if (sent != (int) *size)
2533     {
2534       PDBG (bjnp_dbg
2535 	    (LOG_CRIT, "sanei_bjnp_write_bulk: ERROR - Sent only %ld bytes to scanner, expected %ld!!\n",
2536 	     (unsigned long) sent, (unsigned long) *size));
2537       return SANE_STATUS_IO_ERROR;
2538     }
2539 
2540   if (bjnp_recv_header (dn, &payload_size) != SANE_STATUS_GOOD)
2541     {
2542       PDBG (bjnp_dbg (LOG_CRIT, "sanei_bjnp_write_bulk: ERROR - Could not read response to command!\n"));
2543       return SANE_STATUS_IO_ERROR;
2544     }
2545 
2546   if (payload_size != 4)
2547     {
2548       PDBG (bjnp_dbg (LOG_CRIT,
2549 		       "sanei_bjnp_write_bulk: ERROR - Scanner length of write confirmation = 0x%lx bytes = %ld, expected %d!!\n",
2550 		       (unsigned long) payload_size,
2551 		       (unsigned long) payload_size, 4));
2552       return SANE_STATUS_IO_ERROR;
2553     }
2554   recvd = payload_size;
2555   if ((bjnp_recv_data (dn, (unsigned char *) &buf, 0, &recvd) !=
2556        SANE_STATUS_GOOD) || (recvd != payload_size))
2557     {
2558       PDBG (bjnp_dbg (LOG_CRIT,
2559 		       "sanei_bjnp_write_bulk: ERROR - Could not read length of data confirmed by device\n"));
2560       return SANE_STATUS_IO_ERROR;
2561     }
2562   recvd = ntohl (buf);
2563   if (recvd != *size)
2564     {
2565       PDBG (bjnp_dbg
2566 	    (LOG_CRIT, "sanei_bjnp_write_bulk: ERROR - Scanner confirmed %ld bytes, expected %ld!!\n",
2567 	     (unsigned long) recvd, (unsigned long) *size));
2568       return SANE_STATUS_IO_ERROR;
2569     }
2570   /* we can expect data from the scanner */
2571 
2572   device[dn].last_block = 0;
2573 
2574   return SANE_STATUS_GOOD;
2575 }
2576 
2577 /** Initiate a interrupt transfer read.
2578  *
2579  * Read up to size bytes from the interrupt endpoint from the device to
2580  * buffer. After the read, size contains the number of bytes actually read.
2581  *
2582  * @param dn device number
2583  * @param buffer buffer to store read data in
2584  * @param size size of the data
2585  *
2586  * @return
2587  * - SANE_STATUS_GOOD - on success
2588  * - SANE_STATUS_EOF - if zero bytes have been read
2589  * - SANE_STATUS_IO_ERROR - if an error occurred during the read
2590  * - SANE_STATUS_INVAL - on every other error
2591  *
2592  */
2593 
2594 extern SANE_Status
sanei_bjnp_read_int(SANE_Int dn,SANE_Byte * buffer,size_t * size)2595 sanei_bjnp_read_int (SANE_Int dn, SANE_Byte * buffer, size_t * size)
2596 {
2597 #ifndef PIXMA_BJNP_USE_STATUS
2598   PDBG (bjnp_dbg
2599 	(LOG_INFO, "bjnp_read_int(%d, bufferptr, 0x%lx = %ld):\n", dn,
2600 	 (unsigned long) *size, (unsigned long) *size));
2601 
2602   memset (buffer, 0, *size);
2603   sleep (1);
2604   return SANE_STATUS_IO_ERROR;
2605 #else
2606 
2607   char hostname[256];
2608   int resp_len;
2609   int timeout;
2610   int interval;
2611 
2612   PDBG (bjnp_dbg
2613 	(LOG_INFO, "bjnp_read_int(%d, bufferptr, 0x%lx = %ld):\n", dn,
2614 	 (unsigned long) *size, (unsigned long) *size));
2615 
2616   memset (buffer, 0, *size);
2617 
2618   gethostname (hostname, 32);
2619   hostname[32] = '\0';
2620 
2621 
2622   switch (device[dn].polling_status)
2623     {
2624     case BJNP_POLL_STOPPED:
2625 
2626       /* establish dialog */
2627 
2628       if ( (bjnp_poll_scanner (dn, 0, hostname, getusername (), buffer, *size ) != 0) ||
2629            (bjnp_poll_scanner (dn, 1, hostname, getusername (), buffer, *size ) != 0) )
2630         {
2631 	  PDBG (bjnp_dbg (LOG_NOTICE, "bjnp_read_int: WARNING - Failed to setup read_intr dialog with device!\n"));
2632           device[dn].dialog = 0;
2633           device[dn].status_key = 0;
2634           return SANE_STATUS_IO_ERROR;
2635         }
2636       device[dn].polling_status = BJNP_POLL_STARTED;
2637 
2638       /* fall through */
2639     case BJNP_POLL_STARTED:
2640       /* we use only seonds (rounded up) accuracy between poll attempts */
2641       timeout = device[dn].bjnp_scanner_timeout /1000 + 1;
2642       if (device[dn].bjnp_scanner_timeout %1000 > 0)
2643         {
2644 	  timeout++;
2645 
2646 	}
2647       interval = 1;
2648       do
2649         {
2650           if ( (resp_len = bjnp_poll_scanner (dn, 2, hostname, getusername (), buffer, *size ) ) < 0 )
2651             {
2652               PDBG (bjnp_dbg (LOG_NOTICE, "bjnp_read_int: Poll failed, Restarting polling dialog!\n"));
2653               device[dn].polling_status = BJNP_POLL_STOPPED;
2654               *size = 0;
2655               return SANE_STATUS_EOF;
2656             }
2657           *size = (size_t) resp_len;
2658           if ( resp_len > 0 )
2659             {
2660               device[dn].polling_status = BJNP_POLL_STATUS_RECEIVED;
2661               return SANE_STATUS_GOOD;
2662             }
2663           timeout = timeout - interval;
2664 	  if (timeout <= 0)
2665 	    return SANE_STATUS_EOF;
2666           sleep(interval);
2667         } while ( timeout > 0 ) ;
2668       break;
2669     case BJNP_POLL_STATUS_RECEIVED:
2670        if ( (resp_len = bjnp_poll_scanner (dn, 5, hostname, getusername (), buffer, *size ) ) < 0 )
2671         {
2672           PDBG (bjnp_dbg (LOG_NOTICE, "bjnp_read_int: Restarting polling dialog!\n"));
2673           device[dn].polling_status = BJNP_POLL_STOPPED;
2674           *size = 0;
2675           break;
2676         }
2677     }
2678   return SANE_STATUS_EOF;
2679 #endif
2680 }
2681