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