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