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 encryption
; /* 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 encryption
= HTTP_ENCRYPT_ALWAYS
;
672 encryption
= HTTP_ENCRYPT_IF_REQUESTED
;
674 http
= _httpCreate(hostname
, port
, addrlist
, encryption
, 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
,
909 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
911 local_ipp_ref
= data
.main_ref
;
912 DNSServiceBrowse(&local_ipp_ref
, kDNSServiceFlagsShareConnection
,
913 kDNSServiceInterfaceIndexLocalOnly
,
914 "_ipp._tcp,_cups", NULL
,
915 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
918 ipps_ref
= data
.main_ref
;
919 DNSServiceBrowse(&ipps_ref
, kDNSServiceFlagsShareConnection
, 0,
920 "_ipps._tcp,_cups", NULL
,
921 (DNSServiceBrowseReply
)cups_dnssd_browse_cb
, &data
);
923 local_ipps_ref
= data
.main_ref
;
924 DNSServiceBrowse(&local_ipps_ref
, kDNSServiceFlagsShareConnection
,
925 kDNSServiceInterfaceIndexLocalOnly
,
926 "_ipps._tcp,_cups", NULL
,
927 (DNSServiceBrowseReply
)cups_dnssd_local_cb
, &data
);
928 # endif /* HAVE_SSL */
935 while (remaining
> 0 && (!cancel
|| !*cancel
))
945 nfds
= poll(&pfd
, 1, remaining
> 250 ? 250 : remaining
);
949 FD_SET(main_fd
, &input
);
952 timeout
.tv_usec
= remaining
> 250 ? 250000 : remaining
* 1000;
954 nfds
= select(main_fd
+ 1, &input
, NULL
, NULL
, &timeout
);
955 # endif /* HAVE_POLL */
958 DNSServiceProcessResult(data
.main_ref
);
962 for (device
= (_cups_dnssd_device_t
*)cupsArrayFirst(data
.devices
),
965 device
= (_cups_dnssd_device_t
*)cupsArrayNext(data
.devices
))
970 if (!device
->ref
&& device
->state
== _CUPS_DNSSD_NEW
)
972 device
->ref
= data
.main_ref
;
974 DEBUG_printf(("1cupsEnumDests: Querying '%s'.", device
->fullName
));
976 if (DNSServiceQueryRecord(&(device
->ref
),
977 kDNSServiceFlagsShareConnection
,
981 (DNSServiceQueryRecordReply
)cups_dnssd_query_cb
,
982 &data
) == kDNSServiceErr_NoError
)
989 device
->state
= _CUPS_DNSSD_ERROR
;
991 DEBUG_puts("1cupsEnumDests: Query failed.");
994 else if (device
->ref
&& device
->state
== _CUPS_DNSSD_PENDING
)
996 if (!(*cb
)(user_data
, CUPS_DEST_FLAGS_NONE
, &device
->dest
))
1002 device
->state
= _CUPS_DNSSD_ACTIVE
;
1007 cupsArrayDelete(data
.devices
);
1009 DNSServiceRefDeallocate(ipp_ref
);
1010 DNSServiceRefDeallocate(local_ipp_ref
);
1013 DNSServiceRefDeallocate(ipp_ref
);
1014 DNSServiceRefDeallocate(local_ipp_ref
);
1015 # endif /* HAVE_SSL */
1017 DNSServiceRefDeallocate(data
.main_ref
);
1018 #endif /* HAVE_DNSSD */
1026 * 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
1028 * Destinations are enumerated from one or more sources. The block receives the
1029 * destination name, instance, number of options, and options which can be used
1030 * as input to the @link cupsAddDest@ function. The block must return 1 to
1031 * continue enumeration or 0 to stop.
1033 * Enumeration happens on the current thread and does not return until all
1034 * destinations have been enumerated or the block returns 0.
1039 int /* O - 1 on success, 0 on failure */
1041 unsigned flags
, /* I - Enumeration flags */
1042 int timeout
, /* I - Timeout in milliseconds, 0 for indefinite */
1043 int *cancel
, /* I - Pointer to "cancel" variable */
1044 cups_ptype_t type
, /* I - Printer type bits */
1045 cups_ptype_t mask
, /* I - Mask for printer type bits */
1046 cups_dest_block_t block
) /* I - Block */
1048 return (cupsEnumDests(flags
, timeout
, cancel
, type
, mask
,
1049 (cups_dest_cb_t
)cups_block_cb
, (void *)block
));
1051 # endif /* __BLOCKS__ */
1055 * 'cupsFreeDests()' - Free the memory used by the list of destinations.
1059 cupsFreeDests(int num_dests
, /* I - Number of destinations */
1060 cups_dest_t
*dests
) /* I - Destinations */
1062 int i
; /* Looping var */
1063 cups_dest_t
*dest
; /* Current destination */
1066 if (num_dests
== 0 || dests
== NULL
)
1069 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1071 _cupsStrFree(dest
->name
);
1072 _cupsStrFree(dest
->instance
);
1074 cupsFreeOptions(dest
->num_options
, dest
->options
);
1082 * 'cupsGetDest()' - Get the named destination from the list.
1084 * Use the @link cupsGetDests@ or @link cupsGetDests2@ functions to get a
1085 * list of supported destinations for the current user.
1088 cups_dest_t
* /* O - Destination pointer or @code NULL@ */
1089 cupsGetDest(const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1090 const char *instance
, /* I - Instance name or @code NULL@ */
1091 int num_dests
, /* I - Number of destinations */
1092 cups_dest_t
*dests
) /* I - Destinations */
1094 int diff
, /* Result of comparison */
1095 match
; /* Matching index */
1098 if (num_dests
<= 0 || !dests
)
1104 * NULL name for default printer.
1107 while (num_dests
> 0)
1109 if (dests
->is_default
)
1119 * Lookup name and optionally the instance...
1122 match
= cups_find_dest(name
, instance
, num_dests
, dests
, -1, &diff
);
1125 return (dests
+ match
);
1133 * '_cupsGetDestResource()' - Get the resource path and URI for a destination.
1136 const char * /* O - Printer URI */
1137 _cupsGetDestResource(
1138 cups_dest_t
*dest
, /* I - Destination */
1139 char *resource
, /* I - Resource buffer */
1140 size_t resourcesize
) /* I - Size of resource buffer */
1142 const char *uri
; /* Printer URI */
1143 char scheme
[32], /* URI scheme */
1144 userpass
[256], /* Username and password (unused) */
1145 hostname
[256]; /* Hostname */
1146 int port
; /* Port number */
1150 * Range check input...
1153 if (!dest
|| !resource
|| resourcesize
< 1)
1158 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
1163 * Grab the printer URI...
1166 if ((uri
= cupsGetOption("printer-uri-supported", dest
->num_options
,
1167 dest
->options
)) == NULL
)
1172 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(ENOENT
), 0);
1178 if (strstr(uri
, "._tcp"))
1180 if ((uri
= cups_dnssd_resolve(dest
, uri
, 5000, NULL
, NULL
, NULL
)) == NULL
)
1183 #endif /* HAVE_DNSSD */
1185 if (httpSeparateURI(HTTP_URI_CODING_ALL
, uri
, scheme
, sizeof(scheme
),
1186 userpass
, sizeof(userpass
), hostname
, sizeof(hostname
),
1187 &port
, resource
, resourcesize
) < HTTP_URI_OK
)
1189 _cupsSetError(IPP_INTERNAL_ERROR
, _("Bad printer URI."), 1);
1199 * '_cupsGetDests()' - Get destinations from a server.
1201 * "op" is CUPS_GET_PRINTERS to get a full list, CUPS_GET_DEFAULT to get the
1202 * system-wide default printer, or IPP_GET_PRINTER_ATTRIBUTES for a known
1205 * "name" is the name of an existing printer and is only used when "op" is
1206 * IPP_GET_PRINTER_ATTRIBUTES.
1208 * "dest" is initialized to point to the array of destinations.
1210 * 0 is returned if there are no printers, no default printer, or the named
1211 * printer does not exist, respectively.
1213 * Free the memory used by the destination array using the @link cupsFreeDests@
1216 * Note: On Mac OS X this function also gets the default paper from the system
1217 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1218 * options array for each destination that supports it.
1221 int /* O - Number of destinations */
1222 _cupsGetDests(http_t
*http
, /* I - Connection to server or
1223 * @code CUPS_HTTP_DEFAULT@ */
1224 ipp_op_t op
, /* I - IPP operation */
1225 const char *name
, /* I - Name of destination */
1226 cups_dest_t
**dests
, /* IO - Destinations */
1227 cups_ptype_t type
, /* I - Printer type bits */
1228 cups_ptype_t mask
) /* I - Printer type mask */
1230 int num_dests
= 0; /* Number of destinations */
1231 cups_dest_t
*dest
; /* Current destination */
1232 ipp_t
*request
, /* IPP Request */
1233 *response
; /* IPP Response */
1234 ipp_attribute_t
*attr
; /* Current attribute */
1235 const char *printer_name
; /* printer-name attribute */
1236 char uri
[1024]; /* printer-uri value */
1237 int num_options
; /* Number of options */
1238 cups_option_t
*options
; /* Options */
1240 char media_default
[41]; /* Default paper size */
1241 #endif /* __APPLE__ */
1242 char optname
[1024], /* Option name */
1243 value
[2048], /* Option value */
1244 *ptr
; /* Pointer into name/value */
1245 static const char * const pattrs
[] = /* Attributes we're interested in */
1247 "auth-info-required",
1249 "job-sheets-default",
1250 "marker-change-time",
1252 "marker-high-levels",
1254 "marker-low-levels",
1260 #endif /* __APPLE__ */
1264 "printer-is-accepting-jobs",
1265 "printer-is-shared",
1267 "printer-make-and-model",
1270 "printer-state-change-time",
1271 "printer-state-reasons",
1273 "printer-uri-supported"
1279 * Get the default paper size...
1282 appleGetPaperSize(media_default
, sizeof(media_default
));
1283 #endif /* __APPLE__ */
1286 * Build a CUPS_GET_PRINTERS or IPP_GET_PRINTER_ATTRIBUTES request, which
1287 * require the following attributes:
1289 * attributes-charset
1290 * attributes-natural-language
1291 * requesting-user-name
1292 * printer-uri [for IPP_GET_PRINTER_ATTRIBUTES]
1295 request
= ippNewRequest(op
);
1297 ippAddStrings(request
, IPP_TAG_OPERATION
, IPP_TAG_KEYWORD
,
1298 "requested-attributes", sizeof(pattrs
) / sizeof(pattrs
[0]),
1301 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_NAME
,
1302 "requesting-user-name", NULL
, cupsUser());
1304 if (name
&& op
!= CUPS_GET_DEFAULT
)
1306 httpAssembleURIf(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
), "ipp", NULL
,
1307 "localhost", ippPort(), "/printers/%s", name
);
1308 ippAddString(request
, IPP_TAG_OPERATION
, IPP_TAG_URI
, "printer-uri", NULL
,
1313 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type",
1315 ippAddInteger(request
, IPP_TAG_OPERATION
, IPP_TAG_ENUM
, "printer-type-mask",
1320 * Do the request and get back a response...
1323 if ((response
= cupsDoRequest(http
, request
, "/")) != NULL
)
1325 for (attr
= response
->attrs
; attr
!= NULL
; attr
= attr
->next
)
1328 * Skip leading attributes until we hit a printer...
1331 while (attr
!= NULL
&& attr
->group_tag
!= IPP_TAG_PRINTER
)
1338 * Pull the needed attributes from this printer...
1341 printer_name
= NULL
;
1345 for (; attr
&& attr
->group_tag
== IPP_TAG_PRINTER
; attr
= attr
->next
)
1347 if (attr
->value_tag
!= IPP_TAG_INTEGER
&&
1348 attr
->value_tag
!= IPP_TAG_ENUM
&&
1349 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
1350 attr
->value_tag
!= IPP_TAG_TEXT
&&
1351 attr
->value_tag
!= IPP_TAG_TEXTLANG
&&
1352 attr
->value_tag
!= IPP_TAG_NAME
&&
1353 attr
->value_tag
!= IPP_TAG_NAMELANG
&&
1354 attr
->value_tag
!= IPP_TAG_KEYWORD
&&
1355 attr
->value_tag
!= IPP_TAG_RANGE
&&
1356 attr
->value_tag
!= IPP_TAG_URI
)
1359 if (!strcmp(attr
->name
, "auth-info-required") ||
1360 !strcmp(attr
->name
, "device-uri") ||
1361 !strcmp(attr
->name
, "marker-change-time") ||
1362 !strcmp(attr
->name
, "marker-colors") ||
1363 !strcmp(attr
->name
, "marker-high-levels") ||
1364 !strcmp(attr
->name
, "marker-levels") ||
1365 !strcmp(attr
->name
, "marker-low-levels") ||
1366 !strcmp(attr
->name
, "marker-message") ||
1367 !strcmp(attr
->name
, "marker-names") ||
1368 !strcmp(attr
->name
, "marker-types") ||
1369 !strcmp(attr
->name
, "printer-commands") ||
1370 !strcmp(attr
->name
, "printer-info") ||
1371 !strcmp(attr
->name
, "printer-is-shared") ||
1372 !strcmp(attr
->name
, "printer-make-and-model") ||
1373 !strcmp(attr
->name
, "printer-state") ||
1374 !strcmp(attr
->name
, "printer-state-change-time") ||
1375 !strcmp(attr
->name
, "printer-type") ||
1376 !strcmp(attr
->name
, "printer-is-accepting-jobs") ||
1377 !strcmp(attr
->name
, "printer-location") ||
1378 !strcmp(attr
->name
, "printer-state-reasons") ||
1379 !strcmp(attr
->name
, "printer-uri-supported"))
1382 * Add a printer description attribute...
1385 num_options
= cupsAddOption(attr
->name
,
1386 cups_make_string(attr
, value
,
1388 num_options
, &options
);
1391 else if (!strcmp(attr
->name
, "media-supported"))
1394 * See if we can set a default media size...
1397 int i
; /* Looping var */
1399 for (i
= 0; i
< attr
->num_values
; i
++)
1400 if (!_cups_strcasecmp(media_default
, attr
->values
[i
].string
.text
))
1402 num_options
= cupsAddOption("media", media_default
, num_options
,
1407 #endif /* __APPLE__ */
1408 else if (!strcmp(attr
->name
, "printer-name") &&
1409 attr
->value_tag
== IPP_TAG_NAME
)
1410 printer_name
= attr
->values
[0].string
.text
;
1411 else if (strncmp(attr
->name
, "notify-", 7) &&
1412 (attr
->value_tag
== IPP_TAG_BOOLEAN
||
1413 attr
->value_tag
== IPP_TAG_ENUM
||
1414 attr
->value_tag
== IPP_TAG_INTEGER
||
1415 attr
->value_tag
== IPP_TAG_KEYWORD
||
1416 attr
->value_tag
== IPP_TAG_NAME
||
1417 attr
->value_tag
== IPP_TAG_RANGE
) &&
1418 (ptr
= strstr(attr
->name
, "-default")) != NULL
)
1421 * Add a default option...
1424 strlcpy(optname
, attr
->name
, sizeof(optname
));
1425 optname
[ptr
- attr
->name
] = '\0';
1427 if (_cups_strcasecmp(optname
, "media") ||
1428 !cupsGetOption("media", num_options
, options
))
1429 num_options
= cupsAddOption(optname
,
1430 cups_make_string(attr
, value
,
1432 num_options
, &options
);
1437 * See if we have everything needed...
1442 cupsFreeOptions(num_options
, options
);
1450 if ((dest
= cups_add_dest(printer_name
, NULL
, &num_dests
, dests
)) != NULL
)
1452 dest
->num_options
= num_options
;
1453 dest
->options
= options
;
1456 cupsFreeOptions(num_options
, options
);
1462 ippDelete(response
);
1466 * Return the count...
1474 * 'cupsGetDests()' - Get the list of destinations from the default server.
1476 * Starting with CUPS 1.2, the returned list of destinations include the
1477 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1478 * printer-make-and-model, printer-state, printer-state-change-time,
1479 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1480 * adds the marker-change-time, marker-colors, marker-high-levels,
1481 * marker-levels, marker-low-levels, marker-message, marker-names,
1482 * marker-types, and printer-commands attributes as well.
1484 * Use the @link cupsFreeDests@ function to free the destination list and
1485 * the @link cupsGetDest@ function to find a particular destination.
1488 int /* O - Number of destinations */
1489 cupsGetDests(cups_dest_t
**dests
) /* O - Destinations */
1491 return (cupsGetDests2(CUPS_HTTP_DEFAULT
, dests
));
1496 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1498 * Starting with CUPS 1.2, the returned list of destinations include the
1499 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1500 * printer-make-and-model, printer-state, printer-state-change-time,
1501 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1502 * adds the marker-change-time, marker-colors, marker-high-levels,
1503 * marker-levels, marker-low-levels, marker-message, marker-names,
1504 * marker-types, and printer-commands attributes as well.
1506 * Use the @link cupsFreeDests@ function to free the destination list and
1507 * the @link cupsGetDest@ function to find a particular destination.
1509 * @since CUPS 1.1.21/Mac OS X 10.4@
1512 int /* O - Number of destinations */
1513 cupsGetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1514 cups_dest_t
**dests
) /* O - Destinations */
1516 int i
; /* Looping var */
1517 int num_dests
; /* Number of destinations */
1518 cups_dest_t
*dest
; /* Destination pointer */
1519 const char *home
; /* HOME environment variable */
1520 char filename
[1024]; /* Local ~/.cups/lpoptions file */
1521 const char *defprinter
; /* Default printer */
1522 char name
[1024], /* Copy of printer name */
1523 *instance
, /* Pointer to instance name */
1524 *user_default
; /* User default printer */
1525 int num_reals
; /* Number of real queues */
1526 cups_dest_t
*reals
; /* Real queues */
1527 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1531 * Range check the input...
1536 _cupsSetError(IPP_INTERNAL_ERROR
, _("Bad NULL dests pointer"), 1);
1541 * Grab the printers and classes...
1544 *dests
= (cups_dest_t
*)0;
1545 num_dests
= _cupsGetDests(http
, CUPS_GET_PRINTERS
, NULL
, dests
, 0, 0);
1547 if (cupsLastError() >= IPP_REDIRECTION_OTHER_SITE
)
1549 cupsFreeDests(num_dests
, *dests
);
1550 *dests
= (cups_dest_t
*)0;
1555 * Make a copy of the "real" queues for a later sanity check...
1560 num_reals
= num_dests
;
1561 reals
= calloc(num_reals
, sizeof(cups_dest_t
));
1564 memcpy(reals
, *dests
, num_reals
* sizeof(cups_dest_t
));
1575 * Grab the default destination...
1578 if ((user_default
= _cupsUserDefault(name
, sizeof(name
))) != NULL
)
1580 else if ((defprinter
= cupsGetDefault2(http
)) != NULL
)
1582 strlcpy(name
, defprinter
, sizeof(name
));
1589 * Separate printer and instance name...
1592 if ((instance
= strchr(name
, '/')) != NULL
)
1596 * Lookup the printer and instance and make it the default...
1599 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) != NULL
)
1600 dest
->is_default
= 1;
1606 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
1609 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1610 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1613 if ((home
= getenv("HOME")) != NULL
)
1615 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1617 num_dests
= cups_get_dests(filename
, NULL
, NULL
, user_default
!= NULL
,
1622 * Validate the current default destination - this prevents old
1623 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
1624 * pointing to a non-existent printer or class...
1630 * See if we have a default printer...
1633 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, *dests
)) != NULL
)
1636 * Have a default; see if it is real...
1639 dest
= cupsGetDest(dest
->name
, NULL
, num_reals
, reals
);
1643 * If dest is NULL, then no default (that exists) is set, so we
1644 * need to set a default if one exists...
1647 if (dest
== NULL
&& defprinter
!= NULL
)
1649 for (i
= 0; i
< num_dests
; i
++)
1650 (*dests
)[i
].is_default
= 0;
1652 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) != NULL
)
1653 dest
->is_default
= 1;
1664 * Return the number of destinations...
1668 _cupsSetError(IPP_OK
, NULL
, 0);
1675 * 'cupsGetNamedDest()' - Get options for the named destination.
1677 * This function is optimized for retrieving a single destination and should
1678 * be used instead of @link cupsGetDests@ and @link cupsGetDest@ when you either
1679 * know the name of the destination or want to print to the default destination.
1680 * If @code NULL@ is returned, the destination does not exist or there is no
1681 * default destination.
1683 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
1684 * server will be used.
1686 * If "name" is @code NULL@, the default printer for the current user will be
1689 * The returned destination must be freed using @link cupsFreeDests@ with a
1690 * "num_dests" value of 1.
1692 * @since CUPS 1.4/Mac OS X 10.6@
1695 cups_dest_t
* /* O - Destination or @code NULL@ */
1696 cupsGetNamedDest(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1697 const char *name
, /* I - Destination name or @code NULL@ for the default destination */
1698 const char *instance
) /* I - Instance name or @code NULL@ */
1700 cups_dest_t
*dest
; /* Destination */
1701 char filename
[1024], /* Path to lpoptions */
1702 defname
[256]; /* Default printer name */
1703 const char *home
= getenv("HOME"); /* Home directory */
1704 int set_as_default
= 0; /* Set returned destination as default */
1705 ipp_op_t op
= IPP_GET_PRINTER_ATTRIBUTES
;
1706 /* IPP operation to get server ops */
1707 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1711 * If "name" is NULL, find the default destination...
1717 name
= _cupsUserDefault(defname
, sizeof(defname
));
1721 char *ptr
; /* Temporary pointer... */
1723 if ((ptr
= strchr(defname
, '/')) != NULL
)
1734 * No default in the environment, try the user's lpoptions files...
1737 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1739 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1745 * Still not there? Try the system lpoptions file...
1748 snprintf(filename
, sizeof(filename
), "%s/lpoptions",
1749 cg
->cups_serverroot
);
1750 name
= cups_get_default(filename
, defname
, sizeof(defname
), &instance
);
1756 * No locally-set default destination, ask the server...
1759 op
= CUPS_GET_DEFAULT
;
1764 * Get the printer's attributes...
1767 if (!_cupsGetDests(http
, op
, name
, &dest
, 0, 0))
1769 if (op
== CUPS_GET_DEFAULT
|| (name
&& !set_as_default
))
1773 * The default printer from environment variables or from a
1774 * configuration file does not exist. Find out the real default.
1777 if (!_cupsGetDests(http
, CUPS_GET_DEFAULT
, NULL
, &dest
, 0, 0))
1782 dest
->instance
= _cupsStrAlloc(instance
);
1785 dest
->is_default
= 1;
1788 * Then add local options...
1791 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1792 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
1796 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1798 cups_get_dests(filename
, name
, instance
, 1, 1, &dest
);
1802 * Return the result...
1810 * 'cupsRemoveDest()' - Remove a destination from the destination list.
1812 * Removing a destination/instance does not delete the class or printer
1813 * queue, merely the lpoptions for that destination/instance. Use the
1814 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
1815 * options for the user.
1817 * @since CUPS 1.3/Mac OS X 10.5@
1820 int /* O - New number of destinations */
1821 cupsRemoveDest(const char *name
, /* I - Destination name */
1822 const char *instance
, /* I - Instance name or @code NULL@ */
1823 int num_dests
, /* I - Number of destinations */
1824 cups_dest_t
**dests
) /* IO - Destinations */
1826 int i
; /* Index into destinations */
1827 cups_dest_t
*dest
; /* Pointer to destination */
1831 * Find the destination...
1834 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
1841 _cupsStrFree(dest
->name
);
1842 _cupsStrFree(dest
->instance
);
1843 cupsFreeOptions(dest
->num_options
, dest
->options
);
1846 * Remove the destination from the array...
1854 memmove(dest
, dest
+ 1, (num_dests
- i
) * sizeof(cups_dest_t
));
1861 * 'cupsSetDefaultDest()' - Set the default destination.
1863 * @since CUPS 1.3/Mac OS X 10.5@
1868 const char *name
, /* I - Destination name */
1869 const char *instance
, /* I - Instance name or @code NULL@ */
1870 int num_dests
, /* I - Number of destinations */
1871 cups_dest_t
*dests
) /* I - Destinations */
1873 int i
; /* Looping var */
1874 cups_dest_t
*dest
; /* Current destination */
1878 * Range check input...
1881 if (!name
|| num_dests
<= 0 || !dests
)
1885 * Loop through the array and set the "is_default" flag for the matching
1889 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
1890 dest
->is_default
= !_cups_strcasecmp(name
, dest
->name
) &&
1891 ((!instance
&& !dest
->instance
) ||
1892 (instance
&& dest
->instance
&&
1893 !_cups_strcasecmp(instance
, dest
->instance
)));
1898 * 'cupsSetDests()' - Save the list of destinations for the default server.
1900 * This function saves the destinations to /etc/cups/lpoptions when run
1901 * as root and ~/.cups/lpoptions when run as a normal user.
1905 cupsSetDests(int num_dests
, /* I - Number of destinations */
1906 cups_dest_t
*dests
) /* I - Destinations */
1908 cupsSetDests2(CUPS_HTTP_DEFAULT
, num_dests
, dests
);
1913 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
1915 * This function saves the destinations to /etc/cups/lpoptions when run
1916 * as root and ~/.cups/lpoptions when run as a normal user.
1918 * @since CUPS 1.1.21/Mac OS X 10.4@
1921 int /* O - 0 on success, -1 on error */
1922 cupsSetDests2(http_t
*http
, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1923 int num_dests
, /* I - Number of destinations */
1924 cups_dest_t
*dests
) /* I - Destinations */
1926 int i
, j
; /* Looping vars */
1927 int wrote
; /* Wrote definition? */
1928 cups_dest_t
*dest
; /* Current destination */
1929 cups_option_t
*option
; /* Current option */
1930 _ipp_option_t
*match
; /* Matching attribute for option */
1931 FILE *fp
; /* File pointer */
1933 const char *home
; /* HOME environment variable */
1935 char filename
[1024]; /* lpoptions file */
1936 int num_temps
; /* Number of temporary destinations */
1937 cups_dest_t
*temps
, /* Temporary destinations */
1938 *temp
; /* Current temporary dest */
1939 const char *val
; /* Value of temporary option */
1940 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
1944 * Range check the input...
1947 if (!num_dests
|| !dests
)
1951 * Get the server destinations...
1954 num_temps
= _cupsGetDests(http
, CUPS_GET_PRINTERS
, NULL
, &temps
, 0, 0);
1956 if (cupsLastError() >= IPP_REDIRECTION_OTHER_SITE
)
1958 cupsFreeDests(num_temps
, temps
);
1963 * Figure out which file to write to...
1966 snprintf(filename
, sizeof(filename
), "%s/lpoptions", cg
->cups_serverroot
);
1972 * Merge in server defaults...
1975 num_temps
= cups_get_dests(filename
, NULL
, NULL
, 0, num_temps
, &temps
);
1978 * Point to user defaults...
1981 if ((home
= getenv("HOME")) != NULL
)
1984 * Create ~/.cups subdirectory...
1987 snprintf(filename
, sizeof(filename
), "%s/.cups", home
);
1988 if (access(filename
, 0))
1989 mkdir(filename
, 0700);
1991 snprintf(filename
, sizeof(filename
), "%s/.cups/lpoptions", home
);
1997 * Try to open the file...
2000 if ((fp
= fopen(filename
, "w")) == NULL
)
2002 cupsFreeDests(num_temps
, temps
);
2008 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2013 fchmod(fileno(fp
), 0644);
2017 * Write each printer; each line looks like:
2019 * Dest name[/instance] options
2020 * Default name[/instance] options
2023 for (i
= num_dests
, dest
= dests
; i
> 0; i
--, dest
++)
2024 if (dest
->instance
!= NULL
|| dest
->num_options
!= 0 || dest
->is_default
)
2026 if (dest
->is_default
)
2028 fprintf(fp
, "Default %s", dest
->name
);
2030 fprintf(fp
, "/%s", dest
->instance
);
2037 if ((temp
= cupsGetDest(dest
->name
, dest
->instance
, num_temps
, temps
)) == NULL
)
2038 temp
= cupsGetDest(dest
->name
, NULL
, num_temps
, temps
);
2040 for (j
= dest
->num_options
, option
= dest
->options
; j
> 0; j
--, option
++)
2043 * See if this option is a printer attribute; if so, skip it...
2046 if ((match
= _ippFindOption(option
->name
)) != NULL
&&
2047 match
->group_tag
== IPP_TAG_PRINTER
)
2051 * See if the server/global options match these; if so, don't
2056 (val
= cupsGetOption(option
->name
, temp
->num_options
,
2057 temp
->options
)) != NULL
&&
2058 !_cups_strcasecmp(val
, option
->value
))
2062 * Options don't match, write to the file...
2067 fprintf(fp
, "Dest %s", dest
->name
);
2069 fprintf(fp
, "/%s", dest
->instance
);
2073 if (option
->value
[0])
2075 if (strchr(option
->value
, ' ') ||
2076 strchr(option
->value
, '\\') ||
2077 strchr(option
->value
, '\"') ||
2078 strchr(option
->value
, '\''))
2081 * Quote the value...
2084 fprintf(fp
, " %s=\"", option
->name
);
2086 for (val
= option
->value
; *val
; val
++)
2088 if (strchr("\"\'\\", *val
))
2099 * Store the literal value...
2102 fprintf(fp
, " %s=%s", option
->name
, option
->value
);
2106 fprintf(fp
, " %s", option
->name
);
2114 * Free the temporary destinations and close the file...
2117 cupsFreeDests(num_temps
, temps
);
2123 * Set the default printer for this location - this allows command-line
2124 * and GUI applications to share the same default destination...
2127 if ((dest
= cupsGetDest(NULL
, NULL
, num_dests
, dests
)) != NULL
)
2129 CFStringRef name
= CFStringCreateWithCString(kCFAllocatorDefault
,
2131 kCFStringEncodingUTF8
);
2132 /* Default printer name */
2136 _cupsAppleSetDefaultPrinter(name
);
2140 #endif /* __APPLE__ */
2142 #ifdef HAVE_NOTIFY_POST
2144 * Send a notification so that MacOS X applications can know about the
2148 notify_post("com.apple.printerListChange");
2149 #endif /* HAVE_NOTIFY_POST */
2156 * '_cupsUserDefault()' - Get the user default printer from environment
2157 * variables and location information.
2160 char * /* O - Default printer or NULL */
2161 _cupsUserDefault(char *name
, /* I - Name buffer */
2162 size_t namesize
) /* I - Size of name buffer */
2164 const char *env
; /* LPDEST or PRINTER env variable */
2166 CFStringRef locprinter
; /* Last printer as this location */
2167 #endif /* __APPLE__ */
2170 if ((env
= getenv("LPDEST")) == NULL
)
2171 if ((env
= getenv("PRINTER")) != NULL
&& !strcmp(env
, "lp"))
2176 strlcpy(name
, env
, namesize
);
2182 * Use location-based defaults if "use last printer" is selected in the
2183 * system preferences...
2186 if ((locprinter
= _cupsAppleCopyDefaultPrinter()) != NULL
)
2188 CFStringGetCString(locprinter
, name
, namesize
, kCFStringEncodingUTF8
);
2189 CFRelease(locprinter
);
2194 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name
));
2196 return (*name
? name
: NULL
);
2200 * No location-based defaults on this platform...
2205 #endif /* __APPLE__ */
2211 * 'appleCopyLocations()' - Copy the location history array.
2214 static CFArrayRef
/* O - Location array or NULL */
2215 appleCopyLocations(void)
2217 CFArrayRef locations
; /* Location array */
2221 * Look up the location array in the preferences...
2224 if ((locations
= CFPreferencesCopyAppValue(kLastUsedPrintersKey
,
2225 kCUPSPrintingPrefs
)) == NULL
)
2228 if (CFGetTypeID(locations
) != CFArrayGetTypeID())
2230 CFRelease(locations
);
2239 * 'appleCopyNetwork()' - Get the network ID for the current location.
2242 static CFStringRef
/* O - Network ID */
2243 appleCopyNetwork(void)
2245 SCDynamicStoreRef dynamicStore
; /* System configuration data */
2246 CFStringRef key
; /* Current network configuration key */
2247 CFDictionaryRef ip_dict
; /* Network configuration data */
2248 CFStringRef network
= NULL
; /* Current network ID */
2251 if ((dynamicStore
= SCDynamicStoreCreate(NULL
, CFSTR("libcups"), NULL
,
2255 * First use the IPv6 router address, if available, since that will generally
2256 * be a globally-unique link-local address.
2259 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2260 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv6
)) != NULL
)
2262 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2264 if ((network
= CFDictionaryGetValue(ip_dict
,
2265 kSCPropNetIPv6Router
)) != NULL
)
2275 * If that doesn't work, try the IPv4 router address. This isn't as unique
2276 * and will likely be a 10.x.y.z or 192.168.y.z address...
2281 if ((key
= SCDynamicStoreKeyCreateNetworkGlobalEntity(
2282 NULL
, kSCDynamicStoreDomainState
, kSCEntNetIPv4
)) != NULL
)
2284 if ((ip_dict
= SCDynamicStoreCopyValue(dynamicStore
, key
)) != NULL
)
2286 if ((network
= CFDictionaryGetValue(ip_dict
,
2287 kSCPropNetIPv4Router
)) != NULL
)
2297 CFRelease(dynamicStore
);
2305 * 'appleGetPaperSize()' - Get the default paper size.
2308 char * /* O - Default paper size */
2309 appleGetPaperSize(char *name
, /* I - Paper size name buffer */
2310 int namesize
) /* I - Size of buffer */
2312 CFStringRef defaultPaperID
; /* Default paper ID */
2313 _pwg_media_t
*pwgmedia
; /* PWG media size */
2316 defaultPaperID
= _cupsAppleCopyDefaultPaperID();
2317 if (!defaultPaperID
||
2318 CFGetTypeID(defaultPaperID
) != CFStringGetTypeID() ||
2319 !CFStringGetCString(defaultPaperID
, name
, namesize
,
2320 kCFStringEncodingUTF8
))
2322 else if ((pwgmedia
= _pwgMediaForLegacy(name
)) != NULL
)
2323 strlcpy(name
, pwgmedia
->pwg
, namesize
);
2326 CFRelease(defaultPaperID
);
2333 * 'appleGetPrinter()' - Get a printer from the history array.
2336 static CFStringRef
/* O - Printer name or NULL */
2337 appleGetPrinter(CFArrayRef locations
, /* I - Location array */
2338 CFStringRef network
, /* I - Network name */
2339 CFIndex
*locindex
) /* O - Index in array */
2341 CFIndex i
, /* Looping var */
2342 count
; /* Number of locations */
2343 CFDictionaryRef location
; /* Current location */
2344 CFStringRef locnetwork
, /* Current network */
2345 locprinter
; /* Current printer */
2348 for (i
= 0, count
= CFArrayGetCount(locations
); i
< count
; i
++)
2349 if ((location
= CFArrayGetValueAtIndex(locations
, i
)) != NULL
&&
2350 CFGetTypeID(location
) == CFDictionaryGetTypeID())
2352 if ((locnetwork
= CFDictionaryGetValue(location
,
2353 kLocationNetworkKey
)) != NULL
&&
2354 CFGetTypeID(locnetwork
) == CFStringGetTypeID() &&
2355 CFStringCompare(network
, locnetwork
, 0) == kCFCompareEqualTo
&&
2356 (locprinter
= CFDictionaryGetValue(location
,
2357 kLocationPrinterIDKey
)) != NULL
&&
2358 CFGetTypeID(locprinter
) == CFStringGetTypeID())
2363 return (locprinter
);
2369 #endif /* __APPLE__ */
2373 * 'cups_add_dest()' - Add a destination to the array.
2375 * Unlike cupsAddDest(), this function does not check for duplicates.
2378 static cups_dest_t
* /* O - New destination */
2379 cups_add_dest(const char *name
, /* I - Name of destination */
2380 const char *instance
, /* I - Instance or NULL */
2381 int *num_dests
, /* IO - Number of destinations */
2382 cups_dest_t
**dests
) /* IO - Destinations */
2384 int insert
, /* Insertion point */
2385 diff
; /* Result of comparison */
2386 cups_dest_t
*dest
; /* Destination pointer */
2390 * Add new destination...
2393 if (*num_dests
== 0)
2394 dest
= malloc(sizeof(cups_dest_t
));
2396 dest
= realloc(*dests
, sizeof(cups_dest_t
) * (*num_dests
+ 1));
2404 * Find where to insert the destination...
2407 if (*num_dests
== 0)
2411 insert
= cups_find_dest(name
, instance
, *num_dests
, *dests
, *num_dests
- 1,
2419 * Move the array elements as needed...
2422 if (insert
< *num_dests
)
2423 memmove(*dests
+ insert
+ 1, *dests
+ insert
,
2424 (*num_dests
- insert
) * sizeof(cups_dest_t
));
2429 * Initialize the destination...
2432 dest
= *dests
+ insert
;
2433 dest
->name
= _cupsStrAlloc(name
);
2434 dest
->instance
= _cupsStrAlloc(instance
);
2435 dest
->is_default
= 0;
2436 dest
->num_options
= 0;
2437 dest
->options
= (cups_option_t
*)0;
2445 * 'cups_block_cb()' - Enumeration callback for block API.
2448 static int /* O - 1 to continue, 0 to stop */
2450 cups_dest_block_t block
, /* I - Block */
2451 unsigned flags
, /* I - Destination flags */
2452 cups_dest_t
*dest
) /* I - Destination */
2454 return ((block
)(flags
, dest
));
2456 # endif /* __BLOCKS__ */
2460 * 'cups_compare_dests()' - Compare two destinations.
2463 static int /* O - Result of comparison */
2464 cups_compare_dests(cups_dest_t
*a
, /* I - First destination */
2465 cups_dest_t
*b
) /* I - Second destination */
2467 int diff
; /* Difference */
2470 if ((diff
= _cups_strcasecmp(a
->name
, b
->name
)) != 0)
2472 else if (a
->instance
&& b
->instance
)
2473 return (_cups_strcasecmp(a
->instance
, b
->instance
));
2475 return ((a
->instance
&& !b
->instance
) - (!a
->instance
&& b
->instance
));
2481 * 'cups_dnssd_browse_cb()' - Browse for printers.
2485 cups_dnssd_browse_cb(
2486 DNSServiceRef sdRef
, /* I - Service reference */
2487 DNSServiceFlags flags
, /* I - Option flags */
2488 uint32_t interfaceIndex
, /* I - Interface number */
2489 DNSServiceErrorType errorCode
, /* I - Error, if any */
2490 const char *serviceName
, /* I - Name of service/device */
2491 const char *regtype
, /* I - Type of service */
2492 const char *replyDomain
, /* I - Service domain */
2493 void *context
) /* I - Enumeration data */
2495 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2496 /* Enumeration data */
2499 DEBUG_printf(("5cups_dnssd_browse_cb(sdRef=%p, flags=%x, "
2500 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2501 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2502 sdRef
, flags
, interfaceIndex
, errorCode
, serviceName
, regtype
,
2503 replyDomain
, context
));
2506 * Don't do anything on error...
2509 if (errorCode
!= kDNSServiceErr_NoError
)
2516 cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2521 * 'cups_dnssd_compare_device()' - Compare two devices.
2524 static int /* O - Result of comparison */
2525 cups_dnssd_compare_devices(
2526 _cups_dnssd_device_t
*a
, /* I - First device */
2527 _cups_dnssd_device_t
*b
) /* I - Second device */
2529 return (strcmp(a
->dest
.name
, b
->dest
.name
));
2534 * 'cups_dnssd_free_device()' - Free the memory used by a device.
2538 cups_dnssd_free_device(
2539 _cups_dnssd_device_t
*device
, /* I - Device */
2540 _cups_dnssd_data_t
*data
) /* I - Enumeration data */
2542 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", device
,
2543 device
->dest
.name
, data
));
2546 DNSServiceRefDeallocate(device
->ref
);
2548 _cupsStrFree(device
->domain
);
2549 _cupsStrFree(device
->fullName
);
2550 _cupsStrFree(device
->regtype
);
2551 _cupsStrFree(device
->dest
.name
);
2553 cupsFreeOptions(device
->dest
.num_options
, device
->dest
.options
);
2560 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
2563 static _cups_dnssd_device_t
* /* O - Device */
2564 cups_dnssd_get_device(
2565 _cups_dnssd_data_t
*data
, /* I - Enumeration data */
2566 const char *serviceName
, /* I - Service name */
2567 const char *regtype
, /* I - Registration type */
2568 const char *replyDomain
) /* I - Domain name */
2570 _cups_dnssd_device_t key
, /* Search key */
2571 *device
; /* Device */
2572 char fullName
[kDNSServiceMaxDomainName
];
2573 /* Full name for query */
2576 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", "
2577 "regtype=\"%s\", replyDomain=\"%s\")", data
, serviceName
,
2578 regtype
, replyDomain
));
2581 * See if this is an existing device...
2584 key
.dest
.name
= (char *)serviceName
;
2586 if ((device
= cupsArrayFind(data
->devices
, &key
)) != NULL
)
2589 * Yes, see if we need to do anything with this...
2592 int update
= 0; /* Non-zero if we need to update */
2594 if (!_cups_strcasecmp(replyDomain
, "local.") &&
2595 _cups_strcasecmp(device
->domain
, replyDomain
))
2598 * Update the "global" listing to use the .local domain name instead.
2601 _cupsStrFree(device
->domain
);
2602 device
->domain
= _cupsStrAlloc(replyDomain
);
2604 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
2605 "domain.", device
->dest
.name
));
2610 if (!_cups_strcasecmp(regtype
, "_ipps._tcp") &&
2611 _cups_strcasecmp(device
->regtype
, regtype
))
2614 * Prefer IPPS over IPP.
2617 _cupsStrFree(device
->regtype
);
2618 device
->regtype
= _cupsStrAlloc(regtype
);
2620 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
2621 device
->dest
.name
));
2628 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
2629 device
->dest
.name
));
2636 * No, add the device...
2639 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
2640 "'%s'.", serviceName
,
2641 !strcmp(regtype
, "_ipps._tcp") ? "IPPS" : "IPP",
2644 device
= calloc(sizeof(_cups_dnssd_device_t
), 1);
2645 device
->dest
.name
= _cupsStrAlloc(serviceName
);
2646 device
->domain
= _cupsStrAlloc(replyDomain
);
2647 device
->regtype
= _cupsStrAlloc(regtype
);
2649 cupsArrayAdd(data
->devices
, device
);
2653 * Set the "full name" of this service, which is used for queries...
2656 DNSServiceConstructFullName(fullName
, device
->dest
.name
, device
->regtype
,
2658 _cupsStrFree(device
->fullName
);
2659 device
->fullName
= _cupsStrAlloc(fullName
);
2663 DNSServiceRefDeallocate(device
->ref
);
2667 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
2669 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
2670 device
->state
= _CUPS_DNSSD_NEW
;
2678 * 'cups_dnssd_local_cb()' - Browse for local printers.
2682 cups_dnssd_local_cb(
2683 DNSServiceRef sdRef
, /* I - Service reference */
2684 DNSServiceFlags flags
, /* I - Option flags */
2685 uint32_t interfaceIndex
, /* I - Interface number */
2686 DNSServiceErrorType errorCode
, /* I - Error, if any */
2687 const char *serviceName
, /* I - Name of service/device */
2688 const char *regtype
, /* I - Type of service */
2689 const char *replyDomain
, /* I - Service domain */
2690 void *context
) /* I - Devices array */
2692 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2693 /* Enumeration data */
2694 _cups_dnssd_device_t
*device
; /* Device */
2697 DEBUG_printf(("5cups_dnssd_local_cb(sdRef=%p, flags=%x, "
2698 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2699 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2700 sdRef
, flags
, interfaceIndex
, errorCode
, serviceName
,
2701 regtype
, replyDomain
, context
));
2704 * Only process "add" data...
2707 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
2714 device
= cups_dnssd_get_device(data
, serviceName
, regtype
, replyDomain
);
2717 * Hide locally-registered devices...
2720 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
2725 DNSServiceRefDeallocate(device
->ref
);
2729 if (device
->state
== _CUPS_DNSSD_ACTIVE
)
2730 (*data
->cb
)(data
->user_data
, CUPS_DEST_FLAGS_REMOVED
, &device
->dest
);
2732 device
->state
= _CUPS_DNSSD_LOCAL
;
2737 * 'cups_dnssd_query_cb()' - Process query data.
2741 cups_dnssd_query_cb(
2742 DNSServiceRef sdRef
, /* I - Service reference */
2743 DNSServiceFlags flags
, /* I - Data flags */
2744 uint32_t interfaceIndex
, /* I - Interface */
2745 DNSServiceErrorType errorCode
, /* I - Error, if any */
2746 const char *fullName
, /* I - Full service name */
2747 uint16_t rrtype
, /* I - Record type */
2748 uint16_t rrclass
, /* I - Record class */
2749 uint16_t rdlen
, /* I - Length of record data */
2750 const void *rdata
, /* I - Record data */
2751 uint32_t ttl
, /* I - Time-to-live */
2752 void *context
) /* I - Enumeration data */
2754 _cups_dnssd_data_t
*data
= (_cups_dnssd_data_t
*)context
;
2755 /* Enumeration data */
2756 char name
[1024], /* Service name */
2757 *ptr
; /* Pointer into string */
2758 _cups_dnssd_device_t dkey
, /* Search key */
2759 *device
; /* Device */
2762 DEBUG_printf(("5cups_dnssd_query_cb(sdRef=%p, flags=%x, "
2763 "interfaceIndex=%d, errorCode=%d, fullName=\"%s\", "
2764 "rrtype=%u, rrclass=%u, rdlen=%u, rdata=%p, ttl=%u, "
2765 "context=%p)", sdRef
, flags
, interfaceIndex
, errorCode
,
2766 fullName
, rrtype
, rrclass
, rdlen
, rdata
, ttl
, context
));
2769 * Only process "add" data...
2772 if (errorCode
!= kDNSServiceErr_NoError
|| !(flags
& kDNSServiceFlagsAdd
))
2776 * Lookup the service in the devices array.
2779 dkey
.dest
.name
= name
;
2781 cups_dnssd_unquote(name
, fullName
, sizeof(name
));
2783 if ((ptr
= strstr(name
, "._")) != NULL
)
2786 if ((device
= cupsArrayFind(data
->devices
, &dkey
)) != NULL
)
2789 * Found it, pull out the priority and make and model from the TXT
2790 * record and save it...
2793 const uint8_t *txt
, /* Pointer into data */
2794 *txtnext
, /* Next key/value pair */
2795 *txtend
; /* End of entire TXT record */
2796 uint8_t txtlen
; /* Length of current key/value pair */
2797 char key
[256], /* Key string */
2798 value
[256], /* Value string */
2799 make_and_model
[512],
2800 /* Manufacturer and model */
2801 model
[256], /* Model */
2802 uriname
[1024], /* Name for URI */
2803 uri
[1024]; /* Printer URI */
2804 cups_ptype_t type
; /* Device type */
2806 device
->state
= _CUPS_DNSSD_PENDING
;
2807 make_and_model
[0] = '\0';
2808 type
= CUPS_PRINTER_REMOTE
;
2810 strcpy(model
, "Unknown");
2812 for (txt
= rdata
, txtend
= txt
+ rdlen
;
2817 * Read a key/value pair starting with an 8-bit length. Since the
2818 * length is 8 bits and the size of the key/value buffers is 256, we
2819 * don't need to check for overflow...
2824 if (!txtlen
|| (txt
+ txtlen
) > txtend
)
2827 txtnext
= txt
+ txtlen
;
2829 for (ptr
= key
; txt
< txtnext
&& *txt
!= '='; txt
++)
2833 if (txt
< txtnext
&& *txt
== '=')
2838 memcpy(value
, txt
, txtnext
- txt
);
2839 value
[txtnext
- txt
] = '\0';
2841 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key
, value
));
2845 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key
));
2849 if (!_cups_strcasecmp(key
, "usb_MFG") ||
2850 !_cups_strcasecmp(key
, "usb_MANU") ||
2851 !_cups_strcasecmp(key
, "usb_MANUFACTURER"))
2852 strcpy(make_and_model
, value
);
2853 else if (!_cups_strcasecmp(key
, "usb_MDL") ||
2854 !_cups_strcasecmp(key
, "usb_MODEL"))
2855 strcpy(model
, value
);
2856 else if (!_cups_strcasecmp(key
, "product") && !strstr(value
, "Ghostscript"))
2858 if (value
[0] == '(')
2861 * Strip parenthesis...
2864 if ((ptr
= value
+ strlen(value
) - 1) > value
&& *ptr
== ')')
2867 strcpy(model
, value
+ 1);
2870 strcpy(model
, value
);
2872 else if (!_cups_strcasecmp(key
, "ty"))
2874 strcpy(model
, value
);
2876 if ((ptr
= strchr(model
, ',')) != NULL
)
2879 else if (!_cups_strcasecmp(key
, "printer-type"))
2881 device
->dest
.num_options
= cupsAddOption("printer-type", value
,
2882 device
->dest
.num_options
,
2883 &device
->dest
.options
);
2884 type
= strtol(value
, NULL
, 0);
2889 * Save the make-and-model...
2892 if (make_and_model
[0])
2894 strlcat(make_and_model
, " ", sizeof(make_and_model
));
2895 strlcat(make_and_model
, model
, sizeof(make_and_model
));
2897 device
->dest
.num_options
= cupsAddOption("printer-make-and-model",
2899 device
->dest
.num_options
,
2900 &device
->dest
.options
);
2903 device
->dest
.num_options
= cupsAddOption("printer-make-and-model",
2905 device
->dest
.num_options
,
2906 &device
->dest
.options
);
2912 cups_dnssd_unquote(uriname
, device
->fullName
, sizeof(uriname
));
2913 httpAssembleURI(HTTP_URI_CODING_ALL
, uri
, sizeof(uri
),
2914 !strcmp(device
->regtype
, "_ipps._tcp") ? "ipps" : "ipp",
2915 NULL
, uriname
, 0, "/cups");
2917 DEBUG_printf(("6cups_dnssd_query: printer-uri-supported=\"%s\"", uri
));
2919 device
->dest
.num_options
= cupsAddOption("printer-uri-supported", uri
,
2920 device
->dest
.num_options
,
2921 &device
->dest
.options
);
2924 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
2930 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
2933 static const char * /* O - Resolved URI or NULL */
2935 cups_dest_t
*dest
, /* I - Destination */
2936 const char *uri
, /* I - Current printer URI */
2937 int msec
, /* I - Time in milliseconds */
2938 int *cancel
, /* I - Pointer to "cancel" variable */
2939 cups_dest_cb_t cb
, /* I - Callback */
2940 void *user_data
) /* I - User data for callback */
2942 char tempuri
[1024]; /* Temporary URI buffer */
2943 _cups_dnssd_resolve_t resolve
; /* Resolve data */
2947 * Resolve the URI...
2950 resolve
.cancel
= cancel
;
2951 gettimeofday(&resolve
.end_time
, NULL
);
2954 resolve
.end_time
.tv_sec
+= msec
/ 1000;
2955 resolve
.end_time
.tv_usec
+= (msec
% 1000) * 1000;
2957 while (resolve
.end_time
.tv_usec
>= 1000000)
2959 resolve
.end_time
.tv_sec
++;
2960 resolve
.end_time
.tv_usec
-= 1000000;
2964 resolve
.end_time
.tv_sec
+= 75;
2967 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_RESOLVING
,
2970 if ((uri
= _httpResolveURI(uri
, tempuri
, sizeof(tempuri
),
2971 _HTTP_RESOLVE_FQDN
, cups_dnssd_resolve_cb
,
2974 _cupsSetError(IPP_INTERNAL_ERROR
, _("Unable to resolve printer URI."), 1);
2977 (*cb
)(user_data
, CUPS_DEST_FLAGS_UNCONNECTED
| CUPS_DEST_FLAGS_ERROR
,
2984 * Save the resolved URI...
2987 dest
->num_options
= cupsAddOption("printer-uri-supported", uri
,
2988 dest
->num_options
, &dest
->options
);
2990 return (cupsGetOption("printer-uri-supported", dest
->num_options
,
2996 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
2999 static int /* O - 1 to continue, 0 to stop */
3000 cups_dnssd_resolve_cb(void *context
) /* I - Resolve data */
3002 _cups_dnssd_resolve_t
*resolve
= (_cups_dnssd_resolve_t
*)context
;
3004 struct timeval curtime
; /* Current time */
3008 * If the cancel variable is set, return immediately.
3011 if (*resolve
->cancel
)
3015 * Otherwise check the end time...
3018 gettimeofday(&curtime
, NULL
);
3020 return (curtime
.tv_sec
> resolve
->end_time
.tv_sec
||
3021 (curtime
.tv_sec
== resolve
->end_time
.tv_sec
&&
3022 curtime
.tv_usec
> resolve
->end_time
.tv_usec
));
3027 * 'cups_dnssd_unquote()' - Unquote a name string.
3031 cups_dnssd_unquote(char *dst
, /* I - Destination buffer */
3032 const char *src
, /* I - Source string */
3033 size_t dstsize
) /* I - Size of destination buffer */
3035 char *dstend
= dst
+ dstsize
- 1; /* End of destination buffer */
3038 while (*src
&& dst
< dstend
)
3043 if (isdigit(src
[0] & 255) && isdigit(src
[1] & 255) &&
3044 isdigit(src
[2] & 255))
3046 *dst
++ = ((((src
[0] - '0') * 10) + src
[1] - '0') * 10) + src
[2] - '0';
3058 #endif /* HAVE_DNSSD */
3062 * 'cups_find_dest()' - Find a destination using a binary search.
3065 static int /* O - Index of match */
3066 cups_find_dest(const char *name
, /* I - Destination name */
3067 const char *instance
, /* I - Instance or NULL */
3068 int num_dests
, /* I - Number of destinations */
3069 cups_dest_t
*dests
, /* I - Destinations */
3070 int prev
, /* I - Previous index */
3071 int *rdiff
) /* O - Difference of match */
3073 int left
, /* Low mark for binary search */
3074 right
, /* High mark for binary search */
3075 current
, /* Current index */
3076 diff
; /* Result of comparison */
3077 cups_dest_t key
; /* Search key */
3080 key
.name
= (char *)name
;
3081 key
.instance
= (char *)instance
;
3086 * Start search on either side of previous...
3089 if ((diff
= cups_compare_dests(&key
, dests
+ prev
)) == 0 ||
3090 (diff
< 0 && prev
== 0) ||
3091 (diff
> 0 && prev
== (num_dests
- 1)))
3099 * Start with previous on right side...
3108 * Start wih previous on left side...
3112 right
= num_dests
- 1;
3118 * Start search in the middle...
3122 right
= num_dests
- 1;
3127 current
= (left
+ right
) / 2;
3128 diff
= cups_compare_dests(&key
, dests
+ current
);
3137 while ((right
- left
) > 1);
3142 * Check the last 1 or 2 elements...
3145 if ((diff
= cups_compare_dests(&key
, dests
+ left
)) <= 0)
3149 diff
= cups_compare_dests(&key
, dests
+ right
);
3155 * Return the closest destination and the difference...
3165 * 'cups_get_default()' - Get the default destination from an lpoptions file.
3168 static char * /* O - Default destination or NULL */
3169 cups_get_default(const char *filename
, /* I - File to read */
3170 char *namebuf
, /* I - Name buffer */
3171 size_t namesize
, /* I - Size of name buffer */
3172 const char **instance
) /* I - Instance */
3174 cups_file_t
*fp
; /* lpoptions file */
3175 char line
[8192], /* Line from file */
3176 *value
, /* Value for line */
3177 *nameptr
; /* Pointer into name */
3178 int linenum
; /* Current line */
3183 if ((fp
= cupsFileOpen(filename
, "r")) != NULL
)
3187 while (cupsFileGetConf(fp
, line
, sizeof(line
), &value
, &linenum
))
3189 if (!_cups_strcasecmp(line
, "default") && value
)
3191 strlcpy(namebuf
, value
, namesize
);
3193 if ((nameptr
= strchr(namebuf
, ' ')) != NULL
)
3195 if ((nameptr
= strchr(namebuf
, '\t')) != NULL
)
3198 if ((nameptr
= strchr(namebuf
, '/')) != NULL
)
3201 *instance
= nameptr
;
3209 return (*namebuf
? namebuf
: NULL
);
3214 * 'cups_get_dests()' - Get destinations from a file.
3217 static int /* O - Number of destinations */
3219 const char *filename
, /* I - File to read from */
3220 const char *match_name
, /* I - Destination name we want */
3221 const char *match_inst
, /* I - Instance name we want */
3222 int user_default_set
, /* I - User default printer set? */
3223 int num_dests
, /* I - Number of destinations */
3224 cups_dest_t
**dests
) /* IO - Destinations */
3226 int i
; /* Looping var */
3227 cups_dest_t
*dest
; /* Current destination */
3228 cups_file_t
*fp
; /* File pointer */
3229 char line
[8192], /* Line from file */
3230 *lineptr
, /* Pointer into line */
3231 *name
, /* Name of destination/option */
3232 *instance
; /* Instance of destination */
3233 int linenum
; /* Current line number */
3236 DEBUG_printf(("7cups_get_dests(filename=\"%s\", match_name=\"%s\", "
3237 "match_inst=\"%s\", user_default_set=%d, num_dests=%d, "
3238 "dests=%p)", filename
, match_name
, match_inst
,
3239 user_default_set
, num_dests
, dests
));
3242 * Try to open the file...
3245 if ((fp
= cupsFileOpen(filename
, "r")) == NULL
)
3249 * Read each printer; each line looks like:
3251 * Dest name[/instance] options
3252 * Default name[/instance] options
3257 while (cupsFileGetConf(fp
, line
, sizeof(line
), &lineptr
, &linenum
))
3260 * See what type of line it is...
3263 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
3264 linenum
, line
, lineptr
));
3266 if ((_cups_strcasecmp(line
, "dest") && _cups_strcasecmp(line
, "default")) || !lineptr
)
3268 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
3275 * Search for an instance...
3278 while (!isspace(*lineptr
& 255) && *lineptr
&& *lineptr
!= '/')
3281 if (*lineptr
== '/')
3284 * Found an instance...
3291 * Search for an instance...
3294 while (!isspace(*lineptr
& 255) && *lineptr
)
3303 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name
,
3307 * See if the primary instance of the destination exists; if not,
3308 * ignore this entry and move on...
3313 if (_cups_strcasecmp(name
, match_name
) ||
3314 (!instance
&& match_inst
) ||
3315 (instance
&& !match_inst
) ||
3316 (instance
&& _cups_strcasecmp(instance
, match_inst
)))
3321 else if (cupsGetDest(name
, NULL
, num_dests
, *dests
) == NULL
)
3323 DEBUG_puts("9cups_get_dests: Not found!");
3329 * Add the destination...
3332 num_dests
= cupsAddDest(name
, instance
, num_dests
, dests
);
3334 if ((dest
= cupsGetDest(name
, instance
, num_dests
, *dests
)) == NULL
)
3340 DEBUG_puts("9cups_get_dests: Out of memory!");
3346 * Add options until we hit the end of the line...
3349 dest
->num_options
= cupsParseOptions(lineptr
, dest
->num_options
,
3353 * If we found what we were looking for, stop now...
3360 * Set this as default if needed...
3363 if (!user_default_set
&& !_cups_strcasecmp(line
, "default"))
3365 DEBUG_puts("9cups_get_dests: Setting as default...");
3367 for (i
= 0; i
< num_dests
; i
++)
3368 (*dests
)[i
].is_default
= 0;
3370 dest
->is_default
= 1;
3375 * Close the file and return...
3385 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
3389 static char * /* O - New string */
3391 ipp_attribute_t
*attr
, /* I - Attribute to convert */
3392 char *buffer
, /* I - Buffer */
3393 size_t bufsize
) /* I - Size of buffer */
3395 int i
; /* Looping var */
3396 char *ptr
, /* Pointer into buffer */
3397 *end
, /* Pointer to end of buffer */
3398 *valptr
; /* Pointer into string attribute */
3402 * Return quickly if we have a single string value...
3405 if (attr
->num_values
== 1 &&
3406 attr
->value_tag
!= IPP_TAG_INTEGER
&&
3407 attr
->value_tag
!= IPP_TAG_ENUM
&&
3408 attr
->value_tag
!= IPP_TAG_BOOLEAN
&&
3409 attr
->value_tag
!= IPP_TAG_RANGE
)
3410 return (attr
->values
[0].string
.text
);
3413 * Copy the values to the string, separating with commas and escaping strings
3417 end
= buffer
+ bufsize
- 1;
3419 for (i
= 0, ptr
= buffer
; i
< attr
->num_values
&& ptr
< end
; i
++)
3424 switch (attr
->value_tag
)
3426 case IPP_TAG_INTEGER
:
3428 snprintf(ptr
, end
- ptr
+ 1, "%d", attr
->values
[i
].integer
);
3431 case IPP_TAG_BOOLEAN
:
3432 if (attr
->values
[i
].boolean
)
3433 strlcpy(ptr
, "true", end
- ptr
+ 1);
3435 strlcpy(ptr
, "false", end
- ptr
+ 1);
3438 case IPP_TAG_RANGE
:
3439 if (attr
->values
[i
].range
.lower
== attr
->values
[i
].range
.upper
)
3440 snprintf(ptr
, end
- ptr
+ 1, "%d", attr
->values
[i
].range
.lower
);
3442 snprintf(ptr
, end
- ptr
+ 1, "%d-%d", attr
->values
[i
].range
.lower
,
3443 attr
->values
[i
].range
.upper
);
3447 for (valptr
= attr
->values
[i
].string
.text
;
3448 *valptr
&& ptr
< end
;)
3450 if (strchr(" \t\n\\\'\"", *valptr
))
3452 if (ptr
>= (end
- 1))
3475 * End of "$Id: dest.c 9568 2011-02-25 06:13:56Z mike $".