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