]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/dest.c
Migrate Windows conditional code to _WIN32 define.
[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 connection 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 if (!strncmp(resource, "/ipp/print/", 11))
1285 {
1286 snprintf(temp, sizeof(temp), "%s @ %s", resource + 11, hostname);
1287 name = resource + 11;
1288 info = temp;
1289 }
1290 else
1291 {
1292 name = hostname;
1293 info = hostname;
1294 }
1295 }
1296
1297 /*
1298 * Create the destination...
1299 */
1300
1301 if ((dest = calloc(1, sizeof(cups_dest_t))) == NULL)
1302 {
1303 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
1304 return (NULL);
1305 }
1306
1307 dest->name = _cupsStrAlloc(name);
1308 dest->num_options = cupsAddOption("device-uri", uri, dest->num_options, &(dest->options));
1309 dest->num_options = cupsAddOption("printer-info", info, dest->num_options, &(dest->options));
1310
1311 return (dest);
1312 }
1313
1314
1315 /*
1316 * '_cupsGetDests()' - Get destinations from a server.
1317 *
1318 * "op" is IPP_OP_CUPS_GET_PRINTERS to get a full list, IPP_OP_CUPS_GET_DEFAULT
1319 * to get the system-wide default printer, or IPP_OP_GET_PRINTER_ATTRIBUTES for
1320 * a known printer.
1321 *
1322 * "name" is the name of an existing printer and is only used when "op" is
1323 * IPP_OP_GET_PRINTER_ATTRIBUTES.
1324 *
1325 * "dest" is initialized to point to the array of destinations.
1326 *
1327 * 0 is returned if there are no printers, no default printer, or the named
1328 * printer does not exist, respectively.
1329 *
1330 * Free the memory used by the destination array using the @link cupsFreeDests@
1331 * function.
1332 *
1333 * Note: On macOS this function also gets the default paper from the system
1334 * preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
1335 * options array for each destination that supports it.
1336 */
1337
1338 int /* O - Number of destinations */
1339 _cupsGetDests(http_t *http, /* I - Connection to server or
1340 * @code CUPS_HTTP_DEFAULT@ */
1341 ipp_op_t op, /* I - IPP operation */
1342 const char *name, /* I - Name of destination */
1343 cups_dest_t **dests, /* IO - Destinations */
1344 cups_ptype_t type, /* I - Printer type bits */
1345 cups_ptype_t mask) /* I - Printer type mask */
1346 {
1347 int num_dests = 0; /* Number of destinations */
1348 cups_dest_t *dest; /* Current destination */
1349 ipp_t *request, /* IPP Request */
1350 *response; /* IPP Response */
1351 ipp_attribute_t *attr; /* Current attribute */
1352 const char *printer_name; /* printer-name attribute */
1353 char uri[1024]; /* printer-uri value */
1354 int num_options; /* Number of options */
1355 cups_option_t *options; /* Options */
1356 #ifdef __APPLE__
1357 char media_default[41]; /* Default paper size */
1358 #endif /* __APPLE__ */
1359 char optname[1024], /* Option name */
1360 value[2048], /* Option value */
1361 *ptr; /* Pointer into name/value */
1362 static const char * const pattrs[] = /* Attributes we're interested in */
1363 {
1364 "auth-info-required",
1365 "device-uri",
1366 "job-sheets-default",
1367 "marker-change-time",
1368 "marker-colors",
1369 "marker-high-levels",
1370 "marker-levels",
1371 "marker-low-levels",
1372 "marker-message",
1373 "marker-names",
1374 "marker-types",
1375 #ifdef __APPLE__
1376 "media-supported",
1377 #endif /* __APPLE__ */
1378 "printer-commands",
1379 "printer-defaults",
1380 "printer-info",
1381 "printer-is-accepting-jobs",
1382 "printer-is-shared",
1383 "printer-is-temporary",
1384 "printer-location",
1385 "printer-make-and-model",
1386 "printer-mandatory-job-attributes",
1387 "printer-name",
1388 "printer-state",
1389 "printer-state-change-time",
1390 "printer-state-reasons",
1391 "printer-type",
1392 "printer-uri-supported"
1393 };
1394
1395
1396 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));
1397
1398 #ifdef __APPLE__
1399 /*
1400 * Get the default paper size...
1401 */
1402
1403 appleGetPaperSize(media_default, sizeof(media_default));
1404 DEBUG_printf(("1_cupsGetDests: Default media is '%s'.", media_default));
1405 #endif /* __APPLE__ */
1406
1407 /*
1408 * Build a IPP_OP_CUPS_GET_PRINTERS or IPP_OP_GET_PRINTER_ATTRIBUTES request, which
1409 * require the following attributes:
1410 *
1411 * attributes-charset
1412 * attributes-natural-language
1413 * requesting-user-name
1414 * printer-uri [for IPP_OP_GET_PRINTER_ATTRIBUTES]
1415 */
1416
1417 request = ippNewRequest(op);
1418
1419 ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
1420 "requested-attributes", sizeof(pattrs) / sizeof(pattrs[0]),
1421 NULL, pattrs);
1422
1423 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
1424 "requesting-user-name", NULL, cupsUser());
1425
1426 if (name && op != IPP_OP_CUPS_GET_DEFAULT)
1427 {
1428 httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
1429 "localhost", ippPort(), "/printers/%s", name);
1430 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL,
1431 uri);
1432 }
1433 else if (mask)
1434 {
1435 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type", (int)type);
1436 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type-mask", (int)mask);
1437 }
1438
1439 /*
1440 * Do the request and get back a response...
1441 */
1442
1443 if ((response = cupsDoRequest(http, request, "/")) != NULL)
1444 {
1445 for (attr = response->attrs; attr != NULL; attr = attr->next)
1446 {
1447 /*
1448 * Skip leading attributes until we hit a printer...
1449 */
1450
1451 while (attr != NULL && attr->group_tag != IPP_TAG_PRINTER)
1452 attr = attr->next;
1453
1454 if (attr == NULL)
1455 break;
1456
1457 /*
1458 * Pull the needed attributes from this printer...
1459 */
1460
1461 printer_name = NULL;
1462 num_options = 0;
1463 options = NULL;
1464
1465 for (; attr && attr->group_tag == IPP_TAG_PRINTER; attr = attr->next)
1466 {
1467 if (attr->value_tag != IPP_TAG_INTEGER &&
1468 attr->value_tag != IPP_TAG_ENUM &&
1469 attr->value_tag != IPP_TAG_BOOLEAN &&
1470 attr->value_tag != IPP_TAG_TEXT &&
1471 attr->value_tag != IPP_TAG_TEXTLANG &&
1472 attr->value_tag != IPP_TAG_NAME &&
1473 attr->value_tag != IPP_TAG_NAMELANG &&
1474 attr->value_tag != IPP_TAG_KEYWORD &&
1475 attr->value_tag != IPP_TAG_RANGE &&
1476 attr->value_tag != IPP_TAG_URI)
1477 continue;
1478
1479 if (!strcmp(attr->name, "auth-info-required") ||
1480 !strcmp(attr->name, "device-uri") ||
1481 !strcmp(attr->name, "marker-change-time") ||
1482 !strcmp(attr->name, "marker-colors") ||
1483 !strcmp(attr->name, "marker-high-levels") ||
1484 !strcmp(attr->name, "marker-levels") ||
1485 !strcmp(attr->name, "marker-low-levels") ||
1486 !strcmp(attr->name, "marker-message") ||
1487 !strcmp(attr->name, "marker-names") ||
1488 !strcmp(attr->name, "marker-types") ||
1489 !strcmp(attr->name, "printer-commands") ||
1490 !strcmp(attr->name, "printer-info") ||
1491 !strcmp(attr->name, "printer-is-shared") ||
1492 !strcmp(attr->name, "printer-is-temporary") ||
1493 !strcmp(attr->name, "printer-make-and-model") ||
1494 !strcmp(attr->name, "printer-mandatory-job-attributes") ||
1495 !strcmp(attr->name, "printer-state") ||
1496 !strcmp(attr->name, "printer-state-change-time") ||
1497 !strcmp(attr->name, "printer-type") ||
1498 !strcmp(attr->name, "printer-is-accepting-jobs") ||
1499 !strcmp(attr->name, "printer-location") ||
1500 !strcmp(attr->name, "printer-state-reasons") ||
1501 !strcmp(attr->name, "printer-uri-supported"))
1502 {
1503 /*
1504 * Add a printer description attribute...
1505 */
1506
1507 num_options = cupsAddOption(attr->name,
1508 cups_make_string(attr, value,
1509 sizeof(value)),
1510 num_options, &options);
1511 }
1512 #ifdef __APPLE__
1513 else if (!strcmp(attr->name, "media-supported") && media_default[0])
1514 {
1515 /*
1516 * See if we can set a default media size...
1517 */
1518
1519 int i; /* Looping var */
1520
1521 for (i = 0; i < attr->num_values; i ++)
1522 if (!_cups_strcasecmp(media_default, attr->values[i].string.text))
1523 {
1524 DEBUG_printf(("1_cupsGetDests: Setting media to '%s'.", media_default));
1525 num_options = cupsAddOption("media", media_default, num_options, &options);
1526 break;
1527 }
1528 }
1529 #endif /* __APPLE__ */
1530 else if (!strcmp(attr->name, "printer-name") &&
1531 attr->value_tag == IPP_TAG_NAME)
1532 printer_name = attr->values[0].string.text;
1533 else if (strncmp(attr->name, "notify-", 7) &&
1534 strncmp(attr->name, "print-quality-", 14) &&
1535 (attr->value_tag == IPP_TAG_BOOLEAN ||
1536 attr->value_tag == IPP_TAG_ENUM ||
1537 attr->value_tag == IPP_TAG_INTEGER ||
1538 attr->value_tag == IPP_TAG_KEYWORD ||
1539 attr->value_tag == IPP_TAG_NAME ||
1540 attr->value_tag == IPP_TAG_RANGE) &&
1541 (ptr = strstr(attr->name, "-default")) != NULL)
1542 {
1543 /*
1544 * Add a default option...
1545 */
1546
1547 strlcpy(optname, attr->name, sizeof(optname));
1548 optname[ptr - attr->name] = '\0';
1549
1550 if (_cups_strcasecmp(optname, "media") || !cupsGetOption("media", num_options, options))
1551 num_options = cupsAddOption(optname, cups_make_string(attr, value, sizeof(value)), num_options, &options);
1552 }
1553 }
1554
1555 /*
1556 * See if we have everything needed...
1557 */
1558
1559 if (!printer_name)
1560 {
1561 cupsFreeOptions(num_options, options);
1562
1563 if (attr == NULL)
1564 break;
1565 else
1566 continue;
1567 }
1568
1569 if ((dest = cups_add_dest(printer_name, NULL, &num_dests, dests)) != NULL)
1570 {
1571 dest->num_options = num_options;
1572 dest->options = options;
1573 }
1574 else
1575 cupsFreeOptions(num_options, options);
1576
1577 if (attr == NULL)
1578 break;
1579 }
1580
1581 ippDelete(response);
1582 }
1583
1584 /*
1585 * Return the count...
1586 */
1587
1588 return (num_dests);
1589 }
1590
1591
1592 /*
1593 * 'cupsGetDests()' - Get the list of destinations from the default server.
1594 *
1595 * Starting with CUPS 1.2, the returned list of destinations include the
1596 * "printer-info", "printer-is-accepting-jobs", "printer-is-shared",
1597 * "printer-make-and-model", "printer-state", "printer-state-change-time",
1598 * "printer-state-reasons", "printer-type", and "printer-uri-supported"
1599 * attributes as options.
1600 *
1601 * CUPS 1.4 adds the "marker-change-time", "marker-colors",
1602 * "marker-high-levels", "marker-levels", "marker-low-levels", "marker-message",
1603 * "marker-names", "marker-types", and "printer-commands" attributes as options.
1604 *
1605 * CUPS 2.2 adds accessible IPP printers to the list of destinations that can
1606 * be used. The "printer-uri-supported" option will be present for those IPP
1607 * printers that have been recently used.
1608 *
1609 * Use the @link cupsFreeDests@ function to free the destination list and
1610 * the @link cupsGetDest@ function to find a particular destination.
1611 *
1612 * @exclude all@
1613 */
1614
1615 int /* O - Number of destinations */
1616 cupsGetDests(cups_dest_t **dests) /* O - Destinations */
1617 {
1618 return (cupsGetDests2(CUPS_HTTP_DEFAULT, dests));
1619 }
1620
1621
1622 /*
1623 * 'cupsGetDests2()' - Get the list of destinations from the specified server.
1624 *
1625 * Starting with CUPS 1.2, the returned list of destinations include the
1626 * "printer-info", "printer-is-accepting-jobs", "printer-is-shared",
1627 * "printer-make-and-model", "printer-state", "printer-state-change-time",
1628 * "printer-state-reasons", "printer-type", and "printer-uri-supported"
1629 * attributes as options.
1630 *
1631 * CUPS 1.4 adds the "marker-change-time", "marker-colors",
1632 * "marker-high-levels", "marker-levels", "marker-low-levels", "marker-message",
1633 * "marker-names", "marker-types", and "printer-commands" attributes as options.
1634 *
1635 * CUPS 2.2 adds accessible IPP printers to the list of destinations that can
1636 * be used. The "printer-uri-supported" option will be present for those IPP
1637 * printers that have been recently used.
1638 *
1639 * Use the @link cupsFreeDests@ function to free the destination list and
1640 * the @link cupsGetDest@ function to find a particular destination.
1641 *
1642 * @since CUPS 1.1.21/macOS 10.4@
1643 */
1644
1645 int /* O - Number of destinations */
1646 cupsGetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1647 cups_dest_t **dests) /* O - Destinations */
1648 {
1649 _cups_getdata_t data; /* Enumeration data */
1650
1651
1652 DEBUG_printf(("cupsGetDests2(http=%p, dests=%p)", (void *)http, (void *)dests));
1653
1654 /*
1655 * Range check the input...
1656 */
1657
1658 if (!dests)
1659 {
1660 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad NULL dests pointer"), 1);
1661 DEBUG_puts("1cupsGetDests2: NULL dests pointer, returning 0.");
1662 return (0);
1663 }
1664
1665 /*
1666 * Connect to the server as needed...
1667 */
1668
1669 if (!http)
1670 {
1671 if ((http = _cupsConnect()) == NULL)
1672 {
1673 *dests = NULL;
1674
1675 return (0);
1676 }
1677 }
1678
1679 /*
1680 * Grab the printers and classes...
1681 */
1682
1683 data.num_dests = 0;
1684 data.dests = NULL;
1685
1686 if (!httpAddrLocalhost(httpGetAddress(http)))
1687 {
1688 /*
1689 * When talking to a remote cupsd, just enumerate printers on the remote
1690 * cupsd.
1691 */
1692
1693 cups_enum_dests(http, 0, _CUPS_DNSSD_GET_DESTS, NULL, 0, CUPS_PRINTER_DISCOVERED, (cups_dest_cb_t)cups_get_cb, &data);
1694 }
1695 else
1696 {
1697 /*
1698 * When talking to a local cupsd, enumerate both local printers and ones we
1699 * can find on the network...
1700 */
1701
1702 cups_enum_dests(http, 0, _CUPS_DNSSD_GET_DESTS, NULL, 0, 0, (cups_dest_cb_t)cups_get_cb, &data);
1703 }
1704
1705 /*
1706 * Return the number of destinations...
1707 */
1708
1709 *dests = data.dests;
1710
1711 if (data.num_dests > 0)
1712 _cupsSetError(IPP_STATUS_OK, NULL, 0);
1713
1714 DEBUG_printf(("1cupsGetDests2: Returning %d destinations.", data.num_dests));
1715
1716 return (data.num_dests);
1717 }
1718
1719
1720 /*
1721 * 'cupsGetNamedDest()' - Get options for the named destination.
1722 *
1723 * This function is optimized for retrieving a single destination and should
1724 * be used instead of @link cupsGetDests2@ and @link cupsGetDest@ when you
1725 * either know the name of the destination or want to print to the default
1726 * destination. If @code NULL@ is returned, the destination does not exist or
1727 * there is no default destination.
1728 *
1729 * If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
1730 * server will be used.
1731 *
1732 * If "name" is @code NULL@, the default printer for the current user will be
1733 * returned.
1734 *
1735 * The returned destination must be freed using @link cupsFreeDests@ with a
1736 * "num_dests" value of 1.
1737 *
1738 * @since CUPS 1.4/macOS 10.6@
1739 */
1740
1741 cups_dest_t * /* O - Destination or @code NULL@ */
1742 cupsGetNamedDest(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
1743 const char *name, /* I - Destination name or @code NULL@ for the default destination */
1744 const char *instance) /* I - Instance name or @code NULL@ */
1745 {
1746 const char *dest_name; /* Working destination name */
1747 cups_dest_t *dest; /* Destination */
1748 char filename[1024], /* Path to lpoptions */
1749 defname[256]; /* Default printer name */
1750 const char *home = getenv("HOME"); /* Home directory */
1751 int set_as_default = 0; /* Set returned destination as default */
1752 ipp_op_t op = IPP_OP_GET_PRINTER_ATTRIBUTES;
1753 /* IPP operation to get server ops */
1754 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
1755
1756
1757 DEBUG_printf(("cupsGetNamedDest(http=%p, name=\"%s\", instance=\"%s\")", (void *)http, name, instance));
1758
1759 /*
1760 * If "name" is NULL, find the default destination...
1761 */
1762
1763 dest_name = name;
1764
1765 if (!dest_name)
1766 {
1767 set_as_default = 1;
1768 dest_name = _cupsUserDefault(defname, sizeof(defname));
1769
1770 if (dest_name)
1771 {
1772 char *ptr; /* Temporary pointer... */
1773
1774 if ((ptr = strchr(defname, '/')) != NULL)
1775 {
1776 *ptr++ = '\0';
1777 instance = ptr;
1778 }
1779 else
1780 instance = NULL;
1781 }
1782 else if (home)
1783 {
1784 /*
1785 * No default in the environment, try the user's lpoptions files...
1786 */
1787
1788 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
1789
1790 dest_name = cups_get_default(filename, defname, sizeof(defname), &instance);
1791
1792 if (dest_name)
1793 set_as_default = 2;
1794 }
1795
1796 if (!dest_name)
1797 {
1798 /*
1799 * Still not there? Try the system lpoptions file...
1800 */
1801
1802 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
1803 dest_name = cups_get_default(filename, defname, sizeof(defname), &instance);
1804
1805 if (dest_name)
1806 set_as_default = 3;
1807 }
1808
1809 if (!dest_name)
1810 {
1811 /*
1812 * No locally-set default destination, ask the server...
1813 */
1814
1815 op = IPP_OP_CUPS_GET_DEFAULT;
1816 set_as_default = 4;
1817
1818 DEBUG_puts("1cupsGetNamedDest: Asking server for default printer...");
1819 }
1820 else
1821 DEBUG_printf(("1cupsGetNamedDest: Using name=\"%s\"...", name));
1822 }
1823
1824 /*
1825 * Get the printer's attributes...
1826 */
1827
1828 if (!_cupsGetDests(http, op, dest_name, &dest, 0, 0))
1829 {
1830 if (name)
1831 {
1832 _cups_namedata_t data; /* Callback data */
1833
1834 DEBUG_puts("1cupsGetNamedDest: No queue found for printer, looking on network...");
1835
1836 data.name = name;
1837 data.dest = NULL;
1838
1839 cupsEnumDests(0, 1000, NULL, 0, 0, (cups_dest_cb_t)cups_name_cb, &data);
1840
1841 if (!data.dest)
1842 return (NULL);
1843
1844 dest = data.dest;
1845 }
1846 else
1847 {
1848 switch (set_as_default)
1849 {
1850 default :
1851 break;
1852
1853 case 1 : /* Set from env vars */
1854 if (getenv("LPDEST"))
1855 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("LPDEST environment variable names default destination that does not exist."), 1);
1856 else if (getenv("PRINTER"))
1857 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("PRINTER environment variable names default destination that does not exist."), 1);
1858 else
1859 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("No default destination."), 1);
1860 break;
1861
1862 case 2 : /* Set from ~/.cups/lpoptions */
1863 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("~/.cups/lpoptions file names default destination that does not exist."), 1);
1864 break;
1865
1866 case 3 : /* Set from /etc/cups/lpoptions */
1867 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("/etc/cups/lpoptions file names default destination that does not exist."), 1);
1868 break;
1869
1870 case 4 : /* Set from server */
1871 _cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("No default destination."), 1);
1872 break;
1873 }
1874
1875 return (NULL);
1876 }
1877 }
1878
1879 DEBUG_printf(("1cupsGetNamedDest: Got dest=%p", (void *)dest));
1880
1881 if (instance)
1882 dest->instance = _cupsStrAlloc(instance);
1883
1884 if (set_as_default)
1885 dest->is_default = 1;
1886
1887 /*
1888 * Then add local options...
1889 */
1890
1891 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
1892 cups_get_dests(filename, dest_name, instance, 0, 1, 1, &dest);
1893
1894 if (home)
1895 {
1896 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
1897
1898 cups_get_dests(filename, dest_name, instance, 0, 1, 1, &dest);
1899 }
1900
1901 /*
1902 * Return the result...
1903 */
1904
1905 return (dest);
1906 }
1907
1908
1909 /*
1910 * 'cupsRemoveDest()' - Remove a destination from the destination list.
1911 *
1912 * Removing a destination/instance does not delete the class or printer
1913 * queue, merely the lpoptions for that destination/instance. Use the
1914 * @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
1915 * options for the user.
1916 *
1917 * @since CUPS 1.3/macOS 10.5@
1918 */
1919
1920 int /* O - New number of destinations */
1921 cupsRemoveDest(const char *name, /* I - Destination name */
1922 const char *instance, /* I - Instance name or @code NULL@ */
1923 int num_dests, /* I - Number of destinations */
1924 cups_dest_t **dests) /* IO - Destinations */
1925 {
1926 int i; /* Index into destinations */
1927 cups_dest_t *dest; /* Pointer to destination */
1928
1929
1930 /*
1931 * Find the destination...
1932 */
1933
1934 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
1935 return (num_dests);
1936
1937 /*
1938 * Free memory...
1939 */
1940
1941 _cupsStrFree(dest->name);
1942 _cupsStrFree(dest->instance);
1943 cupsFreeOptions(dest->num_options, dest->options);
1944
1945 /*
1946 * Remove the destination from the array...
1947 */
1948
1949 num_dests --;
1950
1951 i = (int)(dest - *dests);
1952
1953 if (i < num_dests)
1954 memmove(dest, dest + 1, (size_t)(num_dests - i) * sizeof(cups_dest_t));
1955
1956 return (num_dests);
1957 }
1958
1959
1960 /*
1961 * 'cupsSetDefaultDest()' - Set the default destination.
1962 *
1963 * @since CUPS 1.3/macOS 10.5@
1964 */
1965
1966 void
1967 cupsSetDefaultDest(
1968 const char *name, /* I - Destination name */
1969 const char *instance, /* I - Instance name or @code NULL@ */
1970 int num_dests, /* I - Number of destinations */
1971 cups_dest_t *dests) /* I - Destinations */
1972 {
1973 int i; /* Looping var */
1974 cups_dest_t *dest; /* Current destination */
1975
1976
1977 /*
1978 * Range check input...
1979 */
1980
1981 if (!name || num_dests <= 0 || !dests)
1982 return;
1983
1984 /*
1985 * Loop through the array and set the "is_default" flag for the matching
1986 * destination...
1987 */
1988
1989 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
1990 dest->is_default = !_cups_strcasecmp(name, dest->name) &&
1991 ((!instance && !dest->instance) ||
1992 (instance && dest->instance &&
1993 !_cups_strcasecmp(instance, dest->instance)));
1994 }
1995
1996
1997 /*
1998 * 'cupsSetDests()' - Save the list of destinations for the default server.
1999 *
2000 * This function saves the destinations to /etc/cups/lpoptions when run
2001 * as root and ~/.cups/lpoptions when run as a normal user.
2002 *
2003 * @exclude all@
2004 */
2005
2006 void
2007 cupsSetDests(int num_dests, /* I - Number of destinations */
2008 cups_dest_t *dests) /* I - Destinations */
2009 {
2010 cupsSetDests2(CUPS_HTTP_DEFAULT, num_dests, dests);
2011 }
2012
2013
2014 /*
2015 * 'cupsSetDests2()' - Save the list of destinations for the specified server.
2016 *
2017 * This function saves the destinations to /etc/cups/lpoptions when run
2018 * as root and ~/.cups/lpoptions when run as a normal user.
2019 *
2020 * @since CUPS 1.1.21/macOS 10.4@
2021 */
2022
2023 int /* O - 0 on success, -1 on error */
2024 cupsSetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
2025 int num_dests, /* I - Number of destinations */
2026 cups_dest_t *dests) /* I - Destinations */
2027 {
2028 int i, j; /* Looping vars */
2029 int wrote; /* Wrote definition? */
2030 cups_dest_t *dest; /* Current destination */
2031 cups_option_t *option; /* Current option */
2032 _ipp_option_t *match; /* Matching attribute for option */
2033 FILE *fp; /* File pointer */
2034 #ifndef _WIN32
2035 const char *home; /* HOME environment variable */
2036 #endif /* _WIN32 */
2037 char filename[1024]; /* lpoptions file */
2038 int num_temps; /* Number of temporary destinations */
2039 cups_dest_t *temps = NULL, /* Temporary destinations */
2040 *temp; /* Current temporary dest */
2041 const char *val; /* Value of temporary option */
2042 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
2043
2044
2045 /*
2046 * Range check the input...
2047 */
2048
2049 if (!num_dests || !dests)
2050 return (-1);
2051
2052 /*
2053 * Get the server destinations...
2054 */
2055
2056 num_temps = _cupsGetDests(http, IPP_OP_CUPS_GET_PRINTERS, NULL, &temps, 0, 0);
2057
2058 if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE)
2059 {
2060 cupsFreeDests(num_temps, temps);
2061 return (-1);
2062 }
2063
2064 /*
2065 * Figure out which file to write to...
2066 */
2067
2068 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
2069
2070 #ifndef _WIN32
2071 if (getuid())
2072 {
2073 /*
2074 * Point to user defaults...
2075 */
2076
2077 if ((home = getenv("HOME")) != NULL)
2078 {
2079 /*
2080 * Create ~/.cups subdirectory...
2081 */
2082
2083 snprintf(filename, sizeof(filename), "%s/.cups", home);
2084 if (access(filename, 0))
2085 mkdir(filename, 0700);
2086
2087 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
2088 }
2089 }
2090 #endif /* !_WIN32 */
2091
2092 /*
2093 * Try to open the file...
2094 */
2095
2096 if ((fp = fopen(filename, "w")) == NULL)
2097 {
2098 cupsFreeDests(num_temps, temps);
2099 return (-1);
2100 }
2101
2102 #ifndef _WIN32
2103 /*
2104 * Set the permissions to 0644 when saving to the /etc/cups/lpoptions
2105 * file...
2106 */
2107
2108 if (!getuid())
2109 fchmod(fileno(fp), 0644);
2110 #endif /* !_WIN32 */
2111
2112 /*
2113 * Write each printer; each line looks like:
2114 *
2115 * Dest name[/instance] options
2116 * Default name[/instance] options
2117 */
2118
2119 for (i = num_dests, dest = dests; i > 0; i --, dest ++)
2120 if (dest->instance != NULL || dest->num_options != 0 || dest->is_default)
2121 {
2122 if (dest->is_default)
2123 {
2124 fprintf(fp, "Default %s", dest->name);
2125 if (dest->instance)
2126 fprintf(fp, "/%s", dest->instance);
2127
2128 wrote = 1;
2129 }
2130 else
2131 wrote = 0;
2132
2133 temp = cupsGetDest(dest->name, NULL, num_temps, temps);
2134
2135 for (j = dest->num_options, option = dest->options; j > 0; j --, option ++)
2136 {
2137 /*
2138 * See if this option is a printer attribute; if so, skip it...
2139 */
2140
2141 if ((match = _ippFindOption(option->name)) != NULL && match->group_tag == IPP_TAG_PRINTER)
2142 continue;
2143
2144 /*
2145 * See if the server options match these; if so, don't write 'em.
2146 */
2147
2148 if (temp && (val = cupsGetOption(option->name, temp->num_options, temp->options)) != NULL && !_cups_strcasecmp(val, option->value))
2149 continue;
2150
2151 /*
2152 * Options don't match, write to the file...
2153 */
2154
2155 if (!wrote)
2156 {
2157 fprintf(fp, "Dest %s", dest->name);
2158 if (dest->instance)
2159 fprintf(fp, "/%s", dest->instance);
2160 wrote = 1;
2161 }
2162
2163 if (option->value[0])
2164 {
2165 if (strchr(option->value, ' ') || strchr(option->value, '\\') || strchr(option->value, '\"') || strchr(option->value, '\''))
2166 {
2167 /*
2168 * Quote the value...
2169 */
2170
2171 fprintf(fp, " %s=\"", option->name);
2172
2173 for (val = option->value; *val; val ++)
2174 {
2175 if (strchr("\"\'\\", *val))
2176 putc('\\', fp);
2177
2178 putc(*val, fp);
2179 }
2180
2181 putc('\"', fp);
2182 }
2183 else
2184 {
2185 /*
2186 * Store the literal value...
2187 */
2188
2189 fprintf(fp, " %s=%s", option->name, option->value);
2190 }
2191 }
2192 else
2193 fprintf(fp, " %s", option->name);
2194 }
2195
2196 if (wrote)
2197 fputs("\n", fp);
2198 }
2199
2200 /*
2201 * Free the temporary destinations and close the file...
2202 */
2203
2204 cupsFreeDests(num_temps, temps);
2205
2206 fclose(fp);
2207
2208 #ifdef __APPLE__
2209 /*
2210 * Set the default printer for this location - this allows command-line
2211 * and GUI applications to share the same default destination...
2212 */
2213
2214 if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) != NULL)
2215 {
2216 CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, dest->name, kCFStringEncodingUTF8);
2217 /* Default printer name */
2218
2219 if (name)
2220 {
2221 _cupsAppleSetDefaultPrinter(name);
2222 CFRelease(name);
2223 }
2224 }
2225 #endif /* __APPLE__ */
2226
2227 #ifdef HAVE_NOTIFY_POST
2228 /*
2229 * Send a notification so that macOS applications can know about the
2230 * change, too.
2231 */
2232
2233 notify_post("com.apple.printerListChange");
2234 #endif /* HAVE_NOTIFY_POST */
2235
2236 return (0);
2237 }
2238
2239
2240 /*
2241 * '_cupsUserDefault()' - Get the user default printer from environment
2242 * variables and location information.
2243 */
2244
2245 char * /* O - Default printer or NULL */
2246 _cupsUserDefault(char *name, /* I - Name buffer */
2247 size_t namesize) /* I - Size of name buffer */
2248 {
2249 const char *env; /* LPDEST or PRINTER env variable */
2250 #ifdef __APPLE__
2251 CFStringRef locprinter; /* Last printer as this location */
2252 #endif /* __APPLE__ */
2253
2254
2255 if ((env = getenv("LPDEST")) == NULL)
2256 if ((env = getenv("PRINTER")) != NULL && !strcmp(env, "lp"))
2257 env = NULL;
2258
2259 if (env)
2260 {
2261 strlcpy(name, env, namesize);
2262 return (name);
2263 }
2264
2265 #ifdef __APPLE__
2266 /*
2267 * Use location-based defaults if "use last printer" is selected in the
2268 * system preferences...
2269 */
2270
2271 if ((locprinter = _cupsAppleCopyDefaultPrinter()) != NULL)
2272 {
2273 CFStringGetCString(locprinter, name, (CFIndex)namesize, kCFStringEncodingUTF8);
2274 CFRelease(locprinter);
2275 }
2276 else
2277 name[0] = '\0';
2278
2279 DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name));
2280
2281 return (*name ? name : NULL);
2282
2283 #else
2284 /*
2285 * No location-based defaults on this platform...
2286 */
2287
2288 name[0] = '\0';
2289 return (NULL);
2290 #endif /* __APPLE__ */
2291 }
2292
2293
2294 #if _CUPS_LOCATION_DEFAULTS
2295 /*
2296 * 'appleCopyLocations()' - Copy the location history array.
2297 */
2298
2299 static CFArrayRef /* O - Location array or NULL */
2300 appleCopyLocations(void)
2301 {
2302 CFArrayRef locations; /* Location array */
2303
2304
2305 /*
2306 * Look up the location array in the preferences...
2307 */
2308
2309 if ((locations = CFPreferencesCopyAppValue(kLastUsedPrintersKey,
2310 kCUPSPrintingPrefs)) == NULL)
2311 return (NULL);
2312
2313 if (CFGetTypeID(locations) != CFArrayGetTypeID())
2314 {
2315 CFRelease(locations);
2316 return (NULL);
2317 }
2318
2319 return (locations);
2320 }
2321
2322
2323 /*
2324 * 'appleCopyNetwork()' - Get the network ID for the current location.
2325 */
2326
2327 static CFStringRef /* O - Network ID */
2328 appleCopyNetwork(void)
2329 {
2330 SCDynamicStoreRef dynamicStore; /* System configuration data */
2331 CFStringRef key; /* Current network configuration key */
2332 CFDictionaryRef ip_dict; /* Network configuration data */
2333 CFStringRef network = NULL; /* Current network ID */
2334
2335
2336 if ((dynamicStore = SCDynamicStoreCreate(NULL, CFSTR("libcups"), NULL,
2337 NULL)) != NULL)
2338 {
2339 /*
2340 * First use the IPv6 router address, if available, since that will generally
2341 * be a globally-unique link-local address.
2342 */
2343
2344 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
2345 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv6)) != NULL)
2346 {
2347 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2348 {
2349 if ((network = CFDictionaryGetValue(ip_dict,
2350 kSCPropNetIPv6Router)) != NULL)
2351 CFRetain(network);
2352
2353 CFRelease(ip_dict);
2354 }
2355
2356 CFRelease(key);
2357 }
2358
2359 /*
2360 * If that doesn't work, try the IPv4 router address. This isn't as unique
2361 * and will likely be a 10.x.y.z or 192.168.y.z address...
2362 */
2363
2364 if (!network)
2365 {
2366 if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
2367 NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4)) != NULL)
2368 {
2369 if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
2370 {
2371 if ((network = CFDictionaryGetValue(ip_dict,
2372 kSCPropNetIPv4Router)) != NULL)
2373 CFRetain(network);
2374
2375 CFRelease(ip_dict);
2376 }
2377
2378 CFRelease(key);
2379 }
2380 }
2381
2382 CFRelease(dynamicStore);
2383 }
2384
2385 return (network);
2386 }
2387 #endif /* _CUPS_LOCATION_DEFAULTS */
2388
2389
2390 #ifdef __APPLE__
2391 /*
2392 * 'appleGetPaperSize()' - Get the default paper size.
2393 */
2394
2395 static char * /* O - Default paper size */
2396 appleGetPaperSize(char *name, /* I - Paper size name buffer */
2397 size_t namesize) /* I - Size of buffer */
2398 {
2399 CFStringRef defaultPaperID; /* Default paper ID */
2400 pwg_media_t *pwgmedia; /* PWG media size */
2401
2402
2403 defaultPaperID = _cupsAppleCopyDefaultPaperID();
2404 if (!defaultPaperID ||
2405 CFGetTypeID(defaultPaperID) != CFStringGetTypeID() ||
2406 !CFStringGetCString(defaultPaperID, name, (CFIndex)namesize, kCFStringEncodingUTF8))
2407 name[0] = '\0';
2408 else if ((pwgmedia = pwgMediaForLegacy(name)) != NULL)
2409 strlcpy(name, pwgmedia->pwg, namesize);
2410
2411 if (defaultPaperID)
2412 CFRelease(defaultPaperID);
2413
2414 return (name);
2415 }
2416 #endif /* __APPLE__ */
2417
2418
2419 #if _CUPS_LOCATION_DEFAULTS
2420 /*
2421 * 'appleGetPrinter()' - Get a printer from the history array.
2422 */
2423
2424 static CFStringRef /* O - Printer name or NULL */
2425 appleGetPrinter(CFArrayRef locations, /* I - Location array */
2426 CFStringRef network, /* I - Network name */
2427 CFIndex *locindex) /* O - Index in array */
2428 {
2429 CFIndex i, /* Looping var */
2430 count; /* Number of locations */
2431 CFDictionaryRef location; /* Current location */
2432 CFStringRef locnetwork, /* Current network */
2433 locprinter; /* Current printer */
2434
2435
2436 for (i = 0, count = CFArrayGetCount(locations); i < count; i ++)
2437 if ((location = CFArrayGetValueAtIndex(locations, i)) != NULL &&
2438 CFGetTypeID(location) == CFDictionaryGetTypeID())
2439 {
2440 if ((locnetwork = CFDictionaryGetValue(location,
2441 kLocationNetworkKey)) != NULL &&
2442 CFGetTypeID(locnetwork) == CFStringGetTypeID() &&
2443 CFStringCompare(network, locnetwork, 0) == kCFCompareEqualTo &&
2444 (locprinter = CFDictionaryGetValue(location,
2445 kLocationPrinterIDKey)) != NULL &&
2446 CFGetTypeID(locprinter) == CFStringGetTypeID())
2447 {
2448 if (locindex)
2449 *locindex = i;
2450
2451 return (locprinter);
2452 }
2453 }
2454
2455 return (NULL);
2456 }
2457 #endif /* _CUPS_LOCATION_DEFAULTS */
2458
2459
2460 /*
2461 * 'cups_add_dest()' - Add a destination to the array.
2462 *
2463 * Unlike cupsAddDest(), this function does not check for duplicates.
2464 */
2465
2466 static cups_dest_t * /* O - New destination */
2467 cups_add_dest(const char *name, /* I - Name of destination */
2468 const char *instance, /* I - Instance or NULL */
2469 int *num_dests, /* IO - Number of destinations */
2470 cups_dest_t **dests) /* IO - Destinations */
2471 {
2472 int insert, /* Insertion point */
2473 diff; /* Result of comparison */
2474 cups_dest_t *dest; /* Destination pointer */
2475
2476
2477 /*
2478 * Add new destination...
2479 */
2480
2481 if (*num_dests == 0)
2482 dest = malloc(sizeof(cups_dest_t));
2483 else
2484 dest = realloc(*dests, sizeof(cups_dest_t) * (size_t)(*num_dests + 1));
2485
2486 if (!dest)
2487 return (NULL);
2488
2489 *dests = dest;
2490
2491 /*
2492 * Find where to insert the destination...
2493 */
2494
2495 if (*num_dests == 0)
2496 insert = 0;
2497 else
2498 {
2499 insert = cups_find_dest(name, instance, *num_dests, *dests, *num_dests - 1,
2500 &diff);
2501
2502 if (diff > 0)
2503 insert ++;
2504 }
2505
2506 /*
2507 * Move the array elements as needed...
2508 */
2509
2510 if (insert < *num_dests)
2511 memmove(*dests + insert + 1, *dests + insert, (size_t)(*num_dests - insert) * sizeof(cups_dest_t));
2512
2513 (*num_dests) ++;
2514
2515 /*
2516 * Initialize the destination...
2517 */
2518
2519 dest = *dests + insert;
2520 dest->name = _cupsStrAlloc(name);
2521 dest->instance = _cupsStrAlloc(instance);
2522 dest->is_default = 0;
2523 dest->num_options = 0;
2524 dest->options = (cups_option_t *)0;
2525
2526 return (dest);
2527 }
2528
2529
2530 # ifdef __BLOCKS__
2531 /*
2532 * 'cups_block_cb()' - Enumeration callback for block API.
2533 */
2534
2535 static int /* O - 1 to continue, 0 to stop */
2536 cups_block_cb(
2537 cups_dest_block_t block, /* I - Block */
2538 unsigned flags, /* I - Destination flags */
2539 cups_dest_t *dest) /* I - Destination */
2540 {
2541 return ((block)(flags, dest));
2542 }
2543 # endif /* __BLOCKS__ */
2544
2545
2546 /*
2547 * 'cups_compare_dests()' - Compare two destinations.
2548 */
2549
2550 static int /* O - Result of comparison */
2551 cups_compare_dests(cups_dest_t *a, /* I - First destination */
2552 cups_dest_t *b) /* I - Second destination */
2553 {
2554 int diff; /* Difference */
2555
2556
2557 if ((diff = _cups_strcasecmp(a->name, b->name)) != 0)
2558 return (diff);
2559 else if (a->instance && b->instance)
2560 return (_cups_strcasecmp(a->instance, b->instance));
2561 else
2562 return ((a->instance && !b->instance) - (!a->instance && b->instance));
2563 }
2564
2565
2566 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
2567 # ifdef HAVE_DNSSD
2568 /*
2569 * 'cups_dnssd_browse_cb()' - Browse for printers.
2570 */
2571
2572 static void
2573 cups_dnssd_browse_cb(
2574 DNSServiceRef sdRef, /* I - Service reference */
2575 DNSServiceFlags flags, /* I - Option flags */
2576 uint32_t interfaceIndex, /* I - Interface number */
2577 DNSServiceErrorType errorCode, /* I - Error, if any */
2578 const char *serviceName, /* I - Name of service/device */
2579 const char *regtype, /* I - Type of service */
2580 const char *replyDomain, /* I - Service domain */
2581 void *context) /* I - Enumeration data */
2582 {
2583 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2584 /* Enumeration data */
2585
2586
2587 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));
2588
2589 /*
2590 * Don't do anything on error...
2591 */
2592
2593 if (errorCode != kDNSServiceErr_NoError)
2594 return;
2595
2596 /*
2597 * Get the device...
2598 */
2599
2600 cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
2601 }
2602
2603
2604 # else /* HAVE_AVAHI */
2605 /*
2606 * 'cups_dnssd_browse_cb()' - Browse for printers.
2607 */
2608
2609 static void
2610 cups_dnssd_browse_cb(
2611 AvahiServiceBrowser *browser, /* I - Browser */
2612 AvahiIfIndex interface, /* I - Interface index (unused) */
2613 AvahiProtocol protocol, /* I - Network protocol (unused) */
2614 AvahiBrowserEvent event, /* I - What happened */
2615 const char *name, /* I - Service name */
2616 const char *type, /* I - Registration type */
2617 const char *domain, /* I - Domain */
2618 AvahiLookupResultFlags flags, /* I - Flags */
2619 void *context) /* I - Devices array */
2620 {
2621 #ifdef DEBUG
2622 AvahiClient *client = avahi_service_browser_get_client(browser);
2623 /* Client information */
2624 #endif /* DEBUG */
2625 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2626 /* Enumeration data */
2627
2628
2629 (void)interface;
2630 (void)protocol;
2631 (void)context;
2632
2633 DEBUG_printf(("cups_dnssd_browse_cb(..., name=\"%s\", type=\"%s\", domain=\"%s\", ...);", name, type, domain));
2634
2635 switch (event)
2636 {
2637 case AVAHI_BROWSER_FAILURE:
2638 DEBUG_printf(("cups_dnssd_browse_cb: %s", avahi_strerror(avahi_client_errno(client))));
2639 avahi_simple_poll_quit(data->simple_poll);
2640 break;
2641
2642 case AVAHI_BROWSER_NEW:
2643 /*
2644 * This object is new on the network.
2645 */
2646
2647 cups_dnssd_get_device(data, name, type, domain);
2648 break;
2649
2650 case AVAHI_BROWSER_REMOVE :
2651 case AVAHI_BROWSER_CACHE_EXHAUSTED :
2652 break;
2653
2654 case AVAHI_BROWSER_ALL_FOR_NOW :
2655 DEBUG_puts("cups_dnssd_browse_cb: ALL_FOR_NOW");
2656 data->browsers --;
2657 break;
2658 }
2659 }
2660
2661
2662 /*
2663 * 'cups_dnssd_client_cb()' - Avahi client callback function.
2664 */
2665
2666 static void
2667 cups_dnssd_client_cb(
2668 AvahiClient *client, /* I - Client information (unused) */
2669 AvahiClientState state, /* I - Current state */
2670 void *context) /* I - User data (unused) */
2671 {
2672 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2673 /* Enumeration data */
2674
2675
2676 (void)client;
2677
2678 DEBUG_printf(("cups_dnssd_client_cb(client=%p, state=%d, context=%p)", client, state, context));
2679
2680 /*
2681 * If the connection drops, quit.
2682 */
2683
2684 if (state == AVAHI_CLIENT_FAILURE)
2685 {
2686 DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
2687 avahi_simple_poll_quit(data->simple_poll);
2688 }
2689 }
2690 # endif /* HAVE_DNSSD */
2691
2692
2693 /*
2694 * 'cups_dnssd_compare_device()' - Compare two devices.
2695 */
2696
2697 static int /* O - Result of comparison */
2698 cups_dnssd_compare_devices(
2699 _cups_dnssd_device_t *a, /* I - First device */
2700 _cups_dnssd_device_t *b) /* I - Second device */
2701 {
2702 return (strcmp(a->dest.name, b->dest.name));
2703 }
2704
2705
2706 /*
2707 * 'cups_dnssd_free_device()' - Free the memory used by a device.
2708 */
2709
2710 static void
2711 cups_dnssd_free_device(
2712 _cups_dnssd_device_t *device, /* I - Device */
2713 _cups_dnssd_data_t *data) /* I - Enumeration data */
2714 {
2715 DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", (void *)device, device->dest.name, (void *)data));
2716
2717 # ifdef HAVE_DNSSD
2718 if (device->ref)
2719 DNSServiceRefDeallocate(device->ref);
2720 # else /* HAVE_AVAHI */
2721 if (device->ref)
2722 avahi_record_browser_free(device->ref);
2723 # endif /* HAVE_DNSSD */
2724
2725 _cupsStrFree(device->domain);
2726 _cupsStrFree(device->fullName);
2727 _cupsStrFree(device->regtype);
2728 _cupsStrFree(device->dest.name);
2729
2730 cupsFreeOptions(device->dest.num_options, device->dest.options);
2731
2732 free(device);
2733 }
2734
2735
2736 /*
2737 * 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
2738 */
2739
2740 static _cups_dnssd_device_t * /* O - Device */
2741 cups_dnssd_get_device(
2742 _cups_dnssd_data_t *data, /* I - Enumeration data */
2743 const char *serviceName, /* I - Service name */
2744 const char *regtype, /* I - Registration type */
2745 const char *replyDomain) /* I - Domain name */
2746 {
2747 _cups_dnssd_device_t key, /* Search key */
2748 *device; /* Device */
2749 char fullName[kDNSServiceMaxDomainName],
2750 /* Full name for query */
2751 name[128]; /* Queue name */
2752
2753
2754 DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", regtype=\"%s\", replyDomain=\"%s\")", (void *)data, serviceName, regtype, replyDomain));
2755
2756 /*
2757 * See if this is an existing device...
2758 */
2759
2760 cups_queue_name(name, serviceName, sizeof(name));
2761
2762 key.dest.name = name;
2763
2764 if ((device = cupsArrayFind(data->devices, &key)) != NULL)
2765 {
2766 /*
2767 * Yes, see if we need to do anything with this...
2768 */
2769
2770 int update = 0; /* Non-zero if we need to update */
2771
2772 if (!_cups_strcasecmp(replyDomain, "local.") &&
2773 _cups_strcasecmp(device->domain, replyDomain))
2774 {
2775 /*
2776 * Update the "global" listing to use the .local domain name instead.
2777 */
2778
2779 _cupsStrFree(device->domain);
2780 device->domain = _cupsStrAlloc(replyDomain);
2781
2782 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
2783 "domain.", device->dest.name));
2784
2785 update = 1;
2786 }
2787
2788 if (!_cups_strcasecmp(regtype, "_ipps._tcp") &&
2789 _cups_strcasecmp(device->regtype, regtype))
2790 {
2791 /*
2792 * Prefer IPPS over IPP.
2793 */
2794
2795 _cupsStrFree(device->regtype);
2796 device->regtype = _cupsStrAlloc(regtype);
2797
2798 DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
2799 device->dest.name));
2800
2801 update = 1;
2802 }
2803
2804 if (!update)
2805 {
2806 DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
2807 device->dest.name));
2808 return (device);
2809 }
2810 }
2811 else
2812 {
2813 /*
2814 * No, add the device...
2815 */
2816
2817 DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
2818 "'%s'.", serviceName,
2819 !strcmp(regtype, "_ipps._tcp") ? "IPPS" : "IPP",
2820 replyDomain));
2821
2822 device = calloc(sizeof(_cups_dnssd_device_t), 1);
2823 device->dest.name = _cupsStrAlloc(name);
2824 device->domain = _cupsStrAlloc(replyDomain);
2825 device->regtype = _cupsStrAlloc(regtype);
2826
2827 device->dest.num_options = cupsAddOption("printer-info", serviceName, 0, &device->dest.options);
2828
2829 cupsArrayAdd(data->devices, device);
2830 }
2831
2832 /*
2833 * Set the "full name" of this service, which is used for queries...
2834 */
2835
2836 # ifdef HAVE_DNSSD
2837 DNSServiceConstructFullName(fullName, serviceName, regtype, replyDomain);
2838 # else /* HAVE_AVAHI */
2839 avahi_service_name_join(fullName, kDNSServiceMaxDomainName, serviceName, regtype, replyDomain);
2840 # endif /* HAVE_DNSSD */
2841
2842 _cupsStrFree(device->fullName);
2843 device->fullName = _cupsStrAlloc(fullName);
2844
2845 if (device->ref)
2846 {
2847 # ifdef HAVE_DNSSD
2848 DNSServiceRefDeallocate(device->ref);
2849 # else /* HAVE_AVAHI */
2850 avahi_record_browser_free(device->ref);
2851 # endif /* HAVE_DNSSD */
2852
2853 device->ref = 0;
2854 }
2855
2856 if (device->state == _CUPS_DNSSD_ACTIVE)
2857 {
2858 DEBUG_printf(("6cups_dnssd_get_device: Remove callback for \"%s\".", device->dest.name));
2859
2860 (*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
2861 device->state = _CUPS_DNSSD_NEW;
2862 }
2863
2864 return (device);
2865 }
2866
2867
2868 # ifdef HAVE_AVAHI
2869 /*
2870 * 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
2871 *
2872 * Note: This function is needed because avahi_simple_poll_iterate is broken
2873 * and always uses a timeout of 0 (!) milliseconds.
2874 * (https://github.com/lathiat/avahi/issues/127)
2875 *
2876 * @private@
2877 */
2878
2879 static int /* O - Number of file descriptors matching */
2880 cups_dnssd_poll_cb(
2881 struct pollfd *pollfds, /* I - File descriptors */
2882 unsigned int num_pollfds, /* I - Number of file descriptors */
2883 int timeout, /* I - Timeout in milliseconds (unused) */
2884 void *context) /* I - User data (unused) */
2885 {
2886 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2887 /* Enumeration data */
2888 int val; /* Return value */
2889
2890
2891 DEBUG_printf(("cups_dnssd_poll_cb(pollfds=%p, num_pollfds=%d, timeout=%d, context=%p)", pollfds, num_pollfds, timeout, context));
2892
2893 (void)timeout;
2894
2895 val = poll(pollfds, num_pollfds, _CUPS_DNSSD_MAXTIME);
2896
2897 DEBUG_printf(("cups_dnssd_poll_cb: poll() returned %d", val));
2898
2899 if (val < 0)
2900 {
2901 DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno)));
2902 }
2903 else if (val > 0)
2904 {
2905 data->got_data = 1;
2906 }
2907
2908 return (val);
2909 }
2910 # endif /* HAVE_AVAHI */
2911
2912
2913 /*
2914 * 'cups_dnssd_query_cb()' - Process query data.
2915 */
2916
2917 static void
2918 cups_dnssd_query_cb(
2919 # ifdef HAVE_DNSSD
2920 DNSServiceRef sdRef, /* I - Service reference */
2921 DNSServiceFlags flags, /* I - Data flags */
2922 uint32_t interfaceIndex, /* I - Interface */
2923 DNSServiceErrorType errorCode, /* I - Error, if any */
2924 const char *fullName, /* I - Full service name */
2925 uint16_t rrtype, /* I - Record type */
2926 uint16_t rrclass, /* I - Record class */
2927 uint16_t rdlen, /* I - Length of record data */
2928 const void *rdata, /* I - Record data */
2929 uint32_t ttl, /* I - Time-to-live */
2930 # else /* HAVE_AVAHI */
2931 AvahiRecordBrowser *browser, /* I - Record browser */
2932 AvahiIfIndex interfaceIndex,
2933 /* I - Interface index (unused) */
2934 AvahiProtocol protocol, /* I - Network protocol (unused) */
2935 AvahiBrowserEvent event, /* I - What happened? */
2936 const char *fullName, /* I - Service name */
2937 uint16_t rrclass, /* I - Record class */
2938 uint16_t rrtype, /* I - Record type */
2939 const void *rdata, /* I - TXT record */
2940 size_t rdlen, /* I - Length of TXT record */
2941 AvahiLookupResultFlags flags, /* I - Flags */
2942 # endif /* HAVE_DNSSD */
2943 void *context) /* I - Enumeration data */
2944 {
2945 # if defined(DEBUG) && defined(HAVE_AVAHI)
2946 AvahiClient *client = avahi_record_browser_get_client(browser);
2947 /* Client information */
2948 # endif /* DEBUG && HAVE_AVAHI */
2949 _cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
2950 /* Enumeration data */
2951 char serviceName[256],/* Service name */
2952 name[128], /* Queue name */
2953 *ptr; /* Pointer into string */
2954 _cups_dnssd_device_t dkey, /* Search key */
2955 *device; /* Device */
2956
2957
2958 # ifdef HAVE_DNSSD
2959 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));
2960
2961 /*
2962 * Only process "add" data...
2963 */
2964
2965 if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
2966 return;
2967
2968 # else /* HAVE_AVAHI */
2969 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));
2970
2971 /*
2972 * Only process "add" data...
2973 */
2974
2975 if (event != AVAHI_BROWSER_NEW)
2976 {
2977 if (event == AVAHI_BROWSER_FAILURE)
2978 DEBUG_printf(("cups_dnssd_query_cb: %s", avahi_strerror(avahi_client_errno(client))));
2979
2980 return;
2981 }
2982 # endif /* HAVE_DNSSD */
2983
2984 /*
2985 * Lookup the service in the devices array.
2986 */
2987
2988 cups_dnssd_unquote(serviceName, fullName, sizeof(serviceName));
2989
2990 if ((ptr = strstr(serviceName, "._")) != NULL)
2991 *ptr = '\0';
2992
2993 cups_queue_name(name, serviceName, sizeof(name));
2994
2995 dkey.dest.name = name;
2996
2997 if ((device = cupsArrayFind(data->devices, &dkey)) != NULL && device->state == _CUPS_DNSSD_NEW)
2998 {
2999 /*
3000 * Found it, pull out the make and model from the TXT record and save it...
3001 */
3002
3003 const uint8_t *txt, /* Pointer into data */
3004 *txtnext, /* Next key/value pair */
3005 *txtend; /* End of entire TXT record */
3006 uint8_t txtlen; /* Length of current key/value pair */
3007 char key[256], /* Key string */
3008 value[256], /* Value string */
3009 make_and_model[512],
3010 /* Manufacturer and model */
3011 model[256], /* Model */
3012 uriname[1024], /* Name for URI */
3013 uri[1024]; /* Printer URI */
3014 cups_ptype_t type = CUPS_PRINTER_DISCOVERED | CUPS_PRINTER_BW;
3015 /* Printer type */
3016 int saw_printer_type = 0;
3017 /* Did we see a printer-type key? */
3018
3019 device->state = _CUPS_DNSSD_PENDING;
3020 make_and_model[0] = '\0';
3021
3022 strlcpy(model, "Unknown", sizeof(model));
3023
3024 for (txt = rdata, txtend = txt + rdlen;
3025 txt < txtend;
3026 txt = txtnext)
3027 {
3028 /*
3029 * Read a key/value pair starting with an 8-bit length. Since the
3030 * length is 8 bits and the size of the key/value buffers is 256, we
3031 * don't need to check for overflow...
3032 */
3033
3034 txtlen = *txt++;
3035
3036 if (!txtlen || (txt + txtlen) > txtend)
3037 break;
3038
3039 txtnext = txt + txtlen;
3040
3041 for (ptr = key; txt < txtnext && *txt != '='; txt ++)
3042 *ptr++ = (char)*txt;
3043 *ptr = '\0';
3044
3045 if (txt < txtnext && *txt == '=')
3046 {
3047 txt ++;
3048
3049 if (txt < txtnext)
3050 memcpy(value, txt, (size_t)(txtnext - txt));
3051 value[txtnext - txt] = '\0';
3052
3053 DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key, value));
3054 }
3055 else
3056 {
3057 DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key));
3058 continue;
3059 }
3060
3061 if (!_cups_strcasecmp(key, "usb_MFG") ||
3062 !_cups_strcasecmp(key, "usb_MANU") ||
3063 !_cups_strcasecmp(key, "usb_MANUFACTURER"))
3064 strlcpy(make_and_model, value, sizeof(make_and_model));
3065 else if (!_cups_strcasecmp(key, "usb_MDL") ||
3066 !_cups_strcasecmp(key, "usb_MODEL"))
3067 strlcpy(model, value, sizeof(model));
3068 else if (!_cups_strcasecmp(key, "product") && !strstr(value, "Ghostscript"))
3069 {
3070 if (value[0] == '(')
3071 {
3072 /*
3073 * Strip parenthesis...
3074 */
3075
3076 if ((ptr = value + strlen(value) - 1) > value && *ptr == ')')
3077 *ptr = '\0';
3078
3079 strlcpy(model, value + 1, sizeof(model));
3080 }
3081 else
3082 strlcpy(model, value, sizeof(model));
3083 }
3084 else if (!_cups_strcasecmp(key, "ty"))
3085 {
3086 strlcpy(model, value, sizeof(model));
3087
3088 if ((ptr = strchr(model, ',')) != NULL)
3089 *ptr = '\0';
3090 }
3091 else if (!_cups_strcasecmp(key, "note"))
3092 device->dest.num_options = cupsAddOption("printer-location", value,
3093 device->dest.num_options,
3094 &device->dest.options);
3095 else if (!_cups_strcasecmp(key, "pdl"))
3096 {
3097 /*
3098 * Look for PDF-capable printers; only PDF-capable printers are shown.
3099 */
3100
3101 const char *start, *next; /* Pointer into value */
3102 int have_pdf = 0, /* Have PDF? */
3103 have_raster = 0;/* Have raster format support? */
3104
3105 for (start = value; start && *start; start = next)
3106 {
3107 if (!_cups_strncasecmp(start, "application/pdf", 15) && (!start[15] || start[15] == ','))
3108 {
3109 have_pdf = 1;
3110 break;
3111 }
3112 else if ((!_cups_strncasecmp(start, "image/pwg-raster", 16) && (!start[16] || start[16] == ',')) ||
3113 (!_cups_strncasecmp(start, "image/urf", 9) && (!start[9] || start[9] == ',')))
3114 {
3115 have_raster = 1;
3116 break;
3117 }
3118
3119 if ((next = strchr(start, ',')) != NULL)
3120 next ++;
3121 }
3122
3123 if (!have_pdf && !have_raster)
3124 device->state = _CUPS_DNSSD_INCOMPATIBLE;
3125 }
3126 else if (!_cups_strcasecmp(key, "printer-type"))
3127 {
3128 /*
3129 * Value is either NNNN or 0xXXXX
3130 */
3131
3132 saw_printer_type = 1;
3133 type = (cups_ptype_t)strtol(value, NULL, 0) | CUPS_PRINTER_DISCOVERED;
3134 }
3135 else if (!saw_printer_type)
3136 {
3137 if (!_cups_strcasecmp(key, "air") &&
3138 !_cups_strcasecmp(value, "t"))
3139 type |= CUPS_PRINTER_AUTHENTICATED;
3140 else if (!_cups_strcasecmp(key, "bind") &&
3141 !_cups_strcasecmp(value, "t"))
3142 type |= CUPS_PRINTER_BIND;
3143 else if (!_cups_strcasecmp(key, "collate") &&
3144 !_cups_strcasecmp(value, "t"))
3145 type |= CUPS_PRINTER_COLLATE;
3146 else if (!_cups_strcasecmp(key, "color") &&
3147 !_cups_strcasecmp(value, "t"))
3148 type |= CUPS_PRINTER_COLOR;
3149 else if (!_cups_strcasecmp(key, "copies") &&
3150 !_cups_strcasecmp(value, "t"))
3151 type |= CUPS_PRINTER_COPIES;
3152 else if (!_cups_strcasecmp(key, "duplex") &&
3153 !_cups_strcasecmp(value, "t"))
3154 type |= CUPS_PRINTER_DUPLEX;
3155 else if (!_cups_strcasecmp(key, "fax") &&
3156 !_cups_strcasecmp(value, "t"))
3157 type |= CUPS_PRINTER_MFP;
3158 else if (!_cups_strcasecmp(key, "papercustom") &&
3159 !_cups_strcasecmp(value, "t"))
3160 type |= CUPS_PRINTER_VARIABLE;
3161 else if (!_cups_strcasecmp(key, "papermax"))
3162 {
3163 if (!_cups_strcasecmp(value, "legal-a4"))
3164 type |= CUPS_PRINTER_SMALL;
3165 else if (!_cups_strcasecmp(value, "isoc-a2"))
3166 type |= CUPS_PRINTER_MEDIUM;
3167 else if (!_cups_strcasecmp(value, ">isoc-a2"))
3168 type |= CUPS_PRINTER_LARGE;
3169 }
3170 else if (!_cups_strcasecmp(key, "punch") &&
3171 !_cups_strcasecmp(value, "t"))
3172 type |= CUPS_PRINTER_PUNCH;
3173 else if (!_cups_strcasecmp(key, "scan") &&
3174 !_cups_strcasecmp(value, "t"))
3175 type |= CUPS_PRINTER_MFP;
3176 else if (!_cups_strcasecmp(key, "sort") &&
3177 !_cups_strcasecmp(value, "t"))
3178 type |= CUPS_PRINTER_SORT;
3179 else if (!_cups_strcasecmp(key, "staple") &&
3180 !_cups_strcasecmp(value, "t"))
3181 type |= CUPS_PRINTER_STAPLE;
3182 }
3183 }
3184
3185 /*
3186 * Save the printer-xxx values...
3187 */
3188
3189 if (make_and_model[0])
3190 {
3191 strlcat(make_and_model, " ", sizeof(make_and_model));
3192 strlcat(make_and_model, model, sizeof(make_and_model));
3193
3194 device->dest.num_options = cupsAddOption("printer-make-and-model", make_and_model, device->dest.num_options, &device->dest.options);
3195 }
3196 else
3197 device->dest.num_options = cupsAddOption("printer-make-and-model", model, device->dest.num_options, &device->dest.options);
3198
3199 device->type = type;
3200 snprintf(value, sizeof(value), "%u", type);
3201 device->dest.num_options = cupsAddOption("printer-type", value, device->dest.num_options, &device->dest.options);
3202
3203 /*
3204 * Save the URI...
3205 */
3206
3207 cups_dnssd_unquote(uriname, device->fullName, sizeof(uriname));
3208 httpAssembleURI(HTTP_URI_CODING_ALL, uri, sizeof(uri),
3209 !strcmp(device->regtype, "_ipps._tcp") ? "ipps" : "ipp",
3210 NULL, uriname, 0, saw_printer_type ? "/cups" : "/");
3211
3212 DEBUG_printf(("6cups_dnssd_query: device-uri=\"%s\"", uri));
3213
3214 device->dest.num_options = cupsAddOption("device-uri", uri, device->dest.num_options, &device->dest.options);
3215 }
3216 else
3217 DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
3218 fullName));
3219 }
3220
3221
3222 /*
3223 * 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
3224 */
3225
3226 static const char * /* O - Resolved URI or NULL */
3227 cups_dnssd_resolve(
3228 cups_dest_t *dest, /* I - Destination */
3229 const char *uri, /* I - Current printer URI */
3230 int msec, /* I - Time in milliseconds */
3231 int *cancel, /* I - Pointer to "cancel" variable */
3232 cups_dest_cb_t cb, /* I - Callback */
3233 void *user_data) /* I - User data for callback */
3234 {
3235 char tempuri[1024]; /* Temporary URI buffer */
3236 _cups_dnssd_resolve_t resolve; /* Resolve data */
3237
3238
3239 /*
3240 * Resolve the URI...
3241 */
3242
3243 resolve.cancel = cancel;
3244 gettimeofday(&resolve.end_time, NULL);
3245 if (msec > 0)
3246 {
3247 resolve.end_time.tv_sec += msec / 1000;
3248 resolve.end_time.tv_usec += (msec % 1000) * 1000;
3249
3250 while (resolve.end_time.tv_usec >= 1000000)
3251 {
3252 resolve.end_time.tv_sec ++;
3253 resolve.end_time.tv_usec -= 1000000;
3254 }
3255 }
3256 else
3257 resolve.end_time.tv_sec += 75;
3258
3259 if (cb)
3260 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING, dest);
3261
3262 if ((uri = _httpResolveURI(uri, tempuri, sizeof(tempuri), _HTTP_RESOLVE_DEFAULT, cups_dnssd_resolve_cb, &resolve)) == NULL)
3263 {
3264 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to resolve printer-uri."), 1);
3265
3266 if (cb)
3267 (*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR, dest);
3268
3269 return (NULL);
3270 }
3271
3272 /*
3273 * Save the resolved URI...
3274 */
3275
3276 dest->num_options = cupsAddOption("device-uri", uri, dest->num_options, &dest->options);
3277
3278 return (cupsGetOption("device-uri", dest->num_options, dest->options));
3279 }
3280
3281
3282 /*
3283 * 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
3284 */
3285
3286 static int /* O - 1 to continue, 0 to stop */
3287 cups_dnssd_resolve_cb(void *context) /* I - Resolve data */
3288 {
3289 _cups_dnssd_resolve_t *resolve = (_cups_dnssd_resolve_t *)context;
3290 /* Resolve data */
3291 struct timeval curtime; /* Current time */
3292
3293
3294 /*
3295 * If the cancel variable is set, return immediately.
3296 */
3297
3298 if (resolve->cancel && *(resolve->cancel))
3299 {
3300 DEBUG_puts("4cups_dnssd_resolve_cb: Canceled.");
3301 return (0);
3302 }
3303
3304 /*
3305 * Otherwise check the end time...
3306 */
3307
3308 gettimeofday(&curtime, NULL);
3309
3310 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));
3311
3312 return (curtime.tv_sec < resolve->end_time.tv_sec ||
3313 (curtime.tv_sec == resolve->end_time.tv_sec &&
3314 curtime.tv_usec < resolve->end_time.tv_usec));
3315 }
3316
3317
3318 /*
3319 * 'cups_dnssd_unquote()' - Unquote a name string.
3320 */
3321
3322 static void
3323 cups_dnssd_unquote(char *dst, /* I - Destination buffer */
3324 const char *src, /* I - Source string */
3325 size_t dstsize) /* I - Size of destination buffer */
3326 {
3327 char *dstend = dst + dstsize - 1; /* End of destination buffer */
3328
3329
3330 while (*src && dst < dstend)
3331 {
3332 if (*src == '\\')
3333 {
3334 src ++;
3335 if (isdigit(src[0] & 255) && isdigit(src[1] & 255) &&
3336 isdigit(src[2] & 255))
3337 {
3338 *dst++ = ((((src[0] - '0') * 10) + src[1] - '0') * 10) + src[2] - '0';
3339 src += 3;
3340 }
3341 else
3342 *dst++ = *src++;
3343 }
3344 else
3345 *dst++ = *src ++;
3346 }
3347
3348 *dst = '\0';
3349 }
3350 #endif /* HAVE_DNSSD */
3351
3352
3353 #if defined(HAVE_AVAHI) || defined(HAVE_DNSSD)
3354 /*
3355 * 'cups_elapsed()' - Return the elapsed time in milliseconds.
3356 */
3357
3358 static int /* O - Elapsed time in milliseconds */
3359 cups_elapsed(struct timeval *t) /* IO - Previous time */
3360 {
3361 int msecs; /* Milliseconds */
3362 struct timeval nt; /* New time */
3363
3364
3365 gettimeofday(&nt, NULL);
3366
3367 msecs = (int)(1000 * (nt.tv_sec - t->tv_sec) + (nt.tv_usec - t->tv_usec) / 1000);
3368
3369 *t = nt;
3370
3371 return (msecs);
3372 }
3373 #endif /* HAVE_AVAHI || HAVE_DNSSD */
3374
3375
3376 /*
3377 * 'cups_enum_dests()' - Enumerate destinations from a specific server.
3378 */
3379
3380 static int /* O - 1 on success, 0 on failure */
3381 cups_enum_dests(
3382 http_t *http, /* I - Connection to scheduler */
3383 unsigned flags, /* I - Enumeration flags */
3384 int msec, /* I - Timeout in milliseconds, -1 for indefinite */
3385 int *cancel, /* I - Pointer to "cancel" variable */
3386 cups_ptype_t type, /* I - Printer type bits */
3387 cups_ptype_t mask, /* I - Mask for printer type bits */
3388 cups_dest_cb_t cb, /* I - Callback function */
3389 void *user_data) /* I - User data */
3390 {
3391 int i, j, /* Looping vars */
3392 num_dests; /* Number of destinations */
3393 cups_dest_t *dests = NULL, /* Destinations */
3394 *dest, /* Current destination */
3395 *user_dest; /* User destination */
3396 cups_option_t *option; /* Current option */
3397 char *user_default; /* User default printer */
3398 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3399 int count, /* Number of queries started */
3400 completed, /* Number of completed queries */
3401 remaining; /* Remainder of timeout */
3402 struct timeval curtime; /* Current time */
3403 _cups_dnssd_data_t data; /* Data for callback */
3404 _cups_dnssd_device_t *device; /* Current device */
3405 # ifdef HAVE_DNSSD
3406 int nfds, /* Number of files responded */
3407 main_fd; /* File descriptor for lookups */
3408 DNSServiceRef ipp_ref = NULL; /* IPP browser */
3409 # ifdef HAVE_SSL
3410 DNSServiceRef ipps_ref = NULL; /* IPPS browser */
3411 # endif /* HAVE_SSL */
3412 # ifdef HAVE_POLL
3413 struct pollfd pfd; /* Polling data */
3414 # else
3415 fd_set input; /* Input set for select() */
3416 struct timeval timeout; /* Timeout for select() */
3417 # endif /* HAVE_POLL */
3418 # else /* HAVE_AVAHI */
3419 int error; /* Error value */
3420 AvahiServiceBrowser *ipp_ref = NULL; /* IPP browser */
3421 # ifdef HAVE_SSL
3422 AvahiServiceBrowser *ipps_ref = NULL; /* IPPS browser */
3423 # endif /* HAVE_SSL */
3424 # endif /* HAVE_DNSSD */
3425 #else
3426 _cups_getdata_t data; /* Data for callback */
3427 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3428 const char *home; /* HOME environment variable */
3429 char filename[1024]; /* Local lpoptions file */
3430 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
3431
3432
3433 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));
3434
3435 /*
3436 * Range check input...
3437 */
3438
3439 (void)flags;
3440
3441 if (!cb)
3442 {
3443 DEBUG_puts("1cups_enum_dests: No callback, returning 0.");
3444 return (0);
3445 }
3446
3447 /*
3448 * Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
3449 */
3450
3451 memset(&data, 0, sizeof(data));
3452
3453 if ((user_default = _cupsUserDefault(data.def_name, sizeof(data.def_name))) == NULL)
3454 {
3455 const char *defprinter = cupsGetDefault2(http);
3456 /* Server default, if any */
3457
3458 if (defprinter)
3459 strlcpy(data.def_name, defprinter, sizeof(data.def_name));
3460 }
3461
3462 if (data.def_name[0])
3463 {
3464 /*
3465 * Separate printer and instance name...
3466 */
3467
3468 if ((data.def_instance = strchr(data.def_name, '/')) != NULL)
3469 *data.def_instance++ = '\0';
3470 }
3471
3472 DEBUG_printf(("1cups_enum_dests: def_name=\"%s\", def_instance=\"%s\"", data.def_name, data.def_instance));
3473
3474 snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
3475 data.num_dests = cups_get_dests(filename, NULL, NULL, 1, user_default != NULL, data.num_dests, &data.dests);
3476
3477 if ((home = getenv("HOME")) != NULL)
3478 {
3479 snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", home);
3480
3481 data.num_dests = cups_get_dests(filename, NULL, NULL, 1, user_default != NULL, data.num_dests, &data.dests);
3482 }
3483
3484 /*
3485 * Get ready to enumerate...
3486 */
3487
3488 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3489 data.type = type;
3490 data.mask = mask;
3491 data.cb = cb;
3492 data.user_data = user_data;
3493 data.devices = cupsArrayNew3((cups_array_func_t)cups_dnssd_compare_devices, NULL, NULL, 0, NULL, (cups_afree_func_t)cups_dnssd_free_device);
3494 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3495
3496 if (!(mask & CUPS_PRINTER_DISCOVERED) || !(type & CUPS_PRINTER_DISCOVERED))
3497 {
3498 /*
3499 * Get the list of local printers and pass them to the callback function...
3500 */
3501
3502 num_dests = _cupsGetDests(http, IPP_OP_CUPS_GET_PRINTERS, NULL, &dests, type, mask);
3503
3504 if (data.def_name[0])
3505 {
3506 /*
3507 * Lookup the named default printer and instance and make it the default...
3508 */
3509
3510 if ((dest = cupsGetDest(data.def_name, data.def_instance, num_dests, dests)) != NULL)
3511 {
3512 DEBUG_printf(("1cups_enum_dests: Setting is_default on \"%s/%s\".", dest->name, dest->instance));
3513 dest->is_default = 1;
3514 }
3515 }
3516
3517 for (i = num_dests, dest = dests;
3518 i > 0 && (!cancel || !*cancel);
3519 i --, dest ++)
3520 {
3521 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3522 const char *device_uri; /* Device URI */
3523 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3524
3525 if ((user_dest = cupsGetDest(dest->name, dest->instance, data.num_dests, data.dests)) != NULL)
3526 {
3527 /*
3528 * Apply user defaults to this destination...
3529 */
3530
3531 for (j = user_dest->num_options, option = user_dest->options; j > 0; j --, option ++)
3532 dest->num_options = cupsAddOption(option->name, option->value, dest->num_options, &dest->options);
3533 }
3534
3535 if (!(*cb)(user_data, i > 1 ? CUPS_DEST_FLAGS_MORE : CUPS_DEST_FLAGS_NONE, dest))
3536 break;
3537
3538 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3539 if (!dest->instance && (device_uri = cupsGetOption("device-uri", dest->num_options, dest->options)) != NULL && !strncmp(device_uri, "dnssd://", 8))
3540 {
3541 /*
3542 * Add existing queue using service name, etc. so we don't list it again...
3543 */
3544
3545 char scheme[32], /* URI scheme */
3546 userpass[32], /* Username:password */
3547 serviceName[256], /* Service name (host field) */
3548 resource[256], /* Resource (options) */
3549 *regtype, /* Registration type */
3550 *replyDomain; /* Registration domain */
3551 int port; /* Port number (not used) */
3552
3553 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)
3554 {
3555 if ((regtype = strstr(serviceName, "._ipp")) != NULL)
3556 {
3557 *regtype++ = '\0';
3558
3559 if ((replyDomain = strstr(regtype, "._tcp.")) != NULL)
3560 {
3561 replyDomain[5] = '\0';
3562 replyDomain += 6;
3563
3564 if ((device = cups_dnssd_get_device(&data, serviceName, regtype, replyDomain)) != NULL)
3565 device->state = _CUPS_DNSSD_ACTIVE;
3566 }
3567 }
3568 }
3569 }
3570 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3571 }
3572
3573 cupsFreeDests(num_dests, dests);
3574
3575 if (i > 0 || msec == 0)
3576 goto enum_finished;
3577 }
3578
3579 /*
3580 * Return early if the caller doesn't want to do discovery...
3581 */
3582
3583 if ((mask & CUPS_PRINTER_DISCOVERED) && !(type & CUPS_PRINTER_DISCOVERED))
3584 goto enum_finished;
3585
3586 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3587 /*
3588 * Get Bonjour-shared printers...
3589 */
3590
3591 gettimeofday(&curtime, NULL);
3592
3593 # ifdef HAVE_DNSSD
3594 if (DNSServiceCreateConnection(&data.main_ref) != kDNSServiceErr_NoError)
3595 {
3596 DEBUG_puts("1cups_enum_dests: Unable to create service browser, returning 0.");
3597
3598 cupsFreeDests(data.num_dests, data.dests);
3599
3600 return (0);
3601 }
3602
3603 main_fd = DNSServiceRefSockFD(data.main_ref);
3604
3605 ipp_ref = data.main_ref;
3606 if (DNSServiceBrowse(&ipp_ref, kDNSServiceFlagsShareConnection, 0, "_ipp._tcp", NULL, (DNSServiceBrowseReply)cups_dnssd_browse_cb, &data) != kDNSServiceErr_NoError)
3607 {
3608 DEBUG_puts("1cups_enum_dests: Unable to create IPP browser, returning 0.");
3609 DNSServiceRefDeallocate(data.main_ref);
3610
3611 cupsFreeDests(data.num_dests, data.dests);
3612
3613 return (0);
3614 }
3615
3616 # ifdef HAVE_SSL
3617 ipps_ref = data.main_ref;
3618 if (DNSServiceBrowse(&ipps_ref, kDNSServiceFlagsShareConnection, 0, "_ipps._tcp", NULL, (DNSServiceBrowseReply)cups_dnssd_browse_cb, &data) != kDNSServiceErr_NoError)
3619 {
3620 DEBUG_puts("1cups_enum_dests: Unable to create IPPS browser, returning 0.");
3621 DNSServiceRefDeallocate(data.main_ref);
3622
3623 cupsFreeDests(data.num_dests, data.dests);
3624
3625 return (0);
3626 }
3627 # endif /* HAVE_SSL */
3628
3629 # else /* HAVE_AVAHI */
3630 if ((data.simple_poll = avahi_simple_poll_new()) == NULL)
3631 {
3632 DEBUG_puts("1cups_enum_dests: Unable to create Avahi poll, returning 0.");
3633
3634 cupsFreeDests(data.num_dests, data.dests);
3635
3636 return (0);
3637 }
3638
3639 avahi_simple_poll_set_func(data.simple_poll, cups_dnssd_poll_cb, &data);
3640
3641 data.client = avahi_client_new(avahi_simple_poll_get(data.simple_poll),
3642 0, cups_dnssd_client_cb, &data,
3643 &error);
3644 if (!data.client)
3645 {
3646 DEBUG_puts("1cups_enum_dests: Unable to create Avahi client, returning 0.");
3647 avahi_simple_poll_free(data.simple_poll);
3648
3649 cupsFreeDests(data.num_dests, data.dests);
3650
3651 return (0);
3652 }
3653
3654 data.browsers = 1;
3655 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)
3656 {
3657 DEBUG_puts("1cups_enum_dests: Unable to create Avahi IPP browser, returning 0.");
3658
3659 avahi_client_free(data.client);
3660 avahi_simple_poll_free(data.simple_poll);
3661
3662 cupsFreeDests(data.num_dests, data.dests);
3663
3664 return (0);
3665 }
3666
3667 # ifdef HAVE_SSL
3668 data.browsers ++;
3669 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)
3670 {
3671 DEBUG_puts("1cups_enum_dests: Unable to create Avahi IPPS browser, returning 0.");
3672
3673 avahi_service_browser_free(ipp_ref);
3674 avahi_client_free(data.client);
3675 avahi_simple_poll_free(data.simple_poll);
3676
3677 cupsFreeDests(data.num_dests, data.dests);
3678
3679 return (0);
3680 }
3681 # endif /* HAVE_SSL */
3682 # endif /* HAVE_DNSSD */
3683
3684 if (msec < 0)
3685 remaining = INT_MAX;
3686 else
3687 remaining = msec;
3688
3689 while (remaining > 0 && (!cancel || !*cancel))
3690 {
3691 /*
3692 * Check for input...
3693 */
3694
3695 DEBUG_printf(("1cups_enum_dests: remaining=%d", remaining));
3696
3697 cups_elapsed(&curtime);
3698
3699 # ifdef HAVE_DNSSD
3700 # ifdef HAVE_POLL
3701 pfd.fd = main_fd;
3702 pfd.events = POLLIN;
3703
3704 nfds = poll(&pfd, 1, remaining > _CUPS_DNSSD_MAXTIME ? _CUPS_DNSSD_MAXTIME : remaining);
3705
3706 # else
3707 FD_ZERO(&input);
3708 FD_SET(main_fd, &input);
3709
3710 timeout.tv_sec = 0;
3711 timeout.tv_usec = 1000 * (remaining > _CUPS_DNSSD_MAXTIME ? _CUPS_DNSSD_MAXTIME : remaining);
3712
3713 nfds = select(main_fd + 1, &input, NULL, NULL, &timeout);
3714 # endif /* HAVE_POLL */
3715
3716 if (nfds > 0)
3717 DNSServiceProcessResult(data.main_ref);
3718 else if (nfds < 0 && errno != EINTR && errno != EAGAIN)
3719 break;
3720
3721 # else /* HAVE_AVAHI */
3722 data.got_data = 0;
3723
3724 if ((error = avahi_simple_poll_iterate(data.simple_poll, _CUPS_DNSSD_MAXTIME)) > 0)
3725 {
3726 /*
3727 * We've been told to exit the loop. Perhaps the connection to
3728 * Avahi failed.
3729 */
3730
3731 break;
3732 }
3733
3734 DEBUG_printf(("1cups_enum_dests: got_data=%d", data.got_data));
3735 # endif /* HAVE_DNSSD */
3736
3737 remaining -= cups_elapsed(&curtime);
3738
3739 for (device = (_cups_dnssd_device_t *)cupsArrayFirst(data.devices),
3740 count = 0, completed = 0;
3741 device;
3742 device = (_cups_dnssd_device_t *)cupsArrayNext(data.devices))
3743 {
3744 if (device->ref)
3745 count ++;
3746
3747 if (device->state == _CUPS_DNSSD_ACTIVE)
3748 completed ++;
3749
3750 if (!device->ref && device->state == _CUPS_DNSSD_NEW)
3751 {
3752 DEBUG_printf(("1cups_enum_dests: Querying '%s'.", device->fullName));
3753
3754 # ifdef HAVE_DNSSD
3755 device->ref = data.main_ref;
3756
3757 if (DNSServiceQueryRecord(&(device->ref), kDNSServiceFlagsShareConnection, 0, device->fullName, kDNSServiceType_TXT, kDNSServiceClass_IN, (DNSServiceQueryRecordReply)cups_dnssd_query_cb, &data) == kDNSServiceErr_NoError)
3758 {
3759 count ++;
3760 }
3761 else
3762 {
3763 device->ref = 0;
3764 device->state = _CUPS_DNSSD_ERROR;
3765
3766 DEBUG_puts("1cups_enum_dests: Query failed.");
3767 }
3768
3769 # else /* HAVE_AVAHI */
3770 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)
3771 {
3772 DEBUG_printf(("1cups_enum_dests: Query ref=%p", device->ref));
3773 count ++;
3774 }
3775 else
3776 {
3777 device->state = _CUPS_DNSSD_ERROR;
3778
3779 DEBUG_printf(("1cups_enum_dests: Query failed: %s", avahi_strerror(avahi_client_errno(data.client))));
3780 }
3781 # endif /* HAVE_DNSSD */
3782 }
3783 else if (device->ref && device->state == _CUPS_DNSSD_PENDING)
3784 {
3785 completed ++;
3786
3787 DEBUG_printf(("1cups_enum_dests: Query for \"%s\" is complete.", device->fullName));
3788
3789 if ((device->type & mask) == type)
3790 {
3791 dest = &device->dest;
3792
3793 if ((user_dest = cupsGetDest(dest->name, dest->instance, data.num_dests, data.dests)) != NULL)
3794 {
3795 /*
3796 * Apply user defaults to this destination...
3797 */
3798
3799 for (j = user_dest->num_options, option = user_dest->options; j > 0; j --, option ++)
3800 dest->num_options = cupsAddOption(option->name, option->value, dest->num_options, &dest->options);
3801 }
3802
3803 if (!strcasecmp(dest->name, data.def_name) && !data.def_instance)
3804 {
3805 DEBUG_printf(("1cups_enum_dests: Setting is_default on discovered \"%s\".", dest->name));
3806 dest->is_default = 1;
3807 }
3808
3809 DEBUG_printf(("1cups_enum_dests: Add callback for \"%s\".", device->dest.name));
3810 if (!(*cb)(user_data, CUPS_DEST_FLAGS_NONE, dest))
3811 {
3812 remaining = -1;
3813 break;
3814 }
3815 }
3816
3817 device->state = _CUPS_DNSSD_ACTIVE;
3818 }
3819 }
3820
3821 # ifdef HAVE_AVAHI
3822 DEBUG_printf(("1cups_enum_dests: remaining=%d, browsers=%d, completed=%d, count=%d, devices count=%d", remaining, data.browsers, completed, count, cupsArrayCount(data.devices)));
3823
3824 if (data.browsers == 0 && completed == cupsArrayCount(data.devices))
3825 break;
3826 # else
3827 DEBUG_printf(("1cups_enum_dests: remaining=%d, completed=%d, count=%d, devices count=%d", remaining, completed, count, cupsArrayCount(data.devices)));
3828
3829 if (completed == cupsArrayCount(data.devices))
3830 break;
3831 # endif /* HAVE_AVAHI */
3832 }
3833 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3834
3835 /*
3836 * Return...
3837 */
3838
3839 enum_finished:
3840
3841 cupsFreeDests(data.num_dests, data.dests);
3842
3843 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
3844 cupsArrayDelete(data.devices);
3845
3846 # ifdef HAVE_DNSSD
3847 if (ipp_ref)
3848 DNSServiceRefDeallocate(ipp_ref);
3849
3850 # ifdef HAVE_SSL
3851 if (ipps_ref)
3852 DNSServiceRefDeallocate(ipps_ref);
3853 # endif /* HAVE_SSL */
3854
3855 if (data.main_ref)
3856 DNSServiceRefDeallocate(data.main_ref);
3857
3858 # else /* HAVE_AVAHI */
3859 if (ipp_ref)
3860 avahi_service_browser_free(ipp_ref);
3861 # ifdef HAVE_SSL
3862 if (ipps_ref)
3863 avahi_service_browser_free(ipps_ref);
3864 # endif /* HAVE_SSL */
3865
3866 if (data.client)
3867 avahi_client_free(data.client);
3868 if (data.simple_poll)
3869 avahi_simple_poll_free(data.simple_poll);
3870 # endif /* HAVE_DNSSD */
3871 #endif /* HAVE_DNSSD || HAVE_AVAHI */
3872
3873 DEBUG_puts("1cups_enum_dests: Returning 1.");
3874
3875 return (1);
3876 }
3877
3878
3879 /*
3880 * 'cups_find_dest()' - Find a destination using a binary search.
3881 */
3882
3883 static int /* O - Index of match */
3884 cups_find_dest(const char *name, /* I - Destination name */
3885 const char *instance, /* I - Instance or NULL */
3886 int num_dests, /* I - Number of destinations */
3887 cups_dest_t *dests, /* I - Destinations */
3888 int prev, /* I - Previous index */
3889 int *rdiff) /* O - Difference of match */
3890 {
3891 int left, /* Low mark for binary search */
3892 right, /* High mark for binary search */
3893 current, /* Current index */
3894 diff; /* Result of comparison */
3895 cups_dest_t key; /* Search key */
3896
3897
3898 key.name = (char *)name;
3899 key.instance = (char *)instance;
3900
3901 if (prev >= 0)
3902 {
3903 /*
3904 * Start search on either side of previous...
3905 */
3906
3907 if ((diff = cups_compare_dests(&key, dests + prev)) == 0 ||
3908 (diff < 0 && prev == 0) ||
3909 (diff > 0 && prev == (num_dests - 1)))
3910 {
3911 *rdiff = diff;
3912 return (prev);
3913 }
3914 else if (diff < 0)
3915 {
3916 /*
3917 * Start with previous on right side...
3918 */
3919
3920 left = 0;
3921 right = prev;
3922 }
3923 else
3924 {
3925 /*
3926 * Start wih previous on left side...
3927 */
3928
3929 left = prev;
3930 right = num_dests - 1;
3931 }
3932 }
3933 else
3934 {
3935 /*
3936 * Start search in the middle...
3937 */
3938
3939 left = 0;
3940 right = num_dests - 1;
3941 }
3942
3943 do
3944 {
3945 current = (left + right) / 2;
3946 diff = cups_compare_dests(&key, dests + current);
3947
3948 if (diff == 0)
3949 break;
3950 else if (diff < 0)
3951 right = current;
3952 else
3953 left = current;
3954 }
3955 while ((right - left) > 1);
3956
3957 if (diff != 0)
3958 {
3959 /*
3960 * Check the last 1 or 2 elements...
3961 */
3962
3963 if ((diff = cups_compare_dests(&key, dests + left)) <= 0)
3964 current = left;
3965 else
3966 {
3967 diff = cups_compare_dests(&key, dests + right);
3968 current = right;
3969 }
3970 }
3971
3972 /*
3973 * Return the closest destination and the difference...
3974 */
3975
3976 *rdiff = diff;
3977
3978 return (current);
3979 }
3980
3981
3982 /*
3983 * 'cups_get_cb()' - Collect enumerated destinations.
3984 */
3985
3986 static int /* O - 1 to continue, 0 to stop */
3987 cups_get_cb(_cups_getdata_t *data, /* I - Data from cupsGetDests */
3988 unsigned flags, /* I - Enumeration flags */
3989 cups_dest_t *dest) /* I - Destination */
3990 {
3991 if (flags & CUPS_DEST_FLAGS_REMOVED)
3992 {
3993 /*
3994 * Remove destination from array...
3995 */
3996
3997 data->num_dests = cupsRemoveDest(dest->name, dest->instance, data->num_dests, &data->dests);
3998 }
3999 else
4000 {
4001 /*
4002 * Add destination to array...
4003 */
4004
4005 data->num_dests = cupsCopyDest(dest, data->num_dests, &data->dests);
4006 }
4007
4008 return (1);
4009 }
4010
4011
4012 /*
4013 * 'cups_get_default()' - Get the default destination from an lpoptions file.
4014 */
4015
4016 static char * /* O - Default destination or NULL */
4017 cups_get_default(const char *filename, /* I - File to read */
4018 char *namebuf, /* I - Name buffer */
4019 size_t namesize, /* I - Size of name buffer */
4020 const char **instance) /* I - Instance */
4021 {
4022 cups_file_t *fp; /* lpoptions file */
4023 char line[8192], /* Line from file */
4024 *value, /* Value for line */
4025 *nameptr; /* Pointer into name */
4026 int linenum; /* Current line */
4027
4028
4029 *namebuf = '\0';
4030
4031 if ((fp = cupsFileOpen(filename, "r")) != NULL)
4032 {
4033 linenum = 0;
4034
4035 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
4036 {
4037 if (!_cups_strcasecmp(line, "default") && value)
4038 {
4039 strlcpy(namebuf, value, namesize);
4040
4041 if ((nameptr = strchr(namebuf, ' ')) != NULL)
4042 *nameptr = '\0';
4043 if ((nameptr = strchr(namebuf, '\t')) != NULL)
4044 *nameptr = '\0';
4045
4046 if ((nameptr = strchr(namebuf, '/')) != NULL)
4047 *nameptr++ = '\0';
4048
4049 *instance = nameptr;
4050 break;
4051 }
4052 }
4053
4054 cupsFileClose(fp);
4055 }
4056
4057 return (*namebuf ? namebuf : NULL);
4058 }
4059
4060
4061 /*
4062 * 'cups_get_dests()' - Get destinations from a file.
4063 */
4064
4065 static int /* O - Number of destinations */
4066 cups_get_dests(
4067 const char *filename, /* I - File to read from */
4068 const char *match_name, /* I - Destination name we want */
4069 const char *match_inst, /* I - Instance name we want */
4070 int load_all, /* I - Load all saved destinations? */
4071 int user_default_set, /* I - User default printer set? */
4072 int num_dests, /* I - Number of destinations */
4073 cups_dest_t **dests) /* IO - Destinations */
4074 {
4075 int i; /* Looping var */
4076 cups_dest_t *dest; /* Current destination */
4077 cups_file_t *fp; /* File pointer */
4078 char line[8192], /* Line from file */
4079 *lineptr, /* Pointer into line */
4080 *name, /* Name of destination/option */
4081 *instance; /* Instance of destination */
4082 int linenum; /* Current line number */
4083
4084
4085 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));
4086
4087 /*
4088 * Try to open the file...
4089 */
4090
4091 if ((fp = cupsFileOpen(filename, "r")) == NULL)
4092 return (num_dests);
4093
4094 /*
4095 * Read each printer; each line looks like:
4096 *
4097 * Dest name[/instance] options
4098 * Default name[/instance] options
4099 */
4100
4101 linenum = 0;
4102
4103 while (cupsFileGetConf(fp, line, sizeof(line), &lineptr, &linenum))
4104 {
4105 /*
4106 * See what type of line it is...
4107 */
4108
4109 DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
4110 linenum, line, lineptr));
4111
4112 if ((_cups_strcasecmp(line, "dest") && _cups_strcasecmp(line, "default")) || !lineptr)
4113 {
4114 DEBUG_puts("9cups_get_dests: Not a dest or default line...");
4115 continue;
4116 }
4117
4118 name = lineptr;
4119
4120 /*
4121 * Search for an instance...
4122 */
4123
4124 while (!isspace(*lineptr & 255) && *lineptr && *lineptr != '/')
4125 lineptr ++;
4126
4127 if (*lineptr == '/')
4128 {
4129 /*
4130 * Found an instance...
4131 */
4132
4133 *lineptr++ = '\0';
4134 instance = lineptr;
4135
4136 /*
4137 * Search for an instance...
4138 */
4139
4140 while (!isspace(*lineptr & 255) && *lineptr)
4141 lineptr ++;
4142 }
4143 else
4144 instance = NULL;
4145
4146 if (*lineptr)
4147 *lineptr++ = '\0';
4148
4149 DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name,
4150 instance));
4151
4152 /*
4153 * Match and/or ignore missing destinations...
4154 */
4155
4156 if (match_name)
4157 {
4158 if (_cups_strcasecmp(name, match_name) ||
4159 (!instance && match_inst) ||
4160 (instance && !match_inst) ||
4161 (instance && _cups_strcasecmp(instance, match_inst)))
4162 continue;
4163
4164 dest = *dests;
4165 }
4166 else if (!load_all && cupsGetDest(name, NULL, num_dests, *dests) == NULL)
4167 {
4168 DEBUG_puts("9cups_get_dests: Not found!");
4169 continue;
4170 }
4171 else
4172 {
4173 /*
4174 * Add the destination...
4175 */
4176
4177 num_dests = cupsAddDest(name, instance, num_dests, dests);
4178
4179 if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
4180 {
4181 /*
4182 * Out of memory!
4183 */
4184
4185 DEBUG_puts("9cups_get_dests: Out of memory!");
4186 break;
4187 }
4188 }
4189
4190 /*
4191 * Add options until we hit the end of the line...
4192 */
4193
4194 dest->num_options = cupsParseOptions(lineptr, dest->num_options, &(dest->options));
4195
4196 /*
4197 * If we found what we were looking for, stop now...
4198 */
4199
4200 if (match_name)
4201 break;
4202
4203 /*
4204 * Set this as default if needed...
4205 */
4206
4207 if (!user_default_set && !_cups_strcasecmp(line, "default"))
4208 {
4209 DEBUG_puts("9cups_get_dests: Setting as default...");
4210
4211 for (i = 0; i < num_dests; i ++)
4212 (*dests)[i].is_default = 0;
4213
4214 dest->is_default = 1;
4215 }
4216 }
4217
4218 /*
4219 * Close the file and return...
4220 */
4221
4222 cupsFileClose(fp);
4223
4224 return (num_dests);
4225 }
4226
4227
4228 /*
4229 * 'cups_make_string()' - Make a comma-separated string of values from an IPP
4230 * attribute.
4231 */
4232
4233 static char * /* O - New string */
4234 cups_make_string(
4235 ipp_attribute_t *attr, /* I - Attribute to convert */
4236 char *buffer, /* I - Buffer */
4237 size_t bufsize) /* I - Size of buffer */
4238 {
4239 int i; /* Looping var */
4240 char *ptr, /* Pointer into buffer */
4241 *end, /* Pointer to end of buffer */
4242 *valptr; /* Pointer into string attribute */
4243
4244
4245 /*
4246 * Return quickly if we have a single string value...
4247 */
4248
4249 if (attr->num_values == 1 &&
4250 attr->value_tag != IPP_TAG_INTEGER &&
4251 attr->value_tag != IPP_TAG_ENUM &&
4252 attr->value_tag != IPP_TAG_BOOLEAN &&
4253 attr->value_tag != IPP_TAG_RANGE)
4254 return (attr->values[0].string.text);
4255
4256 /*
4257 * Copy the values to the string, separating with commas and escaping strings
4258 * as needed...
4259 */
4260
4261 end = buffer + bufsize - 1;
4262
4263 for (i = 0, ptr = buffer; i < attr->num_values && ptr < end; i ++)
4264 {
4265 if (i)
4266 *ptr++ = ',';
4267
4268 switch (attr->value_tag)
4269 {
4270 case IPP_TAG_INTEGER :
4271 case IPP_TAG_ENUM :
4272 snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].integer);
4273 break;
4274
4275 case IPP_TAG_BOOLEAN :
4276 if (attr->values[i].boolean)
4277 strlcpy(ptr, "true", (size_t)(end - ptr + 1));
4278 else
4279 strlcpy(ptr, "false", (size_t)(end - ptr + 1));
4280 break;
4281
4282 case IPP_TAG_RANGE :
4283 if (attr->values[i].range.lower == attr->values[i].range.upper)
4284 snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].range.lower);
4285 else
4286 snprintf(ptr, (size_t)(end - ptr + 1), "%d-%d", attr->values[i].range.lower, attr->values[i].range.upper);
4287 break;
4288
4289 default :
4290 for (valptr = attr->values[i].string.text;
4291 *valptr && ptr < end;)
4292 {
4293 if (strchr(" \t\n\\\'\"", *valptr))
4294 {
4295 if (ptr >= (end - 1))
4296 break;
4297
4298 *ptr++ = '\\';
4299 }
4300
4301 *ptr++ = *valptr++;
4302 }
4303
4304 *ptr = '\0';
4305 break;
4306 }
4307
4308 ptr += strlen(ptr);
4309 }
4310
4311 *ptr = '\0';
4312
4313 return (buffer);
4314 }
4315
4316
4317 /*
4318 * 'cups_name_cb()' - Find an enumerated destination.
4319 */
4320
4321 static int /* O - 1 to continue, 0 to stop */
4322 cups_name_cb(_cups_namedata_t *data, /* I - Data from cupsGetNamedDest */
4323 unsigned flags, /* I - Enumeration flags */
4324 cups_dest_t *dest) /* I - Destination */
4325 {
4326 DEBUG_printf(("2cups_name_cb(data=%p(%s), flags=%x, dest=%p(%s)", (void *)data, data->name, flags, (void *)dest, dest->name));
4327
4328 if (!(flags & CUPS_DEST_FLAGS_REMOVED) && !dest->instance && !strcasecmp(data->name, dest->name))
4329 {
4330 /*
4331 * Copy destination and stop enumeration...
4332 */
4333
4334 cupsCopyDest(dest, 0, &data->dest);
4335 return (0);
4336 }
4337
4338 return (1);
4339 }
4340
4341
4342 /*
4343 * 'cups_queue_name()' - Create a local queue name based on the service name.
4344 */
4345
4346 static void
4347 cups_queue_name(
4348 char *name, /* I - Name buffer */
4349 const char *serviceName, /* I - Service name */
4350 size_t namesize) /* I - Size of name buffer */
4351 {
4352 const char *ptr; /* Pointer into serviceName */
4353 char *nameptr; /* Pointer into name */
4354
4355
4356 for (nameptr = name, ptr = serviceName; *ptr && nameptr < (name + namesize - 1); ptr ++)
4357 {
4358 /*
4359 * Sanitize the printer name...
4360 */
4361
4362 if (_cups_isalnum(*ptr))
4363 *nameptr++ = *ptr;
4364 else if (nameptr == name || nameptr[-1] != '_')
4365 *nameptr++ = '_';
4366 }
4367
4368 *nameptr = '\0';
4369 }