]> git.ipfire.org Git - thirdparty/cups.git/blame - cups/dest.c
Merge changes from CUPS 1.7svn-r10791.
[thirdparty/cups.git] / cups / dest.c
CommitLineData
ef416fc2 1/*
f14324a7 2 * "$Id: dest.c 9568 2011-02-25 06:13:56Z mike $"
ef416fc2 3 *
71e16022 4 * User-defined destination (and option) support for CUPS.
ef416fc2 5 *
dcb445bc 6 * Copyright 2007-2012 by Apple Inc.
b86bc4cf 7 * Copyright 1997-2007 by Easy Software Products.
ef416fc2 8 *
9 * These coded instructions, statements, and computer programs are the
bc44d920 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/".
ef416fc2 14 *
15 * This file is subject to the Apple OS-Developed Software exception.
16 *
17 * Contents:
18 *
9c80ffa2
MS
19 * cupsAddDest() - Add a destination to the list of
20 * destinations.
c8fef167 21 * _cupsAppleCopyDefaultPaperID() - Get the default paper ID.
f14324a7 22 * _cupsAppleCopyDefaultPrinter() - Get the default printer at this location.
c8fef167
MS
23 * _cupsAppleGetUseLastPrinter() - Get whether to use the last used printer.
24 * _cupsAppleSetDefaultPaperID() - Set the default paper id.
9c80ffa2
MS
25 * _cupsAppleSetDefaultPrinter() - Set the default printer for this
26 * location.
c8fef167 27 * _cupsAppleSetUseLastPrinter() - Set whether to use the last used printer.
9c80ffa2 28 * cupsConnectDest() - Connect to the server for a destination.
dcb445bc
MS
29 * cupsConnectDestBlock() - Connect to the server for a destination.
30 * cupsCopyDest() - Copy a destination.
9c80ffa2
MS
31 * cupsEnumDests() - Enumerate available destinations with a
32 * callback function.
33 * cupsEnumDestsBlock() - Enumerate available destinations with a
34 * block.
35 * cupsFreeDests() - Free the memory used by the list of
36 * destinations.
37 * cupsGetDest() - Get the named destination from the list.
dcb445bc
MS
38 * _cupsGetDestResource() - Get the resource path and URI for a
39 * destination.
9c80ffa2
MS
40 * _cupsGetDests() - Get destinations from a server.
41 * cupsGetDests() - Get the list of destinations from the
42 * default server.
43 * cupsGetDests2() - Get the list of destinations from the
44 * specified server.
45 * cupsGetNamedDest() - Get options for the named destination.
46 * cupsRemoveDest() - Remove a destination from the destination
47 * list.
48 * cupsSetDefaultDest() - Set the default destination.
49 * cupsSetDests() - Save the list of destinations for the
50 * default server.
51 * cupsSetDests2() - Save the list of destinations for the
52 * specified server.
53 * _cupsUserDefault() - Get the user default printer from
54 * environment variables and location
55 * information.
56 * appleCopyLocations() - Copy the location history array.
57 * appleCopyNetwork() - Get the network ID for the current
58 * location.
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.
dcb445bc 64 * cups_dnssd_browse_cb() - Browse for printers.
a29fd7dd
MS
65 * cups_dnssd_browse_cb() - Browse for printers.
66 * cups_dnssd_client_cb() - Avahi client callback function.
dcb445bc
MS
67 * cups_dnssd_compare_device() - Compare two devices.
68 * cups_dnssd_free_device() - Free the memory used by a device.
69 * cups_dnssd_get_device() - Lookup a device and create it as needed.
70 * cups_dnssd_local_cb() - Browse for local printers.
a29fd7dd
MS
71 * cups_dnssd_poll_cb() - Wait for input on the specified file
72 * descriptors.
dcb445bc 73 * cups_dnssd_query_cb() - Process query data.
a29fd7dd
MS
74 * cups_dnssd_resolve() - Resolve a Bonjour printer URI.
75 * cups_dnssd_resolve_cb() - See if we should continue resolving.
dcb445bc 76 * cups_dnssd_unquote() - Unquote a name string.
9c80ffa2
MS
77 * cups_find_dest() - Find a destination using a binary search.
78 * cups_get_default() - Get the default destination from an
79 * lpoptions file.
80 * cups_get_dests() - Get destinations from a file.
81 * cups_make_string() - Make a comma-separated string of values
82 * from an IPP attribute.
ef416fc2 83 */
84
85/*
86 * Include necessary headers...
87 */
88
71e16022 89#include "cups-private.h"
b423cd4c 90#include <sys/stat.h>
ef416fc2 91
fa73b229 92#ifdef HAVE_NOTIFY_H
93# include <notify.h>
94#endif /* HAVE_NOTIFY_H */
95
dcb445bc
MS
96#ifdef HAVE_POLL
97# include <poll.h>
98#endif /* HAVE_POLL */
99
100#ifdef HAVE_DNSSD
101# include <dns_sd.h>
102#endif /* HAVE_DNSSD */
103
a29fd7dd
MS
104#ifdef HAVE_AVAHI
105# include <avahi-client/client.h>
106# include <avahi-client/lookup.h>
107# include <avahi-common/simple-watch.h>
108# include <avahi-common/domain.h>
109# include <avahi-common/error.h>
110# include <avahi-common/malloc.h>
111#define kDNSServiceMaxDomainName AVAHI_DOMAIN_NAME_MAX
112#endif /* HAVE_AVAHI */
113
dcb445bc
MS
114
115/*
116 * Constants...
117 */
118
080811b1 119#ifdef __APPLE__
080811b1 120# include <SystemConfiguration/SystemConfiguration.h>
f14324a7
MS
121# define kCUPSPrintingPrefs CFSTR("org.cups.PrintingPrefs")
122# define kDefaultPaperIDKey CFSTR("DefaultPaperID")
123# define kLastUsedPrintersKey CFSTR("LastUsedPrinters")
124# define kLocationNetworkKey CFSTR("Network")
125# define kLocationPrinterIDKey CFSTR("PrinterID")
126# define kUseLastPrinter CFSTR("UseLastPrinter")
080811b1
MS
127#endif /* __APPLE__ */
128
ef416fc2 129
dcb445bc
MS
130/*
131 * Types...
132 */
133
a29fd7dd 134#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
dcb445bc
MS
135typedef enum _cups_dnssd_state_e /* Enumerated device state */
136{
137 _CUPS_DNSSD_NEW,
138 _CUPS_DNSSD_QUERY,
139 _CUPS_DNSSD_PENDING,
140 _CUPS_DNSSD_ACTIVE,
141 _CUPS_DNSSD_LOCAL,
a29fd7dd 142 _CUPS_DNSSD_INCOMPATIBLE,
dcb445bc
MS
143 _CUPS_DNSSD_ERROR
144} _cups_dnssd_state_t;
145
146typedef struct _cups_dnssd_data_s /* Enumeration data */
147{
a29fd7dd 148# ifdef HAVE_DNSSD
dcb445bc 149 DNSServiceRef main_ref; /* Main service reference */
a29fd7dd
MS
150# else /* HAVE_AVAHI */
151 AvahiSimplePoll *simple_poll; /* Polling interface */
152 AvahiClient *client; /* Client information */
153 int got_data; /* Did we get data? */
154# endif /* HAVE_DNSSD */
dcb445bc
MS
155 cups_dest_cb_t cb; /* Callback */
156 void *user_data; /* User data pointer */
157 cups_ptype_t type, /* Printer type filter */
158 mask; /* Printer type mask */
159 cups_array_t *devices; /* Devices found so far */
160} _cups_dnssd_data_t;
161
162typedef struct _cups_dnssd_device_s /* Enumerated device */
163{
164 _cups_dnssd_state_t state; /* State of device listing */
a29fd7dd 165# ifdef HAVE_DNSSD
dcb445bc 166 DNSServiceRef ref; /* Service reference for query */
a29fd7dd
MS
167# else /* HAVE_AVAHI */
168 AvahiRecordBrowser *ref; /* Browser for query */
169# endif /* HAVE_DNSSD */
dcb445bc
MS
170 char *domain, /* Domain name */
171 *fullName, /* Full name */
172 *regtype; /* Registration type */
173 cups_ptype_t type; /* Device registration type */
174 cups_dest_t dest; /* Destination record */
175} _cups_dnssd_device_t;
176
177typedef struct _cups_dnssd_resolve_s /* Data for resolving URI */
178{
179 int *cancel; /* Pointer to "cancel" variable */
180 struct timeval end_time; /* Ending time */
181} _cups_dnssd_resolve_t;
182#endif /* HAVE_DNSSD */
183
184
ef416fc2 185/*
186 * Local functions...
187 */
188
080811b1 189#ifdef __APPLE__
9c80ffa2
MS
190static CFArrayRef appleCopyLocations(void);
191static CFStringRef appleCopyNetwork(void);
192static char *appleGetPaperSize(char *name, int namesize);
a29fd7dd
MS
193static CFStringRef appleGetPrinter(CFArrayRef locations,
194 CFStringRef network, CFIndex *locindex);
080811b1 195#endif /* __APPLE__ */
9c80ffa2
MS
196static cups_dest_t *cups_add_dest(const char *name, const char *instance,
197 int *num_dests, cups_dest_t **dests);
198#ifdef __BLOCKS__
dcb445bc
MS
199static int cups_block_cb(cups_dest_block_t block, unsigned flags,
200 cups_dest_t *dest);
9c80ffa2
MS
201#endif /* __BLOCKS__ */
202static int cups_compare_dests(cups_dest_t *a, cups_dest_t *b);
a29fd7dd
MS
203#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
204# ifdef HAVE_DNSSD
dcb445bc
MS
205static void cups_dnssd_browse_cb(DNSServiceRef sdRef,
206 DNSServiceFlags flags,
207 uint32_t interfaceIndex,
208 DNSServiceErrorType errorCode,
209 const char *serviceName,
210 const char *regtype,
211 const char *replyDomain,
212 void *context);
a29fd7dd
MS
213# else /* HAVE_AVAHI */
214static void cups_dnssd_browse_cb(AvahiServiceBrowser *browser,
215 AvahiIfIndex interface,
216 AvahiProtocol protocol,
217 AvahiBrowserEvent event,
218 const char *serviceName,
219 const char *regtype,
220 const char *replyDomain,
221 AvahiLookupResultFlags flags,
222 void *context);
223static void cups_dnssd_client_cb(AvahiClient *client,
224 AvahiClientState state,
225 void *context);
226# endif /* HAVE_DNSSD */
dcb445bc
MS
227static int cups_dnssd_compare_devices(_cups_dnssd_device_t *a,
228 _cups_dnssd_device_t *b);
229static void cups_dnssd_free_device(_cups_dnssd_device_t *device,
230 _cups_dnssd_data_t *data);
231static _cups_dnssd_device_t *
232 cups_dnssd_get_device(_cups_dnssd_data_t *data,
233 const char *serviceName,
234 const char *regtype,
235 const char *replyDomain);
a29fd7dd 236# ifdef HAVE_DNSSD
dcb445bc
MS
237static void cups_dnssd_local_cb(DNSServiceRef sdRef,
238 DNSServiceFlags flags,
239 uint32_t interfaceIndex,
240 DNSServiceErrorType errorCode,
241 const char *serviceName,
242 const char *regtype,
243 const char *replyDomain,
244 void *context);
245static void cups_dnssd_query_cb(DNSServiceRef sdRef,
246 DNSServiceFlags flags,
247 uint32_t interfaceIndex,
248 DNSServiceErrorType errorCode,
249 const char *fullName,
250 uint16_t rrtype, uint16_t rrclass,
251 uint16_t rdlen, const void *rdata,
252 uint32_t ttl, void *context);
a29fd7dd
MS
253# else /* HAVE_AVAHI */
254static int cups_dnssd_poll_cb(struct pollfd *pollfds,
255 unsigned int num_pollfds,
256 int timeout, void *context);
257static void cups_dnssd_query_cb(AvahiRecordBrowser *browser,
258 AvahiIfIndex interface,
259 AvahiProtocol protocol,
260 AvahiBrowserEvent event,
261 const char *name, uint16_t rrclass,
262 uint16_t rrtype, const void *rdata,
263 size_t rdlen,
264 AvahiLookupResultFlags flags,
265 void *context);
266# endif /* HAVE_DNSSD */
dcb445bc
MS
267static const char *cups_dnssd_resolve(cups_dest_t *dest, const char *uri,
268 int msec, int *cancel,
269 cups_dest_cb_t cb, void *user_data);
270static int cups_dnssd_resolve_cb(void *context);
271static void cups_dnssd_unquote(char *dst, const char *src,
272 size_t dstsize);
a29fd7dd 273#endif /* HAVE_DNSSD || HAVE_AVAHI */
9c80ffa2
MS
274static int cups_find_dest(const char *name, const char *instance,
275 int num_dests, cups_dest_t *dests, int prev,
276 int *rdiff);
277static char *cups_get_default(const char *filename, char *namebuf,
278 size_t namesize, const char **instance);
279static int cups_get_dests(const char *filename, const char *match_name,
280 const char *match_inst, int user_default_set,
281 int num_dests, cups_dest_t **dests);
282static char *cups_make_string(ipp_attribute_t *attr, char *buffer,
283 size_t bufsize);
ef416fc2 284
285
286/*
287 * 'cupsAddDest()' - Add a destination to the list of destinations.
288 *
2abf387c 289 * This function cannot be used to add a new class or printer queue,
290 * it only adds a new container of saved options for the named
291 * destination or instance.
292 *
293 * If the named destination already exists, the destination list is
294 * returned unchanged. Adding a new instance of a destination creates
295 * a copy of that destination's options.
296 *
5a738aea 297 * Use the @link cupsSaveDests@ function to save the updated list of
2abf387c 298 * destinations to the user's lpoptions file.
ef416fc2 299 */
300
301int /* O - New number of destinations */
2abf387c 302cupsAddDest(const char *name, /* I - Destination name */
5a738aea 303 const char *instance, /* I - Instance name or @code NULL@ for none/primary */
ef416fc2 304 int num_dests, /* I - Number of destinations */
305 cups_dest_t **dests) /* IO - Destinations */
306{
307 int i; /* Looping var */
308 cups_dest_t *dest; /* Destination pointer */
bf3816c7 309 cups_dest_t *parent = NULL; /* Parent destination */
426c6a59
MS
310 cups_option_t *doption, /* Current destination option */
311 *poption; /* Current parent option */
ef416fc2 312
313
2abf387c 314 if (!name || !dests)
ef416fc2 315 return (0);
316
426c6a59
MS
317 if (!cupsGetDest(name, instance, num_dests, *dests))
318 {
41681883 319 if (instance && !cupsGetDest(name, NULL, num_dests, *dests))
426c6a59 320 return (num_dests);
ef416fc2 321
5a9febac
MS
322 if ((dest = cups_add_dest(name, instance, &num_dests, dests)) == NULL)
323 return (num_dests);
2abf387c 324
5a662dc0
MS
325 /*
326 * Find the base dest again now the array has been realloc'd.
327 */
328
329 parent = cupsGetDest(name, NULL, num_dests, *dests);
330
426c6a59
MS
331 if (instance && parent && parent->num_options > 0)
332 {
333 /*
334 * Copy options from parent...
335 */
ef416fc2 336
426c6a59 337 dest->options = calloc(sizeof(cups_option_t), parent->num_options);
2abf387c 338
426c6a59
MS
339 if (dest->options)
340 {
341 dest->num_options = parent->num_options;
ef416fc2 342
426c6a59
MS
343 for (i = dest->num_options, doption = dest->options,
344 poption = parent->options;
345 i > 0;
346 i --, doption ++, poption ++)
347 {
348 doption->name = _cupsStrRetain(poption->name);
349 doption->value = _cupsStrRetain(poption->value);
350 }
351 }
2abf387c 352 }
353 }
354
426c6a59 355 return (num_dests);
ef416fc2 356}
357
358
c8fef167
MS
359#ifdef __APPLE__
360/*
361 * '_cupsAppleCopyDefaultPaperID()' - Get the default paper ID.
362 */
363
364CFStringRef /* O - Default paper ID */
365_cupsAppleCopyDefaultPaperID(void)
366{
f14324a7
MS
367 return (CFPreferencesCopyAppValue(kDefaultPaperIDKey,
368 kCUPSPrintingPrefs));
369}
370
371
372/*
373 * '_cupsAppleCopyDefaultPrinter()' - Get the default printer at this location.
374 */
375
376CFStringRef /* O - Default printer name */
377_cupsAppleCopyDefaultPrinter(void)
378{
379 CFStringRef network; /* Network location */
380 CFArrayRef locations; /* Location array */
381 CFStringRef locprinter; /* Current printer */
c8fef167
MS
382
383
f14324a7
MS
384 /*
385 * Use location-based defaults only if "use last printer" is selected in the
386 * system preferences...
387 */
c8fef167 388
f14324a7
MS
389 if (!_cupsAppleGetUseLastPrinter())
390 {
391 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Not using last printer as "
392 "default.");
393 return (NULL);
394 }
c8fef167 395
f14324a7
MS
396 /*
397 * Get the current location...
398 */
399
400 if ((network = appleCopyNetwork()) == NULL)
401 {
402 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Unable to get current "
403 "network.");
404 return (NULL);
405 }
406
f14324a7
MS
407 /*
408 * Lookup the network in the preferences...
409 */
410
411 if ((locations = appleCopyLocations()) == NULL)
412 {
413 /*
414 * Missing or bad location array, so no location-based default...
415 */
416
417 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Missing or bad last used "
418 "printer array.");
419
420 CFRelease(network);
421
422 return (NULL);
423 }
88f9aafc 424
f14324a7
MS
425 DEBUG_printf(("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.",
426 (int)CFArrayGetCount(locations)));
427
428 if ((locprinter = appleGetPrinter(locations, network, NULL)) != NULL)
429 CFRetain(locprinter);
430
431 CFRelease(network);
432 CFRelease(locations);
433
434 return (locprinter);
c8fef167
MS
435}
436
437
438/*
439 * '_cupsAppleGetUseLastPrinter()' - Get whether to use the last used printer.
440 */
441
442int /* O - 1 to use last printer, 0 otherwise */
443_cupsAppleGetUseLastPrinter(void)
444{
445 Boolean uselast, /* Use last printer preference value */
446 uselast_set; /* Valid is set? */
447
448
449 if (getenv("CUPS_DISABLE_APPLE_DEFAULT"))
450 return (0);
451
f14324a7
MS
452 uselast = CFPreferencesGetAppBooleanValue(kUseLastPrinter,
453 kCUPSPrintingPrefs,
c8fef167 454 &uselast_set);
c8fef167
MS
455 if (!uselast_set)
456 return (1);
457 else
458 return (uselast);
459}
460
461
462/*
463 * '_cupsAppleSetDefaultPaperID()' - Set the default paper id.
464 */
465
466void
467_cupsAppleSetDefaultPaperID(
468 CFStringRef name) /* I - New paper ID */
469{
f14324a7
MS
470 CFPreferencesSetAppValue(kDefaultPaperIDKey, name, kCUPSPrintingPrefs);
471 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
472 notify_post("com.apple.printerPrefsChange");
473}
474
475
476/*
477 * '_cupsAppleSetDefaultPrinter()' - Set the default printer for this location.
478 */
479
480void
481_cupsAppleSetDefaultPrinter(
482 CFStringRef name) /* I - Default printer/class name */
483{
484 CFStringRef network; /* Current network */
485 CFArrayRef locations; /* Old locations array */
486 CFIndex locindex; /* Index in locations array */
487 CFStringRef locprinter; /* Current printer */
488 CFMutableArrayRef newlocations; /* New locations array */
489 CFMutableDictionaryRef newlocation; /* New location */
490
491
492 /*
493 * Get the current location...
494 */
495
496 if ((network = appleCopyNetwork()) == NULL)
497 {
498 DEBUG_puts("1_cupsAppleSetDefaultPrinter: Unable to get current network...");
499 return;
500 }
501
502 /*
503 * Lookup the network in the preferences...
504 */
505
506 if ((locations = appleCopyLocations()) != NULL)
507 locprinter = appleGetPrinter(locations, network, &locindex);
508 else
509 {
510 locprinter = NULL;
511 locindex = -1;
512 }
513
514 if (!locprinter || CFStringCompare(locprinter, name, 0) != kCFCompareEqualTo)
515 {
516 /*
517 * Need to change the locations array...
518 */
519
520 if (locations)
521 {
522 newlocations = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0,
523 locations);
524
525 if (locprinter)
526 CFArrayRemoveValueAtIndex(newlocations, locindex);
527 }
528 else
529 newlocations = CFArrayCreateMutable(kCFAllocatorDefault, 0,
530 &kCFTypeArrayCallBacks);
531
532 newlocation = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
533 &kCFTypeDictionaryKeyCallBacks,
534 &kCFTypeDictionaryValueCallBacks);
535
536 if (newlocation && newlocations)
537 {
538 /*
539 * Put the new location at the front of the array...
540 */
541
542 CFDictionaryAddValue(newlocation, kLocationNetworkKey, network);
543 CFDictionaryAddValue(newlocation, kLocationPrinterIDKey, name);
544 CFArrayInsertValueAtIndex(newlocations, 0, newlocation);
545
546 /*
547 * Limit the number of locations to 10...
548 */
549
550 while (CFArrayGetCount(newlocations) > 10)
551 CFArrayRemoveValueAtIndex(newlocations, 10);
552
553 /*
554 * Push the changes out...
555 */
556
557 CFPreferencesSetAppValue(kLastUsedPrintersKey, newlocations,
558 kCUPSPrintingPrefs);
559 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
560 notify_post("com.apple.printerPrefsChange");
561 }
562
563 if (newlocations)
564 CFRelease(newlocations);
565
566 if (newlocation)
567 CFRelease(newlocation);
568 }
569
570 if (locations)
571 CFRelease(locations);
572
573 CFRelease(network);
c8fef167
MS
574}
575
576
577/*
578 * '_cupsAppleSetUseLastPrinter()' - Set whether to use the last used printer.
579 */
88f9aafc
MS
580
581void
c8fef167
MS
582_cupsAppleSetUseLastPrinter(
583 int uselast) /* O - 1 to use last printer, 0 otherwise */
584{
88f9aafc 585 CFPreferencesSetAppValue(kUseLastPrinter,
c8fef167 586 uselast ? kCFBooleanTrue : kCFBooleanFalse,
f14324a7
MS
587 kCUPSPrintingPrefs);
588 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
589 notify_post("com.apple.printerPrefsChange");
c8fef167
MS
590}
591#endif /* __APPLE__ */
592
593
9c80ffa2
MS
594/*
595 * 'cupsConnectDest()' - Connect to the server for a destination.
596 *
dcb445bc
MS
597 * Connect to the destination, returning a new http_t connection object and
598 * optionally the resource path to use for the destination. These calls will
599 * block until a connection is made, the timeout expires, the integer pointed
600 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
601 * The caller is responsible for calling httpClose() on the returned object.
602 *
f3c17241 603 * @since CUPS 1.6/OS X 10.8@
9c80ffa2
MS
604 */
605
606http_t * /* O - Connection to server or @code NULL@ */
dcb445bc
MS
607cupsConnectDest(
608 cups_dest_t *dest, /* I - Destination */
609 unsigned flags, /* I - Connection flags */
610 int msec, /* I - Timeout in milliseconds */
611 int *cancel, /* I - Pointer to "cancel" variable */
612 char *resource, /* I - Resource buffer */
613 size_t resourcesize, /* I - Size of resource buffer */
614 cups_dest_cb_t cb, /* I - Callback function */
615 void *user_data) /* I - User data pointer */
9c80ffa2 616{
dcb445bc
MS
617 const char *uri; /* Printer URI */
618 char scheme[32], /* URI scheme */
619 userpass[256], /* Username and password (unused) */
620 hostname[256], /* Hostname */
621 tempresource[1024]; /* Temporary resource buffer */
622 int port; /* Port number */
623 char portstr[16]; /* Port number string */
12f89d24 624 http_encryption_t encryption; /* Encryption to use */
dcb445bc
MS
625 http_addrlist_t *addrlist; /* Address list for server */
626 http_t *http; /* Connection to server */
627
628
629 /*
630 * Range check input...
631 */
632
633 if (!dest)
634 {
635 if (resource)
636 *resource = '\0';
637
638 _cupsSetError(IPP_INTERNAL_ERROR, strerror(EINVAL), 0);
639 return (NULL);
640 }
641
642 if (!resource || resourcesize < 1)
643 {
644 resource = tempresource;
645 resourcesize = sizeof(tempresource);
646 }
647
648 /*
649 * Grab the printer URI...
650 */
651
652 if ((uri = cupsGetOption("printer-uri-supported", dest->num_options,
653 dest->options)) == NULL)
654 {
655 _cupsSetError(IPP_INTERNAL_ERROR, strerror(ENOENT), 0);
656
657 if (cb)
658 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
659 dest);
660
661 return (NULL);
662 }
663
a29fd7dd 664#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
dcb445bc
MS
665 if (strstr(uri, "._tcp"))
666 {
667 if ((uri = cups_dnssd_resolve(dest, uri, msec, cancel, cb,
668 user_data)) == NULL)
669 return (NULL);
670 }
a29fd7dd 671#endif /* HAVE_DNSSD || HAVE_AVAHI */
dcb445bc
MS
672
673 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme),
674 userpass, sizeof(userpass), hostname, sizeof(hostname),
675 &port, resource, resourcesize) < HTTP_URI_OK)
676 {
677 _cupsSetError(IPP_INTERNAL_ERROR, _("Bad printer URI."), 1);
678
679 if (cb)
680 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
681 dest);
682
683 return (NULL);
684 }
685
686 /*
687 * Lookup the address for the server...
688 */
689
690 if (cb)
691 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING,
692 dest);
693
694 snprintf(portstr, sizeof(portstr), "%d", port);
695
696 if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portstr)) == NULL)
697 {
698 if (cb)
699 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
700 dest);
701
702 return (NULL);
703 }
704
705 if (cancel && *cancel)
706 {
707 httpAddrFreeList(addrlist);
708
709 if (cb)
710 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CANCELED,
711 dest);
712
713 return (NULL);
714 }
715
716 /*
717 * Create the HTTP object pointing to the server referenced by the URI...
718 */
719
720 if (!strcmp(scheme, "ipps") || port == 443)
12f89d24 721 encryption = HTTP_ENCRYPT_ALWAYS;
dcb445bc 722 else
12f89d24 723 encryption = HTTP_ENCRYPT_IF_REQUESTED;
dcb445bc 724
a469f8a5
MS
725 http = _httpCreate(hostname, port, addrlist, AF_UNSPEC, encryption, 1,
726 _HTTP_MODE_CLIENT);
dcb445bc
MS
727
728 /*
729 * Connect if requested...
730 */
731
732 if (flags & CUPS_DEST_FLAGS_UNCONNECTED)
733 {
734 if (cb)
735 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED, dest);
736 }
737 else
738 {
739 if (cb)
740 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CONNECTING,
741 dest);
742
743 if (!httpReconnect2(http, msec, cancel) && cb)
744 {
745 if (cancel && *cancel)
746 (*cb)(user_data,
747 CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CONNECTING, dest);
748 else
749 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
750 dest);
751 }
752 else if (cb)
753 (*cb)(user_data, CUPS_DEST_FLAGS_NONE, dest);
754 }
755
756 return (http);
757}
758
759
760#ifdef __BLOCKS__
761/*
762 * 'cupsConnectDestBlock()' - Connect to the server for a destination.
763 *
764 * Connect to the destination, returning a new http_t connection object and
765 * optionally the resource path to use for the destination. These calls will
766 * block until a connection is made, the timeout expires, the integer pointed
767 * to by "cancel" is non-zero, or the callback function (or block) returns 0,
768 * The caller is responsible for calling httpClose() on the returned object.
769 *
f3c17241 770 * @since CUPS 1.6/OS X 10.8@
dcb445bc
MS
771 */
772
773http_t * /* O - Connection to server or @code NULL@ */
774cupsConnectDestBlock(
775 cups_dest_t *dest, /* I - Destination */
776 unsigned flags, /* I - Connection flags */
777 int msec, /* I - Timeout in milliseconds */
778 int *cancel, /* I - Pointer to "cancel" variable */
779 char *resource, /* I - Resource buffer */
780 size_t resourcesize, /* I - Size of resource buffer */
781 cups_dest_block_t block) /* I - Callback block */
782{
783 return (cupsConnectDest(dest, flags, msec, cancel, resource, resourcesize,
784 (cups_dest_cb_t)cups_block_cb, (void *)block));
785}
786#endif /* __BLOCKS__ */
787
788
789/*
790 * 'cupsCopyDest()' - Copy a destination.
791 *
792 * Make a copy of the destination to an array of destinations (or just a single
793 * copy) - for use with the cupsEnumDests* functions. The caller is responsible
794 * for calling cupsFreeDests() on the returned object(s).
795 *
f3c17241 796 * @since CUPS 1.6/OS X 10.8@
dcb445bc
MS
797 */
798
799int
800cupsCopyDest(cups_dest_t *dest,
801 int num_dests,
802 cups_dest_t **dests)
803{
804 int i; /* Looping var */
805 cups_dest_t *new_dest; /* New destination pointer */
806 cups_option_t *new_option, /* Current destination option */
807 *option; /* Current parent option */
808
809
810 /*
811 * Range check input...
812 */
813
814 if (!dest || num_dests < 0 || !dests)
815 return (num_dests);
816
817 /*
818 * See if the destination already exists...
819 */
820
821 if ((new_dest = cupsGetDest(dest->name, dest->instance, num_dests,
822 *dests)) != NULL)
823 {
824 /*
825 * Protect against copying destination to itself...
826 */
827
828 if (new_dest == dest)
829 return (num_dests);
830
831 /*
832 * Otherwise, free the options...
833 */
834
835 cupsFreeOptions(new_dest->num_options, new_dest->options);
836
837 new_dest->num_options = 0;
838 new_dest->options = NULL;
839 }
840 else
841 new_dest = cups_add_dest(dest->name, dest->instance, &num_dests, dests);
842
843 if (new_dest)
844 {
845 if ((new_dest->options = calloc(sizeof(cups_option_t),
846 dest->num_options)) == NULL)
847 return (cupsRemoveDest(dest->name, dest->instance, num_dests, dests));
848
849 new_dest->num_options = dest->num_options;
850
851 for (i = dest->num_options, option = dest->options,
852 new_option = new_dest->options;
853 i > 0;
854 i --, option ++, new_option ++)
855 {
856 new_option->name = _cupsStrRetain(option->name);
857 new_option->value = _cupsStrRetain(option->value);
858 }
859 }
860
861 return (num_dests);
9c80ffa2
MS
862}
863
864
865/*
866 * 'cupsEnumDests()' - Enumerate available destinations with a callback function.
867 *
dcb445bc
MS
868 * Destinations are enumerated from one or more sources. The callback function
869 * receives the @code user_data@ pointer, destination name, instance, number of
870 * options, and options which can be used as input to the @link cupsAddDest@
871 * function. The function must return 1 to continue enumeration or 0 to stop.
9c80ffa2 872 *
dcb445bc
MS
873 * Enumeration happens on the current thread and does not return until all
874 * destinations have been enumerated or the callback function returns 0.
9c80ffa2 875 *
f3c17241 876 * @since CUPS 1.6/OS X 10.8@
9c80ffa2
MS
877 */
878
879int /* O - 1 on success, 0 on failure */
dcb445bc
MS
880cupsEnumDests(
881 unsigned flags, /* I - Enumeration flags */
882 int msec, /* I - Timeout in milliseconds,
883 * -1 for indefinite */
884 int *cancel, /* I - Pointer to "cancel" variable */
885 cups_ptype_t type, /* I - Printer type bits */
886 cups_ptype_t mask, /* I - Mask for printer type bits */
887 cups_dest_cb_t cb, /* I - Callback function */
888 void *user_data) /* I - User data */
9c80ffa2 889{
dcb445bc
MS
890 int i, /* Looping var */
891 num_dests; /* Number of destinations */
82cc1f9a 892 cups_dest_t *dests = NULL, /* Destinations */
dcb445bc 893 *dest; /* Current destination */
a29fd7dd
MS
894#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
895 int count, /* Number of queries started */
dcb445bc
MS
896 remaining; /* Remainder of timeout */
897 _cups_dnssd_data_t data; /* Data for callback */
898 _cups_dnssd_device_t *device; /* Current device */
a29fd7dd
MS
899# ifdef HAVE_DNSSD
900 int nfds, /* Number of files responded */
901 main_fd; /* File descriptor for lookups */
dcb445bc
MS
902 DNSServiceRef ipp_ref, /* IPP browser */
903 local_ipp_ref; /* Local IPP browser */
a29fd7dd 904# ifdef HAVE_SSL
dcb445bc
MS
905 DNSServiceRef ipps_ref, /* IPPS browser */
906 local_ipps_ref; /* Local IPPS browser */
a29fd7dd
MS
907# endif /* HAVE_SSL */
908# ifdef HAVE_POLL
dcb445bc 909 struct pollfd pfd; /* Polling data */
a29fd7dd 910# else
dcb445bc
MS
911 fd_set input; /* Input set for select() */
912 struct timeval timeout; /* Timeout for select() */
a29fd7dd
MS
913# endif /* HAVE_POLL */
914# else /* HAVE_AVAHI */
915 int error; /* Error value */
916 AvahiServiceBrowser *ipp_ref; /* IPP browser */
917# ifdef HAVE_SSL
918 AvahiServiceBrowser *ipps_ref; /* IPPS browser */
919# endif /* HAVE_SSL */
920# endif /* HAVE_DNSSD */
921#endif /* HAVE_DNSSD || HAVE_AVAHI */
dcb445bc
MS
922
923 /*
924 * Range check input...
925 */
926
f3c17241
MS
927 (void)flags;
928
dcb445bc
MS
929 if (!cb)
930 return (0);
931
932 /*
933 * Get the list of local printers and pass them to the callback function...
934 */
935
936 num_dests = _cupsGetDests(CUPS_HTTP_DEFAULT, CUPS_GET_PRINTERS, NULL, &dests,
937 type, mask);
938
939 for (i = num_dests, dest = dests;
940 i > 0 && (!cancel || !*cancel);
941 i --, dest ++)
942 if (!(*cb)(user_data, i > 1 ? CUPS_DEST_FLAGS_MORE : CUPS_DEST_FLAGS_NONE,
943 dest))
944 break;
945
946 cupsFreeDests(num_dests, dests);
947
948 if (i > 0 || msec == 0)
949 return (1);
950
a29fd7dd 951#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
dcb445bc
MS
952 /*
953 * Get Bonjour-shared printers...
954 */
955
956 data.type = type;
957 data.mask = mask;
958 data.devices = cupsArrayNew3((cups_array_func_t)cups_dnssd_compare_devices,
959 NULL, NULL, 0, NULL,
960 (cups_afree_func_t)cups_dnssd_free_device);
961
a29fd7dd 962# ifdef HAVE_DNSSD
dcb445bc
MS
963 if (DNSServiceCreateConnection(&data.main_ref) != kDNSServiceErr_NoError)
964 return (0);
965
966 main_fd = DNSServiceRefSockFD(data.main_ref);
967
968 ipp_ref = data.main_ref;
969 DNSServiceBrowse(&ipp_ref, kDNSServiceFlagsShareConnection, 0,
a29fd7dd 970 "_ipp._tcp", NULL,
12f89d24 971 (DNSServiceBrowseReply)cups_dnssd_browse_cb, &data);
dcb445bc
MS
972
973 local_ipp_ref = data.main_ref;
974 DNSServiceBrowse(&local_ipp_ref, kDNSServiceFlagsShareConnection,
975 kDNSServiceInterfaceIndexLocalOnly,
a29fd7dd 976 "_ipp._tcp", NULL,
12f89d24 977 (DNSServiceBrowseReply)cups_dnssd_local_cb, &data);
dcb445bc 978
a29fd7dd 979# ifdef HAVE_SSL
dcb445bc
MS
980 ipps_ref = data.main_ref;
981 DNSServiceBrowse(&ipps_ref, kDNSServiceFlagsShareConnection, 0,
a29fd7dd 982 "_ipps._tcp", NULL,
12f89d24 983 (DNSServiceBrowseReply)cups_dnssd_browse_cb, &data);
dcb445bc
MS
984
985 local_ipps_ref = data.main_ref;
986 DNSServiceBrowse(&local_ipps_ref, kDNSServiceFlagsShareConnection,
987 kDNSServiceInterfaceIndexLocalOnly,
a29fd7dd 988 "_ipps._tcp", NULL,
12f89d24 989 (DNSServiceBrowseReply)cups_dnssd_local_cb, &data);
a29fd7dd
MS
990# endif /* HAVE_SSL */
991
992# else /* HAVE_AVAHI */
993 if ((data.simple_poll = avahi_simple_poll_new()) == NULL)
994 {
995 DEBUG_puts("cupsEnumDests: Unable to create Avahi simple poll object.");
996 return (1);
997 }
998
999 avahi_simple_poll_set_func(data.simple_poll, cups_dnssd_poll_cb, &data);
1000
1001 data.client = avahi_client_new(avahi_simple_poll_get(data.simple_poll),
1002 0, cups_dnssd_client_cb, &data,
1003 &error);
1004 if (!data.client)
1005 {
1006 DEBUG_puts("cupsEnumDests: Unable to create Avahi client.");
1007 avahi_simple_poll_free(data.simple_poll);
1008 return (1);
1009 }
1010
1011 ipp_ref = avahi_service_browser_new(data.client, AVAHI_IF_UNSPEC,
1012 AVAHI_PROTO_UNSPEC, "_ipp._tcp", NULL,
1013 0, cups_dnssd_browse_cb, &data);
1014# ifdef HAVE_SSL
1015 ipps_ref = avahi_service_browser_new(data.client, AVAHI_IF_UNSPEC,
1016 AVAHI_PROTO_UNSPEC, "_ipps._tcp", NULL,
1017 0, cups_dnssd_browse_cb, &data);
1018# endif /* HAVE_SSL */
1019# endif /* HAVE_DNSSD */
dcb445bc
MS
1020
1021 if (msec < 0)
1022 remaining = INT_MAX;
1023 else
1024 remaining = msec;
1025
1026 while (remaining > 0 && (!cancel || !*cancel))
1027 {
1028 /*
1029 * Check for input...
1030 */
1031
a29fd7dd
MS
1032# ifdef HAVE_DNSSD
1033# ifdef HAVE_POLL
dcb445bc
MS
1034 pfd.fd = main_fd;
1035 pfd.events = POLLIN;
1036
1037 nfds = poll(&pfd, 1, remaining > 250 ? 250 : remaining);
1038
a29fd7dd 1039# else
dcb445bc
MS
1040 FD_ZERO(&input);
1041 FD_SET(main_fd, &input);
1042
1043 timeout.tv_sec = 0;
1044 timeout.tv_usec = remaining > 250 ? 250000 : remaining * 1000;
1045
1046 nfds = select(main_fd + 1, &input, NULL, NULL, &timeout);
a29fd7dd 1047# endif /* HAVE_POLL */
dcb445bc
MS
1048
1049 if (nfds > 0)
1050 DNSServiceProcessResult(data.main_ref);
1051 else if (nfds == 0)
1052 remaining -= 250;
1053
a29fd7dd
MS
1054# else /* HAVE_AVAHI */
1055 data.got_data = 0;
1056
1057 if ((error = avahi_simple_poll_iterate(data.simple_poll, 250)) > 0)
1058 {
1059 /*
1060 * We've been told to exit the loop. Perhaps the connection to
1061 * Avahi failed.
1062 */
1063
1064 break;
1065 }
1066
1067 if (!data.got_data)
1068 remaining -= 250;
1069# endif /* HAVE_DNSSD */
1070
dcb445bc
MS
1071 for (device = (_cups_dnssd_device_t *)cupsArrayFirst(data.devices),
1072 count = 0;
1073 device;
1074 device = (_cups_dnssd_device_t *)cupsArrayNext(data.devices))
1075 {
1076 if (device->ref)
1077 count ++;
1078
1079 if (!device->ref && device->state == _CUPS_DNSSD_NEW)
1080 {
dcb445bc
MS
1081 DEBUG_printf(("1cupsEnumDests: Querying '%s'.", device->fullName));
1082
a29fd7dd
MS
1083# ifdef HAVE_DNSSD
1084 device->ref = data.main_ref;
1085
dcb445bc
MS
1086 if (DNSServiceQueryRecord(&(device->ref),
1087 kDNSServiceFlagsShareConnection,
1088 0, device->fullName,
1089 kDNSServiceType_TXT,
12f89d24
MS
1090 kDNSServiceClass_IN,
1091 (DNSServiceQueryRecordReply)cups_dnssd_query_cb,
dcb445bc
MS
1092 &data) == kDNSServiceErr_NoError)
1093 {
1094 count ++;
1095 }
1096 else
1097 {
1098 device->ref = 0;
1099 device->state = _CUPS_DNSSD_ERROR;
1100
1101 DEBUG_puts("1cupsEnumDests: Query failed.");
1102 }
a29fd7dd
MS
1103
1104# else /* HAVE_AVAHI */
1105 if ((device->ref = avahi_record_browser_new(data.client,
1106 AVAHI_IF_UNSPEC,
1107 AVAHI_PROTO_UNSPEC,
1108 device->fullName,
1109 AVAHI_DNS_CLASS_IN,
1110 AVAHI_DNS_TYPE_TXT,
1111 0,
1112 cups_dnssd_query_cb,
1113 &data)) != NULL)
1114 {
1115 count ++;
1116 }
1117 else
1118 {
1119 device->state = _CUPS_DNSSD_ERROR;
1120
1121 DEBUG_printf(("1cupsEnumDests: Query failed: %s",
1122 avahi_strerror(avahi_client_errno(data.client))));
1123 }
1124# endif /* HAVE_DNSSD */
dcb445bc
MS
1125 }
1126 else if (device->ref && device->state == _CUPS_DNSSD_PENDING)
1127 {
a29fd7dd
MS
1128 if ((device->type & mask) == type)
1129 {
1130 if (!(*cb)(user_data, CUPS_DEST_FLAGS_NONE, &device->dest))
1131 {
1132 remaining = -1;
1133 break;
1134 }
1135 }
dcb445bc
MS
1136
1137 device->state = _CUPS_DNSSD_ACTIVE;
1138 }
1139 }
1140 }
1141
1142 cupsArrayDelete(data.devices);
1143
a29fd7dd 1144# ifdef HAVE_DNSSD
dcb445bc
MS
1145 DNSServiceRefDeallocate(ipp_ref);
1146 DNSServiceRefDeallocate(local_ipp_ref);
1147
a29fd7dd 1148# ifdef HAVE_SSL
dcb445bc
MS
1149 DNSServiceRefDeallocate(ipp_ref);
1150 DNSServiceRefDeallocate(local_ipp_ref);
a29fd7dd 1151# endif /* HAVE_SSL */
dcb445bc
MS
1152
1153 DNSServiceRefDeallocate(data.main_ref);
a29fd7dd
MS
1154
1155# else /* HAVE_AVAHI */
1156 avahi_service_browser_free(ipp_ref);
1157# ifdef HAVE_SSL
1158 avahi_service_browser_free(ipps_ref);
1159# endif /* HAVE_SSL */
1160
1161 avahi_client_free(data.client);
1162 avahi_simple_poll_free(data.simple_poll);
1163# endif /* HAVE_DNSSD */
1164#endif /* HAVE_DNSSD || HAVE_DNSSD */
dcb445bc
MS
1165
1166 return (1);
9c80ffa2
MS
1167}
1168
1169
1170# ifdef __BLOCKS__
1171/*
1172 * 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
1173 *
1174 * Destinations are enumerated from one or more sources. The block receives the
dcb445bc
MS
1175 * destination name, instance, number of options, and options which can be used
1176 * as input to the @link cupsAddDest@ function. The block must return 1 to
1177 * continue enumeration or 0 to stop.
9c80ffa2 1178 *
dcb445bc
MS
1179 * Enumeration happens on the current thread and does not return until all
1180 * destinations have been enumerated or the block returns 0.
9c80ffa2 1181 *
f3c17241 1182 * @since CUPS 1.6/OS X 10.8@
9c80ffa2
MS
1183 */
1184
1185int /* O - 1 on success, 0 on failure */
1186cupsEnumDestsBlock(
dcb445bc
MS
1187 unsigned flags, /* I - Enumeration flags */
1188 int timeout, /* I - Timeout in milliseconds, 0 for indefinite */
1189 int *cancel, /* I - Pointer to "cancel" variable */
1190 cups_ptype_t type, /* I - Printer type bits */
1191 cups_ptype_t mask, /* I - Mask for printer type bits */
9c80ffa2
MS
1192 cups_dest_block_t block) /* I - Block */
1193{
dcb445bc
MS
1194 return (cupsEnumDests(flags, timeout, cancel, type, mask,
1195 (cups_dest_cb_t)cups_block_cb, (void *)block));
9c80ffa2
MS
1196}
1197# endif /* __BLOCKS__ */
1198
1199
ef416fc2 1200/*
1201 * 'cupsFreeDests()' - Free the memory used by the list of destinations.
1202 */
1203
1204void
1205cupsFreeDests(int num_dests, /* I - Number of destinations */
1206 cups_dest_t *dests) /* I - Destinations */
1207{
1208 int i; /* Looping var */
1209 cups_dest_t *dest; /* Current destination */
1210
1211
1212 if (num_dests == 0 || dests == NULL)
1213 return;
1214
1215 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
1216 {
2e4ff8af
MS
1217 _cupsStrFree(dest->name);
1218 _cupsStrFree(dest->instance);
ef416fc2 1219
1220 cupsFreeOptions(dest->num_options, dest->options);
1221 }
1222
1223 free(dests);
1224}
1225
1226
1227/*
1228 * 'cupsGetDest()' - Get the named destination from the list.
1229 *
5a738aea 1230 * Use the @link cupsGetDests@ or @link cupsGetDests2@ functions to get a
ef416fc2 1231 * list of supported destinations for the current user.
1232 */
1233
5a738aea
MS
1234cups_dest_t * /* O - Destination pointer or @code NULL@ */
1235cupsGetDest(const char *name, /* I - Destination name or @code NULL@ for the default destination */
1236 const char *instance, /* I - Instance name or @code NULL@ */
ef416fc2 1237 int num_dests, /* I - Number of destinations */
1238 cups_dest_t *dests) /* I - Destinations */
1239{
426c6a59
MS
1240 int diff, /* Result of comparison */
1241 match; /* Matching index */
ef416fc2 1242
1243
2abf387c 1244 if (num_dests <= 0 || !dests)
ef416fc2 1245 return (NULL);
1246
2abf387c 1247 if (!name)
ef416fc2 1248 {
1249 /*
1250 * NULL name for default printer.
1251 */
1252
1253 while (num_dests > 0)
1254 {
1255 if (dests->is_default)
1256 return (dests);
1257
1258 num_dests --;
1259 dests ++;
1260 }
1261 }
1262 else
1263 {
1264 /*
1265 * Lookup name and optionally the instance...
1266 */
1267
426c6a59 1268 match = cups_find_dest(name, instance, num_dests, dests, -1, &diff);
ef416fc2 1269
426c6a59
MS
1270 if (!diff)
1271 return (dests + match);
ef416fc2 1272 }
1273
1274 return (NULL);
1275}
1276
1277
dcb445bc
MS
1278/*
1279 * '_cupsGetDestResource()' - Get the resource path and URI for a destination.
1280 */
1281
1282const char * /* O - Printer URI */
1283_cupsGetDestResource(
1284 cups_dest_t *dest, /* I - Destination */
1285 char *resource, /* I - Resource buffer */
1286 size_t resourcesize) /* I - Size of resource buffer */
1287{
1288 const char *uri; /* Printer URI */
1289 char scheme[32], /* URI scheme */
1290 userpass[256], /* Username and password (unused) */
1291 hostname[256]; /* Hostname */
1292 int port; /* Port number */
1293
1294
1295 /*
1296 * Range check input...
1297 */
1298
1299 if (!dest || !resource || resourcesize < 1)
1300 {
1301 if (resource)
1302 *resource = '\0';
1303
1304 _cupsSetError(IPP_INTERNAL_ERROR, strerror(EINVAL), 0);
1305 return (NULL);
1306 }
1307
1308 /*
1309 * Grab the printer URI...
1310 */
1311
1312 if ((uri = cupsGetOption("printer-uri-supported", dest->num_options,
1313 dest->options)) == NULL)
1314 {
1315 if (resource)
1316 *resource = '\0';
1317
1318 _cupsSetError(IPP_INTERNAL_ERROR, strerror(ENOENT), 0);
1319
1320 return (NULL);
1321 }
1322
1323#ifdef HAVE_DNSSD
1324 if (strstr(uri, "._tcp"))
1325 {
1326 if ((uri = cups_dnssd_resolve(dest, uri, 5000, NULL, NULL, NULL)) == NULL)
1327 return (NULL);
1328 }
1329#endif /* HAVE_DNSSD */
1330
1331 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme),
1332 userpass, sizeof(userpass), hostname, sizeof(hostname),
1333 &port, resource, resourcesize) < HTTP_URI_OK)
1334 {
1335 _cupsSetError(IPP_INTERNAL_ERROR, _("Bad printer URI."), 1);
1336
1337 return (NULL);
1338 }
1339
1340 return (uri);
1341}
1342
1343
c8fef167
MS
1344/*
1345 * '_cupsGetDests()' - Get destinations from a server.
1346 *
1347 * "op" is CUPS_GET_PRINTERS to get a full list, CUPS_GET_DEFAULT to get the
1348 * system-wide default printer, or IPP_GET_PRINTER_ATTRIBUTES for a known
1349 * printer.
1350 *
1351 * "name" is the name of an existing printer and is only used when "op" is
1352 * IPP_GET_PRINTER_ATTRIBUTES.
1353 *
1354 * "dest" is initialized to point to the array of destinations.
1355 *
1356 * 0 is returned if there are no printers, no default printer, or the named
1357 * printer does not exist, respectively.
1358 *
1359 * Free the memory used by the destination array using the @link cupsFreeDests@
1360 * function.
1361 *
f3c17241 1362 * Note: On OS X this function also gets the default paper from the system
c8fef167
MS
1363 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1364 * options array for each destination that supports it.
1365 */
1366
dcb445bc
MS
1367int /* O - Number of destinations */
1368_cupsGetDests(http_t *http, /* I - Connection to server or
1369 * @code CUPS_HTTP_DEFAULT@ */
1370 ipp_op_t op, /* I - IPP operation */
1371 const char *name, /* I - Name of destination */
1372 cups_dest_t **dests, /* IO - Destinations */
1373 cups_ptype_t type, /* I - Printer type bits */
1374 cups_ptype_t mask) /* I - Printer type mask */
c8fef167
MS
1375{
1376 int num_dests = 0; /* Number of destinations */
1377 cups_dest_t *dest; /* Current destination */
1378 ipp_t *request, /* IPP Request */
1379 *response; /* IPP Response */
1380 ipp_attribute_t *attr; /* Current attribute */
1381 const char *printer_name; /* printer-name attribute */
1382 char uri[1024]; /* printer-uri value */
1383 int num_options; /* Number of options */
1384 cups_option_t *options; /* Options */
1385#ifdef __APPLE__
1386 char media_default[41]; /* Default paper size */
1387#endif /* __APPLE__ */
1388 char optname[1024], /* Option name */
1389 value[2048], /* Option value */
1390 *ptr; /* Pointer into name/value */
c1420c87 1391 _cups_globals_t *cg = _cupsGlobals(); /* Thread global data */
c8fef167
MS
1392 static const char * const pattrs[] = /* Attributes we're interested in */
1393 {
1394 "auth-info-required",
1395 "device-uri",
1396 "job-sheets-default",
1397 "marker-change-time",
1398 "marker-colors",
1399 "marker-high-levels",
1400 "marker-levels",
1401 "marker-low-levels",
1402 "marker-message",
1403 "marker-names",
1404 "marker-types",
1405#ifdef __APPLE__
1406 "media-supported",
1407#endif /* __APPLE__ */
1408 "printer-commands",
1409 "printer-defaults",
1410 "printer-info",
1411 "printer-is-accepting-jobs",
1412 "printer-is-shared",
1413 "printer-location",
1414 "printer-make-and-model",
5a9febac 1415 "printer-mandatory-job-attributes",
c8fef167
MS
1416 "printer-name",
1417 "printer-state",
1418 "printer-state-change-time",
1419 "printer-state-reasons",
1420 "printer-type",
1421 "printer-uri-supported"
1422 };
1423
1424
1425#ifdef __APPLE__
1426 /*
1427 * Get the default paper size...
1428 */
1429
1430 appleGetPaperSize(media_default, sizeof(media_default));
1431#endif /* __APPLE__ */
1432
c1420c87
MS
1433 for (;;)
1434 {
1435 /*
1436 * Build a CUPS_GET_PRINTERS or IPP_GET_PRINTER_ATTRIBUTES request, which
1437 * require the following attributes:
1438 *
1439 * attributes-charset
1440 * attributes-natural-language
1441 * requesting-user-name
1442 * printer-uri [for IPP_GET_PRINTER_ATTRIBUTES]
1443 */
c8fef167 1444
c1420c87 1445 request = ippNewRequest(op);
c8fef167 1446
c1420c87 1447 ippSetVersion(request, cg->server_version / 10, cg->server_version % 10);
c8fef167 1448
c1420c87
MS
1449 ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
1450 "requested-attributes", sizeof(pattrs) / sizeof(pattrs[0]),
1451 NULL, pattrs);
c8fef167 1452
c1420c87
MS
1453 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
1454 "requesting-user-name", NULL, cupsUser());
c8fef167 1455
c1420c87
MS
1456 if (name && op != CUPS_GET_DEFAULT)
1457 {
1458 httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
1459 "localhost", ippPort(), "/printers/%s", name);
1460 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL,
1461 uri);
1462 }
1463 else if (mask)
1464 {
1465 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type",
1466 type);
1467 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type-mask",
1468 mask);
1469 }
1470
1471 /*
1472 * Do the request and get back a response...
1473 */
1474
1475 response = cupsDoRequest(http, request, "/");
1476 if (cg->server_version != 20 || !response ||
1477 cupsLastError() != IPP_BAD_REQUEST)
1478 break;
1479
1480 /*
1481 * Retry as an IPP/1.1 request...
1482 */
1483
1484 cg->server_version = 11;
1485 ippDelete(response);
1486 }
c8fef167 1487
c1420c87 1488 if (response)
c8fef167
MS
1489 {
1490 for (attr = response->attrs; attr != NULL; attr = attr->next)
1491 {
1492 /*
1493 * Skip leading attributes until we hit a printer...
1494 */
1495
1496 while (attr != NULL && attr->group_tag != IPP_TAG_PRINTER)
1497 attr = attr->next;
1498
1499 if (attr == NULL)
1500 break;
1501
1502 /*
1503 * Pull the needed attributes from this printer...
1504 */
1505
1506 printer_name = NULL;
1507 num_options = 0;
1508 options = NULL;
1509
1510 for (; attr && attr->group_tag == IPP_TAG_PRINTER; attr = attr->next)
1511 {
1512 if (attr->value_tag != IPP_TAG_INTEGER &&
1513 attr->value_tag != IPP_TAG_ENUM &&
1514 attr->value_tag != IPP_TAG_BOOLEAN &&
1515 attr->value_tag != IPP_TAG_TEXT &&
1516 attr->value_tag != IPP_TAG_TEXTLANG &&
1517 attr->value_tag != IPP_TAG_NAME &&
1518 attr->value_tag != IPP_TAG_NAMELANG &&
1519 attr->value_tag != IPP_TAG_KEYWORD &&
1520 attr->value_tag != IPP_TAG_RANGE &&
1521 attr->value_tag != IPP_TAG_URI)
1522 continue;
1523
1524 if (!strcmp(attr->name, "auth-info-required") ||
1525 !strcmp(attr->name, "device-uri") ||
1526 !strcmp(attr->name, "marker-change-time") ||
1527 !strcmp(attr->name, "marker-colors") ||
1528 !strcmp(attr->name, "marker-high-levels") ||
1529 !strcmp(attr->name, "marker-levels") ||
1530 !strcmp(attr->name, "marker-low-levels") ||
1531 !strcmp(attr->name, "marker-message") ||
1532 !strcmp(attr->name, "marker-names") ||
1533 !strcmp(attr->name, "marker-types") ||
1534 !strcmp(attr->name, "printer-commands") ||
1535 !strcmp(attr->name, "printer-info") ||
1536 !strcmp(attr->name, "printer-is-shared") ||
1537 !strcmp(attr->name, "printer-make-and-model") ||
5a9febac 1538 !strcmp(attr->name, "printer-mandatory-job-attributes") ||
c8fef167
MS
1539 !strcmp(attr->name, "printer-state") ||
1540 !strcmp(attr->name, "printer-state-change-time") ||
1541 !strcmp(attr->name, "printer-type") ||
1542 !strcmp(attr->name, "printer-is-accepting-jobs") ||
1543 !strcmp(attr->name, "printer-location") ||
1544 !strcmp(attr->name, "printer-state-reasons") ||
1545 !strcmp(attr->name, "printer-uri-supported"))
1546 {
1547 /*
1548 * Add a printer description attribute...
1549 */
1550
1551 num_options = cupsAddOption(attr->name,
1552 cups_make_string(attr, value,
1553 sizeof(value)),
1554 num_options, &options);
1555 }
1556#ifdef __APPLE__
1557 else if (!strcmp(attr->name, "media-supported"))
1558 {
1559 /*
1560 * See if we can set a default media size...
1561 */
1562
1563 int i; /* Looping var */
1564
1565 for (i = 0; i < attr->num_values; i ++)
88f9aafc 1566 if (!_cups_strcasecmp(media_default, attr->values[i].string.text))
c8fef167
MS
1567 {
1568 num_options = cupsAddOption("media", media_default, num_options,
1569 &options);
1570 break;
1571 }
1572 }
1573#endif /* __APPLE__ */
1574 else if (!strcmp(attr->name, "printer-name") &&
1575 attr->value_tag == IPP_TAG_NAME)
1576 printer_name = attr->values[0].string.text;
1577 else if (strncmp(attr->name, "notify-", 7) &&
1578 (attr->value_tag == IPP_TAG_BOOLEAN ||
1579 attr->value_tag == IPP_TAG_ENUM ||
1580 attr->value_tag == IPP_TAG_INTEGER ||
1581 attr->value_tag == IPP_TAG_KEYWORD ||
1582 attr->value_tag == IPP_TAG_NAME ||
1583 attr->value_tag == IPP_TAG_RANGE) &&
1584 (ptr = strstr(attr->name, "-default")) != NULL)
1585 {
1586 /*
1587 * Add a default option...
1588 */
1589
1590 strlcpy(optname, attr->name, sizeof(optname));
1591 optname[ptr - attr->name] = '\0';
1592
88f9aafc 1593 if (_cups_strcasecmp(optname, "media") ||
c8fef167
MS
1594 !cupsGetOption("media", num_options, options))
1595 num_options = cupsAddOption(optname,
1596 cups_make_string(attr, value,
1597 sizeof(value)),
1598 num_options, &options);
1599 }
1600 }
1601
1602 /*
1603 * See if we have everything needed...
1604 */
1605
1606 if (!printer_name)
1607 {
1608 cupsFreeOptions(num_options, options);
1609
1610 if (attr == NULL)
1611 break;
1612 else
1613 continue;
1614 }
1615
1616 if ((dest = cups_add_dest(printer_name, NULL, &num_dests, dests)) != NULL)
1617 {
1618 dest->num_options = num_options;
1619 dest->options = options;
1620 }
1621 else
1622 cupsFreeOptions(num_options, options);
1623
1624 if (attr == NULL)
1625 break;
1626 }
1627
1628 ippDelete(response);
1629 }
1630
1631 /*
1632 * Return the count...
1633 */
1634
1635 return (num_dests);
1636}
1637
1638
ef416fc2 1639/*
1640 * 'cupsGetDests()' - Get the list of destinations from the default server.
ecdc0628 1641 *
1642 * Starting with CUPS 1.2, the returned list of destinations include the
1643 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1644 * printer-make-and-model, printer-state, printer-state-change-time,
426c6a59
MS
1645 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1646 * adds the marker-change-time, marker-colors, marker-high-levels,
1647 * marker-levels, marker-low-levels, marker-message, marker-names,
1648 * marker-types, and printer-commands attributes as well.
2abf387c 1649 *
5a738aea
MS
1650 * Use the @link cupsFreeDests@ function to free the destination list and
1651 * the @link cupsGetDest@ function to find a particular destination.
ef416fc2 1652 */
1653
1654int /* O - Number of destinations */
1655cupsGetDests(cups_dest_t **dests) /* O - Destinations */
1656{
3d052e43 1657 return (cupsGetDests2(CUPS_HTTP_DEFAULT, dests));
ef416fc2 1658}
1659
1660
1661/*
1662 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1663 *
ecdc0628 1664 * Starting with CUPS 1.2, the returned list of destinations include the
1665 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1666 * printer-make-and-model, printer-state, printer-state-change-time,
426c6a59
MS
1667 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1668 * adds the marker-change-time, marker-colors, marker-high-levels,
1669 * marker-levels, marker-low-levels, marker-message, marker-names,
1670 * marker-types, and printer-commands attributes as well.
ecdc0628 1671 *
5a738aea
MS
1672 * Use the @link cupsFreeDests@ function to free the destination list and
1673 * the @link cupsGetDest@ function to find a particular destination.
2abf387c 1674 *
f3c17241 1675 * @since CUPS 1.1.21/OS X 10.4@
ef416fc2 1676 */
1677
1678int /* O - Number of destinations */
568fa3fa 1679cupsGetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
ef416fc2 1680 cups_dest_t **dests) /* O - Destinations */
1681{
1682 int i; /* Looping var */
1683 int num_dests; /* Number of destinations */
1684 cups_dest_t *dest; /* Destination pointer */
1685 const char *home; /* HOME environment variable */
b423cd4c 1686 char filename[1024]; /* Local ~/.cups/lpoptions file */
ef416fc2 1687 const char *defprinter; /* Default printer */
1688 char name[1024], /* Copy of printer name */
38e73f87
MS
1689 *instance, /* Pointer to instance name */
1690 *user_default; /* User default printer */
ef416fc2 1691 int num_reals; /* Number of real queues */
1692 cups_dest_t *reals; /* Real queues */
3d052e43 1693 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
ef416fc2 1694
1695
1696 /*
1697 * Range check the input...
1698 */
1699
3d052e43 1700 if (!dests)
1ff0402e
MS
1701 {
1702 _cupsSetError(IPP_INTERNAL_ERROR, _("Bad NULL dests pointer"), 1);
ef416fc2 1703 return (0);
c8fef167 1704 }
ef416fc2 1705
1706 /*
1707 * Grab the printers and classes...
1708 */
1709
c8fef167 1710 *dests = (cups_dest_t *)0;
dcb445bc 1711 num_dests = _cupsGetDests(http, CUPS_GET_PRINTERS, NULL, dests, 0, 0);
b19ccc9e
MS
1712
1713 if (cupsLastError() >= IPP_REDIRECTION_OTHER_SITE)
1714 {
1715 cupsFreeDests(num_dests, *dests);
1716 *dests = (cups_dest_t *)0;
1717 return (0);
1718 }
ef416fc2 1719
1720 /*
1721 * Make a copy of the "real" queues for a later sanity check...
1722 */
1723
1724 if (num_dests > 0)
1725 {
1726 num_reals = num_dests;
1727 reals = calloc(num_reals, sizeof(cups_dest_t));
1728
1729 if (reals)
1730 memcpy(reals, *dests, num_reals * sizeof(cups_dest_t));
1731 else
1732 num_reals = 0;
1733 }
1734 else
1735 {
1736 num_reals = 0;
1737 reals = NULL;
1738 }
1739
1740 /*
1741 * Grab the default destination...
1742 */
1743
38e73f87
MS
1744 if ((user_default = _cupsUserDefault(name, sizeof(name))) != NULL)
1745 defprinter = name;
1746 else if ((defprinter = cupsGetDefault2(http)) != NULL)
1747 {
1748 strlcpy(name, defprinter, sizeof(name));
1749 defprinter = name;
1750 }
080811b1
MS
1751
1752 if (defprinter)
ef416fc2 1753 {
1754 /*
38e73f87 1755 * Separate printer and instance name...
ef416fc2 1756 */
1757
ef416fc2 1758 if ((instance = strchr(name, '/')) != NULL)
1759 *instance++ = '\0';
1760
1761 /*
1762 * Lookup the printer and instance and make it the default...
1763 */
1764
1765 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) != NULL)
1766 dest->is_default = 1;
1767 }
1768 else
ef416fc2 1769 instance = NULL;
ef416fc2 1770
1771 /*
b423cd4c 1772 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
ef416fc2 1773 */
1774
1775 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
38e73f87
MS
1776 num_dests = cups_get_dests(filename, NULL, NULL, user_default != NULL,
1777 num_dests, dests);
ef416fc2 1778
1779 if ((home = getenv("HOME")) != NULL)
1780 {
b423cd4c 1781 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
b423cd4c 1782
38e73f87
MS
1783 num_dests = cups_get_dests(filename, NULL, NULL, user_default != NULL,
1784 num_dests, dests);
ef416fc2 1785 }
1786
1787 /*
1788 * Validate the current default destination - this prevents old
b423cd4c 1789 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
ef416fc2 1790 * pointing to a non-existent printer or class...
1791 */
1792
1793 if (num_reals)
1794 {
1795 /*
1796 * See if we have a default printer...
1797 */
1798
1799 if ((dest = cupsGetDest(NULL, NULL, num_dests, *dests)) != NULL)
1800 {
1801 /*
1802 * Have a default; see if it is real...
1803 */
1804
1805 dest = cupsGetDest(dest->name, NULL, num_reals, reals);
1806 }
1807
1808 /*
1809 * If dest is NULL, then no default (that exists) is set, so we
1810 * need to set a default if one exists...
1811 */
1812
5a9febac 1813 if (!dest && *dests && defprinter)
ef416fc2 1814 {
1815 for (i = 0; i < num_dests; i ++)
1816 (*dests)[i].is_default = 0;
1817
1818 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) != NULL)
1819 dest->is_default = 1;
1820 }
1821
1822 /*
1823 * Free memory...
1824 */
1825
1826 free(reals);
1827 }
1828
1829 /*
1830 * Return the number of destinations...
1831 */
1832
1ff0402e
MS
1833 if (num_dests > 0)
1834 _cupsSetError(IPP_OK, NULL, 0);
1835
ef416fc2 1836 return (num_dests);
1837}
1838
1839
a4924f6c
MS
1840/*
1841 * 'cupsGetNamedDest()' - Get options for the named destination.
1842 *
1843 * This function is optimized for retrieving a single destination and should
5a738aea
MS
1844 * be used instead of @link cupsGetDests@ and @link cupsGetDest@ when you either
1845 * know the name of the destination or want to print to the default destination.
1846 * If @code NULL@ is returned, the destination does not exist or there is no
1847 * default destination.
a4924f6c 1848 *
5a738aea
MS
1849 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
1850 * server will be used.
a4924f6c 1851 *
5a738aea
MS
1852 * If "name" is @code NULL@, the default printer for the current user will be
1853 * returned.
a4924f6c 1854 *
5a738aea
MS
1855 * The returned destination must be freed using @link cupsFreeDests@ with a
1856 * "num_dests" value of 1.
a4924f6c 1857 *
f3c17241 1858 * @since CUPS 1.4/OS X 10.6@
a4924f6c
MS
1859 */
1860
5a738aea 1861cups_dest_t * /* O - Destination or @code NULL@ */
568fa3fa
MS
1862cupsGetNamedDest(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1863 const char *name, /* I - Destination name or @code NULL@ for the default destination */
5a738aea 1864 const char *instance) /* I - Instance name or @code NULL@ */
a4924f6c
MS
1865{
1866 cups_dest_t *dest; /* Destination */
1867 char filename[1024], /* Path to lpoptions */
1868 defname[256]; /* Default printer name */
1869 const char *home = getenv("HOME"); /* Home directory */
38e73f87 1870 int set_as_default = 0; /* Set returned destination as default */
a4924f6c
MS
1871 ipp_op_t op = IPP_GET_PRINTER_ATTRIBUTES;
1872 /* IPP operation to get server ops */
1873 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
1874
1875
a4924f6c
MS
1876 /*
1877 * If "name" is NULL, find the default destination...
1878 */
1879
1880 if (!name)
1881 {
38e73f87
MS
1882 set_as_default = 1;
1883 name = _cupsUserDefault(defname, sizeof(defname));
a4924f6c 1884
7cf5915e
MS
1885 if (name)
1886 {
1887 char *ptr; /* Temporary pointer... */
1888
1889 if ((ptr = strchr(defname, '/')) != NULL)
1890 {
1891 *ptr++ = '\0';
1892 instance = ptr;
1893 }
1894 else
1895 instance = NULL;
1896 }
1897 else if (home)
a4924f6c
MS
1898 {
1899 /*
1900 * No default in the environment, try the user's lpoptions files...
1901 */
1902
1903 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
1904
5a6b583a 1905 name = cups_get_default(filename, defname, sizeof(defname), &instance);
a4924f6c
MS
1906 }
1907
1908 if (!name)
1909 {
1910 /*
1911 * Still not there? Try the system lpoptions file...
1912 */
1913
1914 snprintf(filename, sizeof(filename), "%s/lpoptions",
1915 cg->cups_serverroot);
1916 name = cups_get_default(filename, defname, sizeof(defname), &instance);
1917 }
1918
1919 if (!name)
1920 {
1921 /*
1922 * No locally-set default destination, ask the server...
1923 */
1924
1925 op = CUPS_GET_DEFAULT;
1926 }
1927 }
1928
1929 /*
1930 * Get the printer's attributes...
1931 */
1932
dcb445bc 1933 if (!_cupsGetDests(http, op, name, &dest, 0, 0))
745129be 1934 {
ba55dc12 1935 if (op == CUPS_GET_DEFAULT || (name && !set_as_default))
745129be
MS
1936 return (NULL);
1937
1938 /*
1939 * The default printer from environment variables or from a
1940 * configuration file does not exist. Find out the real default.
1941 */
1942
dcb445bc 1943 if (!_cupsGetDests(http, CUPS_GET_DEFAULT, NULL, &dest, 0, 0))
745129be
MS
1944 return (NULL);
1945 }
a4924f6c
MS
1946
1947 if (instance)
1948 dest->instance = _cupsStrAlloc(instance);
1949
38e73f87
MS
1950 if (set_as_default)
1951 dest->is_default = 1;
1952
a4924f6c
MS
1953 /*
1954 * Then add local options...
1955 */
1956
1957 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
38e73f87 1958 cups_get_dests(filename, name, instance, 1, 1, &dest);
a4924f6c
MS
1959
1960 if (home)
1961 {
1962 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
1963
38e73f87 1964 cups_get_dests(filename, name, instance, 1, 1, &dest);
a4924f6c
MS
1965 }
1966
1967 /*
1968 * Return the result...
1969 */
1970
1971 return (dest);
1972}
1973
1974
f7deaa1a 1975/*
1976 * 'cupsRemoveDest()' - Remove a destination from the destination list.
1977 *
1978 * Removing a destination/instance does not delete the class or printer
1979 * queue, merely the lpoptions for that destination/instance. Use the
5a738aea
MS
1980 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
1981 * options for the user.
f7deaa1a 1982 *
f3c17241 1983 * @since CUPS 1.3/OS X 10.5@
f7deaa1a 1984 */
1985
1986int /* O - New number of destinations */
1987cupsRemoveDest(const char *name, /* I - Destination name */
5a738aea 1988 const char *instance, /* I - Instance name or @code NULL@ */
f7deaa1a 1989 int num_dests, /* I - Number of destinations */
1990 cups_dest_t **dests) /* IO - Destinations */
1991{
1992 int i; /* Index into destinations */
1993 cups_dest_t *dest; /* Pointer to destination */
1994
1995
1996 /*
1997 * Find the destination...
1998 */
1999
2000 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
2001 return (num_dests);
2002
2003 /*
2004 * Free memory...
2005 */
2006
2e4ff8af
MS
2007 _cupsStrFree(dest->name);
2008 _cupsStrFree(dest->instance);
f7deaa1a 2009 cupsFreeOptions(dest->num_options, dest->options);
2010
2011 /*
2012 * Remove the destination from the array...
2013 */
2014
2015 num_dests --;
2016
2017 i = dest - *dests;
2018
2019 if (i < num_dests)
2020 memmove(dest, dest + 1, (num_dests - i) * sizeof(cups_dest_t));
2021
2022 return (num_dests);
2023}
2024
2025
2026/*
3d052e43 2027 * 'cupsSetDefaultDest()' - Set the default destination.
f7deaa1a 2028 *
f3c17241 2029 * @since CUPS 1.3/OS X 10.5@
f7deaa1a 2030 */
2031
2032void
2033cupsSetDefaultDest(
2034 const char *name, /* I - Destination name */
5a738aea 2035 const char *instance, /* I - Instance name or @code NULL@ */
f7deaa1a 2036 int num_dests, /* I - Number of destinations */
2037 cups_dest_t *dests) /* I - Destinations */
2038{
2039 int i; /* Looping var */
2040 cups_dest_t *dest; /* Current destination */
2041
2042
2043 /*
2044 * Range check input...
2045 */
2046
2047 if (!name || num_dests <= 0 || !dests)
2048 return;
2049
2050 /*
2051 * Loop through the array and set the "is_default" flag for the matching
2052 * destination...
2053 */
2054
2055 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
88f9aafc 2056 dest->is_default = !_cups_strcasecmp(name, dest->name) &&
f7deaa1a 2057 ((!instance && !dest->instance) ||
2058 (instance && dest->instance &&
88f9aafc 2059 !_cups_strcasecmp(instance, dest->instance)));
f7deaa1a 2060}
2061
2062
ef416fc2 2063/*
2064 * 'cupsSetDests()' - Save the list of destinations for the default server.
2065 *
2066 * This function saves the destinations to /etc/cups/lpoptions when run
b423cd4c 2067 * as root and ~/.cups/lpoptions when run as a normal user.
ef416fc2 2068 */
2069
2070void
2071cupsSetDests(int num_dests, /* I - Number of destinations */
2072 cups_dest_t *dests) /* I - Destinations */
2073{
3d052e43 2074 cupsSetDests2(CUPS_HTTP_DEFAULT, num_dests, dests);
ef416fc2 2075}
2076
2077
2078/*
2079 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
2080 *
2081 * This function saves the destinations to /etc/cups/lpoptions when run
b423cd4c 2082 * as root and ~/.cups/lpoptions when run as a normal user.
ef416fc2 2083 *
f3c17241 2084 * @since CUPS 1.1.21/OS X 10.4@
ef416fc2 2085 */
2086
2087int /* O - 0 on success, -1 on error */
568fa3fa 2088cupsSetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
ef416fc2 2089 int num_dests, /* I - Number of destinations */
2090 cups_dest_t *dests) /* I - Destinations */
2091{
2092 int i, j; /* Looping vars */
2093 int wrote; /* Wrote definition? */
2094 cups_dest_t *dest; /* Current destination */
2095 cups_option_t *option; /* Current option */
8ca02f3c 2096 _ipp_option_t *match; /* Matching attribute for option */
ef416fc2 2097 FILE *fp; /* File pointer */
b86bc4cf 2098#ifndef WIN32
ef416fc2 2099 const char *home; /* HOME environment variable */
b86bc4cf 2100#endif /* WIN32 */
ef416fc2 2101 char filename[1024]; /* lpoptions file */
2102 int num_temps; /* Number of temporary destinations */
82cc1f9a 2103 cups_dest_t *temps = NULL, /* Temporary destinations */
ef416fc2 2104 *temp; /* Current temporary dest */
2105 const char *val; /* Value of temporary option */
3d052e43 2106 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
ef416fc2 2107
2108
2109 /*
2110 * Range check the input...
2111 */
2112
3d052e43 2113 if (!num_dests || !dests)
ef416fc2 2114 return (-1);
2115
2116 /*
2117 * Get the server destinations...
2118 */
2119
dcb445bc 2120 num_temps = _cupsGetDests(http, CUPS_GET_PRINTERS, NULL, &temps, 0, 0);
426c6a59
MS
2121
2122 if (cupsLastError() >= IPP_REDIRECTION_OTHER_SITE)
2123 {
2124 cupsFreeDests(num_temps, temps);
2125 return (-1);
2126 }
ef416fc2 2127
2128 /*
2129 * Figure out which file to write to...
2130 */
2131
2132 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
2133
2134#ifndef WIN32
2135 if (getuid())
2136 {
2137 /*
2138 * Merge in server defaults...
2139 */
2140
38e73f87 2141 num_temps = cups_get_dests(filename, NULL, NULL, 0, num_temps, &temps);
ef416fc2 2142
2143 /*
2144 * Point to user defaults...
2145 */
2146
2147 if ((home = getenv("HOME")) != NULL)
b423cd4c 2148 {
b423cd4c 2149 /*
2150 * Create ~/.cups subdirectory...
2151 */
2152
2153 snprintf(filename, sizeof(filename), "%s/.cups", home);
2154 if (access(filename, 0))
2155 mkdir(filename, 0700);
2156
2157 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2158 }
ef416fc2 2159 }
2160#endif /* !WIN32 */
2161
2162 /*
2163 * Try to open the file...
2164 */
2165
2166 if ((fp = fopen(filename, "w")) == NULL)
2167 {
2168 cupsFreeDests(num_temps, temps);
2169 return (-1);
2170 }
2171
d6ae789d 2172#ifndef WIN32
2173 /*
2174 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2175 * file...
2176 */
2177
2178 if (!getuid())
2179 fchmod(fileno(fp), 0644);
2180#endif /* !WIN32 */
2181
ef416fc2 2182 /*
2183 * Write each printer; each line looks like:
2184 *
2185 * Dest name[/instance] options
2186 * Default name[/instance] options
2187 */
2188
2189 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
2190 if (dest->instance != NULL || dest->num_options != 0 || dest->is_default)
2191 {
2192 if (dest->is_default)
2193 {
2194 fprintf(fp, "Default %s", dest->name);
2195 if (dest->instance)
2196 fprintf(fp, "/%s", dest->instance);
2197
2198 wrote = 1;
2199 }
2200 else
2201 wrote = 0;
2202
2203 if ((temp = cupsGetDest(dest->name, dest->instance, num_temps, temps)) == NULL)
2204 temp = cupsGetDest(dest->name, NULL, num_temps, temps);
2205
2206 for (j = dest->num_options, option = dest->options; j > 0; j --, option ++)
2207 {
8ca02f3c 2208 /*
2209 * See if this option is a printer attribute; if so, skip it...
2210 */
2211
2212 if ((match = _ippFindOption(option->name)) != NULL &&
2213 match->group_tag == IPP_TAG_PRINTER)
2214 continue;
2215
ef416fc2 2216 /*
2217 * See if the server/global options match these; if so, don't
2218 * write 'em.
2219 */
2220
8ca02f3c 2221 if (temp &&
2222 (val = cupsGetOption(option->name, temp->num_options,
2223 temp->options)) != NULL &&
88f9aafc 2224 !_cups_strcasecmp(val, option->value))
8ca02f3c 2225 continue;
ef416fc2 2226
2227 /*
2228 * Options don't match, write to the file...
2229 */
2230
2231 if (!wrote)
2232 {
2233 fprintf(fp, "Dest %s", dest->name);
2234 if (dest->instance)
2235 fprintf(fp, "/%s", dest->instance);
2236 wrote = 1;
2237 }
88f9aafc 2238
ef416fc2 2239 if (option->value[0])
2240 {
8ca02f3c 2241 if (strchr(option->value, ' ') ||
2242 strchr(option->value, '\\') ||
2243 strchr(option->value, '\"') ||
2244 strchr(option->value, '\''))
2245 {
2246 /*
2247 * Quote the value...
2248 */
2249
2250 fprintf(fp, " %s=\"", option->name);
2251
2252 for (val = option->value; *val; val ++)
2253 {
2254 if (strchr("\"\'\\", *val))
2255 putc('\\', fp);
2256
2257 putc(*val, fp);
2258 }
2259
2260 putc('\"', fp);
2261 }
2262 else
2263 {
2264 /*
2265 * Store the literal value...
2266 */
2267
ef416fc2 2268 fprintf(fp, " %s=%s", option->name, option->value);
8ca02f3c 2269 }
ef416fc2 2270 }
2271 else
2272 fprintf(fp, " %s", option->name);
2273 }
2274
2275 if (wrote)
2276 fputs("\n", fp);
2277 }
2278
2279 /*
fa73b229 2280 * Free the temporary destinations and close the file...
ef416fc2 2281 */
2282
2283 cupsFreeDests(num_temps, temps);
2284
fa73b229 2285 fclose(fp);
2286
080811b1
MS
2287#ifdef __APPLE__
2288 /*
2289 * Set the default printer for this location - this allows command-line
2290 * and GUI applications to share the same default destination...
2291 */
2292
2293 if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) != NULL)
f14324a7
MS
2294 {
2295 CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault,
2296 dest->name,
2297 kCFStringEncodingUTF8);
2298 /* Default printer name */
2299
2300 if (name)
2301 {
2302 _cupsAppleSetDefaultPrinter(name);
2303 CFRelease(name);
2304 }
2305 }
080811b1
MS
2306#endif /* __APPLE__ */
2307
fa73b229 2308#ifdef HAVE_NOTIFY_POST
ef416fc2 2309 /*
fa73b229 2310 * Send a notification so that MacOS X applications can know about the
2311 * change, too.
ef416fc2 2312 */
2313
fa73b229 2314 notify_post("com.apple.printerListChange");
2315#endif /* HAVE_NOTIFY_POST */
ef416fc2 2316
2317 return (0);
2318}
2319
2320
38e73f87
MS
2321/*
2322 * '_cupsUserDefault()' - Get the user default printer from environment
2323 * variables and location information.
2324 */
2325
2326char * /* O - Default printer or NULL */
2327_cupsUserDefault(char *name, /* I - Name buffer */
2328 size_t namesize) /* I - Size of name buffer */
2329{
2330 const char *env; /* LPDEST or PRINTER env variable */
2331#ifdef __APPLE__
f14324a7 2332 CFStringRef locprinter; /* Last printer as this location */
38e73f87
MS
2333#endif /* __APPLE__ */
2334
2335
2336 if ((env = getenv("LPDEST")) == NULL)
2337 if ((env = getenv("PRINTER")) != NULL && !strcmp(env, "lp"))
2338 env = NULL;
2339
2340 if (env)
2341 {
2342 strlcpy(name, env, namesize);
2343 return (name);
2344 }
2345
2346#ifdef __APPLE__
2347 /*
2348 * Use location-based defaults if "use last printer" is selected in the
2349 * system preferences...
2350 */
2351
f14324a7 2352 if ((locprinter = _cupsAppleCopyDefaultPrinter()) != NULL)
38e73f87 2353 {
38e73f87 2354 CFStringGetCString(locprinter, name, namesize, kCFStringEncodingUTF8);
f14324a7
MS
2355 CFRelease(locprinter);
2356 }
38e73f87
MS
2357 else
2358 name[0] = '\0';
2359
f14324a7 2360 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name));
38e73f87
MS
2361
2362 return (*name ? name : NULL);
2363
2364#else
2365 /*
2366 * No location-based defaults on this platform...
2367 */
2368
2369 name[0] = '\0';
2370 return (NULL);
2371#endif /* __APPLE__ */
2372}
2373
2374
080811b1 2375#ifdef __APPLE__
06d4e77b
MS
2376/*
2377 * 'appleCopyLocations()' - Copy the location history array.
2378 */
2379
2380static CFArrayRef /* O - Location array or NULL */
2381appleCopyLocations(void)
2382{
2383 CFArrayRef locations; /* Location array */
2384
2385
2386 /*
2387 * Look up the location array in the preferences...
2388 */
2389
f14324a7
MS
2390 if ((locations = CFPreferencesCopyAppValue(kLastUsedPrintersKey,
2391 kCUPSPrintingPrefs)) == NULL)
06d4e77b
MS
2392 return (NULL);
2393
2394 if (CFGetTypeID(locations) != CFArrayGetTypeID())
2395 {
2396 CFRelease(locations);
2397 return (NULL);
2398 }
2399
2400 return (locations);
2401}
2402
2403
749b1e90
MS
2404/*
2405 * 'appleCopyNetwork()' - Get the network ID for the current location.
2406 */
2407
2408static CFStringRef /* O - Network ID */
2409appleCopyNetwork(void)
2410{
2411 SCDynamicStoreRef dynamicStore; /* System configuration data */
2412 CFStringRef key; /* Current network configuration key */
2413 CFDictionaryRef ip_dict; /* Network configuration data */
2414 CFStringRef network = NULL; /* Current network ID */
88f9aafc 2415
749b1e90 2416
f14324a7 2417 if ((dynamicStore = SCDynamicStoreCreate(NULL, CFSTR("libcups"), NULL,
749b1e90
MS
2418 NULL)) != NULL)
2419 {
f14324a7
MS
2420 /*
2421 * First use the IPv6 router address, if available, since that will generally
2422 * be a globally-unique link-local address.
2423 */
2424
749b1e90 2425 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
f14324a7 2426 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv6)) != NULL)
749b1e90
MS
2427 {
2428 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2429 {
2430 if ((network = CFDictionaryGetValue(ip_dict,
f14324a7 2431 kSCPropNetIPv6Router)) != NULL)
749b1e90
MS
2432 CFRetain(network);
2433
2434 CFRelease(ip_dict);
2435 }
2436
2437 CFRelease(key);
2438 }
2439
f14324a7
MS
2440 /*
2441 * If that doesn't work, try the IPv4 router address. This isn't as unique
2442 * and will likely be a 10.x.y.z or 192.168.y.z address...
2443 */
2444
2445 if (!network)
2446 {
2447 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
2448 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4)) != NULL)
2449 {
2450 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2451 {
2452 if ((network = CFDictionaryGetValue(ip_dict,
2453 kSCPropNetIPv4Router)) != NULL)
2454 CFRetain(network);
2455
2456 CFRelease(ip_dict);
2457 }
2458
2459 CFRelease(key);
2460 }
2461 }
2462
749b1e90
MS
2463 CFRelease(dynamicStore);
2464 }
2465
2466 return (network);
2467}
2468
2469
426c6a59
MS
2470/*
2471 * 'appleGetPaperSize()' - Get the default paper size.
2472 */
2473
5a9febac 2474static char * /* O - Default paper size */
426c6a59
MS
2475appleGetPaperSize(char *name, /* I - Paper size name buffer */
2476 int namesize) /* I - Size of buffer */
2477{
54afec33
MS
2478 CFStringRef defaultPaperID; /* Default paper ID */
2479 _pwg_media_t *pwgmedia; /* PWG media size */
426c6a59
MS
2480
2481
c8fef167 2482 defaultPaperID = _cupsAppleCopyDefaultPaperID();
426c6a59 2483 if (!defaultPaperID ||
557dde9f 2484 CFGetTypeID(defaultPaperID) != CFStringGetTypeID() ||
426c6a59
MS
2485 !CFStringGetCString(defaultPaperID, name, namesize,
2486 kCFStringEncodingUTF8))
2487 name[0] = '\0';
54afec33 2488 else if ((pwgmedia = _pwgMediaForLegacy(name)) != NULL)
c168a833 2489 strlcpy(name, pwgmedia->pwg, namesize);
426c6a59
MS
2490
2491 if (defaultPaperID)
2492 CFRelease(defaultPaperID);
2493
2494 return (name);
2495}
2496
2497
080811b1
MS
2498/*
2499 * 'appleGetPrinter()' - Get a printer from the history array.
2500 */
2501
2502static CFStringRef /* O - Printer name or NULL */
2503appleGetPrinter(CFArrayRef locations, /* I - Location array */
2504 CFStringRef network, /* I - Network name */
2505 CFIndex *locindex) /* O - Index in array */
2506{
2507 CFIndex i, /* Looping var */
2508 count; /* Number of locations */
2509 CFDictionaryRef location; /* Current location */
2510 CFStringRef locnetwork, /* Current network */
2511 locprinter; /* Current printer */
2512
2513
2514 for (i = 0, count = CFArrayGetCount(locations); i < count; i ++)
2515 if ((location = CFArrayGetValueAtIndex(locations, i)) != NULL &&
2516 CFGetTypeID(location) == CFDictionaryGetTypeID())
2517 {
2518 if ((locnetwork = CFDictionaryGetValue(location,
2519 kLocationNetworkKey)) != NULL &&
2520 CFGetTypeID(locnetwork) == CFStringGetTypeID() &&
2521 CFStringCompare(network, locnetwork, 0) == kCFCompareEqualTo &&
2522 (locprinter = CFDictionaryGetValue(location,
2523 kLocationPrinterIDKey)) != NULL &&
2524 CFGetTypeID(locprinter) == CFStringGetTypeID())
2525 {
2526 if (locindex)
2527 *locindex = i;
2528
2529 return (locprinter);
2530 }
2531 }
2532
2533 return (NULL);
2534}
080811b1
MS
2535#endif /* __APPLE__ */
2536
2537
426c6a59
MS
2538/*
2539 * 'cups_add_dest()' - Add a destination to the array.
2540 *
2541 * Unlike cupsAddDest(), this function does not check for duplicates.
2542 */
2543
2544static cups_dest_t * /* O - New destination */
2545cups_add_dest(const char *name, /* I - Name of destination */
2546 const char *instance, /* I - Instance or NULL */
2547 int *num_dests, /* IO - Number of destinations */
2548 cups_dest_t **dests) /* IO - Destinations */
2549{
2550 int insert, /* Insertion point */
2551 diff; /* Result of comparison */
2552 cups_dest_t *dest; /* Destination pointer */
2553
2554
2555 /*
2556 * Add new destination...
2557 */
2558
2559 if (*num_dests == 0)
2560 dest = malloc(sizeof(cups_dest_t));
2561 else
2562 dest = realloc(*dests, sizeof(cups_dest_t) * (*num_dests + 1));
2563
2564 if (!dest)
2565 return (NULL);
2566
2567 *dests = dest;
2568
2569 /*
2570 * Find where to insert the destination...
2571 */
2572
2573 if (*num_dests == 0)
2574 insert = 0;
2575 else
2576 {
2577 insert = cups_find_dest(name, instance, *num_dests, *dests, *num_dests - 1,
2578 &diff);
2579
2580 if (diff > 0)
2581 insert ++;
2582 }
2583
2584 /*
2585 * Move the array elements as needed...
2586 */
2587
2588 if (insert < *num_dests)
2589 memmove(*dests + insert + 1, *dests + insert,
2590 (*num_dests - insert) * sizeof(cups_dest_t));
2591
2592 (*num_dests) ++;
2593
2594 /*
2595 * Initialize the destination...
2596 */
2597
2598 dest = *dests + insert;
2599 dest->name = _cupsStrAlloc(name);
2600 dest->instance = _cupsStrAlloc(instance);
2601 dest->is_default = 0;
2602 dest->num_options = 0;
2603 dest->options = (cups_option_t *)0;
2604
2605 return (dest);
2606}
2607
2608
9c80ffa2
MS
2609# ifdef __BLOCKS__
2610/*
2611 * 'cups_block_cb()' - Enumeration callback for block API.
2612 */
2613
2614static int /* O - 1 to continue, 0 to stop */
2615cups_block_cb(
2616 cups_dest_block_t block, /* I - Block */
dcb445bc
MS
2617 unsigned flags, /* I - Destination flags */
2618 cups_dest_t *dest) /* I - Destination */
9c80ffa2 2619{
dcb445bc 2620 return ((block)(flags, dest));
9c80ffa2
MS
2621}
2622# endif /* __BLOCKS__ */
2623
2624
426c6a59
MS
2625/*
2626 * 'cups_compare_dests()' - Compare two destinations.
2627 */
2628
2629static int /* O - Result of comparison */
2630cups_compare_dests(cups_dest_t *a, /* I - First destination */
2631 cups_dest_t *b) /* I - Second destination */
2632{
2633 int diff; /* Difference */
2634
2635
88f9aafc 2636 if ((diff = _cups_strcasecmp(a->name, b->name)) != 0)
426c6a59
MS
2637 return (diff);
2638 else if (a->instance && b->instance)
88f9aafc 2639 return (_cups_strcasecmp(a->instance, b->instance));
426c6a59
MS
2640 else
2641 return ((a->instance && !b->instance) - (!a->instance && b->instance));
2642}
2643
2644
a29fd7dd
MS
2645#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
2646# ifdef HAVE_DNSSD
dcb445bc
MS
2647/*
2648 * 'cups_dnssd_browse_cb()' - Browse for printers.
2649 */
2650
2651static void
2652cups_dnssd_browse_cb(
2653 DNSServiceRef sdRef, /* I - Service reference */
2654 DNSServiceFlags flags, /* I - Option flags */
2655 uint32_t interfaceIndex, /* I - Interface number */
2656 DNSServiceErrorType errorCode, /* I - Error, if any */
2657 const char *serviceName, /* I - Name of service/device */
2658 const char *regtype, /* I - Type of service */
2659 const char *replyDomain, /* I - Service domain */
2660 void *context) /* I - Enumeration data */
2661{
2662 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2663 /* Enumeration data */
2664
2665
2666 DEBUG_printf(("5cups_dnssd_browse_cb(sdRef=%p, flags=%x, "
2667 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2668 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2669 sdRef, flags, interfaceIndex, errorCode, serviceName, regtype,
2670 replyDomain, context));
2671
2672 /*
2673 * Don't do anything on error...
2674 */
2675
2676 if (errorCode != kDNSServiceErr_NoError)
2677 return;
2678
2679 /*
2680 * Get the device...
2681 */
2682
2683 cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
2684}
2685
2686
a29fd7dd
MS
2687# else /* HAVE_AVAHI */
2688/*
2689 * 'cups_dnssd_browse_cb()' - Browse for printers.
2690 */
2691
2692static void
2693cups_dnssd_browse_cb(
2694 AvahiServiceBrowser *browser, /* I - Browser */
2695 AvahiIfIndex interface, /* I - Interface index (unused) */
2696 AvahiProtocol protocol, /* I - Network protocol (unused) */
2697 AvahiBrowserEvent event, /* I - What happened */
2698 const char *name, /* I - Service name */
2699 const char *type, /* I - Registration type */
2700 const char *domain, /* I - Domain */
2701 AvahiLookupResultFlags flags, /* I - Flags */
2702 void *context) /* I - Devices array */
2703{
37e7e6e0 2704#ifdef DEBUG
a29fd7dd
MS
2705 AvahiClient *client = avahi_service_browser_get_client(browser);
2706 /* Client information */
37e7e6e0 2707#endif /* DEBUG */
a29fd7dd
MS
2708 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2709 /* Enumeration data */
2710
2711
2712 (void)interface;
2713 (void)protocol;
2714 (void)context;
2715
2716 switch (event)
2717 {
2718 case AVAHI_BROWSER_FAILURE:
2719 DEBUG_printf(("cups_dnssd_browse_cb: %s",
2720 avahi_strerror(avahi_client_errno(client))));
2721 avahi_simple_poll_quit(data->simple_poll);
2722 break;
2723
2724 case AVAHI_BROWSER_NEW:
2725 /*
2726 * This object is new on the network.
2727 */
2728
2729 if (flags & AVAHI_LOOKUP_RESULT_LOCAL)
2730 {
2731 /*
2732 * This comes from the local machine so ignore it.
2733 */
2734
2735 DEBUG_printf(("cups_dnssd_browse_cb: Ignoring local service \"%s\".",
2736 name));
2737 }
2738 else
2739 {
2740 /*
2741 * Create a device entry for it if it doesn't yet exist.
2742 */
2743
2744 cups_dnssd_get_device(data, name, type, domain);
2745 }
2746 break;
2747
2748 case AVAHI_BROWSER_REMOVE:
2749 case AVAHI_BROWSER_ALL_FOR_NOW:
2750 case AVAHI_BROWSER_CACHE_EXHAUSTED:
2751 break;
2752 }
2753}
2754
2755
2756/*
2757 * 'cups_dnssd_client_cb()' - Avahi client callback function.
2758 */
2759
2760static void
2761cups_dnssd_client_cb(
2762 AvahiClient *client, /* I - Client information (unused) */
2763 AvahiClientState state, /* I - Current state */
2764 void *context) /* I - User data (unused) */
2765{
2766 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2767 /* Enumeration data */
2768
2769
2770 (void)client;
2771
2772 /*
2773 * If the connection drops, quit.
2774 */
2775
2776 if (state == AVAHI_CLIENT_FAILURE)
2777 {
2778 DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
2779 avahi_simple_poll_quit(data->simple_poll);
2780 }
2781}
2782# endif /* HAVE_DNSSD */
2783
2784
dcb445bc
MS
2785/*
2786 * 'cups_dnssd_compare_device()' - Compare two devices.
2787 */
2788
2789static int /* O - Result of comparison */
2790cups_dnssd_compare_devices(
2791 _cups_dnssd_device_t *a, /* I - First device */
2792 _cups_dnssd_device_t *b) /* I - Second device */
2793{
2794 return (strcmp(a->dest.name, b->dest.name));
2795}
2796
2797
2798/*
2799 * 'cups_dnssd_free_device()' - Free the memory used by a device.
2800 */
2801
2802static void
2803cups_dnssd_free_device(
2804 _cups_dnssd_device_t *device, /* I - Device */
2805 _cups_dnssd_data_t *data) /* I - Enumeration data */
2806{
2807 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", device,
2808 device->dest.name, data));
2809
a29fd7dd 2810# ifdef HAVE_DNSSD
dcb445bc
MS
2811 if (device->ref)
2812 DNSServiceRefDeallocate(device->ref);
a29fd7dd
MS
2813# else /* HAVE_AVAHI */
2814 if (device->ref)
2815 avahi_record_browser_free(device->ref);
2816# endif /* HAVE_DNSSD */
dcb445bc
MS
2817
2818 _cupsStrFree(device->domain);
2819 _cupsStrFree(device->fullName);
2820 _cupsStrFree(device->regtype);
2821 _cupsStrFree(device->dest.name);
2822
2823 cupsFreeOptions(device->dest.num_options, device->dest.options);
2824
2825 free(device);
2826}
2827
2828
2829/*
2830 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
2831 */
2832
2833static _cups_dnssd_device_t * /* O - Device */
2834cups_dnssd_get_device(
2835 _cups_dnssd_data_t *data, /* I - Enumeration data */
2836 const char *serviceName, /* I - Service name */
2837 const char *regtype, /* I - Registration type */
2838 const char *replyDomain) /* I - Domain name */
2839{
2840 _cups_dnssd_device_t key, /* Search key */
2841 *device; /* Device */
2842 char fullName[kDNSServiceMaxDomainName];
2843 /* Full name for query */
2844
2845
2846 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", "
2847 "regtype=\"%s\", replyDomain=\"%s\")", data, serviceName,
2848 regtype, replyDomain));
2849
2850 /*
2851 * See if this is an existing device...
2852 */
2853
2854 key.dest.name = (char *)serviceName;
2855
2856 if ((device = cupsArrayFind(data->devices, &key)) != NULL)
2857 {
2858 /*
2859 * Yes, see if we need to do anything with this...
2860 */
2861
2862 int update = 0; /* Non-zero if we need to update */
2863
2864 if (!_cups_strcasecmp(replyDomain, "local.") &&
2865 _cups_strcasecmp(device->domain, replyDomain))
2866 {
2867 /*
2868 * Update the "global" listing to use the .local domain name instead.
2869 */
2870
2871 _cupsStrFree(device->domain);
2872 device->domain = _cupsStrAlloc(replyDomain);
2873
2874 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
2875 "domain.", device->dest.name));
2876
2877 update = 1;
2878 }
2879
2880 if (!_cups_strcasecmp(regtype, "_ipps._tcp") &&
2881 _cups_strcasecmp(device->regtype, regtype))
2882 {
2883 /*
2884 * Prefer IPPS over IPP.
2885 */
2886
2887 _cupsStrFree(device->regtype);
2888 device->regtype = _cupsStrAlloc(regtype);
2889
2890 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
2891 device->dest.name));
2892
2893 update = 1;
2894 }
2895
2896 if (!update)
2897 {
2898 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
2899 device->dest.name));
2900 return (device);
2901 }
2902 }
2903 else
2904 {
2905 /*
2906 * No, add the device...
2907 */
2908
2909 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
2910 "'%s'.", serviceName,
2911 !strcmp(regtype, "_ipps._tcp") ? "IPPS" : "IPP",
2912 replyDomain));
2913
2914 device = calloc(sizeof(_cups_dnssd_device_t), 1);
2915 device->dest.name = _cupsStrAlloc(serviceName);
2916 device->domain = _cupsStrAlloc(replyDomain);
2917 device->regtype = _cupsStrAlloc(regtype);
2918
2919 cupsArrayAdd(data->devices, device);
2920 }
2921
2922 /*
2923 * Set the "full name" of this service, which is used for queries...
2924 */
2925
a29fd7dd 2926# ifdef HAVE_DNSSD
dcb445bc
MS
2927 DNSServiceConstructFullName(fullName, device->dest.name, device->regtype,
2928 device->domain);
a29fd7dd
MS
2929# else /* HAVE_AVAHI */
2930 avahi_service_name_join(fullName, kDNSServiceMaxDomainName, serviceName,
2931 regtype, replyDomain);
2932# endif /* HAVE_DNSSD */
2933
dcb445bc
MS
2934 _cupsStrFree(device->fullName);
2935 device->fullName = _cupsStrAlloc(fullName);
2936
2937 if (device->ref)
2938 {
a29fd7dd 2939# ifdef HAVE_DNSSD
dcb445bc 2940 DNSServiceRefDeallocate(device->ref);
a29fd7dd
MS
2941# else /* HAVE_AVAHI */
2942 avahi_record_browser_free(device->ref);
2943# endif /* HAVE_DNSSD */
2944
dcb445bc
MS
2945 device->ref = 0;
2946 }
2947
2948 if (device->state == _CUPS_DNSSD_ACTIVE)
2949 {
2950 (*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
2951 device->state = _CUPS_DNSSD_NEW;
2952 }
2953
2954 return (device);
2955}
2956
2957
a29fd7dd 2958# ifdef HAVE_DNSSD
dcb445bc
MS
2959/*
2960 * 'cups_dnssd_local_cb()' - Browse for local printers.
2961 */
2962
2963static void
2964cups_dnssd_local_cb(
2965 DNSServiceRef sdRef, /* I - Service reference */
2966 DNSServiceFlags flags, /* I - Option flags */
2967 uint32_t interfaceIndex, /* I - Interface number */
2968 DNSServiceErrorType errorCode, /* I - Error, if any */
2969 const char *serviceName, /* I - Name of service/device */
2970 const char *regtype, /* I - Type of service */
2971 const char *replyDomain, /* I - Service domain */
2972 void *context) /* I - Devices array */
2973{
2974 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2975 /* Enumeration data */
2976 _cups_dnssd_device_t *device; /* Device */
2977
2978
2979 DEBUG_printf(("5cups_dnssd_local_cb(sdRef=%p, flags=%x, "
2980 "interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", "
2981 "regtype=\"%s\", replyDomain=\"%s\", context=%p)",
2982 sdRef, flags, interfaceIndex, errorCode, serviceName,
2983 regtype, replyDomain, context));
2984
2985 /*
2986 * Only process "add" data...
2987 */
2988
2989 if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
2990 return;
2991
2992 /*
2993 * Get the device...
2994 */
2995
2996 device = cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
2997
2998 /*
2999 * Hide locally-registered devices...
3000 */
3001
3002 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
3003 serviceName));
3004
3005 if (device->ref)
3006 {
3007 DNSServiceRefDeallocate(device->ref);
3008 device->ref = 0;
3009 }
3010
3011 if (device->state == _CUPS_DNSSD_ACTIVE)
3012 (*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
3013
3014 device->state = _CUPS_DNSSD_LOCAL;
3015}
a29fd7dd
MS
3016# endif /* HAVE_DNSSD */
3017
3018
3019# ifdef HAVE_AVAHI
3020/*
3021 * 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
3022 *
3023 * Note: This function is needed because avahi_simple_poll_iterate is broken
3024 * and always uses a timeout of 0 (!) milliseconds.
3025 * (Avahi Ticket #364)
3026 */
3027
3028static int /* O - Number of file descriptors matching */
3029cups_dnssd_poll_cb(
3030 struct pollfd *pollfds, /* I - File descriptors */
3031 unsigned int num_pollfds, /* I - Number of file descriptors */
3032 int timeout, /* I - Timeout in milliseconds (unused) */
3033 void *context) /* I - User data (unused) */
3034{
3035 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3036 /* Enumeration data */
3037 int val; /* Return value */
3038
3039
3040 (void)timeout;
3041
3042 val = poll(pollfds, num_pollfds, 250);
3043
3044 if (val < 0)
3045 {
3046 DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno)));
3047 }
3048 else if (val > 0)
3049 data->got_data = 1;
3050
3051 return (val);
3052}
3053# endif /* HAVE_AVAHI */
dcb445bc
MS
3054
3055
3056/*
3057 * 'cups_dnssd_query_cb()' - Process query data.
3058 */
3059
a29fd7dd 3060# ifdef HAVE_DNSSD
dcb445bc
MS
3061static void
3062cups_dnssd_query_cb(
3063 DNSServiceRef sdRef, /* I - Service reference */
3064 DNSServiceFlags flags, /* I - Data flags */
3065 uint32_t interfaceIndex, /* I - Interface */
3066 DNSServiceErrorType errorCode, /* I - Error, if any */
3067 const char *fullName, /* I - Full service name */
3068 uint16_t rrtype, /* I - Record type */
3069 uint16_t rrclass, /* I - Record class */
3070 uint16_t rdlen, /* I - Length of record data */
3071 const void *rdata, /* I - Record data */
3072 uint32_t ttl, /* I - Time-to-live */
3073 void *context) /* I - Enumeration data */
3074{
a29fd7dd
MS
3075# else /* HAVE_AVAHI */
3076static void
3077cups_dnssd_query_cb(
3078 AvahiRecordBrowser *browser, /* I - Record browser */
3079 AvahiIfIndex interfaceIndex,
3080 /* I - Interface index (unused) */
3081 AvahiProtocol protocol, /* I - Network protocol (unused) */
3082 AvahiBrowserEvent event, /* I - What happened? */
3083 const char *fullName, /* I - Service name */
3084 uint16_t rrclass, /* I - Record class */
3085 uint16_t rrtype, /* I - Record type */
3086 const void *rdata, /* I - TXT record */
3087 size_t rdlen, /* I - Length of TXT record */
3088 AvahiLookupResultFlags flags, /* I - Flags */
3089 void *context) /* I - Enumeration data */
3090{
37e7e6e0 3091# ifdef DEBUG
a29fd7dd
MS
3092 AvahiClient *client = avahi_record_browser_get_client(browser);
3093 /* Client information */
37e7e6e0 3094# endif /* DEBUG */
a29fd7dd 3095# endif /* HAVE_DNSSD */
dcb445bc
MS
3096 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3097 /* Enumeration data */
3098 char name[1024], /* Service name */
3099 *ptr; /* Pointer into string */
3100 _cups_dnssd_device_t dkey, /* Search key */
3101 *device; /* Device */
3102
3103
a29fd7dd 3104# ifdef HAVE_DNSSD
dcb445bc
MS
3105 DEBUG_printf(("5cups_dnssd_query_cb(sdRef=%p, flags=%x, "
3106 "interfaceIndex=%d, errorCode=%d, fullName=\"%s\", "
3107 "rrtype=%u, rrclass=%u, rdlen=%u, rdata=%p, ttl=%u, "
3108 "context=%p)", sdRef, flags, interfaceIndex, errorCode,
3109 fullName, rrtype, rrclass, rdlen, rdata, ttl, context));
3110
3111 /*
3112 * Only process "add" data...
3113 */
3114
3115 if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
3116 return;
3117
a29fd7dd
MS
3118# else /* HAVE_AVAHI */
3119 DEBUG_printf(("5cups_dnssd_query_cb(browser=%p, interfaceIndex=%d, "
3120 "protocol=%d, event=%d, fullName=\"%s\", rrclass=%u, "
3121 "rrtype=%u, rdata=%p, rdlen=%u, flags=%x, context=%p)",
3122 browser, interfaceIndex, protocol, event, fullName, rrclass,
3123 rrtype, rdata, (unsigned)rdlen, flags, context));
3124
3125 /*
3126 * Only process "add" data...
3127 */
3128
3129 if (event != AVAHI_BROWSER_NEW)
3130 {
3131 if (event == AVAHI_BROWSER_FAILURE)
3132 DEBUG_printf(("cups_dnssd_query_cb: %s",
3133 avahi_strerror(avahi_client_errno(client))));
3134
3135 return;
3136 }
3137# endif /* HAVE_DNSSD */
3138
dcb445bc
MS
3139 /*
3140 * Lookup the service in the devices array.
3141 */
3142
3143 dkey.dest.name = name;
3144
3145 cups_dnssd_unquote(name, fullName, sizeof(name));
3146
3147 if ((ptr = strstr(name, "._")) != NULL)
3148 *ptr = '\0';
3149
3150 if ((device = cupsArrayFind(data->devices, &dkey)) != NULL)
3151 {
3152 /*
a29fd7dd 3153 * Found it, pull out the make and model from the TXT record and save it...
dcb445bc
MS
3154 */
3155
3156 const uint8_t *txt, /* Pointer into data */
3157 *txtnext, /* Next key/value pair */
3158 *txtend; /* End of entire TXT record */
3159 uint8_t txtlen; /* Length of current key/value pair */
3160 char key[256], /* Key string */
3161 value[256], /* Value string */
3162 make_and_model[512],
3163 /* Manufacturer and model */
3164 model[256], /* Model */
3165 uriname[1024], /* Name for URI */
3166 uri[1024]; /* Printer URI */
a29fd7dd
MS
3167 cups_ptype_t type = CUPS_PRINTER_REMOTE | CUPS_PRINTER_BW;
3168 /* Printer type */
3169 int saw_printer_type = 0;
3170 /* Did we see a printer-type key? */
dcb445bc
MS
3171
3172 device->state = _CUPS_DNSSD_PENDING;
3173 make_and_model[0] = '\0';
dcb445bc 3174
5a9febac 3175 strlcpy(model, "Unknown", sizeof(model));
dcb445bc
MS
3176
3177 for (txt = rdata, txtend = txt + rdlen;
3178 txt < txtend;
3179 txt = txtnext)
3180 {
3181 /*
3182 * Read a key/value pair starting with an 8-bit length. Since the
3183 * length is 8 bits and the size of the key/value buffers is 256, we
3184 * don't need to check for overflow...
3185 */
3186
3187 txtlen = *txt++;
3188
3189 if (!txtlen || (txt + txtlen) > txtend)
3190 break;
3191
3192 txtnext = txt + txtlen;
3193
3194 for (ptr = key; txt < txtnext && *txt != '='; txt ++)
3195 *ptr++ = *txt;
3196 *ptr = '\0';
3197
3198 if (txt < txtnext && *txt == '=')
3199 {
3200 txt ++;
3201
3202 if (txt < txtnext)
3203 memcpy(value, txt, txtnext - txt);
3204 value[txtnext - txt] = '\0';
3205
3206 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key, value));
3207 }
3208 else
3209 {
3210 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key));
3211 continue;
3212 }
3213
3214 if (!_cups_strcasecmp(key, "usb_MFG") ||
3215 !_cups_strcasecmp(key, "usb_MANU") ||
3216 !_cups_strcasecmp(key, "usb_MANUFACTURER"))
5a9febac 3217 strlcpy(make_and_model, value, sizeof(make_and_model));
dcb445bc
MS
3218 else if (!_cups_strcasecmp(key, "usb_MDL") ||
3219 !_cups_strcasecmp(key, "usb_MODEL"))
5a9febac 3220 strlcpy(model, value, sizeof(model));
dcb445bc
MS
3221 else if (!_cups_strcasecmp(key, "product") && !strstr(value, "Ghostscript"))
3222 {
3223 if (value[0] == '(')
3224 {
3225 /*
3226 * Strip parenthesis...
3227 */
3228
3229 if ((ptr = value + strlen(value) - 1) > value && *ptr == ')')
3230 *ptr = '\0';
3231
5a9febac 3232 strlcpy(model, value + 1, sizeof(model));
dcb445bc
MS
3233 }
3234 else
5a9febac 3235 strlcpy(model, value, sizeof(model));
dcb445bc
MS
3236 }
3237 else if (!_cups_strcasecmp(key, "ty"))
3238 {
5a9febac 3239 strlcpy(model, value, sizeof(model));
dcb445bc
MS
3240
3241 if ((ptr = strchr(model, ',')) != NULL)
3242 *ptr = '\0';
3243 }
a29fd7dd
MS
3244 else if (!_cups_strcasecmp(key, "note"))
3245 device->dest.num_options = cupsAddOption("printer-location", value,
3246 device->dest.num_options,
3247 &device->dest.options);
3248 else if (!_cups_strcasecmp(key, "pdl"))
3249 {
3250 /*
3251 * Look for PDF-capable printers; only PDF-capable printers are shown.
3252 */
3253
3254 const char *start, *next; /* Pointer into value */
3255 int have_pdf = 0; /* Have PDF? */
3256
3257 for (start = value; start && *start; start = next)
3258 {
3259 if (!_cups_strncasecmp(start, "application/pdf", 15) &&
3260 (!start[15] || start[15] == ','))
3261 {
3262 have_pdf = 1;
3263 break;
3264 }
3265
3266 if ((next = strchr(start, ',')) != NULL)
3267 next ++;
3268 }
3269
3270 if (!have_pdf)
3271 device->state = _CUPS_DNSSD_INCOMPATIBLE;
3272 }
dcb445bc
MS
3273 else if (!_cups_strcasecmp(key, "printer-type"))
3274 {
a29fd7dd
MS
3275 /*
3276 * Value is either NNNN or 0xXXXX
3277 */
3278
3279 saw_printer_type = 1;
3280 type = strtol(value, NULL, 0);
3281 }
3282 else if (!saw_printer_type)
3283 {
3284 if (!_cups_strcasecmp(key, "air") &&
3285 !_cups_strcasecmp(value, "t"))
3286 type |= CUPS_PRINTER_AUTHENTICATED;
3287 else if (!_cups_strcasecmp(key, "bind") &&
3288 !_cups_strcasecmp(value, "t"))
3289 type |= CUPS_PRINTER_BIND;
3290 else if (!_cups_strcasecmp(key, "collate") &&
3291 !_cups_strcasecmp(value, "t"))
3292 type |= CUPS_PRINTER_COLLATE;
3293 else if (!_cups_strcasecmp(key, "color") &&
3294 !_cups_strcasecmp(value, "t"))
3295 type |= CUPS_PRINTER_COLOR;
3296 else if (!_cups_strcasecmp(key, "copies") &&
3297 !_cups_strcasecmp(value, "t"))
3298 type |= CUPS_PRINTER_COPIES;
3299 else if (!_cups_strcasecmp(key, "duplex") &&
3300 !_cups_strcasecmp(value, "t"))
3301 type |= CUPS_PRINTER_DUPLEX;
3302 else if (!_cups_strcasecmp(key, "fax") &&
3303 !_cups_strcasecmp(value, "t"))
3304 type |= CUPS_PRINTER_MFP;
3305 else if (!_cups_strcasecmp(key, "papercustom") &&
3306 !_cups_strcasecmp(value, "t"))
3307 type |= CUPS_PRINTER_VARIABLE;
3308 else if (!_cups_strcasecmp(key, "papermax"))
3309 {
3310 if (!_cups_strcasecmp(value, "legal-a4"))
3311 type |= CUPS_PRINTER_SMALL;
3312 else if (!_cups_strcasecmp(value, "isoc-a2"))
3313 type |= CUPS_PRINTER_MEDIUM;
3314 else if (!_cups_strcasecmp(value, ">isoc-a2"))
3315 type |= CUPS_PRINTER_LARGE;
3316 }
3317 else if (!_cups_strcasecmp(key, "punch") &&
3318 !_cups_strcasecmp(value, "t"))
3319 type |= CUPS_PRINTER_PUNCH;
3320 else if (!_cups_strcasecmp(key, "scan") &&
3321 !_cups_strcasecmp(value, "t"))
3322 type |= CUPS_PRINTER_MFP;
3323 else if (!_cups_strcasecmp(key, "sort") &&
3324 !_cups_strcasecmp(value, "t"))
3325 type |= CUPS_PRINTER_SORT;
3326 else if (!_cups_strcasecmp(key, "staple") &&
3327 !_cups_strcasecmp(value, "t"))
3328 type |= CUPS_PRINTER_STAPLE;
dcb445bc
MS
3329 }
3330 }
3331
3332 /*
a29fd7dd 3333 * Save the printer-xxx values...
dcb445bc
MS
3334 */
3335
a29fd7dd
MS
3336 device->dest.num_options = cupsAddOption("printer-info", name,
3337 device->dest.num_options,
3338 &device->dest.options);
3339
dcb445bc
MS
3340 if (make_and_model[0])
3341 {
3342 strlcat(make_and_model, " ", sizeof(make_and_model));
3343 strlcat(make_and_model, model, sizeof(make_and_model));
3344
3345 device->dest.num_options = cupsAddOption("printer-make-and-model",
3346 make_and_model,
3347 device->dest.num_options,
3348 &device->dest.options);
3349 }
3350 else
3351 device->dest.num_options = cupsAddOption("printer-make-and-model",
3352 model,
3353 device->dest.num_options,
3354 &device->dest.options);
3355
a29fd7dd
MS
3356 device->type = type;
3357 snprintf(value, sizeof(value), "%u", type);
3358 device->dest.num_options = cupsAddOption("printer-type", value,
3359 device->dest.num_options,
3360 &device->dest.options);
3361
dcb445bc
MS
3362 /*
3363 * Save the URI...
3364 */
3365
3366 cups_dnssd_unquote(uriname, device->fullName, sizeof(uriname));
3367 httpAssembleURI(HTTP_URI_CODING_ALL, uri, sizeof(uri),
3368 !strcmp(device->regtype, "_ipps._tcp") ? "ipps" : "ipp",
a29fd7dd 3369 NULL, uriname, 0, saw_printer_type ? "/cups" : "/");
dcb445bc
MS
3370
3371 DEBUG_printf(("6cups_dnssd_query: printer-uri-supported=\"%s\"", uri));
3372
3373 device->dest.num_options = cupsAddOption("printer-uri-supported", uri,
3374 device->dest.num_options,
3375 &device->dest.options);
3376 }
3377 else
3378 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
3379 fullName));
3380}
3381
3382
3383/*
3384 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
3385 */
3386
3387static const char * /* O - Resolved URI or NULL */
3388cups_dnssd_resolve(
3389 cups_dest_t *dest, /* I - Destination */
3390 const char *uri, /* I - Current printer URI */
3391 int msec, /* I - Time in milliseconds */
3392 int *cancel, /* I - Pointer to "cancel" variable */
3393 cups_dest_cb_t cb, /* I - Callback */
3394 void *user_data) /* I - User data for callback */
3395{
3396 char tempuri[1024]; /* Temporary URI buffer */
3397 _cups_dnssd_resolve_t resolve; /* Resolve data */
3398
3399
3400 /*
3401 * Resolve the URI...
3402 */
3403
3404 resolve.cancel = cancel;
3405 gettimeofday(&resolve.end_time, NULL);
3406 if (msec > 0)
3407 {
3408 resolve.end_time.tv_sec += msec / 1000;
3409 resolve.end_time.tv_usec += (msec % 1000) * 1000;
3410
3411 while (resolve.end_time.tv_usec >= 1000000)
3412 {
3413 resolve.end_time.tv_sec ++;
3414 resolve.end_time.tv_usec -= 1000000;
3415 }
3416 }
3417 else
3418 resolve.end_time.tv_sec += 75;
3419
3420 if (cb)
3421 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING,
3422 dest);
3423
3424 if ((uri = _httpResolveURI(uri, tempuri, sizeof(tempuri),
3425 _HTTP_RESOLVE_FQDN, cups_dnssd_resolve_cb,
3426 &resolve)) == NULL)
3427 {
3428 _cupsSetError(IPP_INTERNAL_ERROR, _("Unable to resolve printer URI."), 1);
3429
3430 if (cb)
3431 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
3432 dest);
3433
3434 return (NULL);
3435 }
3436
3437 /*
3438 * Save the resolved URI...
3439 */
3440
3441 dest->num_options = cupsAddOption("printer-uri-supported", uri,
3442 dest->num_options, &dest->options);
3443
3444 return (cupsGetOption("printer-uri-supported", dest->num_options,
3445 dest->options));
3446}
3447
3448
3449/*
3450 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
3451 */
3452
3453static int /* O - 1 to continue, 0 to stop */
3454cups_dnssd_resolve_cb(void *context) /* I - Resolve data */
3455{
3456 _cups_dnssd_resolve_t *resolve = (_cups_dnssd_resolve_t *)context;
3457 /* Resolve data */
3458 struct timeval curtime; /* Current time */
3459
3460
3461 /*
3462 * If the cancel variable is set, return immediately.
3463 */
3464
3465 if (*resolve->cancel)
3466 return (0);
3467
3468 /*
3469 * Otherwise check the end time...
3470 */
3471
3472 gettimeofday(&curtime, NULL);
3473
3474 return (curtime.tv_sec > resolve->end_time.tv_sec ||
3475 (curtime.tv_sec == resolve->end_time.tv_sec &&
3476 curtime.tv_usec > resolve->end_time.tv_usec));
3477}
3478
3479
3480/*
3481 * 'cups_dnssd_unquote()' - Unquote a name string.
3482 */
3483
3484static void
3485cups_dnssd_unquote(char *dst, /* I - Destination buffer */
3486 const char *src, /* I - Source string */
3487 size_t dstsize) /* I - Size of destination buffer */
3488{
3489 char *dstend = dst + dstsize - 1; /* End of destination buffer */
3490
3491
3492 while (*src && dst < dstend)
3493 {
3494 if (*src == '\\')
3495 {
3496 src ++;
3497 if (isdigit(src[0] & 255) && isdigit(src[1] & 255) &&
3498 isdigit(src[2] & 255))
3499 {
3500 *dst++ = ((((src[0] - '0') * 10) + src[1] - '0') * 10) + src[2] - '0';
3501 src += 3;
3502 }
3503 else
3504 *dst++ = *src++;
3505 }
3506 else
3507 *dst++ = *src ++;
3508 }
3509
3510 *dst = '\0';
3511}
3512#endif /* HAVE_DNSSD */
3513
3514
426c6a59
MS
3515/*
3516 * 'cups_find_dest()' - Find a destination using a binary search.
3517 */
3518
3519static int /* O - Index of match */
3520cups_find_dest(const char *name, /* I - Destination name */
3521 const char *instance, /* I - Instance or NULL */
3522 int num_dests, /* I - Number of destinations */
3523 cups_dest_t *dests, /* I - Destinations */
3524 int prev, /* I - Previous index */
3525 int *rdiff) /* O - Difference of match */
3526{
3527 int left, /* Low mark for binary search */
3528 right, /* High mark for binary search */
3529 current, /* Current index */
3530 diff; /* Result of comparison */
3531 cups_dest_t key; /* Search key */
3532
3533
3534 key.name = (char *)name;
3535 key.instance = (char *)instance;
3536
3537 if (prev >= 0)
3538 {
3539 /*
3540 * Start search on either side of previous...
3541 */
3542
3543 if ((diff = cups_compare_dests(&key, dests + prev)) == 0 ||
3544 (diff < 0 && prev == 0) ||
3545 (diff > 0 && prev == (num_dests - 1)))
3546 {
3547 *rdiff = diff;
3548 return (prev);
3549 }
3550 else if (diff < 0)
3551 {
3552 /*
3553 * Start with previous on right side...
3554 */
3555
3556 left = 0;
3557 right = prev;
3558 }
3559 else
3560 {
3561 /*
3562 * Start wih previous on left side...
3563 */
3564
3565 left = prev;
3566 right = num_dests - 1;
3567 }
3568 }
3569 else
3570 {
3571 /*
3572 * Start search in the middle...
3573 */
3574
3575 left = 0;
3576 right = num_dests - 1;
3577 }
3578
3579 do
3580 {
3581 current = (left + right) / 2;
3582 diff = cups_compare_dests(&key, dests + current);
3583
3584 if (diff == 0)
3585 break;
3586 else if (diff < 0)
3587 right = current;
3588 else
3589 left = current;
3590 }
3591 while ((right - left) > 1);
3592
3593 if (diff != 0)
3594 {
3595 /*
3596 * Check the last 1 or 2 elements...
3597 */
3598
3599 if ((diff = cups_compare_dests(&key, dests + left)) <= 0)
3600 current = left;
3601 else
3602 {
3603 diff = cups_compare_dests(&key, dests + right);
3604 current = right;
3605 }
3606 }
3607
3608 /*
3609 * Return the closest destination and the difference...
3610 */
3611
3612 *rdiff = diff;
3613
3614 return (current);
3615}
3616
3617
a4924f6c
MS
3618/*
3619 * 'cups_get_default()' - Get the default destination from an lpoptions file.
3620 */
3621
080811b1 3622static char * /* O - Default destination or NULL */
a4924f6c
MS
3623cups_get_default(const char *filename, /* I - File to read */
3624 char *namebuf, /* I - Name buffer */
3625 size_t namesize, /* I - Size of name buffer */
3626 const char **instance) /* I - Instance */
3627{
3628 cups_file_t *fp; /* lpoptions file */
3629 char line[8192], /* Line from file */
3630 *value, /* Value for line */
3631 *nameptr; /* Pointer into name */
88f9aafc 3632 int linenum; /* Current line */
a4924f6c
MS
3633
3634
3635 *namebuf = '\0';
3636
3637 if ((fp = cupsFileOpen(filename, "r")) != NULL)
3638 {
3639 linenum = 0;
3640
3641 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
3642 {
88f9aafc 3643 if (!_cups_strcasecmp(line, "default") && value)
a4924f6c
MS
3644 {
3645 strlcpy(namebuf, value, namesize);
3646
3647 if ((nameptr = strchr(namebuf, ' ')) != NULL)
3648 *nameptr = '\0';
3649 if ((nameptr = strchr(namebuf, '\t')) != NULL)
3650 *nameptr = '\0';
3651
3652 if ((nameptr = strchr(namebuf, '/')) != NULL)
3653 *nameptr++ = '\0';
3654
3655 *instance = nameptr;
3656 break;
3657 }
3658 }
3659
3660 cupsFileClose(fp);
3661 }
3662
3663 return (*namebuf ? namebuf : NULL);
3664}
3665
3666
ef416fc2 3667/*
3668 * 'cups_get_dests()' - Get destinations from a file.
3669 */
3670
3671static int /* O - Number of destinations */
38e73f87
MS
3672cups_get_dests(
3673 const char *filename, /* I - File to read from */
3674 const char *match_name, /* I - Destination name we want */
3675 const char *match_inst, /* I - Instance name we want */
3676 int user_default_set, /* I - User default printer set? */
3677 int num_dests, /* I - Number of destinations */
3678 cups_dest_t **dests) /* IO - Destinations */
ef416fc2 3679{
3680 int i; /* Looping var */
3681 cups_dest_t *dest; /* Current destination */
a4924f6c 3682 cups_file_t *fp; /* File pointer */
ef416fc2 3683 char line[8192], /* Line from file */
3684 *lineptr, /* Pointer into line */
3685 *name, /* Name of destination/option */
3686 *instance; /* Instance of destination */
a4924f6c 3687 int linenum; /* Current line number */
ef416fc2 3688
3689
e07d4801 3690 DEBUG_printf(("7cups_get_dests(filename=\"%s\", match_name=\"%s\", "
38e73f87 3691 "match_inst=\"%s\", user_default_set=%d, num_dests=%d, "
e07d4801 3692 "dests=%p)", filename, match_name, match_inst,
38e73f87 3693 user_default_set, num_dests, dests));
a4924f6c
MS
3694
3695 /*
3696 * Try to open the file...
3697 */
3698
3699 if ((fp = cupsFileOpen(filename, "r")) == NULL)
3700 return (num_dests);
3701
ef416fc2 3702 /*
3703 * Read each printer; each line looks like:
3704 *
3705 * Dest name[/instance] options
3706 * Default name[/instance] options
3707 */
3708
a4924f6c
MS
3709 linenum = 0;
3710
3711 while (cupsFileGetConf(fp, line, sizeof(line), &lineptr, &linenum))
ef416fc2 3712 {
3713 /*
3714 * See what type of line it is...
3715 */
3716
e07d4801 3717 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
38e73f87 3718 linenum, line, lineptr));
ef416fc2 3719
88f9aafc 3720 if ((_cups_strcasecmp(line, "dest") && _cups_strcasecmp(line, "default")) || !lineptr)
a4924f6c 3721 {
e07d4801 3722 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
ef416fc2 3723 continue;
a4924f6c 3724 }
ef416fc2 3725
3726 name = lineptr;
3727
3728 /*
3729 * Search for an instance...
3730 */
3731
3732 while (!isspace(*lineptr & 255) && *lineptr && *lineptr != '/')
3733 lineptr ++;
3734
ef416fc2 3735 if (*lineptr == '/')
3736 {
3737 /*
3738 * Found an instance...
3739 */
3740
3741 *lineptr++ = '\0';
3742 instance = lineptr;
3743
3744 /*
3745 * Search for an instance...
3746 */
3747
3748 while (!isspace(*lineptr & 255) && *lineptr)
3749 lineptr ++;
3750 }
3751 else
3752 instance = NULL;
3753
a4924f6c
MS
3754 if (*lineptr)
3755 *lineptr++ = '\0';
3756
e07d4801 3757 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name,
a4924f6c 3758 instance));
ef416fc2 3759
3760 /*
3761 * See if the primary instance of the destination exists; if not,
3762 * ignore this entry and move on...
3763 */
3764
a4924f6c
MS
3765 if (match_name)
3766 {
88f9aafc 3767 if (_cups_strcasecmp(name, match_name) ||
a4924f6c
MS
3768 (!instance && match_inst) ||
3769 (instance && !match_inst) ||
88f9aafc 3770 (instance && _cups_strcasecmp(instance, match_inst)))
a4924f6c 3771 continue;
ef416fc2 3772
a4924f6c
MS
3773 dest = *dests;
3774 }
3775 else if (cupsGetDest(name, NULL, num_dests, *dests) == NULL)
3776 {
e07d4801 3777 DEBUG_puts("9cups_get_dests: Not found!");
a4924f6c
MS
3778 continue;
3779 }
3780 else
ef416fc2 3781 {
3782 /*
a4924f6c 3783 * Add the destination...
ef416fc2 3784 */
3785
a4924f6c
MS
3786 num_dests = cupsAddDest(name, instance, num_dests, dests);
3787
3788 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
3789 {
3790 /*
3791 * Out of memory!
3792 */
3793
e07d4801 3794 DEBUG_puts("9cups_get_dests: Out of memory!");
a4924f6c
MS
3795 break;
3796 }
ef416fc2 3797 }
3798
3799 /*
3800 * Add options until we hit the end of the line...
3801 */
3802
3803 dest->num_options = cupsParseOptions(lineptr, dest->num_options,
3804 &(dest->options));
3805
a4924f6c
MS
3806 /*
3807 * If we found what we were looking for, stop now...
3808 */
3809
3810 if (match_name)
3811 break;
3812
ef416fc2 3813 /*
3814 * Set this as default if needed...
3815 */
3816
88f9aafc 3817 if (!user_default_set && !_cups_strcasecmp(line, "default"))
ef416fc2 3818 {
e07d4801 3819 DEBUG_puts("9cups_get_dests: Setting as default...");
a4924f6c 3820
ef416fc2 3821 for (i = 0; i < num_dests; i ++)
3822 (*dests)[i].is_default = 0;
3823
3824 dest->is_default = 1;
3825 }
3826 }
3827
3828 /*
3829 * Close the file and return...
3830 */
3831
88f9aafc 3832 cupsFileClose(fp);
ef416fc2 3833
3834 return (num_dests);
3835}
3836
3837
426c6a59
MS
3838/*
3839 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
3840 * attribute.
3841 */
3842
3843static char * /* O - New string */
3844cups_make_string(
3845 ipp_attribute_t *attr, /* I - Attribute to convert */
3846 char *buffer, /* I - Buffer */
3847 size_t bufsize) /* I - Size of buffer */
3848{
3849 int i; /* Looping var */
3850 char *ptr, /* Pointer into buffer */
3851 *end, /* Pointer to end of buffer */
3852 *valptr; /* Pointer into string attribute */
3853
3854
3855 /*
3856 * Return quickly if we have a single string value...
3857 */
3858
3859 if (attr->num_values == 1 &&
3860 attr->value_tag != IPP_TAG_INTEGER &&
3861 attr->value_tag != IPP_TAG_ENUM &&
3862 attr->value_tag != IPP_TAG_BOOLEAN &&
3863 attr->value_tag != IPP_TAG_RANGE)
3864 return (attr->values[0].string.text);
3865
3866 /*
3867 * Copy the values to the string, separating with commas and escaping strings
3868 * as needed...
3869 */
3870
3871 end = buffer + bufsize - 1;
3872
3873 for (i = 0, ptr = buffer; i < attr->num_values && ptr < end; i ++)
3874 {
3875 if (i)
3876 *ptr++ = ',';
3877
3878 switch (attr->value_tag)
3879 {
3880 case IPP_TAG_INTEGER :
3881 case IPP_TAG_ENUM :
3882 snprintf(ptr, end - ptr + 1, "%d", attr->values[i].integer);
3883 break;
3884
3885 case IPP_TAG_BOOLEAN :
3886 if (attr->values[i].boolean)
3887 strlcpy(ptr, "true", end - ptr + 1);
3888 else
3889 strlcpy(ptr, "false", end - ptr + 1);
3890 break;
3891
3892 case IPP_TAG_RANGE :
3893 if (attr->values[i].range.lower == attr->values[i].range.upper)
3894 snprintf(ptr, end - ptr + 1, "%d", attr->values[i].range.lower);
3895 else
3896 snprintf(ptr, end - ptr + 1, "%d-%d", attr->values[i].range.lower,
3897 attr->values[i].range.upper);
3898 break;
3899
3900 default :
3901 for (valptr = attr->values[i].string.text;
3902 *valptr && ptr < end;)
3903 {
3904 if (strchr(" \t\n\\\'\"", *valptr))
3905 {
3906 if (ptr >= (end - 1))
3907 break;
3908
3909 *ptr++ = '\\';
3910 }
3911
3912 *ptr++ = *valptr++;
3913 }
3914
3915 *ptr = '\0';
3916 break;
3917 }
3918
3919 ptr += strlen(ptr);
3920 }
3921
3922 *ptr = '\0';
3923
3924 return (buffer);
3925}
3926
3927
ef416fc2 3928/*
f14324a7 3929 * End of "$Id: dest.c 9568 2011-02-25 06:13:56Z mike $".
ef416fc2 3930 */