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