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