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 # endif /* HAVE_DNSSD */
89 cups_dest_cb_t cb
; /* Callback */
90 void *user_data
; /* User data pointer */
91 cups_ptype_t type
, /* Printer type filter */
92 mask
; /* Printer type mask */
93 cups_array_t
*devices
; /* Devices found so far */
96 typedef struct _cups_dnssd_device_s
/* Enumerated device */
98 _cups_dnssd_state_t state
; /* State of device listing */
100 DNSServiceRef ref
; /* Service reference for query */
101 # else /* HAVE_AVAHI */
102 AvahiRecordBrowser
*ref
; /* Browser for query */
103 # endif /* HAVE_DNSSD */
104 char *fullName
, /* Full name */
105 // *serviceName, /* Service 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 const char *device_uri
; /* Device URI */
1026 if (!(*cb
)(user_data
, i
> 1 ? CUPS_DEST_FLAGS_MORE
: CUPS_DEST_FLAGS_NONE
,
1030 if (!dest
->instance
&& (device_uri
= cupsGetOption("device-uri", dest
->num_options
, dest
->options
)) != NULL
&& !strncmp(device_uri
, "dnssd://", 8))
1033 * Add existing queue using service name, etc. so we don't list it again...
1036 char scheme
[32], /* URI scheme */
1037 userpass
[32], /* Username:password */
1038 serviceName
[256], /* Service name (host field) */
1039 resource
[256], /* Resource (options) */
1040 *regtype
, /* Registration type */
1041 *replyDomain
; /* Registration domain */
1042 int port
; /* Port number (not used) */
1044 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
)
1046 if ((regtype
= strstr(serviceName
, "._ipp")) != NULL
)
1050 if ((replyDomain
= strstr(regtype
, "._tcp.")) != NULL
)
1052 replyDomain
[5] = '\0';
1055 if ((device
= cups_dnssd_get_device(&data
, serviceName
, regtype
, replyDomain
)) != NULL
)
1056 device
->state
= _CUPS_DNSSD_ACTIVE
;
1063 cupsFreeDests(num_dests
, dests
);
1065 if (i
> 0 || msec
== 0)
1067 cupsArrayDelete(data
.devices
);
1071 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1073 * Get Bonjour-shared printers...
1077 if (DNSServiceCreateConnection(&data
.main_ref
) != kDNSServiceErr_NoError
)
1080 main_fd
= DNSServiceRefSockFD(data
.main_ref
);
1082 ipp_ref
= data
.main_ref
;
1083 DNSServiceBrowse(&ipp_ref
, kDNSServiceFlagsShareConnection
, 0,
1085 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
1087 local_ipp_ref
= data
.main_ref
;
1088 DNSServiceBrowse(&local_ipp_ref
, kDNSServiceFlagsShareConnection
,
1089 kDNSServiceInterfaceIndexLocalOnly
,
1091 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
1094 ipps_ref
= data
.main_ref
;
1095 DNSServiceBrowse(&ipps_ref
, kDNSServiceFlagsShareConnection
, 0,
1097 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
1099 local_ipps_ref
= data
.main_ref
;
1100 DNSServiceBrowse(&local_ipps_ref
, kDNSServiceFlagsShareConnection
,
1101 kDNSServiceInterfaceIndexLocalOnly
,
1103 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
1104 # endif /* HAVE_SSL */
1106 # else /* HAVE_AVAHI */
1107 if ((data
.simple_poll
= avahi_simple_poll_new()) == NULL
)
1109 DEBUG_puts("cupsEnumDests: Unable to create Avahi simple poll object.");
1113 avahi_simple_poll_set_func(data
.simple_poll
, cups_dnssd_poll_cb
, &data
);
1115 data
.client
= avahi_client_new(avahi_simple_poll_get(data
.simple_poll
),
1116 0, cups_dnssd_client_cb
, &data
,
1120 DEBUG_puts("cupsEnumDests: Unable to create Avahi client.");
1121 avahi_simple_poll_free(data
.simple_poll
);
1125 ipp_ref
= avahi_service_browser_new(data
.client
, AVAHI_IF_UNSPEC
,
1126 AVAHI_PROTO_UNSPEC
, "_ipp._tcp", NULL
,
1127 0, cups_dnssd_browse_cb
, &data
);
1129 ipps_ref
= avahi_service_browser_new(data
.client
, AVAHI_IF_UNSPEC
,
1130 AVAHI_PROTO_UNSPEC
, "_ipps._tcp", NULL
,
1131 0, cups_dnssd_browse_cb
, &data
);
1132 # endif /* HAVE_SSL */
1133 # endif /* HAVE_DNSSD */
1136 remaining
= INT_MAX
;
1140 while (remaining
> 0 && (!cancel
|| !*cancel
))
1143 * Check for input...
1149 pfd
.events
= POLLIN
;
1151 nfds
= poll(&pfd
, 1, remaining
> 500 ? 500 : remaining
);
1155 FD_SET(main_fd
, &input
);
1158 timeout
.tv_usec
= remaining
> 500 ? 500000 : remaining
* 1000;
1160 nfds
= select(main_fd
+ 1, &input
, NULL
, NULL
, &timeout
);
1161 # endif /* HAVE_POLL */
1164 DNSServiceProcessResult(data
.main_ref
);
1166 # else /* HAVE_AVAHI */
1169 if ((error
= avahi_simple_poll_iterate(data
.simple_poll
, 500)) > 0)
1172 * We've been told to exit the loop. Perhaps the connection to
1179 # endif /* HAVE_DNSSD */
1183 for (device
= (_cups_dnssd_device_t
*)cupsArrayFirst(data
.devices
),
1184 count
= 0, completed
= 0;
1186 device
= (_cups_dnssd_device_t
*)cupsArrayNext(data
.devices
))
1191 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
1194 if (!device
->ref
&& device
->state
== _CUPS_DNSSD_NEW
)
1196 DEBUG_printf(("1cupsEnumDests: Querying '%s'.", device
->fullName
));
1199 device
->ref
= data
.main_ref
;
1201 if (DNSServiceQueryRecord(&(device
->ref
),
1202 kDNSServiceFlagsShareConnection
,
1203 0, device
->fullName
,
1204 kDNSServiceType_TXT
,
1205 kDNSServiceClass_IN
,
1206 (DNSServiceQueryRecordReply
)cups_dnssd_query_cb
,
1207 &data
) == kDNSServiceErr_NoError
)
1214 device
->state
= _CUPS_DNSSD_ERROR
;
1216 DEBUG_puts("1cupsEnumDests: Query failed.");
1219 # else /* HAVE_AVAHI */
1220 if ((device
->ref
= avahi_record_browser_new(data
.client
,
1227 cups_dnssd_query_cb
,
1234 device
->state
= _CUPS_DNSSD_ERROR
;
1236 DEBUG_printf(("1cupsEnumDests: Query failed: %s",
1237 avahi_strerror(avahi_client_errno(data
.client
))));
1239 # endif /* HAVE_DNSSD */
1241 else if (device
->ref
&& device
->state
== _CUPS_DNSSD_PENDING
)
1245 if ((device
->type
& mask
) == type
)
1247 DEBUG_printf(("1cupsEnumDests: Add callback for \"%s\".", device
->dest
.name
));
1248 if (!(*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, &device
->dest
))
1255 device
->state
= _CUPS_DNSSD_ACTIVE
;
1259 if (completed
== cupsArrayCount(data
.devices
))
1263 cupsArrayDelete(data
.devices
);
1266 DNSServiceRefDeallocate(ipp_ref
);
1267 DNSServiceRefDeallocate(local_ipp_ref
);
1270 DNSServiceRefDeallocate(ipp_ref
);
1271 DNSServiceRefDeallocate(local_ipp_ref
);
1272 # endif /* HAVE_SSL */
1274 DNSServiceRefDeallocate(data
.main_ref
);
1276 # else /* HAVE_AVAHI */
1277 avahi_service_browser_free(ipp_ref
);
1279 avahi_service_browser_free(ipps_ref
);
1280 # endif /* HAVE_SSL */
1282 avahi_client_free(data
.client
);
1283 avahi_simple_poll_free(data
.simple_poll
);
1284 # endif /* HAVE_DNSSD */
1285 #endif /* HAVE_DNSSD || HAVE_DNSSD */
1293 * 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
1295 * Destinations are enumerated from one or more sources. The block receives the
1296 * destination name, instance, number of options, and options which can be used
1297 * as input to the @link cupsAddDest@ function. The block must return 1 to
1298 * continue enumeration or 0 to stop.
1300 * Enumeration happens on the current thread and does not return until all
1301 * destinations have been enumerated or the block returns 0.
1303 * @since CUPS 1.6/macOS 10.8@
1306 int /* O - 1 on success, 0 on failure */
1308 unsigned flags
, /* I - Enumeration flags */
1309 int timeout
, /* I - Timeout in milliseconds, 0 for indefinite */
1310 int *cancel
, /* I - Pointer to "cancel" variable */
1311 cups_ptype_t type
, /* I - Printer type bits */
1312 cups_ptype_t mask
, /* I - Mask for printer type bits */
1313 cups_dest_block_t block
) /* I - Block */
1315 return (cupsEnumDests(flags
, timeout
, cancel
, type
, mask
,
1316 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
1318 # endif /* __BLOCKS__ */
1322 * 'cupsFreeDests()' - Free the memory used by the list of destinations.
1326 cupsFreeDests(int num_dests
, /* I - Number of destinations */
1327 cups_dest_t
*dests
) /* I - Destinations */
1329 int i
; /* Looping var */
1330 cups_dest_t
*dest
; /* Current destination */
1333 if (num_dests
== 0 || dests
== NULL
)
1336 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1338 _cupsStrFree(dest
->name
);
1339 _cupsStrFree(dest
->instance
);
1341 cupsFreeOptions(dest
->num_options
, dest
->options
);
1349 * 'cupsGetDest()' - Get the named destination from the list.
1351 * Use the @link cupsGetDests@ or @link cupsGetDests2@ functions to get a
1352 * list of supported destinations for the current user.
1355 cups_dest_t
* /* O - Destination pointer or @code NULL@ */
1356 cupsGetDest(const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1357 const char *instance
, /* I - Instance name or @code NULL@ */
1358 int num_dests
, /* I - Number of destinations */
1359 cups_dest_t
*dests
) /* I - Destinations */
1361 int diff
, /* Result of comparison */
1362 match
; /* Matching index */
1365 if (num_dests
<= 0 || !dests
)
1371 * NULL name for default printer.
1374 while (num_dests
> 0)
1376 if (dests
->is_default
)
1386 * Lookup name and optionally the instance...
1389 match
= cups_find_dest(name
, instance
, num_dests
, dests
, -1, &diff
);
1392 return (dests
+ match
);
1400 * '_cupsGetDestResource()' - Get the resource path and URI for a destination.
1403 const char * /* O - Printer URI */
1404 _cupsGetDestResource(
1405 cups_dest_t
*dest
, /* I - Destination */
1406 char *resource
, /* I - Resource buffer */
1407 size_t resourcesize
) /* I - Size of resource buffer */
1409 const char *uri
; /* Printer URI */
1410 char scheme
[32], /* URI scheme */
1411 userpass
[256], /* Username and password (unused) */
1412 hostname
[256]; /* Hostname */
1413 int port
; /* Port number */
1417 * Range check input...
1420 if (!dest
|| !resource
|| resourcesize
< 1)
1425 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
1430 * Grab the printer URI...
1433 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
,
1434 dest
->options
)) == NULL
)
1439 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(ENOENT
), 0);
1445 if (strstr(uri
, "._tcp"))
1447 if ((uri
= cups_dnssd_resolve(dest
, uri
, 5000, NULL
, NULL
, NULL
)) == NULL
)
1450 #endif /* HAVE_DNSSD */
1452 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
1453 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
1454 &port
, resource
, (int)resourcesize
) < HTTP_URI_STATUS_OK
)
1456 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer-uri."), 1);
1466 * 'cupsGetDestWithURI()' - Get a destination associated with a URI.
1468 * "name" is the desired name for the printer. If @code NULL@, a name will be
1469 * created using the URI.
1471 * "uri" is the "ipp" or "ipps" URI for the printer.
1473 * @since CUPS 2.0/macOS 10.10@
1476 cups_dest_t
* /* O - Destination or @code NULL@ */
1477 cupsGetDestWithURI(const char *name
, /* I - Desired printer name or @code NULL@ */
1478 const char *uri
) /* I - URI for the printer */
1480 cups_dest_t
*dest
; /* New destination */
1481 char temp
[1024], /* Temporary string */
1482 scheme
[256], /* Scheme from URI */
1483 userpass
[256], /* Username:password from URI */
1484 hostname
[256], /* Hostname from URI */
1485 resource
[1024], /* Resource path from URI */
1486 *ptr
; /* Pointer into string */
1487 int port
; /* Port number from URI */
1491 * Range check input...
1496 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
1500 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
), userpass
, sizeof(userpass
), hostname
, sizeof(hostname
), &port
, resource
, sizeof(resource
)) < HTTP_URI_STATUS_OK
||
1501 (strncmp(uri
, "ipp://", 6) && strncmp(uri
, "ipps://", 7)))
1503 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad printer-uri."), 1);
1511 * Create the name from the URI...
1514 if (strstr(hostname
, "._tcp"))
1517 * Use the service instance name...
1520 if ((ptr
= strchr(hostname
, '.')) != NULL
)
1525 else if (!strncmp(resource
, "/classes/", 9))
1527 snprintf(temp
, sizeof(temp
), "%s @ %s", resource
+ 9, hostname
);
1530 else if (!strncmp(resource
, "/printers/", 10))
1532 snprintf(temp
, sizeof(temp
), "%s @ %s", resource
+ 10, hostname
);
1542 * Create the destination...
1545 if ((dest
= calloc(1, sizeof(cups_dest_t
))) == NULL
)
1547 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
1551 dest
->name
= _cupsStrAlloc(name
);
1552 dest
->num_options
= cupsAddOption("device-uri", uri
, dest
->num_options
, &(dest
->options
));
1553 dest
->num_options
= cupsAddOption("printer-info", name
, dest
->num_options
, &(dest
->options
));
1560 * '_cupsGetDests()' - Get destinations from a server.
1562 * "op" is IPP_OP_CUPS_GET_PRINTERS to get a full list, IPP_OP_CUPS_GET_DEFAULT
1563 * to get the system-wide default printer, or IPP_OP_GET_PRINTER_ATTRIBUTES for
1566 * "name" is the name of an existing printer and is only used when "op" is
1567 * IPP_OP_GET_PRINTER_ATTRIBUTES.
1569 * "dest" is initialized to point to the array of destinations.
1571 * 0 is returned if there are no printers, no default printer, or the named
1572 * printer does not exist, respectively.
1574 * Free the memory used by the destination array using the @link cupsFreeDests@
1577 * Note: On macOS this function also gets the default paper from the system
1578 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1579 * options array for each destination that supports it.
1582 int /* O - Number of destinations */
1583 _cupsGetDests(http_t
*http
, /* I - Connection to server or
1584 * @code CUPS_HTTP_DEFAULT@ */
1585 ipp_op_t op
, /* I - IPP operation */
1586 const char *name
, /* I - Name of destination */
1587 cups_dest_t
**dests
, /* IO - Destinations */
1588 cups_ptype_t type
, /* I - Printer type bits */
1589 cups_ptype_t mask
) /* I - Printer type mask */
1591 int num_dests
= 0; /* Number of destinations */
1592 cups_dest_t
*dest
; /* Current destination */
1593 ipp_t
*request
, /* IPP Request */
1594 *response
; /* IPP Response */
1595 ipp_attribute_t
*attr
; /* Current attribute */
1596 const char *printer_name
; /* printer-name attribute */
1597 char uri
[1024]; /* printer-uri value */
1598 int num_options
; /* Number of options */
1599 cups_option_t
*options
; /* Options */
1601 char media_default
[41]; /* Default paper size */
1602 #endif /* __APPLE__ */
1603 char optname
[1024], /* Option name */
1604 value
[2048], /* Option value */
1605 *ptr
; /* Pointer into name/value */
1606 static const char * const pattrs
[] = /* Attributes we're interested in */
1608 "auth-info-required",
1610 "job-sheets-default",
1611 "marker-change-time",
1613 "marker-high-levels",
1615 "marker-low-levels",
1621 #endif /* __APPLE__ */
1625 "printer-is-accepting-jobs",
1626 "printer-is-shared",
1628 "printer-make-and-model",
1629 "printer-mandatory-job-attributes",
1632 "printer-state-change-time",
1633 "printer-state-reasons",
1635 "printer-uri-supported"
1641 * Get the default paper size...
1644 appleGetPaperSize(media_default
, sizeof(media_default
));
1645 #endif /* __APPLE__ */
1648 * Build a IPP_OP_CUPS_GET_PRINTERS or IPP_OP_GET_PRINTER_ATTRIBUTES request, which
1649 * require the following attributes:
1651 * attributes-charset
1652 * attributes-natural-language
1653 * requesting-user-name
1654 * printer-uri [for IPP_OP_GET_PRINTER_ATTRIBUTES]
1657 request
= ippNewRequest(op
);
1659 ippAddStrings(request
, IPP_TAG_OPERATION
, IPP_TAG_KEYWORD
,
1660 "requested-attributes", sizeof(pattrs
) / sizeof(pattrs
[0]),
1663 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
,
1664 "requesting-user-name", NULL
, cupsUser());
1666 if (name
&& op
!= IPP_OP_CUPS_GET_DEFAULT
)
1668 httpAssembleURIf(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
), "ipp", NULL
,
1669 "localhost", ippPort(), "/printers/%s", name
);
1670 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
,
1675 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type", (int)type
);
1676 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type-mask", (int)mask
);
1680 * Do the request and get back a response...
1683 if ((response
= cupsDoRequest(http
, request
, "/")) != NULL
)
1685 for (attr
= response
->attrs
; attr
!= NULL
; attr
= attr
->next
)
1688 * Skip leading attributes until we hit a printer...
1691 while (attr
!= NULL
&& attr
->group_tag
!= IPP_TAG_PRINTER
)
1698 * Pull the needed attributes from this printer...
1701 printer_name
= NULL
;
1705 for (; attr
&& attr
->group_tag
== IPP_TAG_PRINTER
; attr
= attr
->next
)
1707 if (attr
->value_tag
!= IPP_TAG_INTEGER
&&
1708 attr
->value_tag
!= IPP_TAG_ENUM
&&
1709 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
1710 attr
->value_tag
!= IPP_TAG_TEXT
&&
1711 attr
->value_tag
!= IPP_TAG_TEXTLANG
&&
1712 attr
->value_tag
!= IPP_TAG_NAME
&&
1713 attr
->value_tag
!= IPP_TAG_NAMELANG
&&
1714 attr
->value_tag
!= IPP_TAG_KEYWORD
&&
1715 attr
->value_tag
!= IPP_TAG_RANGE
&&
1716 attr
->value_tag
!= IPP_TAG_URI
)
1719 if (!strcmp(attr
->name
, "auth-info-required") ||
1720 !strcmp(attr
->name
, "device-uri") ||
1721 !strcmp(attr
->name
, "marker-change-time") ||
1722 !strcmp(attr
->name
, "marker-colors") ||
1723 !strcmp(attr
->name
, "marker-high-levels") ||
1724 !strcmp(attr
->name
, "marker-levels") ||
1725 !strcmp(attr
->name
, "marker-low-levels") ||
1726 !strcmp(attr
->name
, "marker-message") ||
1727 !strcmp(attr
->name
, "marker-names") ||
1728 !strcmp(attr
->name
, "marker-types") ||
1729 !strcmp(attr
->name
, "printer-commands") ||
1730 !strcmp(attr
->name
, "printer-info") ||
1731 !strcmp(attr
->name
, "printer-is-shared") ||
1732 !strcmp(attr
->name
, "printer-make-and-model") ||
1733 !strcmp(attr
->name
, "printer-mandatory-job-attributes") ||
1734 !strcmp(attr
->name
, "printer-state") ||
1735 !strcmp(attr
->name
, "printer-state-change-time") ||
1736 !strcmp(attr
->name
, "printer-type") ||
1737 !strcmp(attr
->name
, "printer-is-accepting-jobs") ||
1738 !strcmp(attr
->name
, "printer-location") ||
1739 !strcmp(attr
->name
, "printer-state-reasons") ||
1740 !strcmp(attr
->name
, "printer-uri-supported"))
1743 * Add a printer description attribute...
1746 num_options
= cupsAddOption(attr
->name
,
1747 cups_make_string(attr
, value
,
1749 num_options
, &options
);
1752 else if (!strcmp(attr
->name
, "media-supported"))
1755 * See if we can set a default media size...
1758 int i
; /* Looping var */
1760 for (i
= 0; i
< attr
->num_values
; i
++)
1761 if (!_cups_strcasecmp(media_default
, attr
->values
[i
].string
.text
))
1763 num_options
= cupsAddOption("media", media_default
, num_options
,
1768 #endif /* __APPLE__ */
1769 else if (!strcmp(attr
->name
, "printer-name") &&
1770 attr
->value_tag
== IPP_TAG_NAME
)
1771 printer_name
= attr
->values
[0].string
.text
;
1772 else if (strncmp(attr
->name
, "notify-", 7) &&
1773 (attr
->value_tag
== IPP_TAG_BOOLEAN
||
1774 attr
->value_tag
== IPP_TAG_ENUM
||
1775 attr
->value_tag
== IPP_TAG_INTEGER
||
1776 attr
->value_tag
== IPP_TAG_KEYWORD
||
1777 attr
->value_tag
== IPP_TAG_NAME
||
1778 attr
->value_tag
== IPP_TAG_RANGE
) &&
1779 (ptr
= strstr(attr
->name
, "-default")) != NULL
)
1782 * Add a default option...
1785 strlcpy(optname
, attr
->name
, sizeof(optname
));
1786 optname
[ptr
- attr
->name
] = '\0';
1788 if (_cups_strcasecmp(optname
, "media") ||
1789 !cupsGetOption("media", num_options
, options
))
1790 num_options
= cupsAddOption(optname
,
1791 cups_make_string(attr
, value
,
1793 num_options
, &options
);
1798 * See if we have everything needed...
1803 cupsFreeOptions(num_options
, options
);
1811 if ((dest
= cups_add_dest(printer_name
, NULL
, &num_dests
, dests
)) != NULL
)
1813 dest
->num_options
= num_options
;
1814 dest
->options
= options
;
1817 cupsFreeOptions(num_options
, options
);
1823 ippDelete(response
);
1827 * Return the count...
1835 * 'cupsGetDests()' - Get the list of destinations from the default server.
1837 * Starting with CUPS 1.2, the returned list of destinations include the
1838 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1839 * printer-make-and-model, printer-state, printer-state-change-time,
1840 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1841 * adds the marker-change-time, marker-colors, marker-high-levels,
1842 * marker-levels, marker-low-levels, marker-message, marker-names,
1843 * marker-types, and printer-commands attributes as well.
1845 * Use the @link cupsFreeDests@ function to free the destination list and
1846 * the @link cupsGetDest@ function to find a particular destination.
1849 int /* O - Number of destinations */
1850 cupsGetDests(cups_dest_t
**dests
) /* O - Destinations */
1852 return (cupsGetDests2(CUPS_HTTP_DEFAULT
, dests
));
1857 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1859 * Starting with CUPS 1.2, the returned list of destinations include the
1860 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1861 * printer-make-and-model, printer-state, printer-state-change-time,
1862 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1863 * adds the marker-change-time, marker-colors, marker-high-levels,
1864 * marker-levels, marker-low-levels, marker-message, marker-names,
1865 * marker-types, and printer-commands attributes as well.
1867 * Use the @link cupsFreeDests@ function to free the destination list and
1868 * the @link cupsGetDest@ function to find a particular destination.
1870 * @since CUPS 1.1.21/macOS 10.4@
1873 int /* O - Number of destinations */
1874 cupsGetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1875 cups_dest_t
**dests
) /* O - Destinations */
1877 int num_dests
; /* Number of destinations */
1878 cups_dest_t
*dest
; /* Destination pointer */
1879 const char *home
; /* HOME environment variable */
1880 char filename
[1024]; /* Local ~/.cups/lpoptions file */
1881 const char *defprinter
; /* Default printer */
1882 char name
[1024], /* Copy of printer name */
1883 *instance
, /* Pointer to instance name */
1884 *user_default
; /* User default printer */
1885 int num_reals
; /* Number of real queues */
1886 cups_dest_t
*reals
; /* Real queues */
1887 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1891 * Range check the input...
1896 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Bad NULL dests pointer"), 1);
1901 * Grab the printers and classes...
1904 *dests
= (cups_dest_t
*)0;
1905 num_dests
= _cupsGetDests(http
, IPP_OP_CUPS_GET_PRINTERS
, NULL
, dests
, 0, CUPS_PRINTER_3D
);
1907 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE
)
1909 cupsFreeDests(num_dests
, *dests
);
1910 *dests
= (cups_dest_t
*)0;
1915 * Make a copy of the "real" queues for a later sanity check...
1920 num_reals
= num_dests
;
1921 reals
= calloc((size_t)num_reals
, sizeof(cups_dest_t
));
1924 memcpy(reals
, *dests
, (size_t)num_reals
* sizeof(cups_dest_t
));
1935 * Grab the default destination...
1938 if ((user_default
= _cupsUserDefault(name
, sizeof(name
))) != NULL
)
1940 else if ((defprinter
= cupsGetDefault2(http
)) != NULL
)
1942 strlcpy(name
, defprinter
, sizeof(name
));
1949 * Separate printer and instance name...
1952 if ((instance
= strchr(name
, '/')) != NULL
)
1956 * Lookup the printer and instance and make it the default...
1959 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) != NULL
)
1960 dest
->is_default
= 1;
1966 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
1969 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1970 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1973 if ((home
= getenv("HOME")) != NULL
)
1975 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1977 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1982 * Validate the current default destination - this prevents old
1983 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
1984 * pointing to a non-existent printer or class...
1990 * See if we have a default printer...
1993 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, *dests
)) != NULL
)
1996 * Have a default; see if it is real...
1999 if (!cupsGetDest(dest
->name
, NULL
, num_reals
, reals
))
2002 * Remove the non-real printer from the list, since we don't want jobs
2003 * going to an unexpected printer... (<rdar://problem/14216472>)
2006 num_dests
= cupsRemoveDest(dest
->name
, dest
->instance
, num_dests
,
2019 * Return the number of destinations...
2023 _cupsSetError(IPP_STATUS_OK
, NULL
, 0);
2030 * 'cupsGetNamedDest()' - Get options for the named destination.
2032 * This function is optimized for retrieving a single destination and should
2033 * be used instead of @link cupsGetDests@ and @link cupsGetDest@ when you either
2034 * know the name of the destination or want to print to the default destination.
2035 * If @code NULL@ is returned, the destination does not exist or there is no
2036 * default destination.
2038 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
2039 * server will be used.
2041 * If "name" is @code NULL@, the default printer for the current user will be
2044 * The returned destination must be freed using @link cupsFreeDests@ with a
2045 * "num_dests" value of 1.
2047 * @since CUPS 1.4/macOS 10.6@
2050 cups_dest_t
* /* O - Destination or @code NULL@ */
2051 cupsGetNamedDest(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2052 const char *name
, /* I - Destination name or @code NULL@ for the default destination */
2053 const char *instance
) /* I - Instance name or @code NULL@ */
2055 cups_dest_t
*dest
; /* Destination */
2056 char filename
[1024], /* Path to lpoptions */
2057 defname
[256]; /* Default printer name */
2058 const char *home
= getenv("HOME"); /* Home directory */
2059 int set_as_default
= 0; /* Set returned destination as default */
2060 ipp_op_t op
= IPP_OP_GET_PRINTER_ATTRIBUTES
;
2061 /* IPP operation to get server ops */
2062 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
2066 * If "name" is NULL, find the default destination...
2072 name
= _cupsUserDefault(defname
, sizeof(defname
));
2076 char *ptr
; /* Temporary pointer... */
2078 if ((ptr
= strchr(defname
, '/')) != NULL
)
2089 * No default in the environment, try the user's lpoptions files...
2092 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
2094 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
2100 * Still not there? Try the system lpoptions file...
2103 snprintf(filename
, sizeof(filename
), "%s/lpoptions",
2104 cg
->cups_serverroot
);
2105 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
2111 * No locally-set default destination, ask the server...
2114 op
= IPP_OP_CUPS_GET_DEFAULT
;
2119 * Get the printer's attributes...
2122 if (!_cupsGetDests(http
, op
, name
, &dest
, 0, CUPS_PRINTER_3D
))
2126 dest
->instance
= _cupsStrAlloc(instance
);
2129 dest
->is_default
= 1;
2132 * Then add local options...
2135 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
2136 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
2140 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
2142 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
2146 * Return the result...
2154 * 'cupsRemoveDest()' - Remove a destination from the destination list.
2156 * Removing a destination/instance does not delete the class or printer
2157 * queue, merely the lpoptions for that destination/instance. Use the
2158 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
2159 * options for the user.
2161 * @since CUPS 1.3/macOS 10.5@
2164 int /* O - New number of destinations */
2165 cupsRemoveDest(const char *name
, /* I - Destination name */
2166 const char *instance
, /* I - Instance name or @code NULL@ */
2167 int num_dests
, /* I - Number of destinations */
2168 cups_dest_t
**dests
) /* IO - Destinations */
2170 int i
; /* Index into destinations */
2171 cups_dest_t
*dest
; /* Pointer to destination */
2175 * Find the destination...
2178 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
2185 _cupsStrFree(dest
->name
);
2186 _cupsStrFree(dest
->instance
);
2187 cupsFreeOptions(dest
->num_options
, dest
->options
);
2190 * Remove the destination from the array...
2195 i
= (int)(dest
- *dests
);
2198 memmove(dest
, dest
+ 1, (size_t)(num_dests
- i
) * sizeof(cups_dest_t
));
2205 * 'cupsSetDefaultDest()' - Set the default destination.
2207 * @since CUPS 1.3/macOS 10.5@
2212 const char *name
, /* I - Destination name */
2213 const char *instance
, /* I - Instance name or @code NULL@ */
2214 int num_dests
, /* I - Number of destinations */
2215 cups_dest_t
*dests
) /* I - Destinations */
2217 int i
; /* Looping var */
2218 cups_dest_t
*dest
; /* Current destination */
2222 * Range check input...
2225 if (!name
|| num_dests
<= 0 || !dests
)
2229 * Loop through the array and set the "is_default" flag for the matching
2233 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
2234 dest
->is_default
= !_cups_strcasecmp(name
, dest
->name
) &&
2235 ((!instance
&& !dest
->instance
) ||
2236 (instance
&& dest
->instance
&&
2237 !_cups_strcasecmp(instance
, dest
->instance
)));
2242 * 'cupsSetDests()' - Save the list of destinations for the default server.
2244 * This function saves the destinations to /etc/cups/lpoptions when run
2245 * as root and ~/.cups/lpoptions when run as a normal user.
2249 cupsSetDests(int num_dests
, /* I - Number of destinations */
2250 cups_dest_t
*dests
) /* I - Destinations */
2252 cupsSetDests2(CUPS_HTTP_DEFAULT
, num_dests
, dests
);
2257 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
2259 * This function saves the destinations to /etc/cups/lpoptions when run
2260 * as root and ~/.cups/lpoptions when run as a normal user.
2262 * @since CUPS 1.1.21/macOS 10.4@
2265 int /* O - 0 on success, -1 on error */
2266 cupsSetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2267 int num_dests
, /* I - Number of destinations */
2268 cups_dest_t
*dests
) /* I - Destinations */
2270 int i
, j
; /* Looping vars */
2271 int wrote
; /* Wrote definition? */
2272 cups_dest_t
*dest
; /* Current destination */
2273 cups_option_t
*option
; /* Current option */
2274 _ipp_option_t
*match
; /* Matching attribute for option */
2275 FILE *fp
; /* File pointer */
2277 const char *home
; /* HOME environment variable */
2279 char filename
[1024]; /* lpoptions file */
2280 int num_temps
; /* Number of temporary destinations */
2281 cups_dest_t
*temps
= NULL
, /* Temporary destinations */
2282 *temp
; /* Current temporary dest */
2283 const char *val
; /* Value of temporary option */
2284 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
2288 * Range check the input...
2291 if (!num_dests
|| !dests
)
2295 * Get the server destinations...
2298 num_temps
= _cupsGetDests(http
, IPP_OP_CUPS_GET_PRINTERS
, NULL
, &temps
, 0, CUPS_PRINTER_3D
);
2300 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE
)
2302 cupsFreeDests(num_temps
, temps
);
2307 * Figure out which file to write to...
2310 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
2316 * Merge in server defaults...
2319 num_temps
= cups_get_dests(filename
, NULL
, NULL
, 0, num_temps
, &temps
);
2322 * Point to user defaults...
2325 if ((home
= getenv("HOME")) != NULL
)
2328 * Create ~/.cups subdirectory...
2331 snprintf(filename
, sizeof(filename
), "%s/.cups", home
);
2332 if (access(filename
, 0))
2333 mkdir(filename
, 0700);
2335 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
2341 * Try to open the file...
2344 if ((fp
= fopen(filename
, "w")) == NULL
)
2346 cupsFreeDests(num_temps
, temps
);
2352 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2357 fchmod(fileno(fp
), 0644);
2361 * Write each printer; each line looks like:
2363 * Dest name[/instance] options
2364 * Default name[/instance] options
2367 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
2368 if (dest
->instance
!= NULL
|| dest
->num_options
!= 0 || dest
->is_default
)
2370 if (dest
->is_default
)
2372 fprintf(fp
, "Default %s", dest
->name
);
2374 fprintf(fp
, "/%s", dest
->instance
);
2381 if ((temp
= cupsGetDest(dest
->name
, dest
->instance
, num_temps
, temps
)) == NULL
)
2382 temp
= cupsGetDest(dest
->name
, NULL
, num_temps
, temps
);
2384 for (j
= dest
->num_options
, option
= dest
->options
; j
> 0; j
--, option
++)
2387 * See if this option is a printer attribute; if so, skip it...
2390 if ((match
= _ippFindOption(option
->name
)) != NULL
&&
2391 match
->group_tag
== IPP_TAG_PRINTER
)
2395 * See if the server/global options match these; if so, don't
2400 (val
= cupsGetOption(option
->name
, temp
->num_options
,
2401 temp
->options
)) != NULL
&&
2402 !_cups_strcasecmp(val
, option
->value
))
2406 * Options don't match, write to the file...
2411 fprintf(fp
, "Dest %s", dest
->name
);
2413 fprintf(fp
, "/%s", dest
->instance
);
2417 if (option
->value
[0])
2419 if (strchr(option
->value
, ' ') ||
2420 strchr(option
->value
, '\\') ||
2421 strchr(option
->value
, '\"') ||
2422 strchr(option
->value
, '\''))
2425 * Quote the value...
2428 fprintf(fp
, " %s=\"", option
->name
);
2430 for (val
= option
->value
; *val
; val
++)
2432 if (strchr("\"\'\\", *val
))
2443 * Store the literal value...
2446 fprintf(fp
, " %s=%s", option
->name
, option
->value
);
2450 fprintf(fp
, " %s", option
->name
);
2458 * Free the temporary destinations and close the file...
2461 cupsFreeDests(num_temps
, temps
);
2467 * Set the default printer for this location - this allows command-line
2468 * and GUI applications to share the same default destination...
2471 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, dests
)) != NULL
)
2473 CFStringRef name
= CFStringCreateWithCString(kCFAllocatorDefault
,
2475 kCFStringEncodingUTF8
);
2476 /* Default printer name */
2480 _cupsAppleSetDefaultPrinter(name
);
2484 #endif /* __APPLE__ */
2486 #ifdef HAVE_NOTIFY_POST
2488 * Send a notification so that macOS applications can know about the
2492 notify_post("com.apple.printerListChange");
2493 #endif /* HAVE_NOTIFY_POST */
2500 * '_cupsUserDefault()' - Get the user default printer from environment
2501 * variables and location information.
2504 char * /* O - Default printer or NULL */
2505 _cupsUserDefault(char *name
, /* I - Name buffer */
2506 size_t namesize
) /* I - Size of name buffer */
2508 const char *env
; /* LPDEST or PRINTER env variable */
2510 CFStringRef locprinter
; /* Last printer as this location */
2511 #endif /* __APPLE__ */
2514 if ((env
= getenv("LPDEST")) == NULL
)
2515 if ((env
= getenv("PRINTER")) != NULL
&& !strcmp(env
, "lp"))
2520 strlcpy(name
, env
, namesize
);
2526 * Use location-based defaults if "use last printer" is selected in the
2527 * system preferences...
2530 if ((locprinter
= _cupsAppleCopyDefaultPrinter()) != NULL
)
2532 CFStringGetCString(locprinter
, name
, (CFIndex
)namesize
, kCFStringEncodingUTF8
);
2533 CFRelease(locprinter
);
2538 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name
));
2540 return (*name
? name
: NULL
);
2544 * No location-based defaults on this platform...
2549 #endif /* __APPLE__ */
2553 #if _CUPS_LOCATION_DEFAULTS
2555 * 'appleCopyLocations()' - Copy the location history array.
2558 static CFArrayRef
/* O - Location array or NULL */
2559 appleCopyLocations(void)
2561 CFArrayRef locations
; /* Location array */
2565 * Look up the location array in the preferences...
2568 if ((locations
= CFPreferencesCopyAppValue(kLastUsedPrintersKey
,
2569 kCUPSPrintingPrefs
)) == NULL
)
2572 if (CFGetTypeID(locations
) != CFArrayGetTypeID())
2574 CFRelease(locations
);
2583 * 'appleCopyNetwork()' - Get the network ID for the current location.
2586 static CFStringRef
/* O - Network ID */
2587 appleCopyNetwork(void)
2589 SCDynamicStoreRef dynamicStore
; /* System configuration data */
2590 CFStringRef key
; /* Current network configuration key */
2591 CFDictionaryRef ip_dict
; /* Network configuration data */
2592 CFStringRef network
= NULL
; /* Current network ID */
2595 if ((dynamicStore
= SCDynamicStoreCreate(NULL
, CFSTR("libcups"), NULL
,
2599 * First use the IPv6 router address, if available, since that will generally
2600 * be a globally-unique link-local address.
2603 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2604 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv6
)) != NULL
)
2606 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2608 if ((network
= CFDictionaryGetValue(ip_dict
,
2609 kSCPropNetIPv6Router
)) != NULL
)
2619 * If that doesn't work, try the IPv4 router address. This isn't as unique
2620 * and will likely be a 10.x.y.z or 192.168.y.z address...
2625 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2626 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv4
)) != NULL
)
2628 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2630 if ((network
= CFDictionaryGetValue(ip_dict
,
2631 kSCPropNetIPv4Router
)) != NULL
)
2641 CFRelease(dynamicStore
);
2646 #endif /* _CUPS_LOCATION_DEFAULTS */
2651 * 'appleGetPaperSize()' - Get the default paper size.
2654 static char * /* O - Default paper size */
2655 appleGetPaperSize(char *name
, /* I - Paper size name buffer */
2656 size_t namesize
) /* I - Size of buffer */
2658 CFStringRef defaultPaperID
; /* Default paper ID */
2659 pwg_media_t
*pwgmedia
; /* PWG media size */
2662 defaultPaperID
= _cupsAppleCopyDefaultPaperID();
2663 if (!defaultPaperID
||
2664 CFGetTypeID(defaultPaperID
) != CFStringGetTypeID() ||
2665 !CFStringGetCString(defaultPaperID
, name
, (CFIndex
)namesize
, kCFStringEncodingUTF8
))
2667 else if ((pwgmedia
= pwgMediaForLegacy(name
)) != NULL
)
2668 strlcpy(name
, pwgmedia
->pwg
, namesize
);
2671 CFRelease(defaultPaperID
);
2675 #endif /* __APPLE__ */
2678 #if _CUPS_LOCATION_DEFAULTS
2680 * 'appleGetPrinter()' - Get a printer from the history array.
2683 static CFStringRef
/* O - Printer name or NULL */
2684 appleGetPrinter(CFArrayRef locations
, /* I - Location array */
2685 CFStringRef network
, /* I - Network name */
2686 CFIndex
*locindex
) /* O - Index in array */
2688 CFIndex i
, /* Looping var */
2689 count
; /* Number of locations */
2690 CFDictionaryRef location
; /* Current location */
2691 CFStringRef locnetwork
, /* Current network */
2692 locprinter
; /* Current printer */
2695 for (i
= 0, count
= CFArrayGetCount(locations
); i
< count
; i
++)
2696 if ((location
= CFArrayGetValueAtIndex(locations
, i
)) != NULL
&&
2697 CFGetTypeID(location
) == CFDictionaryGetTypeID())
2699 if ((locnetwork
= CFDictionaryGetValue(location
,
2700 kLocationNetworkKey
)) != NULL
&&
2701 CFGetTypeID(locnetwork
) == CFStringGetTypeID() &&
2702 CFStringCompare(network
, locnetwork
, 0) == kCFCompareEqualTo
&&
2703 (locprinter
= CFDictionaryGetValue(location
,
2704 kLocationPrinterIDKey
)) != NULL
&&
2705 CFGetTypeID(locprinter
) == CFStringGetTypeID())
2710 return (locprinter
);
2716 #endif /* _CUPS_LOCATION_DEFAULTS */
2720 * 'cups_add_dest()' - Add a destination to the array.
2722 * Unlike cupsAddDest(), this function does not check for duplicates.
2725 static cups_dest_t
* /* O - New destination */
2726 cups_add_dest(const char *name
, /* I - Name of destination */
2727 const char *instance
, /* I - Instance or NULL */
2728 int *num_dests
, /* IO - Number of destinations */
2729 cups_dest_t
**dests
) /* IO - Destinations */
2731 int insert
, /* Insertion point */
2732 diff
; /* Result of comparison */
2733 cups_dest_t
*dest
; /* Destination pointer */
2737 * Add new destination...
2740 if (*num_dests
== 0)
2741 dest
= malloc(sizeof(cups_dest_t
));
2743 dest
= realloc(*dests
, sizeof(cups_dest_t
) * (size_t)(*num_dests
+ 1));
2751 * Find where to insert the destination...
2754 if (*num_dests
== 0)
2758 insert
= cups_find_dest(name
, instance
, *num_dests
, *dests
, *num_dests
- 1,
2766 * Move the array elements as needed...
2769 if (insert
< *num_dests
)
2770 memmove(*dests
+ insert
+ 1, *dests
+ insert
, (size_t)(*num_dests
- insert
) * sizeof(cups_dest_t
));
2775 * Initialize the destination...
2778 dest
= *dests
+ insert
;
2779 dest
->name
= _cupsStrAlloc(name
);
2780 dest
->instance
= _cupsStrAlloc(instance
);
2781 dest
->is_default
= 0;
2782 dest
->num_options
= 0;
2783 dest
->options
= (cups_option_t
*)0;
2791 * 'cups_block_cb()' - Enumeration callback for block API.
2794 static int /* O - 1 to continue, 0 to stop */
2796 cups_dest_block_t block
, /* I - Block */
2797 unsigned flags
, /* I - Destination flags */
2798 cups_dest_t
*dest
) /* I - Destination */
2800 return ((block
)(flags
, dest
));
2802 # endif /* __BLOCKS__ */
2806 * 'cups_compare_dests()' - Compare two destinations.
2809 static int /* O - Result of comparison */
2810 cups_compare_dests(cups_dest_t
*a
, /* I - First destination */
2811 cups_dest_t
*b
) /* I - Second destination */
2813 int diff
; /* Difference */
2816 if ((diff
= _cups_strcasecmp(a
->name
, b
->name
)) != 0)
2818 else if (a
->instance
&& b
->instance
)
2819 return (_cups_strcasecmp(a
->instance
, b
->instance
));
2821 return ((a
->instance
&& !b
->instance
) - (!a
->instance
&& b
->instance
));
2825 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
2828 * 'cups_dnssd_browse_cb()' - Browse for printers.
2832 cups_dnssd_browse_cb(
2833 DNSServiceRef sdRef
, /* I - Service reference */
2834 DNSServiceFlags flags
, /* I - Option flags */
2835 uint32_t interfaceIndex
, /* I - Interface number */
2836 DNSServiceErrorType errorCode
, /* I - Error, if any */
2837 const char *serviceName
, /* I - Name of service/device */
2838 const char *regtype
, /* I - Type of service */
2839 const char *replyDomain
, /* I - Service domain */
2840 void *context
) /* I - Enumeration data */
2842 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2843 /* Enumeration data */
2846 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
));
2849 * Don't do anything on error...
2852 if (errorCode
!= kDNSServiceErr_NoError
)
2859 cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2863 # else /* HAVE_AVAHI */
2865 * 'cups_dnssd_browse_cb()' - Browse for printers.
2869 cups_dnssd_browse_cb(
2870 AvahiServiceBrowser
*browser
, /* I - Browser */
2871 AvahiIfIndex interface
, /* I - Interface index (unused) */
2872 AvahiProtocol protocol
, /* I - Network protocol (unused) */
2873 AvahiBrowserEvent event
, /* I - What happened */
2874 const char *name
, /* I - Service name */
2875 const char *type
, /* I - Registration type */
2876 const char *domain
, /* I - Domain */
2877 AvahiLookupResultFlags flags
, /* I - Flags */
2878 void *context
) /* I - Devices array */
2881 AvahiClient
*client
= avahi_service_browser_get_client(browser
);
2882 /* Client information */
2884 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2885 /* Enumeration data */
2894 case AVAHI_BROWSER_FAILURE
:
2895 DEBUG_printf(("cups_dnssd_browse_cb: %s",
2896 avahi_strerror(avahi_client_errno(client
))));
2897 avahi_simple_poll_quit(data
->simple_poll
);
2900 case AVAHI_BROWSER_NEW
:
2902 * This object is new on the network.
2905 if (flags
& AVAHI_LOOKUP_RESULT_LOCAL
)
2908 * This comes from the local machine so ignore it.
2911 DEBUG_printf(("cups_dnssd_browse_cb: Ignoring local service \"%s\".",
2917 * Create a device entry for it if it doesn't yet exist.
2920 cups_dnssd_get_device(data
, name
, type
, domain
);
2924 case AVAHI_BROWSER_REMOVE
:
2925 case AVAHI_BROWSER_ALL_FOR_NOW
:
2926 case AVAHI_BROWSER_CACHE_EXHAUSTED
:
2933 * 'cups_dnssd_client_cb()' - Avahi client callback function.
2937 cups_dnssd_client_cb(
2938 AvahiClient
*client
, /* I - Client information (unused) */
2939 AvahiClientState state
, /* I - Current state */
2940 void *context
) /* I - User data (unused) */
2942 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2943 /* Enumeration data */
2949 * If the connection drops, quit.
2952 if (state
== AVAHI_CLIENT_FAILURE
)
2954 DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
2955 avahi_simple_poll_quit(data
->simple_poll
);
2958 # endif /* HAVE_DNSSD */
2962 * 'cups_dnssd_compare_device()' - Compare two devices.
2965 static int /* O - Result of comparison */
2966 cups_dnssd_compare_devices(
2967 _cups_dnssd_device_t
*a
, /* I - First device */
2968 _cups_dnssd_device_t
*b
) /* I - Second device */
2970 return (strcmp(a
->dest
.name
, b
->dest
.name
));
2975 * 'cups_dnssd_free_device()' - Free the memory used by a device.
2979 cups_dnssd_free_device(
2980 _cups_dnssd_device_t
*device
, /* I - Device */
2981 _cups_dnssd_data_t
*data
) /* I - Enumeration data */
2983 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", (void *)device
, device
->dest
.name
, (void *)data
));
2987 DNSServiceRefDeallocate(device
->ref
);
2988 # else /* HAVE_AVAHI */
2990 avahi_record_browser_free(device
->ref
);
2991 # endif /* HAVE_DNSSD */
2993 _cupsStrFree(device
->domain
);
2994 _cupsStrFree(device
->fullName
);
2995 _cupsStrFree(device
->regtype
);
2996 _cupsStrFree(device
->dest
.name
);
2998 cupsFreeOptions(device
->dest
.num_options
, device
->dest
.options
);
3005 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
3008 static _cups_dnssd_device_t
* /* O - Device */
3009 cups_dnssd_get_device(
3010 _cups_dnssd_data_t
*data
, /* I - Enumeration data */
3011 const char *serviceName
, /* I - Service name */
3012 const char *regtype
, /* I - Registration type */
3013 const char *replyDomain
) /* I - Domain name */
3015 _cups_dnssd_device_t key
, /* Search key */
3016 *device
; /* Device */
3017 char fullName
[kDNSServiceMaxDomainName
],
3018 /* Full name for query */
3019 name
[128]; /* Queue name */
3022 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", regtype=\"%s\", replyDomain=\"%s\")", (void *)data
, serviceName
, regtype
, replyDomain
));
3025 * See if this is an existing device...
3028 cups_dnssd_queue_name(name
, serviceName
, sizeof(name
));
3030 key
.dest
.name
= name
;
3032 if ((device
= cupsArrayFind(data
->devices
, &key
)) != NULL
)
3035 * Yes, see if we need to do anything with this...
3038 int update
= 0; /* Non-zero if we need to update */
3040 if (!_cups_strcasecmp(replyDomain
, "local.") &&
3041 _cups_strcasecmp(device
->domain
, replyDomain
))
3044 * Update the "global" listing to use the .local domain name instead.
3047 _cupsStrFree(device
->domain
);
3048 device
->domain
= _cupsStrAlloc(replyDomain
);
3050 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
3051 "domain.", device
->dest
.name
));
3056 if (!_cups_strcasecmp(regtype
, "_ipps._tcp") &&
3057 _cups_strcasecmp(device
->regtype
, regtype
))
3060 * Prefer IPPS over IPP.
3063 _cupsStrFree(device
->regtype
);
3064 device
->regtype
= _cupsStrAlloc(regtype
);
3066 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
3067 device
->dest
.name
));
3074 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
3075 device
->dest
.name
));
3082 * No, add the device...
3085 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
3086 "'%s'.", serviceName
,
3087 !strcmp(regtype
, "_ipps._tcp") ? "IPPS" : "IPP",
3090 device
= calloc(sizeof(_cups_dnssd_device_t
), 1);
3091 device
->dest
.name
= _cupsStrAlloc(name
);
3092 device
->domain
= _cupsStrAlloc(replyDomain
);
3093 device
->regtype
= _cupsStrAlloc(regtype
);
3095 device
->dest
.num_options
= cupsAddOption("printer-info", serviceName
, 0, &device
->dest
.options
);
3097 cupsArrayAdd(data
->devices
, device
);
3101 * Set the "full name" of this service, which is used for queries...
3105 DNSServiceConstructFullName(fullName
, serviceName
, regtype
, replyDomain
);
3106 # else /* HAVE_AVAHI */
3107 avahi_service_name_join(fullName
, kDNSServiceMaxDomainName
, serviceName
, regtype
, replyDomain
);
3108 # endif /* HAVE_DNSSD */
3110 _cupsStrFree(device
->fullName
);
3111 device
->fullName
= _cupsStrAlloc(fullName
);
3116 DNSServiceRefDeallocate(device
->ref
);
3117 # else /* HAVE_AVAHI */
3118 avahi_record_browser_free(device
->ref
);
3119 # endif /* HAVE_DNSSD */
3124 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
3126 DEBUG_printf(("6cups_dnssd_get_device: Remove callback for \"%s\".", device
->dest
.name
));
3128 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
3129 device
->state
= _CUPS_DNSSD_NEW
;
3138 * 'cups_dnssd_local_cb()' - Browse for local printers.
3142 cups_dnssd_local_cb(
3143 DNSServiceRef sdRef
, /* I - Service reference */
3144 DNSServiceFlags flags
, /* I - Option flags */
3145 uint32_t interfaceIndex
, /* I - Interface number */
3146 DNSServiceErrorType errorCode
, /* I - Error, if any */
3147 const char *serviceName
, /* I - Name of service/device */
3148 const char *regtype
, /* I - Type of service */
3149 const char *replyDomain
, /* I - Service domain */
3150 void *context
) /* I - Devices array */
3152 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
3153 /* Enumeration data */
3154 _cups_dnssd_device_t
*device
; /* Device */
3157 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
));
3160 * Only process "add" data...
3163 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
3170 device
= cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
3173 * Hide locally-registered devices...
3176 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
3181 DNSServiceRefDeallocate(device
->ref
);
3185 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
3187 DEBUG_printf(("6cups_dnssd_local_cb: Remove callback for \"%s\".", device
->dest
.name
));
3188 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
3191 device
->state
= _CUPS_DNSSD_LOCAL
;
3193 # endif /* HAVE_DNSSD */
3198 * 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
3200 * Note: This function is needed because avahi_simple_poll_iterate is broken
3201 * and always uses a timeout of 0 (!) milliseconds.
3202 * (Avahi Ticket #364)
3205 static int /* O - Number of file descriptors matching */
3207 struct pollfd
*pollfds
, /* I - File descriptors */
3208 unsigned int num_pollfds
, /* I - Number of file descriptors */
3209 int timeout
, /* I - Timeout in milliseconds (unused) */
3210 void *context
) /* I - User data (unused) */
3212 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
3213 /* Enumeration data */
3214 int val
; /* Return value */
3219 val
= poll(pollfds
, num_pollfds
, 250);
3223 DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno
)));
3230 # endif /* HAVE_AVAHI */
3234 * 'cups_dnssd_query_cb()' - Process query data.
3239 cups_dnssd_query_cb(
3240 DNSServiceRef sdRef
, /* I - Service reference */
3241 DNSServiceFlags flags
, /* I - Data flags */
3242 uint32_t interfaceIndex
, /* I - Interface */
3243 DNSServiceErrorType errorCode
, /* I - Error, if any */
3244 const char *fullName
, /* I - Full service name */
3245 uint16_t rrtype
, /* I - Record type */
3246 uint16_t rrclass
, /* I - Record class */
3247 uint16_t rdlen
, /* I - Length of record data */
3248 const void *rdata
, /* I - Record data */
3249 uint32_t ttl
, /* I - Time-to-live */
3250 void *context
) /* I - Enumeration data */
3252 # else /* HAVE_AVAHI */
3254 cups_dnssd_query_cb(
3255 AvahiRecordBrowser
*browser
, /* I - Record browser */
3256 AvahiIfIndex interfaceIndex
,
3257 /* I - Interface index (unused) */
3258 AvahiProtocol protocol
, /* I - Network protocol (unused) */
3259 AvahiBrowserEvent event
, /* I - What happened? */
3260 const char *fullName
, /* I - Service name */
3261 uint16_t rrclass
, /* I - Record class */
3262 uint16_t rrtype
, /* I - Record type */
3263 const void *rdata
, /* I - TXT record */
3264 size_t rdlen
, /* I - Length of TXT record */
3265 AvahiLookupResultFlags flags
, /* I - Flags */
3266 void *context
) /* I - Enumeration data */
3269 AvahiClient
*client
= avahi_record_browser_get_client(browser
);
3270 /* Client information */
3272 # endif /* HAVE_DNSSD */
3273 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
3274 /* Enumeration data */
3275 char serviceName
[256],/* Service name */
3276 name
[128], /* Queue name */
3277 *ptr
; /* Pointer into string */
3278 _cups_dnssd_device_t dkey
, /* Search key */
3279 *device
; /* Device */
3283 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
));
3286 * Only process "add" data...
3289 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
3292 # else /* HAVE_AVAHI */
3293 DEBUG_printf(("5cups_dnssd_query_cb(browser=%p, interfaceIndex=%d, "
3294 "protocol=%d, event=%d, fullName=\"%s\", rrclass=%u, "
3295 "rrtype=%u, rdata=%p, rdlen=%u, flags=%x, context=%p)",
3296 browser
, interfaceIndex
, protocol
, event
, fullName
, rrclass
,
3297 rrtype
, rdata
, (unsigned)rdlen
, flags
, context
));
3300 * Only process "add" data...
3303 if (event
!= AVAHI_BROWSER_NEW
)
3305 if (event
== AVAHI_BROWSER_FAILURE
)
3306 DEBUG_printf(("cups_dnssd_query_cb: %s",
3307 avahi_strerror(avahi_client_errno(client
))));
3311 # endif /* HAVE_DNSSD */
3314 * Lookup the service in the devices array.
3317 cups_dnssd_unquote(serviceName
, fullName
, sizeof(serviceName
));
3319 if ((ptr
= strstr(serviceName
, "._")) != NULL
)
3322 cups_dnssd_queue_name(name
, serviceName
, sizeof(name
));
3324 dkey
.dest
.name
= name
;
3326 if ((device
= cupsArrayFind(data
->devices
, &dkey
)) != NULL
&& device
->state
== _CUPS_DNSSD_NEW
)
3329 * Found it, pull out the make and model from the TXT record and save it...
3332 const uint8_t *txt
, /* Pointer into data */
3333 *txtnext
, /* Next key/value pair */
3334 *txtend
; /* End of entire TXT record */
3335 uint8_t txtlen
; /* Length of current key/value pair */
3336 char key
[256], /* Key string */
3337 value
[256], /* Value string */
3338 make_and_model
[512],
3339 /* Manufacturer and model */
3340 model
[256], /* Model */
3341 uriname
[1024], /* Name for URI */
3342 uri
[1024]; /* Printer URI */
3343 cups_ptype_t type
= CUPS_PRINTER_REMOTE
| CUPS_PRINTER_BW
;
3345 int saw_printer_type
= 0;
3346 /* Did we see a printer-type key? */
3348 device
->state
= _CUPS_DNSSD_PENDING
;
3349 make_and_model
[0] = '\0';
3351 strlcpy(model
, "Unknown", sizeof(model
));
3353 for (txt
= rdata
, txtend
= txt
+ rdlen
;
3358 * Read a key/value pair starting with an 8-bit length. Since the
3359 * length is 8 bits and the size of the key/value buffers is 256, we
3360 * don't need to check for overflow...
3365 if (!txtlen
|| (txt
+ txtlen
) > txtend
)
3368 txtnext
= txt
+ txtlen
;
3370 for (ptr
= key
; txt
< txtnext
&& *txt
!= '='; txt
++)
3371 *ptr
++ = (char)*txt
;
3374 if (txt
< txtnext
&& *txt
== '=')
3379 memcpy(value
, txt
, (size_t)(txtnext
- txt
));
3380 value
[txtnext
- txt
] = '\0';
3382 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key
, value
));
3386 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key
));
3390 if (!_cups_strcasecmp(key
, "usb_MFG") ||
3391 !_cups_strcasecmp(key
, "usb_MANU") ||
3392 !_cups_strcasecmp(key
, "usb_MANUFACTURER"))
3393 strlcpy(make_and_model
, value
, sizeof(make_and_model
));
3394 else if (!_cups_strcasecmp(key
, "usb_MDL") ||
3395 !_cups_strcasecmp(key
, "usb_MODEL"))
3396 strlcpy(model
, value
, sizeof(model
));
3397 else if (!_cups_strcasecmp(key
, "product") && !strstr(value
, "Ghostscript"))
3399 if (value
[0] == '(')
3402 * Strip parenthesis...
3405 if ((ptr
= value
+ strlen(value
) - 1) > value
&& *ptr
== ')')
3408 strlcpy(model
, value
+ 1, sizeof(model
));
3411 strlcpy(model
, value
, sizeof(model
));
3413 else if (!_cups_strcasecmp(key
, "ty"))
3415 strlcpy(model
, value
, sizeof(model
));
3417 if ((ptr
= strchr(model
, ',')) != NULL
)
3420 else if (!_cups_strcasecmp(key
, "note"))
3421 device
->dest
.num_options
= cupsAddOption("printer-location", value
,
3422 device
->dest
.num_options
,
3423 &device
->dest
.options
);
3424 else if (!_cups_strcasecmp(key
, "pdl"))
3427 * Look for PDF-capable printers; only PDF-capable printers are shown.
3430 const char *start
, *next
; /* Pointer into value */
3431 int have_pdf
= 0, /* Have PDF? */
3432 have_raster
= 0;/* Have raster format support? */
3434 for (start
= value
; start
&& *start
; start
= next
)
3436 if (!_cups_strncasecmp(start
, "application/pdf", 15) && (!start
[15] || start
[15] == ','))
3441 else if ((!_cups_strncasecmp(start
, "image/pwg-raster", 16) && (!start
[16] || start
[16] == ',')) ||
3442 (!_cups_strncasecmp(start
, "image/urf", 9) && (!start
[9] || start
[9] == ',')))
3448 if ((next
= strchr(start
, ',')) != NULL
)
3452 if (!have_pdf
&& !have_raster
)
3453 device
->state
= _CUPS_DNSSD_INCOMPATIBLE
;
3455 else if (!_cups_strcasecmp(key
, "printer-type"))
3458 * Value is either NNNN or 0xXXXX
3461 saw_printer_type
= 1;
3462 type
= (cups_ptype_t
)strtol(value
, NULL
, 0);
3464 else if (!saw_printer_type
)
3466 if (!_cups_strcasecmp(key
, "air") &&
3467 !_cups_strcasecmp(value
, "t"))
3468 type
|= CUPS_PRINTER_AUTHENTICATED
;
3469 else if (!_cups_strcasecmp(key
, "bind") &&
3470 !_cups_strcasecmp(value
, "t"))
3471 type
|= CUPS_PRINTER_BIND
;
3472 else if (!_cups_strcasecmp(key
, "collate") &&
3473 !_cups_strcasecmp(value
, "t"))
3474 type
|= CUPS_PRINTER_COLLATE
;
3475 else if (!_cups_strcasecmp(key
, "color") &&
3476 !_cups_strcasecmp(value
, "t"))
3477 type
|= CUPS_PRINTER_COLOR
;
3478 else if (!_cups_strcasecmp(key
, "copies") &&
3479 !_cups_strcasecmp(value
, "t"))
3480 type
|= CUPS_PRINTER_COPIES
;
3481 else if (!_cups_strcasecmp(key
, "duplex") &&
3482 !_cups_strcasecmp(value
, "t"))
3483 type
|= CUPS_PRINTER_DUPLEX
;
3484 else if (!_cups_strcasecmp(key
, "fax") &&
3485 !_cups_strcasecmp(value
, "t"))
3486 type
|= CUPS_PRINTER_MFP
;
3487 else if (!_cups_strcasecmp(key
, "papercustom") &&
3488 !_cups_strcasecmp(value
, "t"))
3489 type
|= CUPS_PRINTER_VARIABLE
;
3490 else if (!_cups_strcasecmp(key
, "papermax"))
3492 if (!_cups_strcasecmp(value
, "legal-a4"))
3493 type
|= CUPS_PRINTER_SMALL
;
3494 else if (!_cups_strcasecmp(value
, "isoc-a2"))
3495 type
|= CUPS_PRINTER_MEDIUM
;
3496 else if (!_cups_strcasecmp(value
, ">isoc-a2"))
3497 type
|= CUPS_PRINTER_LARGE
;
3499 else if (!_cups_strcasecmp(key
, "punch") &&
3500 !_cups_strcasecmp(value
, "t"))
3501 type
|= CUPS_PRINTER_PUNCH
;
3502 else if (!_cups_strcasecmp(key
, "scan") &&
3503 !_cups_strcasecmp(value
, "t"))
3504 type
|= CUPS_PRINTER_MFP
;
3505 else if (!_cups_strcasecmp(key
, "sort") &&
3506 !_cups_strcasecmp(value
, "t"))
3507 type
|= CUPS_PRINTER_SORT
;
3508 else if (!_cups_strcasecmp(key
, "staple") &&
3509 !_cups_strcasecmp(value
, "t"))
3510 type
|= CUPS_PRINTER_STAPLE
;
3515 * Save the printer-xxx values...
3518 device
->dest
.num_options
= cupsAddOption("printer-info", name
, device
->dest
.num_options
, &device
->dest
.options
);
3520 if (make_and_model
[0])
3522 strlcat(make_and_model
, " ", sizeof(make_and_model
));
3523 strlcat(make_and_model
, model
, sizeof(make_and_model
));
3525 device
->dest
.num_options
= cupsAddOption("printer-make-and-model", make_and_model
, device
->dest
.num_options
, &device
->dest
.options
);
3528 device
->dest
.num_options
= cupsAddOption("printer-make-and-model", model
, device
->dest
.num_options
, &device
->dest
.options
);
3530 device
->type
= type
;
3531 snprintf(value
, sizeof(value
), "%u", type
);
3532 device
->dest
.num_options
= cupsAddOption("printer-type", value
, device
->dest
.num_options
, &device
->dest
.options
);
3538 cups_dnssd_unquote(uriname
, device
->fullName
, sizeof(uriname
));
3539 httpAssembleURI(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
),
3540 !strcmp(device
->regtype
, "_ipps._tcp") ? "ipps" : "ipp",
3541 NULL
, uriname
, 0, saw_printer_type
? "/cups" : "/");
3543 DEBUG_printf(("6cups_dnssd_query: device-uri=\"%s\"", uri
));
3545 device
->dest
.num_options
= cupsAddOption("device-uri", uri
, device
->dest
.num_options
, &device
->dest
.options
);
3548 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
3554 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
3557 static const char * /* O - Resolved URI or NULL */
3559 cups_dest_t
*dest
, /* I - Destination */
3560 const char *uri
, /* I - Current printer URI */
3561 int msec
, /* I - Time in milliseconds */
3562 int *cancel
, /* I - Pointer to "cancel" variable */
3563 cups_dest_cb_t cb
, /* I - Callback */
3564 void *user_data
) /* I - User data for callback */
3566 char tempuri
[1024]; /* Temporary URI buffer */
3567 _cups_dnssd_resolve_t resolve
; /* Resolve data */
3571 * Resolve the URI...
3574 resolve
.cancel
= cancel
;
3575 gettimeofday(&resolve
.end_time
, NULL
);
3578 resolve
.end_time
.tv_sec
+= msec
/ 1000;
3579 resolve
.end_time
.tv_usec
+= (msec
% 1000) * 1000;
3581 while (resolve
.end_time
.tv_usec
>= 1000000)
3583 resolve
.end_time
.tv_sec
++;
3584 resolve
.end_time
.tv_usec
-= 1000000;
3588 resolve
.end_time
.tv_sec
+= 75;
3591 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
, dest
);
3593 if ((uri
= _httpResolveURI(uri
, tempuri
, sizeof(tempuri
), _HTTP_RESOLVE_DEFAULT
, cups_dnssd_resolve_cb
, &resolve
)) == NULL
)
3595 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unable to resolve printer-uri."), 1);
3598 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
, dest
);
3604 * Save the resolved URI...
3607 dest
->num_options
= cupsAddOption("resolved-device-uri", uri
, dest
->num_options
, &dest
->options
);
3609 return (cupsGetOption("resolved-device-uri", dest
->num_options
, dest
->options
));
3614 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
3617 static int /* O - 1 to continue, 0 to stop */
3618 cups_dnssd_resolve_cb(void *context
) /* I - Resolve data */
3620 _cups_dnssd_resolve_t
*resolve
= (_cups_dnssd_resolve_t
*)context
;
3622 struct timeval curtime
; /* Current time */
3626 * If the cancel variable is set, return immediately.
3629 if (resolve
->cancel
&& *(resolve
->cancel
))
3631 DEBUG_puts("4cups_dnssd_resolve_cb: Canceled.");
3636 * Otherwise check the end time...
3639 gettimeofday(&curtime
, NULL
);
3641 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
));
3643 return (curtime
.tv_sec
< resolve
->end_time
.tv_sec
||
3644 (curtime
.tv_sec
== resolve
->end_time
.tv_sec
&&
3645 curtime
.tv_usec
< resolve
->end_time
.tv_usec
));
3650 * 'cups_dnssd_unquote()' - Unquote a name string.
3654 cups_dnssd_unquote(char *dst
, /* I - Destination buffer */
3655 const char *src
, /* I - Source string */
3656 size_t dstsize
) /* I - Size of destination buffer */
3658 char *dstend
= dst
+ dstsize
- 1; /* End of destination buffer */
3661 while (*src
&& dst
< dstend
)
3666 if (isdigit(src
[0] & 255) && isdigit(src
[1] & 255) &&
3667 isdigit(src
[2] & 255))
3669 *dst
++ = ((((src
[0] - '0') * 10) + src
[1] - '0') * 10) + src
[2] - '0';
3681 #endif /* HAVE_DNSSD */
3684 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3686 * 'cups_dnssd_queue_name()' - Create a local queue name based on the service name.
3690 cups_dnssd_queue_name(
3691 char *name
, /* I - Name buffer */
3692 const char *serviceName
, /* I - Service name */
3693 size_t namesize
) /* I - Size of name buffer */
3695 const char *ptr
; /* Pointer into serviceName */
3696 char *nameptr
; /* Pointer into name */
3699 for (nameptr
= name
, ptr
= serviceName
; *ptr
&& nameptr
< (name
+ namesize
- 1); ptr
++)
3702 * Sanitize the printer name...
3705 if (_cups_isalnum(*ptr
))
3707 else if (nameptr
== name
|| nameptr
[-1] != '_')
3713 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3717 * 'cups_find_dest()' - Find a destination using a binary search.
3720 static int /* O - Index of match */
3721 cups_find_dest(const char *name
, /* I - Destination name */
3722 const char *instance
, /* I - Instance or NULL */
3723 int num_dests
, /* I - Number of destinations */
3724 cups_dest_t
*dests
, /* I - Destinations */
3725 int prev
, /* I - Previous index */
3726 int *rdiff
) /* O - Difference of match */
3728 int left
, /* Low mark for binary search */
3729 right
, /* High mark for binary search */
3730 current
, /* Current index */
3731 diff
; /* Result of comparison */
3732 cups_dest_t key
; /* Search key */
3735 key
.name
= (char *)name
;
3736 key
.instance
= (char *)instance
;
3741 * Start search on either side of previous...
3744 if ((diff
= cups_compare_dests(&key
, dests
+ prev
)) == 0 ||
3745 (diff
< 0 && prev
== 0) ||
3746 (diff
> 0 && prev
== (num_dests
- 1)))
3754 * Start with previous on right side...
3763 * Start wih previous on left side...
3767 right
= num_dests
- 1;
3773 * Start search in the middle...
3777 right
= num_dests
- 1;
3782 current
= (left
+ right
) / 2;
3783 diff
= cups_compare_dests(&key
, dests
+ current
);
3792 while ((right
- left
) > 1);
3797 * Check the last 1 or 2 elements...
3800 if ((diff
= cups_compare_dests(&key
, dests
+ left
)) <= 0)
3804 diff
= cups_compare_dests(&key
, dests
+ right
);
3810 * Return the closest destination and the difference...
3820 * 'cups_get_default()' - Get the default destination from an lpoptions file.
3823 static char * /* O - Default destination or NULL */
3824 cups_get_default(const char *filename
, /* I - File to read */
3825 char *namebuf
, /* I - Name buffer */
3826 size_t namesize
, /* I - Size of name buffer */
3827 const char **instance
) /* I - Instance */
3829 cups_file_t
*fp
; /* lpoptions file */
3830 char line
[8192], /* Line from file */
3831 *value
, /* Value for line */
3832 *nameptr
; /* Pointer into name */
3833 int linenum
; /* Current line */
3838 if ((fp
= cupsFileOpen(filename
, "r")) != NULL
)
3842 while (cupsFileGetConf(fp
, line
, sizeof(line
), &value
, &linenum
))
3844 if (!_cups_strcasecmp(line
, "default") && value
)
3846 strlcpy(namebuf
, value
, namesize
);
3848 if ((nameptr
= strchr(namebuf
, ' ')) != NULL
)
3850 if ((nameptr
= strchr(namebuf
, '\t')) != NULL
)
3853 if ((nameptr
= strchr(namebuf
, '/')) != NULL
)
3856 *instance
= nameptr
;
3864 return (*namebuf
? namebuf
: NULL
);
3869 * 'cups_get_dests()' - Get destinations from a file.
3872 static int /* O - Number of destinations */
3874 const char *filename
, /* I - File to read from */
3875 const char *match_name
, /* I - Destination name we want */
3876 const char *match_inst
, /* I - Instance name we want */
3877 int user_default_set
, /* I - User default printer set? */
3878 int num_dests
, /* I - Number of destinations */
3879 cups_dest_t
**dests
) /* IO - Destinations */
3881 int i
; /* Looping var */
3882 cups_dest_t
*dest
; /* Current destination */
3883 cups_file_t
*fp
; /* File pointer */
3884 char line
[8192], /* Line from file */
3885 *lineptr
, /* Pointer into line */
3886 *name
, /* Name of destination/option */
3887 *instance
; /* Instance of destination */
3888 int linenum
; /* Current line number */
3891 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
));
3894 * Try to open the file...
3897 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
3901 * Read each printer; each line looks like:
3903 * Dest name[/instance] options
3904 * Default name[/instance] options
3909 while (cupsFileGetConf(fp
, line
, sizeof(line
), &lineptr
, &linenum
))
3912 * See what type of line it is...
3915 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
3916 linenum
, line
, lineptr
));
3918 if ((_cups_strcasecmp(line
, "dest") && _cups_strcasecmp(line
, "default")) || !lineptr
)
3920 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
3927 * Search for an instance...
3930 while (!isspace(*lineptr
& 255) && *lineptr
&& *lineptr
!= '/')
3933 if (*lineptr
== '/')
3936 * Found an instance...
3943 * Search for an instance...
3946 while (!isspace(*lineptr
& 255) && *lineptr
)
3955 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name
,
3959 * See if the primary instance of the destination exists; if not,
3960 * ignore this entry and move on...
3965 if (_cups_strcasecmp(name
, match_name
) ||
3966 (!instance
&& match_inst
) ||
3967 (instance
&& !match_inst
) ||
3968 (instance
&& _cups_strcasecmp(instance
, match_inst
)))
3973 else if (cupsGetDest(name
, NULL
, num_dests
, *dests
) == NULL
)
3975 DEBUG_puts("9cups_get_dests: Not found!");
3981 * Add the destination...
3984 num_dests
= cupsAddDest(name
, instance
, num_dests
, dests
);
3986 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
3992 DEBUG_puts("9cups_get_dests: Out of memory!");
3998 * Add options until we hit the end of the line...
4001 dest
->num_options
= cupsParseOptions(lineptr
, dest
->num_options
,
4005 * If we found what we were looking for, stop now...
4012 * Set this as default if needed...
4015 if (!user_default_set
&& !_cups_strcasecmp(line
, "default"))
4017 DEBUG_puts("9cups_get_dests: Setting as default...");
4019 for (i
= 0; i
< num_dests
; i
++)
4020 (*dests
)[i
].is_default
= 0;
4022 dest
->is_default
= 1;
4027 * Close the file and return...
4037 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
4041 static char * /* O - New string */
4043 ipp_attribute_t
*attr
, /* I - Attribute to convert */
4044 char *buffer
, /* I - Buffer */
4045 size_t bufsize
) /* I - Size of buffer */
4047 int i
; /* Looping var */
4048 char *ptr
, /* Pointer into buffer */
4049 *end
, /* Pointer to end of buffer */
4050 *valptr
; /* Pointer into string attribute */
4054 * Return quickly if we have a single string value...
4057 if (attr
->num_values
== 1 &&
4058 attr
->value_tag
!= IPP_TAG_INTEGER
&&
4059 attr
->value_tag
!= IPP_TAG_ENUM
&&
4060 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
4061 attr
->value_tag
!= IPP_TAG_RANGE
)
4062 return (attr
->values
[0].string
.text
);
4065 * Copy the values to the string, separating with commas and escaping strings
4069 end
= buffer
+ bufsize
- 1;
4071 for (i
= 0, ptr
= buffer
; i
< attr
->num_values
&& ptr
< end
; i
++)
4076 switch (attr
->value_tag
)
4078 case IPP_TAG_INTEGER
:
4080 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d", attr
->values
[i
].integer
);
4083 case IPP_TAG_BOOLEAN
:
4084 if (attr
->values
[i
].boolean
)
4085 strlcpy(ptr
, "true", (size_t)(end
- ptr
+ 1));
4087 strlcpy(ptr
, "false", (size_t)(end
- ptr
+ 1));
4090 case IPP_TAG_RANGE
:
4091 if (attr
->values
[i
].range
.lower
== attr
->values
[i
].range
.upper
)
4092 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d", attr
->values
[i
].range
.lower
);
4094 snprintf(ptr
, (size_t)(end
- ptr
+ 1), "%d-%d", attr
->values
[i
].range
.lower
, attr
->values
[i
].range
.upper
);
4098 for (valptr
= attr
->values
[i
].string
.text
;
4099 *valptr
&& ptr
< end
;)
4101 if (strchr(" \t\n\\\'\"", *valptr
))
4103 if (ptr
>= (end
- 1))