2 * "$Id: dest.c 9568 2011-02-25 06:13:56Z mike $"
4 * User-defined destination (and option) support for CUPS.
6 * Copyright 2007-2012 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
15 * This file is subject to the Apple OS-Developed Software exception.
19 * cupsAddDest() - Add a destination to the list of
21 * _cupsAppleCopyDefaultPaperID() - Get the default paper ID.
22 * _cupsAppleCopyDefaultPrinter() - Get the default printer at this location.
23 * _cupsAppleGetUseLastPrinter() - Get whether to use the last used printer.
24 * _cupsAppleSetDefaultPaperID() - Set the default paper id.
25 * _cupsAppleSetDefaultPrinter() - Set the default printer for this
27 * _cupsAppleSetUseLastPrinter() - Set whether to use the last used printer.
28 * cupsConnectDest() - Connect to the server for a destination.
29 * cupsConnectDestBlock() - Connect to the server for a destination.
30 * cupsCopyDest() - Copy a destination.
31 * cupsEnumDests() - Enumerate available destinations with a
33 * cupsEnumDestsBlock() - Enumerate available destinations with a
35 * cupsFreeDests() - Free the memory used by the list of
37 * cupsGetDest() - Get the named destination from the list.
38 * _cupsGetDestResource() - Get the resource path and URI for a
40 * _cupsGetDests() - Get destinations from a server.
41 * cupsGetDests() - Get the list of destinations from the
43 * cupsGetDests2() - Get the list of destinations from the
45 * cupsGetNamedDest() - Get options for the named destination.
46 * cupsRemoveDest() - Remove a destination from the destination
48 * cupsSetDefaultDest() - Set the default destination.
49 * cupsSetDests() - Save the list of destinations for the
51 * cupsSetDests2() - Save the list of destinations for the
53 * _cupsUserDefault() - Get the user default printer from
54 * environment variables and location
56 * appleCopyLocations() - Copy the location history array.
57 * appleCopyNetwork() - Get the network ID for the current
59 * appleGetPaperSize() - Get the default paper size.
60 * appleGetPrinter() - Get a printer from the history array.
61 * cups_add_dest() - Add a destination to the array.
62 * cups_block_cb() - Enumeration callback for block API.
63 * cups_compare_dests() - Compare two destinations.
64 * cups_dnssd_browse_cb() - Browse for printers.
65 * cups_dnssd_compare_device() - Compare two devices.
66 * cups_dnssd_free_device() - Free the memory used by a device.
67 * cups_dnssd_get_device() - Lookup a device and create it as needed.
68 * cups_dnssd_local_cb() - Browse for local printers.
69 * cups_dnssd_query_cb() - Process query data.
70 * cups_dnssd_resolve() - Resolve a Bonjour printer URI.
71 * cups_dnssd_resolve_cb() - See if we should continue resolving.
72 * cups_dnssd_unquote() - Unquote a name string.
73 * cups_find_dest() - Find a destination using a binary search.
74 * cups_get_default() - Get the default destination from an
76 * cups_get_dests() - Get destinations from a file.
77 * cups_make_string() - Make a comma-separated string of values
78 * from an IPP attribute.
82 * Include necessary headers...
85 #include "cups-private.h"
90 #endif /* HAVE_NOTIFY_H */
94 #endif /* HAVE_POLL */
98 #endif /* HAVE_DNSSD */
106 # include <SystemConfiguration/SystemConfiguration.h>
107 # define kCUPSPrintingPrefs CFSTR("org.cups.PrintingPrefs")
108 # define kDefaultPaperIDKey CFSTR("DefaultPaperID")
109 # define kLastUsedPrintersKey CFSTR("LastUsedPrinters")
110 # define kLocationNetworkKey CFSTR("Network")
111 # define kLocationPrinterIDKey CFSTR("PrinterID")
112 # define kUseLastPrinter CFSTR("UseLastPrinter")
113 #endif /* __APPLE__ */
121 typedef enum _cups_dnssd_state_e
/* Enumerated device state */
129 } _cups_dnssd_state_t
;
131 typedef struct _cups_dnssd_data_s
/* Enumeration data */
133 DNSServiceRef main_ref
; /* Main service reference */
134 cups_dest_cb_t cb
; /* Callback */
135 void *user_data
; /* User data pointer */
136 cups_ptype_t type
, /* Printer type filter */
137 mask
; /* Printer type mask */
138 cups_array_t
*devices
; /* Devices found so far */
139 } _cups_dnssd_data_t
;
141 typedef struct _cups_dnssd_device_s
/* Enumerated device */
143 _cups_dnssd_state_t state
; /* State of device listing */
144 DNSServiceRef ref
; /* Service reference for query */
145 char *domain
, /* Domain name */
146 *fullName
, /* Full name */
147 *regtype
; /* Registration type */
148 cups_ptype_t type
; /* Device registration type */
149 cups_dest_t dest
; /* Destination record */
150 } _cups_dnssd_device_t
;
152 typedef struct _cups_dnssd_resolve_s
/* Data for resolving URI */
154 int *cancel
; /* Pointer to "cancel" variable */
155 struct timeval end_time
; /* Ending time */
156 } _cups_dnssd_resolve_t
;
157 #endif /* HAVE_DNSSD */
165 static CFArrayRef
appleCopyLocations(void);
166 static CFStringRef
appleCopyNetwork(void);
167 static char *appleGetPaperSize(char *name
, int namesize
);
168 static CFStringRef
appleGetPrinter(CFArrayRef locations
, CFStringRef network
,
170 #endif /* __APPLE__ */
171 static cups_dest_t
*cups_add_dest(const char *name
, const char *instance
,
172 int *num_dests
, cups_dest_t
**dests
);
174 static int cups_block_cb(cups_dest_block_t block
, unsigned flags
,
176 #endif /* __BLOCKS__ */
177 static int cups_compare_dests(cups_dest_t
*a
, cups_dest_t
*b
);
179 static void cups_dnssd_browse_cb(DNSServiceRef sdRef
,
180 DNSServiceFlags flags
,
181 uint32_t interfaceIndex
,
182 DNSServiceErrorType errorCode
,
183 const char *serviceName
,
185 const char *replyDomain
,
187 static int cups_dnssd_compare_devices(_cups_dnssd_device_t
*a
,
188 _cups_dnssd_device_t
*b
);
189 static void cups_dnssd_free_device(_cups_dnssd_device_t
*device
,
190 _cups_dnssd_data_t
*data
);
191 static _cups_dnssd_device_t
*
192 cups_dnssd_get_device(_cups_dnssd_data_t
*data
,
193 const char *serviceName
,
195 const char *replyDomain
);
196 static void cups_dnssd_local_cb(DNSServiceRef sdRef
,
197 DNSServiceFlags flags
,
198 uint32_t interfaceIndex
,
199 DNSServiceErrorType errorCode
,
200 const char *serviceName
,
202 const char *replyDomain
,
204 static void cups_dnssd_query_cb(DNSServiceRef sdRef
,
205 DNSServiceFlags flags
,
206 uint32_t interfaceIndex
,
207 DNSServiceErrorType errorCode
,
208 const char *fullName
,
209 uint16_t rrtype
, uint16_t rrclass
,
210 uint16_t rdlen
, const void *rdata
,
211 uint32_t ttl
, void *context
);
212 static const char *cups_dnssd_resolve(cups_dest_t
*dest
, const char *uri
,
213 int msec
, int *cancel
,
214 cups_dest_cb_t cb
, void *user_data
);
215 static int cups_dnssd_resolve_cb(void *context
);
216 static void cups_dnssd_unquote(char *dst
, const char *src
,
218 #endif /* HAVE_DNSSD */
219 static int cups_find_dest(const char *name
, const char *instance
,
220 int num_dests
, cups_dest_t
*dests
, int prev
,
222 static char *cups_get_default(const char *filename
, char *namebuf
,
223 size_t namesize
, const char **instance
);
224 static int cups_get_dests(const char *filename
, const char *match_name
,
225 const char *match_inst
, int user_default_set
,
226 int num_dests
, cups_dest_t
**dests
);
227 static char *cups_make_string(ipp_attribute_t
*attr
, char *buffer
,
232 * 'cupsAddDest()' - Add a destination to the list of destinations.
234 * This function cannot be used to add a new class or printer queue,
235 * it only adds a new container of saved options for the named
236 * destination or instance.
238 * If the named destination already exists, the destination list is
239 * returned unchanged. Adding a new instance of a destination creates
240 * a copy of that destination's options.
242 * Use the @link cupsSaveDests@ function to save the updated list of
243 * destinations to the user's lpoptions file.
246 int /* O - New number of destinations */
247 cupsAddDest(const char *name
, /* I - Destination name */
248 const char *instance
, /* I - Instance name or @code NULL@ for none/primary */
249 int num_dests
, /* I - Number of destinations */
250 cups_dest_t
**dests
) /* IO - Destinations */
252 int i
; /* Looping var */
253 cups_dest_t
*dest
; /* Destination pointer */
254 cups_dest_t
*parent
= NULL
; /* Parent destination */
255 cups_option_t
*doption
, /* Current destination option */
256 *poption
; /* Current parent option */
262 if (!cupsGetDest(name
, instance
, num_dests
, *dests
))
264 if (instance
&& !cupsGetDest(name
, NULL
, num_dests
, *dests
))
267 dest
= cups_add_dest(name
, instance
, &num_dests
, dests
);
270 * Find the base dest again now the array has been realloc'd.
273 parent
= cupsGetDest(name
, NULL
, num_dests
, *dests
);
275 if (instance
&& parent
&& parent
->num_options
> 0)
278 * Copy options from parent...
281 dest
->options
= calloc(sizeof(cups_option_t
), parent
->num_options
);
285 dest
->num_options
= parent
->num_options
;
287 for (i
= dest
->num_options
, doption
= dest
->options
,
288 poption
= parent
->options
;
290 i
--, doption
++, poption
++)
292 doption
->name
= _cupsStrRetain(poption
->name
);
293 doption
->value
= _cupsStrRetain(poption
->value
);
305 * '_cupsAppleCopyDefaultPaperID()' - Get the default paper ID.
308 CFStringRef
/* O - Default paper ID */
309 _cupsAppleCopyDefaultPaperID(void)
311 return (CFPreferencesCopyAppValue(kDefaultPaperIDKey
,
312 kCUPSPrintingPrefs
));
317 * '_cupsAppleCopyDefaultPrinter()' - Get the default printer at this location.
320 CFStringRef
/* O - Default printer name */
321 _cupsAppleCopyDefaultPrinter(void)
323 CFStringRef network
; /* Network location */
324 CFArrayRef locations
; /* Location array */
325 CFStringRef locprinter
; /* Current printer */
329 * Use location-based defaults only if "use last printer" is selected in the
330 * system preferences...
333 if (!_cupsAppleGetUseLastPrinter())
335 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Not using last printer as "
341 * Get the current location...
344 if ((network
= appleCopyNetwork()) == NULL
)
346 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Unable to get current "
352 * Lookup the network in the preferences...
355 if ((locations
= appleCopyLocations()) == NULL
)
358 * Missing or bad location array, so no location-based default...
361 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Missing or bad last used "
369 DEBUG_printf(("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.",
370 (int)CFArrayGetCount(locations
)));
372 if ((locprinter
= appleGetPrinter(locations
, network
, NULL
)) != NULL
)
373 CFRetain(locprinter
);
376 CFRelease(locations
);
383 * '_cupsAppleGetUseLastPrinter()' - Get whether to use the last used printer.
386 int /* O - 1 to use last printer, 0 otherwise */
387 _cupsAppleGetUseLastPrinter(void)
389 Boolean uselast
, /* Use last printer preference value */
390 uselast_set
; /* Valid is set? */
393 if (getenv("CUPS_DISABLE_APPLE_DEFAULT"))
396 uselast
= CFPreferencesGetAppBooleanValue(kUseLastPrinter
,
407 * '_cupsAppleSetDefaultPaperID()' - Set the default paper id.
411 _cupsAppleSetDefaultPaperID(
412 CFStringRef name
) /* I - New paper ID */
414 CFPreferencesSetAppValue(kDefaultPaperIDKey
, name
, kCUPSPrintingPrefs
);
415 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
416 notify_post("com.apple.printerPrefsChange");
421 * '_cupsAppleSetDefaultPrinter()' - Set the default printer for this location.
425 _cupsAppleSetDefaultPrinter(
426 CFStringRef name
) /* I - Default printer/class name */
428 CFStringRef network
; /* Current network */
429 CFArrayRef locations
; /* Old locations array */
430 CFIndex locindex
; /* Index in locations array */
431 CFStringRef locprinter
; /* Current printer */
432 CFMutableArrayRef newlocations
; /* New locations array */
433 CFMutableDictionaryRef newlocation
; /* New location */
437 * Get the current location...
440 if ((network
= appleCopyNetwork()) == NULL
)
442 DEBUG_puts("1_cupsAppleSetDefaultPrinter: Unable to get current network...");
447 * Lookup the network in the preferences...
450 if ((locations
= appleCopyLocations()) != NULL
)
451 locprinter
= appleGetPrinter(locations
, network
, &locindex
);
458 if (!locprinter
|| CFStringCompare(locprinter
, name
, 0) != kCFCompareEqualTo
)
461 * Need to change the locations array...
466 newlocations
= CFArrayCreateMutableCopy(kCFAllocatorDefault
, 0,
470 CFArrayRemoveValueAtIndex(newlocations
, locindex
);
473 newlocations
= CFArrayCreateMutable(kCFAllocatorDefault
, 0,
474 &kCFTypeArrayCallBacks
);
476 newlocation
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
477 &kCFTypeDictionaryKeyCallBacks
,
478 &kCFTypeDictionaryValueCallBacks
);
480 if (newlocation
&& newlocations
)
483 * Put the new location at the front of the array...
486 CFDictionaryAddValue(newlocation
, kLocationNetworkKey
, network
);
487 CFDictionaryAddValue(newlocation
, kLocationPrinterIDKey
, name
);
488 CFArrayInsertValueAtIndex(newlocations
, 0, newlocation
);
491 * Limit the number of locations to 10...
494 while (CFArrayGetCount(newlocations
) > 10)
495 CFArrayRemoveValueAtIndex(newlocations
, 10);
498 * Push the changes out...
501 CFPreferencesSetAppValue(kLastUsedPrintersKey
, newlocations
,
503 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
504 notify_post("com.apple.printerPrefsChange");
508 CFRelease(newlocations
);
511 CFRelease(newlocation
);
515 CFRelease(locations
);
522 * '_cupsAppleSetUseLastPrinter()' - Set whether to use the last used printer.
526 _cupsAppleSetUseLastPrinter(
527 int uselast
) /* O - 1 to use last printer, 0 otherwise */
529 CFPreferencesSetAppValue(kUseLastPrinter
,
530 uselast
? kCFBooleanTrue
: kCFBooleanFalse
,
532 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
533 notify_post("com.apple.printerPrefsChange");
535 #endif /* __APPLE__ */
539 * 'cupsConnectDest()' - Connect to the server for a destination.
541 * Connect to the destination, returning a new http_t connection object and
542 * optionally the resource path to use for the destination. These calls will
543 * block until a connection is made, the timeout expires, the integer pointed
544 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
545 * The caller is responsible for calling httpClose() on the returned object.
547 * @since CUPS 1.6/OS X 10.8@
550 http_t
* /* O - Connection to server or @code NULL@ */
552 cups_dest_t
*dest
, /* I - Destination */
553 unsigned flags
, /* I - Connection flags */
554 int msec
, /* I - Timeout in milliseconds */
555 int *cancel
, /* I - Pointer to "cancel" variable */
556 char *resource
, /* I - Resource buffer */
557 size_t resourcesize
, /* I - Size of resource buffer */
558 cups_dest_cb_t cb
, /* I - Callback function */
559 void *user_data
) /* I - User data pointer */
561 const char *uri
; /* Printer URI */
562 char scheme
[32], /* URI scheme */
563 userpass
[256], /* Username and password (unused) */
564 hostname
[256], /* Hostname */
565 tempresource
[1024]; /* Temporary resource buffer */
566 int port
; /* Port number */
567 char portstr
[16]; /* Port number string */
568 http_encryption_t encryption
; /* Encryption to use */
569 http_addrlist_t
*addrlist
; /* Address list for server */
570 http_t
*http
; /* Connection to server */
574 * Range check input...
582 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
586 if (!resource
|| resourcesize
< 1)
588 resource
= tempresource
;
589 resourcesize
= sizeof(tempresource
);
593 * Grab the printer URI...
596 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
,
597 dest
->options
)) == NULL
)
599 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(ENOENT
), 0);
602 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
609 if (strstr(uri
, "._tcp"))
611 if ((uri
= cups_dnssd_resolve(dest
, uri
, msec
, cancel
, cb
,
615 #endif /* HAVE_DNSSD */
617 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
618 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
619 &port
, resource
, resourcesize
) < HTTP_URI_OK
)
621 _cupsSetError(IPP_INTERNAL_ERROR
, _("Bad printer URI."), 1);
624 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
631 * Lookup the address for the server...
635 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
,
638 snprintf(portstr
, sizeof(portstr
), "%d", port
);
640 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, portstr
)) == NULL
)
643 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
649 if (cancel
&& *cancel
)
651 httpAddrFreeList(addrlist
);
654 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CANCELED
,
661 * Create the HTTP object pointing to the server referenced by the URI...
664 if (!strcmp(scheme
, "ipps") || port
== 443)
665 encryption
= HTTP_ENCRYPT_ALWAYS
;
667 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
669 http
= _httpCreate(hostname
, port
, addrlist
, encryption
, AF_UNSPEC
);
672 * Connect if requested...
675 if (flags
& CUPS_DEST_FLAGS_UNCONNECTED
)
678 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
, dest
);
683 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
,
686 if (!httpReconnect2(http
, msec
, cancel
) && cb
)
688 if (cancel
&& *cancel
)
690 CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
, dest
);
692 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
696 (*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, dest
);
705 * 'cupsConnectDestBlock()' - Connect to the server for a destination.
707 * Connect to the destination, returning a new http_t connection object and
708 * optionally the resource path to use for the destination. These calls will
709 * block until a connection is made, the timeout expires, the integer pointed
710 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
711 * The caller is responsible for calling httpClose() on the returned object.
713 * @since CUPS 1.6/OS X 10.8@
716 http_t
* /* O - Connection to server or @code NULL@ */
717 cupsConnectDestBlock(
718 cups_dest_t
*dest
, /* I - Destination */
719 unsigned flags
, /* I - Connection flags */
720 int msec
, /* I - Timeout in milliseconds */
721 int *cancel
, /* I - Pointer to "cancel" variable */
722 char *resource
, /* I - Resource buffer */
723 size_t resourcesize
, /* I - Size of resource buffer */
724 cups_dest_block_t block
) /* I - Callback block */
726 return (cupsConnectDest(dest
, flags
, msec
, cancel
, resource
, resourcesize
,
727 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
729 #endif /* __BLOCKS__ */
733 * 'cupsCopyDest()' - Copy a destination.
735 * Make a copy of the destination to an array of destinations (or just a single
736 * copy) - for use with the cupsEnumDests* functions. The caller is responsible
737 * for calling cupsFreeDests() on the returned object(s).
739 * @since CUPS 1.6/OS X 10.8@
743 cupsCopyDest(cups_dest_t
*dest
,
747 int i
; /* Looping var */
748 cups_dest_t
*new_dest
; /* New destination pointer */
749 cups_option_t
*new_option
, /* Current destination option */
750 *option
; /* Current parent option */
754 * Range check input...
757 if (!dest
|| num_dests
< 0 || !dests
)
761 * See if the destination already exists...
764 if ((new_dest
= cupsGetDest(dest
->name
, dest
->instance
, num_dests
,
768 * Protect against copying destination to itself...
771 if (new_dest
== dest
)
775 * Otherwise, free the options...
778 cupsFreeOptions(new_dest
->num_options
, new_dest
->options
);
780 new_dest
->num_options
= 0;
781 new_dest
->options
= NULL
;
784 new_dest
= cups_add_dest(dest
->name
, dest
->instance
, &num_dests
, dests
);
788 if ((new_dest
->options
= calloc(sizeof(cups_option_t
),
789 dest
->num_options
)) == NULL
)
790 return (cupsRemoveDest(dest
->name
, dest
->instance
, num_dests
, dests
));
792 new_dest
->num_options
= dest
->num_options
;
794 for (i
= dest
->num_options
, option
= dest
->options
,
795 new_option
= new_dest
->options
;
797 i
--, option
++, new_option
++)
799 new_option
->name
= _cupsStrRetain(option
->name
);
800 new_option
->value
= _cupsStrRetain(option
->value
);
809 * 'cupsEnumDests()' - Enumerate available destinations with a callback function.
811 * Destinations are enumerated from one or more sources. The callback function
812 * receives the @code user_data@ pointer, destination name, instance, number of
813 * options, and options which can be used as input to the @link cupsAddDest@
814 * function. The function must return 1 to continue enumeration or 0 to stop.
816 * Enumeration happens on the current thread and does not return until all
817 * destinations have been enumerated or the callback function returns 0.
819 * @since CUPS 1.6/OS X 10.8@
822 int /* O - 1 on success, 0 on failure */
824 unsigned flags
, /* I - Enumeration flags */
825 int msec
, /* I - Timeout in milliseconds,
826 * -1 for indefinite */
827 int *cancel
, /* I - Pointer to "cancel" variable */
828 cups_ptype_t type
, /* I - Printer type bits */
829 cups_ptype_t mask
, /* I - Mask for printer type bits */
830 cups_dest_cb_t cb
, /* I - Callback function */
831 void *user_data
) /* I - User data */
833 int i
, /* Looping var */
834 num_dests
; /* Number of destinations */
835 cups_dest_t
*dests
= NULL
, /* Destinations */
836 *dest
; /* Current destination */
838 int nfds
, /* Number of files responded */
839 count
, /* Number of queries started */
840 remaining
; /* Remainder of timeout */
841 _cups_dnssd_data_t data
; /* Data for callback */
842 _cups_dnssd_device_t
*device
; /* Current device */
843 int main_fd
; /* File descriptor for lookups */
844 DNSServiceRef ipp_ref
, /* IPP browser */
845 local_ipp_ref
; /* Local IPP browser */
847 DNSServiceRef ipps_ref
, /* IPPS browser */
848 local_ipps_ref
; /* Local IPPS browser */
849 # endif /* HAVE_SSL */
851 struct pollfd pfd
; /* Polling data */
853 fd_set input
; /* Input set for select() */
854 struct timeval timeout
; /* Timeout for select() */
855 # endif /* HAVE_POLL */
856 #endif /* HAVE_DNSSD */
860 * Range check input...
869 * Get the list of local printers and pass them to the callback function...
872 num_dests
= _cupsGetDests(CUPS_HTTP_DEFAULT
, CUPS_GET_PRINTERS
, NULL
, &dests
,
875 for (i
= num_dests
, dest
= dests
;
876 i
> 0 && (!cancel
|| !*cancel
);
878 if (!(*cb
)(user_data
, i
> 1 ? CUPS_DEST_FLAGS_MORE
: CUPS_DEST_FLAGS_NONE
,
882 cupsFreeDests(num_dests
, dests
);
884 if (i
> 0 || msec
== 0)
889 * Get Bonjour-shared printers...
894 data
.devices
= cupsArrayNew3((cups_array_func_t
)cups_dnssd_compare_devices
,
896 (cups_afree_func_t
)cups_dnssd_free_device
);
898 if (DNSServiceCreateConnection(&data
.main_ref
) != kDNSServiceErr_NoError
)
901 main_fd
= DNSServiceRefSockFD(data
.main_ref
);
903 ipp_ref
= data
.main_ref
;
904 DNSServiceBrowse(&ipp_ref
, kDNSServiceFlagsShareConnection
, 0,
905 "_ipp._tcp,_cups", NULL
,
906 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
908 local_ipp_ref
= data
.main_ref
;
909 DNSServiceBrowse(&local_ipp_ref
, kDNSServiceFlagsShareConnection
,
910 kDNSServiceInterfaceIndexLocalOnly
,
911 "_ipp._tcp,_cups", NULL
,
912 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
915 ipps_ref
= data
.main_ref
;
916 DNSServiceBrowse(&ipps_ref
, kDNSServiceFlagsShareConnection
, 0,
917 "_ipps._tcp,_cups", NULL
,
918 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
920 local_ipps_ref
= data
.main_ref
;
921 DNSServiceBrowse(&local_ipps_ref
, kDNSServiceFlagsShareConnection
,
922 kDNSServiceInterfaceIndexLocalOnly
,
923 "_ipps._tcp,_cups", NULL
,
924 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
925 # endif /* HAVE_SSL */
932 while (remaining
> 0 && (!cancel
|| !*cancel
))
942 nfds
= poll(&pfd
, 1, remaining
> 250 ? 250 : remaining
);
946 FD_SET(main_fd
, &input
);
949 timeout
.tv_usec
= remaining
> 250 ? 250000 : remaining
* 1000;
951 nfds
= select(main_fd
+ 1, &input
, NULL
, NULL
, &timeout
);
952 # endif /* HAVE_POLL */
955 DNSServiceProcessResult(data
.main_ref
);
959 for (device
= (_cups_dnssd_device_t
*)cupsArrayFirst(data
.devices
),
962 device
= (_cups_dnssd_device_t
*)cupsArrayNext(data
.devices
))
967 if (!device
->ref
&& device
->state
== _CUPS_DNSSD_NEW
)
969 device
->ref
= data
.main_ref
;
971 DEBUG_printf(("1cupsEnumDests: Querying '%s'.", device
->fullName
));
973 if (DNSServiceQueryRecord(&(device
->ref
),
974 kDNSServiceFlagsShareConnection
,
978 (DNSServiceQueryRecordReply
)cups_dnssd_query_cb
,
979 &data
) == kDNSServiceErr_NoError
)
986 device
->state
= _CUPS_DNSSD_ERROR
;
988 DEBUG_puts("1cupsEnumDests: Query failed.");
991 else if (device
->ref
&& device
->state
== _CUPS_DNSSD_PENDING
)
993 if (!(*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, &device
->dest
))
999 device
->state
= _CUPS_DNSSD_ACTIVE
;
1004 cupsArrayDelete(data
.devices
);
1006 DNSServiceRefDeallocate(ipp_ref
);
1007 DNSServiceRefDeallocate(local_ipp_ref
);
1010 DNSServiceRefDeallocate(ipp_ref
);
1011 DNSServiceRefDeallocate(local_ipp_ref
);
1012 # endif /* HAVE_SSL */
1014 DNSServiceRefDeallocate(data
.main_ref
);
1015 #endif /* HAVE_DNSSD */
1023 * 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
1025 * Destinations are enumerated from one or more sources. The block receives the
1026 * destination name, instance, number of options, and options which can be used
1027 * as input to the @link cupsAddDest@ function. The block must return 1 to
1028 * continue enumeration or 0 to stop.
1030 * Enumeration happens on the current thread and does not return until all
1031 * destinations have been enumerated or the block returns 0.
1033 * @since CUPS 1.6/OS X 10.8@
1036 int /* O - 1 on success, 0 on failure */
1038 unsigned flags
, /* I - Enumeration flags */
1039 int timeout
, /* I - Timeout in milliseconds, 0 for indefinite */
1040 int *cancel
, /* I - Pointer to "cancel" variable */
1041 cups_ptype_t type
, /* I - Printer type bits */
1042 cups_ptype_t mask
, /* I - Mask for printer type bits */
1043 cups_dest_block_t block
) /* I - Block */
1045 return (cupsEnumDests(flags
, timeout
, cancel
, type
, mask
,
1046 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
1048 # endif /* __BLOCKS__ */
1052 * 'cupsFreeDests()' - Free the memory used by the list of destinations.
1056 cupsFreeDests(int num_dests
, /* I - Number of destinations */
1057 cups_dest_t
*dests
) /* I - Destinations */
1059 int i
; /* Looping var */
1060 cups_dest_t
*dest
; /* Current destination */
1063 if (num_dests
== 0 || dests
== NULL
)
1066 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1068 _cupsStrFree(dest
->name
);
1069 _cupsStrFree(dest
->instance
);
1071 cupsFreeOptions(dest
->num_options
, dest
->options
);
1079 * 'cupsGetDest()' - Get the named destination from the list.
1081 * Use the @link cupsGetDests@ or @link cupsGetDests2@ functions to get a
1082 * list of supported destinations for the current user.
1085 cups_dest_t
* /* O - Destination pointer or @code NULL@ */
1086 cupsGetDest(const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1087 const char *instance
, /* I - Instance name or @code NULL@ */
1088 int num_dests
, /* I - Number of destinations */
1089 cups_dest_t
*dests
) /* I - Destinations */
1091 int diff
, /* Result of comparison */
1092 match
; /* Matching index */
1095 if (num_dests
<= 0 || !dests
)
1101 * NULL name for default printer.
1104 while (num_dests
> 0)
1106 if (dests
->is_default
)
1116 * Lookup name and optionally the instance...
1119 match
= cups_find_dest(name
, instance
, num_dests
, dests
, -1, &diff
);
1122 return (dests
+ match
);
1130 * '_cupsGetDestResource()' - Get the resource path and URI for a destination.
1133 const char * /* O - Printer URI */
1134 _cupsGetDestResource(
1135 cups_dest_t
*dest
, /* I - Destination */
1136 char *resource
, /* I - Resource buffer */
1137 size_t resourcesize
) /* I - Size of resource buffer */
1139 const char *uri
; /* Printer URI */
1140 char scheme
[32], /* URI scheme */
1141 userpass
[256], /* Username and password (unused) */
1142 hostname
[256]; /* Hostname */
1143 int port
; /* Port number */
1147 * Range check input...
1150 if (!dest
|| !resource
|| resourcesize
< 1)
1155 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
1160 * Grab the printer URI...
1163 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
,
1164 dest
->options
)) == NULL
)
1169 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(ENOENT
), 0);
1175 if (strstr(uri
, "._tcp"))
1177 if ((uri
= cups_dnssd_resolve(dest
, uri
, 5000, NULL
, NULL
, NULL
)) == NULL
)
1180 #endif /* HAVE_DNSSD */
1182 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
1183 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
1184 &port
, resource
, resourcesize
) < HTTP_URI_OK
)
1186 _cupsSetError(IPP_INTERNAL_ERROR
, _("Bad printer URI."), 1);
1196 * '_cupsGetDests()' - Get destinations from a server.
1198 * "op" is CUPS_GET_PRINTERS to get a full list, CUPS_GET_DEFAULT to get the
1199 * system-wide default printer, or IPP_GET_PRINTER_ATTRIBUTES for a known
1202 * "name" is the name of an existing printer and is only used when "op" is
1203 * IPP_GET_PRINTER_ATTRIBUTES.
1205 * "dest" is initialized to point to the array of destinations.
1207 * 0 is returned if there are no printers, no default printer, or the named
1208 * printer does not exist, respectively.
1210 * Free the memory used by the destination array using the @link cupsFreeDests@
1213 * Note: On OS X this function also gets the default paper from the system
1214 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1215 * options array for each destination that supports it.
1218 int /* O - Number of destinations */
1219 _cupsGetDests(http_t
*http
, /* I - Connection to server or
1220 * @code CUPS_HTTP_DEFAULT@ */
1221 ipp_op_t op
, /* I - IPP operation */
1222 const char *name
, /* I - Name of destination */
1223 cups_dest_t
**dests
, /* IO - Destinations */
1224 cups_ptype_t type
, /* I - Printer type bits */
1225 cups_ptype_t mask
) /* I - Printer type mask */
1227 int num_dests
= 0; /* Number of destinations */
1228 cups_dest_t
*dest
; /* Current destination */
1229 ipp_t
*request
, /* IPP Request */
1230 *response
; /* IPP Response */
1231 ipp_attribute_t
*attr
; /* Current attribute */
1232 const char *printer_name
; /* printer-name attribute */
1233 char uri
[1024]; /* printer-uri value */
1234 int num_options
; /* Number of options */
1235 cups_option_t
*options
; /* Options */
1237 char media_default
[41]; /* Default paper size */
1238 #endif /* __APPLE__ */
1239 char optname
[1024], /* Option name */
1240 value
[2048], /* Option value */
1241 *ptr
; /* Pointer into name/value */
1242 static const char * const pattrs
[] = /* Attributes we're interested in */
1244 "auth-info-required",
1246 "job-sheets-default",
1247 "marker-change-time",
1249 "marker-high-levels",
1251 "marker-low-levels",
1257 #endif /* __APPLE__ */
1261 "printer-is-accepting-jobs",
1262 "printer-is-shared",
1264 "printer-make-and-model",
1267 "printer-state-change-time",
1268 "printer-state-reasons",
1270 "printer-uri-supported"
1276 * Get the default paper size...
1279 appleGetPaperSize(media_default
, sizeof(media_default
));
1280 #endif /* __APPLE__ */
1283 * Build a CUPS_GET_PRINTERS or IPP_GET_PRINTER_ATTRIBUTES request, which
1284 * require the following attributes:
1286 * attributes-charset
1287 * attributes-natural-language
1288 * requesting-user-name
1289 * printer-uri [for IPP_GET_PRINTER_ATTRIBUTES]
1292 request
= ippNewRequest(op
);
1294 ippAddStrings(request
, IPP_TAG_OPERATION
, IPP_TAG_KEYWORD
,
1295 "requested-attributes", sizeof(pattrs
) / sizeof(pattrs
[0]),
1298 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
,
1299 "requesting-user-name", NULL
, cupsUser());
1301 if (name
&& op
!= CUPS_GET_DEFAULT
)
1303 httpAssembleURIf(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
), "ipp", NULL
,
1304 "localhost", ippPort(), "/printers/%s", name
);
1305 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
,
1310 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type",
1312 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type-mask",
1317 * Do the request and get back a response...
1320 if ((response
= cupsDoRequest(http
, request
, "/")) != NULL
)
1322 for (attr
= response
->attrs
; attr
!= NULL
; attr
= attr
->next
)
1325 * Skip leading attributes until we hit a printer...
1328 while (attr
!= NULL
&& attr
->group_tag
!= IPP_TAG_PRINTER
)
1335 * Pull the needed attributes from this printer...
1338 printer_name
= NULL
;
1342 for (; attr
&& attr
->group_tag
== IPP_TAG_PRINTER
; attr
= attr
->next
)
1344 if (attr
->value_tag
!= IPP_TAG_INTEGER
&&
1345 attr
->value_tag
!= IPP_TAG_ENUM
&&
1346 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
1347 attr
->value_tag
!= IPP_TAG_TEXT
&&
1348 attr
->value_tag
!= IPP_TAG_TEXTLANG
&&
1349 attr
->value_tag
!= IPP_TAG_NAME
&&
1350 attr
->value_tag
!= IPP_TAG_NAMELANG
&&
1351 attr
->value_tag
!= IPP_TAG_KEYWORD
&&
1352 attr
->value_tag
!= IPP_TAG_RANGE
&&
1353 attr
->value_tag
!= IPP_TAG_URI
)
1356 if (!strcmp(attr
->name
, "auth-info-required") ||
1357 !strcmp(attr
->name
, "device-uri") ||
1358 !strcmp(attr
->name
, "marker-change-time") ||
1359 !strcmp(attr
->name
, "marker-colors") ||
1360 !strcmp(attr
->name
, "marker-high-levels") ||
1361 !strcmp(attr
->name
, "marker-levels") ||
1362 !strcmp(attr
->name
, "marker-low-levels") ||
1363 !strcmp(attr
->name
, "marker-message") ||
1364 !strcmp(attr
->name
, "marker-names") ||
1365 !strcmp(attr
->name
, "marker-types") ||
1366 !strcmp(attr
->name
, "printer-commands") ||
1367 !strcmp(attr
->name
, "printer-info") ||
1368 !strcmp(attr
->name
, "printer-is-shared") ||
1369 !strcmp(attr
->name
, "printer-make-and-model") ||
1370 !strcmp(attr
->name
, "printer-state") ||
1371 !strcmp(attr
->name
, "printer-state-change-time") ||
1372 !strcmp(attr
->name
, "printer-type") ||
1373 !strcmp(attr
->name
, "printer-is-accepting-jobs") ||
1374 !strcmp(attr
->name
, "printer-location") ||
1375 !strcmp(attr
->name
, "printer-state-reasons") ||
1376 !strcmp(attr
->name
, "printer-uri-supported"))
1379 * Add a printer description attribute...
1382 num_options
= cupsAddOption(attr
->name
,
1383 cups_make_string(attr
, value
,
1385 num_options
, &options
);
1388 else if (!strcmp(attr
->name
, "media-supported"))
1391 * See if we can set a default media size...
1394 int i
; /* Looping var */
1396 for (i
= 0; i
< attr
->num_values
; i
++)
1397 if (!_cups_strcasecmp(media_default
, attr
->values
[i
].string
.text
))
1399 num_options
= cupsAddOption("media", media_default
, num_options
,
1404 #endif /* __APPLE__ */
1405 else if (!strcmp(attr
->name
, "printer-name") &&
1406 attr
->value_tag
== IPP_TAG_NAME
)
1407 printer_name
= attr
->values
[0].string
.text
;
1408 else if (strncmp(attr
->name
, "notify-", 7) &&
1409 (attr
->value_tag
== IPP_TAG_BOOLEAN
||
1410 attr
->value_tag
== IPP_TAG_ENUM
||
1411 attr
->value_tag
== IPP_TAG_INTEGER
||
1412 attr
->value_tag
== IPP_TAG_KEYWORD
||
1413 attr
->value_tag
== IPP_TAG_NAME
||
1414 attr
->value_tag
== IPP_TAG_RANGE
) &&
1415 (ptr
= strstr(attr
->name
, "-default")) != NULL
)
1418 * Add a default option...
1421 strlcpy(optname
, attr
->name
, sizeof(optname
));
1422 optname
[ptr
- attr
->name
] = '\0';
1424 if (_cups_strcasecmp(optname
, "media") ||
1425 !cupsGetOption("media", num_options
, options
))
1426 num_options
= cupsAddOption(optname
,
1427 cups_make_string(attr
, value
,
1429 num_options
, &options
);
1434 * See if we have everything needed...
1439 cupsFreeOptions(num_options
, options
);
1447 if ((dest
= cups_add_dest(printer_name
, NULL
, &num_dests
, dests
)) != NULL
)
1449 dest
->num_options
= num_options
;
1450 dest
->options
= options
;
1453 cupsFreeOptions(num_options
, options
);
1459 ippDelete(response
);
1463 * Return the count...
1471 * 'cupsGetDests()' - Get the list of destinations from the default server.
1473 * Starting with CUPS 1.2, the returned list of destinations include the
1474 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1475 * printer-make-and-model, printer-state, printer-state-change-time,
1476 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1477 * adds the marker-change-time, marker-colors, marker-high-levels,
1478 * marker-levels, marker-low-levels, marker-message, marker-names,
1479 * marker-types, and printer-commands attributes as well.
1481 * Use the @link cupsFreeDests@ function to free the destination list and
1482 * the @link cupsGetDest@ function to find a particular destination.
1485 int /* O - Number of destinations */
1486 cupsGetDests(cups_dest_t
**dests
) /* O - Destinations */
1488 return (cupsGetDests2(CUPS_HTTP_DEFAULT
, dests
));
1493 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1495 * Starting with CUPS 1.2, the returned list of destinations include the
1496 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1497 * printer-make-and-model, printer-state, printer-state-change-time,
1498 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1499 * adds the marker-change-time, marker-colors, marker-high-levels,
1500 * marker-levels, marker-low-levels, marker-message, marker-names,
1501 * marker-types, and printer-commands attributes as well.
1503 * Use the @link cupsFreeDests@ function to free the destination list and
1504 * the @link cupsGetDest@ function to find a particular destination.
1506 * @since CUPS 1.1.21/OS X 10.4@
1509 int /* O - Number of destinations */
1510 cupsGetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1511 cups_dest_t
**dests
) /* O - Destinations */
1513 int i
; /* Looping var */
1514 int num_dests
; /* Number of destinations */
1515 cups_dest_t
*dest
; /* Destination pointer */
1516 const char *home
; /* HOME environment variable */
1517 char filename
[1024]; /* Local ~/.cups/lpoptions file */
1518 const char *defprinter
; /* Default printer */
1519 char name
[1024], /* Copy of printer name */
1520 *instance
, /* Pointer to instance name */
1521 *user_default
; /* User default printer */
1522 int num_reals
; /* Number of real queues */
1523 cups_dest_t
*reals
; /* Real queues */
1524 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1528 * Range check the input...
1533 _cupsSetError(IPP_INTERNAL_ERROR
, _("Bad NULL dests pointer"), 1);
1538 * Grab the printers and classes...
1541 *dests
= (cups_dest_t
*)0;
1542 num_dests
= _cupsGetDests(http
, CUPS_GET_PRINTERS
, NULL
, dests
, 0, 0);
1544 if (cupsLastError() >= IPP_REDIRECTION_OTHER_SITE
)
1546 cupsFreeDests(num_dests
, *dests
);
1547 *dests
= (cups_dest_t
*)0;
1552 * Make a copy of the "real" queues for a later sanity check...
1557 num_reals
= num_dests
;
1558 reals
= calloc(num_reals
, sizeof(cups_dest_t
));
1561 memcpy(reals
, *dests
, num_reals
* sizeof(cups_dest_t
));
1572 * Grab the default destination...
1575 if ((user_default
= _cupsUserDefault(name
, sizeof(name
))) != NULL
)
1577 else if ((defprinter
= cupsGetDefault2(http
)) != NULL
)
1579 strlcpy(name
, defprinter
, sizeof(name
));
1586 * Separate printer and instance name...
1589 if ((instance
= strchr(name
, '/')) != NULL
)
1593 * Lookup the printer and instance and make it the default...
1596 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) != NULL
)
1597 dest
->is_default
= 1;
1603 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
1606 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1607 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1610 if ((home
= getenv("HOME")) != NULL
)
1612 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1614 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1619 * Validate the current default destination - this prevents old
1620 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
1621 * pointing to a non-existent printer or class...
1627 * See if we have a default printer...
1630 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, *dests
)) != NULL
)
1633 * Have a default; see if it is real...
1636 dest
= cupsGetDest(dest
->name
, NULL
, num_reals
, reals
);
1640 * If dest is NULL, then no default (that exists) is set, so we
1641 * need to set a default if one exists...
1644 if (dest
== NULL
&& defprinter
!= NULL
)
1646 for (i
= 0; i
< num_dests
; i
++)
1647 (*dests
)[i
].is_default
= 0;
1649 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) != NULL
)
1650 dest
->is_default
= 1;
1661 * Return the number of destinations...
1665 _cupsSetError(IPP_OK
, NULL
, 0);
1672 * 'cupsGetNamedDest()' - Get options for the named destination.
1674 * This function is optimized for retrieving a single destination and should
1675 * be used instead of @link cupsGetDests@ and @link cupsGetDest@ when you either
1676 * know the name of the destination or want to print to the default destination.
1677 * If @code NULL@ is returned, the destination does not exist or there is no
1678 * default destination.
1680 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
1681 * server will be used.
1683 * If "name" is @code NULL@, the default printer for the current user will be
1686 * The returned destination must be freed using @link cupsFreeDests@ with a
1687 * "num_dests" value of 1.
1689 * @since CUPS 1.4/OS X 10.6@
1692 cups_dest_t
* /* O - Destination or @code NULL@ */
1693 cupsGetNamedDest(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1694 const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1695 const char *instance
) /* I - Instance name or @code NULL@ */
1697 cups_dest_t
*dest
; /* Destination */
1698 char filename
[1024], /* Path to lpoptions */
1699 defname
[256]; /* Default printer name */
1700 const char *home
= getenv("HOME"); /* Home directory */
1701 int set_as_default
= 0; /* Set returned destination as default */
1702 ipp_op_t op
= IPP_GET_PRINTER_ATTRIBUTES
;
1703 /* IPP operation to get server ops */
1704 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1708 * If "name" is NULL, find the default destination...
1714 name
= _cupsUserDefault(defname
, sizeof(defname
));
1718 char *ptr
; /* Temporary pointer... */
1720 if ((ptr
= strchr(defname
, '/')) != NULL
)
1731 * No default in the environment, try the user's lpoptions files...
1734 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1736 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1742 * Still not there? Try the system lpoptions file...
1745 snprintf(filename
, sizeof(filename
), "%s/lpoptions",
1746 cg
->cups_serverroot
);
1747 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1753 * No locally-set default destination, ask the server...
1756 op
= CUPS_GET_DEFAULT
;
1761 * Get the printer's attributes...
1764 if (!_cupsGetDests(http
, op
, name
, &dest
, 0, 0))
1766 if (op
== CUPS_GET_DEFAULT
|| (name
&& !set_as_default
))
1770 * The default printer from environment variables or from a
1771 * configuration file does not exist. Find out the real default.
1774 if (!_cupsGetDests(http
, CUPS_GET_DEFAULT
, NULL
, &dest
, 0, 0))
1779 dest
->instance
= _cupsStrAlloc(instance
);
1782 dest
->is_default
= 1;
1785 * Then add local options...
1788 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1789 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
1793 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1795 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
1799 * Return the result...
1807 * 'cupsRemoveDest()' - Remove a destination from the destination list.
1809 * Removing a destination/instance does not delete the class or printer
1810 * queue, merely the lpoptions for that destination/instance. Use the
1811 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
1812 * options for the user.
1814 * @since CUPS 1.3/OS X 10.5@
1817 int /* O - New number of destinations */
1818 cupsRemoveDest(const char *name
, /* I - Destination name */
1819 const char *instance
, /* I - Instance name or @code NULL@ */
1820 int num_dests
, /* I - Number of destinations */
1821 cups_dest_t
**dests
) /* IO - Destinations */
1823 int i
; /* Index into destinations */
1824 cups_dest_t
*dest
; /* Pointer to destination */
1828 * Find the destination...
1831 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
1838 _cupsStrFree(dest
->name
);
1839 _cupsStrFree(dest
->instance
);
1840 cupsFreeOptions(dest
->num_options
, dest
->options
);
1843 * Remove the destination from the array...
1851 memmove(dest
, dest
+ 1, (num_dests
- i
) * sizeof(cups_dest_t
));
1858 * 'cupsSetDefaultDest()' - Set the default destination.
1860 * @since CUPS 1.3/OS X 10.5@
1865 const char *name
, /* I - Destination name */
1866 const char *instance
, /* I - Instance name or @code NULL@ */
1867 int num_dests
, /* I - Number of destinations */
1868 cups_dest_t
*dests
) /* I - Destinations */
1870 int i
; /* Looping var */
1871 cups_dest_t
*dest
; /* Current destination */
1875 * Range check input...
1878 if (!name
|| num_dests
<= 0 || !dests
)
1882 * Loop through the array and set the "is_default" flag for the matching
1886 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1887 dest
->is_default
= !_cups_strcasecmp(name
, dest
->name
) &&
1888 ((!instance
&& !dest
->instance
) ||
1889 (instance
&& dest
->instance
&&
1890 !_cups_strcasecmp(instance
, dest
->instance
)));
1895 * 'cupsSetDests()' - Save the list of destinations for the default server.
1897 * This function saves the destinations to /etc/cups/lpoptions when run
1898 * as root and ~/.cups/lpoptions when run as a normal user.
1902 cupsSetDests(int num_dests
, /* I - Number of destinations */
1903 cups_dest_t
*dests
) /* I - Destinations */
1905 cupsSetDests2(CUPS_HTTP_DEFAULT
, num_dests
, dests
);
1910 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
1912 * This function saves the destinations to /etc/cups/lpoptions when run
1913 * as root and ~/.cups/lpoptions when run as a normal user.
1915 * @since CUPS 1.1.21/OS X 10.4@
1918 int /* O - 0 on success, -1 on error */
1919 cupsSetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1920 int num_dests
, /* I - Number of destinations */
1921 cups_dest_t
*dests
) /* I - Destinations */
1923 int i
, j
; /* Looping vars */
1924 int wrote
; /* Wrote definition? */
1925 cups_dest_t
*dest
; /* Current destination */
1926 cups_option_t
*option
; /* Current option */
1927 _ipp_option_t
*match
; /* Matching attribute for option */
1928 FILE *fp
; /* File pointer */
1930 const char *home
; /* HOME environment variable */
1932 char filename
[1024]; /* lpoptions file */
1933 int num_temps
; /* Number of temporary destinations */
1934 cups_dest_t
*temps
= NULL
, /* Temporary destinations */
1935 *temp
; /* Current temporary dest */
1936 const char *val
; /* Value of temporary option */
1937 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1941 * Range check the input...
1944 if (!num_dests
|| !dests
)
1948 * Get the server destinations...
1951 num_temps
= _cupsGetDests(http
, CUPS_GET_PRINTERS
, NULL
, &temps
, 0, 0);
1953 if (cupsLastError() >= IPP_REDIRECTION_OTHER_SITE
)
1955 cupsFreeDests(num_temps
, temps
);
1960 * Figure out which file to write to...
1963 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1969 * Merge in server defaults...
1972 num_temps
= cups_get_dests(filename
, NULL
, NULL
, 0, num_temps
, &temps
);
1975 * Point to user defaults...
1978 if ((home
= getenv("HOME")) != NULL
)
1981 * Create ~/.cups subdirectory...
1984 snprintf(filename
, sizeof(filename
), "%s/.cups", home
);
1985 if (access(filename
, 0))
1986 mkdir(filename
, 0700);
1988 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1994 * Try to open the file...
1997 if ((fp
= fopen(filename
, "w")) == NULL
)
1999 cupsFreeDests(num_temps
, temps
);
2005 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2010 fchmod(fileno(fp
), 0644);
2014 * Write each printer; each line looks like:
2016 * Dest name[/instance] options
2017 * Default name[/instance] options
2020 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
2021 if (dest
->instance
!= NULL
|| dest
->num_options
!= 0 || dest
->is_default
)
2023 if (dest
->is_default
)
2025 fprintf(fp
, "Default %s", dest
->name
);
2027 fprintf(fp
, "/%s", dest
->instance
);
2034 if ((temp
= cupsGetDest(dest
->name
, dest
->instance
, num_temps
, temps
)) == NULL
)
2035 temp
= cupsGetDest(dest
->name
, NULL
, num_temps
, temps
);
2037 for (j
= dest
->num_options
, option
= dest
->options
; j
> 0; j
--, option
++)
2040 * See if this option is a printer attribute; if so, skip it...
2043 if ((match
= _ippFindOption(option
->name
)) != NULL
&&
2044 match
->group_tag
== IPP_TAG_PRINTER
)
2048 * See if the server/global options match these; if so, don't
2053 (val
= cupsGetOption(option
->name
, temp
->num_options
,
2054 temp
->options
)) != NULL
&&
2055 !_cups_strcasecmp(val
, option
->value
))
2059 * Options don't match, write to the file...
2064 fprintf(fp
, "Dest %s", dest
->name
);
2066 fprintf(fp
, "/%s", dest
->instance
);
2070 if (option
->value
[0])
2072 if (strchr(option
->value
, ' ') ||
2073 strchr(option
->value
, '\\') ||
2074 strchr(option
->value
, '\"') ||
2075 strchr(option
->value
, '\''))
2078 * Quote the value...
2081 fprintf(fp
, " %s=\"", option
->name
);
2083 for (val
= option
->value
; *val
; val
++)
2085 if (strchr("\"\'\\", *val
))
2096 * Store the literal value...
2099 fprintf(fp
, " %s=%s", option
->name
, option
->value
);
2103 fprintf(fp
, " %s", option
->name
);
2111 * Free the temporary destinations and close the file...
2114 cupsFreeDests(num_temps
, temps
);
2120 * Set the default printer for this location - this allows command-line
2121 * and GUI applications to share the same default destination...
2124 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, dests
)) != NULL
)
2126 CFStringRef name
= CFStringCreateWithCString(kCFAllocatorDefault
,
2128 kCFStringEncodingUTF8
);
2129 /* Default printer name */
2133 _cupsAppleSetDefaultPrinter(name
);
2137 #endif /* __APPLE__ */
2139 #ifdef HAVE_NOTIFY_POST
2141 * Send a notification so that MacOS X applications can know about the
2145 notify_post("com.apple.printerListChange");
2146 #endif /* HAVE_NOTIFY_POST */
2153 * '_cupsUserDefault()' - Get the user default printer from environment
2154 * variables and location information.
2157 char * /* O - Default printer or NULL */
2158 _cupsUserDefault(char *name
, /* I - Name buffer */
2159 size_t namesize
) /* I - Size of name buffer */
2161 const char *env
; /* LPDEST or PRINTER env variable */
2163 CFStringRef locprinter
; /* Last printer as this location */
2164 #endif /* __APPLE__ */
2167 if ((env
= getenv("LPDEST")) == NULL
)
2168 if ((env
= getenv("PRINTER")) != NULL
&& !strcmp(env
, "lp"))
2173 strlcpy(name
, env
, namesize
);
2179 * Use location-based defaults if "use last printer" is selected in the
2180 * system preferences...
2183 if ((locprinter
= _cupsAppleCopyDefaultPrinter()) != NULL
)
2185 CFStringGetCString(locprinter
, name
, namesize
, kCFStringEncodingUTF8
);
2186 CFRelease(locprinter
);
2191 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name
));
2193 return (*name
? name
: NULL
);
2197 * No location-based defaults on this platform...
2202 #endif /* __APPLE__ */
2208 * 'appleCopyLocations()' - Copy the location history array.
2211 static CFArrayRef
/* O - Location array or NULL */
2212 appleCopyLocations(void)
2214 CFArrayRef locations
; /* Location array */
2218 * Look up the location array in the preferences...
2221 if ((locations
= CFPreferencesCopyAppValue(kLastUsedPrintersKey
,
2222 kCUPSPrintingPrefs
)) == NULL
)
2225 if (CFGetTypeID(locations
) != CFArrayGetTypeID())
2227 CFRelease(locations
);
2236 * 'appleCopyNetwork()' - Get the network ID for the current location.
2239 static CFStringRef
/* O - Network ID */
2240 appleCopyNetwork(void)
2242 SCDynamicStoreRef dynamicStore
; /* System configuration data */
2243 CFStringRef key
; /* Current network configuration key */
2244 CFDictionaryRef ip_dict
; /* Network configuration data */
2245 CFStringRef network
= NULL
; /* Current network ID */
2248 if ((dynamicStore
= SCDynamicStoreCreate(NULL
, CFSTR("libcups"), NULL
,
2252 * First use the IPv6 router address, if available, since that will generally
2253 * be a globally-unique link-local address.
2256 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2257 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv6
)) != NULL
)
2259 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2261 if ((network
= CFDictionaryGetValue(ip_dict
,
2262 kSCPropNetIPv6Router
)) != NULL
)
2272 * If that doesn't work, try the IPv4 router address. This isn't as unique
2273 * and will likely be a 10.x.y.z or 192.168.y.z address...
2278 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2279 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv4
)) != NULL
)
2281 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2283 if ((network
= CFDictionaryGetValue(ip_dict
,
2284 kSCPropNetIPv4Router
)) != NULL
)
2294 CFRelease(dynamicStore
);
2302 * 'appleGetPaperSize()' - Get the default paper size.
2305 char * /* O - Default paper size */
2306 appleGetPaperSize(char *name
, /* I - Paper size name buffer */
2307 int namesize
) /* I - Size of buffer */
2309 CFStringRef defaultPaperID
; /* Default paper ID */
2310 _pwg_media_t
*pwgmedia
; /* PWG media size */
2313 defaultPaperID
= _cupsAppleCopyDefaultPaperID();
2314 if (!defaultPaperID
||
2315 CFGetTypeID(defaultPaperID
) != CFStringGetTypeID() ||
2316 !CFStringGetCString(defaultPaperID
, name
, namesize
,
2317 kCFStringEncodingUTF8
))
2319 else if ((pwgmedia
= _pwgMediaForLegacy(name
)) != NULL
)
2320 strlcpy(name
, pwgmedia
->pwg
, namesize
);
2323 CFRelease(defaultPaperID
);
2330 * 'appleGetPrinter()' - Get a printer from the history array.
2333 static CFStringRef
/* O - Printer name or NULL */
2334 appleGetPrinter(CFArrayRef locations
, /* I - Location array */
2335 CFStringRef network
, /* I - Network name */
2336 CFIndex
*locindex
) /* O - Index in array */
2338 CFIndex i
, /* Looping var */
2339 count
; /* Number of locations */
2340 CFDictionaryRef location
; /* Current location */
2341 CFStringRef locnetwork
, /* Current network */
2342 locprinter
; /* Current printer */
2345 for (i
= 0, count
= CFArrayGetCount(locations
); i
< count
; i
++)
2346 if ((location
= CFArrayGetValueAtIndex(locations
, i
)) != NULL
&&
2347 CFGetTypeID(location
) == CFDictionaryGetTypeID())
2349 if ((locnetwork
= CFDictionaryGetValue(location
,
2350 kLocationNetworkKey
)) != NULL
&&
2351 CFGetTypeID(locnetwork
) == CFStringGetTypeID() &&
2352 CFStringCompare(network
, locnetwork
, 0) == kCFCompareEqualTo
&&
2353 (locprinter
= CFDictionaryGetValue(location
,
2354 kLocationPrinterIDKey
)) != NULL
&&
2355 CFGetTypeID(locprinter
) == CFStringGetTypeID())
2360 return (locprinter
);
2366 #endif /* __APPLE__ */
2370 * 'cups_add_dest()' - Add a destination to the array.
2372 * Unlike cupsAddDest(), this function does not check for duplicates.
2375 static cups_dest_t
* /* O - New destination */
2376 cups_add_dest(const char *name
, /* I - Name of destination */
2377 const char *instance
, /* I - Instance or NULL */
2378 int *num_dests
, /* IO - Number of destinations */
2379 cups_dest_t
**dests
) /* IO - Destinations */
2381 int insert
, /* Insertion point */
2382 diff
; /* Result of comparison */
2383 cups_dest_t
*dest
; /* Destination pointer */
2387 * Add new destination...
2390 if (*num_dests
== 0)
2391 dest
= malloc(sizeof(cups_dest_t
));
2393 dest
= realloc(*dests
, sizeof(cups_dest_t
) * (*num_dests
+ 1));
2401 * Find where to insert the destination...
2404 if (*num_dests
== 0)
2408 insert
= cups_find_dest(name
, instance
, *num_dests
, *dests
, *num_dests
- 1,
2416 * Move the array elements as needed...
2419 if (insert
< *num_dests
)
2420 memmove(*dests
+ insert
+ 1, *dests
+ insert
,
2421 (*num_dests
- insert
) * sizeof(cups_dest_t
));
2426 * Initialize the destination...
2429 dest
= *dests
+ insert
;
2430 dest
->name
= _cupsStrAlloc(name
);
2431 dest
->instance
= _cupsStrAlloc(instance
);
2432 dest
->is_default
= 0;
2433 dest
->num_options
= 0;
2434 dest
->options
= (cups_option_t
*)0;
2442 * 'cups_block_cb()' - Enumeration callback for block API.
2445 static int /* O - 1 to continue, 0 to stop */
2447 cups_dest_block_t block
, /* I - Block */
2448 unsigned flags
, /* I - Destination flags */
2449 cups_dest_t
*dest
) /* I - Destination */
2451 return ((block
)(flags
, dest
));
2453 # endif /* __BLOCKS__ */
2457 * 'cups_compare_dests()' - Compare two destinations.
2460 static int /* O - Result of comparison */
2461 cups_compare_dests(cups_dest_t
*a
, /* I - First destination */
2462 cups_dest_t
*b
) /* I - Second destination */
2464 int diff
; /* Difference */
2467 if ((diff
= _cups_strcasecmp(a
->name
, b
->name
)) != 0)
2469 else if (a
->instance
&& b
->instance
)
2470 return (_cups_strcasecmp(a
->instance
, b
->instance
));
2472 return ((a
->instance
&& !b
->instance
) - (!a
->instance
&& b
->instance
));
2478 * 'cups_dnssd_browse_cb()' - Browse for printers.
2482 cups_dnssd_browse_cb(
2483 DNSServiceRef sdRef
, /* I - Service reference */
2484 DNSServiceFlags flags
, /* I - Option flags */
2485 uint32_t interfaceIndex
, /* I - Interface number */
2486 DNSServiceErrorType errorCode
, /* I - Error, if any */
2487 const char *serviceName
, /* I - Name of service/device */
2488 const char *regtype
, /* I - Type of service */
2489 const char *replyDomain
, /* I - Service domain */
2490 void *context
) /* I - Enumeration data */
2492 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2493 /* Enumeration data */
2496 DEBUG_printf(("5cups_dnssd_browse_cb(sdRef=%p, flags=%x, "
2497 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2498 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2499 sdRef
, flags
, interfaceIndex
, errorCode
, serviceName
, regtype
,
2500 replyDomain
, context
));
2503 * Don't do anything on error...
2506 if (errorCode
!= kDNSServiceErr_NoError
)
2513 cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2518 * 'cups_dnssd_compare_device()' - Compare two devices.
2521 static int /* O - Result of comparison */
2522 cups_dnssd_compare_devices(
2523 _cups_dnssd_device_t
*a
, /* I - First device */
2524 _cups_dnssd_device_t
*b
) /* I - Second device */
2526 return (strcmp(a
->dest
.name
, b
->dest
.name
));
2531 * 'cups_dnssd_free_device()' - Free the memory used by a device.
2535 cups_dnssd_free_device(
2536 _cups_dnssd_device_t
*device
, /* I - Device */
2537 _cups_dnssd_data_t
*data
) /* I - Enumeration data */
2539 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", device
,
2540 device
->dest
.name
, data
));
2543 DNSServiceRefDeallocate(device
->ref
);
2545 _cupsStrFree(device
->domain
);
2546 _cupsStrFree(device
->fullName
);
2547 _cupsStrFree(device
->regtype
);
2548 _cupsStrFree(device
->dest
.name
);
2550 cupsFreeOptions(device
->dest
.num_options
, device
->dest
.options
);
2557 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
2560 static _cups_dnssd_device_t
* /* O - Device */
2561 cups_dnssd_get_device(
2562 _cups_dnssd_data_t
*data
, /* I - Enumeration data */
2563 const char *serviceName
, /* I - Service name */
2564 const char *regtype
, /* I - Registration type */
2565 const char *replyDomain
) /* I - Domain name */
2567 _cups_dnssd_device_t key
, /* Search key */
2568 *device
; /* Device */
2569 char fullName
[kDNSServiceMaxDomainName
];
2570 /* Full name for query */
2573 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", "
2574 "regtype=\"%s\", replyDomain=\"%s\")", data
, serviceName
,
2575 regtype
, replyDomain
));
2578 * See if this is an existing device...
2581 key
.dest
.name
= (char *)serviceName
;
2583 if ((device
= cupsArrayFind(data
->devices
, &key
)) != NULL
)
2586 * Yes, see if we need to do anything with this...
2589 int update
= 0; /* Non-zero if we need to update */
2591 if (!_cups_strcasecmp(replyDomain
, "local.") &&
2592 _cups_strcasecmp(device
->domain
, replyDomain
))
2595 * Update the "global" listing to use the .local domain name instead.
2598 _cupsStrFree(device
->domain
);
2599 device
->domain
= _cupsStrAlloc(replyDomain
);
2601 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
2602 "domain.", device
->dest
.name
));
2607 if (!_cups_strcasecmp(regtype
, "_ipps._tcp") &&
2608 _cups_strcasecmp(device
->regtype
, regtype
))
2611 * Prefer IPPS over IPP.
2614 _cupsStrFree(device
->regtype
);
2615 device
->regtype
= _cupsStrAlloc(regtype
);
2617 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
2618 device
->dest
.name
));
2625 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
2626 device
->dest
.name
));
2633 * No, add the device...
2636 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
2637 "'%s'.", serviceName
,
2638 !strcmp(regtype
, "_ipps._tcp") ? "IPPS" : "IPP",
2641 device
= calloc(sizeof(_cups_dnssd_device_t
), 1);
2642 device
->dest
.name
= _cupsStrAlloc(serviceName
);
2643 device
->domain
= _cupsStrAlloc(replyDomain
);
2644 device
->regtype
= _cupsStrAlloc(regtype
);
2646 cupsArrayAdd(data
->devices
, device
);
2650 * Set the "full name" of this service, which is used for queries...
2653 DNSServiceConstructFullName(fullName
, device
->dest
.name
, device
->regtype
,
2655 _cupsStrFree(device
->fullName
);
2656 device
->fullName
= _cupsStrAlloc(fullName
);
2660 DNSServiceRefDeallocate(device
->ref
);
2664 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
2666 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
2667 device
->state
= _CUPS_DNSSD_NEW
;
2675 * 'cups_dnssd_local_cb()' - Browse for local printers.
2679 cups_dnssd_local_cb(
2680 DNSServiceRef sdRef
, /* I - Service reference */
2681 DNSServiceFlags flags
, /* I - Option flags */
2682 uint32_t interfaceIndex
, /* I - Interface number */
2683 DNSServiceErrorType errorCode
, /* I - Error, if any */
2684 const char *serviceName
, /* I - Name of service/device */
2685 const char *regtype
, /* I - Type of service */
2686 const char *replyDomain
, /* I - Service domain */
2687 void *context
) /* I - Devices array */
2689 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2690 /* Enumeration data */
2691 _cups_dnssd_device_t
*device
; /* Device */
2694 DEBUG_printf(("5cups_dnssd_local_cb(sdRef=%p, flags=%x, "
2695 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2696 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2697 sdRef
, flags
, interfaceIndex
, errorCode
, serviceName
,
2698 regtype
, replyDomain
, context
));
2701 * Only process "add" data...
2704 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
2711 device
= cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2714 * Hide locally-registered devices...
2717 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
2722 DNSServiceRefDeallocate(device
->ref
);
2726 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
2727 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
2729 device
->state
= _CUPS_DNSSD_LOCAL
;
2734 * 'cups_dnssd_query_cb()' - Process query data.
2738 cups_dnssd_query_cb(
2739 DNSServiceRef sdRef
, /* I - Service reference */
2740 DNSServiceFlags flags
, /* I - Data flags */
2741 uint32_t interfaceIndex
, /* I - Interface */
2742 DNSServiceErrorType errorCode
, /* I - Error, if any */
2743 const char *fullName
, /* I - Full service name */
2744 uint16_t rrtype
, /* I - Record type */
2745 uint16_t rrclass
, /* I - Record class */
2746 uint16_t rdlen
, /* I - Length of record data */
2747 const void *rdata
, /* I - Record data */
2748 uint32_t ttl
, /* I - Time-to-live */
2749 void *context
) /* I - Enumeration data */
2751 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2752 /* Enumeration data */
2753 char name
[1024], /* Service name */
2754 *ptr
; /* Pointer into string */
2755 _cups_dnssd_device_t dkey
, /* Search key */
2756 *device
; /* Device */
2759 DEBUG_printf(("5cups_dnssd_query_cb(sdRef=%p, flags=%x, "
2760 "interfaceIndex=%d, errorCode=%d, fullName=\"%s\", "
2761 "rrtype=%u, rrclass=%u, rdlen=%u, rdata=%p, ttl=%u, "
2762 "context=%p)", sdRef
, flags
, interfaceIndex
, errorCode
,
2763 fullName
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, context
));
2766 * Only process "add" data...
2769 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
2773 * Lookup the service in the devices array.
2776 dkey
.dest
.name
= name
;
2778 cups_dnssd_unquote(name
, fullName
, sizeof(name
));
2780 if ((ptr
= strstr(name
, "._")) != NULL
)
2783 if ((device
= cupsArrayFind(data
->devices
, &dkey
)) != NULL
)
2786 * Found it, pull out the priority and make and model from the TXT
2787 * record and save it...
2790 const uint8_t *txt
, /* Pointer into data */
2791 *txtnext
, /* Next key/value pair */
2792 *txtend
; /* End of entire TXT record */
2793 uint8_t txtlen
; /* Length of current key/value pair */
2794 char key
[256], /* Key string */
2795 value
[256], /* Value string */
2796 make_and_model
[512],
2797 /* Manufacturer and model */
2798 model
[256], /* Model */
2799 uriname
[1024], /* Name for URI */
2800 uri
[1024]; /* Printer URI */
2802 device
->state
= _CUPS_DNSSD_PENDING
;
2803 make_and_model
[0] = '\0';
2805 strcpy(model
, "Unknown");
2807 for (txt
= rdata
, txtend
= txt
+ rdlen
;
2812 * Read a key/value pair starting with an 8-bit length. Since the
2813 * length is 8 bits and the size of the key/value buffers is 256, we
2814 * don't need to check for overflow...
2819 if (!txtlen
|| (txt
+ txtlen
) > txtend
)
2822 txtnext
= txt
+ txtlen
;
2824 for (ptr
= key
; txt
< txtnext
&& *txt
!= '='; txt
++)
2828 if (txt
< txtnext
&& *txt
== '=')
2833 memcpy(value
, txt
, txtnext
- txt
);
2834 value
[txtnext
- txt
] = '\0';
2836 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key
, value
));
2840 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key
));
2844 if (!_cups_strcasecmp(key
, "usb_MFG") ||
2845 !_cups_strcasecmp(key
, "usb_MANU") ||
2846 !_cups_strcasecmp(key
, "usb_MANUFACTURER"))
2847 strcpy(make_and_model
, value
);
2848 else if (!_cups_strcasecmp(key
, "usb_MDL") ||
2849 !_cups_strcasecmp(key
, "usb_MODEL"))
2850 strcpy(model
, value
);
2851 else if (!_cups_strcasecmp(key
, "product") && !strstr(value
, "Ghostscript"))
2853 if (value
[0] == '(')
2856 * Strip parenthesis...
2859 if ((ptr
= value
+ strlen(value
) - 1) > value
&& *ptr
== ')')
2862 strcpy(model
, value
+ 1);
2865 strcpy(model
, value
);
2867 else if (!_cups_strcasecmp(key
, "ty"))
2869 strcpy(model
, value
);
2871 if ((ptr
= strchr(model
, ',')) != NULL
)
2874 else if (!_cups_strcasecmp(key
, "printer-type"))
2876 device
->dest
.num_options
= cupsAddOption("printer-type", value
,
2877 device
->dest
.num_options
,
2878 &device
->dest
.options
);
2883 * Save the make-and-model...
2886 if (make_and_model
[0])
2888 strlcat(make_and_model
, " ", sizeof(make_and_model
));
2889 strlcat(make_and_model
, model
, sizeof(make_and_model
));
2891 device
->dest
.num_options
= cupsAddOption("printer-make-and-model",
2893 device
->dest
.num_options
,
2894 &device
->dest
.options
);
2897 device
->dest
.num_options
= cupsAddOption("printer-make-and-model",
2899 device
->dest
.num_options
,
2900 &device
->dest
.options
);
2906 cups_dnssd_unquote(uriname
, device
->fullName
, sizeof(uriname
));
2907 httpAssembleURI(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
),
2908 !strcmp(device
->regtype
, "_ipps._tcp") ? "ipps" : "ipp",
2909 NULL
, uriname
, 0, "/cups");
2911 DEBUG_printf(("6cups_dnssd_query: printer-uri-supported=\"%s\"", uri
));
2913 device
->dest
.num_options
= cupsAddOption("printer-uri-supported", uri
,
2914 device
->dest
.num_options
,
2915 &device
->dest
.options
);
2918 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
2924 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
2927 static const char * /* O - Resolved URI or NULL */
2929 cups_dest_t
*dest
, /* I - Destination */
2930 const char *uri
, /* I - Current printer URI */
2931 int msec
, /* I - Time in milliseconds */
2932 int *cancel
, /* I - Pointer to "cancel" variable */
2933 cups_dest_cb_t cb
, /* I - Callback */
2934 void *user_data
) /* I - User data for callback */
2936 char tempuri
[1024]; /* Temporary URI buffer */
2937 _cups_dnssd_resolve_t resolve
; /* Resolve data */
2941 * Resolve the URI...
2944 resolve
.cancel
= cancel
;
2945 gettimeofday(&resolve
.end_time
, NULL
);
2948 resolve
.end_time
.tv_sec
+= msec
/ 1000;
2949 resolve
.end_time
.tv_usec
+= (msec
% 1000) * 1000;
2951 while (resolve
.end_time
.tv_usec
>= 1000000)
2953 resolve
.end_time
.tv_sec
++;
2954 resolve
.end_time
.tv_usec
-= 1000000;
2958 resolve
.end_time
.tv_sec
+= 75;
2961 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
,
2964 if ((uri
= _httpResolveURI(uri
, tempuri
, sizeof(tempuri
),
2965 _HTTP_RESOLVE_FQDN
, cups_dnssd_resolve_cb
,
2968 _cupsSetError(IPP_INTERNAL_ERROR
, _("Unable to resolve printer URI."), 1);
2971 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
2978 * Save the resolved URI...
2981 dest
->num_options
= cupsAddOption("printer-uri-supported", uri
,
2982 dest
->num_options
, &dest
->options
);
2984 return (cupsGetOption("printer-uri-supported", dest
->num_options
,
2990 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
2993 static int /* O - 1 to continue, 0 to stop */
2994 cups_dnssd_resolve_cb(void *context
) /* I - Resolve data */
2996 _cups_dnssd_resolve_t
*resolve
= (_cups_dnssd_resolve_t
*)context
;
2998 struct timeval curtime
; /* Current time */
3002 * If the cancel variable is set, return immediately.
3005 if (*resolve
->cancel
)
3009 * Otherwise check the end time...
3012 gettimeofday(&curtime
, NULL
);
3014 return (curtime
.tv_sec
> resolve
->end_time
.tv_sec
||
3015 (curtime
.tv_sec
== resolve
->end_time
.tv_sec
&&
3016 curtime
.tv_usec
> resolve
->end_time
.tv_usec
));
3021 * 'cups_dnssd_unquote()' - Unquote a name string.
3025 cups_dnssd_unquote(char *dst
, /* I - Destination buffer */
3026 const char *src
, /* I - Source string */
3027 size_t dstsize
) /* I - Size of destination buffer */
3029 char *dstend
= dst
+ dstsize
- 1; /* End of destination buffer */
3032 while (*src
&& dst
< dstend
)
3037 if (isdigit(src
[0] & 255) && isdigit(src
[1] & 255) &&
3038 isdigit(src
[2] & 255))
3040 *dst
++ = ((((src
[0] - '0') * 10) + src
[1] - '0') * 10) + src
[2] - '0';
3052 #endif /* HAVE_DNSSD */
3056 * 'cups_find_dest()' - Find a destination using a binary search.
3059 static int /* O - Index of match */
3060 cups_find_dest(const char *name
, /* I - Destination name */
3061 const char *instance
, /* I - Instance or NULL */
3062 int num_dests
, /* I - Number of destinations */
3063 cups_dest_t
*dests
, /* I - Destinations */
3064 int prev
, /* I - Previous index */
3065 int *rdiff
) /* O - Difference of match */
3067 int left
, /* Low mark for binary search */
3068 right
, /* High mark for binary search */
3069 current
, /* Current index */
3070 diff
; /* Result of comparison */
3071 cups_dest_t key
; /* Search key */
3074 key
.name
= (char *)name
;
3075 key
.instance
= (char *)instance
;
3080 * Start search on either side of previous...
3083 if ((diff
= cups_compare_dests(&key
, dests
+ prev
)) == 0 ||
3084 (diff
< 0 && prev
== 0) ||
3085 (diff
> 0 && prev
== (num_dests
- 1)))
3093 * Start with previous on right side...
3102 * Start wih previous on left side...
3106 right
= num_dests
- 1;
3112 * Start search in the middle...
3116 right
= num_dests
- 1;
3121 current
= (left
+ right
) / 2;
3122 diff
= cups_compare_dests(&key
, dests
+ current
);
3131 while ((right
- left
) > 1);
3136 * Check the last 1 or 2 elements...
3139 if ((diff
= cups_compare_dests(&key
, dests
+ left
)) <= 0)
3143 diff
= cups_compare_dests(&key
, dests
+ right
);
3149 * Return the closest destination and the difference...
3159 * 'cups_get_default()' - Get the default destination from an lpoptions file.
3162 static char * /* O - Default destination or NULL */
3163 cups_get_default(const char *filename
, /* I - File to read */
3164 char *namebuf
, /* I - Name buffer */
3165 size_t namesize
, /* I - Size of name buffer */
3166 const char **instance
) /* I - Instance */
3168 cups_file_t
*fp
; /* lpoptions file */
3169 char line
[8192], /* Line from file */
3170 *value
, /* Value for line */
3171 *nameptr
; /* Pointer into name */
3172 int linenum
; /* Current line */
3177 if ((fp
= cupsFileOpen(filename
, "r")) != NULL
)
3181 while (cupsFileGetConf(fp
, line
, sizeof(line
), &value
, &linenum
))
3183 if (!_cups_strcasecmp(line
, "default") && value
)
3185 strlcpy(namebuf
, value
, namesize
);
3187 if ((nameptr
= strchr(namebuf
, ' ')) != NULL
)
3189 if ((nameptr
= strchr(namebuf
, '\t')) != NULL
)
3192 if ((nameptr
= strchr(namebuf
, '/')) != NULL
)
3195 *instance
= nameptr
;
3203 return (*namebuf
? namebuf
: NULL
);
3208 * 'cups_get_dests()' - Get destinations from a file.
3211 static int /* O - Number of destinations */
3213 const char *filename
, /* I - File to read from */
3214 const char *match_name
, /* I - Destination name we want */
3215 const char *match_inst
, /* I - Instance name we want */
3216 int user_default_set
, /* I - User default printer set? */
3217 int num_dests
, /* I - Number of destinations */
3218 cups_dest_t
**dests
) /* IO - Destinations */
3220 int i
; /* Looping var */
3221 cups_dest_t
*dest
; /* Current destination */
3222 cups_file_t
*fp
; /* File pointer */
3223 char line
[8192], /* Line from file */
3224 *lineptr
, /* Pointer into line */
3225 *name
, /* Name of destination/option */
3226 *instance
; /* Instance of destination */
3227 int linenum
; /* Current line number */
3230 DEBUG_printf(("7cups_get_dests(filename=\"%s\", match_name=\"%s\", "
3231 "match_inst=\"%s\", user_default_set=%d, num_dests=%d, "
3232 "dests=%p)", filename
, match_name
, match_inst
,
3233 user_default_set
, num_dests
, dests
));
3236 * Try to open the file...
3239 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
3243 * Read each printer; each line looks like:
3245 * Dest name[/instance] options
3246 * Default name[/instance] options
3251 while (cupsFileGetConf(fp
, line
, sizeof(line
), &lineptr
, &linenum
))
3254 * See what type of line it is...
3257 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
3258 linenum
, line
, lineptr
));
3260 if ((_cups_strcasecmp(line
, "dest") && _cups_strcasecmp(line
, "default")) || !lineptr
)
3262 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
3269 * Search for an instance...
3272 while (!isspace(*lineptr
& 255) && *lineptr
&& *lineptr
!= '/')
3275 if (*lineptr
== '/')
3278 * Found an instance...
3285 * Search for an instance...
3288 while (!isspace(*lineptr
& 255) && *lineptr
)
3297 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name
,
3301 * See if the primary instance of the destination exists; if not,
3302 * ignore this entry and move on...
3307 if (_cups_strcasecmp(name
, match_name
) ||
3308 (!instance
&& match_inst
) ||
3309 (instance
&& !match_inst
) ||
3310 (instance
&& _cups_strcasecmp(instance
, match_inst
)))
3315 else if (cupsGetDest(name
, NULL
, num_dests
, *dests
) == NULL
)
3317 DEBUG_puts("9cups_get_dests: Not found!");
3323 * Add the destination...
3326 num_dests
= cupsAddDest(name
, instance
, num_dests
, dests
);
3328 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
3334 DEBUG_puts("9cups_get_dests: Out of memory!");
3340 * Add options until we hit the end of the line...
3343 dest
->num_options
= cupsParseOptions(lineptr
, dest
->num_options
,
3347 * If we found what we were looking for, stop now...
3354 * Set this as default if needed...
3357 if (!user_default_set
&& !_cups_strcasecmp(line
, "default"))
3359 DEBUG_puts("9cups_get_dests: Setting as default...");
3361 for (i
= 0; i
< num_dests
; i
++)
3362 (*dests
)[i
].is_default
= 0;
3364 dest
->is_default
= 1;
3369 * Close the file and return...
3379 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
3383 static char * /* O - New string */
3385 ipp_attribute_t
*attr
, /* I - Attribute to convert */
3386 char *buffer
, /* I - Buffer */
3387 size_t bufsize
) /* I - Size of buffer */
3389 int i
; /* Looping var */
3390 char *ptr
, /* Pointer into buffer */
3391 *end
, /* Pointer to end of buffer */
3392 *valptr
; /* Pointer into string attribute */
3396 * Return quickly if we have a single string value...
3399 if (attr
->num_values
== 1 &&
3400 attr
->value_tag
!= IPP_TAG_INTEGER
&&
3401 attr
->value_tag
!= IPP_TAG_ENUM
&&
3402 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
3403 attr
->value_tag
!= IPP_TAG_RANGE
)
3404 return (attr
->values
[0].string
.text
);
3407 * Copy the values to the string, separating with commas and escaping strings
3411 end
= buffer
+ bufsize
- 1;
3413 for (i
= 0, ptr
= buffer
; i
< attr
->num_values
&& ptr
< end
; i
++)
3418 switch (attr
->value_tag
)
3420 case IPP_TAG_INTEGER
:
3422 snprintf(ptr
, end
- ptr
+ 1, "%d", attr
->values
[i
].integer
);
3425 case IPP_TAG_BOOLEAN
:
3426 if (attr
->values
[i
].boolean
)
3427 strlcpy(ptr
, "true", end
- ptr
+ 1);
3429 strlcpy(ptr
, "false", end
- ptr
+ 1);
3432 case IPP_TAG_RANGE
:
3433 if (attr
->values
[i
].range
.lower
== attr
->values
[i
].range
.upper
)
3434 snprintf(ptr
, end
- ptr
+ 1, "%d", attr
->values
[i
].range
.lower
);
3436 snprintf(ptr
, end
- ptr
+ 1, "%d-%d", attr
->values
[i
].range
.lower
,
3437 attr
->values
[i
].range
.upper
);
3441 for (valptr
= attr
->values
[i
].string
.text
;
3442 *valptr
&& ptr
< end
;)
3444 if (strchr(" \t\n\\\'\"", *valptr
))
3446 if (ptr
>= (end
- 1))
3469 * End of "$Id: dest.c 9568 2011-02-25 06:13:56Z mike $".