]> git.ipfire.org Git - thirdparty/cups.git/blame - cups/dest.c
The `ipptool` program did not compare URI scheme or hostname components
[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));
1823#endif /* __APPLE__ */
1824
0cb67df3 1825 /*
cb7f98ee 1826 * Build a IPP_OP_CUPS_GET_PRINTERS or IPP_OP_GET_PRINTER_ATTRIBUTES request, which
0cb67df3
MS
1827 * require the following attributes:
1828 *
1829 * attributes-charset
1830 * attributes-natural-language
1831 * requesting-user-name
cb7f98ee 1832 * printer-uri [for IPP_OP_GET_PRINTER_ATTRIBUTES]
0cb67df3 1833 */
c1420c87 1834
0cb67df3 1835 request = ippNewRequest(op);
c1420c87 1836
0cb67df3
MS
1837 ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
1838 "requested-attributes", sizeof(pattrs) / sizeof(pattrs[0]),
1839 NULL, pattrs);
c1420c87 1840
0cb67df3
MS
1841 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
1842 "requesting-user-name", NULL, cupsUser());
c1420c87 1843
cb7f98ee 1844 if (name && op != IPP_OP_CUPS_GET_DEFAULT)
0cb67df3
MS
1845 {
1846 httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
1847 "localhost", ippPort(), "/printers/%s", name);
1848 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL,
1849 uri);
1850 }
1851 else if (mask)
1852 {
7e86f2f6
MS
1853 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type", (int)type);
1854 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type-mask", (int)mask);
c1420c87 1855 }
c8fef167 1856
0cb67df3
MS
1857 /*
1858 * Do the request and get back a response...
1859 */
1860
1861 if ((response = cupsDoRequest(http, request, "/")) != NULL)
c8fef167
MS
1862 {
1863 for (attr = response->attrs; attr != NULL; attr = attr->next)
1864 {
1865 /*
1866 * Skip leading attributes until we hit a printer...
1867 */
1868
1869 while (attr != NULL && attr->group_tag != IPP_TAG_PRINTER)
1870 attr = attr->next;
1871
1872 if (attr == NULL)
1873 break;
1874
1875 /*
1876 * Pull the needed attributes from this printer...
1877 */
1878
1879 printer_name = NULL;
1880 num_options = 0;
1881 options = NULL;
1882
1883 for (; attr && attr->group_tag == IPP_TAG_PRINTER; attr = attr->next)
1884 {
1885 if (attr->value_tag != IPP_TAG_INTEGER &&
1886 attr->value_tag != IPP_TAG_ENUM &&
1887 attr->value_tag != IPP_TAG_BOOLEAN &&
1888 attr->value_tag != IPP_TAG_TEXT &&
1889 attr->value_tag != IPP_TAG_TEXTLANG &&
1890 attr->value_tag != IPP_TAG_NAME &&
1891 attr->value_tag != IPP_TAG_NAMELANG &&
1892 attr->value_tag != IPP_TAG_KEYWORD &&
1893 attr->value_tag != IPP_TAG_RANGE &&
1894 attr->value_tag != IPP_TAG_URI)
1895 continue;
1896
1897 if (!strcmp(attr->name, "auth-info-required") ||
1898 !strcmp(attr->name, "device-uri") ||
1899 !strcmp(attr->name, "marker-change-time") ||
1900 !strcmp(attr->name, "marker-colors") ||
1901 !strcmp(attr->name, "marker-high-levels") ||
1902 !strcmp(attr->name, "marker-levels") ||
1903 !strcmp(attr->name, "marker-low-levels") ||
1904 !strcmp(attr->name, "marker-message") ||
1905 !strcmp(attr->name, "marker-names") ||
1906 !strcmp(attr->name, "marker-types") ||
1907 !strcmp(attr->name, "printer-commands") ||
1908 !strcmp(attr->name, "printer-info") ||
12b798a0
MS
1909 !strcmp(attr->name, "printer-is-shared") ||
1910 !strcmp(attr->name, "printer-is-temporary") ||
c8fef167 1911 !strcmp(attr->name, "printer-make-and-model") ||
5a9febac 1912 !strcmp(attr->name, "printer-mandatory-job-attributes") ||
c8fef167
MS
1913 !strcmp(attr->name, "printer-state") ||
1914 !strcmp(attr->name, "printer-state-change-time") ||
1915 !strcmp(attr->name, "printer-type") ||
1916 !strcmp(attr->name, "printer-is-accepting-jobs") ||
1917 !strcmp(attr->name, "printer-location") ||
1918 !strcmp(attr->name, "printer-state-reasons") ||
1919 !strcmp(attr->name, "printer-uri-supported"))
1920 {
1921 /*
1922 * Add a printer description attribute...
1923 */
1924
1925 num_options = cupsAddOption(attr->name,
1926 cups_make_string(attr, value,
1927 sizeof(value)),
1928 num_options, &options);
1929 }
1930#ifdef __APPLE__
1931 else if (!strcmp(attr->name, "media-supported"))
1932 {
1933 /*
1934 * See if we can set a default media size...
1935 */
1936
1937 int i; /* Looping var */
1938
1939 for (i = 0; i < attr->num_values; i ++)
88f9aafc 1940 if (!_cups_strcasecmp(media_default, attr->values[i].string.text))
c8fef167
MS
1941 {
1942 num_options = cupsAddOption("media", media_default, num_options,
1943 &options);
1944 break;
1945 }
1946 }
1947#endif /* __APPLE__ */
1948 else if (!strcmp(attr->name, "printer-name") &&
1949 attr->value_tag == IPP_TAG_NAME)
1950 printer_name = attr->values[0].string.text;
1951 else if (strncmp(attr->name, "notify-", 7) &&
1952 (attr->value_tag == IPP_TAG_BOOLEAN ||
1953 attr->value_tag == IPP_TAG_ENUM ||
1954 attr->value_tag == IPP_TAG_INTEGER ||
1955 attr->value_tag == IPP_TAG_KEYWORD ||
1956 attr->value_tag == IPP_TAG_NAME ||
1957 attr->value_tag == IPP_TAG_RANGE) &&
1958 (ptr = strstr(attr->name, "-default")) != NULL)
1959 {
1960 /*
1961 * Add a default option...
1962 */
1963
1964 strlcpy(optname, attr->name, sizeof(optname));
1965 optname[ptr - attr->name] = '\0';
1966
88f9aafc 1967 if (_cups_strcasecmp(optname, "media") ||
c8fef167
MS
1968 !cupsGetOption("media", num_options, options))
1969 num_options = cupsAddOption(optname,
1970 cups_make_string(attr, value,
1971 sizeof(value)),
1972 num_options, &options);
1973 }
1974 }
1975
1976 /*
1977 * See if we have everything needed...
1978 */
1979
1980 if (!printer_name)
1981 {
1982 cupsFreeOptions(num_options, options);
1983
1984 if (attr == NULL)
1985 break;
1986 else
1987 continue;
1988 }
1989
1990 if ((dest = cups_add_dest(printer_name, NULL, &num_dests, dests)) != NULL)
1991 {
1992 dest->num_options = num_options;
1993 dest->options = options;
1994 }
1995 else
1996 cupsFreeOptions(num_options, options);
1997
1998 if (attr == NULL)
1999 break;
2000 }
2001
2002 ippDelete(response);
2003 }
2004
2005 /*
2006 * Return the count...
2007 */
2008
2009 return (num_dests);
2010}
2011
2012
ef416fc2 2013/*
2014 * 'cupsGetDests()' - Get the list of destinations from the default server.
ecdc0628 2015 *
2016 * Starting with CUPS 1.2, the returned list of destinations include the
98d88c8d
MS
2017 * "printer-info", "printer-is-accepting-jobs", "printer-is-shared",
2018 * "printer-make-and-model", "printer-state", "printer-state-change-time",
2019 * "printer-state-reasons", "printer-type", and "printer-uri-supported"
2020 * attributes as options.
2021 *
2022 * CUPS 1.4 adds the "marker-change-time", "marker-colors",
2023 * "marker-high-levels", "marker-levels", "marker-low-levels", "marker-message",
2024 * "marker-names", "marker-types", and "printer-commands" attributes as options.
2025 *
2026 * CUPS 2.2 adds accessible IPP printers to the list of destinations that can
2027 * be used. The "printer-uri-supported" option will be present for those IPP
2028 * printers that have been recently used.
2abf387c 2029 *
5a738aea
MS
2030 * Use the @link cupsFreeDests@ function to free the destination list and
2031 * the @link cupsGetDest@ function to find a particular destination.
53af7f21
MS
2032 *
2033 * @exclude all@
ef416fc2 2034 */
2035
2036int /* O - Number of destinations */
2037cupsGetDests(cups_dest_t **dests) /* O - Destinations */
2038{
3d052e43 2039 return (cupsGetDests2(CUPS_HTTP_DEFAULT, dests));
ef416fc2 2040}
2041
2042
2043/*
2044 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
2045 *
ecdc0628 2046 * Starting with CUPS 1.2, the returned list of destinations include the
98d88c8d
MS
2047 * "printer-info", "printer-is-accepting-jobs", "printer-is-shared",
2048 * "printer-make-and-model", "printer-state", "printer-state-change-time",
2049 * "printer-state-reasons", "printer-type", and "printer-uri-supported"
2050 * attributes as options.
2051 *
2052 * CUPS 1.4 adds the "marker-change-time", "marker-colors",
2053 * "marker-high-levels", "marker-levels", "marker-low-levels", "marker-message",
2054 * "marker-names", "marker-types", and "printer-commands" attributes as options.
2055 *
2056 * CUPS 2.2 adds accessible IPP printers to the list of destinations that can
2057 * be used. The "printer-uri-supported" option will be present for those IPP
2058 * printers that have been recently used.
ecdc0628 2059 *
5a738aea
MS
2060 * Use the @link cupsFreeDests@ function to free the destination list and
2061 * the @link cupsGetDest@ function to find a particular destination.
2abf387c 2062 *
98d88c8d 2063 * @since CUPS 1.1.21/macOS 10.4@
ef416fc2 2064 */
2065
2066int /* O - Number of destinations */
568fa3fa 2067cupsGetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
ef416fc2 2068 cups_dest_t **dests) /* O - Destinations */
2069{
7536de1a
MS
2070 _cups_getdata_t data; /* Enumeration data */
2071 cups_dest_t *dest; /* Current destination */
ef416fc2 2072 const char *home; /* HOME environment variable */
b423cd4c 2073 char filename[1024]; /* Local ~/.cups/lpoptions file */
ef416fc2 2074 const char *defprinter; /* Default printer */
2075 char name[1024], /* Copy of printer name */
38e73f87
MS
2076 *instance, /* Pointer to instance name */
2077 *user_default; /* User default printer */
ef416fc2 2078 int num_reals; /* Number of real queues */
2079 cups_dest_t *reals; /* Real queues */
3d052e43 2080 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
ef416fc2 2081
2082
fb963b8d
MS
2083 DEBUG_printf(("cupsGetDests2(http=%p, dests=%p)", (void *)http, (void *)dests));
2084
2085/*
ef416fc2 2086 * Range check the input...
2087 */
2088
3d052e43 2089 if (!dests)
1ff0402e 2090 {
cb7f98ee 2091 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad NULL dests pointer"), 1);
fb963b8d 2092 DEBUG_puts("1cupsGetDests2: NULL dests pointer, returning 0.");
ef416fc2 2093 return (0);
c8fef167 2094 }
ef416fc2 2095
2096 /*
2097 * Grab the printers and classes...
2098 */
2099
7536de1a
MS
2100 data.num_dests = 0;
2101 data.dests = NULL;
2102
ced9dda8 2103 cupsEnumDests(0, _CUPS_DNSSD_GET_DESTS, NULL, 0, 0, (cups_dest_cb_t)cups_get_cb, &data);
b19ccc9e 2104
ef416fc2 2105 /*
2106 * Make a copy of the "real" queues for a later sanity check...
2107 */
2108
7536de1a 2109 if (data.num_dests > 0)
ef416fc2 2110 {
7536de1a 2111 num_reals = data.num_dests;
7e86f2f6 2112 reals = calloc((size_t)num_reals, sizeof(cups_dest_t));
ef416fc2 2113
2114 if (reals)
7536de1a 2115 memcpy(reals, data.dests, (size_t)num_reals * sizeof(cups_dest_t));
ef416fc2 2116 else
2117 num_reals = 0;
2118 }
2119 else
2120 {
2121 num_reals = 0;
2122 reals = NULL;
2123 }
2124
2125 /*
2126 * Grab the default destination...
2127 */
2128
38e73f87
MS
2129 if ((user_default = _cupsUserDefault(name, sizeof(name))) != NULL)
2130 defprinter = name;
2131 else if ((defprinter = cupsGetDefault2(http)) != NULL)
2132 {
2133 strlcpy(name, defprinter, sizeof(name));
2134 defprinter = name;
2135 }
080811b1
MS
2136
2137 if (defprinter)
ef416fc2 2138 {
2139 /*
38e73f87 2140 * Separate printer and instance name...
ef416fc2 2141 */
2142
ef416fc2 2143 if ((instance = strchr(name, '/')) != NULL)
2144 *instance++ = '\0';
2145
2146 /*
2147 * Lookup the printer and instance and make it the default...
2148 */
2149
7536de1a 2150 if ((dest = cupsGetDest(name, instance, data.num_dests, data.dests)) != NULL)
ef416fc2 2151 dest->is_default = 1;
2152 }
2153 else
ef416fc2 2154 instance = NULL;
ef416fc2 2155
2156 /*
b423cd4c 2157 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
ef416fc2 2158 */
2159
2160 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
7536de1a 2161 data.num_dests = cups_get_dests(filename, NULL, NULL, user_default != NULL, data.num_dests, &data.dests);
ef416fc2 2162
2163 if ((home = getenv("HOME")) != NULL)
2164 {
b423cd4c 2165 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
b423cd4c 2166
7536de1a 2167 data.num_dests = cups_get_dests(filename, NULL, NULL, user_default != NULL, data.num_dests, &data.dests);
ef416fc2 2168 }
2169
2170 /*
2171 * Validate the current default destination - this prevents old
b423cd4c 2172 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
ef416fc2 2173 * pointing to a non-existent printer or class...
2174 */
2175
2176 if (num_reals)
2177 {
2178 /*
2179 * See if we have a default printer...
2180 */
2181
7536de1a 2182 if ((dest = cupsGetDest(NULL, NULL, data.num_dests, data.dests)) != NULL)
ef416fc2 2183 {
2184 /*
2185 * Have a default; see if it is real...
2186 */
2187
5489ad43
MS
2188 if (!cupsGetDest(dest->name, NULL, num_reals, reals))
2189 {
2190 /*
2191 * Remove the non-real printer from the list, since we don't want jobs
2192 * going to an unexpected printer... (<rdar://problem/14216472>)
2193 */
ef416fc2 2194
7536de1a 2195 data.num_dests = cupsRemoveDest(dest->name, dest->instance, data.num_dests, &data.dests);
5489ad43 2196 }
ef416fc2 2197 }
2198
2199 /*
2200 * Free memory...
2201 */
2202
2203 free(reals);
2204 }
2205
2206 /*
2207 * Return the number of destinations...
2208 */
2209
7536de1a
MS
2210 *dests = data.dests;
2211
2212 if (data.num_dests > 0)
cb7f98ee 2213 _cupsSetError(IPP_STATUS_OK, NULL, 0);
1ff0402e 2214
fb963b8d
MS
2215 DEBUG_printf(("1cupsGetDests2: Returning %d destinations.", data.num_dests));
2216
7536de1a 2217 return (data.num_dests);
ef416fc2 2218}
2219
2220
a4924f6c
MS
2221/*
2222 * 'cupsGetNamedDest()' - Get options for the named destination.
2223 *
2224 * This function is optimized for retrieving a single destination and should
98d88c8d
MS
2225 * be used instead of @link cupsGetDests2@ and @link cupsGetDest@ when you
2226 * either know the name of the destination or want to print to the default
2227 * destination. If @code NULL@ is returned, the destination does not exist or
2228 * there is no default destination.
a4924f6c 2229 *
5a738aea
MS
2230 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
2231 * server will be used.
a4924f6c 2232 *
5a738aea
MS
2233 * If "name" is @code NULL@, the default printer for the current user will be
2234 * returned.
a4924f6c 2235 *
5a738aea
MS
2236 * The returned destination must be freed using @link cupsFreeDests@ with a
2237 * "num_dests" value of 1.
a4924f6c 2238 *
8072030b 2239 * @since CUPS 1.4/macOS 10.6@
a4924f6c
MS
2240 */
2241
5a738aea 2242cups_dest_t * /* O - Destination or @code NULL@ */
568fa3fa
MS
2243cupsGetNamedDest(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2244 const char *name, /* I - Destination name or @code NULL@ for the default destination */
5a738aea 2245 const char *instance) /* I - Instance name or @code NULL@ */
a4924f6c 2246{
89c924d5 2247 const char *dest_name; /* Working destination name */
a4924f6c
MS
2248 cups_dest_t *dest; /* Destination */
2249 char filename[1024], /* Path to lpoptions */
2250 defname[256]; /* Default printer name */
2251 const char *home = getenv("HOME"); /* Home directory */
38e73f87 2252 int set_as_default = 0; /* Set returned destination as default */
cb7f98ee 2253 ipp_op_t op = IPP_OP_GET_PRINTER_ATTRIBUTES;
a4924f6c
MS
2254 /* IPP operation to get server ops */
2255 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
2256
2257
2a75f21b 2258 DEBUG_printf(("cupsGetNamedDest(http=%p, name=\"%s\", instance=\"%s\")", (void *)http, name, instance));
4a366251 2259
a4924f6c
MS
2260 /*
2261 * If "name" is NULL, find the default destination...
2262 */
2263
89c924d5
MS
2264 dest_name = name;
2265
2266 if (!dest_name)
a4924f6c 2267 {
38e73f87 2268 set_as_default = 1;
89c924d5 2269 dest_name = _cupsUserDefault(defname, sizeof(defname));
a4924f6c 2270
89c924d5 2271 if (dest_name)
7cf5915e
MS
2272 {
2273 char *ptr; /* Temporary pointer... */
2274
2275 if ((ptr = strchr(defname, '/')) != NULL)
2276 {
2277 *ptr++ = '\0';
2278 instance = ptr;
2279 }
2280 else
2281 instance = NULL;
2282 }
2283 else if (home)
a4924f6c
MS
2284 {
2285 /*
2286 * No default in the environment, try the user's lpoptions files...
2287 */
2288
2289 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2290
89c924d5 2291 dest_name = cups_get_default(filename, defname, sizeof(defname), &instance);
a4924f6c
MS
2292 }
2293
c536b6c5 2294 if (!dest_name)
a4924f6c
MS
2295 {
2296 /*
2297 * Still not there? Try the system lpoptions file...
2298 */
2299
89c924d5
MS
2300 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
2301 dest_name = cups_get_default(filename, defname, sizeof(defname), &instance);
a4924f6c
MS
2302 }
2303
89c924d5 2304 if (!dest_name)
a4924f6c
MS
2305 {
2306 /*
2307 * No locally-set default destination, ask the server...
2308 */
2309
cb7f98ee 2310 op = IPP_OP_CUPS_GET_DEFAULT;
4a366251
MS
2311
2312 DEBUG_puts("1cupsGetNamedDest: Asking server for default printer...");
a4924f6c 2313 }
4a366251
MS
2314 else
2315 DEBUG_printf(("1cupsGetNamedDest: Using name=\"%s\"...", name));
a4924f6c
MS
2316 }
2317
2318 /*
2319 * Get the printer's attributes...
2320 */
2321
89c924d5 2322 if (!_cupsGetDests(http, op, dest_name, &dest, 0, 0))
4a366251
MS
2323 {
2324 if (name)
2325 {
2326 _cups_namedata_t data; /* Callback data */
2327
2328 DEBUG_puts("1cupsGetNamedDest: No queue found for printer, looking on network...");
2329
2330 data.name = name;
2331 data.dest = NULL;
2332
f50db552 2333 cupsEnumDests(0, 1000, NULL, 0, 0, (cups_dest_cb_t)cups_name_cb, &data);
4a366251
MS
2334
2335 if (!data.dest)
2336 return (NULL);
2337
2338 dest = data.dest;
2339 }
2340 else
2341 return (NULL);
2342 }
2343
2a75f21b 2344 DEBUG_printf(("1cupsGetNamedDest: Got dest=%p", (void *)dest));
a4924f6c
MS
2345
2346 if (instance)
2347 dest->instance = _cupsStrAlloc(instance);
2348
38e73f87
MS
2349 if (set_as_default)
2350 dest->is_default = 1;
2351
a4924f6c
MS
2352 /*
2353 * Then add local options...
2354 */
2355
2356 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
89c924d5 2357 cups_get_dests(filename, dest_name, instance, 1, 1, &dest);
a4924f6c
MS
2358
2359 if (home)
2360 {
2361 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2362
89c924d5 2363 cups_get_dests(filename, dest_name, instance, 1, 1, &dest);
a4924f6c
MS
2364 }
2365
2366 /*
2367 * Return the result...
2368 */
2369
2370 return (dest);
2371}
2372
2373
f7deaa1a 2374/*
2375 * 'cupsRemoveDest()' - Remove a destination from the destination list.
2376 *
2377 * Removing a destination/instance does not delete the class or printer
2378 * queue, merely the lpoptions for that destination/instance. Use the
5a738aea
MS
2379 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
2380 * options for the user.
f7deaa1a 2381 *
8072030b 2382 * @since CUPS 1.3/macOS 10.5@
f7deaa1a 2383 */
2384
2385int /* O - New number of destinations */
2386cupsRemoveDest(const char *name, /* I - Destination name */
5a738aea 2387 const char *instance, /* I - Instance name or @code NULL@ */
f7deaa1a 2388 int num_dests, /* I - Number of destinations */
2389 cups_dest_t **dests) /* IO - Destinations */
2390{
2391 int i; /* Index into destinations */
2392 cups_dest_t *dest; /* Pointer to destination */
2393
2394
2395 /*
2396 * Find the destination...
2397 */
2398
2399 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
2400 return (num_dests);
2401
2402 /*
2403 * Free memory...
2404 */
2405
2e4ff8af
MS
2406 _cupsStrFree(dest->name);
2407 _cupsStrFree(dest->instance);
f7deaa1a 2408 cupsFreeOptions(dest->num_options, dest->options);
2409
2410 /*
2411 * Remove the destination from the array...
2412 */
2413
2414 num_dests --;
2415
7e86f2f6 2416 i = (int)(dest - *dests);
f7deaa1a 2417
2418 if (i < num_dests)
7e86f2f6 2419 memmove(dest, dest + 1, (size_t)(num_dests - i) * sizeof(cups_dest_t));
f7deaa1a 2420
2421 return (num_dests);
2422}
2423
2424
2425/*
3d052e43 2426 * 'cupsSetDefaultDest()' - Set the default destination.
f7deaa1a 2427 *
8072030b 2428 * @since CUPS 1.3/macOS 10.5@
f7deaa1a 2429 */
2430
2431void
2432cupsSetDefaultDest(
2433 const char *name, /* I - Destination name */
5a738aea 2434 const char *instance, /* I - Instance name or @code NULL@ */
f7deaa1a 2435 int num_dests, /* I - Number of destinations */
2436 cups_dest_t *dests) /* I - Destinations */
2437{
2438 int i; /* Looping var */
2439 cups_dest_t *dest; /* Current destination */
2440
2441
2442 /*
2443 * Range check input...
2444 */
2445
2446 if (!name || num_dests <= 0 || !dests)
2447 return;
2448
2449 /*
2450 * Loop through the array and set the "is_default" flag for the matching
2451 * destination...
2452 */
2453
2454 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
88f9aafc 2455 dest->is_default = !_cups_strcasecmp(name, dest->name) &&
f7deaa1a 2456 ((!instance && !dest->instance) ||
2457 (instance && dest->instance &&
88f9aafc 2458 !_cups_strcasecmp(instance, dest->instance)));
f7deaa1a 2459}
2460
2461
ef416fc2 2462/*
2463 * 'cupsSetDests()' - Save the list of destinations for the default server.
2464 *
2465 * This function saves the destinations to /etc/cups/lpoptions when run
b423cd4c 2466 * as root and ~/.cups/lpoptions when run as a normal user.
98d88c8d
MS
2467 *
2468 * @exclude all@
ef416fc2 2469 */
2470
2471void
2472cupsSetDests(int num_dests, /* I - Number of destinations */
2473 cups_dest_t *dests) /* I - Destinations */
2474{
3d052e43 2475 cupsSetDests2(CUPS_HTTP_DEFAULT, num_dests, dests);
ef416fc2 2476}
2477
2478
2479/*
2480 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
2481 *
2482 * This function saves the destinations to /etc/cups/lpoptions when run
b423cd4c 2483 * as root and ~/.cups/lpoptions when run as a normal user.
ef416fc2 2484 *
8072030b 2485 * @since CUPS 1.1.21/macOS 10.4@
ef416fc2 2486 */
2487
2488int /* O - 0 on success, -1 on error */
568fa3fa 2489cupsSetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
ef416fc2 2490 int num_dests, /* I - Number of destinations */
2491 cups_dest_t *dests) /* I - Destinations */
2492{
2493 int i, j; /* Looping vars */
2494 int wrote; /* Wrote definition? */
2495 cups_dest_t *dest; /* Current destination */
2496 cups_option_t *option; /* Current option */
8ca02f3c 2497 _ipp_option_t *match; /* Matching attribute for option */
ef416fc2 2498 FILE *fp; /* File pointer */
b86bc4cf 2499#ifndef WIN32
ef416fc2 2500 const char *home; /* HOME environment variable */
b86bc4cf 2501#endif /* WIN32 */
ef416fc2 2502 char filename[1024]; /* lpoptions file */
2503 int num_temps; /* Number of temporary destinations */
82cc1f9a 2504 cups_dest_t *temps = NULL, /* Temporary destinations */
ef416fc2 2505 *temp; /* Current temporary dest */
2506 const char *val; /* Value of temporary option */
3d052e43 2507 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
ef416fc2 2508
2509
2510 /*
2511 * Range check the input...
2512 */
2513
3d052e43 2514 if (!num_dests || !dests)
ef416fc2 2515 return (-1);
2516
2517 /*
2518 * Get the server destinations...
2519 */
2520
f50db552 2521 num_temps = _cupsGetDests(http, IPP_OP_CUPS_GET_PRINTERS, NULL, &temps, 0, 0);
426c6a59 2522
cb7f98ee 2523 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE)
426c6a59
MS
2524 {
2525 cupsFreeDests(num_temps, temps);
2526 return (-1);
2527 }
ef416fc2 2528
2529 /*
2530 * Figure out which file to write to...
2531 */
2532
2533 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
2534
2535#ifndef WIN32
2536 if (getuid())
2537 {
2538 /*
2539 * Merge in server defaults...
2540 */
2541
38e73f87 2542 num_temps = cups_get_dests(filename, NULL, NULL, 0, num_temps, &temps);
ef416fc2 2543
2544 /*
2545 * Point to user defaults...
2546 */
2547
2548 if ((home = getenv("HOME")) != NULL)
b423cd4c 2549 {
b423cd4c 2550 /*
2551 * Create ~/.cups subdirectory...
2552 */
2553
2554 snprintf(filename, sizeof(filename), "%s/.cups", home);
2555 if (access(filename, 0))
2556 mkdir(filename, 0700);
2557
2558 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2559 }
ef416fc2 2560 }
2561#endif /* !WIN32 */
2562
2563 /*
2564 * Try to open the file...
2565 */
2566
2567 if ((fp = fopen(filename, "w")) == NULL)
2568 {
2569 cupsFreeDests(num_temps, temps);
2570 return (-1);
2571 }
2572
d6ae789d 2573#ifndef WIN32
2574 /*
2575 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2576 * file...
2577 */
2578
2579 if (!getuid())
2580 fchmod(fileno(fp), 0644);
2581#endif /* !WIN32 */
2582
ef416fc2 2583 /*
2584 * Write each printer; each line looks like:
2585 *
2586 * Dest name[/instance] options
2587 * Default name[/instance] options
2588 */
2589
2590 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
2591 if (dest->instance != NULL || dest->num_options != 0 || dest->is_default)
2592 {
2593 if (dest->is_default)
2594 {
2595 fprintf(fp, "Default %s", dest->name);
2596 if (dest->instance)
2597 fprintf(fp, "/%s", dest->instance);
2598
2599 wrote = 1;
2600 }
2601 else
2602 wrote = 0;
2603
2604 if ((temp = cupsGetDest(dest->name, dest->instance, num_temps, temps)) == NULL)
2605 temp = cupsGetDest(dest->name, NULL, num_temps, temps);
2606
2607 for (j = dest->num_options, option = dest->options; j > 0; j --, option ++)
2608 {
8ca02f3c 2609 /*
2610 * See if this option is a printer attribute; if so, skip it...
2611 */
2612
2613 if ((match = _ippFindOption(option->name)) != NULL &&
2614 match->group_tag == IPP_TAG_PRINTER)
2615 continue;
2616
ef416fc2 2617 /*
2618 * See if the server/global options match these; if so, don't
2619 * write 'em.
2620 */
2621
8ca02f3c 2622 if (temp &&
2623 (val = cupsGetOption(option->name, temp->num_options,
2624 temp->options)) != NULL &&
88f9aafc 2625 !_cups_strcasecmp(val, option->value))
8ca02f3c 2626 continue;
ef416fc2 2627
2628 /*
2629 * Options don't match, write to the file...
2630 */
2631
2632 if (!wrote)
2633 {
2634 fprintf(fp, "Dest %s", dest->name);
2635 if (dest->instance)
2636 fprintf(fp, "/%s", dest->instance);
2637 wrote = 1;
2638 }
88f9aafc 2639
ef416fc2 2640 if (option->value[0])
2641 {
8ca02f3c 2642 if (strchr(option->value, ' ') ||
2643 strchr(option->value, '\\') ||
2644 strchr(option->value, '\"') ||
2645 strchr(option->value, '\''))
2646 {
2647 /*
2648 * Quote the value...
2649 */
2650
2651 fprintf(fp, " %s=\"", option->name);
2652
2653 for (val = option->value; *val; val ++)
2654 {
2655 if (strchr("\"\'\\", *val))
2656 putc('\\', fp);
2657
2658 putc(*val, fp);
2659 }
2660
2661 putc('\"', fp);
2662 }
2663 else
2664 {
2665 /*
2666 * Store the literal value...
2667 */
2668
ef416fc2 2669 fprintf(fp, " %s=%s", option->name, option->value);
8ca02f3c 2670 }
ef416fc2 2671 }
2672 else
2673 fprintf(fp, " %s", option->name);
2674 }
2675
2676 if (wrote)
2677 fputs("\n", fp);
2678 }
2679
2680 /*
fa73b229 2681 * Free the temporary destinations and close the file...
ef416fc2 2682 */
2683
2684 cupsFreeDests(num_temps, temps);
2685
fa73b229 2686 fclose(fp);
2687
080811b1
MS
2688#ifdef __APPLE__
2689 /*
2690 * Set the default printer for this location - this allows command-line
2691 * and GUI applications to share the same default destination...
2692 */
2693
2694 if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) != NULL)
f14324a7
MS
2695 {
2696 CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault,
2697 dest->name,
2698 kCFStringEncodingUTF8);
2699 /* Default printer name */
2700
2701 if (name)
2702 {
2703 _cupsAppleSetDefaultPrinter(name);
2704 CFRelease(name);
2705 }
2706 }
080811b1
MS
2707#endif /* __APPLE__ */
2708
fa73b229 2709#ifdef HAVE_NOTIFY_POST
ef416fc2 2710 /*
d4874933 2711 * Send a notification so that macOS applications can know about the
fa73b229 2712 * change, too.
ef416fc2 2713 */
2714
fa73b229 2715 notify_post("com.apple.printerListChange");
2716#endif /* HAVE_NOTIFY_POST */
ef416fc2 2717
2718 return (0);
2719}
2720
2721
38e73f87
MS
2722/*
2723 * '_cupsUserDefault()' - Get the user default printer from environment
2724 * variables and location information.
2725 */
2726
2727char * /* O - Default printer or NULL */
2728_cupsUserDefault(char *name, /* I - Name buffer */
2729 size_t namesize) /* I - Size of name buffer */
2730{
2731 const char *env; /* LPDEST or PRINTER env variable */
2732#ifdef __APPLE__
f14324a7 2733 CFStringRef locprinter; /* Last printer as this location */
38e73f87
MS
2734#endif /* __APPLE__ */
2735
2736
2737 if ((env = getenv("LPDEST")) == NULL)
2738 if ((env = getenv("PRINTER")) != NULL && !strcmp(env, "lp"))
2739 env = NULL;
2740
2741 if (env)
2742 {
2743 strlcpy(name, env, namesize);
2744 return (name);
2745 }
2746
2747#ifdef __APPLE__
2748 /*
2749 * Use location-based defaults if "use last printer" is selected in the
2750 * system preferences...
2751 */
2752
f14324a7 2753 if ((locprinter = _cupsAppleCopyDefaultPrinter()) != NULL)
38e73f87 2754 {
7e86f2f6 2755 CFStringGetCString(locprinter, name, (CFIndex)namesize, kCFStringEncodingUTF8);
f14324a7
MS
2756 CFRelease(locprinter);
2757 }
38e73f87
MS
2758 else
2759 name[0] = '\0';
2760
f14324a7 2761 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name));
38e73f87
MS
2762
2763 return (*name ? name : NULL);
2764
2765#else
2766 /*
2767 * No location-based defaults on this platform...
2768 */
2769
2770 name[0] = '\0';
2771 return (NULL);
2772#endif /* __APPLE__ */
2773}
2774
2775
9688061e 2776#if _CUPS_LOCATION_DEFAULTS
06d4e77b
MS
2777/*
2778 * 'appleCopyLocations()' - Copy the location history array.
2779 */
2780
2781static CFArrayRef /* O - Location array or NULL */
2782appleCopyLocations(void)
2783{
2784 CFArrayRef locations; /* Location array */
2785
2786
2787 /*
2788 * Look up the location array in the preferences...
2789 */
2790
f14324a7
MS
2791 if ((locations = CFPreferencesCopyAppValue(kLastUsedPrintersKey,
2792 kCUPSPrintingPrefs)) == NULL)
06d4e77b
MS
2793 return (NULL);
2794
2795 if (CFGetTypeID(locations) != CFArrayGetTypeID())
2796 {
2797 CFRelease(locations);
2798 return (NULL);
2799 }
2800
2801 return (locations);
2802}
2803
2804
749b1e90
MS
2805/*
2806 * 'appleCopyNetwork()' - Get the network ID for the current location.
2807 */
2808
2809static CFStringRef /* O - Network ID */
2810appleCopyNetwork(void)
2811{
2812 SCDynamicStoreRef dynamicStore; /* System configuration data */
2813 CFStringRef key; /* Current network configuration key */
2814 CFDictionaryRef ip_dict; /* Network configuration data */
2815 CFStringRef network = NULL; /* Current network ID */
88f9aafc 2816
749b1e90 2817
f14324a7 2818 if ((dynamicStore = SCDynamicStoreCreate(NULL, CFSTR("libcups"), NULL,
749b1e90
MS
2819 NULL)) != NULL)
2820 {
f14324a7
MS
2821 /*
2822 * First use the IPv6 router address, if available, since that will generally
2823 * be a globally-unique link-local address.
2824 */
2825
749b1e90 2826 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
f14324a7 2827 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv6)) != NULL)
749b1e90
MS
2828 {
2829 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2830 {
2831 if ((network = CFDictionaryGetValue(ip_dict,
f14324a7 2832 kSCPropNetIPv6Router)) != NULL)
749b1e90
MS
2833 CFRetain(network);
2834
2835 CFRelease(ip_dict);
2836 }
2837
2838 CFRelease(key);
2839 }
2840
f14324a7
MS
2841 /*
2842 * If that doesn't work, try the IPv4 router address. This isn't as unique
2843 * and will likely be a 10.x.y.z or 192.168.y.z address...
2844 */
2845
2846 if (!network)
2847 {
2848 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
2849 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4)) != NULL)
2850 {
2851 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2852 {
2853 if ((network = CFDictionaryGetValue(ip_dict,
2854 kSCPropNetIPv4Router)) != NULL)
2855 CFRetain(network);
2856
2857 CFRelease(ip_dict);
2858 }
2859
2860 CFRelease(key);
2861 }
2862 }
2863
749b1e90
MS
2864 CFRelease(dynamicStore);
2865 }
2866
2867 return (network);
2868}
9688061e 2869#endif /* _CUPS_LOCATION_DEFAULTS */
749b1e90
MS
2870
2871
9688061e 2872#ifdef __APPLE__
426c6a59
MS
2873/*
2874 * 'appleGetPaperSize()' - Get the default paper size.
2875 */
2876
5a9febac 2877static char * /* O - Default paper size */
d649be59
MS
2878appleGetPaperSize(char *name, /* I - Paper size name buffer */
2879 size_t namesize) /* I - Size of buffer */
426c6a59 2880{
54afec33 2881 CFStringRef defaultPaperID; /* Default paper ID */
6961465f 2882 pwg_media_t *pwgmedia; /* PWG media size */
426c6a59
MS
2883
2884
c8fef167 2885 defaultPaperID = _cupsAppleCopyDefaultPaperID();
426c6a59 2886 if (!defaultPaperID ||
557dde9f 2887 CFGetTypeID(defaultPaperID) != CFStringGetTypeID() ||
d649be59 2888 !CFStringGetCString(defaultPaperID, name, (CFIndex)namesize, kCFStringEncodingUTF8))
426c6a59 2889 name[0] = '\0';
6961465f 2890 else if ((pwgmedia = pwgMediaForLegacy(name)) != NULL)
c168a833 2891 strlcpy(name, pwgmedia->pwg, namesize);
426c6a59
MS
2892
2893 if (defaultPaperID)
2894 CFRelease(defaultPaperID);
2895
2896 return (name);
2897}
9688061e 2898#endif /* __APPLE__ */
426c6a59
MS
2899
2900
9688061e 2901#if _CUPS_LOCATION_DEFAULTS
080811b1
MS
2902/*
2903 * 'appleGetPrinter()' - Get a printer from the history array.
2904 */
2905
2906static CFStringRef /* O - Printer name or NULL */
2907appleGetPrinter(CFArrayRef locations, /* I - Location array */
2908 CFStringRef network, /* I - Network name */
2909 CFIndex *locindex) /* O - Index in array */
2910{
2911 CFIndex i, /* Looping var */
2912 count; /* Number of locations */
2913 CFDictionaryRef location; /* Current location */
2914 CFStringRef locnetwork, /* Current network */
2915 locprinter; /* Current printer */
2916
2917
2918 for (i = 0, count = CFArrayGetCount(locations); i < count; i ++)
2919 if ((location = CFArrayGetValueAtIndex(locations, i)) != NULL &&
2920 CFGetTypeID(location) == CFDictionaryGetTypeID())
2921 {
2922 if ((locnetwork = CFDictionaryGetValue(location,
2923 kLocationNetworkKey)) != NULL &&
2924 CFGetTypeID(locnetwork) == CFStringGetTypeID() &&
2925 CFStringCompare(network, locnetwork, 0) == kCFCompareEqualTo &&
2926 (locprinter = CFDictionaryGetValue(location,
2927 kLocationPrinterIDKey)) != NULL &&
2928 CFGetTypeID(locprinter) == CFStringGetTypeID())
2929 {
2930 if (locindex)
2931 *locindex = i;
2932
2933 return (locprinter);
2934 }
2935 }
2936
2937 return (NULL);
2938}
9688061e 2939#endif /* _CUPS_LOCATION_DEFAULTS */
080811b1
MS
2940
2941
426c6a59
MS
2942/*
2943 * 'cups_add_dest()' - Add a destination to the array.
2944 *
2945 * Unlike cupsAddDest(), this function does not check for duplicates.
2946 */
2947
2948static cups_dest_t * /* O - New destination */
2949cups_add_dest(const char *name, /* I - Name of destination */
2950 const char *instance, /* I - Instance or NULL */
2951 int *num_dests, /* IO - Number of destinations */
2952 cups_dest_t **dests) /* IO - Destinations */
2953{
2954 int insert, /* Insertion point */
2955 diff; /* Result of comparison */
2956 cups_dest_t *dest; /* Destination pointer */
2957
2958
2959 /*
2960 * Add new destination...
2961 */
2962
2963 if (*num_dests == 0)
2964 dest = malloc(sizeof(cups_dest_t));
2965 else
7e86f2f6 2966 dest = realloc(*dests, sizeof(cups_dest_t) * (size_t)(*num_dests + 1));
426c6a59
MS
2967
2968 if (!dest)
2969 return (NULL);
2970
2971 *dests = dest;
2972
2973 /*
2974 * Find where to insert the destination...
2975 */
2976
2977 if (*num_dests == 0)
2978 insert = 0;
2979 else
2980 {
2981 insert = cups_find_dest(name, instance, *num_dests, *dests, *num_dests - 1,
2982 &diff);
2983
2984 if (diff > 0)
2985 insert ++;
2986 }
2987
2988 /*
2989 * Move the array elements as needed...
2990 */
2991
2992 if (insert < *num_dests)
7e86f2f6 2993 memmove(*dests + insert + 1, *dests + insert, (size_t)(*num_dests - insert) * sizeof(cups_dest_t));
426c6a59
MS
2994
2995 (*num_dests) ++;
2996
2997 /*
2998 * Initialize the destination...
2999 */
3000
3001 dest = *dests + insert;
3002 dest->name = _cupsStrAlloc(name);
3003 dest->instance = _cupsStrAlloc(instance);
3004 dest->is_default = 0;
3005 dest->num_options = 0;
3006 dest->options = (cups_option_t *)0;
3007
3008 return (dest);
3009}
3010
3011
9c80ffa2
MS
3012# ifdef __BLOCKS__
3013/*
3014 * 'cups_block_cb()' - Enumeration callback for block API.
3015 */
3016
3017static int /* O - 1 to continue, 0 to stop */
3018cups_block_cb(
3019 cups_dest_block_t block, /* I - Block */
dcb445bc
MS
3020 unsigned flags, /* I - Destination flags */
3021 cups_dest_t *dest) /* I - Destination */
9c80ffa2 3022{
dcb445bc 3023 return ((block)(flags, dest));
9c80ffa2
MS
3024}
3025# endif /* __BLOCKS__ */
3026
3027
426c6a59
MS
3028/*
3029 * 'cups_compare_dests()' - Compare two destinations.
3030 */
3031
3032static int /* O - Result of comparison */
3033cups_compare_dests(cups_dest_t *a, /* I - First destination */
3034 cups_dest_t *b) /* I - Second destination */
3035{
3036 int diff; /* Difference */
3037
3038
88f9aafc 3039 if ((diff = _cups_strcasecmp(a->name, b->name)) != 0)
426c6a59
MS
3040 return (diff);
3041 else if (a->instance && b->instance)
88f9aafc 3042 return (_cups_strcasecmp(a->instance, b->instance));
426c6a59
MS
3043 else
3044 return ((a->instance && !b->instance) - (!a->instance && b->instance));
3045}
3046
3047
a29fd7dd
MS
3048#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3049# ifdef HAVE_DNSSD
dcb445bc
MS
3050/*
3051 * 'cups_dnssd_browse_cb()' - Browse for printers.
3052 */
3053
3054static void
3055cups_dnssd_browse_cb(
3056 DNSServiceRef sdRef, /* I - Service reference */
3057 DNSServiceFlags flags, /* I - Option flags */
3058 uint32_t interfaceIndex, /* I - Interface number */
3059 DNSServiceErrorType errorCode, /* I - Error, if any */
3060 const char *serviceName, /* I - Name of service/device */
3061 const char *regtype, /* I - Type of service */
3062 const char *replyDomain, /* I - Service domain */
3063 void *context) /* I - Enumeration data */
3064{
3065 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3066 /* Enumeration data */
3067
3068
807315e6 3069 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
3070
3071 /*
3072 * Don't do anything on error...
3073 */
3074
3075 if (errorCode != kDNSServiceErr_NoError)
3076 return;
3077
3078 /*
3079 * Get the device...
3080 */
3081
3082 cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
3083}
3084
3085
a29fd7dd
MS
3086# else /* HAVE_AVAHI */
3087/*
3088 * 'cups_dnssd_browse_cb()' - Browse for printers.
3089 */
3090
3091static void
3092cups_dnssd_browse_cb(
3093 AvahiServiceBrowser *browser, /* I - Browser */
3094 AvahiIfIndex interface, /* I - Interface index (unused) */
3095 AvahiProtocol protocol, /* I - Network protocol (unused) */
3096 AvahiBrowserEvent event, /* I - What happened */
3097 const char *name, /* I - Service name */
3098 const char *type, /* I - Registration type */
3099 const char *domain, /* I - Domain */
3100 AvahiLookupResultFlags flags, /* I - Flags */
3101 void *context) /* I - Devices array */
3102{
37e7e6e0 3103#ifdef DEBUG
a29fd7dd
MS
3104 AvahiClient *client = avahi_service_browser_get_client(browser);
3105 /* Client information */
37e7e6e0 3106#endif /* DEBUG */
a29fd7dd
MS
3107 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3108 /* Enumeration data */
3109
3110
3111 (void)interface;
3112 (void)protocol;
3113 (void)context;
3114
657c5b5f
MS
3115 DEBUG_printf(("cups_dnssd_browse_cb(..., name=\"%s\", type=\"%s\", domain=\"%s\", ...);", name, type, domain));
3116
a29fd7dd
MS
3117 switch (event)
3118 {
3119 case AVAHI_BROWSER_FAILURE:
657c5b5f 3120 DEBUG_printf(("cups_dnssd_browse_cb: %s", avahi_strerror(avahi_client_errno(client))));
a29fd7dd
MS
3121 avahi_simple_poll_quit(data->simple_poll);
3122 break;
3123
3124 case AVAHI_BROWSER_NEW:
3125 /*
3126 * This object is new on the network.
3127 */
3128
3129 if (flags & AVAHI_LOOKUP_RESULT_LOCAL)
3130 {
3131 /*
3132 * This comes from the local machine so ignore it.
3133 */
3134
657c5b5f 3135 DEBUG_printf(("cups_dnssd_browse_cb: Ignoring local service \"%s\".", name));
a29fd7dd
MS
3136 }
3137 else
3138 {
3139 /*
3140 * Create a device entry for it if it doesn't yet exist.
3141 */
3142
3143 cups_dnssd_get_device(data, name, type, domain);
3144 }
3145 break;
3146
657c5b5f
MS
3147 case AVAHI_BROWSER_REMOVE :
3148 case AVAHI_BROWSER_CACHE_EXHAUSTED :
3149 break;
3150
3151 case AVAHI_BROWSER_ALL_FOR_NOW :
3152 DEBUG_puts("cups_dnssd_browse_cb: ALL_FOR_NOW");
3153 data->browsers --;
a29fd7dd
MS
3154 break;
3155 }
3156}
3157
3158
3159/*
3160 * 'cups_dnssd_client_cb()' - Avahi client callback function.
3161 */
3162
3163static void
3164cups_dnssd_client_cb(
3165 AvahiClient *client, /* I - Client information (unused) */
3166 AvahiClientState state, /* I - Current state */
3167 void *context) /* I - User data (unused) */
3168{
3169 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3170 /* Enumeration data */
3171
3172
3173 (void)client;
3174
657c5b5f
MS
3175 DEBUG_printf(("cups_dnssd_client_cb(client=%p, state=%d, context=%p)", client, state, context));
3176
a29fd7dd
MS
3177 /*
3178 * If the connection drops, quit.
3179 */
3180
3181 if (state == AVAHI_CLIENT_FAILURE)
3182 {
3183 DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
3184 avahi_simple_poll_quit(data->simple_poll);
3185 }
3186}
3187# endif /* HAVE_DNSSD */
3188
3189
dcb445bc
MS
3190/*
3191 * 'cups_dnssd_compare_device()' - Compare two devices.
3192 */
3193
3194static int /* O - Result of comparison */
3195cups_dnssd_compare_devices(
3196 _cups_dnssd_device_t *a, /* I - First device */
3197 _cups_dnssd_device_t *b) /* I - Second device */
3198{
3199 return (strcmp(a->dest.name, b->dest.name));
3200}
3201
3202
3203/*
3204 * 'cups_dnssd_free_device()' - Free the memory used by a device.
3205 */
3206
3207static void
3208cups_dnssd_free_device(
3209 _cups_dnssd_device_t *device, /* I - Device */
3210 _cups_dnssd_data_t *data) /* I - Enumeration data */
3211{
807315e6 3212 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", (void *)device, device->dest.name, (void *)data));
dcb445bc 3213
a29fd7dd 3214# ifdef HAVE_DNSSD
dcb445bc
MS
3215 if (device->ref)
3216 DNSServiceRefDeallocate(device->ref);
a29fd7dd
MS
3217# else /* HAVE_AVAHI */
3218 if (device->ref)
3219 avahi_record_browser_free(device->ref);
3220# endif /* HAVE_DNSSD */
dcb445bc
MS
3221
3222 _cupsStrFree(device->domain);
3223 _cupsStrFree(device->fullName);
3224 _cupsStrFree(device->regtype);
3225 _cupsStrFree(device->dest.name);
3226
3227 cupsFreeOptions(device->dest.num_options, device->dest.options);
3228
3229 free(device);
3230}
3231
3232
3233/*
3234 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
3235 */
3236
3237static _cups_dnssd_device_t * /* O - Device */
3238cups_dnssd_get_device(
3239 _cups_dnssd_data_t *data, /* I - Enumeration data */
3240 const char *serviceName, /* I - Service name */
3241 const char *regtype, /* I - Registration type */
3242 const char *replyDomain) /* I - Domain name */
3243{
3244 _cups_dnssd_device_t key, /* Search key */
3245 *device; /* Device */
a2187a63 3246 char fullName[kDNSServiceMaxDomainName],
dcb445bc 3247 /* Full name for query */
a2187a63 3248 name[128]; /* Queue name */
dcb445bc
MS
3249
3250
807315e6 3251 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", regtype=\"%s\", replyDomain=\"%s\")", (void *)data, serviceName, regtype, replyDomain));
dcb445bc
MS
3252
3253 /*
3254 * See if this is an existing device...
3255 */
3256
efa72f61 3257 cups_queue_name(name, serviceName, sizeof(name));
a2187a63
MS
3258
3259 key.dest.name = name;
dcb445bc
MS
3260
3261 if ((device = cupsArrayFind(data->devices, &key)) != NULL)
3262 {
3263 /*
3264 * Yes, see if we need to do anything with this...
3265 */
3266
3267 int update = 0; /* Non-zero if we need to update */
3268
3269 if (!_cups_strcasecmp(replyDomain, "local.") &&
3270 _cups_strcasecmp(device->domain, replyDomain))
3271 {
3272 /*
3273 * Update the "global" listing to use the .local domain name instead.
3274 */
3275
3276 _cupsStrFree(device->domain);
3277 device->domain = _cupsStrAlloc(replyDomain);
3278
3279 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
3280 "domain.", device->dest.name));
3281
3282 update = 1;
3283 }
3284
3285 if (!_cups_strcasecmp(regtype, "_ipps._tcp") &&
3286 _cups_strcasecmp(device->regtype, regtype))
3287 {
3288 /*
3289 * Prefer IPPS over IPP.
3290 */
3291
3292 _cupsStrFree(device->regtype);
3293 device->regtype = _cupsStrAlloc(regtype);
3294
3295 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
3296 device->dest.name));
3297
3298 update = 1;
3299 }
3300
3301 if (!update)
3302 {
3303 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
3304 device->dest.name));
3305 return (device);
3306 }
3307 }
3308 else
3309 {
3310 /*
3311 * No, add the device...
3312 */
3313
3314 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
3315 "'%s'.", serviceName,
3316 !strcmp(regtype, "_ipps._tcp") ? "IPPS" : "IPP",
3317 replyDomain));
3318
3319 device = calloc(sizeof(_cups_dnssd_device_t), 1);
a2187a63 3320 device->dest.name = _cupsStrAlloc(name);
dcb445bc
MS
3321 device->domain = _cupsStrAlloc(replyDomain);
3322 device->regtype = _cupsStrAlloc(regtype);
3323
a2187a63
MS
3324 device->dest.num_options = cupsAddOption("printer-info", serviceName, 0, &device->dest.options);
3325
dcb445bc
MS
3326 cupsArrayAdd(data->devices, device);
3327 }
3328
3329 /*
3330 * Set the "full name" of this service, which is used for queries...
3331 */
3332
a29fd7dd 3333# ifdef HAVE_DNSSD
a2187a63 3334 DNSServiceConstructFullName(fullName, serviceName, regtype, replyDomain);
a29fd7dd 3335# else /* HAVE_AVAHI */
a2187a63 3336 avahi_service_name_join(fullName, kDNSServiceMaxDomainName, serviceName, regtype, replyDomain);
a29fd7dd
MS
3337# endif /* HAVE_DNSSD */
3338
dcb445bc
MS
3339 _cupsStrFree(device->fullName);
3340 device->fullName = _cupsStrAlloc(fullName);
3341
3342 if (device->ref)
3343 {
a29fd7dd 3344# ifdef HAVE_DNSSD
dcb445bc 3345 DNSServiceRefDeallocate(device->ref);
a29fd7dd
MS
3346# else /* HAVE_AVAHI */
3347 avahi_record_browser_free(device->ref);
3348# endif /* HAVE_DNSSD */
3349
dcb445bc
MS
3350 device->ref = 0;
3351 }
3352
3353 if (device->state == _CUPS_DNSSD_ACTIVE)
3354 {
a2187a63
MS
3355 DEBUG_printf(("6cups_dnssd_get_device: Remove callback for \"%s\".", device->dest.name));
3356
dcb445bc
MS
3357 (*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
3358 device->state = _CUPS_DNSSD_NEW;
3359 }
3360
3361 return (device);
3362}
3363
3364
a29fd7dd 3365# ifdef HAVE_DNSSD
dcb445bc
MS
3366/*
3367 * 'cups_dnssd_local_cb()' - Browse for local printers.
3368 */
3369
3370static void
3371cups_dnssd_local_cb(
3372 DNSServiceRef sdRef, /* I - Service reference */
3373 DNSServiceFlags flags, /* I - Option flags */
3374 uint32_t interfaceIndex, /* I - Interface number */
3375 DNSServiceErrorType errorCode, /* I - Error, if any */
3376 const char *serviceName, /* I - Name of service/device */
3377 const char *regtype, /* I - Type of service */
3378 const char *replyDomain, /* I - Service domain */
3379 void *context) /* I - Devices array */
3380{
3381 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3382 /* Enumeration data */
3383 _cups_dnssd_device_t *device; /* Device */
3384
3385
807315e6 3386 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
3387
3388 /*
3389 * Only process "add" data...
3390 */
3391
3392 if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
3393 return;
3394
3395 /*
3396 * Get the device...
3397 */
3398
3399 device = cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
3400
3401 /*
3402 * Hide locally-registered devices...
3403 */
3404
3405 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
3406 serviceName));
3407
3408 if (device->ref)
3409 {
3410 DNSServiceRefDeallocate(device->ref);
3411 device->ref = 0;
3412 }
3413
3414 if (device->state == _CUPS_DNSSD_ACTIVE)
a2187a63
MS
3415 {
3416 DEBUG_printf(("6cups_dnssd_local_cb: Remove callback for \"%s\".", device->dest.name));
dcb445bc 3417 (*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
a2187a63 3418 }
dcb445bc
MS
3419
3420 device->state = _CUPS_DNSSD_LOCAL;
3421}
a29fd7dd
MS
3422# endif /* HAVE_DNSSD */
3423
3424
3425# ifdef HAVE_AVAHI
3426/*
3427 * 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
3428 *
3429 * Note: This function is needed because avahi_simple_poll_iterate is broken
3430 * and always uses a timeout of 0 (!) milliseconds.
ac032efa 3431 * (https://github.com/lathiat/avahi/issues/127)
53af7f21
MS
3432 *
3433 * @private@
a29fd7dd
MS
3434 */
3435
3436static int /* O - Number of file descriptors matching */
3437cups_dnssd_poll_cb(
3438 struct pollfd *pollfds, /* I - File descriptors */
3439 unsigned int num_pollfds, /* I - Number of file descriptors */
3440 int timeout, /* I - Timeout in milliseconds (unused) */
3441 void *context) /* I - User data (unused) */
3442{
3443 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3444 /* Enumeration data */
3445 int val; /* Return value */
3446
3447
657c5b5f
MS
3448 DEBUG_printf(("cups_dnssd_poll_cb(pollfds=%p, num_pollfds=%d, timeout=%d, context=%p)", pollfds, num_pollfds, timeout, context));
3449
a29fd7dd
MS
3450 (void)timeout;
3451
3fae3b33 3452 val = poll(pollfds, num_pollfds, _CUPS_DNSSD_MAXTIME);
657c5b5f
MS
3453
3454 DEBUG_printf(("cups_dnssd_poll_cb: poll() returned %d", val));
a29fd7dd
MS
3455
3456 if (val < 0)
3457 {
3458 DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno)));
3459 }
3460 else if (val > 0)
657c5b5f 3461 {
a29fd7dd 3462 data->got_data = 1;
657c5b5f 3463 }
a29fd7dd
MS
3464
3465 return (val);
3466}
3467# endif /* HAVE_AVAHI */
dcb445bc
MS
3468
3469
3470/*
3471 * 'cups_dnssd_query_cb()' - Process query data.
3472 */
3473
a29fd7dd 3474# ifdef HAVE_DNSSD
dcb445bc
MS
3475static void
3476cups_dnssd_query_cb(
3477 DNSServiceRef sdRef, /* I - Service reference */
3478 DNSServiceFlags flags, /* I - Data flags */
3479 uint32_t interfaceIndex, /* I - Interface */
3480 DNSServiceErrorType errorCode, /* I - Error, if any */
3481 const char *fullName, /* I - Full service name */
3482 uint16_t rrtype, /* I - Record type */
3483 uint16_t rrclass, /* I - Record class */
3484 uint16_t rdlen, /* I - Length of record data */
3485 const void *rdata, /* I - Record data */
3486 uint32_t ttl, /* I - Time-to-live */
3487 void *context) /* I - Enumeration data */
3488{
a29fd7dd
MS
3489# else /* HAVE_AVAHI */
3490static void
3491cups_dnssd_query_cb(
3492 AvahiRecordBrowser *browser, /* I - Record browser */
3493 AvahiIfIndex interfaceIndex,
3494 /* I - Interface index (unused) */
3495 AvahiProtocol protocol, /* I - Network protocol (unused) */
3496 AvahiBrowserEvent event, /* I - What happened? */
3497 const char *fullName, /* I - Service name */
3498 uint16_t rrclass, /* I - Record class */
3499 uint16_t rrtype, /* I - Record type */
3500 const void *rdata, /* I - TXT record */
3501 size_t rdlen, /* I - Length of TXT record */
3502 AvahiLookupResultFlags flags, /* I - Flags */
3503 void *context) /* I - Enumeration data */
3504{
37e7e6e0 3505# ifdef DEBUG
a29fd7dd
MS
3506 AvahiClient *client = avahi_record_browser_get_client(browser);
3507 /* Client information */
37e7e6e0 3508# endif /* DEBUG */
a29fd7dd 3509# endif /* HAVE_DNSSD */
dcb445bc
MS
3510 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3511 /* Enumeration data */
a2187a63
MS
3512 char serviceName[256],/* Service name */
3513 name[128], /* Queue name */
dcb445bc
MS
3514 *ptr; /* Pointer into string */
3515 _cups_dnssd_device_t dkey, /* Search key */
3516 *device; /* Device */
3517
3518
a29fd7dd 3519# ifdef HAVE_DNSSD
807315e6 3520 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
3521
3522 /*
3523 * Only process "add" data...
3524 */
3525
3526 if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
3527 return;
3528
a29fd7dd 3529# else /* HAVE_AVAHI */
657c5b5f 3530 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
3531
3532 /*
3533 * Only process "add" data...
3534 */
3535
3536 if (event != AVAHI_BROWSER_NEW)
3537 {
3538 if (event == AVAHI_BROWSER_FAILURE)
657c5b5f 3539 DEBUG_printf(("cups_dnssd_query_cb: %s", avahi_strerror(avahi_client_errno(client))));
a29fd7dd
MS
3540
3541 return;
3542 }
3543# endif /* HAVE_DNSSD */
3544
dcb445bc
MS
3545 /*
3546 * Lookup the service in the devices array.
3547 */
3548
a2187a63 3549 cups_dnssd_unquote(serviceName, fullName, sizeof(serviceName));
dcb445bc 3550
a2187a63 3551 if ((ptr = strstr(serviceName, "._")) != NULL)
dcb445bc
MS
3552 *ptr = '\0';
3553
efa72f61 3554 cups_queue_name(name, serviceName, sizeof(name));
a2187a63
MS
3555
3556 dkey.dest.name = name;
3557
3558 if ((device = cupsArrayFind(data->devices, &dkey)) != NULL && device->state == _CUPS_DNSSD_NEW)
dcb445bc
MS
3559 {
3560 /*
a29fd7dd 3561 * Found it, pull out the make and model from the TXT record and save it...
dcb445bc
MS
3562 */
3563
3564 const uint8_t *txt, /* Pointer into data */
3565 *txtnext, /* Next key/value pair */
3566 *txtend; /* End of entire TXT record */
3567 uint8_t txtlen; /* Length of current key/value pair */
3568 char key[256], /* Key string */
3569 value[256], /* Value string */
3570 make_and_model[512],
3571 /* Manufacturer and model */
3572 model[256], /* Model */
3573 uriname[1024], /* Name for URI */
3574 uri[1024]; /* Printer URI */
f50db552 3575 cups_ptype_t type = CUPS_PRINTER_DISCOVERED | CUPS_PRINTER_BW;
a29fd7dd
MS
3576 /* Printer type */
3577 int saw_printer_type = 0;
3578 /* Did we see a printer-type key? */
dcb445bc
MS
3579
3580 device->state = _CUPS_DNSSD_PENDING;
3581 make_and_model[0] = '\0';
dcb445bc 3582
5a9febac 3583 strlcpy(model, "Unknown", sizeof(model));
dcb445bc
MS
3584
3585 for (txt = rdata, txtend = txt + rdlen;
3586 txt < txtend;
3587 txt = txtnext)
3588 {
3589 /*
3590 * Read a key/value pair starting with an 8-bit length. Since the
3591 * length is 8 bits and the size of the key/value buffers is 256, we
3592 * don't need to check for overflow...
3593 */
3594
3595 txtlen = *txt++;
3596
3597 if (!txtlen || (txt + txtlen) > txtend)
3598 break;
3599
3600 txtnext = txt + txtlen;
3601
3602 for (ptr = key; txt < txtnext && *txt != '='; txt ++)
7e86f2f6 3603 *ptr++ = (char)*txt;
dcb445bc
MS
3604 *ptr = '\0';
3605
3606 if (txt < txtnext && *txt == '=')
3607 {
3608 txt ++;
3609
3610 if (txt < txtnext)
07623986 3611 memcpy(value, txt, (size_t)(txtnext - txt));
dcb445bc
MS
3612 value[txtnext - txt] = '\0';
3613
3614 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key, value));
3615 }
3616 else
3617 {
3618 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key));
3619 continue;
3620 }
3621
3622 if (!_cups_strcasecmp(key, "usb_MFG") ||
3623 !_cups_strcasecmp(key, "usb_MANU") ||
3624 !_cups_strcasecmp(key, "usb_MANUFACTURER"))
5a9febac 3625 strlcpy(make_and_model, value, sizeof(make_and_model));
dcb445bc
MS
3626 else if (!_cups_strcasecmp(key, "usb_MDL") ||
3627 !_cups_strcasecmp(key, "usb_MODEL"))
5a9febac 3628 strlcpy(model, value, sizeof(model));
dcb445bc
MS
3629 else if (!_cups_strcasecmp(key, "product") && !strstr(value, "Ghostscript"))
3630 {
3631 if (value[0] == '(')
3632 {
3633 /*
3634 * Strip parenthesis...
3635 */
3636
3637 if ((ptr = value + strlen(value) - 1) > value && *ptr == ')')
3638 *ptr = '\0';
3639
5a9febac 3640 strlcpy(model, value + 1, sizeof(model));
dcb445bc
MS
3641 }
3642 else
5a9febac 3643 strlcpy(model, value, sizeof(model));
dcb445bc
MS
3644 }
3645 else if (!_cups_strcasecmp(key, "ty"))
3646 {
5a9febac 3647 strlcpy(model, value, sizeof(model));
dcb445bc
MS
3648
3649 if ((ptr = strchr(model, ',')) != NULL)
3650 *ptr = '\0';
3651 }
a29fd7dd
MS
3652 else if (!_cups_strcasecmp(key, "note"))
3653 device->dest.num_options = cupsAddOption("printer-location", value,
3654 device->dest.num_options,
3655 &device->dest.options);
3656 else if (!_cups_strcasecmp(key, "pdl"))
3657 {
3658 /*
3659 * Look for PDF-capable printers; only PDF-capable printers are shown.
3660 */
3661
3662 const char *start, *next; /* Pointer into value */
46385a1a
MS
3663 int have_pdf = 0, /* Have PDF? */
3664 have_raster = 0;/* Have raster format support? */
a29fd7dd
MS
3665
3666 for (start = value; start && *start; start = next)
3667 {
46385a1a 3668 if (!_cups_strncasecmp(start, "application/pdf", 15) && (!start[15] || start[15] == ','))
a29fd7dd
MS
3669 {
3670 have_pdf = 1;
3671 break;
3672 }
46385a1a
MS
3673 else if ((!_cups_strncasecmp(start, "image/pwg-raster", 16) && (!start[16] || start[16] == ',')) ||
3674 (!_cups_strncasecmp(start, "image/urf", 9) && (!start[9] || start[9] == ',')))
3675 {
3676 have_raster = 1;
3677 break;
3678 }
a29fd7dd
MS
3679
3680 if ((next = strchr(start, ',')) != NULL)
3681 next ++;
3682 }
3683
46385a1a 3684 if (!have_pdf && !have_raster)
a29fd7dd
MS
3685 device->state = _CUPS_DNSSD_INCOMPATIBLE;
3686 }
dcb445bc
MS
3687 else if (!_cups_strcasecmp(key, "printer-type"))
3688 {
a29fd7dd
MS
3689 /*
3690 * Value is either NNNN or 0xXXXX
3691 */
3692
3693 saw_printer_type = 1;
f50db552 3694 type = (cups_ptype_t)strtol(value, NULL, 0) | CUPS_PRINTER_DISCOVERED;
a29fd7dd
MS
3695 }
3696 else if (!saw_printer_type)
3697 {
3698 if (!_cups_strcasecmp(key, "air") &&
3699 !_cups_strcasecmp(value, "t"))
3700 type |= CUPS_PRINTER_AUTHENTICATED;
3701 else if (!_cups_strcasecmp(key, "bind") &&
3702 !_cups_strcasecmp(value, "t"))
3703 type |= CUPS_PRINTER_BIND;
3704 else if (!_cups_strcasecmp(key, "collate") &&
3705 !_cups_strcasecmp(value, "t"))
3706 type |= CUPS_PRINTER_COLLATE;
3707 else if (!_cups_strcasecmp(key, "color") &&
3708 !_cups_strcasecmp(value, "t"))
3709 type |= CUPS_PRINTER_COLOR;
3710 else if (!_cups_strcasecmp(key, "copies") &&
3711 !_cups_strcasecmp(value, "t"))
3712 type |= CUPS_PRINTER_COPIES;
3713 else if (!_cups_strcasecmp(key, "duplex") &&
3714 !_cups_strcasecmp(value, "t"))
3715 type |= CUPS_PRINTER_DUPLEX;
3716 else if (!_cups_strcasecmp(key, "fax") &&
3717 !_cups_strcasecmp(value, "t"))
3718 type |= CUPS_PRINTER_MFP;
3719 else if (!_cups_strcasecmp(key, "papercustom") &&
3720 !_cups_strcasecmp(value, "t"))
3721 type |= CUPS_PRINTER_VARIABLE;
3722 else if (!_cups_strcasecmp(key, "papermax"))
3723 {
3724 if (!_cups_strcasecmp(value, "legal-a4"))
3725 type |= CUPS_PRINTER_SMALL;
3726 else if (!_cups_strcasecmp(value, "isoc-a2"))
3727 type |= CUPS_PRINTER_MEDIUM;
3728 else if (!_cups_strcasecmp(value, ">isoc-a2"))
3729 type |= CUPS_PRINTER_LARGE;
3730 }
3731 else if (!_cups_strcasecmp(key, "punch") &&
3732 !_cups_strcasecmp(value, "t"))
3733 type |= CUPS_PRINTER_PUNCH;
3734 else if (!_cups_strcasecmp(key, "scan") &&
3735 !_cups_strcasecmp(value, "t"))
3736 type |= CUPS_PRINTER_MFP;
3737 else if (!_cups_strcasecmp(key, "sort") &&
3738 !_cups_strcasecmp(value, "t"))
3739 type |= CUPS_PRINTER_SORT;
3740 else if (!_cups_strcasecmp(key, "staple") &&
3741 !_cups_strcasecmp(value, "t"))
3742 type |= CUPS_PRINTER_STAPLE;
dcb445bc
MS
3743 }
3744 }
3745
3746 /*
a29fd7dd 3747 * Save the printer-xxx values...
dcb445bc
MS
3748 */
3749
3750 if (make_and_model[0])
3751 {
3752 strlcat(make_and_model, " ", sizeof(make_and_model));
3753 strlcat(make_and_model, model, sizeof(make_and_model));
3754
46385a1a 3755 device->dest.num_options = cupsAddOption("printer-make-and-model", make_and_model, device->dest.num_options, &device->dest.options);
dcb445bc
MS
3756 }
3757 else
46385a1a 3758 device->dest.num_options = cupsAddOption("printer-make-and-model", model, device->dest.num_options, &device->dest.options);
dcb445bc 3759
a29fd7dd
MS
3760 device->type = type;
3761 snprintf(value, sizeof(value), "%u", type);
46385a1a 3762 device->dest.num_options = cupsAddOption("printer-type", value, device->dest.num_options, &device->dest.options);
a29fd7dd 3763
dcb445bc
MS
3764 /*
3765 * Save the URI...
3766 */
3767
3768 cups_dnssd_unquote(uriname, device->fullName, sizeof(uriname));
3769 httpAssembleURI(HTTP_URI_CODING_ALL, uri, sizeof(uri),
3770 !strcmp(device->regtype, "_ipps._tcp") ? "ipps" : "ipp",
a29fd7dd 3771 NULL, uriname, 0, saw_printer_type ? "/cups" : "/");
dcb445bc 3772
46385a1a 3773 DEBUG_printf(("6cups_dnssd_query: device-uri=\"%s\"", uri));
dcb445bc 3774
46385a1a 3775 device->dest.num_options = cupsAddOption("device-uri", uri, device->dest.num_options, &device->dest.options);
dcb445bc
MS
3776 }
3777 else
3778 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
3779 fullName));
3780}
3781
3782
3783/*
3784 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
3785 */
3786
3787static const char * /* O - Resolved URI or NULL */
3788cups_dnssd_resolve(
3789 cups_dest_t *dest, /* I - Destination */
3790 const char *uri, /* I - Current printer URI */
3791 int msec, /* I - Time in milliseconds */
3792 int *cancel, /* I - Pointer to "cancel" variable */
3793 cups_dest_cb_t cb, /* I - Callback */
3794 void *user_data) /* I - User data for callback */
3795{
3796 char tempuri[1024]; /* Temporary URI buffer */
3797 _cups_dnssd_resolve_t resolve; /* Resolve data */
3798
3799
3800 /*
3801 * Resolve the URI...
3802 */
3803
3804 resolve.cancel = cancel;
3805 gettimeofday(&resolve.end_time, NULL);
3806 if (msec > 0)
3807 {
3808 resolve.end_time.tv_sec += msec / 1000;
3809 resolve.end_time.tv_usec += (msec % 1000) * 1000;
3810
3811 while (resolve.end_time.tv_usec >= 1000000)
3812 {
3813 resolve.end_time.tv_sec ++;
3814 resolve.end_time.tv_usec -= 1000000;
3815 }
3816 }
3817 else
3818 resolve.end_time.tv_sec += 75;
3819
3820 if (cb)
4db7fcee 3821 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING, dest);
dcb445bc 3822
c585706d 3823 if ((uri = _httpResolveURI(uri, tempuri, sizeof(tempuri), _HTTP_RESOLVE_DEFAULT, cups_dnssd_resolve_cb, &resolve)) == NULL)
dcb445bc 3824 {
f5f2e19e 3825 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to resolve printer-uri."), 1);
dcb445bc
MS
3826
3827 if (cb)
46385a1a 3828 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR, dest);
dcb445bc
MS
3829
3830 return (NULL);
3831 }
3832
3833 /*
3834 * Save the resolved URI...
3835 */
3836
c9a0ff62 3837 dest->num_options = cupsAddOption("device-uri", uri, dest->num_options, &dest->options);
dcb445bc 3838
c9a0ff62 3839 return (cupsGetOption("device-uri", dest->num_options, dest->options));
dcb445bc
MS
3840}
3841
3842
3843/*
3844 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
3845 */
3846
3847static int /* O - 1 to continue, 0 to stop */
3848cups_dnssd_resolve_cb(void *context) /* I - Resolve data */
3849{
3850 _cups_dnssd_resolve_t *resolve = (_cups_dnssd_resolve_t *)context;
3851 /* Resolve data */
3852 struct timeval curtime; /* Current time */
3853
3854
3855 /*
3856 * If the cancel variable is set, return immediately.
3857 */
3858
4db7fcee
MS
3859 if (resolve->cancel && *(resolve->cancel))
3860 {
3861 DEBUG_puts("4cups_dnssd_resolve_cb: Canceled.");
dcb445bc 3862 return (0);
4db7fcee 3863 }
dcb445bc
MS
3864
3865 /*
3866 * Otherwise check the end time...
3867 */
3868
3869 gettimeofday(&curtime, NULL);
3870
8ddb0f60 3871 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
3872
3873 return (curtime.tv_sec < resolve->end_time.tv_sec ||
dcb445bc 3874 (curtime.tv_sec == resolve->end_time.tv_sec &&
4db7fcee 3875 curtime.tv_usec < resolve->end_time.tv_usec));
dcb445bc
MS
3876}
3877
3878
3879/*
3880 * 'cups_dnssd_unquote()' - Unquote a name string.
3881 */
3882
3883static void
3884cups_dnssd_unquote(char *dst, /* I - Destination buffer */
3885 const char *src, /* I - Source string */
3886 size_t dstsize) /* I - Size of destination buffer */
3887{
3888 char *dstend = dst + dstsize - 1; /* End of destination buffer */
3889
3890
3891 while (*src && dst < dstend)
3892 {
3893 if (*src == '\\')
3894 {
3895 src ++;
3896 if (isdigit(src[0] & 255) && isdigit(src[1] & 255) &&
3897 isdigit(src[2] & 255))
3898 {
3899 *dst++ = ((((src[0] - '0') * 10) + src[1] - '0') * 10) + src[2] - '0';
3900 src += 3;
3901 }
3902 else
3903 *dst++ = *src++;
3904 }
3905 else
3906 *dst++ = *src ++;
3907 }
3908
3909 *dst = '\0';
3910}
3911#endif /* HAVE_DNSSD */
3912
3913
f34c1c99 3914#if defined(HAVE_AVAHI) || defined(HAVE_DNSSD)
3fae3b33
MS
3915/*
3916 * 'cups_elapsed()' - Return the elapsed time in milliseconds.
3917 */
3918
3919static int /* O - Elapsed time in milliseconds */
3920cups_elapsed(struct timeval *t) /* IO - Previous time */
3921{
3922 int msecs; /* Milliseconds */
3923 struct timeval nt; /* New time */
3924
3925
3926 gettimeofday(&nt, NULL);
3927
2a75f21b 3928 msecs = (int)(1000 * (nt.tv_sec - t->tv_sec) + (nt.tv_usec - t->tv_usec) / 1000);
3fae3b33
MS
3929
3930 *t = nt;
3931
3932 return (msecs);
3933}
f34c1c99 3934#endif /* HAVE_AVAHI || HAVE_DNSSD */
3fae3b33 3935
798d6e29 3936
426c6a59
MS
3937/*
3938 * 'cups_find_dest()' - Find a destination using a binary search.
3939 */
3940
3941static int /* O - Index of match */
3942cups_find_dest(const char *name, /* I - Destination name */
3943 const char *instance, /* I - Instance or NULL */
3944 int num_dests, /* I - Number of destinations */
3945 cups_dest_t *dests, /* I - Destinations */
3946 int prev, /* I - Previous index */
3947 int *rdiff) /* O - Difference of match */
3948{
3949 int left, /* Low mark for binary search */
3950 right, /* High mark for binary search */
3951 current, /* Current index */
3952 diff; /* Result of comparison */
3953 cups_dest_t key; /* Search key */
3954
3955
3956 key.name = (char *)name;
3957 key.instance = (char *)instance;
3958
3959 if (prev >= 0)
3960 {
3961 /*
3962 * Start search on either side of previous...
3963 */
3964
3965 if ((diff = cups_compare_dests(&key, dests + prev)) == 0 ||
3966 (diff < 0 && prev == 0) ||
3967 (diff > 0 && prev == (num_dests - 1)))
3968 {
3969 *rdiff = diff;
3970 return (prev);
3971 }
3972 else if (diff < 0)
3973 {
3974 /*
3975 * Start with previous on right side...
3976 */
3977
3978 left = 0;
3979 right = prev;
3980 }
3981 else
3982 {
3983 /*
3984 * Start wih previous on left side...
3985 */
3986
3987 left = prev;
3988 right = num_dests - 1;
3989 }
3990 }
3991 else
3992 {
3993 /*
3994 * Start search in the middle...
3995 */
3996
3997 left = 0;
3998 right = num_dests - 1;
3999 }
4000
4001 do
4002 {
4003 current = (left + right) / 2;
4004 diff = cups_compare_dests(&key, dests + current);
4005
4006 if (diff == 0)
4007 break;
4008 else if (diff < 0)
4009 right = current;
4010 else
4011 left = current;
4012 }
4013 while ((right - left) > 1);
4014
4015 if (diff != 0)
4016 {
4017 /*
4018 * Check the last 1 or 2 elements...
4019 */
4020
4021 if ((diff = cups_compare_dests(&key, dests + left)) <= 0)
4022 current = left;
4023 else
4024 {
4025 diff = cups_compare_dests(&key, dests + right);
4026 current = right;
4027 }
4028 }
4029
4030 /*
4031 * Return the closest destination and the difference...
4032 */
4033
4034 *rdiff = diff;
4035
4036 return (current);
4037}
4038
4039
7536de1a
MS
4040/*
4041 * 'cups_get_cb()' - Collect enumerated destinations.
4042 */
4043
4044static int /* O - 1 to continue, 0 to stop */
4045cups_get_cb(_cups_getdata_t *data, /* I - Data from cupsGetDests */
4046 unsigned flags, /* I - Enumeration flags */
4047 cups_dest_t *dest) /* I - Destination */
4048{
4049 if (flags & CUPS_DEST_FLAGS_REMOVED)
4050 {
4051 /*
4052 * Remove destination from array...
4053 */
4054
4055 data->num_dests = cupsRemoveDest(dest->name, dest->instance, data->num_dests, &data->dests);
4056 }
4057 else
4058 {
4059 /*
4060 * Add destination to array...
4061 */
4062
4063 data->num_dests = cupsCopyDest(dest, data->num_dests, &data->dests);
4064 }
4065
4066 return (1);
4067}
4068
4069
a4924f6c
MS
4070/*
4071 * 'cups_get_default()' - Get the default destination from an lpoptions file.
4072 */
4073
080811b1 4074static char * /* O - Default destination or NULL */
a4924f6c
MS
4075cups_get_default(const char *filename, /* I - File to read */
4076 char *namebuf, /* I - Name buffer */
4077 size_t namesize, /* I - Size of name buffer */
4078 const char **instance) /* I - Instance */
4079{
4080 cups_file_t *fp; /* lpoptions file */
4081 char line[8192], /* Line from file */
4082 *value, /* Value for line */
4083 *nameptr; /* Pointer into name */
88f9aafc 4084 int linenum; /* Current line */
a4924f6c
MS
4085
4086
4087 *namebuf = '\0';
4088
4089 if ((fp = cupsFileOpen(filename, "r")) != NULL)
4090 {
4091 linenum = 0;
4092
4093 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
4094 {
88f9aafc 4095 if (!_cups_strcasecmp(line, "default") && value)
a4924f6c
MS
4096 {
4097 strlcpy(namebuf, value, namesize);
4098
4099 if ((nameptr = strchr(namebuf, ' ')) != NULL)
4100 *nameptr = '\0';
4101 if ((nameptr = strchr(namebuf, '\t')) != NULL)
4102 *nameptr = '\0';
4103
4104 if ((nameptr = strchr(namebuf, '/')) != NULL)
4105 *nameptr++ = '\0';
4106
4107 *instance = nameptr;
4108 break;
4109 }
4110 }
4111
4112 cupsFileClose(fp);
4113 }
4114
4115 return (*namebuf ? namebuf : NULL);
4116}
4117
4118
ef416fc2 4119/*
4120 * 'cups_get_dests()' - Get destinations from a file.
4121 */
4122
4123static int /* O - Number of destinations */
38e73f87
MS
4124cups_get_dests(
4125 const char *filename, /* I - File to read from */
4126 const char *match_name, /* I - Destination name we want */
4127 const char *match_inst, /* I - Instance name we want */
4128 int user_default_set, /* I - User default printer set? */
4129 int num_dests, /* I - Number of destinations */
4130 cups_dest_t **dests) /* IO - Destinations */
ef416fc2 4131{
4132 int i; /* Looping var */
4133 cups_dest_t *dest; /* Current destination */
a4924f6c 4134 cups_file_t *fp; /* File pointer */
ef416fc2 4135 char line[8192], /* Line from file */
4136 *lineptr, /* Pointer into line */
4137 *name, /* Name of destination/option */
4138 *instance; /* Instance of destination */
a4924f6c 4139 int linenum; /* Current line number */
ef416fc2 4140
4141
807315e6 4142 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
4143
4144 /*
4145 * Try to open the file...
4146 */
4147
4148 if ((fp = cupsFileOpen(filename, "r")) == NULL)
4149 return (num_dests);
4150
ef416fc2 4151 /*
4152 * Read each printer; each line looks like:
4153 *
4154 * Dest name[/instance] options
4155 * Default name[/instance] options
4156 */
4157
a4924f6c
MS
4158 linenum = 0;
4159
4160 while (cupsFileGetConf(fp, line, sizeof(line), &lineptr, &linenum))
ef416fc2 4161 {
4162 /*
4163 * See what type of line it is...
4164 */
4165
e07d4801 4166 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
38e73f87 4167 linenum, line, lineptr));
ef416fc2 4168
88f9aafc 4169 if ((_cups_strcasecmp(line, "dest") && _cups_strcasecmp(line, "default")) || !lineptr)
a4924f6c 4170 {
e07d4801 4171 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
ef416fc2 4172 continue;
a4924f6c 4173 }
ef416fc2 4174
4175 name = lineptr;
4176
4177 /*
4178 * Search for an instance...
4179 */
4180
4181 while (!isspace(*lineptr & 255) && *lineptr && *lineptr != '/')
4182 lineptr ++;
4183
ef416fc2 4184 if (*lineptr == '/')
4185 {
4186 /*
4187 * Found an instance...
4188 */
4189
4190 *lineptr++ = '\0';
4191 instance = lineptr;
4192
4193 /*
4194 * Search for an instance...
4195 */
4196
4197 while (!isspace(*lineptr & 255) && *lineptr)
4198 lineptr ++;
4199 }
4200 else
4201 instance = NULL;
4202
a4924f6c
MS
4203 if (*lineptr)
4204 *lineptr++ = '\0';
4205
e07d4801 4206 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name,
a4924f6c 4207 instance));
ef416fc2 4208
4209 /*
4210 * See if the primary instance of the destination exists; if not,
4211 * ignore this entry and move on...
4212 */
4213
a4924f6c
MS
4214 if (match_name)
4215 {
88f9aafc 4216 if (_cups_strcasecmp(name, match_name) ||
a4924f6c
MS
4217 (!instance && match_inst) ||
4218 (instance && !match_inst) ||
88f9aafc 4219 (instance && _cups_strcasecmp(instance, match_inst)))
a4924f6c 4220 continue;
ef416fc2 4221
a4924f6c
MS
4222 dest = *dests;
4223 }
4224 else if (cupsGetDest(name, NULL, num_dests, *dests) == NULL)
4225 {
e07d4801 4226 DEBUG_puts("9cups_get_dests: Not found!");
a4924f6c
MS
4227 continue;
4228 }
4229 else
ef416fc2 4230 {
4231 /*
a4924f6c 4232 * Add the destination...
ef416fc2 4233 */
4234
a4924f6c
MS
4235 num_dests = cupsAddDest(name, instance, num_dests, dests);
4236
4237 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
4238 {
4239 /*
4240 * Out of memory!
4241 */
4242
e07d4801 4243 DEBUG_puts("9cups_get_dests: Out of memory!");
a4924f6c
MS
4244 break;
4245 }
ef416fc2 4246 }
4247
4248 /*
4249 * Add options until we hit the end of the line...
4250 */
4251
4252 dest->num_options = cupsParseOptions(lineptr, dest->num_options,
4253 &(dest->options));
4254
a4924f6c
MS
4255 /*
4256 * If we found what we were looking for, stop now...
4257 */
4258
4259 if (match_name)
4260 break;
4261
ef416fc2 4262 /*
4263 * Set this as default if needed...
4264 */
4265
88f9aafc 4266 if (!user_default_set && !_cups_strcasecmp(line, "default"))
ef416fc2 4267 {
e07d4801 4268 DEBUG_puts("9cups_get_dests: Setting as default...");
a4924f6c 4269
ef416fc2 4270 for (i = 0; i < num_dests; i ++)
4271 (*dests)[i].is_default = 0;
4272
4273 dest->is_default = 1;
4274 }
4275 }
4276
4277 /*
4278 * Close the file and return...
4279 */
4280
88f9aafc 4281 cupsFileClose(fp);
ef416fc2 4282
4283 return (num_dests);
4284}
4285
4286
426c6a59
MS
4287/*
4288 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
4289 * attribute.
4290 */
4291
4292static char * /* O - New string */
4293cups_make_string(
4294 ipp_attribute_t *attr, /* I - Attribute to convert */
4295 char *buffer, /* I - Buffer */
4296 size_t bufsize) /* I - Size of buffer */
4297{
4298 int i; /* Looping var */
4299 char *ptr, /* Pointer into buffer */
4300 *end, /* Pointer to end of buffer */
4301 *valptr; /* Pointer into string attribute */
4302
4303
4304 /*
4305 * Return quickly if we have a single string value...
4306 */
4307
4308 if (attr->num_values == 1 &&
4309 attr->value_tag != IPP_TAG_INTEGER &&
4310 attr->value_tag != IPP_TAG_ENUM &&
4311 attr->value_tag != IPP_TAG_BOOLEAN &&
4312 attr->value_tag != IPP_TAG_RANGE)
4313 return (attr->values[0].string.text);
4314
4315 /*
4316 * Copy the values to the string, separating with commas and escaping strings
4317 * as needed...
4318 */
4319
4320 end = buffer + bufsize - 1;
4321
4322 for (i = 0, ptr = buffer; i < attr->num_values && ptr < end; i ++)
4323 {
4324 if (i)
4325 *ptr++ = ',';
4326
4327 switch (attr->value_tag)
4328 {
4329 case IPP_TAG_INTEGER :
4330 case IPP_TAG_ENUM :
07623986 4331 snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].integer);
426c6a59
MS
4332 break;
4333
4334 case IPP_TAG_BOOLEAN :
4335 if (attr->values[i].boolean)
07623986 4336 strlcpy(ptr, "true", (size_t)(end - ptr + 1));
426c6a59 4337 else
07623986 4338 strlcpy(ptr, "false", (size_t)(end - ptr + 1));
426c6a59
MS
4339 break;
4340
4341 case IPP_TAG_RANGE :
4342 if (attr->values[i].range.lower == attr->values[i].range.upper)
07623986 4343 snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].range.lower);
426c6a59 4344 else
07623986 4345 snprintf(ptr, (size_t)(end - ptr + 1), "%d-%d", attr->values[i].range.lower, attr->values[i].range.upper);
426c6a59
MS
4346 break;
4347
4348 default :
4349 for (valptr = attr->values[i].string.text;
4350 *valptr && ptr < end;)
4351 {
4352 if (strchr(" \t\n\\\'\"", *valptr))
4353 {
4354 if (ptr >= (end - 1))
4355 break;
4356
4357 *ptr++ = '\\';
4358 }
4359
4360 *ptr++ = *valptr++;
4361 }
4362
4363 *ptr = '\0';
4364 break;
4365 }
4366
4367 ptr += strlen(ptr);
4368 }
4369
4370 *ptr = '\0';
4371
4372 return (buffer);
4373}
efa72f61
MS
4374
4375
4a366251
MS
4376/*
4377 * 'cups_name_cb()' - Find an enumerated destination.
4378 */
4379
4380static int /* O - 1 to continue, 0 to stop */
4381cups_name_cb(_cups_namedata_t *data, /* I - Data from cupsGetNamedDest */
4382 unsigned flags, /* I - Enumeration flags */
4383 cups_dest_t *dest) /* I - Destination */
4384{
2a75f21b 4385 DEBUG_printf(("2cups_name_cb(data=%p(%s), flags=%x, dest=%p(%s)", (void *)data, data->name, flags, (void *)dest, dest->name));
4a366251
MS
4386
4387 if (!(flags & CUPS_DEST_FLAGS_REMOVED) && !dest->instance && !strcasecmp(data->name, dest->name))
4388 {
4389 /*
4390 * Copy destination and stop enumeration...
4391 */
4392
4393 cupsCopyDest(dest, 0, &data->dest);
4394 return (0);
4395 }
4396
4397 return (1);
4398}
4399
4400
efa72f61
MS
4401/*
4402 * 'cups_queue_name()' - Create a local queue name based on the service name.
4403 */
4404
4405static void
4406cups_queue_name(
4407 char *name, /* I - Name buffer */
4408 const char *serviceName, /* I - Service name */
4409 size_t namesize) /* I - Size of name buffer */
4410{
4411 const char *ptr; /* Pointer into serviceName */
4412 char *nameptr; /* Pointer into name */
4413
4414
4415 for (nameptr = name, ptr = serviceName; *ptr && nameptr < (name + namesize - 1); ptr ++)
4416 {
4417 /*
4418 * Sanitize the printer name...
4419 */
4420
4421 if (_cups_isalnum(*ptr))
4422 *nameptr++ = *ptr;
4423 else if (nameptr == name || nameptr[-1] != '_')
4424 *nameptr++ = '_';
4425 }
4426
4427 *nameptr = '\0';
4428}