]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/dest.c
Save work on Avahi code
[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 int browsers; /* How many browsers are running? */
89 # endif /* HAVE_DNSSD */
90 cups_dest_cb_t cb; /* Callback */
91 void *user_data; /* User data pointer */
92 cups_ptype_t type, /* Printer type filter */
93 mask; /* Printer type mask */
94 cups_array_t *devices; /* Devices found so far */
95 } _cups_dnssd_data_t;
96
97 typedef struct _cups_dnssd_device_s /* Enumerated device */
98 {
99 _cups_dnssd_state_t state; /* State of device listing */
100 # ifdef HAVE_DNSSD
101 DNSServiceRef ref; /* Service reference for query */
102 # else /* HAVE_AVAHI */
103 AvahiRecordBrowser *ref; /* Browser for query */
104 # endif /* HAVE_DNSSD */
105 char *fullName, /* Full 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 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1025 const char *device_uri; /* Device URI */
1026 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1027
1028 if (!(*cb)(user_data, i > 1 ? CUPS_DEST_FLAGS_MORE : CUPS_DEST_FLAGS_NONE,
1029 dest))
1030 break;
1031
1032 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1033 if (!dest->instance && (device_uri = cupsGetOption("device-uri", dest->num_options, dest->options)) != NULL && !strncmp(device_uri, "dnssd://", 8))
1034 {
1035 /*
1036 * Add existing queue using service name, etc. so we don't list it again...
1037 */
1038
1039 char scheme[32], /* URI scheme */
1040 userpass[32], /* Username:password */
1041 serviceName[256], /* Service name (host field) */
1042 resource[256], /* Resource (options) */
1043 *regtype, /* Registration type */
1044 *replyDomain; /* Registration domain */
1045 int port; /* Port number (not used) */
1046
1047 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)
1048 {
1049 if ((regtype = strstr(serviceName, "._ipp")) != NULL)
1050 {
1051 *regtype++ = '\0';
1052
1053 if ((replyDomain = strstr(regtype, "._tcp.")) != NULL)
1054 {
1055 replyDomain[5] = '\0';
1056 replyDomain += 6;
1057
1058 if ((device = cups_dnssd_get_device(&data, serviceName, regtype, replyDomain)) != NULL)
1059 device->state = _CUPS_DNSSD_ACTIVE;
1060 }
1061 }
1062 }
1063 }
1064 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1065 }
1066
1067 cupsFreeDests(num_dests, dests);
1068
1069 if (i > 0 || msec == 0)
1070 {
1071 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1072 cupsArrayDelete(data.devices);
1073 #endif /* HAVE_DNSSD || HAVE_AVAHI */
1074
1075 return (1);
1076 }
1077
1078 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
1079 /*
1080 * Get Bonjour-shared printers...
1081 */
1082
1083 # ifdef HAVE_DNSSD
1084 if (DNSServiceCreateConnection(&data.main_ref) != kDNSServiceErr_NoError)
1085 return (0);
1086
1087 main_fd = DNSServiceRefSockFD(data.main_ref);
1088
1089 ipp_ref = data.main_ref;
1090 DNSServiceBrowse(&ipp_ref, kDNSServiceFlagsShareConnection, 0,
1091 "_ipp._tcp", NULL,
1092 (DNSServiceBrowseReply)cups_dnssd_browse_cb, &data);
1093
1094 local_ipp_ref = data.main_ref;
1095 DNSServiceBrowse(&local_ipp_ref, kDNSServiceFlagsShareConnection,
1096 kDNSServiceInterfaceIndexLocalOnly,
1097 "_ipp._tcp", NULL,
1098 (DNSServiceBrowseReply)cups_dnssd_local_cb, &data);
1099
1100 # ifdef HAVE_SSL
1101 ipps_ref = data.main_ref;
1102 DNSServiceBrowse(&ipps_ref, kDNSServiceFlagsShareConnection, 0,
1103 "_ipps._tcp", NULL,
1104 (DNSServiceBrowseReply)cups_dnssd_browse_cb, &data);
1105
1106 local_ipps_ref = data.main_ref;
1107 DNSServiceBrowse(&local_ipps_ref, kDNSServiceFlagsShareConnection,
1108 kDNSServiceInterfaceIndexLocalOnly,
1109 "_ipps._tcp", NULL,
1110 (DNSServiceBrowseReply)cups_dnssd_local_cb, &data);
1111 # endif /* HAVE_SSL */
1112
1113 # else /* HAVE_AVAHI */
1114 if ((data.simple_poll = avahi_simple_poll_new()) == NULL)
1115 {
1116 DEBUG_puts("cupsEnumDests: Unable to create Avahi simple poll object.");
1117 return (1);
1118 }
1119
1120 avahi_simple_poll_set_func(data.simple_poll, cups_dnssd_poll_cb, &data);
1121
1122 data.client = avahi_client_new(avahi_simple_poll_get(data.simple_poll),
1123 0, cups_dnssd_client_cb, &data,
1124 &error);
1125 if (!data.client)
1126 {
1127 DEBUG_puts("cupsEnumDests: Unable to create Avahi client.");
1128 avahi_simple_poll_free(data.simple_poll);
1129 return (1);
1130 }
1131
1132 data.browsers ++;
1133 ipp_ref = avahi_service_browser_new(data.client, AVAHI_IF_UNSPEC,
1134 AVAHI_PROTO_UNSPEC, "_ipp._tcp", NULL,
1135 0, cups_dnssd_browse_cb, &data);
1136 # ifdef HAVE_SSL
1137 data.browsers ++;
1138 ipps_ref = avahi_service_browser_new(data.client, AVAHI_IF_UNSPEC,
1139 AVAHI_PROTO_UNSPEC, "_ipps._tcp", NULL,
1140 0, cups_dnssd_browse_cb, &data);
1141 # endif /* HAVE_SSL */
1142 # endif /* HAVE_DNSSD */
1143
1144 if (msec < 0)
1145 remaining = INT_MAX;
1146 else
1147 remaining = msec;
1148
1149 while (remaining > 0 && (!cancel || !*cancel))
1150 {
1151 /*
1152 * Check for input...
1153 */
1154
1155 # ifdef HAVE_DNSSD
1156 # ifdef HAVE_POLL
1157 pfd.fd = main_fd;
1158 pfd.events = POLLIN;
1159
1160 nfds = poll(&pfd, 1, remaining > 500 ? 500 : remaining);
1161
1162 # else
1163 FD_ZERO(&input);
1164 FD_SET(main_fd, &input);
1165
1166 timeout.tv_sec = 0;
1167 timeout.tv_usec = remaining > 500 ? 500000 : remaining * 1000;
1168
1169 nfds = select(main_fd + 1, &input, NULL, NULL, &timeout);
1170 # endif /* HAVE_POLL */
1171
1172 if (nfds > 0)
1173 DNSServiceProcessResult(data.main_ref);
1174
1175 # else /* HAVE_AVAHI */
1176 data.got_data = 0;
1177
1178 if ((error = avahi_simple_poll_iterate(data.simple_poll, 1000)) > 0)
1179 {
1180 /*
1181 * We've been told to exit the loop. Perhaps the connection to
1182 * Avahi failed.
1183 */
1184
1185 break;
1186 }
1187
1188 DEBUG_printf(("1cupsEnumDests: got_data=%d", data.got_data));
1189 # endif /* HAVE_DNSSD */
1190
1191 remaining -= 500;
1192
1193 for (device = (_cups_dnssd_device_t *)cupsArrayFirst(data.devices),
1194 count = 0, completed = 0;
1195 device;
1196 device = (_cups_dnssd_device_t *)cupsArrayNext(data.devices))
1197 {
1198 if (device->ref)
1199 count ++;
1200
1201 if (device->state == _CUPS_DNSSD_ACTIVE)
1202 completed ++;
1203
1204 if (!device->ref && device->state == _CUPS_DNSSD_NEW)
1205 {
1206 DEBUG_printf(("1cupsEnumDests: Querying '%s'.", device->fullName));
1207
1208 # ifdef HAVE_DNSSD
1209 device->ref = data.main_ref;
1210
1211 if (DNSServiceQueryRecord(&(device->ref),
1212 kDNSServiceFlagsShareConnection,
1213 0, device->fullName,
1214 kDNSServiceType_TXT,
1215 kDNSServiceClass_IN,
1216 (DNSServiceQueryRecordReply)cups_dnssd_query_cb,
1217 &data) == kDNSServiceErr_NoError)
1218 {
1219 count ++;
1220 }
1221 else
1222 {
1223 device->ref = 0;
1224 device->state = _CUPS_DNSSD_ERROR;
1225
1226 DEBUG_puts("1cupsEnumDests: Query failed.");
1227 }
1228
1229 # else /* HAVE_AVAHI */
1230 if ((device->ref = avahi_record_browser_new(data.client,
1231 AVAHI_IF_UNSPEC,
1232 AVAHI_PROTO_UNSPEC,
1233 device->fullName,
1234 AVAHI_DNS_CLASS_IN,
1235 AVAHI_DNS_TYPE_TXT,
1236 0,
1237 cups_dnssd_query_cb,
1238 &data)) != NULL)
1239 {
1240 DEBUG_printf(("1cupsEnumDests: browser ref=%p", device->ref));
1241 count ++;
1242 }
1243 else
1244 {
1245 device->state = _CUPS_DNSSD_ERROR;
1246
1247 DEBUG_printf(("1cupsEnumDests: Query failed: %s", avahi_strerror(avahi_client_errno(data.client))));
1248 }
1249 # endif /* HAVE_DNSSD */
1250 }
1251 else if (device->ref && device->state == _CUPS_DNSSD_PENDING)
1252 {
1253 completed ++;
1254
1255 if ((device->type & mask) == type)
1256 {
1257 DEBUG_printf(("1cupsEnumDests: Add callback for \"%s\".", device->dest.name));
1258 if (!(*cb)(user_data, CUPS_DEST_FLAGS_NONE, &device->dest))
1259 {
1260 remaining = -1;
1261 break;
1262 }
1263 }
1264
1265 device->state = _CUPS_DNSSD_ACTIVE;
1266 }
1267 }
1268
1269 # ifdef HAVE_AVAHI
1270 DEBUG_printf(("1cupsEnumDests: browsers=%d, completed=%d, count=%d, devices count=%d", data.browsers, completed, count, cupsArrayCount(data.devices)));
1271
1272 if (data.browsers == 0 && completed == cupsArrayCount(data.devices))
1273 break;
1274 # else
1275 DEBUG_printf(("1cupsEnumDests: completed=%d, count=%d, devices count=%d", completed, count, cupsArrayCount(data.devices)));
1276
1277 if (completed == cupsArrayCount(data.devices))
1278 break;
1279 # endif /* HAVE_AVAHI */
1280 }
1281
1282 cupsArrayDelete(data.devices);
1283
1284 # ifdef HAVE_DNSSD
1285 DNSServiceRefDeallocate(ipp_ref);
1286 DNSServiceRefDeallocate(local_ipp_ref);
1287
1288 # ifdef HAVE_SSL
1289 DNSServiceRefDeallocate(ipp_ref);
1290 DNSServiceRefDeallocate(local_ipp_ref);
1291 # endif /* HAVE_SSL */
1292
1293 DNSServiceRefDeallocate(data.main_ref);
1294
1295 # else /* HAVE_AVAHI */
1296 avahi_service_browser_free(ipp_ref);
1297 # ifdef HAVE_SSL
1298 avahi_service_browser_free(ipps_ref);
1299 # endif /* HAVE_SSL */
1300
1301 avahi_client_free(data.client);
1302 avahi_simple_poll_free(data.simple_poll);
1303 # endif /* HAVE_DNSSD */
1304 #endif /* HAVE_DNSSD || HAVE_DNSSD */
1305
1306 return (1);
1307 }
1308
1309
1310 # ifdef __BLOCKS__
1311 /*
1312 * 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
1313 *
1314 * Destinations are enumerated from one or more sources. The block receives the
1315 * destination name, instance, number of options, and options which can be used
1316 * as input to the @link cupsAddDest@ function. The block must return 1 to
1317 * continue enumeration or 0 to stop.
1318 *
1319 * Enumeration happens on the current thread and does not return until all
1320 * destinations have been enumerated or the block returns 0.
1321 *
1322 * @since CUPS 1.6/macOS 10.8@
1323 */
1324
1325 int /* O - 1 on success, 0 on failure */
1326 cupsEnumDestsBlock(
1327 unsigned flags, /* I - Enumeration flags */
1328 int timeout, /* I - Timeout in milliseconds, 0 for indefinite */
1329 int *cancel, /* I - Pointer to "cancel" variable */
1330 cups_ptype_t type, /* I - Printer type bits */
1331 cups_ptype_t mask, /* I - Mask for printer type bits */
1332 cups_dest_block_t block) /* I - Block */
1333 {
1334 return (cupsEnumDests(flags, timeout, cancel, type, mask,
1335 (cups_dest_cb_t)cups_block_cb, (void *)block));
1336 }
1337 # endif /* __BLOCKS__ */
1338
1339
1340 /*
1341 * 'cupsFreeDests()' - Free the memory used by the list of destinations.
1342 */
1343
1344 void
1345 cupsFreeDests(int num_dests, /* I - Number of destinations */
1346 cups_dest_t *dests) /* I - Destinations */
1347 {
1348 int i; /* Looping var */
1349 cups_dest_t *dest; /* Current destination */
1350
1351
1352 if (num_dests == 0 || dests == NULL)
1353 return;
1354
1355 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
1356 {
1357 _cupsStrFree(dest->name);
1358 _cupsStrFree(dest->instance);
1359
1360 cupsFreeOptions(dest->num_options, dest->options);
1361 }
1362
1363 free(dests);
1364 }
1365
1366
1367 /*
1368 * 'cupsGetDest()' - Get the named destination from the list.
1369 *
1370 * Use the @link cupsGetDests@ or @link cupsGetDests2@ functions to get a
1371 * list of supported destinations for the current user.
1372 */
1373
1374 cups_dest_t * /* O - Destination pointer or @code NULL@ */
1375 cupsGetDest(const char *name, /* I - Destination name or @code NULL@ for the default destination */
1376 const char *instance, /* I - Instance name or @code NULL@ */
1377 int num_dests, /* I - Number of destinations */
1378 cups_dest_t *dests) /* I - Destinations */
1379 {
1380 int diff, /* Result of comparison */
1381 match; /* Matching index */
1382
1383
1384 if (num_dests <= 0 || !dests)
1385 return (NULL);
1386
1387 if (!name)
1388 {
1389 /*
1390 * NULL name for default printer.
1391 */
1392
1393 while (num_dests > 0)
1394 {
1395 if (dests->is_default)
1396 return (dests);
1397
1398 num_dests --;
1399 dests ++;
1400 }
1401 }
1402 else
1403 {
1404 /*
1405 * Lookup name and optionally the instance...
1406 */
1407
1408 match = cups_find_dest(name, instance, num_dests, dests, -1, &diff);
1409
1410 if (!diff)
1411 return (dests + match);
1412 }
1413
1414 return (NULL);
1415 }
1416
1417
1418 /*
1419 * '_cupsGetDestResource()' - Get the resource path and URI for a destination.
1420 */
1421
1422 const char * /* O - Printer URI */
1423 _cupsGetDestResource(
1424 cups_dest_t *dest, /* I - Destination */
1425 char *resource, /* I - Resource buffer */
1426 size_t resourcesize) /* I - Size of resource buffer */
1427 {
1428 const char *uri; /* Printer URI */
1429 char scheme[32], /* URI scheme */
1430 userpass[256], /* Username and password (unused) */
1431 hostname[256]; /* Hostname */
1432 int port; /* Port number */
1433
1434
1435 /*
1436 * Range check input...
1437 */
1438
1439 if (!dest || !resource || resourcesize < 1)
1440 {
1441 if (resource)
1442 *resource = '\0';
1443
1444 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
1445 return (NULL);
1446 }
1447
1448 /*
1449 * Grab the printer URI...
1450 */
1451
1452 if ((uri = cupsGetOption("printer-uri-supported", dest->num_options,
1453 dest->options)) == NULL)
1454 {
1455 if (resource)
1456 *resource = '\0';
1457
1458 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(ENOENT), 0);
1459
1460 return (NULL);
1461 }
1462
1463 #ifdef HAVE_DNSSD
1464 if (strstr(uri, "._tcp"))
1465 {
1466 if ((uri = cups_dnssd_resolve(dest, uri, 5000, NULL, NULL, NULL)) == NULL)
1467 return (NULL);
1468 }
1469 #endif /* HAVE_DNSSD */
1470
1471 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme),
1472 userpass, sizeof(userpass), hostname, sizeof(hostname),
1473 &port, resource, (int)resourcesize) < HTTP_URI_STATUS_OK)
1474 {
1475 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad printer-uri."), 1);
1476
1477 return (NULL);
1478 }
1479
1480 return (uri);
1481 }
1482
1483
1484 /*
1485 * 'cupsGetDestWithURI()' - Get a destination associated with a URI.
1486 *
1487 * "name" is the desired name for the printer. If @code NULL@, a name will be
1488 * created using the URI.
1489 *
1490 * "uri" is the "ipp" or "ipps" URI for the printer.
1491 *
1492 * @since CUPS 2.0/macOS 10.10@
1493 */
1494
1495 cups_dest_t * /* O - Destination or @code NULL@ */
1496 cupsGetDestWithURI(const char *name, /* I - Desired printer name or @code NULL@ */
1497 const char *uri) /* I - URI for the printer */
1498 {
1499 cups_dest_t *dest; /* New destination */
1500 char temp[1024], /* Temporary string */
1501 scheme[256], /* Scheme from URI */
1502 userpass[256], /* Username:password from URI */
1503 hostname[256], /* Hostname from URI */
1504 resource[1024], /* Resource path from URI */
1505 *ptr; /* Pointer into string */
1506 int port; /* Port number from URI */
1507
1508
1509 /*
1510 * Range check input...
1511 */
1512
1513 if (!uri)
1514 {
1515 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
1516 return (NULL);
1517 }
1518
1519 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme), userpass, sizeof(userpass), hostname, sizeof(hostname), &port, resource, sizeof(resource)) < HTTP_URI_STATUS_OK ||
1520 (strncmp(uri, "ipp://", 6) && strncmp(uri, "ipps://", 7)))
1521 {
1522 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad printer-uri."), 1);
1523
1524 return (NULL);
1525 }
1526
1527 if (!name)
1528 {
1529 /*
1530 * Create the name from the URI...
1531 */
1532
1533 if (strstr(hostname, "._tcp"))
1534 {
1535 /*
1536 * Use the service instance name...
1537 */
1538
1539 if ((ptr = strchr(hostname, '.')) != NULL)
1540 *ptr = '\0';
1541
1542 name = hostname;
1543 }
1544 else if (!strncmp(resource, "/classes/", 9))
1545 {
1546 snprintf(temp, sizeof(temp), "%s @ %s", resource + 9, hostname);
1547 name = temp;
1548 }
1549 else if (!strncmp(resource, "/printers/", 10))
1550 {
1551 snprintf(temp, sizeof(temp), "%s @ %s", resource + 10, hostname);
1552 name = temp;
1553 }
1554 else
1555 {
1556 name = hostname;
1557 }
1558 }
1559
1560 /*
1561 * Create the destination...
1562 */
1563
1564 if ((dest = calloc(1, sizeof(cups_dest_t))) == NULL)
1565 {
1566 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
1567 return (NULL);
1568 }
1569
1570 dest->name = _cupsStrAlloc(name);
1571 dest->num_options = cupsAddOption("device-uri", uri, dest->num_options, &(dest->options));
1572 dest->num_options = cupsAddOption("printer-info", name, dest->num_options, &(dest->options));
1573
1574 return (dest);
1575 }
1576
1577
1578 /*
1579 * '_cupsGetDests()' - Get destinations from a server.
1580 *
1581 * "op" is IPP_OP_CUPS_GET_PRINTERS to get a full list, IPP_OP_CUPS_GET_DEFAULT
1582 * to get the system-wide default printer, or IPP_OP_GET_PRINTER_ATTRIBUTES for
1583 * a known printer.
1584 *
1585 * "name" is the name of an existing printer and is only used when "op" is
1586 * IPP_OP_GET_PRINTER_ATTRIBUTES.
1587 *
1588 * "dest" is initialized to point to the array of destinations.
1589 *
1590 * 0 is returned if there are no printers, no default printer, or the named
1591 * printer does not exist, respectively.
1592 *
1593 * Free the memory used by the destination array using the @link cupsFreeDests@
1594 * function.
1595 *
1596 * Note: On macOS this function also gets the default paper from the system
1597 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1598 * options array for each destination that supports it.
1599 */
1600
1601 int /* O - Number of destinations */
1602 _cupsGetDests(http_t *http, /* I - Connection to server or
1603 * @code CUPS_HTTP_DEFAULT@ */
1604 ipp_op_t op, /* I - IPP operation */
1605 const char *name, /* I - Name of destination */
1606 cups_dest_t **dests, /* IO - Destinations */
1607 cups_ptype_t type, /* I - Printer type bits */
1608 cups_ptype_t mask) /* I - Printer type mask */
1609 {
1610 int num_dests = 0; /* Number of destinations */
1611 cups_dest_t *dest; /* Current destination */
1612 ipp_t *request, /* IPP Request */
1613 *response; /* IPP Response */
1614 ipp_attribute_t *attr; /* Current attribute */
1615 const char *printer_name; /* printer-name attribute */
1616 char uri[1024]; /* printer-uri value */
1617 int num_options; /* Number of options */
1618 cups_option_t *options; /* Options */
1619 #ifdef __APPLE__
1620 char media_default[41]; /* Default paper size */
1621 #endif /* __APPLE__ */
1622 char optname[1024], /* Option name */
1623 value[2048], /* Option value */
1624 *ptr; /* Pointer into name/value */
1625 static const char * const pattrs[] = /* Attributes we're interested in */
1626 {
1627 "auth-info-required",
1628 "device-uri",
1629 "job-sheets-default",
1630 "marker-change-time",
1631 "marker-colors",
1632 "marker-high-levels",
1633 "marker-levels",
1634 "marker-low-levels",
1635 "marker-message",
1636 "marker-names",
1637 "marker-types",
1638 #ifdef __APPLE__
1639 "media-supported",
1640 #endif /* __APPLE__ */
1641 "printer-commands",
1642 "printer-defaults",
1643 "printer-info",
1644 "printer-is-accepting-jobs",
1645 "printer-is-shared",
1646 "printer-location",
1647 "printer-make-and-model",
1648 "printer-mandatory-job-attributes",
1649 "printer-name",
1650 "printer-state",
1651 "printer-state-change-time",
1652 "printer-state-reasons",
1653 "printer-type",
1654 "printer-uri-supported"
1655 };
1656
1657
1658 #ifdef __APPLE__
1659 /*
1660 * Get the default paper size...
1661 */
1662
1663 appleGetPaperSize(media_default, sizeof(media_default));
1664 #endif /* __APPLE__ */
1665
1666 /*
1667 * Build a IPP_OP_CUPS_GET_PRINTERS or IPP_OP_GET_PRINTER_ATTRIBUTES request, which
1668 * require the following attributes:
1669 *
1670 * attributes-charset
1671 * attributes-natural-language
1672 * requesting-user-name
1673 * printer-uri [for IPP_OP_GET_PRINTER_ATTRIBUTES]
1674 */
1675
1676 request = ippNewRequest(op);
1677
1678 ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
1679 "requested-attributes", sizeof(pattrs) / sizeof(pattrs[0]),
1680 NULL, pattrs);
1681
1682 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
1683 "requesting-user-name", NULL, cupsUser());
1684
1685 if (name && op != IPP_OP_CUPS_GET_DEFAULT)
1686 {
1687 httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
1688 "localhost", ippPort(), "/printers/%s", name);
1689 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL,
1690 uri);
1691 }
1692 else if (mask)
1693 {
1694 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type", (int)type);
1695 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type-mask", (int)mask);
1696 }
1697
1698 /*
1699 * Do the request and get back a response...
1700 */
1701
1702 if ((response = cupsDoRequest(http, request, "/")) != NULL)
1703 {
1704 for (attr = response->attrs; attr != NULL; attr = attr->next)
1705 {
1706 /*
1707 * Skip leading attributes until we hit a printer...
1708 */
1709
1710 while (attr != NULL && attr->group_tag != IPP_TAG_PRINTER)
1711 attr = attr->next;
1712
1713 if (attr == NULL)
1714 break;
1715
1716 /*
1717 * Pull the needed attributes from this printer...
1718 */
1719
1720 printer_name = NULL;
1721 num_options = 0;
1722 options = NULL;
1723
1724 for (; attr && attr->group_tag == IPP_TAG_PRINTER; attr = attr->next)
1725 {
1726 if (attr->value_tag != IPP_TAG_INTEGER &&
1727 attr->value_tag != IPP_TAG_ENUM &&
1728 attr->value_tag != IPP_TAG_BOOLEAN &&
1729 attr->value_tag != IPP_TAG_TEXT &&
1730 attr->value_tag != IPP_TAG_TEXTLANG &&
1731 attr->value_tag != IPP_TAG_NAME &&
1732 attr->value_tag != IPP_TAG_NAMELANG &&
1733 attr->value_tag != IPP_TAG_KEYWORD &&
1734 attr->value_tag != IPP_TAG_RANGE &&
1735 attr->value_tag != IPP_TAG_URI)
1736 continue;
1737
1738 if (!strcmp(attr->name, "auth-info-required") ||
1739 !strcmp(attr->name, "device-uri") ||
1740 !strcmp(attr->name, "marker-change-time") ||
1741 !strcmp(attr->name, "marker-colors") ||
1742 !strcmp(attr->name, "marker-high-levels") ||
1743 !strcmp(attr->name, "marker-levels") ||
1744 !strcmp(attr->name, "marker-low-levels") ||
1745 !strcmp(attr->name, "marker-message") ||
1746 !strcmp(attr->name, "marker-names") ||
1747 !strcmp(attr->name, "marker-types") ||
1748 !strcmp(attr->name, "printer-commands") ||
1749 !strcmp(attr->name, "printer-info") ||
1750 !strcmp(attr->name, "printer-is-shared") ||
1751 !strcmp(attr->name, "printer-make-and-model") ||
1752 !strcmp(attr->name, "printer-mandatory-job-attributes") ||
1753 !strcmp(attr->name, "printer-state") ||
1754 !strcmp(attr->name, "printer-state-change-time") ||
1755 !strcmp(attr->name, "printer-type") ||
1756 !strcmp(attr->name, "printer-is-accepting-jobs") ||
1757 !strcmp(attr->name, "printer-location") ||
1758 !strcmp(attr->name, "printer-state-reasons") ||
1759 !strcmp(attr->name, "printer-uri-supported"))
1760 {
1761 /*
1762 * Add a printer description attribute...
1763 */
1764
1765 num_options = cupsAddOption(attr->name,
1766 cups_make_string(attr, value,
1767 sizeof(value)),
1768 num_options, &options);
1769 }
1770 #ifdef __APPLE__
1771 else if (!strcmp(attr->name, "media-supported"))
1772 {
1773 /*
1774 * See if we can set a default media size...
1775 */
1776
1777 int i; /* Looping var */
1778
1779 for (i = 0; i < attr->num_values; i ++)
1780 if (!_cups_strcasecmp(media_default, attr->values[i].string.text))
1781 {
1782 num_options = cupsAddOption("media", media_default, num_options,
1783 &options);
1784 break;
1785 }
1786 }
1787 #endif /* __APPLE__ */
1788 else if (!strcmp(attr->name, "printer-name") &&
1789 attr->value_tag == IPP_TAG_NAME)
1790 printer_name = attr->values[0].string.text;
1791 else if (strncmp(attr->name, "notify-", 7) &&
1792 (attr->value_tag == IPP_TAG_BOOLEAN ||
1793 attr->value_tag == IPP_TAG_ENUM ||
1794 attr->value_tag == IPP_TAG_INTEGER ||
1795 attr->value_tag == IPP_TAG_KEYWORD ||
1796 attr->value_tag == IPP_TAG_NAME ||
1797 attr->value_tag == IPP_TAG_RANGE) &&
1798 (ptr = strstr(attr->name, "-default")) != NULL)
1799 {
1800 /*
1801 * Add a default option...
1802 */
1803
1804 strlcpy(optname, attr->name, sizeof(optname));
1805 optname[ptr - attr->name] = '\0';
1806
1807 if (_cups_strcasecmp(optname, "media") ||
1808 !cupsGetOption("media", num_options, options))
1809 num_options = cupsAddOption(optname,
1810 cups_make_string(attr, value,
1811 sizeof(value)),
1812 num_options, &options);
1813 }
1814 }
1815
1816 /*
1817 * See if we have everything needed...
1818 */
1819
1820 if (!printer_name)
1821 {
1822 cupsFreeOptions(num_options, options);
1823
1824 if (attr == NULL)
1825 break;
1826 else
1827 continue;
1828 }
1829
1830 if ((dest = cups_add_dest(printer_name, NULL, &num_dests, dests)) != NULL)
1831 {
1832 dest->num_options = num_options;
1833 dest->options = options;
1834 }
1835 else
1836 cupsFreeOptions(num_options, options);
1837
1838 if (attr == NULL)
1839 break;
1840 }
1841
1842 ippDelete(response);
1843 }
1844
1845 /*
1846 * Return the count...
1847 */
1848
1849 return (num_dests);
1850 }
1851
1852
1853 /*
1854 * 'cupsGetDests()' - Get the list of destinations from the default server.
1855 *
1856 * Starting with CUPS 1.2, the returned list of destinations include the
1857 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1858 * printer-make-and-model, printer-state, printer-state-change-time,
1859 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1860 * adds the marker-change-time, marker-colors, marker-high-levels,
1861 * marker-levels, marker-low-levels, marker-message, marker-names,
1862 * marker-types, and printer-commands attributes as well.
1863 *
1864 * Use the @link cupsFreeDests@ function to free the destination list and
1865 * the @link cupsGetDest@ function to find a particular destination.
1866 */
1867
1868 int /* O - Number of destinations */
1869 cupsGetDests(cups_dest_t **dests) /* O - Destinations */
1870 {
1871 return (cupsGetDests2(CUPS_HTTP_DEFAULT, dests));
1872 }
1873
1874
1875 /*
1876 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1877 *
1878 * Starting with CUPS 1.2, the returned list of destinations include the
1879 * printer-info, printer-is-accepting-jobs, printer-is-shared,
1880 * printer-make-and-model, printer-state, printer-state-change-time,
1881 * printer-state-reasons, and printer-type attributes as options. CUPS 1.4
1882 * adds the marker-change-time, marker-colors, marker-high-levels,
1883 * marker-levels, marker-low-levels, marker-message, marker-names,
1884 * marker-types, and printer-commands attributes as well.
1885 *
1886 * Use the @link cupsFreeDests@ function to free the destination list and
1887 * the @link cupsGetDest@ function to find a particular destination.
1888 *
1889 * @since CUPS 1.1.21/macOS 10.4@
1890 */
1891
1892 int /* O - Number of destinations */
1893 cupsGetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1894 cups_dest_t **dests) /* O - Destinations */
1895 {
1896 int num_dests; /* Number of destinations */
1897 cups_dest_t *dest; /* Destination pointer */
1898 const char *home; /* HOME environment variable */
1899 char filename[1024]; /* Local ~/.cups/lpoptions file */
1900 const char *defprinter; /* Default printer */
1901 char name[1024], /* Copy of printer name */
1902 *instance, /* Pointer to instance name */
1903 *user_default; /* User default printer */
1904 int num_reals; /* Number of real queues */
1905 cups_dest_t *reals; /* Real queues */
1906 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
1907
1908
1909 /*
1910 * Range check the input...
1911 */
1912
1913 if (!dests)
1914 {
1915 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad NULL dests pointer"), 1);
1916 return (0);
1917 }
1918
1919 /*
1920 * Grab the printers and classes...
1921 */
1922
1923 *dests = (cups_dest_t *)0;
1924 num_dests = _cupsGetDests(http, IPP_OP_CUPS_GET_PRINTERS, NULL, dests, 0, CUPS_PRINTER_3D);
1925
1926 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE)
1927 {
1928 cupsFreeDests(num_dests, *dests);
1929 *dests = (cups_dest_t *)0;
1930 return (0);
1931 }
1932
1933 /*
1934 * Make a copy of the "real" queues for a later sanity check...
1935 */
1936
1937 if (num_dests > 0)
1938 {
1939 num_reals = num_dests;
1940 reals = calloc((size_t)num_reals, sizeof(cups_dest_t));
1941
1942 if (reals)
1943 memcpy(reals, *dests, (size_t)num_reals * sizeof(cups_dest_t));
1944 else
1945 num_reals = 0;
1946 }
1947 else
1948 {
1949 num_reals = 0;
1950 reals = NULL;
1951 }
1952
1953 /*
1954 * Grab the default destination...
1955 */
1956
1957 if ((user_default = _cupsUserDefault(name, sizeof(name))) != NULL)
1958 defprinter = name;
1959 else if ((defprinter = cupsGetDefault2(http)) != NULL)
1960 {
1961 strlcpy(name, defprinter, sizeof(name));
1962 defprinter = name;
1963 }
1964
1965 if (defprinter)
1966 {
1967 /*
1968 * Separate printer and instance name...
1969 */
1970
1971 if ((instance = strchr(name, '/')) != NULL)
1972 *instance++ = '\0';
1973
1974 /*
1975 * Lookup the printer and instance and make it the default...
1976 */
1977
1978 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) != NULL)
1979 dest->is_default = 1;
1980 }
1981 else
1982 instance = NULL;
1983
1984 /*
1985 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
1986 */
1987
1988 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
1989 num_dests = cups_get_dests(filename, NULL, NULL, user_default != NULL,
1990 num_dests, dests);
1991
1992 if ((home = getenv("HOME")) != NULL)
1993 {
1994 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
1995
1996 num_dests = cups_get_dests(filename, NULL, NULL, user_default != NULL,
1997 num_dests, dests);
1998 }
1999
2000 /*
2001 * Validate the current default destination - this prevents old
2002 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
2003 * pointing to a non-existent printer or class...
2004 */
2005
2006 if (num_reals)
2007 {
2008 /*
2009 * See if we have a default printer...
2010 */
2011
2012 if ((dest = cupsGetDest(NULL, NULL, num_dests, *dests)) != NULL)
2013 {
2014 /*
2015 * Have a default; see if it is real...
2016 */
2017
2018 if (!cupsGetDest(dest->name, NULL, num_reals, reals))
2019 {
2020 /*
2021 * Remove the non-real printer from the list, since we don't want jobs
2022 * going to an unexpected printer... (<rdar://problem/14216472>)
2023 */
2024
2025 num_dests = cupsRemoveDest(dest->name, dest->instance, num_dests,
2026 dests);
2027 }
2028 }
2029
2030 /*
2031 * Free memory...
2032 */
2033
2034 free(reals);
2035 }
2036
2037 /*
2038 * Return the number of destinations...
2039 */
2040
2041 if (num_dests > 0)
2042 _cupsSetError(IPP_STATUS_OK, NULL, 0);
2043
2044 return (num_dests);
2045 }
2046
2047
2048 /*
2049 * 'cupsGetNamedDest()' - Get options for the named destination.
2050 *
2051 * This function is optimized for retrieving a single destination and should
2052 * be used instead of @link cupsGetDests@ and @link cupsGetDest@ when you either
2053 * know the name of the destination or want to print to the default destination.
2054 * If @code NULL@ is returned, the destination does not exist or there is no
2055 * default destination.
2056 *
2057 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
2058 * server will be used.
2059 *
2060 * If "name" is @code NULL@, the default printer for the current user will be
2061 * returned.
2062 *
2063 * The returned destination must be freed using @link cupsFreeDests@ with a
2064 * "num_dests" value of 1.
2065 *
2066 * @since CUPS 1.4/macOS 10.6@
2067 */
2068
2069 cups_dest_t * /* O - Destination or @code NULL@ */
2070 cupsGetNamedDest(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2071 const char *name, /* I - Destination name or @code NULL@ for the default destination */
2072 const char *instance) /* I - Instance name or @code NULL@ */
2073 {
2074 cups_dest_t *dest; /* Destination */
2075 char filename[1024], /* Path to lpoptions */
2076 defname[256]; /* Default printer name */
2077 const char *home = getenv("HOME"); /* Home directory */
2078 int set_as_default = 0; /* Set returned destination as default */
2079 ipp_op_t op = IPP_OP_GET_PRINTER_ATTRIBUTES;
2080 /* IPP operation to get server ops */
2081 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
2082
2083
2084 /*
2085 * If "name" is NULL, find the default destination...
2086 */
2087
2088 if (!name)
2089 {
2090 set_as_default = 1;
2091 name = _cupsUserDefault(defname, sizeof(defname));
2092
2093 if (name)
2094 {
2095 char *ptr; /* Temporary pointer... */
2096
2097 if ((ptr = strchr(defname, '/')) != NULL)
2098 {
2099 *ptr++ = '\0';
2100 instance = ptr;
2101 }
2102 else
2103 instance = NULL;
2104 }
2105 else if (home)
2106 {
2107 /*
2108 * No default in the environment, try the user's lpoptions files...
2109 */
2110
2111 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2112
2113 name = cups_get_default(filename, defname, sizeof(defname), &instance);
2114 }
2115
2116 if (!name)
2117 {
2118 /*
2119 * Still not there? Try the system lpoptions file...
2120 */
2121
2122 snprintf(filename, sizeof(filename), "%s/lpoptions",
2123 cg->cups_serverroot);
2124 name = cups_get_default(filename, defname, sizeof(defname), &instance);
2125 }
2126
2127 if (!name)
2128 {
2129 /*
2130 * No locally-set default destination, ask the server...
2131 */
2132
2133 op = IPP_OP_CUPS_GET_DEFAULT;
2134 }
2135 }
2136
2137 /*
2138 * Get the printer's attributes...
2139 */
2140
2141 if (!_cupsGetDests(http, op, name, &dest, 0, CUPS_PRINTER_3D))
2142 return (NULL);
2143
2144 if (instance)
2145 dest->instance = _cupsStrAlloc(instance);
2146
2147 if (set_as_default)
2148 dest->is_default = 1;
2149
2150 /*
2151 * Then add local options...
2152 */
2153
2154 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
2155 cups_get_dests(filename, name, instance, 1, 1, &dest);
2156
2157 if (home)
2158 {
2159 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2160
2161 cups_get_dests(filename, name, instance, 1, 1, &dest);
2162 }
2163
2164 /*
2165 * Return the result...
2166 */
2167
2168 return (dest);
2169 }
2170
2171
2172 /*
2173 * 'cupsRemoveDest()' - Remove a destination from the destination list.
2174 *
2175 * Removing a destination/instance does not delete the class or printer
2176 * queue, merely the lpoptions for that destination/instance. Use the
2177 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
2178 * options for the user.
2179 *
2180 * @since CUPS 1.3/macOS 10.5@
2181 */
2182
2183 int /* O - New number of destinations */
2184 cupsRemoveDest(const char *name, /* I - Destination name */
2185 const char *instance, /* I - Instance name or @code NULL@ */
2186 int num_dests, /* I - Number of destinations */
2187 cups_dest_t **dests) /* IO - Destinations */
2188 {
2189 int i; /* Index into destinations */
2190 cups_dest_t *dest; /* Pointer to destination */
2191
2192
2193 /*
2194 * Find the destination...
2195 */
2196
2197 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
2198 return (num_dests);
2199
2200 /*
2201 * Free memory...
2202 */
2203
2204 _cupsStrFree(dest->name);
2205 _cupsStrFree(dest->instance);
2206 cupsFreeOptions(dest->num_options, dest->options);
2207
2208 /*
2209 * Remove the destination from the array...
2210 */
2211
2212 num_dests --;
2213
2214 i = (int)(dest - *dests);
2215
2216 if (i < num_dests)
2217 memmove(dest, dest + 1, (size_t)(num_dests - i) * sizeof(cups_dest_t));
2218
2219 return (num_dests);
2220 }
2221
2222
2223 /*
2224 * 'cupsSetDefaultDest()' - Set the default destination.
2225 *
2226 * @since CUPS 1.3/macOS 10.5@
2227 */
2228
2229 void
2230 cupsSetDefaultDest(
2231 const char *name, /* I - Destination name */
2232 const char *instance, /* I - Instance name or @code NULL@ */
2233 int num_dests, /* I - Number of destinations */
2234 cups_dest_t *dests) /* I - Destinations */
2235 {
2236 int i; /* Looping var */
2237 cups_dest_t *dest; /* Current destination */
2238
2239
2240 /*
2241 * Range check input...
2242 */
2243
2244 if (!name || num_dests <= 0 || !dests)
2245 return;
2246
2247 /*
2248 * Loop through the array and set the "is_default" flag for the matching
2249 * destination...
2250 */
2251
2252 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
2253 dest->is_default = !_cups_strcasecmp(name, dest->name) &&
2254 ((!instance && !dest->instance) ||
2255 (instance && dest->instance &&
2256 !_cups_strcasecmp(instance, dest->instance)));
2257 }
2258
2259
2260 /*
2261 * 'cupsSetDests()' - Save the list of destinations for the default server.
2262 *
2263 * This function saves the destinations to /etc/cups/lpoptions when run
2264 * as root and ~/.cups/lpoptions when run as a normal user.
2265 */
2266
2267 void
2268 cupsSetDests(int num_dests, /* I - Number of destinations */
2269 cups_dest_t *dests) /* I - Destinations */
2270 {
2271 cupsSetDests2(CUPS_HTTP_DEFAULT, num_dests, dests);
2272 }
2273
2274
2275 /*
2276 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
2277 *
2278 * This function saves the destinations to /etc/cups/lpoptions when run
2279 * as root and ~/.cups/lpoptions when run as a normal user.
2280 *
2281 * @since CUPS 1.1.21/macOS 10.4@
2282 */
2283
2284 int /* O - 0 on success, -1 on error */
2285 cupsSetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2286 int num_dests, /* I - Number of destinations */
2287 cups_dest_t *dests) /* I - Destinations */
2288 {
2289 int i, j; /* Looping vars */
2290 int wrote; /* Wrote definition? */
2291 cups_dest_t *dest; /* Current destination */
2292 cups_option_t *option; /* Current option */
2293 _ipp_option_t *match; /* Matching attribute for option */
2294 FILE *fp; /* File pointer */
2295 #ifndef WIN32
2296 const char *home; /* HOME environment variable */
2297 #endif /* WIN32 */
2298 char filename[1024]; /* lpoptions file */
2299 int num_temps; /* Number of temporary destinations */
2300 cups_dest_t *temps = NULL, /* Temporary destinations */
2301 *temp; /* Current temporary dest */
2302 const char *val; /* Value of temporary option */
2303 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
2304
2305
2306 /*
2307 * Range check the input...
2308 */
2309
2310 if (!num_dests || !dests)
2311 return (-1);
2312
2313 /*
2314 * Get the server destinations...
2315 */
2316
2317 num_temps = _cupsGetDests(http, IPP_OP_CUPS_GET_PRINTERS, NULL, &temps, 0, CUPS_PRINTER_3D);
2318
2319 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE)
2320 {
2321 cupsFreeDests(num_temps, temps);
2322 return (-1);
2323 }
2324
2325 /*
2326 * Figure out which file to write to...
2327 */
2328
2329 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
2330
2331 #ifndef WIN32
2332 if (getuid())
2333 {
2334 /*
2335 * Merge in server defaults...
2336 */
2337
2338 num_temps = cups_get_dests(filename, NULL, NULL, 0, num_temps, &temps);
2339
2340 /*
2341 * Point to user defaults...
2342 */
2343
2344 if ((home = getenv("HOME")) != NULL)
2345 {
2346 /*
2347 * Create ~/.cups subdirectory...
2348 */
2349
2350 snprintf(filename, sizeof(filename), "%s/.cups", home);
2351 if (access(filename, 0))
2352 mkdir(filename, 0700);
2353
2354 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2355 }
2356 }
2357 #endif /* !WIN32 */
2358
2359 /*
2360 * Try to open the file...
2361 */
2362
2363 if ((fp = fopen(filename, "w")) == NULL)
2364 {
2365 cupsFreeDests(num_temps, temps);
2366 return (-1);
2367 }
2368
2369 #ifndef WIN32
2370 /*
2371 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2372 * file...
2373 */
2374
2375 if (!getuid())
2376 fchmod(fileno(fp), 0644);
2377 #endif /* !WIN32 */
2378
2379 /*
2380 * Write each printer; each line looks like:
2381 *
2382 * Dest name[/instance] options
2383 * Default name[/instance] options
2384 */
2385
2386 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
2387 if (dest->instance != NULL || dest->num_options != 0 || dest->is_default)
2388 {
2389 if (dest->is_default)
2390 {
2391 fprintf(fp, "Default %s", dest->name);
2392 if (dest->instance)
2393 fprintf(fp, "/%s", dest->instance);
2394
2395 wrote = 1;
2396 }
2397 else
2398 wrote = 0;
2399
2400 if ((temp = cupsGetDest(dest->name, dest->instance, num_temps, temps)) == NULL)
2401 temp = cupsGetDest(dest->name, NULL, num_temps, temps);
2402
2403 for (j = dest->num_options, option = dest->options; j > 0; j --, option ++)
2404 {
2405 /*
2406 * See if this option is a printer attribute; if so, skip it...
2407 */
2408
2409 if ((match = _ippFindOption(option->name)) != NULL &&
2410 match->group_tag == IPP_TAG_PRINTER)
2411 continue;
2412
2413 /*
2414 * See if the server/global options match these; if so, don't
2415 * write 'em.
2416 */
2417
2418 if (temp &&
2419 (val = cupsGetOption(option->name, temp->num_options,
2420 temp->options)) != NULL &&
2421 !_cups_strcasecmp(val, option->value))
2422 continue;
2423
2424 /*
2425 * Options don't match, write to the file...
2426 */
2427
2428 if (!wrote)
2429 {
2430 fprintf(fp, "Dest %s", dest->name);
2431 if (dest->instance)
2432 fprintf(fp, "/%s", dest->instance);
2433 wrote = 1;
2434 }
2435
2436 if (option->value[0])
2437 {
2438 if (strchr(option->value, ' ') ||
2439 strchr(option->value, '\\') ||
2440 strchr(option->value, '\"') ||
2441 strchr(option->value, '\''))
2442 {
2443 /*
2444 * Quote the value...
2445 */
2446
2447 fprintf(fp, " %s=\"", option->name);
2448
2449 for (val = option->value; *val; val ++)
2450 {
2451 if (strchr("\"\'\\", *val))
2452 putc('\\', fp);
2453
2454 putc(*val, fp);
2455 }
2456
2457 putc('\"', fp);
2458 }
2459 else
2460 {
2461 /*
2462 * Store the literal value...
2463 */
2464
2465 fprintf(fp, " %s=%s", option->name, option->value);
2466 }
2467 }
2468 else
2469 fprintf(fp, " %s", option->name);
2470 }
2471
2472 if (wrote)
2473 fputs("\n", fp);
2474 }
2475
2476 /*
2477 * Free the temporary destinations and close the file...
2478 */
2479
2480 cupsFreeDests(num_temps, temps);
2481
2482 fclose(fp);
2483
2484 #ifdef __APPLE__
2485 /*
2486 * Set the default printer for this location - this allows command-line
2487 * and GUI applications to share the same default destination...
2488 */
2489
2490 if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) != NULL)
2491 {
2492 CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault,
2493 dest->name,
2494 kCFStringEncodingUTF8);
2495 /* Default printer name */
2496
2497 if (name)
2498 {
2499 _cupsAppleSetDefaultPrinter(name);
2500 CFRelease(name);
2501 }
2502 }
2503 #endif /* __APPLE__ */
2504
2505 #ifdef HAVE_NOTIFY_POST
2506 /*
2507 * Send a notification so that macOS applications can know about the
2508 * change, too.
2509 */
2510
2511 notify_post("com.apple.printerListChange");
2512 #endif /* HAVE_NOTIFY_POST */
2513
2514 return (0);
2515 }
2516
2517
2518 /*
2519 * '_cupsUserDefault()' - Get the user default printer from environment
2520 * variables and location information.
2521 */
2522
2523 char * /* O - Default printer or NULL */
2524 _cupsUserDefault(char *name, /* I - Name buffer */
2525 size_t namesize) /* I - Size of name buffer */
2526 {
2527 const char *env; /* LPDEST or PRINTER env variable */
2528 #ifdef __APPLE__
2529 CFStringRef locprinter; /* Last printer as this location */
2530 #endif /* __APPLE__ */
2531
2532
2533 if ((env = getenv("LPDEST")) == NULL)
2534 if ((env = getenv("PRINTER")) != NULL && !strcmp(env, "lp"))
2535 env = NULL;
2536
2537 if (env)
2538 {
2539 strlcpy(name, env, namesize);
2540 return (name);
2541 }
2542
2543 #ifdef __APPLE__
2544 /*
2545 * Use location-based defaults if "use last printer" is selected in the
2546 * system preferences...
2547 */
2548
2549 if ((locprinter = _cupsAppleCopyDefaultPrinter()) != NULL)
2550 {
2551 CFStringGetCString(locprinter, name, (CFIndex)namesize, kCFStringEncodingUTF8);
2552 CFRelease(locprinter);
2553 }
2554 else
2555 name[0] = '\0';
2556
2557 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name));
2558
2559 return (*name ? name : NULL);
2560
2561 #else
2562 /*
2563 * No location-based defaults on this platform...
2564 */
2565
2566 name[0] = '\0';
2567 return (NULL);
2568 #endif /* __APPLE__ */
2569 }
2570
2571
2572 #if _CUPS_LOCATION_DEFAULTS
2573 /*
2574 * 'appleCopyLocations()' - Copy the location history array.
2575 */
2576
2577 static CFArrayRef /* O - Location array or NULL */
2578 appleCopyLocations(void)
2579 {
2580 CFArrayRef locations; /* Location array */
2581
2582
2583 /*
2584 * Look up the location array in the preferences...
2585 */
2586
2587 if ((locations = CFPreferencesCopyAppValue(kLastUsedPrintersKey,
2588 kCUPSPrintingPrefs)) == NULL)
2589 return (NULL);
2590
2591 if (CFGetTypeID(locations) != CFArrayGetTypeID())
2592 {
2593 CFRelease(locations);
2594 return (NULL);
2595 }
2596
2597 return (locations);
2598 }
2599
2600
2601 /*
2602 * 'appleCopyNetwork()' - Get the network ID for the current location.
2603 */
2604
2605 static CFStringRef /* O - Network ID */
2606 appleCopyNetwork(void)
2607 {
2608 SCDynamicStoreRef dynamicStore; /* System configuration data */
2609 CFStringRef key; /* Current network configuration key */
2610 CFDictionaryRef ip_dict; /* Network configuration data */
2611 CFStringRef network = NULL; /* Current network ID */
2612
2613
2614 if ((dynamicStore = SCDynamicStoreCreate(NULL, CFSTR("libcups"), NULL,
2615 NULL)) != NULL)
2616 {
2617 /*
2618 * First use the IPv6 router address, if available, since that will generally
2619 * be a globally-unique link-local address.
2620 */
2621
2622 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
2623 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv6)) != NULL)
2624 {
2625 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2626 {
2627 if ((network = CFDictionaryGetValue(ip_dict,
2628 kSCPropNetIPv6Router)) != NULL)
2629 CFRetain(network);
2630
2631 CFRelease(ip_dict);
2632 }
2633
2634 CFRelease(key);
2635 }
2636
2637 /*
2638 * If that doesn't work, try the IPv4 router address. This isn't as unique
2639 * and will likely be a 10.x.y.z or 192.168.y.z address...
2640 */
2641
2642 if (!network)
2643 {
2644 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
2645 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4)) != NULL)
2646 {
2647 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2648 {
2649 if ((network = CFDictionaryGetValue(ip_dict,
2650 kSCPropNetIPv4Router)) != NULL)
2651 CFRetain(network);
2652
2653 CFRelease(ip_dict);
2654 }
2655
2656 CFRelease(key);
2657 }
2658 }
2659
2660 CFRelease(dynamicStore);
2661 }
2662
2663 return (network);
2664 }
2665 #endif /* _CUPS_LOCATION_DEFAULTS */
2666
2667
2668 #ifdef __APPLE__
2669 /*
2670 * 'appleGetPaperSize()' - Get the default paper size.
2671 */
2672
2673 static char * /* O - Default paper size */
2674 appleGetPaperSize(char *name, /* I - Paper size name buffer */
2675 size_t namesize) /* I - Size of buffer */
2676 {
2677 CFStringRef defaultPaperID; /* Default paper ID */
2678 pwg_media_t *pwgmedia; /* PWG media size */
2679
2680
2681 defaultPaperID = _cupsAppleCopyDefaultPaperID();
2682 if (!defaultPaperID ||
2683 CFGetTypeID(defaultPaperID) != CFStringGetTypeID() ||
2684 !CFStringGetCString(defaultPaperID, name, (CFIndex)namesize, kCFStringEncodingUTF8))
2685 name[0] = '\0';
2686 else if ((pwgmedia = pwgMediaForLegacy(name)) != NULL)
2687 strlcpy(name, pwgmedia->pwg, namesize);
2688
2689 if (defaultPaperID)
2690 CFRelease(defaultPaperID);
2691
2692 return (name);
2693 }
2694 #endif /* __APPLE__ */
2695
2696
2697 #if _CUPS_LOCATION_DEFAULTS
2698 /*
2699 * 'appleGetPrinter()' - Get a printer from the history array.
2700 */
2701
2702 static CFStringRef /* O - Printer name or NULL */
2703 appleGetPrinter(CFArrayRef locations, /* I - Location array */
2704 CFStringRef network, /* I - Network name */
2705 CFIndex *locindex) /* O - Index in array */
2706 {
2707 CFIndex i, /* Looping var */
2708 count; /* Number of locations */
2709 CFDictionaryRef location; /* Current location */
2710 CFStringRef locnetwork, /* Current network */
2711 locprinter; /* Current printer */
2712
2713
2714 for (i = 0, count = CFArrayGetCount(locations); i < count; i ++)
2715 if ((location = CFArrayGetValueAtIndex(locations, i)) != NULL &&
2716 CFGetTypeID(location) == CFDictionaryGetTypeID())
2717 {
2718 if ((locnetwork = CFDictionaryGetValue(location,
2719 kLocationNetworkKey)) != NULL &&
2720 CFGetTypeID(locnetwork) == CFStringGetTypeID() &&
2721 CFStringCompare(network, locnetwork, 0) == kCFCompareEqualTo &&
2722 (locprinter = CFDictionaryGetValue(location,
2723 kLocationPrinterIDKey)) != NULL &&
2724 CFGetTypeID(locprinter) == CFStringGetTypeID())
2725 {
2726 if (locindex)
2727 *locindex = i;
2728
2729 return (locprinter);
2730 }
2731 }
2732
2733 return (NULL);
2734 }
2735 #endif /* _CUPS_LOCATION_DEFAULTS */
2736
2737
2738 /*
2739 * 'cups_add_dest()' - Add a destination to the array.
2740 *
2741 * Unlike cupsAddDest(), this function does not check for duplicates.
2742 */
2743
2744 static cups_dest_t * /* O - New destination */
2745 cups_add_dest(const char *name, /* I - Name of destination */
2746 const char *instance, /* I - Instance or NULL */
2747 int *num_dests, /* IO - Number of destinations */
2748 cups_dest_t **dests) /* IO - Destinations */
2749 {
2750 int insert, /* Insertion point */
2751 diff; /* Result of comparison */
2752 cups_dest_t *dest; /* Destination pointer */
2753
2754
2755 /*
2756 * Add new destination...
2757 */
2758
2759 if (*num_dests == 0)
2760 dest = malloc(sizeof(cups_dest_t));
2761 else
2762 dest = realloc(*dests, sizeof(cups_dest_t) * (size_t)(*num_dests + 1));
2763
2764 if (!dest)
2765 return (NULL);
2766
2767 *dests = dest;
2768
2769 /*
2770 * Find where to insert the destination...
2771 */
2772
2773 if (*num_dests == 0)
2774 insert = 0;
2775 else
2776 {
2777 insert = cups_find_dest(name, instance, *num_dests, *dests, *num_dests - 1,
2778 &diff);
2779
2780 if (diff > 0)
2781 insert ++;
2782 }
2783
2784 /*
2785 * Move the array elements as needed...
2786 */
2787
2788 if (insert < *num_dests)
2789 memmove(*dests + insert + 1, *dests + insert, (size_t)(*num_dests - insert) * sizeof(cups_dest_t));
2790
2791 (*num_dests) ++;
2792
2793 /*
2794 * Initialize the destination...
2795 */
2796
2797 dest = *dests + insert;
2798 dest->name = _cupsStrAlloc(name);
2799 dest->instance = _cupsStrAlloc(instance);
2800 dest->is_default = 0;
2801 dest->num_options = 0;
2802 dest->options = (cups_option_t *)0;
2803
2804 return (dest);
2805 }
2806
2807
2808 # ifdef __BLOCKS__
2809 /*
2810 * 'cups_block_cb()' - Enumeration callback for block API.
2811 */
2812
2813 static int /* O - 1 to continue, 0 to stop */
2814 cups_block_cb(
2815 cups_dest_block_t block, /* I - Block */
2816 unsigned flags, /* I - Destination flags */
2817 cups_dest_t *dest) /* I - Destination */
2818 {
2819 return ((block)(flags, dest));
2820 }
2821 # endif /* __BLOCKS__ */
2822
2823
2824 /*
2825 * 'cups_compare_dests()' - Compare two destinations.
2826 */
2827
2828 static int /* O - Result of comparison */
2829 cups_compare_dests(cups_dest_t *a, /* I - First destination */
2830 cups_dest_t *b) /* I - Second destination */
2831 {
2832 int diff; /* Difference */
2833
2834
2835 if ((diff = _cups_strcasecmp(a->name, b->name)) != 0)
2836 return (diff);
2837 else if (a->instance && b->instance)
2838 return (_cups_strcasecmp(a->instance, b->instance));
2839 else
2840 return ((a->instance && !b->instance) - (!a->instance && b->instance));
2841 }
2842
2843
2844 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
2845 # ifdef HAVE_DNSSD
2846 /*
2847 * 'cups_dnssd_browse_cb()' - Browse for printers.
2848 */
2849
2850 static void
2851 cups_dnssd_browse_cb(
2852 DNSServiceRef sdRef, /* I - Service reference */
2853 DNSServiceFlags flags, /* I - Option flags */
2854 uint32_t interfaceIndex, /* I - Interface number */
2855 DNSServiceErrorType errorCode, /* I - Error, if any */
2856 const char *serviceName, /* I - Name of service/device */
2857 const char *regtype, /* I - Type of service */
2858 const char *replyDomain, /* I - Service domain */
2859 void *context) /* I - Enumeration data */
2860 {
2861 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2862 /* Enumeration data */
2863
2864
2865 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));
2866
2867 /*
2868 * Don't do anything on error...
2869 */
2870
2871 if (errorCode != kDNSServiceErr_NoError)
2872 return;
2873
2874 /*
2875 * Get the device...
2876 */
2877
2878 cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
2879 }
2880
2881
2882 # else /* HAVE_AVAHI */
2883 /*
2884 * 'cups_dnssd_browse_cb()' - Browse for printers.
2885 */
2886
2887 static void
2888 cups_dnssd_browse_cb(
2889 AvahiServiceBrowser *browser, /* I - Browser */
2890 AvahiIfIndex interface, /* I - Interface index (unused) */
2891 AvahiProtocol protocol, /* I - Network protocol (unused) */
2892 AvahiBrowserEvent event, /* I - What happened */
2893 const char *name, /* I - Service name */
2894 const char *type, /* I - Registration type */
2895 const char *domain, /* I - Domain */
2896 AvahiLookupResultFlags flags, /* I - Flags */
2897 void *context) /* I - Devices array */
2898 {
2899 #ifdef DEBUG
2900 AvahiClient *client = avahi_service_browser_get_client(browser);
2901 /* Client information */
2902 #endif /* DEBUG */
2903 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2904 /* Enumeration data */
2905
2906
2907 (void)interface;
2908 (void)protocol;
2909 (void)context;
2910
2911 DEBUG_printf(("cups_dnssd_browse_cb(..., name=\"%s\", type=\"%s\", domain=\"%s\", ...);", name, type, domain));
2912
2913 switch (event)
2914 {
2915 case AVAHI_BROWSER_FAILURE:
2916 DEBUG_printf(("cups_dnssd_browse_cb: %s", avahi_strerror(avahi_client_errno(client))));
2917 avahi_simple_poll_quit(data->simple_poll);
2918 break;
2919
2920 case AVAHI_BROWSER_NEW:
2921 /*
2922 * This object is new on the network.
2923 */
2924
2925 if (flags & AVAHI_LOOKUP_RESULT_LOCAL)
2926 {
2927 /*
2928 * This comes from the local machine so ignore it.
2929 */
2930
2931 DEBUG_printf(("cups_dnssd_browse_cb: Ignoring local service \"%s\".", name));
2932 }
2933 else
2934 {
2935 /*
2936 * Create a device entry for it if it doesn't yet exist.
2937 */
2938
2939 cups_dnssd_get_device(data, name, type, domain);
2940 }
2941 break;
2942
2943 case AVAHI_BROWSER_REMOVE :
2944 case AVAHI_BROWSER_CACHE_EXHAUSTED :
2945 break;
2946
2947 case AVAHI_BROWSER_ALL_FOR_NOW :
2948 DEBUG_puts("cups_dnssd_browse_cb: ALL_FOR_NOW");
2949 data->browsers --;
2950 break;
2951 }
2952 }
2953
2954
2955 /*
2956 * 'cups_dnssd_client_cb()' - Avahi client callback function.
2957 */
2958
2959 static void
2960 cups_dnssd_client_cb(
2961 AvahiClient *client, /* I - Client information (unused) */
2962 AvahiClientState state, /* I - Current state */
2963 void *context) /* I - User data (unused) */
2964 {
2965 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2966 /* Enumeration data */
2967
2968
2969 (void)client;
2970
2971 DEBUG_printf(("cups_dnssd_client_cb(client=%p, state=%d, context=%p)", client, state, context));
2972
2973 /*
2974 * If the connection drops, quit.
2975 */
2976
2977 if (state == AVAHI_CLIENT_FAILURE)
2978 {
2979 DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
2980 avahi_simple_poll_quit(data->simple_poll);
2981 }
2982 }
2983 # endif /* HAVE_DNSSD */
2984
2985
2986 /*
2987 * 'cups_dnssd_compare_device()' - Compare two devices.
2988 */
2989
2990 static int /* O - Result of comparison */
2991 cups_dnssd_compare_devices(
2992 _cups_dnssd_device_t *a, /* I - First device */
2993 _cups_dnssd_device_t *b) /* I - Second device */
2994 {
2995 return (strcmp(a->dest.name, b->dest.name));
2996 }
2997
2998
2999 /*
3000 * 'cups_dnssd_free_device()' - Free the memory used by a device.
3001 */
3002
3003 static void
3004 cups_dnssd_free_device(
3005 _cups_dnssd_device_t *device, /* I - Device */
3006 _cups_dnssd_data_t *data) /* I - Enumeration data */
3007 {
3008 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", (void *)device, device->dest.name, (void *)data));
3009
3010 # ifdef HAVE_DNSSD
3011 if (device->ref)
3012 DNSServiceRefDeallocate(device->ref);
3013 # else /* HAVE_AVAHI */
3014 if (device->ref)
3015 avahi_record_browser_free(device->ref);
3016 # endif /* HAVE_DNSSD */
3017
3018 _cupsStrFree(device->domain);
3019 _cupsStrFree(device->fullName);
3020 _cupsStrFree(device->regtype);
3021 _cupsStrFree(device->dest.name);
3022
3023 cupsFreeOptions(device->dest.num_options, device->dest.options);
3024
3025 free(device);
3026 }
3027
3028
3029 /*
3030 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
3031 */
3032
3033 static _cups_dnssd_device_t * /* O - Device */
3034 cups_dnssd_get_device(
3035 _cups_dnssd_data_t *data, /* I - Enumeration data */
3036 const char *serviceName, /* I - Service name */
3037 const char *regtype, /* I - Registration type */
3038 const char *replyDomain) /* I - Domain name */
3039 {
3040 _cups_dnssd_device_t key, /* Search key */
3041 *device; /* Device */
3042 char fullName[kDNSServiceMaxDomainName],
3043 /* Full name for query */
3044 name[128]; /* Queue name */
3045
3046
3047 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", regtype=\"%s\", replyDomain=\"%s\")", (void *)data, serviceName, regtype, replyDomain));
3048
3049 /*
3050 * See if this is an existing device...
3051 */
3052
3053 cups_dnssd_queue_name(name, serviceName, sizeof(name));
3054
3055 key.dest.name = name;
3056
3057 if ((device = cupsArrayFind(data->devices, &key)) != NULL)
3058 {
3059 /*
3060 * Yes, see if we need to do anything with this...
3061 */
3062
3063 int update = 0; /* Non-zero if we need to update */
3064
3065 if (!_cups_strcasecmp(replyDomain, "local.") &&
3066 _cups_strcasecmp(device->domain, replyDomain))
3067 {
3068 /*
3069 * Update the "global" listing to use the .local domain name instead.
3070 */
3071
3072 _cupsStrFree(device->domain);
3073 device->domain = _cupsStrAlloc(replyDomain);
3074
3075 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
3076 "domain.", device->dest.name));
3077
3078 update = 1;
3079 }
3080
3081 if (!_cups_strcasecmp(regtype, "_ipps._tcp") &&
3082 _cups_strcasecmp(device->regtype, regtype))
3083 {
3084 /*
3085 * Prefer IPPS over IPP.
3086 */
3087
3088 _cupsStrFree(device->regtype);
3089 device->regtype = _cupsStrAlloc(regtype);
3090
3091 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
3092 device->dest.name));
3093
3094 update = 1;
3095 }
3096
3097 if (!update)
3098 {
3099 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
3100 device->dest.name));
3101 return (device);
3102 }
3103 }
3104 else
3105 {
3106 /*
3107 * No, add the device...
3108 */
3109
3110 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
3111 "'%s'.", serviceName,
3112 !strcmp(regtype, "_ipps._tcp") ? "IPPS" : "IPP",
3113 replyDomain));
3114
3115 device = calloc(sizeof(_cups_dnssd_device_t), 1);
3116 device->dest.name = _cupsStrAlloc(name);
3117 device->domain = _cupsStrAlloc(replyDomain);
3118 device->regtype = _cupsStrAlloc(regtype);
3119
3120 device->dest.num_options = cupsAddOption("printer-info", serviceName, 0, &device->dest.options);
3121
3122 cupsArrayAdd(data->devices, device);
3123 }
3124
3125 /*
3126 * Set the "full name" of this service, which is used for queries...
3127 */
3128
3129 # ifdef HAVE_DNSSD
3130 DNSServiceConstructFullName(fullName, serviceName, regtype, replyDomain);
3131 # else /* HAVE_AVAHI */
3132 avahi_service_name_join(fullName, kDNSServiceMaxDomainName, serviceName, regtype, replyDomain);
3133 # endif /* HAVE_DNSSD */
3134
3135 _cupsStrFree(device->fullName);
3136 device->fullName = _cupsStrAlloc(fullName);
3137
3138 if (device->ref)
3139 {
3140 # ifdef HAVE_DNSSD
3141 DNSServiceRefDeallocate(device->ref);
3142 # else /* HAVE_AVAHI */
3143 avahi_record_browser_free(device->ref);
3144 # endif /* HAVE_DNSSD */
3145
3146 device->ref = 0;
3147 }
3148
3149 if (device->state == _CUPS_DNSSD_ACTIVE)
3150 {
3151 DEBUG_printf(("6cups_dnssd_get_device: Remove callback for \"%s\".", device->dest.name));
3152
3153 (*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
3154 device->state = _CUPS_DNSSD_NEW;
3155 }
3156
3157 return (device);
3158 }
3159
3160
3161 # ifdef HAVE_DNSSD
3162 /*
3163 * 'cups_dnssd_local_cb()' - Browse for local printers.
3164 */
3165
3166 static void
3167 cups_dnssd_local_cb(
3168 DNSServiceRef sdRef, /* I - Service reference */
3169 DNSServiceFlags flags, /* I - Option flags */
3170 uint32_t interfaceIndex, /* I - Interface number */
3171 DNSServiceErrorType errorCode, /* I - Error, if any */
3172 const char *serviceName, /* I - Name of service/device */
3173 const char *regtype, /* I - Type of service */
3174 const char *replyDomain, /* I - Service domain */
3175 void *context) /* I - Devices array */
3176 {
3177 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3178 /* Enumeration data */
3179 _cups_dnssd_device_t *device; /* Device */
3180
3181
3182 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));
3183
3184 /*
3185 * Only process "add" data...
3186 */
3187
3188 if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
3189 return;
3190
3191 /*
3192 * Get the device...
3193 */
3194
3195 device = cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
3196
3197 /*
3198 * Hide locally-registered devices...
3199 */
3200
3201 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
3202 serviceName));
3203
3204 if (device->ref)
3205 {
3206 DNSServiceRefDeallocate(device->ref);
3207 device->ref = 0;
3208 }
3209
3210 if (device->state == _CUPS_DNSSD_ACTIVE)
3211 {
3212 DEBUG_printf(("6cups_dnssd_local_cb: Remove callback for \"%s\".", device->dest.name));
3213 (*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
3214 }
3215
3216 device->state = _CUPS_DNSSD_LOCAL;
3217 }
3218 # endif /* HAVE_DNSSD */
3219
3220
3221 # ifdef HAVE_AVAHI
3222 /*
3223 * 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
3224 *
3225 * Note: This function is needed because avahi_simple_poll_iterate is broken
3226 * and always uses a timeout of 0 (!) milliseconds.
3227 * (Avahi Ticket #364)
3228 */
3229
3230 static int /* O - Number of file descriptors matching */
3231 cups_dnssd_poll_cb(
3232 struct pollfd *pollfds, /* I - File descriptors */
3233 unsigned int num_pollfds, /* I - Number of file descriptors */
3234 int timeout, /* I - Timeout in milliseconds (unused) */
3235 void *context) /* I - User data (unused) */
3236 {
3237 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3238 /* Enumeration data */
3239 int val; /* Return value */
3240
3241
3242 DEBUG_printf(("cups_dnssd_poll_cb(pollfds=%p, num_pollfds=%d, timeout=%d, context=%p)", pollfds, num_pollfds, timeout, context));
3243
3244 (void)timeout;
3245
3246 val = poll(pollfds, num_pollfds, 500);
3247
3248 DEBUG_printf(("cups_dnssd_poll_cb: poll() returned %d", val));
3249
3250 if (val < 0)
3251 {
3252 DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno)));
3253 }
3254 else if (val > 0)
3255 {
3256 data->got_data = 1;
3257 }
3258
3259 return (val);
3260 }
3261 # endif /* HAVE_AVAHI */
3262
3263
3264 /*
3265 * 'cups_dnssd_query_cb()' - Process query data.
3266 */
3267
3268 # ifdef HAVE_DNSSD
3269 static void
3270 cups_dnssd_query_cb(
3271 DNSServiceRef sdRef, /* I - Service reference */
3272 DNSServiceFlags flags, /* I - Data flags */
3273 uint32_t interfaceIndex, /* I - Interface */
3274 DNSServiceErrorType errorCode, /* I - Error, if any */
3275 const char *fullName, /* I - Full service name */
3276 uint16_t rrtype, /* I - Record type */
3277 uint16_t rrclass, /* I - Record class */
3278 uint16_t rdlen, /* I - Length of record data */
3279 const void *rdata, /* I - Record data */
3280 uint32_t ttl, /* I - Time-to-live */
3281 void *context) /* I - Enumeration data */
3282 {
3283 # else /* HAVE_AVAHI */
3284 static void
3285 cups_dnssd_query_cb(
3286 AvahiRecordBrowser *browser, /* I - Record browser */
3287 AvahiIfIndex interfaceIndex,
3288 /* I - Interface index (unused) */
3289 AvahiProtocol protocol, /* I - Network protocol (unused) */
3290 AvahiBrowserEvent event, /* I - What happened? */
3291 const char *fullName, /* I - Service name */
3292 uint16_t rrclass, /* I - Record class */
3293 uint16_t rrtype, /* I - Record type */
3294 const void *rdata, /* I - TXT record */
3295 size_t rdlen, /* I - Length of TXT record */
3296 AvahiLookupResultFlags flags, /* I - Flags */
3297 void *context) /* I - Enumeration data */
3298 {
3299 # ifdef DEBUG
3300 AvahiClient *client = avahi_record_browser_get_client(browser);
3301 /* Client information */
3302 # endif /* DEBUG */
3303 # endif /* HAVE_DNSSD */
3304 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3305 /* Enumeration data */
3306 char serviceName[256],/* Service name */
3307 name[128], /* Queue name */
3308 *ptr; /* Pointer into string */
3309 _cups_dnssd_device_t dkey, /* Search key */
3310 *device; /* Device */
3311
3312
3313 # ifdef HAVE_DNSSD
3314 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));
3315
3316 /*
3317 * Only process "add" data...
3318 */
3319
3320 if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
3321 return;
3322
3323 # else /* HAVE_AVAHI */
3324 DEBUG_printf(("cups_dnssd_query_cb(browser=%p, interfaceIndex=%d, protocol=%d, event=%d, fullName=\"%s\", rrclass=%u, rrtype=%u, rdata=%p, rdlen=%u, flags=%x, context=%p)", browser, interfaceIndex, protocol, event, fullName, rrclass, rrtype, rdata, (unsigned)rdlen, flags, context));
3325
3326 /*
3327 * Only process "add" data...
3328 */
3329
3330 if (event != AVAHI_BROWSER_NEW)
3331 {
3332 if (event == AVAHI_BROWSER_FAILURE)
3333 DEBUG_printf(("cups_dnssd_query_cb: %s", avahi_strerror(avahi_client_errno(client))));
3334
3335 return;
3336 }
3337 # endif /* HAVE_DNSSD */
3338
3339 /*
3340 * Lookup the service in the devices array.
3341 */
3342
3343 cups_dnssd_unquote(serviceName, fullName, sizeof(serviceName));
3344
3345 if ((ptr = strstr(serviceName, "._")) != NULL)
3346 *ptr = '\0';
3347
3348 cups_dnssd_queue_name(name, serviceName, sizeof(name));
3349
3350 dkey.dest.name = name;
3351
3352 if ((device = cupsArrayFind(data->devices, &dkey)) != NULL && device->state == _CUPS_DNSSD_NEW)
3353 {
3354 /*
3355 * Found it, pull out the make and model from the TXT record and save it...
3356 */
3357
3358 const uint8_t *txt, /* Pointer into data */
3359 *txtnext, /* Next key/value pair */
3360 *txtend; /* End of entire TXT record */
3361 uint8_t txtlen; /* Length of current key/value pair */
3362 char key[256], /* Key string */
3363 value[256], /* Value string */
3364 make_and_model[512],
3365 /* Manufacturer and model */
3366 model[256], /* Model */
3367 uriname[1024], /* Name for URI */
3368 uri[1024]; /* Printer URI */
3369 cups_ptype_t type = CUPS_PRINTER_REMOTE | CUPS_PRINTER_BW;
3370 /* Printer type */
3371 int saw_printer_type = 0;
3372 /* Did we see a printer-type key? */
3373
3374 device->state = _CUPS_DNSSD_PENDING;
3375 make_and_model[0] = '\0';
3376
3377 strlcpy(model, "Unknown", sizeof(model));
3378
3379 for (txt = rdata, txtend = txt + rdlen;
3380 txt < txtend;
3381 txt = txtnext)
3382 {
3383 /*
3384 * Read a key/value pair starting with an 8-bit length. Since the
3385 * length is 8 bits and the size of the key/value buffers is 256, we
3386 * don't need to check for overflow...
3387 */
3388
3389 txtlen = *txt++;
3390
3391 if (!txtlen || (txt + txtlen) > txtend)
3392 break;
3393
3394 txtnext = txt + txtlen;
3395
3396 for (ptr = key; txt < txtnext && *txt != '='; txt ++)
3397 *ptr++ = (char)*txt;
3398 *ptr = '\0';
3399
3400 if (txt < txtnext && *txt == '=')
3401 {
3402 txt ++;
3403
3404 if (txt < txtnext)
3405 memcpy(value, txt, (size_t)(txtnext - txt));
3406 value[txtnext - txt] = '\0';
3407
3408 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key, value));
3409 }
3410 else
3411 {
3412 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key));
3413 continue;
3414 }
3415
3416 if (!_cups_strcasecmp(key, "usb_MFG") ||
3417 !_cups_strcasecmp(key, "usb_MANU") ||
3418 !_cups_strcasecmp(key, "usb_MANUFACTURER"))
3419 strlcpy(make_and_model, value, sizeof(make_and_model));
3420 else if (!_cups_strcasecmp(key, "usb_MDL") ||
3421 !_cups_strcasecmp(key, "usb_MODEL"))
3422 strlcpy(model, value, sizeof(model));
3423 else if (!_cups_strcasecmp(key, "product") && !strstr(value, "Ghostscript"))
3424 {
3425 if (value[0] == '(')
3426 {
3427 /*
3428 * Strip parenthesis...
3429 */
3430
3431 if ((ptr = value + strlen(value) - 1) > value && *ptr == ')')
3432 *ptr = '\0';
3433
3434 strlcpy(model, value + 1, sizeof(model));
3435 }
3436 else
3437 strlcpy(model, value, sizeof(model));
3438 }
3439 else if (!_cups_strcasecmp(key, "ty"))
3440 {
3441 strlcpy(model, value, sizeof(model));
3442
3443 if ((ptr = strchr(model, ',')) != NULL)
3444 *ptr = '\0';
3445 }
3446 else if (!_cups_strcasecmp(key, "note"))
3447 device->dest.num_options = cupsAddOption("printer-location", value,
3448 device->dest.num_options,
3449 &device->dest.options);
3450 else if (!_cups_strcasecmp(key, "pdl"))
3451 {
3452 /*
3453 * Look for PDF-capable printers; only PDF-capable printers are shown.
3454 */
3455
3456 const char *start, *next; /* Pointer into value */
3457 int have_pdf = 0, /* Have PDF? */
3458 have_raster = 0;/* Have raster format support? */
3459
3460 for (start = value; start && *start; start = next)
3461 {
3462 if (!_cups_strncasecmp(start, "application/pdf", 15) && (!start[15] || start[15] == ','))
3463 {
3464 have_pdf = 1;
3465 break;
3466 }
3467 else if ((!_cups_strncasecmp(start, "image/pwg-raster", 16) && (!start[16] || start[16] == ',')) ||
3468 (!_cups_strncasecmp(start, "image/urf", 9) && (!start[9] || start[9] == ',')))
3469 {
3470 have_raster = 1;
3471 break;
3472 }
3473
3474 if ((next = strchr(start, ',')) != NULL)
3475 next ++;
3476 }
3477
3478 if (!have_pdf && !have_raster)
3479 device->state = _CUPS_DNSSD_INCOMPATIBLE;
3480 }
3481 else if (!_cups_strcasecmp(key, "printer-type"))
3482 {
3483 /*
3484 * Value is either NNNN or 0xXXXX
3485 */
3486
3487 saw_printer_type = 1;
3488 type = (cups_ptype_t)strtol(value, NULL, 0);
3489 }
3490 else if (!saw_printer_type)
3491 {
3492 if (!_cups_strcasecmp(key, "air") &&
3493 !_cups_strcasecmp(value, "t"))
3494 type |= CUPS_PRINTER_AUTHENTICATED;
3495 else if (!_cups_strcasecmp(key, "bind") &&
3496 !_cups_strcasecmp(value, "t"))
3497 type |= CUPS_PRINTER_BIND;
3498 else if (!_cups_strcasecmp(key, "collate") &&
3499 !_cups_strcasecmp(value, "t"))
3500 type |= CUPS_PRINTER_COLLATE;
3501 else if (!_cups_strcasecmp(key, "color") &&
3502 !_cups_strcasecmp(value, "t"))
3503 type |= CUPS_PRINTER_COLOR;
3504 else if (!_cups_strcasecmp(key, "copies") &&
3505 !_cups_strcasecmp(value, "t"))
3506 type |= CUPS_PRINTER_COPIES;
3507 else if (!_cups_strcasecmp(key, "duplex") &&
3508 !_cups_strcasecmp(value, "t"))
3509 type |= CUPS_PRINTER_DUPLEX;
3510 else if (!_cups_strcasecmp(key, "fax") &&
3511 !_cups_strcasecmp(value, "t"))
3512 type |= CUPS_PRINTER_MFP;
3513 else if (!_cups_strcasecmp(key, "papercustom") &&
3514 !_cups_strcasecmp(value, "t"))
3515 type |= CUPS_PRINTER_VARIABLE;
3516 else if (!_cups_strcasecmp(key, "papermax"))
3517 {
3518 if (!_cups_strcasecmp(value, "legal-a4"))
3519 type |= CUPS_PRINTER_SMALL;
3520 else if (!_cups_strcasecmp(value, "isoc-a2"))
3521 type |= CUPS_PRINTER_MEDIUM;
3522 else if (!_cups_strcasecmp(value, ">isoc-a2"))
3523 type |= CUPS_PRINTER_LARGE;
3524 }
3525 else if (!_cups_strcasecmp(key, "punch") &&
3526 !_cups_strcasecmp(value, "t"))
3527 type |= CUPS_PRINTER_PUNCH;
3528 else if (!_cups_strcasecmp(key, "scan") &&
3529 !_cups_strcasecmp(value, "t"))
3530 type |= CUPS_PRINTER_MFP;
3531 else if (!_cups_strcasecmp(key, "sort") &&
3532 !_cups_strcasecmp(value, "t"))
3533 type |= CUPS_PRINTER_SORT;
3534 else if (!_cups_strcasecmp(key, "staple") &&
3535 !_cups_strcasecmp(value, "t"))
3536 type |= CUPS_PRINTER_STAPLE;
3537 }
3538 }
3539
3540 /*
3541 * Save the printer-xxx values...
3542 */
3543
3544 device->dest.num_options = cupsAddOption("printer-info", name, device->dest.num_options, &device->dest.options);
3545
3546 if (make_and_model[0])
3547 {
3548 strlcat(make_and_model, " ", sizeof(make_and_model));
3549 strlcat(make_and_model, model, sizeof(make_and_model));
3550
3551 device->dest.num_options = cupsAddOption("printer-make-and-model", make_and_model, device->dest.num_options, &device->dest.options);
3552 }
3553 else
3554 device->dest.num_options = cupsAddOption("printer-make-and-model", model, device->dest.num_options, &device->dest.options);
3555
3556 device->type = type;
3557 snprintf(value, sizeof(value), "%u", type);
3558 device->dest.num_options = cupsAddOption("printer-type", value, device->dest.num_options, &device->dest.options);
3559
3560 /*
3561 * Save the URI...
3562 */
3563
3564 cups_dnssd_unquote(uriname, device->fullName, sizeof(uriname));
3565 httpAssembleURI(HTTP_URI_CODING_ALL, uri, sizeof(uri),
3566 !strcmp(device->regtype, "_ipps._tcp") ? "ipps" : "ipp",
3567 NULL, uriname, 0, saw_printer_type ? "/cups" : "/");
3568
3569 DEBUG_printf(("6cups_dnssd_query: device-uri=\"%s\"", uri));
3570
3571 device->dest.num_options = cupsAddOption("device-uri", uri, device->dest.num_options, &device->dest.options);
3572 }
3573 else
3574 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
3575 fullName));
3576 }
3577
3578
3579 /*
3580 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
3581 */
3582
3583 static const char * /* O - Resolved URI or NULL */
3584 cups_dnssd_resolve(
3585 cups_dest_t *dest, /* I - Destination */
3586 const char *uri, /* I - Current printer URI */
3587 int msec, /* I - Time in milliseconds */
3588 int *cancel, /* I - Pointer to "cancel" variable */
3589 cups_dest_cb_t cb, /* I - Callback */
3590 void *user_data) /* I - User data for callback */
3591 {
3592 char tempuri[1024]; /* Temporary URI buffer */
3593 _cups_dnssd_resolve_t resolve; /* Resolve data */
3594
3595
3596 /*
3597 * Resolve the URI...
3598 */
3599
3600 resolve.cancel = cancel;
3601 gettimeofday(&resolve.end_time, NULL);
3602 if (msec > 0)
3603 {
3604 resolve.end_time.tv_sec += msec / 1000;
3605 resolve.end_time.tv_usec += (msec % 1000) * 1000;
3606
3607 while (resolve.end_time.tv_usec >= 1000000)
3608 {
3609 resolve.end_time.tv_sec ++;
3610 resolve.end_time.tv_usec -= 1000000;
3611 }
3612 }
3613 else
3614 resolve.end_time.tv_sec += 75;
3615
3616 if (cb)
3617 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING, dest);
3618
3619 if ((uri = _httpResolveURI(uri, tempuri, sizeof(tempuri), _HTTP_RESOLVE_DEFAULT, cups_dnssd_resolve_cb, &resolve)) == NULL)
3620 {
3621 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to resolve printer-uri."), 1);
3622
3623 if (cb)
3624 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR, dest);
3625
3626 return (NULL);
3627 }
3628
3629 /*
3630 * Save the resolved URI...
3631 */
3632
3633 dest->num_options = cupsAddOption("resolved-device-uri", uri, dest->num_options, &dest->options);
3634
3635 return (cupsGetOption("resolved-device-uri", dest->num_options, dest->options));
3636 }
3637
3638
3639 /*
3640 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
3641 */
3642
3643 static int /* O - 1 to continue, 0 to stop */
3644 cups_dnssd_resolve_cb(void *context) /* I - Resolve data */
3645 {
3646 _cups_dnssd_resolve_t *resolve = (_cups_dnssd_resolve_t *)context;
3647 /* Resolve data */
3648 struct timeval curtime; /* Current time */
3649
3650
3651 /*
3652 * If the cancel variable is set, return immediately.
3653 */
3654
3655 if (resolve->cancel && *(resolve->cancel))
3656 {
3657 DEBUG_puts("4cups_dnssd_resolve_cb: Canceled.");
3658 return (0);
3659 }
3660
3661 /*
3662 * Otherwise check the end time...
3663 */
3664
3665 gettimeofday(&curtime, NULL);
3666
3667 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));
3668
3669 return (curtime.tv_sec < resolve->end_time.tv_sec ||
3670 (curtime.tv_sec == resolve->end_time.tv_sec &&
3671 curtime.tv_usec < resolve->end_time.tv_usec));
3672 }
3673
3674
3675 /*
3676 * 'cups_dnssd_unquote()' - Unquote a name string.
3677 */
3678
3679 static void
3680 cups_dnssd_unquote(char *dst, /* I - Destination buffer */
3681 const char *src, /* I - Source string */
3682 size_t dstsize) /* I - Size of destination buffer */
3683 {
3684 char *dstend = dst + dstsize - 1; /* End of destination buffer */
3685
3686
3687 while (*src && dst < dstend)
3688 {
3689 if (*src == '\\')
3690 {
3691 src ++;
3692 if (isdigit(src[0] & 255) && isdigit(src[1] & 255) &&
3693 isdigit(src[2] & 255))
3694 {
3695 *dst++ = ((((src[0] - '0') * 10) + src[1] - '0') * 10) + src[2] - '0';
3696 src += 3;
3697 }
3698 else
3699 *dst++ = *src++;
3700 }
3701 else
3702 *dst++ = *src ++;
3703 }
3704
3705 *dst = '\0';
3706 }
3707 #endif /* HAVE_DNSSD */
3708
3709
3710 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3711 /*
3712 * 'cups_dnssd_queue_name()' - Create a local queue name based on the service name.
3713 */
3714
3715 static void
3716 cups_dnssd_queue_name(
3717 char *name, /* I - Name buffer */
3718 const char *serviceName, /* I - Service name */
3719 size_t namesize) /* I - Size of name buffer */
3720 {
3721 const char *ptr; /* Pointer into serviceName */
3722 char *nameptr; /* Pointer into name */
3723
3724
3725 for (nameptr = name, ptr = serviceName; *ptr && nameptr < (name + namesize - 1); ptr ++)
3726 {
3727 /*
3728 * Sanitize the printer name...
3729 */
3730
3731 if (_cups_isalnum(*ptr))
3732 *nameptr++ = *ptr;
3733 else if (nameptr == name || nameptr[-1] != '_')
3734 *nameptr++ = '_';
3735 }
3736
3737 *nameptr = '\0';
3738 }
3739 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3740
3741
3742 /*
3743 * 'cups_find_dest()' - Find a destination using a binary search.
3744 */
3745
3746 static int /* O - Index of match */
3747 cups_find_dest(const char *name, /* I - Destination name */
3748 const char *instance, /* I - Instance or NULL */
3749 int num_dests, /* I - Number of destinations */
3750 cups_dest_t *dests, /* I - Destinations */
3751 int prev, /* I - Previous index */
3752 int *rdiff) /* O - Difference of match */
3753 {
3754 int left, /* Low mark for binary search */
3755 right, /* High mark for binary search */
3756 current, /* Current index */
3757 diff; /* Result of comparison */
3758 cups_dest_t key; /* Search key */
3759
3760
3761 key.name = (char *)name;
3762 key.instance = (char *)instance;
3763
3764 if (prev >= 0)
3765 {
3766 /*
3767 * Start search on either side of previous...
3768 */
3769
3770 if ((diff = cups_compare_dests(&key, dests + prev)) == 0 ||
3771 (diff < 0 && prev == 0) ||
3772 (diff > 0 && prev == (num_dests - 1)))
3773 {
3774 *rdiff = diff;
3775 return (prev);
3776 }
3777 else if (diff < 0)
3778 {
3779 /*
3780 * Start with previous on right side...
3781 */
3782
3783 left = 0;
3784 right = prev;
3785 }
3786 else
3787 {
3788 /*
3789 * Start wih previous on left side...
3790 */
3791
3792 left = prev;
3793 right = num_dests - 1;
3794 }
3795 }
3796 else
3797 {
3798 /*
3799 * Start search in the middle...
3800 */
3801
3802 left = 0;
3803 right = num_dests - 1;
3804 }
3805
3806 do
3807 {
3808 current = (left + right) / 2;
3809 diff = cups_compare_dests(&key, dests + current);
3810
3811 if (diff == 0)
3812 break;
3813 else if (diff < 0)
3814 right = current;
3815 else
3816 left = current;
3817 }
3818 while ((right - left) > 1);
3819
3820 if (diff != 0)
3821 {
3822 /*
3823 * Check the last 1 or 2 elements...
3824 */
3825
3826 if ((diff = cups_compare_dests(&key, dests + left)) <= 0)
3827 current = left;
3828 else
3829 {
3830 diff = cups_compare_dests(&key, dests + right);
3831 current = right;
3832 }
3833 }
3834
3835 /*
3836 * Return the closest destination and the difference...
3837 */
3838
3839 *rdiff = diff;
3840
3841 return (current);
3842 }
3843
3844
3845 /*
3846 * 'cups_get_default()' - Get the default destination from an lpoptions file.
3847 */
3848
3849 static char * /* O - Default destination or NULL */
3850 cups_get_default(const char *filename, /* I - File to read */
3851 char *namebuf, /* I - Name buffer */
3852 size_t namesize, /* I - Size of name buffer */
3853 const char **instance) /* I - Instance */
3854 {
3855 cups_file_t *fp; /* lpoptions file */
3856 char line[8192], /* Line from file */
3857 *value, /* Value for line */
3858 *nameptr; /* Pointer into name */
3859 int linenum; /* Current line */
3860
3861
3862 *namebuf = '\0';
3863
3864 if ((fp = cupsFileOpen(filename, "r")) != NULL)
3865 {
3866 linenum = 0;
3867
3868 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
3869 {
3870 if (!_cups_strcasecmp(line, "default") && value)
3871 {
3872 strlcpy(namebuf, value, namesize);
3873
3874 if ((nameptr = strchr(namebuf, ' ')) != NULL)
3875 *nameptr = '\0';
3876 if ((nameptr = strchr(namebuf, '\t')) != NULL)
3877 *nameptr = '\0';
3878
3879 if ((nameptr = strchr(namebuf, '/')) != NULL)
3880 *nameptr++ = '\0';
3881
3882 *instance = nameptr;
3883 break;
3884 }
3885 }
3886
3887 cupsFileClose(fp);
3888 }
3889
3890 return (*namebuf ? namebuf : NULL);
3891 }
3892
3893
3894 /*
3895 * 'cups_get_dests()' - Get destinations from a file.
3896 */
3897
3898 static int /* O - Number of destinations */
3899 cups_get_dests(
3900 const char *filename, /* I - File to read from */
3901 const char *match_name, /* I - Destination name we want */
3902 const char *match_inst, /* I - Instance name we want */
3903 int user_default_set, /* I - User default printer set? */
3904 int num_dests, /* I - Number of destinations */
3905 cups_dest_t **dests) /* IO - Destinations */
3906 {
3907 int i; /* Looping var */
3908 cups_dest_t *dest; /* Current destination */
3909 cups_file_t *fp; /* File pointer */
3910 char line[8192], /* Line from file */
3911 *lineptr, /* Pointer into line */
3912 *name, /* Name of destination/option */
3913 *instance; /* Instance of destination */
3914 int linenum; /* Current line number */
3915
3916
3917 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));
3918
3919 /*
3920 * Try to open the file...
3921 */
3922
3923 if ((fp = cupsFileOpen(filename, "r")) == NULL)
3924 return (num_dests);
3925
3926 /*
3927 * Read each printer; each line looks like:
3928 *
3929 * Dest name[/instance] options
3930 * Default name[/instance] options
3931 */
3932
3933 linenum = 0;
3934
3935 while (cupsFileGetConf(fp, line, sizeof(line), &lineptr, &linenum))
3936 {
3937 /*
3938 * See what type of line it is...
3939 */
3940
3941 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
3942 linenum, line, lineptr));
3943
3944 if ((_cups_strcasecmp(line, "dest") && _cups_strcasecmp(line, "default")) || !lineptr)
3945 {
3946 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
3947 continue;
3948 }
3949
3950 name = lineptr;
3951
3952 /*
3953 * Search for an instance...
3954 */
3955
3956 while (!isspace(*lineptr & 255) && *lineptr && *lineptr != '/')
3957 lineptr ++;
3958
3959 if (*lineptr == '/')
3960 {
3961 /*
3962 * Found an instance...
3963 */
3964
3965 *lineptr++ = '\0';
3966 instance = lineptr;
3967
3968 /*
3969 * Search for an instance...
3970 */
3971
3972 while (!isspace(*lineptr & 255) && *lineptr)
3973 lineptr ++;
3974 }
3975 else
3976 instance = NULL;
3977
3978 if (*lineptr)
3979 *lineptr++ = '\0';
3980
3981 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name,
3982 instance));
3983
3984 /*
3985 * See if the primary instance of the destination exists; if not,
3986 * ignore this entry and move on...
3987 */
3988
3989 if (match_name)
3990 {
3991 if (_cups_strcasecmp(name, match_name) ||
3992 (!instance && match_inst) ||
3993 (instance && !match_inst) ||
3994 (instance && _cups_strcasecmp(instance, match_inst)))
3995 continue;
3996
3997 dest = *dests;
3998 }
3999 else if (cupsGetDest(name, NULL, num_dests, *dests) == NULL)
4000 {
4001 DEBUG_puts("9cups_get_dests: Not found!");
4002 continue;
4003 }
4004 else
4005 {
4006 /*
4007 * Add the destination...
4008 */
4009
4010 num_dests = cupsAddDest(name, instance, num_dests, dests);
4011
4012 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
4013 {
4014 /*
4015 * Out of memory!
4016 */
4017
4018 DEBUG_puts("9cups_get_dests: Out of memory!");
4019 break;
4020 }
4021 }
4022
4023 /*
4024 * Add options until we hit the end of the line...
4025 */
4026
4027 dest->num_options = cupsParseOptions(lineptr, dest->num_options,
4028 &(dest->options));
4029
4030 /*
4031 * If we found what we were looking for, stop now...
4032 */
4033
4034 if (match_name)
4035 break;
4036
4037 /*
4038 * Set this as default if needed...
4039 */
4040
4041 if (!user_default_set && !_cups_strcasecmp(line, "default"))
4042 {
4043 DEBUG_puts("9cups_get_dests: Setting as default...");
4044
4045 for (i = 0; i < num_dests; i ++)
4046 (*dests)[i].is_default = 0;
4047
4048 dest->is_default = 1;
4049 }
4050 }
4051
4052 /*
4053 * Close the file and return...
4054 */
4055
4056 cupsFileClose(fp);
4057
4058 return (num_dests);
4059 }
4060
4061
4062 /*
4063 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
4064 * attribute.
4065 */
4066
4067 static char * /* O - New string */
4068 cups_make_string(
4069 ipp_attribute_t *attr, /* I - Attribute to convert */
4070 char *buffer, /* I - Buffer */
4071 size_t bufsize) /* I - Size of buffer */
4072 {
4073 int i; /* Looping var */
4074 char *ptr, /* Pointer into buffer */
4075 *end, /* Pointer to end of buffer */
4076 *valptr; /* Pointer into string attribute */
4077
4078
4079 /*
4080 * Return quickly if we have a single string value...
4081 */
4082
4083 if (attr->num_values == 1 &&
4084 attr->value_tag != IPP_TAG_INTEGER &&
4085 attr->value_tag != IPP_TAG_ENUM &&
4086 attr->value_tag != IPP_TAG_BOOLEAN &&
4087 attr->value_tag != IPP_TAG_RANGE)
4088 return (attr->values[0].string.text);
4089
4090 /*
4091 * Copy the values to the string, separating with commas and escaping strings
4092 * as needed...
4093 */
4094
4095 end = buffer + bufsize - 1;
4096
4097 for (i = 0, ptr = buffer; i < attr->num_values && ptr < end; i ++)
4098 {
4099 if (i)
4100 *ptr++ = ',';
4101
4102 switch (attr->value_tag)
4103 {
4104 case IPP_TAG_INTEGER :
4105 case IPP_TAG_ENUM :
4106 snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].integer);
4107 break;
4108
4109 case IPP_TAG_BOOLEAN :
4110 if (attr->values[i].boolean)
4111 strlcpy(ptr, "true", (size_t)(end - ptr + 1));
4112 else
4113 strlcpy(ptr, "false", (size_t)(end - ptr + 1));
4114 break;
4115
4116 case IPP_TAG_RANGE :
4117 if (attr->values[i].range.lower == attr->values[i].range.upper)
4118 snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].range.lower);
4119 else
4120 snprintf(ptr, (size_t)(end - ptr + 1), "%d-%d", attr->values[i].range.lower, attr->values[i].range.upper);
4121 break;
4122
4123 default :
4124 for (valptr = attr->values[i].string.text;
4125 *valptr && ptr < end;)
4126 {
4127 if (strchr(" \t\n\\\'\"", *valptr))
4128 {
4129 if (ptr >= (end - 1))
4130 break;
4131
4132 *ptr++ = '\\';
4133 }
4134
4135 *ptr++ = *valptr++;
4136 }
4137
4138 *ptr = '\0';
4139 break;
4140 }
4141
4142 ptr += strlen(ptr);
4143 }
4144
4145 *ptr = '\0';
4146
4147 return (buffer);
4148 }