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