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