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 // CFStringGetCString(network, name, namesize, kCFStringEncodingUTF8);
353 // DEBUG_printf(("2_cupsUserDefault: network=\"%s\"", name));
354 //# endif /* DEBUG */
357 * Lookup the network in the preferences...
360 if ((locations
= appleCopyLocations()) == NULL
)
363 * Missing or bad location array, so no location-based default...
366 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Missing or bad last used "
374 DEBUG_printf(("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.",
375 (int)CFArrayGetCount(locations
)));
377 if ((locprinter
= appleGetPrinter(locations
, network
, NULL
)) != NULL
)
378 CFRetain(locprinter
);
381 CFRelease(locations
);
388 * '_cupsAppleGetUseLastPrinter()' - Get whether to use the last used printer.
391 int /* O - 1 to use last printer, 0 otherwise */
392 _cupsAppleGetUseLastPrinter(void)
394 Boolean uselast
, /* Use last printer preference value */
395 uselast_set
; /* Valid is set? */
398 if (getenv("CUPS_DISABLE_APPLE_DEFAULT"))
401 uselast
= CFPreferencesGetAppBooleanValue(kUseLastPrinter
,
412 * '_cupsAppleSetDefaultPaperID()' - Set the default paper id.
416 _cupsAppleSetDefaultPaperID(
417 CFStringRef name
) /* I - New paper ID */
419 CFPreferencesSetAppValue(kDefaultPaperIDKey
, name
, kCUPSPrintingPrefs
);
420 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
421 notify_post("com.apple.printerPrefsChange");
426 * '_cupsAppleSetDefaultPrinter()' - Set the default printer for this location.
430 _cupsAppleSetDefaultPrinter(
431 CFStringRef name
) /* I - Default printer/class name */
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
);
509 notify_post("com.apple.printerPrefsChange");
513 CFRelease(newlocations
);
516 CFRelease(newlocation
);
520 CFRelease(locations
);
527 * '_cupsAppleSetUseLastPrinter()' - Set whether to use the last used printer.
531 _cupsAppleSetUseLastPrinter(
532 int uselast
) /* O - 1 to use last printer, 0 otherwise */
534 CFPreferencesSetAppValue(kUseLastPrinter
,
535 uselast
? kCFBooleanTrue
: kCFBooleanFalse
,
537 CFPreferencesAppSynchronize(kCUPSPrintingPrefs
);
538 notify_post("com.apple.printerPrefsChange");
540 #endif /* __APPLE__ */
544 * 'cupsConnectDest()' - Connect to the server for a destination.
546 * Connect to the destination, returning a new http_t connection object and
547 * optionally the resource path to use for the destination. These calls will
548 * block until a connection is made, the timeout expires, the integer pointed
549 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
550 * The caller is responsible for calling httpClose() on the returned object.
555 http_t
* /* O - Connection to server or @code NULL@ */
557 cups_dest_t
*dest
, /* I - Destination */
558 unsigned flags
, /* I - Connection flags */
559 int msec
, /* I - Timeout in milliseconds */
560 int *cancel
, /* I - Pointer to "cancel" variable */
561 char *resource
, /* I - Resource buffer */
562 size_t resourcesize
, /* I - Size of resource buffer */
563 cups_dest_cb_t cb
, /* I - Callback function */
564 void *user_data
) /* I - User data pointer */
566 const char *uri
; /* Printer URI */
567 char scheme
[32], /* URI scheme */
568 userpass
[256], /* Username and password (unused) */
569 hostname
[256], /* Hostname */
570 tempresource
[1024]; /* Temporary resource buffer */
571 int port
; /* Port number */
572 char portstr
[16]; /* Port number string */
573 http_encryption_t encrypt
; /* Encryption to use */
574 http_addrlist_t
*addrlist
; /* Address list for server */
575 http_t
*http
; /* Connection to server */
579 * Range check input...
587 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
591 if (!resource
|| resourcesize
< 1)
593 resource
= tempresource
;
594 resourcesize
= sizeof(tempresource
);
598 * Grab the printer URI...
601 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
,
602 dest
->options
)) == NULL
)
604 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(ENOENT
), 0);
607 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
614 if (strstr(uri
, "._tcp"))
616 if ((uri
= cups_dnssd_resolve(dest
, uri
, msec
, cancel
, cb
,
620 #endif /* HAVE_DNSSD */
622 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
623 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
624 &port
, resource
, resourcesize
) < HTTP_URI_OK
)
626 _cupsSetError(IPP_INTERNAL_ERROR
, _("Bad printer URI."), 1);
629 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
636 * Lookup the address for the server...
640 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
,
643 snprintf(portstr
, sizeof(portstr
), "%d", port
);
645 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, portstr
)) == NULL
)
648 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
654 if (cancel
&& *cancel
)
656 httpAddrFreeList(addrlist
);
659 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CANCELED
,
666 * Create the HTTP object pointing to the server referenced by the URI...
669 if (!strcmp(scheme
, "ipps") || port
== 443)
670 encrypt
= HTTP_ENCRYPT_ALWAYS
;
672 encrypt
= HTTP_ENCRYPT_IF_REQUESTED
;
674 http
= _httpCreate(hostname
, port
, addrlist
, encrypt
, AF_UNSPEC
);
677 * Connect if requested...
680 if (flags
& CUPS_DEST_FLAGS_UNCONNECTED
)
683 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
, dest
);
688 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
,
691 if (!httpReconnect2(http
, msec
, cancel
) && cb
)
693 if (cancel
&& *cancel
)
695 CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_CONNECTING
, dest
);
697 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
701 (*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, dest
);
710 * 'cupsConnectDestBlock()' - Connect to the server for a destination.
712 * Connect to the destination, returning a new http_t connection object and
713 * optionally the resource path to use for the destination. These calls will
714 * block until a connection is made, the timeout expires, the integer pointed
715 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
716 * The caller is responsible for calling httpClose() on the returned object.
721 http_t
* /* O - Connection to server or @code NULL@ */
722 cupsConnectDestBlock(
723 cups_dest_t
*dest
, /* I - Destination */
724 unsigned flags
, /* I - Connection flags */
725 int msec
, /* I - Timeout in milliseconds */
726 int *cancel
, /* I - Pointer to "cancel" variable */
727 char *resource
, /* I - Resource buffer */
728 size_t resourcesize
, /* I - Size of resource buffer */
729 cups_dest_block_t block
) /* I - Callback block */
731 return (cupsConnectDest(dest
, flags
, msec
, cancel
, resource
, resourcesize
,
732 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
734 #endif /* __BLOCKS__ */
738 * 'cupsCopyDest()' - Copy a destination.
740 * Make a copy of the destination to an array of destinations (or just a single
741 * copy) - for use with the cupsEnumDests* functions. The caller is responsible
742 * for calling cupsFreeDests() on the returned object(s).
748 cupsCopyDest(cups_dest_t
*dest
,
752 int i
; /* Looping var */
753 cups_dest_t
*new_dest
; /* New destination pointer */
754 cups_option_t
*new_option
, /* Current destination option */
755 *option
; /* Current parent option */
759 * Range check input...
762 if (!dest
|| num_dests
< 0 || !dests
)
766 * See if the destination already exists...
769 if ((new_dest
= cupsGetDest(dest
->name
, dest
->instance
, num_dests
,
773 * Protect against copying destination to itself...
776 if (new_dest
== dest
)
780 * Otherwise, free the options...
783 cupsFreeOptions(new_dest
->num_options
, new_dest
->options
);
785 new_dest
->num_options
= 0;
786 new_dest
->options
= NULL
;
789 new_dest
= cups_add_dest(dest
->name
, dest
->instance
, &num_dests
, dests
);
793 if ((new_dest
->options
= calloc(sizeof(cups_option_t
),
794 dest
->num_options
)) == NULL
)
795 return (cupsRemoveDest(dest
->name
, dest
->instance
, num_dests
, dests
));
797 new_dest
->num_options
= dest
->num_options
;
799 for (i
= dest
->num_options
, option
= dest
->options
,
800 new_option
= new_dest
->options
;
802 i
--, option
++, new_option
++)
804 new_option
->name
= _cupsStrRetain(option
->name
);
805 new_option
->value
= _cupsStrRetain(option
->value
);
814 * 'cupsEnumDests()' - Enumerate available destinations with a callback function.
816 * Destinations are enumerated from one or more sources. The callback function
817 * receives the @code user_data@ pointer, destination name, instance, number of
818 * options, and options which can be used as input to the @link cupsAddDest@
819 * function. The function must return 1 to continue enumeration or 0 to stop.
821 * Enumeration happens on the current thread and does not return until all
822 * destinations have been enumerated or the callback function returns 0.
827 int /* O - 1 on success, 0 on failure */
829 unsigned flags
, /* I - Enumeration flags */
830 int msec
, /* I - Timeout in milliseconds,
831 * -1 for indefinite */
832 int *cancel
, /* I - Pointer to "cancel" variable */
833 cups_ptype_t type
, /* I - Printer type bits */
834 cups_ptype_t mask
, /* I - Mask for printer type bits */
835 cups_dest_cb_t cb
, /* I - Callback function */
836 void *user_data
) /* I - User data */
838 int i
, /* Looping var */
839 num_dests
; /* Number of destinations */
840 cups_dest_t
*dests
, /* Destinations */
841 *dest
; /* Current destination */
843 int nfds
, /* Number of files responded */
844 count
, /* Number of queries started */
845 remaining
; /* Remainder of timeout */
846 _cups_dnssd_data_t data
; /* Data for callback */
847 _cups_dnssd_device_t
*device
; /* Current device */
848 int main_fd
; /* File descriptor for lookups */
849 DNSServiceRef ipp_ref
, /* IPP browser */
850 local_ipp_ref
; /* Local IPP browser */
852 DNSServiceRef ipps_ref
, /* IPPS browser */
853 local_ipps_ref
; /* Local IPPS browser */
854 # endif /* HAVE_SSL */
856 struct pollfd pfd
; /* Polling data */
858 fd_set input
; /* Input set for select() */
859 struct timeval timeout
; /* Timeout for select() */
860 # endif /* HAVE_POLL */
861 #endif /* HAVE_DNSSD */
865 * Range check input...
872 * Get the list of local printers and pass them to the callback function...
875 num_dests
= _cupsGetDests(CUPS_HTTP_DEFAULT
, CUPS_GET_PRINTERS
, NULL
, &dests
,
878 for (i
= num_dests
, dest
= dests
;
879 i
> 0 && (!cancel
|| !*cancel
);
881 if (!(*cb
)(user_data
, i
> 1 ? CUPS_DEST_FLAGS_MORE
: CUPS_DEST_FLAGS_NONE
,
885 cupsFreeDests(num_dests
, dests
);
887 if (i
> 0 || msec
== 0)
892 * Get Bonjour-shared printers...
897 data
.devices
= cupsArrayNew3((cups_array_func_t
)cups_dnssd_compare_devices
,
899 (cups_afree_func_t
)cups_dnssd_free_device
);
901 if (DNSServiceCreateConnection(&data
.main_ref
) != kDNSServiceErr_NoError
)
904 main_fd
= DNSServiceRefSockFD(data
.main_ref
);
906 ipp_ref
= data
.main_ref
;
907 DNSServiceBrowse(&ipp_ref
, kDNSServiceFlagsShareConnection
, 0,
908 "_ipp._tcp,_cups", NULL
, cups_dnssd_browse_cb
, &data
);
910 local_ipp_ref
= data
.main_ref
;
911 DNSServiceBrowse(&local_ipp_ref
, kDNSServiceFlagsShareConnection
,
912 kDNSServiceInterfaceIndexLocalOnly
,
913 "_ipp._tcp,_cups", NULL
, cups_dnssd_local_cb
, &data
);
916 ipps_ref
= data
.main_ref
;
917 DNSServiceBrowse(&ipps_ref
, kDNSServiceFlagsShareConnection
, 0,
918 "_ipps._tcp,_cups", NULL
, 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
, cups_dnssd_local_cb
, &data
);
924 # endif /* HAVE_SSL */
931 while (remaining
> 0 && (!cancel
|| !*cancel
))
941 nfds
= poll(&pfd
, 1, remaining
> 250 ? 250 : remaining
);
945 FD_SET(main_fd
, &input
);
948 timeout
.tv_usec
= remaining
> 250 ? 250000 : remaining
* 1000;
950 nfds
= select(main_fd
+ 1, &input
, NULL
, NULL
, &timeout
);
951 # endif /* HAVE_POLL */
954 DNSServiceProcessResult(data
.main_ref
);
958 for (device
= (_cups_dnssd_device_t
*)cupsArrayFirst(data
.devices
),
961 device
= (_cups_dnssd_device_t
*)cupsArrayNext(data
.devices
))
966 if (!device
->ref
&& device
->state
== _CUPS_DNSSD_NEW
)
968 device
->ref
= data
.main_ref
;
970 DEBUG_printf(("1cupsEnumDests: Querying '%s'.", device
->fullName
));
972 if (DNSServiceQueryRecord(&(device
->ref
),
973 kDNSServiceFlagsShareConnection
,
976 kDNSServiceClass_IN
, cups_dnssd_query_cb
,
977 &data
) == kDNSServiceErr_NoError
)
984 device
->state
= _CUPS_DNSSD_ERROR
;
986 DEBUG_puts("1cupsEnumDests: Query failed.");
989 else if (device
->ref
&& device
->state
== _CUPS_DNSSD_PENDING
)
991 if (!(*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, &device
->dest
))
997 device
->state
= _CUPS_DNSSD_ACTIVE
;
1002 cupsArrayDelete(data
.devices
);
1004 DNSServiceRefDeallocate(ipp_ref
);
1005 DNSServiceRefDeallocate(local_ipp_ref
);
1008 DNSServiceRefDeallocate(ipp_ref
);
1009 DNSServiceRefDeallocate(local_ipp_ref
);
1010 # endif /* HAVE_SSL */
1012 DNSServiceRefDeallocate(data
.main_ref
);
1013 #endif /* HAVE_DNSSD */
1021 * 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
1023 * Destinations are enumerated from one or more sources. The block receives the
1024 * destination name, instance, number of options, and options which can be used
1025 * as input to the @link cupsAddDest@ function. The block must return 1 to
1026 * continue enumeration or 0 to stop.
1028 * Enumeration happens on the current thread and does not return until all
1029 * destinations have been enumerated or the block returns 0.
1034 int /* O - 1 on success, 0 on failure */
1036 unsigned flags
, /* I - Enumeration flags */
1037 int timeout
, /* I - Timeout in milliseconds, 0 for indefinite */
1038 int *cancel
, /* I - Pointer to "cancel" variable */
1039 cups_ptype_t type
, /* I - Printer type bits */
1040 cups_ptype_t mask
, /* I - Mask for printer type bits */
1041 cups_dest_block_t block
) /* I - Block */
1043 return (cupsEnumDests(flags
, timeout
, cancel
, type
, mask
,
1044 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
1046 # endif /* __BLOCKS__ */
1050 * 'cupsFreeDests()' - Free the memory used by the list of destinations.
1054 cupsFreeDests(int num_dests
, /* I - Number of destinations */
1055 cups_dest_t
*dests
) /* I - Destinations */
1057 int i
; /* Looping var */
1058 cups_dest_t
*dest
; /* Current destination */
1061 if (num_dests
== 0 || dests
== NULL
)
1064 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1066 _cupsStrFree(dest
->name
);
1067 _cupsStrFree(dest
->instance
);
1069 cupsFreeOptions(dest
->num_options
, dest
->options
);
1077 * 'cupsGetDest()' - Get the named destination from the list.
1079 * Use the @link cupsGetDests@ or @link cupsGetDests2@ functions to get a
1080 * list of supported destinations for the current user.
1083 cups_dest_t
* /* O - Destination pointer or @code NULL@ */
1084 cupsGetDest(const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1085 const char *instance
, /* I - Instance name or @code NULL@ */
1086 int num_dests
, /* I - Number of destinations */
1087 cups_dest_t
*dests
) /* I - Destinations */
1089 int diff
, /* Result of comparison */
1090 match
; /* Matching index */
1093 if (num_dests
<= 0 || !dests
)
1099 * NULL name for default printer.
1102 while (num_dests
> 0)
1104 if (dests
->is_default
)
1114 * Lookup name and optionally the instance...
1117 match
= cups_find_dest(name
, instance
, num_dests
, dests
, -1, &diff
);
1120 return (dests
+ match
);
1128 * '_cupsGetDestResource()' - Get the resource path and URI for a destination.
1131 const char * /* O - Printer URI */
1132 _cupsGetDestResource(
1133 cups_dest_t
*dest
, /* I - Destination */
1134 char *resource
, /* I - Resource buffer */
1135 size_t resourcesize
) /* I - Size of resource buffer */
1137 const char *uri
; /* Printer URI */
1138 char scheme
[32], /* URI scheme */
1139 userpass
[256], /* Username and password (unused) */
1140 hostname
[256]; /* Hostname */
1141 int port
; /* Port number */
1145 * Range check input...
1148 if (!dest
|| !resource
|| resourcesize
< 1)
1153 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
1158 * Grab the printer URI...
1161 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
,
1162 dest
->options
)) == NULL
)
1167 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(ENOENT
), 0);
1173 if (strstr(uri
, "._tcp"))
1175 if ((uri
= cups_dnssd_resolve(dest
, uri
, 5000, NULL
, NULL
, NULL
)) == NULL
)
1178 #endif /* HAVE_DNSSD */
1180 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
1181 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
1182 &port
, resource
, resourcesize
) < HTTP_URI_OK
)
1184 _cupsSetError(IPP_INTERNAL_ERROR
, _("Bad printer URI."), 1);
1194 * '_cupsGetDests()' - Get destinations from a server.
1196 * "op" is CUPS_GET_PRINTERS to get a full list, CUPS_GET_DEFAULT to get the
1197 * system-wide default printer, or IPP_GET_PRINTER_ATTRIBUTES for a known
1200 * "name" is the name of an existing printer and is only used when "op" is
1201 * IPP_GET_PRINTER_ATTRIBUTES.
1203 * "dest" is initialized to point to the array of destinations.
1205 * 0 is returned if there are no printers, no default printer, or the named
1206 * printer does not exist, respectively.
1208 * Free the memory used by the destination array using the @link cupsFreeDests@
1211 * Note: On Mac OS X this function also gets the default paper from the system
1212 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1213 * options array for each destination that supports it.
1216 int /* O - Number of destinations */
1217 _cupsGetDests(http_t
*http
, /* I - Connection to server or
1218 * @code CUPS_HTTP_DEFAULT@ */
1219 ipp_op_t op
, /* I - IPP operation */
1220 const char *name
, /* I - Name of destination */
1221 cups_dest_t
**dests
, /* IO - Destinations */
1222 cups_ptype_t type
, /* I - Printer type bits */
1223 cups_ptype_t mask
) /* I - Printer type mask */
1225 int num_dests
= 0; /* Number of destinations */
1226 cups_dest_t
*dest
; /* Current destination */
1227 ipp_t
*request
, /* IPP Request */
1228 *response
; /* IPP Response */
1229 ipp_attribute_t
*attr
; /* Current attribute */
1230 const char *printer_name
; /* printer-name attribute */
1231 char uri
[1024]; /* printer-uri value */
1232 int num_options
; /* Number of options */
1233 cups_option_t
*options
; /* Options */
1235 char media_default
[41]; /* Default paper size */
1236 #endif /* __APPLE__ */
1237 char optname
[1024], /* Option name */
1238 value
[2048], /* Option value */
1239 *ptr
; /* Pointer into name/value */
1240 static const char * const pattrs
[] = /* Attributes we're interested in */
1242 "auth-info-required",
1244 "job-sheets-default",
1245 "marker-change-time",
1247 "marker-high-levels",
1249 "marker-low-levels",
1255 #endif /* __APPLE__ */
1259 "printer-is-accepting-jobs",
1260 "printer-is-shared",
1262 "printer-make-and-model",
1265 "printer-state-change-time",
1266 "printer-state-reasons",
1268 "printer-uri-supported"
1274 * Get the default paper size...
1277 appleGetPaperSize(media_default
, sizeof(media_default
));
1278 #endif /* __APPLE__ */
1281 * Build a CUPS_GET_PRINTERS or IPP_GET_PRINTER_ATTRIBUTES request, which
1282 * require the following attributes:
1284 * attributes-charset
1285 * attributes-natural-language
1286 * requesting-user-name
1287 * printer-uri [for IPP_GET_PRINTER_ATTRIBUTES]
1290 request
= ippNewRequest(op
);
1292 ippAddStrings(request
, IPP_TAG_OPERATION
, IPP_TAG_KEYWORD
,
1293 "requested-attributes", sizeof(pattrs
) / sizeof(pattrs
[0]),
1296 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
,
1297 "requesting-user-name", NULL
, cupsUser());
1299 if (name
&& op
!= CUPS_GET_DEFAULT
)
1301 httpAssembleURIf(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
), "ipp", NULL
,
1302 "localhost", ippPort(), "/printers/%s", name
);
1303 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
,
1308 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type",
1310 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type-mask",
1315 * Do the request and get back a response...
1318 if ((response
= cupsDoRequest(http
, request
, "/")) != NULL
)
1320 for (attr
= response
->attrs
; attr
!= NULL
; attr
= attr
->next
)
1323 * Skip leading attributes until we hit a printer...
1326 while (attr
!= NULL
&& attr
->group_tag
!= IPP_TAG_PRINTER
)
1333 * Pull the needed attributes from this printer...
1336 printer_name
= NULL
;
1340 for (; attr
&& attr
->group_tag
== IPP_TAG_PRINTER
; attr
= attr
->next
)
1342 if (attr
->value_tag
!= IPP_TAG_INTEGER
&&
1343 attr
->value_tag
!= IPP_TAG_ENUM
&&
1344 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
1345 attr
->value_tag
!= IPP_TAG_TEXT
&&
1346 attr
->value_tag
!= IPP_TAG_TEXTLANG
&&
1347 attr
->value_tag
!= IPP_TAG_NAME
&&
1348 attr
->value_tag
!= IPP_TAG_NAMELANG
&&
1349 attr
->value_tag
!= IPP_TAG_KEYWORD
&&
1350 attr
->value_tag
!= IPP_TAG_RANGE
&&
1351 attr
->value_tag
!= IPP_TAG_URI
)
1354 if (!strcmp(attr
->name
, "auth-info-required") ||
1355 !strcmp(attr
->name
, "device-uri") ||
1356 !strcmp(attr
->name
, "marker-change-time") ||
1357 !strcmp(attr
->name
, "marker-colors") ||
1358 !strcmp(attr
->name
, "marker-high-levels") ||
1359 !strcmp(attr
->name
, "marker-levels") ||
1360 !strcmp(attr
->name
, "marker-low-levels") ||
1361 !strcmp(attr
->name
, "marker-message") ||
1362 !strcmp(attr
->name
, "marker-names") ||
1363 !strcmp(attr
->name
, "marker-types") ||
1364 !strcmp(attr
->name
, "printer-commands") ||
1365 !strcmp(attr
->name
, "printer-info") ||
1366 !strcmp(attr
->name
, "printer-is-shared") ||
1367 !strcmp(attr
->name
, "printer-make-and-model") ||
1368 !strcmp(attr
->name
, "printer-state") ||
1369 !strcmp(attr
->name
, "printer-state-change-time") ||
1370 !strcmp(attr
->name
, "printer-type") ||
1371 !strcmp(attr
->name
, "printer-is-accepting-jobs") ||
1372 !strcmp(attr
->name
, "printer-location") ||
1373 !strcmp(attr
->name
, "printer-state-reasons") ||
1374 !strcmp(attr
->name
, "printer-uri-supported"))
1377 * Add a printer description attribute...
1380 num_options
= cupsAddOption(attr
->name
,
1381 cups_make_string(attr
, value
,
1383 num_options
, &options
);
1386 else if (!strcmp(attr
->name
, "media-supported"))
1389 * See if we can set a default media size...
1392 int i
; /* Looping var */
1394 for (i
= 0; i
< attr
->num_values
; i
++)
1395 if (!_cups_strcasecmp(media_default
, attr
->values
[i
].string
.text
))
1397 num_options
= cupsAddOption("media", media_default
, num_options
,
1402 #endif /* __APPLE__ */
1403 else if (!strcmp(attr
->name
, "printer-name") &&
1404 attr
->value_tag
== IPP_TAG_NAME
)
1405 printer_name
= attr
->values
[0].string
.text
;
1406 else if (strncmp(attr
->name
, "notify-", 7) &&
1407 (attr
->value_tag
== IPP_TAG_BOOLEAN
||
1408 attr
->value_tag
== IPP_TAG_ENUM
||
1409 attr
->value_tag
== IPP_TAG_INTEGER
||
1410 attr
->value_tag
== IPP_TAG_KEYWORD
||
1411 attr
->value_tag
== IPP_TAG_NAME
||
1412 attr
->value_tag
== IPP_TAG_RANGE
) &&
1413 (ptr
= strstr(attr
->name
, "-default")) != NULL
)
1416 * Add a default option...
1419 strlcpy(optname
, attr
->name
, sizeof(optname
));
1420 optname
[ptr
- attr
->name
] = '\0';
1422 if (_cups_strcasecmp(optname
, "media") ||
1423 !cupsGetOption("media", num_options
, options
))
1424 num_options
= cupsAddOption(optname
,
1425 cups_make_string(attr
, value
,
1427 num_options
, &options
);
1432 * See if we have everything needed...
1437 cupsFreeOptions(num_options
, options
);
1445 if ((dest
= cups_add_dest(printer_name
, NULL
, &num_dests
, dests
)) != NULL
)
1447 dest
->num_options
= num_options
;
1448 dest
->options
= options
;
1451 cupsFreeOptions(num_options
, options
);
1457 ippDelete(response
);
1461 * Return the count...
1469 * 'cupsGetDests()' - Get the list of destinations from the default server.
1471 * Starting with CUPS 1.2, the returned list of destinations include the
1472 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1473 * printer-make-and-model, printer-state, printer-state-change-time,
1474 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1475 * adds the marker-change-time, marker-colors, marker-high-levels,
1476 * marker-levels, marker-low-levels, marker-message, marker-names,
1477 * marker-types, and printer-commands attributes as well.
1479 * Use the @link cupsFreeDests@ function to free the destination list and
1480 * the @link cupsGetDest@ function to find a particular destination.
1483 int /* O - Number of destinations */
1484 cupsGetDests(cups_dest_t
**dests
) /* O - Destinations */
1486 return (cupsGetDests2(CUPS_HTTP_DEFAULT
, dests
));
1491 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1493 * Starting with CUPS 1.2, the returned list of destinations include the
1494 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1495 * printer-make-and-model, printer-state, printer-state-change-time,
1496 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1497 * adds the marker-change-time, marker-colors, marker-high-levels,
1498 * marker-levels, marker-low-levels, marker-message, marker-names,
1499 * marker-types, and printer-commands attributes as well.
1501 * Use the @link cupsFreeDests@ function to free the destination list and
1502 * the @link cupsGetDest@ function to find a particular destination.
1504 * @since CUPS 1.1.21/Mac OS X 10.4@
1507 int /* O - Number of destinations */
1508 cupsGetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1509 cups_dest_t
**dests
) /* O - Destinations */
1511 int i
; /* Looping var */
1512 int num_dests
; /* Number of destinations */
1513 cups_dest_t
*dest
; /* Destination pointer */
1514 const char *home
; /* HOME environment variable */
1515 char filename
[1024]; /* Local ~/.cups/lpoptions file */
1516 const char *defprinter
; /* Default printer */
1517 char name
[1024], /* Copy of printer name */
1518 *instance
, /* Pointer to instance name */
1519 *user_default
; /* User default printer */
1520 int num_reals
; /* Number of real queues */
1521 cups_dest_t
*reals
; /* Real queues */
1522 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1526 * Range check the input...
1531 _cupsSetError(IPP_INTERNAL_ERROR
, _("Bad NULL dests pointer"), 1);
1536 * Grab the printers and classes...
1539 *dests
= (cups_dest_t
*)0;
1540 num_dests
= _cupsGetDests(http
, CUPS_GET_PRINTERS
, NULL
, dests
, 0, 0);
1542 if (cupsLastError() >= IPP_REDIRECTION_OTHER_SITE
)
1544 cupsFreeDests(num_dests
, *dests
);
1545 *dests
= (cups_dest_t
*)0;
1550 * Make a copy of the "real" queues for a later sanity check...
1555 num_reals
= num_dests
;
1556 reals
= calloc(num_reals
, sizeof(cups_dest_t
));
1559 memcpy(reals
, *dests
, num_reals
* sizeof(cups_dest_t
));
1570 * Grab the default destination...
1573 if ((user_default
= _cupsUserDefault(name
, sizeof(name
))) != NULL
)
1575 else if ((defprinter
= cupsGetDefault2(http
)) != NULL
)
1577 strlcpy(name
, defprinter
, sizeof(name
));
1584 * Separate printer and instance name...
1587 if ((instance
= strchr(name
, '/')) != NULL
)
1591 * Lookup the printer and instance and make it the default...
1594 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) != NULL
)
1595 dest
->is_default
= 1;
1601 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
1604 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1605 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1608 if ((home
= getenv("HOME")) != NULL
)
1610 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1612 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1617 * Validate the current default destination - this prevents old
1618 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
1619 * pointing to a non-existent printer or class...
1625 * See if we have a default printer...
1628 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, *dests
)) != NULL
)
1631 * Have a default; see if it is real...
1634 dest
= cupsGetDest(dest
->name
, NULL
, num_reals
, reals
);
1638 * If dest is NULL, then no default (that exists) is set, so we
1639 * need to set a default if one exists...
1642 if (dest
== NULL
&& defprinter
!= NULL
)
1644 for (i
= 0; i
< num_dests
; i
++)
1645 (*dests
)[i
].is_default
= 0;
1647 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) != NULL
)
1648 dest
->is_default
= 1;
1659 * Return the number of destinations...
1663 _cupsSetError(IPP_OK
, NULL
, 0);
1670 * 'cupsGetNamedDest()' - Get options for the named destination.
1672 * This function is optimized for retrieving a single destination and should
1673 * be used instead of @link cupsGetDests@ and @link cupsGetDest@ when you either
1674 * know the name of the destination or want to print to the default destination.
1675 * If @code NULL@ is returned, the destination does not exist or there is no
1676 * default destination.
1678 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
1679 * server will be used.
1681 * If "name" is @code NULL@, the default printer for the current user will be
1684 * The returned destination must be freed using @link cupsFreeDests@ with a
1685 * "num_dests" value of 1.
1687 * @since CUPS 1.4/Mac OS X 10.6@
1690 cups_dest_t
* /* O - Destination or @code NULL@ */
1691 cupsGetNamedDest(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1692 const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1693 const char *instance
) /* I - Instance name or @code NULL@ */
1695 cups_dest_t
*dest
; /* Destination */
1696 char filename
[1024], /* Path to lpoptions */
1697 defname
[256]; /* Default printer name */
1698 const char *home
= getenv("HOME"); /* Home directory */
1699 int set_as_default
= 0; /* Set returned destination as default */
1700 ipp_op_t op
= IPP_GET_PRINTER_ATTRIBUTES
;
1701 /* IPP operation to get server ops */
1702 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1706 * If "name" is NULL, find the default destination...
1712 name
= _cupsUserDefault(defname
, sizeof(defname
));
1716 char *ptr
; /* Temporary pointer... */
1718 if ((ptr
= strchr(defname
, '/')) != NULL
)
1729 * No default in the environment, try the user's lpoptions files...
1732 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1734 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1740 * Still not there? Try the system lpoptions file...
1743 snprintf(filename
, sizeof(filename
), "%s/lpoptions",
1744 cg
->cups_serverroot
);
1745 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1751 * No locally-set default destination, ask the server...
1754 op
= CUPS_GET_DEFAULT
;
1759 * Get the printer's attributes...
1762 if (!_cupsGetDests(http
, op
, name
, &dest
, 0, 0))
1764 if (op
== CUPS_GET_DEFAULT
|| (name
&& !set_as_default
))
1768 * The default printer from environment variables or from a
1769 * configuration file does not exist. Find out the real default.
1772 if (!_cupsGetDests(http
, CUPS_GET_DEFAULT
, NULL
, &dest
, 0, 0))
1777 dest
->instance
= _cupsStrAlloc(instance
);
1780 dest
->is_default
= 1;
1783 * Then add local options...
1786 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1787 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
1791 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1793 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
1797 * Return the result...
1805 * 'cupsRemoveDest()' - Remove a destination from the destination list.
1807 * Removing a destination/instance does not delete the class or printer
1808 * queue, merely the lpoptions for that destination/instance. Use the
1809 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
1810 * options for the user.
1812 * @since CUPS 1.3/Mac OS X 10.5@
1815 int /* O - New number of destinations */
1816 cupsRemoveDest(const char *name
, /* I - Destination name */
1817 const char *instance
, /* I - Instance name or @code NULL@ */
1818 int num_dests
, /* I - Number of destinations */
1819 cups_dest_t
**dests
) /* IO - Destinations */
1821 int i
; /* Index into destinations */
1822 cups_dest_t
*dest
; /* Pointer to destination */
1826 * Find the destination...
1829 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
1836 _cupsStrFree(dest
->name
);
1837 _cupsStrFree(dest
->instance
);
1838 cupsFreeOptions(dest
->num_options
, dest
->options
);
1841 * Remove the destination from the array...
1849 memmove(dest
, dest
+ 1, (num_dests
- i
) * sizeof(cups_dest_t
));
1856 * 'cupsSetDefaultDest()' - Set the default destination.
1858 * @since CUPS 1.3/Mac OS X 10.5@
1863 const char *name
, /* I - Destination name */
1864 const char *instance
, /* I - Instance name or @code NULL@ */
1865 int num_dests
, /* I - Number of destinations */
1866 cups_dest_t
*dests
) /* I - Destinations */
1868 int i
; /* Looping var */
1869 cups_dest_t
*dest
; /* Current destination */
1873 * Range check input...
1876 if (!name
|| num_dests
<= 0 || !dests
)
1880 * Loop through the array and set the "is_default" flag for the matching
1884 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1885 dest
->is_default
= !_cups_strcasecmp(name
, dest
->name
) &&
1886 ((!instance
&& !dest
->instance
) ||
1887 (instance
&& dest
->instance
&&
1888 !_cups_strcasecmp(instance
, dest
->instance
)));
1893 * 'cupsSetDests()' - Save the list of destinations for the default server.
1895 * This function saves the destinations to /etc/cups/lpoptions when run
1896 * as root and ~/.cups/lpoptions when run as a normal user.
1900 cupsSetDests(int num_dests
, /* I - Number of destinations */
1901 cups_dest_t
*dests
) /* I - Destinations */
1903 cupsSetDests2(CUPS_HTTP_DEFAULT
, num_dests
, dests
);
1908 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
1910 * This function saves the destinations to /etc/cups/lpoptions when run
1911 * as root and ~/.cups/lpoptions when run as a normal user.
1913 * @since CUPS 1.1.21/Mac OS X 10.4@
1916 int /* O - 0 on success, -1 on error */
1917 cupsSetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1918 int num_dests
, /* I - Number of destinations */
1919 cups_dest_t
*dests
) /* I - Destinations */
1921 int i
, j
; /* Looping vars */
1922 int wrote
; /* Wrote definition? */
1923 cups_dest_t
*dest
; /* Current destination */
1924 cups_option_t
*option
; /* Current option */
1925 _ipp_option_t
*match
; /* Matching attribute for option */
1926 FILE *fp
; /* File pointer */
1928 const char *home
; /* HOME environment variable */
1930 char filename
[1024]; /* lpoptions file */
1931 int num_temps
; /* Number of temporary destinations */
1932 cups_dest_t
*temps
, /* Temporary destinations */
1933 *temp
; /* Current temporary dest */
1934 const char *val
; /* Value of temporary option */
1935 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1939 * Range check the input...
1942 if (!num_dests
|| !dests
)
1946 * Get the server destinations...
1949 num_temps
= _cupsGetDests(http
, CUPS_GET_PRINTERS
, NULL
, &temps
, 0, 0);
1951 if (cupsLastError() >= IPP_REDIRECTION_OTHER_SITE
)
1953 cupsFreeDests(num_temps
, temps
);
1958 * Figure out which file to write to...
1961 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1967 * Merge in server defaults...
1970 num_temps
= cups_get_dests(filename
, NULL
, NULL
, 0, num_temps
, &temps
);
1973 * Point to user defaults...
1976 if ((home
= getenv("HOME")) != NULL
)
1979 * Create ~/.cups subdirectory...
1982 snprintf(filename
, sizeof(filename
), "%s/.cups", home
);
1983 if (access(filename
, 0))
1984 mkdir(filename
, 0700);
1986 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1992 * Try to open the file...
1995 if ((fp
= fopen(filename
, "w")) == NULL
)
1997 cupsFreeDests(num_temps
, temps
);
2003 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2008 fchmod(fileno(fp
), 0644);
2012 * Write each printer; each line looks like:
2014 * Dest name[/instance] options
2015 * Default name[/instance] options
2018 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
2019 if (dest
->instance
!= NULL
|| dest
->num_options
!= 0 || dest
->is_default
)
2021 if (dest
->is_default
)
2023 fprintf(fp
, "Default %s", dest
->name
);
2025 fprintf(fp
, "/%s", dest
->instance
);
2032 if ((temp
= cupsGetDest(dest
->name
, dest
->instance
, num_temps
, temps
)) == NULL
)
2033 temp
= cupsGetDest(dest
->name
, NULL
, num_temps
, temps
);
2035 for (j
= dest
->num_options
, option
= dest
->options
; j
> 0; j
--, option
++)
2038 * See if this option is a printer attribute; if so, skip it...
2041 if ((match
= _ippFindOption(option
->name
)) != NULL
&&
2042 match
->group_tag
== IPP_TAG_PRINTER
)
2046 * See if the server/global options match these; if so, don't
2051 (val
= cupsGetOption(option
->name
, temp
->num_options
,
2052 temp
->options
)) != NULL
&&
2053 !_cups_strcasecmp(val
, option
->value
))
2057 * Options don't match, write to the file...
2062 fprintf(fp
, "Dest %s", dest
->name
);
2064 fprintf(fp
, "/%s", dest
->instance
);
2068 if (option
->value
[0])
2070 if (strchr(option
->value
, ' ') ||
2071 strchr(option
->value
, '\\') ||
2072 strchr(option
->value
, '\"') ||
2073 strchr(option
->value
, '\''))
2076 * Quote the value...
2079 fprintf(fp
, " %s=\"", option
->name
);
2081 for (val
= option
->value
; *val
; val
++)
2083 if (strchr("\"\'\\", *val
))
2094 * Store the literal value...
2097 fprintf(fp
, " %s=%s", option
->name
, option
->value
);
2101 fprintf(fp
, " %s", option
->name
);
2109 * Free the temporary destinations and close the file...
2112 cupsFreeDests(num_temps
, temps
);
2118 * Set the default printer for this location - this allows command-line
2119 * and GUI applications to share the same default destination...
2122 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, dests
)) != NULL
)
2124 CFStringRef name
= CFStringCreateWithCString(kCFAllocatorDefault
,
2126 kCFStringEncodingUTF8
);
2127 /* Default printer name */
2131 _cupsAppleSetDefaultPrinter(name
);
2135 #endif /* __APPLE__ */
2137 #ifdef HAVE_NOTIFY_POST
2139 * Send a notification so that MacOS X applications can know about the
2143 notify_post("com.apple.printerListChange");
2144 #endif /* HAVE_NOTIFY_POST */
2151 * '_cupsUserDefault()' - Get the user default printer from environment
2152 * variables and location information.
2155 char * /* O - Default printer or NULL */
2156 _cupsUserDefault(char *name
, /* I - Name buffer */
2157 size_t namesize
) /* I - Size of name buffer */
2159 const char *env
; /* LPDEST or PRINTER env variable */
2161 CFStringRef locprinter
; /* Last printer as this location */
2162 #endif /* __APPLE__ */
2165 if ((env
= getenv("LPDEST")) == NULL
)
2166 if ((env
= getenv("PRINTER")) != NULL
&& !strcmp(env
, "lp"))
2171 strlcpy(name
, env
, namesize
);
2177 * Use location-based defaults if "use last printer" is selected in the
2178 * system preferences...
2181 if ((locprinter
= _cupsAppleCopyDefaultPrinter()) != NULL
)
2183 CFStringGetCString(locprinter
, name
, namesize
, kCFStringEncodingUTF8
);
2184 CFRelease(locprinter
);
2189 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name
));
2191 return (*name
? name
: NULL
);
2195 * No location-based defaults on this platform...
2200 #endif /* __APPLE__ */
2206 * 'appleCopyLocations()' - Copy the location history array.
2209 static CFArrayRef
/* O - Location array or NULL */
2210 appleCopyLocations(void)
2212 CFArrayRef locations
; /* Location array */
2216 * Look up the location array in the preferences...
2219 if ((locations
= CFPreferencesCopyAppValue(kLastUsedPrintersKey
,
2220 kCUPSPrintingPrefs
)) == NULL
)
2223 if (CFGetTypeID(locations
) != CFArrayGetTypeID())
2225 CFRelease(locations
);
2234 * 'appleCopyNetwork()' - Get the network ID for the current location.
2237 static CFStringRef
/* O - Network ID */
2238 appleCopyNetwork(void)
2240 SCDynamicStoreRef dynamicStore
; /* System configuration data */
2241 CFStringRef key
; /* Current network configuration key */
2242 CFDictionaryRef ip_dict
; /* Network configuration data */
2243 CFStringRef network
= NULL
; /* Current network ID */
2246 if ((dynamicStore
= SCDynamicStoreCreate(NULL
, CFSTR("libcups"), NULL
,
2250 * First use the IPv6 router address, if available, since that will generally
2251 * be a globally-unique link-local address.
2254 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2255 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv6
)) != NULL
)
2257 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2259 if ((network
= CFDictionaryGetValue(ip_dict
,
2260 kSCPropNetIPv6Router
)) != NULL
)
2270 * If that doesn't work, try the IPv4 router address. This isn't as unique
2271 * and will likely be a 10.x.y.z or 192.168.y.z address...
2276 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2277 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv4
)) != NULL
)
2279 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2281 if ((network
= CFDictionaryGetValue(ip_dict
,
2282 kSCPropNetIPv4Router
)) != NULL
)
2292 CFRelease(dynamicStore
);
2300 * 'appleGetPaperSize()' - Get the default paper size.
2303 char * /* O - Default paper size */
2304 appleGetPaperSize(char *name
, /* I - Paper size name buffer */
2305 int namesize
) /* I - Size of buffer */
2307 CFStringRef defaultPaperID
; /* Default paper ID */
2308 _pwg_media_t
*pwgmedia
; /* PWG media size */
2311 defaultPaperID
= _cupsAppleCopyDefaultPaperID();
2312 if (!defaultPaperID
||
2313 CFGetTypeID(defaultPaperID
) != CFStringGetTypeID() ||
2314 !CFStringGetCString(defaultPaperID
, name
, namesize
,
2315 kCFStringEncodingUTF8
))
2317 else if ((pwgmedia
= _pwgMediaForLegacy(name
)) != NULL
)
2318 strlcpy(name
, pwgmedia
->pwg
, namesize
);
2321 CFRelease(defaultPaperID
);
2328 * 'appleGetPrinter()' - Get a printer from the history array.
2331 static CFStringRef
/* O - Printer name or NULL */
2332 appleGetPrinter(CFArrayRef locations
, /* I - Location array */
2333 CFStringRef network
, /* I - Network name */
2334 CFIndex
*locindex
) /* O - Index in array */
2336 CFIndex i
, /* Looping var */
2337 count
; /* Number of locations */
2338 CFDictionaryRef location
; /* Current location */
2339 CFStringRef locnetwork
, /* Current network */
2340 locprinter
; /* Current printer */
2343 for (i
= 0, count
= CFArrayGetCount(locations
); i
< count
; i
++)
2344 if ((location
= CFArrayGetValueAtIndex(locations
, i
)) != NULL
&&
2345 CFGetTypeID(location
) == CFDictionaryGetTypeID())
2347 if ((locnetwork
= CFDictionaryGetValue(location
,
2348 kLocationNetworkKey
)) != NULL
&&
2349 CFGetTypeID(locnetwork
) == CFStringGetTypeID() &&
2350 CFStringCompare(network
, locnetwork
, 0) == kCFCompareEqualTo
&&
2351 (locprinter
= CFDictionaryGetValue(location
,
2352 kLocationPrinterIDKey
)) != NULL
&&
2353 CFGetTypeID(locprinter
) == CFStringGetTypeID())
2358 return (locprinter
);
2364 #endif /* __APPLE__ */
2368 * 'cups_add_dest()' - Add a destination to the array.
2370 * Unlike cupsAddDest(), this function does not check for duplicates.
2373 static cups_dest_t
* /* O - New destination */
2374 cups_add_dest(const char *name
, /* I - Name of destination */
2375 const char *instance
, /* I - Instance or NULL */
2376 int *num_dests
, /* IO - Number of destinations */
2377 cups_dest_t
**dests
) /* IO - Destinations */
2379 int insert
, /* Insertion point */
2380 diff
; /* Result of comparison */
2381 cups_dest_t
*dest
; /* Destination pointer */
2385 * Add new destination...
2388 if (*num_dests
== 0)
2389 dest
= malloc(sizeof(cups_dest_t
));
2391 dest
= realloc(*dests
, sizeof(cups_dest_t
) * (*num_dests
+ 1));
2399 * Find where to insert the destination...
2402 if (*num_dests
== 0)
2406 insert
= cups_find_dest(name
, instance
, *num_dests
, *dests
, *num_dests
- 1,
2414 * Move the array elements as needed...
2417 if (insert
< *num_dests
)
2418 memmove(*dests
+ insert
+ 1, *dests
+ insert
,
2419 (*num_dests
- insert
) * sizeof(cups_dest_t
));
2424 * Initialize the destination...
2427 dest
= *dests
+ insert
;
2428 dest
->name
= _cupsStrAlloc(name
);
2429 dest
->instance
= _cupsStrAlloc(instance
);
2430 dest
->is_default
= 0;
2431 dest
->num_options
= 0;
2432 dest
->options
= (cups_option_t
*)0;
2440 * 'cups_block_cb()' - Enumeration callback for block API.
2443 static int /* O - 1 to continue, 0 to stop */
2445 cups_dest_block_t block
, /* I - Block */
2446 unsigned flags
, /* I - Destination flags */
2447 cups_dest_t
*dest
) /* I - Destination */
2449 return ((block
)(flags
, dest
));
2451 # endif /* __BLOCKS__ */
2455 * 'cups_compare_dests()' - Compare two destinations.
2458 static int /* O - Result of comparison */
2459 cups_compare_dests(cups_dest_t
*a
, /* I - First destination */
2460 cups_dest_t
*b
) /* I - Second destination */
2462 int diff
; /* Difference */
2465 if ((diff
= _cups_strcasecmp(a
->name
, b
->name
)) != 0)
2467 else if (a
->instance
&& b
->instance
)
2468 return (_cups_strcasecmp(a
->instance
, b
->instance
));
2470 return ((a
->instance
&& !b
->instance
) - (!a
->instance
&& b
->instance
));
2476 * 'cups_dnssd_browse_cb()' - Browse for printers.
2480 cups_dnssd_browse_cb(
2481 DNSServiceRef sdRef
, /* I - Service reference */
2482 DNSServiceFlags flags
, /* I - Option flags */
2483 uint32_t interfaceIndex
, /* I - Interface number */
2484 DNSServiceErrorType errorCode
, /* I - Error, if any */
2485 const char *serviceName
, /* I - Name of service/device */
2486 const char *regtype
, /* I - Type of service */
2487 const char *replyDomain
, /* I - Service domain */
2488 void *context
) /* I - Enumeration data */
2490 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2491 /* Enumeration data */
2494 DEBUG_printf(("5cups_dnssd_browse_cb(sdRef=%p, flags=%x, "
2495 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2496 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2497 sdRef
, flags
, interfaceIndex
, errorCode
, serviceName
, regtype
,
2498 replyDomain
, context
));
2501 * Don't do anything on error...
2504 if (errorCode
!= kDNSServiceErr_NoError
)
2511 cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2516 * 'cups_dnssd_compare_device()' - Compare two devices.
2519 static int /* O - Result of comparison */
2520 cups_dnssd_compare_devices(
2521 _cups_dnssd_device_t
*a
, /* I - First device */
2522 _cups_dnssd_device_t
*b
) /* I - Second device */
2524 return (strcmp(a
->dest
.name
, b
->dest
.name
));
2529 * 'cups_dnssd_free_device()' - Free the memory used by a device.
2533 cups_dnssd_free_device(
2534 _cups_dnssd_device_t
*device
, /* I - Device */
2535 _cups_dnssd_data_t
*data
) /* I - Enumeration data */
2537 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", device
,
2538 device
->dest
.name
, data
));
2541 DNSServiceRefDeallocate(device
->ref
);
2543 _cupsStrFree(device
->domain
);
2544 _cupsStrFree(device
->fullName
);
2545 _cupsStrFree(device
->regtype
);
2546 _cupsStrFree(device
->dest
.name
);
2548 cupsFreeOptions(device
->dest
.num_options
, device
->dest
.options
);
2555 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
2558 static _cups_dnssd_device_t
* /* O - Device */
2559 cups_dnssd_get_device(
2560 _cups_dnssd_data_t
*data
, /* I - Enumeration data */
2561 const char *serviceName
, /* I - Service name */
2562 const char *regtype
, /* I - Registration type */
2563 const char *replyDomain
) /* I - Domain name */
2565 _cups_dnssd_device_t key
, /* Search key */
2566 *device
; /* Device */
2567 char fullName
[kDNSServiceMaxDomainName
];
2568 /* Full name for query */
2571 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", "
2572 "regtype=\"%s\", replyDomain=\"%s\")", data
, serviceName
,
2573 regtype
, replyDomain
));
2576 * See if this is an existing device...
2579 key
.dest
.name
= (char *)serviceName
;
2581 if ((device
= cupsArrayFind(data
->devices
, &key
)) != NULL
)
2584 * Yes, see if we need to do anything with this...
2587 int update
= 0; /* Non-zero if we need to update */
2589 if (!_cups_strcasecmp(replyDomain
, "local.") &&
2590 _cups_strcasecmp(device
->domain
, replyDomain
))
2593 * Update the "global" listing to use the .local domain name instead.
2596 _cupsStrFree(device
->domain
);
2597 device
->domain
= _cupsStrAlloc(replyDomain
);
2599 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
2600 "domain.", device
->dest
.name
));
2605 if (!_cups_strcasecmp(regtype
, "_ipps._tcp") &&
2606 _cups_strcasecmp(device
->regtype
, regtype
))
2609 * Prefer IPPS over IPP.
2612 _cupsStrFree(device
->regtype
);
2613 device
->regtype
= _cupsStrAlloc(regtype
);
2615 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
2616 device
->dest
.name
));
2623 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
2624 device
->dest
.name
));
2631 * No, add the device...
2634 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
2635 "'%s'.", serviceName
,
2636 !strcmp(regtype
, "_ipps._tcp") ? "IPPS" : "IPP",
2639 device
= calloc(sizeof(_cups_dnssd_device_t
), 1);
2640 device
->dest
.name
= _cupsStrAlloc(serviceName
);
2641 device
->domain
= _cupsStrAlloc(replyDomain
);
2642 device
->regtype
= _cupsStrAlloc(regtype
);
2644 cupsArrayAdd(data
->devices
, device
);
2648 * Set the "full name" of this service, which is used for queries...
2651 DNSServiceConstructFullName(fullName
, device
->dest
.name
, device
->regtype
,
2653 _cupsStrFree(device
->fullName
);
2654 device
->fullName
= _cupsStrAlloc(fullName
);
2658 DNSServiceRefDeallocate(device
->ref
);
2662 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
2664 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
2665 device
->state
= _CUPS_DNSSD_NEW
;
2673 * 'cups_dnssd_local_cb()' - Browse for local printers.
2677 cups_dnssd_local_cb(
2678 DNSServiceRef sdRef
, /* I - Service reference */
2679 DNSServiceFlags flags
, /* I - Option flags */
2680 uint32_t interfaceIndex
, /* I - Interface number */
2681 DNSServiceErrorType errorCode
, /* I - Error, if any */
2682 const char *serviceName
, /* I - Name of service/device */
2683 const char *regtype
, /* I - Type of service */
2684 const char *replyDomain
, /* I - Service domain */
2685 void *context
) /* I - Devices array */
2687 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2688 /* Enumeration data */
2689 _cups_dnssd_device_t
*device
; /* Device */
2692 DEBUG_printf(("5cups_dnssd_local_cb(sdRef=%p, flags=%x, "
2693 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2694 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2695 sdRef
, flags
, interfaceIndex
, errorCode
, serviceName
,
2696 regtype
, replyDomain
, context
));
2699 * Only process "add" data...
2702 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
2709 device
= cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2712 * Hide locally-registered devices...
2715 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
2720 DNSServiceRefDeallocate(device
->ref
);
2724 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
2725 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
2727 device
->state
= _CUPS_DNSSD_LOCAL
;
2732 * 'cups_dnssd_query_cb()' - Process query data.
2736 cups_dnssd_query_cb(
2737 DNSServiceRef sdRef
, /* I - Service reference */
2738 DNSServiceFlags flags
, /* I - Data flags */
2739 uint32_t interfaceIndex
, /* I - Interface */
2740 DNSServiceErrorType errorCode
, /* I - Error, if any */
2741 const char *fullName
, /* I - Full service name */
2742 uint16_t rrtype
, /* I - Record type */
2743 uint16_t rrclass
, /* I - Record class */
2744 uint16_t rdlen
, /* I - Length of record data */
2745 const void *rdata
, /* I - Record data */
2746 uint32_t ttl
, /* I - Time-to-live */
2747 void *context
) /* I - Enumeration data */
2749 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2750 /* Enumeration data */
2751 char name
[1024], /* Service name */
2752 *ptr
; /* Pointer into string */
2753 _cups_dnssd_device_t dkey
, /* Search key */
2754 *device
; /* Device */
2757 DEBUG_printf(("5cups_dnssd_query_cb(sdRef=%p, flags=%x, "
2758 "interfaceIndex=%d, errorCode=%d, fullName=\"%s\", "
2759 "rrtype=%u, rrclass=%u, rdlen=%u, rdata=%p, ttl=%u, "
2760 "context=%p)", sdRef
, flags
, interfaceIndex
, errorCode
,
2761 fullName
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, context
));
2764 * Only process "add" data...
2767 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
2771 * Lookup the service in the devices array.
2774 dkey
.dest
.name
= name
;
2776 cups_dnssd_unquote(name
, fullName
, sizeof(name
));
2778 if ((ptr
= strstr(name
, "._")) != NULL
)
2781 if ((device
= cupsArrayFind(data
->devices
, &dkey
)) != NULL
)
2784 * Found it, pull out the priority and make and model from the TXT
2785 * record and save it...
2788 const uint8_t *txt
, /* Pointer into data */
2789 *txtnext
, /* Next key/value pair */
2790 *txtend
; /* End of entire TXT record */
2791 uint8_t txtlen
; /* Length of current key/value pair */
2792 char key
[256], /* Key string */
2793 value
[256], /* Value string */
2794 make_and_model
[512],
2795 /* Manufacturer and model */
2796 model
[256], /* Model */
2797 uriname
[1024], /* Name for URI */
2798 uri
[1024]; /* Printer URI */
2799 cups_ptype_t type
; /* Device type */
2801 device
->state
= _CUPS_DNSSD_PENDING
;
2802 make_and_model
[0] = '\0';
2803 type
= CUPS_PRINTER_REMOTE
;
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
);
2879 type
= strtol(value
, NULL
, 0);
2884 * Save the make-and-model...
2887 if (make_and_model
[0])
2889 strlcat(make_and_model
, " ", sizeof(make_and_model
));
2890 strlcat(make_and_model
, model
, sizeof(make_and_model
));
2892 device
->dest
.num_options
= cupsAddOption("printer-make-and-model",
2894 device
->dest
.num_options
,
2895 &device
->dest
.options
);
2898 device
->dest
.num_options
= cupsAddOption("printer-make-and-model",
2900 device
->dest
.num_options
,
2901 &device
->dest
.options
);
2907 cups_dnssd_unquote(uriname
, device
->fullName
, sizeof(uriname
));
2908 httpAssembleURI(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
),
2909 !strcmp(device
->regtype
, "_ipps._tcp") ? "ipps" : "ipp",
2910 NULL
, uriname
, 0, "/cups");
2912 DEBUG_printf(("6cups_dnssd_query: printer-uri-supported=\"%s\"", uri
));
2914 device
->dest
.num_options
= cupsAddOption("printer-uri-supported", uri
,
2915 device
->dest
.num_options
,
2916 &device
->dest
.options
);
2919 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
2925 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
2928 static const char * /* O - Resolved URI or NULL */
2930 cups_dest_t
*dest
, /* I - Destination */
2931 const char *uri
, /* I - Current printer URI */
2932 int msec
, /* I - Time in milliseconds */
2933 int *cancel
, /* I - Pointer to "cancel" variable */
2934 cups_dest_cb_t cb
, /* I - Callback */
2935 void *user_data
) /* I - User data for callback */
2937 char tempuri
[1024]; /* Temporary URI buffer */
2938 _cups_dnssd_resolve_t resolve
; /* Resolve data */
2942 * Resolve the URI...
2945 resolve
.cancel
= cancel
;
2946 gettimeofday(&resolve
.end_time
, NULL
);
2949 resolve
.end_time
.tv_sec
+= msec
/ 1000;
2950 resolve
.end_time
.tv_usec
+= (msec
% 1000) * 1000;
2952 while (resolve
.end_time
.tv_usec
>= 1000000)
2954 resolve
.end_time
.tv_sec
++;
2955 resolve
.end_time
.tv_usec
-= 1000000;
2959 resolve
.end_time
.tv_sec
+= 75;
2962 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
,
2965 if ((uri
= _httpResolveURI(uri
, tempuri
, sizeof(tempuri
),
2966 _HTTP_RESOLVE_FQDN
, cups_dnssd_resolve_cb
,
2969 _cupsSetError(IPP_INTERNAL_ERROR
, _("Unable to resolve printer URI."), 1);
2972 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
2979 * Save the resolved URI...
2982 dest
->num_options
= cupsAddOption("printer-uri-supported", uri
,
2983 dest
->num_options
, &dest
->options
);
2985 return (cupsGetOption("printer-uri-supported", dest
->num_options
,
2991 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
2994 static int /* O - 1 to continue, 0 to stop */
2995 cups_dnssd_resolve_cb(void *context
) /* I - Resolve data */
2997 _cups_dnssd_resolve_t
*resolve
= (_cups_dnssd_resolve_t
*)context
;
2999 struct timeval curtime
; /* Current time */
3003 * If the cancel variable is set, return immediately.
3006 if (*resolve
->cancel
)
3010 * Otherwise check the end time...
3013 gettimeofday(&curtime
, NULL
);
3015 return (curtime
.tv_sec
> resolve
->end_time
.tv_sec
||
3016 (curtime
.tv_sec
== resolve
->end_time
.tv_sec
&&
3017 curtime
.tv_usec
> resolve
->end_time
.tv_usec
));
3022 * 'cups_dnssd_unquote()' - Unquote a name string.
3026 cups_dnssd_unquote(char *dst
, /* I - Destination buffer */
3027 const char *src
, /* I - Source string */
3028 size_t dstsize
) /* I - Size of destination buffer */
3030 char *dstend
= dst
+ dstsize
- 1; /* End of destination buffer */
3033 while (*src
&& dst
< dstend
)
3038 if (isdigit(src
[0] & 255) && isdigit(src
[1] & 255) &&
3039 isdigit(src
[2] & 255))
3041 *dst
++ = ((((src
[0] - '0') * 10) + src
[1] - '0') * 10) + src
[2] - '0';
3053 #endif /* HAVE_DNSSD */
3057 * 'cups_find_dest()' - Find a destination using a binary search.
3060 static int /* O - Index of match */
3061 cups_find_dest(const char *name
, /* I - Destination name */
3062 const char *instance
, /* I - Instance or NULL */
3063 int num_dests
, /* I - Number of destinations */
3064 cups_dest_t
*dests
, /* I - Destinations */
3065 int prev
, /* I - Previous index */
3066 int *rdiff
) /* O - Difference of match */
3068 int left
, /* Low mark for binary search */
3069 right
, /* High mark for binary search */
3070 current
, /* Current index */
3071 diff
; /* Result of comparison */
3072 cups_dest_t key
; /* Search key */
3075 key
.name
= (char *)name
;
3076 key
.instance
= (char *)instance
;
3081 * Start search on either side of previous...
3084 if ((diff
= cups_compare_dests(&key
, dests
+ prev
)) == 0 ||
3085 (diff
< 0 && prev
== 0) ||
3086 (diff
> 0 && prev
== (num_dests
- 1)))
3094 * Start with previous on right side...
3103 * Start wih previous on left side...
3107 right
= num_dests
- 1;
3113 * Start search in the middle...
3117 right
= num_dests
- 1;
3122 current
= (left
+ right
) / 2;
3123 diff
= cups_compare_dests(&key
, dests
+ current
);
3132 while ((right
- left
) > 1);
3137 * Check the last 1 or 2 elements...
3140 if ((diff
= cups_compare_dests(&key
, dests
+ left
)) <= 0)
3144 diff
= cups_compare_dests(&key
, dests
+ right
);
3150 * Return the closest destination and the difference...
3160 * 'cups_get_default()' - Get the default destination from an lpoptions file.
3163 static char * /* O - Default destination or NULL */
3164 cups_get_default(const char *filename
, /* I - File to read */
3165 char *namebuf
, /* I - Name buffer */
3166 size_t namesize
, /* I - Size of name buffer */
3167 const char **instance
) /* I - Instance */
3169 cups_file_t
*fp
; /* lpoptions file */
3170 char line
[8192], /* Line from file */
3171 *value
, /* Value for line */
3172 *nameptr
; /* Pointer into name */
3173 int linenum
; /* Current line */
3178 if ((fp
= cupsFileOpen(filename
, "r")) != NULL
)
3182 while (cupsFileGetConf(fp
, line
, sizeof(line
), &value
, &linenum
))
3184 if (!_cups_strcasecmp(line
, "default") && value
)
3186 strlcpy(namebuf
, value
, namesize
);
3188 if ((nameptr
= strchr(namebuf
, ' ')) != NULL
)
3190 if ((nameptr
= strchr(namebuf
, '\t')) != NULL
)
3193 if ((nameptr
= strchr(namebuf
, '/')) != NULL
)
3196 *instance
= nameptr
;
3204 return (*namebuf
? namebuf
: NULL
);
3209 * 'cups_get_dests()' - Get destinations from a file.
3212 static int /* O - Number of destinations */
3214 const char *filename
, /* I - File to read from */
3215 const char *match_name
, /* I - Destination name we want */
3216 const char *match_inst
, /* I - Instance name we want */
3217 int user_default_set
, /* I - User default printer set? */
3218 int num_dests
, /* I - Number of destinations */
3219 cups_dest_t
**dests
) /* IO - Destinations */
3221 int i
; /* Looping var */
3222 cups_dest_t
*dest
; /* Current destination */
3223 cups_file_t
*fp
; /* File pointer */
3224 char line
[8192], /* Line from file */
3225 *lineptr
, /* Pointer into line */
3226 *name
, /* Name of destination/option */
3227 *instance
; /* Instance of destination */
3228 int linenum
; /* Current line number */
3231 DEBUG_printf(("7cups_get_dests(filename=\"%s\", match_name=\"%s\", "
3232 "match_inst=\"%s\", user_default_set=%d, num_dests=%d, "
3233 "dests=%p)", filename
, match_name
, match_inst
,
3234 user_default_set
, num_dests
, dests
));
3237 * Try to open the file...
3240 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
3244 * Read each printer; each line looks like:
3246 * Dest name[/instance] options
3247 * Default name[/instance] options
3252 while (cupsFileGetConf(fp
, line
, sizeof(line
), &lineptr
, &linenum
))
3255 * See what type of line it is...
3258 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
3259 linenum
, line
, lineptr
));
3261 if ((_cups_strcasecmp(line
, "dest") && _cups_strcasecmp(line
, "default")) || !lineptr
)
3263 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
3270 * Search for an instance...
3273 while (!isspace(*lineptr
& 255) && *lineptr
&& *lineptr
!= '/')
3276 if (*lineptr
== '/')
3279 * Found an instance...
3286 * Search for an instance...
3289 while (!isspace(*lineptr
& 255) && *lineptr
)
3298 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name
,
3302 * See if the primary instance of the destination exists; if not,
3303 * ignore this entry and move on...
3308 if (_cups_strcasecmp(name
, match_name
) ||
3309 (!instance
&& match_inst
) ||
3310 (instance
&& !match_inst
) ||
3311 (instance
&& _cups_strcasecmp(instance
, match_inst
)))
3316 else if (cupsGetDest(name
, NULL
, num_dests
, *dests
) == NULL
)
3318 DEBUG_puts("9cups_get_dests: Not found!");
3324 * Add the destination...
3327 num_dests
= cupsAddDest(name
, instance
, num_dests
, dests
);
3329 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
3335 DEBUG_puts("9cups_get_dests: Out of memory!");
3341 * Add options until we hit the end of the line...
3344 dest
->num_options
= cupsParseOptions(lineptr
, dest
->num_options
,
3348 * If we found what we were looking for, stop now...
3355 * Set this as default if needed...
3358 if (!user_default_set
&& !_cups_strcasecmp(line
, "default"))
3360 DEBUG_puts("9cups_get_dests: Setting as default...");
3362 for (i
= 0; i
< num_dests
; i
++)
3363 (*dests
)[i
].is_default
= 0;
3365 dest
->is_default
= 1;
3370 * Close the file and return...
3380 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
3384 static char * /* O - New string */
3386 ipp_attribute_t
*attr
, /* I - Attribute to convert */
3387 char *buffer
, /* I - Buffer */
3388 size_t bufsize
) /* I - Size of buffer */
3390 int i
; /* Looping var */
3391 char *ptr
, /* Pointer into buffer */
3392 *end
, /* Pointer to end of buffer */
3393 *valptr
; /* Pointer into string attribute */
3397 * Return quickly if we have a single string value...
3400 if (attr
->num_values
== 1 &&
3401 attr
->value_tag
!= IPP_TAG_INTEGER
&&
3402 attr
->value_tag
!= IPP_TAG_ENUM
&&
3403 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
3404 attr
->value_tag
!= IPP_TAG_RANGE
)
3405 return (attr
->values
[0].string
.text
);
3408 * Copy the values to the string, separating with commas and escaping strings
3412 end
= buffer
+ bufsize
- 1;
3414 for (i
= 0, ptr
= buffer
; i
< attr
->num_values
&& ptr
< end
; i
++)
3419 switch (attr
->value_tag
)
3421 case IPP_TAG_INTEGER
:
3423 snprintf(ptr
, end
- ptr
+ 1, "%d", attr
->values
[i
].integer
);
3426 case IPP_TAG_BOOLEAN
:
3427 if (attr
->values
[i
].boolean
)
3428 strlcpy(ptr
, "true", end
- ptr
+ 1);
3430 strlcpy(ptr
, "false", end
- ptr
+ 1);
3433 case IPP_TAG_RANGE
:
3434 if (attr
->values
[i
].range
.lower
== attr
->values
[i
].range
.upper
)
3435 snprintf(ptr
, end
- ptr
+ 1, "%d", attr
->values
[i
].range
.lower
);
3437 snprintf(ptr
, end
- ptr
+ 1, "%d-%d", attr
->values
[i
].range
.lower
,
3438 attr
->values
[i
].range
.upper
);
3442 for (valptr
= attr
->values
[i
].string
.text
;
3443 *valptr
&& ptr
< end
;)
3445 if (strchr(" \t\n\\\'\"", *valptr
))
3447 if (ptr
>= (end
- 1))
3470 * End of "$Id: dest.c 9568 2011-02-25 06:13:56Z mike $".