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