2 * User-defined destination (and option) support for CUPS.
4 * Copyright 2007-2016 by Apple Inc.
5 * Copyright 1997-2007 by Easy Software Products.
7 * These coded instructions, statements, and computer programs are the
8 * property of Apple Inc. and are protected by Federal copyright
9 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
10 * which should have been included with this file. If this file is
11 * missing or damaged, see the license at "http://www.cups.org/".
13 * This file is subject to the Apple OS-Developed Software exception.
17 * Include necessary headers...
20 #include "cups-private.h"
25 #endif /* HAVE_NOTIFY_H */
29 #endif /* HAVE_POLL */
33 #endif /* HAVE_DNSSD */
36 # include <avahi-client/client.h>
37 # include <avahi-client/lookup.h>
38 # include <avahi-common/simple-watch.h>
39 # include <avahi-common/domain.h>
40 # include <avahi-common/error.h>
41 # include <avahi-common/malloc.h>
42 #define kDNSServiceMaxDomainName AVAHI_DOMAIN_NAME_MAX
43 #endif /* HAVE_AVAHI */
52 # include <SystemConfiguration/SystemConfiguration.h>
53 # define _CUPS_LOCATION_DEFAULTS 1
54 # endif /* !TARGET_OS_IOS */
55 # define kCUPSPrintingPrefs CFSTR("org.cups.PrintingPrefs")
56 # define kDefaultPaperIDKey CFSTR("DefaultPaperID")
57 # define kLastUsedPrintersKey CFSTR("LastUsedPrinters")
58 # define kLocationNetworkKey CFSTR("Network")
59 # define kLocationPrinterIDKey CFSTR("PrinterID")
60 # define kUseLastPrinter CFSTR("UseLastPrinter")
61 #endif /* __APPLE__ */
68 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
69 typedef enum _cups_dnssd_state_e
/* Enumerated device state */
76 _CUPS_DNSSD_INCOMPATIBLE
,
78 } _cups_dnssd_state_t
;
80 typedef struct _cups_dnssd_data_s
/* Enumeration data */
83 DNSServiceRef main_ref
; /* Main service reference */
84 # else /* HAVE_AVAHI */
85 AvahiSimplePoll
*simple_poll
; /* Polling interface */
86 AvahiClient
*client
; /* Client information */
87 int got_data
; /* Did we get data? */
88 int browsers
; /* How many browsers are running? */
89 # endif /* HAVE_DNSSD */
90 cups_dest_cb_t cb
; /* Callback */
91 void *user_data
; /* User data pointer */
92 cups_ptype_t type
, /* Printer type filter */
93 mask
; /* Printer type mask */
94 cups_array_t
*devices
; /* Devices found so far */
97 typedef struct _cups_dnssd_device_s
/* Enumerated device */
99 _cups_dnssd_state_t state
; /* State of device listing */
101 DNSServiceRef ref
; /* Service reference for query */
102 # else /* HAVE_AVAHI */
103 AvahiRecordBrowser
*ref
; /* Browser for query */
104 # endif /* HAVE_DNSSD */
105 char *fullName
, /* Full name */
106 *regtype
, /* Registration type */
107 *domain
; /* Domain name */
108 cups_ptype_t type
; /* Device registration type */
109 cups_dest_t dest
; /* Destination record */
110 } _cups_dnssd_device_t
;
112 typedef struct _cups_dnssd_resolve_s
/* Data for resolving URI */
114 int *cancel
; /* Pointer to "cancel" variable */
115 struct timeval end_time
; /* Ending time */
116 } _cups_dnssd_resolve_t
;
117 #endif /* HAVE_DNSSD */
124 #if _CUPS_LOCATION_DEFAULTS
125 static CFArrayRef
appleCopyLocations(void);
126 static CFStringRef
appleCopyNetwork(void);
127 #endif /* _CUPS_LOCATION_DEFAULTS */
129 static char *appleGetPaperSize(char *name
, size_t namesize
);
130 #endif /* __APPLE__ */
131 #if _CUPS_LOCATION_DEFAULTS
132 static CFStringRef
appleGetPrinter(CFArrayRef locations
,
133 CFStringRef network
, CFIndex
*locindex
);
134 #endif /* _CUPS_LOCATION_DEFAULTS */
135 static cups_dest_t
*cups_add_dest(const char *name
, const char *instance
,
136 int *num_dests
, cups_dest_t
**dests
);
138 static int cups_block_cb(cups_dest_block_t block
, unsigned flags
,
140 #endif /* __BLOCKS__ */
141 static int cups_compare_dests(cups_dest_t
*a
, cups_dest_t
*b
);
142 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
144 static void cups_dnssd_browse_cb(DNSServiceRef sdRef
,
145 DNSServiceFlags flags
,
146 uint32_t interfaceIndex
,
147 DNSServiceErrorType errorCode
,
148 const char *serviceName
,
150 const char *replyDomain
,
152 # else /* HAVE_AVAHI */
153 static void cups_dnssd_browse_cb(AvahiServiceBrowser
*browser
,
154 AvahiIfIndex interface
,
155 AvahiProtocol protocol
,
156 AvahiBrowserEvent event
,
157 const char *serviceName
,
159 const char *replyDomain
,
160 AvahiLookupResultFlags flags
,
162 static void cups_dnssd_client_cb(AvahiClient
*client
,
163 AvahiClientState state
,
165 # endif /* HAVE_DNSSD */
166 static int cups_dnssd_compare_devices(_cups_dnssd_device_t
*a
,
167 _cups_dnssd_device_t
*b
);
168 static void cups_dnssd_free_device(_cups_dnssd_device_t
*device
,
169 _cups_dnssd_data_t
*data
);
170 static _cups_dnssd_device_t
*
171 cups_dnssd_get_device(_cups_dnssd_data_t
*data
,
172 const char *serviceName
,
174 const char *replyDomain
);
176 static void cups_dnssd_local_cb(DNSServiceRef sdRef
,
177 DNSServiceFlags flags
,
178 uint32_t interfaceIndex
,
179 DNSServiceErrorType errorCode
,
180 const char *serviceName
,
182 const char *replyDomain
,
184 static void cups_dnssd_query_cb(DNSServiceRef sdRef
,
185 DNSServiceFlags flags
,
186 uint32_t interfaceIndex
,
187 DNSServiceErrorType errorCode
,
188 const char *fullName
,
189 uint16_t rrtype
, uint16_t rrclass
,
190 uint16_t rdlen
, const void *rdata
,
191 uint32_t ttl
, void *context
);
192 # else /* HAVE_AVAHI */
193 static int cups_dnssd_poll_cb(struct pollfd
*pollfds
,
194 unsigned int num_pollfds
,
195 int timeout
, void *context
);
196 static void cups_dnssd_query_cb(AvahiRecordBrowser
*browser
,
197 AvahiIfIndex interface
,
198 AvahiProtocol protocol
,
199 AvahiBrowserEvent event
,
200 const char *name
, uint16_t rrclass
,
201 uint16_t rrtype
, const void *rdata
,
203 AvahiLookupResultFlags flags
,
205 # endif /* HAVE_DNSSD */
206 static void cups_dnssd_queue_name(char *name
, const char *serviceName
, size_t namesize
);
207 static const char *cups_dnssd_resolve(cups_dest_t
*dest
, const char *uri
,
208 int msec
, int *cancel
,
209 cups_dest_cb_t cb
, void *user_data
);
210 static int cups_dnssd_resolve_cb(void *context
);
211 static void cups_dnssd_unquote(char *dst
, const char *src
,
213 #endif /* HAVE_DNSSD || HAVE_AVAHI */
214 static int cups_find_dest(const char *name
, const char *instance
,
215 int num_dests
, cups_dest_t
*dests
, int prev
,
217 static char *cups_get_default(const char *filename
, char *namebuf
,
218 size_t namesize
, const char **instance
);
219 static int cups_get_dests(const char *filename
, const char *match_name
,
220 const char *match_inst
, int user_default_set
,
221 int num_dests
, cups_dest_t
**dests
);
222 static char *cups_make_string(ipp_attribute_t
*attr
, char *buffer
,
227 * 'cupsAddDest()' - Add a destination to the list of destinations.
229 * This function cannot be used to add a new class or printer queue,
230 * it only adds a new container of saved options for the named
231 * destination or instance.
233 * If the named destination already exists, the destination list is
234 * returned unchanged. Adding a new instance of a destination creates
235 * a copy of that destination's options.
237 * Use the @link cupsSaveDests@ function to save the updated list of
238 * destinations to the user's lpoptions file.
241 int /* O - New number of destinations */
242 cupsAddDest(const char *name
, /* I - Destination name */
243 const char *instance
, /* I - Instance name or @code NULL@ for none/primary */
244 int num_dests
, /* I - Number of destinations */
245 cups_dest_t
**dests
) /* IO - Destinations */
247 int i
; /* Looping var */
248 cups_dest_t
*dest
; /* Destination pointer */
249 cups_dest_t
*parent
= NULL
; /* Parent destination */
250 cups_option_t
*doption
, /* Current destination option */
251 *poption
; /* Current parent option */
257 if (!cupsGetDest(name
, instance
, num_dests
, *dests
))
259 if (instance
&& !cupsGetDest(name
, NULL
, num_dests
, *dests
))
262 if ((dest
= cups_add_dest(name
, instance
, &num_dests
, dests
)) == NULL
)
266 * Find the base dest again now the array has been realloc'd.
269 parent
= cupsGetDest(name
, NULL
, num_dests
, *dests
);
271 if (instance
&& parent
&& parent
->num_options
> 0)
274 * Copy options from parent...
277 dest
->options
= calloc(sizeof(cups_option_t
), (size_t)parent
->num_options
);
281 dest
->num_options
= parent
->num_options
;
283 for (i
= dest
->num_options
, doption
= dest
->options
,
284 poption
= parent
->options
;
286 i
--, doption
++, poption
++)
288 doption
->name
= _cupsStrRetain(poption
->name
);
289 doption
->value
= _cupsStrRetain(poption
->value
);
301 * '_cupsAppleCopyDefaultPaperID()' - Get the default paper ID.
304 CFStringRef
/* O - Default paper ID */
305 _cupsAppleCopyDefaultPaperID(void)
307 return (CFPreferencesCopyAppValue(kDefaultPaperIDKey
,
308 kCUPSPrintingPrefs
));
313 * '_cupsAppleCopyDefaultPrinter()' - Get the default printer at this location.
316 CFStringRef
/* O - Default printer name */
317 _cupsAppleCopyDefaultPrinter(void)
319 # if _CUPS_LOCATION_DEFAULTS
320 CFStringRef network
; /* Network location */
321 CFArrayRef locations
; /* Location array */
322 CFStringRef locprinter
; /* Current printer */
326 * Use location-based defaults only if "use last printer" is selected in the
327 * system preferences...
330 if (!_cupsAppleGetUseLastPrinter())
332 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Not using last printer as "
338 * Get the current location...
341 if ((network
= appleCopyNetwork()) == NULL
)
343 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Unable to get current "
349 * Lookup the network in the preferences...
352 if ((locations
= appleCopyLocations()) == NULL
)
355 * Missing or bad location array, so no location-based default...
358 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Missing or bad last used "
366 DEBUG_printf(("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.",
367 (int)CFArrayGetCount(locations
)));
369 if ((locprinter
= appleGetPrinter(locations
, network
, NULL
)) != NULL
)
370 CFRetain(locprinter
);
373 CFRelease(locations
);
379 # endif /* _CUPS_LOCATION_DEFAULTS */
384 * '_cupsAppleGetUseLastPrinter()' - Get whether to use the last used printer.
387 int /* O - 1 to use last printer, 0 otherwise */
388 _cupsAppleGetUseLastPrinter(void)
390 Boolean uselast
, /* Use last printer preference value */
391 uselast_set
; /* Valid is set? */
394 if (getenv("CUPS_DISABLE_APPLE_DEFAULT"))
397 uselast
= CFPreferencesGetAppBooleanValue(kUseLastPrinter
,
408 * '_cupsAppleSetDefaultPaperID()' - Set the default paper id.
412 _cupsAppleSetDefaultPaperID(
413 CFStringRef name
) /* I - New paper ID */
415 CFPreferencesSetAppValue(kDefaultPaperIDKey
, name
, kCUPSPrintingPrefs
);
416 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
418 # ifdef HAVE_NOTIFY_POST
419 notify_post("com.apple.printerPrefsChange");
420 # endif /* HAVE_NOTIFY_POST */
425 * '_cupsAppleSetDefaultPrinter()' - Set the default printer for this location.
429 _cupsAppleSetDefaultPrinter(
430 CFStringRef name
) /* I - Default printer/class name */
432 # if _CUPS_LOCATION_DEFAULTS
433 CFStringRef network
; /* Current network */
434 CFArrayRef locations
; /* Old locations array */
435 CFIndex locindex
; /* Index in locations array */
436 CFStringRef locprinter
; /* Current printer */
437 CFMutableArrayRef newlocations
; /* New locations array */
438 CFMutableDictionaryRef newlocation
; /* New location */
442 * Get the current location...
445 if ((network
= appleCopyNetwork()) == NULL
)
447 DEBUG_puts("1_cupsAppleSetDefaultPrinter: Unable to get current network...");
452 * Lookup the network in the preferences...
455 if ((locations
= appleCopyLocations()) != NULL
)
456 locprinter
= appleGetPrinter(locations
, network
, &locindex
);
463 if (!locprinter
|| CFStringCompare(locprinter
, name
, 0) != kCFCompareEqualTo
)
466 * Need to change the locations array...
471 newlocations
= CFArrayCreateMutableCopy(kCFAllocatorDefault
, 0,
475 CFArrayRemoveValueAtIndex(newlocations
, locindex
);
478 newlocations
= CFArrayCreateMutable(kCFAllocatorDefault
, 0,
479 &kCFTypeArrayCallBacks
);
481 newlocation
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
482 &kCFTypeDictionaryKeyCallBacks
,
483 &kCFTypeDictionaryValueCallBacks
);
485 if (newlocation
&& newlocations
)
488 * Put the new location at the front of the array...
491 CFDictionaryAddValue(newlocation
, kLocationNetworkKey
, network
);
492 CFDictionaryAddValue(newlocation
, kLocationPrinterIDKey
, name
);
493 CFArrayInsertValueAtIndex(newlocations
, 0, newlocation
);
496 * Limit the number of locations to 10...
499 while (CFArrayGetCount(newlocations
) > 10)
500 CFArrayRemoveValueAtIndex(newlocations
, 10);
503 * Push the changes out...
506 CFPreferencesSetAppValue(kLastUsedPrintersKey
, newlocations
,
508 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
510 # ifdef HAVE_NOTIFY_POST
511 notify_post("com.apple.printerPrefsChange");
512 # endif /* HAVE_NOTIFY_POST */
516 CFRelease(newlocations
);
519 CFRelease(newlocation
);
523 CFRelease(locations
);
529 # endif /* _CUPS_LOCATION_DEFAULTS */
534 * '_cupsAppleSetUseLastPrinter()' - Set whether to use the last used printer.
538 _cupsAppleSetUseLastPrinter(
539 int uselast
) /* O - 1 to use last printer, 0 otherwise */
541 CFPreferencesSetAppValue(kUseLastPrinter
,
542 uselast
? kCFBooleanTrue
: kCFBooleanFalse
,
544 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
546 # ifdef HAVE_NOTIFY_POST
547 notify_post("com.apple.printerPrefsChange");
548 # endif /* HAVE_NOTIFY_POST */
550 #endif /* __APPLE__ */
554 * 'cupsConnectDest()' - Connect to the server for a destination.
556 * Connect to the destination, returning a new http_t connection object and
557 * optionally the resource path to use for the destination. These calls will
558 * block until a connection is made, the timeout expires, the integer pointed
559 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
560 * The caller is responsible for calling httpClose() on the returned object.
562 * @since CUPS 1.6/macOS 10.8@
565 http_t
* /* O - Connection to server or @code NULL@ */
567 cups_dest_t
*dest
, /* I - Destination */
568 unsigned flags
, /* I - Connection flags */
569 int msec
, /* I - Timeout in milliseconds */
570 int *cancel
, /* I - Pointer to "cancel" variable */
571 char *resource
, /* I - Resource buffer */
572 size_t resourcesize
, /* I - Size of resource buffer */
573 cups_dest_cb_t cb
, /* I - Callback function */
574 void *user_data
) /* I - User data pointer */
576 const char *uri
; /* Printer URI */
577 char scheme
[32], /* URI scheme */
578 userpass
[256], /* Username and password (unused) */
579 hostname
[256], /* Hostname */
580 tempresource
[1024]; /* Temporary resource buffer */
581 int port
; /* Port number */
582 char portstr
[16]; /* Port number string */
583 http_encryption_t encryption
; /* Encryption to use */
584 http_addrlist_t
*addrlist
; /* Address list for server */
585 http_t
*http
; /* Connection to server */
588 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
));
591 * Range check input...
599 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
603 if (!resource
|| resourcesize
< 1)
605 resource
= tempresource
;
606 resourcesize
= sizeof(tempresource
);
610 * Grab the printer URI...
613 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
, dest
->options
)) == NULL
)
615 if ((uri
= cupsGetOption("resolved-device-uri", dest
->num_options
, dest
->options
)) == NULL
)
617 if ((uri
= cupsGetOption("device-uri", dest
->num_options
, dest
->options
)) != NULL
)
619 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
620 if (strstr(uri
, "._tcp"))
621 uri
= cups_dnssd_resolve(dest
, uri
, msec
, cancel
, cb
, user_data
);
622 #endif /* HAVE_DNSSD || HAVE_AVAHI */
627 uri
= _cupsCreateDest(dest
->name
, cupsGetOption("printer-info", dest
->num_options
, dest
->options
), NULL
, uri
, tempresource
, sizeof(tempresource
));
631 dest
->num_options
= cupsAddOption("printer-uri-supported", uri
, dest
->num_options
, &dest
->options
);
633 uri
= cupsGetOption("printer-uri-supported", dest
->num_options
, dest
->options
);
639 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(ENOENT
), 0);
642 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
, dest
);
647 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
648 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
649 &port
, resource
, (int)resourcesize
) < HTTP_URI_STATUS_OK
)
651 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer-uri."), 1);
654 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
661 * Lookup the address for the server...
665 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
, dest
);
667 snprintf(portstr
, sizeof(portstr
), "%d", port
);
669 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, portstr
)) == NULL
)
672 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
, dest
);
677 if (cancel
&& *cancel
)
679 httpAddrFreeList(addrlist
);
682 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CANCELED
, dest
);
688 * Create the HTTP object pointing to the server referenced by the URI...
691 if (!strcmp(scheme
, "ipps") || port
== 443)
692 encryption
= HTTP_ENCRYPTION_ALWAYS
;
694 encryption
= HTTP_ENCRYPTION_IF_REQUESTED
;
696 http
= httpConnect2(hostname
, port
, addrlist
, AF_UNSPEC
, encryption
, 1, 0, NULL
);
697 httpAddrFreeList(addrlist
);
700 * Connect if requested...
703 if (flags
& CUPS_DEST_FLAGS_UNCONNECTED
)
706 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
, dest
);
711 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
, dest
);
713 if (!httpReconnect2(http
, msec
, cancel
) && cb
)
715 if (cancel
&& *cancel
)
716 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
, dest
);
718 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
, dest
);
721 (*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, dest
);
730 * 'cupsConnectDestBlock()' - Connect to the server for a destination.
732 * Connect to the destination, returning a new http_t connection object and
733 * optionally the resource path to use for the destination. These calls will
734 * block until a connection is made, the timeout expires, the integer pointed
735 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
736 * The caller is responsible for calling httpClose() on the returned object.
738 * @since CUPS 1.6/macOS 10.8@
741 http_t
* /* O - Connection to server or @code NULL@ */
742 cupsConnectDestBlock(
743 cups_dest_t
*dest
, /* I - Destination */
744 unsigned flags
, /* I - Connection flags */
745 int msec
, /* I - Timeout in milliseconds */
746 int *cancel
, /* I - Pointer to "cancel" variable */
747 char *resource
, /* I - Resource buffer */
748 size_t resourcesize
, /* I - Size of resource buffer */
749 cups_dest_block_t block
) /* I - Callback block */
751 return (cupsConnectDest(dest
, flags
, msec
, cancel
, resource
, resourcesize
,
752 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
754 #endif /* __BLOCKS__ */
758 * 'cupsCopyDest()' - Copy a destination.
760 * Make a copy of the destination to an array of destinations (or just a single
761 * copy) - for use with the cupsEnumDests* functions. The caller is responsible
762 * for calling cupsFreeDests() on the returned object(s).
764 * @since CUPS 1.6/macOS 10.8@
768 cupsCopyDest(cups_dest_t
*dest
,
772 int i
; /* Looping var */
773 cups_dest_t
*new_dest
; /* New destination pointer */
774 cups_option_t
*new_option
, /* Current destination option */
775 *option
; /* Current parent option */
779 * Range check input...
782 if (!dest
|| num_dests
< 0 || !dests
)
786 * See if the destination already exists...
789 if ((new_dest
= cupsGetDest(dest
->name
, dest
->instance
, num_dests
,
793 * Protect against copying destination to itself...
796 if (new_dest
== dest
)
800 * Otherwise, free the options...
803 cupsFreeOptions(new_dest
->num_options
, new_dest
->options
);
805 new_dest
->num_options
= 0;
806 new_dest
->options
= NULL
;
809 new_dest
= cups_add_dest(dest
->name
, dest
->instance
, &num_dests
, dests
);
813 if ((new_dest
->options
= calloc(sizeof(cups_option_t
), (size_t)dest
->num_options
)) == NULL
)
814 return (cupsRemoveDest(dest
->name
, dest
->instance
, num_dests
, dests
));
816 new_dest
->num_options
= dest
->num_options
;
818 for (i
= dest
->num_options
, option
= dest
->options
,
819 new_option
= new_dest
->options
;
821 i
--, option
++, new_option
++)
823 new_option
->name
= _cupsStrRetain(option
->name
);
824 new_option
->value
= _cupsStrRetain(option
->value
);
833 * '_cupsCreateDest()' - Create a local (temporary) queue.
836 char * /* O - Printer URI or @code NULL@ on error */
837 _cupsCreateDest(const char *name
, /* I - Printer name */
838 const char *info
, /* I - Printer description of @code NULL@ */
839 const char *device_id
, /* I - 1284 Device ID or @code NULL@ */
840 const char *device_uri
, /* I - Device URI */
841 char *uri
, /* I - Printer URI buffer */
842 size_t urisize
) /* I - Size of URI buffer */
844 http_t
*http
; /* Connection to server */
845 ipp_t
*request
, /* CUPS-Create-Local-Printer request */
846 *response
; /* CUPS-Create-Local-Printer response */
847 ipp_attribute_t
*attr
; /* printer-uri-supported attribute */
848 ipp_pstate_t state
= IPP_PSTATE_STOPPED
;
849 /* printer-state value */
852 if (!name
|| !device_uri
|| !uri
|| urisize
< 32)
855 if ((http
= httpConnect2(cupsServer(), ippPort(), NULL
, AF_UNSPEC
, HTTP_ENCRYPTION_IF_REQUESTED
, 1, 30000, NULL
)) == NULL
)
858 request
= ippNewRequest(IPP_OP_CUPS_CREATE_LOCAL_PRINTER
);
860 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
, "ipp://localhost/");
861 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
, "requesting-user-name", NULL
, cupsUser());
863 ippAddString(request
, IPP_TAG_PRINTER
, IPP_TAG_URI
, "device-uri", NULL
, device_uri
);
864 ippAddString(request
, IPP_TAG_PRINTER
, IPP_TAG_NAME
, "printer-name", NULL
, name
);
866 ippAddString(request
, IPP_TAG_PRINTER
, IPP_TAG_TEXT
, "printer-info", NULL
, info
);
868 ippAddString(request
, IPP_TAG_PRINTER
, IPP_TAG_TEXT
, "printer-device-id", NULL
, device_id
);
870 response
= cupsDoRequest(http
, request
, "/");
872 if ((attr
= ippFindAttribute(response
, "printer-uri-supported", IPP_TAG_URI
)) != NULL
)
873 strlcpy(uri
, ippGetString(attr
, 0, NULL
), urisize
);
881 if ((attr
= ippFindAttribute(response
, "printer-state", IPP_TAG_ENUM
)) != NULL
)
882 state
= (ipp_pstate_t
)ippGetInteger(attr
, 0);
884 while (state
== IPP_PSTATE_STOPPED
&& cupsLastError() == IPP_STATUS_OK
)
889 request
= ippNewRequest(IPP_OP_GET_PRINTER_ATTRIBUTES
);
891 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
, uri
);
892 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
, "requesting-user-name", NULL
, cupsUser());
893 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_KEYWORD
, "requested-attributes", NULL
, "printer-state");
895 response
= cupsDoRequest(http
, request
, "/");
897 if ((attr
= ippFindAttribute(response
, "printer-state", IPP_TAG_ENUM
)) != NULL
)
898 state
= (ipp_pstate_t
)ippGetInteger(attr
, 0);
910 * 'cupsEnumDests()' - Enumerate available destinations with a callback function.
912 * Destinations are enumerated from one or more sources. The callback function
913 * receives the @code user_data@ pointer, destination name, instance, number of
914 * options, and options which can be used as input to the @link cupsAddDest@
915 * function. The function must return 1 to continue enumeration or 0 to stop.
917 * Enumeration happens on the current thread and does not return until all
918 * destinations have been enumerated or the callback function returns 0.
920 * @since CUPS 1.6/macOS 10.8@
923 int /* O - 1 on success, 0 on failure */
925 unsigned flags
, /* I - Enumeration flags */
926 int msec
, /* I - Timeout in milliseconds, -1 for indefinite */
927 int *cancel
, /* I - Pointer to "cancel" variable */
928 cups_ptype_t type
, /* I - Printer type bits */
929 cups_ptype_t mask
, /* I - Mask for printer type bits */
930 cups_dest_cb_t cb
, /* I - Callback function */
931 void *user_data
) /* I - User data */
933 int i
, /* Looping var */
934 num_dests
; /* Number of destinations */
935 cups_dest_t
*dests
= NULL
, /* Destinations */
936 *dest
; /* Current destination */
937 const char *defprinter
; /* Default printer */
938 char name
[1024], /* Copy of printer name */
939 *instance
, /* Pointer to instance name */
940 *user_default
; /* User default printer */
941 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
942 int count
, /* Number of queries started */
943 completed
, /* Number of completed queries */
944 remaining
; /* Remainder of timeout */
945 _cups_dnssd_data_t data
; /* Data for callback */
946 _cups_dnssd_device_t
*device
; /* Current device */
948 int nfds
, /* Number of files responded */
949 main_fd
; /* File descriptor for lookups */
950 DNSServiceRef ipp_ref
, /* IPP browser */
951 local_ipp_ref
; /* Local IPP browser */
953 DNSServiceRef ipps_ref
, /* IPPS browser */
954 local_ipps_ref
; /* Local IPPS browser */
955 # endif /* HAVE_SSL */
957 struct pollfd pfd
; /* Polling data */
959 fd_set input
; /* Input set for select() */
960 struct timeval timeout
; /* Timeout for select() */
961 # endif /* HAVE_POLL */
962 # else /* HAVE_AVAHI */
963 int error
; /* Error value */
964 AvahiServiceBrowser
*ipp_ref
; /* IPP browser */
966 AvahiServiceBrowser
*ipps_ref
; /* IPPS browser */
967 # endif /* HAVE_SSL */
968 # endif /* HAVE_DNSSD */
969 #endif /* HAVE_DNSSD || HAVE_AVAHI */
972 * Range check input...
981 * Get the list of local printers and pass them to the callback function...
984 num_dests
= _cupsGetDests(CUPS_HTTP_DEFAULT
, IPP_OP_CUPS_GET_PRINTERS
, NULL
,
985 &dests
, type
, mask
| CUPS_PRINTER_3D
);
987 if ((user_default
= _cupsUserDefault(name
, sizeof(name
))) != NULL
)
989 else if ((defprinter
= cupsGetDefault2(CUPS_HTTP_DEFAULT
)) != NULL
)
991 strlcpy(name
, defprinter
, sizeof(name
));
998 * Separate printer and instance name...
1001 if ((instance
= strchr(name
, '/')) != NULL
)
1005 * Lookup the printer and instance and make it the default...
1008 if ((dest
= cupsGetDest(name
, instance
, num_dests
, dests
)) != NULL
)
1009 dest
->is_default
= 1;
1012 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1016 data
.user_data
= user_data
;
1017 data
.devices
= cupsArrayNew3((cups_array_func_t
)cups_dnssd_compare_devices
, NULL
, NULL
, 0, NULL
, (cups_afree_func_t
)cups_dnssd_free_device
);
1018 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1020 for (i
= num_dests
, dest
= dests
;
1021 i
> 0 && (!cancel
|| !*cancel
);
1024 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1025 const char *device_uri
; /* Device URI */
1026 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1028 if (!(*cb
)(user_data
, i
> 1 ? CUPS_DEST_FLAGS_MORE
: CUPS_DEST_FLAGS_NONE
,
1032 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1033 if (!dest
->instance
&& (device_uri
= cupsGetOption("device-uri", dest
->num_options
, dest
->options
)) != NULL
&& !strncmp(device_uri
, "dnssd://", 8))
1036 * Add existing queue using service name, etc. so we don't list it again...
1039 char scheme
[32], /* URI scheme */
1040 userpass
[32], /* Username:password */
1041 serviceName
[256], /* Service name (host field) */
1042 resource
[256], /* Resource (options) */
1043 *regtype
, /* Registration type */
1044 *replyDomain
; /* Registration domain */
1045 int port
; /* Port number (not used) */
1047 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
)
1049 if ((regtype
= strstr(serviceName
, "._ipp")) != NULL
)
1053 if ((replyDomain
= strstr(regtype
, "._tcp.")) != NULL
)
1055 replyDomain
[5] = '\0';
1058 if ((device
= cups_dnssd_get_device(&data
, serviceName
, regtype
, replyDomain
)) != NULL
)
1059 device
->state
= _CUPS_DNSSD_ACTIVE
;
1064 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1067 cupsFreeDests(num_dests
, dests
);
1069 if (i
> 0 || msec
== 0)
1071 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1072 cupsArrayDelete(data
.devices
);
1073 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1078 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1080 * Get Bonjour-shared printers...
1084 if (DNSServiceCreateConnection(&data
.main_ref
) != kDNSServiceErr_NoError
)
1087 main_fd
= DNSServiceRefSockFD(data
.main_ref
);
1089 ipp_ref
= data
.main_ref
;
1090 DNSServiceBrowse(&ipp_ref
, kDNSServiceFlagsShareConnection
, 0,
1092 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
1094 local_ipp_ref
= data
.main_ref
;
1095 DNSServiceBrowse(&local_ipp_ref
, kDNSServiceFlagsShareConnection
,
1096 kDNSServiceInterfaceIndexLocalOnly
,
1098 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
1101 ipps_ref
= data
.main_ref
;
1102 DNSServiceBrowse(&ipps_ref
, kDNSServiceFlagsShareConnection
, 0,
1104 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
1106 local_ipps_ref
= data
.main_ref
;
1107 DNSServiceBrowse(&local_ipps_ref
, kDNSServiceFlagsShareConnection
,
1108 kDNSServiceInterfaceIndexLocalOnly
,
1110 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
1111 # endif /* HAVE_SSL */
1113 # else /* HAVE_AVAHI */
1114 if ((data
.simple_poll
= avahi_simple_poll_new()) == NULL
)
1116 DEBUG_puts("cupsEnumDests: Unable to create Avahi simple poll object.");
1120 avahi_simple_poll_set_func(data
.simple_poll
, cups_dnssd_poll_cb
, &data
);
1122 data
.client
= avahi_client_new(avahi_simple_poll_get(data
.simple_poll
),
1123 0, cups_dnssd_client_cb
, &data
,
1127 DEBUG_puts("cupsEnumDests: Unable to create Avahi client.");
1128 avahi_simple_poll_free(data
.simple_poll
);
1133 ipp_ref
= avahi_service_browser_new(data
.client
, AVAHI_IF_UNSPEC
,
1134 AVAHI_PROTO_UNSPEC
, "_ipp._tcp", NULL
,
1135 0, cups_dnssd_browse_cb
, &data
);
1138 ipps_ref
= avahi_service_browser_new(data
.client
, AVAHI_IF_UNSPEC
,
1139 AVAHI_PROTO_UNSPEC
, "_ipps._tcp", NULL
,
1140 0, cups_dnssd_browse_cb
, &data
);
1141 # endif /* HAVE_SSL */
1142 # endif /* HAVE_DNSSD */
1145 remaining
= INT_MAX
;
1149 while (remaining
> 0 && (!cancel
|| !*cancel
))
1152 * Check for input...
1158 pfd
.events
= POLLIN
;
1160 nfds
= poll(&pfd
, 1, remaining
> 500 ? 500 : remaining
);
1164 FD_SET(main_fd
, &input
);
1167 timeout
.tv_usec
= remaining
> 500 ? 500000 : remaining
* 1000;
1169 nfds
= select(main_fd
+ 1, &input
, NULL
, NULL
, &timeout
);
1170 # endif /* HAVE_POLL */
1173 DNSServiceProcessResult(data
.main_ref
);
1175 # else /* HAVE_AVAHI */
1178 if ((error
= avahi_simple_poll_iterate(data
.simple_poll
, 1000)) > 0)
1181 * We've been told to exit the loop. Perhaps the connection to
1188 DEBUG_printf(("1cupsEnumDests: got_data=%d", data
.got_data
));
1189 # endif /* HAVE_DNSSD */
1193 for (device
= (_cups_dnssd_device_t
*)cupsArrayFirst(data
.devices
),
1194 count
= 0, completed
= 0;
1196 device
= (_cups_dnssd_device_t
*)cupsArrayNext(data
.devices
))
1201 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
1204 if (!device
->ref
&& device
->state
== _CUPS_DNSSD_NEW
)
1206 DEBUG_printf(("1cupsEnumDests: Querying '%s'.", device
->fullName
));
1209 device
->ref
= data
.main_ref
;
1211 if (DNSServiceQueryRecord(&(device
->ref
),
1212 kDNSServiceFlagsShareConnection
,
1213 0, device
->fullName
,
1214 kDNSServiceType_TXT
,
1215 kDNSServiceClass_IN
,
1216 (DNSServiceQueryRecordReply
)cups_dnssd_query_cb
,
1217 &data
) == kDNSServiceErr_NoError
)
1224 device
->state
= _CUPS_DNSSD_ERROR
;
1226 DEBUG_puts("1cupsEnumDests: Query failed.");
1229 # else /* HAVE_AVAHI */
1230 if ((device
->ref
= avahi_record_browser_new(data
.client
,
1237 cups_dnssd_query_cb
,
1240 DEBUG_printf(("1cupsEnumDests: browser ref=%p", device
->ref
));
1245 device
->state
= _CUPS_DNSSD_ERROR
;
1247 DEBUG_printf(("1cupsEnumDests: Query failed: %s", avahi_strerror(avahi_client_errno(data
.client
))));
1249 # endif /* HAVE_DNSSD */
1251 else if (device
->ref
&& device
->state
== _CUPS_DNSSD_PENDING
)
1255 if ((device
->type
& mask
) == type
)
1257 DEBUG_printf(("1cupsEnumDests: Add callback for \"%s\".", device
->dest
.name
));
1258 if (!(*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, &device
->dest
))
1265 device
->state
= _CUPS_DNSSD_ACTIVE
;
1270 DEBUG_printf(("1cupsEnumDests: browsers=%d, completed=%d, count=%d, devices count=%d", data
.browsers
, completed
, count
, cupsArrayCount(data
.devices
)));
1272 if (data
.browsers
== 0 && completed
== cupsArrayCount(data
.devices
))
1275 DEBUG_printf(("1cupsEnumDests: completed=%d, count=%d, devices count=%d", completed
, count
, cupsArrayCount(data
.devices
)));
1277 if (completed
== cupsArrayCount(data
.devices
))
1279 # endif /* HAVE_AVAHI */
1282 cupsArrayDelete(data
.devices
);
1285 DNSServiceRefDeallocate(ipp_ref
);
1286 DNSServiceRefDeallocate(local_ipp_ref
);
1289 DNSServiceRefDeallocate(ipp_ref
);
1290 DNSServiceRefDeallocate(local_ipp_ref
);
1291 # endif /* HAVE_SSL */
1293 DNSServiceRefDeallocate(data
.main_ref
);
1295 # else /* HAVE_AVAHI */
1296 avahi_service_browser_free(ipp_ref
);
1298 avahi_service_browser_free(ipps_ref
);
1299 # endif /* HAVE_SSL */
1301 avahi_client_free(data
.client
);
1302 avahi_simple_poll_free(data
.simple_poll
);
1303 # endif /* HAVE_DNSSD */
1304 #endif /* HAVE_DNSSD || HAVE_DNSSD */
1312 * 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
1314 * Destinations are enumerated from one or more sources. The block receives the
1315 * destination name, instance, number of options, and options which can be used
1316 * as input to the @link cupsAddDest@ function. The block must return 1 to
1317 * continue enumeration or 0 to stop.
1319 * Enumeration happens on the current thread and does not return until all
1320 * destinations have been enumerated or the block returns 0.
1322 * @since CUPS 1.6/macOS 10.8@
1325 int /* O - 1 on success, 0 on failure */
1327 unsigned flags
, /* I - Enumeration flags */
1328 int timeout
, /* I - Timeout in milliseconds, 0 for indefinite */
1329 int *cancel
, /* I - Pointer to "cancel" variable */
1330 cups_ptype_t type
, /* I - Printer type bits */
1331 cups_ptype_t mask
, /* I - Mask for printer type bits */
1332 cups_dest_block_t block
) /* I - Block */
1334 return (cupsEnumDests(flags
, timeout
, cancel
, type
, mask
,
1335 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
1337 # endif /* __BLOCKS__ */
1341 * 'cupsFreeDests()' - Free the memory used by the list of destinations.
1345 cupsFreeDests(int num_dests
, /* I - Number of destinations */
1346 cups_dest_t
*dests
) /* I - Destinations */
1348 int i
; /* Looping var */
1349 cups_dest_t
*dest
; /* Current destination */
1352 if (num_dests
== 0 || dests
== NULL
)
1355 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1357 _cupsStrFree(dest
->name
);
1358 _cupsStrFree(dest
->instance
);
1360 cupsFreeOptions(dest
->num_options
, dest
->options
);
1368 * 'cupsGetDest()' - Get the named destination from the list.
1370 * Use the @link cupsGetDests@ or @link cupsGetDests2@ functions to get a
1371 * list of supported destinations for the current user.
1374 cups_dest_t
* /* O - Destination pointer or @code NULL@ */
1375 cupsGetDest(const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1376 const char *instance
, /* I - Instance name or @code NULL@ */
1377 int num_dests
, /* I - Number of destinations */
1378 cups_dest_t
*dests
) /* I - Destinations */
1380 int diff
, /* Result of comparison */
1381 match
; /* Matching index */
1384 if (num_dests
<= 0 || !dests
)
1390 * NULL name for default printer.
1393 while (num_dests
> 0)
1395 if (dests
->is_default
)
1405 * Lookup name and optionally the instance...
1408 match
= cups_find_dest(name
, instance
, num_dests
, dests
, -1, &diff
);
1411 return (dests
+ match
);
1419 * '_cupsGetDestResource()' - Get the resource path and URI for a destination.
1422 const char * /* O - Printer URI */
1423 _cupsGetDestResource(
1424 cups_dest_t
*dest
, /* I - Destination */
1425 char *resource
, /* I - Resource buffer */
1426 size_t resourcesize
) /* I - Size of resource buffer */
1428 const char *uri
; /* Printer URI */
1429 char scheme
[32], /* URI scheme */
1430 userpass
[256], /* Username and password (unused) */
1431 hostname
[256]; /* Hostname */
1432 int port
; /* Port number */
1436 * Range check input...
1439 if (!dest
|| !resource
|| resourcesize
< 1)
1444 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
1449 * Grab the printer URI...
1452 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
,
1453 dest
->options
)) == NULL
)
1458 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(ENOENT
), 0);
1464 if (strstr(uri
, "._tcp"))
1466 if ((uri
= cups_dnssd_resolve(dest
, uri
, 5000, NULL
, NULL
, NULL
)) == NULL
)
1469 #endif /* HAVE_DNSSD */
1471 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
1472 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
1473 &port
, resource
, (int)resourcesize
) < HTTP_URI_STATUS_OK
)
1475 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer-uri."), 1);
1485 * 'cupsGetDestWithURI()' - Get a destination associated with a URI.
1487 * "name" is the desired name for the printer. If @code NULL@, a name will be
1488 * created using the URI.
1490 * "uri" is the "ipp" or "ipps" URI for the printer.
1492 * @since CUPS 2.0/macOS 10.10@
1495 cups_dest_t
* /* O - Destination or @code NULL@ */
1496 cupsGetDestWithURI(const char *name
, /* I - Desired printer name or @code NULL@ */
1497 const char *uri
) /* I - URI for the printer */
1499 cups_dest_t
*dest
; /* New destination */
1500 char temp
[1024], /* Temporary string */
1501 scheme
[256], /* Scheme from URI */
1502 userpass
[256], /* Username:password from URI */
1503 hostname
[256], /* Hostname from URI */
1504 resource
[1024], /* Resource path from URI */
1505 *ptr
; /* Pointer into string */
1506 int port
; /* Port number from URI */
1510 * Range check input...
1515 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
1519 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
), userpass
, sizeof(userpass
), hostname
, sizeof(hostname
), &port
, resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
||
1520 (strncmp(uri
, "ipp://", 6) && strncmp(uri
, "ipps://", 7)))
1522 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer-uri."), 1);
1530 * Create the name from the URI...
1533 if (strstr(hostname
, "._tcp"))
1536 * Use the service instance name...
1539 if ((ptr
= strchr(hostname
, '.')) != NULL
)
1544 else if (!strncmp(resource
, "/classes/", 9))
1546 snprintf(temp
, sizeof(temp
), "%s @ %s", resource
+ 9, hostname
);
1549 else if (!strncmp(resource
, "/printers/", 10))
1551 snprintf(temp
, sizeof(temp
), "%s @ %s", resource
+ 10, hostname
);
1561 * Create the destination...
1564 if ((dest
= calloc(1, sizeof(cups_dest_t
))) == NULL
)
1566 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
1570 dest
->name
= _cupsStrAlloc(name
);
1571 dest
->num_options
= cupsAddOption("device-uri", uri
, dest
->num_options
, &(dest
->options
));
1572 dest
->num_options
= cupsAddOption("printer-info", name
, dest
->num_options
, &(dest
->options
));
1579 * '_cupsGetDests()' - Get destinations from a server.
1581 * "op" is IPP_OP_CUPS_GET_PRINTERS to get a full list, IPP_OP_CUPS_GET_DEFAULT
1582 * to get the system-wide default printer, or IPP_OP_GET_PRINTER_ATTRIBUTES for
1585 * "name" is the name of an existing printer and is only used when "op" is
1586 * IPP_OP_GET_PRINTER_ATTRIBUTES.
1588 * "dest" is initialized to point to the array of destinations.
1590 * 0 is returned if there are no printers, no default printer, or the named
1591 * printer does not exist, respectively.
1593 * Free the memory used by the destination array using the @link cupsFreeDests@
1596 * Note: On macOS this function also gets the default paper from the system
1597 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1598 * options array for each destination that supports it.
1601 int /* O - Number of destinations */
1602 _cupsGetDests(http_t
*http
, /* I - Connection to server or
1603 * @code CUPS_HTTP_DEFAULT@ */
1604 ipp_op_t op
, /* I - IPP operation */
1605 const char *name
, /* I - Name of destination */
1606 cups_dest_t
**dests
, /* IO - Destinations */
1607 cups_ptype_t type
, /* I - Printer type bits */
1608 cups_ptype_t mask
) /* I - Printer type mask */
1610 int num_dests
= 0; /* Number of destinations */
1611 cups_dest_t
*dest
; /* Current destination */
1612 ipp_t
*request
, /* IPP Request */
1613 *response
; /* IPP Response */
1614 ipp_attribute_t
*attr
; /* Current attribute */
1615 const char *printer_name
; /* printer-name attribute */
1616 char uri
[1024]; /* printer-uri value */
1617 int num_options
; /* Number of options */
1618 cups_option_t
*options
; /* Options */
1620 char media_default
[41]; /* Default paper size */
1621 #endif /* __APPLE__ */
1622 char optname
[1024], /* Option name */
1623 value
[2048], /* Option value */
1624 *ptr
; /* Pointer into name/value */
1625 static const char * const pattrs
[] = /* Attributes we're interested in */
1627 "auth-info-required",
1629 "job-sheets-default",
1630 "marker-change-time",
1632 "marker-high-levels",
1634 "marker-low-levels",
1640 #endif /* __APPLE__ */
1644 "printer-is-accepting-jobs",
1645 "printer-is-shared",
1647 "printer-make-and-model",
1648 "printer-mandatory-job-attributes",
1651 "printer-state-change-time",
1652 "printer-state-reasons",
1654 "printer-uri-supported"
1660 * Get the default paper size...
1663 appleGetPaperSize(media_default
, sizeof(media_default
));
1664 #endif /* __APPLE__ */
1667 * Build a IPP_OP_CUPS_GET_PRINTERS or IPP_OP_GET_PRINTER_ATTRIBUTES request, which
1668 * require the following attributes:
1670 * attributes-charset
1671 * attributes-natural-language
1672 * requesting-user-name
1673 * printer-uri [for IPP_OP_GET_PRINTER_ATTRIBUTES]
1676 request
= ippNewRequest(op
);
1678 ippAddStrings(request
, IPP_TAG_OPERATION
, IPP_TAG_KEYWORD
,
1679 "requested-attributes", sizeof(pattrs
) / sizeof(pattrs
[0]),
1682 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
,
1683 "requesting-user-name", NULL
, cupsUser());
1685 if (name
&& op
!= IPP_OP_CUPS_GET_DEFAULT
)
1687 httpAssembleURIf(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
), "ipp", NULL
,
1688 "localhost", ippPort(), "/printers/%s", name
);
1689 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
,
1694 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type", (int)type
);
1695 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type-mask", (int)mask
);
1699 * Do the request and get back a response...
1702 if ((response
= cupsDoRequest(http
, request
, "/")) != NULL
)
1704 for (attr
= response
->attrs
; attr
!= NULL
; attr
= attr
->next
)
1707 * Skip leading attributes until we hit a printer...
1710 while (attr
!= NULL
&& attr
->group_tag
!= IPP_TAG_PRINTER
)
1717 * Pull the needed attributes from this printer...
1720 printer_name
= NULL
;
1724 for (; attr
&& attr
->group_tag
== IPP_TAG_PRINTER
; attr
= attr
->next
)
1726 if (attr
->value_tag
!= IPP_TAG_INTEGER
&&
1727 attr
->value_tag
!= IPP_TAG_ENUM
&&
1728 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
1729 attr
->value_tag
!= IPP_TAG_TEXT
&&
1730 attr
->value_tag
!= IPP_TAG_TEXTLANG
&&
1731 attr
->value_tag
!= IPP_TAG_NAME
&&
1732 attr
->value_tag
!= IPP_TAG_NAMELANG
&&
1733 attr
->value_tag
!= IPP_TAG_KEYWORD
&&
1734 attr
->value_tag
!= IPP_TAG_RANGE
&&
1735 attr
->value_tag
!= IPP_TAG_URI
)
1738 if (!strcmp(attr
->name
, "auth-info-required") ||
1739 !strcmp(attr
->name
, "device-uri") ||
1740 !strcmp(attr
->name
, "marker-change-time") ||
1741 !strcmp(attr
->name
, "marker-colors") ||
1742 !strcmp(attr
->name
, "marker-high-levels") ||
1743 !strcmp(attr
->name
, "marker-levels") ||
1744 !strcmp(attr
->name
, "marker-low-levels") ||
1745 !strcmp(attr
->name
, "marker-message") ||
1746 !strcmp(attr
->name
, "marker-names") ||
1747 !strcmp(attr
->name
, "marker-types") ||
1748 !strcmp(attr
->name
, "printer-commands") ||
1749 !strcmp(attr
->name
, "printer-info") ||
1750 !strcmp(attr
->name
, "printer-is-shared") ||
1751 !strcmp(attr
->name
, "printer-make-and-model") ||
1752 !strcmp(attr
->name
, "printer-mandatory-job-attributes") ||
1753 !strcmp(attr
->name
, "printer-state") ||
1754 !strcmp(attr
->name
, "printer-state-change-time") ||
1755 !strcmp(attr
->name
, "printer-type") ||
1756 !strcmp(attr
->name
, "printer-is-accepting-jobs") ||
1757 !strcmp(attr
->name
, "printer-location") ||
1758 !strcmp(attr
->name
, "printer-state-reasons") ||
1759 !strcmp(attr
->name
, "printer-uri-supported"))
1762 * Add a printer description attribute...
1765 num_options
= cupsAddOption(attr
->name
,
1766 cups_make_string(attr
, value
,
1768 num_options
, &options
);
1771 else if (!strcmp(attr
->name
, "media-supported"))
1774 * See if we can set a default media size...
1777 int i
; /* Looping var */
1779 for (i
= 0; i
< attr
->num_values
; i
++)
1780 if (!_cups_strcasecmp(media_default
, attr
->values
[i
].string
.text
))
1782 num_options
= cupsAddOption("media", media_default
, num_options
,
1787 #endif /* __APPLE__ */
1788 else if (!strcmp(attr
->name
, "printer-name") &&
1789 attr
->value_tag
== IPP_TAG_NAME
)
1790 printer_name
= attr
->values
[0].string
.text
;
1791 else if (strncmp(attr
->name
, "notify-", 7) &&
1792 (attr
->value_tag
== IPP_TAG_BOOLEAN
||
1793 attr
->value_tag
== IPP_TAG_ENUM
||
1794 attr
->value_tag
== IPP_TAG_INTEGER
||
1795 attr
->value_tag
== IPP_TAG_KEYWORD
||
1796 attr
->value_tag
== IPP_TAG_NAME
||
1797 attr
->value_tag
== IPP_TAG_RANGE
) &&
1798 (ptr
= strstr(attr
->name
, "-default")) != NULL
)
1801 * Add a default option...
1804 strlcpy(optname
, attr
->name
, sizeof(optname
));
1805 optname
[ptr
- attr
->name
] = '\0';
1807 if (_cups_strcasecmp(optname
, "media") ||
1808 !cupsGetOption("media", num_options
, options
))
1809 num_options
= cupsAddOption(optname
,
1810 cups_make_string(attr
, value
,
1812 num_options
, &options
);
1817 * See if we have everything needed...
1822 cupsFreeOptions(num_options
, options
);
1830 if ((dest
= cups_add_dest(printer_name
, NULL
, &num_dests
, dests
)) != NULL
)
1832 dest
->num_options
= num_options
;
1833 dest
->options
= options
;
1836 cupsFreeOptions(num_options
, options
);
1842 ippDelete(response
);
1846 * Return the count...
1854 * 'cupsGetDests()' - Get the list of destinations from the default server.
1856 * Starting with CUPS 1.2, the returned list of destinations include the
1857 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1858 * printer-make-and-model, printer-state, printer-state-change-time,
1859 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1860 * adds the marker-change-time, marker-colors, marker-high-levels,
1861 * marker-levels, marker-low-levels, marker-message, marker-names,
1862 * marker-types, and printer-commands attributes as well.
1864 * Use the @link cupsFreeDests@ function to free the destination list and
1865 * the @link cupsGetDest@ function to find a particular destination.
1868 int /* O - Number of destinations */
1869 cupsGetDests(cups_dest_t
**dests
) /* O - Destinations */
1871 return (cupsGetDests2(CUPS_HTTP_DEFAULT
, dests
));
1876 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1878 * Starting with CUPS 1.2, the returned list of destinations include the
1879 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1880 * printer-make-and-model, printer-state, printer-state-change-time,
1881 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1882 * adds the marker-change-time, marker-colors, marker-high-levels,
1883 * marker-levels, marker-low-levels, marker-message, marker-names,
1884 * marker-types, and printer-commands attributes as well.
1886 * Use the @link cupsFreeDests@ function to free the destination list and
1887 * the @link cupsGetDest@ function to find a particular destination.
1889 * @since CUPS 1.1.21/macOS 10.4@
1892 int /* O - Number of destinations */
1893 cupsGetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1894 cups_dest_t
**dests
) /* O - Destinations */
1896 int num_dests
; /* Number of destinations */
1897 cups_dest_t
*dest
; /* Destination pointer */
1898 const char *home
; /* HOME environment variable */
1899 char filename
[1024]; /* Local ~/.cups/lpoptions file */
1900 const char *defprinter
; /* Default printer */
1901 char name
[1024], /* Copy of printer name */
1902 *instance
, /* Pointer to instance name */
1903 *user_default
; /* User default printer */
1904 int num_reals
; /* Number of real queues */
1905 cups_dest_t
*reals
; /* Real queues */
1906 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1910 * Range check the input...
1915 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad NULL dests pointer"), 1);
1920 * Grab the printers and classes...
1923 *dests
= (cups_dest_t
*)0;
1924 num_dests
= _cupsGetDests(http
, IPP_OP_CUPS_GET_PRINTERS
, NULL
, dests
, 0, CUPS_PRINTER_3D
);
1926 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE
)
1928 cupsFreeDests(num_dests
, *dests
);
1929 *dests
= (cups_dest_t
*)0;
1934 * Make a copy of the "real" queues for a later sanity check...
1939 num_reals
= num_dests
;
1940 reals
= calloc((size_t)num_reals
, sizeof(cups_dest_t
));
1943 memcpy(reals
, *dests
, (size_t)num_reals
* sizeof(cups_dest_t
));
1954 * Grab the default destination...
1957 if ((user_default
= _cupsUserDefault(name
, sizeof(name
))) != NULL
)
1959 else if ((defprinter
= cupsGetDefault2(http
)) != NULL
)
1961 strlcpy(name
, defprinter
, sizeof(name
));
1968 * Separate printer and instance name...
1971 if ((instance
= strchr(name
, '/')) != NULL
)
1975 * Lookup the printer and instance and make it the default...
1978 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) != NULL
)
1979 dest
->is_default
= 1;
1985 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
1988 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1989 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1992 if ((home
= getenv("HOME")) != NULL
)
1994 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1996 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
2001 * Validate the current default destination - this prevents old
2002 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
2003 * pointing to a non-existent printer or class...
2009 * See if we have a default printer...
2012 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, *dests
)) != NULL
)
2015 * Have a default; see if it is real...
2018 if (!cupsGetDest(dest
->name
, NULL
, num_reals
, reals
))
2021 * Remove the non-real printer from the list, since we don't want jobs
2022 * going to an unexpected printer... (<rdar://problem/14216472>)
2025 num_dests
= cupsRemoveDest(dest
->name
, dest
->instance
, num_dests
,
2038 * Return the number of destinations...
2042 _cupsSetError(IPP_STATUS_OK
, NULL
, 0);
2049 * 'cupsGetNamedDest()' - Get options for the named destination.
2051 * This function is optimized for retrieving a single destination and should
2052 * be used instead of @link cupsGetDests@ and @link cupsGetDest@ when you either
2053 * know the name of the destination or want to print to the default destination.
2054 * If @code NULL@ is returned, the destination does not exist or there is no
2055 * default destination.
2057 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
2058 * server will be used.
2060 * If "name" is @code NULL@, the default printer for the current user will be
2063 * The returned destination must be freed using @link cupsFreeDests@ with a
2064 * "num_dests" value of 1.
2066 * @since CUPS 1.4/macOS 10.6@
2069 cups_dest_t
* /* O - Destination or @code NULL@ */
2070 cupsGetNamedDest(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2071 const char *name
, /* I - Destination name or @code NULL@ for the default destination */
2072 const char *instance
) /* I - Instance name or @code NULL@ */
2074 cups_dest_t
*dest
; /* Destination */
2075 char filename
[1024], /* Path to lpoptions */
2076 defname
[256]; /* Default printer name */
2077 const char *home
= getenv("HOME"); /* Home directory */
2078 int set_as_default
= 0; /* Set returned destination as default */
2079 ipp_op_t op
= IPP_OP_GET_PRINTER_ATTRIBUTES
;
2080 /* IPP operation to get server ops */
2081 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
2085 * If "name" is NULL, find the default destination...
2091 name
= _cupsUserDefault(defname
, sizeof(defname
));
2095 char *ptr
; /* Temporary pointer... */
2097 if ((ptr
= strchr(defname
, '/')) != NULL
)
2108 * No default in the environment, try the user's lpoptions files...
2111 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
2113 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
2119 * Still not there? Try the system lpoptions file...
2122 snprintf(filename
, sizeof(filename
), "%s/lpoptions",
2123 cg
->cups_serverroot
);
2124 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
2130 * No locally-set default destination, ask the server...
2133 op
= IPP_OP_CUPS_GET_DEFAULT
;
2138 * Get the printer's attributes...
2141 if (!_cupsGetDests(http
, op
, name
, &dest
, 0, CUPS_PRINTER_3D
))
2145 dest
->instance
= _cupsStrAlloc(instance
);
2148 dest
->is_default
= 1;
2151 * Then add local options...
2154 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
2155 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
2159 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
2161 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
2165 * Return the result...
2173 * 'cupsRemoveDest()' - Remove a destination from the destination list.
2175 * Removing a destination/instance does not delete the class or printer
2176 * queue, merely the lpoptions for that destination/instance. Use the
2177 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
2178 * options for the user.
2180 * @since CUPS 1.3/macOS 10.5@
2183 int /* O - New number of destinations */
2184 cupsRemoveDest(const char *name
, /* I - Destination name */
2185 const char *instance
, /* I - Instance name or @code NULL@ */
2186 int num_dests
, /* I - Number of destinations */
2187 cups_dest_t
**dests
) /* IO - Destinations */
2189 int i
; /* Index into destinations */
2190 cups_dest_t
*dest
; /* Pointer to destination */
2194 * Find the destination...
2197 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
2204 _cupsStrFree(dest
->name
);
2205 _cupsStrFree(dest
->instance
);
2206 cupsFreeOptions(dest
->num_options
, dest
->options
);
2209 * Remove the destination from the array...
2214 i
= (int)(dest
- *dests
);
2217 memmove(dest
, dest
+ 1, (size_t)(num_dests
- i
) * sizeof(cups_dest_t
));
2224 * 'cupsSetDefaultDest()' - Set the default destination.
2226 * @since CUPS 1.3/macOS 10.5@
2231 const char *name
, /* I - Destination name */
2232 const char *instance
, /* I - Instance name or @code NULL@ */
2233 int num_dests
, /* I - Number of destinations */
2234 cups_dest_t
*dests
) /* I - Destinations */
2236 int i
; /* Looping var */
2237 cups_dest_t
*dest
; /* Current destination */
2241 * Range check input...
2244 if (!name
|| num_dests
<= 0 || !dests
)
2248 * Loop through the array and set the "is_default" flag for the matching
2252 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
2253 dest
->is_default
= !_cups_strcasecmp(name
, dest
->name
) &&
2254 ((!instance
&& !dest
->instance
) ||
2255 (instance
&& dest
->instance
&&
2256 !_cups_strcasecmp(instance
, dest
->instance
)));
2261 * 'cupsSetDests()' - Save the list of destinations for the default server.
2263 * This function saves the destinations to /etc/cups/lpoptions when run
2264 * as root and ~/.cups/lpoptions when run as a normal user.
2268 cupsSetDests(int num_dests
, /* I - Number of destinations */
2269 cups_dest_t
*dests
) /* I - Destinations */
2271 cupsSetDests2(CUPS_HTTP_DEFAULT
, num_dests
, dests
);
2276 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
2278 * This function saves the destinations to /etc/cups/lpoptions when run
2279 * as root and ~/.cups/lpoptions when run as a normal user.
2281 * @since CUPS 1.1.21/macOS 10.4@
2284 int /* O - 0 on success, -1 on error */
2285 cupsSetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2286 int num_dests
, /* I - Number of destinations */
2287 cups_dest_t
*dests
) /* I - Destinations */
2289 int i
, j
; /* Looping vars */
2290 int wrote
; /* Wrote definition? */
2291 cups_dest_t
*dest
; /* Current destination */
2292 cups_option_t
*option
; /* Current option */
2293 _ipp_option_t
*match
; /* Matching attribute for option */
2294 FILE *fp
; /* File pointer */
2296 const char *home
; /* HOME environment variable */
2298 char filename
[1024]; /* lpoptions file */
2299 int num_temps
; /* Number of temporary destinations */
2300 cups_dest_t
*temps
= NULL
, /* Temporary destinations */
2301 *temp
; /* Current temporary dest */
2302 const char *val
; /* Value of temporary option */
2303 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
2307 * Range check the input...
2310 if (!num_dests
|| !dests
)
2314 * Get the server destinations...
2317 num_temps
= _cupsGetDests(http
, IPP_OP_CUPS_GET_PRINTERS
, NULL
, &temps
, 0, CUPS_PRINTER_3D
);
2319 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE
)
2321 cupsFreeDests(num_temps
, temps
);
2326 * Figure out which file to write to...
2329 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
2335 * Merge in server defaults...
2338 num_temps
= cups_get_dests(filename
, NULL
, NULL
, 0, num_temps
, &temps
);
2341 * Point to user defaults...
2344 if ((home
= getenv("HOME")) != NULL
)
2347 * Create ~/.cups subdirectory...
2350 snprintf(filename
, sizeof(filename
), "%s/.cups", home
);
2351 if (access(filename
, 0))
2352 mkdir(filename
, 0700);
2354 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
2360 * Try to open the file...
2363 if ((fp
= fopen(filename
, "w")) == NULL
)
2365 cupsFreeDests(num_temps
, temps
);
2371 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2376 fchmod(fileno(fp
), 0644);
2380 * Write each printer; each line looks like:
2382 * Dest name[/instance] options
2383 * Default name[/instance] options
2386 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
2387 if (dest
->instance
!= NULL
|| dest
->num_options
!= 0 || dest
->is_default
)
2389 if (dest
->is_default
)
2391 fprintf(fp
, "Default %s", dest
->name
);
2393 fprintf(fp
, "/%s", dest
->instance
);
2400 if ((temp
= cupsGetDest(dest
->name
, dest
->instance
, num_temps
, temps
)) == NULL
)
2401 temp
= cupsGetDest(dest
->name
, NULL
, num_temps
, temps
);
2403 for (j
= dest
->num_options
, option
= dest
->options
; j
> 0; j
--, option
++)
2406 * See if this option is a printer attribute; if so, skip it...
2409 if ((match
= _ippFindOption(option
->name
)) != NULL
&&
2410 match
->group_tag
== IPP_TAG_PRINTER
)
2414 * See if the server/global options match these; if so, don't
2419 (val
= cupsGetOption(option
->name
, temp
->num_options
,
2420 temp
->options
)) != NULL
&&
2421 !_cups_strcasecmp(val
, option
->value
))
2425 * Options don't match, write to the file...
2430 fprintf(fp
, "Dest %s", dest
->name
);
2432 fprintf(fp
, "/%s", dest
->instance
);
2436 if (option
->value
[0])
2438 if (strchr(option
->value
, ' ') ||
2439 strchr(option
->value
, '\\') ||
2440 strchr(option
->value
, '\"') ||
2441 strchr(option
->value
, '\''))
2444 * Quote the value...
2447 fprintf(fp
, " %s=\"", option
->name
);
2449 for (val
= option
->value
; *val
; val
++)
2451 if (strchr("\"\'\\", *val
))
2462 * Store the literal value...
2465 fprintf(fp
, " %s=%s", option
->name
, option
->value
);
2469 fprintf(fp
, " %s", option
->name
);
2477 * Free the temporary destinations and close the file...
2480 cupsFreeDests(num_temps
, temps
);
2486 * Set the default printer for this location - this allows command-line
2487 * and GUI applications to share the same default destination...
2490 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, dests
)) != NULL
)
2492 CFStringRef name
= CFStringCreateWithCString(kCFAllocatorDefault
,
2494 kCFStringEncodingUTF8
);
2495 /* Default printer name */
2499 _cupsAppleSetDefaultPrinter(name
);
2503 #endif /* __APPLE__ */
2505 #ifdef HAVE_NOTIFY_POST
2507 * Send a notification so that macOS applications can know about the
2511 notify_post("com.apple.printerListChange");
2512 #endif /* HAVE_NOTIFY_POST */
2519 * '_cupsUserDefault()' - Get the user default printer from environment
2520 * variables and location information.
2523 char * /* O - Default printer or NULL */
2524 _cupsUserDefault(char *name
, /* I - Name buffer */
2525 size_t namesize
) /* I - Size of name buffer */
2527 const char *env
; /* LPDEST or PRINTER env variable */
2529 CFStringRef locprinter
; /* Last printer as this location */
2530 #endif /* __APPLE__ */
2533 if ((env
= getenv("LPDEST")) == NULL
)
2534 if ((env
= getenv("PRINTER")) != NULL
&& !strcmp(env
, "lp"))
2539 strlcpy(name
, env
, namesize
);
2545 * Use location-based defaults if "use last printer" is selected in the
2546 * system preferences...
2549 if ((locprinter
= _cupsAppleCopyDefaultPrinter()) != NULL
)
2551 CFStringGetCString(locprinter
, name
, (CFIndex
)namesize
, kCFStringEncodingUTF8
);
2552 CFRelease(locprinter
);
2557 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name
));
2559 return (*name
? name
: NULL
);
2563 * No location-based defaults on this platform...
2568 #endif /* __APPLE__ */
2572 #if _CUPS_LOCATION_DEFAULTS
2574 * 'appleCopyLocations()' - Copy the location history array.
2577 static CFArrayRef
/* O - Location array or NULL */
2578 appleCopyLocations(void)
2580 CFArrayRef locations
; /* Location array */
2584 * Look up the location array in the preferences...
2587 if ((locations
= CFPreferencesCopyAppValue(kLastUsedPrintersKey
,
2588 kCUPSPrintingPrefs
)) == NULL
)
2591 if (CFGetTypeID(locations
) != CFArrayGetTypeID())
2593 CFRelease(locations
);
2602 * 'appleCopyNetwork()' - Get the network ID for the current location.
2605 static CFStringRef
/* O - Network ID */
2606 appleCopyNetwork(void)
2608 SCDynamicStoreRef dynamicStore
; /* System configuration data */
2609 CFStringRef key
; /* Current network configuration key */
2610 CFDictionaryRef ip_dict
; /* Network configuration data */
2611 CFStringRef network
= NULL
; /* Current network ID */
2614 if ((dynamicStore
= SCDynamicStoreCreate(NULL
, CFSTR("libcups"), NULL
,
2618 * First use the IPv6 router address, if available, since that will generally
2619 * be a globally-unique link-local address.
2622 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2623 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv6
)) != NULL
)
2625 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2627 if ((network
= CFDictionaryGetValue(ip_dict
,
2628 kSCPropNetIPv6Router
)) != NULL
)
2638 * If that doesn't work, try the IPv4 router address. This isn't as unique
2639 * and will likely be a 10.x.y.z or 192.168.y.z address...
2644 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2645 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv4
)) != NULL
)
2647 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2649 if ((network
= CFDictionaryGetValue(ip_dict
,
2650 kSCPropNetIPv4Router
)) != NULL
)
2660 CFRelease(dynamicStore
);
2665 #endif /* _CUPS_LOCATION_DEFAULTS */
2670 * 'appleGetPaperSize()' - Get the default paper size.
2673 static char * /* O - Default paper size */
2674 appleGetPaperSize(char *name
, /* I - Paper size name buffer */
2675 size_t namesize
) /* I - Size of buffer */
2677 CFStringRef defaultPaperID
; /* Default paper ID */
2678 pwg_media_t
*pwgmedia
; /* PWG media size */
2681 defaultPaperID
= _cupsAppleCopyDefaultPaperID();
2682 if (!defaultPaperID
||
2683 CFGetTypeID(defaultPaperID
) != CFStringGetTypeID() ||
2684 !CFStringGetCString(defaultPaperID
, name
, (CFIndex
)namesize
, kCFStringEncodingUTF8
))
2686 else if ((pwgmedia
= pwgMediaForLegacy(name
)) != NULL
)
2687 strlcpy(name
, pwgmedia
->pwg
, namesize
);
2690 CFRelease(defaultPaperID
);
2694 #endif /* __APPLE__ */
2697 #if _CUPS_LOCATION_DEFAULTS
2699 * 'appleGetPrinter()' - Get a printer from the history array.
2702 static CFStringRef
/* O - Printer name or NULL */
2703 appleGetPrinter(CFArrayRef locations
, /* I - Location array */
2704 CFStringRef network
, /* I - Network name */
2705 CFIndex
*locindex
) /* O - Index in array */
2707 CFIndex i
, /* Looping var */
2708 count
; /* Number of locations */
2709 CFDictionaryRef location
; /* Current location */
2710 CFStringRef locnetwork
, /* Current network */
2711 locprinter
; /* Current printer */
2714 for (i
= 0, count
= CFArrayGetCount(locations
); i
< count
; i
++)
2715 if ((location
= CFArrayGetValueAtIndex(locations
, i
)) != NULL
&&
2716 CFGetTypeID(location
) == CFDictionaryGetTypeID())
2718 if ((locnetwork
= CFDictionaryGetValue(location
,
2719 kLocationNetworkKey
)) != NULL
&&
2720 CFGetTypeID(locnetwork
) == CFStringGetTypeID() &&
2721 CFStringCompare(network
, locnetwork
, 0) == kCFCompareEqualTo
&&
2722 (locprinter
= CFDictionaryGetValue(location
,
2723 kLocationPrinterIDKey
)) != NULL
&&
2724 CFGetTypeID(locprinter
) == CFStringGetTypeID())
2729 return (locprinter
);
2735 #endif /* _CUPS_LOCATION_DEFAULTS */
2739 * 'cups_add_dest()' - Add a destination to the array.
2741 * Unlike cupsAddDest(), this function does not check for duplicates.
2744 static cups_dest_t
* /* O - New destination */
2745 cups_add_dest(const char *name
, /* I - Name of destination */
2746 const char *instance
, /* I - Instance or NULL */
2747 int *num_dests
, /* IO - Number of destinations */
2748 cups_dest_t
**dests
) /* IO - Destinations */
2750 int insert
, /* Insertion point */
2751 diff
; /* Result of comparison */
2752 cups_dest_t
*dest
; /* Destination pointer */
2756 * Add new destination...
2759 if (*num_dests
== 0)
2760 dest
= malloc(sizeof(cups_dest_t
));
2762 dest
= realloc(*dests
, sizeof(cups_dest_t
) * (size_t)(*num_dests
+ 1));
2770 * Find where to insert the destination...
2773 if (*num_dests
== 0)
2777 insert
= cups_find_dest(name
, instance
, *num_dests
, *dests
, *num_dests
- 1,
2785 * Move the array elements as needed...
2788 if (insert
< *num_dests
)
2789 memmove(*dests
+ insert
+ 1, *dests
+ insert
, (size_t)(*num_dests
- insert
) * sizeof(cups_dest_t
));
2794 * Initialize the destination...
2797 dest
= *dests
+ insert
;
2798 dest
->name
= _cupsStrAlloc(name
);
2799 dest
->instance
= _cupsStrAlloc(instance
);
2800 dest
->is_default
= 0;
2801 dest
->num_options
= 0;
2802 dest
->options
= (cups_option_t
*)0;
2810 * 'cups_block_cb()' - Enumeration callback for block API.
2813 static int /* O - 1 to continue, 0 to stop */
2815 cups_dest_block_t block
, /* I - Block */
2816 unsigned flags
, /* I - Destination flags */
2817 cups_dest_t
*dest
) /* I - Destination */
2819 return ((block
)(flags
, dest
));
2821 # endif /* __BLOCKS__ */
2825 * 'cups_compare_dests()' - Compare two destinations.
2828 static int /* O - Result of comparison */
2829 cups_compare_dests(cups_dest_t
*a
, /* I - First destination */
2830 cups_dest_t
*b
) /* I - Second destination */
2832 int diff
; /* Difference */
2835 if ((diff
= _cups_strcasecmp(a
->name
, b
->name
)) != 0)
2837 else if (a
->instance
&& b
->instance
)
2838 return (_cups_strcasecmp(a
->instance
, b
->instance
));
2840 return ((a
->instance
&& !b
->instance
) - (!a
->instance
&& b
->instance
));
2844 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
2847 * 'cups_dnssd_browse_cb()' - Browse for printers.
2851 cups_dnssd_browse_cb(
2852 DNSServiceRef sdRef
, /* I - Service reference */
2853 DNSServiceFlags flags
, /* I - Option flags */
2854 uint32_t interfaceIndex
, /* I - Interface number */
2855 DNSServiceErrorType errorCode
, /* I - Error, if any */
2856 const char *serviceName
, /* I - Name of service/device */
2857 const char *regtype
, /* I - Type of service */
2858 const char *replyDomain
, /* I - Service domain */
2859 void *context
) /* I - Enumeration data */
2861 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2862 /* Enumeration data */
2865 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
));
2868 * Don't do anything on error...
2871 if (errorCode
!= kDNSServiceErr_NoError
)
2878 cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2882 # else /* HAVE_AVAHI */
2884 * 'cups_dnssd_browse_cb()' - Browse for printers.
2888 cups_dnssd_browse_cb(
2889 AvahiServiceBrowser
*browser
, /* I - Browser */
2890 AvahiIfIndex interface
, /* I - Interface index (unused) */
2891 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2892 AvahiBrowserEvent event
, /* I - What happened */
2893 const char *name
, /* I - Service name */
2894 const char *type
, /* I - Registration type */
2895 const char *domain
, /* I - Domain */
2896 AvahiLookupResultFlags flags
, /* I - Flags */
2897 void *context
) /* I - Devices array */
2900 AvahiClient
*client
= avahi_service_browser_get_client(browser
);
2901 /* Client information */
2903 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2904 /* Enumeration data */
2911 DEBUG_printf(("cups_dnssd_browse_cb(..., name=\"%s\", type=\"%s\", domain=\"%s\", ...);", name
, type
, domain
));
2915 case AVAHI_BROWSER_FAILURE
:
2916 DEBUG_printf(("cups_dnssd_browse_cb: %s", avahi_strerror(avahi_client_errno(client
))));
2917 avahi_simple_poll_quit(data
->simple_poll
);
2920 case AVAHI_BROWSER_NEW
:
2922 * This object is new on the network.
2925 if (flags
& AVAHI_LOOKUP_RESULT_LOCAL
)
2928 * This comes from the local machine so ignore it.
2931 DEBUG_printf(("cups_dnssd_browse_cb: Ignoring local service \"%s\".", name
));
2936 * Create a device entry for it if it doesn't yet exist.
2939 cups_dnssd_get_device(data
, name
, type
, domain
);
2943 case AVAHI_BROWSER_REMOVE
:
2944 case AVAHI_BROWSER_CACHE_EXHAUSTED
:
2947 case AVAHI_BROWSER_ALL_FOR_NOW
:
2948 DEBUG_puts("cups_dnssd_browse_cb: ALL_FOR_NOW");
2956 * 'cups_dnssd_client_cb()' - Avahi client callback function.
2960 cups_dnssd_client_cb(
2961 AvahiClient
*client
, /* I - Client information (unused) */
2962 AvahiClientState state
, /* I - Current state */
2963 void *context
) /* I - User data (unused) */
2965 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2966 /* Enumeration data */
2971 DEBUG_printf(("cups_dnssd_client_cb(client=%p, state=%d, context=%p)", client
, state
, context
));
2974 * If the connection drops, quit.
2977 if (state
== AVAHI_CLIENT_FAILURE
)
2979 DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
2980 avahi_simple_poll_quit(data
->simple_poll
);
2983 # endif /* HAVE_DNSSD */
2987 * 'cups_dnssd_compare_device()' - Compare two devices.
2990 static int /* O - Result of comparison */
2991 cups_dnssd_compare_devices(
2992 _cups_dnssd_device_t
*a
, /* I - First device */
2993 _cups_dnssd_device_t
*b
) /* I - Second device */
2995 return (strcmp(a
->dest
.name
, b
->dest
.name
));
3000 * 'cups_dnssd_free_device()' - Free the memory used by a device.
3004 cups_dnssd_free_device(
3005 _cups_dnssd_device_t
*device
, /* I - Device */
3006 _cups_dnssd_data_t
*data
) /* I - Enumeration data */
3008 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", (void *)device
, device
->dest
.name
, (void *)data
));
3012 DNSServiceRefDeallocate(device
->ref
);
3013 # else /* HAVE_AVAHI */
3015 avahi_record_browser_free(device
->ref
);
3016 # endif /* HAVE_DNSSD */
3018 _cupsStrFree(device
->domain
);
3019 _cupsStrFree(device
->fullName
);
3020 _cupsStrFree(device
->regtype
);
3021 _cupsStrFree(device
->dest
.name
);
3023 cupsFreeOptions(device
->dest
.num_options
, device
->dest
.options
);
3030 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
3033 static _cups_dnssd_device_t
* /* O - Device */
3034 cups_dnssd_get_device(
3035 _cups_dnssd_data_t
*data
, /* I - Enumeration data */
3036 const char *serviceName
, /* I - Service name */
3037 const char *regtype
, /* I - Registration type */
3038 const char *replyDomain
) /* I - Domain name */
3040 _cups_dnssd_device_t key
, /* Search key */
3041 *device
; /* Device */
3042 char fullName
[kDNSServiceMaxDomainName
],
3043 /* Full name for query */
3044 name
[128]; /* Queue name */
3047 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", regtype=\"%s\", replyDomain=\"%s\")", (void *)data
, serviceName
, regtype
, replyDomain
));
3050 * See if this is an existing device...
3053 cups_dnssd_queue_name(name
, serviceName
, sizeof(name
));
3055 key
.dest
.name
= name
;
3057 if ((device
= cupsArrayFind(data
->devices
, &key
)) != NULL
)
3060 * Yes, see if we need to do anything with this...
3063 int update
= 0; /* Non-zero if we need to update */
3065 if (!_cups_strcasecmp(replyDomain
, "local.") &&
3066 _cups_strcasecmp(device
->domain
, replyDomain
))
3069 * Update the "global" listing to use the .local domain name instead.
3072 _cupsStrFree(device
->domain
);
3073 device
->domain
= _cupsStrAlloc(replyDomain
);
3075 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
3076 "domain.", device
->dest
.name
));
3081 if (!_cups_strcasecmp(regtype
, "_ipps._tcp") &&
3082 _cups_strcasecmp(device
->regtype
, regtype
))
3085 * Prefer IPPS over IPP.
3088 _cupsStrFree(device
->regtype
);
3089 device
->regtype
= _cupsStrAlloc(regtype
);
3091 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
3092 device
->dest
.name
));
3099 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
3100 device
->dest
.name
));
3107 * No, add the device...
3110 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
3111 "'%s'.", serviceName
,
3112 !strcmp(regtype
, "_ipps._tcp") ? "IPPS" : "IPP",
3115 device
= calloc(sizeof(_cups_dnssd_device_t
), 1);
3116 device
->dest
.name
= _cupsStrAlloc(name
);
3117 device
->domain
= _cupsStrAlloc(replyDomain
);
3118 device
->regtype
= _cupsStrAlloc(regtype
);
3120 device
->dest
.num_options
= cupsAddOption("printer-info", serviceName
, 0, &device
->dest
.options
);
3122 cupsArrayAdd(data
->devices
, device
);
3126 * Set the "full name" of this service, which is used for queries...
3130 DNSServiceConstructFullName(fullName
, serviceName
, regtype
, replyDomain
);
3131 # else /* HAVE_AVAHI */
3132 avahi_service_name_join(fullName
, kDNSServiceMaxDomainName
, serviceName
, regtype
, replyDomain
);
3133 # endif /* HAVE_DNSSD */
3135 _cupsStrFree(device
->fullName
);
3136 device
->fullName
= _cupsStrAlloc(fullName
);
3141 DNSServiceRefDeallocate(device
->ref
);
3142 # else /* HAVE_AVAHI */
3143 avahi_record_browser_free(device
->ref
);
3144 # endif /* HAVE_DNSSD */
3149 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
3151 DEBUG_printf(("6cups_dnssd_get_device: Remove callback for \"%s\".", device
->dest
.name
));
3153 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
3154 device
->state
= _CUPS_DNSSD_NEW
;
3163 * 'cups_dnssd_local_cb()' - Browse for local printers.
3167 cups_dnssd_local_cb(
3168 DNSServiceRef sdRef
, /* I - Service reference */
3169 DNSServiceFlags flags
, /* I - Option flags */
3170 uint32_t interfaceIndex
, /* I - Interface number */
3171 DNSServiceErrorType errorCode
, /* I - Error, if any */
3172 const char *serviceName
, /* I - Name of service/device */
3173 const char *regtype
, /* I - Type of service */
3174 const char *replyDomain
, /* I - Service domain */
3175 void *context
) /* I - Devices array */
3177 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
3178 /* Enumeration data */
3179 _cups_dnssd_device_t
*device
; /* Device */
3182 DEBUG_printf(("5cups_dnssd_local_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
));
3185 * Only process "add" data...
3188 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
3195 device
= cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
3198 * Hide locally-registered devices...
3201 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
3206 DNSServiceRefDeallocate(device
->ref
);
3210 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
3212 DEBUG_printf(("6cups_dnssd_local_cb: Remove callback for \"%s\".", device
->dest
.name
));
3213 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
3216 device
->state
= _CUPS_DNSSD_LOCAL
;
3218 # endif /* HAVE_DNSSD */
3223 * 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
3225 * Note: This function is needed because avahi_simple_poll_iterate is broken
3226 * and always uses a timeout of 0 (!) milliseconds.
3227 * (Avahi Ticket #364)
3230 static int /* O - Number of file descriptors matching */
3232 struct pollfd
*pollfds
, /* I - File descriptors */
3233 unsigned int num_pollfds
, /* I - Number of file descriptors */
3234 int timeout
, /* I - Timeout in milliseconds (unused) */
3235 void *context
) /* I - User data (unused) */
3237 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
3238 /* Enumeration data */
3239 int val
; /* Return value */
3242 DEBUG_printf(("cups_dnssd_poll_cb(pollfds=%p, num_pollfds=%d, timeout=%d, context=%p)", pollfds
, num_pollfds
, timeout
, context
));
3246 val
= poll(pollfds
, num_pollfds
, 500);
3248 DEBUG_printf(("cups_dnssd_poll_cb: poll() returned %d", val
));
3252 DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno
)));
3261 # endif /* HAVE_AVAHI */
3265 * 'cups_dnssd_query_cb()' - Process query data.
3270 cups_dnssd_query_cb(
3271 DNSServiceRef sdRef
, /* I - Service reference */
3272 DNSServiceFlags flags
, /* I - Data flags */
3273 uint32_t interfaceIndex
, /* I - Interface */
3274 DNSServiceErrorType errorCode
, /* I - Error, if any */
3275 const char *fullName
, /* I - Full service name */
3276 uint16_t rrtype
, /* I - Record type */
3277 uint16_t rrclass
, /* I - Record class */
3278 uint16_t rdlen
, /* I - Length of record data */
3279 const void *rdata
, /* I - Record data */
3280 uint32_t ttl
, /* I - Time-to-live */
3281 void *context
) /* I - Enumeration data */
3283 # else /* HAVE_AVAHI */
3285 cups_dnssd_query_cb(
3286 AvahiRecordBrowser
*browser
, /* I - Record browser */
3287 AvahiIfIndex interfaceIndex
,
3288 /* I - Interface index (unused) */
3289 AvahiProtocol protocol
, /* I - Network protocol (unused) */
3290 AvahiBrowserEvent event
, /* I - What happened? */
3291 const char *fullName
, /* I - Service name */
3292 uint16_t rrclass
, /* I - Record class */
3293 uint16_t rrtype
, /* I - Record type */
3294 const void *rdata
, /* I - TXT record */
3295 size_t rdlen
, /* I - Length of TXT record */
3296 AvahiLookupResultFlags flags
, /* I - Flags */
3297 void *context
) /* I - Enumeration data */
3300 AvahiClient
*client
= avahi_record_browser_get_client(browser
);
3301 /* Client information */
3303 # endif /* HAVE_DNSSD */
3304 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
3305 /* Enumeration data */
3306 char serviceName
[256],/* Service name */
3307 name
[128], /* Queue name */
3308 *ptr
; /* Pointer into string */
3309 _cups_dnssd_device_t dkey
, /* Search key */
3310 *device
; /* Device */
3314 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
));
3317 * Only process "add" data...
3320 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
3323 # else /* HAVE_AVAHI */
3324 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
));
3327 * Only process "add" data...
3330 if (event
!= AVAHI_BROWSER_NEW
)
3332 if (event
== AVAHI_BROWSER_FAILURE
)
3333 DEBUG_printf(("cups_dnssd_query_cb: %s", avahi_strerror(avahi_client_errno(client
))));
3337 # endif /* HAVE_DNSSD */
3340 * Lookup the service in the devices array.
3343 cups_dnssd_unquote(serviceName
, fullName
, sizeof(serviceName
));
3345 if ((ptr
= strstr(serviceName
, "._")) != NULL
)
3348 cups_dnssd_queue_name(name
, serviceName
, sizeof(name
));
3350 dkey
.dest
.name
= name
;
3352 if ((device
= cupsArrayFind(data
->devices
, &dkey
)) != NULL
&& device
->state
== _CUPS_DNSSD_NEW
)
3355 * Found it, pull out the make and model from the TXT record and save it...
3358 const uint8_t *txt
, /* Pointer into data */
3359 *txtnext
, /* Next key/value pair */
3360 *txtend
; /* End of entire TXT record */
3361 uint8_t txtlen
; /* Length of current key/value pair */
3362 char key
[256], /* Key string */
3363 value
[256], /* Value string */
3364 make_and_model
[512],
3365 /* Manufacturer and model */
3366 model
[256], /* Model */
3367 uriname
[1024], /* Name for URI */
3368 uri
[1024]; /* Printer URI */
3369 cups_ptype_t type
= CUPS_PRINTER_REMOTE
| CUPS_PRINTER_BW
;
3371 int saw_printer_type
= 0;
3372 /* Did we see a printer-type key? */
3374 device
->state
= _CUPS_DNSSD_PENDING
;
3375 make_and_model
[0] = '\0';
3377 strlcpy(model
, "Unknown", sizeof(model
));
3379 for (txt
= rdata
, txtend
= txt
+ rdlen
;
3384 * Read a key/value pair starting with an 8-bit length. Since the
3385 * length is 8 bits and the size of the key/value buffers is 256, we
3386 * don't need to check for overflow...
3391 if (!txtlen
|| (txt
+ txtlen
) > txtend
)
3394 txtnext
= txt
+ txtlen
;
3396 for (ptr
= key
; txt
< txtnext
&& *txt
!= '='; txt
++)
3397 *ptr
++ = (char)*txt
;
3400 if (txt
< txtnext
&& *txt
== '=')
3405 memcpy(value
, txt
, (size_t)(txtnext
- txt
));
3406 value
[txtnext
- txt
] = '\0';
3408 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key
, value
));
3412 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key
));
3416 if (!_cups_strcasecmp(key
, "usb_MFG") ||
3417 !_cups_strcasecmp(key
, "usb_MANU") ||
3418 !_cups_strcasecmp(key
, "usb_MANUFACTURER"))
3419 strlcpy(make_and_model
, value
, sizeof(make_and_model
));
3420 else if (!_cups_strcasecmp(key
, "usb_MDL") ||
3421 !_cups_strcasecmp(key
, "usb_MODEL"))
3422 strlcpy(model
, value
, sizeof(model
));
3423 else if (!_cups_strcasecmp(key
, "product") && !strstr(value
, "Ghostscript"))
3425 if (value
[0] == '(')
3428 * Strip parenthesis...
3431 if ((ptr
= value
+ strlen(value
) - 1) > value
&& *ptr
== ')')
3434 strlcpy(model
, value
+ 1, sizeof(model
));
3437 strlcpy(model
, value
, sizeof(model
));
3439 else if (!_cups_strcasecmp(key
, "ty"))
3441 strlcpy(model
, value
, sizeof(model
));
3443 if ((ptr
= strchr(model
, ',')) != NULL
)
3446 else if (!_cups_strcasecmp(key
, "note"))
3447 device
->dest
.num_options
= cupsAddOption("printer-location", value
,
3448 device
->dest
.num_options
,
3449 &device
->dest
.options
);
3450 else if (!_cups_strcasecmp(key
, "pdl"))
3453 * Look for PDF-capable printers; only PDF-capable printers are shown.
3456 const char *start
, *next
; /* Pointer into value */
3457 int have_pdf
= 0, /* Have PDF? */
3458 have_raster
= 0;/* Have raster format support? */
3460 for (start
= value
; start
&& *start
; start
= next
)
3462 if (!_cups_strncasecmp(start
, "application/pdf", 15) && (!start
[15] || start
[15] == ','))
3467 else if ((!_cups_strncasecmp(start
, "image/pwg-raster", 16) && (!start
[16] || start
[16] == ',')) ||
3468 (!_cups_strncasecmp(start
, "image/urf", 9) && (!start
[9] || start
[9] == ',')))
3474 if ((next
= strchr(start
, ',')) != NULL
)
3478 if (!have_pdf
&& !have_raster
)
3479 device
->state
= _CUPS_DNSSD_INCOMPATIBLE
;
3481 else if (!_cups_strcasecmp(key
, "printer-type"))
3484 * Value is either NNNN or 0xXXXX
3487 saw_printer_type
= 1;
3488 type
= (cups_ptype_t
)strtol(value
, NULL
, 0);
3490 else if (!saw_printer_type
)
3492 if (!_cups_strcasecmp(key
, "air") &&
3493 !_cups_strcasecmp(value
, "t"))
3494 type
|= CUPS_PRINTER_AUTHENTICATED
;
3495 else if (!_cups_strcasecmp(key
, "bind") &&
3496 !_cups_strcasecmp(value
, "t"))
3497 type
|= CUPS_PRINTER_BIND
;
3498 else if (!_cups_strcasecmp(key
, "collate") &&
3499 !_cups_strcasecmp(value
, "t"))
3500 type
|= CUPS_PRINTER_COLLATE
;
3501 else if (!_cups_strcasecmp(key
, "color") &&
3502 !_cups_strcasecmp(value
, "t"))
3503 type
|= CUPS_PRINTER_COLOR
;
3504 else if (!_cups_strcasecmp(key
, "copies") &&
3505 !_cups_strcasecmp(value
, "t"))
3506 type
|= CUPS_PRINTER_COPIES
;
3507 else if (!_cups_strcasecmp(key
, "duplex") &&
3508 !_cups_strcasecmp(value
, "t"))
3509 type
|= CUPS_PRINTER_DUPLEX
;
3510 else if (!_cups_strcasecmp(key
, "fax") &&
3511 !_cups_strcasecmp(value
, "t"))
3512 type
|= CUPS_PRINTER_MFP
;
3513 else if (!_cups_strcasecmp(key
, "papercustom") &&
3514 !_cups_strcasecmp(value
, "t"))
3515 type
|= CUPS_PRINTER_VARIABLE
;
3516 else if (!_cups_strcasecmp(key
, "papermax"))
3518 if (!_cups_strcasecmp(value
, "legal-a4"))
3519 type
|= CUPS_PRINTER_SMALL
;
3520 else if (!_cups_strcasecmp(value
, "isoc-a2"))
3521 type
|= CUPS_PRINTER_MEDIUM
;
3522 else if (!_cups_strcasecmp(value
, ">isoc-a2"))
3523 type
|= CUPS_PRINTER_LARGE
;
3525 else if (!_cups_strcasecmp(key
, "punch") &&
3526 !_cups_strcasecmp(value
, "t"))
3527 type
|= CUPS_PRINTER_PUNCH
;
3528 else if (!_cups_strcasecmp(key
, "scan") &&
3529 !_cups_strcasecmp(value
, "t"))
3530 type
|= CUPS_PRINTER_MFP
;
3531 else if (!_cups_strcasecmp(key
, "sort") &&
3532 !_cups_strcasecmp(value
, "t"))
3533 type
|= CUPS_PRINTER_SORT
;
3534 else if (!_cups_strcasecmp(key
, "staple") &&
3535 !_cups_strcasecmp(value
, "t"))
3536 type
|= CUPS_PRINTER_STAPLE
;
3541 * Save the printer-xxx values...
3544 device
->dest
.num_options
= cupsAddOption("printer-info", name
, device
->dest
.num_options
, &device
->dest
.options
);
3546 if (make_and_model
[0])
3548 strlcat(make_and_model
, " ", sizeof(make_and_model
));
3549 strlcat(make_and_model
, model
, sizeof(make_and_model
));
3551 device
->dest
.num_options
= cupsAddOption("printer-make-and-model", make_and_model
, device
->dest
.num_options
, &device
->dest
.options
);
3554 device
->dest
.num_options
= cupsAddOption("printer-make-and-model", model
, device
->dest
.num_options
, &device
->dest
.options
);
3556 device
->type
= type
;
3557 snprintf(value
, sizeof(value
), "%u", type
);
3558 device
->dest
.num_options
= cupsAddOption("printer-type", value
, device
->dest
.num_options
, &device
->dest
.options
);
3564 cups_dnssd_unquote(uriname
, device
->fullName
, sizeof(uriname
));
3565 httpAssembleURI(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
),
3566 !strcmp(device
->regtype
, "_ipps._tcp") ? "ipps" : "ipp",
3567 NULL
, uriname
, 0, saw_printer_type
? "/cups" : "/");
3569 DEBUG_printf(("6cups_dnssd_query: device-uri=\"%s\"", uri
));
3571 device
->dest
.num_options
= cupsAddOption("device-uri", uri
, device
->dest
.num_options
, &device
->dest
.options
);
3574 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
3580 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
3583 static const char * /* O - Resolved URI or NULL */
3585 cups_dest_t
*dest
, /* I - Destination */
3586 const char *uri
, /* I - Current printer URI */
3587 int msec
, /* I - Time in milliseconds */
3588 int *cancel
, /* I - Pointer to "cancel" variable */
3589 cups_dest_cb_t cb
, /* I - Callback */
3590 void *user_data
) /* I - User data for callback */
3592 char tempuri
[1024]; /* Temporary URI buffer */
3593 _cups_dnssd_resolve_t resolve
; /* Resolve data */
3597 * Resolve the URI...
3600 resolve
.cancel
= cancel
;
3601 gettimeofday(&resolve
.end_time
, NULL
);
3604 resolve
.end_time
.tv_sec
+= msec
/ 1000;
3605 resolve
.end_time
.tv_usec
+= (msec
% 1000) * 1000;
3607 while (resolve
.end_time
.tv_usec
>= 1000000)
3609 resolve
.end_time
.tv_sec
++;
3610 resolve
.end_time
.tv_usec
-= 1000000;
3614 resolve
.end_time
.tv_sec
+= 75;
3617 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
, dest
);
3619 if ((uri
= _httpResolveURI(uri
, tempuri
, sizeof(tempuri
), _HTTP_RESOLVE_DEFAULT
, cups_dnssd_resolve_cb
, &resolve
)) == NULL
)
3621 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to resolve printer-uri."), 1);
3624 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
, dest
);
3630 * Save the resolved URI...
3633 dest
->num_options
= cupsAddOption("resolved-device-uri", uri
, dest
->num_options
, &dest
->options
);
3635 return (cupsGetOption("resolved-device-uri", dest
->num_options
, dest
->options
));
3640 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
3643 static int /* O - 1 to continue, 0 to stop */
3644 cups_dnssd_resolve_cb(void *context
) /* I - Resolve data */
3646 _cups_dnssd_resolve_t
*resolve
= (_cups_dnssd_resolve_t
*)context
;
3648 struct timeval curtime
; /* Current time */
3652 * If the cancel variable is set, return immediately.
3655 if (resolve
->cancel
&& *(resolve
->cancel
))
3657 DEBUG_puts("4cups_dnssd_resolve_cb: Canceled.");
3662 * Otherwise check the end time...
3665 gettimeofday(&curtime
, NULL
);
3667 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
));
3669 return (curtime
.tv_sec
< resolve
->end_time
.tv_sec
||
3670 (curtime
.tv_sec
== resolve
->end_time
.tv_sec
&&
3671 curtime
.tv_usec
< resolve
->end_time
.tv_usec
));
3676 * 'cups_dnssd_unquote()' - Unquote a name string.
3680 cups_dnssd_unquote(char *dst
, /* I - Destination buffer */
3681 const char *src
, /* I - Source string */
3682 size_t dstsize
) /* I - Size of destination buffer */
3684 char *dstend
= dst
+ dstsize
- 1; /* End of destination buffer */
3687 while (*src
&& dst
< dstend
)
3692 if (isdigit(src
[0] & 255) && isdigit(src
[1] & 255) &&
3693 isdigit(src
[2] & 255))
3695 *dst
++ = ((((src
[0] - '0') * 10) + src
[1] - '0') * 10) + src
[2] - '0';
3707 #endif /* HAVE_DNSSD */
3710 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3712 * 'cups_dnssd_queue_name()' - Create a local queue name based on the service name.
3716 cups_dnssd_queue_name(
3717 char *name
, /* I - Name buffer */
3718 const char *serviceName
, /* I - Service name */
3719 size_t namesize
) /* I - Size of name buffer */
3721 const char *ptr
; /* Pointer into serviceName */
3722 char *nameptr
; /* Pointer into name */
3725 for (nameptr
= name
, ptr
= serviceName
; *ptr
&& nameptr
< (name
+ namesize
- 1); ptr
++)
3728 * Sanitize the printer name...
3731 if (_cups_isalnum(*ptr
))
3733 else if (nameptr
== name
|| nameptr
[-1] != '_')
3739 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3743 * 'cups_find_dest()' - Find a destination using a binary search.
3746 static int /* O - Index of match */
3747 cups_find_dest(const char *name
, /* I - Destination name */
3748 const char *instance
, /* I - Instance or NULL */
3749 int num_dests
, /* I - Number of destinations */
3750 cups_dest_t
*dests
, /* I - Destinations */
3751 int prev
, /* I - Previous index */
3752 int *rdiff
) /* O - Difference of match */
3754 int left
, /* Low mark for binary search */
3755 right
, /* High mark for binary search */
3756 current
, /* Current index */
3757 diff
; /* Result of comparison */
3758 cups_dest_t key
; /* Search key */
3761 key
.name
= (char *)name
;
3762 key
.instance
= (char *)instance
;
3767 * Start search on either side of previous...
3770 if ((diff
= cups_compare_dests(&key
, dests
+ prev
)) == 0 ||
3771 (diff
< 0 && prev
== 0) ||
3772 (diff
> 0 && prev
== (num_dests
- 1)))
3780 * Start with previous on right side...
3789 * Start wih previous on left side...
3793 right
= num_dests
- 1;
3799 * Start search in the middle...
3803 right
= num_dests
- 1;
3808 current
= (left
+ right
) / 2;
3809 diff
= cups_compare_dests(&key
, dests
+ current
);
3818 while ((right
- left
) > 1);
3823 * Check the last 1 or 2 elements...
3826 if ((diff
= cups_compare_dests(&key
, dests
+ left
)) <= 0)
3830 diff
= cups_compare_dests(&key
, dests
+ right
);
3836 * Return the closest destination and the difference...
3846 * 'cups_get_default()' - Get the default destination from an lpoptions file.
3849 static char * /* O - Default destination or NULL */
3850 cups_get_default(const char *filename
, /* I - File to read */
3851 char *namebuf
, /* I - Name buffer */
3852 size_t namesize
, /* I - Size of name buffer */
3853 const char **instance
) /* I - Instance */
3855 cups_file_t
*fp
; /* lpoptions file */
3856 char line
[8192], /* Line from file */
3857 *value
, /* Value for line */
3858 *nameptr
; /* Pointer into name */
3859 int linenum
; /* Current line */
3864 if ((fp
= cupsFileOpen(filename
, "r")) != NULL
)
3868 while (cupsFileGetConf(fp
, line
, sizeof(line
), &value
, &linenum
))
3870 if (!_cups_strcasecmp(line
, "default") && value
)
3872 strlcpy(namebuf
, value
, namesize
);
3874 if ((nameptr
= strchr(namebuf
, ' ')) != NULL
)
3876 if ((nameptr
= strchr(namebuf
, '\t')) != NULL
)
3879 if ((nameptr
= strchr(namebuf
, '/')) != NULL
)
3882 *instance
= nameptr
;
3890 return (*namebuf
? namebuf
: NULL
);
3895 * 'cups_get_dests()' - Get destinations from a file.
3898 static int /* O - Number of destinations */
3900 const char *filename
, /* I - File to read from */
3901 const char *match_name
, /* I - Destination name we want */
3902 const char *match_inst
, /* I - Instance name we want */
3903 int user_default_set
, /* I - User default printer set? */
3904 int num_dests
, /* I - Number of destinations */
3905 cups_dest_t
**dests
) /* IO - Destinations */
3907 int i
; /* Looping var */
3908 cups_dest_t
*dest
; /* Current destination */
3909 cups_file_t
*fp
; /* File pointer */
3910 char line
[8192], /* Line from file */
3911 *lineptr
, /* Pointer into line */
3912 *name
, /* Name of destination/option */
3913 *instance
; /* Instance of destination */
3914 int linenum
; /* Current line number */
3917 DEBUG_printf(("7cups_get_dests(filename=\"%s\", match_name=\"%s\", match_inst=\"%s\", user_default_set=%d, num_dests=%d, dests=%p)", filename
, match_name
, match_inst
, user_default_set
, num_dests
, (void *)dests
));
3920 * Try to open the file...
3923 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
3927 * Read each printer; each line looks like:
3929 * Dest name[/instance] options
3930 * Default name[/instance] options
3935 while (cupsFileGetConf(fp
, line
, sizeof(line
), &lineptr
, &linenum
))
3938 * See what type of line it is...
3941 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
3942 linenum
, line
, lineptr
));
3944 if ((_cups_strcasecmp(line
, "dest") && _cups_strcasecmp(line
, "default")) || !lineptr
)
3946 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
3953 * Search for an instance...
3956 while (!isspace(*lineptr
& 255) && *lineptr
&& *lineptr
!= '/')
3959 if (*lineptr
== '/')
3962 * Found an instance...
3969 * Search for an instance...
3972 while (!isspace(*lineptr
& 255) && *lineptr
)
3981 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name
,
3985 * See if the primary instance of the destination exists; if not,
3986 * ignore this entry and move on...
3991 if (_cups_strcasecmp(name
, match_name
) ||
3992 (!instance
&& match_inst
) ||
3993 (instance
&& !match_inst
) ||
3994 (instance
&& _cups_strcasecmp(instance
, match_inst
)))
3999 else if (cupsGetDest(name
, NULL
, num_dests
, *dests
) == NULL
)
4001 DEBUG_puts("9cups_get_dests: Not found!");
4007 * Add the destination...
4010 num_dests
= cupsAddDest(name
, instance
, num_dests
, dests
);
4012 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
4018 DEBUG_puts("9cups_get_dests: Out of memory!");
4024 * Add options until we hit the end of the line...
4027 dest
->num_options
= cupsParseOptions(lineptr
, dest
->num_options
,
4031 * If we found what we were looking for, stop now...
4038 * Set this as default if needed...
4041 if (!user_default_set
&& !_cups_strcasecmp(line
, "default"))
4043 DEBUG_puts("9cups_get_dests: Setting as default...");
4045 for (i
= 0; i
< num_dests
; i
++)
4046 (*dests
)[i
].is_default
= 0;
4048 dest
->is_default
= 1;
4053 * Close the file and return...
4063 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
4067 static char * /* O - New string */
4069 ipp_attribute_t
*attr
, /* I - Attribute to convert */
4070 char *buffer
, /* I - Buffer */
4071 size_t bufsize
) /* I - Size of buffer */
4073 int i
; /* Looping var */
4074 char *ptr
, /* Pointer into buffer */
4075 *end
, /* Pointer to end of buffer */
4076 *valptr
; /* Pointer into string attribute */
4080 * Return quickly if we have a single string value...
4083 if (attr
->num_values
== 1 &&
4084 attr
->value_tag
!= IPP_TAG_INTEGER
&&
4085 attr
->value_tag
!= IPP_TAG_ENUM
&&
4086 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
4087 attr
->value_tag
!= IPP_TAG_RANGE
)
4088 return (attr
->values
[0].string
.text
);
4091 * Copy the values to the string, separating with commas and escaping strings
4095 end
= buffer
+ bufsize
- 1;
4097 for (i
= 0, ptr
= buffer
; i
< attr
->num_values
&& ptr
< end
; i
++)
4102 switch (attr
->value_tag
)
4104 case IPP_TAG_INTEGER
:
4106 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d", attr
->values
[i
].integer
);
4109 case IPP_TAG_BOOLEAN
:
4110 if (attr
->values
[i
].boolean
)
4111 strlcpy(ptr
, "true", (size_t)(end
- ptr
+ 1));
4113 strlcpy(ptr
, "false", (size_t)(end
- ptr
+ 1));
4116 case IPP_TAG_RANGE
:
4117 if (attr
->values
[i
].range
.lower
== attr
->values
[i
].range
.upper
)
4118 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d", attr
->values
[i
].range
.lower
);
4120 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d-%d", attr
->values
[i
].range
.lower
, attr
->values
[i
].range
.upper
);
4124 for (valptr
= attr
->values
[i
].string
.text
;
4125 *valptr
&& ptr
< end
;)
4127 if (strchr(" \t\n\\\'\"", *valptr
))
4129 if (ptr
>= (end
- 1))