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