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