]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/dest.c
Add some more debug printfs to figure out Issue #5046...
[thirdparty/cups.git] / cups / dest.c
1 /*
2 * User-defined destination (and option) support for CUPS.
3 *
4 * Copyright 2007-2017 by Apple Inc.
5 * Copyright 1997-2007 by Easy Software Products.
6 *
7 * These coded instructions, statements, and computer programs are the
8 * property of Apple Inc. and are protected by Federal copyright
9 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
10 * which should have been included with this file. If this file is
11 * missing or damaged, see the license at "http://www.cups.org/".
12 *
13 * This file is subject to the Apple OS-Developed Software exception.
14 */
15
16 /*
17 * Include necessary headers...
18 */
19
20 #include "cups-private.h"
21 #include <sys/stat.h>
22
23 #ifdef HAVE_NOTIFY_H
24 # include <notify.h>
25 #endif /* HAVE_NOTIFY_H */
26
27 #ifdef HAVE_POLL
28 # include <poll.h>
29 #endif /* HAVE_POLL */
30
31 #ifdef HAVE_DNSSD
32 # include <dns_sd.h>
33 #endif /* HAVE_DNSSD */
34
35 #ifdef HAVE_AVAHI
36 # include <avahi-client/client.h>
37 # include <avahi-client/lookup.h>
38 # include <avahi-common/simple-watch.h>
39 # include <avahi-common/domain.h>
40 # include <avahi-common/error.h>
41 # include <avahi-common/malloc.h>
42 #define kDNSServiceMaxDomainName AVAHI_DOMAIN_NAME_MAX
43 #endif /* HAVE_AVAHI */
44
45
46 /*
47 * Constants...
48 */
49
50 #ifdef __APPLE__
51 # if !TARGET_OS_IOS
52 # include <SystemConfiguration/SystemConfiguration.h>
53 # define _CUPS_LOCATION_DEFAULTS 1
54 # endif /* !TARGET_OS_IOS */
55 # define kCUPSPrintingPrefs CFSTR("org.cups.PrintingPrefs")
56 # define kDefaultPaperIDKey CFSTR("DefaultPaperID")
57 # define kLastUsedPrintersKey CFSTR("LastUsedPrinters")
58 # define kLocationNetworkKey CFSTR("Network")
59 # define kLocationPrinterIDKey CFSTR("PrinterID")
60 # define kUseLastPrinter CFSTR("UseLastPrinter")
61 #endif /* __APPLE__ */
62
63 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
64 # define _CUPS_DNSSD_MAXTIME 500 /* Milliseconds for maximum quantum of time */
65 #endif /* HAVE_DNSSD || HAVE_AVAHI */
66
67
68 /*
69 * Types...
70 */
71
72 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
73 typedef enum _cups_dnssd_state_e /* Enumerated device state */
74 {
75 _CUPS_DNSSD_NEW,
76 _CUPS_DNSSD_QUERY,
77 _CUPS_DNSSD_PENDING,
78 _CUPS_DNSSD_ACTIVE,
79 _CUPS_DNSSD_LOCAL,
80 _CUPS_DNSSD_INCOMPATIBLE,
81 _CUPS_DNSSD_ERROR
82 } _cups_dnssd_state_t;
83
84 typedef struct _cups_dnssd_data_s /* Enumeration data */
85 {
86 # ifdef HAVE_DNSSD
87 DNSServiceRef main_ref; /* Main service reference */
88 # else /* HAVE_AVAHI */
89 AvahiSimplePoll *simple_poll; /* Polling interface */
90 AvahiClient *client; /* Client information */
91 int got_data; /* Did we get data? */
92 int browsers; /* How many browsers are running? */
93 # endif /* HAVE_DNSSD */
94 cups_dest_cb_t cb; /* Callback */
95 void *user_data; /* User data pointer */
96 cups_ptype_t type, /* Printer type filter */
97 mask; /* Printer type mask */
98 cups_array_t *devices; /* Devices found so far */
99 } _cups_dnssd_data_t;
100
101 typedef struct _cups_dnssd_device_s /* Enumerated device */
102 {
103 _cups_dnssd_state_t state; /* State of device listing */
104 # ifdef HAVE_DNSSD
105 DNSServiceRef ref; /* Service reference for query */
106 # else /* HAVE_AVAHI */
107 AvahiRecordBrowser *ref; /* Browser for query */
108 # endif /* HAVE_DNSSD */
109 char *fullName, /* Full name */
110 *regtype, /* Registration type */
111 *domain; /* Domain name */
112 cups_ptype_t type; /* Device registration type */
113 cups_dest_t dest; /* Destination record */
114 } _cups_dnssd_device_t;
115
116 typedef struct _cups_dnssd_resolve_s /* Data for resolving URI */
117 {
118 int *cancel; /* Pointer to "cancel" variable */
119 struct timeval end_time; /* Ending time */
120 } _cups_dnssd_resolve_t;
121 #endif /* HAVE_DNSSD */
122
123 typedef struct _cups_getdata_s
124 {
125 int num_dests; /* Number of destinations */
126 cups_dest_t *dests; /* Destinations */
127 } _cups_getdata_t;
128
129 typedef struct _cups_namedata_s
130 {
131 const char *name; /* Named destination */
132 cups_dest_t *dest; /* Destination */
133 } _cups_namedata_t;
134
135
136 /*
137 * Local functions...
138 */
139
140 #if _CUPS_LOCATION_DEFAULTS
141 static CFArrayRef appleCopyLocations(void);
142 static CFStringRef appleCopyNetwork(void);
143 #endif /* _CUPS_LOCATION_DEFAULTS */
144 #ifdef __APPLE__
145 static char *appleGetPaperSize(char *name, size_t namesize);
146 #endif /* __APPLE__ */
147 #if _CUPS_LOCATION_DEFAULTS
148 static CFStringRef appleGetPrinter(CFArrayRef locations,
149 CFStringRef network, CFIndex *locindex);
150 #endif /* _CUPS_LOCATION_DEFAULTS */
151 static cups_dest_t *cups_add_dest(const char *name, const char *instance,
152 int *num_dests, cups_dest_t **dests);
153 #ifdef __BLOCKS__
154 static int cups_block_cb(cups_dest_block_t block, unsigned flags,
155 cups_dest_t *dest);
156 #endif /* __BLOCKS__ */
157 static int cups_compare_dests(cups_dest_t *a, cups_dest_t *b);
158 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
159 # ifdef HAVE_DNSSD
160 static void cups_dnssd_browse_cb(DNSServiceRef sdRef,
161 DNSServiceFlags flags,
162 uint32_t interfaceIndex,
163 DNSServiceErrorType errorCode,
164 const char *serviceName,
165 const char *regtype,
166 const char *replyDomain,
167 void *context);
168 # else /* HAVE_AVAHI */
169 static void cups_dnssd_browse_cb(AvahiServiceBrowser *browser,
170 AvahiIfIndex interface,
171 AvahiProtocol protocol,
172 AvahiBrowserEvent event,
173 const char *serviceName,
174 const char *regtype,
175 const char *replyDomain,
176 AvahiLookupResultFlags flags,
177 void *context);
178 static void cups_dnssd_client_cb(AvahiClient *client,
179 AvahiClientState state,
180 void *context);
181 # endif /* HAVE_DNSSD */
182 static int cups_dnssd_compare_devices(_cups_dnssd_device_t *a,
183 _cups_dnssd_device_t *b);
184 static void cups_dnssd_free_device(_cups_dnssd_device_t *device,
185 _cups_dnssd_data_t *data);
186 static _cups_dnssd_device_t *
187 cups_dnssd_get_device(_cups_dnssd_data_t *data,
188 const char *serviceName,
189 const char *regtype,
190 const char *replyDomain);
191 # ifdef HAVE_DNSSD
192 static void cups_dnssd_local_cb(DNSServiceRef sdRef,
193 DNSServiceFlags flags,
194 uint32_t interfaceIndex,
195 DNSServiceErrorType errorCode,
196 const char *serviceName,
197 const char *regtype,
198 const char *replyDomain,
199 void *context);
200 static void cups_dnssd_query_cb(DNSServiceRef sdRef,
201 DNSServiceFlags flags,
202 uint32_t interfaceIndex,
203 DNSServiceErrorType errorCode,
204 const char *fullName,
205 uint16_t rrtype, uint16_t rrclass,
206 uint16_t rdlen, const void *rdata,
207 uint32_t ttl, void *context);
208 # else /* HAVE_AVAHI */
209 static int cups_dnssd_poll_cb(struct pollfd *pollfds,
210 unsigned int num_pollfds,
211 int timeout, void *context);
212 static void cups_dnssd_query_cb(AvahiRecordBrowser *browser,
213 AvahiIfIndex interface,
214 AvahiProtocol protocol,
215 AvahiBrowserEvent event,
216 const char *name, uint16_t rrclass,
217 uint16_t rrtype, const void *rdata,
218 size_t rdlen,
219 AvahiLookupResultFlags flags,
220 void *context);
221 # endif /* HAVE_DNSSD */
222 static const char *cups_dnssd_resolve(cups_dest_t *dest, const char *uri,
223 int msec, int *cancel,
224 cups_dest_cb_t cb, void *user_data);
225 static int cups_dnssd_resolve_cb(void *context);
226 static void cups_dnssd_unquote(char *dst, const char *src,
227 size_t dstsize);
228 static int cups_elapsed(struct timeval *t);
229 #endif /* HAVE_DNSSD || HAVE_AVAHI */
230 static int cups_find_dest(const char *name, const char *instance,
231 int num_dests, cups_dest_t *dests, int prev,
232 int *rdiff);
233 static int cups_get_cb(_cups_getdata_t *data, unsigned flags, cups_dest_t *dest);
234 static char *cups_get_default(const char *filename, char *namebuf,
235 size_t namesize, const char **instance);
236 static int cups_get_dests(const char *filename, const char *match_name,
237 const char *match_inst, int user_default_set,
238 int num_dests, cups_dest_t **dests);
239 static char *cups_make_string(ipp_attribute_t *attr, char *buffer,
240 size_t bufsize);
241 static int cups_name_cb(_cups_namedata_t *data, unsigned flags, cups_dest_t *dest);
242 static void cups_queue_name(char *name, const char *serviceName, size_t namesize);
243
244
245 /*
246 * 'cupsAddDest()' - Add a destination to the list of destinations.
247 *
248 * This function cannot be used to add a new class or printer queue,
249 * it only adds a new container of saved options for the named
250 * destination or instance.
251 *
252 * If the named destination already exists, the destination list is
253 * returned unchanged. Adding a new instance of a destination creates
254 * a copy of that destination's options.
255 *
256 * Use the @link cupsSaveDests@ function to save the updated list of
257 * destinations to the user's lpoptions file.
258 */
259
260 int /* O - New number of destinations */
261 cupsAddDest(const char *name, /* I - Destination name */
262 const char *instance, /* I - Instance name or @code NULL@ for none/primary */
263 int num_dests, /* I - Number of destinations */
264 cups_dest_t **dests) /* IO - Destinations */
265 {
266 int i; /* Looping var */
267 cups_dest_t *dest; /* Destination pointer */
268 cups_dest_t *parent = NULL; /* Parent destination */
269 cups_option_t *doption, /* Current destination option */
270 *poption; /* Current parent option */
271
272
273 if (!name || !dests)
274 return (0);
275
276 if (!cupsGetDest(name, instance, num_dests, *dests))
277 {
278 if (instance && !cupsGetDest(name, NULL, num_dests, *dests))
279 return (num_dests);
280
281 if ((dest = cups_add_dest(name, instance, &num_dests, dests)) == NULL)
282 return (num_dests);
283
284 /*
285 * Find the base dest again now the array has been realloc'd.
286 */
287
288 parent = cupsGetDest(name, NULL, num_dests, *dests);
289
290 if (instance && parent && parent->num_options > 0)
291 {
292 /*
293 * Copy options from parent...
294 */
295
296 dest->options = calloc(sizeof(cups_option_t), (size_t)parent->num_options);
297
298 if (dest->options)
299 {
300 dest->num_options = parent->num_options;
301
302 for (i = dest->num_options, doption = dest->options,
303 poption = parent->options;
304 i > 0;
305 i --, doption ++, poption ++)
306 {
307 doption->name = _cupsStrRetain(poption->name);
308 doption->value = _cupsStrRetain(poption->value);
309 }
310 }
311 }
312 }
313
314 return (num_dests);
315 }
316
317
318 #ifdef __APPLE__
319 /*
320 * '_cupsAppleCopyDefaultPaperID()' - Get the default paper ID.
321 */
322
323 CFStringRef /* O - Default paper ID */
324 _cupsAppleCopyDefaultPaperID(void)
325 {
326 return (CFPreferencesCopyAppValue(kDefaultPaperIDKey,
327 kCUPSPrintingPrefs));
328 }
329
330
331 /*
332 * '_cupsAppleCopyDefaultPrinter()' - Get the default printer at this location.
333 */
334
335 CFStringRef /* O - Default printer name */
336 _cupsAppleCopyDefaultPrinter(void)
337 {
338 # if _CUPS_LOCATION_DEFAULTS
339 CFStringRef network; /* Network location */
340 CFArrayRef locations; /* Location array */
341 CFStringRef locprinter; /* Current printer */
342
343
344 /*
345 * Use location-based defaults only if "use last printer" is selected in the
346 * system preferences...
347 */
348
349 if (!_cupsAppleGetUseLastPrinter())
350 {
351 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Not using last printer as "
352 "default.");
353 return (NULL);
354 }
355
356 /*
357 * Get the current location...
358 */
359
360 if ((network = appleCopyNetwork()) == NULL)
361 {
362 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Unable to get current "
363 "network.");
364 return (NULL);
365 }
366
367 /*
368 * Lookup the network in the preferences...
369 */
370
371 if ((locations = appleCopyLocations()) == NULL)
372 {
373 /*
374 * Missing or bad location array, so no location-based default...
375 */
376
377 DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Missing or bad last used "
378 "printer array.");
379
380 CFRelease(network);
381
382 return (NULL);
383 }
384
385 DEBUG_printf(("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.",
386 (int)CFArrayGetCount(locations)));
387
388 if ((locprinter = appleGetPrinter(locations, network, NULL)) != NULL)
389 CFRetain(locprinter);
390
391 CFRelease(network);
392 CFRelease(locations);
393
394 return (locprinter);
395
396 # else
397 return (NULL);
398 # endif /* _CUPS_LOCATION_DEFAULTS */
399 }
400
401
402 /*
403 * '_cupsAppleGetUseLastPrinter()' - Get whether to use the last used printer.
404 */
405
406 int /* O - 1 to use last printer, 0 otherwise */
407 _cupsAppleGetUseLastPrinter(void)
408 {
409 Boolean uselast, /* Use last printer preference value */
410 uselast_set; /* Valid is set? */
411
412
413 if (getenv("CUPS_DISABLE_APPLE_DEFAULT"))
414 return (0);
415
416 uselast = CFPreferencesGetAppBooleanValue(kUseLastPrinter,
417 kCUPSPrintingPrefs,
418 &uselast_set);
419 if (!uselast_set)
420 return (1);
421 else
422 return (uselast);
423 }
424
425
426 /*
427 * '_cupsAppleSetDefaultPaperID()' - Set the default paper id.
428 */
429
430 void
431 _cupsAppleSetDefaultPaperID(
432 CFStringRef name) /* I - New paper ID */
433 {
434 CFPreferencesSetAppValue(kDefaultPaperIDKey, name, kCUPSPrintingPrefs);
435 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
436
437 # ifdef HAVE_NOTIFY_POST
438 notify_post("com.apple.printerPrefsChange");
439 # endif /* HAVE_NOTIFY_POST */
440 }
441
442
443 /*
444 * '_cupsAppleSetDefaultPrinter()' - Set the default printer for this location.
445 */
446
447 void
448 _cupsAppleSetDefaultPrinter(
449 CFStringRef name) /* I - Default printer/class name */
450 {
451 # if _CUPS_LOCATION_DEFAULTS
452 CFStringRef network; /* Current network */
453 CFArrayRef locations; /* Old locations array */
454 CFIndex locindex; /* Index in locations array */
455 CFStringRef locprinter; /* Current printer */
456 CFMutableArrayRef newlocations; /* New locations array */
457 CFMutableDictionaryRef newlocation; /* New location */
458
459
460 /*
461 * Get the current location...
462 */
463
464 if ((network = appleCopyNetwork()) == NULL)
465 {
466 DEBUG_puts("1_cupsAppleSetDefaultPrinter: Unable to get current network...");
467 return;
468 }
469
470 /*
471 * Lookup the network in the preferences...
472 */
473
474 if ((locations = appleCopyLocations()) != NULL)
475 locprinter = appleGetPrinter(locations, network, &locindex);
476 else
477 {
478 locprinter = NULL;
479 locindex = -1;
480 }
481
482 if (!locprinter || CFStringCompare(locprinter, name, 0) != kCFCompareEqualTo)
483 {
484 /*
485 * Need to change the locations array...
486 */
487
488 if (locations)
489 {
490 newlocations = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0,
491 locations);
492
493 if (locprinter)
494 CFArrayRemoveValueAtIndex(newlocations, locindex);
495 }
496 else
497 newlocations = CFArrayCreateMutable(kCFAllocatorDefault, 0,
498 &kCFTypeArrayCallBacks);
499
500 newlocation = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
501 &kCFTypeDictionaryKeyCallBacks,
502 &kCFTypeDictionaryValueCallBacks);
503
504 if (newlocation && newlocations)
505 {
506 /*
507 * Put the new location at the front of the array...
508 */
509
510 CFDictionaryAddValue(newlocation, kLocationNetworkKey, network);
511 CFDictionaryAddValue(newlocation, kLocationPrinterIDKey, name);
512 CFArrayInsertValueAtIndex(newlocations, 0, newlocation);
513
514 /*
515 * Limit the number of locations to 10...
516 */
517
518 while (CFArrayGetCount(newlocations) > 10)
519 CFArrayRemoveValueAtIndex(newlocations, 10);
520
521 /*
522 * Push the changes out...
523 */
524
525 CFPreferencesSetAppValue(kLastUsedPrintersKey, newlocations,
526 kCUPSPrintingPrefs);
527 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
528
529 # ifdef HAVE_NOTIFY_POST
530 notify_post("com.apple.printerPrefsChange");
531 # endif /* HAVE_NOTIFY_POST */
532 }
533
534 if (newlocations)
535 CFRelease(newlocations);
536
537 if (newlocation)
538 CFRelease(newlocation);
539 }
540
541 if (locations)
542 CFRelease(locations);
543
544 CFRelease(network);
545
546 # else
547 (void)name;
548 # endif /* _CUPS_LOCATION_DEFAULTS */
549 }
550
551
552 /*
553 * '_cupsAppleSetUseLastPrinter()' - Set whether to use the last used printer.
554 */
555
556 void
557 _cupsAppleSetUseLastPrinter(
558 int uselast) /* O - 1 to use last printer, 0 otherwise */
559 {
560 CFPreferencesSetAppValue(kUseLastPrinter,
561 uselast ? kCFBooleanTrue : kCFBooleanFalse,
562 kCUPSPrintingPrefs);
563 CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
564
565 # ifdef HAVE_NOTIFY_POST
566 notify_post("com.apple.printerPrefsChange");
567 # endif /* HAVE_NOTIFY_POST */
568 }
569 #endif /* __APPLE__ */
570
571
572 /*
573 * 'cupsConnectDest()' - Open a conection to the destination.
574 *
575 * Connect to the destination, returning a new @code http_t@ connection object
576 * and optionally the resource path to use for the destination. These calls
577 * will block until a connection is made, the timeout expires, the integer
578 * pointed to by "cancel" is non-zero, or the callback function (or block)
579 * returns 0. The caller is responsible for calling @link httpClose@ on the
580 * returned connection.
581 *
582 * 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, 1000, NULL, 0, 0, (cups_dest_cb_t)cups_get_cb, &data);
2074
2075 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE)
2076 {
2077 DEBUG_printf(("1cupsGetDests2: cupsLastError() is %s, returning 0.", cupsLastErrorString()));
2078
2079 cupsFreeDests(data.num_dests, data.dests);
2080
2081 *dests = (cups_dest_t *)0;
2082
2083 return (0);
2084 }
2085
2086 /*
2087 * Make a copy of the "real" queues for a later sanity check...
2088 */
2089
2090 if (data.num_dests > 0)
2091 {
2092 num_reals = data.num_dests;
2093 reals = calloc((size_t)num_reals, sizeof(cups_dest_t));
2094
2095 if (reals)
2096 memcpy(reals, data.dests, (size_t)num_reals * sizeof(cups_dest_t));
2097 else
2098 num_reals = 0;
2099 }
2100 else
2101 {
2102 num_reals = 0;
2103 reals = NULL;
2104 }
2105
2106 /*
2107 * Grab the default destination...
2108 */
2109
2110 if ((user_default = _cupsUserDefault(name, sizeof(name))) != NULL)
2111 defprinter = name;
2112 else if ((defprinter = cupsGetDefault2(http)) != NULL)
2113 {
2114 strlcpy(name, defprinter, sizeof(name));
2115 defprinter = name;
2116 }
2117
2118 if (defprinter)
2119 {
2120 /*
2121 * Separate printer and instance name...
2122 */
2123
2124 if ((instance = strchr(name, '/')) != NULL)
2125 *instance++ = '\0';
2126
2127 /*
2128 * Lookup the printer and instance and make it the default...
2129 */
2130
2131 if ((dest = cupsGetDest(name, instance, data.num_dests, data.dests)) != NULL)
2132 dest->is_default = 1;
2133 }
2134 else
2135 instance = NULL;
2136
2137 /*
2138 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
2139 */
2140
2141 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
2142 data.num_dests = cups_get_dests(filename, NULL, NULL, user_default != NULL, data.num_dests, &data.dests);
2143
2144 if ((home = getenv("HOME")) != NULL)
2145 {
2146 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2147
2148 data.num_dests = cups_get_dests(filename, NULL, NULL, user_default != NULL, data.num_dests, &data.dests);
2149 }
2150
2151 /*
2152 * Validate the current default destination - this prevents old
2153 * Default lines in /etc/cups/lpoptions and ~/.cups/lpoptions from
2154 * pointing to a non-existent printer or class...
2155 */
2156
2157 if (num_reals)
2158 {
2159 /*
2160 * See if we have a default printer...
2161 */
2162
2163 if ((dest = cupsGetDest(NULL, NULL, data.num_dests, data.dests)) != NULL)
2164 {
2165 /*
2166 * Have a default; see if it is real...
2167 */
2168
2169 if (!cupsGetDest(dest->name, NULL, num_reals, reals))
2170 {
2171 /*
2172 * Remove the non-real printer from the list, since we don't want jobs
2173 * going to an unexpected printer... (<rdar://problem/14216472>)
2174 */
2175
2176 data.num_dests = cupsRemoveDest(dest->name, dest->instance, data.num_dests, &data.dests);
2177 }
2178 }
2179
2180 /*
2181 * Free memory...
2182 */
2183
2184 free(reals);
2185 }
2186
2187 /*
2188 * Return the number of destinations...
2189 */
2190
2191 *dests = data.dests;
2192
2193 if (data.num_dests > 0)
2194 _cupsSetError(IPP_STATUS_OK, NULL, 0);
2195
2196 DEBUG_printf(("1cupsGetDests2: Returning %d destinations.", data.num_dests));
2197
2198 return (data.num_dests);
2199 }
2200
2201
2202 /*
2203 * 'cupsGetNamedDest()' - Get options for the named destination.
2204 *
2205 * This function is optimized for retrieving a single destination and should
2206 * be used instead of @link cupsGetDests2@ and @link cupsGetDest@ when you
2207 * either know the name of the destination or want to print to the default
2208 * destination. If @code NULL@ is returned, the destination does not exist or
2209 * there is no default destination.
2210 *
2211 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
2212 * server will be used.
2213 *
2214 * If "name" is @code NULL@, the default printer for the current user will be
2215 * returned.
2216 *
2217 * The returned destination must be freed using @link cupsFreeDests@ with a
2218 * "num_dests" value of 1.
2219 *
2220 * @since CUPS 1.4/macOS 10.6@
2221 */
2222
2223 cups_dest_t * /* O - Destination or @code NULL@ */
2224 cupsGetNamedDest(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2225 const char *name, /* I - Destination name or @code NULL@ for the default destination */
2226 const char *instance) /* I - Instance name or @code NULL@ */
2227 {
2228 const char *dest_name; /* Working destination name */
2229 cups_dest_t *dest; /* Destination */
2230 char filename[1024], /* Path to lpoptions */
2231 defname[256]; /* Default printer name */
2232 const char *home = getenv("HOME"); /* Home directory */
2233 int set_as_default = 0; /* Set returned destination as default */
2234 ipp_op_t op = IPP_OP_GET_PRINTER_ATTRIBUTES;
2235 /* IPP operation to get server ops */
2236 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
2237
2238
2239 DEBUG_printf(("cupsGetNamedDest(http=%p, name=\"%s\", instance=\"%s\")", (void *)http, name, instance));
2240
2241 /*
2242 * If "name" is NULL, find the default destination...
2243 */
2244
2245 dest_name = name;
2246
2247 if (!dest_name)
2248 {
2249 set_as_default = 1;
2250 dest_name = _cupsUserDefault(defname, sizeof(defname));
2251
2252 if (dest_name)
2253 {
2254 char *ptr; /* Temporary pointer... */
2255
2256 if ((ptr = strchr(defname, '/')) != NULL)
2257 {
2258 *ptr++ = '\0';
2259 instance = ptr;
2260 }
2261 else
2262 instance = NULL;
2263 }
2264 else if (home)
2265 {
2266 /*
2267 * No default in the environment, try the user's lpoptions files...
2268 */
2269
2270 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2271
2272 dest_name = cups_get_default(filename, defname, sizeof(defname), &instance);
2273 }
2274
2275 if (!name)
2276 {
2277 /*
2278 * Still not there? Try the system lpoptions file...
2279 */
2280
2281 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
2282 dest_name = cups_get_default(filename, defname, sizeof(defname), &instance);
2283 }
2284
2285 if (!dest_name)
2286 {
2287 /*
2288 * No locally-set default destination, ask the server...
2289 */
2290
2291 op = IPP_OP_CUPS_GET_DEFAULT;
2292
2293 DEBUG_puts("1cupsGetNamedDest: Asking server for default printer...");
2294 }
2295 else
2296 DEBUG_printf(("1cupsGetNamedDest: Using name=\"%s\"...", name));
2297 }
2298
2299 /*
2300 * Get the printer's attributes...
2301 */
2302
2303 if (!_cupsGetDests(http, op, dest_name, &dest, 0, 0))
2304 {
2305 if (name)
2306 {
2307 _cups_namedata_t data; /* Callback data */
2308
2309 DEBUG_puts("1cupsGetNamedDest: No queue found for printer, looking on network...");
2310
2311 data.name = name;
2312 data.dest = NULL;
2313
2314 cupsEnumDests(0, 1000, NULL, 0, 0, (cups_dest_cb_t)cups_name_cb, &data);
2315
2316 if (!data.dest)
2317 return (NULL);
2318
2319 dest = data.dest;
2320 }
2321 else
2322 return (NULL);
2323 }
2324
2325 DEBUG_printf(("1cupsGetNamedDest: Got dest=%p", (void *)dest));
2326
2327 if (instance)
2328 dest->instance = _cupsStrAlloc(instance);
2329
2330 if (set_as_default)
2331 dest->is_default = 1;
2332
2333 /*
2334 * Then add local options...
2335 */
2336
2337 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
2338 cups_get_dests(filename, dest_name, instance, 1, 1, &dest);
2339
2340 if (home)
2341 {
2342 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2343
2344 cups_get_dests(filename, dest_name, instance, 1, 1, &dest);
2345 }
2346
2347 /*
2348 * Return the result...
2349 */
2350
2351 return (dest);
2352 }
2353
2354
2355 /*
2356 * 'cupsRemoveDest()' - Remove a destination from the destination list.
2357 *
2358 * Removing a destination/instance does not delete the class or printer
2359 * queue, merely the lpoptions for that destination/instance. Use the
2360 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
2361 * options for the user.
2362 *
2363 * @since CUPS 1.3/macOS 10.5@
2364 */
2365
2366 int /* O - New number of destinations */
2367 cupsRemoveDest(const char *name, /* I - Destination name */
2368 const char *instance, /* I - Instance name or @code NULL@ */
2369 int num_dests, /* I - Number of destinations */
2370 cups_dest_t **dests) /* IO - Destinations */
2371 {
2372 int i; /* Index into destinations */
2373 cups_dest_t *dest; /* Pointer to destination */
2374
2375
2376 /*
2377 * Find the destination...
2378 */
2379
2380 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
2381 return (num_dests);
2382
2383 /*
2384 * Free memory...
2385 */
2386
2387 _cupsStrFree(dest->name);
2388 _cupsStrFree(dest->instance);
2389 cupsFreeOptions(dest->num_options, dest->options);
2390
2391 /*
2392 * Remove the destination from the array...
2393 */
2394
2395 num_dests --;
2396
2397 i = (int)(dest - *dests);
2398
2399 if (i < num_dests)
2400 memmove(dest, dest + 1, (size_t)(num_dests - i) * sizeof(cups_dest_t));
2401
2402 return (num_dests);
2403 }
2404
2405
2406 /*
2407 * 'cupsSetDefaultDest()' - Set the default destination.
2408 *
2409 * @since CUPS 1.3/macOS 10.5@
2410 */
2411
2412 void
2413 cupsSetDefaultDest(
2414 const char *name, /* I - Destination name */
2415 const char *instance, /* I - Instance name or @code NULL@ */
2416 int num_dests, /* I - Number of destinations */
2417 cups_dest_t *dests) /* I - Destinations */
2418 {
2419 int i; /* Looping var */
2420 cups_dest_t *dest; /* Current destination */
2421
2422
2423 /*
2424 * Range check input...
2425 */
2426
2427 if (!name || num_dests <= 0 || !dests)
2428 return;
2429
2430 /*
2431 * Loop through the array and set the "is_default" flag for the matching
2432 * destination...
2433 */
2434
2435 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
2436 dest->is_default = !_cups_strcasecmp(name, dest->name) &&
2437 ((!instance && !dest->instance) ||
2438 (instance && dest->instance &&
2439 !_cups_strcasecmp(instance, dest->instance)));
2440 }
2441
2442
2443 /*
2444 * 'cupsSetDests()' - Save the list of destinations for the default server.
2445 *
2446 * This function saves the destinations to /etc/cups/lpoptions when run
2447 * as root and ~/.cups/lpoptions when run as a normal user.
2448 *
2449 * @exclude all@
2450 */
2451
2452 void
2453 cupsSetDests(int num_dests, /* I - Number of destinations */
2454 cups_dest_t *dests) /* I - Destinations */
2455 {
2456 cupsSetDests2(CUPS_HTTP_DEFAULT, num_dests, dests);
2457 }
2458
2459
2460 /*
2461 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
2462 *
2463 * This function saves the destinations to /etc/cups/lpoptions when run
2464 * as root and ~/.cups/lpoptions when run as a normal user.
2465 *
2466 * @since CUPS 1.1.21/macOS 10.4@
2467 */
2468
2469 int /* O - 0 on success, -1 on error */
2470 cupsSetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2471 int num_dests, /* I - Number of destinations */
2472 cups_dest_t *dests) /* I - Destinations */
2473 {
2474 int i, j; /* Looping vars */
2475 int wrote; /* Wrote definition? */
2476 cups_dest_t *dest; /* Current destination */
2477 cups_option_t *option; /* Current option */
2478 _ipp_option_t *match; /* Matching attribute for option */
2479 FILE *fp; /* File pointer */
2480 #ifndef WIN32
2481 const char *home; /* HOME environment variable */
2482 #endif /* WIN32 */
2483 char filename[1024]; /* lpoptions file */
2484 int num_temps; /* Number of temporary destinations */
2485 cups_dest_t *temps = NULL, /* Temporary destinations */
2486 *temp; /* Current temporary dest */
2487 const char *val; /* Value of temporary option */
2488 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
2489
2490
2491 /*
2492 * Range check the input...
2493 */
2494
2495 if (!num_dests || !dests)
2496 return (-1);
2497
2498 /*
2499 * Get the server destinations...
2500 */
2501
2502 num_temps = _cupsGetDests(http, IPP_OP_CUPS_GET_PRINTERS, NULL, &temps, 0, 0);
2503
2504 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE)
2505 {
2506 cupsFreeDests(num_temps, temps);
2507 return (-1);
2508 }
2509
2510 /*
2511 * Figure out which file to write to...
2512 */
2513
2514 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
2515
2516 #ifndef WIN32
2517 if (getuid())
2518 {
2519 /*
2520 * Merge in server defaults...
2521 */
2522
2523 num_temps = cups_get_dests(filename, NULL, NULL, 0, num_temps, &temps);
2524
2525 /*
2526 * Point to user defaults...
2527 */
2528
2529 if ((home = getenv("HOME")) != NULL)
2530 {
2531 /*
2532 * Create ~/.cups subdirectory...
2533 */
2534
2535 snprintf(filename, sizeof(filename), "%s/.cups", home);
2536 if (access(filename, 0))
2537 mkdir(filename, 0700);
2538
2539 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2540 }
2541 }
2542 #endif /* !WIN32 */
2543
2544 /*
2545 * Try to open the file...
2546 */
2547
2548 if ((fp = fopen(filename, "w")) == NULL)
2549 {
2550 cupsFreeDests(num_temps, temps);
2551 return (-1);
2552 }
2553
2554 #ifndef WIN32
2555 /*
2556 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2557 * file...
2558 */
2559
2560 if (!getuid())
2561 fchmod(fileno(fp), 0644);
2562 #endif /* !WIN32 */
2563
2564 /*
2565 * Write each printer; each line looks like:
2566 *
2567 * Dest name[/instance] options
2568 * Default name[/instance] options
2569 */
2570
2571 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
2572 if (dest->instance != NULL || dest->num_options != 0 || dest->is_default)
2573 {
2574 if (dest->is_default)
2575 {
2576 fprintf(fp, "Default %s", dest->name);
2577 if (dest->instance)
2578 fprintf(fp, "/%s", dest->instance);
2579
2580 wrote = 1;
2581 }
2582 else
2583 wrote = 0;
2584
2585 if ((temp = cupsGetDest(dest->name, dest->instance, num_temps, temps)) == NULL)
2586 temp = cupsGetDest(dest->name, NULL, num_temps, temps);
2587
2588 for (j = dest->num_options, option = dest->options; j > 0; j --, option ++)
2589 {
2590 /*
2591 * See if this option is a printer attribute; if so, skip it...
2592 */
2593
2594 if ((match = _ippFindOption(option->name)) != NULL &&
2595 match->group_tag == IPP_TAG_PRINTER)
2596 continue;
2597
2598 /*
2599 * See if the server/global options match these; if so, don't
2600 * write 'em.
2601 */
2602
2603 if (temp &&
2604 (val = cupsGetOption(option->name, temp->num_options,
2605 temp->options)) != NULL &&
2606 !_cups_strcasecmp(val, option->value))
2607 continue;
2608
2609 /*
2610 * Options don't match, write to the file...
2611 */
2612
2613 if (!wrote)
2614 {
2615 fprintf(fp, "Dest %s", dest->name);
2616 if (dest->instance)
2617 fprintf(fp, "/%s", dest->instance);
2618 wrote = 1;
2619 }
2620
2621 if (option->value[0])
2622 {
2623 if (strchr(option->value, ' ') ||
2624 strchr(option->value, '\\') ||
2625 strchr(option->value, '\"') ||
2626 strchr(option->value, '\''))
2627 {
2628 /*
2629 * Quote the value...
2630 */
2631
2632 fprintf(fp, " %s=\"", option->name);
2633
2634 for (val = option->value; *val; val ++)
2635 {
2636 if (strchr("\"\'\\", *val))
2637 putc('\\', fp);
2638
2639 putc(*val, fp);
2640 }
2641
2642 putc('\"', fp);
2643 }
2644 else
2645 {
2646 /*
2647 * Store the literal value...
2648 */
2649
2650 fprintf(fp, " %s=%s", option->name, option->value);
2651 }
2652 }
2653 else
2654 fprintf(fp, " %s", option->name);
2655 }
2656
2657 if (wrote)
2658 fputs("\n", fp);
2659 }
2660
2661 /*
2662 * Free the temporary destinations and close the file...
2663 */
2664
2665 cupsFreeDests(num_temps, temps);
2666
2667 fclose(fp);
2668
2669 #ifdef __APPLE__
2670 /*
2671 * Set the default printer for this location - this allows command-line
2672 * and GUI applications to share the same default destination...
2673 */
2674
2675 if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) != NULL)
2676 {
2677 CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault,
2678 dest->name,
2679 kCFStringEncodingUTF8);
2680 /* Default printer name */
2681
2682 if (name)
2683 {
2684 _cupsAppleSetDefaultPrinter(name);
2685 CFRelease(name);
2686 }
2687 }
2688 #endif /* __APPLE__ */
2689
2690 #ifdef HAVE_NOTIFY_POST
2691 /*
2692 * Send a notification so that macOS applications can know about the
2693 * change, too.
2694 */
2695
2696 notify_post("com.apple.printerListChange");
2697 #endif /* HAVE_NOTIFY_POST */
2698
2699 return (0);
2700 }
2701
2702
2703 /*
2704 * '_cupsUserDefault()' - Get the user default printer from environment
2705 * variables and location information.
2706 */
2707
2708 char * /* O - Default printer or NULL */
2709 _cupsUserDefault(char *name, /* I - Name buffer */
2710 size_t namesize) /* I - Size of name buffer */
2711 {
2712 const char *env; /* LPDEST or PRINTER env variable */
2713 #ifdef __APPLE__
2714 CFStringRef locprinter; /* Last printer as this location */
2715 #endif /* __APPLE__ */
2716
2717
2718 if ((env = getenv("LPDEST")) == NULL)
2719 if ((env = getenv("PRINTER")) != NULL && !strcmp(env, "lp"))
2720 env = NULL;
2721
2722 if (env)
2723 {
2724 strlcpy(name, env, namesize);
2725 return (name);
2726 }
2727
2728 #ifdef __APPLE__
2729 /*
2730 * Use location-based defaults if "use last printer" is selected in the
2731 * system preferences...
2732 */
2733
2734 if ((locprinter = _cupsAppleCopyDefaultPrinter()) != NULL)
2735 {
2736 CFStringGetCString(locprinter, name, (CFIndex)namesize, kCFStringEncodingUTF8);
2737 CFRelease(locprinter);
2738 }
2739 else
2740 name[0] = '\0';
2741
2742 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name));
2743
2744 return (*name ? name : NULL);
2745
2746 #else
2747 /*
2748 * No location-based defaults on this platform...
2749 */
2750
2751 name[0] = '\0';
2752 return (NULL);
2753 #endif /* __APPLE__ */
2754 }
2755
2756
2757 #if _CUPS_LOCATION_DEFAULTS
2758 /*
2759 * 'appleCopyLocations()' - Copy the location history array.
2760 */
2761
2762 static CFArrayRef /* O - Location array or NULL */
2763 appleCopyLocations(void)
2764 {
2765 CFArrayRef locations; /* Location array */
2766
2767
2768 /*
2769 * Look up the location array in the preferences...
2770 */
2771
2772 if ((locations = CFPreferencesCopyAppValue(kLastUsedPrintersKey,
2773 kCUPSPrintingPrefs)) == NULL)
2774 return (NULL);
2775
2776 if (CFGetTypeID(locations) != CFArrayGetTypeID())
2777 {
2778 CFRelease(locations);
2779 return (NULL);
2780 }
2781
2782 return (locations);
2783 }
2784
2785
2786 /*
2787 * 'appleCopyNetwork()' - Get the network ID for the current location.
2788 */
2789
2790 static CFStringRef /* O - Network ID */
2791 appleCopyNetwork(void)
2792 {
2793 SCDynamicStoreRef dynamicStore; /* System configuration data */
2794 CFStringRef key; /* Current network configuration key */
2795 CFDictionaryRef ip_dict; /* Network configuration data */
2796 CFStringRef network = NULL; /* Current network ID */
2797
2798
2799 if ((dynamicStore = SCDynamicStoreCreate(NULL, CFSTR("libcups"), NULL,
2800 NULL)) != NULL)
2801 {
2802 /*
2803 * First use the IPv6 router address, if available, since that will generally
2804 * be a globally-unique link-local address.
2805 */
2806
2807 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
2808 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv6)) != NULL)
2809 {
2810 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2811 {
2812 if ((network = CFDictionaryGetValue(ip_dict,
2813 kSCPropNetIPv6Router)) != NULL)
2814 CFRetain(network);
2815
2816 CFRelease(ip_dict);
2817 }
2818
2819 CFRelease(key);
2820 }
2821
2822 /*
2823 * If that doesn't work, try the IPv4 router address. This isn't as unique
2824 * and will likely be a 10.x.y.z or 192.168.y.z address...
2825 */
2826
2827 if (!network)
2828 {
2829 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
2830 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4)) != NULL)
2831 {
2832 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2833 {
2834 if ((network = CFDictionaryGetValue(ip_dict,
2835 kSCPropNetIPv4Router)) != NULL)
2836 CFRetain(network);
2837
2838 CFRelease(ip_dict);
2839 }
2840
2841 CFRelease(key);
2842 }
2843 }
2844
2845 CFRelease(dynamicStore);
2846 }
2847
2848 return (network);
2849 }
2850 #endif /* _CUPS_LOCATION_DEFAULTS */
2851
2852
2853 #ifdef __APPLE__
2854 /*
2855 * 'appleGetPaperSize()' - Get the default paper size.
2856 */
2857
2858 static char * /* O - Default paper size */
2859 appleGetPaperSize(char *name, /* I - Paper size name buffer */
2860 size_t namesize) /* I - Size of buffer */
2861 {
2862 CFStringRef defaultPaperID; /* Default paper ID */
2863 pwg_media_t *pwgmedia; /* PWG media size */
2864
2865
2866 defaultPaperID = _cupsAppleCopyDefaultPaperID();
2867 if (!defaultPaperID ||
2868 CFGetTypeID(defaultPaperID) != CFStringGetTypeID() ||
2869 !CFStringGetCString(defaultPaperID, name, (CFIndex)namesize, kCFStringEncodingUTF8))
2870 name[0] = '\0';
2871 else if ((pwgmedia = pwgMediaForLegacy(name)) != NULL)
2872 strlcpy(name, pwgmedia->pwg, namesize);
2873
2874 if (defaultPaperID)
2875 CFRelease(defaultPaperID);
2876
2877 return (name);
2878 }
2879 #endif /* __APPLE__ */
2880
2881
2882 #if _CUPS_LOCATION_DEFAULTS
2883 /*
2884 * 'appleGetPrinter()' - Get a printer from the history array.
2885 */
2886
2887 static CFStringRef /* O - Printer name or NULL */
2888 appleGetPrinter(CFArrayRef locations, /* I - Location array */
2889 CFStringRef network, /* I - Network name */
2890 CFIndex *locindex) /* O - Index in array */
2891 {
2892 CFIndex i, /* Looping var */
2893 count; /* Number of locations */
2894 CFDictionaryRef location; /* Current location */
2895 CFStringRef locnetwork, /* Current network */
2896 locprinter; /* Current printer */
2897
2898
2899 for (i = 0, count = CFArrayGetCount(locations); i < count; i ++)
2900 if ((location = CFArrayGetValueAtIndex(locations, i)) != NULL &&
2901 CFGetTypeID(location) == CFDictionaryGetTypeID())
2902 {
2903 if ((locnetwork = CFDictionaryGetValue(location,
2904 kLocationNetworkKey)) != NULL &&
2905 CFGetTypeID(locnetwork) == CFStringGetTypeID() &&
2906 CFStringCompare(network, locnetwork, 0) == kCFCompareEqualTo &&
2907 (locprinter = CFDictionaryGetValue(location,
2908 kLocationPrinterIDKey)) != NULL &&
2909 CFGetTypeID(locprinter) == CFStringGetTypeID())
2910 {
2911 if (locindex)
2912 *locindex = i;
2913
2914 return (locprinter);
2915 }
2916 }
2917
2918 return (NULL);
2919 }
2920 #endif /* _CUPS_LOCATION_DEFAULTS */
2921
2922
2923 /*
2924 * 'cups_add_dest()' - Add a destination to the array.
2925 *
2926 * Unlike cupsAddDest(), this function does not check for duplicates.
2927 */
2928
2929 static cups_dest_t * /* O - New destination */
2930 cups_add_dest(const char *name, /* I - Name of destination */
2931 const char *instance, /* I - Instance or NULL */
2932 int *num_dests, /* IO - Number of destinations */
2933 cups_dest_t **dests) /* IO - Destinations */
2934 {
2935 int insert, /* Insertion point */
2936 diff; /* Result of comparison */
2937 cups_dest_t *dest; /* Destination pointer */
2938
2939
2940 /*
2941 * Add new destination...
2942 */
2943
2944 if (*num_dests == 0)
2945 dest = malloc(sizeof(cups_dest_t));
2946 else
2947 dest = realloc(*dests, sizeof(cups_dest_t) * (size_t)(*num_dests + 1));
2948
2949 if (!dest)
2950 return (NULL);
2951
2952 *dests = dest;
2953
2954 /*
2955 * Find where to insert the destination...
2956 */
2957
2958 if (*num_dests == 0)
2959 insert = 0;
2960 else
2961 {
2962 insert = cups_find_dest(name, instance, *num_dests, *dests, *num_dests - 1,
2963 &diff);
2964
2965 if (diff > 0)
2966 insert ++;
2967 }
2968
2969 /*
2970 * Move the array elements as needed...
2971 */
2972
2973 if (insert < *num_dests)
2974 memmove(*dests + insert + 1, *dests + insert, (size_t)(*num_dests - insert) * sizeof(cups_dest_t));
2975
2976 (*num_dests) ++;
2977
2978 /*
2979 * Initialize the destination...
2980 */
2981
2982 dest = *dests + insert;
2983 dest->name = _cupsStrAlloc(name);
2984 dest->instance = _cupsStrAlloc(instance);
2985 dest->is_default = 0;
2986 dest->num_options = 0;
2987 dest->options = (cups_option_t *)0;
2988
2989 return (dest);
2990 }
2991
2992
2993 # ifdef __BLOCKS__
2994 /*
2995 * 'cups_block_cb()' - Enumeration callback for block API.
2996 */
2997
2998 static int /* O - 1 to continue, 0 to stop */
2999 cups_block_cb(
3000 cups_dest_block_t block, /* I - Block */
3001 unsigned flags, /* I - Destination flags */
3002 cups_dest_t *dest) /* I - Destination */
3003 {
3004 return ((block)(flags, dest));
3005 }
3006 # endif /* __BLOCKS__ */
3007
3008
3009 /*
3010 * 'cups_compare_dests()' - Compare two destinations.
3011 */
3012
3013 static int /* O - Result of comparison */
3014 cups_compare_dests(cups_dest_t *a, /* I - First destination */
3015 cups_dest_t *b) /* I - Second destination */
3016 {
3017 int diff; /* Difference */
3018
3019
3020 if ((diff = _cups_strcasecmp(a->name, b->name)) != 0)
3021 return (diff);
3022 else if (a->instance && b->instance)
3023 return (_cups_strcasecmp(a->instance, b->instance));
3024 else
3025 return ((a->instance && !b->instance) - (!a->instance && b->instance));
3026 }
3027
3028
3029 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3030 # ifdef HAVE_DNSSD
3031 /*
3032 * 'cups_dnssd_browse_cb()' - Browse for printers.
3033 */
3034
3035 static void
3036 cups_dnssd_browse_cb(
3037 DNSServiceRef sdRef, /* I - Service reference */
3038 DNSServiceFlags flags, /* I - Option flags */
3039 uint32_t interfaceIndex, /* I - Interface number */
3040 DNSServiceErrorType errorCode, /* I - Error, if any */
3041 const char *serviceName, /* I - Name of service/device */
3042 const char *regtype, /* I - Type of service */
3043 const char *replyDomain, /* I - Service domain */
3044 void *context) /* I - Enumeration data */
3045 {
3046 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3047 /* Enumeration data */
3048
3049
3050 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));
3051
3052 /*
3053 * Don't do anything on error...
3054 */
3055
3056 if (errorCode != kDNSServiceErr_NoError)
3057 return;
3058
3059 /*
3060 * Get the device...
3061 */
3062
3063 cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
3064 }
3065
3066
3067 # else /* HAVE_AVAHI */
3068 /*
3069 * 'cups_dnssd_browse_cb()' - Browse for printers.
3070 */
3071
3072 static void
3073 cups_dnssd_browse_cb(
3074 AvahiServiceBrowser *browser, /* I - Browser */
3075 AvahiIfIndex interface, /* I - Interface index (unused) */
3076 AvahiProtocol protocol, /* I - Network protocol (unused) */
3077 AvahiBrowserEvent event, /* I - What happened */
3078 const char *name, /* I - Service name */
3079 const char *type, /* I - Registration type */
3080 const char *domain, /* I - Domain */
3081 AvahiLookupResultFlags flags, /* I - Flags */
3082 void *context) /* I - Devices array */
3083 {
3084 #ifdef DEBUG
3085 AvahiClient *client = avahi_service_browser_get_client(browser);
3086 /* Client information */
3087 #endif /* DEBUG */
3088 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3089 /* Enumeration data */
3090
3091
3092 (void)interface;
3093 (void)protocol;
3094 (void)context;
3095
3096 DEBUG_printf(("cups_dnssd_browse_cb(..., name=\"%s\", type=\"%s\", domain=\"%s\", ...);", name, type, domain));
3097
3098 switch (event)
3099 {
3100 case AVAHI_BROWSER_FAILURE:
3101 DEBUG_printf(("cups_dnssd_browse_cb: %s", avahi_strerror(avahi_client_errno(client))));
3102 avahi_simple_poll_quit(data->simple_poll);
3103 break;
3104
3105 case AVAHI_BROWSER_NEW:
3106 /*
3107 * This object is new on the network.
3108 */
3109
3110 if (flags & AVAHI_LOOKUP_RESULT_LOCAL)
3111 {
3112 /*
3113 * This comes from the local machine so ignore it.
3114 */
3115
3116 DEBUG_printf(("cups_dnssd_browse_cb: Ignoring local service \"%s\".", name));
3117 }
3118 else
3119 {
3120 /*
3121 * Create a device entry for it if it doesn't yet exist.
3122 */
3123
3124 cups_dnssd_get_device(data, name, type, domain);
3125 }
3126 break;
3127
3128 case AVAHI_BROWSER_REMOVE :
3129 case AVAHI_BROWSER_CACHE_EXHAUSTED :
3130 break;
3131
3132 case AVAHI_BROWSER_ALL_FOR_NOW :
3133 DEBUG_puts("cups_dnssd_browse_cb: ALL_FOR_NOW");
3134 data->browsers --;
3135 break;
3136 }
3137 }
3138
3139
3140 /*
3141 * 'cups_dnssd_client_cb()' - Avahi client callback function.
3142 */
3143
3144 static void
3145 cups_dnssd_client_cb(
3146 AvahiClient *client, /* I - Client information (unused) */
3147 AvahiClientState state, /* I - Current state */
3148 void *context) /* I - User data (unused) */
3149 {
3150 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3151 /* Enumeration data */
3152
3153
3154 (void)client;
3155
3156 DEBUG_printf(("cups_dnssd_client_cb(client=%p, state=%d, context=%p)", client, state, context));
3157
3158 /*
3159 * If the connection drops, quit.
3160 */
3161
3162 if (state == AVAHI_CLIENT_FAILURE)
3163 {
3164 DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
3165 avahi_simple_poll_quit(data->simple_poll);
3166 }
3167 }
3168 # endif /* HAVE_DNSSD */
3169
3170
3171 /*
3172 * 'cups_dnssd_compare_device()' - Compare two devices.
3173 */
3174
3175 static int /* O - Result of comparison */
3176 cups_dnssd_compare_devices(
3177 _cups_dnssd_device_t *a, /* I - First device */
3178 _cups_dnssd_device_t *b) /* I - Second device */
3179 {
3180 return (strcmp(a->dest.name, b->dest.name));
3181 }
3182
3183
3184 /*
3185 * 'cups_dnssd_free_device()' - Free the memory used by a device.
3186 */
3187
3188 static void
3189 cups_dnssd_free_device(
3190 _cups_dnssd_device_t *device, /* I - Device */
3191 _cups_dnssd_data_t *data) /* I - Enumeration data */
3192 {
3193 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", (void *)device, device->dest.name, (void *)data));
3194
3195 # ifdef HAVE_DNSSD
3196 if (device->ref)
3197 DNSServiceRefDeallocate(device->ref);
3198 # else /* HAVE_AVAHI */
3199 if (device->ref)
3200 avahi_record_browser_free(device->ref);
3201 # endif /* HAVE_DNSSD */
3202
3203 _cupsStrFree(device->domain);
3204 _cupsStrFree(device->fullName);
3205 _cupsStrFree(device->regtype);
3206 _cupsStrFree(device->dest.name);
3207
3208 cupsFreeOptions(device->dest.num_options, device->dest.options);
3209
3210 free(device);
3211 }
3212
3213
3214 /*
3215 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
3216 */
3217
3218 static _cups_dnssd_device_t * /* O - Device */
3219 cups_dnssd_get_device(
3220 _cups_dnssd_data_t *data, /* I - Enumeration data */
3221 const char *serviceName, /* I - Service name */
3222 const char *regtype, /* I - Registration type */
3223 const char *replyDomain) /* I - Domain name */
3224 {
3225 _cups_dnssd_device_t key, /* Search key */
3226 *device; /* Device */
3227 char fullName[kDNSServiceMaxDomainName],
3228 /* Full name for query */
3229 name[128]; /* Queue name */
3230
3231
3232 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", regtype=\"%s\", replyDomain=\"%s\")", (void *)data, serviceName, regtype, replyDomain));
3233
3234 /*
3235 * See if this is an existing device...
3236 */
3237
3238 cups_queue_name(name, serviceName, sizeof(name));
3239
3240 key.dest.name = name;
3241
3242 if ((device = cupsArrayFind(data->devices, &key)) != NULL)
3243 {
3244 /*
3245 * Yes, see if we need to do anything with this...
3246 */
3247
3248 int update = 0; /* Non-zero if we need to update */
3249
3250 if (!_cups_strcasecmp(replyDomain, "local.") &&
3251 _cups_strcasecmp(device->domain, replyDomain))
3252 {
3253 /*
3254 * Update the "global" listing to use the .local domain name instead.
3255 */
3256
3257 _cupsStrFree(device->domain);
3258 device->domain = _cupsStrAlloc(replyDomain);
3259
3260 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
3261 "domain.", device->dest.name));
3262
3263 update = 1;
3264 }
3265
3266 if (!_cups_strcasecmp(regtype, "_ipps._tcp") &&
3267 _cups_strcasecmp(device->regtype, regtype))
3268 {
3269 /*
3270 * Prefer IPPS over IPP.
3271 */
3272
3273 _cupsStrFree(device->regtype);
3274 device->regtype = _cupsStrAlloc(regtype);
3275
3276 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
3277 device->dest.name));
3278
3279 update = 1;
3280 }
3281
3282 if (!update)
3283 {
3284 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
3285 device->dest.name));
3286 return (device);
3287 }
3288 }
3289 else
3290 {
3291 /*
3292 * No, add the device...
3293 */
3294
3295 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
3296 "'%s'.", serviceName,
3297 !strcmp(regtype, "_ipps._tcp") ? "IPPS" : "IPP",
3298 replyDomain));
3299
3300 device = calloc(sizeof(_cups_dnssd_device_t), 1);
3301 device->dest.name = _cupsStrAlloc(name);
3302 device->domain = _cupsStrAlloc(replyDomain);
3303 device->regtype = _cupsStrAlloc(regtype);
3304
3305 device->dest.num_options = cupsAddOption("printer-info", serviceName, 0, &device->dest.options);
3306
3307 cupsArrayAdd(data->devices, device);
3308 }
3309
3310 /*
3311 * Set the "full name" of this service, which is used for queries...
3312 */
3313
3314 # ifdef HAVE_DNSSD
3315 DNSServiceConstructFullName(fullName, serviceName, regtype, replyDomain);
3316 # else /* HAVE_AVAHI */
3317 avahi_service_name_join(fullName, kDNSServiceMaxDomainName, serviceName, regtype, replyDomain);
3318 # endif /* HAVE_DNSSD */
3319
3320 _cupsStrFree(device->fullName);
3321 device->fullName = _cupsStrAlloc(fullName);
3322
3323 if (device->ref)
3324 {
3325 # ifdef HAVE_DNSSD
3326 DNSServiceRefDeallocate(device->ref);
3327 # else /* HAVE_AVAHI */
3328 avahi_record_browser_free(device->ref);
3329 # endif /* HAVE_DNSSD */
3330
3331 device->ref = 0;
3332 }
3333
3334 if (device->state == _CUPS_DNSSD_ACTIVE)
3335 {
3336 DEBUG_printf(("6cups_dnssd_get_device: Remove callback for \"%s\".", device->dest.name));
3337
3338 (*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
3339 device->state = _CUPS_DNSSD_NEW;
3340 }
3341
3342 return (device);
3343 }
3344
3345
3346 # ifdef HAVE_DNSSD
3347 /*
3348 * 'cups_dnssd_local_cb()' - Browse for local printers.
3349 */
3350
3351 static void
3352 cups_dnssd_local_cb(
3353 DNSServiceRef sdRef, /* I - Service reference */
3354 DNSServiceFlags flags, /* I - Option flags */
3355 uint32_t interfaceIndex, /* I - Interface number */
3356 DNSServiceErrorType errorCode, /* I - Error, if any */
3357 const char *serviceName, /* I - Name of service/device */
3358 const char *regtype, /* I - Type of service */
3359 const char *replyDomain, /* I - Service domain */
3360 void *context) /* I - Devices array */
3361 {
3362 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3363 /* Enumeration data */
3364 _cups_dnssd_device_t *device; /* Device */
3365
3366
3367 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));
3368
3369 /*
3370 * Only process "add" data...
3371 */
3372
3373 if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
3374 return;
3375
3376 /*
3377 * Get the device...
3378 */
3379
3380 device = cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
3381
3382 /*
3383 * Hide locally-registered devices...
3384 */
3385
3386 DEBUG_printf(("6cups_dnssd_local_cb: Hiding local printer '%s'.",
3387 serviceName));
3388
3389 if (device->ref)
3390 {
3391 DNSServiceRefDeallocate(device->ref);
3392 device->ref = 0;
3393 }
3394
3395 if (device->state == _CUPS_DNSSD_ACTIVE)
3396 {
3397 DEBUG_printf(("6cups_dnssd_local_cb: Remove callback for \"%s\".", device->dest.name));
3398 (*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
3399 }
3400
3401 device->state = _CUPS_DNSSD_LOCAL;
3402 }
3403 # endif /* HAVE_DNSSD */
3404
3405
3406 # ifdef HAVE_AVAHI
3407 /*
3408 * 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
3409 *
3410 * Note: This function is needed because avahi_simple_poll_iterate is broken
3411 * and always uses a timeout of 0 (!) milliseconds.
3412 * (https://github.com/lathiat/avahi/issues/127)
3413 *
3414 * @private@
3415 */
3416
3417 static int /* O - Number of file descriptors matching */
3418 cups_dnssd_poll_cb(
3419 struct pollfd *pollfds, /* I - File descriptors */
3420 unsigned int num_pollfds, /* I - Number of file descriptors */
3421 int timeout, /* I - Timeout in milliseconds (unused) */
3422 void *context) /* I - User data (unused) */
3423 {
3424 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3425 /* Enumeration data */
3426 int val; /* Return value */
3427
3428
3429 DEBUG_printf(("cups_dnssd_poll_cb(pollfds=%p, num_pollfds=%d, timeout=%d, context=%p)", pollfds, num_pollfds, timeout, context));
3430
3431 (void)timeout;
3432
3433 val = poll(pollfds, num_pollfds, _CUPS_DNSSD_MAXTIME);
3434
3435 DEBUG_printf(("cups_dnssd_poll_cb: poll() returned %d", val));
3436
3437 if (val < 0)
3438 {
3439 DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno)));
3440 }
3441 else if (val > 0)
3442 {
3443 data->got_data = 1;
3444 }
3445
3446 return (val);
3447 }
3448 # endif /* HAVE_AVAHI */
3449
3450
3451 /*
3452 * 'cups_dnssd_query_cb()' - Process query data.
3453 */
3454
3455 # ifdef HAVE_DNSSD
3456 static void
3457 cups_dnssd_query_cb(
3458 DNSServiceRef sdRef, /* I - Service reference */
3459 DNSServiceFlags flags, /* I - Data flags */
3460 uint32_t interfaceIndex, /* I - Interface */
3461 DNSServiceErrorType errorCode, /* I - Error, if any */
3462 const char *fullName, /* I - Full service name */
3463 uint16_t rrtype, /* I - Record type */
3464 uint16_t rrclass, /* I - Record class */
3465 uint16_t rdlen, /* I - Length of record data */
3466 const void *rdata, /* I - Record data */
3467 uint32_t ttl, /* I - Time-to-live */
3468 void *context) /* I - Enumeration data */
3469 {
3470 # else /* HAVE_AVAHI */
3471 static void
3472 cups_dnssd_query_cb(
3473 AvahiRecordBrowser *browser, /* I - Record browser */
3474 AvahiIfIndex interfaceIndex,
3475 /* I - Interface index (unused) */
3476 AvahiProtocol protocol, /* I - Network protocol (unused) */
3477 AvahiBrowserEvent event, /* I - What happened? */
3478 const char *fullName, /* I - Service name */
3479 uint16_t rrclass, /* I - Record class */
3480 uint16_t rrtype, /* I - Record type */
3481 const void *rdata, /* I - TXT record */
3482 size_t rdlen, /* I - Length of TXT record */
3483 AvahiLookupResultFlags flags, /* I - Flags */
3484 void *context) /* I - Enumeration data */
3485 {
3486 # ifdef DEBUG
3487 AvahiClient *client = avahi_record_browser_get_client(browser);
3488 /* Client information */
3489 # endif /* DEBUG */
3490 # endif /* HAVE_DNSSD */
3491 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
3492 /* Enumeration data */
3493 char serviceName[256],/* Service name */
3494 name[128], /* Queue name */
3495 *ptr; /* Pointer into string */
3496 _cups_dnssd_device_t dkey, /* Search key */
3497 *device; /* Device */
3498
3499
3500 # ifdef HAVE_DNSSD
3501 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));
3502
3503 /*
3504 * Only process "add" data...
3505 */
3506
3507 if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
3508 return;
3509
3510 # else /* HAVE_AVAHI */
3511 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));
3512
3513 /*
3514 * Only process "add" data...
3515 */
3516
3517 if (event != AVAHI_BROWSER_NEW)
3518 {
3519 if (event == AVAHI_BROWSER_FAILURE)
3520 DEBUG_printf(("cups_dnssd_query_cb: %s", avahi_strerror(avahi_client_errno(client))));
3521
3522 return;
3523 }
3524 # endif /* HAVE_DNSSD */
3525
3526 /*
3527 * Lookup the service in the devices array.
3528 */
3529
3530 cups_dnssd_unquote(serviceName, fullName, sizeof(serviceName));
3531
3532 if ((ptr = strstr(serviceName, "._")) != NULL)
3533 *ptr = '\0';
3534
3535 cups_queue_name(name, serviceName, sizeof(name));
3536
3537 dkey.dest.name = name;
3538
3539 if ((device = cupsArrayFind(data->devices, &dkey)) != NULL && device->state == _CUPS_DNSSD_NEW)
3540 {
3541 /*
3542 * Found it, pull out the make and model from the TXT record and save it...
3543 */
3544
3545 const uint8_t *txt, /* Pointer into data */
3546 *txtnext, /* Next key/value pair */
3547 *txtend; /* End of entire TXT record */
3548 uint8_t txtlen; /* Length of current key/value pair */
3549 char key[256], /* Key string */
3550 value[256], /* Value string */
3551 make_and_model[512],
3552 /* Manufacturer and model */
3553 model[256], /* Model */
3554 uriname[1024], /* Name for URI */
3555 uri[1024]; /* Printer URI */
3556 cups_ptype_t type = CUPS_PRINTER_DISCOVERED | CUPS_PRINTER_BW;
3557 /* Printer type */
3558 int saw_printer_type = 0;
3559 /* Did we see a printer-type key? */
3560
3561 device->state = _CUPS_DNSSD_PENDING;
3562 make_and_model[0] = '\0';
3563
3564 strlcpy(model, "Unknown", sizeof(model));
3565
3566 for (txt = rdata, txtend = txt + rdlen;
3567 txt < txtend;
3568 txt = txtnext)
3569 {
3570 /*
3571 * Read a key/value pair starting with an 8-bit length. Since the
3572 * length is 8 bits and the size of the key/value buffers is 256, we
3573 * don't need to check for overflow...
3574 */
3575
3576 txtlen = *txt++;
3577
3578 if (!txtlen || (txt + txtlen) > txtend)
3579 break;
3580
3581 txtnext = txt + txtlen;
3582
3583 for (ptr = key; txt < txtnext && *txt != '='; txt ++)
3584 *ptr++ = (char)*txt;
3585 *ptr = '\0';
3586
3587 if (txt < txtnext && *txt == '=')
3588 {
3589 txt ++;
3590
3591 if (txt < txtnext)
3592 memcpy(value, txt, (size_t)(txtnext - txt));
3593 value[txtnext - txt] = '\0';
3594
3595 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key, value));
3596 }
3597 else
3598 {
3599 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key));
3600 continue;
3601 }
3602
3603 if (!_cups_strcasecmp(key, "usb_MFG") ||
3604 !_cups_strcasecmp(key, "usb_MANU") ||
3605 !_cups_strcasecmp(key, "usb_MANUFACTURER"))
3606 strlcpy(make_and_model, value, sizeof(make_and_model));
3607 else if (!_cups_strcasecmp(key, "usb_MDL") ||
3608 !_cups_strcasecmp(key, "usb_MODEL"))
3609 strlcpy(model, value, sizeof(model));
3610 else if (!_cups_strcasecmp(key, "product") && !strstr(value, "Ghostscript"))
3611 {
3612 if (value[0] == '(')
3613 {
3614 /*
3615 * Strip parenthesis...
3616 */
3617
3618 if ((ptr = value + strlen(value) - 1) > value && *ptr == ')')
3619 *ptr = '\0';
3620
3621 strlcpy(model, value + 1, sizeof(model));
3622 }
3623 else
3624 strlcpy(model, value, sizeof(model));
3625 }
3626 else if (!_cups_strcasecmp(key, "ty"))
3627 {
3628 strlcpy(model, value, sizeof(model));
3629
3630 if ((ptr = strchr(model, ',')) != NULL)
3631 *ptr = '\0';
3632 }
3633 else if (!_cups_strcasecmp(key, "note"))
3634 device->dest.num_options = cupsAddOption("printer-location", value,
3635 device->dest.num_options,
3636 &device->dest.options);
3637 else if (!_cups_strcasecmp(key, "pdl"))
3638 {
3639 /*
3640 * Look for PDF-capable printers; only PDF-capable printers are shown.
3641 */
3642
3643 const char *start, *next; /* Pointer into value */
3644 int have_pdf = 0, /* Have PDF? */
3645 have_raster = 0;/* Have raster format support? */
3646
3647 for (start = value; start && *start; start = next)
3648 {
3649 if (!_cups_strncasecmp(start, "application/pdf", 15) && (!start[15] || start[15] == ','))
3650 {
3651 have_pdf = 1;
3652 break;
3653 }
3654 else if ((!_cups_strncasecmp(start, "image/pwg-raster", 16) && (!start[16] || start[16] == ',')) ||
3655 (!_cups_strncasecmp(start, "image/urf", 9) && (!start[9] || start[9] == ',')))
3656 {
3657 have_raster = 1;
3658 break;
3659 }
3660
3661 if ((next = strchr(start, ',')) != NULL)
3662 next ++;
3663 }
3664
3665 if (!have_pdf && !have_raster)
3666 device->state = _CUPS_DNSSD_INCOMPATIBLE;
3667 }
3668 else if (!_cups_strcasecmp(key, "printer-type"))
3669 {
3670 /*
3671 * Value is either NNNN or 0xXXXX
3672 */
3673
3674 saw_printer_type = 1;
3675 type = (cups_ptype_t)strtol(value, NULL, 0) | CUPS_PRINTER_DISCOVERED;
3676 }
3677 else if (!saw_printer_type)
3678 {
3679 if (!_cups_strcasecmp(key, "air") &&
3680 !_cups_strcasecmp(value, "t"))
3681 type |= CUPS_PRINTER_AUTHENTICATED;
3682 else if (!_cups_strcasecmp(key, "bind") &&
3683 !_cups_strcasecmp(value, "t"))
3684 type |= CUPS_PRINTER_BIND;
3685 else if (!_cups_strcasecmp(key, "collate") &&
3686 !_cups_strcasecmp(value, "t"))
3687 type |= CUPS_PRINTER_COLLATE;
3688 else if (!_cups_strcasecmp(key, "color") &&
3689 !_cups_strcasecmp(value, "t"))
3690 type |= CUPS_PRINTER_COLOR;
3691 else if (!_cups_strcasecmp(key, "copies") &&
3692 !_cups_strcasecmp(value, "t"))
3693 type |= CUPS_PRINTER_COPIES;
3694 else if (!_cups_strcasecmp(key, "duplex") &&
3695 !_cups_strcasecmp(value, "t"))
3696 type |= CUPS_PRINTER_DUPLEX;
3697 else if (!_cups_strcasecmp(key, "fax") &&
3698 !_cups_strcasecmp(value, "t"))
3699 type |= CUPS_PRINTER_MFP;
3700 else if (!_cups_strcasecmp(key, "papercustom") &&
3701 !_cups_strcasecmp(value, "t"))
3702 type |= CUPS_PRINTER_VARIABLE;
3703 else if (!_cups_strcasecmp(key, "papermax"))
3704 {
3705 if (!_cups_strcasecmp(value, "legal-a4"))
3706 type |= CUPS_PRINTER_SMALL;
3707 else if (!_cups_strcasecmp(value, "isoc-a2"))
3708 type |= CUPS_PRINTER_MEDIUM;
3709 else if (!_cups_strcasecmp(value, ">isoc-a2"))
3710 type |= CUPS_PRINTER_LARGE;
3711 }
3712 else if (!_cups_strcasecmp(key, "punch") &&
3713 !_cups_strcasecmp(value, "t"))
3714 type |= CUPS_PRINTER_PUNCH;
3715 else if (!_cups_strcasecmp(key, "scan") &&
3716 !_cups_strcasecmp(value, "t"))
3717 type |= CUPS_PRINTER_MFP;
3718 else if (!_cups_strcasecmp(key, "sort") &&
3719 !_cups_strcasecmp(value, "t"))
3720 type |= CUPS_PRINTER_SORT;
3721 else if (!_cups_strcasecmp(key, "staple") &&
3722 !_cups_strcasecmp(value, "t"))
3723 type |= CUPS_PRINTER_STAPLE;
3724 }
3725 }
3726
3727 /*
3728 * Save the printer-xxx values...
3729 */
3730
3731 if (make_and_model[0])
3732 {
3733 strlcat(make_and_model, " ", sizeof(make_and_model));
3734 strlcat(make_and_model, model, sizeof(make_and_model));
3735
3736 device->dest.num_options = cupsAddOption("printer-make-and-model", make_and_model, device->dest.num_options, &device->dest.options);
3737 }
3738 else
3739 device->dest.num_options = cupsAddOption("printer-make-and-model", model, device->dest.num_options, &device->dest.options);
3740
3741 device->type = type;
3742 snprintf(value, sizeof(value), "%u", type);
3743 device->dest.num_options = cupsAddOption("printer-type", value, device->dest.num_options, &device->dest.options);
3744
3745 /*
3746 * Save the URI...
3747 */
3748
3749 cups_dnssd_unquote(uriname, device->fullName, sizeof(uriname));
3750 httpAssembleURI(HTTP_URI_CODING_ALL, uri, sizeof(uri),
3751 !strcmp(device->regtype, "_ipps._tcp") ? "ipps" : "ipp",
3752 NULL, uriname, 0, saw_printer_type ? "/cups" : "/");
3753
3754 DEBUG_printf(("6cups_dnssd_query: device-uri=\"%s\"", uri));
3755
3756 device->dest.num_options = cupsAddOption("device-uri", uri, device->dest.num_options, &device->dest.options);
3757 }
3758 else
3759 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
3760 fullName));
3761 }
3762
3763
3764 /*
3765 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
3766 */
3767
3768 static const char * /* O - Resolved URI or NULL */
3769 cups_dnssd_resolve(
3770 cups_dest_t *dest, /* I - Destination */
3771 const char *uri, /* I - Current printer URI */
3772 int msec, /* I - Time in milliseconds */
3773 int *cancel, /* I - Pointer to "cancel" variable */
3774 cups_dest_cb_t cb, /* I - Callback */
3775 void *user_data) /* I - User data for callback */
3776 {
3777 char tempuri[1024]; /* Temporary URI buffer */
3778 _cups_dnssd_resolve_t resolve; /* Resolve data */
3779
3780
3781 /*
3782 * Resolve the URI...
3783 */
3784
3785 resolve.cancel = cancel;
3786 gettimeofday(&resolve.end_time, NULL);
3787 if (msec > 0)
3788 {
3789 resolve.end_time.tv_sec += msec / 1000;
3790 resolve.end_time.tv_usec += (msec % 1000) * 1000;
3791
3792 while (resolve.end_time.tv_usec >= 1000000)
3793 {
3794 resolve.end_time.tv_sec ++;
3795 resolve.end_time.tv_usec -= 1000000;
3796 }
3797 }
3798 else
3799 resolve.end_time.tv_sec += 75;
3800
3801 if (cb)
3802 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING, dest);
3803
3804 if ((uri = _httpResolveURI(uri, tempuri, sizeof(tempuri), _HTTP_RESOLVE_DEFAULT, cups_dnssd_resolve_cb, &resolve)) == NULL)
3805 {
3806 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to resolve printer-uri."), 1);
3807
3808 if (cb)
3809 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR, dest);
3810
3811 return (NULL);
3812 }
3813
3814 /*
3815 * Save the resolved URI...
3816 */
3817
3818 dest->num_options = cupsAddOption("device-uri", uri, dest->num_options, &dest->options);
3819
3820 return (cupsGetOption("device-uri", dest->num_options, dest->options));
3821 }
3822
3823
3824 /*
3825 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
3826 */
3827
3828 static int /* O - 1 to continue, 0 to stop */
3829 cups_dnssd_resolve_cb(void *context) /* I - Resolve data */
3830 {
3831 _cups_dnssd_resolve_t *resolve = (_cups_dnssd_resolve_t *)context;
3832 /* Resolve data */
3833 struct timeval curtime; /* Current time */
3834
3835
3836 /*
3837 * If the cancel variable is set, return immediately.
3838 */
3839
3840 if (resolve->cancel && *(resolve->cancel))
3841 {
3842 DEBUG_puts("4cups_dnssd_resolve_cb: Canceled.");
3843 return (0);
3844 }
3845
3846 /*
3847 * Otherwise check the end time...
3848 */
3849
3850 gettimeofday(&curtime, NULL);
3851
3852 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));
3853
3854 return (curtime.tv_sec < resolve->end_time.tv_sec ||
3855 (curtime.tv_sec == resolve->end_time.tv_sec &&
3856 curtime.tv_usec < resolve->end_time.tv_usec));
3857 }
3858
3859
3860 /*
3861 * 'cups_dnssd_unquote()' - Unquote a name string.
3862 */
3863
3864 static void
3865 cups_dnssd_unquote(char *dst, /* I - Destination buffer */
3866 const char *src, /* I - Source string */
3867 size_t dstsize) /* I - Size of destination buffer */
3868 {
3869 char *dstend = dst + dstsize - 1; /* End of destination buffer */
3870
3871
3872 while (*src && dst < dstend)
3873 {
3874 if (*src == '\\')
3875 {
3876 src ++;
3877 if (isdigit(src[0] & 255) && isdigit(src[1] & 255) &&
3878 isdigit(src[2] & 255))
3879 {
3880 *dst++ = ((((src[0] - '0') * 10) + src[1] - '0') * 10) + src[2] - '0';
3881 src += 3;
3882 }
3883 else
3884 *dst++ = *src++;
3885 }
3886 else
3887 *dst++ = *src ++;
3888 }
3889
3890 *dst = '\0';
3891 }
3892 #endif /* HAVE_DNSSD */
3893
3894
3895 #if defined(HAVE_AVAHI) || defined(HAVE_DNSSD)
3896 /*
3897 * 'cups_elapsed()' - Return the elapsed time in milliseconds.
3898 */
3899
3900 static int /* O - Elapsed time in milliseconds */
3901 cups_elapsed(struct timeval *t) /* IO - Previous time */
3902 {
3903 int msecs; /* Milliseconds */
3904 struct timeval nt; /* New time */
3905
3906
3907 gettimeofday(&nt, NULL);
3908
3909 msecs = (int)(1000 * (nt.tv_sec - t->tv_sec) + (nt.tv_usec - t->tv_usec) / 1000);
3910
3911 *t = nt;
3912
3913 return (msecs);
3914 }
3915 #endif /* HAVE_AVAHI || HAVE_DNSSD */
3916
3917
3918 /*
3919 * 'cups_find_dest()' - Find a destination using a binary search.
3920 */
3921
3922 static int /* O - Index of match */
3923 cups_find_dest(const char *name, /* I - Destination name */
3924 const char *instance, /* I - Instance or NULL */
3925 int num_dests, /* I - Number of destinations */
3926 cups_dest_t *dests, /* I - Destinations */
3927 int prev, /* I - Previous index */
3928 int *rdiff) /* O - Difference of match */
3929 {
3930 int left, /* Low mark for binary search */
3931 right, /* High mark for binary search */
3932 current, /* Current index */
3933 diff; /* Result of comparison */
3934 cups_dest_t key; /* Search key */
3935
3936
3937 key.name = (char *)name;
3938 key.instance = (char *)instance;
3939
3940 if (prev >= 0)
3941 {
3942 /*
3943 * Start search on either side of previous...
3944 */
3945
3946 if ((diff = cups_compare_dests(&key, dests + prev)) == 0 ||
3947 (diff < 0 && prev == 0) ||
3948 (diff > 0 && prev == (num_dests - 1)))
3949 {
3950 *rdiff = diff;
3951 return (prev);
3952 }
3953 else if (diff < 0)
3954 {
3955 /*
3956 * Start with previous on right side...
3957 */
3958
3959 left = 0;
3960 right = prev;
3961 }
3962 else
3963 {
3964 /*
3965 * Start wih previous on left side...
3966 */
3967
3968 left = prev;
3969 right = num_dests - 1;
3970 }
3971 }
3972 else
3973 {
3974 /*
3975 * Start search in the middle...
3976 */
3977
3978 left = 0;
3979 right = num_dests - 1;
3980 }
3981
3982 do
3983 {
3984 current = (left + right) / 2;
3985 diff = cups_compare_dests(&key, dests + current);
3986
3987 if (diff == 0)
3988 break;
3989 else if (diff < 0)
3990 right = current;
3991 else
3992 left = current;
3993 }
3994 while ((right - left) > 1);
3995
3996 if (diff != 0)
3997 {
3998 /*
3999 * Check the last 1 or 2 elements...
4000 */
4001
4002 if ((diff = cups_compare_dests(&key, dests + left)) <= 0)
4003 current = left;
4004 else
4005 {
4006 diff = cups_compare_dests(&key, dests + right);
4007 current = right;
4008 }
4009 }
4010
4011 /*
4012 * Return the closest destination and the difference...
4013 */
4014
4015 *rdiff = diff;
4016
4017 return (current);
4018 }
4019
4020
4021 /*
4022 * 'cups_get_cb()' - Collect enumerated destinations.
4023 */
4024
4025 static int /* O - 1 to continue, 0 to stop */
4026 cups_get_cb(_cups_getdata_t *data, /* I - Data from cupsGetDests */
4027 unsigned flags, /* I - Enumeration flags */
4028 cups_dest_t *dest) /* I - Destination */
4029 {
4030 if (flags & CUPS_DEST_FLAGS_REMOVED)
4031 {
4032 /*
4033 * Remove destination from array...
4034 */
4035
4036 data->num_dests = cupsRemoveDest(dest->name, dest->instance, data->num_dests, &data->dests);
4037 }
4038 else
4039 {
4040 /*
4041 * Add destination to array...
4042 */
4043
4044 data->num_dests = cupsCopyDest(dest, data->num_dests, &data->dests);
4045 }
4046
4047 return (1);
4048 }
4049
4050
4051 /*
4052 * 'cups_get_default()' - Get the default destination from an lpoptions file.
4053 */
4054
4055 static char * /* O - Default destination or NULL */
4056 cups_get_default(const char *filename, /* I - File to read */
4057 char *namebuf, /* I - Name buffer */
4058 size_t namesize, /* I - Size of name buffer */
4059 const char **instance) /* I - Instance */
4060 {
4061 cups_file_t *fp; /* lpoptions file */
4062 char line[8192], /* Line from file */
4063 *value, /* Value for line */
4064 *nameptr; /* Pointer into name */
4065 int linenum; /* Current line */
4066
4067
4068 *namebuf = '\0';
4069
4070 if ((fp = cupsFileOpen(filename, "r")) != NULL)
4071 {
4072 linenum = 0;
4073
4074 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
4075 {
4076 if (!_cups_strcasecmp(line, "default") && value)
4077 {
4078 strlcpy(namebuf, value, namesize);
4079
4080 if ((nameptr = strchr(namebuf, ' ')) != NULL)
4081 *nameptr = '\0';
4082 if ((nameptr = strchr(namebuf, '\t')) != NULL)
4083 *nameptr = '\0';
4084
4085 if ((nameptr = strchr(namebuf, '/')) != NULL)
4086 *nameptr++ = '\0';
4087
4088 *instance = nameptr;
4089 break;
4090 }
4091 }
4092
4093 cupsFileClose(fp);
4094 }
4095
4096 return (*namebuf ? namebuf : NULL);
4097 }
4098
4099
4100 /*
4101 * 'cups_get_dests()' - Get destinations from a file.
4102 */
4103
4104 static int /* O - Number of destinations */
4105 cups_get_dests(
4106 const char *filename, /* I - File to read from */
4107 const char *match_name, /* I - Destination name we want */
4108 const char *match_inst, /* I - Instance name we want */
4109 int user_default_set, /* I - User default printer set? */
4110 int num_dests, /* I - Number of destinations */
4111 cups_dest_t **dests) /* IO - Destinations */
4112 {
4113 int i; /* Looping var */
4114 cups_dest_t *dest; /* Current destination */
4115 cups_file_t *fp; /* File pointer */
4116 char line[8192], /* Line from file */
4117 *lineptr, /* Pointer into line */
4118 *name, /* Name of destination/option */
4119 *instance; /* Instance of destination */
4120 int linenum; /* Current line number */
4121
4122
4123 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));
4124
4125 /*
4126 * Try to open the file...
4127 */
4128
4129 if ((fp = cupsFileOpen(filename, "r")) == NULL)
4130 return (num_dests);
4131
4132 /*
4133 * Read each printer; each line looks like:
4134 *
4135 * Dest name[/instance] options
4136 * Default name[/instance] options
4137 */
4138
4139 linenum = 0;
4140
4141 while (cupsFileGetConf(fp, line, sizeof(line), &lineptr, &linenum))
4142 {
4143 /*
4144 * See what type of line it is...
4145 */
4146
4147 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
4148 linenum, line, lineptr));
4149
4150 if ((_cups_strcasecmp(line, "dest") && _cups_strcasecmp(line, "default")) || !lineptr)
4151 {
4152 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
4153 continue;
4154 }
4155
4156 name = lineptr;
4157
4158 /*
4159 * Search for an instance...
4160 */
4161
4162 while (!isspace(*lineptr & 255) && *lineptr && *lineptr != '/')
4163 lineptr ++;
4164
4165 if (*lineptr == '/')
4166 {
4167 /*
4168 * Found an instance...
4169 */
4170
4171 *lineptr++ = '\0';
4172 instance = lineptr;
4173
4174 /*
4175 * Search for an instance...
4176 */
4177
4178 while (!isspace(*lineptr & 255) && *lineptr)
4179 lineptr ++;
4180 }
4181 else
4182 instance = NULL;
4183
4184 if (*lineptr)
4185 *lineptr++ = '\0';
4186
4187 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name,
4188 instance));
4189
4190 /*
4191 * See if the primary instance of the destination exists; if not,
4192 * ignore this entry and move on...
4193 */
4194
4195 if (match_name)
4196 {
4197 if (_cups_strcasecmp(name, match_name) ||
4198 (!instance && match_inst) ||
4199 (instance && !match_inst) ||
4200 (instance && _cups_strcasecmp(instance, match_inst)))
4201 continue;
4202
4203 dest = *dests;
4204 }
4205 else if (cupsGetDest(name, NULL, num_dests, *dests) == NULL)
4206 {
4207 DEBUG_puts("9cups_get_dests: Not found!");
4208 continue;
4209 }
4210 else
4211 {
4212 /*
4213 * Add the destination...
4214 */
4215
4216 num_dests = cupsAddDest(name, instance, num_dests, dests);
4217
4218 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
4219 {
4220 /*
4221 * Out of memory!
4222 */
4223
4224 DEBUG_puts("9cups_get_dests: Out of memory!");
4225 break;
4226 }
4227 }
4228
4229 /*
4230 * Add options until we hit the end of the line...
4231 */
4232
4233 dest->num_options = cupsParseOptions(lineptr, dest->num_options,
4234 &(dest->options));
4235
4236 /*
4237 * If we found what we were looking for, stop now...
4238 */
4239
4240 if (match_name)
4241 break;
4242
4243 /*
4244 * Set this as default if needed...
4245 */
4246
4247 if (!user_default_set && !_cups_strcasecmp(line, "default"))
4248 {
4249 DEBUG_puts("9cups_get_dests: Setting as default...");
4250
4251 for (i = 0; i < num_dests; i ++)
4252 (*dests)[i].is_default = 0;
4253
4254 dest->is_default = 1;
4255 }
4256 }
4257
4258 /*
4259 * Close the file and return...
4260 */
4261
4262 cupsFileClose(fp);
4263
4264 return (num_dests);
4265 }
4266
4267
4268 /*
4269 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
4270 * attribute.
4271 */
4272
4273 static char * /* O - New string */
4274 cups_make_string(
4275 ipp_attribute_t *attr, /* I - Attribute to convert */
4276 char *buffer, /* I - Buffer */
4277 size_t bufsize) /* I - Size of buffer */
4278 {
4279 int i; /* Looping var */
4280 char *ptr, /* Pointer into buffer */
4281 *end, /* Pointer to end of buffer */
4282 *valptr; /* Pointer into string attribute */
4283
4284
4285 /*
4286 * Return quickly if we have a single string value...
4287 */
4288
4289 if (attr->num_values == 1 &&
4290 attr->value_tag != IPP_TAG_INTEGER &&
4291 attr->value_tag != IPP_TAG_ENUM &&
4292 attr->value_tag != IPP_TAG_BOOLEAN &&
4293 attr->value_tag != IPP_TAG_RANGE)
4294 return (attr->values[0].string.text);
4295
4296 /*
4297 * Copy the values to the string, separating with commas and escaping strings
4298 * as needed...
4299 */
4300
4301 end = buffer + bufsize - 1;
4302
4303 for (i = 0, ptr = buffer; i < attr->num_values && ptr < end; i ++)
4304 {
4305 if (i)
4306 *ptr++ = ',';
4307
4308 switch (attr->value_tag)
4309 {
4310 case IPP_TAG_INTEGER :
4311 case IPP_TAG_ENUM :
4312 snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].integer);
4313 break;
4314
4315 case IPP_TAG_BOOLEAN :
4316 if (attr->values[i].boolean)
4317 strlcpy(ptr, "true", (size_t)(end - ptr + 1));
4318 else
4319 strlcpy(ptr, "false", (size_t)(end - ptr + 1));
4320 break;
4321
4322 case IPP_TAG_RANGE :
4323 if (attr->values[i].range.lower == attr->values[i].range.upper)
4324 snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].range.lower);
4325 else
4326 snprintf(ptr, (size_t)(end - ptr + 1), "%d-%d", attr->values[i].range.lower, attr->values[i].range.upper);
4327 break;
4328
4329 default :
4330 for (valptr = attr->values[i].string.text;
4331 *valptr && ptr < end;)
4332 {
4333 if (strchr(" \t\n\\\'\"", *valptr))
4334 {
4335 if (ptr >= (end - 1))
4336 break;
4337
4338 *ptr++ = '\\';
4339 }
4340
4341 *ptr++ = *valptr++;
4342 }
4343
4344 *ptr = '\0';
4345 break;
4346 }
4347
4348 ptr += strlen(ptr);
4349 }
4350
4351 *ptr = '\0';
4352
4353 return (buffer);
4354 }
4355
4356
4357 /*
4358 * 'cups_name_cb()' - Find an enumerated destination.
4359 */
4360
4361 static int /* O - 1 to continue, 0 to stop */
4362 cups_name_cb(_cups_namedata_t *data, /* I - Data from cupsGetNamedDest */
4363 unsigned flags, /* I - Enumeration flags */
4364 cups_dest_t *dest) /* I - Destination */
4365 {
4366 DEBUG_printf(("2cups_name_cb(data=%p(%s), flags=%x, dest=%p(%s)", (void *)data, data->name, flags, (void *)dest, dest->name));
4367
4368 if (!(flags & CUPS_DEST_FLAGS_REMOVED) && !dest->instance && !strcasecmp(data->name, dest->name))
4369 {
4370 /*
4371 * Copy destination and stop enumeration...
4372 */
4373
4374 cupsCopyDest(dest, 0, &data->dest);
4375 return (0);
4376 }
4377
4378 return (1);
4379 }
4380
4381
4382 /*
4383 * 'cups_queue_name()' - Create a local queue name based on the service name.
4384 */
4385
4386 static void
4387 cups_queue_name(
4388 char *name, /* I - Name buffer */
4389 const char *serviceName, /* I - Service name */
4390 size_t namesize) /* I - Size of name buffer */
4391 {
4392 const char *ptr; /* Pointer into serviceName */
4393 char *nameptr; /* Pointer into name */
4394
4395
4396 for (nameptr = name, ptr = serviceName; *ptr && nameptr < (name + namesize - 1); ptr ++)
4397 {
4398 /*
4399 * Sanitize the printer name...
4400 */
4401
4402 if (_cups_isalnum(*ptr))
4403 *nameptr++ = *ptr;
4404 else if (nameptr == name || nameptr[-1] != '_')
4405 *nameptr++ = '_';
4406 }
4407
4408 *nameptr = '\0';
4409 }