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