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