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