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