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