2 * User-defined destination (and option) support for CUPS.
4 * Copyright © 2007-2018 by Apple Inc.
5 * Copyright © 1997-2007 by Easy Software Products.
7 * Licensed under Apache License v2.0. See the file "LICENSE" for more
12 * Include necessary headers...
15 #include "cups-private.h"
20 #endif /* HAVE_NOTIFY_H */
24 #endif /* HAVE_POLL */
28 #endif /* HAVE_DNSSD */
31 # include <avahi-client/client.h>
32 # include <avahi-client/lookup.h>
33 # include <avahi-common/simple-watch.h>
34 # include <avahi-common/domain.h>
35 # include <avahi-common/error.h>
36 # include <avahi-common/malloc.h>
37 #define kDNSServiceMaxDomainName AVAHI_DOMAIN_NAME_MAX
38 #endif /* HAVE_AVAHI */
47 # include <SystemConfiguration/SystemConfiguration.h>
48 # define _CUPS_LOCATION_DEFAULTS 1
49 # endif /* !TARGET_OS_IOS */
50 # define kCUPSPrintingPrefs CFSTR("org.cups.PrintingPrefs")
51 # define kDefaultPaperIDKey CFSTR("DefaultPaperID")
52 # define kLastUsedPrintersKey CFSTR("LastUsedPrinters")
53 # define kLocationNetworkKey CFSTR("Network")
54 # define kLocationPrinterIDKey CFSTR("PrinterID")
55 # define kUseLastPrinter CFSTR("UseLastPrinter")
56 #endif /* __APPLE__ */
58 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
59 # define _CUPS_DNSSD_GET_DESTS 250 /* Milliseconds for cupsGetDests */
60 # define _CUPS_DNSSD_MAXTIME 50 /* Milliseconds for maximum quantum of time */
62 # define _CUPS_DNSSD_GET_DESTS 0 /* Milliseconds for cupsGetDests */
63 #endif /* HAVE_DNSSD || HAVE_AVAHI */
70 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
71 typedef enum _cups_dnssd_state_e
/* Enumerated device state */
77 _CUPS_DNSSD_INCOMPATIBLE
,
79 } _cups_dnssd_state_t
;
81 typedef struct _cups_dnssd_data_s
/* Enumeration data */
84 DNSServiceRef main_ref
; /* Main service reference */
85 # else /* HAVE_AVAHI */
86 AvahiSimplePoll
*simple_poll
; /* Polling interface */
87 AvahiClient
*client
; /* Client information */
88 int got_data
; /* Did we get data? */
89 int browsers
; /* How many browsers are running? */
90 # endif /* HAVE_DNSSD */
91 cups_dest_cb_t cb
; /* Callback */
92 void *user_data
; /* User data pointer */
93 cups_ptype_t type
, /* Printer type filter */
94 mask
; /* Printer type mask */
95 cups_array_t
*devices
; /* Devices found so far */
96 int num_dests
; /* Number of lpoptions destinations */
97 cups_dest_t
*dests
; /* lpoptions destinations */
98 char def_name
[1024], /* Default printer name, if any */
99 *def_instance
; /* Default printer instance, if any */
100 } _cups_dnssd_data_t
;
102 typedef struct _cups_dnssd_device_s
/* Enumerated device */
104 _cups_dnssd_state_t state
; /* State of device listing */
106 DNSServiceRef ref
; /* Service reference for query */
107 # else /* HAVE_AVAHI */
108 AvahiRecordBrowser
*ref
; /* Browser for query */
109 # endif /* HAVE_DNSSD */
110 char *fullName
, /* Full name */
111 *regtype
, /* Registration type */
112 *domain
; /* Domain name */
113 cups_ptype_t type
; /* Device registration type */
114 cups_dest_t dest
; /* Destination record */
115 } _cups_dnssd_device_t
;
117 typedef struct _cups_dnssd_resolve_s
/* Data for resolving URI */
119 int *cancel
; /* Pointer to "cancel" variable */
120 struct timeval end_time
; /* Ending time */
121 } _cups_dnssd_resolve_t
;
122 #endif /* HAVE_DNSSD */
124 typedef struct _cups_getdata_s
126 int num_dests
; /* Number of destinations */
127 cups_dest_t
*dests
; /* Destinations */
128 char def_name
[1024], /* Default printer name, if any */
129 *def_instance
; /* Default printer instance, if any */
132 typedef struct _cups_namedata_s
134 const char *name
; /* Named destination */
135 cups_dest_t
*dest
; /* Destination */
143 #if _CUPS_LOCATION_DEFAULTS
144 static CFArrayRef
appleCopyLocations(void);
145 static CFStringRef
appleCopyNetwork(void);
146 #endif /* _CUPS_LOCATION_DEFAULTS */
148 static char *appleGetPaperSize(char *name
, size_t namesize
);
149 #endif /* __APPLE__ */
150 #if _CUPS_LOCATION_DEFAULTS
151 static CFStringRef
appleGetPrinter(CFArrayRef locations
,
152 CFStringRef network
, CFIndex
*locindex
);
153 #endif /* _CUPS_LOCATION_DEFAULTS */
154 static cups_dest_t
*cups_add_dest(const char *name
, const char *instance
,
155 int *num_dests
, cups_dest_t
**dests
);
157 static int cups_block_cb(cups_dest_block_t block
, unsigned flags
,
159 #endif /* __BLOCKS__ */
160 static int cups_compare_dests(cups_dest_t
*a
, cups_dest_t
*b
);
161 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
163 static void cups_dnssd_browse_cb(DNSServiceRef sdRef
,
164 DNSServiceFlags flags
,
165 uint32_t interfaceIndex
,
166 DNSServiceErrorType errorCode
,
167 const char *serviceName
,
169 const char *replyDomain
,
171 # else /* HAVE_AVAHI */
172 static void cups_dnssd_browse_cb(AvahiServiceBrowser
*browser
,
173 AvahiIfIndex interface
,
174 AvahiProtocol protocol
,
175 AvahiBrowserEvent event
,
176 const char *serviceName
,
178 const char *replyDomain
,
179 AvahiLookupResultFlags flags
,
181 static void cups_dnssd_client_cb(AvahiClient
*client
,
182 AvahiClientState state
,
184 # endif /* HAVE_DNSSD */
185 static int cups_dnssd_compare_devices(_cups_dnssd_device_t
*a
,
186 _cups_dnssd_device_t
*b
);
187 static void cups_dnssd_free_device(_cups_dnssd_device_t
*device
,
188 _cups_dnssd_data_t
*data
);
189 static _cups_dnssd_device_t
*
190 cups_dnssd_get_device(_cups_dnssd_data_t
*data
,
191 const char *serviceName
,
193 const char *replyDomain
);
195 static void cups_dnssd_query_cb(DNSServiceRef sdRef
,
196 DNSServiceFlags flags
,
197 uint32_t interfaceIndex
,
198 DNSServiceErrorType errorCode
,
199 const char *fullName
,
200 uint16_t rrtype
, uint16_t rrclass
,
201 uint16_t rdlen
, const void *rdata
,
202 uint32_t ttl
, void *context
);
203 # else /* HAVE_AVAHI */
204 static int cups_dnssd_poll_cb(struct pollfd
*pollfds
,
205 unsigned int num_pollfds
,
206 int timeout
, void *context
);
207 static void cups_dnssd_query_cb(AvahiRecordBrowser
*browser
,
208 AvahiIfIndex interface
,
209 AvahiProtocol protocol
,
210 AvahiBrowserEvent event
,
211 const char *name
, uint16_t rrclass
,
212 uint16_t rrtype
, const void *rdata
,
214 AvahiLookupResultFlags flags
,
216 # endif /* HAVE_DNSSD */
217 static const char *cups_dnssd_resolve(cups_dest_t
*dest
, const char *uri
,
218 int msec
, int *cancel
,
219 cups_dest_cb_t cb
, void *user_data
);
220 static int cups_dnssd_resolve_cb(void *context
);
221 static void cups_dnssd_unquote(char *dst
, const char *src
,
223 static int cups_elapsed(struct timeval
*t
);
224 #endif /* HAVE_DNSSD || HAVE_AVAHI */
225 static int cups_enum_dests(http_t
*http
, unsigned flags
, int msec
, int *cancel
, cups_ptype_t type
, cups_ptype_t mask
, cups_dest_cb_t cb
, void *user_data
);
226 static int cups_find_dest(const char *name
, const char *instance
,
227 int num_dests
, cups_dest_t
*dests
, int prev
,
229 static int cups_get_cb(_cups_getdata_t
*data
, unsigned flags
, cups_dest_t
*dest
);
230 static char *cups_get_default(const char *filename
, char *namebuf
,
231 size_t namesize
, const char **instance
);
232 static int cups_get_dests(const char *filename
, const char *match_name
, const char *match_inst
, int load_all
, int user_default_set
, int num_dests
, cups_dest_t
**dests
);
233 static char *cups_make_string(ipp_attribute_t
*attr
, char *buffer
,
235 static int cups_name_cb(_cups_namedata_t
*data
, unsigned flags
, cups_dest_t
*dest
);
236 static void cups_queue_name(char *name
, const char *serviceName
, size_t namesize
);
240 * 'cupsAddDest()' - Add a destination to the list of destinations.
242 * This function cannot be used to add a new class or printer queue,
243 * it only adds a new container of saved options for the named
244 * destination or instance.
246 * If the named destination already exists, the destination list is
247 * returned unchanged. Adding a new instance of a destination creates
248 * a copy of that destination's options.
250 * Use the @link cupsSaveDests@ function to save the updated list of
251 * destinations to the user's lpoptions file.
254 int /* O - New number of destinations */
255 cupsAddDest(const char *name
, /* I - Destination name */
256 const char *instance
, /* I - Instance name or @code NULL@ for none/primary */
257 int num_dests
, /* I - Number of destinations */
258 cups_dest_t
**dests
) /* IO - Destinations */
260 int i
; /* Looping var */
261 cups_dest_t
*dest
; /* Destination pointer */
262 cups_dest_t
*parent
= NULL
; /* Parent destination */
263 cups_option_t
*doption
, /* Current destination option */
264 *poption
; /* Current parent option */
270 if (!cupsGetDest(name
, instance
, num_dests
, *dests
))
272 if (instance
&& !cupsGetDest(name
, NULL
, num_dests
, *dests
))
275 if ((dest
= cups_add_dest(name
, instance
, &num_dests
, dests
)) == NULL
)
279 * Find the base dest again now the array has been realloc'd.
282 parent
= cupsGetDest(name
, NULL
, num_dests
, *dests
);
284 if (instance
&& parent
&& parent
->num_options
> 0)
287 * Copy options from parent...
290 dest
->options
= calloc(sizeof(cups_option_t
), (size_t)parent
->num_options
);
294 dest
->num_options
= parent
->num_options
;
296 for (i
= dest
->num_options
, doption
= dest
->options
,
297 poption
= parent
->options
;
299 i
--, doption
++, poption
++)
301 doption
->name
= _cupsStrRetain(poption
->name
);
302 doption
->value
= _cupsStrRetain(poption
->value
);
314 * '_cupsAppleCopyDefaultPaperID()' - Get the default paper ID.
317 CFStringRef
/* O - Default paper ID */
318 _cupsAppleCopyDefaultPaperID(void)
320 return (CFPreferencesCopyAppValue(kDefaultPaperIDKey
,
321 kCUPSPrintingPrefs
));
326 * '_cupsAppleCopyDefaultPrinter()' - Get the default printer at this location.
329 CFStringRef
/* O - Default printer name */
330 _cupsAppleCopyDefaultPrinter(void)
332 # if _CUPS_LOCATION_DEFAULTS
333 CFStringRef network
; /* Network location */
334 CFArrayRef locations
; /* Location array */
335 CFStringRef locprinter
; /* Current printer */
339 * Use location-based defaults only if "use last printer" is selected in the
340 * system preferences...
343 if (!_cupsAppleGetUseLastPrinter())
345 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Not using last printer as "
351 * Get the current location...
354 if ((network
= appleCopyNetwork()) == NULL
)
356 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Unable to get current "
362 * Lookup the network in the preferences...
365 if ((locations
= appleCopyLocations()) == NULL
)
368 * Missing or bad location array, so no location-based default...
371 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Missing or bad last used "
379 DEBUG_printf(("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.",
380 (int)CFArrayGetCount(locations
)));
382 if ((locprinter
= appleGetPrinter(locations
, network
, NULL
)) != NULL
)
383 CFRetain(locprinter
);
386 CFRelease(locations
);
392 # endif /* _CUPS_LOCATION_DEFAULTS */
397 * '_cupsAppleGetUseLastPrinter()' - Get whether to use the last used printer.
400 int /* O - 1 to use last printer, 0 otherwise */
401 _cupsAppleGetUseLastPrinter(void)
403 Boolean uselast
, /* Use last printer preference value */
404 uselast_set
; /* Valid is set? */
407 if (getenv("CUPS_DISABLE_APPLE_DEFAULT"))
410 uselast
= CFPreferencesGetAppBooleanValue(kUseLastPrinter
,
421 * '_cupsAppleSetDefaultPaperID()' - Set the default paper id.
425 _cupsAppleSetDefaultPaperID(
426 CFStringRef name
) /* I - New paper ID */
428 CFPreferencesSetAppValue(kDefaultPaperIDKey
, name
, kCUPSPrintingPrefs
);
429 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
431 # ifdef HAVE_NOTIFY_POST
432 notify_post("com.apple.printerPrefsChange");
433 # endif /* HAVE_NOTIFY_POST */
438 * '_cupsAppleSetDefaultPrinter()' - Set the default printer for this location.
442 _cupsAppleSetDefaultPrinter(
443 CFStringRef name
) /* I - Default printer/class name */
445 # if _CUPS_LOCATION_DEFAULTS
446 CFStringRef network
; /* Current network */
447 CFArrayRef locations
; /* Old locations array */
448 CFIndex locindex
; /* Index in locations array */
449 CFStringRef locprinter
; /* Current printer */
450 CFMutableArrayRef newlocations
; /* New locations array */
451 CFMutableDictionaryRef newlocation
; /* New location */
455 * Get the current location...
458 if ((network
= appleCopyNetwork()) == NULL
)
460 DEBUG_puts("1_cupsAppleSetDefaultPrinter: Unable to get current network...");
465 * Lookup the network in the preferences...
468 if ((locations
= appleCopyLocations()) != NULL
)
469 locprinter
= appleGetPrinter(locations
, network
, &locindex
);
476 if (!locprinter
|| CFStringCompare(locprinter
, name
, 0) != kCFCompareEqualTo
)
479 * Need to change the locations array...
484 newlocations
= CFArrayCreateMutableCopy(kCFAllocatorDefault
, 0,
488 CFArrayRemoveValueAtIndex(newlocations
, locindex
);
491 newlocations
= CFArrayCreateMutable(kCFAllocatorDefault
, 0,
492 &kCFTypeArrayCallBacks
);
494 newlocation
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
495 &kCFTypeDictionaryKeyCallBacks
,
496 &kCFTypeDictionaryValueCallBacks
);
498 if (newlocation
&& newlocations
)
501 * Put the new location at the front of the array...
504 CFDictionaryAddValue(newlocation
, kLocationNetworkKey
, network
);
505 CFDictionaryAddValue(newlocation
, kLocationPrinterIDKey
, name
);
506 CFArrayInsertValueAtIndex(newlocations
, 0, newlocation
);
509 * Limit the number of locations to 10...
512 while (CFArrayGetCount(newlocations
) > 10)
513 CFArrayRemoveValueAtIndex(newlocations
, 10);
516 * Push the changes out...
519 CFPreferencesSetAppValue(kLastUsedPrintersKey
, newlocations
,
521 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
523 # ifdef HAVE_NOTIFY_POST
524 notify_post("com.apple.printerPrefsChange");
525 # endif /* HAVE_NOTIFY_POST */
529 CFRelease(newlocations
);
532 CFRelease(newlocation
);
536 CFRelease(locations
);
542 # endif /* _CUPS_LOCATION_DEFAULTS */
547 * '_cupsAppleSetUseLastPrinter()' - Set whether to use the last used printer.
551 _cupsAppleSetUseLastPrinter(
552 int uselast
) /* O - 1 to use last printer, 0 otherwise */
554 CFPreferencesSetAppValue(kUseLastPrinter
,
555 uselast
? kCFBooleanTrue
: kCFBooleanFalse
,
557 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
559 # ifdef HAVE_NOTIFY_POST
560 notify_post("com.apple.printerPrefsChange");
561 # endif /* HAVE_NOTIFY_POST */
563 #endif /* __APPLE__ */
567 * 'cupsConnectDest()' - Open a connection to the destination.
569 * Connect to the destination, returning a new @code http_t@ connection object
570 * and optionally the resource path to use for the destination. These calls
571 * will block until a connection is made, the timeout expires, the integer
572 * pointed to by "cancel" is non-zero, or the callback function (or block)
573 * returns 0. The caller is responsible for calling @link httpClose@ on the
574 * returned connection.
576 * Starting with CUPS 2.2.4, the caller can pass @code CUPS_DEST_FLAGS_DEVICE@
577 * for the "flags" argument to connect directly to the device associated with
578 * the destination. Otherwise, the connection is made to the CUPS scheduler
579 * associated with the destination.
581 * @since CUPS 1.6/macOS 10.8@
584 http_t
* /* O - Connection to destination or @code NULL@ */
586 cups_dest_t
*dest
, /* I - Destination */
587 unsigned flags
, /* I - Connection flags */
588 int msec
, /* I - Timeout in milliseconds */
589 int *cancel
, /* I - Pointer to "cancel" variable */
590 char *resource
, /* I - Resource buffer */
591 size_t resourcesize
, /* I - Size of resource buffer */
592 cups_dest_cb_t cb
, /* I - Callback function */
593 void *user_data
) /* I - User data pointer */
595 const char *uri
; /* Printer URI */
596 char scheme
[32], /* URI scheme */
597 userpass
[256], /* Username and password (unused) */
598 hostname
[256], /* Hostname */
599 tempresource
[1024]; /* Temporary resource buffer */
600 int port
; /* Port number */
601 char portstr
[16]; /* Port number string */
602 http_encryption_t encryption
; /* Encryption to use */
603 http_addrlist_t
*addrlist
; /* Address list for server */
604 http_t
*http
; /* Connection to server */
607 DEBUG_printf(("cupsConnectDest(dest=%p, flags=0x%x, msec=%d, cancel=%p(%d), resource=\"%s\", resourcesize=" CUPS_LLFMT
", cb=%p, user_data=%p)", (void *)dest
, flags
, msec
, (void *)cancel
, cancel
? *cancel
: -1, resource
, CUPS_LLCAST resourcesize
, (void *)cb
, user_data
));
610 * Range check input...
618 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
622 if (!resource
|| resourcesize
< 1)
624 resource
= tempresource
;
625 resourcesize
= sizeof(tempresource
);
629 * Grab the printer URI...
632 if (flags
& CUPS_DEST_FLAGS_DEVICE
)
634 if ((uri
= cupsGetOption("device-uri", dest
->num_options
, dest
->options
)) != NULL
)
636 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
637 if (strstr(uri
, "._tcp"))
638 uri
= cups_dnssd_resolve(dest
, uri
, msec
, cancel
, cb
, user_data
);
639 #endif /* HAVE_DNSSD || HAVE_AVAHI */
642 else if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
, dest
->options
)) == NULL
)
644 if ((uri
= cupsGetOption("device-uri", dest
->num_options
, dest
->options
)) != NULL
)
646 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
647 if (strstr(uri
, "._tcp"))
648 uri
= cups_dnssd_resolve(dest
, uri
, msec
, cancel
, cb
, user_data
);
649 #endif /* HAVE_DNSSD || HAVE_AVAHI */
653 uri
= _cupsCreateDest(dest
->name
, cupsGetOption("printer-info", dest
->num_options
, dest
->options
), NULL
, uri
, tempresource
, sizeof(tempresource
));
657 dest
->num_options
= cupsAddOption("printer-uri-supported", uri
, dest
->num_options
, &dest
->options
);
659 uri
= cupsGetOption("printer-uri-supported", dest
->num_options
, dest
->options
);
665 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(ENOENT
), 0);
668 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
, dest
);
673 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
674 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
675 &port
, resource
, (int)resourcesize
) < HTTP_URI_STATUS_OK
)
677 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer-uri."), 1);
680 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
687 * Lookup the address for the server...
691 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
, dest
);
693 snprintf(portstr
, sizeof(portstr
), "%d", port
);
695 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, portstr
)) == NULL
)
698 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
, dest
);
703 if (cancel
&& *cancel
)
705 httpAddrFreeList(addrlist
);
708 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CANCELED
, dest
);
714 * Create the HTTP object pointing to the server referenced by the URI...
717 if (!strcmp(scheme
, "ipps") || port
== 443)
718 encryption
= HTTP_ENCRYPTION_ALWAYS
;
720 encryption
= HTTP_ENCRYPTION_IF_REQUESTED
;
722 http
= httpConnect2(hostname
, port
, addrlist
, AF_UNSPEC
, encryption
, 1, 0, NULL
);
723 httpAddrFreeList(addrlist
);
726 * Connect if requested...
729 if (flags
& CUPS_DEST_FLAGS_UNCONNECTED
)
732 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
, dest
);
737 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
, dest
);
739 if (!httpReconnect2(http
, msec
, cancel
) && cb
)
741 if (cancel
&& *cancel
)
742 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
, dest
);
744 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
, dest
);
747 (*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, dest
);
756 * 'cupsConnectDestBlock()' - Open a connection to the destination.
758 * Connect to the destination, returning a new @code http_t@ connection object
759 * and optionally the resource path to use for the destination. These calls
760 * will block until a connection is made, the timeout expires, the integer
761 * pointed to by "cancel" is non-zero, or the block returns 0. The caller is
762 * responsible for calling @link httpClose@ on the returned connection.
764 * Starting with CUPS 2.2.4, the caller can pass @code CUPS_DEST_FLAGS_DEVICE@
765 * for the "flags" argument to connect directly to the device associated with
766 * the destination. Otherwise, the connection is made to the CUPS scheduler
767 * associated with the destination.
769 * @since CUPS 1.6/macOS 10.8@ @exclude all@
772 http_t
* /* O - Connection to destination or @code NULL@ */
773 cupsConnectDestBlock(
774 cups_dest_t
*dest
, /* I - Destination */
775 unsigned flags
, /* I - Connection flags */
776 int msec
, /* I - Timeout in milliseconds */
777 int *cancel
, /* I - Pointer to "cancel" variable */
778 char *resource
, /* I - Resource buffer */
779 size_t resourcesize
, /* I - Size of resource buffer */
780 cups_dest_block_t block
) /* I - Callback block */
782 return (cupsConnectDest(dest
, flags
, msec
, cancel
, resource
, resourcesize
,
783 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
785 #endif /* __BLOCKS__ */
789 * 'cupsCopyDest()' - Copy a destination.
791 * Make a copy of the destination to an array of destinations (or just a single
792 * copy) - for use with the cupsEnumDests* functions. The caller is responsible
793 * for calling cupsFreeDests() on the returned object(s).
795 * @since CUPS 1.6/macOS 10.8@
798 int /* O - New number of destinations */
799 cupsCopyDest(cups_dest_t
*dest
, /* I - Destination to copy */
800 int num_dests
, /* I - Number of destinations */
801 cups_dest_t
**dests
) /* IO - Destination array */
803 int i
; /* Looping var */
804 cups_dest_t
*new_dest
; /* New destination pointer */
805 cups_option_t
*new_option
, /* Current destination option */
806 *option
; /* Current parent option */
810 * Range check input...
813 if (!dest
|| num_dests
< 0 || !dests
)
817 * See if the destination already exists...
820 if ((new_dest
= cupsGetDest(dest
->name
, dest
->instance
, num_dests
,
824 * Protect against copying destination to itself...
827 if (new_dest
== dest
)
831 * Otherwise, free the options...
834 cupsFreeOptions(new_dest
->num_options
, new_dest
->options
);
836 new_dest
->num_options
= 0;
837 new_dest
->options
= NULL
;
840 new_dest
= cups_add_dest(dest
->name
, dest
->instance
, &num_dests
, dests
);
844 new_dest
->is_default
= dest
->is_default
;
846 if ((new_dest
->options
= calloc(sizeof(cups_option_t
), (size_t)dest
->num_options
)) == NULL
)
847 return (cupsRemoveDest(dest
->name
, dest
->instance
, num_dests
, dests
));
849 new_dest
->num_options
= dest
->num_options
;
851 for (i
= dest
->num_options
, option
= dest
->options
,
852 new_option
= new_dest
->options
;
854 i
--, option
++, new_option
++)
856 new_option
->name
= _cupsStrRetain(option
->name
);
857 new_option
->value
= _cupsStrRetain(option
->value
);
866 * '_cupsCreateDest()' - Create a local (temporary) queue.
869 char * /* O - Printer URI or @code NULL@ on error */
870 _cupsCreateDest(const char *name
, /* I - Printer name */
871 const char *info
, /* I - Printer description of @code NULL@ */
872 const char *device_id
, /* I - 1284 Device ID or @code NULL@ */
873 const char *device_uri
, /* I - Device URI */
874 char *uri
, /* I - Printer URI buffer */
875 size_t urisize
) /* I - Size of URI buffer */
877 http_t
*http
; /* Connection to server */
878 ipp_t
*request
, /* CUPS-Create-Local-Printer request */
879 *response
; /* CUPS-Create-Local-Printer response */
880 ipp_attribute_t
*attr
; /* printer-uri-supported attribute */
881 ipp_pstate_t state
= IPP_PSTATE_STOPPED
;
882 /* printer-state value */
885 if (!name
|| !device_uri
|| !uri
|| urisize
< 32)
888 if ((http
= httpConnect2(cupsServer(), ippPort(), NULL
, AF_UNSPEC
, HTTP_ENCRYPTION_IF_REQUESTED
, 1, 30000, NULL
)) == NULL
)
891 request
= ippNewRequest(IPP_OP_CUPS_CREATE_LOCAL_PRINTER
);
893 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
, "ipp://localhost/");
894 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
, "requesting-user-name", NULL
, cupsUser());
896 ippAddString(request
, IPP_TAG_PRINTER
, IPP_TAG_URI
, "device-uri", NULL
, device_uri
);
897 ippAddString(request
, IPP_TAG_PRINTER
, IPP_TAG_NAME
, "printer-name", NULL
, name
);
899 ippAddString(request
, IPP_TAG_PRINTER
, IPP_TAG_TEXT
, "printer-info", NULL
, info
);
901 ippAddString(request
, IPP_TAG_PRINTER
, IPP_TAG_TEXT
, "printer-device-id", NULL
, device_id
);
903 response
= cupsDoRequest(http
, request
, "/");
905 if ((attr
= ippFindAttribute(response
, "printer-uri-supported", IPP_TAG_URI
)) != NULL
)
906 strlcpy(uri
, ippGetString(attr
, 0, NULL
), urisize
);
914 if ((attr
= ippFindAttribute(response
, "printer-state", IPP_TAG_ENUM
)) != NULL
)
915 state
= (ipp_pstate_t
)ippGetInteger(attr
, 0);
917 while (state
== IPP_PSTATE_STOPPED
&& cupsLastError() == IPP_STATUS_OK
)
922 request
= ippNewRequest(IPP_OP_GET_PRINTER_ATTRIBUTES
);
924 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
, uri
);
925 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
, "requesting-user-name", NULL
, cupsUser());
926 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_KEYWORD
, "requested-attributes", NULL
, "printer-state");
928 response
= cupsDoRequest(http
, request
, "/");
930 if ((attr
= ippFindAttribute(response
, "printer-state", IPP_TAG_ENUM
)) != NULL
)
931 state
= (ipp_pstate_t
)ippGetInteger(attr
, 0);
943 * 'cupsEnumDests()' - Enumerate available destinations with a callback function.
945 * Destinations are enumerated from one or more sources. The callback function
946 * receives the @code user_data@ pointer and the destination pointer which can
947 * be used as input to the @link cupsCopyDest@ function. The function must
948 * return 1 to continue enumeration or 0 to stop.
950 * The @code type@ and @code mask@ arguments allow the caller to filter the
951 * destinations that are enumerated. Passing 0 for both will enumerate all
952 * printers. The constant @code CUPS_PRINTER_DISCOVERED@ is used to filter on
953 * destinations that are available but have not yet been added locally.
955 * Enumeration happens on the current thread and does not return until all
956 * destinations have been enumerated or the callback function returns 0.
958 * Note: The callback function will likely receive multiple updates for the same
959 * destinations - it is up to the caller to suppress any duplicate destinations.
961 * @since CUPS 1.6/macOS 10.8@
964 int /* O - 1 on success, 0 on failure */
966 unsigned flags
, /* I - Enumeration flags */
967 int msec
, /* I - Timeout in milliseconds, -1 for indefinite */
968 int *cancel
, /* I - Pointer to "cancel" variable */
969 cups_ptype_t type
, /* I - Printer type bits */
970 cups_ptype_t mask
, /* I - Mask for printer type bits */
971 cups_dest_cb_t cb
, /* I - Callback function */
972 void *user_data
) /* I - User data */
974 return (cups_enum_dests(CUPS_HTTP_DEFAULT
, flags
, msec
, cancel
, type
, mask
, cb
, user_data
));
980 * 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
982 * Destinations are enumerated from one or more sources. The block receives the
983 * @code user_data@ pointer and the destination pointer which can be used as
984 * input to the @link cupsCopyDest@ function. The block must return 1 to
985 * continue enumeration or 0 to stop.
987 * The @code type@ and @code mask@ arguments allow the caller to filter the
988 * destinations that are enumerated. Passing 0 for both will enumerate all
989 * printers. The constant @code CUPS_PRINTER_DISCOVERED@ is used to filter on
990 * destinations that are available but have not yet been added locally.
992 * Enumeration happens on the current thread and does not return until all
993 * destinations have been enumerated or the block returns 0.
995 * Note: The block will likely receive multiple updates for the same
996 * destinations - it is up to the caller to suppress any duplicate destinations.
998 * @since CUPS 1.6/macOS 10.8@ @exclude all@
1001 int /* O - 1 on success, 0 on failure */
1003 unsigned flags
, /* I - Enumeration flags */
1004 int timeout
, /* I - Timeout in milliseconds, 0 for indefinite */
1005 int *cancel
, /* I - Pointer to "cancel" variable */
1006 cups_ptype_t type
, /* I - Printer type bits */
1007 cups_ptype_t mask
, /* I - Mask for printer type bits */
1008 cups_dest_block_t block
) /* I - Block */
1010 return (cupsEnumDests(flags
, timeout
, cancel
, type
, mask
,
1011 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
1013 # endif /* __BLOCKS__ */
1017 * 'cupsFreeDests()' - Free the memory used by the list of destinations.
1021 cupsFreeDests(int num_dests
, /* I - Number of destinations */
1022 cups_dest_t
*dests
) /* I - Destinations */
1024 int i
; /* Looping var */
1025 cups_dest_t
*dest
; /* Current destination */
1028 if (num_dests
== 0 || dests
== NULL
)
1031 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1033 _cupsStrFree(dest
->name
);
1034 _cupsStrFree(dest
->instance
);
1036 cupsFreeOptions(dest
->num_options
, dest
->options
);
1044 * 'cupsGetDest()' - Get the named destination from the list.
1046 * Use the @link cupsEnumDests@ or @link cupsGetDests2@ functions to get a
1047 * list of supported destinations for the current user.
1050 cups_dest_t
* /* O - Destination pointer or @code NULL@ */
1051 cupsGetDest(const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1052 const char *instance
, /* I - Instance name or @code NULL@ */
1053 int num_dests
, /* I - Number of destinations */
1054 cups_dest_t
*dests
) /* I - Destinations */
1056 int diff
, /* Result of comparison */
1057 match
; /* Matching index */
1060 if (num_dests
<= 0 || !dests
)
1066 * NULL name for default printer.
1069 while (num_dests
> 0)
1071 if (dests
->is_default
)
1081 * Lookup name and optionally the instance...
1084 match
= cups_find_dest(name
, instance
, num_dests
, dests
, -1, &diff
);
1087 return (dests
+ match
);
1095 * '_cupsGetDestResource()' - Get the resource path and URI for a destination.
1098 const char * /* O - URI */
1099 _cupsGetDestResource(
1100 cups_dest_t
*dest
, /* I - Destination */
1101 unsigned flags
, /* I - Destination flags */
1102 char *resource
, /* I - Resource buffer */
1103 size_t resourcesize
) /* I - Size of resource buffer */
1105 const char *uri
, /* URI */
1106 *device_uri
, /* Device URI */
1107 *printer_uri
; /* Printer URI */
1108 char scheme
[32], /* URI scheme */
1109 userpass
[256], /* Username and password (unused) */
1110 hostname
[256]; /* Hostname */
1111 int port
; /* Port number */
1114 DEBUG_printf(("_cupsGetDestResource(dest=%p(%s), flags=%u, resource=%p, resourcesize=%d)", (void *)dest
, dest
->name
, flags
, (void *)resource
, (int)resourcesize
));
1117 * Range check input...
1120 if (!dest
|| !resource
|| resourcesize
< 1)
1125 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
1130 * Grab the printer and device URIs...
1133 device_uri
= cupsGetOption("device-uri", dest
->num_options
, dest
->options
);
1134 printer_uri
= cupsGetOption("printer-uri-supported", dest
->num_options
, dest
->options
);
1136 DEBUG_printf(("1_cupsGetDestResource: device-uri=\"%s\", printer-uri-supported=\"%s\".", device_uri
, printer_uri
));
1138 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1139 if (((flags
& CUPS_DEST_FLAGS_DEVICE
) || !printer_uri
) && strstr(device_uri
, "._tcp"))
1141 if ((device_uri
= cups_dnssd_resolve(dest
, device_uri
, 5000, NULL
, NULL
, NULL
)) != NULL
)
1143 DEBUG_printf(("1_cupsGetDestResource: Resolved device-uri=\"%s\".", device_uri
));
1147 DEBUG_puts("1_cupsGetDestResource: Unable to resolve device.");
1152 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(ENOENT
), 0);
1157 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1159 if (flags
& CUPS_DEST_FLAGS_DEVICE
)
1163 else if (printer_uri
)
1169 uri
= _cupsCreateDest(dest
->name
, cupsGetOption("printer-info", dest
->num_options
, dest
->options
), NULL
, device_uri
, resource
, resourcesize
);
1173 DEBUG_printf(("1_cupsGetDestResource: Local printer-uri-supported=\"%s\"", uri
));
1175 dest
->num_options
= cupsAddOption("printer-uri-supported", uri
, dest
->num_options
, &dest
->options
);
1177 uri
= cupsGetOption("printer-uri-supported", dest
->num_options
, dest
->options
);
1183 DEBUG_puts("1_cupsGetDestResource: No printer-uri-supported or device-uri found.");
1188 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(ENOENT
), 0);
1192 else if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
), userpass
, sizeof(userpass
), hostname
, sizeof(hostname
), &port
, resource
, (int)resourcesize
) < HTTP_URI_STATUS_OK
)
1194 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad URI."), 1);
1199 DEBUG_printf(("1_cupsGetDestResource: resource=\"%s\"", resource
));
1206 * 'cupsGetDestWithURI()' - Get a destination associated with a URI.
1208 * "name" is the desired name for the printer. If @code NULL@, a name will be
1209 * created using the URI.
1211 * "uri" is the "ipp" or "ipps" URI for the printer.
1213 * @since CUPS 2.0/macOS 10.10@
1216 cups_dest_t
* /* O - Destination or @code NULL@ */
1217 cupsGetDestWithURI(const char *name
, /* I - Desired printer name or @code NULL@ */
1218 const char *uri
) /* I - URI for the printer */
1220 cups_dest_t
*dest
; /* New destination */
1221 char temp
[1024], /* Temporary string */
1222 scheme
[256], /* Scheme from URI */
1223 userpass
[256], /* Username:password from URI */
1224 hostname
[256], /* Hostname from URI */
1225 resource
[1024], /* Resource path from URI */
1226 *ptr
; /* Pointer into string */
1227 const char *info
; /* printer-info string */
1228 int port
; /* Port number from URI */
1232 * Range check input...
1237 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
1241 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
), userpass
, sizeof(userpass
), hostname
, sizeof(hostname
), &port
, resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
||
1242 (strncmp(uri
, "ipp://", 6) && strncmp(uri
, "ipps://", 7)))
1244 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer-uri."), 1);
1256 * Create the name from the URI...
1259 if (strstr(hostname
, "._tcp"))
1262 * Use the service instance name...
1265 if ((ptr
= strstr(hostname
, "._")) != NULL
)
1268 cups_queue_name(temp
, hostname
, sizeof(temp
));
1272 else if (!strncmp(resource
, "/classes/", 9))
1274 snprintf(temp
, sizeof(temp
), "%s @ %s", resource
+ 9, hostname
);
1275 name
= resource
+ 9;
1278 else if (!strncmp(resource
, "/printers/", 10))
1280 snprintf(temp
, sizeof(temp
), "%s @ %s", resource
+ 10, hostname
);
1281 name
= resource
+ 10;
1292 * Create the destination...
1295 if ((dest
= calloc(1, sizeof(cups_dest_t
))) == NULL
)
1297 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
1301 dest
->name
= _cupsStrAlloc(name
);
1302 dest
->num_options
= cupsAddOption("device-uri", uri
, dest
->num_options
, &(dest
->options
));
1303 dest
->num_options
= cupsAddOption("printer-info", info
, dest
->num_options
, &(dest
->options
));
1310 * '_cupsGetDests()' - Get destinations from a server.
1312 * "op" is IPP_OP_CUPS_GET_PRINTERS to get a full list, IPP_OP_CUPS_GET_DEFAULT
1313 * to get the system-wide default printer, or IPP_OP_GET_PRINTER_ATTRIBUTES for
1316 * "name" is the name of an existing printer and is only used when "op" is
1317 * IPP_OP_GET_PRINTER_ATTRIBUTES.
1319 * "dest" is initialized to point to the array of destinations.
1321 * 0 is returned if there are no printers, no default printer, or the named
1322 * printer does not exist, respectively.
1324 * Free the memory used by the destination array using the @link cupsFreeDests@
1327 * Note: On macOS this function also gets the default paper from the system
1328 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1329 * options array for each destination that supports it.
1332 int /* O - Number of destinations */
1333 _cupsGetDests(http_t
*http
, /* I - Connection to server or
1334 * @code CUPS_HTTP_DEFAULT@ */
1335 ipp_op_t op
, /* I - IPP operation */
1336 const char *name
, /* I - Name of destination */
1337 cups_dest_t
**dests
, /* IO - Destinations */
1338 cups_ptype_t type
, /* I - Printer type bits */
1339 cups_ptype_t mask
) /* I - Printer type mask */
1341 int num_dests
= 0; /* Number of destinations */
1342 cups_dest_t
*dest
; /* Current destination */
1343 ipp_t
*request
, /* IPP Request */
1344 *response
; /* IPP Response */
1345 ipp_attribute_t
*attr
; /* Current attribute */
1346 const char *printer_name
; /* printer-name attribute */
1347 char uri
[1024]; /* printer-uri value */
1348 int num_options
; /* Number of options */
1349 cups_option_t
*options
; /* Options */
1351 char media_default
[41]; /* Default paper size */
1352 #endif /* __APPLE__ */
1353 char optname
[1024], /* Option name */
1354 value
[2048], /* Option value */
1355 *ptr
; /* Pointer into name/value */
1356 static const char * const pattrs
[] = /* Attributes we're interested in */
1358 "auth-info-required",
1360 "job-sheets-default",
1361 "marker-change-time",
1363 "marker-high-levels",
1365 "marker-low-levels",
1371 #endif /* __APPLE__ */
1375 "printer-is-accepting-jobs",
1376 "printer-is-shared",
1377 "printer-is-temporary",
1379 "printer-make-and-model",
1380 "printer-mandatory-job-attributes",
1383 "printer-state-change-time",
1384 "printer-state-reasons",
1386 "printer-uri-supported"
1390 DEBUG_printf(("_cupsGetDests(http=%p, op=%x(%s), name=\"%s\", dests=%p, type=%x, mask=%x)", (void *)http
, op
, ippOpString(op
), name
, (void *)dests
, type
, mask
));
1394 * Get the default paper size...
1397 appleGetPaperSize(media_default
, sizeof(media_default
));
1398 DEBUG_printf(("1_cupsGetDests: Default media is '%s'.", media_default
));
1399 #endif /* __APPLE__ */
1402 * Build a IPP_OP_CUPS_GET_PRINTERS or IPP_OP_GET_PRINTER_ATTRIBUTES request, which
1403 * require the following attributes:
1405 * attributes-charset
1406 * attributes-natural-language
1407 * requesting-user-name
1408 * printer-uri [for IPP_OP_GET_PRINTER_ATTRIBUTES]
1411 request
= ippNewRequest(op
);
1413 ippAddStrings(request
, IPP_TAG_OPERATION
, IPP_TAG_KEYWORD
,
1414 "requested-attributes", sizeof(pattrs
) / sizeof(pattrs
[0]),
1417 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
,
1418 "requesting-user-name", NULL
, cupsUser());
1420 if (name
&& op
!= IPP_OP_CUPS_GET_DEFAULT
)
1422 httpAssembleURIf(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
), "ipp", NULL
,
1423 "localhost", ippPort(), "/printers/%s", name
);
1424 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
,
1429 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type", (int)type
);
1430 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type-mask", (int)mask
);
1434 * Do the request and get back a response...
1437 if ((response
= cupsDoRequest(http
, request
, "/")) != NULL
)
1439 for (attr
= response
->attrs
; attr
!= NULL
; attr
= attr
->next
)
1442 * Skip leading attributes until we hit a printer...
1445 while (attr
!= NULL
&& attr
->group_tag
!= IPP_TAG_PRINTER
)
1452 * Pull the needed attributes from this printer...
1455 printer_name
= NULL
;
1459 for (; attr
&& attr
->group_tag
== IPP_TAG_PRINTER
; attr
= attr
->next
)
1461 if (attr
->value_tag
!= IPP_TAG_INTEGER
&&
1462 attr
->value_tag
!= IPP_TAG_ENUM
&&
1463 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
1464 attr
->value_tag
!= IPP_TAG_TEXT
&&
1465 attr
->value_tag
!= IPP_TAG_TEXTLANG
&&
1466 attr
->value_tag
!= IPP_TAG_NAME
&&
1467 attr
->value_tag
!= IPP_TAG_NAMELANG
&&
1468 attr
->value_tag
!= IPP_TAG_KEYWORD
&&
1469 attr
->value_tag
!= IPP_TAG_RANGE
&&
1470 attr
->value_tag
!= IPP_TAG_URI
)
1473 if (!strcmp(attr
->name
, "auth-info-required") ||
1474 !strcmp(attr
->name
, "device-uri") ||
1475 !strcmp(attr
->name
, "marker-change-time") ||
1476 !strcmp(attr
->name
, "marker-colors") ||
1477 !strcmp(attr
->name
, "marker-high-levels") ||
1478 !strcmp(attr
->name
, "marker-levels") ||
1479 !strcmp(attr
->name
, "marker-low-levels") ||
1480 !strcmp(attr
->name
, "marker-message") ||
1481 !strcmp(attr
->name
, "marker-names") ||
1482 !strcmp(attr
->name
, "marker-types") ||
1483 !strcmp(attr
->name
, "printer-commands") ||
1484 !strcmp(attr
->name
, "printer-info") ||
1485 !strcmp(attr
->name
, "printer-is-shared") ||
1486 !strcmp(attr
->name
, "printer-is-temporary") ||
1487 !strcmp(attr
->name
, "printer-make-and-model") ||
1488 !strcmp(attr
->name
, "printer-mandatory-job-attributes") ||
1489 !strcmp(attr
->name
, "printer-state") ||
1490 !strcmp(attr
->name
, "printer-state-change-time") ||
1491 !strcmp(attr
->name
, "printer-type") ||
1492 !strcmp(attr
->name
, "printer-is-accepting-jobs") ||
1493 !strcmp(attr
->name
, "printer-location") ||
1494 !strcmp(attr
->name
, "printer-state-reasons") ||
1495 !strcmp(attr
->name
, "printer-uri-supported"))
1498 * Add a printer description attribute...
1501 num_options
= cupsAddOption(attr
->name
,
1502 cups_make_string(attr
, value
,
1504 num_options
, &options
);
1507 else if (!strcmp(attr
->name
, "media-supported") && media_default
[0])
1510 * See if we can set a default media size...
1513 int i
; /* Looping var */
1515 for (i
= 0; i
< attr
->num_values
; i
++)
1516 if (!_cups_strcasecmp(media_default
, attr
->values
[i
].string
.text
))
1518 DEBUG_printf(("1_cupsGetDests: Setting media to '%s'.", media_default
));
1519 num_options
= cupsAddOption("media", media_default
, num_options
, &options
);
1523 #endif /* __APPLE__ */
1524 else if (!strcmp(attr
->name
, "printer-name") &&
1525 attr
->value_tag
== IPP_TAG_NAME
)
1526 printer_name
= attr
->values
[0].string
.text
;
1527 else if (strncmp(attr
->name
, "notify-", 7) &&
1528 strncmp(attr
->name
, "print-quality-", 14) &&
1529 (attr
->value_tag
== IPP_TAG_BOOLEAN
||
1530 attr
->value_tag
== IPP_TAG_ENUM
||
1531 attr
->value_tag
== IPP_TAG_INTEGER
||
1532 attr
->value_tag
== IPP_TAG_KEYWORD
||
1533 attr
->value_tag
== IPP_TAG_NAME
||
1534 attr
->value_tag
== IPP_TAG_RANGE
) &&
1535 (ptr
= strstr(attr
->name
, "-default")) != NULL
)
1538 * Add a default option...
1541 strlcpy(optname
, attr
->name
, sizeof(optname
));
1542 optname
[ptr
- attr
->name
] = '\0';
1544 if (_cups_strcasecmp(optname
, "media") || !cupsGetOption("media", num_options
, options
))
1545 num_options
= cupsAddOption(optname
, cups_make_string(attr
, value
, sizeof(value
)), num_options
, &options
);
1550 * See if we have everything needed...
1555 cupsFreeOptions(num_options
, options
);
1563 if ((dest
= cups_add_dest(printer_name
, NULL
, &num_dests
, dests
)) != NULL
)
1565 dest
->num_options
= num_options
;
1566 dest
->options
= options
;
1569 cupsFreeOptions(num_options
, options
);
1575 ippDelete(response
);
1579 * Return the count...
1587 * 'cupsGetDests()' - Get the list of destinations from the default server.
1589 * Starting with CUPS 1.2, the returned list of destinations include the
1590 * "printer-info", "printer-is-accepting-jobs", "printer-is-shared",
1591 * "printer-make-and-model", "printer-state", "printer-state-change-time",
1592 * "printer-state-reasons", "printer-type", and "printer-uri-supported"
1593 * attributes as options.
1595 * CUPS 1.4 adds the "marker-change-time", "marker-colors",
1596 * "marker-high-levels", "marker-levels", "marker-low-levels", "marker-message",
1597 * "marker-names", "marker-types", and "printer-commands" attributes as options.
1599 * CUPS 2.2 adds accessible IPP printers to the list of destinations that can
1600 * be used. The "printer-uri-supported" option will be present for those IPP
1601 * printers that have been recently used.
1603 * Use the @link cupsFreeDests@ function to free the destination list and
1604 * the @link cupsGetDest@ function to find a particular destination.
1609 int /* O - Number of destinations */
1610 cupsGetDests(cups_dest_t
**dests
) /* O - Destinations */
1612 return (cupsGetDests2(CUPS_HTTP_DEFAULT
, dests
));
1617 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1619 * Starting with CUPS 1.2, the returned list of destinations include the
1620 * "printer-info", "printer-is-accepting-jobs", "printer-is-shared",
1621 * "printer-make-and-model", "printer-state", "printer-state-change-time",
1622 * "printer-state-reasons", "printer-type", and "printer-uri-supported"
1623 * attributes as options.
1625 * CUPS 1.4 adds the "marker-change-time", "marker-colors",
1626 * "marker-high-levels", "marker-levels", "marker-low-levels", "marker-message",
1627 * "marker-names", "marker-types", and "printer-commands" attributes as options.
1629 * CUPS 2.2 adds accessible IPP printers to the list of destinations that can
1630 * be used. The "printer-uri-supported" option will be present for those IPP
1631 * printers that have been recently used.
1633 * Use the @link cupsFreeDests@ function to free the destination list and
1634 * the @link cupsGetDest@ function to find a particular destination.
1636 * @since CUPS 1.1.21/macOS 10.4@
1639 int /* O - Number of destinations */
1640 cupsGetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1641 cups_dest_t
**dests
) /* O - Destinations */
1643 _cups_getdata_t data
; /* Enumeration data */
1646 DEBUG_printf(("cupsGetDests2(http=%p, dests=%p)", (void *)http
, (void *)dests
));
1649 * Range check the input...
1654 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad NULL dests pointer"), 1);
1655 DEBUG_puts("1cupsGetDests2: NULL dests pointer, returning 0.");
1660 * Connect to the server as needed...
1665 if ((http
= _cupsConnect()) == NULL
)
1674 * Grab the printers and classes...
1680 if (!httpAddrLocalhost(httpGetAddress(http
)))
1683 * When talking to a remote cupsd, just enumerate printers on the remote
1687 cups_enum_dests(http
, 0, _CUPS_DNSSD_GET_DESTS
, NULL
, 0, CUPS_PRINTER_DISCOVERED
, (cups_dest_cb_t
)cups_get_cb
, &data
);
1692 * When talking to a local cupsd, enumerate both local printers and ones we
1693 * can find on the network...
1696 cups_enum_dests(http
, 0, _CUPS_DNSSD_GET_DESTS
, NULL
, 0, 0, (cups_dest_cb_t
)cups_get_cb
, &data
);
1700 * Return the number of destinations...
1703 *dests
= data
.dests
;
1705 if (data
.num_dests
> 0)
1706 _cupsSetError(IPP_STATUS_OK
, NULL
, 0);
1708 DEBUG_printf(("1cupsGetDests2: Returning %d destinations.", data
.num_dests
));
1710 return (data
.num_dests
);
1715 * 'cupsGetNamedDest()' - Get options for the named destination.
1717 * This function is optimized for retrieving a single destination and should
1718 * be used instead of @link cupsGetDests2@ and @link cupsGetDest@ when you
1719 * either know the name of the destination or want to print to the default
1720 * destination. If @code NULL@ is returned, the destination does not exist or
1721 * there is no default destination.
1723 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
1724 * server will be used.
1726 * If "name" is @code NULL@, the default printer for the current user will be
1729 * The returned destination must be freed using @link cupsFreeDests@ with a
1730 * "num_dests" value of 1.
1732 * @since CUPS 1.4/macOS 10.6@
1735 cups_dest_t
* /* O - Destination or @code NULL@ */
1736 cupsGetNamedDest(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1737 const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1738 const char *instance
) /* I - Instance name or @code NULL@ */
1740 const char *dest_name
; /* Working destination name */
1741 cups_dest_t
*dest
; /* Destination */
1742 char filename
[1024], /* Path to lpoptions */
1743 defname
[256]; /* Default printer name */
1744 const char *home
= getenv("HOME"); /* Home directory */
1745 int set_as_default
= 0; /* Set returned destination as default */
1746 ipp_op_t op
= IPP_OP_GET_PRINTER_ATTRIBUTES
;
1747 /* IPP operation to get server ops */
1748 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1751 DEBUG_printf(("cupsGetNamedDest(http=%p, name=\"%s\", instance=\"%s\")", (void *)http
, name
, instance
));
1754 * If "name" is NULL, find the default destination...
1762 dest_name
= _cupsUserDefault(defname
, sizeof(defname
));
1766 char *ptr
; /* Temporary pointer... */
1768 if ((ptr
= strchr(defname
, '/')) != NULL
)
1779 * No default in the environment, try the user's lpoptions files...
1782 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1784 dest_name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1793 * Still not there? Try the system lpoptions file...
1796 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1797 dest_name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1806 * No locally-set default destination, ask the server...
1809 op
= IPP_OP_CUPS_GET_DEFAULT
;
1812 DEBUG_puts("1cupsGetNamedDest: Asking server for default printer...");
1815 DEBUG_printf(("1cupsGetNamedDest: Using name=\"%s\"...", name
));
1819 * Get the printer's attributes...
1822 if (!_cupsGetDests(http
, op
, dest_name
, &dest
, 0, 0))
1826 _cups_namedata_t data
; /* Callback data */
1828 DEBUG_puts("1cupsGetNamedDest: No queue found for printer, looking on network...");
1833 cupsEnumDests(0, 1000, NULL
, 0, 0, (cups_dest_cb_t
)cups_name_cb
, &data
);
1842 switch (set_as_default
)
1847 case 1 : /* Set from env vars */
1848 if (getenv("LPDEST"))
1849 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND
, _("LPDEST environment variable names default destination that does not exist."), 1);
1850 else if (getenv("PRINTER"))
1851 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND
, _("PRINTER environment variable names default destination that does not exist."), 1);
1853 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND
, _("No default destination."), 1);
1856 case 2 : /* Set from ~/.cups/lpoptions */
1857 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND
, _("~/.cups/lpoptions file names default destination that does not exist."), 1);
1860 case 3 : /* Set from /etc/cups/lpoptions */
1861 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND
, _("/etc/cups/lpoptions file names default destination that does not exist."), 1);
1864 case 4 : /* Set from server */
1865 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND
, _("No default destination."), 1);
1873 DEBUG_printf(("1cupsGetNamedDest: Got dest=%p", (void *)dest
));
1876 dest
->instance
= _cupsStrAlloc(instance
);
1879 dest
->is_default
= 1;
1882 * Then add local options...
1885 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1886 cups_get_dests(filename
, dest_name
, instance
, 0, 1, 1, &dest
);
1890 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1892 cups_get_dests(filename
, dest_name
, instance
, 0, 1, 1, &dest
);
1896 * Return the result...
1904 * 'cupsRemoveDest()' - Remove a destination from the destination list.
1906 * Removing a destination/instance does not delete the class or printer
1907 * queue, merely the lpoptions for that destination/instance. Use the
1908 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
1909 * options for the user.
1911 * @since CUPS 1.3/macOS 10.5@
1914 int /* O - New number of destinations */
1915 cupsRemoveDest(const char *name
, /* I - Destination name */
1916 const char *instance
, /* I - Instance name or @code NULL@ */
1917 int num_dests
, /* I - Number of destinations */
1918 cups_dest_t
**dests
) /* IO - Destinations */
1920 int i
; /* Index into destinations */
1921 cups_dest_t
*dest
; /* Pointer to destination */
1925 * Find the destination...
1928 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
1935 _cupsStrFree(dest
->name
);
1936 _cupsStrFree(dest
->instance
);
1937 cupsFreeOptions(dest
->num_options
, dest
->options
);
1940 * Remove the destination from the array...
1945 i
= (int)(dest
- *dests
);
1948 memmove(dest
, dest
+ 1, (size_t)(num_dests
- i
) * sizeof(cups_dest_t
));
1955 * 'cupsSetDefaultDest()' - Set the default destination.
1957 * @since CUPS 1.3/macOS 10.5@
1962 const char *name
, /* I - Destination name */
1963 const char *instance
, /* I - Instance name or @code NULL@ */
1964 int num_dests
, /* I - Number of destinations */
1965 cups_dest_t
*dests
) /* I - Destinations */
1967 int i
; /* Looping var */
1968 cups_dest_t
*dest
; /* Current destination */
1972 * Range check input...
1975 if (!name
|| num_dests
<= 0 || !dests
)
1979 * Loop through the array and set the "is_default" flag for the matching
1983 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1984 dest
->is_default
= !_cups_strcasecmp(name
, dest
->name
) &&
1985 ((!instance
&& !dest
->instance
) ||
1986 (instance
&& dest
->instance
&&
1987 !_cups_strcasecmp(instance
, dest
->instance
)));
1992 * 'cupsSetDests()' - Save the list of destinations for the default server.
1994 * This function saves the destinations to /etc/cups/lpoptions when run
1995 * as root and ~/.cups/lpoptions when run as a normal user.
2001 cupsSetDests(int num_dests
, /* I - Number of destinations */
2002 cups_dest_t
*dests
) /* I - Destinations */
2004 cupsSetDests2(CUPS_HTTP_DEFAULT
, num_dests
, dests
);
2009 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
2011 * This function saves the destinations to /etc/cups/lpoptions when run
2012 * as root and ~/.cups/lpoptions when run as a normal user.
2014 * @since CUPS 1.1.21/macOS 10.4@
2017 int /* O - 0 on success, -1 on error */
2018 cupsSetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2019 int num_dests
, /* I - Number of destinations */
2020 cups_dest_t
*dests
) /* I - Destinations */
2022 int i
, j
; /* Looping vars */
2023 int wrote
; /* Wrote definition? */
2024 cups_dest_t
*dest
; /* Current destination */
2025 cups_option_t
*option
; /* Current option */
2026 _ipp_option_t
*match
; /* Matching attribute for option */
2027 FILE *fp
; /* File pointer */
2029 const char *home
; /* HOME environment variable */
2031 char filename
[1024]; /* lpoptions file */
2032 int num_temps
; /* Number of temporary destinations */
2033 cups_dest_t
*temps
= NULL
, /* Temporary destinations */
2034 *temp
; /* Current temporary dest */
2035 const char *val
; /* Value of temporary option */
2036 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
2040 * Range check the input...
2043 if (!num_dests
|| !dests
)
2047 * Get the server destinations...
2050 num_temps
= _cupsGetDests(http
, IPP_OP_CUPS_GET_PRINTERS
, NULL
, &temps
, 0, 0);
2052 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE
)
2054 cupsFreeDests(num_temps
, temps
);
2059 * Figure out which file to write to...
2062 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
2068 * Point to user defaults...
2071 if ((home
= getenv("HOME")) != NULL
)
2074 * Create ~/.cups subdirectory...
2077 snprintf(filename
, sizeof(filename
), "%s/.cups", home
);
2078 if (access(filename
, 0))
2079 mkdir(filename
, 0700);
2081 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
2087 * Try to open the file...
2090 if ((fp
= fopen(filename
, "w")) == NULL
)
2092 cupsFreeDests(num_temps
, temps
);
2098 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2103 fchmod(fileno(fp
), 0644);
2107 * Write each printer; each line looks like:
2109 * Dest name[/instance] options
2110 * Default name[/instance] options
2113 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
2114 if (dest
->instance
!= NULL
|| dest
->num_options
!= 0 || dest
->is_default
)
2116 if (dest
->is_default
)
2118 fprintf(fp
, "Default %s", dest
->name
);
2120 fprintf(fp
, "/%s", dest
->instance
);
2127 temp
= cupsGetDest(dest
->name
, NULL
, num_temps
, temps
);
2129 for (j
= dest
->num_options
, option
= dest
->options
; j
> 0; j
--, option
++)
2132 * See if this option is a printer attribute; if so, skip it...
2135 if ((match
= _ippFindOption(option
->name
)) != NULL
&& match
->group_tag
== IPP_TAG_PRINTER
)
2139 * See if the server options match these; if so, don't write 'em.
2142 if (temp
&& (val
= cupsGetOption(option
->name
, temp
->num_options
, temp
->options
)) != NULL
&& !_cups_strcasecmp(val
, option
->value
))
2146 * Options don't match, write to the file...
2151 fprintf(fp
, "Dest %s", dest
->name
);
2153 fprintf(fp
, "/%s", dest
->instance
);
2157 if (option
->value
[0])
2159 if (strchr(option
->value
, ' ') || strchr(option
->value
, '\\') || strchr(option
->value
, '\"') || strchr(option
->value
, '\''))
2162 * Quote the value...
2165 fprintf(fp
, " %s=\"", option
->name
);
2167 for (val
= option
->value
; *val
; val
++)
2169 if (strchr("\"\'\\", *val
))
2180 * Store the literal value...
2183 fprintf(fp
, " %s=%s", option
->name
, option
->value
);
2187 fprintf(fp
, " %s", option
->name
);
2195 * Free the temporary destinations and close the file...
2198 cupsFreeDests(num_temps
, temps
);
2204 * Set the default printer for this location - this allows command-line
2205 * and GUI applications to share the same default destination...
2208 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, dests
)) != NULL
)
2210 CFStringRef name
= CFStringCreateWithCString(kCFAllocatorDefault
, dest
->name
, kCFStringEncodingUTF8
);
2211 /* Default printer name */
2215 _cupsAppleSetDefaultPrinter(name
);
2219 #endif /* __APPLE__ */
2221 #ifdef HAVE_NOTIFY_POST
2223 * Send a notification so that macOS applications can know about the
2227 notify_post("com.apple.printerListChange");
2228 #endif /* HAVE_NOTIFY_POST */
2235 * '_cupsUserDefault()' - Get the user default printer from environment
2236 * variables and location information.
2239 char * /* O - Default printer or NULL */
2240 _cupsUserDefault(char *name
, /* I - Name buffer */
2241 size_t namesize
) /* I - Size of name buffer */
2243 const char *env
; /* LPDEST or PRINTER env variable */
2245 CFStringRef locprinter
; /* Last printer as this location */
2246 #endif /* __APPLE__ */
2249 if ((env
= getenv("LPDEST")) == NULL
)
2250 if ((env
= getenv("PRINTER")) != NULL
&& !strcmp(env
, "lp"))
2255 strlcpy(name
, env
, namesize
);
2261 * Use location-based defaults if "use last printer" is selected in the
2262 * system preferences...
2265 if ((locprinter
= _cupsAppleCopyDefaultPrinter()) != NULL
)
2267 CFStringGetCString(locprinter
, name
, (CFIndex
)namesize
, kCFStringEncodingUTF8
);
2268 CFRelease(locprinter
);
2273 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name
));
2275 return (*name
? name
: NULL
);
2279 * No location-based defaults on this platform...
2284 #endif /* __APPLE__ */
2288 #if _CUPS_LOCATION_DEFAULTS
2290 * 'appleCopyLocations()' - Copy the location history array.
2293 static CFArrayRef
/* O - Location array or NULL */
2294 appleCopyLocations(void)
2296 CFArrayRef locations
; /* Location array */
2300 * Look up the location array in the preferences...
2303 if ((locations
= CFPreferencesCopyAppValue(kLastUsedPrintersKey
,
2304 kCUPSPrintingPrefs
)) == NULL
)
2307 if (CFGetTypeID(locations
) != CFArrayGetTypeID())
2309 CFRelease(locations
);
2318 * 'appleCopyNetwork()' - Get the network ID for the current location.
2321 static CFStringRef
/* O - Network ID */
2322 appleCopyNetwork(void)
2324 SCDynamicStoreRef dynamicStore
; /* System configuration data */
2325 CFStringRef key
; /* Current network configuration key */
2326 CFDictionaryRef ip_dict
; /* Network configuration data */
2327 CFStringRef network
= NULL
; /* Current network ID */
2330 if ((dynamicStore
= SCDynamicStoreCreate(NULL
, CFSTR("libcups"), NULL
,
2334 * First use the IPv6 router address, if available, since that will generally
2335 * be a globally-unique link-local address.
2338 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2339 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv6
)) != NULL
)
2341 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2343 if ((network
= CFDictionaryGetValue(ip_dict
,
2344 kSCPropNetIPv6Router
)) != NULL
)
2354 * If that doesn't work, try the IPv4 router address. This isn't as unique
2355 * and will likely be a 10.x.y.z or 192.168.y.z address...
2360 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2361 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv4
)) != NULL
)
2363 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2365 if ((network
= CFDictionaryGetValue(ip_dict
,
2366 kSCPropNetIPv4Router
)) != NULL
)
2376 CFRelease(dynamicStore
);
2381 #endif /* _CUPS_LOCATION_DEFAULTS */
2386 * 'appleGetPaperSize()' - Get the default paper size.
2389 static char * /* O - Default paper size */
2390 appleGetPaperSize(char *name
, /* I - Paper size name buffer */
2391 size_t namesize
) /* I - Size of buffer */
2393 CFStringRef defaultPaperID
; /* Default paper ID */
2394 pwg_media_t
*pwgmedia
; /* PWG media size */
2397 defaultPaperID
= _cupsAppleCopyDefaultPaperID();
2398 if (!defaultPaperID
||
2399 CFGetTypeID(defaultPaperID
) != CFStringGetTypeID() ||
2400 !CFStringGetCString(defaultPaperID
, name
, (CFIndex
)namesize
, kCFStringEncodingUTF8
))
2402 else if ((pwgmedia
= pwgMediaForLegacy(name
)) != NULL
)
2403 strlcpy(name
, pwgmedia
->pwg
, namesize
);
2406 CFRelease(defaultPaperID
);
2410 #endif /* __APPLE__ */
2413 #if _CUPS_LOCATION_DEFAULTS
2415 * 'appleGetPrinter()' - Get a printer from the history array.
2418 static CFStringRef
/* O - Printer name or NULL */
2419 appleGetPrinter(CFArrayRef locations
, /* I - Location array */
2420 CFStringRef network
, /* I - Network name */
2421 CFIndex
*locindex
) /* O - Index in array */
2423 CFIndex i
, /* Looping var */
2424 count
; /* Number of locations */
2425 CFDictionaryRef location
; /* Current location */
2426 CFStringRef locnetwork
, /* Current network */
2427 locprinter
; /* Current printer */
2430 for (i
= 0, count
= CFArrayGetCount(locations
); i
< count
; i
++)
2431 if ((location
= CFArrayGetValueAtIndex(locations
, i
)) != NULL
&&
2432 CFGetTypeID(location
) == CFDictionaryGetTypeID())
2434 if ((locnetwork
= CFDictionaryGetValue(location
,
2435 kLocationNetworkKey
)) != NULL
&&
2436 CFGetTypeID(locnetwork
) == CFStringGetTypeID() &&
2437 CFStringCompare(network
, locnetwork
, 0) == kCFCompareEqualTo
&&
2438 (locprinter
= CFDictionaryGetValue(location
,
2439 kLocationPrinterIDKey
)) != NULL
&&
2440 CFGetTypeID(locprinter
) == CFStringGetTypeID())
2445 return (locprinter
);
2451 #endif /* _CUPS_LOCATION_DEFAULTS */
2455 * 'cups_add_dest()' - Add a destination to the array.
2457 * Unlike cupsAddDest(), this function does not check for duplicates.
2460 static cups_dest_t
* /* O - New destination */
2461 cups_add_dest(const char *name
, /* I - Name of destination */
2462 const char *instance
, /* I - Instance or NULL */
2463 int *num_dests
, /* IO - Number of destinations */
2464 cups_dest_t
**dests
) /* IO - Destinations */
2466 int insert
, /* Insertion point */
2467 diff
; /* Result of comparison */
2468 cups_dest_t
*dest
; /* Destination pointer */
2472 * Add new destination...
2475 if (*num_dests
== 0)
2476 dest
= malloc(sizeof(cups_dest_t
));
2478 dest
= realloc(*dests
, sizeof(cups_dest_t
) * (size_t)(*num_dests
+ 1));
2486 * Find where to insert the destination...
2489 if (*num_dests
== 0)
2493 insert
= cups_find_dest(name
, instance
, *num_dests
, *dests
, *num_dests
- 1,
2501 * Move the array elements as needed...
2504 if (insert
< *num_dests
)
2505 memmove(*dests
+ insert
+ 1, *dests
+ insert
, (size_t)(*num_dests
- insert
) * sizeof(cups_dest_t
));
2510 * Initialize the destination...
2513 dest
= *dests
+ insert
;
2514 dest
->name
= _cupsStrAlloc(name
);
2515 dest
->instance
= _cupsStrAlloc(instance
);
2516 dest
->is_default
= 0;
2517 dest
->num_options
= 0;
2518 dest
->options
= (cups_option_t
*)0;
2526 * 'cups_block_cb()' - Enumeration callback for block API.
2529 static int /* O - 1 to continue, 0 to stop */
2531 cups_dest_block_t block
, /* I - Block */
2532 unsigned flags
, /* I - Destination flags */
2533 cups_dest_t
*dest
) /* I - Destination */
2535 return ((block
)(flags
, dest
));
2537 # endif /* __BLOCKS__ */
2541 * 'cups_compare_dests()' - Compare two destinations.
2544 static int /* O - Result of comparison */
2545 cups_compare_dests(cups_dest_t
*a
, /* I - First destination */
2546 cups_dest_t
*b
) /* I - Second destination */
2548 int diff
; /* Difference */
2551 if ((diff
= _cups_strcasecmp(a
->name
, b
->name
)) != 0)
2553 else if (a
->instance
&& b
->instance
)
2554 return (_cups_strcasecmp(a
->instance
, b
->instance
));
2556 return ((a
->instance
&& !b
->instance
) - (!a
->instance
&& b
->instance
));
2560 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
2563 * 'cups_dnssd_browse_cb()' - Browse for printers.
2567 cups_dnssd_browse_cb(
2568 DNSServiceRef sdRef
, /* I - Service reference */
2569 DNSServiceFlags flags
, /* I - Option flags */
2570 uint32_t interfaceIndex
, /* I - Interface number */
2571 DNSServiceErrorType errorCode
, /* I - Error, if any */
2572 const char *serviceName
, /* I - Name of service/device */
2573 const char *regtype
, /* I - Type of service */
2574 const char *replyDomain
, /* I - Service domain */
2575 void *context
) /* I - Enumeration data */
2577 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2578 /* Enumeration data */
2581 DEBUG_printf(("5cups_dnssd_browse_cb(sdRef=%p, flags=%x, interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", regtype=\"%s\", replyDomain=\"%s\", context=%p)", (void *)sdRef
, flags
, interfaceIndex
, errorCode
, serviceName
, regtype
, replyDomain
, context
));
2584 * Don't do anything on error...
2587 if (errorCode
!= kDNSServiceErr_NoError
)
2594 cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2598 # else /* HAVE_AVAHI */
2600 * 'cups_dnssd_browse_cb()' - Browse for printers.
2604 cups_dnssd_browse_cb(
2605 AvahiServiceBrowser
*browser
, /* I - Browser */
2606 AvahiIfIndex interface
, /* I - Interface index (unused) */
2607 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2608 AvahiBrowserEvent event
, /* I - What happened */
2609 const char *name
, /* I - Service name */
2610 const char *type
, /* I - Registration type */
2611 const char *domain
, /* I - Domain */
2612 AvahiLookupResultFlags flags
, /* I - Flags */
2613 void *context
) /* I - Devices array */
2616 AvahiClient
*client
= avahi_service_browser_get_client(browser
);
2617 /* Client information */
2619 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2620 /* Enumeration data */
2627 DEBUG_printf(("cups_dnssd_browse_cb(..., name=\"%s\", type=\"%s\", domain=\"%s\", ...);", name
, type
, domain
));
2631 case AVAHI_BROWSER_FAILURE
:
2632 DEBUG_printf(("cups_dnssd_browse_cb: %s", avahi_strerror(avahi_client_errno(client
))));
2633 avahi_simple_poll_quit(data
->simple_poll
);
2636 case AVAHI_BROWSER_NEW
:
2638 * This object is new on the network.
2641 cups_dnssd_get_device(data
, name
, type
, domain
);
2644 case AVAHI_BROWSER_REMOVE
:
2645 case AVAHI_BROWSER_CACHE_EXHAUSTED
:
2648 case AVAHI_BROWSER_ALL_FOR_NOW
:
2649 DEBUG_puts("cups_dnssd_browse_cb: ALL_FOR_NOW");
2657 * 'cups_dnssd_client_cb()' - Avahi client callback function.
2661 cups_dnssd_client_cb(
2662 AvahiClient
*client
, /* I - Client information (unused) */
2663 AvahiClientState state
, /* I - Current state */
2664 void *context
) /* I - User data (unused) */
2666 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2667 /* Enumeration data */
2672 DEBUG_printf(("cups_dnssd_client_cb(client=%p, state=%d, context=%p)", client
, state
, context
));
2675 * If the connection drops, quit.
2678 if (state
== AVAHI_CLIENT_FAILURE
)
2680 DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
2681 avahi_simple_poll_quit(data
->simple_poll
);
2684 # endif /* HAVE_DNSSD */
2688 * 'cups_dnssd_compare_device()' - Compare two devices.
2691 static int /* O - Result of comparison */
2692 cups_dnssd_compare_devices(
2693 _cups_dnssd_device_t
*a
, /* I - First device */
2694 _cups_dnssd_device_t
*b
) /* I - Second device */
2696 return (strcmp(a
->dest
.name
, b
->dest
.name
));
2701 * 'cups_dnssd_free_device()' - Free the memory used by a device.
2705 cups_dnssd_free_device(
2706 _cups_dnssd_device_t
*device
, /* I - Device */
2707 _cups_dnssd_data_t
*data
) /* I - Enumeration data */
2709 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", (void *)device
, device
->dest
.name
, (void *)data
));
2713 DNSServiceRefDeallocate(device
->ref
);
2714 # else /* HAVE_AVAHI */
2716 avahi_record_browser_free(device
->ref
);
2717 # endif /* HAVE_DNSSD */
2719 _cupsStrFree(device
->domain
);
2720 _cupsStrFree(device
->fullName
);
2721 _cupsStrFree(device
->regtype
);
2722 _cupsStrFree(device
->dest
.name
);
2724 cupsFreeOptions(device
->dest
.num_options
, device
->dest
.options
);
2731 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
2734 static _cups_dnssd_device_t
* /* O - Device */
2735 cups_dnssd_get_device(
2736 _cups_dnssd_data_t
*data
, /* I - Enumeration data */
2737 const char *serviceName
, /* I - Service name */
2738 const char *regtype
, /* I - Registration type */
2739 const char *replyDomain
) /* I - Domain name */
2741 _cups_dnssd_device_t key
, /* Search key */
2742 *device
; /* Device */
2743 char fullName
[kDNSServiceMaxDomainName
],
2744 /* Full name for query */
2745 name
[128]; /* Queue name */
2748 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", regtype=\"%s\", replyDomain=\"%s\")", (void *)data
, serviceName
, regtype
, replyDomain
));
2751 * See if this is an existing device...
2754 cups_queue_name(name
, serviceName
, sizeof(name
));
2756 key
.dest
.name
= name
;
2758 if ((device
= cupsArrayFind(data
->devices
, &key
)) != NULL
)
2761 * Yes, see if we need to do anything with this...
2764 int update
= 0; /* Non-zero if we need to update */
2766 if (!_cups_strcasecmp(replyDomain
, "local.") &&
2767 _cups_strcasecmp(device
->domain
, replyDomain
))
2770 * Update the "global" listing to use the .local domain name instead.
2773 _cupsStrFree(device
->domain
);
2774 device
->domain
= _cupsStrAlloc(replyDomain
);
2776 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
2777 "domain.", device
->dest
.name
));
2782 if (!_cups_strcasecmp(regtype
, "_ipps._tcp") &&
2783 _cups_strcasecmp(device
->regtype
, regtype
))
2786 * Prefer IPPS over IPP.
2789 _cupsStrFree(device
->regtype
);
2790 device
->regtype
= _cupsStrAlloc(regtype
);
2792 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
2793 device
->dest
.name
));
2800 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
2801 device
->dest
.name
));
2808 * No, add the device...
2811 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
2812 "'%s'.", serviceName
,
2813 !strcmp(regtype
, "_ipps._tcp") ? "IPPS" : "IPP",
2816 device
= calloc(sizeof(_cups_dnssd_device_t
), 1);
2817 device
->dest
.name
= _cupsStrAlloc(name
);
2818 device
->domain
= _cupsStrAlloc(replyDomain
);
2819 device
->regtype
= _cupsStrAlloc(regtype
);
2821 device
->dest
.num_options
= cupsAddOption("printer-info", serviceName
, 0, &device
->dest
.options
);
2823 cupsArrayAdd(data
->devices
, device
);
2827 * Set the "full name" of this service, which is used for queries...
2831 DNSServiceConstructFullName(fullName
, serviceName
, regtype
, replyDomain
);
2832 # else /* HAVE_AVAHI */
2833 avahi_service_name_join(fullName
, kDNSServiceMaxDomainName
, serviceName
, regtype
, replyDomain
);
2834 # endif /* HAVE_DNSSD */
2836 _cupsStrFree(device
->fullName
);
2837 device
->fullName
= _cupsStrAlloc(fullName
);
2842 DNSServiceRefDeallocate(device
->ref
);
2843 # else /* HAVE_AVAHI */
2844 avahi_record_browser_free(device
->ref
);
2845 # endif /* HAVE_DNSSD */
2850 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
2852 DEBUG_printf(("6cups_dnssd_get_device: Remove callback for \"%s\".", device
->dest
.name
));
2854 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
2855 device
->state
= _CUPS_DNSSD_NEW
;
2864 * 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
2866 * Note: This function is needed because avahi_simple_poll_iterate is broken
2867 * and always uses a timeout of 0 (!) milliseconds.
2868 * (https://github.com/lathiat/avahi/issues/127)
2873 static int /* O - Number of file descriptors matching */
2875 struct pollfd
*pollfds
, /* I - File descriptors */
2876 unsigned int num_pollfds
, /* I - Number of file descriptors */
2877 int timeout
, /* I - Timeout in milliseconds (unused) */
2878 void *context
) /* I - User data (unused) */
2880 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2881 /* Enumeration data */
2882 int val
; /* Return value */
2885 DEBUG_printf(("cups_dnssd_poll_cb(pollfds=%p, num_pollfds=%d, timeout=%d, context=%p)", pollfds
, num_pollfds
, timeout
, context
));
2889 val
= poll(pollfds
, num_pollfds
, _CUPS_DNSSD_MAXTIME
);
2891 DEBUG_printf(("cups_dnssd_poll_cb: poll() returned %d", val
));
2895 DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno
)));
2904 # endif /* HAVE_AVAHI */
2908 * 'cups_dnssd_query_cb()' - Process query data.
2912 cups_dnssd_query_cb(
2914 DNSServiceRef sdRef
, /* I - Service reference */
2915 DNSServiceFlags flags
, /* I - Data flags */
2916 uint32_t interfaceIndex
, /* I - Interface */
2917 DNSServiceErrorType errorCode
, /* I - Error, if any */
2918 const char *fullName
, /* I - Full service name */
2919 uint16_t rrtype
, /* I - Record type */
2920 uint16_t rrclass
, /* I - Record class */
2921 uint16_t rdlen
, /* I - Length of record data */
2922 const void *rdata
, /* I - Record data */
2923 uint32_t ttl
, /* I - Time-to-live */
2924 # else /* HAVE_AVAHI */
2925 AvahiRecordBrowser
*browser
, /* I - Record browser */
2926 AvahiIfIndex interfaceIndex
,
2927 /* I - Interface index (unused) */
2928 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2929 AvahiBrowserEvent event
, /* I - What happened? */
2930 const char *fullName
, /* I - Service name */
2931 uint16_t rrclass
, /* I - Record class */
2932 uint16_t rrtype
, /* I - Record type */
2933 const void *rdata
, /* I - TXT record */
2934 size_t rdlen
, /* I - Length of TXT record */
2935 AvahiLookupResultFlags flags
, /* I - Flags */
2936 # endif /* HAVE_DNSSD */
2937 void *context
) /* I - Enumeration data */
2939 # if defined(DEBUG) && defined(HAVE_AVAHI)
2940 AvahiClient
*client
= avahi_record_browser_get_client(browser
);
2941 /* Client information */
2942 # endif /* DEBUG && HAVE_AVAHI */
2943 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2944 /* Enumeration data */
2945 char serviceName
[256],/* Service name */
2946 name
[128], /* Queue name */
2947 *ptr
; /* Pointer into string */
2948 _cups_dnssd_device_t dkey
, /* Search key */
2949 *device
; /* Device */
2953 DEBUG_printf(("5cups_dnssd_query_cb(sdRef=%p, flags=%x, interfaceIndex=%d, errorCode=%d, fullName=\"%s\", rrtype=%u, rrclass=%u, rdlen=%u, rdata=%p, ttl=%u, context=%p)", (void *)sdRef
, flags
, interfaceIndex
, errorCode
, fullName
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, context
));
2956 * Only process "add" data...
2959 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
2962 # else /* HAVE_AVAHI */
2963 DEBUG_printf(("cups_dnssd_query_cb(browser=%p, interfaceIndex=%d, protocol=%d, event=%d, fullName=\"%s\", rrclass=%u, rrtype=%u, rdata=%p, rdlen=%u, flags=%x, context=%p)", browser
, interfaceIndex
, protocol
, event
, fullName
, rrclass
, rrtype
, rdata
, (unsigned)rdlen
, flags
, context
));
2966 * Only process "add" data...
2969 if (event
!= AVAHI_BROWSER_NEW
)
2971 if (event
== AVAHI_BROWSER_FAILURE
)
2972 DEBUG_printf(("cups_dnssd_query_cb: %s", avahi_strerror(avahi_client_errno(client
))));
2976 # endif /* HAVE_DNSSD */
2979 * Lookup the service in the devices array.
2982 cups_dnssd_unquote(serviceName
, fullName
, sizeof(serviceName
));
2984 if ((ptr
= strstr(serviceName
, "._")) != NULL
)
2987 cups_queue_name(name
, serviceName
, sizeof(name
));
2989 dkey
.dest
.name
= name
;
2991 if ((device
= cupsArrayFind(data
->devices
, &dkey
)) != NULL
&& device
->state
== _CUPS_DNSSD_NEW
)
2994 * Found it, pull out the make and model from the TXT record and save it...
2997 const uint8_t *txt
, /* Pointer into data */
2998 *txtnext
, /* Next key/value pair */
2999 *txtend
; /* End of entire TXT record */
3000 uint8_t txtlen
; /* Length of current key/value pair */
3001 char key
[256], /* Key string */
3002 value
[256], /* Value string */
3003 make_and_model
[512],
3004 /* Manufacturer and model */
3005 model
[256], /* Model */
3006 uriname
[1024], /* Name for URI */
3007 uri
[1024]; /* Printer URI */
3008 cups_ptype_t type
= CUPS_PRINTER_DISCOVERED
| CUPS_PRINTER_BW
;
3010 int saw_printer_type
= 0;
3011 /* Did we see a printer-type key? */
3013 device
->state
= _CUPS_DNSSD_PENDING
;
3014 make_and_model
[0] = '\0';
3016 strlcpy(model
, "Unknown", sizeof(model
));
3018 for (txt
= rdata
, txtend
= txt
+ rdlen
;
3023 * Read a key/value pair starting with an 8-bit length. Since the
3024 * length is 8 bits and the size of the key/value buffers is 256, we
3025 * don't need to check for overflow...
3030 if (!txtlen
|| (txt
+ txtlen
) > txtend
)
3033 txtnext
= txt
+ txtlen
;
3035 for (ptr
= key
; txt
< txtnext
&& *txt
!= '='; txt
++)
3036 *ptr
++ = (char)*txt
;
3039 if (txt
< txtnext
&& *txt
== '=')
3044 memcpy(value
, txt
, (size_t)(txtnext
- txt
));
3045 value
[txtnext
- txt
] = '\0';
3047 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key
, value
));
3051 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key
));
3055 if (!_cups_strcasecmp(key
, "usb_MFG") ||
3056 !_cups_strcasecmp(key
, "usb_MANU") ||
3057 !_cups_strcasecmp(key
, "usb_MANUFACTURER"))
3058 strlcpy(make_and_model
, value
, sizeof(make_and_model
));
3059 else if (!_cups_strcasecmp(key
, "usb_MDL") ||
3060 !_cups_strcasecmp(key
, "usb_MODEL"))
3061 strlcpy(model
, value
, sizeof(model
));
3062 else if (!_cups_strcasecmp(key
, "product") && !strstr(value
, "Ghostscript"))
3064 if (value
[0] == '(')
3067 * Strip parenthesis...
3070 if ((ptr
= value
+ strlen(value
) - 1) > value
&& *ptr
== ')')
3073 strlcpy(model
, value
+ 1, sizeof(model
));
3076 strlcpy(model
, value
, sizeof(model
));
3078 else if (!_cups_strcasecmp(key
, "ty"))
3080 strlcpy(model
, value
, sizeof(model
));
3082 if ((ptr
= strchr(model
, ',')) != NULL
)
3085 else if (!_cups_strcasecmp(key
, "note"))
3086 device
->dest
.num_options
= cupsAddOption("printer-location", value
,
3087 device
->dest
.num_options
,
3088 &device
->dest
.options
);
3089 else if (!_cups_strcasecmp(key
, "pdl"))
3092 * Look for PDF-capable printers; only PDF-capable printers are shown.
3095 const char *start
, *next
; /* Pointer into value */
3096 int have_pdf
= 0, /* Have PDF? */
3097 have_raster
= 0;/* Have raster format support? */
3099 for (start
= value
; start
&& *start
; start
= next
)
3101 if (!_cups_strncasecmp(start
, "application/pdf", 15) && (!start
[15] || start
[15] == ','))
3106 else if ((!_cups_strncasecmp(start
, "image/pwg-raster", 16) && (!start
[16] || start
[16] == ',')) ||
3107 (!_cups_strncasecmp(start
, "image/urf", 9) && (!start
[9] || start
[9] == ',')))
3113 if ((next
= strchr(start
, ',')) != NULL
)
3117 if (!have_pdf
&& !have_raster
)
3118 device
->state
= _CUPS_DNSSD_INCOMPATIBLE
;
3120 else if (!_cups_strcasecmp(key
, "printer-type"))
3123 * Value is either NNNN or 0xXXXX
3126 saw_printer_type
= 1;
3127 type
= (cups_ptype_t
)strtol(value
, NULL
, 0) | CUPS_PRINTER_DISCOVERED
;
3129 else if (!saw_printer_type
)
3131 if (!_cups_strcasecmp(key
, "air") &&
3132 !_cups_strcasecmp(value
, "t"))
3133 type
|= CUPS_PRINTER_AUTHENTICATED
;
3134 else if (!_cups_strcasecmp(key
, "bind") &&
3135 !_cups_strcasecmp(value
, "t"))
3136 type
|= CUPS_PRINTER_BIND
;
3137 else if (!_cups_strcasecmp(key
, "collate") &&
3138 !_cups_strcasecmp(value
, "t"))
3139 type
|= CUPS_PRINTER_COLLATE
;
3140 else if (!_cups_strcasecmp(key
, "color") &&
3141 !_cups_strcasecmp(value
, "t"))
3142 type
|= CUPS_PRINTER_COLOR
;
3143 else if (!_cups_strcasecmp(key
, "copies") &&
3144 !_cups_strcasecmp(value
, "t"))
3145 type
|= CUPS_PRINTER_COPIES
;
3146 else if (!_cups_strcasecmp(key
, "duplex") &&
3147 !_cups_strcasecmp(value
, "t"))
3148 type
|= CUPS_PRINTER_DUPLEX
;
3149 else if (!_cups_strcasecmp(key
, "fax") &&
3150 !_cups_strcasecmp(value
, "t"))
3151 type
|= CUPS_PRINTER_MFP
;
3152 else if (!_cups_strcasecmp(key
, "papercustom") &&
3153 !_cups_strcasecmp(value
, "t"))
3154 type
|= CUPS_PRINTER_VARIABLE
;
3155 else if (!_cups_strcasecmp(key
, "papermax"))
3157 if (!_cups_strcasecmp(value
, "legal-a4"))
3158 type
|= CUPS_PRINTER_SMALL
;
3159 else if (!_cups_strcasecmp(value
, "isoc-a2"))
3160 type
|= CUPS_PRINTER_MEDIUM
;
3161 else if (!_cups_strcasecmp(value
, ">isoc-a2"))
3162 type
|= CUPS_PRINTER_LARGE
;
3164 else if (!_cups_strcasecmp(key
, "punch") &&
3165 !_cups_strcasecmp(value
, "t"))
3166 type
|= CUPS_PRINTER_PUNCH
;
3167 else if (!_cups_strcasecmp(key
, "scan") &&
3168 !_cups_strcasecmp(value
, "t"))
3169 type
|= CUPS_PRINTER_MFP
;
3170 else if (!_cups_strcasecmp(key
, "sort") &&
3171 !_cups_strcasecmp(value
, "t"))
3172 type
|= CUPS_PRINTER_SORT
;
3173 else if (!_cups_strcasecmp(key
, "staple") &&
3174 !_cups_strcasecmp(value
, "t"))
3175 type
|= CUPS_PRINTER_STAPLE
;
3180 * Save the printer-xxx values...
3183 if (make_and_model
[0])
3185 strlcat(make_and_model
, " ", sizeof(make_and_model
));
3186 strlcat(make_and_model
, model
, sizeof(make_and_model
));
3188 device
->dest
.num_options
= cupsAddOption("printer-make-and-model", make_and_model
, device
->dest
.num_options
, &device
->dest
.options
);
3191 device
->dest
.num_options
= cupsAddOption("printer-make-and-model", model
, device
->dest
.num_options
, &device
->dest
.options
);
3193 device
->type
= type
;
3194 snprintf(value
, sizeof(value
), "%u", type
);
3195 device
->dest
.num_options
= cupsAddOption("printer-type", value
, device
->dest
.num_options
, &device
->dest
.options
);
3201 cups_dnssd_unquote(uriname
, device
->fullName
, sizeof(uriname
));
3202 httpAssembleURI(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
),
3203 !strcmp(device
->regtype
, "_ipps._tcp") ? "ipps" : "ipp",
3204 NULL
, uriname
, 0, saw_printer_type
? "/cups" : "/");
3206 DEBUG_printf(("6cups_dnssd_query: device-uri=\"%s\"", uri
));
3208 device
->dest
.num_options
= cupsAddOption("device-uri", uri
, device
->dest
.num_options
, &device
->dest
.options
);
3211 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
3217 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
3220 static const char * /* O - Resolved URI or NULL */
3222 cups_dest_t
*dest
, /* I - Destination */
3223 const char *uri
, /* I - Current printer URI */
3224 int msec
, /* I - Time in milliseconds */
3225 int *cancel
, /* I - Pointer to "cancel" variable */
3226 cups_dest_cb_t cb
, /* I - Callback */
3227 void *user_data
) /* I - User data for callback */
3229 char tempuri
[1024]; /* Temporary URI buffer */
3230 _cups_dnssd_resolve_t resolve
; /* Resolve data */
3234 * Resolve the URI...
3237 resolve
.cancel
= cancel
;
3238 gettimeofday(&resolve
.end_time
, NULL
);
3241 resolve
.end_time
.tv_sec
+= msec
/ 1000;
3242 resolve
.end_time
.tv_usec
+= (msec
% 1000) * 1000;
3244 while (resolve
.end_time
.tv_usec
>= 1000000)
3246 resolve
.end_time
.tv_sec
++;
3247 resolve
.end_time
.tv_usec
-= 1000000;
3251 resolve
.end_time
.tv_sec
+= 75;
3254 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
, dest
);
3256 if ((uri
= _httpResolveURI(uri
, tempuri
, sizeof(tempuri
), _HTTP_RESOLVE_DEFAULT
, cups_dnssd_resolve_cb
, &resolve
)) == NULL
)
3258 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to resolve printer-uri."), 1);
3261 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
, dest
);
3267 * Save the resolved URI...
3270 dest
->num_options
= cupsAddOption("device-uri", uri
, dest
->num_options
, &dest
->options
);
3272 return (cupsGetOption("device-uri", dest
->num_options
, dest
->options
));
3277 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
3280 static int /* O - 1 to continue, 0 to stop */
3281 cups_dnssd_resolve_cb(void *context
) /* I - Resolve data */
3283 _cups_dnssd_resolve_t
*resolve
= (_cups_dnssd_resolve_t
*)context
;
3285 struct timeval curtime
; /* Current time */
3289 * If the cancel variable is set, return immediately.
3292 if (resolve
->cancel
&& *(resolve
->cancel
))
3294 DEBUG_puts("4cups_dnssd_resolve_cb: Canceled.");
3299 * Otherwise check the end time...
3302 gettimeofday(&curtime
, NULL
);
3304 DEBUG_printf(("4cups_dnssd_resolve_cb: curtime=%d.%06d, end_time=%d.%06d", (int)curtime
.tv_sec
, (int)curtime
.tv_usec
, (int)resolve
->end_time
.tv_sec
, (int)resolve
->end_time
.tv_usec
));
3306 return (curtime
.tv_sec
< resolve
->end_time
.tv_sec
||
3307 (curtime
.tv_sec
== resolve
->end_time
.tv_sec
&&
3308 curtime
.tv_usec
< resolve
->end_time
.tv_usec
));
3313 * 'cups_dnssd_unquote()' - Unquote a name string.
3317 cups_dnssd_unquote(char *dst
, /* I - Destination buffer */
3318 const char *src
, /* I - Source string */
3319 size_t dstsize
) /* I - Size of destination buffer */
3321 char *dstend
= dst
+ dstsize
- 1; /* End of destination buffer */
3324 while (*src
&& dst
< dstend
)
3329 if (isdigit(src
[0] & 255) && isdigit(src
[1] & 255) &&
3330 isdigit(src
[2] & 255))
3332 *dst
++ = ((((src
[0] - '0') * 10) + src
[1] - '0') * 10) + src
[2] - '0';
3344 #endif /* HAVE_DNSSD */
3347 #if defined(HAVE_AVAHI) || defined(HAVE_DNSSD)
3349 * 'cups_elapsed()' - Return the elapsed time in milliseconds.
3352 static int /* O - Elapsed time in milliseconds */
3353 cups_elapsed(struct timeval
*t
) /* IO - Previous time */
3355 int msecs
; /* Milliseconds */
3356 struct timeval nt
; /* New time */
3359 gettimeofday(&nt
, NULL
);
3361 msecs
= (int)(1000 * (nt
.tv_sec
- t
->tv_sec
) + (nt
.tv_usec
- t
->tv_usec
) / 1000);
3367 #endif /* HAVE_AVAHI || HAVE_DNSSD */
3371 * 'cups_enum_dests()' - Enumerate destinations from a specific server.
3374 static int /* O - 1 on success, 0 on failure */
3376 http_t
*http
, /* I - Connection to scheduler */
3377 unsigned flags
, /* I - Enumeration flags */
3378 int msec
, /* I - Timeout in milliseconds, -1 for indefinite */
3379 int *cancel
, /* I - Pointer to "cancel" variable */
3380 cups_ptype_t type
, /* I - Printer type bits */
3381 cups_ptype_t mask
, /* I - Mask for printer type bits */
3382 cups_dest_cb_t cb
, /* I - Callback function */
3383 void *user_data
) /* I - User data */
3385 int i
, j
, /* Looping vars */
3386 num_dests
; /* Number of destinations */
3387 cups_dest_t
*dests
= NULL
, /* Destinations */
3388 *dest
, /* Current destination */
3389 *user_dest
; /* User destination */
3390 cups_option_t
*option
; /* Current option */
3391 char *user_default
; /* User default printer */
3392 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3393 int count
, /* Number of queries started */
3394 completed
, /* Number of completed queries */
3395 remaining
; /* Remainder of timeout */
3396 struct timeval curtime
; /* Current time */
3397 _cups_dnssd_data_t data
; /* Data for callback */
3398 _cups_dnssd_device_t
*device
; /* Current device */
3400 int nfds
, /* Number of files responded */
3401 main_fd
; /* File descriptor for lookups */
3402 DNSServiceRef ipp_ref
= NULL
; /* IPP browser */
3404 DNSServiceRef ipps_ref
= NULL
; /* IPPS browser */
3405 # endif /* HAVE_SSL */
3407 struct pollfd pfd
; /* Polling data */
3409 fd_set input
; /* Input set for select() */
3410 struct timeval timeout
; /* Timeout for select() */
3411 # endif /* HAVE_POLL */
3412 # else /* HAVE_AVAHI */
3413 int error
; /* Error value */
3414 AvahiServiceBrowser
*ipp_ref
= NULL
; /* IPP browser */
3416 AvahiServiceBrowser
*ipps_ref
= NULL
; /* IPPS browser */
3417 # endif /* HAVE_SSL */
3418 # endif /* HAVE_DNSSD */
3420 _cups_getdata_t data
; /* Data for callback */
3421 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3422 const char *home
; /* HOME environment variable */
3423 char filename
[1024]; /* Local lpoptions file */
3424 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3427 DEBUG_printf(("cups_enum_dests(flags=%x, msec=%d, cancel=%p, type=%x, mask=%x, cb=%p, user_data=%p)", flags
, msec
, (void *)cancel
, type
, mask
, (void *)cb
, (void *)user_data
));
3430 * Range check input...
3437 DEBUG_puts("1cups_enum_dests: No callback, returning 0.");
3442 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
3445 memset(&data
, 0, sizeof(data
));
3447 if ((user_default
= _cupsUserDefault(data
.def_name
, sizeof(data
.def_name
))) == NULL
)
3449 const char *defprinter
= cupsGetDefault2(http
);
3450 /* Server default, if any */
3453 strlcpy(data
.def_name
, defprinter
, sizeof(data
.def_name
));
3456 if (data
.def_name
[0])
3459 * Separate printer and instance name...
3462 if ((data
.def_instance
= strchr(data
.def_name
, '/')) != NULL
)
3463 *data
.def_instance
++ = '\0';
3466 DEBUG_printf(("1cups_enum_dests: def_name=\"%s\", def_instance=\"%s\"", data
.def_name
, data
.def_instance
));
3468 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
3469 data
.num_dests
= cups_get_dests(filename
, NULL
, NULL
, 1, user_default
!= NULL
, data
.num_dests
, &data
.dests
);
3471 if ((home
= getenv("HOME")) != NULL
)
3473 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
3475 data
.num_dests
= cups_get_dests(filename
, NULL
, NULL
, 1, user_default
!= NULL
, data
.num_dests
, &data
.dests
);
3479 * Get ready to enumerate...
3482 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3486 data
.user_data
= user_data
;
3487 data
.devices
= cupsArrayNew3((cups_array_func_t
)cups_dnssd_compare_devices
, NULL
, NULL
, 0, NULL
, (cups_afree_func_t
)cups_dnssd_free_device
);
3488 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3490 if (!(mask
& CUPS_PRINTER_DISCOVERED
) || !(type
& CUPS_PRINTER_DISCOVERED
))
3493 * Get the list of local printers and pass them to the callback function...
3496 num_dests
= _cupsGetDests(http
, IPP_OP_CUPS_GET_PRINTERS
, NULL
, &dests
, type
, mask
);
3498 if (data
.def_name
[0])
3501 * Lookup the named default printer and instance and make it the default...
3504 if ((dest
= cupsGetDest(data
.def_name
, data
.def_instance
, num_dests
, dests
)) != NULL
)
3506 DEBUG_printf(("1cups_enum_dests: Setting is_default on \"%s/%s\".", dest
->name
, dest
->instance
));
3507 dest
->is_default
= 1;
3511 for (i
= num_dests
, dest
= dests
;
3512 i
> 0 && (!cancel
|| !*cancel
);
3515 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3516 const char *device_uri
; /* Device URI */
3517 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3519 if ((user_dest
= cupsGetDest(dest
->name
, dest
->instance
, data
.num_dests
, data
.dests
)) != NULL
)
3522 * Apply user defaults to this destination...
3525 for (j
= user_dest
->num_options
, option
= user_dest
->options
; j
> 0; j
--, option
++)
3526 dest
->num_options
= cupsAddOption(option
->name
, option
->value
, dest
->num_options
, &dest
->options
);
3529 if (!(*cb
)(user_data
, i
> 1 ? CUPS_DEST_FLAGS_MORE
: CUPS_DEST_FLAGS_NONE
, dest
))
3532 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3533 if (!dest
->instance
&& (device_uri
= cupsGetOption("device-uri", dest
->num_options
, dest
->options
)) != NULL
&& !strncmp(device_uri
, "dnssd://", 8))
3536 * Add existing queue using service name, etc. so we don't list it again...
3539 char scheme
[32], /* URI scheme */
3540 userpass
[32], /* Username:password */
3541 serviceName
[256], /* Service name (host field) */
3542 resource
[256], /* Resource (options) */
3543 *regtype
, /* Registration type */
3544 *replyDomain
; /* Registration domain */
3545 int port
; /* Port number (not used) */
3547 if (httpSeparateURI(HTTP_URI_CODING_ALL
, device_uri
, scheme
, sizeof(scheme
), userpass
, sizeof(userpass
), serviceName
, sizeof(serviceName
), &port
, resource
, sizeof(resource
)) >= HTTP_URI_STATUS_OK
)
3549 if ((regtype
= strstr(serviceName
, "._ipp")) != NULL
)
3553 if ((replyDomain
= strstr(regtype
, "._tcp.")) != NULL
)
3555 replyDomain
[5] = '\0';
3558 if ((device
= cups_dnssd_get_device(&data
, serviceName
, regtype
, replyDomain
)) != NULL
)
3559 device
->state
= _CUPS_DNSSD_ACTIVE
;
3564 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3567 cupsFreeDests(num_dests
, dests
);
3569 if (i
> 0 || msec
== 0)
3574 * Return early if the caller doesn't want to do discovery...
3577 if ((mask
& CUPS_PRINTER_DISCOVERED
) && !(type
& CUPS_PRINTER_DISCOVERED
))
3580 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3582 * Get Bonjour-shared printers...
3585 gettimeofday(&curtime
, NULL
);
3588 if (DNSServiceCreateConnection(&data
.main_ref
) != kDNSServiceErr_NoError
)
3590 DEBUG_puts("1cups_enum_dests: Unable to create service browser, returning 0.");
3592 cupsFreeDests(data
.num_dests
, data
.dests
);
3597 main_fd
= DNSServiceRefSockFD(data
.main_ref
);
3599 ipp_ref
= data
.main_ref
;
3600 if (DNSServiceBrowse(&ipp_ref
, kDNSServiceFlagsShareConnection
, 0, "_ipp._tcp", NULL
, (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
) != kDNSServiceErr_NoError
)
3602 DEBUG_puts("1cups_enum_dests: Unable to create IPP browser, returning 0.");
3603 DNSServiceRefDeallocate(data
.main_ref
);
3605 cupsFreeDests(data
.num_dests
, data
.dests
);
3611 ipps_ref
= data
.main_ref
;
3612 if (DNSServiceBrowse(&ipps_ref
, kDNSServiceFlagsShareConnection
, 0, "_ipps._tcp", NULL
, (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
) != kDNSServiceErr_NoError
)
3614 DEBUG_puts("1cups_enum_dests: Unable to create IPPS browser, returning 0.");
3615 DNSServiceRefDeallocate(data
.main_ref
);
3617 cupsFreeDests(data
.num_dests
, data
.dests
);
3621 # endif /* HAVE_SSL */
3623 # else /* HAVE_AVAHI */
3624 if ((data
.simple_poll
= avahi_simple_poll_new()) == NULL
)
3626 DEBUG_puts("1cups_enum_dests: Unable to create Avahi poll, returning 0.");
3628 cupsFreeDests(data
.num_dests
, data
.dests
);
3633 avahi_simple_poll_set_func(data
.simple_poll
, cups_dnssd_poll_cb
, &data
);
3635 data
.client
= avahi_client_new(avahi_simple_poll_get(data
.simple_poll
),
3636 0, cups_dnssd_client_cb
, &data
,
3640 DEBUG_puts("1cups_enum_dests: Unable to create Avahi client, returning 0.");
3641 avahi_simple_poll_free(data
.simple_poll
);
3643 cupsFreeDests(data
.num_dests
, data
.dests
);
3649 if ((ipp_ref
= avahi_service_browser_new(data
.client
, AVAHI_IF_UNSPEC
, AVAHI_PROTO_UNSPEC
, "_ipp._tcp", NULL
, 0, cups_dnssd_browse_cb
, &data
)) == NULL
)
3651 DEBUG_puts("1cups_enum_dests: Unable to create Avahi IPP browser, returning 0.");
3653 avahi_client_free(data
.client
);
3654 avahi_simple_poll_free(data
.simple_poll
);
3656 cupsFreeDests(data
.num_dests
, data
.dests
);
3663 if ((ipps_ref
= avahi_service_browser_new(data
.client
, AVAHI_IF_UNSPEC
, AVAHI_PROTO_UNSPEC
, "_ipps._tcp", NULL
, 0, cups_dnssd_browse_cb
, &data
)) == NULL
)
3665 DEBUG_puts("1cups_enum_dests: Unable to create Avahi IPPS browser, returning 0.");
3667 avahi_service_browser_free(ipp_ref
);
3668 avahi_client_free(data
.client
);
3669 avahi_simple_poll_free(data
.simple_poll
);
3671 cupsFreeDests(data
.num_dests
, data
.dests
);
3675 # endif /* HAVE_SSL */
3676 # endif /* HAVE_DNSSD */
3679 remaining
= INT_MAX
;
3683 while (remaining
> 0 && (!cancel
|| !*cancel
))
3686 * Check for input...
3689 DEBUG_printf(("1cups_enum_dests: remaining=%d", remaining
));
3691 cups_elapsed(&curtime
);
3696 pfd
.events
= POLLIN
;
3698 nfds
= poll(&pfd
, 1, remaining
> _CUPS_DNSSD_MAXTIME
? _CUPS_DNSSD_MAXTIME
: remaining
);
3702 FD_SET(main_fd
, &input
);
3705 timeout
.tv_usec
= 1000 * (remaining
> _CUPS_DNSSD_MAXTIME
? _CUPS_DNSSD_MAXTIME
: remaining
);
3707 nfds
= select(main_fd
+ 1, &input
, NULL
, NULL
, &timeout
);
3708 # endif /* HAVE_POLL */
3711 DNSServiceProcessResult(data
.main_ref
);
3712 else if (nfds
< 0 && errno
!= EINTR
&& errno
!= EAGAIN
)
3715 # else /* HAVE_AVAHI */
3718 if ((error
= avahi_simple_poll_iterate(data
.simple_poll
, _CUPS_DNSSD_MAXTIME
)) > 0)
3721 * We've been told to exit the loop. Perhaps the connection to
3728 DEBUG_printf(("1cups_enum_dests: got_data=%d", data
.got_data
));
3729 # endif /* HAVE_DNSSD */
3731 remaining
-= cups_elapsed(&curtime
);
3733 for (device
= (_cups_dnssd_device_t
*)cupsArrayFirst(data
.devices
),
3734 count
= 0, completed
= 0;
3736 device
= (_cups_dnssd_device_t
*)cupsArrayNext(data
.devices
))
3741 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
3744 if (!device
->ref
&& device
->state
== _CUPS_DNSSD_NEW
)
3746 DEBUG_printf(("1cups_enum_dests: Querying '%s'.", device
->fullName
));
3749 device
->ref
= data
.main_ref
;
3751 if (DNSServiceQueryRecord(&(device
->ref
), kDNSServiceFlagsShareConnection
, 0, device
->fullName
, kDNSServiceType_TXT
, kDNSServiceClass_IN
, (DNSServiceQueryRecordReply
)cups_dnssd_query_cb
, &data
) == kDNSServiceErr_NoError
)
3758 device
->state
= _CUPS_DNSSD_ERROR
;
3760 DEBUG_puts("1cups_enum_dests: Query failed.");
3763 # else /* HAVE_AVAHI */
3764 if ((device
->ref
= avahi_record_browser_new(data
.client
, AVAHI_IF_UNSPEC
, AVAHI_PROTO_UNSPEC
, device
->fullName
, AVAHI_DNS_CLASS_IN
, AVAHI_DNS_TYPE_TXT
, 0, cups_dnssd_query_cb
, &data
)) != NULL
)
3766 DEBUG_printf(("1cups_enum_dests: Query ref=%p", device
->ref
));
3771 device
->state
= _CUPS_DNSSD_ERROR
;
3773 DEBUG_printf(("1cups_enum_dests: Query failed: %s", avahi_strerror(avahi_client_errno(data
.client
))));
3775 # endif /* HAVE_DNSSD */
3777 else if (device
->ref
&& device
->state
== _CUPS_DNSSD_PENDING
)
3781 DEBUG_printf(("1cups_enum_dests: Query for \"%s\" is complete.", device
->fullName
));
3783 if ((device
->type
& mask
) == type
)
3785 dest
= &device
->dest
;
3787 if ((user_dest
= cupsGetDest(dest
->name
, dest
->instance
, data
.num_dests
, data
.dests
)) != NULL
)
3790 * Apply user defaults to this destination...
3793 for (j
= user_dest
->num_options
, option
= user_dest
->options
; j
> 0; j
--, option
++)
3794 dest
->num_options
= cupsAddOption(option
->name
, option
->value
, dest
->num_options
, &dest
->options
);
3797 if (!strcasecmp(dest
->name
, data
.def_name
) && !data
.def_instance
)
3799 DEBUG_printf(("1cups_enum_dests: Setting is_default on discovered \"%s\".", dest
->name
));
3800 dest
->is_default
= 1;
3803 DEBUG_printf(("1cups_enum_dests: Add callback for \"%s\".", device
->dest
.name
));
3804 if (!(*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, dest
))
3811 device
->state
= _CUPS_DNSSD_ACTIVE
;
3816 DEBUG_printf(("1cups_enum_dests: remaining=%d, browsers=%d, completed=%d, count=%d, devices count=%d", remaining
, data
.browsers
, completed
, count
, cupsArrayCount(data
.devices
)));
3818 if (data
.browsers
== 0 && completed
== cupsArrayCount(data
.devices
))
3821 DEBUG_printf(("1cups_enum_dests: remaining=%d, completed=%d, count=%d, devices count=%d", remaining
, completed
, count
, cupsArrayCount(data
.devices
)));
3823 if (completed
== cupsArrayCount(data
.devices
))
3825 # endif /* HAVE_AVAHI */
3827 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3835 cupsFreeDests(data
.num_dests
, data
.dests
);
3837 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3838 cupsArrayDelete(data
.devices
);
3842 DNSServiceRefDeallocate(ipp_ref
);
3846 DNSServiceRefDeallocate(ipps_ref
);
3847 # endif /* HAVE_SSL */
3850 DNSServiceRefDeallocate(data
.main_ref
);
3852 # else /* HAVE_AVAHI */
3854 avahi_service_browser_free(ipp_ref
);
3857 avahi_service_browser_free(ipps_ref
);
3858 # endif /* HAVE_SSL */
3861 avahi_client_free(data
.client
);
3862 if (data
.simple_poll
)
3863 avahi_simple_poll_free(data
.simple_poll
);
3864 # endif /* HAVE_DNSSD */
3865 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3867 DEBUG_puts("1cups_enum_dests: Returning 1.");
3874 * 'cups_find_dest()' - Find a destination using a binary search.
3877 static int /* O - Index of match */
3878 cups_find_dest(const char *name
, /* I - Destination name */
3879 const char *instance
, /* I - Instance or NULL */
3880 int num_dests
, /* I - Number of destinations */
3881 cups_dest_t
*dests
, /* I - Destinations */
3882 int prev
, /* I - Previous index */
3883 int *rdiff
) /* O - Difference of match */
3885 int left
, /* Low mark for binary search */
3886 right
, /* High mark for binary search */
3887 current
, /* Current index */
3888 diff
; /* Result of comparison */
3889 cups_dest_t key
; /* Search key */
3892 key
.name
= (char *)name
;
3893 key
.instance
= (char *)instance
;
3898 * Start search on either side of previous...
3901 if ((diff
= cups_compare_dests(&key
, dests
+ prev
)) == 0 ||
3902 (diff
< 0 && prev
== 0) ||
3903 (diff
> 0 && prev
== (num_dests
- 1)))
3911 * Start with previous on right side...
3920 * Start wih previous on left side...
3924 right
= num_dests
- 1;
3930 * Start search in the middle...
3934 right
= num_dests
- 1;
3939 current
= (left
+ right
) / 2;
3940 diff
= cups_compare_dests(&key
, dests
+ current
);
3949 while ((right
- left
) > 1);
3954 * Check the last 1 or 2 elements...
3957 if ((diff
= cups_compare_dests(&key
, dests
+ left
)) <= 0)
3961 diff
= cups_compare_dests(&key
, dests
+ right
);
3967 * Return the closest destination and the difference...
3977 * 'cups_get_cb()' - Collect enumerated destinations.
3980 static int /* O - 1 to continue, 0 to stop */
3981 cups_get_cb(_cups_getdata_t
*data
, /* I - Data from cupsGetDests */
3982 unsigned flags
, /* I - Enumeration flags */
3983 cups_dest_t
*dest
) /* I - Destination */
3985 if (flags
& CUPS_DEST_FLAGS_REMOVED
)
3988 * Remove destination from array...
3991 data
->num_dests
= cupsRemoveDest(dest
->name
, dest
->instance
, data
->num_dests
, &data
->dests
);
3996 * Add destination to array...
3999 data
->num_dests
= cupsCopyDest(dest
, data
->num_dests
, &data
->dests
);
4007 * 'cups_get_default()' - Get the default destination from an lpoptions file.
4010 static char * /* O - Default destination or NULL */
4011 cups_get_default(const char *filename
, /* I - File to read */
4012 char *namebuf
, /* I - Name buffer */
4013 size_t namesize
, /* I - Size of name buffer */
4014 const char **instance
) /* I - Instance */
4016 cups_file_t
*fp
; /* lpoptions file */
4017 char line
[8192], /* Line from file */
4018 *value
, /* Value for line */
4019 *nameptr
; /* Pointer into name */
4020 int linenum
; /* Current line */
4025 if ((fp
= cupsFileOpen(filename
, "r")) != NULL
)
4029 while (cupsFileGetConf(fp
, line
, sizeof(line
), &value
, &linenum
))
4031 if (!_cups_strcasecmp(line
, "default") && value
)
4033 strlcpy(namebuf
, value
, namesize
);
4035 if ((nameptr
= strchr(namebuf
, ' ')) != NULL
)
4037 if ((nameptr
= strchr(namebuf
, '\t')) != NULL
)
4040 if ((nameptr
= strchr(namebuf
, '/')) != NULL
)
4043 *instance
= nameptr
;
4051 return (*namebuf
? namebuf
: NULL
);
4056 * 'cups_get_dests()' - Get destinations from a file.
4059 static int /* O - Number of destinations */
4061 const char *filename
, /* I - File to read from */
4062 const char *match_name
, /* I - Destination name we want */
4063 const char *match_inst
, /* I - Instance name we want */
4064 int load_all
, /* I - Load all saved destinations? */
4065 int user_default_set
, /* I - User default printer set? */
4066 int num_dests
, /* I - Number of destinations */
4067 cups_dest_t
**dests
) /* IO - Destinations */
4069 int i
; /* Looping var */
4070 cups_dest_t
*dest
; /* Current destination */
4071 cups_file_t
*fp
; /* File pointer */
4072 char line
[8192], /* Line from file */
4073 *lineptr
, /* Pointer into line */
4074 *name
, /* Name of destination/option */
4075 *instance
; /* Instance of destination */
4076 int linenum
; /* Current line number */
4079 DEBUG_printf(("7cups_get_dests(filename=\"%s\", match_name=\"%s\", match_inst=\"%s\", load_all=%d, user_default_set=%d, num_dests=%d, dests=%p)", filename
, match_name
, match_inst
, load_all
, user_default_set
, num_dests
, (void *)dests
));
4082 * Try to open the file...
4085 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
4089 * Read each printer; each line looks like:
4091 * Dest name[/instance] options
4092 * Default name[/instance] options
4097 while (cupsFileGetConf(fp
, line
, sizeof(line
), &lineptr
, &linenum
))
4100 * See what type of line it is...
4103 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
4104 linenum
, line
, lineptr
));
4106 if ((_cups_strcasecmp(line
, "dest") && _cups_strcasecmp(line
, "default")) || !lineptr
)
4108 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
4115 * Search for an instance...
4118 while (!isspace(*lineptr
& 255) && *lineptr
&& *lineptr
!= '/')
4121 if (*lineptr
== '/')
4124 * Found an instance...
4131 * Search for an instance...
4134 while (!isspace(*lineptr
& 255) && *lineptr
)
4143 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name
,
4147 * Match and/or ignore missing destinations...
4152 if (_cups_strcasecmp(name
, match_name
) ||
4153 (!instance
&& match_inst
) ||
4154 (instance
&& !match_inst
) ||
4155 (instance
&& _cups_strcasecmp(instance
, match_inst
)))
4160 else if (!load_all
&& cupsGetDest(name
, NULL
, num_dests
, *dests
) == NULL
)
4162 DEBUG_puts("9cups_get_dests: Not found!");
4168 * Add the destination...
4171 num_dests
= cupsAddDest(name
, instance
, num_dests
, dests
);
4173 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
4179 DEBUG_puts("9cups_get_dests: Out of memory!");
4185 * Add options until we hit the end of the line...
4188 dest
->num_options
= cupsParseOptions(lineptr
, dest
->num_options
, &(dest
->options
));
4191 * If we found what we were looking for, stop now...
4198 * Set this as default if needed...
4201 if (!user_default_set
&& !_cups_strcasecmp(line
, "default"))
4203 DEBUG_puts("9cups_get_dests: Setting as default...");
4205 for (i
= 0; i
< num_dests
; i
++)
4206 (*dests
)[i
].is_default
= 0;
4208 dest
->is_default
= 1;
4213 * Close the file and return...
4223 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
4227 static char * /* O - New string */
4229 ipp_attribute_t
*attr
, /* I - Attribute to convert */
4230 char *buffer
, /* I - Buffer */
4231 size_t bufsize
) /* I - Size of buffer */
4233 int i
; /* Looping var */
4234 char *ptr
, /* Pointer into buffer */
4235 *end
, /* Pointer to end of buffer */
4236 *valptr
; /* Pointer into string attribute */
4240 * Return quickly if we have a single string value...
4243 if (attr
->num_values
== 1 &&
4244 attr
->value_tag
!= IPP_TAG_INTEGER
&&
4245 attr
->value_tag
!= IPP_TAG_ENUM
&&
4246 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
4247 attr
->value_tag
!= IPP_TAG_RANGE
)
4248 return (attr
->values
[0].string
.text
);
4251 * Copy the values to the string, separating with commas and escaping strings
4255 end
= buffer
+ bufsize
- 1;
4257 for (i
= 0, ptr
= buffer
; i
< attr
->num_values
&& ptr
< end
; i
++)
4262 switch (attr
->value_tag
)
4264 case IPP_TAG_INTEGER
:
4266 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d", attr
->values
[i
].integer
);
4269 case IPP_TAG_BOOLEAN
:
4270 if (attr
->values
[i
].boolean
)
4271 strlcpy(ptr
, "true", (size_t)(end
- ptr
+ 1));
4273 strlcpy(ptr
, "false", (size_t)(end
- ptr
+ 1));
4276 case IPP_TAG_RANGE
:
4277 if (attr
->values
[i
].range
.lower
== attr
->values
[i
].range
.upper
)
4278 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d", attr
->values
[i
].range
.lower
);
4280 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d-%d", attr
->values
[i
].range
.lower
, attr
->values
[i
].range
.upper
);
4284 for (valptr
= attr
->values
[i
].string
.text
;
4285 *valptr
&& ptr
< end
;)
4287 if (strchr(" \t\n\\\'\"", *valptr
))
4289 if (ptr
>= (end
- 1))
4312 * 'cups_name_cb()' - Find an enumerated destination.
4315 static int /* O - 1 to continue, 0 to stop */
4316 cups_name_cb(_cups_namedata_t
*data
, /* I - Data from cupsGetNamedDest */
4317 unsigned flags
, /* I - Enumeration flags */
4318 cups_dest_t
*dest
) /* I - Destination */
4320 DEBUG_printf(("2cups_name_cb(data=%p(%s), flags=%x, dest=%p(%s)", (void *)data
, data
->name
, flags
, (void *)dest
, dest
->name
));
4322 if (!(flags
& CUPS_DEST_FLAGS_REMOVED
) && !dest
->instance
&& !strcasecmp(data
->name
, dest
->name
))
4325 * Copy destination and stop enumeration...
4328 cupsCopyDest(dest
, 0, &data
->dest
);
4337 * 'cups_queue_name()' - Create a local queue name based on the service name.
4342 char *name
, /* I - Name buffer */
4343 const char *serviceName
, /* I - Service name */
4344 size_t namesize
) /* I - Size of name buffer */
4346 const char *ptr
; /* Pointer into serviceName */
4347 char *nameptr
; /* Pointer into name */
4350 for (nameptr
= name
, ptr
= serviceName
; *ptr
&& nameptr
< (name
+ namesize
- 1); ptr
++)
4353 * Sanitize the printer name...
4356 if (_cups_isalnum(*ptr
))
4358 else if (nameptr
== name
|| nameptr
[-1] != '_')