4 * User-defined destination (and option) support for CUPS.
6 * Copyright 2007-2015 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
, size_t 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
);
406 # ifdef HAVE_NOTIFY_POST
407 notify_post("com.apple.printerPrefsChange");
408 # endif /* HAVE_NOTIFY_POST */
413 * '_cupsAppleSetDefaultPrinter()' - Set the default printer for this location.
417 _cupsAppleSetDefaultPrinter(
418 CFStringRef name
) /* I - Default printer/class name */
420 CFStringRef network
; /* Current network */
421 CFArrayRef locations
; /* Old locations array */
422 CFIndex locindex
; /* Index in locations array */
423 CFStringRef locprinter
; /* Current printer */
424 CFMutableArrayRef newlocations
; /* New locations array */
425 CFMutableDictionaryRef newlocation
; /* New location */
429 * Get the current location...
432 if ((network
= appleCopyNetwork()) == NULL
)
434 DEBUG_puts("1_cupsAppleSetDefaultPrinter: Unable to get current network...");
439 * Lookup the network in the preferences...
442 if ((locations
= appleCopyLocations()) != NULL
)
443 locprinter
= appleGetPrinter(locations
, network
, &locindex
);
450 if (!locprinter
|| CFStringCompare(locprinter
, name
, 0) != kCFCompareEqualTo
)
453 * Need to change the locations array...
458 newlocations
= CFArrayCreateMutableCopy(kCFAllocatorDefault
, 0,
462 CFArrayRemoveValueAtIndex(newlocations
, locindex
);
465 newlocations
= CFArrayCreateMutable(kCFAllocatorDefault
, 0,
466 &kCFTypeArrayCallBacks
);
468 newlocation
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
469 &kCFTypeDictionaryKeyCallBacks
,
470 &kCFTypeDictionaryValueCallBacks
);
472 if (newlocation
&& newlocations
)
475 * Put the new location at the front of the array...
478 CFDictionaryAddValue(newlocation
, kLocationNetworkKey
, network
);
479 CFDictionaryAddValue(newlocation
, kLocationPrinterIDKey
, name
);
480 CFArrayInsertValueAtIndex(newlocations
, 0, newlocation
);
483 * Limit the number of locations to 10...
486 while (CFArrayGetCount(newlocations
) > 10)
487 CFArrayRemoveValueAtIndex(newlocations
, 10);
490 * Push the changes out...
493 CFPreferencesSetAppValue(kLastUsedPrintersKey
, newlocations
,
495 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
497 # ifdef HAVE_NOTIFY_POST
498 notify_post("com.apple.printerPrefsChange");
499 # endif /* HAVE_NOTIFY_POST */
503 CFRelease(newlocations
);
506 CFRelease(newlocation
);
510 CFRelease(locations
);
517 * '_cupsAppleSetUseLastPrinter()' - Set whether to use the last used printer.
521 _cupsAppleSetUseLastPrinter(
522 int uselast
) /* O - 1 to use last printer, 0 otherwise */
524 CFPreferencesSetAppValue(kUseLastPrinter
,
525 uselast
? kCFBooleanTrue
: kCFBooleanFalse
,
527 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
529 # ifdef HAVE_NOTIFY_POST
530 notify_post("com.apple.printerPrefsChange");
531 # endif /* HAVE_NOTIFY_POST */
533 #endif /* __APPLE__ */
537 * 'cupsConnectDest()' - Connect to the server for a destination.
539 * Connect to the destination, returning a new http_t connection object and
540 * optionally the resource path to use for the destination. These calls will
541 * block until a connection is made, the timeout expires, the integer pointed
542 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
543 * The caller is responsible for calling httpClose() on the returned object.
545 * @since CUPS 1.6/OS X 10.8@
548 http_t
* /* O - Connection to server or @code NULL@ */
550 cups_dest_t
*dest
, /* I - Destination */
551 unsigned flags
, /* I - Connection flags */
552 int msec
, /* I - Timeout in milliseconds */
553 int *cancel
, /* I - Pointer to "cancel" variable */
554 char *resource
, /* I - Resource buffer */
555 size_t resourcesize
, /* I - Size of resource buffer */
556 cups_dest_cb_t cb
, /* I - Callback function */
557 void *user_data
) /* I - User data pointer */
559 const char *uri
; /* Printer URI */
560 char scheme
[32], /* URI scheme */
561 userpass
[256], /* Username and password (unused) */
562 hostname
[256], /* Hostname */
563 tempresource
[1024]; /* Temporary resource buffer */
564 int port
; /* Port number */
565 char portstr
[16]; /* Port number string */
566 http_encryption_t encryption
; /* Encryption to use */
567 http_addrlist_t
*addrlist
; /* Address list for server */
568 http_t
*http
; /* Connection to server */
572 * Range check input...
580 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
584 if (!resource
|| resourcesize
< 1)
586 resource
= tempresource
;
587 resourcesize
= sizeof(tempresource
);
591 * Grab the printer URI...
594 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
,
595 dest
->options
)) == NULL
)
597 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(ENOENT
), 0);
600 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
606 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
607 if (strstr(uri
, "._tcp"))
609 if ((uri
= cups_dnssd_resolve(dest
, uri
, msec
, cancel
, cb
,
613 #endif /* HAVE_DNSSD || HAVE_AVAHI */
615 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
616 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
617 &port
, resource
, (int)resourcesize
) < HTTP_URI_STATUS_OK
)
619 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer-uri."), 1);
622 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
629 * Lookup the address for the server...
633 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
,
636 snprintf(portstr
, sizeof(portstr
), "%d", port
);
638 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, portstr
)) == NULL
)
641 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
647 if (cancel
&& *cancel
)
649 httpAddrFreeList(addrlist
);
652 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CANCELED
,
659 * Create the HTTP object pointing to the server referenced by the URI...
662 if (!strcmp(scheme
, "ipps") || port
== 443)
663 encryption
= HTTP_ENCRYPTION_ALWAYS
;
665 encryption
= HTTP_ENCRYPTION_IF_REQUESTED
;
667 http
= httpConnect2(hostname
, port
, addrlist
, AF_UNSPEC
, encryption
, 1, 0,
669 httpAddrFreeList(addrlist
);
672 * Connect if requested...
675 if (flags
& CUPS_DEST_FLAGS_UNCONNECTED
)
678 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
, dest
);
683 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
,
686 if (!httpReconnect2(http
, msec
, cancel
) && cb
)
688 if (cancel
&& *cancel
)
690 CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
, dest
);
692 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
696 (*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, dest
);
705 * 'cupsConnectDestBlock()' - Connect to the server for a destination.
707 * Connect to the destination, returning a new http_t connection object and
708 * optionally the resource path to use for the destination. These calls will
709 * block until a connection is made, the timeout expires, the integer pointed
710 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
711 * The caller is responsible for calling httpClose() on the returned object.
713 * @since CUPS 1.6/OS X 10.8@
716 http_t
* /* O - Connection to server or @code NULL@ */
717 cupsConnectDestBlock(
718 cups_dest_t
*dest
, /* I - Destination */
719 unsigned flags
, /* I - Connection flags */
720 int msec
, /* I - Timeout in milliseconds */
721 int *cancel
, /* I - Pointer to "cancel" variable */
722 char *resource
, /* I - Resource buffer */
723 size_t resourcesize
, /* I - Size of resource buffer */
724 cups_dest_block_t block
) /* I - Callback block */
726 return (cupsConnectDest(dest
, flags
, msec
, cancel
, resource
, resourcesize
,
727 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
729 #endif /* __BLOCKS__ */
733 * 'cupsCopyDest()' - Copy a destination.
735 * Make a copy of the destination to an array of destinations (or just a single
736 * copy) - for use with the cupsEnumDests* functions. The caller is responsible
737 * for calling cupsFreeDests() on the returned object(s).
739 * @since CUPS 1.6/OS X 10.8@
743 cupsCopyDest(cups_dest_t
*dest
,
747 int i
; /* Looping var */
748 cups_dest_t
*new_dest
; /* New destination pointer */
749 cups_option_t
*new_option
, /* Current destination option */
750 *option
; /* Current parent option */
754 * Range check input...
757 if (!dest
|| num_dests
< 0 || !dests
)
761 * See if the destination already exists...
764 if ((new_dest
= cupsGetDest(dest
->name
, dest
->instance
, num_dests
,
768 * Protect against copying destination to itself...
771 if (new_dest
== dest
)
775 * Otherwise, free the options...
778 cupsFreeOptions(new_dest
->num_options
, new_dest
->options
);
780 new_dest
->num_options
= 0;
781 new_dest
->options
= NULL
;
784 new_dest
= cups_add_dest(dest
->name
, dest
->instance
, &num_dests
, dests
);
788 if ((new_dest
->options
= calloc(sizeof(cups_option_t
), (size_t)dest
->num_options
)) == NULL
)
789 return (cupsRemoveDest(dest
->name
, dest
->instance
, num_dests
, dests
));
791 new_dest
->num_options
= dest
->num_options
;
793 for (i
= dest
->num_options
, option
= dest
->options
,
794 new_option
= new_dest
->options
;
796 i
--, option
++, new_option
++)
798 new_option
->name
= _cupsStrRetain(option
->name
);
799 new_option
->value
= _cupsStrRetain(option
->value
);
808 * 'cupsEnumDests()' - Enumerate available destinations with a callback function.
810 * Destinations are enumerated from one or more sources. The callback function
811 * receives the @code user_data@ pointer, destination name, instance, number of
812 * options, and options which can be used as input to the @link cupsAddDest@
813 * function. The function must return 1 to continue enumeration or 0 to stop.
815 * Enumeration happens on the current thread and does not return until all
816 * destinations have been enumerated or the callback function returns 0.
818 * @since CUPS 1.6/OS X 10.8@
821 int /* O - 1 on success, 0 on failure */
823 unsigned flags
, /* I - Enumeration flags */
824 int msec
, /* I - Timeout in milliseconds,
825 * -1 for indefinite */
826 int *cancel
, /* I - Pointer to "cancel" variable */
827 cups_ptype_t type
, /* I - Printer type bits */
828 cups_ptype_t mask
, /* I - Mask for printer type bits */
829 cups_dest_cb_t cb
, /* I - Callback function */
830 void *user_data
) /* I - User data */
832 int i
, /* Looping var */
833 num_dests
; /* Number of destinations */
834 cups_dest_t
*dests
= NULL
, /* Destinations */
835 *dest
; /* Current destination */
836 const char *defprinter
; /* Default printer */
837 char name
[1024], /* Copy of printer name */
838 *instance
, /* Pointer to instance name */
839 *user_default
; /* User default printer */
840 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
841 int count
, /* Number of queries started */
842 remaining
; /* Remainder of timeout */
843 _cups_dnssd_data_t data
; /* Data for callback */
844 _cups_dnssd_device_t
*device
; /* Current device */
846 int nfds
, /* Number of files responded */
847 main_fd
; /* File descriptor for lookups */
848 DNSServiceRef ipp_ref
, /* IPP browser */
849 local_ipp_ref
; /* Local IPP browser */
851 DNSServiceRef ipps_ref
, /* IPPS browser */
852 local_ipps_ref
; /* Local IPPS browser */
853 # endif /* HAVE_SSL */
855 struct pollfd pfd
; /* Polling data */
857 fd_set input
; /* Input set for select() */
858 struct timeval timeout
; /* Timeout for select() */
859 # endif /* HAVE_POLL */
860 # else /* HAVE_AVAHI */
861 int error
; /* Error value */
862 AvahiServiceBrowser
*ipp_ref
; /* IPP browser */
864 AvahiServiceBrowser
*ipps_ref
; /* IPPS browser */
865 # endif /* HAVE_SSL */
866 # endif /* HAVE_DNSSD */
867 #endif /* HAVE_DNSSD || HAVE_AVAHI */
870 * Range check input...
879 * Get the list of local printers and pass them to the callback function...
882 num_dests
= _cupsGetDests(CUPS_HTTP_DEFAULT
, IPP_OP_CUPS_GET_PRINTERS
, NULL
,
883 &dests
, type
, mask
| CUPS_PRINTER_3D
);
885 if ((user_default
= _cupsUserDefault(name
, sizeof(name
))) != NULL
)
887 else if ((defprinter
= cupsGetDefault2(CUPS_HTTP_DEFAULT
)) != NULL
)
889 strlcpy(name
, defprinter
, sizeof(name
));
896 * Separate printer and instance name...
899 if ((instance
= strchr(name
, '/')) != NULL
)
903 * Lookup the printer and instance and make it the default...
906 if ((dest
= cupsGetDest(name
, instance
, num_dests
, dests
)) != NULL
)
907 dest
->is_default
= 1;
910 for (i
= num_dests
, dest
= dests
;
911 i
> 0 && (!cancel
|| !*cancel
);
913 if (!(*cb
)(user_data
, i
> 1 ? CUPS_DEST_FLAGS_MORE
: CUPS_DEST_FLAGS_NONE
,
917 cupsFreeDests(num_dests
, dests
);
919 if (i
> 0 || msec
== 0)
922 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
924 * Get Bonjour-shared printers...
930 data
.user_data
= user_data
;
931 data
.devices
= cupsArrayNew3((cups_array_func_t
)cups_dnssd_compare_devices
, NULL
, NULL
, 0, NULL
, (cups_afree_func_t
)cups_dnssd_free_device
);
934 if (DNSServiceCreateConnection(&data
.main_ref
) != kDNSServiceErr_NoError
)
937 main_fd
= DNSServiceRefSockFD(data
.main_ref
);
939 ipp_ref
= data
.main_ref
;
940 DNSServiceBrowse(&ipp_ref
, kDNSServiceFlagsShareConnection
, 0,
942 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
944 local_ipp_ref
= data
.main_ref
;
945 DNSServiceBrowse(&local_ipp_ref
, kDNSServiceFlagsShareConnection
,
946 kDNSServiceInterfaceIndexLocalOnly
,
948 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
951 ipps_ref
= data
.main_ref
;
952 DNSServiceBrowse(&ipps_ref
, kDNSServiceFlagsShareConnection
, 0,
954 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
956 local_ipps_ref
= data
.main_ref
;
957 DNSServiceBrowse(&local_ipps_ref
, kDNSServiceFlagsShareConnection
,
958 kDNSServiceInterfaceIndexLocalOnly
,
960 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
961 # endif /* HAVE_SSL */
963 # else /* HAVE_AVAHI */
964 if ((data
.simple_poll
= avahi_simple_poll_new()) == NULL
)
966 DEBUG_puts("cupsEnumDests: Unable to create Avahi simple poll object.");
970 avahi_simple_poll_set_func(data
.simple_poll
, cups_dnssd_poll_cb
, &data
);
972 data
.client
= avahi_client_new(avahi_simple_poll_get(data
.simple_poll
),
973 0, cups_dnssd_client_cb
, &data
,
977 DEBUG_puts("cupsEnumDests: Unable to create Avahi client.");
978 avahi_simple_poll_free(data
.simple_poll
);
982 ipp_ref
= avahi_service_browser_new(data
.client
, AVAHI_IF_UNSPEC
,
983 AVAHI_PROTO_UNSPEC
, "_ipp._tcp", NULL
,
984 0, cups_dnssd_browse_cb
, &data
);
986 ipps_ref
= avahi_service_browser_new(data
.client
, AVAHI_IF_UNSPEC
,
987 AVAHI_PROTO_UNSPEC
, "_ipps._tcp", NULL
,
988 0, cups_dnssd_browse_cb
, &data
);
989 # endif /* HAVE_SSL */
990 # endif /* HAVE_DNSSD */
997 while (remaining
> 0 && (!cancel
|| !*cancel
))
1000 * Check for input...
1006 pfd
.events
= POLLIN
;
1008 nfds
= poll(&pfd
, 1, remaining
> 250 ? 250 : remaining
);
1012 FD_SET(main_fd
, &input
);
1015 timeout
.tv_usec
= remaining
> 250 ? 250000 : remaining
* 1000;
1017 nfds
= select(main_fd
+ 1, &input
, NULL
, NULL
, &timeout
);
1018 # endif /* HAVE_POLL */
1021 DNSServiceProcessResult(data
.main_ref
);
1025 # else /* HAVE_AVAHI */
1028 if ((error
= avahi_simple_poll_iterate(data
.simple_poll
, 250)) > 0)
1031 * We've been told to exit the loop. Perhaps the connection to
1040 # endif /* HAVE_DNSSD */
1042 for (device
= (_cups_dnssd_device_t
*)cupsArrayFirst(data
.devices
),
1045 device
= (_cups_dnssd_device_t
*)cupsArrayNext(data
.devices
))
1050 if (!device
->ref
&& device
->state
== _CUPS_DNSSD_NEW
)
1052 DEBUG_printf(("1cupsEnumDests: Querying '%s'.", device
->fullName
));
1055 device
->ref
= data
.main_ref
;
1057 if (DNSServiceQueryRecord(&(device
->ref
),
1058 kDNSServiceFlagsShareConnection
,
1059 0, device
->fullName
,
1060 kDNSServiceType_TXT
,
1061 kDNSServiceClass_IN
,
1062 (DNSServiceQueryRecordReply
)cups_dnssd_query_cb
,
1063 &data
) == kDNSServiceErr_NoError
)
1070 device
->state
= _CUPS_DNSSD_ERROR
;
1072 DEBUG_puts("1cupsEnumDests: Query failed.");
1075 # else /* HAVE_AVAHI */
1076 if ((device
->ref
= avahi_record_browser_new(data
.client
,
1083 cups_dnssd_query_cb
,
1090 device
->state
= _CUPS_DNSSD_ERROR
;
1092 DEBUG_printf(("1cupsEnumDests: Query failed: %s",
1093 avahi_strerror(avahi_client_errno(data
.client
))));
1095 # endif /* HAVE_DNSSD */
1097 else if (device
->ref
&& device
->state
== _CUPS_DNSSD_PENDING
)
1099 if ((device
->type
& mask
) == type
)
1101 if (!(*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, &device
->dest
))
1108 device
->state
= _CUPS_DNSSD_ACTIVE
;
1113 cupsArrayDelete(data
.devices
);
1116 DNSServiceRefDeallocate(ipp_ref
);
1117 DNSServiceRefDeallocate(local_ipp_ref
);
1120 DNSServiceRefDeallocate(ipp_ref
);
1121 DNSServiceRefDeallocate(local_ipp_ref
);
1122 # endif /* HAVE_SSL */
1124 DNSServiceRefDeallocate(data
.main_ref
);
1126 # else /* HAVE_AVAHI */
1127 avahi_service_browser_free(ipp_ref
);
1129 avahi_service_browser_free(ipps_ref
);
1130 # endif /* HAVE_SSL */
1132 avahi_client_free(data
.client
);
1133 avahi_simple_poll_free(data
.simple_poll
);
1134 # endif /* HAVE_DNSSD */
1135 #endif /* HAVE_DNSSD || HAVE_DNSSD */
1143 * 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
1145 * Destinations are enumerated from one or more sources. The block receives the
1146 * destination name, instance, number of options, and options which can be used
1147 * as input to the @link cupsAddDest@ function. The block must return 1 to
1148 * continue enumeration or 0 to stop.
1150 * Enumeration happens on the current thread and does not return until all
1151 * destinations have been enumerated or the block returns 0.
1153 * @since CUPS 1.6/OS X 10.8@
1156 int /* O - 1 on success, 0 on failure */
1158 unsigned flags
, /* I - Enumeration flags */
1159 int timeout
, /* I - Timeout in milliseconds, 0 for indefinite */
1160 int *cancel
, /* I - Pointer to "cancel" variable */
1161 cups_ptype_t type
, /* I - Printer type bits */
1162 cups_ptype_t mask
, /* I - Mask for printer type bits */
1163 cups_dest_block_t block
) /* I - Block */
1165 return (cupsEnumDests(flags
, timeout
, cancel
, type
, mask
,
1166 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
1168 # endif /* __BLOCKS__ */
1172 * 'cupsFreeDests()' - Free the memory used by the list of destinations.
1176 cupsFreeDests(int num_dests
, /* I - Number of destinations */
1177 cups_dest_t
*dests
) /* I - Destinations */
1179 int i
; /* Looping var */
1180 cups_dest_t
*dest
; /* Current destination */
1183 if (num_dests
== 0 || dests
== NULL
)
1186 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1188 _cupsStrFree(dest
->name
);
1189 _cupsStrFree(dest
->instance
);
1191 cupsFreeOptions(dest
->num_options
, dest
->options
);
1199 * 'cupsGetDest()' - Get the named destination from the list.
1201 * Use the @link cupsGetDests@ or @link cupsGetDests2@ functions to get a
1202 * list of supported destinations for the current user.
1205 cups_dest_t
* /* O - Destination pointer or @code NULL@ */
1206 cupsGetDest(const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1207 const char *instance
, /* I - Instance name or @code NULL@ */
1208 int num_dests
, /* I - Number of destinations */
1209 cups_dest_t
*dests
) /* I - Destinations */
1211 int diff
, /* Result of comparison */
1212 match
; /* Matching index */
1215 if (num_dests
<= 0 || !dests
)
1221 * NULL name for default printer.
1224 while (num_dests
> 0)
1226 if (dests
->is_default
)
1236 * Lookup name and optionally the instance...
1239 match
= cups_find_dest(name
, instance
, num_dests
, dests
, -1, &diff
);
1242 return (dests
+ match
);
1250 * '_cupsGetDestResource()' - Get the resource path and URI for a destination.
1253 const char * /* O - Printer URI */
1254 _cupsGetDestResource(
1255 cups_dest_t
*dest
, /* I - Destination */
1256 char *resource
, /* I - Resource buffer */
1257 size_t resourcesize
) /* I - Size of resource buffer */
1259 const char *uri
; /* Printer URI */
1260 char scheme
[32], /* URI scheme */
1261 userpass
[256], /* Username and password (unused) */
1262 hostname
[256]; /* Hostname */
1263 int port
; /* Port number */
1267 * Range check input...
1270 if (!dest
|| !resource
|| resourcesize
< 1)
1275 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
1280 * Grab the printer URI...
1283 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
,
1284 dest
->options
)) == NULL
)
1289 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(ENOENT
), 0);
1295 if (strstr(uri
, "._tcp"))
1297 if ((uri
= cups_dnssd_resolve(dest
, uri
, 5000, NULL
, NULL
, NULL
)) == NULL
)
1300 #endif /* HAVE_DNSSD */
1302 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
1303 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
1304 &port
, resource
, (int)resourcesize
) < HTTP_URI_STATUS_OK
)
1306 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer-uri."), 1);
1316 * 'cupsGetDestWithURI()' - Get a destination associated with a URI.
1318 * "name" is the desired name for the printer. If @code NULL@, a name will be
1319 * created using the URI.
1321 * "uri" is the "ipp" or "ipps" URI for the printer.
1323 * @since CUPS 2.0/OS X 10.10@
1326 cups_dest_t
* /* O - Destination or @code NULL@ */
1327 cupsGetDestWithURI(const char *name
, /* I - Desired printer name or @code NULL@ */
1328 const char *uri
) /* I - URI for the printer */
1330 cups_dest_t
*dest
; /* New destination */
1331 char temp
[1024], /* Temporary string */
1332 scheme
[256], /* Scheme from URI */
1333 userpass
[256], /* Username:password from URI */
1334 hostname
[256], /* Hostname from URI */
1335 resource
[1024], /* Resource path from URI */
1336 *ptr
; /* Pointer into string */
1337 int port
; /* Port number from URI */
1341 * Range check input...
1346 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
1350 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
), userpass
, sizeof(userpass
), hostname
, sizeof(hostname
), &port
, resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
||
1351 (strncmp(uri
, "ipp://", 6) && strncmp(uri
, "ipps://", 7)))
1353 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer-uri."), 1);
1361 * Create the name from the URI...
1364 if (strstr(hostname
, "._tcp"))
1367 * Use the service instance name...
1370 if ((ptr
= strchr(hostname
, '.')) != NULL
)
1375 else if (!strncmp(resource
, "/classes/", 9))
1377 snprintf(temp
, sizeof(temp
), "%s @ %s", resource
+ 9, hostname
);
1380 else if (!strncmp(resource
, "/printers/", 10))
1382 snprintf(temp
, sizeof(temp
), "%s @ %s", resource
+ 10, hostname
);
1392 * Create the destination...
1395 if ((dest
= calloc(1, sizeof(cups_dest_t
))) == NULL
)
1397 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
1401 dest
->name
= _cupsStrAlloc(name
);
1402 dest
->num_options
= cupsAddOption("printer-uri-supported", uri
, dest
->num_options
, &(dest
->options
));
1403 dest
->num_options
= cupsAddOption("printer-info", name
, dest
->num_options
, &(dest
->options
));
1410 * '_cupsGetDests()' - Get destinations from a server.
1412 * "op" is IPP_OP_CUPS_GET_PRINTERS to get a full list, IPP_OP_CUPS_GET_DEFAULT
1413 * to get the system-wide default printer, or IPP_OP_GET_PRINTER_ATTRIBUTES for
1416 * "name" is the name of an existing printer and is only used when "op" is
1417 * IPP_OP_GET_PRINTER_ATTRIBUTES.
1419 * "dest" is initialized to point to the array of destinations.
1421 * 0 is returned if there are no printers, no default printer, or the named
1422 * printer does not exist, respectively.
1424 * Free the memory used by the destination array using the @link cupsFreeDests@
1427 * Note: On OS X this function also gets the default paper from the system
1428 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1429 * options array for each destination that supports it.
1432 int /* O - Number of destinations */
1433 _cupsGetDests(http_t
*http
, /* I - Connection to server or
1434 * @code CUPS_HTTP_DEFAULT@ */
1435 ipp_op_t op
, /* I - IPP operation */
1436 const char *name
, /* I - Name of destination */
1437 cups_dest_t
**dests
, /* IO - Destinations */
1438 cups_ptype_t type
, /* I - Printer type bits */
1439 cups_ptype_t mask
) /* I - Printer type mask */
1441 int num_dests
= 0; /* Number of destinations */
1442 cups_dest_t
*dest
; /* Current destination */
1443 ipp_t
*request
, /* IPP Request */
1444 *response
; /* IPP Response */
1445 ipp_attribute_t
*attr
; /* Current attribute */
1446 const char *printer_name
; /* printer-name attribute */
1447 char uri
[1024]; /* printer-uri value */
1448 int num_options
; /* Number of options */
1449 cups_option_t
*options
; /* Options */
1451 char media_default
[41]; /* Default paper size */
1452 #endif /* __APPLE__ */
1453 char optname
[1024], /* Option name */
1454 value
[2048], /* Option value */
1455 *ptr
; /* Pointer into name/value */
1456 static const char * const pattrs
[] = /* Attributes we're interested in */
1458 "auth-info-required",
1460 "job-sheets-default",
1461 "marker-change-time",
1463 "marker-high-levels",
1465 "marker-low-levels",
1471 #endif /* __APPLE__ */
1475 "printer-is-accepting-jobs",
1476 "printer-is-shared",
1478 "printer-make-and-model",
1479 "printer-mandatory-job-attributes",
1482 "printer-state-change-time",
1483 "printer-state-reasons",
1485 "printer-uri-supported"
1491 * Get the default paper size...
1494 appleGetPaperSize(media_default
, sizeof(media_default
));
1495 #endif /* __APPLE__ */
1498 * Build a IPP_OP_CUPS_GET_PRINTERS or IPP_OP_GET_PRINTER_ATTRIBUTES request, which
1499 * require the following attributes:
1501 * attributes-charset
1502 * attributes-natural-language
1503 * requesting-user-name
1504 * printer-uri [for IPP_OP_GET_PRINTER_ATTRIBUTES]
1507 request
= ippNewRequest(op
);
1509 ippAddStrings(request
, IPP_TAG_OPERATION
, IPP_TAG_KEYWORD
,
1510 "requested-attributes", sizeof(pattrs
) / sizeof(pattrs
[0]),
1513 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
,
1514 "requesting-user-name", NULL
, cupsUser());
1516 if (name
&& op
!= IPP_OP_CUPS_GET_DEFAULT
)
1518 httpAssembleURIf(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
), "ipp", NULL
,
1519 "localhost", ippPort(), "/printers/%s", name
);
1520 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
,
1525 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type", (int)type
);
1526 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type-mask", (int)mask
);
1530 * Do the request and get back a response...
1533 if ((response
= cupsDoRequest(http
, request
, "/")) != NULL
)
1535 for (attr
= response
->attrs
; attr
!= NULL
; attr
= attr
->next
)
1538 * Skip leading attributes until we hit a printer...
1541 while (attr
!= NULL
&& attr
->group_tag
!= IPP_TAG_PRINTER
)
1548 * Pull the needed attributes from this printer...
1551 printer_name
= NULL
;
1555 for (; attr
&& attr
->group_tag
== IPP_TAG_PRINTER
; attr
= attr
->next
)
1557 if (attr
->value_tag
!= IPP_TAG_INTEGER
&&
1558 attr
->value_tag
!= IPP_TAG_ENUM
&&
1559 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
1560 attr
->value_tag
!= IPP_TAG_TEXT
&&
1561 attr
->value_tag
!= IPP_TAG_TEXTLANG
&&
1562 attr
->value_tag
!= IPP_TAG_NAME
&&
1563 attr
->value_tag
!= IPP_TAG_NAMELANG
&&
1564 attr
->value_tag
!= IPP_TAG_KEYWORD
&&
1565 attr
->value_tag
!= IPP_TAG_RANGE
&&
1566 attr
->value_tag
!= IPP_TAG_URI
)
1569 if (!strcmp(attr
->name
, "auth-info-required") ||
1570 !strcmp(attr
->name
, "device-uri") ||
1571 !strcmp(attr
->name
, "marker-change-time") ||
1572 !strcmp(attr
->name
, "marker-colors") ||
1573 !strcmp(attr
->name
, "marker-high-levels") ||
1574 !strcmp(attr
->name
, "marker-levels") ||
1575 !strcmp(attr
->name
, "marker-low-levels") ||
1576 !strcmp(attr
->name
, "marker-message") ||
1577 !strcmp(attr
->name
, "marker-names") ||
1578 !strcmp(attr
->name
, "marker-types") ||
1579 !strcmp(attr
->name
, "printer-commands") ||
1580 !strcmp(attr
->name
, "printer-info") ||
1581 !strcmp(attr
->name
, "printer-is-shared") ||
1582 !strcmp(attr
->name
, "printer-make-and-model") ||
1583 !strcmp(attr
->name
, "printer-mandatory-job-attributes") ||
1584 !strcmp(attr
->name
, "printer-state") ||
1585 !strcmp(attr
->name
, "printer-state-change-time") ||
1586 !strcmp(attr
->name
, "printer-type") ||
1587 !strcmp(attr
->name
, "printer-is-accepting-jobs") ||
1588 !strcmp(attr
->name
, "printer-location") ||
1589 !strcmp(attr
->name
, "printer-state-reasons") ||
1590 !strcmp(attr
->name
, "printer-uri-supported"))
1593 * Add a printer description attribute...
1596 num_options
= cupsAddOption(attr
->name
,
1597 cups_make_string(attr
, value
,
1599 num_options
, &options
);
1602 else if (!strcmp(attr
->name
, "media-supported"))
1605 * See if we can set a default media size...
1608 int i
; /* Looping var */
1610 for (i
= 0; i
< attr
->num_values
; i
++)
1611 if (!_cups_strcasecmp(media_default
, attr
->values
[i
].string
.text
))
1613 num_options
= cupsAddOption("media", media_default
, num_options
,
1618 #endif /* __APPLE__ */
1619 else if (!strcmp(attr
->name
, "printer-name") &&
1620 attr
->value_tag
== IPP_TAG_NAME
)
1621 printer_name
= attr
->values
[0].string
.text
;
1622 else if (strncmp(attr
->name
, "notify-", 7) &&
1623 (attr
->value_tag
== IPP_TAG_BOOLEAN
||
1624 attr
->value_tag
== IPP_TAG_ENUM
||
1625 attr
->value_tag
== IPP_TAG_INTEGER
||
1626 attr
->value_tag
== IPP_TAG_KEYWORD
||
1627 attr
->value_tag
== IPP_TAG_NAME
||
1628 attr
->value_tag
== IPP_TAG_RANGE
) &&
1629 (ptr
= strstr(attr
->name
, "-default")) != NULL
)
1632 * Add a default option...
1635 strlcpy(optname
, attr
->name
, sizeof(optname
));
1636 optname
[ptr
- attr
->name
] = '\0';
1638 if (_cups_strcasecmp(optname
, "media") ||
1639 !cupsGetOption("media", num_options
, options
))
1640 num_options
= cupsAddOption(optname
,
1641 cups_make_string(attr
, value
,
1643 num_options
, &options
);
1648 * See if we have everything needed...
1653 cupsFreeOptions(num_options
, options
);
1661 if ((dest
= cups_add_dest(printer_name
, NULL
, &num_dests
, dests
)) != NULL
)
1663 dest
->num_options
= num_options
;
1664 dest
->options
= options
;
1667 cupsFreeOptions(num_options
, options
);
1673 ippDelete(response
);
1677 * Return the count...
1685 * 'cupsGetDests()' - Get the list of destinations from the default server.
1687 * Starting with CUPS 1.2, the returned list of destinations include the
1688 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1689 * printer-make-and-model, printer-state, printer-state-change-time,
1690 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1691 * adds the marker-change-time, marker-colors, marker-high-levels,
1692 * marker-levels, marker-low-levels, marker-message, marker-names,
1693 * marker-types, and printer-commands attributes as well.
1695 * Use the @link cupsFreeDests@ function to free the destination list and
1696 * the @link cupsGetDest@ function to find a particular destination.
1699 int /* O - Number of destinations */
1700 cupsGetDests(cups_dest_t
**dests
) /* O - Destinations */
1702 return (cupsGetDests2(CUPS_HTTP_DEFAULT
, dests
));
1707 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1709 * Starting with CUPS 1.2, the returned list of destinations include the
1710 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1711 * printer-make-and-model, printer-state, printer-state-change-time,
1712 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1713 * adds the marker-change-time, marker-colors, marker-high-levels,
1714 * marker-levels, marker-low-levels, marker-message, marker-names,
1715 * marker-types, and printer-commands attributes as well.
1717 * Use the @link cupsFreeDests@ function to free the destination list and
1718 * the @link cupsGetDest@ function to find a particular destination.
1720 * @since CUPS 1.1.21/OS X 10.4@
1723 int /* O - Number of destinations */
1724 cupsGetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1725 cups_dest_t
**dests
) /* O - Destinations */
1727 int num_dests
; /* Number of destinations */
1728 cups_dest_t
*dest
; /* Destination pointer */
1729 const char *home
; /* HOME environment variable */
1730 char filename
[1024]; /* Local ~/.cups/lpoptions file */
1731 const char *defprinter
; /* Default printer */
1732 char name
[1024], /* Copy of printer name */
1733 *instance
, /* Pointer to instance name */
1734 *user_default
; /* User default printer */
1735 int num_reals
; /* Number of real queues */
1736 cups_dest_t
*reals
; /* Real queues */
1737 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1741 * Range check the input...
1746 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad NULL dests pointer"), 1);
1751 * Grab the printers and classes...
1754 *dests
= (cups_dest_t
*)0;
1755 num_dests
= _cupsGetDests(http
, IPP_OP_CUPS_GET_PRINTERS
, NULL
, dests
, 0, CUPS_PRINTER_3D
);
1757 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE
)
1759 cupsFreeDests(num_dests
, *dests
);
1760 *dests
= (cups_dest_t
*)0;
1765 * Make a copy of the "real" queues for a later sanity check...
1770 num_reals
= num_dests
;
1771 reals
= calloc((size_t)num_reals
, sizeof(cups_dest_t
));
1774 memcpy(reals
, *dests
, (size_t)num_reals
* sizeof(cups_dest_t
));
1785 * Grab the default destination...
1788 if ((user_default
= _cupsUserDefault(name
, sizeof(name
))) != NULL
)
1790 else if ((defprinter
= cupsGetDefault2(http
)) != NULL
)
1792 strlcpy(name
, defprinter
, sizeof(name
));
1799 * Separate printer and instance name...
1802 if ((instance
= strchr(name
, '/')) != NULL
)
1806 * Lookup the printer and instance and make it the default...
1809 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) != NULL
)
1810 dest
->is_default
= 1;
1816 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
1819 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1820 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1823 if ((home
= getenv("HOME")) != NULL
)
1825 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1827 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1832 * Validate the current default destination - this prevents old
1833 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
1834 * pointing to a non-existent printer or class...
1840 * See if we have a default printer...
1843 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, *dests
)) != NULL
)
1846 * Have a default; see if it is real...
1849 if (!cupsGetDest(dest
->name
, NULL
, num_reals
, reals
))
1852 * Remove the non-real printer from the list, since we don't want jobs
1853 * going to an unexpected printer... (<rdar://problem/14216472>)
1856 num_dests
= cupsRemoveDest(dest
->name
, dest
->instance
, num_dests
,
1869 * Return the number of destinations...
1873 _cupsSetError(IPP_STATUS_OK
, NULL
, 0);
1880 * 'cupsGetNamedDest()' - Get options for the named destination.
1882 * This function is optimized for retrieving a single destination and should
1883 * be used instead of @link cupsGetDests@ and @link cupsGetDest@ when you either
1884 * know the name of the destination or want to print to the default destination.
1885 * If @code NULL@ is returned, the destination does not exist or there is no
1886 * default destination.
1888 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
1889 * server will be used.
1891 * If "name" is @code NULL@, the default printer for the current user will be
1894 * The returned destination must be freed using @link cupsFreeDests@ with a
1895 * "num_dests" value of 1.
1897 * @since CUPS 1.4/OS X 10.6@
1900 cups_dest_t
* /* O - Destination or @code NULL@ */
1901 cupsGetNamedDest(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1902 const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1903 const char *instance
) /* I - Instance name or @code NULL@ */
1905 cups_dest_t
*dest
; /* Destination */
1906 char filename
[1024], /* Path to lpoptions */
1907 defname
[256]; /* Default printer name */
1908 const char *home
= getenv("HOME"); /* Home directory */
1909 int set_as_default
= 0; /* Set returned destination as default */
1910 ipp_op_t op
= IPP_OP_GET_PRINTER_ATTRIBUTES
;
1911 /* IPP operation to get server ops */
1912 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1916 * If "name" is NULL, find the default destination...
1922 name
= _cupsUserDefault(defname
, sizeof(defname
));
1926 char *ptr
; /* Temporary pointer... */
1928 if ((ptr
= strchr(defname
, '/')) != NULL
)
1939 * No default in the environment, try the user's lpoptions files...
1942 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1944 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1950 * Still not there? Try the system lpoptions file...
1953 snprintf(filename
, sizeof(filename
), "%s/lpoptions",
1954 cg
->cups_serverroot
);
1955 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1961 * No locally-set default destination, ask the server...
1964 op
= IPP_OP_CUPS_GET_DEFAULT
;
1969 * Get the printer's attributes...
1972 if (!_cupsGetDests(http
, op
, name
, &dest
, 0, CUPS_PRINTER_3D
))
1976 dest
->instance
= _cupsStrAlloc(instance
);
1979 dest
->is_default
= 1;
1982 * Then add local options...
1985 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1986 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
1990 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1992 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
1996 * Return the result...
2004 * 'cupsRemoveDest()' - Remove a destination from the destination list.
2006 * Removing a destination/instance does not delete the class or printer
2007 * queue, merely the lpoptions for that destination/instance. Use the
2008 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
2009 * options for the user.
2011 * @since CUPS 1.3/OS X 10.5@
2014 int /* O - New number of destinations */
2015 cupsRemoveDest(const char *name
, /* I - Destination name */
2016 const char *instance
, /* I - Instance name or @code NULL@ */
2017 int num_dests
, /* I - Number of destinations */
2018 cups_dest_t
**dests
) /* IO - Destinations */
2020 int i
; /* Index into destinations */
2021 cups_dest_t
*dest
; /* Pointer to destination */
2025 * Find the destination...
2028 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
2035 _cupsStrFree(dest
->name
);
2036 _cupsStrFree(dest
->instance
);
2037 cupsFreeOptions(dest
->num_options
, dest
->options
);
2040 * Remove the destination from the array...
2045 i
= (int)(dest
- *dests
);
2048 memmove(dest
, dest
+ 1, (size_t)(num_dests
- i
) * sizeof(cups_dest_t
));
2055 * 'cupsSetDefaultDest()' - Set the default destination.
2057 * @since CUPS 1.3/OS X 10.5@
2062 const char *name
, /* I - Destination name */
2063 const char *instance
, /* I - Instance name or @code NULL@ */
2064 int num_dests
, /* I - Number of destinations */
2065 cups_dest_t
*dests
) /* I - Destinations */
2067 int i
; /* Looping var */
2068 cups_dest_t
*dest
; /* Current destination */
2072 * Range check input...
2075 if (!name
|| num_dests
<= 0 || !dests
)
2079 * Loop through the array and set the "is_default" flag for the matching
2083 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
2084 dest
->is_default
= !_cups_strcasecmp(name
, dest
->name
) &&
2085 ((!instance
&& !dest
->instance
) ||
2086 (instance
&& dest
->instance
&&
2087 !_cups_strcasecmp(instance
, dest
->instance
)));
2092 * 'cupsSetDests()' - Save the list of destinations for the default server.
2094 * This function saves the destinations to /etc/cups/lpoptions when run
2095 * as root and ~/.cups/lpoptions when run as a normal user.
2099 cupsSetDests(int num_dests
, /* I - Number of destinations */
2100 cups_dest_t
*dests
) /* I - Destinations */
2102 cupsSetDests2(CUPS_HTTP_DEFAULT
, num_dests
, dests
);
2107 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
2109 * This function saves the destinations to /etc/cups/lpoptions when run
2110 * as root and ~/.cups/lpoptions when run as a normal user.
2112 * @since CUPS 1.1.21/OS X 10.4@
2115 int /* O - 0 on success, -1 on error */
2116 cupsSetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2117 int num_dests
, /* I - Number of destinations */
2118 cups_dest_t
*dests
) /* I - Destinations */
2120 int i
, j
; /* Looping vars */
2121 int wrote
; /* Wrote definition? */
2122 cups_dest_t
*dest
; /* Current destination */
2123 cups_option_t
*option
; /* Current option */
2124 _ipp_option_t
*match
; /* Matching attribute for option */
2125 FILE *fp
; /* File pointer */
2127 const char *home
; /* HOME environment variable */
2129 char filename
[1024]; /* lpoptions file */
2130 int num_temps
; /* Number of temporary destinations */
2131 cups_dest_t
*temps
= NULL
, /* Temporary destinations */
2132 *temp
; /* Current temporary dest */
2133 const char *val
; /* Value of temporary option */
2134 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
2138 * Range check the input...
2141 if (!num_dests
|| !dests
)
2145 * Get the server destinations...
2148 num_temps
= _cupsGetDests(http
, IPP_OP_CUPS_GET_PRINTERS
, NULL
, &temps
, 0, CUPS_PRINTER_3D
);
2150 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE
)
2152 cupsFreeDests(num_temps
, temps
);
2157 * Figure out which file to write to...
2160 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
2166 * Merge in server defaults...
2169 num_temps
= cups_get_dests(filename
, NULL
, NULL
, 0, num_temps
, &temps
);
2172 * Point to user defaults...
2175 if ((home
= getenv("HOME")) != NULL
)
2178 * Create ~/.cups subdirectory...
2181 snprintf(filename
, sizeof(filename
), "%s/.cups", home
);
2182 if (access(filename
, 0))
2183 mkdir(filename
, 0700);
2185 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
2191 * Try to open the file...
2194 if ((fp
= fopen(filename
, "w")) == NULL
)
2196 cupsFreeDests(num_temps
, temps
);
2202 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2207 fchmod(fileno(fp
), 0644);
2211 * Write each printer; each line looks like:
2213 * Dest name[/instance] options
2214 * Default name[/instance] options
2217 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
2218 if (dest
->instance
!= NULL
|| dest
->num_options
!= 0 || dest
->is_default
)
2220 if (dest
->is_default
)
2222 fprintf(fp
, "Default %s", dest
->name
);
2224 fprintf(fp
, "/%s", dest
->instance
);
2231 if ((temp
= cupsGetDest(dest
->name
, dest
->instance
, num_temps
, temps
)) == NULL
)
2232 temp
= cupsGetDest(dest
->name
, NULL
, num_temps
, temps
);
2234 for (j
= dest
->num_options
, option
= dest
->options
; j
> 0; j
--, option
++)
2237 * See if this option is a printer attribute; if so, skip it...
2240 if ((match
= _ippFindOption(option
->name
)) != NULL
&&
2241 match
->group_tag
== IPP_TAG_PRINTER
)
2245 * See if the server/global options match these; if so, don't
2250 (val
= cupsGetOption(option
->name
, temp
->num_options
,
2251 temp
->options
)) != NULL
&&
2252 !_cups_strcasecmp(val
, option
->value
))
2256 * Options don't match, write to the file...
2261 fprintf(fp
, "Dest %s", dest
->name
);
2263 fprintf(fp
, "/%s", dest
->instance
);
2267 if (option
->value
[0])
2269 if (strchr(option
->value
, ' ') ||
2270 strchr(option
->value
, '\\') ||
2271 strchr(option
->value
, '\"') ||
2272 strchr(option
->value
, '\''))
2275 * Quote the value...
2278 fprintf(fp
, " %s=\"", option
->name
);
2280 for (val
= option
->value
; *val
; val
++)
2282 if (strchr("\"\'\\", *val
))
2293 * Store the literal value...
2296 fprintf(fp
, " %s=%s", option
->name
, option
->value
);
2300 fprintf(fp
, " %s", option
->name
);
2308 * Free the temporary destinations and close the file...
2311 cupsFreeDests(num_temps
, temps
);
2317 * Set the default printer for this location - this allows command-line
2318 * and GUI applications to share the same default destination...
2321 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, dests
)) != NULL
)
2323 CFStringRef name
= CFStringCreateWithCString(kCFAllocatorDefault
,
2325 kCFStringEncodingUTF8
);
2326 /* Default printer name */
2330 _cupsAppleSetDefaultPrinter(name
);
2334 #endif /* __APPLE__ */
2336 #ifdef HAVE_NOTIFY_POST
2338 * Send a notification so that MacOS X applications can know about the
2342 notify_post("com.apple.printerListChange");
2343 #endif /* HAVE_NOTIFY_POST */
2350 * '_cupsUserDefault()' - Get the user default printer from environment
2351 * variables and location information.
2354 char * /* O - Default printer or NULL */
2355 _cupsUserDefault(char *name
, /* I - Name buffer */
2356 size_t namesize
) /* I - Size of name buffer */
2358 const char *env
; /* LPDEST or PRINTER env variable */
2360 CFStringRef locprinter
; /* Last printer as this location */
2361 #endif /* __APPLE__ */
2364 if ((env
= getenv("LPDEST")) == NULL
)
2365 if ((env
= getenv("PRINTER")) != NULL
&& !strcmp(env
, "lp"))
2370 strlcpy(name
, env
, namesize
);
2376 * Use location-based defaults if "use last printer" is selected in the
2377 * system preferences...
2380 if ((locprinter
= _cupsAppleCopyDefaultPrinter()) != NULL
)
2382 CFStringGetCString(locprinter
, name
, (CFIndex
)namesize
, kCFStringEncodingUTF8
);
2383 CFRelease(locprinter
);
2388 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name
));
2390 return (*name
? name
: NULL
);
2394 * No location-based defaults on this platform...
2399 #endif /* __APPLE__ */
2405 * 'appleCopyLocations()' - Copy the location history array.
2408 static CFArrayRef
/* O - Location array or NULL */
2409 appleCopyLocations(void)
2411 CFArrayRef locations
; /* Location array */
2415 * Look up the location array in the preferences...
2418 if ((locations
= CFPreferencesCopyAppValue(kLastUsedPrintersKey
,
2419 kCUPSPrintingPrefs
)) == NULL
)
2422 if (CFGetTypeID(locations
) != CFArrayGetTypeID())
2424 CFRelease(locations
);
2433 * 'appleCopyNetwork()' - Get the network ID for the current location.
2436 static CFStringRef
/* O - Network ID */
2437 appleCopyNetwork(void)
2439 SCDynamicStoreRef dynamicStore
; /* System configuration data */
2440 CFStringRef key
; /* Current network configuration key */
2441 CFDictionaryRef ip_dict
; /* Network configuration data */
2442 CFStringRef network
= NULL
; /* Current network ID */
2445 if ((dynamicStore
= SCDynamicStoreCreate(NULL
, CFSTR("libcups"), NULL
,
2449 * First use the IPv6 router address, if available, since that will generally
2450 * be a globally-unique link-local address.
2453 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2454 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv6
)) != NULL
)
2456 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2458 if ((network
= CFDictionaryGetValue(ip_dict
,
2459 kSCPropNetIPv6Router
)) != NULL
)
2469 * If that doesn't work, try the IPv4 router address. This isn't as unique
2470 * and will likely be a 10.x.y.z or 192.168.y.z address...
2475 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2476 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv4
)) != NULL
)
2478 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2480 if ((network
= CFDictionaryGetValue(ip_dict
,
2481 kSCPropNetIPv4Router
)) != NULL
)
2491 CFRelease(dynamicStore
);
2499 * 'appleGetPaperSize()' - Get the default paper size.
2502 static char * /* O - Default paper size */
2503 appleGetPaperSize(char *name
, /* I - Paper size name buffer */
2504 size_t namesize
) /* I - Size of buffer */
2506 CFStringRef defaultPaperID
; /* Default paper ID */
2507 pwg_media_t
*pwgmedia
; /* PWG media size */
2510 defaultPaperID
= _cupsAppleCopyDefaultPaperID();
2511 if (!defaultPaperID
||
2512 CFGetTypeID(defaultPaperID
) != CFStringGetTypeID() ||
2513 !CFStringGetCString(defaultPaperID
, name
, (CFIndex
)namesize
, kCFStringEncodingUTF8
))
2515 else if ((pwgmedia
= pwgMediaForLegacy(name
)) != NULL
)
2516 strlcpy(name
, pwgmedia
->pwg
, namesize
);
2519 CFRelease(defaultPaperID
);
2526 * 'appleGetPrinter()' - Get a printer from the history array.
2529 static CFStringRef
/* O - Printer name or NULL */
2530 appleGetPrinter(CFArrayRef locations
, /* I - Location array */
2531 CFStringRef network
, /* I - Network name */
2532 CFIndex
*locindex
) /* O - Index in array */
2534 CFIndex i
, /* Looping var */
2535 count
; /* Number of locations */
2536 CFDictionaryRef location
; /* Current location */
2537 CFStringRef locnetwork
, /* Current network */
2538 locprinter
; /* Current printer */
2541 for (i
= 0, count
= CFArrayGetCount(locations
); i
< count
; i
++)
2542 if ((location
= CFArrayGetValueAtIndex(locations
, i
)) != NULL
&&
2543 CFGetTypeID(location
) == CFDictionaryGetTypeID())
2545 if ((locnetwork
= CFDictionaryGetValue(location
,
2546 kLocationNetworkKey
)) != NULL
&&
2547 CFGetTypeID(locnetwork
) == CFStringGetTypeID() &&
2548 CFStringCompare(network
, locnetwork
, 0) == kCFCompareEqualTo
&&
2549 (locprinter
= CFDictionaryGetValue(location
,
2550 kLocationPrinterIDKey
)) != NULL
&&
2551 CFGetTypeID(locprinter
) == CFStringGetTypeID())
2556 return (locprinter
);
2562 #endif /* __APPLE__ */
2566 * 'cups_add_dest()' - Add a destination to the array.
2568 * Unlike cupsAddDest(), this function does not check for duplicates.
2571 static cups_dest_t
* /* O - New destination */
2572 cups_add_dest(const char *name
, /* I - Name of destination */
2573 const char *instance
, /* I - Instance or NULL */
2574 int *num_dests
, /* IO - Number of destinations */
2575 cups_dest_t
**dests
) /* IO - Destinations */
2577 int insert
, /* Insertion point */
2578 diff
; /* Result of comparison */
2579 cups_dest_t
*dest
; /* Destination pointer */
2583 * Add new destination...
2586 if (*num_dests
== 0)
2587 dest
= malloc(sizeof(cups_dest_t
));
2589 dest
= realloc(*dests
, sizeof(cups_dest_t
) * (size_t)(*num_dests
+ 1));
2597 * Find where to insert the destination...
2600 if (*num_dests
== 0)
2604 insert
= cups_find_dest(name
, instance
, *num_dests
, *dests
, *num_dests
- 1,
2612 * Move the array elements as needed...
2615 if (insert
< *num_dests
)
2616 memmove(*dests
+ insert
+ 1, *dests
+ insert
, (size_t)(*num_dests
- insert
) * sizeof(cups_dest_t
));
2621 * Initialize the destination...
2624 dest
= *dests
+ insert
;
2625 dest
->name
= _cupsStrAlloc(name
);
2626 dest
->instance
= _cupsStrAlloc(instance
);
2627 dest
->is_default
= 0;
2628 dest
->num_options
= 0;
2629 dest
->options
= (cups_option_t
*)0;
2637 * 'cups_block_cb()' - Enumeration callback for block API.
2640 static int /* O - 1 to continue, 0 to stop */
2642 cups_dest_block_t block
, /* I - Block */
2643 unsigned flags
, /* I - Destination flags */
2644 cups_dest_t
*dest
) /* I - Destination */
2646 return ((block
)(flags
, dest
));
2648 # endif /* __BLOCKS__ */
2652 * 'cups_compare_dests()' - Compare two destinations.
2655 static int /* O - Result of comparison */
2656 cups_compare_dests(cups_dest_t
*a
, /* I - First destination */
2657 cups_dest_t
*b
) /* I - Second destination */
2659 int diff
; /* Difference */
2662 if ((diff
= _cups_strcasecmp(a
->name
, b
->name
)) != 0)
2664 else if (a
->instance
&& b
->instance
)
2665 return (_cups_strcasecmp(a
->instance
, b
->instance
));
2667 return ((a
->instance
&& !b
->instance
) - (!a
->instance
&& b
->instance
));
2671 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
2674 * 'cups_dnssd_browse_cb()' - Browse for printers.
2678 cups_dnssd_browse_cb(
2679 DNSServiceRef sdRef
, /* I - Service reference */
2680 DNSServiceFlags flags
, /* I - Option flags */
2681 uint32_t interfaceIndex
, /* I - Interface number */
2682 DNSServiceErrorType errorCode
, /* I - Error, if any */
2683 const char *serviceName
, /* I - Name of service/device */
2684 const char *regtype
, /* I - Type of service */
2685 const char *replyDomain
, /* I - Service domain */
2686 void *context
) /* I - Enumeration data */
2688 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2689 /* Enumeration data */
2692 DEBUG_printf(("5cups_dnssd_browse_cb(sdRef=%p, flags=%x, "
2693 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2694 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2695 sdRef
, flags
, interfaceIndex
, errorCode
, serviceName
, regtype
,
2696 replyDomain
, context
));
2699 * Don't do anything on error...
2702 if (errorCode
!= kDNSServiceErr_NoError
)
2709 cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2713 # else /* HAVE_AVAHI */
2715 * 'cups_dnssd_browse_cb()' - Browse for printers.
2719 cups_dnssd_browse_cb(
2720 AvahiServiceBrowser
*browser
, /* I - Browser */
2721 AvahiIfIndex interface
, /* I - Interface index (unused) */
2722 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2723 AvahiBrowserEvent event
, /* I - What happened */
2724 const char *name
, /* I - Service name */
2725 const char *type
, /* I - Registration type */
2726 const char *domain
, /* I - Domain */
2727 AvahiLookupResultFlags flags
, /* I - Flags */
2728 void *context
) /* I - Devices array */
2731 AvahiClient
*client
= avahi_service_browser_get_client(browser
);
2732 /* Client information */
2734 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2735 /* Enumeration data */
2744 case AVAHI_BROWSER_FAILURE
:
2745 DEBUG_printf(("cups_dnssd_browse_cb: %s",
2746 avahi_strerror(avahi_client_errno(client
))));
2747 avahi_simple_poll_quit(data
->simple_poll
);
2750 case AVAHI_BROWSER_NEW
:
2752 * This object is new on the network.
2755 if (flags
& AVAHI_LOOKUP_RESULT_LOCAL
)
2758 * This comes from the local machine so ignore it.
2761 DEBUG_printf(("cups_dnssd_browse_cb: Ignoring local service \"%s\".",
2767 * Create a device entry for it if it doesn't yet exist.
2770 cups_dnssd_get_device(data
, name
, type
, domain
);
2774 case AVAHI_BROWSER_REMOVE
:
2775 case AVAHI_BROWSER_ALL_FOR_NOW
:
2776 case AVAHI_BROWSER_CACHE_EXHAUSTED
:
2783 * 'cups_dnssd_client_cb()' - Avahi client callback function.
2787 cups_dnssd_client_cb(
2788 AvahiClient
*client
, /* I - Client information (unused) */
2789 AvahiClientState state
, /* I - Current state */
2790 void *context
) /* I - User data (unused) */
2792 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2793 /* Enumeration data */
2799 * If the connection drops, quit.
2802 if (state
== AVAHI_CLIENT_FAILURE
)
2804 DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
2805 avahi_simple_poll_quit(data
->simple_poll
);
2808 # endif /* HAVE_DNSSD */
2812 * 'cups_dnssd_compare_device()' - Compare two devices.
2815 static int /* O - Result of comparison */
2816 cups_dnssd_compare_devices(
2817 _cups_dnssd_device_t
*a
, /* I - First device */
2818 _cups_dnssd_device_t
*b
) /* I - Second device */
2820 return (strcmp(a
->dest
.name
, b
->dest
.name
));
2825 * 'cups_dnssd_free_device()' - Free the memory used by a device.
2829 cups_dnssd_free_device(
2830 _cups_dnssd_device_t
*device
, /* I - Device */
2831 _cups_dnssd_data_t
*data
) /* I - Enumeration data */
2833 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", device
,
2834 device
->dest
.name
, data
));
2838 DNSServiceRefDeallocate(device
->ref
);
2839 # else /* HAVE_AVAHI */
2841 avahi_record_browser_free(device
->ref
);
2842 # endif /* HAVE_DNSSD */
2844 _cupsStrFree(device
->domain
);
2845 _cupsStrFree(device
->fullName
);
2846 _cupsStrFree(device
->regtype
);
2847 _cupsStrFree(device
->dest
.name
);
2849 cupsFreeOptions(device
->dest
.num_options
, device
->dest
.options
);
2856 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
2859 static _cups_dnssd_device_t
* /* O - Device */
2860 cups_dnssd_get_device(
2861 _cups_dnssd_data_t
*data
, /* I - Enumeration data */
2862 const char *serviceName
, /* I - Service name */
2863 const char *regtype
, /* I - Registration type */
2864 const char *replyDomain
) /* I - Domain name */
2866 _cups_dnssd_device_t key
, /* Search key */
2867 *device
; /* Device */
2868 char fullName
[kDNSServiceMaxDomainName
];
2869 /* Full name for query */
2872 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", "
2873 "regtype=\"%s\", replyDomain=\"%s\")", data
, serviceName
,
2874 regtype
, replyDomain
));
2877 * See if this is an existing device...
2880 key
.dest
.name
= (char *)serviceName
;
2882 if ((device
= cupsArrayFind(data
->devices
, &key
)) != NULL
)
2885 * Yes, see if we need to do anything with this...
2888 int update
= 0; /* Non-zero if we need to update */
2890 if (!_cups_strcasecmp(replyDomain
, "local.") &&
2891 _cups_strcasecmp(device
->domain
, replyDomain
))
2894 * Update the "global" listing to use the .local domain name instead.
2897 _cupsStrFree(device
->domain
);
2898 device
->domain
= _cupsStrAlloc(replyDomain
);
2900 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
2901 "domain.", device
->dest
.name
));
2906 if (!_cups_strcasecmp(regtype
, "_ipps._tcp") &&
2907 _cups_strcasecmp(device
->regtype
, regtype
))
2910 * Prefer IPPS over IPP.
2913 _cupsStrFree(device
->regtype
);
2914 device
->regtype
= _cupsStrAlloc(regtype
);
2916 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
2917 device
->dest
.name
));
2924 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
2925 device
->dest
.name
));
2932 * No, add the device...
2935 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
2936 "'%s'.", serviceName
,
2937 !strcmp(regtype
, "_ipps._tcp") ? "IPPS" : "IPP",
2940 device
= calloc(sizeof(_cups_dnssd_device_t
), 1);
2941 device
->dest
.name
= _cupsStrAlloc(serviceName
);
2942 device
->domain
= _cupsStrAlloc(replyDomain
);
2943 device
->regtype
= _cupsStrAlloc(regtype
);
2945 cupsArrayAdd(data
->devices
, device
);
2949 * Set the "full name" of this service, which is used for queries...
2953 DNSServiceConstructFullName(fullName
, device
->dest
.name
, device
->regtype
,
2955 # else /* HAVE_AVAHI */
2956 avahi_service_name_join(fullName
, kDNSServiceMaxDomainName
, serviceName
,
2957 regtype
, replyDomain
);
2958 # endif /* HAVE_DNSSD */
2960 _cupsStrFree(device
->fullName
);
2961 device
->fullName
= _cupsStrAlloc(fullName
);
2966 DNSServiceRefDeallocate(device
->ref
);
2967 # else /* HAVE_AVAHI */
2968 avahi_record_browser_free(device
->ref
);
2969 # endif /* HAVE_DNSSD */
2974 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
2976 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
2977 device
->state
= _CUPS_DNSSD_NEW
;
2986 * 'cups_dnssd_local_cb()' - Browse for local printers.
2990 cups_dnssd_local_cb(
2991 DNSServiceRef sdRef
, /* I - Service reference */
2992 DNSServiceFlags flags
, /* I - Option flags */
2993 uint32_t interfaceIndex
, /* I - Interface number */
2994 DNSServiceErrorType errorCode
, /* I - Error, if any */
2995 const char *serviceName
, /* I - Name of service/device */
2996 const char *regtype
, /* I - Type of service */
2997 const char *replyDomain
, /* I - Service domain */
2998 void *context
) /* I - Devices array */
3000 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
3001 /* Enumeration data */
3002 _cups_dnssd_device_t
*device
; /* Device */
3005 DEBUG_printf(("5cups_dnssd_local_cb(sdRef=%p, flags=%x, "
3006 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
3007 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
3008 sdRef
, flags
, interfaceIndex
, errorCode
, serviceName
,
3009 regtype
, replyDomain
, context
));
3012 * Only process "add" data...
3015 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
3022 device
= cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
3025 * Hide locally-registered devices...
3028 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
3033 DNSServiceRefDeallocate(device
->ref
);
3037 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
3038 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
3040 device
->state
= _CUPS_DNSSD_LOCAL
;
3042 # endif /* HAVE_DNSSD */
3047 * 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
3049 * Note: This function is needed because avahi_simple_poll_iterate is broken
3050 * and always uses a timeout of 0 (!) milliseconds.
3051 * (Avahi Ticket #364)
3054 static int /* O - Number of file descriptors matching */
3056 struct pollfd
*pollfds
, /* I - File descriptors */
3057 unsigned int num_pollfds
, /* I - Number of file descriptors */
3058 int timeout
, /* I - Timeout in milliseconds (unused) */
3059 void *context
) /* I - User data (unused) */
3061 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
3062 /* Enumeration data */
3063 int val
; /* Return value */
3068 val
= poll(pollfds
, num_pollfds
, 250);
3072 DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno
)));
3079 # endif /* HAVE_AVAHI */
3083 * 'cups_dnssd_query_cb()' - Process query data.
3088 cups_dnssd_query_cb(
3089 DNSServiceRef sdRef
, /* I - Service reference */
3090 DNSServiceFlags flags
, /* I - Data flags */
3091 uint32_t interfaceIndex
, /* I - Interface */
3092 DNSServiceErrorType errorCode
, /* I - Error, if any */
3093 const char *fullName
, /* I - Full service name */
3094 uint16_t rrtype
, /* I - Record type */
3095 uint16_t rrclass
, /* I - Record class */
3096 uint16_t rdlen
, /* I - Length of record data */
3097 const void *rdata
, /* I - Record data */
3098 uint32_t ttl
, /* I - Time-to-live */
3099 void *context
) /* I - Enumeration data */
3101 # else /* HAVE_AVAHI */
3103 cups_dnssd_query_cb(
3104 AvahiRecordBrowser
*browser
, /* I - Record browser */
3105 AvahiIfIndex interfaceIndex
,
3106 /* I - Interface index (unused) */
3107 AvahiProtocol protocol
, /* I - Network protocol (unused) */
3108 AvahiBrowserEvent event
, /* I - What happened? */
3109 const char *fullName
, /* I - Service name */
3110 uint16_t rrclass
, /* I - Record class */
3111 uint16_t rrtype
, /* I - Record type */
3112 const void *rdata
, /* I - TXT record */
3113 size_t rdlen
, /* I - Length of TXT record */
3114 AvahiLookupResultFlags flags
, /* I - Flags */
3115 void *context
) /* I - Enumeration data */
3118 AvahiClient
*client
= avahi_record_browser_get_client(browser
);
3119 /* Client information */
3121 # endif /* HAVE_DNSSD */
3122 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
3123 /* Enumeration data */
3124 char name
[1024], /* Service name */
3125 *ptr
; /* Pointer into string */
3126 _cups_dnssd_device_t dkey
, /* Search key */
3127 *device
; /* Device */
3131 DEBUG_printf(("5cups_dnssd_query_cb(sdRef=%p, flags=%x, "
3132 "interfaceIndex=%d, errorCode=%d, fullName=\"%s\", "
3133 "rrtype=%u, rrclass=%u, rdlen=%u, rdata=%p, ttl=%u, "
3134 "context=%p)", sdRef
, flags
, interfaceIndex
, errorCode
,
3135 fullName
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, context
));
3138 * Only process "add" data...
3141 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
3144 # else /* HAVE_AVAHI */
3145 DEBUG_printf(("5cups_dnssd_query_cb(browser=%p, interfaceIndex=%d, "
3146 "protocol=%d, event=%d, fullName=\"%s\", rrclass=%u, "
3147 "rrtype=%u, rdata=%p, rdlen=%u, flags=%x, context=%p)",
3148 browser
, interfaceIndex
, protocol
, event
, fullName
, rrclass
,
3149 rrtype
, rdata
, (unsigned)rdlen
, flags
, context
));
3152 * Only process "add" data...
3155 if (event
!= AVAHI_BROWSER_NEW
)
3157 if (event
== AVAHI_BROWSER_FAILURE
)
3158 DEBUG_printf(("cups_dnssd_query_cb: %s",
3159 avahi_strerror(avahi_client_errno(client
))));
3163 # endif /* HAVE_DNSSD */
3166 * Lookup the service in the devices array.
3169 dkey
.dest
.name
= name
;
3171 cups_dnssd_unquote(name
, fullName
, sizeof(name
));
3173 if ((ptr
= strstr(name
, "._")) != NULL
)
3176 if ((device
= cupsArrayFind(data
->devices
, &dkey
)) != NULL
)
3179 * Found it, pull out the make and model from the TXT record and save it...
3182 const uint8_t *txt
, /* Pointer into data */
3183 *txtnext
, /* Next key/value pair */
3184 *txtend
; /* End of entire TXT record */
3185 uint8_t txtlen
; /* Length of current key/value pair */
3186 char key
[256], /* Key string */
3187 value
[256], /* Value string */
3188 make_and_model
[512],
3189 /* Manufacturer and model */
3190 model
[256], /* Model */
3191 uriname
[1024], /* Name for URI */
3192 uri
[1024]; /* Printer URI */
3193 cups_ptype_t type
= CUPS_PRINTER_REMOTE
| CUPS_PRINTER_BW
;
3195 int saw_printer_type
= 0;
3196 /* Did we see a printer-type key? */
3198 device
->state
= _CUPS_DNSSD_PENDING
;
3199 make_and_model
[0] = '\0';
3201 strlcpy(model
, "Unknown", sizeof(model
));
3203 for (txt
= rdata
, txtend
= txt
+ rdlen
;
3208 * Read a key/value pair starting with an 8-bit length. Since the
3209 * length is 8 bits and the size of the key/value buffers is 256, we
3210 * don't need to check for overflow...
3215 if (!txtlen
|| (txt
+ txtlen
) > txtend
)
3218 txtnext
= txt
+ txtlen
;
3220 for (ptr
= key
; txt
< txtnext
&& *txt
!= '='; txt
++)
3221 *ptr
++ = (char)*txt
;
3224 if (txt
< txtnext
&& *txt
== '=')
3229 memcpy(value
, txt
, (size_t)(txtnext
- txt
));
3230 value
[txtnext
- txt
] = '\0';
3232 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key
, value
));
3236 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key
));
3240 if (!_cups_strcasecmp(key
, "usb_MFG") ||
3241 !_cups_strcasecmp(key
, "usb_MANU") ||
3242 !_cups_strcasecmp(key
, "usb_MANUFACTURER"))
3243 strlcpy(make_and_model
, value
, sizeof(make_and_model
));
3244 else if (!_cups_strcasecmp(key
, "usb_MDL") ||
3245 !_cups_strcasecmp(key
, "usb_MODEL"))
3246 strlcpy(model
, value
, sizeof(model
));
3247 else if (!_cups_strcasecmp(key
, "product") && !strstr(value
, "Ghostscript"))
3249 if (value
[0] == '(')
3252 * Strip parenthesis...
3255 if ((ptr
= value
+ strlen(value
) - 1) > value
&& *ptr
== ')')
3258 strlcpy(model
, value
+ 1, sizeof(model
));
3261 strlcpy(model
, value
, sizeof(model
));
3263 else if (!_cups_strcasecmp(key
, "ty"))
3265 strlcpy(model
, value
, sizeof(model
));
3267 if ((ptr
= strchr(model
, ',')) != NULL
)
3270 else if (!_cups_strcasecmp(key
, "note"))
3271 device
->dest
.num_options
= cupsAddOption("printer-location", value
,
3272 device
->dest
.num_options
,
3273 &device
->dest
.options
);
3274 else if (!_cups_strcasecmp(key
, "pdl"))
3277 * Look for PDF-capable printers; only PDF-capable printers are shown.
3280 const char *start
, *next
; /* Pointer into value */
3281 int have_pdf
= 0; /* Have PDF? */
3283 for (start
= value
; start
&& *start
; start
= next
)
3285 if (!_cups_strncasecmp(start
, "application/pdf", 15) &&
3286 (!start
[15] || start
[15] == ','))
3292 if ((next
= strchr(start
, ',')) != NULL
)
3297 device
->state
= _CUPS_DNSSD_INCOMPATIBLE
;
3299 else if (!_cups_strcasecmp(key
, "printer-type"))
3302 * Value is either NNNN or 0xXXXX
3305 saw_printer_type
= 1;
3306 type
= (cups_ptype_t
)strtol(value
, NULL
, 0);
3308 else if (!saw_printer_type
)
3310 if (!_cups_strcasecmp(key
, "air") &&
3311 !_cups_strcasecmp(value
, "t"))
3312 type
|= CUPS_PRINTER_AUTHENTICATED
;
3313 else if (!_cups_strcasecmp(key
, "bind") &&
3314 !_cups_strcasecmp(value
, "t"))
3315 type
|= CUPS_PRINTER_BIND
;
3316 else if (!_cups_strcasecmp(key
, "collate") &&
3317 !_cups_strcasecmp(value
, "t"))
3318 type
|= CUPS_PRINTER_COLLATE
;
3319 else if (!_cups_strcasecmp(key
, "color") &&
3320 !_cups_strcasecmp(value
, "t"))
3321 type
|= CUPS_PRINTER_COLOR
;
3322 else if (!_cups_strcasecmp(key
, "copies") &&
3323 !_cups_strcasecmp(value
, "t"))
3324 type
|= CUPS_PRINTER_COPIES
;
3325 else if (!_cups_strcasecmp(key
, "duplex") &&
3326 !_cups_strcasecmp(value
, "t"))
3327 type
|= CUPS_PRINTER_DUPLEX
;
3328 else if (!_cups_strcasecmp(key
, "fax") &&
3329 !_cups_strcasecmp(value
, "t"))
3330 type
|= CUPS_PRINTER_MFP
;
3331 else if (!_cups_strcasecmp(key
, "papercustom") &&
3332 !_cups_strcasecmp(value
, "t"))
3333 type
|= CUPS_PRINTER_VARIABLE
;
3334 else if (!_cups_strcasecmp(key
, "papermax"))
3336 if (!_cups_strcasecmp(value
, "legal-a4"))
3337 type
|= CUPS_PRINTER_SMALL
;
3338 else if (!_cups_strcasecmp(value
, "isoc-a2"))
3339 type
|= CUPS_PRINTER_MEDIUM
;
3340 else if (!_cups_strcasecmp(value
, ">isoc-a2"))
3341 type
|= CUPS_PRINTER_LARGE
;
3343 else if (!_cups_strcasecmp(key
, "punch") &&
3344 !_cups_strcasecmp(value
, "t"))
3345 type
|= CUPS_PRINTER_PUNCH
;
3346 else if (!_cups_strcasecmp(key
, "scan") &&
3347 !_cups_strcasecmp(value
, "t"))
3348 type
|= CUPS_PRINTER_MFP
;
3349 else if (!_cups_strcasecmp(key
, "sort") &&
3350 !_cups_strcasecmp(value
, "t"))
3351 type
|= CUPS_PRINTER_SORT
;
3352 else if (!_cups_strcasecmp(key
, "staple") &&
3353 !_cups_strcasecmp(value
, "t"))
3354 type
|= CUPS_PRINTER_STAPLE
;
3359 * Save the printer-xxx values...
3362 device
->dest
.num_options
= cupsAddOption("printer-info", name
,
3363 device
->dest
.num_options
,
3364 &device
->dest
.options
);
3366 if (make_and_model
[0])
3368 strlcat(make_and_model
, " ", sizeof(make_and_model
));
3369 strlcat(make_and_model
, model
, sizeof(make_and_model
));
3371 device
->dest
.num_options
= cupsAddOption("printer-make-and-model",
3373 device
->dest
.num_options
,
3374 &device
->dest
.options
);
3377 device
->dest
.num_options
= cupsAddOption("printer-make-and-model",
3379 device
->dest
.num_options
,
3380 &device
->dest
.options
);
3382 device
->type
= type
;
3383 snprintf(value
, sizeof(value
), "%u", type
);
3384 device
->dest
.num_options
= cupsAddOption("printer-type", value
,
3385 device
->dest
.num_options
,
3386 &device
->dest
.options
);
3392 cups_dnssd_unquote(uriname
, device
->fullName
, sizeof(uriname
));
3393 httpAssembleURI(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
),
3394 !strcmp(device
->regtype
, "_ipps._tcp") ? "ipps" : "ipp",
3395 NULL
, uriname
, 0, saw_printer_type
? "/cups" : "/");
3397 DEBUG_printf(("6cups_dnssd_query: printer-uri-supported=\"%s\"", uri
));
3399 device
->dest
.num_options
= cupsAddOption("printer-uri-supported", uri
,
3400 device
->dest
.num_options
,
3401 &device
->dest
.options
);
3404 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
3410 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
3413 static const char * /* O - Resolved URI or NULL */
3415 cups_dest_t
*dest
, /* I - Destination */
3416 const char *uri
, /* I - Current printer URI */
3417 int msec
, /* I - Time in milliseconds */
3418 int *cancel
, /* I - Pointer to "cancel" variable */
3419 cups_dest_cb_t cb
, /* I - Callback */
3420 void *user_data
) /* I - User data for callback */
3422 char tempuri
[1024]; /* Temporary URI buffer */
3423 _cups_dnssd_resolve_t resolve
; /* Resolve data */
3427 * Resolve the URI...
3430 resolve
.cancel
= cancel
;
3431 gettimeofday(&resolve
.end_time
, NULL
);
3434 resolve
.end_time
.tv_sec
+= msec
/ 1000;
3435 resolve
.end_time
.tv_usec
+= (msec
% 1000) * 1000;
3437 while (resolve
.end_time
.tv_usec
>= 1000000)
3439 resolve
.end_time
.tv_sec
++;
3440 resolve
.end_time
.tv_usec
-= 1000000;
3444 resolve
.end_time
.tv_sec
+= 75;
3447 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
,
3450 if ((uri
= _httpResolveURI(uri
, tempuri
, sizeof(tempuri
),
3451 _HTTP_RESOLVE_FQDN
, cups_dnssd_resolve_cb
,
3454 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to resolve printer-uri."), 1);
3457 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
3464 * Save the resolved URI...
3467 dest
->num_options
= cupsAddOption("printer-uri-supported", uri
,
3468 dest
->num_options
, &dest
->options
);
3470 return (cupsGetOption("printer-uri-supported", dest
->num_options
,
3476 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
3479 static int /* O - 1 to continue, 0 to stop */
3480 cups_dnssd_resolve_cb(void *context
) /* I - Resolve data */
3482 _cups_dnssd_resolve_t
*resolve
= (_cups_dnssd_resolve_t
*)context
;
3484 struct timeval curtime
; /* Current time */
3488 * If the cancel variable is set, return immediately.
3491 if (*resolve
->cancel
)
3495 * Otherwise check the end time...
3498 gettimeofday(&curtime
, NULL
);
3500 return (curtime
.tv_sec
> resolve
->end_time
.tv_sec
||
3501 (curtime
.tv_sec
== resolve
->end_time
.tv_sec
&&
3502 curtime
.tv_usec
> resolve
->end_time
.tv_usec
));
3507 * 'cups_dnssd_unquote()' - Unquote a name string.
3511 cups_dnssd_unquote(char *dst
, /* I - Destination buffer */
3512 const char *src
, /* I - Source string */
3513 size_t dstsize
) /* I - Size of destination buffer */
3515 char *dstend
= dst
+ dstsize
- 1; /* End of destination buffer */
3518 while (*src
&& dst
< dstend
)
3523 if (isdigit(src
[0] & 255) && isdigit(src
[1] & 255) &&
3524 isdigit(src
[2] & 255))
3526 *dst
++ = ((((src
[0] - '0') * 10) + src
[1] - '0') * 10) + src
[2] - '0';
3538 #endif /* HAVE_DNSSD */
3542 * 'cups_find_dest()' - Find a destination using a binary search.
3545 static int /* O - Index of match */
3546 cups_find_dest(const char *name
, /* I - Destination name */
3547 const char *instance
, /* I - Instance or NULL */
3548 int num_dests
, /* I - Number of destinations */
3549 cups_dest_t
*dests
, /* I - Destinations */
3550 int prev
, /* I - Previous index */
3551 int *rdiff
) /* O - Difference of match */
3553 int left
, /* Low mark for binary search */
3554 right
, /* High mark for binary search */
3555 current
, /* Current index */
3556 diff
; /* Result of comparison */
3557 cups_dest_t key
; /* Search key */
3560 key
.name
= (char *)name
;
3561 key
.instance
= (char *)instance
;
3566 * Start search on either side of previous...
3569 if ((diff
= cups_compare_dests(&key
, dests
+ prev
)) == 0 ||
3570 (diff
< 0 && prev
== 0) ||
3571 (diff
> 0 && prev
== (num_dests
- 1)))
3579 * Start with previous on right side...
3588 * Start wih previous on left side...
3592 right
= num_dests
- 1;
3598 * Start search in the middle...
3602 right
= num_dests
- 1;
3607 current
= (left
+ right
) / 2;
3608 diff
= cups_compare_dests(&key
, dests
+ current
);
3617 while ((right
- left
) > 1);
3622 * Check the last 1 or 2 elements...
3625 if ((diff
= cups_compare_dests(&key
, dests
+ left
)) <= 0)
3629 diff
= cups_compare_dests(&key
, dests
+ right
);
3635 * Return the closest destination and the difference...
3645 * 'cups_get_default()' - Get the default destination from an lpoptions file.
3648 static char * /* O - Default destination or NULL */
3649 cups_get_default(const char *filename
, /* I - File to read */
3650 char *namebuf
, /* I - Name buffer */
3651 size_t namesize
, /* I - Size of name buffer */
3652 const char **instance
) /* I - Instance */
3654 cups_file_t
*fp
; /* lpoptions file */
3655 char line
[8192], /* Line from file */
3656 *value
, /* Value for line */
3657 *nameptr
; /* Pointer into name */
3658 int linenum
; /* Current line */
3663 if ((fp
= cupsFileOpen(filename
, "r")) != NULL
)
3667 while (cupsFileGetConf(fp
, line
, sizeof(line
), &value
, &linenum
))
3669 if (!_cups_strcasecmp(line
, "default") && value
)
3671 strlcpy(namebuf
, value
, namesize
);
3673 if ((nameptr
= strchr(namebuf
, ' ')) != NULL
)
3675 if ((nameptr
= strchr(namebuf
, '\t')) != NULL
)
3678 if ((nameptr
= strchr(namebuf
, '/')) != NULL
)
3681 *instance
= nameptr
;
3689 return (*namebuf
? namebuf
: NULL
);
3694 * 'cups_get_dests()' - Get destinations from a file.
3697 static int /* O - Number of destinations */
3699 const char *filename
, /* I - File to read from */
3700 const char *match_name
, /* I - Destination name we want */
3701 const char *match_inst
, /* I - Instance name we want */
3702 int user_default_set
, /* I - User default printer set? */
3703 int num_dests
, /* I - Number of destinations */
3704 cups_dest_t
**dests
) /* IO - Destinations */
3706 int i
; /* Looping var */
3707 cups_dest_t
*dest
; /* Current destination */
3708 cups_file_t
*fp
; /* File pointer */
3709 char line
[8192], /* Line from file */
3710 *lineptr
, /* Pointer into line */
3711 *name
, /* Name of destination/option */
3712 *instance
; /* Instance of destination */
3713 int linenum
; /* Current line number */
3716 DEBUG_printf(("7cups_get_dests(filename=\"%s\", match_name=\"%s\", "
3717 "match_inst=\"%s\", user_default_set=%d, num_dests=%d, "
3718 "dests=%p)", filename
, match_name
, match_inst
,
3719 user_default_set
, num_dests
, dests
));
3722 * Try to open the file...
3725 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
3729 * Read each printer; each line looks like:
3731 * Dest name[/instance] options
3732 * Default name[/instance] options
3737 while (cupsFileGetConf(fp
, line
, sizeof(line
), &lineptr
, &linenum
))
3740 * See what type of line it is...
3743 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
3744 linenum
, line
, lineptr
));
3746 if ((_cups_strcasecmp(line
, "dest") && _cups_strcasecmp(line
, "default")) || !lineptr
)
3748 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
3755 * Search for an instance...
3758 while (!isspace(*lineptr
& 255) && *lineptr
&& *lineptr
!= '/')
3761 if (*lineptr
== '/')
3764 * Found an instance...
3771 * Search for an instance...
3774 while (!isspace(*lineptr
& 255) && *lineptr
)
3783 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name
,
3787 * See if the primary instance of the destination exists; if not,
3788 * ignore this entry and move on...
3793 if (_cups_strcasecmp(name
, match_name
) ||
3794 (!instance
&& match_inst
) ||
3795 (instance
&& !match_inst
) ||
3796 (instance
&& _cups_strcasecmp(instance
, match_inst
)))
3801 else if (cupsGetDest(name
, NULL
, num_dests
, *dests
) == NULL
)
3803 DEBUG_puts("9cups_get_dests: Not found!");
3809 * Add the destination...
3812 num_dests
= cupsAddDest(name
, instance
, num_dests
, dests
);
3814 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
3820 DEBUG_puts("9cups_get_dests: Out of memory!");
3826 * Add options until we hit the end of the line...
3829 dest
->num_options
= cupsParseOptions(lineptr
, dest
->num_options
,
3833 * If we found what we were looking for, stop now...
3840 * Set this as default if needed...
3843 if (!user_default_set
&& !_cups_strcasecmp(line
, "default"))
3845 DEBUG_puts("9cups_get_dests: Setting as default...");
3847 for (i
= 0; i
< num_dests
; i
++)
3848 (*dests
)[i
].is_default
= 0;
3850 dest
->is_default
= 1;
3855 * Close the file and return...
3865 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
3869 static char * /* O - New string */
3871 ipp_attribute_t
*attr
, /* I - Attribute to convert */
3872 char *buffer
, /* I - Buffer */
3873 size_t bufsize
) /* I - Size of buffer */
3875 int i
; /* Looping var */
3876 char *ptr
, /* Pointer into buffer */
3877 *end
, /* Pointer to end of buffer */
3878 *valptr
; /* Pointer into string attribute */
3882 * Return quickly if we have a single string value...
3885 if (attr
->num_values
== 1 &&
3886 attr
->value_tag
!= IPP_TAG_INTEGER
&&
3887 attr
->value_tag
!= IPP_TAG_ENUM
&&
3888 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
3889 attr
->value_tag
!= IPP_TAG_RANGE
)
3890 return (attr
->values
[0].string
.text
);
3893 * Copy the values to the string, separating with commas and escaping strings
3897 end
= buffer
+ bufsize
- 1;
3899 for (i
= 0, ptr
= buffer
; i
< attr
->num_values
&& ptr
< end
; i
++)
3904 switch (attr
->value_tag
)
3906 case IPP_TAG_INTEGER
:
3908 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d", attr
->values
[i
].integer
);
3911 case IPP_TAG_BOOLEAN
:
3912 if (attr
->values
[i
].boolean
)
3913 strlcpy(ptr
, "true", (size_t)(end
- ptr
+ 1));
3915 strlcpy(ptr
, "false", (size_t)(end
- ptr
+ 1));
3918 case IPP_TAG_RANGE
:
3919 if (attr
->values
[i
].range
.lower
== attr
->values
[i
].range
.upper
)
3920 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d", attr
->values
[i
].range
.lower
);
3922 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d-%d", attr
->values
[i
].range
.lower
, attr
->values
[i
].range
.upper
);
3926 for (valptr
= attr
->values
[i
].string
.text
;
3927 *valptr
&& ptr
< end
;)
3929 if (strchr(" \t\n\\\'\"", *valptr
))
3931 if (ptr
>= (end
- 1))