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