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