• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* sane - Scanner Access Now Easy.
2    Copyright (C) 1997 David Mosberger-Tang
3    Copyright (C) 2003, 2008 Julien BLACHE <jb@jblache.org>
4       AF-independent code + IPv6, Avahi support
5 
6    This file is part of the SANE package.
7 
8    This program is free software; you can redistribute it and/or
9    modify it under the terms of the GNU General Public License as
10    published by the Free Software Foundation; either version 2 of the
11    License, or (at your option) any later version.
12 
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16    General Public License for more details.
17 
18    You should have received a copy of the GNU General Public License
19    along with this program.  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    This file implements a SANE network-based meta backend.  */
43 
44 #ifdef _AIX
45 # include "../include/lalloca.h" /* MUST come first for AIX! */
46 #endif
47 
48 #include "../include/sane/config.h"
49 #include "../include/lalloca.h"
50 #include "../include/_stdint.h"
51 
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <limits.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 #ifdef HAVE_LIBC_H
59 # include <libc.h> /* NeXTStep/OpenStep */
60 #endif
61 
62 #include <sys/time.h>
63 #include <sys/types.h>
64 
65 #include <netinet/in.h>
66 #include <netdb.h> /* OS/2 needs this _after_ <netinet/in.h>, grrr... */
67 
68 #if WITH_AVAHI
69 # include <avahi-client/client.h>
70 # include <avahi-client/lookup.h>
71 
72 # include <avahi-common/thread-watch.h>
73 # include <avahi-common/malloc.h>
74 # include <avahi-common/error.h>
75 
76 # define SANED_SERVICE_DNS "_sane-port._tcp"
77 
78 static AvahiClient *avahi_client = NULL;
79 static AvahiThreadedPoll *avahi_thread = NULL;
80 static AvahiServiceBrowser *avahi_browser = NULL;
81 #endif /* WITH_AVAHI */
82 
83 #include "../include/sane/sane.h"
84 #include "../include/sane/sanei.h"
85 #include "../include/sane/sanei_net.h"
86 #include "../include/sane/sanei_codec_bin.h"
87 #include "net.h"
88 
89 #define BACKEND_NAME    net
90 #include "../include/sane/sanei_backend.h"
91 
92 #ifndef PATH_MAX
93 # define PATH_MAX       1024
94 #endif
95 
96 #include "../include/sane/sanei_config.h"
97 #define NET_CONFIG_FILE "net.conf"
98 
99 /* Please increase version number with every change
100    (don't forget to update net.desc) */
101 
102 /* define the version string depending on which network code is used */
103 #if defined (HAVE_GETADDRINFO) && defined (HAVE_GETNAMEINFO)
104 # define NET_USES_AF_INDEP
105 # ifdef ENABLE_IPV6
106 #  define NET_VERSION "1.0.14 (AF-indep+IPv6)"
107 # else
108 #  define NET_VERSION "1.0.14 (AF-indep)"
109 # endif /* ENABLE_IPV6 */
110 #else
111 # undef ENABLE_IPV6
112 # define NET_VERSION "1.0.14"
113 #endif /* HAVE_GETADDRINFO && HAVE_GETNAMEINFO */
114 
115 static SANE_Auth_Callback auth_callback;
116 static Net_Device *first_device;
117 static Net_Scanner *first_handle;
118 static const SANE_Device **devlist;
119 static int client_big_endian; /* 1 == big endian; 0 == little endian */
120 static int server_big_endian; /* 1 == big endian; 0 == little endian */
121 static int depth; /* bits per pixel */
122 static int connect_timeout = -1; /* timeout for connection to saned */
123 
124 #ifndef NET_USES_AF_INDEP
125 static int saned_port;
126 #endif /* !NET_USES_AF_INDEP */
127 
128 /* This variable is only needed, if the depth is 16bit/channel and
129    client/server have different endianness.  A value of -1 means, that there's
130    no hang over; otherwise the value has to be casted to SANE_Byte.  hang_over
131    means, that there is a remaining byte from a previous call to sane_read,
132    which could not be byte-swapped, e.g. because the frontend requested an odd
133    number of bytes.
134 */
135 static int hang_over;
136 
137 /* This variable is only needed, if the depth is 16bit/channel and
138    client/server have different endianness.  A value of -1 means, that there's
139    no left over; otherwise the value has to be casted to SANE_Byte.  left_over
140    means, that there is a remaining byte from a previous call to sane_read,
141    which already is in the correct byte order, but could not be returned,
142    e.g.  because the frontend requested only one byte per call.
143 */
144 static int left_over;
145 
146 
147 #ifdef NET_USES_AF_INDEP
148 static SANE_Status
add_device(const char * name,Net_Device ** ndp)149 add_device (const char *name, Net_Device ** ndp)
150 {
151   struct addrinfo hints;
152   struct addrinfo *res;
153   struct addrinfo *resp;
154   struct sockaddr_in *sin;
155 #ifdef ENABLE_IPV6
156   struct sockaddr_in6 *sin6;
157 #endif /* ENABLE_IPV6 */
158 
159   Net_Device *nd = NULL;
160 
161   int error;
162   short sane_port = htons (6566);
163 
164   DBG (1, "add_device: adding backend %s\n", name);
165 
166   for (nd = first_device; nd; nd = nd->next)
167     if (strcmp (nd->name, name) == 0)
168       {
169 	DBG (1, "add_device: already in list\n");
170 
171 	if (ndp)
172 	  *ndp = nd;
173 
174 	return SANE_STATUS_GOOD;
175       }
176 
177   memset (&hints, 0, sizeof(hints));
178 
179 # ifdef ENABLE_IPV6
180   hints.ai_family = PF_UNSPEC;
181 # else
182   hints.ai_family = PF_INET;
183 # endif /* ENABLE_IPV6 */
184 
185   error = getaddrinfo (name, "sane-port", &hints, &res);
186   if (error)
187     {
188       error = getaddrinfo (name, NULL, &hints, &res);
189       if (error)
190 	{
191 	  DBG (1, "add_device: error while getting address of host %s: %s\n",
192 	       name, gai_strerror (error));
193 
194 	  return SANE_STATUS_IO_ERROR;
195 	}
196       else
197 	{
198           for (resp = res; resp != NULL; resp = resp->ai_next)
199             {
200               switch (resp->ai_family)
201                 {
202                   case AF_INET:
203                     sin = (struct sockaddr_in *) resp->ai_addr;
204                     sin->sin_port = sane_port;
205                     break;
206 #ifdef ENABLE_IPV6
207 		  case AF_INET6:
208 		    sin6 = (struct sockaddr_in6 *) resp->ai_addr;
209 		    sin6->sin6_port = sane_port;
210 		    break;
211 #endif /* ENABLE_IPV6 */
212                 }
213 	    }
214 	}
215     }
216 
217   nd = malloc (sizeof (Net_Device));
218   if (!nd)
219     {
220       DBG (1, "add_device: not enough memory for Net_Device struct\n");
221 
222       freeaddrinfo (res);
223       return SANE_STATUS_NO_MEM;
224     }
225 
226   memset (nd, 0, sizeof (Net_Device));
227   nd->name = strdup (name);
228   if (!nd->name)
229     {
230       DBG (1, "add_device: not enough memory to duplicate name\n");
231       free(nd);
232       return SANE_STATUS_NO_MEM;
233     }
234 
235   nd->addr = res;
236   nd->ctl = -1;
237 
238   nd->next = first_device;
239 
240   first_device = nd;
241 
242   if (ndp)
243     *ndp = nd;
244   DBG (2, "add_device: backend %s added\n", name);
245   return SANE_STATUS_GOOD;
246 }
247 
248 #else /* !NET_USES_AF_INDEP */
249 
250 static SANE_Status
add_device(const char * name,Net_Device ** ndp)251 add_device (const char *name, Net_Device ** ndp)
252 {
253   struct hostent *he;
254   Net_Device *nd;
255   struct sockaddr_in *sin;
256 
257   DBG (1, "add_device: adding backend %s\n", name);
258 
259   for (nd = first_device; nd; nd = nd->next)
260     if (strcmp (nd->name, name) == 0)
261       {
262 	DBG (1, "add_device: already in list\n");
263 
264 	if (ndp)
265 	  *ndp = nd;
266 
267 	return SANE_STATUS_GOOD;
268       }
269 
270   he = gethostbyname (name);
271   if (!he)
272     {
273       DBG (1, "add_device: can't get address of host %s\n", name);
274       return SANE_STATUS_IO_ERROR;
275     }
276 
277   if (he->h_addrtype != AF_INET)
278     {
279       DBG (1, "add_device: don't know how to deal with addr family %d\n",
280 	   he->h_addrtype);
281       return SANE_STATUS_INVAL;
282     }
283 
284   nd = malloc (sizeof (*nd));
285   if (!nd)
286     {
287       DBG (1, "add_device: not enough memory for Net_Device struct\n");
288       return SANE_STATUS_NO_MEM;
289     }
290 
291   memset (nd, 0, sizeof (*nd));
292   nd->name = strdup (name);
293   if (!nd->name)
294     {
295       DBG (1, "add_device: not enough memory to duplicate name\n");
296       free (nd);
297       return SANE_STATUS_NO_MEM;
298     }
299   nd->addr.sa_family = he->h_addrtype;
300 
301   sin = (struct sockaddr_in *) &nd->addr;
302   memcpy (&sin->sin_addr, he->h_addr_list[0], he->h_length);
303 
304   nd->ctl = -1;
305   nd->next = first_device;
306   first_device = nd;
307   if (ndp)
308     *ndp = nd;
309   DBG (2, "add_device: backend %s added\n", name);
310   return SANE_STATUS_GOOD;
311 }
312 #endif /* NET_USES_AF_INDEP */
313 
314 
315 #ifdef NET_USES_AF_INDEP
316 static SANE_Status
connect_dev(Net_Device * dev)317 connect_dev (Net_Device * dev)
318 {
319   struct addrinfo *addrp;
320 
321   SANE_Word version_code;
322   SANE_Init_Reply reply;
323   SANE_Status status = SANE_STATUS_IO_ERROR;
324   SANE_Init_Req req;
325   SANE_Bool connected = SANE_FALSE;
326 #ifdef TCP_NODELAY
327   int on = 1;
328   int level = -1;
329 #endif
330   struct timeval tv;
331 
332   int i;
333 
334   DBG (2, "connect_dev: trying to connect to %s\n", dev->name);
335 
336   for (addrp = dev->addr, i = 0; (addrp != NULL) && (connected == SANE_FALSE); addrp = addrp->ai_next, i++)
337     {
338 # ifdef ENABLE_IPV6
339       if ((addrp->ai_family != AF_INET) && (addrp->ai_family != AF_INET6))
340 # else /* !ENABLE_IPV6 */
341       if (addrp->ai_family != AF_INET)
342 # endif /* ENABLE_IPV6 */
343 	{
344 	  DBG (1, "connect_dev: [%d] don't know how to deal with addr family %d\n",
345 	       i, addrp->ai_family);
346 	  continue;
347 	}
348 
349       dev->ctl = socket (addrp->ai_family, SOCK_STREAM, 0);
350       if (dev->ctl < 0)
351 	{
352 	  DBG (1, "connect_dev: [%d] failed to obtain socket (%s)\n",
353 	       i, strerror (errno));
354 	  dev->ctl = -1;
355 	  continue;
356 	}
357 
358       /* Set SO_SNDTIMEO for the connection to saned */
359       if (connect_timeout > 0)
360 	{
361 	  tv.tv_sec = connect_timeout;
362 	  tv.tv_usec = 0;
363 
364 	  if (setsockopt (dev->ctl, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0)
365 	    {
366 	      DBG (1, "connect_dev: [%d] failed to set SO_SNDTIMEO (%s)\n", i, strerror (errno));
367 	    }
368 	}
369 
370       if (connect (dev->ctl, addrp->ai_addr, addrp->ai_addrlen) < 0)
371 	{
372 	  DBG (1, "connect_dev: [%d] failed to connect (%s)\n", i, strerror (errno));
373 	  dev->ctl = -1;
374 	  continue;
375 	}
376       DBG (3, "connect_dev: [%d] connection succeeded (%s)\n", i, (addrp->ai_family == AF_INET6) ? "IPv6" : "IPv4");
377       dev->addr_used = addrp;
378       connected = SANE_TRUE;
379     }
380 
381   if (connected != SANE_TRUE)
382     {
383       DBG (1, "connect_dev: couldn't connect to host (see messages above)\n");
384       return SANE_STATUS_IO_ERROR;
385     }
386 
387 #else /* !NET_USES_AF_INDEP */
388 
389 static SANE_Status
390 connect_dev (Net_Device * dev)
391 {
392   struct sockaddr_in *sin;
393   SANE_Word version_code;
394   SANE_Init_Reply reply;
395   SANE_Status status = SANE_STATUS_IO_ERROR;
396   SANE_Init_Req req;
397 #ifdef TCP_NODELAY
398   int on = 1;
399   int level = -1;
400 #endif
401   struct timeval tv;
402 
403   DBG (2, "connect_dev: trying to connect to %s\n", dev->name);
404 
405   if (dev->addr.sa_family != AF_INET)
406     {
407       DBG (1, "connect_dev: don't know how to deal with addr family %d\n",
408 	   dev->addr.sa_family);
409       return SANE_STATUS_IO_ERROR;
410     }
411 
412   dev->ctl = socket (dev->addr.sa_family, SOCK_STREAM, 0);
413   if (dev->ctl < 0)
414     {
415       DBG (1, "connect_dev: failed to obtain socket (%s)\n",
416 	   strerror (errno));
417       dev->ctl = -1;
418       return SANE_STATUS_IO_ERROR;
419     }
420   sin = (struct sockaddr_in *) &dev->addr;
421   sin->sin_port = saned_port;
422 
423 
424   /* Set SO_SNDTIMEO for the connection to saned */
425   if (connect_timeout > 0)
426     {
427       tv.tv_sec = connect_timeout;
428       tv.tv_usec = 0;
429 
430       if (setsockopt (dev->ctl, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0)
431 	{
432 	  DBG (1, "connect_dev: failed to set SO_SNDTIMEO (%s)\n", strerror (errno));
433 	}
434     }
435 
436   if (connect (dev->ctl, &dev->addr, sizeof (dev->addr)) < 0)
437     {
438       DBG (1, "connect_dev: failed to connect (%s)\n", strerror (errno));
439       dev->ctl = -1;
440       return SANE_STATUS_IO_ERROR;
441     }
442   DBG (3, "connect_dev: connection succeeded\n");
443 #endif /* NET_USES_AF_INDEP */
444 
445   /* We're connected now, so reset SO_SNDTIMEO to the default value of 0 */
446   if (connect_timeout > 0)
447     {
448       tv.tv_sec = 0;
449       tv.tv_usec = 0;
450 
451       if (setsockopt (dev->ctl, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0)
452 	{
453 	  DBG (1, "connect_dev: failed to reset SO_SNDTIMEO (%s)\n", strerror (errno));
454 	}
455     }
456 
457 #ifdef TCP_NODELAY
458 # ifdef SOL_TCP
459   level = SOL_TCP;
460 # else /* !SOL_TCP */
461   /* Look up the protocol level in the protocols database. */
462   {
463     struct protoent *p;
464     p = getprotobyname ("tcp");
465     if (p == 0)
466       DBG (1, "connect_dev: cannot look up `tcp' protocol number");
467     else
468       level = p->p_proto;
469   }
470 # endif	/* SOL_TCP */
471 
472   if (level == -1 ||
473       setsockopt (dev->ctl, level, TCP_NODELAY, &on, sizeof (on)))
474     DBG (1, "connect_dev: failed to put send socket in TCP_NODELAY mode (%s)",
475 	 strerror (errno));
476 #endif /* !TCP_NODELAY */
477 
478   DBG (2, "connect_dev: sanei_w_init\n");
479   sanei_w_init (&dev->wire, sanei_codec_bin_init);
480   dev->wire.io.fd = dev->ctl;
481   dev->wire.io.read = read;
482   dev->wire.io.write = write;
483 
484   /* exchange version codes with the server: */
485   req.version_code = SANE_VERSION_CODE (V_MAJOR, V_MINOR,
486 					SANEI_NET_PROTOCOL_VERSION);
487   req.username = getlogin ();
488   DBG (2, "connect_dev: net_init (user=%s, local version=%d.%d.%d)\n",
489        req.username, V_MAJOR, V_MINOR, SANEI_NET_PROTOCOL_VERSION);
490   sanei_w_call (&dev->wire, SANE_NET_INIT,
491 		(WireCodecFunc) sanei_w_init_req, &req,
492 		(WireCodecFunc) sanei_w_init_reply, &reply);
493 
494   if (dev->wire.status != 0)
495     {
496       DBG (1, "connect_dev: argument marshalling error (%s)\n",
497 	   strerror (dev->wire.status));
498       status = SANE_STATUS_IO_ERROR;
499       goto fail;
500     }
501 
502   status = reply.status;
503   version_code = reply.version_code;
504   DBG (2, "connect_dev: freeing init reply (status=%s, remote "
505        "version=%d.%d.%d)\n", sane_strstatus (status),
506        SANE_VERSION_MAJOR (version_code),
507        SANE_VERSION_MINOR (version_code), SANE_VERSION_BUILD (version_code));
508   sanei_w_free (&dev->wire, (WireCodecFunc) sanei_w_init_reply, &reply);
509 
510   if (status != 0)
511     {
512       DBG (1, "connect_dev: access to %s denied\n", dev->name);
513       goto fail;
514     }
515   if (SANE_VERSION_MAJOR (version_code) != V_MAJOR)
516     {
517       DBG (1, "connect_dev: major version mismatch: got %d, expected %d\n",
518 	   SANE_VERSION_MAJOR (version_code), V_MAJOR);
519       status = SANE_STATUS_IO_ERROR;
520       goto fail;
521     }
522   if (SANE_VERSION_BUILD (version_code) != SANEI_NET_PROTOCOL_VERSION
523       && SANE_VERSION_BUILD (version_code) != 2)
524     {
525       DBG (1, "connect_dev: network protocol version mismatch: "
526 	   "got %d, expected %d\n",
527 	   SANE_VERSION_BUILD (version_code), SANEI_NET_PROTOCOL_VERSION);
528       status = SANE_STATUS_IO_ERROR;
529       goto fail;
530     }
531   dev->wire.version = SANE_VERSION_BUILD (version_code);
532   DBG (4, "connect_dev: done\n");
533   return SANE_STATUS_GOOD;
534 
535 fail:
536   DBG (2, "connect_dev: closing connection to %s\n", dev->name);
537   close (dev->ctl);
538   dev->ctl = -1;
539   return status;
540 }
541 
542 
543 static SANE_Status
544 fetch_options (Net_Scanner * s)
545 {
546   int option_number;
547   DBG (3, "fetch_options: %p\n", (void *) s);
548 
549   if (s->opt.num_options)
550     {
551       DBG (2, "fetch_options: %d option descriptors cached... freeing\n",
552 	   s->opt.num_options);
553       sanei_w_set_dir (&s->hw->wire, WIRE_FREE);
554       s->hw->wire.status = 0;
555       sanei_w_option_descriptor_array (&s->hw->wire, &s->opt);
556       if (s->hw->wire.status)
557 	{
558 	  DBG (1, "fetch_options: failed to free old list (%s)\n",
559 	       strerror (s->hw->wire.status));
560 	  return SANE_STATUS_IO_ERROR;
561 	}
562     }
563   DBG (3, "fetch_options: get_option_descriptors\n");
564   sanei_w_call (&s->hw->wire, SANE_NET_GET_OPTION_DESCRIPTORS,
565 		(WireCodecFunc) sanei_w_word, &s->handle,
566 		(WireCodecFunc) sanei_w_option_descriptor_array, &s->opt);
567   if (s->hw->wire.status)
568     {
569       DBG (1, "fetch_options: failed to get option descriptors (%s)\n",
570 	   strerror (s->hw->wire.status));
571       return SANE_STATUS_IO_ERROR;
572     }
573 
574   if (s->local_opt.num_options == 0)
575     {
576       DBG (3, "fetch_options: creating %d local option descriptors\n",
577 	   s->opt.num_options);
578       s->local_opt.desc =
579 	malloc (s->opt.num_options * sizeof (s->local_opt.desc));
580       if (!s->local_opt.desc)
581 	{
582 	  DBG (1, "fetch_options: couldn't malloc s->local_opt.desc\n");
583 	  return SANE_STATUS_NO_MEM;
584 	}
585       for (option_number = 0;
586 	   option_number < s->opt.num_options;
587 	   option_number++)
588 	{
589 	  s->local_opt.desc[option_number] =
590 	    malloc (sizeof (SANE_Option_Descriptor));
591 	  if (!s->local_opt.desc[option_number])
592 	    {
593 	      DBG (1, "fetch_options: couldn't malloc "
594 		   "s->local_opt.desc[%d]\n", option_number);
595 	      return SANE_STATUS_NO_MEM;
596 	    }
597 	}
598       s->local_opt.num_options = s->opt.num_options;
599     }
600   else if (s->local_opt.num_options != s->opt.num_options)
601     {
602       DBG (1, "fetch_options: option number count changed during runtime?\n");
603       return SANE_STATUS_INVAL;
604     }
605 
606   DBG (3, "fetch_options: copying %d option descriptors\n",
607        s->opt.num_options);
608 
609   for (option_number = 0; option_number < s->opt.num_options; option_number++)
610     {
611       memcpy (s->local_opt.desc[option_number], s->opt.desc[option_number],
612 	      sizeof (SANE_Option_Descriptor));
613     }
614 
615   s->options_valid = 1;
616   DBG (3, "fetch_options: %d options fetched\n", s->opt.num_options);
617   return SANE_STATUS_GOOD;
618 }
619 
620 static SANE_Status
621 do_cancel (Net_Scanner * s)
622 {
623   DBG (2, "do_cancel: %p\n", (void *) s);
624   s->hw->auth_active = 0;
625   if (s->data >= 0)
626     {
627       DBG (3, "do_cancel: closing data pipe\n");
628       close (s->data);
629       s->data = -1;
630     }
631   return SANE_STATUS_CANCELLED;
632 }
633 
634 static void
635 do_authorization (Net_Device * dev, SANE_String resource)
636 {
637   SANE_Authorization_Req req;
638   SANE_Char username[SANE_MAX_USERNAME_LEN];
639   SANE_Char password[SANE_MAX_PASSWORD_LEN];
640   char *net_resource;
641 
642   DBG (2, "do_authorization: dev=%p resource=%s\n", (void *) dev, resource);
643 
644   dev->auth_active = 1;
645 
646   memset (&req, 0, sizeof (req));
647   memset (username, 0, sizeof (SANE_Char) * SANE_MAX_USERNAME_LEN);
648   memset (password, 0, sizeof (SANE_Char) * SANE_MAX_PASSWORD_LEN);
649 
650   net_resource = malloc (strlen (resource) + 6 + strlen (dev->name));
651 
652   if (net_resource != NULL)
653     {
654       sprintf (net_resource, "net:%s:%s", dev->name, resource);
655       if (auth_callback)
656 	{
657 	  DBG (2, "do_authorization: invoking auth_callback, resource = %s\n",
658 	       net_resource);
659 	  (*auth_callback) (net_resource, username, password);
660 	}
661       else
662 	DBG (1, "do_authorization: no auth_callback present\n");
663       free (net_resource);
664     }
665   else /* Is this necessary? If we don't have these few bytes we will get
666 	  in trouble later anyway */
667     {
668       DBG (1, "do_authorization: not enough memory for net_resource\n");
669       if (auth_callback)
670 	{
671 	  DBG (2, "do_authorization: invoking auth_callback, resource = %s\n",
672 	       resource);
673 	  (*auth_callback) (resource, username, password);
674 	}
675       else
676 	DBG (1, "do_authorization: no auth_callback present\n");
677     }
678 
679   if (dev->auth_active)
680     {
681       SANE_Word ack;
682 
683       req.resource = resource;
684       req.username = username;
685       req.password = password;
686       DBG (2, "do_authorization: relaying authentication data\n");
687       sanei_w_call (&dev->wire, SANE_NET_AUTHORIZE,
688 		    (WireCodecFunc) sanei_w_authorization_req, &req,
689 		    (WireCodecFunc) sanei_w_word, &ack);
690     }
691   else
692     DBG (1, "do_authorization: auth_active is false... strange\n");
693 }
694 
695 
696 #if WITH_AVAHI
697 static void
698 net_avahi_resolve_callback (AvahiServiceResolver *r, AvahiIfIndex interface, AvahiProtocol protocol,
699 			    AvahiResolverEvent event, const char *name, const char *type,
700 			    const char *domain, const char *host_name, const AvahiAddress *address,
701 			    uint16_t port, AvahiStringList *txt, AvahiLookupResultFlags flags,
702 			    void *userdata)
703 {
704   char a[AVAHI_ADDRESS_STR_MAX];
705   char *t;
706 
707   /* unused */
708   (void) interface;
709   (void) protocol;
710   (void) userdata;
711 
712   if (!r)
713     return;
714 
715   switch (event)
716     {
717       case AVAHI_RESOLVER_FAILURE:
718 	DBG (1, "net_avahi_resolve_callback: failed to resolve service '%s' of type '%s' in domain '%s': %s\n",
719 	     name, type, domain, avahi_strerror (avahi_client_errno (avahi_service_resolver_get_client (r))));
720 	break;
721 
722       case AVAHI_RESOLVER_FOUND:
723 	DBG (3, "net_avahi_resolve_callback: service '%s' of type '%s' in domain '%s':\n", name, type, domain);
724 
725 	avahi_address_snprint(a, sizeof (a), address);
726 	t = avahi_string_list_to_string (txt);
727 
728 	DBG (3, "\t%s:%u (%s)\n\tTXT=%s\n\tcookie is %u\n\tis_local: %i\n\tour_own: %i\n"
729 	     "\twide_area: %i\n\tmulticast: %i\n\tcached: %i\n",
730 	     host_name, port, a, t, avahi_string_list_get_service_cookie (txt),
731 	     !!(flags & AVAHI_LOOKUP_RESULT_LOCAL), !!(flags & AVAHI_LOOKUP_RESULT_OUR_OWN),
732 	     !!(flags & AVAHI_LOOKUP_RESULT_WIDE_AREA), !!(flags & AVAHI_LOOKUP_RESULT_MULTICAST),
733 	     !!(flags & AVAHI_LOOKUP_RESULT_CACHED));
734 
735 	/* TODO: evaluate TXT record */
736 
737 	/* Try first with the name */
738 	if (add_device (host_name, NULL) != SANE_STATUS_GOOD)
739 	  {
740 	    DBG (1, "net_avahi_resolve_callback: couldn't add backend with name %s\n", host_name);
741 
742 	    /* Then try the raw IP address */
743 	    if (add_device (t, NULL) != SANE_STATUS_GOOD)
744 	      DBG (1, "net_avahi_resolve_callback: couldn't add backend with IP address %s either\n", t);
745 	  }
746 
747 	avahi_free (t);
748 	break;
749     }
750 
751   avahi_service_resolver_free(r);
752 }
753 
754 static void
755 net_avahi_browse_callback (AvahiServiceBrowser *b, AvahiIfIndex interface, AvahiProtocol protocol,
756 			   AvahiBrowserEvent event, const char *name, const char *type,
757 			   const char *domain, AvahiLookupResultFlags flags, void *userdata)
758 {
759   AvahiProtocol proto;
760 
761   /* unused */
762   (void) flags;
763   (void) userdata;
764 
765   if (!b)
766     return;
767 
768   switch (event)
769     {
770       case AVAHI_BROWSER_FAILURE:
771 	DBG (1, "net_avahi_browse_callback: %s\n", avahi_strerror (avahi_client_errno (avahi_service_browser_get_client (b))));
772 	avahi_threaded_poll_quit (avahi_thread);
773 	return;
774 
775       case AVAHI_BROWSER_NEW:
776 	DBG (3, "net_avahi_browse_callback: NEW: service '%s' of type '%s' in domain '%s'\n", name, type, domain);
777 
778 	/* The server will actually be added to our list in the resolver callback */
779 
780 	/* The resolver object will be freed in the resolver callback, or by
781 	 * the server if it terminates before the callback is called.
782 	 */
783 #ifdef ENABLE_IPV6
784 	proto = AVAHI_PROTO_UNSPEC;
785 #else
786 	proto = AVAHI_PROTO_INET;
787 #endif /* ENABLE_IPV6 */
788 	if (!(avahi_service_resolver_new (avahi_client, interface, protocol, name, type, domain, proto, 0, net_avahi_resolve_callback, NULL)))
789 	  DBG (2, "net_avahi_browse_callback: failed to resolve service '%s': %s\n", name, avahi_strerror (avahi_client_errno (avahi_client)));
790 	break;
791 
792       case AVAHI_BROWSER_REMOVE:
793 	DBG (3, "net_avahi_browse_callback: REMOVE: service '%s' of type '%s' in domain '%s'\n", name, type, domain);
794 	/* With the current architecture, we cannot safely remove a server from the list */
795 	break;
796 
797       case AVAHI_BROWSER_ALL_FOR_NOW:
798       case AVAHI_BROWSER_CACHE_EXHAUSTED:
799 	DBG (3, "net_avahi_browse_callback: %s\n", event == AVAHI_BROWSER_CACHE_EXHAUSTED ? "CACHE_EXHAUSTED" : "ALL_FOR_NOW");
800 	break;
801     }
802 }
803 
804 static void
805 net_avahi_callback (AvahiClient *c, AvahiClientState state, void * userdata)
806 {
807   AvahiProtocol proto;
808   int error;
809 
810   /* unused */
811   (void) userdata;
812 
813   if (!c)
814     return;
815 
816   switch (state)
817     {
818       case AVAHI_CLIENT_CONNECTING:
819 	break;
820 
821       case AVAHI_CLIENT_S_COLLISION:
822       case AVAHI_CLIENT_S_REGISTERING:
823       case AVAHI_CLIENT_S_RUNNING:
824 	if (avahi_browser)
825 	  return;
826 
827 #ifdef ENABLE_IPV6
828 	proto = AVAHI_PROTO_UNSPEC;
829 #else
830 	proto = AVAHI_PROTO_INET;
831 #endif /* ENABLE_IPV6 */
832 
833 	avahi_browser = avahi_service_browser_new (c, AVAHI_IF_UNSPEC, proto, SANED_SERVICE_DNS, NULL, 0, net_avahi_browse_callback, NULL);
834 	if (avahi_browser == NULL)
835 	  {
836 	    DBG (1, "net_avahi_callback: could not create service browser: %s\n", avahi_strerror (avahi_client_errno (c)));
837 	    avahi_threaded_poll_quit (avahi_thread);
838 	  }
839 	break;
840 
841       case AVAHI_CLIENT_FAILURE:
842 	error = avahi_client_errno (c);
843 
844 	if (error == AVAHI_ERR_DISCONNECTED)
845 	  {
846 	    /* Server disappeared - try to reconnect */
847 	    if (avahi_browser)
848 	      {
849 		avahi_service_browser_free (avahi_browser);
850 		avahi_browser = NULL;
851 	      }
852 
853 	    avahi_client_free (avahi_client);
854 	    avahi_client = NULL;
855 
856 	    avahi_client = avahi_client_new (avahi_threaded_poll_get (avahi_thread), AVAHI_CLIENT_NO_FAIL, net_avahi_callback, NULL, &error);
857 	    if (avahi_client == NULL)
858 	      {
859 		DBG (1, "net_avahi_init: could not create Avahi client: %s\n", avahi_strerror (error));
860 		avahi_threaded_poll_quit (avahi_thread);
861 	      }
862 	  }
863 	else
864 	  {
865 	    /* Another error happened - game over */
866 	    DBG (1, "net_avahi_callback: server connection failure: %s\n", avahi_strerror (error));
867 	    avahi_threaded_poll_quit (avahi_thread);
868 	  }
869 	break;
870     }
871 }
872 
873 
874 static void
875 net_avahi_init (void)
876 {
877   int error;
878 
879   avahi_thread = avahi_threaded_poll_new ();
880   if (avahi_thread == NULL)
881     {
882       DBG (1, "net_avahi_init: could not create threaded poll object\n");
883       goto fail;
884     }
885 
886   avahi_client = avahi_client_new (avahi_threaded_poll_get (avahi_thread), AVAHI_CLIENT_NO_FAIL, net_avahi_callback, NULL, &error);
887   if (avahi_client == NULL)
888     {
889       DBG (1, "net_avahi_init: could not create Avahi client: %s\n", avahi_strerror (error));
890       goto fail;
891     }
892 
893   if (avahi_threaded_poll_start (avahi_thread) < 0)
894     {
895       DBG (1, "net_avahi_init: Avahi thread failed to start\n");
896       goto fail;
897     }
898 
899   /* All done */
900   return;
901 
902  fail:
903   DBG (1, "net_avahi_init: Avahi init failed, support disabled\n");
904 
905   if (avahi_client)
906     {
907       avahi_client_free (avahi_client);
908       avahi_client = NULL;
909     }
910 
911   if (avahi_thread)
912     {
913       avahi_threaded_poll_free (avahi_thread);
914       avahi_thread = NULL;
915     }
916 }
917 
918 static void
919 net_avahi_cleanup (void)
920 {
921   if (!avahi_thread)
922     return;
923 
924   DBG (1, "net_avahi_cleanup: stopping thread\n");
925 
926   avahi_threaded_poll_stop (avahi_thread);
927 
928   if (avahi_browser)
929     avahi_service_browser_free (avahi_browser);
930 
931   if (avahi_client)
932     avahi_client_free (avahi_client);
933 
934   avahi_threaded_poll_free (avahi_thread);
935 
936   DBG (1, "net_avahi_cleanup: done\n");
937 }
938 #endif /* WITH_AVAHI */
939 
940 
941 SANE_Status
942 sane_init (SANE_Int * version_code, SANE_Auth_Callback authorize)
943 {
944   char device_name[PATH_MAX];
945   const char *optval;
946   const char *env;
947   size_t len;
948   FILE *fp;
949   short ns = 0x1234;
950   unsigned char *p = (unsigned char *)(&ns);
951 
952 #ifndef NET_USES_AF_INDEP
953   struct servent *serv;
954 #endif /* !NET_USES_AF_INDEP */
955 
956   DBG_INIT ();
957 
958   DBG (2, "sane_init: authorize %s null, version_code %s null\n", (authorize) ? "!=" : "==",
959        (version_code) ? "!=" : "==");
960 
961   devlist = NULL;
962   first_device = NULL;
963   first_handle = NULL;
964 
965 #if WITH_AVAHI
966   net_avahi_init ();
967 #endif /* WITH_AVAHI */
968 
969   auth_callback = authorize;
970 
971   /* Return the version number of the sane-backends package to allow
972      the frontend to print them. This is done only for net and dll,
973      because these backends are usually called by the frontend. */
974   if (version_code)
975     *version_code = SANE_VERSION_CODE (SANE_DLL_V_MAJOR, SANE_DLL_V_MINOR,
976 				       SANE_DLL_V_BUILD);
977 
978   DBG (1, "sane_init: SANE net backend version %s from %s\n", NET_VERSION,
979        PACKAGE_STRING);
980 
981   /* determine (client) machine byte order */
982   if (*p == 0x12)
983     {
984       client_big_endian = 1;
985       DBG (3, "sane_init: Client has big endian byte order\n");
986     }
987   else
988     {
989       client_big_endian = 0;
990       DBG (3, "sane_init: Client has little endian byte order\n");
991     }
992 
993 #ifndef NET_USES_AF_INDEP
994   DBG (2, "sane_init: determining sane service port\n");
995   serv = getservbyname ("sane-port", "tcp");
996 
997   if (serv)
998     {
999       DBG (2, "sane_init: found port %d\n", ntohs (serv->s_port));
1000       saned_port = serv->s_port;
1001     }
1002   else
1003     {
1004       saned_port = htons (6566);
1005       DBG (1, "sane_init: could not find `sane-port' service (%s); using default "
1006 	   "port %d\n", strerror (errno), ntohs (saned_port));
1007     }
1008 #endif /* !NET_USES_AF_INDEP */
1009 
1010   DBG (2, "sane_init: searching for config file\n");
1011   fp = sanei_config_open (NET_CONFIG_FILE);
1012   if (fp)
1013     {
1014       while (sanei_config_read (device_name, sizeof (device_name), fp))
1015 	{
1016 	  if (device_name[0] == '#')	/* ignore line comments */
1017 	    continue;
1018 	  len = strlen (device_name);
1019 
1020 	  if (!len)
1021 	    continue;		/* ignore empty lines */
1022 
1023 	  /*
1024 	   * Check for net backend options.
1025 	   * Anything that isn't an option is a saned host.
1026 	   */
1027 	  if (strstr(device_name, "connect_timeout") != NULL)
1028 	    {
1029 	      /* Look for the = sign; if it's not there, error out */
1030 	      optval = strchr(device_name, '=');
1031 
1032 	      if (!optval)
1033 		continue;
1034 
1035 	      optval = sanei_config_skip_whitespace (++optval);
1036 	      if ((optval != NULL) && (*optval != '\0'))
1037 		{
1038 		  connect_timeout = atoi(optval);
1039 
1040 		  DBG (2, "sane_init: connect timeout set to %d seconds\n", connect_timeout);
1041 		}
1042 
1043 	      continue;
1044 	    }
1045 #if WITH_AVAHI
1046 	  avahi_threaded_poll_lock (avahi_thread);
1047 #endif /* WITH_AVAHI */
1048 	  DBG (2, "sane_init: trying to add %s\n", device_name);
1049 	  add_device (device_name, 0);
1050 #if WITH_AVAHI
1051 	  avahi_threaded_poll_unlock (avahi_thread);
1052 #endif /* WITH_AVAHI */
1053 	}
1054 
1055       fclose (fp);
1056       DBG (2, "sane_init: done reading config\n");
1057     }
1058   else
1059     DBG (1, "sane_init: could not open config file (%s): %s\n",
1060 	 NET_CONFIG_FILE, strerror (errno));
1061 
1062   DBG (2, "sane_init: evaluating environment variable SANE_NET_HOSTS\n");
1063   env = getenv ("SANE_NET_HOSTS");
1064   if (env)
1065     {
1066       char *copy, *next, *host;
1067       if ((copy = strdup (env)) != NULL)
1068 	{
1069 	  next = copy;
1070 	  while ((host = strsep (&next, ":")))
1071 	    {
1072 #ifdef ENABLE_IPV6
1073 	      if (host[0] == '[')
1074 		{
1075 		  /* skip '[' (host[0]) */
1076 		  host++;
1077 		  /* get the rest of the IPv6 addr (we're screwed if ] is missing)
1078 		   * Is it worth checking for the matching ] ? Not for now. */
1079 		  strsep (&next, "]");
1080 		  /* add back the ":" that got removed by the strsep() */
1081 		  host[strlen (host)] = ':';
1082 		  /* host now holds the IPv6 address */
1083 
1084 		  /* skip the ':' that could be after ] (avoids a call to strsep() */
1085 		  if (next[0] == ':')
1086 		    next++;
1087 		}
1088 
1089 	      /*
1090 	       * if the IPv6 is last in the list, the strsep() call in the while()
1091 	       * will return a string with the first char being '\0'. Skip it.
1092 	       */
1093 	      if (host[0] == '\0')
1094 		  continue;
1095 #endif /* ENABLE_IPV6 */
1096 #if WITH_AVAHI
1097 	      avahi_threaded_poll_lock (avahi_thread);
1098 #endif /* WITH_AVAHI */
1099 	      DBG (2, "sane_init: trying to add %s\n", host);
1100 	      add_device (host, 0);
1101 #if WITH_AVAHI
1102 	      avahi_threaded_poll_unlock (avahi_thread);
1103 #endif /* WITH_AVAHI */
1104 	    }
1105 	  free (copy);
1106 	}
1107       else
1108 	DBG (1, "sane_init: not enough memory to duplicate "
1109 	     "environment variable\n");
1110     }
1111 
1112   DBG (2, "sane_init: evaluating environment variable SANE_NET_TIMEOUT\n");
1113   env = getenv ("SANE_NET_TIMEOUT");
1114   if (env)
1115     {
1116       connect_timeout = atoi(env);
1117       DBG (2, "sane_init: connect timeout set to %d seconds from env\n", connect_timeout);
1118     }
1119 
1120   DBG (2, "sane_init: done\n");
1121   return SANE_STATUS_GOOD;
1122 }
1123 
1124 void
1125 sane_exit (void)
1126 {
1127   Net_Scanner *handle, *next_handle;
1128   Net_Device *dev, *next_device;
1129   int i;
1130 
1131   DBG (1, "sane_exit: exiting\n");
1132 
1133 #if WITH_AVAHI
1134   net_avahi_cleanup ();
1135 #endif /* WITH_AVAHI */
1136 
1137   /* first, close all handles: */
1138   for (handle = first_handle; handle; handle = next_handle)
1139     {
1140       next_handle = handle->next;
1141       sane_close (handle);
1142     }
1143   first_handle = 0;
1144 
1145   /* now close all devices: */
1146   for (dev = first_device; dev; dev = next_device)
1147     {
1148       next_device = dev->next;
1149 
1150       DBG (2, "sane_exit: closing dev %p, ctl=%d\n", (void *) dev, dev->ctl);
1151 
1152       if (dev->ctl >= 0)
1153 	{
1154 	  sanei_w_call (&dev->wire, SANE_NET_EXIT,
1155 			(WireCodecFunc) sanei_w_void, 0,
1156 			(WireCodecFunc) sanei_w_void, 0);
1157 	  sanei_w_exit (&dev->wire);
1158 	  close (dev->ctl);
1159 	}
1160       if (dev->name)
1161 	free ((void *) dev->name);
1162 
1163 #ifdef NET_USES_AF_INDEP
1164       if (dev->addr)
1165 	freeaddrinfo(dev->addr);
1166 #endif /* NET_USES_AF_INDEP */
1167 
1168       free (dev);
1169     }
1170   if (devlist)
1171     {
1172       for (i = 0; devlist[i]; ++i)
1173 	{
1174 	  if (devlist[i]->vendor)
1175 	    free ((void *) devlist[i]->vendor);
1176 	  if (devlist[i]->model)
1177 	    free ((void *) devlist[i]->model);
1178 	  if (devlist[i]->type)
1179 	    free ((void *) devlist[i]->type);
1180 	  free ((void *) devlist[i]);
1181 	}
1182       free (devlist);
1183     }
1184   DBG (3, "sane_exit: finished.\n");
1185 }
1186 
1187 /* Note that a call to get_devices() implies that we'll have to
1188    connect to all remote hosts.  To avoid this, you can call
1189    sane_open() directly (assuming you know the name of the
1190    backend/device).  This is appropriate for the command-line
1191    interface of SANE, for example.
1192  */
1193 SANE_Status
1194 sane_get_devices (const SANE_Device *** device_list, SANE_Bool local_only)
1195 {
1196   static int devlist_size = 0, devlist_len = 0;
1197   static const SANE_Device *empty_devlist[1] = { 0 };
1198   SANE_Get_Devices_Reply reply;
1199   SANE_Status status;
1200   Net_Device *dev;
1201   char *full_name;
1202   int i, num_devs;
1203   size_t len;
1204 #define ASSERT_SPACE(n) do                                                 \
1205   {                                                                        \
1206     if (devlist_len + (n) > devlist_size)                                  \
1207       {                                                                    \
1208         devlist_size += (n) + 15;                                          \
1209         if (devlist)                                                       \
1210           devlist = realloc (devlist, devlist_size * sizeof (devlist[0])); \
1211         else                                                               \
1212           devlist = malloc (devlist_size * sizeof (devlist[0]));           \
1213         if (!devlist)                                                      \
1214           {                                                                \
1215              DBG (1, "sane_get_devices: not enough memory\n");	           \
1216              return SANE_STATUS_NO_MEM;                                    \
1217           }                                                                \
1218       }                                                                    \
1219   } while (0)
1220 
1221   DBG (3, "sane_get_devices: local_only = %d\n", local_only);
1222 
1223   if (local_only)
1224     {
1225       *device_list = empty_devlist;
1226       return SANE_STATUS_GOOD;
1227     }
1228 
1229   if (devlist)
1230     {
1231       DBG (2, "sane_get_devices: freeing devlist\n");
1232       for (i = 0; devlist[i]; ++i)
1233 	{
1234 	  if (devlist[i]->vendor)
1235 	    free ((void *) devlist[i]->vendor);
1236 	  if (devlist[i]->model)
1237 	    free ((void *) devlist[i]->model);
1238 	  if (devlist[i]->type)
1239 	    free ((void *) devlist[i]->type);
1240 	  free ((void *) devlist[i]);
1241 	}
1242       free (devlist);
1243       devlist = 0;
1244     }
1245   devlist_len = 0;
1246   devlist_size = 0;
1247 
1248   for (dev = first_device; dev; dev = dev->next)
1249     {
1250       if (dev->ctl < 0)
1251 	{
1252 	  status = connect_dev (dev);
1253 	  if (status != SANE_STATUS_GOOD)
1254 	    {
1255 	      DBG (1, "sane_get_devices: ignoring failure to connect to %s\n",
1256 		   dev->name);
1257 	      continue;
1258 	    }
1259 	}
1260       sanei_w_call (&dev->wire, SANE_NET_GET_DEVICES,
1261 		    (WireCodecFunc) sanei_w_void, 0,
1262 		    (WireCodecFunc) sanei_w_get_devices_reply, &reply);
1263       if (reply.status != SANE_STATUS_GOOD)
1264 	{
1265 	  DBG (1, "sane_get_devices: ignoring rpc-returned status %s\n",
1266 	       sane_strstatus (reply.status));
1267 	  sanei_w_free (&dev->wire,
1268 			(WireCodecFunc) sanei_w_get_devices_reply, &reply);
1269 	  continue;
1270 	}
1271 
1272       /* count the number of devices for this backend: */
1273       for (num_devs = 0; reply.device_list[num_devs]; ++num_devs);
1274 
1275       ASSERT_SPACE (num_devs);
1276 
1277       for (i = 0; i < num_devs; ++i)
1278 	{
1279 	  SANE_Device *rdev;
1280 	  char *mem;
1281 #ifdef ENABLE_IPV6
1282 	  SANE_Bool IPv6 = SANE_FALSE;
1283 #endif /* ENABLE_IPV6 */
1284 
1285 	  /* create a new device entry with a device name that is the
1286 	     sum of the backend name a colon and the backend's device
1287 	     name: */
1288 	  len = strlen (dev->name) + 1 + strlen (reply.device_list[i]->name);
1289 
1290 #ifdef ENABLE_IPV6
1291 	  if (strchr (dev->name, ':') != NULL)
1292 	    {
1293 	      len += 2;
1294 	      IPv6 = SANE_TRUE;
1295 	    }
1296 #endif /* ENABLE_IPV6 */
1297 
1298 	  mem = malloc (sizeof (*dev) + len + 1);
1299 	  if (!mem)
1300 	    {
1301 	      DBG (1, "sane_get_devices: not enough free memory\n");
1302 	      sanei_w_free (&dev->wire,
1303 			    (WireCodecFunc) sanei_w_get_devices_reply,
1304 			    &reply);
1305 	      return SANE_STATUS_NO_MEM;
1306 	    }
1307 
1308 	  memset (mem, 0, sizeof (*dev) + len);
1309 	  full_name = mem + sizeof (*dev);
1310 
1311 #ifdef ENABLE_IPV6
1312 	  if (IPv6 == SANE_TRUE)
1313 	    strcat (full_name, "[");
1314 #endif /* ENABLE_IPV6 */
1315 
1316 	  strcat (full_name, dev->name);
1317 
1318 #ifdef ENABLE_IPV6
1319 	  if (IPv6 == SANE_TRUE)
1320 	    strcat (full_name, "]");
1321 #endif /* ENABLE_IPV6 */
1322 
1323 	  strcat (full_name, ":");
1324 	  strcat (full_name, reply.device_list[i]->name);
1325 	  DBG (3, "sane_get_devices: got %s\n", full_name);
1326 
1327 	  rdev = (SANE_Device *) mem;
1328 	  rdev->name = full_name;
1329 	  rdev->vendor = strdup (reply.device_list[i]->vendor);
1330 	  rdev->model = strdup (reply.device_list[i]->model);
1331 	  rdev->type = strdup (reply.device_list[i]->type);
1332 
1333 	  if ((!rdev->vendor) || (!rdev->model) || (!rdev->type))
1334 	    {
1335 	      DBG (1, "sane_get_devices: not enough free memory\n");
1336 	      if (rdev->vendor)
1337 		free ((void *) rdev->vendor);
1338 	      if (rdev->model)
1339 		free ((void *) rdev->model);
1340 	      if (rdev->type)
1341 		free ((void *) rdev->type);
1342 	      free (rdev);
1343 	      sanei_w_free (&dev->wire,
1344 			    (WireCodecFunc) sanei_w_get_devices_reply,
1345 			    &reply);
1346 	      return SANE_STATUS_NO_MEM;
1347 	    }
1348 
1349 	  devlist[devlist_len++] = rdev;
1350 	}
1351       /* now free up the rpc return value: */
1352       sanei_w_free (&dev->wire,
1353 		    (WireCodecFunc) sanei_w_get_devices_reply, &reply);
1354     }
1355 
1356   /* terminate device list with NULL entry: */
1357   ASSERT_SPACE (1);
1358   devlist[devlist_len++] = 0;
1359 
1360   *device_list = devlist;
1361   DBG (2, "sane_get_devices: finished (%d devices)\n", devlist_len - 1);
1362   return SANE_STATUS_GOOD;
1363 }
1364 
1365 SANE_Status
1366 sane_open (SANE_String_Const full_name, SANE_Handle * meta_handle)
1367 {
1368   SANE_Open_Reply reply;
1369   const char *dev_name;
1370 #ifdef ENABLE_IPV6
1371   const char *tmp_name;
1372   SANE_Bool v6addr = SANE_FALSE;
1373 #endif /* ENABLE_IPV6 */
1374   SANE_String nd_name;
1375   SANE_Status status;
1376   SANE_Word handle;
1377   SANE_Word ack;
1378   Net_Device *dev;
1379   Net_Scanner *s;
1380   int need_auth;
1381 
1382   DBG (3, "sane_open(\"%s\")\n", full_name);
1383 
1384 #ifdef ENABLE_IPV6
1385   /*
1386    * Check whether a numerical IPv6 host was specified
1387    * [2001:42:42::12] <== check for '[' as full_name[0]
1388    * ex: [2001:42:42::12]:test:0 (syntax taken from Apache 2)
1389    */
1390   if (full_name[0] == '[')
1391     {
1392       v6addr = SANE_TRUE;
1393       tmp_name = strchr (full_name, ']');
1394       if (!tmp_name)
1395 	{
1396 	  DBG (1, "sane_open: incorrect host address: missing matching ']'\n");
1397 	  return SANE_STATUS_INVAL;
1398 	}
1399     }
1400   else
1401     tmp_name = full_name;
1402 
1403   dev_name = strchr (tmp_name, ':');
1404 #else /* !ENABLE_IPV6 */
1405 
1406   dev_name = strchr (full_name, ':');
1407 #endif /* ENABLE_IPV6 */
1408 
1409   if (dev_name)
1410     {
1411 #ifdef strndupa
1412 # ifdef ENABLE_IPV6
1413       if (v6addr == SANE_TRUE)
1414 	nd_name = strndupa (full_name + 1, dev_name - full_name - 2);
1415       else
1416 	nd_name = strndupa (full_name, dev_name - full_name);
1417 
1418 # else /* !ENABLE_IPV6 */
1419 
1420       nd_name = strndupa (full_name, dev_name - full_name);
1421 # endif /* ENABLE_IPV6 */
1422 
1423       if (!nd_name)
1424 	{
1425 	  DBG (1, "sane_open: not enough free memory\n");
1426 	  return SANE_STATUS_NO_MEM;
1427 	}
1428 #else
1429       char *tmp;
1430 
1431 # ifdef ENABLE_IPV6
1432       if (v6addr == SANE_TRUE)
1433 	tmp = alloca (dev_name - full_name - 2 + 1);
1434       else
1435 	tmp = alloca (dev_name - full_name + 1);
1436 
1437 # else /* !ENABLE_IPV6 */
1438 
1439       tmp = alloca (dev_name - full_name + 1);
1440 # endif /* ENABLE_IPV6 */
1441 
1442       if (!tmp)
1443 	{
1444 	  DBG (1, "sane_open: not enough free memory\n");
1445 	  return SANE_STATUS_NO_MEM;
1446 	}
1447 
1448 # ifdef ENABLE_IPV6
1449       if (v6addr == SANE_TRUE)
1450 	{
1451 	  memcpy (tmp, full_name + 1, dev_name - full_name - 2);
1452 	  tmp[dev_name - full_name - 2] = '\0';
1453 	}
1454       else
1455 	{
1456 	  memcpy (tmp, full_name, dev_name - full_name);
1457 	  tmp[dev_name - full_name] = '\0';
1458 	}
1459 
1460 # else /* !ENABLE_IPV6 */
1461 
1462       memcpy (tmp, full_name, dev_name - full_name);
1463       tmp[dev_name - full_name] = '\0';
1464 # endif /* ENABLE_IPV6 */
1465 
1466       nd_name = tmp;
1467 #endif
1468       ++dev_name;		/* skip colon */
1469     }
1470   else
1471     {
1472       /* if no colon interpret full_name as the host name; an empty
1473          device name will cause us to open the first device of that
1474          host.  */
1475 #ifdef ENABLE_IPV6
1476       if (v6addr == SANE_TRUE)
1477 	{
1478 	  nd_name = alloca (strlen (full_name) - 2 + 1);
1479 	  if (!nd_name)
1480 	    {
1481 	      DBG (1, "sane_open: not enough free memory\n");
1482 	      return SANE_STATUS_NO_MEM;
1483 	    }
1484 	  memcpy (nd_name, full_name + 1, strlen (full_name) - 2);
1485 	  nd_name[strlen (full_name) - 2] = '\0';
1486 	}
1487       else
1488 	nd_name = (char *) full_name;
1489 
1490 #else /* !ENABLE_IPV6 */
1491 
1492       nd_name = (char *) full_name;
1493 #endif /* ENABLE_IPV6 */
1494 
1495       dev_name = "";
1496     }
1497   DBG (2, "sane_open: host = %s, device = %s\n", nd_name, dev_name);
1498 
1499   if (!nd_name[0])
1500     {
1501       /* Unlike other backends, we never allow an empty backend-name.
1502          Otherwise, it's possible that sane_open("") will result in
1503          endless looping (consider the case where NET is the first
1504          backend...) */
1505 
1506       DBG (1, "sane_open: empty backend name is not allowed\n");
1507       return SANE_STATUS_INVAL;
1508     }
1509   else
1510     for (dev = first_device; dev; dev = dev->next)
1511       if (strcmp (dev->name, nd_name) == 0)
1512 	break;
1513 
1514   if (!dev)
1515     {
1516       DBG (1,
1517 	   "sane_open: device %s not found, trying to register it anyway\n",
1518 	   nd_name);
1519 #if WITH_AVAHI
1520       avahi_threaded_poll_lock (avahi_thread);
1521 #endif /* WITH_AVAHI */
1522       status = add_device (nd_name, &dev);
1523 #if WITH_AVAHI
1524       avahi_threaded_poll_unlock (avahi_thread);
1525 #endif /* WITH_AVAHI */
1526       if (status != SANE_STATUS_GOOD)
1527 	{
1528 	  DBG (1, "sane_open: could not open device\n");
1529 	  return status;
1530 	}
1531     }
1532   else
1533     DBG (2, "sane_open: device found in list\n");
1534 
1535   if (dev->ctl < 0)
1536     {
1537       DBG (2, "sane_open: device not connected yet...\n");
1538       status = connect_dev (dev);
1539       if (status != SANE_STATUS_GOOD)
1540 	{
1541 	  DBG (1, "sane_open: could not connect to device\n");
1542 	  return status;
1543 	}
1544     }
1545 
1546   DBG (3, "sane_open: net_open\n");
1547   sanei_w_call (&dev->wire, SANE_NET_OPEN,
1548 		(WireCodecFunc) sanei_w_string, &dev_name,
1549 		(WireCodecFunc) sanei_w_open_reply, &reply);
1550   do
1551     {
1552       if (dev->wire.status != 0)
1553 	{
1554 	  DBG (1, "sane_open: open rpc call failed (%s)\n",
1555 	       strerror (dev->wire.status));
1556 	  return SANE_STATUS_IO_ERROR;
1557 	}
1558 
1559       status = reply.status;
1560       handle = reply.handle;
1561       need_auth = (reply.resource_to_authorize != 0);
1562 
1563       if (need_auth)
1564 	{
1565 	  DBG (3, "sane_open: authorization required\n");
1566 	  do_authorization (dev, reply.resource_to_authorize);
1567 
1568 	  sanei_w_free (&dev->wire, (WireCodecFunc) sanei_w_open_reply,
1569 			&reply);
1570 
1571 	  if (dev->wire.direction != WIRE_DECODE)
1572 	    sanei_w_set_dir (&dev->wire, WIRE_DECODE);
1573 	  sanei_w_open_reply (&dev->wire, &reply);
1574 
1575 	  continue;
1576 	}
1577       else
1578 	sanei_w_free (&dev->wire, (WireCodecFunc) sanei_w_open_reply, &reply);
1579 
1580       if (need_auth && !dev->auth_active)
1581 	{
1582 	  DBG (2, "sane_open: open cancelled\n");
1583 	  return SANE_STATUS_CANCELLED;
1584 	}
1585 
1586       if (status != SANE_STATUS_GOOD)
1587 	{
1588 	  DBG (1, "sane_open: remote open failed\n");
1589 	  return reply.status;
1590 	}
1591     }
1592   while (need_auth);
1593 
1594   s = malloc (sizeof (*s));
1595   if (!s)
1596     {
1597       DBG (1, "sane_open: not enough free memory\n");
1598       return SANE_STATUS_NO_MEM;
1599     }
1600 
1601   memset (s, 0, sizeof (*s));
1602   s->hw = dev;
1603   s->handle = handle;
1604   s->data = -1;
1605   s->next = first_handle;
1606   s->local_opt.desc = 0;
1607   s->local_opt.num_options = 0;
1608 
1609   DBG (3, "sane_open: getting option descriptors\n");
1610   status = fetch_options (s);
1611   if (status != SANE_STATUS_GOOD)
1612     {
1613       DBG (1, "sane_open: fetch_options failed (%s), closing device again\n",
1614 	   sane_strstatus (status));
1615 
1616       sanei_w_call (&s->hw->wire, SANE_NET_CLOSE,
1617 		    (WireCodecFunc) sanei_w_word, &s->handle,
1618 		    (WireCodecFunc) sanei_w_word, &ack);
1619 
1620       free (s);
1621 
1622       return status;
1623     }
1624 
1625   first_handle = s;
1626   *meta_handle = s;
1627 
1628   DBG (3, "sane_open: success\n");
1629   return SANE_STATUS_GOOD;
1630 }
1631 
1632 void
1633 sane_close (SANE_Handle handle)
1634 {
1635   Net_Scanner *prev, *s;
1636   SANE_Word ack;
1637   int option_number;
1638 
1639   DBG (3, "sane_close: handle %p\n", handle);
1640 
1641   prev = 0;
1642   for (s = first_handle; s; s = s->next)
1643     {
1644       if (s == handle)
1645 	break;
1646       prev = s;
1647     }
1648   if (!s)
1649     {
1650       DBG (1, "sane_close: invalid handle %p\n", handle);
1651       return;			/* oops, not a handle we know about */
1652     }
1653   if (prev)
1654     prev->next = s->next;
1655   else
1656     first_handle = s->next;
1657 
1658   if (s->opt.num_options)
1659     {
1660       DBG (2, "sane_close: removing cached option descriptors\n");
1661       sanei_w_set_dir (&s->hw->wire, WIRE_FREE);
1662       s->hw->wire.status = 0;
1663       sanei_w_option_descriptor_array (&s->hw->wire, &s->opt);
1664       if (s->hw->wire.status)
1665 	DBG (1, "sane_close: couldn't free sanei_w_option_descriptor_array "
1666 	     "(%s)\n", sane_strstatus (s->hw->wire.status));
1667     }
1668 
1669   DBG (2, "sane_close: removing local option descriptors\n");
1670   for (option_number = 0; option_number < s->local_opt.num_options;
1671        option_number++)
1672     free (s->local_opt.desc[option_number]);
1673   if (s->local_opt.desc)
1674     free (s->local_opt.desc);
1675 
1676   DBG (2, "sane_close: net_close\n");
1677   sanei_w_call (&s->hw->wire, SANE_NET_CLOSE,
1678 		(WireCodecFunc) sanei_w_word, &s->handle,
1679 		(WireCodecFunc) sanei_w_word, &ack);
1680   if (s->data >= 0)
1681     {
1682       DBG (2, "sane_close: closing data pipe\n");
1683       close (s->data);
1684     }
1685   free (s);
1686   DBG (2, "sane_close: done\n");
1687 }
1688 
1689 const SANE_Option_Descriptor *
1690 sane_get_option_descriptor (SANE_Handle handle, SANE_Int option)
1691 {
1692   Net_Scanner *s = handle;
1693   SANE_Status status;
1694 
1695   DBG (3, "sane_get_option_descriptor: option %d\n", option);
1696 
1697   if (!s->options_valid)
1698     {
1699       DBG (3, "sane_get_option_descriptor: getting option descriptors\n");
1700       status = fetch_options (s);
1701       if (status != SANE_STATUS_GOOD)
1702 	{
1703 	  DBG (1, "sane_get_option_descriptor: fetch_options failed (%s)\n",
1704 	       sane_strstatus (status));
1705 	  return 0;
1706 	}
1707     }
1708 
1709   if (((SANE_Word) option >= s->opt.num_options) || (option < 0))
1710     {
1711       DBG (2, "sane_get_option_descriptor: invalid option number\n");
1712       return 0;
1713     }
1714   return s->local_opt.desc[option];
1715 }
1716 
1717 SANE_Status
1718 sane_control_option (SANE_Handle handle, SANE_Int option,
1719 		     SANE_Action action, void *value, SANE_Word * info)
1720 {
1721   Net_Scanner *s = handle;
1722   SANE_Control_Option_Req req;
1723   SANE_Control_Option_Reply reply;
1724   SANE_Status status;
1725   size_t value_size;
1726   int need_auth;
1727   SANE_Word local_info;
1728 
1729   DBG (3, "sane_control_option: option %d, action %d\n", option, action);
1730 
1731   if (!s->options_valid)
1732     {
1733       DBG (1, "sane_control_option: FRONTEND BUG: option descriptors reload needed\n");
1734       return SANE_STATUS_INVAL;
1735     }
1736 
1737   if (((SANE_Word) option >= s->opt.num_options) || (option < 0))
1738     {
1739       DBG (1, "sane_control_option: invalid option number\n");
1740       return SANE_STATUS_INVAL;
1741     }
1742 
1743   switch (s->opt.desc[option]->type)
1744     {
1745     case SANE_TYPE_BUTTON:
1746     case SANE_TYPE_GROUP:	/* shouldn't happen... */
1747       /* the SANE standard defines that the option size of a BUTTON or
1748          GROUP is IGNORED.  */
1749       value_size = 0;
1750       break;
1751     case SANE_TYPE_STRING:	/* strings can be smaller than size */
1752       value_size = s->opt.desc[option]->size;
1753       if ((action == SANE_ACTION_SET_VALUE)
1754 	  && (((SANE_Int) strlen ((SANE_String) value) + 1)
1755 	      < s->opt.desc[option]->size))
1756 	value_size = strlen ((SANE_String) value) + 1;
1757       break;
1758     default:
1759       value_size = s->opt.desc[option]->size;
1760       break;
1761     }
1762 
1763   /* Avoid leaking memory bits */
1764   if (value && (action != SANE_ACTION_SET_VALUE))
1765     memset (value, 0, value_size);
1766 
1767   /* for SET_AUTO the parameter ``value'' is ignored */
1768   if (action == SANE_ACTION_SET_AUTO)
1769     value_size = 0;
1770 
1771   req.handle = s->handle;
1772   req.option = option;
1773   req.action = action;
1774   req.value_type = s->opt.desc[option]->type;
1775   req.value_size = value_size;
1776   req.value = value;
1777 
1778   local_info = 0;
1779 
1780   DBG (3, "sane_control_option: remote control option\n");
1781   sanei_w_call (&s->hw->wire, SANE_NET_CONTROL_OPTION,
1782 		(WireCodecFunc) sanei_w_control_option_req, &req,
1783 		(WireCodecFunc) sanei_w_control_option_reply, &reply);
1784 
1785   do
1786     {
1787       status = reply.status;
1788       need_auth = (reply.resource_to_authorize != 0);
1789       if (need_auth)
1790 	{
1791 	  DBG (3, "sane_control_option: auth required\n");
1792 	  do_authorization (s->hw, reply.resource_to_authorize);
1793 	  sanei_w_free (&s->hw->wire,
1794 			(WireCodecFunc) sanei_w_control_option_reply, &reply);
1795 
1796 	  sanei_w_set_dir (&s->hw->wire, WIRE_DECODE);
1797 
1798 	  sanei_w_control_option_reply (&s->hw->wire, &reply);
1799 	  continue;
1800 
1801 	}
1802       else if (status == SANE_STATUS_GOOD)
1803 	{
1804 	  local_info = reply.info;
1805 
1806 	  if (info)
1807 	    *info = reply.info;
1808 	  if (value_size > 0)
1809 	    {
1810 	      if ((SANE_Word) value_size == reply.value_size)
1811 		memcpy (value, reply.value, reply.value_size);
1812 	      else
1813 		DBG (1, "sane_control_option: size changed from %d to %d\n",
1814 		     s->opt.desc[option]->size, reply.value_size);
1815 	    }
1816 
1817 	  if (reply.info & SANE_INFO_RELOAD_OPTIONS)
1818 	    s->options_valid = 0;
1819 	}
1820       sanei_w_free (&s->hw->wire,
1821 		    (WireCodecFunc) sanei_w_control_option_reply, &reply);
1822       if (need_auth && !s->hw->auth_active)
1823 	return SANE_STATUS_CANCELLED;
1824     }
1825   while (need_auth);
1826 
1827   DBG (2, "sane_control_option: remote done (%s, info %x)\n", sane_strstatus (status), local_info);
1828 
1829   if ((status == SANE_STATUS_GOOD) && (info == NULL) && (local_info & SANE_INFO_RELOAD_OPTIONS))
1830     {
1831       DBG (2, "sane_control_option: reloading options as frontend does not care\n");
1832 
1833       status = fetch_options (s);
1834 
1835       DBG (2, "sane_control_option: reload done (%s)\n", sane_strstatus (status));
1836     }
1837 
1838   DBG (2, "sane_control_option: done (%s, info %x)\n", sane_strstatus (status), local_info);
1839 
1840   return status;
1841 }
1842 
1843 SANE_Status
1844 sane_get_parameters (SANE_Handle handle, SANE_Parameters * params)
1845 {
1846   Net_Scanner *s = handle;
1847   SANE_Get_Parameters_Reply reply;
1848   SANE_Status status;
1849 
1850   DBG (3, "sane_get_parameters\n");
1851 
1852   if (!params)
1853     {
1854       DBG (1, "sane_get_parameters: parameter params not supplied\n");
1855       return SANE_STATUS_INVAL;
1856     }
1857 
1858   DBG (3, "sane_get_parameters: remote get parameters\n");
1859   sanei_w_call (&s->hw->wire, SANE_NET_GET_PARAMETERS,
1860 		(WireCodecFunc) sanei_w_word, &s->handle,
1861 		(WireCodecFunc) sanei_w_get_parameters_reply, &reply);
1862 
1863   status = reply.status;
1864   *params = reply.params;
1865   depth = reply.params.depth;
1866   sanei_w_free (&s->hw->wire,
1867 		(WireCodecFunc) sanei_w_get_parameters_reply, &reply);
1868 
1869   DBG (3, "sane_get_parameters: returned status %s\n",
1870        sane_strstatus (status));
1871   return status;
1872 }
1873 
1874 #ifdef NET_USES_AF_INDEP
1875 SANE_Status
1876 sane_start (SANE_Handle handle)
1877 {
1878   Net_Scanner *s = handle;
1879   SANE_Start_Reply reply;
1880   struct sockaddr_in sin;
1881   struct sockaddr *sa;
1882 #ifdef ENABLE_IPV6
1883   struct sockaddr_in6 sin6;
1884 #endif /* ENABLE_IPV6 */
1885   SANE_Status status;
1886   int fd, need_auth;
1887   socklen_t len;
1888   uint16_t port;			/* Internet-specific */
1889 
1890 
1891   DBG (3, "sane_start\n");
1892 
1893   hang_over = -1;
1894   left_over = -1;
1895 
1896   if (s->data >= 0)
1897     {
1898       DBG (2, "sane_start: data pipe already exists\n");
1899       return SANE_STATUS_INVAL;
1900     }
1901 
1902   /* Do this ahead of time so in case anything fails, we can
1903      recover gracefully (without hanging our server).  */
1904 
1905   switch (s->hw->addr_used->ai_family)
1906     {
1907       case AF_INET:
1908 	len = sizeof (sin);
1909 	sa = (struct sockaddr *) &sin;
1910 	break;
1911 #ifdef ENABLE_IPV6
1912       case AF_INET6:
1913 	len = sizeof (sin6);
1914 	sa = (struct sockaddr *) &sin6;
1915 	break;
1916 #endif /* ENABLE_IPV6 */
1917       default:
1918 	DBG (1, "sane_start: unknown address family : %d\n",
1919 	     s->hw->addr_used->ai_family);
1920 	return SANE_STATUS_INVAL;
1921     }
1922 
1923   if (getpeername (s->hw->ctl, sa, &len) < 0)
1924     {
1925       DBG (1, "sane_start: getpeername() failed (%s)\n", strerror (errno));
1926       return SANE_STATUS_IO_ERROR;
1927     }
1928 
1929   fd = socket (s->hw->addr_used->ai_family, SOCK_STREAM, 0);
1930   if (fd < 0)
1931     {
1932       DBG (1, "sane_start: socket() failed (%s)\n", strerror (errno));
1933       return SANE_STATUS_IO_ERROR;
1934     }
1935 
1936   DBG (3, "sane_start: remote start\n");
1937   sanei_w_call (&s->hw->wire, SANE_NET_START,
1938 		(WireCodecFunc) sanei_w_word, &s->handle,
1939 		(WireCodecFunc) sanei_w_start_reply, &reply);
1940   do
1941     {
1942       status = reply.status;
1943       port = reply.port;
1944       if (reply.byte_order == 0x1234)
1945 	{
1946 	  server_big_endian = 0;
1947 	  DBG (1, "sane_start: server has little endian byte order\n");
1948 	}
1949       else
1950 	{
1951 	  server_big_endian = 1;
1952 	  DBG (1, "sane_start: server has big endian byte order\n");
1953 	}
1954 
1955       need_auth = (reply.resource_to_authorize != 0);
1956       if (need_auth)
1957 	{
1958 	  DBG (3, "sane_start: auth required\n");
1959 	  do_authorization (s->hw, reply.resource_to_authorize);
1960 
1961 	  sanei_w_free (&s->hw->wire,
1962 			(WireCodecFunc) sanei_w_start_reply, &reply);
1963 
1964 	  sanei_w_set_dir (&s->hw->wire, WIRE_DECODE);
1965 
1966 	  sanei_w_start_reply (&s->hw->wire, &reply);
1967 
1968 	  continue;
1969 	}
1970       sanei_w_free (&s->hw->wire, (WireCodecFunc) sanei_w_start_reply,
1971 		    &reply);
1972       if (need_auth && !s->hw->auth_active)
1973 	return SANE_STATUS_CANCELLED;
1974 
1975       if (status != SANE_STATUS_GOOD)
1976 	{
1977 	  DBG (1, "sane_start: remote start failed (%s)\n",
1978 	       sane_strstatus (status));
1979 	  close (fd);
1980 	  return status;
1981 	}
1982     }
1983   while (need_auth);
1984   DBG (3, "sane_start: remote start finished, data at port %hu\n", port);
1985 
1986   switch (s->hw->addr_used->ai_family)
1987     {
1988       case AF_INET:
1989 	sin.sin_port = htons (port);
1990 	break;
1991 #ifdef ENABLE_IPV6
1992       case AF_INET6:
1993 	sin6.sin6_port = htons (port);
1994 	break;
1995 #endif /* ENABLE_IPV6 */
1996     }
1997 
1998   if (connect (fd, sa, len) < 0)
1999     {
2000       DBG (1, "sane_start: connect() failed (%s)\n", strerror (errno));
2001       close (fd);
2002       return SANE_STATUS_IO_ERROR;
2003     }
2004   shutdown (fd, 1);
2005   s->data = fd;
2006   s->reclen_buf_offset = 0;
2007   s->bytes_remaining = 0;
2008   DBG (3, "sane_start: done (%s)\n", sane_strstatus (status));
2009   return status;
2010 }
2011 
2012 #else /* !NET_USES_AF_INDEP */
2013 
2014 SANE_Status
2015 sane_start (SANE_Handle handle)
2016 {
2017   Net_Scanner *s = handle;
2018   SANE_Start_Reply reply;
2019   struct sockaddr_in sin;
2020   SANE_Status status;
2021   int fd, need_auth;
2022   socklen_t len;
2023   uint16_t port;			/* Internet-specific */
2024 
2025 
2026   DBG (3, "sane_start\n");
2027 
2028   hang_over = -1;
2029   left_over = -1;
2030 
2031   if (s->data >= 0)
2032     {
2033       DBG (2, "sane_start: data pipe already exists\n");
2034       return SANE_STATUS_INVAL;
2035     }
2036 
2037   /* Do this ahead of time so in case anything fails, we can
2038      recover gracefully (without hanging our server).  */
2039   len = sizeof (sin);
2040   if (getpeername (s->hw->ctl, (struct sockaddr *) &sin, &len) < 0)
2041     {
2042       DBG (1, "sane_start: getpeername() failed (%s)\n", strerror (errno));
2043       return SANE_STATUS_IO_ERROR;
2044     }
2045 
2046   fd = socket (s->hw->addr.sa_family, SOCK_STREAM, 0);
2047   if (fd < 0)
2048     {
2049       DBG (1, "sane_start: socket() failed (%s)\n", strerror (errno));
2050       return SANE_STATUS_IO_ERROR;
2051     }
2052 
2053   DBG (3, "sane_start: remote start\n");
2054   sanei_w_call (&s->hw->wire, SANE_NET_START,
2055 		(WireCodecFunc) sanei_w_word, &s->handle,
2056 		(WireCodecFunc) sanei_w_start_reply, &reply);
2057   do
2058     {
2059 
2060       status = reply.status;
2061       port = reply.port;
2062       if (reply.byte_order == 0x1234)
2063 	{
2064 	  server_big_endian = 0;
2065 	  DBG (1, "sane_start: server has little endian byte order\n");
2066 	}
2067       else
2068 	{
2069 	  server_big_endian = 1;
2070 	  DBG (1, "sane_start: server has big endian byte order\n");
2071 	}
2072 
2073       need_auth = (reply.resource_to_authorize != 0);
2074       if (need_auth)
2075 	{
2076 	  DBG (3, "sane_start: auth required\n");
2077 	  do_authorization (s->hw, reply.resource_to_authorize);
2078 
2079 	  sanei_w_free (&s->hw->wire,
2080 			(WireCodecFunc) sanei_w_start_reply, &reply);
2081 
2082 	  sanei_w_set_dir (&s->hw->wire, WIRE_DECODE);
2083 
2084 	  sanei_w_start_reply (&s->hw->wire, &reply);
2085 
2086 	  continue;
2087 	}
2088       sanei_w_free (&s->hw->wire, (WireCodecFunc) sanei_w_start_reply,
2089 		    &reply);
2090       if (need_auth && !s->hw->auth_active)
2091 	return SANE_STATUS_CANCELLED;
2092 
2093       if (status != SANE_STATUS_GOOD)
2094 	{
2095 	  DBG (1, "sane_start: remote start failed (%s)\n",
2096 	       sane_strstatus (status));
2097 	  close (fd);
2098 	  return status;
2099 	}
2100     }
2101   while (need_auth);
2102   DBG (3, "sane_start: remote start finished, data at port %hu\n", port);
2103   sin.sin_port = htons (port);
2104 
2105   if (connect (fd, (struct sockaddr *) &sin, len) < 0)
2106     {
2107       DBG (1, "sane_start: connect() failed (%s)\n", strerror (errno));
2108       close (fd);
2109       return SANE_STATUS_IO_ERROR;
2110     }
2111   shutdown (fd, 1);
2112   s->data = fd;
2113   s->reclen_buf_offset = 0;
2114   s->bytes_remaining = 0;
2115   DBG (3, "sane_start: done (%s)\n", sane_strstatus (status));
2116   return status;
2117 }
2118 #endif /* NET_USES_AF_INDEP */
2119 
2120 
2121 SANE_Status
2122 sane_read (SANE_Handle handle, SANE_Byte * data, SANE_Int max_length,
2123 	   SANE_Int * length)
2124 {
2125   Net_Scanner *s = handle;
2126   ssize_t nread;
2127   SANE_Int cnt;
2128   SANE_Int start_cnt;
2129   SANE_Int end_cnt;
2130   SANE_Byte swap_buf;
2131   SANE_Byte temp_hang_over;
2132   int is_even;
2133 
2134   DBG (3, "sane_read: handle=%p, data=%p, max_length=%d, length=%p\n",
2135        handle, (void *) data, max_length, (void *) length);
2136   if (!length)
2137     {
2138       DBG (1, "sane_read: length == NULL\n");
2139       return SANE_STATUS_INVAL;
2140     }
2141 
2142   is_even = 1;
2143   *length = 0;
2144 
2145   /* If there's a left over, i.e. a byte already in the correct byte order,
2146      return it immediately; otherwise read may fail with a SANE_STATUS_EOF and
2147      the caller never can read the last byte */
2148   if ((depth == 16) && (server_big_endian != client_big_endian))
2149     {
2150       if (left_over > -1)
2151 	{
2152 	  DBG (3, "sane_read: left_over from previous call, return "
2153 	       "immediately\n");
2154 	  /* return the byte, we've currently scanned; hang_over becomes
2155 	     left_over */
2156 	  *data = (SANE_Byte) left_over;
2157 	  left_over = -1;
2158 	  *length = 1;
2159 	  return SANE_STATUS_GOOD;
2160 	}
2161     }
2162 
2163   if (s->data < 0)
2164     {
2165       DBG (1, "sane_read: data pipe doesn't exist, scan cancelled?\n");
2166       return SANE_STATUS_CANCELLED;
2167     }
2168 
2169   if (s->bytes_remaining == 0)
2170     {
2171       /* boy, is this painful or what? */
2172 
2173       DBG (4, "sane_read: reading packet length\n");
2174       nread = read (s->data, s->reclen_buf + s->reclen_buf_offset,
2175 		    4 - s->reclen_buf_offset);
2176       if (nread < 0)
2177 	{
2178 	  DBG (3, "sane_read: read failed (%s)\n", strerror (errno));
2179 	  if (errno == EAGAIN)
2180 	    {
2181 	      DBG (3, "sane_read: try again later\n");
2182 	      return SANE_STATUS_GOOD;
2183 	    }
2184 	  else
2185 	    {
2186 	      DBG (1, "sane_read: cancelling read\n");
2187 	      do_cancel (s);
2188 	      return SANE_STATUS_IO_ERROR;
2189 	    }
2190 	}
2191       DBG (4, "sane_read: read %lu bytes, %d from 4 total\n", (u_long) nread,
2192 	   s->reclen_buf_offset);
2193       s->reclen_buf_offset += nread;
2194       if (s->reclen_buf_offset < 4)
2195 	{
2196 	  DBG (4, "sane_read: enough for now\n");
2197 	  return SANE_STATUS_GOOD;
2198 	}
2199 
2200       s->reclen_buf_offset = 0;
2201       s->bytes_remaining = (((u_long) s->reclen_buf[0] << 24)
2202 			    | ((u_long) s->reclen_buf[1] << 16)
2203 			    | ((u_long) s->reclen_buf[2] << 8)
2204 			    | ((u_long) s->reclen_buf[3] << 0));
2205       DBG (3, "sane_read: next record length=%ld bytes\n",
2206 	   (long) s->bytes_remaining);
2207       if (s->bytes_remaining == 0xffffffff)
2208 	{
2209 	  char ch;
2210 
2211 	  DBG (2, "sane_read: received error signal\n");
2212 
2213 	  /* turn off non-blocking I/O (s->data will be closed anyhow): */
2214 	  fcntl (s->data, F_SETFL, 0);
2215 
2216 	  /* read the status byte: */
2217 	  if (read (s->data, &ch, sizeof (ch)) != 1)
2218 	    {
2219 	      DBG (1, "sane_read: failed to read error code\n");
2220 	      ch = SANE_STATUS_IO_ERROR;
2221 	    }
2222 	  DBG (1, "sane_read: error code %s\n",
2223 	       sane_strstatus ((SANE_Status) ch));
2224 	  do_cancel (s);
2225 	  return (SANE_Status) ch;
2226 	}
2227     }
2228 
2229   if (max_length > (SANE_Int) s->bytes_remaining)
2230     max_length = s->bytes_remaining;
2231 
2232   nread = read (s->data, data, max_length);
2233 
2234   if (nread < 0)
2235     {
2236       DBG (2, "sane_read: error code %s\n", strerror (errno));
2237       if (errno == EAGAIN)
2238 	return SANE_STATUS_GOOD;
2239       else
2240 	{
2241 	  DBG (1, "sane_read: cancelling scan\n");
2242 	  do_cancel (s);
2243 	  return SANE_STATUS_IO_ERROR;
2244 	}
2245     }
2246 
2247   s->bytes_remaining -= nread;
2248 
2249   *length = nread;
2250   /* Check whether we are scanning with a depth of 16 bits/pixel and whether
2251      server and client have different byte order. If this is true, then it's
2252      necessary to check whether read returned an odd number. If an odd number
2253      has been returned, we must save the last byte.
2254   */
2255   if ((depth == 16) && (server_big_endian != client_big_endian))
2256     {
2257       DBG (1,"sane_read: client/server have different byte order; "
2258 	   "must swap\n");
2259       /* special case: 1 byte scanned and hang_over */
2260       if ((nread == 1) && (hang_over > -1))
2261 	{
2262 	  /* return the byte, we've currently scanned; hang_over becomes
2263 	     left_over */
2264 	  left_over = hang_over;
2265 	  hang_over = -1;
2266 	  return SANE_STATUS_GOOD;
2267 	}
2268       /* check whether an even or an odd number of bytes has been scanned */
2269       if ((nread % 2) == 0)
2270         is_even = 1;
2271       else
2272         is_even = 0;
2273       /* check, whether there's a hang over from a previous call;
2274 	 in this case we memcopy the data up one byte */
2275       if ((nread > 1) && (hang_over > -1))
2276 	{
2277 	  /* store last byte */
2278 	  temp_hang_over = *(data + nread - 1);
2279 	  memmove (data + 1, data, nread - 1);
2280 	  *data = (SANE_Byte) hang_over;
2281 	  /* what happens with the last byte depends on whether the number
2282 	     of bytes is even or odd */
2283 	  if (is_even == 1)
2284 	    {
2285 	      /* number of bytes is even; no new hang_over, exchange last
2286 		 byte with hang over; last byte becomes left_over */
2287 	      left_over = *(data + nread - 1);
2288 	      *(data + nread - 1) = temp_hang_over;
2289 	      hang_over = -1;
2290 	      start_cnt = 0;
2291 	      /* last byte already swapped */
2292 	      end_cnt = nread - 2;
2293 	    }
2294 	  else
2295 	    {
2296 	      /* number of bytes is odd; last byte becomes new hang_over */
2297 	      hang_over = temp_hang_over;
2298 	      left_over = -1;
2299 	      start_cnt = 0;
2300 	      end_cnt = nread - 1;
2301 	    }
2302 	}
2303       else if (nread == 1)
2304 	{
2305 	  /* if only one byte has been read, save it as hang_over and return
2306 	     length=0 */
2307 	  hang_over = (int) *data;
2308 	  *length = 0;
2309 	  return SANE_STATUS_GOOD;
2310 	}
2311       else
2312 	{
2313 	  /* no hang_over; test for even or odd byte number */
2314 	  if(is_even == 1)
2315 	    {
2316 	      start_cnt = 0;
2317 	      end_cnt = *length;
2318 	    }
2319 	  else
2320 	    {
2321 	      start_cnt = 0;
2322 	      hang_over = *(data + *length - 1);
2323 	      *length -= 1;
2324 	      end_cnt = *length;
2325 	    }
2326 	}
2327       /* swap the bytes */
2328       for (cnt = start_cnt; cnt < end_cnt - 1; cnt += 2)
2329 	{
2330 	  swap_buf = *(data + cnt);
2331 	  *(data + cnt) = *(data + cnt + 1);
2332 	  *(data + cnt + 1) = swap_buf;
2333 	}
2334     }
2335   DBG (3, "sane_read: %lu bytes read, %lu remaining\n", (u_long) nread,
2336        (u_long) s->bytes_remaining);
2337 
2338   return SANE_STATUS_GOOD;
2339 }
2340 
2341 void
2342 sane_cancel (SANE_Handle handle)
2343 {
2344   Net_Scanner *s = handle;
2345   SANE_Word ack;
2346 
2347   DBG (3, "sane_cancel: sending net_cancel\n");
2348 
2349   sanei_w_call (&s->hw->wire, SANE_NET_CANCEL,
2350 		(WireCodecFunc) sanei_w_word, &s->handle,
2351 		(WireCodecFunc) sanei_w_word, &ack);
2352   do_cancel (s);
2353   DBG (4, "sane_cancel: done\n");
2354 }
2355 
2356 SANE_Status
2357 sane_set_io_mode (SANE_Handle handle, SANE_Bool non_blocking)
2358 {
2359   Net_Scanner *s = handle;
2360 
2361   DBG (3, "sane_set_io_mode: non_blocking = %d\n", non_blocking);
2362   if (s->data < 0)
2363     {
2364       DBG (1, "sane_set_io_mode: pipe doesn't exist\n");
2365       return SANE_STATUS_INVAL;
2366     }
2367 
2368   if (fcntl (s->data, F_SETFL, non_blocking ? O_NONBLOCK : 0) < 0)
2369     {
2370       DBG (1, "sane_set_io_mode: fcntl failed (%s)\n", strerror (errno));
2371       return SANE_STATUS_IO_ERROR;
2372     }
2373 
2374   return SANE_STATUS_GOOD;
2375 }
2376 
2377 SANE_Status
2378 sane_get_select_fd (SANE_Handle handle, SANE_Int * fd)
2379 {
2380   Net_Scanner *s = handle;
2381 
2382   DBG (3, "sane_get_select_fd\n");
2383 
2384   if (s->data < 0)
2385     {
2386       DBG (1, "sane_get_select_fd: pipe doesn't exist\n");
2387       return SANE_STATUS_INVAL;
2388     }
2389 
2390   *fd = s->data;
2391   DBG (3, "sane_get_select_fd: done; *fd = %d\n", *fd);
2392   return SANE_STATUS_GOOD;
2393 }
2394