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