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