4 * User-defined destination (and option) support for CUPS.
6 * Copyright 2007-2014 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
15 * This file is subject to the Apple OS-Developed Software exception.
19 * Include necessary headers...
22 #include "cups-private.h"
27 #endif /* HAVE_NOTIFY_H */
31 #endif /* HAVE_POLL */
35 #endif /* HAVE_DNSSD */
38 # include <avahi-client/client.h>
39 # include <avahi-client/lookup.h>
40 # include <avahi-common/simple-watch.h>
41 # include <avahi-common/domain.h>
42 # include <avahi-common/error.h>
43 # include <avahi-common/malloc.h>
44 #define kDNSServiceMaxDomainName AVAHI_DOMAIN_NAME_MAX
45 #endif /* HAVE_AVAHI */
53 # include <SystemConfiguration/SystemConfiguration.h>
54 # define kCUPSPrintingPrefs CFSTR("org.cups.PrintingPrefs")
55 # define kDefaultPaperIDKey CFSTR("DefaultPaperID")
56 # define kLastUsedPrintersKey CFSTR("LastUsedPrinters")
57 # define kLocationNetworkKey CFSTR("Network")
58 # define kLocationPrinterIDKey CFSTR("PrinterID")
59 # define kUseLastPrinter CFSTR("UseLastPrinter")
60 #endif /* __APPLE__ */
67 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
68 typedef enum _cups_dnssd_state_e
/* Enumerated device state */
75 _CUPS_DNSSD_INCOMPATIBLE
,
77 } _cups_dnssd_state_t
;
79 typedef struct _cups_dnssd_data_s
/* Enumeration data */
82 DNSServiceRef main_ref
; /* Main service reference */
83 # else /* HAVE_AVAHI */
84 AvahiSimplePoll
*simple_poll
; /* Polling interface */
85 AvahiClient
*client
; /* Client information */
86 int got_data
; /* Did we get data? */
87 # endif /* HAVE_DNSSD */
88 cups_dest_cb_t cb
; /* Callback */
89 void *user_data
; /* User data pointer */
90 cups_ptype_t type
, /* Printer type filter */
91 mask
; /* Printer type mask */
92 cups_array_t
*devices
; /* Devices found so far */
95 typedef struct _cups_dnssd_device_s
/* Enumerated device */
97 _cups_dnssd_state_t state
; /* State of device listing */
99 DNSServiceRef ref
; /* Service reference for query */
100 # else /* HAVE_AVAHI */
101 AvahiRecordBrowser
*ref
; /* Browser for query */
102 # endif /* HAVE_DNSSD */
103 char *domain
, /* Domain name */
104 *fullName
, /* Full name */
105 *regtype
; /* Registration type */
106 cups_ptype_t type
; /* Device registration type */
107 cups_dest_t dest
; /* Destination record */
108 } _cups_dnssd_device_t
;
110 typedef struct _cups_dnssd_resolve_s
/* Data for resolving URI */
112 int *cancel
; /* Pointer to "cancel" variable */
113 struct timeval end_time
; /* Ending time */
114 } _cups_dnssd_resolve_t
;
115 #endif /* HAVE_DNSSD */
123 static CFArrayRef
appleCopyLocations(void);
124 static CFStringRef
appleCopyNetwork(void);
125 static char *appleGetPaperSize(char *name
, int namesize
);
126 static CFStringRef
appleGetPrinter(CFArrayRef locations
,
127 CFStringRef network
, CFIndex
*locindex
);
128 #endif /* __APPLE__ */
129 static cups_dest_t
*cups_add_dest(const char *name
, const char *instance
,
130 int *num_dests
, cups_dest_t
**dests
);
132 static int cups_block_cb(cups_dest_block_t block
, unsigned flags
,
134 #endif /* __BLOCKS__ */
135 static int cups_compare_dests(cups_dest_t
*a
, cups_dest_t
*b
);
136 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
138 static void cups_dnssd_browse_cb(DNSServiceRef sdRef
,
139 DNSServiceFlags flags
,
140 uint32_t interfaceIndex
,
141 DNSServiceErrorType errorCode
,
142 const char *serviceName
,
144 const char *replyDomain
,
146 # else /* HAVE_AVAHI */
147 static void cups_dnssd_browse_cb(AvahiServiceBrowser
*browser
,
148 AvahiIfIndex interface
,
149 AvahiProtocol protocol
,
150 AvahiBrowserEvent event
,
151 const char *serviceName
,
153 const char *replyDomain
,
154 AvahiLookupResultFlags flags
,
156 static void cups_dnssd_client_cb(AvahiClient
*client
,
157 AvahiClientState state
,
159 # endif /* HAVE_DNSSD */
160 static int cups_dnssd_compare_devices(_cups_dnssd_device_t
*a
,
161 _cups_dnssd_device_t
*b
);
162 static void cups_dnssd_free_device(_cups_dnssd_device_t
*device
,
163 _cups_dnssd_data_t
*data
);
164 static _cups_dnssd_device_t
*
165 cups_dnssd_get_device(_cups_dnssd_data_t
*data
,
166 const char *serviceName
,
168 const char *replyDomain
);
170 static void cups_dnssd_local_cb(DNSServiceRef sdRef
,
171 DNSServiceFlags flags
,
172 uint32_t interfaceIndex
,
173 DNSServiceErrorType errorCode
,
174 const char *serviceName
,
176 const char *replyDomain
,
178 static void cups_dnssd_query_cb(DNSServiceRef sdRef
,
179 DNSServiceFlags flags
,
180 uint32_t interfaceIndex
,
181 DNSServiceErrorType errorCode
,
182 const char *fullName
,
183 uint16_t rrtype
, uint16_t rrclass
,
184 uint16_t rdlen
, const void *rdata
,
185 uint32_t ttl
, void *context
);
186 # else /* HAVE_AVAHI */
187 static int cups_dnssd_poll_cb(struct pollfd
*pollfds
,
188 unsigned int num_pollfds
,
189 int timeout
, void *context
);
190 static void cups_dnssd_query_cb(AvahiRecordBrowser
*browser
,
191 AvahiIfIndex interface
,
192 AvahiProtocol protocol
,
193 AvahiBrowserEvent event
,
194 const char *name
, uint16_t rrclass
,
195 uint16_t rrtype
, const void *rdata
,
197 AvahiLookupResultFlags flags
,
199 # endif /* HAVE_DNSSD */
200 static const char *cups_dnssd_resolve(cups_dest_t
*dest
, const char *uri
,
201 int msec
, int *cancel
,
202 cups_dest_cb_t cb
, void *user_data
);
203 static int cups_dnssd_resolve_cb(void *context
);
204 static void cups_dnssd_unquote(char *dst
, const char *src
,
206 #endif /* HAVE_DNSSD || HAVE_AVAHI */
207 static int cups_find_dest(const char *name
, const char *instance
,
208 int num_dests
, cups_dest_t
*dests
, int prev
,
210 static char *cups_get_default(const char *filename
, char *namebuf
,
211 size_t namesize
, const char **instance
);
212 static int cups_get_dests(const char *filename
, const char *match_name
,
213 const char *match_inst
, int user_default_set
,
214 int num_dests
, cups_dest_t
**dests
);
215 static char *cups_make_string(ipp_attribute_t
*attr
, char *buffer
,
220 * 'cupsAddDest()' - Add a destination to the list of destinations.
222 * This function cannot be used to add a new class or printer queue,
223 * it only adds a new container of saved options for the named
224 * destination or instance.
226 * If the named destination already exists, the destination list is
227 * returned unchanged. Adding a new instance of a destination creates
228 * a copy of that destination's options.
230 * Use the @link cupsSaveDests@ function to save the updated list of
231 * destinations to the user's lpoptions file.
234 int /* O - New number of destinations */
235 cupsAddDest(const char *name
, /* I - Destination name */
236 const char *instance
, /* I - Instance name or @code NULL@ for none/primary */
237 int num_dests
, /* I - Number of destinations */
238 cups_dest_t
**dests
) /* IO - Destinations */
240 int i
; /* Looping var */
241 cups_dest_t
*dest
; /* Destination pointer */
242 cups_dest_t
*parent
= NULL
; /* Parent destination */
243 cups_option_t
*doption
, /* Current destination option */
244 *poption
; /* Current parent option */
250 if (!cupsGetDest(name
, instance
, num_dests
, *dests
))
252 if (instance
&& !cupsGetDest(name
, NULL
, num_dests
, *dests
))
255 if ((dest
= cups_add_dest(name
, instance
, &num_dests
, dests
)) == NULL
)
259 * Find the base dest again now the array has been realloc'd.
262 parent
= cupsGetDest(name
, NULL
, num_dests
, *dests
);
264 if (instance
&& parent
&& parent
->num_options
> 0)
267 * Copy options from parent...
270 dest
->options
= calloc(sizeof(cups_option_t
), (size_t)parent
->num_options
);
274 dest
->num_options
= parent
->num_options
;
276 for (i
= dest
->num_options
, doption
= dest
->options
,
277 poption
= parent
->options
;
279 i
--, doption
++, poption
++)
281 doption
->name
= _cupsStrRetain(poption
->name
);
282 doption
->value
= _cupsStrRetain(poption
->value
);
294 * '_cupsAppleCopyDefaultPaperID()' - Get the default paper ID.
297 CFStringRef
/* O - Default paper ID */
298 _cupsAppleCopyDefaultPaperID(void)
300 return (CFPreferencesCopyAppValue(kDefaultPaperIDKey
,
301 kCUPSPrintingPrefs
));
306 * '_cupsAppleCopyDefaultPrinter()' - Get the default printer at this location.
309 CFStringRef
/* O - Default printer name */
310 _cupsAppleCopyDefaultPrinter(void)
312 CFStringRef network
; /* Network location */
313 CFArrayRef locations
; /* Location array */
314 CFStringRef locprinter
; /* Current printer */
318 * Use location-based defaults only if "use last printer" is selected in the
319 * system preferences...
322 if (!_cupsAppleGetUseLastPrinter())
324 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Not using last printer as "
330 * Get the current location...
333 if ((network
= appleCopyNetwork()) == NULL
)
335 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Unable to get current "
341 * Lookup the network in the preferences...
344 if ((locations
= appleCopyLocations()) == NULL
)
347 * Missing or bad location array, so no location-based default...
350 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Missing or bad last used "
358 DEBUG_printf(("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.",
359 (int)CFArrayGetCount(locations
)));
361 if ((locprinter
= appleGetPrinter(locations
, network
, NULL
)) != NULL
)
362 CFRetain(locprinter
);
365 CFRelease(locations
);
372 * '_cupsAppleGetUseLastPrinter()' - Get whether to use the last used printer.
375 int /* O - 1 to use last printer, 0 otherwise */
376 _cupsAppleGetUseLastPrinter(void)
378 Boolean uselast
, /* Use last printer preference value */
379 uselast_set
; /* Valid is set? */
382 if (getenv("CUPS_DISABLE_APPLE_DEFAULT"))
385 uselast
= CFPreferencesGetAppBooleanValue(kUseLastPrinter
,
396 * '_cupsAppleSetDefaultPaperID()' - Set the default paper id.
400 _cupsAppleSetDefaultPaperID(
401 CFStringRef name
) /* I - New paper ID */
403 CFPreferencesSetAppValue(kDefaultPaperIDKey
, name
, kCUPSPrintingPrefs
);
404 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
405 notify_post("com.apple.printerPrefsChange");
410 * '_cupsAppleSetDefaultPrinter()' - Set the default printer for this location.
414 _cupsAppleSetDefaultPrinter(
415 CFStringRef name
) /* I - Default printer/class name */
417 CFStringRef network
; /* Current network */
418 CFArrayRef locations
; /* Old locations array */
419 CFIndex locindex
; /* Index in locations array */
420 CFStringRef locprinter
; /* Current printer */
421 CFMutableArrayRef newlocations
; /* New locations array */
422 CFMutableDictionaryRef newlocation
; /* New location */
426 * Get the current location...
429 if ((network
= appleCopyNetwork()) == NULL
)
431 DEBUG_puts("1_cupsAppleSetDefaultPrinter: Unable to get current network...");
436 * Lookup the network in the preferences...
439 if ((locations
= appleCopyLocations()) != NULL
)
440 locprinter
= appleGetPrinter(locations
, network
, &locindex
);
447 if (!locprinter
|| CFStringCompare(locprinter
, name
, 0) != kCFCompareEqualTo
)
450 * Need to change the locations array...
455 newlocations
= CFArrayCreateMutableCopy(kCFAllocatorDefault
, 0,
459 CFArrayRemoveValueAtIndex(newlocations
, locindex
);
462 newlocations
= CFArrayCreateMutable(kCFAllocatorDefault
, 0,
463 &kCFTypeArrayCallBacks
);
465 newlocation
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
466 &kCFTypeDictionaryKeyCallBacks
,
467 &kCFTypeDictionaryValueCallBacks
);
469 if (newlocation
&& newlocations
)
472 * Put the new location at the front of the array...
475 CFDictionaryAddValue(newlocation
, kLocationNetworkKey
, network
);
476 CFDictionaryAddValue(newlocation
, kLocationPrinterIDKey
, name
);
477 CFArrayInsertValueAtIndex(newlocations
, 0, newlocation
);
480 * Limit the number of locations to 10...
483 while (CFArrayGetCount(newlocations
) > 10)
484 CFArrayRemoveValueAtIndex(newlocations
, 10);
487 * Push the changes out...
490 CFPreferencesSetAppValue(kLastUsedPrintersKey
, newlocations
,
492 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
493 notify_post("com.apple.printerPrefsChange");
497 CFRelease(newlocations
);
500 CFRelease(newlocation
);
504 CFRelease(locations
);
511 * '_cupsAppleSetUseLastPrinter()' - Set whether to use the last used printer.
515 _cupsAppleSetUseLastPrinter(
516 int uselast
) /* O - 1 to use last printer, 0 otherwise */
518 CFPreferencesSetAppValue(kUseLastPrinter
,
519 uselast
? kCFBooleanTrue
: kCFBooleanFalse
,
521 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
522 notify_post("com.apple.printerPrefsChange");
524 #endif /* __APPLE__ */
528 * 'cupsConnectDest()' - Connect to the server for a destination.
530 * Connect to the destination, returning a new http_t connection object and
531 * optionally the resource path to use for the destination. These calls will
532 * block until a connection is made, the timeout expires, the integer pointed
533 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
534 * The caller is responsible for calling httpClose() on the returned object.
536 * @since CUPS 1.6/OS X 10.8@
539 http_t
* /* O - Connection to server or @code NULL@ */
541 cups_dest_t
*dest
, /* I - Destination */
542 unsigned flags
, /* I - Connection flags */
543 int msec
, /* I - Timeout in milliseconds */
544 int *cancel
, /* I - Pointer to "cancel" variable */
545 char *resource
, /* I - Resource buffer */
546 size_t resourcesize
, /* I - Size of resource buffer */
547 cups_dest_cb_t cb
, /* I - Callback function */
548 void *user_data
) /* I - User data pointer */
550 const char *uri
; /* Printer URI */
551 char scheme
[32], /* URI scheme */
552 userpass
[256], /* Username and password (unused) */
553 hostname
[256], /* Hostname */
554 tempresource
[1024]; /* Temporary resource buffer */
555 int port
; /* Port number */
556 char portstr
[16]; /* Port number string */
557 http_encryption_t encryption
; /* Encryption to use */
558 http_addrlist_t
*addrlist
; /* Address list for server */
559 http_t
*http
; /* Connection to server */
563 * Range check input...
571 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
575 if (!resource
|| resourcesize
< 1)
577 resource
= tempresource
;
578 resourcesize
= sizeof(tempresource
);
582 * Grab the printer URI...
585 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
,
586 dest
->options
)) == NULL
)
588 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(ENOENT
), 0);
591 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
597 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
598 if (strstr(uri
, "._tcp"))
600 if ((uri
= cups_dnssd_resolve(dest
, uri
, msec
, cancel
, cb
,
604 #endif /* HAVE_DNSSD || HAVE_AVAHI */
606 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
607 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
608 &port
, resource
, (int)resourcesize
) < HTTP_URI_STATUS_OK
)
610 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer URI."), 1);
613 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
620 * Lookup the address for the server...
624 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
,
627 snprintf(portstr
, sizeof(portstr
), "%d", port
);
629 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, portstr
)) == NULL
)
632 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
638 if (cancel
&& *cancel
)
640 httpAddrFreeList(addrlist
);
643 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CANCELED
,
650 * Create the HTTP object pointing to the server referenced by the URI...
653 if (!strcmp(scheme
, "ipps") || port
== 443)
654 encryption
= HTTP_ENCRYPTION_ALWAYS
;
656 encryption
= HTTP_ENCRYPTION_IF_REQUESTED
;
658 http
= httpConnect2(hostname
, port
, addrlist
, AF_UNSPEC
, encryption
, 1, 0,
662 * Connect if requested...
665 if (flags
& CUPS_DEST_FLAGS_UNCONNECTED
)
668 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
, dest
);
673 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
,
676 if (!httpReconnect2(http
, msec
, cancel
) && cb
)
678 if (cancel
&& *cancel
)
680 CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
, dest
);
682 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
686 (*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, dest
);
695 * 'cupsConnectDestBlock()' - Connect to the server for a destination.
697 * Connect to the destination, returning a new http_t connection object and
698 * optionally the resource path to use for the destination. These calls will
699 * block until a connection is made, the timeout expires, the integer pointed
700 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
701 * The caller is responsible for calling httpClose() on the returned object.
703 * @since CUPS 1.6/OS X 10.8@
706 http_t
* /* O - Connection to server or @code NULL@ */
707 cupsConnectDestBlock(
708 cups_dest_t
*dest
, /* I - Destination */
709 unsigned flags
, /* I - Connection flags */
710 int msec
, /* I - Timeout in milliseconds */
711 int *cancel
, /* I - Pointer to "cancel" variable */
712 char *resource
, /* I - Resource buffer */
713 size_t resourcesize
, /* I - Size of resource buffer */
714 cups_dest_block_t block
) /* I - Callback block */
716 return (cupsConnectDest(dest
, flags
, msec
, cancel
, resource
, resourcesize
,
717 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
719 #endif /* __BLOCKS__ */
723 * 'cupsCopyDest()' - Copy a destination.
725 * Make a copy of the destination to an array of destinations (or just a single
726 * copy) - for use with the cupsEnumDests* functions. The caller is responsible
727 * for calling cupsFreeDests() on the returned object(s).
729 * @since CUPS 1.6/OS X 10.8@
733 cupsCopyDest(cups_dest_t
*dest
,
737 int i
; /* Looping var */
738 cups_dest_t
*new_dest
; /* New destination pointer */
739 cups_option_t
*new_option
, /* Current destination option */
740 *option
; /* Current parent option */
744 * Range check input...
747 if (!dest
|| num_dests
< 0 || !dests
)
751 * See if the destination already exists...
754 if ((new_dest
= cupsGetDest(dest
->name
, dest
->instance
, num_dests
,
758 * Protect against copying destination to itself...
761 if (new_dest
== dest
)
765 * Otherwise, free the options...
768 cupsFreeOptions(new_dest
->num_options
, new_dest
->options
);
770 new_dest
->num_options
= 0;
771 new_dest
->options
= NULL
;
774 new_dest
= cups_add_dest(dest
->name
, dest
->instance
, &num_dests
, dests
);
778 if ((new_dest
->options
= calloc(sizeof(cups_option_t
), (size_t)dest
->num_options
)) == NULL
)
779 return (cupsRemoveDest(dest
->name
, dest
->instance
, num_dests
, dests
));
781 new_dest
->num_options
= dest
->num_options
;
783 for (i
= dest
->num_options
, option
= dest
->options
,
784 new_option
= new_dest
->options
;
786 i
--, option
++, new_option
++)
788 new_option
->name
= _cupsStrRetain(option
->name
);
789 new_option
->value
= _cupsStrRetain(option
->value
);
798 * 'cupsEnumDests()' - Enumerate available destinations with a callback function.
800 * Destinations are enumerated from one or more sources. The callback function
801 * receives the @code user_data@ pointer, destination name, instance, number of
802 * options, and options which can be used as input to the @link cupsAddDest@
803 * function. The function must return 1 to continue enumeration or 0 to stop.
805 * Enumeration happens on the current thread and does not return until all
806 * destinations have been enumerated or the callback function returns 0.
808 * @since CUPS 1.6/OS X 10.8@
811 int /* O - 1 on success, 0 on failure */
813 unsigned flags
, /* I - Enumeration flags */
814 int msec
, /* I - Timeout in milliseconds,
815 * -1 for indefinite */
816 int *cancel
, /* I - Pointer to "cancel" variable */
817 cups_ptype_t type
, /* I - Printer type bits */
818 cups_ptype_t mask
, /* I - Mask for printer type bits */
819 cups_dest_cb_t cb
, /* I - Callback function */
820 void *user_data
) /* I - User data */
822 int i
, /* Looping var */
823 num_dests
; /* Number of destinations */
824 cups_dest_t
*dests
= NULL
, /* Destinations */
825 *dest
; /* Current destination */
826 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
827 int count
, /* Number of queries started */
828 remaining
; /* Remainder of timeout */
829 _cups_dnssd_data_t data
; /* Data for callback */
830 _cups_dnssd_device_t
*device
; /* Current device */
832 int nfds
, /* Number of files responded */
833 main_fd
; /* File descriptor for lookups */
834 DNSServiceRef ipp_ref
, /* IPP browser */
835 local_ipp_ref
; /* Local IPP browser */
837 DNSServiceRef ipps_ref
, /* IPPS browser */
838 local_ipps_ref
; /* Local IPPS browser */
839 # endif /* HAVE_SSL */
841 struct pollfd pfd
; /* Polling data */
843 fd_set input
; /* Input set for select() */
844 struct timeval timeout
; /* Timeout for select() */
845 # endif /* HAVE_POLL */
846 # else /* HAVE_AVAHI */
847 int error
; /* Error value */
848 AvahiServiceBrowser
*ipp_ref
; /* IPP browser */
850 AvahiServiceBrowser
*ipps_ref
; /* IPPS browser */
851 # endif /* HAVE_SSL */
852 # endif /* HAVE_DNSSD */
853 #endif /* HAVE_DNSSD || HAVE_AVAHI */
856 * Range check input...
865 * Get the list of local printers and pass them to the callback function...
868 num_dests
= _cupsGetDests(CUPS_HTTP_DEFAULT
, IPP_OP_CUPS_GET_PRINTERS
, NULL
,
871 for (i
= num_dests
, dest
= dests
;
872 i
> 0 && (!cancel
|| !*cancel
);
874 if (!(*cb
)(user_data
, i
> 1 ? CUPS_DEST_FLAGS_MORE
: CUPS_DEST_FLAGS_NONE
,
878 cupsFreeDests(num_dests
, dests
);
880 if (i
> 0 || msec
== 0)
883 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
885 * Get Bonjour-shared printers...
890 data
.devices
= cupsArrayNew3((cups_array_func_t
)cups_dnssd_compare_devices
,
892 (cups_afree_func_t
)cups_dnssd_free_device
);
895 if (DNSServiceCreateConnection(&data
.main_ref
) != kDNSServiceErr_NoError
)
898 main_fd
= DNSServiceRefSockFD(data
.main_ref
);
900 ipp_ref
= data
.main_ref
;
901 DNSServiceBrowse(&ipp_ref
, kDNSServiceFlagsShareConnection
, 0,
903 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
905 local_ipp_ref
= data
.main_ref
;
906 DNSServiceBrowse(&local_ipp_ref
, kDNSServiceFlagsShareConnection
,
907 kDNSServiceInterfaceIndexLocalOnly
,
909 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
912 ipps_ref
= data
.main_ref
;
913 DNSServiceBrowse(&ipps_ref
, kDNSServiceFlagsShareConnection
, 0,
915 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
917 local_ipps_ref
= data
.main_ref
;
918 DNSServiceBrowse(&local_ipps_ref
, kDNSServiceFlagsShareConnection
,
919 kDNSServiceInterfaceIndexLocalOnly
,
921 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
922 # endif /* HAVE_SSL */
924 # else /* HAVE_AVAHI */
925 if ((data
.simple_poll
= avahi_simple_poll_new()) == NULL
)
927 DEBUG_puts("cupsEnumDests: Unable to create Avahi simple poll object.");
931 avahi_simple_poll_set_func(data
.simple_poll
, cups_dnssd_poll_cb
, &data
);
933 data
.client
= avahi_client_new(avahi_simple_poll_get(data
.simple_poll
),
934 0, cups_dnssd_client_cb
, &data
,
938 DEBUG_puts("cupsEnumDests: Unable to create Avahi client.");
939 avahi_simple_poll_free(data
.simple_poll
);
943 ipp_ref
= avahi_service_browser_new(data
.client
, AVAHI_IF_UNSPEC
,
944 AVAHI_PROTO_UNSPEC
, "_ipp._tcp", NULL
,
945 0, cups_dnssd_browse_cb
, &data
);
947 ipps_ref
= avahi_service_browser_new(data
.client
, AVAHI_IF_UNSPEC
,
948 AVAHI_PROTO_UNSPEC
, "_ipps._tcp", NULL
,
949 0, cups_dnssd_browse_cb
, &data
);
950 # endif /* HAVE_SSL */
951 # endif /* HAVE_DNSSD */
958 while (remaining
> 0 && (!cancel
|| !*cancel
))
969 nfds
= poll(&pfd
, 1, remaining
> 250 ? 250 : remaining
);
973 FD_SET(main_fd
, &input
);
976 timeout
.tv_usec
= remaining
> 250 ? 250000 : remaining
* 1000;
978 nfds
= select(main_fd
+ 1, &input
, NULL
, NULL
, &timeout
);
979 # endif /* HAVE_POLL */
982 DNSServiceProcessResult(data
.main_ref
);
986 # else /* HAVE_AVAHI */
989 if ((error
= avahi_simple_poll_iterate(data
.simple_poll
, 250)) > 0)
992 * We've been told to exit the loop. Perhaps the connection to
1001 # endif /* HAVE_DNSSD */
1003 for (device
= (_cups_dnssd_device_t
*)cupsArrayFirst(data
.devices
),
1006 device
= (_cups_dnssd_device_t
*)cupsArrayNext(data
.devices
))
1011 if (!device
->ref
&& device
->state
== _CUPS_DNSSD_NEW
)
1013 DEBUG_printf(("1cupsEnumDests: Querying '%s'.", device
->fullName
));
1016 device
->ref
= data
.main_ref
;
1018 if (DNSServiceQueryRecord(&(device
->ref
),
1019 kDNSServiceFlagsShareConnection
,
1020 0, device
->fullName
,
1021 kDNSServiceType_TXT
,
1022 kDNSServiceClass_IN
,
1023 (DNSServiceQueryRecordReply
)cups_dnssd_query_cb
,
1024 &data
) == kDNSServiceErr_NoError
)
1031 device
->state
= _CUPS_DNSSD_ERROR
;
1033 DEBUG_puts("1cupsEnumDests: Query failed.");
1036 # else /* HAVE_AVAHI */
1037 if ((device
->ref
= avahi_record_browser_new(data
.client
,
1044 cups_dnssd_query_cb
,
1051 device
->state
= _CUPS_DNSSD_ERROR
;
1053 DEBUG_printf(("1cupsEnumDests: Query failed: %s",
1054 avahi_strerror(avahi_client_errno(data
.client
))));
1056 # endif /* HAVE_DNSSD */
1058 else if (device
->ref
&& device
->state
== _CUPS_DNSSD_PENDING
)
1060 if ((device
->type
& mask
) == type
)
1062 if (!(*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, &device
->dest
))
1069 device
->state
= _CUPS_DNSSD_ACTIVE
;
1074 cupsArrayDelete(data
.devices
);
1077 DNSServiceRefDeallocate(ipp_ref
);
1078 DNSServiceRefDeallocate(local_ipp_ref
);
1081 DNSServiceRefDeallocate(ipp_ref
);
1082 DNSServiceRefDeallocate(local_ipp_ref
);
1083 # endif /* HAVE_SSL */
1085 DNSServiceRefDeallocate(data
.main_ref
);
1087 # else /* HAVE_AVAHI */
1088 avahi_service_browser_free(ipp_ref
);
1090 avahi_service_browser_free(ipps_ref
);
1091 # endif /* HAVE_SSL */
1093 avahi_client_free(data
.client
);
1094 avahi_simple_poll_free(data
.simple_poll
);
1095 # endif /* HAVE_DNSSD */
1096 #endif /* HAVE_DNSSD || HAVE_DNSSD */
1104 * 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
1106 * Destinations are enumerated from one or more sources. The block receives the
1107 * destination name, instance, number of options, and options which can be used
1108 * as input to the @link cupsAddDest@ function. The block must return 1 to
1109 * continue enumeration or 0 to stop.
1111 * Enumeration happens on the current thread and does not return until all
1112 * destinations have been enumerated or the block returns 0.
1114 * @since CUPS 1.6/OS X 10.8@
1117 int /* O - 1 on success, 0 on failure */
1119 unsigned flags
, /* I - Enumeration flags */
1120 int timeout
, /* I - Timeout in milliseconds, 0 for indefinite */
1121 int *cancel
, /* I - Pointer to "cancel" variable */
1122 cups_ptype_t type
, /* I - Printer type bits */
1123 cups_ptype_t mask
, /* I - Mask for printer type bits */
1124 cups_dest_block_t block
) /* I - Block */
1126 return (cupsEnumDests(flags
, timeout
, cancel
, type
, mask
,
1127 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
1129 # endif /* __BLOCKS__ */
1133 * 'cupsFreeDests()' - Free the memory used by the list of destinations.
1137 cupsFreeDests(int num_dests
, /* I - Number of destinations */
1138 cups_dest_t
*dests
) /* I - Destinations */
1140 int i
; /* Looping var */
1141 cups_dest_t
*dest
; /* Current destination */
1144 if (num_dests
== 0 || dests
== NULL
)
1147 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1149 _cupsStrFree(dest
->name
);
1150 _cupsStrFree(dest
->instance
);
1152 cupsFreeOptions(dest
->num_options
, dest
->options
);
1160 * 'cupsGetDest()' - Get the named destination from the list.
1162 * Use the @link cupsGetDests@ or @link cupsGetDests2@ functions to get a
1163 * list of supported destinations for the current user.
1166 cups_dest_t
* /* O - Destination pointer or @code NULL@ */
1167 cupsGetDest(const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1168 const char *instance
, /* I - Instance name or @code NULL@ */
1169 int num_dests
, /* I - Number of destinations */
1170 cups_dest_t
*dests
) /* I - Destinations */
1172 int diff
, /* Result of comparison */
1173 match
; /* Matching index */
1176 if (num_dests
<= 0 || !dests
)
1182 * NULL name for default printer.
1185 while (num_dests
> 0)
1187 if (dests
->is_default
)
1197 * Lookup name and optionally the instance...
1200 match
= cups_find_dest(name
, instance
, num_dests
, dests
, -1, &diff
);
1203 return (dests
+ match
);
1211 * '_cupsGetDestResource()' - Get the resource path and URI for a destination.
1214 const char * /* O - Printer URI */
1215 _cupsGetDestResource(
1216 cups_dest_t
*dest
, /* I - Destination */
1217 char *resource
, /* I - Resource buffer */
1218 size_t resourcesize
) /* I - Size of resource buffer */
1220 const char *uri
; /* Printer URI */
1221 char scheme
[32], /* URI scheme */
1222 userpass
[256], /* Username and password (unused) */
1223 hostname
[256]; /* Hostname */
1224 int port
; /* Port number */
1228 * Range check input...
1231 if (!dest
|| !resource
|| resourcesize
< 1)
1236 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
1241 * Grab the printer URI...
1244 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
,
1245 dest
->options
)) == NULL
)
1250 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(ENOENT
), 0);
1256 if (strstr(uri
, "._tcp"))
1258 if ((uri
= cups_dnssd_resolve(dest
, uri
, 5000, NULL
, NULL
, NULL
)) == NULL
)
1261 #endif /* HAVE_DNSSD */
1263 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
1264 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
1265 &port
, resource
, (int)resourcesize
) < HTTP_URI_STATUS_OK
)
1267 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer URI."), 1);
1277 * '_cupsGetDests()' - Get destinations from a server.
1279 * "op" is IPP_OP_CUPS_GET_PRINTERS to get a full list, IPP_OP_CUPS_GET_DEFAULT
1280 * to get the system-wide default printer, or IPP_OP_GET_PRINTER_ATTRIBUTES for
1283 * "name" is the name of an existing printer and is only used when "op" is
1284 * IPP_OP_GET_PRINTER_ATTRIBUTES.
1286 * "dest" is initialized to point to the array of destinations.
1288 * 0 is returned if there are no printers, no default printer, or the named
1289 * printer does not exist, respectively.
1291 * Free the memory used by the destination array using the @link cupsFreeDests@
1294 * Note: On OS X this function also gets the default paper from the system
1295 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1296 * options array for each destination that supports it.
1299 int /* O - Number of destinations */
1300 _cupsGetDests(http_t
*http
, /* I - Connection to server or
1301 * @code CUPS_HTTP_DEFAULT@ */
1302 ipp_op_t op
, /* I - IPP operation */
1303 const char *name
, /* I - Name of destination */
1304 cups_dest_t
**dests
, /* IO - Destinations */
1305 cups_ptype_t type
, /* I - Printer type bits */
1306 cups_ptype_t mask
) /* I - Printer type mask */
1308 int num_dests
= 0; /* Number of destinations */
1309 cups_dest_t
*dest
; /* Current destination */
1310 ipp_t
*request
, /* IPP Request */
1311 *response
; /* IPP Response */
1312 ipp_attribute_t
*attr
; /* Current attribute */
1313 const char *printer_name
; /* printer-name attribute */
1314 char uri
[1024]; /* printer-uri value */
1315 int num_options
; /* Number of options */
1316 cups_option_t
*options
; /* Options */
1318 char media_default
[41]; /* Default paper size */
1319 #endif /* __APPLE__ */
1320 char optname
[1024], /* Option name */
1321 value
[2048], /* Option value */
1322 *ptr
; /* Pointer into name/value */
1323 static const char * const pattrs
[] = /* Attributes we're interested in */
1325 "auth-info-required",
1327 "job-sheets-default",
1328 "marker-change-time",
1330 "marker-high-levels",
1332 "marker-low-levels",
1338 #endif /* __APPLE__ */
1342 "printer-is-accepting-jobs",
1343 "printer-is-shared",
1345 "printer-make-and-model",
1346 "printer-mandatory-job-attributes",
1349 "printer-state-change-time",
1350 "printer-state-reasons",
1352 "printer-uri-supported"
1358 * Get the default paper size...
1361 appleGetPaperSize(media_default
, sizeof(media_default
));
1362 #endif /* __APPLE__ */
1365 * Build a IPP_OP_CUPS_GET_PRINTERS or IPP_OP_GET_PRINTER_ATTRIBUTES request, which
1366 * require the following attributes:
1368 * attributes-charset
1369 * attributes-natural-language
1370 * requesting-user-name
1371 * printer-uri [for IPP_OP_GET_PRINTER_ATTRIBUTES]
1374 request
= ippNewRequest(op
);
1376 ippAddStrings(request
, IPP_TAG_OPERATION
, IPP_TAG_KEYWORD
,
1377 "requested-attributes", sizeof(pattrs
) / sizeof(pattrs
[0]),
1380 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
,
1381 "requesting-user-name", NULL
, cupsUser());
1383 if (name
&& op
!= IPP_OP_CUPS_GET_DEFAULT
)
1385 httpAssembleURIf(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
), "ipp", NULL
,
1386 "localhost", ippPort(), "/printers/%s", name
);
1387 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
,
1392 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type", (int)type
);
1393 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type-mask", (int)mask
);
1397 * Do the request and get back a response...
1400 if ((response
= cupsDoRequest(http
, request
, "/")) != NULL
)
1402 for (attr
= response
->attrs
; attr
!= NULL
; attr
= attr
->next
)
1405 * Skip leading attributes until we hit a printer...
1408 while (attr
!= NULL
&& attr
->group_tag
!= IPP_TAG_PRINTER
)
1415 * Pull the needed attributes from this printer...
1418 printer_name
= NULL
;
1422 for (; attr
&& attr
->group_tag
== IPP_TAG_PRINTER
; attr
= attr
->next
)
1424 if (attr
->value_tag
!= IPP_TAG_INTEGER
&&
1425 attr
->value_tag
!= IPP_TAG_ENUM
&&
1426 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
1427 attr
->value_tag
!= IPP_TAG_TEXT
&&
1428 attr
->value_tag
!= IPP_TAG_TEXTLANG
&&
1429 attr
->value_tag
!= IPP_TAG_NAME
&&
1430 attr
->value_tag
!= IPP_TAG_NAMELANG
&&
1431 attr
->value_tag
!= IPP_TAG_KEYWORD
&&
1432 attr
->value_tag
!= IPP_TAG_RANGE
&&
1433 attr
->value_tag
!= IPP_TAG_URI
)
1436 if (!strcmp(attr
->name
, "auth-info-required") ||
1437 !strcmp(attr
->name
, "device-uri") ||
1438 !strcmp(attr
->name
, "marker-change-time") ||
1439 !strcmp(attr
->name
, "marker-colors") ||
1440 !strcmp(attr
->name
, "marker-high-levels") ||
1441 !strcmp(attr
->name
, "marker-levels") ||
1442 !strcmp(attr
->name
, "marker-low-levels") ||
1443 !strcmp(attr
->name
, "marker-message") ||
1444 !strcmp(attr
->name
, "marker-names") ||
1445 !strcmp(attr
->name
, "marker-types") ||
1446 !strcmp(attr
->name
, "printer-commands") ||
1447 !strcmp(attr
->name
, "printer-info") ||
1448 !strcmp(attr
->name
, "printer-is-shared") ||
1449 !strcmp(attr
->name
, "printer-make-and-model") ||
1450 !strcmp(attr
->name
, "printer-mandatory-job-attributes") ||
1451 !strcmp(attr
->name
, "printer-state") ||
1452 !strcmp(attr
->name
, "printer-state-change-time") ||
1453 !strcmp(attr
->name
, "printer-type") ||
1454 !strcmp(attr
->name
, "printer-is-accepting-jobs") ||
1455 !strcmp(attr
->name
, "printer-location") ||
1456 !strcmp(attr
->name
, "printer-state-reasons") ||
1457 !strcmp(attr
->name
, "printer-uri-supported"))
1460 * Add a printer description attribute...
1463 num_options
= cupsAddOption(attr
->name
,
1464 cups_make_string(attr
, value
,
1466 num_options
, &options
);
1469 else if (!strcmp(attr
->name
, "media-supported"))
1472 * See if we can set a default media size...
1475 int i
; /* Looping var */
1477 for (i
= 0; i
< attr
->num_values
; i
++)
1478 if (!_cups_strcasecmp(media_default
, attr
->values
[i
].string
.text
))
1480 num_options
= cupsAddOption("media", media_default
, num_options
,
1485 #endif /* __APPLE__ */
1486 else if (!strcmp(attr
->name
, "printer-name") &&
1487 attr
->value_tag
== IPP_TAG_NAME
)
1488 printer_name
= attr
->values
[0].string
.text
;
1489 else if (strncmp(attr
->name
, "notify-", 7) &&
1490 (attr
->value_tag
== IPP_TAG_BOOLEAN
||
1491 attr
->value_tag
== IPP_TAG_ENUM
||
1492 attr
->value_tag
== IPP_TAG_INTEGER
||
1493 attr
->value_tag
== IPP_TAG_KEYWORD
||
1494 attr
->value_tag
== IPP_TAG_NAME
||
1495 attr
->value_tag
== IPP_TAG_RANGE
) &&
1496 (ptr
= strstr(attr
->name
, "-default")) != NULL
)
1499 * Add a default option...
1502 strlcpy(optname
, attr
->name
, sizeof(optname
));
1503 optname
[ptr
- attr
->name
] = '\0';
1505 if (_cups_strcasecmp(optname
, "media") ||
1506 !cupsGetOption("media", num_options
, options
))
1507 num_options
= cupsAddOption(optname
,
1508 cups_make_string(attr
, value
,
1510 num_options
, &options
);
1515 * See if we have everything needed...
1520 cupsFreeOptions(num_options
, options
);
1528 if ((dest
= cups_add_dest(printer_name
, NULL
, &num_dests
, dests
)) != NULL
)
1530 dest
->num_options
= num_options
;
1531 dest
->options
= options
;
1534 cupsFreeOptions(num_options
, options
);
1540 ippDelete(response
);
1544 * Return the count...
1552 * 'cupsGetDests()' - Get the list of destinations from the default server.
1554 * Starting with CUPS 1.2, the returned list of destinations include the
1555 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1556 * printer-make-and-model, printer-state, printer-state-change-time,
1557 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1558 * adds the marker-change-time, marker-colors, marker-high-levels,
1559 * marker-levels, marker-low-levels, marker-message, marker-names,
1560 * marker-types, and printer-commands attributes as well.
1562 * Use the @link cupsFreeDests@ function to free the destination list and
1563 * the @link cupsGetDest@ function to find a particular destination.
1566 int /* O - Number of destinations */
1567 cupsGetDests(cups_dest_t
**dests
) /* O - Destinations */
1569 return (cupsGetDests2(CUPS_HTTP_DEFAULT
, dests
));
1574 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1576 * Starting with CUPS 1.2, the returned list of destinations include the
1577 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1578 * printer-make-and-model, printer-state, printer-state-change-time,
1579 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1580 * adds the marker-change-time, marker-colors, marker-high-levels,
1581 * marker-levels, marker-low-levels, marker-message, marker-names,
1582 * marker-types, and printer-commands attributes as well.
1584 * Use the @link cupsFreeDests@ function to free the destination list and
1585 * the @link cupsGetDest@ function to find a particular destination.
1587 * @since CUPS 1.1.21/OS X 10.4@
1590 int /* O - Number of destinations */
1591 cupsGetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1592 cups_dest_t
**dests
) /* O - Destinations */
1594 int num_dests
; /* Number of destinations */
1595 cups_dest_t
*dest
; /* Destination pointer */
1596 const char *home
; /* HOME environment variable */
1597 char filename
[1024]; /* Local ~/.cups/lpoptions file */
1598 const char *defprinter
; /* Default printer */
1599 char name
[1024], /* Copy of printer name */
1600 *instance
, /* Pointer to instance name */
1601 *user_default
; /* User default printer */
1602 int num_reals
; /* Number of real queues */
1603 cups_dest_t
*reals
; /* Real queues */
1604 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1608 * Range check the input...
1613 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad NULL dests pointer"), 1);
1618 * Grab the printers and classes...
1621 *dests
= (cups_dest_t
*)0;
1622 num_dests
= _cupsGetDests(http
, IPP_OP_CUPS_GET_PRINTERS
, NULL
, dests
, 0, 0);
1624 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE
)
1626 cupsFreeDests(num_dests
, *dests
);
1627 *dests
= (cups_dest_t
*)0;
1632 * Make a copy of the "real" queues for a later sanity check...
1637 num_reals
= num_dests
;
1638 reals
= calloc((size_t)num_reals
, sizeof(cups_dest_t
));
1641 memcpy(reals
, *dests
, (size_t)num_reals
* sizeof(cups_dest_t
));
1652 * Grab the default destination...
1655 if ((user_default
= _cupsUserDefault(name
, sizeof(name
))) != NULL
)
1657 else if ((defprinter
= cupsGetDefault2(http
)) != NULL
)
1659 strlcpy(name
, defprinter
, sizeof(name
));
1666 * Separate printer and instance name...
1669 if ((instance
= strchr(name
, '/')) != NULL
)
1673 * Lookup the printer and instance and make it the default...
1676 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) != NULL
)
1677 dest
->is_default
= 1;
1683 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
1686 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1687 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1690 if ((home
= getenv("HOME")) != NULL
)
1692 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1694 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1699 * Validate the current default destination - this prevents old
1700 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
1701 * pointing to a non-existent printer or class...
1707 * See if we have a default printer...
1710 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, *dests
)) != NULL
)
1713 * Have a default; see if it is real...
1716 if (!cupsGetDest(dest
->name
, NULL
, num_reals
, reals
))
1719 * Remove the non-real printer from the list, since we don't want jobs
1720 * going to an unexpected printer... (<rdar://problem/14216472>)
1723 num_dests
= cupsRemoveDest(dest
->name
, dest
->instance
, num_dests
,
1736 * Return the number of destinations...
1740 _cupsSetError(IPP_STATUS_OK
, NULL
, 0);
1747 * 'cupsGetNamedDest()' - Get options for the named destination.
1749 * This function is optimized for retrieving a single destination and should
1750 * be used instead of @link cupsGetDests@ and @link cupsGetDest@ when you either
1751 * know the name of the destination or want to print to the default destination.
1752 * If @code NULL@ is returned, the destination does not exist or there is no
1753 * default destination.
1755 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
1756 * server will be used.
1758 * If "name" is @code NULL@, the default printer for the current user will be
1761 * The returned destination must be freed using @link cupsFreeDests@ with a
1762 * "num_dests" value of 1.
1764 * @since CUPS 1.4/OS X 10.6@
1767 cups_dest_t
* /* O - Destination or @code NULL@ */
1768 cupsGetNamedDest(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1769 const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1770 const char *instance
) /* I - Instance name or @code NULL@ */
1772 cups_dest_t
*dest
; /* Destination */
1773 char filename
[1024], /* Path to lpoptions */
1774 defname
[256]; /* Default printer name */
1775 const char *home
= getenv("HOME"); /* Home directory */
1776 int set_as_default
= 0; /* Set returned destination as default */
1777 ipp_op_t op
= IPP_OP_GET_PRINTER_ATTRIBUTES
;
1778 /* IPP operation to get server ops */
1779 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1783 * If "name" is NULL, find the default destination...
1789 name
= _cupsUserDefault(defname
, sizeof(defname
));
1793 char *ptr
; /* Temporary pointer... */
1795 if ((ptr
= strchr(defname
, '/')) != NULL
)
1806 * No default in the environment, try the user's lpoptions files...
1809 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1811 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1817 * Still not there? Try the system lpoptions file...
1820 snprintf(filename
, sizeof(filename
), "%s/lpoptions",
1821 cg
->cups_serverroot
);
1822 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1828 * No locally-set default destination, ask the server...
1831 op
= IPP_OP_CUPS_GET_DEFAULT
;
1836 * Get the printer's attributes...
1839 if (!_cupsGetDests(http
, op
, name
, &dest
, 0, 0))
1843 dest
->instance
= _cupsStrAlloc(instance
);
1846 dest
->is_default
= 1;
1849 * Then add local options...
1852 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1853 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
1857 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1859 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
1863 * Return the result...
1871 * 'cupsRemoveDest()' - Remove a destination from the destination list.
1873 * Removing a destination/instance does not delete the class or printer
1874 * queue, merely the lpoptions for that destination/instance. Use the
1875 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
1876 * options for the user.
1878 * @since CUPS 1.3/OS X 10.5@
1881 int /* O - New number of destinations */
1882 cupsRemoveDest(const char *name
, /* I - Destination name */
1883 const char *instance
, /* I - Instance name or @code NULL@ */
1884 int num_dests
, /* I - Number of destinations */
1885 cups_dest_t
**dests
) /* IO - Destinations */
1887 int i
; /* Index into destinations */
1888 cups_dest_t
*dest
; /* Pointer to destination */
1892 * Find the destination...
1895 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
1902 _cupsStrFree(dest
->name
);
1903 _cupsStrFree(dest
->instance
);
1904 cupsFreeOptions(dest
->num_options
, dest
->options
);
1907 * Remove the destination from the array...
1912 i
= (int)(dest
- *dests
);
1915 memmove(dest
, dest
+ 1, (size_t)(num_dests
- i
) * sizeof(cups_dest_t
));
1922 * 'cupsSetDefaultDest()' - Set the default destination.
1924 * @since CUPS 1.3/OS X 10.5@
1929 const char *name
, /* I - Destination name */
1930 const char *instance
, /* I - Instance name or @code NULL@ */
1931 int num_dests
, /* I - Number of destinations */
1932 cups_dest_t
*dests
) /* I - Destinations */
1934 int i
; /* Looping var */
1935 cups_dest_t
*dest
; /* Current destination */
1939 * Range check input...
1942 if (!name
|| num_dests
<= 0 || !dests
)
1946 * Loop through the array and set the "is_default" flag for the matching
1950 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1951 dest
->is_default
= !_cups_strcasecmp(name
, dest
->name
) &&
1952 ((!instance
&& !dest
->instance
) ||
1953 (instance
&& dest
->instance
&&
1954 !_cups_strcasecmp(instance
, dest
->instance
)));
1959 * 'cupsSetDests()' - Save the list of destinations for the default server.
1961 * This function saves the destinations to /etc/cups/lpoptions when run
1962 * as root and ~/.cups/lpoptions when run as a normal user.
1966 cupsSetDests(int num_dests
, /* I - Number of destinations */
1967 cups_dest_t
*dests
) /* I - Destinations */
1969 cupsSetDests2(CUPS_HTTP_DEFAULT
, num_dests
, dests
);
1974 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
1976 * This function saves the destinations to /etc/cups/lpoptions when run
1977 * as root and ~/.cups/lpoptions when run as a normal user.
1979 * @since CUPS 1.1.21/OS X 10.4@
1982 int /* O - 0 on success, -1 on error */
1983 cupsSetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1984 int num_dests
, /* I - Number of destinations */
1985 cups_dest_t
*dests
) /* I - Destinations */
1987 int i
, j
; /* Looping vars */
1988 int wrote
; /* Wrote definition? */
1989 cups_dest_t
*dest
; /* Current destination */
1990 cups_option_t
*option
; /* Current option */
1991 _ipp_option_t
*match
; /* Matching attribute for option */
1992 FILE *fp
; /* File pointer */
1994 const char *home
; /* HOME environment variable */
1996 char filename
[1024]; /* lpoptions file */
1997 int num_temps
; /* Number of temporary destinations */
1998 cups_dest_t
*temps
= NULL
, /* Temporary destinations */
1999 *temp
; /* Current temporary dest */
2000 const char *val
; /* Value of temporary option */
2001 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
2005 * Range check the input...
2008 if (!num_dests
|| !dests
)
2012 * Get the server destinations...
2015 num_temps
= _cupsGetDests(http
, IPP_OP_CUPS_GET_PRINTERS
, NULL
, &temps
, 0, 0);
2017 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE
)
2019 cupsFreeDests(num_temps
, temps
);
2024 * Figure out which file to write to...
2027 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
2033 * Merge in server defaults...
2036 num_temps
= cups_get_dests(filename
, NULL
, NULL
, 0, num_temps
, &temps
);
2039 * Point to user defaults...
2042 if ((home
= getenv("HOME")) != NULL
)
2045 * Create ~/.cups subdirectory...
2048 snprintf(filename
, sizeof(filename
), "%s/.cups", home
);
2049 if (access(filename
, 0))
2050 mkdir(filename
, 0700);
2052 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
2058 * Try to open the file...
2061 if ((fp
= fopen(filename
, "w")) == NULL
)
2063 cupsFreeDests(num_temps
, temps
);
2069 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2074 fchmod(fileno(fp
), 0644);
2078 * Write each printer; each line looks like:
2080 * Dest name[/instance] options
2081 * Default name[/instance] options
2084 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
2085 if (dest
->instance
!= NULL
|| dest
->num_options
!= 0 || dest
->is_default
)
2087 if (dest
->is_default
)
2089 fprintf(fp
, "Default %s", dest
->name
);
2091 fprintf(fp
, "/%s", dest
->instance
);
2098 if ((temp
= cupsGetDest(dest
->name
, dest
->instance
, num_temps
, temps
)) == NULL
)
2099 temp
= cupsGetDest(dest
->name
, NULL
, num_temps
, temps
);
2101 for (j
= dest
->num_options
, option
= dest
->options
; j
> 0; j
--, option
++)
2104 * See if this option is a printer attribute; if so, skip it...
2107 if ((match
= _ippFindOption(option
->name
)) != NULL
&&
2108 match
->group_tag
== IPP_TAG_PRINTER
)
2112 * See if the server/global options match these; if so, don't
2117 (val
= cupsGetOption(option
->name
, temp
->num_options
,
2118 temp
->options
)) != NULL
&&
2119 !_cups_strcasecmp(val
, option
->value
))
2123 * Options don't match, write to the file...
2128 fprintf(fp
, "Dest %s", dest
->name
);
2130 fprintf(fp
, "/%s", dest
->instance
);
2134 if (option
->value
[0])
2136 if (strchr(option
->value
, ' ') ||
2137 strchr(option
->value
, '\\') ||
2138 strchr(option
->value
, '\"') ||
2139 strchr(option
->value
, '\''))
2142 * Quote the value...
2145 fprintf(fp
, " %s=\"", option
->name
);
2147 for (val
= option
->value
; *val
; val
++)
2149 if (strchr("\"\'\\", *val
))
2160 * Store the literal value...
2163 fprintf(fp
, " %s=%s", option
->name
, option
->value
);
2167 fprintf(fp
, " %s", option
->name
);
2175 * Free the temporary destinations and close the file...
2178 cupsFreeDests(num_temps
, temps
);
2184 * Set the default printer for this location - this allows command-line
2185 * and GUI applications to share the same default destination...
2188 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, dests
)) != NULL
)
2190 CFStringRef name
= CFStringCreateWithCString(kCFAllocatorDefault
,
2192 kCFStringEncodingUTF8
);
2193 /* Default printer name */
2197 _cupsAppleSetDefaultPrinter(name
);
2201 #endif /* __APPLE__ */
2203 #ifdef HAVE_NOTIFY_POST
2205 * Send a notification so that MacOS X applications can know about the
2209 notify_post("com.apple.printerListChange");
2210 #endif /* HAVE_NOTIFY_POST */
2217 * '_cupsUserDefault()' - Get the user default printer from environment
2218 * variables and location information.
2221 char * /* O - Default printer or NULL */
2222 _cupsUserDefault(char *name
, /* I - Name buffer */
2223 size_t namesize
) /* I - Size of name buffer */
2225 const char *env
; /* LPDEST or PRINTER env variable */
2227 CFStringRef locprinter
; /* Last printer as this location */
2228 #endif /* __APPLE__ */
2231 if ((env
= getenv("LPDEST")) == NULL
)
2232 if ((env
= getenv("PRINTER")) != NULL
&& !strcmp(env
, "lp"))
2237 strlcpy(name
, env
, namesize
);
2243 * Use location-based defaults if "use last printer" is selected in the
2244 * system preferences...
2247 if ((locprinter
= _cupsAppleCopyDefaultPrinter()) != NULL
)
2249 CFStringGetCString(locprinter
, name
, (CFIndex
)namesize
, kCFStringEncodingUTF8
);
2250 CFRelease(locprinter
);
2255 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name
));
2257 return (*name
? name
: NULL
);
2261 * No location-based defaults on this platform...
2266 #endif /* __APPLE__ */
2272 * 'appleCopyLocations()' - Copy the location history array.
2275 static CFArrayRef
/* O - Location array or NULL */
2276 appleCopyLocations(void)
2278 CFArrayRef locations
; /* Location array */
2282 * Look up the location array in the preferences...
2285 if ((locations
= CFPreferencesCopyAppValue(kLastUsedPrintersKey
,
2286 kCUPSPrintingPrefs
)) == NULL
)
2289 if (CFGetTypeID(locations
) != CFArrayGetTypeID())
2291 CFRelease(locations
);
2300 * 'appleCopyNetwork()' - Get the network ID for the current location.
2303 static CFStringRef
/* O - Network ID */
2304 appleCopyNetwork(void)
2306 SCDynamicStoreRef dynamicStore
; /* System configuration data */
2307 CFStringRef key
; /* Current network configuration key */
2308 CFDictionaryRef ip_dict
; /* Network configuration data */
2309 CFStringRef network
= NULL
; /* Current network ID */
2312 if ((dynamicStore
= SCDynamicStoreCreate(NULL
, CFSTR("libcups"), NULL
,
2316 * First use the IPv6 router address, if available, since that will generally
2317 * be a globally-unique link-local address.
2320 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2321 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv6
)) != NULL
)
2323 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2325 if ((network
= CFDictionaryGetValue(ip_dict
,
2326 kSCPropNetIPv6Router
)) != NULL
)
2336 * If that doesn't work, try the IPv4 router address. This isn't as unique
2337 * and will likely be a 10.x.y.z or 192.168.y.z address...
2342 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2343 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv4
)) != NULL
)
2345 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2347 if ((network
= CFDictionaryGetValue(ip_dict
,
2348 kSCPropNetIPv4Router
)) != NULL
)
2358 CFRelease(dynamicStore
);
2366 * 'appleGetPaperSize()' - Get the default paper size.
2369 static char * /* O - Default paper size */
2370 appleGetPaperSize(char *name
, /* I - Paper size name buffer */
2371 int namesize
) /* I - Size of buffer */
2373 CFStringRef defaultPaperID
; /* Default paper ID */
2374 pwg_media_t
*pwgmedia
; /* PWG media size */
2377 defaultPaperID
= _cupsAppleCopyDefaultPaperID();
2378 if (!defaultPaperID
||
2379 CFGetTypeID(defaultPaperID
) != CFStringGetTypeID() ||
2380 !CFStringGetCString(defaultPaperID
, name
, namesize
,
2381 kCFStringEncodingUTF8
))
2383 else if ((pwgmedia
= pwgMediaForLegacy(name
)) != NULL
)
2384 strlcpy(name
, pwgmedia
->pwg
, namesize
);
2387 CFRelease(defaultPaperID
);
2394 * 'appleGetPrinter()' - Get a printer from the history array.
2397 static CFStringRef
/* O - Printer name or NULL */
2398 appleGetPrinter(CFArrayRef locations
, /* I - Location array */
2399 CFStringRef network
, /* I - Network name */
2400 CFIndex
*locindex
) /* O - Index in array */
2402 CFIndex i
, /* Looping var */
2403 count
; /* Number of locations */
2404 CFDictionaryRef location
; /* Current location */
2405 CFStringRef locnetwork
, /* Current network */
2406 locprinter
; /* Current printer */
2409 for (i
= 0, count
= CFArrayGetCount(locations
); i
< count
; i
++)
2410 if ((location
= CFArrayGetValueAtIndex(locations
, i
)) != NULL
&&
2411 CFGetTypeID(location
) == CFDictionaryGetTypeID())
2413 if ((locnetwork
= CFDictionaryGetValue(location
,
2414 kLocationNetworkKey
)) != NULL
&&
2415 CFGetTypeID(locnetwork
) == CFStringGetTypeID() &&
2416 CFStringCompare(network
, locnetwork
, 0) == kCFCompareEqualTo
&&
2417 (locprinter
= CFDictionaryGetValue(location
,
2418 kLocationPrinterIDKey
)) != NULL
&&
2419 CFGetTypeID(locprinter
) == CFStringGetTypeID())
2424 return (locprinter
);
2430 #endif /* __APPLE__ */
2434 * 'cups_add_dest()' - Add a destination to the array.
2436 * Unlike cupsAddDest(), this function does not check for duplicates.
2439 static cups_dest_t
* /* O - New destination */
2440 cups_add_dest(const char *name
, /* I - Name of destination */
2441 const char *instance
, /* I - Instance or NULL */
2442 int *num_dests
, /* IO - Number of destinations */
2443 cups_dest_t
**dests
) /* IO - Destinations */
2445 int insert
, /* Insertion point */
2446 diff
; /* Result of comparison */
2447 cups_dest_t
*dest
; /* Destination pointer */
2451 * Add new destination...
2454 if (*num_dests
== 0)
2455 dest
= malloc(sizeof(cups_dest_t
));
2457 dest
= realloc(*dests
, sizeof(cups_dest_t
) * (size_t)(*num_dests
+ 1));
2465 * Find where to insert the destination...
2468 if (*num_dests
== 0)
2472 insert
= cups_find_dest(name
, instance
, *num_dests
, *dests
, *num_dests
- 1,
2480 * Move the array elements as needed...
2483 if (insert
< *num_dests
)
2484 memmove(*dests
+ insert
+ 1, *dests
+ insert
, (size_t)(*num_dests
- insert
) * sizeof(cups_dest_t
));
2489 * Initialize the destination...
2492 dest
= *dests
+ insert
;
2493 dest
->name
= _cupsStrAlloc(name
);
2494 dest
->instance
= _cupsStrAlloc(instance
);
2495 dest
->is_default
= 0;
2496 dest
->num_options
= 0;
2497 dest
->options
= (cups_option_t
*)0;
2505 * 'cups_block_cb()' - Enumeration callback for block API.
2508 static int /* O - 1 to continue, 0 to stop */
2510 cups_dest_block_t block
, /* I - Block */
2511 unsigned flags
, /* I - Destination flags */
2512 cups_dest_t
*dest
) /* I - Destination */
2514 return ((block
)(flags
, dest
));
2516 # endif /* __BLOCKS__ */
2520 * 'cups_compare_dests()' - Compare two destinations.
2523 static int /* O - Result of comparison */
2524 cups_compare_dests(cups_dest_t
*a
, /* I - First destination */
2525 cups_dest_t
*b
) /* I - Second destination */
2527 int diff
; /* Difference */
2530 if ((diff
= _cups_strcasecmp(a
->name
, b
->name
)) != 0)
2532 else if (a
->instance
&& b
->instance
)
2533 return (_cups_strcasecmp(a
->instance
, b
->instance
));
2535 return ((a
->instance
&& !b
->instance
) - (!a
->instance
&& b
->instance
));
2539 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
2542 * 'cups_dnssd_browse_cb()' - Browse for printers.
2546 cups_dnssd_browse_cb(
2547 DNSServiceRef sdRef
, /* I - Service reference */
2548 DNSServiceFlags flags
, /* I - Option flags */
2549 uint32_t interfaceIndex
, /* I - Interface number */
2550 DNSServiceErrorType errorCode
, /* I - Error, if any */
2551 const char *serviceName
, /* I - Name of service/device */
2552 const char *regtype
, /* I - Type of service */
2553 const char *replyDomain
, /* I - Service domain */
2554 void *context
) /* I - Enumeration data */
2556 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2557 /* Enumeration data */
2560 DEBUG_printf(("5cups_dnssd_browse_cb(sdRef=%p, flags=%x, "
2561 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2562 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2563 sdRef
, flags
, interfaceIndex
, errorCode
, serviceName
, regtype
,
2564 replyDomain
, context
));
2567 * Don't do anything on error...
2570 if (errorCode
!= kDNSServiceErr_NoError
)
2577 cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2581 # else /* HAVE_AVAHI */
2583 * 'cups_dnssd_browse_cb()' - Browse for printers.
2587 cups_dnssd_browse_cb(
2588 AvahiServiceBrowser
*browser
, /* I - Browser */
2589 AvahiIfIndex interface
, /* I - Interface index (unused) */
2590 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2591 AvahiBrowserEvent event
, /* I - What happened */
2592 const char *name
, /* I - Service name */
2593 const char *type
, /* I - Registration type */
2594 const char *domain
, /* I - Domain */
2595 AvahiLookupResultFlags flags
, /* I - Flags */
2596 void *context
) /* I - Devices array */
2599 AvahiClient
*client
= avahi_service_browser_get_client(browser
);
2600 /* Client information */
2602 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2603 /* Enumeration data */
2612 case AVAHI_BROWSER_FAILURE
:
2613 DEBUG_printf(("cups_dnssd_browse_cb: %s",
2614 avahi_strerror(avahi_client_errno(client
))));
2615 avahi_simple_poll_quit(data
->simple_poll
);
2618 case AVAHI_BROWSER_NEW
:
2620 * This object is new on the network.
2623 if (flags
& AVAHI_LOOKUP_RESULT_LOCAL
)
2626 * This comes from the local machine so ignore it.
2629 DEBUG_printf(("cups_dnssd_browse_cb: Ignoring local service \"%s\".",
2635 * Create a device entry for it if it doesn't yet exist.
2638 cups_dnssd_get_device(data
, name
, type
, domain
);
2642 case AVAHI_BROWSER_REMOVE
:
2643 case AVAHI_BROWSER_ALL_FOR_NOW
:
2644 case AVAHI_BROWSER_CACHE_EXHAUSTED
:
2651 * 'cups_dnssd_client_cb()' - Avahi client callback function.
2655 cups_dnssd_client_cb(
2656 AvahiClient
*client
, /* I - Client information (unused) */
2657 AvahiClientState state
, /* I - Current state */
2658 void *context
) /* I - User data (unused) */
2660 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2661 /* Enumeration data */
2667 * If the connection drops, quit.
2670 if (state
== AVAHI_CLIENT_FAILURE
)
2672 DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
2673 avahi_simple_poll_quit(data
->simple_poll
);
2676 # endif /* HAVE_DNSSD */
2680 * 'cups_dnssd_compare_device()' - Compare two devices.
2683 static int /* O - Result of comparison */
2684 cups_dnssd_compare_devices(
2685 _cups_dnssd_device_t
*a
, /* I - First device */
2686 _cups_dnssd_device_t
*b
) /* I - Second device */
2688 return (strcmp(a
->dest
.name
, b
->dest
.name
));
2693 * 'cups_dnssd_free_device()' - Free the memory used by a device.
2697 cups_dnssd_free_device(
2698 _cups_dnssd_device_t
*device
, /* I - Device */
2699 _cups_dnssd_data_t
*data
) /* I - Enumeration data */
2701 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", device
,
2702 device
->dest
.name
, data
));
2706 DNSServiceRefDeallocate(device
->ref
);
2707 # else /* HAVE_AVAHI */
2709 avahi_record_browser_free(device
->ref
);
2710 # endif /* HAVE_DNSSD */
2712 _cupsStrFree(device
->domain
);
2713 _cupsStrFree(device
->fullName
);
2714 _cupsStrFree(device
->regtype
);
2715 _cupsStrFree(device
->dest
.name
);
2717 cupsFreeOptions(device
->dest
.num_options
, device
->dest
.options
);
2724 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
2727 static _cups_dnssd_device_t
* /* O - Device */
2728 cups_dnssd_get_device(
2729 _cups_dnssd_data_t
*data
, /* I - Enumeration data */
2730 const char *serviceName
, /* I - Service name */
2731 const char *regtype
, /* I - Registration type */
2732 const char *replyDomain
) /* I - Domain name */
2734 _cups_dnssd_device_t key
, /* Search key */
2735 *device
; /* Device */
2736 char fullName
[kDNSServiceMaxDomainName
];
2737 /* Full name for query */
2740 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", "
2741 "regtype=\"%s\", replyDomain=\"%s\")", data
, serviceName
,
2742 regtype
, replyDomain
));
2745 * See if this is an existing device...
2748 key
.dest
.name
= (char *)serviceName
;
2750 if ((device
= cupsArrayFind(data
->devices
, &key
)) != NULL
)
2753 * Yes, see if we need to do anything with this...
2756 int update
= 0; /* Non-zero if we need to update */
2758 if (!_cups_strcasecmp(replyDomain
, "local.") &&
2759 _cups_strcasecmp(device
->domain
, replyDomain
))
2762 * Update the "global" listing to use the .local domain name instead.
2765 _cupsStrFree(device
->domain
);
2766 device
->domain
= _cupsStrAlloc(replyDomain
);
2768 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
2769 "domain.", device
->dest
.name
));
2774 if (!_cups_strcasecmp(regtype
, "_ipps._tcp") &&
2775 _cups_strcasecmp(device
->regtype
, regtype
))
2778 * Prefer IPPS over IPP.
2781 _cupsStrFree(device
->regtype
);
2782 device
->regtype
= _cupsStrAlloc(regtype
);
2784 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
2785 device
->dest
.name
));
2792 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
2793 device
->dest
.name
));
2800 * No, add the device...
2803 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
2804 "'%s'.", serviceName
,
2805 !strcmp(regtype
, "_ipps._tcp") ? "IPPS" : "IPP",
2808 device
= calloc(sizeof(_cups_dnssd_device_t
), 1);
2809 device
->dest
.name
= _cupsStrAlloc(serviceName
);
2810 device
->domain
= _cupsStrAlloc(replyDomain
);
2811 device
->regtype
= _cupsStrAlloc(regtype
);
2813 cupsArrayAdd(data
->devices
, device
);
2817 * Set the "full name" of this service, which is used for queries...
2821 DNSServiceConstructFullName(fullName
, device
->dest
.name
, device
->regtype
,
2823 # else /* HAVE_AVAHI */
2824 avahi_service_name_join(fullName
, kDNSServiceMaxDomainName
, serviceName
,
2825 regtype
, replyDomain
);
2826 # endif /* HAVE_DNSSD */
2828 _cupsStrFree(device
->fullName
);
2829 device
->fullName
= _cupsStrAlloc(fullName
);
2834 DNSServiceRefDeallocate(device
->ref
);
2835 # else /* HAVE_AVAHI */
2836 avahi_record_browser_free(device
->ref
);
2837 # endif /* HAVE_DNSSD */
2842 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
2844 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
2845 device
->state
= _CUPS_DNSSD_NEW
;
2854 * 'cups_dnssd_local_cb()' - Browse for local printers.
2858 cups_dnssd_local_cb(
2859 DNSServiceRef sdRef
, /* I - Service reference */
2860 DNSServiceFlags flags
, /* I - Option flags */
2861 uint32_t interfaceIndex
, /* I - Interface number */
2862 DNSServiceErrorType errorCode
, /* I - Error, if any */
2863 const char *serviceName
, /* I - Name of service/device */
2864 const char *regtype
, /* I - Type of service */
2865 const char *replyDomain
, /* I - Service domain */
2866 void *context
) /* I - Devices array */
2868 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2869 /* Enumeration data */
2870 _cups_dnssd_device_t
*device
; /* Device */
2873 DEBUG_printf(("5cups_dnssd_local_cb(sdRef=%p, flags=%x, "
2874 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2875 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2876 sdRef
, flags
, interfaceIndex
, errorCode
, serviceName
,
2877 regtype
, replyDomain
, context
));
2880 * Only process "add" data...
2883 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
2890 device
= cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2893 * Hide locally-registered devices...
2896 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
2901 DNSServiceRefDeallocate(device
->ref
);
2905 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
2906 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
2908 device
->state
= _CUPS_DNSSD_LOCAL
;
2910 # endif /* HAVE_DNSSD */
2915 * 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
2917 * Note: This function is needed because avahi_simple_poll_iterate is broken
2918 * and always uses a timeout of 0 (!) milliseconds.
2919 * (Avahi Ticket #364)
2922 static int /* O - Number of file descriptors matching */
2924 struct pollfd
*pollfds
, /* I - File descriptors */
2925 unsigned int num_pollfds
, /* I - Number of file descriptors */
2926 int timeout
, /* I - Timeout in milliseconds (unused) */
2927 void *context
) /* I - User data (unused) */
2929 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2930 /* Enumeration data */
2931 int val
; /* Return value */
2936 val
= poll(pollfds
, num_pollfds
, 250);
2940 DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno
)));
2947 # endif /* HAVE_AVAHI */
2951 * 'cups_dnssd_query_cb()' - Process query data.
2956 cups_dnssd_query_cb(
2957 DNSServiceRef sdRef
, /* I - Service reference */
2958 DNSServiceFlags flags
, /* I - Data flags */
2959 uint32_t interfaceIndex
, /* I - Interface */
2960 DNSServiceErrorType errorCode
, /* I - Error, if any */
2961 const char *fullName
, /* I - Full service name */
2962 uint16_t rrtype
, /* I - Record type */
2963 uint16_t rrclass
, /* I - Record class */
2964 uint16_t rdlen
, /* I - Length of record data */
2965 const void *rdata
, /* I - Record data */
2966 uint32_t ttl
, /* I - Time-to-live */
2967 void *context
) /* I - Enumeration data */
2969 # else /* HAVE_AVAHI */
2971 cups_dnssd_query_cb(
2972 AvahiRecordBrowser
*browser
, /* I - Record browser */
2973 AvahiIfIndex interfaceIndex
,
2974 /* I - Interface index (unused) */
2975 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2976 AvahiBrowserEvent event
, /* I - What happened? */
2977 const char *fullName
, /* I - Service name */
2978 uint16_t rrclass
, /* I - Record class */
2979 uint16_t rrtype
, /* I - Record type */
2980 const void *rdata
, /* I - TXT record */
2981 size_t rdlen
, /* I - Length of TXT record */
2982 AvahiLookupResultFlags flags
, /* I - Flags */
2983 void *context
) /* I - Enumeration data */
2986 AvahiClient
*client
= avahi_record_browser_get_client(browser
);
2987 /* Client information */
2989 # endif /* HAVE_DNSSD */
2990 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2991 /* Enumeration data */
2992 char name
[1024], /* Service name */
2993 *ptr
; /* Pointer into string */
2994 _cups_dnssd_device_t dkey
, /* Search key */
2995 *device
; /* Device */
2999 DEBUG_printf(("5cups_dnssd_query_cb(sdRef=%p, flags=%x, "
3000 "interfaceIndex=%d, errorCode=%d, fullName=\"%s\", "
3001 "rrtype=%u, rrclass=%u, rdlen=%u, rdata=%p, ttl=%u, "
3002 "context=%p)", sdRef
, flags
, interfaceIndex
, errorCode
,
3003 fullName
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, context
));
3006 * Only process "add" data...
3009 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
3012 # else /* HAVE_AVAHI */
3013 DEBUG_printf(("5cups_dnssd_query_cb(browser=%p, interfaceIndex=%d, "
3014 "protocol=%d, event=%d, fullName=\"%s\", rrclass=%u, "
3015 "rrtype=%u, rdata=%p, rdlen=%u, flags=%x, context=%p)",
3016 browser
, interfaceIndex
, protocol
, event
, fullName
, rrclass
,
3017 rrtype
, rdata
, (unsigned)rdlen
, flags
, context
));
3020 * Only process "add" data...
3023 if (event
!= AVAHI_BROWSER_NEW
)
3025 if (event
== AVAHI_BROWSER_FAILURE
)
3026 DEBUG_printf(("cups_dnssd_query_cb: %s",
3027 avahi_strerror(avahi_client_errno(client
))));
3031 # endif /* HAVE_DNSSD */
3034 * Lookup the service in the devices array.
3037 dkey
.dest
.name
= name
;
3039 cups_dnssd_unquote(name
, fullName
, sizeof(name
));
3041 if ((ptr
= strstr(name
, "._")) != NULL
)
3044 if ((device
= cupsArrayFind(data
->devices
, &dkey
)) != NULL
)
3047 * Found it, pull out the make and model from the TXT record and save it...
3050 const uint8_t *txt
, /* Pointer into data */
3051 *txtnext
, /* Next key/value pair */
3052 *txtend
; /* End of entire TXT record */
3053 uint8_t txtlen
; /* Length of current key/value pair */
3054 char key
[256], /* Key string */
3055 value
[256], /* Value string */
3056 make_and_model
[512],
3057 /* Manufacturer and model */
3058 model
[256], /* Model */
3059 uriname
[1024], /* Name for URI */
3060 uri
[1024]; /* Printer URI */
3061 cups_ptype_t type
= CUPS_PRINTER_REMOTE
| CUPS_PRINTER_BW
;
3063 int saw_printer_type
= 0;
3064 /* Did we see a printer-type key? */
3066 device
->state
= _CUPS_DNSSD_PENDING
;
3067 make_and_model
[0] = '\0';
3069 strlcpy(model
, "Unknown", sizeof(model
));
3071 for (txt
= rdata
, txtend
= txt
+ rdlen
;
3076 * Read a key/value pair starting with an 8-bit length. Since the
3077 * length is 8 bits and the size of the key/value buffers is 256, we
3078 * don't need to check for overflow...
3083 if (!txtlen
|| (txt
+ txtlen
) > txtend
)
3086 txtnext
= txt
+ txtlen
;
3088 for (ptr
= key
; txt
< txtnext
&& *txt
!= '='; txt
++)
3089 *ptr
++ = (char)*txt
;
3092 if (txt
< txtnext
&& *txt
== '=')
3097 memcpy(value
, txt
, txtnext
- txt
);
3098 value
[txtnext
- txt
] = '\0';
3100 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key
, value
));
3104 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key
));
3108 if (!_cups_strcasecmp(key
, "usb_MFG") ||
3109 !_cups_strcasecmp(key
, "usb_MANU") ||
3110 !_cups_strcasecmp(key
, "usb_MANUFACTURER"))
3111 strlcpy(make_and_model
, value
, sizeof(make_and_model
));
3112 else if (!_cups_strcasecmp(key
, "usb_MDL") ||
3113 !_cups_strcasecmp(key
, "usb_MODEL"))
3114 strlcpy(model
, value
, sizeof(model
));
3115 else if (!_cups_strcasecmp(key
, "product") && !strstr(value
, "Ghostscript"))
3117 if (value
[0] == '(')
3120 * Strip parenthesis...
3123 if ((ptr
= value
+ strlen(value
) - 1) > value
&& *ptr
== ')')
3126 strlcpy(model
, value
+ 1, sizeof(model
));
3129 strlcpy(model
, value
, sizeof(model
));
3131 else if (!_cups_strcasecmp(key
, "ty"))
3133 strlcpy(model
, value
, sizeof(model
));
3135 if ((ptr
= strchr(model
, ',')) != NULL
)
3138 else if (!_cups_strcasecmp(key
, "note"))
3139 device
->dest
.num_options
= cupsAddOption("printer-location", value
,
3140 device
->dest
.num_options
,
3141 &device
->dest
.options
);
3142 else if (!_cups_strcasecmp(key
, "pdl"))
3145 * Look for PDF-capable printers; only PDF-capable printers are shown.
3148 const char *start
, *next
; /* Pointer into value */
3149 int have_pdf
= 0; /* Have PDF? */
3151 for (start
= value
; start
&& *start
; start
= next
)
3153 if (!_cups_strncasecmp(start
, "application/pdf", 15) &&
3154 (!start
[15] || start
[15] == ','))
3160 if ((next
= strchr(start
, ',')) != NULL
)
3165 device
->state
= _CUPS_DNSSD_INCOMPATIBLE
;
3167 else if (!_cups_strcasecmp(key
, "printer-type"))
3170 * Value is either NNNN or 0xXXXX
3173 saw_printer_type
= 1;
3174 type
= (cups_ptype_t
)strtol(value
, NULL
, 0);
3176 else if (!saw_printer_type
)
3178 if (!_cups_strcasecmp(key
, "air") &&
3179 !_cups_strcasecmp(value
, "t"))
3180 type
|= CUPS_PRINTER_AUTHENTICATED
;
3181 else if (!_cups_strcasecmp(key
, "bind") &&
3182 !_cups_strcasecmp(value
, "t"))
3183 type
|= CUPS_PRINTER_BIND
;
3184 else if (!_cups_strcasecmp(key
, "collate") &&
3185 !_cups_strcasecmp(value
, "t"))
3186 type
|= CUPS_PRINTER_COLLATE
;
3187 else if (!_cups_strcasecmp(key
, "color") &&
3188 !_cups_strcasecmp(value
, "t"))
3189 type
|= CUPS_PRINTER_COLOR
;
3190 else if (!_cups_strcasecmp(key
, "copies") &&
3191 !_cups_strcasecmp(value
, "t"))
3192 type
|= CUPS_PRINTER_COPIES
;
3193 else if (!_cups_strcasecmp(key
, "duplex") &&
3194 !_cups_strcasecmp(value
, "t"))
3195 type
|= CUPS_PRINTER_DUPLEX
;
3196 else if (!_cups_strcasecmp(key
, "fax") &&
3197 !_cups_strcasecmp(value
, "t"))
3198 type
|= CUPS_PRINTER_MFP
;
3199 else if (!_cups_strcasecmp(key
, "papercustom") &&
3200 !_cups_strcasecmp(value
, "t"))
3201 type
|= CUPS_PRINTER_VARIABLE
;
3202 else if (!_cups_strcasecmp(key
, "papermax"))
3204 if (!_cups_strcasecmp(value
, "legal-a4"))
3205 type
|= CUPS_PRINTER_SMALL
;
3206 else if (!_cups_strcasecmp(value
, "isoc-a2"))
3207 type
|= CUPS_PRINTER_MEDIUM
;
3208 else if (!_cups_strcasecmp(value
, ">isoc-a2"))
3209 type
|= CUPS_PRINTER_LARGE
;
3211 else if (!_cups_strcasecmp(key
, "punch") &&
3212 !_cups_strcasecmp(value
, "t"))
3213 type
|= CUPS_PRINTER_PUNCH
;
3214 else if (!_cups_strcasecmp(key
, "scan") &&
3215 !_cups_strcasecmp(value
, "t"))
3216 type
|= CUPS_PRINTER_MFP
;
3217 else if (!_cups_strcasecmp(key
, "sort") &&
3218 !_cups_strcasecmp(value
, "t"))
3219 type
|= CUPS_PRINTER_SORT
;
3220 else if (!_cups_strcasecmp(key
, "staple") &&
3221 !_cups_strcasecmp(value
, "t"))
3222 type
|= CUPS_PRINTER_STAPLE
;
3227 * Save the printer-xxx values...
3230 device
->dest
.num_options
= cupsAddOption("printer-info", name
,
3231 device
->dest
.num_options
,
3232 &device
->dest
.options
);
3234 if (make_and_model
[0])
3236 strlcat(make_and_model
, " ", sizeof(make_and_model
));
3237 strlcat(make_and_model
, model
, sizeof(make_and_model
));
3239 device
->dest
.num_options
= cupsAddOption("printer-make-and-model",
3241 device
->dest
.num_options
,
3242 &device
->dest
.options
);
3245 device
->dest
.num_options
= cupsAddOption("printer-make-and-model",
3247 device
->dest
.num_options
,
3248 &device
->dest
.options
);
3250 device
->type
= type
;
3251 snprintf(value
, sizeof(value
), "%u", type
);
3252 device
->dest
.num_options
= cupsAddOption("printer-type", value
,
3253 device
->dest
.num_options
,
3254 &device
->dest
.options
);
3260 cups_dnssd_unquote(uriname
, device
->fullName
, sizeof(uriname
));
3261 httpAssembleURI(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
),
3262 !strcmp(device
->regtype
, "_ipps._tcp") ? "ipps" : "ipp",
3263 NULL
, uriname
, 0, saw_printer_type
? "/cups" : "/");
3265 DEBUG_printf(("6cups_dnssd_query: printer-uri-supported=\"%s\"", uri
));
3267 device
->dest
.num_options
= cupsAddOption("printer-uri-supported", uri
,
3268 device
->dest
.num_options
,
3269 &device
->dest
.options
);
3272 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
3278 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
3281 static const char * /* O - Resolved URI or NULL */
3283 cups_dest_t
*dest
, /* I - Destination */
3284 const char *uri
, /* I - Current printer URI */
3285 int msec
, /* I - Time in milliseconds */
3286 int *cancel
, /* I - Pointer to "cancel" variable */
3287 cups_dest_cb_t cb
, /* I - Callback */
3288 void *user_data
) /* I - User data for callback */
3290 char tempuri
[1024]; /* Temporary URI buffer */
3291 _cups_dnssd_resolve_t resolve
; /* Resolve data */
3295 * Resolve the URI...
3298 resolve
.cancel
= cancel
;
3299 gettimeofday(&resolve
.end_time
, NULL
);
3302 resolve
.end_time
.tv_sec
+= msec
/ 1000;
3303 resolve
.end_time
.tv_usec
+= (msec
% 1000) * 1000;
3305 while (resolve
.end_time
.tv_usec
>= 1000000)
3307 resolve
.end_time
.tv_sec
++;
3308 resolve
.end_time
.tv_usec
-= 1000000;
3312 resolve
.end_time
.tv_sec
+= 75;
3315 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
,
3318 if ((uri
= _httpResolveURI(uri
, tempuri
, sizeof(tempuri
),
3319 _HTTP_RESOLVE_FQDN
, cups_dnssd_resolve_cb
,
3322 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to resolve printer URI."), 1);
3325 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
3332 * Save the resolved URI...
3335 dest
->num_options
= cupsAddOption("printer-uri-supported", uri
,
3336 dest
->num_options
, &dest
->options
);
3338 return (cupsGetOption("printer-uri-supported", dest
->num_options
,
3344 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
3347 static int /* O - 1 to continue, 0 to stop */
3348 cups_dnssd_resolve_cb(void *context
) /* I - Resolve data */
3350 _cups_dnssd_resolve_t
*resolve
= (_cups_dnssd_resolve_t
*)context
;
3352 struct timeval curtime
; /* Current time */
3356 * If the cancel variable is set, return immediately.
3359 if (*resolve
->cancel
)
3363 * Otherwise check the end time...
3366 gettimeofday(&curtime
, NULL
);
3368 return (curtime
.tv_sec
> resolve
->end_time
.tv_sec
||
3369 (curtime
.tv_sec
== resolve
->end_time
.tv_sec
&&
3370 curtime
.tv_usec
> resolve
->end_time
.tv_usec
));
3375 * 'cups_dnssd_unquote()' - Unquote a name string.
3379 cups_dnssd_unquote(char *dst
, /* I - Destination buffer */
3380 const char *src
, /* I - Source string */
3381 size_t dstsize
) /* I - Size of destination buffer */
3383 char *dstend
= dst
+ dstsize
- 1; /* End of destination buffer */
3386 while (*src
&& dst
< dstend
)
3391 if (isdigit(src
[0] & 255) && isdigit(src
[1] & 255) &&
3392 isdigit(src
[2] & 255))
3394 *dst
++ = ((((src
[0] - '0') * 10) + src
[1] - '0') * 10) + src
[2] - '0';
3406 #endif /* HAVE_DNSSD */
3410 * 'cups_find_dest()' - Find a destination using a binary search.
3413 static int /* O - Index of match */
3414 cups_find_dest(const char *name
, /* I - Destination name */
3415 const char *instance
, /* I - Instance or NULL */
3416 int num_dests
, /* I - Number of destinations */
3417 cups_dest_t
*dests
, /* I - Destinations */
3418 int prev
, /* I - Previous index */
3419 int *rdiff
) /* O - Difference of match */
3421 int left
, /* Low mark for binary search */
3422 right
, /* High mark for binary search */
3423 current
, /* Current index */
3424 diff
; /* Result of comparison */
3425 cups_dest_t key
; /* Search key */
3428 key
.name
= (char *)name
;
3429 key
.instance
= (char *)instance
;
3434 * Start search on either side of previous...
3437 if ((diff
= cups_compare_dests(&key
, dests
+ prev
)) == 0 ||
3438 (diff
< 0 && prev
== 0) ||
3439 (diff
> 0 && prev
== (num_dests
- 1)))
3447 * Start with previous on right side...
3456 * Start wih previous on left side...
3460 right
= num_dests
- 1;
3466 * Start search in the middle...
3470 right
= num_dests
- 1;
3475 current
= (left
+ right
) / 2;
3476 diff
= cups_compare_dests(&key
, dests
+ current
);
3485 while ((right
- left
) > 1);
3490 * Check the last 1 or 2 elements...
3493 if ((diff
= cups_compare_dests(&key
, dests
+ left
)) <= 0)
3497 diff
= cups_compare_dests(&key
, dests
+ right
);
3503 * Return the closest destination and the difference...
3513 * 'cups_get_default()' - Get the default destination from an lpoptions file.
3516 static char * /* O - Default destination or NULL */
3517 cups_get_default(const char *filename
, /* I - File to read */
3518 char *namebuf
, /* I - Name buffer */
3519 size_t namesize
, /* I - Size of name buffer */
3520 const char **instance
) /* I - Instance */
3522 cups_file_t
*fp
; /* lpoptions file */
3523 char line
[8192], /* Line from file */
3524 *value
, /* Value for line */
3525 *nameptr
; /* Pointer into name */
3526 int linenum
; /* Current line */
3531 if ((fp
= cupsFileOpen(filename
, "r")) != NULL
)
3535 while (cupsFileGetConf(fp
, line
, sizeof(line
), &value
, &linenum
))
3537 if (!_cups_strcasecmp(line
, "default") && value
)
3539 strlcpy(namebuf
, value
, namesize
);
3541 if ((nameptr
= strchr(namebuf
, ' ')) != NULL
)
3543 if ((nameptr
= strchr(namebuf
, '\t')) != NULL
)
3546 if ((nameptr
= strchr(namebuf
, '/')) != NULL
)
3549 *instance
= nameptr
;
3557 return (*namebuf
? namebuf
: NULL
);
3562 * 'cups_get_dests()' - Get destinations from a file.
3565 static int /* O - Number of destinations */
3567 const char *filename
, /* I - File to read from */
3568 const char *match_name
, /* I - Destination name we want */
3569 const char *match_inst
, /* I - Instance name we want */
3570 int user_default_set
, /* I - User default printer set? */
3571 int num_dests
, /* I - Number of destinations */
3572 cups_dest_t
**dests
) /* IO - Destinations */
3574 int i
; /* Looping var */
3575 cups_dest_t
*dest
; /* Current destination */
3576 cups_file_t
*fp
; /* File pointer */
3577 char line
[8192], /* Line from file */
3578 *lineptr
, /* Pointer into line */
3579 *name
, /* Name of destination/option */
3580 *instance
; /* Instance of destination */
3581 int linenum
; /* Current line number */
3584 DEBUG_printf(("7cups_get_dests(filename=\"%s\", match_name=\"%s\", "
3585 "match_inst=\"%s\", user_default_set=%d, num_dests=%d, "
3586 "dests=%p)", filename
, match_name
, match_inst
,
3587 user_default_set
, num_dests
, dests
));
3590 * Try to open the file...
3593 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
3597 * Read each printer; each line looks like:
3599 * Dest name[/instance] options
3600 * Default name[/instance] options
3605 while (cupsFileGetConf(fp
, line
, sizeof(line
), &lineptr
, &linenum
))
3608 * See what type of line it is...
3611 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
3612 linenum
, line
, lineptr
));
3614 if ((_cups_strcasecmp(line
, "dest") && _cups_strcasecmp(line
, "default")) || !lineptr
)
3616 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
3623 * Search for an instance...
3626 while (!isspace(*lineptr
& 255) && *lineptr
&& *lineptr
!= '/')
3629 if (*lineptr
== '/')
3632 * Found an instance...
3639 * Search for an instance...
3642 while (!isspace(*lineptr
& 255) && *lineptr
)
3651 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name
,
3655 * See if the primary instance of the destination exists; if not,
3656 * ignore this entry and move on...
3661 if (_cups_strcasecmp(name
, match_name
) ||
3662 (!instance
&& match_inst
) ||
3663 (instance
&& !match_inst
) ||
3664 (instance
&& _cups_strcasecmp(instance
, match_inst
)))
3669 else if (cupsGetDest(name
, NULL
, num_dests
, *dests
) == NULL
)
3671 DEBUG_puts("9cups_get_dests: Not found!");
3677 * Add the destination...
3680 num_dests
= cupsAddDest(name
, instance
, num_dests
, dests
);
3682 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
3688 DEBUG_puts("9cups_get_dests: Out of memory!");
3694 * Add options until we hit the end of the line...
3697 dest
->num_options
= cupsParseOptions(lineptr
, dest
->num_options
,
3701 * If we found what we were looking for, stop now...
3708 * Set this as default if needed...
3711 if (!user_default_set
&& !_cups_strcasecmp(line
, "default"))
3713 DEBUG_puts("9cups_get_dests: Setting as default...");
3715 for (i
= 0; i
< num_dests
; i
++)
3716 (*dests
)[i
].is_default
= 0;
3718 dest
->is_default
= 1;
3723 * Close the file and return...
3733 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
3737 static char * /* O - New string */
3739 ipp_attribute_t
*attr
, /* I - Attribute to convert */
3740 char *buffer
, /* I - Buffer */
3741 size_t bufsize
) /* I - Size of buffer */
3743 int i
; /* Looping var */
3744 char *ptr
, /* Pointer into buffer */
3745 *end
, /* Pointer to end of buffer */
3746 *valptr
; /* Pointer into string attribute */
3750 * Return quickly if we have a single string value...
3753 if (attr
->num_values
== 1 &&
3754 attr
->value_tag
!= IPP_TAG_INTEGER
&&
3755 attr
->value_tag
!= IPP_TAG_ENUM
&&
3756 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
3757 attr
->value_tag
!= IPP_TAG_RANGE
)
3758 return (attr
->values
[0].string
.text
);
3761 * Copy the values to the string, separating with commas and escaping strings
3765 end
= buffer
+ bufsize
- 1;
3767 for (i
= 0, ptr
= buffer
; i
< attr
->num_values
&& ptr
< end
; i
++)
3772 switch (attr
->value_tag
)
3774 case IPP_TAG_INTEGER
:
3776 snprintf(ptr
, end
- ptr
+ 1, "%d", attr
->values
[i
].integer
);
3779 case IPP_TAG_BOOLEAN
:
3780 if (attr
->values
[i
].boolean
)
3781 strlcpy(ptr
, "true", end
- ptr
+ 1);
3783 strlcpy(ptr
, "false", end
- ptr
+ 1);
3786 case IPP_TAG_RANGE
:
3787 if (attr
->values
[i
].range
.lower
== attr
->values
[i
].range
.upper
)
3788 snprintf(ptr
, end
- ptr
+ 1, "%d", attr
->values
[i
].range
.lower
);
3790 snprintf(ptr
, end
- ptr
+ 1, "%d-%d", attr
->values
[i
].range
.lower
,
3791 attr
->values
[i
].range
.upper
);
3795 for (valptr
= attr
->values
[i
].string
.text
;
3796 *valptr
&& ptr
< end
;)
3798 if (strchr(" \t\n\\\'\"", *valptr
))
3800 if (ptr
>= (end
- 1))