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