]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/dirsvc.c
Merge changes from CUPS 1.5svn-r9313.
[thirdparty/cups.git] / scheduler / dirsvc.c
1 /*
2 * "$Id: dirsvc.c 7933 2008-09-11 00:44:58Z mike $"
3 *
4 * Directory services routines for the Common UNIX Printing System (CUPS).
5 *
6 * Copyright 2007-2010 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
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 * Contents:
16 *
17 * cupsdDeregisterPrinter() - Stop sending broadcast information for a local
18 * printer and remove any pending references to
19 * remote printers.
20 * cupsdLoadRemoteCache() - Load the remote printer cache.
21 * cupsdRegisterPrinter() - Start sending broadcast information for a
22 * printer or update the broadcast contents.
23 * cupsdRestartPolling() - Restart polling servers as needed.
24 * cupsdSaveRemoteCache() - Save the remote printer cache.
25 * cupsdSendBrowseList() - Send new browsing information as necessary.
26 * ldap_rebind_proc() - Callback function for LDAP rebind
27 * ldap_connect() - Start new LDAP connection
28 * ldap_reconnect() - Reconnect to LDAP Server
29 * ldap_disconnect() - Disconnect from LDAP Server
30 * cupsdStartBrowsing() - Start sending and receiving broadcast
31 * information.
32 * cupsdStartPolling() - Start polling servers as needed.
33 * cupsdStopBrowsing() - Stop sending and receiving broadcast
34 * information.
35 * cupsdStopPolling() - Stop polling servers as needed.
36 * cupsdUpdateDNSSDName() - Update the computer name we use for
37 * browsing...
38 * cupsdUpdateLDAPBrowse() - Scan for new printers via LDAP...
39 * cupsdUpdateSLPBrowse() - Get browsing information via SLP.
40 * dequote() - Remote quotes from a string.
41 * dnssdAddAlias() - Add a DNS-SD alias name.
42 * dnssdBuildTxtRecord() - Build a TXT record from printer info.
43 * dnssdComparePrinters() - Compare the registered names of two printers.
44 * dnssdDeregisterPrinter() - Stop sending broadcast information for a
45 * printer.
46 * dnssdPackTxtRecord() - Pack an array of key/value pairs into the TXT
47 * record format.
48 * dnssdRegisterCallback() - DNSServiceRegister callback.
49 * dnssdRegisterPrinter() - Start sending broadcast information for a
50 * printer or update the broadcast contents.
51 * dnssdStop() - Stop all DNS-SD registrations.
52 * dnssdUpdate() - Handle DNS-SD queries.
53 * get_auth_info_required() - Get the auth-info-required value to advertise.
54 * get_hostconfig() - Get an /etc/hostconfig service setting.
55 * is_local_queue() - Determine whether the URI points at a local
56 * queue.
57 * process_browse_data() - Process new browse data.
58 * process_implicit_classes() - Create/update implicit classes as needed.
59 * send_cups_browse() - Send new browsing information using the CUPS
60 * protocol.
61 * ldap_search_rec() - LDAP Search with reconnect
62 * ldap_freeres() - Free LDAPMessage
63 * ldap_getval_char() - Get first LDAP value and convert to string
64 * send_ldap_ou() - Send LDAP ou registrations.
65 * send_ldap_browse() - Send LDAP printer registrations.
66 * ldap_dereg_printer() - Delete printer from directory
67 * ldap_dereg_ou() - Remove the organizational unit.
68 * send_slp_browse() - Register the specified printer with SLP.
69 * slp_attr_callback() - SLP attribute callback
70 * slp_dereg_printer() - SLPDereg() the specified printer
71 * slp_get_attr() - Get an attribute from an SLP registration.
72 * slp_reg_callback() - Empty SLPRegReport.
73 * slp_url_callback() - SLP service url callback
74 * update_cups_browse() - Update the browse lists using the CUPS
75 * protocol.
76 * update_lpd() - Update the LPD configuration as needed.
77 * update_polling() - Read status messages from the poll daemons.
78 * update_smb() - Update the SMB configuration as needed.
79 */
80
81 /*
82 * Include necessary headers...
83 */
84
85 #include "cupsd.h"
86 #include <grp.h>
87
88 #ifdef HAVE_DNSSD
89 # include <dns_sd.h>
90 # ifdef __APPLE__
91 # include <nameser.h>
92 # ifdef HAVE_COREFOUNDATION
93 # include <CoreFoundation/CoreFoundation.h>
94 # endif /* HAVE_COREFOUNDATION */
95 # ifdef HAVE_SYSTEMCONFIGURATION
96 # include <SystemConfiguration/SystemConfiguration.h>
97 # endif /* HAVE_SYSTEMCONFIGURATION */
98 # endif /* __APPLE__ */
99 #endif /* HAVE_DNSSD */
100
101
102 /*
103 * Local functions...
104 */
105
106 static char *dequote(char *d, const char *s, int dlen);
107 static char *get_auth_info_required(cupsd_printer_t *p, char *buffer,
108 size_t bufsize);
109 #ifdef __APPLE__
110 static int get_hostconfig(const char *name);
111 #endif /* __APPLE__ */
112 static int is_local_queue(const char *uri, char *host, int hostlen,
113 char *resource, int resourcelen);
114 static void process_browse_data(const char *uri, const char *host,
115 const char *resource, cups_ptype_t type,
116 ipp_pstate_t state, const char *location,
117 const char *info, const char *make_model,
118 int num_attrs, cups_option_t *attrs);
119 static void process_implicit_classes(void);
120 static void send_cups_browse(cupsd_printer_t *p);
121 #ifdef HAVE_LDAP
122 static LDAP *ldap_connect(void);
123 static LDAP *ldap_reconnect(void);
124 static void ldap_disconnect(LDAP *ld);
125 static int ldap_search_rec(LDAP *ld, char *base, int scope,
126 char *filter, char *attrs[],
127 int attrsonly, LDAPMessage **res);
128 static int ldap_getval_firststring(LDAP *ld, LDAPMessage *entry,
129 char *attr, char *retval,
130 unsigned long maxsize);
131 static void ldap_freeres(LDAPMessage *entry);
132 static void send_ldap_ou(char *ou, char *basedn, char *descstring);
133 static void send_ldap_browse(cupsd_printer_t *p);
134 static void ldap_dereg_printer(cupsd_printer_t *p);
135 static void ldap_dereg_ou(char *ou, char *basedn);
136 # ifdef HAVE_LDAP_REBIND_PROC
137 # if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
138 static int ldap_rebind_proc(LDAP *RebindLDAPHandle,
139 LDAP_CONST char *refsp,
140 ber_tag_t request,
141 ber_int_t msgid,
142 void *params);
143 # else
144 static int ldap_rebind_proc(LDAP *RebindLDAPHandle,
145 char **dnp,
146 char **passwdp,
147 int *authmethodp,
148 int freeit,
149 void *arg);
150 # endif /* defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000) */
151 # endif /* HAVE_LDAP_REBIND_PROC */
152 #endif /* HAVE_LDAP */
153 #ifdef HAVE_LIBSLP
154 static void send_slp_browse(cupsd_printer_t *p);
155 #endif /* HAVE_LIBSLP */
156 static void update_cups_browse(void);
157 static void update_lpd(int onoff);
158 static void update_polling(void);
159 static void update_smb(int onoff);
160
161
162 #ifdef HAVE_DNSSD
163 # ifdef HAVE_COREFOUNDATION
164 static void dnssdAddAlias(const void *key, const void *value,
165 void *context);
166 # endif /* HAVE_COREFOUNDATION */
167 static char *dnssdBuildTxtRecord(int *txt_len, cupsd_printer_t *p,
168 int for_lpd);
169 static int dnssdComparePrinters(cupsd_printer_t *a, cupsd_printer_t *b);
170 static void dnssdDeregisterPrinter(cupsd_printer_t *p);
171 static char *dnssdPackTxtRecord(int *txt_len, char *keyvalue[][2],
172 int count);
173 static void dnssdRegisterCallback(DNSServiceRef sdRef,
174 DNSServiceFlags flags,
175 DNSServiceErrorType errorCode,
176 const char *name, const char *regtype,
177 const char *domain, void *context);
178 static void dnssdRegisterPrinter(cupsd_printer_t *p);
179 static void dnssdStop(void);
180 static void dnssdUpdate(void);
181 #endif /* HAVE_DNSSD */
182
183 #ifdef HAVE_LDAP
184 static const char * const ldap_attrs[] =/* CUPS LDAP attributes */
185 {
186 "printerDescription",
187 "printerLocation",
188 "printerMakeAndModel",
189 "printerType",
190 "printerURI",
191 NULL
192 };
193 #endif /* HAVE_LDAP */
194
195 #ifdef HAVE_LIBSLP
196 /*
197 * SLP definitions...
198 */
199
200 /*
201 * SLP service name for CUPS...
202 */
203
204 # define SLP_CUPS_SRVTYPE "service:printer"
205 # define SLP_CUPS_SRVLEN 15
206
207
208 /*
209 * Printer service URL structure
210 */
211
212 typedef struct _slpsrvurl_s /**** SLP URL list ****/
213 {
214 struct _slpsrvurl_s *next; /* Next URL in list */
215 char url[HTTP_MAX_URI];
216 /* URL */
217 } slpsrvurl_t;
218
219
220 /*
221 * Local functions...
222 */
223
224 static SLPBoolean slp_attr_callback(SLPHandle hslp, const char *attrlist,
225 SLPError errcode, void *cookie);
226 static void slp_dereg_printer(cupsd_printer_t *p);
227 static int slp_get_attr(const char *attrlist, const char *tag,
228 char **valbuf);
229 static void slp_reg_callback(SLPHandle hslp, SLPError errcode,
230 void *cookie);
231 static SLPBoolean slp_url_callback(SLPHandle hslp, const char *srvurl,
232 unsigned short lifetime,
233 SLPError errcode, void *cookie);
234 #endif /* HAVE_LIBSLP */
235
236
237 /*
238 * 'cupsdDeregisterPrinter()' - Stop sending broadcast information for a
239 * local printer and remove any pending
240 * references to remote printers.
241 */
242
243 void
244 cupsdDeregisterPrinter(
245 cupsd_printer_t *p, /* I - Printer to register */
246 int removeit) /* I - Printer being permanently removed */
247 {
248 /*
249 * Only deregister if browsing is enabled and it's a local printer...
250 */
251
252 cupsdLogMessage(CUPSD_LOG_DEBUG,
253 "cupsdDeregisterPrinter(p=%p(%s), removeit=%d)", p, p->name,
254 removeit);
255
256 if (!Browsing || !p->shared ||
257 (p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
258 CUPS_PRINTER_SCANNER)))
259 return;
260
261 /*
262 * Announce the deletion...
263 */
264
265 if ((BrowseLocalProtocols & BROWSE_CUPS) && BrowseSocket >= 0)
266 {
267 cups_ptype_t savedtype = p->type; /* Saved printer type */
268
269 p->type |= CUPS_PRINTER_DELETE;
270
271 send_cups_browse(p);
272
273 p->type = savedtype;
274 }
275
276 #ifdef HAVE_LIBSLP
277 if (BrowseLocalProtocols & BROWSE_SLP)
278 slp_dereg_printer(p);
279 #endif /* HAVE_LIBSLP */
280
281 #ifdef HAVE_LDAP
282 if (BrowseLocalProtocols & BROWSE_LDAP)
283 ldap_dereg_printer(p);
284 #endif /* HAVE_LDAP */
285
286 #ifdef HAVE_DNSSD
287 if (removeit && (BrowseLocalProtocols & BROWSE_DNSSD) && DNSSDRef)
288 dnssdDeregisterPrinter(p);
289 #endif /* HAVE_DNSSD */
290 }
291
292
293 /*
294 * 'cupsdLoadRemoteCache()' - Load the remote printer cache.
295 */
296
297 void
298 cupsdLoadRemoteCache(void)
299 {
300 int i; /* Looping var */
301 cups_file_t *fp; /* remote.cache file */
302 int linenum; /* Current line number */
303 char line[4096], /* Line from file */
304 *value, /* Pointer to value */
305 *valueptr, /* Pointer into value */
306 scheme[32], /* Scheme portion of URI */
307 username[64], /* Username portion of URI */
308 host[HTTP_MAX_HOST],
309 /* Hostname portion of URI */
310 resource[HTTP_MAX_URI];
311 /* Resource portion of URI */
312 int port; /* Port number */
313 cupsd_printer_t *p; /* Current printer */
314 time_t now; /* Current time */
315
316
317 /*
318 * Don't load the cache if the remote protocols are disabled...
319 */
320
321 if (!Browsing)
322 {
323 cupsdLogMessage(CUPSD_LOG_DEBUG,
324 "cupsdLoadRemoteCache: Not loading remote cache.");
325 return;
326 }
327
328 /*
329 * Open the remote.cache file...
330 */
331
332 snprintf(line, sizeof(line), "%s/remote.cache", CacheDir);
333 if ((fp = cupsFileOpen(line, "r")) == NULL)
334 return;
335
336 /*
337 * Read printer configurations until we hit EOF...
338 */
339
340 linenum = 0;
341 p = NULL;
342 now = time(NULL);
343
344 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
345 {
346 /*
347 * Decode the directive...
348 */
349
350 if (!strcasecmp(line, "<Printer") ||
351 !strcasecmp(line, "<DefaultPrinter"))
352 {
353 /*
354 * <Printer name> or <DefaultPrinter name>
355 */
356
357 if (p == NULL && value)
358 {
359 /*
360 * Add the printer and a base file type...
361 */
362
363 cupsdLogMessage(CUPSD_LOG_DEBUG,
364 "cupsdLoadRemoteCache: Loading printer %s...", value);
365
366 if ((p = cupsdFindDest(value)) != NULL)
367 {
368 if (p->type & CUPS_PRINTER_CLASS)
369 {
370 cupsdLogMessage(CUPSD_LOG_WARN,
371 "Cached remote printer \"%s\" conflicts with "
372 "existing class!",
373 value);
374 p = NULL;
375 continue;
376 }
377 }
378 else
379 p = cupsdAddPrinter(value);
380
381 p->accepting = 1;
382 p->state = IPP_PRINTER_IDLE;
383 p->type |= CUPS_PRINTER_REMOTE | CUPS_PRINTER_DISCOVERED;
384 p->browse_time = now;
385 p->browse_expire = now + BrowseTimeout;
386
387 /*
388 * Set the default printer as needed...
389 */
390
391 if (!strcasecmp(line, "<DefaultPrinter"))
392 DefaultPrinter = p;
393 }
394 else
395 {
396 cupsdLogMessage(CUPSD_LOG_ERROR,
397 "Syntax error on line %d of remote.cache.", linenum);
398 break;
399 }
400 }
401 else if (!strcasecmp(line, "<Class") ||
402 !strcasecmp(line, "<DefaultClass"))
403 {
404 /*
405 * <Class name> or <DefaultClass name>
406 */
407
408 if (p == NULL && value)
409 {
410 /*
411 * Add the printer and a base file type...
412 */
413
414 cupsdLogMessage(CUPSD_LOG_DEBUG,
415 "cupsdLoadRemoteCache: Loading class %s...", value);
416
417 if ((p = cupsdFindDest(value)) != NULL)
418 p->type = CUPS_PRINTER_CLASS;
419 else
420 p = cupsdAddClass(value);
421
422 p->accepting = 1;
423 p->state = IPP_PRINTER_IDLE;
424 p->type |= CUPS_PRINTER_REMOTE | CUPS_PRINTER_DISCOVERED;
425 p->browse_time = now;
426 p->browse_expire = now + BrowseTimeout;
427
428 /*
429 * Set the default printer as needed...
430 */
431
432 if (!strcasecmp(line, "<DefaultClass"))
433 DefaultPrinter = p;
434 }
435 else
436 {
437 cupsdLogMessage(CUPSD_LOG_ERROR,
438 "Syntax error on line %d of remote.cache.", linenum);
439 break;
440 }
441 }
442 else if (!strcasecmp(line, "</Printer>") ||
443 !strcasecmp(line, "</Class>"))
444 {
445 if (p != NULL)
446 {
447 /*
448 * Close out the current printer...
449 */
450
451 cupsdSetPrinterAttrs(p);
452
453 p = NULL;
454 }
455 else
456 cupsdLogMessage(CUPSD_LOG_ERROR,
457 "Syntax error on line %d of remote.cache.", linenum);
458 }
459 else if (!p)
460 {
461 cupsdLogMessage(CUPSD_LOG_ERROR,
462 "Syntax error on line %d of remote.cache.", linenum);
463 }
464 else if (!strcasecmp(line, "Info"))
465 {
466 if (value)
467 cupsdSetString(&p->info, value);
468 }
469 else if (!strcasecmp(line, "MakeModel"))
470 {
471 if (value)
472 cupsdSetString(&p->make_model, value);
473 }
474 else if (!strcasecmp(line, "Location"))
475 {
476 if (value)
477 cupsdSetString(&p->location, value);
478 }
479 else if (!strcasecmp(line, "DeviceURI"))
480 {
481 if (value)
482 {
483 httpSeparateURI(HTTP_URI_CODING_ALL, value, scheme, sizeof(scheme),
484 username, sizeof(username), host, sizeof(host), &port,
485 resource, sizeof(resource));
486
487 cupsdSetString(&p->hostname, host);
488 cupsdSetString(&p->uri, value);
489 cupsdSetDeviceURI(p, value);
490 }
491 else
492 cupsdLogMessage(CUPSD_LOG_ERROR,
493 "Syntax error on line %d of remote.cache.", linenum);
494 }
495 else if (!strcasecmp(line, "Option") && value)
496 {
497 /*
498 * Option name value
499 */
500
501 for (valueptr = value; *valueptr && !isspace(*valueptr & 255); valueptr ++);
502
503 if (!*valueptr)
504 cupsdLogMessage(CUPSD_LOG_ERROR,
505 "Syntax error on line %d of remote.cache.", linenum);
506 else
507 {
508 for (; *valueptr && isspace(*valueptr & 255); *valueptr++ = '\0');
509
510 p->num_options = cupsAddOption(value, valueptr, p->num_options,
511 &(p->options));
512 }
513 }
514 else if (!strcasecmp(line, "Reason"))
515 {
516 if (value)
517 {
518 for (i = 0 ; i < p->num_reasons; i ++)
519 if (!strcmp(value, p->reasons[i]))
520 break;
521
522 if (i >= p->num_reasons &&
523 p->num_reasons < (int)(sizeof(p->reasons) / sizeof(p->reasons[0])))
524 {
525 p->reasons[p->num_reasons] = _cupsStrAlloc(value);
526 p->num_reasons ++;
527 }
528 }
529 else
530 cupsdLogMessage(CUPSD_LOG_ERROR,
531 "Syntax error on line %d of remote.cache.", linenum);
532 }
533 else if (!strcasecmp(line, "State"))
534 {
535 /*
536 * Set the initial queue state...
537 */
538
539 if (value && !strcasecmp(value, "idle"))
540 p->state = IPP_PRINTER_IDLE;
541 else if (value && !strcasecmp(value, "stopped"))
542 {
543 p->state = IPP_PRINTER_STOPPED;
544 cupsdSetPrinterReasons(p, "+paused");
545 }
546 else
547 cupsdLogMessage(CUPSD_LOG_ERROR,
548 "Syntax error on line %d of remote.cache.", linenum);
549 }
550 else if (!strcasecmp(line, "StateMessage"))
551 {
552 /*
553 * Set the initial queue state message...
554 */
555
556 if (value)
557 strlcpy(p->state_message, value, sizeof(p->state_message));
558 }
559 else if (!strcasecmp(line, "Accepting"))
560 {
561 /*
562 * Set the initial accepting state...
563 */
564
565 if (value &&
566 (!strcasecmp(value, "yes") ||
567 !strcasecmp(value, "on") ||
568 !strcasecmp(value, "true")))
569 p->accepting = 1;
570 else if (value &&
571 (!strcasecmp(value, "no") ||
572 !strcasecmp(value, "off") ||
573 !strcasecmp(value, "false")))
574 p->accepting = 0;
575 else
576 cupsdLogMessage(CUPSD_LOG_ERROR,
577 "Syntax error on line %d of remote.cache.", linenum);
578 }
579 else if (!strcasecmp(line, "Type"))
580 {
581 if (value)
582 p->type = atoi(value);
583 else
584 cupsdLogMessage(CUPSD_LOG_ERROR,
585 "Syntax error on line %d of remote.cache.", linenum);
586 }
587 else if (!strcasecmp(line, "BrowseTime"))
588 {
589 if (value)
590 {
591 time_t t = atoi(value);
592
593 if (t > p->browse_expire)
594 p->browse_expire = t;
595 }
596 else
597 cupsdLogMessage(CUPSD_LOG_ERROR,
598 "Syntax error on line %d of remote.cache.", linenum);
599 }
600 else if (!strcasecmp(line, "JobSheets"))
601 {
602 /*
603 * Set the initial job sheets...
604 */
605
606 if (value)
607 {
608 for (valueptr = value; *valueptr && !isspace(*valueptr & 255); valueptr ++);
609
610 if (*valueptr)
611 *valueptr++ = '\0';
612
613 cupsdSetString(&p->job_sheets[0], value);
614
615 while (isspace(*valueptr & 255))
616 valueptr ++;
617
618 if (*valueptr)
619 {
620 for (value = valueptr; *valueptr && !isspace(*valueptr & 255); valueptr ++);
621
622 if (*valueptr)
623 *valueptr = '\0';
624
625 cupsdSetString(&p->job_sheets[1], value);
626 }
627 }
628 else
629 cupsdLogMessage(CUPSD_LOG_ERROR,
630 "Syntax error on line %d of remote.cache.", linenum);
631 }
632 else if (!strcasecmp(line, "AllowUser"))
633 {
634 if (value)
635 {
636 p->deny_users = 0;
637 cupsdAddPrinterUser(p, value);
638 }
639 else
640 cupsdLogMessage(CUPSD_LOG_ERROR,
641 "Syntax error on line %d of remote.cache.", linenum);
642 }
643 else if (!strcasecmp(line, "DenyUser"))
644 {
645 if (value)
646 {
647 p->deny_users = 1;
648 cupsdAddPrinterUser(p, value);
649 }
650 else
651 cupsdLogMessage(CUPSD_LOG_ERROR,
652 "Syntax error on line %d of remote.cache.", linenum);
653 }
654 else
655 {
656 /*
657 * Something else we don't understand...
658 */
659
660 cupsdLogMessage(CUPSD_LOG_ERROR,
661 "Unknown configuration directive %s on line %d of remote.cache.",
662 line, linenum);
663 }
664 }
665
666 cupsFileClose(fp);
667
668 /*
669 * Do auto-classing if needed...
670 */
671
672 process_implicit_classes();
673 }
674
675
676 /*
677 * 'cupsdRegisterPrinter()' - Start sending broadcast information for a
678 * printer or update the broadcast contents.
679 */
680
681 void
682 cupsdRegisterPrinter(cupsd_printer_t *p)/* I - Printer */
683 {
684 cupsdLogMessage(CUPSD_LOG_DEBUG, "cupsdRegisterPrinter(p=%p(%s))", p,
685 p->name);
686
687 if (!Browsing || !BrowseLocalProtocols ||
688 (p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
689 CUPS_PRINTER_SCANNER)))
690 return;
691
692 #ifdef HAVE_LIBSLP
693 /* if (BrowseLocalProtocols & BROWSE_SLP)
694 slpRegisterPrinter(p); */
695 #endif /* HAVE_LIBSLP */
696
697 #ifdef HAVE_DNSSD
698 if ((BrowseLocalProtocols & BROWSE_DNSSD) && DNSSDRef)
699 dnssdRegisterPrinter(p);
700 #endif /* HAVE_DNSSD */
701 }
702
703
704 /*
705 * 'cupsdRestartPolling()' - Restart polling servers as needed.
706 */
707
708 void
709 cupsdRestartPolling(void)
710 {
711 int i; /* Looping var */
712 cupsd_dirsvc_poll_t *pollp; /* Current polling server */
713
714
715 for (i = 0, pollp = Polled; i < NumPolled; i ++, pollp ++)
716 if (pollp->pid)
717 kill(pollp->pid, SIGHUP);
718 }
719
720
721 /*
722 * 'cupsdSaveRemoteCache()' - Save the remote printer cache.
723 */
724
725 void
726 cupsdSaveRemoteCache(void)
727 {
728 int i; /* Looping var */
729 cups_file_t *fp; /* printers.conf file */
730 char temp[1024], /* Temporary string */
731 value[2048]; /* Value string */
732 cupsd_printer_t *printer; /* Current printer class */
733 time_t curtime; /* Current time */
734 struct tm *curdate; /* Current date */
735 cups_option_t *option; /* Current option */
736
737
738 /*
739 * Create the remote.cache file...
740 */
741
742 snprintf(temp, sizeof(temp), "%s/remote.cache", CacheDir);
743
744 if ((fp = cupsFileOpen(temp, "w")) == NULL)
745 {
746 cupsdLogMessage(CUPSD_LOG_ERROR,
747 "Unable to save remote.cache - %s", strerror(errno));
748 return;
749 }
750 else
751 cupsdLogMessage(CUPSD_LOG_DEBUG, "Saving remote.cache...");
752
753 /*
754 * Restrict access to the file...
755 */
756
757 fchown(cupsFileNumber(fp), getuid(), Group);
758 fchmod(cupsFileNumber(fp), ConfigFilePerm);
759
760 /*
761 * Write a small header to the file...
762 */
763
764 curtime = time(NULL);
765 curdate = localtime(&curtime);
766 strftime(temp, sizeof(temp) - 1, "%Y-%m-%d %H:%M", curdate);
767
768 cupsFilePuts(fp, "# Remote cache file for " CUPS_SVERSION "\n");
769 cupsFilePrintf(fp, "# Written by cupsd on %s\n", temp);
770
771 /*
772 * Write each local printer known to the system...
773 */
774
775 for (printer = (cupsd_printer_t *)cupsArrayFirst(Printers);
776 printer;
777 printer = (cupsd_printer_t *)cupsArrayNext(Printers))
778 {
779 /*
780 * Skip local destinations...
781 */
782
783 if (!(printer->type & CUPS_PRINTER_DISCOVERED))
784 continue;
785
786 /*
787 * Write printers as needed...
788 */
789
790 if (printer == DefaultPrinter)
791 cupsFilePuts(fp, "<Default");
792 else
793 cupsFilePutChar(fp, '<');
794
795 if (printer->type & CUPS_PRINTER_CLASS)
796 cupsFilePrintf(fp, "Class %s>\n", printer->name);
797 else
798 cupsFilePrintf(fp, "Printer %s>\n", printer->name);
799
800 cupsFilePrintf(fp, "BrowseTime %d\n", (int)printer->browse_expire);
801
802 if (printer->info)
803 cupsFilePutConf(fp, "Info", printer->info);
804
805 if (printer->location)
806 cupsFilePutConf(fp, "Location", printer->location);
807
808 if (printer->make_model)
809 cupsFilePutConf(fp, "MakeModel", printer->make_model);
810
811 cupsFilePutConf(fp, "DeviceURI", printer->device_uri);
812
813 if (printer->state == IPP_PRINTER_STOPPED)
814 cupsFilePuts(fp, "State Stopped\n");
815 else
816 cupsFilePuts(fp, "State Idle\n");
817
818 for (i = 0; i < printer->num_reasons; i ++)
819 cupsFilePutConf(fp, "Reason", printer->reasons[i]);
820
821 cupsFilePrintf(fp, "Type %d\n", printer->type);
822
823 if (printer->accepting)
824 cupsFilePuts(fp, "Accepting Yes\n");
825 else
826 cupsFilePuts(fp, "Accepting No\n");
827
828 snprintf(value, sizeof(value), "%s %s", printer->job_sheets[0],
829 printer->job_sheets[1]);
830 cupsFilePutConf(fp, "JobSheets", value);
831
832 for (i = 0; i < printer->num_users; i ++)
833 cupsFilePutConf(fp, printer->deny_users ? "DenyUser" : "AllowUser",
834 printer->users[i]);
835
836 for (i = printer->num_options, option = printer->options;
837 i > 0;
838 i --, option ++)
839 {
840 snprintf(value, sizeof(value), "%s %s", option->name, option->value);
841 cupsFilePutConf(fp, "Option", value);
842 }
843
844 if (printer->type & CUPS_PRINTER_CLASS)
845 cupsFilePuts(fp, "</Class>\n");
846 else
847 cupsFilePuts(fp, "</Printer>\n");
848 }
849
850 cupsFileClose(fp);
851 }
852
853
854 /*
855 * 'cupsdSendBrowseList()' - Send new browsing information as necessary.
856 */
857
858 void
859 cupsdSendBrowseList(void)
860 {
861 int count; /* Number of dests to update */
862 cupsd_printer_t *p; /* Current printer */
863 time_t ut, /* Minimum update time */
864 to; /* Timeout time */
865
866
867 if (!Browsing || !Printers)
868 return;
869
870 /*
871 * Compute the update and timeout times...
872 */
873
874 to = time(NULL);
875 ut = to - BrowseInterval;
876
877 /*
878 * Figure out how many printers need an update...
879 */
880
881 if (BrowseInterval > 0 && BrowseLocalProtocols)
882 {
883 int max_count; /* Maximum number to update */
884
885
886 /*
887 * Throttle the number of printers we'll be updating this time
888 * around based on the number of queues that need updating and
889 * the maximum number of queues to update each second...
890 */
891
892 max_count = 2 * cupsArrayCount(Printers) / BrowseInterval + 1;
893
894 for (count = 0, p = (cupsd_printer_t *)cupsArrayFirst(Printers);
895 count < max_count && p != NULL;
896 p = (cupsd_printer_t *)cupsArrayNext(Printers))
897 if (!(p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
898 CUPS_PRINTER_SCANNER)) &&
899 p->shared && p->browse_time < ut)
900 count ++;
901
902 /*
903 * Loop through all of the printers and send local updates as needed...
904 */
905
906 if (BrowseNext)
907 p = (cupsd_printer_t *)cupsArrayFind(Printers, BrowseNext);
908 else
909 p = (cupsd_printer_t *)cupsArrayFirst(Printers);
910
911 for (;
912 count > 0;
913 p = (cupsd_printer_t *)cupsArrayNext(Printers))
914 {
915 /*
916 * Check for wraparound...
917 */
918
919 if (!p)
920 p = (cupsd_printer_t *)cupsArrayFirst(Printers);
921
922 if (!p)
923 break;
924 else if ((p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
925 CUPS_PRINTER_SCANNER)) ||
926 !p->shared)
927 continue;
928 else if (p->browse_time < ut)
929 {
930 /*
931 * Need to send an update...
932 */
933
934 count --;
935
936 p->browse_time = time(NULL);
937
938 if ((BrowseLocalProtocols & BROWSE_CUPS) && BrowseSocket >= 0)
939 send_cups_browse(p);
940
941 #ifdef HAVE_LIBSLP
942 if (BrowseLocalProtocols & BROWSE_SLP)
943 send_slp_browse(p);
944 #endif /* HAVE_LIBSLP */
945
946 #ifdef HAVE_LDAP
947 if (BrowseLocalProtocols & BROWSE_LDAP)
948 send_ldap_browse(p);
949 #endif /* HAVE_LDAP */
950 }
951 }
952
953 /*
954 * Save where we left off so that all printers get updated...
955 */
956
957 BrowseNext = p;
958 }
959
960 /*
961 * Loop through all of the printers and timeout old printers as needed...
962 */
963
964 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
965 p;
966 p = (cupsd_printer_t *)cupsArrayNext(Printers))
967 {
968 /*
969 * If this is a remote queue, see if it needs to be timed out...
970 */
971
972 if ((p->type & CUPS_PRINTER_DISCOVERED) &&
973 !(p->type & CUPS_PRINTER_IMPLICIT) &&
974 p->browse_expire < to)
975 {
976 cupsdAddEvent(CUPSD_EVENT_PRINTER_DELETED, p, NULL,
977 "%s \'%s\' deleted by directory services (timeout).",
978 (p->type & CUPS_PRINTER_CLASS) ? "Class" : "Printer",
979 p->name);
980
981 cupsdLogMessage(CUPSD_LOG_DEBUG,
982 "Remote destination \"%s\" has timed out; "
983 "deleting it...",
984 p->name);
985
986 cupsArraySave(Printers);
987 cupsdDeletePrinter(p, 1);
988 cupsArrayRestore(Printers);
989 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP | CUPSD_DIRTY_REMOTE);
990 }
991 }
992 }
993
994
995 #ifdef HAVE_LDAP_REBIND_PROC
996 # if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
997 /*
998 * 'ldap_rebind_proc()' - Callback function for LDAP rebind
999 */
1000
1001 static int /* O - Result code */
1002 ldap_rebind_proc(
1003 LDAP *RebindLDAPHandle, /* I - LDAP handle */
1004 LDAP_CONST char *refsp, /* I - ??? */
1005 ber_tag_t request, /* I - ??? */
1006 ber_int_t msgid, /* I - ??? */
1007 void *params) /* I - ??? */
1008 {
1009 int rc; /* Result code */
1010 # if LDAP_API_VERSION > 3000
1011 struct berval bval; /* Bind value */
1012 # endif /* LDAP_API_VERSION > 3000 */
1013
1014 /*
1015 * Bind to new LDAP server...
1016 */
1017
1018 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_rebind_proc: Rebind to %s", refsp);
1019
1020 # if LDAP_API_VERSION > 3000
1021 bval.bv_val = BrowseLDAPPassword;
1022 bval.bv_len = (BrowseLDAPPassword == NULL) ? 0 : strlen(BrowseLDAPPassword);
1023
1024 rc = ldap_sasl_bind_s(RebindLDAPHandle, BrowseLDAPBindDN, LDAP_SASL_SIMPLE,
1025 &bval, NULL, NULL, NULL);
1026 # else
1027 rc = ldap_bind_s(RebindLDAPHandle, BrowseLDAPBindDN, BrowseLDAPPassword,
1028 LDAP_AUTH_SIMPLE);
1029 # endif /* LDAP_API_VERSION > 3000 */
1030
1031 return (rc);
1032 }
1033
1034
1035 # else /* defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000) */
1036 /*
1037 * 'ldap_rebind_proc()' - Callback function for LDAP rebind
1038 */
1039
1040 static int /* O - Result code */
1041 ldap_rebind_proc(
1042 LDAP *RebindLDAPHandle, /* I - LDAP handle */
1043 char **dnp, /* I - ??? */
1044 char **passwdp, /* I - ??? */
1045 int *authmethodp, /* I - ??? */
1046 int freeit, /* I - ??? */
1047 void *arg) /* I - ??? */
1048 {
1049 switch (freeit)
1050 {
1051 case 1:
1052 /*
1053 * Free current values...
1054 */
1055
1056 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_rebind_proc: Free values...");
1057
1058 if (dnp && *dnp)
1059 free(*dnp);
1060
1061 if (passwdp && *passwdp)
1062 free(*passwdp);
1063 break;
1064
1065 case 0:
1066 /*
1067 * Return credentials for LDAP referal...
1068 */
1069
1070 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1071 "ldap_rebind_proc: Return necessary values...");
1072
1073 *dnp = strdup(BrowseLDAPBindDN);
1074 *passwdp = strdup(BrowseLDAPPassword);
1075 *authmethodp = LDAP_AUTH_SIMPLE;
1076 break;
1077
1078 default:
1079 /*
1080 * Should never happen...
1081 */
1082
1083 cupsdLogMessage(CUPSD_LOG_ERROR,
1084 "LDAP rebind has been called with wrong freeit value!");
1085 break;
1086 }
1087
1088 return (LDAP_SUCCESS);
1089 }
1090 # endif /* defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000) */
1091 #endif /* HAVE_LDAP_REBIND_PROC */
1092
1093
1094 #ifdef HAVE_LDAP
1095 /*
1096 * 'ldap_connect()' - Start new LDAP connection
1097 */
1098
1099 static LDAP * /* O - LDAP handle */
1100 ldap_connect(void)
1101 {
1102 int rc; /* LDAP API status */
1103 int version = 3; /* LDAP version */
1104 struct berval bv = {0, ""}; /* SASL bind value */
1105 LDAP *TempBrowseLDAPHandle=NULL;
1106 /* Temporary LDAP Handle */
1107 # if defined(HAVE_LDAP_SSL) && defined (HAVE_MOZILLA_LDAP)
1108 int ldap_ssl = 0; /* LDAP SSL indicator */
1109 int ssl_err = 0; /* LDAP SSL error value */
1110 # endif /* defined(HAVE_LDAP_SSL) && defined (HAVE_MOZILLA_LDAP) */
1111
1112
1113 # ifdef HAVE_OPENLDAP
1114 # ifdef HAVE_LDAP_SSL
1115 /*
1116 * Set the certificate file to use for encrypted LDAP sessions...
1117 */
1118
1119 if (BrowseLDAPCACertFile)
1120 {
1121 cupsdLogMessage(CUPSD_LOG_DEBUG,
1122 "ldap_connect: Setting CA certificate file \"%s\"",
1123 BrowseLDAPCACertFile);
1124
1125 if ((rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE,
1126 (void *)BrowseLDAPCACertFile)) != LDAP_SUCCESS)
1127 cupsdLogMessage(CUPSD_LOG_ERROR,
1128 "Unable to set CA certificate file for LDAP "
1129 "connections: %d - %s", rc, ldap_err2string(rc));
1130 }
1131 # endif /* HAVE_LDAP_SSL */
1132
1133 /*
1134 * Initialize OPENLDAP connection...
1135 * LDAP stuff currently only supports ldapi EXTERNAL SASL binds...
1136 */
1137
1138 if (!BrowseLDAPServer || !strcasecmp(BrowseLDAPServer, "localhost"))
1139 rc = ldap_initialize(&TempBrowseLDAPHandle, "ldapi:///");
1140 else
1141 rc = ldap_initialize(&TempBrowseLDAPHandle, BrowseLDAPServer);
1142
1143 # else /* HAVE_OPENLDAP */
1144
1145 int ldap_port = 0; /* LDAP port */
1146 char ldap_protocol[11], /* LDAP protocol */
1147 ldap_host[255]; /* LDAP host */
1148
1149 /*
1150 * Split LDAP URI into its components...
1151 */
1152
1153 if (!BrowseLDAPServer)
1154 {
1155 cupsdLogMessage(CUPSD_LOG_ERROR, "BrowseLDAPServer not configured!");
1156 cupsdLogMessage(CUPSD_LOG_ERROR, "Disabling LDAP browsing!");
1157 BrowseLocalProtocols &= ~BROWSE_LDAP;
1158 BrowseRemoteProtocols &= ~BROWSE_LDAP;
1159 return (NULL);
1160 }
1161
1162 sscanf(BrowseLDAPServer, "%10[^:]://%254[^:/]:%d", ldap_protocol, ldap_host,
1163 &ldap_port);
1164
1165 if (!strcmp(ldap_protocol, "ldap"))
1166 ldap_ssl = 0;
1167 else if (!strcmp(ldap_protocol, "ldaps"))
1168 ldap_ssl = 1;
1169 else
1170 {
1171 cupsdLogMessage(CUPSD_LOG_ERROR, "Unrecognized LDAP protocol (%s)!",
1172 ldap_protocol);
1173 cupsdLogMessage(CUPSD_LOG_ERROR, "Disabling LDAP browsing!");
1174 BrowseLocalProtocols &= ~BROWSE_LDAP;
1175 BrowseRemoteProtocols &= ~BROWSE_LDAP;
1176 return (NULL);
1177 }
1178
1179 if (ldap_port == 0)
1180 {
1181 if (ldap_ssl)
1182 ldap_port = LDAPS_PORT;
1183 else
1184 ldap_port = LDAP_PORT;
1185 }
1186
1187 cupsdLogMessage(CUPSD_LOG_DEBUG, "ldap_connect: PROT:%s HOST:%s PORT:%d",
1188 ldap_protocol, ldap_host, ldap_port);
1189
1190 /*
1191 * Initialize LDAP connection...
1192 */
1193
1194 if (!ldap_ssl)
1195 {
1196 if ((TempBrowseLDAPHandle = ldap_init(ldap_host, ldap_port)) == NULL)
1197 rc = LDAP_OPERATIONS_ERROR;
1198 else
1199 rc = LDAP_SUCCESS;
1200
1201 # ifdef HAVE_LDAP_SSL
1202 }
1203 else
1204 {
1205 /*
1206 * Initialize SSL LDAP connection...
1207 */
1208
1209 if (BrowseLDAPCACertFile)
1210 {
1211 rc = ldapssl_client_init(BrowseLDAPCACertFile, (void *)NULL);
1212 if (rc != LDAP_SUCCESS)
1213 {
1214 cupsdLogMessage(CUPSD_LOG_ERROR,
1215 "Failed to initialize LDAP SSL client!");
1216 rc = LDAP_OPERATIONS_ERROR;
1217 }
1218 else
1219 {
1220 if ((TempBrowseLDAPHandle = ldapssl_init(ldap_host, ldap_port,
1221 1)) == NULL)
1222 rc = LDAP_OPERATIONS_ERROR;
1223 else
1224 rc = LDAP_SUCCESS;
1225 }
1226 }
1227 else
1228 {
1229 cupsdLogMessage(CUPSD_LOG_ERROR,
1230 "LDAP SSL certificate file/database not configured!");
1231 rc = LDAP_OPERATIONS_ERROR;
1232 }
1233
1234 # else /* HAVE_LDAP_SSL */
1235
1236 /*
1237 * Return error, because client libraries doesn't support SSL
1238 */
1239
1240 cupsdLogMessage(CUPSD_LOG_ERROR,
1241 "LDAP client libraries do not support SSL");
1242 rc = LDAP_OPERATIONS_ERROR;
1243
1244 # endif /* HAVE_LDAP_SSL */
1245 }
1246 # endif /* HAVE_OPENLDAP */
1247
1248 /*
1249 * Check return code from LDAP initialize...
1250 */
1251
1252 if (rc != LDAP_SUCCESS)
1253 {
1254 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to initialize LDAP!");
1255
1256 if (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR)
1257 cupsdLogMessage(CUPSD_LOG_ERROR, "Temporarily disabling LDAP browsing...");
1258 else
1259 {
1260 cupsdLogMessage(CUPSD_LOG_ERROR, "Disabling LDAP browsing!");
1261
1262 BrowseLocalProtocols &= ~BROWSE_LDAP;
1263 BrowseRemoteProtocols &= ~BROWSE_LDAP;
1264 }
1265
1266 ldap_disconnect(TempBrowseLDAPHandle);
1267
1268 return (NULL);
1269 }
1270
1271 /*
1272 * Upgrade LDAP version...
1273 */
1274
1275 if (ldap_set_option(TempBrowseLDAPHandle, LDAP_OPT_PROTOCOL_VERSION,
1276 (const void *)&version) != LDAP_SUCCESS)
1277 {
1278 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to set LDAP protocol version %d!",
1279 version);
1280 cupsdLogMessage(CUPSD_LOG_ERROR, "Disabling LDAP browsing!");
1281
1282 BrowseLocalProtocols &= ~BROWSE_LDAP;
1283 BrowseRemoteProtocols &= ~BROWSE_LDAP;
1284 ldap_disconnect(TempBrowseLDAPHandle);
1285
1286 return (NULL);
1287 }
1288
1289 /*
1290 * Register LDAP rebind procedure...
1291 */
1292
1293 # ifdef HAVE_LDAP_REBIND_PROC
1294 # if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1295
1296 rc = ldap_set_rebind_proc(TempBrowseLDAPHandle, &ldap_rebind_proc,
1297 (void *)NULL);
1298 if (rc != LDAP_SUCCESS)
1299 cupsdLogMessage(CUPSD_LOG_ERROR,
1300 "Setting LDAP rebind function failed with status %d: %s",
1301 rc, ldap_err2string(rc));
1302
1303 # else
1304
1305 ldap_set_rebind_proc(TempBrowseLDAPHandle, &ldap_rebind_proc, (void *)NULL);
1306
1307 # endif /* defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000) */
1308 # endif /* HAVE_LDAP_REBIND_PROC */
1309
1310 /*
1311 * Start LDAP bind...
1312 */
1313
1314 # if LDAP_API_VERSION > 3000
1315 struct berval bval;
1316 bval.bv_val = BrowseLDAPPassword;
1317 bval.bv_len = (BrowseLDAPPassword == NULL) ? 0 : strlen(BrowseLDAPPassword);
1318
1319 if (!BrowseLDAPServer || !strcasecmp(BrowseLDAPServer, "localhost"))
1320 rc = ldap_sasl_bind_s(TempBrowseLDAPHandle, NULL, "EXTERNAL", &bv, NULL,
1321 NULL, NULL);
1322 else
1323 rc = ldap_sasl_bind_s(TempBrowseLDAPHandle, BrowseLDAPBindDN, LDAP_SASL_SIMPLE, &bval, NULL, NULL, NULL);
1324
1325 # else
1326 rc = ldap_bind_s(TempBrowseLDAPHandle, BrowseLDAPBindDN,
1327 BrowseLDAPPassword, LDAP_AUTH_SIMPLE);
1328 # endif /* LDAP_API_VERSION > 3000 */
1329
1330 if (rc != LDAP_SUCCESS)
1331 {
1332 cupsdLogMessage(CUPSD_LOG_ERROR, "LDAP bind failed with error %d: %s",
1333 rc, ldap_err2string(rc));
1334
1335 # if defined(HAVE_LDAP_SSL) && defined (HAVE_MOZILLA_LDAP)
1336 if (ldap_ssl && (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR))
1337 {
1338 ssl_err = PORT_GetError();
1339 if (ssl_err != 0)
1340 cupsdLogMessage(CUPSD_LOG_ERROR, "LDAP SSL error %d: %s", ssl_err,
1341 ldapssl_err2string(ssl_err));
1342 }
1343 # endif /* defined(HAVE_LDAP_SSL) && defined (HAVE_MOZILLA_LDAP) */
1344
1345 ldap_disconnect(TempBrowseLDAPHandle);
1346
1347 return (NULL);
1348 }
1349
1350 cupsdLogMessage(CUPSD_LOG_INFO, "LDAP connection established");
1351
1352 return (TempBrowseLDAPHandle);
1353 }
1354
1355
1356 /*
1357 * 'ldap_reconnect()' - Reconnect to LDAP Server
1358 */
1359
1360 static LDAP * /* O - New LDAP handle */
1361 ldap_reconnect(void)
1362 {
1363 LDAP *TempBrowseLDAPHandle = NULL; /* Temp Handle to LDAP server */
1364
1365
1366 /*
1367 * Get a new LDAP Handle and replace the global Handle
1368 * if the new connection was successful.
1369 */
1370
1371 cupsdLogMessage(CUPSD_LOG_INFO, "Try LDAP reconnect...");
1372
1373 TempBrowseLDAPHandle = ldap_connect();
1374
1375 if (TempBrowseLDAPHandle != NULL)
1376 {
1377 if (BrowseLDAPHandle != NULL)
1378 ldap_disconnect(BrowseLDAPHandle);
1379
1380 BrowseLDAPHandle = TempBrowseLDAPHandle;
1381 }
1382
1383 return (BrowseLDAPHandle);
1384 }
1385
1386
1387 /*
1388 * 'ldap_disconnect()' - Disconnect from LDAP Server
1389 */
1390
1391 static void
1392 ldap_disconnect(LDAP *ld) /* I - LDAP handle */
1393 {
1394 int rc; /* Return code */
1395
1396
1397 /*
1398 * Close LDAP handle...
1399 */
1400
1401 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
1402 rc = ldap_unbind_ext_s(ld, NULL, NULL);
1403 # else
1404 rc = ldap_unbind_s(ld);
1405 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
1406
1407 if (rc != LDAP_SUCCESS)
1408 cupsdLogMessage(CUPSD_LOG_ERROR,
1409 "Unbind from LDAP server failed with status %d: %s",
1410 rc, ldap_err2string(rc));
1411 }
1412 #endif /* HAVE_LDAP */
1413
1414
1415 /*
1416 * 'cupsdStartBrowsing()' - Start sending and receiving broadcast information.
1417 */
1418
1419 void
1420 cupsdStartBrowsing(void)
1421 {
1422 int val; /* Socket option value */
1423 struct sockaddr_in addr; /* Broadcast address */
1424 cupsd_printer_t *p; /* Current printer */
1425
1426
1427 BrowseNext = NULL;
1428
1429 if (!Browsing || !(BrowseLocalProtocols | BrowseRemoteProtocols))
1430 return;
1431
1432 if ((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_CUPS)
1433 {
1434 if (BrowseSocket < 0)
1435 {
1436 /*
1437 * Create the broadcast socket...
1438 */
1439
1440 if ((BrowseSocket = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1441 {
1442 cupsdLogMessage(CUPSD_LOG_ERROR,
1443 "Unable to create broadcast socket - %s.",
1444 strerror(errno));
1445 BrowseLocalProtocols &= ~BROWSE_CUPS;
1446 BrowseRemoteProtocols &= ~BROWSE_CUPS;
1447
1448 if (FatalErrors & CUPSD_FATAL_BROWSE)
1449 cupsdEndProcess(getpid(), 0);
1450 }
1451 }
1452
1453 if (BrowseSocket >= 0)
1454 {
1455 /*
1456 * Bind the socket to browse port...
1457 */
1458
1459 memset(&addr, 0, sizeof(addr));
1460 addr.sin_addr.s_addr = htonl(INADDR_ANY);
1461 addr.sin_family = AF_INET;
1462 addr.sin_port = htons(BrowsePort);
1463
1464 if (bind(BrowseSocket, (struct sockaddr *)&addr, sizeof(addr)))
1465 {
1466 cupsdLogMessage(CUPSD_LOG_ERROR,
1467 "Unable to bind broadcast socket - %s.",
1468 strerror(errno));
1469
1470 #ifdef WIN32
1471 closesocket(BrowseSocket);
1472 #else
1473 close(BrowseSocket);
1474 #endif /* WIN32 */
1475
1476 BrowseSocket = -1;
1477 BrowseLocalProtocols &= ~BROWSE_CUPS;
1478 BrowseRemoteProtocols &= ~BROWSE_CUPS;
1479
1480 if (FatalErrors & CUPSD_FATAL_BROWSE)
1481 cupsdEndProcess(getpid(), 0);
1482 }
1483 }
1484
1485 if (BrowseSocket >= 0)
1486 {
1487 /*
1488 * Set the "broadcast" flag...
1489 */
1490
1491 val = 1;
1492 if (setsockopt(BrowseSocket, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val)))
1493 {
1494 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to set broadcast mode - %s.",
1495 strerror(errno));
1496
1497 #ifdef WIN32
1498 closesocket(BrowseSocket);
1499 #else
1500 close(BrowseSocket);
1501 #endif /* WIN32 */
1502
1503 BrowseSocket = -1;
1504 BrowseLocalProtocols &= ~BROWSE_CUPS;
1505 BrowseRemoteProtocols &= ~BROWSE_CUPS;
1506
1507 if (FatalErrors & CUPSD_FATAL_BROWSE)
1508 cupsdEndProcess(getpid(), 0);
1509 }
1510 }
1511
1512 if (BrowseSocket >= 0)
1513 {
1514 /*
1515 * Close the socket on exec...
1516 */
1517
1518 fcntl(BrowseSocket, F_SETFD, fcntl(BrowseSocket, F_GETFD) | FD_CLOEXEC);
1519
1520 /*
1521 * Finally, add the socket to the input selection set as needed...
1522 */
1523
1524 if (BrowseRemoteProtocols & BROWSE_CUPS)
1525 {
1526 /*
1527 * We only listen if we want remote printers...
1528 */
1529
1530 cupsdAddSelect(BrowseSocket, (cupsd_selfunc_t)update_cups_browse,
1531 NULL, NULL);
1532 }
1533 }
1534 }
1535 else
1536 BrowseSocket = -1;
1537
1538 #ifdef HAVE_DNSSD
1539 if ((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_DNSSD)
1540 {
1541 DNSServiceErrorType error; /* Error from service creation */
1542 cupsd_listener_t *lis; /* Current listening socket */
1543
1544
1545 /*
1546 * First create a "master" connection for all registrations...
1547 */
1548
1549 if ((error = DNSServiceCreateConnection(&DNSSDRef))
1550 != kDNSServiceErr_NoError)
1551 {
1552 cupsdLogMessage(CUPSD_LOG_ERROR,
1553 "Unable to create master DNS-SD reference: %d", error);
1554
1555 if (FatalErrors & CUPSD_FATAL_BROWSE)
1556 cupsdEndProcess(getpid(), 0);
1557 }
1558 else
1559 {
1560 /*
1561 * Add the master connection to the select list...
1562 */
1563
1564 int fd = DNSServiceRefSockFD(DNSSDRef);
1565
1566 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
1567
1568 cupsdAddSelect(fd, (cupsd_selfunc_t)dnssdUpdate, NULL, NULL);
1569
1570 /*
1571 * Then get the port we use for registrations. If we are not listening
1572 * on any non-local ports, there is no sense sharing local printers via
1573 * Bonjour...
1574 */
1575
1576 DNSSDPort = 0;
1577
1578 for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
1579 lis;
1580 lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
1581 {
1582 if (httpAddrLocalhost(&(lis->address)))
1583 continue;
1584
1585 if (lis->address.addr.sa_family == AF_INET)
1586 {
1587 DNSSDPort = ntohs(lis->address.ipv4.sin_port);
1588 break;
1589 }
1590 else if (lis->address.addr.sa_family == AF_INET6)
1591 {
1592 DNSSDPort = ntohs(lis->address.ipv6.sin6_port);
1593 break;
1594 }
1595 }
1596
1597 /*
1598 * Create an array to track the printers we share...
1599 */
1600
1601 if (BrowseRemoteProtocols & BROWSE_DNSSD)
1602 DNSSDPrinters = cupsArrayNew((cups_array_func_t)dnssdComparePrinters,
1603 NULL);
1604
1605 /*
1606 * Set the computer name and register the web interface...
1607 */
1608
1609 cupsdUpdateDNSSDName();
1610 }
1611 }
1612 #endif /* HAVE_DNSSD */
1613
1614 #ifdef HAVE_LIBSLP
1615 if ((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_SLP)
1616 {
1617 /*
1618 * Open SLP handle...
1619 */
1620
1621 if (SLPOpen("en", SLP_FALSE, &BrowseSLPHandle) != SLP_OK)
1622 {
1623 cupsdLogMessage(CUPSD_LOG_ERROR,
1624 "Unable to open an SLP handle; disabling SLP browsing!");
1625 BrowseLocalProtocols &= ~BROWSE_SLP;
1626 BrowseRemoteProtocols &= ~BROWSE_SLP;
1627 BrowseSLPHandle = NULL;
1628
1629 if (FatalErrors & CUPSD_FATAL_BROWSE)
1630 cupsdEndProcess(getpid(), 0);
1631 }
1632
1633 BrowseSLPRefresh = 0;
1634 }
1635 else
1636 BrowseSLPHandle = NULL;
1637 #endif /* HAVE_LIBSLP */
1638
1639 #ifdef HAVE_LDAP
1640 if ((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_LDAP)
1641 {
1642 if (!BrowseLDAPDN)
1643 {
1644 cupsdLogMessage(CUPSD_LOG_ERROR,
1645 "Need to set BrowseLDAPDN to use LDAP browsing!");
1646 BrowseLocalProtocols &= ~BROWSE_LDAP;
1647 BrowseRemoteProtocols &= ~BROWSE_LDAP;
1648
1649 if (FatalErrors & CUPSD_FATAL_BROWSE)
1650 cupsdEndProcess(getpid(), 0);
1651 }
1652 else
1653 {
1654 /*
1655 * Open LDAP handle...
1656 */
1657
1658 if ((BrowseLDAPHandle = ldap_connect()) == NULL &&
1659 (FatalErrors & CUPSD_FATAL_BROWSE))
1660 cupsdEndProcess(getpid(), 0);
1661 }
1662
1663 BrowseLDAPRefresh = 0;
1664 }
1665 #endif /* HAVE_LDAP */
1666
1667 /*
1668 * Enable LPD and SMB printer sharing as needed through external programs...
1669 */
1670
1671 if (BrowseLocalProtocols & BROWSE_LPD)
1672 update_lpd(1);
1673
1674 if (BrowseLocalProtocols & BROWSE_SMB)
1675 update_smb(1);
1676
1677 /*
1678 * Register the individual printers
1679 */
1680
1681 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
1682 p;
1683 p = (cupsd_printer_t *)cupsArrayNext(Printers))
1684 if (!(p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
1685 CUPS_PRINTER_SCANNER)))
1686 cupsdRegisterPrinter(p);
1687 }
1688
1689
1690 /*
1691 * 'cupsdStartPolling()' - Start polling servers as needed.
1692 */
1693
1694 void
1695 cupsdStartPolling(void)
1696 {
1697 int i; /* Looping var */
1698 cupsd_dirsvc_poll_t *pollp; /* Current polling server */
1699 char polld[1024]; /* Poll daemon path */
1700 char sport[255]; /* Server port */
1701 char bport[255]; /* Browser port */
1702 char interval[255]; /* Poll interval */
1703 int statusfds[2]; /* Status pipe */
1704 char *argv[6]; /* Arguments */
1705 char *envp[100]; /* Environment */
1706
1707
1708 /*
1709 * Don't do anything if we aren't polling...
1710 */
1711
1712 if (NumPolled == 0 || BrowseSocket < 0)
1713 {
1714 PollPipe = -1;
1715 PollStatusBuffer = NULL;
1716 return;
1717 }
1718
1719 /*
1720 * Setup string arguments for polld, port and interval options.
1721 */
1722
1723 snprintf(polld, sizeof(polld), "%s/daemon/cups-polld", ServerBin);
1724
1725 sprintf(bport, "%d", BrowsePort);
1726
1727 if (BrowseInterval)
1728 sprintf(interval, "%d", BrowseInterval);
1729 else
1730 strcpy(interval, "30");
1731
1732 argv[0] = "cups-polld";
1733 argv[2] = sport;
1734 argv[3] = interval;
1735 argv[4] = bport;
1736 argv[5] = NULL;
1737
1738 cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
1739
1740 /*
1741 * Create a pipe that receives the status messages from each
1742 * polling daemon...
1743 */
1744
1745 if (cupsdOpenPipe(statusfds))
1746 {
1747 cupsdLogMessage(CUPSD_LOG_ERROR,
1748 "Unable to create polling status pipes - %s.",
1749 strerror(errno));
1750 PollPipe = -1;
1751 PollStatusBuffer = NULL;
1752 return;
1753 }
1754
1755 PollPipe = statusfds[0];
1756 PollStatusBuffer = cupsdStatBufNew(PollPipe, "[Poll]");
1757
1758 /*
1759 * Run each polling daemon, redirecting stderr to the polling pipe...
1760 */
1761
1762 for (i = 0, pollp = Polled; i < NumPolled; i ++, pollp ++)
1763 {
1764 sprintf(sport, "%d", pollp->port);
1765
1766 argv[1] = pollp->hostname;
1767
1768 if (cupsdStartProcess(polld, argv, envp, -1, -1, statusfds[1], -1, -1,
1769 0, DefaultProfile, NULL, &(pollp->pid)) < 0)
1770 {
1771 cupsdLogMessage(CUPSD_LOG_ERROR,
1772 "cupsdStartPolling: Unable to fork polling daemon - %s",
1773 strerror(errno));
1774 pollp->pid = 0;
1775 break;
1776 }
1777 else
1778 cupsdLogMessage(CUPSD_LOG_DEBUG,
1779 "cupsdStartPolling: Started polling daemon for %s:%d, pid = %d",
1780 pollp->hostname, pollp->port, pollp->pid);
1781 }
1782
1783 close(statusfds[1]);
1784
1785 /*
1786 * Finally, add the pipe to the input selection set...
1787 */
1788
1789 cupsdAddSelect(PollPipe, (cupsd_selfunc_t)update_polling, NULL, NULL);
1790 }
1791
1792
1793 /*
1794 * 'cupsdStopBrowsing()' - Stop sending and receiving broadcast information.
1795 */
1796
1797 void
1798 cupsdStopBrowsing(void)
1799 {
1800 cupsd_printer_t *p; /* Current printer */
1801
1802
1803 if (!Browsing || !(BrowseLocalProtocols | BrowseRemoteProtocols))
1804 return;
1805
1806 /*
1807 * De-register the individual printers
1808 */
1809
1810 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
1811 p;
1812 p = (cupsd_printer_t *)cupsArrayNext(Printers))
1813 if (!(p->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT |
1814 CUPS_PRINTER_SCANNER)))
1815 cupsdDeregisterPrinter(p, 1);
1816
1817 /*
1818 * Shut down browsing sockets...
1819 */
1820
1821 if (((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_CUPS) &&
1822 BrowseSocket >= 0)
1823 {
1824 /*
1825 * Close the socket and remove it from the input selection set.
1826 */
1827
1828 #ifdef WIN32
1829 closesocket(BrowseSocket);
1830 #else
1831 close(BrowseSocket);
1832 #endif /* WIN32 */
1833
1834 cupsdRemoveSelect(BrowseSocket);
1835 BrowseSocket = -1;
1836 }
1837
1838 #ifdef HAVE_DNSSD
1839 if ((BrowseLocalProtocols & BROWSE_DNSSD) && DNSSDRef)
1840 dnssdStop();
1841 #endif /* HAVE_DNSSD */
1842
1843 #ifdef HAVE_LIBSLP
1844 if (((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_SLP) &&
1845 BrowseSLPHandle)
1846 {
1847 /*
1848 * Close SLP handle...
1849 */
1850
1851 SLPClose(BrowseSLPHandle);
1852 BrowseSLPHandle = NULL;
1853 }
1854 #endif /* HAVE_LIBSLP */
1855
1856 #ifdef HAVE_LDAP
1857 if (((BrowseLocalProtocols | BrowseRemoteProtocols) & BROWSE_LDAP) &&
1858 BrowseLDAPHandle)
1859 {
1860 ldap_dereg_ou(ServerName, BrowseLDAPDN);
1861 ldap_disconnect(BrowseLDAPHandle);
1862 BrowseLDAPHandle = NULL;
1863 }
1864 #endif /* HAVE_OPENLDAP */
1865
1866 /*
1867 * Disable LPD and SMB printer sharing as needed through external programs...
1868 */
1869
1870 if (BrowseLocalProtocols & BROWSE_LPD)
1871 update_lpd(0);
1872
1873 if (BrowseLocalProtocols & BROWSE_SMB)
1874 update_smb(0);
1875 }
1876
1877
1878 /*
1879 * 'cupsdStopPolling()' - Stop polling servers as needed.
1880 */
1881
1882 void
1883 cupsdStopPolling(void)
1884 {
1885 int i; /* Looping var */
1886 cupsd_dirsvc_poll_t *pollp; /* Current polling server */
1887
1888
1889 if (PollPipe >= 0)
1890 {
1891 cupsdStatBufDelete(PollStatusBuffer);
1892 close(PollPipe);
1893
1894 cupsdRemoveSelect(PollPipe);
1895
1896 PollPipe = -1;
1897 PollStatusBuffer = NULL;
1898 }
1899
1900 for (i = 0, pollp = Polled; i < NumPolled; i ++, pollp ++)
1901 if (pollp->pid)
1902 cupsdEndProcess(pollp->pid, 0);
1903 }
1904
1905
1906 #ifdef HAVE_DNSSD
1907 /*
1908 * 'cupsdUpdateDNSSDName()' - Update the computer name we use for browsing...
1909 */
1910
1911 void
1912 cupsdUpdateDNSSDName(void)
1913 {
1914 DNSServiceErrorType error; /* Error from service creation */
1915 char webif[1024]; /* Web interface share name */
1916 #ifdef HAVE_COREFOUNDATION_H
1917 SCDynamicStoreRef sc; /* Context for dynamic store */
1918 CFDictionaryRef btmm; /* Back-to-My-Mac domains */
1919 CFStringEncoding nameEncoding; /* Encoding of computer name */
1920 CFStringRef nameRef; /* Host name CFString */
1921 char nameBuffer[1024]; /* C-string buffer */
1922 #endif /* HAVE_COREFOUNDATION_H */
1923
1924
1925 /*
1926 * Only share the web interface and printers when non-local listening is
1927 * enabled...
1928 */
1929
1930
1931 if (!DNSSDPort)
1932 return;
1933
1934 /*
1935 * Get the computer name as a c-string...
1936 */
1937
1938 #ifdef HAVE_COREFOUNDATION_H
1939 sc = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("cupsd"), NULL, NULL);
1940
1941 if (sc)
1942 {
1943 /*
1944 * Get the computer name from the dynamic store...
1945 */
1946
1947 cupsdClearString(&DNSSDComputerName);
1948
1949 if ((nameRef = SCDynamicStoreCopyComputerName(sc, &nameEncoding)) != NULL)
1950 {
1951 if (CFStringGetCString(nameRef, nameBuffer, sizeof(nameBuffer),
1952 kCFStringEncodingUTF8))
1953 {
1954 cupsdLogMessage(CUPSD_LOG_DEBUG,
1955 "Dynamic store computer name is \"%s\".", nameBuffer);
1956 cupsdSetString(&DNSSDComputerName, nameBuffer);
1957 }
1958
1959 CFRelease(nameRef);
1960 }
1961
1962 if (!DNSSDComputerName)
1963 {
1964 /*
1965 * Use the ServerName instead...
1966 */
1967
1968 cupsdLogMessage(CUPSD_LOG_DEBUG,
1969 "Using ServerName \"%s\" as computer name.", ServerName);
1970 cupsdSetString(&DNSSDComputerName, ServerName);
1971 }
1972
1973 /*
1974 * Get the local hostname from the dynamic store...
1975 */
1976
1977 cupsdClearString(&DNSSDHostName);
1978
1979 if ((nameRef = SCDynamicStoreCopyLocalHostName(sc)) != NULL)
1980 {
1981 if (CFStringGetCString(nameRef, nameBuffer, sizeof(nameBuffer),
1982 kCFStringEncodingUTF8))
1983 {
1984 cupsdLogMessage(CUPSD_LOG_DEBUG,
1985 "Dynamic store host name is \"%s\".", nameBuffer);
1986 cupsdSetString(&DNSSDHostName, nameBuffer);
1987 }
1988
1989 CFRelease(nameRef);
1990 }
1991
1992 if (!DNSSDHostName)
1993 {
1994 /*
1995 * Use the ServerName instead...
1996 */
1997
1998 cupsdLogMessage(CUPSD_LOG_DEBUG,
1999 "Using ServerName \"%s\" as host name.", ServerName);
2000 cupsdSetString(&DNSSDHostName, ServerName);
2001 }
2002
2003 /*
2004 * Get any Back-to-My-Mac domains and add them as aliases...
2005 */
2006
2007 cupsdFreeAliases(DNSSDAlias);
2008 DNSSDAlias = NULL;
2009
2010 btmm = SCDynamicStoreCopyValue(sc, CFSTR("Setup:/Network/BackToMyMac"));
2011 if (btmm && CFGetTypeID(btmm) == CFDictionaryGetTypeID())
2012 {
2013 cupsdLogMessage(CUPSD_LOG_DEBUG, "%d Back to My Mac aliases to add.",
2014 (int)CFDictionaryGetCount(btmm));
2015 CFDictionaryApplyFunction(btmm, dnssdAddAlias, NULL);
2016 }
2017 else if (btmm)
2018 cupsdLogMessage(CUPSD_LOG_ERROR,
2019 "Bad Back to My Mac data in dynamic store!");
2020 else
2021 cupsdLogMessage(CUPSD_LOG_DEBUG, "No Back to My Mac aliases to add.");
2022
2023 if (btmm)
2024 CFRelease(btmm);
2025
2026 CFRelease(sc);
2027 }
2028 else
2029 #endif /* HAVE_COREFOUNDATION_H */
2030 {
2031 cupsdSetString(&DNSSDComputerName, ServerName);
2032 cupsdSetString(&DNSSDHostName, ServerName);
2033 }
2034
2035 /*
2036 * Then (re)register the web interface if enabled...
2037 */
2038
2039 if (BrowseWebIF)
2040 {
2041 if (DNSSDComputerName)
2042 snprintf(webif, sizeof(webif), "CUPS @ %s", DNSSDComputerName);
2043 else
2044 strlcpy(webif, "CUPS Web Interface", sizeof(webif));
2045
2046 if (WebIFRef)
2047 DNSServiceRefDeallocate(WebIFRef);
2048
2049 WebIFRef = DNSSDRef;
2050 if ((error = DNSServiceRegister(&WebIFRef,
2051 kDNSServiceFlagsShareConnection,
2052 0, webif, "_http._tcp", NULL,
2053 NULL, htons(DNSSDPort), 7,
2054 "\006path=/", dnssdRegisterCallback,
2055 NULL)) != kDNSServiceErr_NoError)
2056 cupsdLogMessage(CUPSD_LOG_ERROR,
2057 "DNS-SD web interface registration failed: %d", error);
2058 }
2059 }
2060 #endif /* HAVE_DNSSD */
2061
2062
2063 #ifdef HAVE_LDAP
2064 /*
2065 * 'cupsdUpdateLDAPBrowse()' - Scan for new printers via LDAP...
2066 */
2067
2068 void
2069 cupsdUpdateLDAPBrowse(void)
2070 {
2071 char uri[HTTP_MAX_URI], /* Printer URI */
2072 host[HTTP_MAX_URI], /* Hostname */
2073 resource[HTTP_MAX_URI], /* Resource path */
2074 location[1024], /* Printer location */
2075 info[1024], /* Printer information */
2076 make_model[1024], /* Printer make and model */
2077 type_num[30]; /* Printer type number */
2078 int type; /* Printer type */
2079 int rc; /* LDAP status */
2080 int limit; /* Size limit */
2081 LDAPMessage *res, /* LDAP search results */
2082 *e; /* Current entry from search */
2083
2084 cupsdLogMessage(CUPSD_LOG_DEBUG2, "UpdateLDAPBrowse: %s", ServerName);
2085
2086 BrowseLDAPRefresh = time(NULL) + BrowseInterval;
2087
2088 /*
2089 * Reconnect if LDAP Handle is invalid...
2090 */
2091
2092 if (! BrowseLDAPHandle)
2093 {
2094 ldap_reconnect();
2095 return;
2096 }
2097
2098 /*
2099 * Search for cups printers in LDAP directory...
2100 */
2101
2102 rc = ldap_search_rec(BrowseLDAPHandle, BrowseLDAPDN, LDAP_SCOPE_SUBTREE,
2103 "(objectclass=cupsPrinter)", (char **)ldap_attrs, 0, &res);
2104
2105 /*
2106 * If ldap search was successfull then exit function
2107 * and temporary disable LDAP updates...
2108 */
2109
2110 if (rc != LDAP_SUCCESS)
2111 {
2112 if (BrowseLDAPUpdate && ((rc == LDAP_SERVER_DOWN) || (rc == LDAP_CONNECT_ERROR)))
2113 {
2114 BrowseLDAPUpdate = FALSE;
2115 cupsdLogMessage(CUPSD_LOG_INFO,
2116 "LDAP update temporary disabled");
2117 }
2118 return;
2119 }
2120
2121 /*
2122 * If LDAP updates were disabled, we will reenable them...
2123 */
2124
2125 if (! BrowseLDAPUpdate)
2126 {
2127 BrowseLDAPUpdate = TRUE;
2128 cupsdLogMessage(CUPSD_LOG_INFO,
2129 "LDAP update enabled");
2130 }
2131
2132 /*
2133 * Count LDAP entries and return if no entry exist...
2134 */
2135
2136 limit = ldap_count_entries(BrowseLDAPHandle, res);
2137 cupsdLogMessage(CUPSD_LOG_DEBUG2, "LDAP search returned %d entries", limit);
2138 if (limit < 1)
2139 {
2140 ldap_freeres(res);
2141 return;
2142 }
2143
2144 /*
2145 * Loop through the available printers...
2146 */
2147
2148 for (e = ldap_first_entry(BrowseLDAPHandle, res);
2149 e;
2150 e = ldap_next_entry(BrowseLDAPHandle, e))
2151 {
2152 /*
2153 * Get the required values from this entry...
2154 */
2155
2156 if (ldap_getval_firststring(BrowseLDAPHandle, e,
2157 "printerDescription", info, sizeof(info)) == -1)
2158 continue;
2159
2160 if (ldap_getval_firststring(BrowseLDAPHandle, e,
2161 "printerLocation", location, sizeof(location)) == -1)
2162 continue;
2163
2164 if (ldap_getval_firststring(BrowseLDAPHandle, e,
2165 "printerMakeAndModel", make_model, sizeof(make_model)) == -1)
2166 continue;
2167
2168 if (ldap_getval_firststring(BrowseLDAPHandle, e,
2169 "printerType", type_num, sizeof(type_num)) == -1)
2170 continue;
2171
2172 type = atoi(type_num);
2173
2174 if (ldap_getval_firststring(BrowseLDAPHandle, e,
2175 "printerURI", uri, sizeof(uri)) == -1)
2176 continue;
2177
2178 /*
2179 * Process the entry as browse data...
2180 */
2181
2182 if (!is_local_queue(uri, host, sizeof(host), resource, sizeof(resource)))
2183 process_browse_data(uri, host, resource, type, IPP_PRINTER_IDLE,
2184 location, info, make_model, 0, NULL);
2185
2186 }
2187
2188 ldap_freeres(res);
2189 }
2190 #endif /* HAVE_LDAP */
2191
2192
2193 #ifdef HAVE_LIBSLP
2194 /*
2195 * 'cupsdUpdateSLPBrowse()' - Get browsing information via SLP.
2196 */
2197
2198 void
2199 cupsdUpdateSLPBrowse(void)
2200 {
2201 slpsrvurl_t *s, /* Temporary list of service URLs */
2202 *next; /* Next service in list */
2203 cupsd_printer_t p; /* Printer information */
2204 const char *uri; /* Pointer to printer URI */
2205 char host[HTTP_MAX_URI], /* Host portion of URI */
2206 resource[HTTP_MAX_URI]; /* Resource portion of URI */
2207
2208
2209 /*
2210 * Reset the refresh time...
2211 */
2212
2213 BrowseSLPRefresh = time(NULL) + BrowseInterval;
2214
2215 /*
2216 * Poll for remote printers using SLP...
2217 */
2218
2219 s = NULL;
2220
2221 SLPFindSrvs(BrowseSLPHandle, SLP_CUPS_SRVTYPE, "", "",
2222 slp_url_callback, &s);
2223
2224 /*
2225 * Loop through the list of available printers...
2226 */
2227
2228 for (; s; s = next)
2229 {
2230 /*
2231 * Save the "next" pointer...
2232 */
2233
2234 next = s->next;
2235
2236 /*
2237 * Load a cupsd_printer_t structure with the SLP service attributes...
2238 */
2239
2240 SLPFindAttrs(BrowseSLPHandle, s->url, "", "", slp_attr_callback, &p);
2241
2242 /*
2243 * Process this printer entry...
2244 */
2245
2246 uri = s->url + SLP_CUPS_SRVLEN + 1;
2247
2248 if (!strncmp(uri, "http://", 7) || !strncmp(uri, "ipp://", 6))
2249 {
2250 /*
2251 * Pull the URI apart to see if this is a local or remote printer...
2252 */
2253
2254 if (!is_local_queue(uri, host, sizeof(host), resource, sizeof(resource)))
2255 process_browse_data(uri, host, resource, p.type, IPP_PRINTER_IDLE,
2256 p.location, p.info, p.make_model, 0, NULL);
2257 }
2258
2259 /*
2260 * Free this listing...
2261 */
2262
2263 cupsdClearString(&p.info);
2264 cupsdClearString(&p.location);
2265 cupsdClearString(&p.make_model);
2266
2267 free(s);
2268 }
2269 }
2270 #endif /* HAVE_LIBSLP */
2271
2272
2273 /*
2274 * 'dequote()' - Remote quotes from a string.
2275 */
2276
2277 static char * /* O - Dequoted string */
2278 dequote(char *d, /* I - Destination string */
2279 const char *s, /* I - Source string */
2280 int dlen) /* I - Destination length */
2281 {
2282 char *dptr; /* Pointer into destination */
2283
2284
2285 if (s)
2286 {
2287 for (dptr = d, dlen --; *s && dlen > 0; s ++)
2288 if (*s != '\"')
2289 {
2290 *dptr++ = *s;
2291 dlen --;
2292 }
2293
2294 *dptr = '\0';
2295 }
2296 else
2297 *d = '\0';
2298
2299 return (d);
2300 }
2301
2302
2303 #ifdef HAVE_DNSSD
2304 # ifdef HAVE_COREFOUNDATION
2305 /*
2306 * 'dnssdAddAlias()' - Add a DNS-SD alias name.
2307 */
2308
2309 static void
2310 dnssdAddAlias(const void *key, /* I - Key */
2311 const void *value, /* I - Value (domain) */
2312 void *context) /* I - Unused */
2313 {
2314 char valueStr[1024], /* Domain string */
2315 hostname[1024]; /* Complete hostname */
2316
2317
2318 (void)context;
2319
2320 if (CFGetTypeID((CFStringRef)value) == CFStringGetTypeID() &&
2321 CFStringGetCString((CFStringRef)value, valueStr, sizeof(valueStr),
2322 kCFStringEncodingUTF8))
2323 {
2324 snprintf(hostname, sizeof(hostname), "%s.%s", DNSSDHostName, valueStr);
2325 if (!DNSSDAlias)
2326 DNSSDAlias = cupsArrayNew(NULL, NULL);
2327
2328 cupsdAddAlias(DNSSDAlias, hostname);
2329 cupsdLogMessage(CUPSD_LOG_DEBUG, "Added Back to My Mac ServerAlias %s",
2330 hostname);
2331 }
2332 else
2333 cupsdLogMessage(CUPSD_LOG_ERROR,
2334 "Bad Back to My Mac domain in dynamic store!");
2335 }
2336 # endif /* HAVE_COREFOUNDATION */
2337
2338
2339 /*
2340 * 'dnssdBuildTxtRecord()' - Build a TXT record from printer info.
2341 */
2342
2343 static char * /* O - TXT record */
2344 dnssdBuildTxtRecord(
2345 int *txt_len, /* O - TXT record length */
2346 cupsd_printer_t *p, /* I - Printer information */
2347 int for_lpd) /* I - 1 = LPD, 0 = IPP */
2348 {
2349 int i; /* Looping var */
2350 char adminurl_str[256], /* URL for the admin page */
2351 type_str[32], /* Type to string buffer */
2352 state_str[32], /* State to string buffer */
2353 rp_str[1024], /* Queue name string buffer */
2354 air_str[1024], /* auth-info-required string buffer */
2355 *keyvalue[32][2]; /* Table of key/value pairs */
2356
2357
2358 /*
2359 * Load up the key value pairs...
2360 */
2361
2362 i = 0;
2363
2364 keyvalue[i ][0] = "txtvers";
2365 keyvalue[i++][1] = "1";
2366
2367 keyvalue[i ][0] = "qtotal";
2368 keyvalue[i++][1] = "1";
2369
2370 keyvalue[i ][0] = "rp";
2371 keyvalue[i++][1] = rp_str;
2372 if (for_lpd)
2373 strlcpy(rp_str, p->name, sizeof(rp_str));
2374 else
2375 snprintf(rp_str, sizeof(rp_str), "%s/%s",
2376 (p->type & CUPS_PRINTER_CLASS) ? "classes" : "printers", p->name);
2377
2378 keyvalue[i ][0] = "ty";
2379 keyvalue[i++][1] = p->make_model ? p->make_model : "Unknown";
2380
2381 httpAssembleURIf(HTTP_URI_CODING_ALL, adminurl_str, sizeof(adminurl_str),
2382 "http", NULL, DNSSDHostName, DNSSDPort, "/%s/%s",
2383 (p->type & CUPS_PRINTER_CLASS) ? "classes" : "printers",
2384 p->name);
2385 keyvalue[i ][0] = "adminurl";
2386 keyvalue[i++][1] = adminurl_str;
2387
2388 keyvalue[i ][0] = "note";
2389 keyvalue[i++][1] = p->location ? p->location : "";
2390
2391 keyvalue[i ][0] = "priority";
2392 keyvalue[i++][1] = for_lpd ? "100" : "0";
2393
2394 keyvalue[i ][0] = "product";
2395 keyvalue[i++][1] = p->product ? p->product : "Unknown";
2396
2397 snprintf(type_str, sizeof(type_str), "0x%X", p->type | CUPS_PRINTER_REMOTE);
2398 snprintf(state_str, sizeof(state_str), "%d", p->state);
2399
2400 keyvalue[i ][0] = "printer-state";
2401 keyvalue[i++][1] = state_str;
2402
2403 keyvalue[i ][0] = "printer-type";
2404 keyvalue[i++][1] = type_str;
2405
2406 keyvalue[i ][0] = "Transparent";
2407 keyvalue[i++][1] = "T";
2408
2409 keyvalue[i ][0] = "Binary";
2410 keyvalue[i++][1] = "T";
2411
2412 keyvalue[i ][0] = "Fax";
2413 keyvalue[i++][1] = (p->type & CUPS_PRINTER_FAX) ? "T" : "F";
2414
2415 keyvalue[i ][0] = "Color";
2416 keyvalue[i++][1] = (p->type & CUPS_PRINTER_COLOR) ? "T" : "F";
2417
2418 keyvalue[i ][0] = "Duplex";
2419 keyvalue[i++][1] = (p->type & CUPS_PRINTER_DUPLEX) ? "T" : "F";
2420
2421 keyvalue[i ][0] = "Staple";
2422 keyvalue[i++][1] = (p->type & CUPS_PRINTER_STAPLE) ? "T" : "F";
2423
2424 keyvalue[i ][0] = "Copies";
2425 keyvalue[i++][1] = (p->type & CUPS_PRINTER_COPIES) ? "T" : "F";
2426
2427 keyvalue[i ][0] = "Collate";
2428 keyvalue[i++][1] = (p->type & CUPS_PRINTER_COLLATE) ? "T" : "F";
2429
2430 keyvalue[i ][0] = "Punch";
2431 keyvalue[i++][1] = (p->type & CUPS_PRINTER_PUNCH) ? "T" : "F";
2432
2433 keyvalue[i ][0] = "Bind";
2434 keyvalue[i++][1] = (p->type & CUPS_PRINTER_BIND) ? "T" : "F";
2435
2436 keyvalue[i ][0] = "Sort";
2437 keyvalue[i++][1] = (p->type & CUPS_PRINTER_SORT) ? "T" : "F";
2438
2439 keyvalue[i ][0] = "Scan";
2440 keyvalue[i++][1] = (p->type & CUPS_PRINTER_MFP) ? "T" : "F";
2441
2442 keyvalue[i ][0] = "pdl";
2443 keyvalue[i++][1] = p->pdl ? p->pdl : "application/postscript";
2444
2445 if (get_auth_info_required(p, air_str, sizeof(air_str)))
2446 {
2447 keyvalue[i ][0] = "air";
2448 keyvalue[i++][1] = air_str;
2449 }
2450
2451 /*
2452 * Then pack them into a proper txt record...
2453 */
2454
2455 return (dnssdPackTxtRecord(txt_len, keyvalue, i));
2456 }
2457
2458
2459 /*
2460 * 'dnssdComparePrinters()' - Compare the registered names of two printers.
2461 */
2462
2463 static int /* O - Result of comparison */
2464 dnssdComparePrinters(cupsd_printer_t *a,/* I - First printer */
2465 cupsd_printer_t *b)/* I - Second printer */
2466 {
2467 return (strcasecmp(a->reg_name, b->reg_name));
2468 }
2469
2470
2471 /*
2472 * 'dnssdDeregisterPrinter()' - Stop sending broadcast information for a
2473 * printer.
2474 */
2475
2476 static void
2477 dnssdDeregisterPrinter(
2478 cupsd_printer_t *p) /* I - Printer */
2479 {
2480 cupsdLogMessage(CUPSD_LOG_DEBUG2, "dnssdDeregisterPrinter(%s)", p->name);
2481
2482 /*
2483 * Closing the socket deregisters the service
2484 */
2485
2486 if (p->ipp_ref)
2487 {
2488 DNSServiceRefDeallocate(p->ipp_ref);
2489 p->ipp_ref = NULL;
2490 }
2491
2492 if (p->ipp_txt)
2493 {
2494 /*
2495 * p->ipp_txt is malloc'd, not _cupsStrAlloc'd...
2496 */
2497
2498 free(p->ipp_txt);
2499 p->ipp_txt = NULL;
2500 }
2501
2502 if (p->printer_ref)
2503 {
2504 DNSServiceRefDeallocate(p->printer_ref);
2505 p->printer_ref = NULL;
2506 }
2507
2508 if (p->printer_txt)
2509 {
2510 /*
2511 * p->printer_txt is malloc'd, not _cupsStrAlloc'd...
2512 */
2513
2514 free(p->printer_txt);
2515 p->printer_txt = NULL;
2516 }
2517
2518 /*
2519 * Remove the printer from the array of DNS-SD printers, then clear the
2520 * registered name...
2521 */
2522
2523 cupsArrayRemove(DNSSDPrinters, p);
2524 cupsdClearString(&p->reg_name);
2525 }
2526
2527
2528 /*
2529 * 'dnssdPackTxtRecord()' - Pack an array of key/value pairs into the
2530 * TXT record format.
2531 */
2532
2533 static char * /* O - TXT record */
2534 dnssdPackTxtRecord(int *txt_len, /* O - TXT record length */
2535 char *keyvalue[][2], /* I - Table of key value pairs */
2536 int count) /* I - Items in table */
2537 {
2538 int i; /* Looping var */
2539 int length; /* Length of TXT record */
2540 int length2; /* Length of value */
2541 char *txtRecord; /* TXT record buffer */
2542 char *cursor; /* Looping pointer */
2543
2544
2545 /*
2546 * Calculate the buffer size
2547 */
2548
2549 for (length = i = 0; i < count; i++)
2550 length += 1 + strlen(keyvalue[i][0]) +
2551 (keyvalue[i][1] ? 1 + strlen(keyvalue[i][1]) : 0);
2552
2553 /*
2554 * Allocate and fill it
2555 */
2556
2557 txtRecord = malloc(length);
2558 if (txtRecord)
2559 {
2560 *txt_len = length;
2561
2562 for (cursor = txtRecord, i = 0; i < count; i++)
2563 {
2564 /*
2565 * Drop in the p-string style length byte followed by the data
2566 */
2567
2568 length = strlen(keyvalue[i][0]);
2569 length2 = keyvalue[i][1] ? 1 + strlen(keyvalue[i][1]) : 0;
2570
2571 *cursor++ = (unsigned char)(length + length2);
2572
2573 memcpy(cursor, keyvalue[i][0], length);
2574 cursor += length;
2575
2576 if (length2)
2577 {
2578 length2 --;
2579 *cursor++ = '=';
2580 memcpy(cursor, keyvalue[i][1], length2);
2581 cursor += length2;
2582 }
2583 }
2584 }
2585
2586 return (txtRecord);
2587 }
2588
2589
2590 /*
2591 * 'dnssdRegisterCallback()' - DNSServiceRegister callback.
2592 */
2593
2594 static void
2595 dnssdRegisterCallback(
2596 DNSServiceRef sdRef, /* I - DNS Service reference */
2597 DNSServiceFlags flags, /* I - Reserved for future use */
2598 DNSServiceErrorType errorCode, /* I - Error code */
2599 const char *name, /* I - Service name */
2600 const char *regtype, /* I - Service type */
2601 const char *domain, /* I - Domain. ".local" for now */
2602 void *context) /* I - User-defined context */
2603 {
2604 cupsd_printer_t *p = (cupsd_printer_t *)context;
2605 /* Current printer */
2606
2607
2608 cupsdLogMessage(CUPSD_LOG_DEBUG2, "dnssdRegisterCallback(%s, %s) for %s (%s)",
2609 name, regtype, p ? p->name : "Web Interface",
2610 p ? (p->reg_name ? p->reg_name : "(null)") : "NA");
2611
2612 if (errorCode)
2613 {
2614 cupsdLogMessage(CUPSD_LOG_ERROR,
2615 "DNSServiceRegister failed with error %d", (int)errorCode);
2616 return;
2617 }
2618 else if (p && (!p->reg_name || strcasecmp(name, p->reg_name)))
2619 {
2620 cupsdLogMessage(CUPSD_LOG_INFO, "Using service name \"%s\" for \"%s\"",
2621 name, p->name);
2622
2623 cupsArrayRemove(DNSSDPrinters, p);
2624 cupsdSetString(&p->reg_name, name);
2625 cupsArrayAdd(DNSSDPrinters, p);
2626
2627 LastEvent |= CUPSD_EVENT_PRINTER_MODIFIED;
2628 }
2629 }
2630
2631
2632 /*
2633 * 'dnssdRegisterPrinter()' - Start sending broadcast information for a printer
2634 * or update the broadcast contents.
2635 */
2636
2637 static void
2638 dnssdRegisterPrinter(cupsd_printer_t *p)/* I - Printer */
2639 {
2640 DNSServiceErrorType se; /* dnssd errors */
2641 char *ipp_txt, /* IPP TXT record buffer */
2642 *printer_txt, /* LPD TXT record buffer */
2643 name[1024], /* Service name */
2644 *nameptr; /* Pointer into name */
2645 int ipp_len, /* IPP TXT record length */
2646 printer_len; /* LPD TXT record length */
2647 const char *regtype; /* Registration type */
2648
2649
2650 cupsdLogMessage(CUPSD_LOG_DEBUG2, "dnssdRegisterPrinter(%s) %s", p->name,
2651 !p->ipp_ref ? "new" : "update");
2652
2653 /*
2654 * If per-printer sharing was just disabled make sure we're not
2655 * registered before returning.
2656 */
2657
2658 if (!p->shared)
2659 {
2660 dnssdDeregisterPrinter(p);
2661 return;
2662 }
2663
2664 /*
2665 * The registered name takes the form of "<printer-info> @ <computer name>"...
2666 */
2667
2668 if (p->info && strlen(p->info) > 0)
2669 {
2670 if (DNSSDComputerName)
2671 snprintf(name, sizeof(name), "%s @ %s", p->info, DNSSDComputerName);
2672 else
2673 strlcpy(name, p->info, sizeof(name));
2674 }
2675 else if (DNSSDComputerName)
2676 snprintf(name, sizeof(name), "%s @ %s", p->name, DNSSDComputerName);
2677 else
2678 strlcpy(name, p->name, sizeof(name));
2679
2680 /*
2681 * If an existing printer was renamed, unregister it and start over...
2682 */
2683
2684 if (p->reg_name && strcmp(p->reg_name, name))
2685 dnssdDeregisterPrinter(p);
2686
2687 if (!p->reg_name)
2688 {
2689 cupsdSetString(&p->reg_name, name);
2690 cupsArrayAdd(DNSSDPrinters, p);
2691 }
2692
2693 /*
2694 * Register IPP and (optionally) LPD...
2695 */
2696
2697 ipp_len = 0; /* anti-compiler-warning-code */
2698 ipp_txt = dnssdBuildTxtRecord(&ipp_len, p, 0);
2699
2700 if (p->ipp_ref &&
2701 (ipp_len != p->ipp_len || memcmp(ipp_txt, p->ipp_txt, ipp_len)))
2702 {
2703 /*
2704 * Update the existing registration...
2705 */
2706
2707 /* A TTL of 0 means use record's original value (Radar 3176248) */
2708 if ((se = DNSServiceUpdateRecord(p->ipp_ref, NULL, 0, ipp_len, ipp_txt,
2709 0)) == kDNSServiceErr_NoError)
2710 {
2711 if (p->ipp_txt)
2712 free(p->ipp_txt);
2713
2714 p->ipp_txt = ipp_txt;
2715 p->ipp_len = ipp_len;
2716 ipp_txt = NULL;
2717 }
2718 else
2719 {
2720 /*
2721 * Failed to update record, lets close this reference and move on...
2722 */
2723
2724 cupsdLogMessage(CUPSD_LOG_ERROR,
2725 "Unable to update IPP DNS-SD record for %s - %d", p->name,
2726 se);
2727
2728 DNSServiceRefDeallocate(p->ipp_ref);
2729 p->ipp_ref = NULL;
2730 }
2731 }
2732
2733 if (!p->ipp_ref)
2734 {
2735 /*
2736 * Initial registration. Use the _fax subtype for fax queues...
2737 */
2738
2739 regtype = (p->type & CUPS_PRINTER_FAX) ? "_fax-ipp._tcp" :
2740 "_ipp._tcp,_cups";
2741
2742 cupsdLogMessage(CUPSD_LOG_DEBUG,
2743 "Registering DNS-SD printer %s with name \"%s\" and "
2744 "type \"%s\"", p->name, name, regtype);
2745
2746 /*
2747 * Register the queue, dropping characters as needed until we succeed...
2748 */
2749
2750 nameptr = name + strlen(name);
2751
2752 do
2753 {
2754 p->ipp_ref = DNSSDRef;
2755 if ((se = DNSServiceRegister(&p->ipp_ref, kDNSServiceFlagsShareConnection,
2756 0, name, regtype, NULL, NULL,
2757 htons(DNSSDPort), ipp_len, ipp_txt,
2758 dnssdRegisterCallback,
2759 p)) == kDNSServiceErr_BadParam)
2760 {
2761 /*
2762 * Name is too long, drop trailing characters, taking into account
2763 * UTF-8 encoding...
2764 */
2765
2766 nameptr --;
2767
2768 while (nameptr > name && (*nameptr & 0xc0) == 0x80)
2769 nameptr --;
2770
2771 if (nameptr > name)
2772 *nameptr = '\0';
2773 }
2774 }
2775 while (se == kDNSServiceErr_BadParam && nameptr > name);
2776
2777 if (se == kDNSServiceErr_NoError)
2778 {
2779 p->ipp_txt = ipp_txt;
2780 p->ipp_len = ipp_len;
2781 ipp_txt = NULL;
2782 }
2783 else
2784 cupsdLogMessage(CUPSD_LOG_WARN,
2785 "DNS-SD IPP registration of \"%s\" failed: %d",
2786 p->name, se);
2787 }
2788
2789 if (ipp_txt)
2790 free(ipp_txt);
2791
2792 if (BrowseLocalProtocols & BROWSE_LPD)
2793 {
2794 printer_len = 0; /* anti-compiler-warning-code */
2795 printer_txt = dnssdBuildTxtRecord(&printer_len, p, 1);
2796
2797 if (p->printer_ref &&
2798 (printer_len != p->printer_len ||
2799 memcmp(printer_txt, p->printer_txt, printer_len)))
2800 {
2801 /*
2802 * Update the existing registration...
2803 */
2804
2805 /* A TTL of 0 means use record's original value (Radar 3176248) */
2806 if ((se = DNSServiceUpdateRecord(p->printer_ref, NULL, 0, printer_len,
2807 printer_txt,
2808 0)) == kDNSServiceErr_NoError)
2809 {
2810 if (p->printer_txt)
2811 free(p->printer_txt);
2812
2813 p->printer_txt = printer_txt;
2814 p->printer_len = printer_len;
2815 printer_txt = NULL;
2816 }
2817 else
2818 {
2819 /*
2820 * Failed to update record, lets close this reference and move on...
2821 */
2822
2823 cupsdLogMessage(CUPSD_LOG_ERROR,
2824 "Unable to update LPD DNS-SD record for %s - %d",
2825 p->name, se);
2826
2827 DNSServiceRefDeallocate(p->printer_ref);
2828 p->printer_ref = NULL;
2829 }
2830 }
2831
2832 if (!p->printer_ref)
2833 {
2834 /*
2835 * Initial registration...
2836 */
2837
2838 cupsdLogMessage(CUPSD_LOG_DEBUG,
2839 "Registering DNS-SD printer %s with name \"%s\" and "
2840 "type \"_printer._tcp\"", p->name, name);
2841
2842 p->printer_ref = DNSSDRef;
2843 if ((se = DNSServiceRegister(&p->printer_ref,
2844 kDNSServiceFlagsShareConnection,
2845 0, name, "_printer._tcp", NULL, NULL,
2846 htons(515), printer_len, printer_txt,
2847 dnssdRegisterCallback,
2848 p)) == kDNSServiceErr_NoError)
2849 {
2850 p->printer_txt = printer_txt;
2851 p->printer_len = printer_len;
2852 printer_txt = NULL;
2853 }
2854 else
2855 cupsdLogMessage(CUPSD_LOG_WARN,
2856 "DNS-SD LPD registration of \"%s\" failed: %d",
2857 p->name, se);
2858 }
2859
2860 if (printer_txt)
2861 free(printer_txt);
2862 }
2863 }
2864
2865
2866 /*
2867 * 'dnssdStop()' - Stop all DNS-SD registrations.
2868 */
2869
2870 static void
2871 dnssdStop(void)
2872 {
2873 cupsd_printer_t *p; /* Current printer */
2874
2875
2876 /*
2877 * De-register the individual printers
2878 */
2879
2880 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
2881 p;
2882 p = (cupsd_printer_t *)cupsArrayNext(Printers))
2883 dnssdDeregisterPrinter(p);
2884
2885 /*
2886 * Shutdown the rest of the service refs...
2887 */
2888
2889 if (WebIFRef)
2890 {
2891 DNSServiceRefDeallocate(WebIFRef);
2892 WebIFRef = NULL;
2893 }
2894
2895 if (RemoteRef)
2896 {
2897 DNSServiceRefDeallocate(RemoteRef);
2898 RemoteRef = NULL;
2899 }
2900
2901 cupsdRemoveSelect(DNSServiceRefSockFD(DNSSDRef));
2902
2903 DNSServiceRefDeallocate(DNSSDRef);
2904 DNSSDRef = NULL;
2905
2906 cupsArrayDelete(DNSSDPrinters);
2907 DNSSDPrinters = NULL;
2908
2909 DNSSDPort = 0;
2910 }
2911
2912
2913 /*
2914 * 'dnssdUpdate()' - Handle DNS-SD queries.
2915 */
2916
2917 static void
2918 dnssdUpdate(void)
2919 {
2920 DNSServiceErrorType sdErr; /* Service discovery error */
2921
2922
2923 if ((sdErr = DNSServiceProcessResult(DNSSDRef)) != kDNSServiceErr_NoError)
2924 {
2925 cupsdLogMessage(CUPSD_LOG_ERROR,
2926 "DNS Service Discovery registration error %d!",
2927 sdErr);
2928 dnssdStop();
2929 }
2930 }
2931 #endif /* HAVE_DNSSD */
2932
2933
2934 /*
2935 * 'get_auth_info_required()' - Get the auth-info-required value to advertise.
2936 */
2937
2938 static char * /* O - String or NULL if none */
2939 get_auth_info_required(
2940 cupsd_printer_t *p, /* I - Printer */
2941 char *buffer, /* I - Value buffer */
2942 size_t bufsize) /* I - Size of value buffer */
2943 {
2944 cupsd_location_t *auth; /* Pointer to authentication element */
2945 char resource[1024]; /* Printer/class resource path */
2946
2947
2948 /*
2949 * If auth-info-required is set for this printer, return that...
2950 */
2951
2952 if (p->num_auth_info_required > 0 && strcmp(p->auth_info_required[0], "none"))
2953 {
2954 int i; /* Looping var */
2955 char *bufptr; /* Pointer into buffer */
2956
2957 for (i = 0, bufptr = buffer; i < p->num_auth_info_required; i ++)
2958 {
2959 if (bufptr >= (buffer + bufsize - 2))
2960 break;
2961
2962 if (i)
2963 *bufptr++ = ',';
2964
2965 strlcpy(bufptr, p->auth_info_required[i], bufsize - (bufptr - buffer));
2966 bufptr += strlen(bufptr);
2967 }
2968
2969 return (buffer);
2970 }
2971
2972 /*
2973 * Figure out the authentication data requirements to advertise...
2974 */
2975
2976 if (p->type & CUPS_PRINTER_CLASS)
2977 snprintf(resource, sizeof(resource), "/classes/%s", p->name);
2978 else
2979 snprintf(resource, sizeof(resource), "/printers/%s", p->name);
2980
2981 if ((auth = cupsdFindBest(resource, HTTP_POST)) == NULL ||
2982 auth->type == CUPSD_AUTH_NONE)
2983 auth = cupsdFindPolicyOp(p->op_policy_ptr, IPP_PRINT_JOB);
2984
2985 if (auth)
2986 {
2987 int auth_type; /* Authentication type */
2988
2989 if ((auth_type = auth->type) == CUPSD_AUTH_DEFAULT)
2990 auth_type = DefaultAuthType;
2991
2992 switch (auth_type)
2993 {
2994 case CUPSD_AUTH_NONE :
2995 return (NULL);
2996
2997 case CUPSD_AUTH_NEGOTIATE :
2998 strlcpy(buffer, "negotiate", bufsize);
2999 break;
3000
3001 default :
3002 strlcpy(buffer, "username,password", bufsize);
3003 break;
3004 }
3005
3006 return (buffer);
3007 }
3008
3009 return (NULL);
3010 }
3011
3012
3013 #ifdef __APPLE__
3014 /*
3015 * 'get_hostconfig()' - Get an /etc/hostconfig service setting.
3016 */
3017
3018 static int /* O - 1 for YES or AUTOMATIC, 0 for NO */
3019 get_hostconfig(const char *name) /* I - Name of service */
3020 {
3021 cups_file_t *fp; /* Hostconfig file */
3022 char line[1024], /* Line from file */
3023 *ptr; /* Pointer to value */
3024 int state = 1; /* State of service */
3025
3026
3027 /*
3028 * Try opening the /etc/hostconfig file; if we can't open it, assume that
3029 * the service is enabled/auto.
3030 */
3031
3032 if ((fp = cupsFileOpen("/etc/hostconfig", "r")) != NULL)
3033 {
3034 /*
3035 * Read lines from the file until we find the service...
3036 */
3037
3038 while (cupsFileGets(fp, line, sizeof(line)))
3039 {
3040 if (line[0] == '#' || (ptr = strchr(line, '=')) == NULL)
3041 continue;
3042
3043 *ptr++ = '\0';
3044
3045 if (!strcasecmp(line, name))
3046 {
3047 /*
3048 * Found the service, see if it is set to "-NO-"...
3049 */
3050
3051 if (!strncasecmp(ptr, "-NO-", 4))
3052 state = 0;
3053 break;
3054 }
3055 }
3056
3057 cupsFileClose(fp);
3058 }
3059
3060 return (state);
3061 }
3062 #endif /* __APPLE__ */
3063
3064
3065 /*
3066 * 'is_local_queue()' - Determine whether the URI points at a local queue.
3067 */
3068
3069 static int /* O - 1 = local, 0 = remote, -1 = bad URI */
3070 is_local_queue(const char *uri, /* I - Printer URI */
3071 char *host, /* O - Host string */
3072 int hostlen, /* I - Length of host buffer */
3073 char *resource, /* O - Resource string */
3074 int resourcelen) /* I - Length of resource buffer */
3075 {
3076 char scheme[32], /* Scheme portion of URI */
3077 username[HTTP_MAX_URI]; /* Username portion of URI */
3078 int port; /* Port portion of URI */
3079 cupsd_netif_t *iface; /* Network interface */
3080
3081
3082 /*
3083 * Pull the URI apart to see if this is a local or remote printer...
3084 */
3085
3086 if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme),
3087 username, sizeof(username), host, hostlen, &port,
3088 resource, resourcelen) < HTTP_URI_OK)
3089 return (-1);
3090
3091 DEBUG_printf(("host=\"%s\", ServerName=\"%s\"\n", host, ServerName));
3092
3093 /*
3094 * Check for local server addresses...
3095 */
3096
3097 if (!strcasecmp(host, ServerName) && port == LocalPort)
3098 return (1);
3099
3100 cupsdNetIFUpdate();
3101
3102 for (iface = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
3103 iface;
3104 iface = (cupsd_netif_t *)cupsArrayNext(NetIFList))
3105 if (!strcasecmp(host, iface->hostname) && port == iface->port)
3106 return (1);
3107
3108 /*
3109 * If we get here, the printer is remote...
3110 */
3111
3112 return (0);
3113 }
3114
3115
3116 /*
3117 * 'process_browse_data()' - Process new browse data.
3118 */
3119
3120 static void
3121 process_browse_data(
3122 const char *uri, /* I - URI of printer/class */
3123 const char *host, /* I - Hostname */
3124 const char *resource, /* I - Resource path */
3125 cups_ptype_t type, /* I - Printer type */
3126 ipp_pstate_t state, /* I - Printer state */
3127 const char *location, /* I - Printer location */
3128 const char *info, /* I - Printer information */
3129 const char *make_model, /* I - Printer make and model */
3130 int num_attrs, /* I - Number of attributes */
3131 cups_option_t *attrs) /* I - Attributes */
3132 {
3133 int i; /* Looping var */
3134 int update; /* Update printer attributes? */
3135 char finaluri[HTTP_MAX_URI], /* Final URI for printer */
3136 name[IPP_MAX_NAME], /* Name of printer */
3137 newname[IPP_MAX_NAME], /* New name of printer */
3138 *hptr, /* Pointer into hostname */
3139 *sptr; /* Pointer into ServerName */
3140 const char *shortname; /* Short queue name (queue) */
3141 char local_make_model[IPP_MAX_NAME];
3142 /* Local make and model */
3143 cupsd_printer_t *p; /* Printer information */
3144 const char *ipp_options, /* ipp-options value */
3145 *lease_duration; /* lease-duration value */
3146 int is_class; /* Is this queue a class? */
3147
3148
3149 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3150 "process_browse_data(uri=\"%s\", host=\"%s\", "
3151 "resource=\"%s\", type=%x, state=%d, location=\"%s\", "
3152 "info=\"%s\", make_model=\"%s\", num_attrs=%d, attrs=%p)",
3153 uri, host, resource, type, state,
3154 location ? location : "(nil)", info ? info : "(nil)",
3155 make_model ? make_model : "(nil)", num_attrs, attrs);
3156
3157 /*
3158 * Determine if the URI contains any illegal characters in it...
3159 */
3160
3161 if (strncmp(uri, "ipp://", 6) || !host[0] ||
3162 (strncmp(resource, "/printers/", 10) &&
3163 strncmp(resource, "/classes/", 9)))
3164 {
3165 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad printer URI in browse data: %s", uri);
3166 return;
3167 }
3168
3169 if (strchr(resource, '?') ||
3170 (!strncmp(resource, "/printers/", 10) && strchr(resource + 10, '/')) ||
3171 (!strncmp(resource, "/classes/", 9) && strchr(resource + 9, '/')))
3172 {
3173 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad resource in browse data: %s",
3174 resource);
3175 return;
3176 }
3177
3178 /*
3179 * OK, this isn't a local printer; add any remote options...
3180 */
3181
3182 ipp_options = cupsGetOption("ipp-options", num_attrs, attrs);
3183
3184 if (BrowseRemoteOptions)
3185 {
3186 if (BrowseRemoteOptions[0] == '?')
3187 {
3188 /*
3189 * Override server-supplied options...
3190 */
3191
3192 snprintf(finaluri, sizeof(finaluri), "%s%s", uri, BrowseRemoteOptions);
3193 }
3194 else if (ipp_options)
3195 {
3196 /*
3197 * Combine the server and local options...
3198 */
3199
3200 snprintf(finaluri, sizeof(finaluri), "%s?%s+%s", uri, ipp_options,
3201 BrowseRemoteOptions);
3202 }
3203 else
3204 {
3205 /*
3206 * Just use the local options...
3207 */
3208
3209 snprintf(finaluri, sizeof(finaluri), "%s?%s", uri, BrowseRemoteOptions);
3210 }
3211
3212 uri = finaluri;
3213 }
3214 else if (ipp_options)
3215 {
3216 /*
3217 * Just use the server-supplied options...
3218 */
3219
3220 snprintf(finaluri, sizeof(finaluri), "%s?%s", uri, ipp_options);
3221 uri = finaluri;
3222 }
3223
3224 /*
3225 * See if we already have it listed in the Printers list, and add it if not...
3226 */
3227
3228 type |= CUPS_PRINTER_REMOTE | CUPS_PRINTER_DISCOVERED;
3229 type &= ~CUPS_PRINTER_IMPLICIT;
3230 update = 0;
3231 hptr = strchr(host, '.');
3232 sptr = strchr(ServerName, '.');
3233 is_class = type & CUPS_PRINTER_CLASS;
3234
3235 if (!ServerNameIsIP && sptr != NULL && hptr != NULL)
3236 {
3237 /*
3238 * Strip the common domain name components...
3239 */
3240
3241 while (hptr != NULL)
3242 {
3243 if (!strcasecmp(hptr, sptr))
3244 {
3245 *hptr = '\0';
3246 break;
3247 }
3248 else
3249 hptr = strchr(hptr + 1, '.');
3250 }
3251 }
3252
3253 if (is_class)
3254 {
3255 /*
3256 * Remote destination is a class...
3257 */
3258
3259 if (!strncmp(resource, "/classes/", 9))
3260 snprintf(name, sizeof(name), "%s@%s", resource + 9, host);
3261 else
3262 return;
3263
3264 shortname = resource + 9;
3265 }
3266 else
3267 {
3268 /*
3269 * Remote destination is a printer...
3270 */
3271
3272 if (!strncmp(resource, "/printers/", 10))
3273 snprintf(name, sizeof(name), "%s@%s", resource + 10, host);
3274 else
3275 return;
3276
3277 shortname = resource + 10;
3278 }
3279
3280 if (hptr && !*hptr)
3281 *hptr = '.'; /* Resource FQDN */
3282
3283 if ((p = cupsdFindDest(name)) == NULL && BrowseShortNames)
3284 {
3285 /*
3286 * Long name doesn't exist, try short name...
3287 */
3288
3289 cupsdLogMessage(CUPSD_LOG_DEBUG, "process_browse_data: %s not found...",
3290 name);
3291
3292 if ((p = cupsdFindDest(shortname)) == NULL)
3293 {
3294 /*
3295 * Short name doesn't exist, use it for this shared queue.
3296 */
3297
3298 cupsdLogMessage(CUPSD_LOG_DEBUG2, "process_browse_data: %s not found...",
3299 shortname);
3300 strlcpy(name, shortname, sizeof(name));
3301 }
3302 else
3303 {
3304 /*
3305 * Short name exists...
3306 */
3307
3308 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3309 "process_browse_data: %s found, type=%x, hostname=%s...",
3310 shortname, p->type, p->hostname ? p->hostname : "(nil)");
3311
3312 if (p->type & CUPS_PRINTER_IMPLICIT)
3313 p = NULL; /* Don't replace implicit classes */
3314 else if (p->hostname && strcasecmp(p->hostname, host))
3315 {
3316 /*
3317 * Short name exists but is for a different host. If this is a remote
3318 * queue, rename it and use the long name...
3319 */
3320
3321 if (p->type & CUPS_PRINTER_REMOTE)
3322 {
3323 cupsdLogMessage(CUPSD_LOG_DEBUG,
3324 "Renamed remote %s \"%s\" to \"%s@%s\"...",
3325 is_class ? "class" : "printer", p->name, p->name,
3326 p->hostname);
3327 cupsdAddEvent(CUPSD_EVENT_PRINTER_DELETED, p, NULL,
3328 "%s \'%s\' deleted by directory services.",
3329 is_class ? "Class" : "Printer", p->name);
3330
3331 snprintf(newname, sizeof(newname), "%s@%s", p->name, p->hostname);
3332 cupsdRenamePrinter(p, newname);
3333
3334 cupsdAddEvent(CUPSD_EVENT_PRINTER_ADDED, p, NULL,
3335 "%s \'%s\' added by directory services.",
3336 is_class ? "Class" : "Printer", p->name);
3337 }
3338
3339 /*
3340 * Force creation with long name...
3341 */
3342
3343 p = NULL;
3344 }
3345 }
3346 }
3347 else if (p)
3348 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3349 "process_browse_data: %s found, type=%x, hostname=%s...",
3350 name, p->type, p->hostname ? p->hostname : "(nil)");
3351
3352 if (!p)
3353 {
3354 /*
3355 * Queue doesn't exist; add it...
3356 */
3357
3358 if (is_class)
3359 p = cupsdAddClass(name);
3360 else
3361 p = cupsdAddPrinter(name);
3362
3363 if (!p)
3364 return;
3365
3366 cupsdClearString(&(p->hostname));
3367
3368 cupsdLogMessage(CUPSD_LOG_DEBUG, "Added remote %s \"%s\"...",
3369 is_class ? "class" : "printer", name);
3370
3371 cupsdAddEvent(CUPSD_EVENT_PRINTER_ADDED, p, NULL,
3372 "%s \'%s\' added by directory services.",
3373 is_class ? "Class" : "Printer", name);
3374
3375 /*
3376 * Force the URI to point to the real server...
3377 */
3378
3379 p->type = type & ~CUPS_PRINTER_REJECTING;
3380 p->accepting = 1;
3381
3382 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP);
3383 }
3384
3385 if (!p->hostname)
3386 {
3387 /*
3388 * Hostname not set, so this must be a cached remote printer
3389 * that was created for a pending print job...
3390 */
3391
3392 cupsdSetString(&p->hostname, host);
3393 cupsdSetString(&p->uri, uri);
3394 cupsdSetString(&p->device_uri, uri);
3395 update = 1;
3396
3397 cupsdMarkDirty(CUPSD_DIRTY_REMOTE);
3398 }
3399
3400 /*
3401 * Update the state...
3402 */
3403
3404 p->state = state;
3405 p->browse_time = time(NULL);
3406
3407 if ((lease_duration = cupsGetOption("lease-duration", num_attrs,
3408 attrs)) != NULL)
3409 {
3410 /*
3411 * Grab the lease-duration for the browse data; anything less then 1
3412 * second or more than 1 week gets the default BrowseTimeout...
3413 */
3414
3415 i = atoi(lease_duration);
3416 if (i < 1 || i > 604800)
3417 i = BrowseTimeout;
3418
3419 p->browse_expire = p->browse_time + i;
3420 }
3421 else
3422 p->browse_expire = p->browse_time + BrowseTimeout;
3423
3424 if (type & CUPS_PRINTER_REJECTING)
3425 {
3426 type &= ~CUPS_PRINTER_REJECTING;
3427
3428 if (p->accepting)
3429 {
3430 update = 1;
3431 p->accepting = 0;
3432 }
3433 }
3434 else if (!p->accepting)
3435 {
3436 update = 1;
3437 p->accepting = 1;
3438 }
3439
3440 if (p->type != type)
3441 {
3442 p->type = type;
3443 update = 1;
3444 }
3445
3446 if (location && (!p->location || strcmp(p->location, location)))
3447 {
3448 cupsdSetString(&p->location, location);
3449 update = 1;
3450 }
3451
3452 if (info && (!p->info || strcmp(p->info, info)))
3453 {
3454 cupsdSetString(&p->info, info);
3455 update = 1;
3456
3457 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP | CUPSD_DIRTY_REMOTE);
3458 }
3459
3460 if (!make_model || !make_model[0])
3461 {
3462 if (is_class)
3463 snprintf(local_make_model, sizeof(local_make_model),
3464 "Remote Class on %s", host);
3465 else
3466 snprintf(local_make_model, sizeof(local_make_model),
3467 "Remote Printer on %s", host);
3468 }
3469 else
3470 snprintf(local_make_model, sizeof(local_make_model),
3471 "%s on %s", make_model, host);
3472
3473 if (!p->make_model || strcmp(p->make_model, local_make_model))
3474 {
3475 cupsdSetString(&p->make_model, local_make_model);
3476 update = 1;
3477 }
3478
3479 if (p->num_options)
3480 {
3481 if (!update && !(type & CUPS_PRINTER_DELETE))
3482 {
3483 /*
3484 * See if we need to update the attributes...
3485 */
3486
3487 if (p->num_options != num_attrs)
3488 update = 1;
3489 else
3490 {
3491 for (i = 0; i < num_attrs; i ++)
3492 if (strcmp(attrs[i].name, p->options[i].name) ||
3493 (!attrs[i].value != !p->options[i].value) ||
3494 (attrs[i].value && strcmp(attrs[i].value, p->options[i].value)))
3495 {
3496 update = 1;
3497 break;
3498 }
3499 }
3500 }
3501
3502 /*
3503 * Free the old options...
3504 */
3505
3506 cupsFreeOptions(p->num_options, p->options);
3507 }
3508
3509 p->num_options = num_attrs;
3510 p->options = attrs;
3511
3512 if (type & CUPS_PRINTER_DELETE)
3513 {
3514 cupsdAddEvent(CUPSD_EVENT_PRINTER_DELETED, p, NULL,
3515 "%s \'%s\' deleted by directory services.",
3516 is_class ? "Class" : "Printer", p->name);
3517
3518 cupsdExpireSubscriptions(p, NULL);
3519
3520 cupsdDeletePrinter(p, 1);
3521 cupsdUpdateImplicitClasses();
3522 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP | CUPSD_DIRTY_REMOTE);
3523 }
3524 else if (update)
3525 {
3526 cupsdSetPrinterAttrs(p);
3527 cupsdUpdateImplicitClasses();
3528 }
3529
3530 /*
3531 * See if we have a default printer... If not, make the first network
3532 * default printer the default.
3533 */
3534
3535 if (DefaultPrinter == NULL && Printers != NULL && UseNetworkDefault)
3536 {
3537 /*
3538 * Find the first network default printer and use it...
3539 */
3540
3541 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
3542 p;
3543 p = (cupsd_printer_t *)cupsArrayNext(Printers))
3544 if (p->type & CUPS_PRINTER_DEFAULT)
3545 {
3546 DefaultPrinter = p;
3547 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP | CUPSD_DIRTY_REMOTE);
3548 break;
3549 }
3550 }
3551
3552 /*
3553 * Do auto-classing if needed...
3554 */
3555
3556 process_implicit_classes();
3557 }
3558
3559
3560 /*
3561 * 'process_implicit_classes()' - Create/update implicit classes as needed.
3562 */
3563
3564 static void
3565 process_implicit_classes(void)
3566 {
3567 int i; /* Looping var */
3568 int update; /* Update printer attributes? */
3569 char name[IPP_MAX_NAME], /* Name of printer */
3570 *hptr; /* Pointer into hostname */
3571 cupsd_printer_t *p, /* Printer information */
3572 *pclass, /* Printer class */
3573 *first; /* First printer in class */
3574 int offset, /* Offset of name */
3575 len; /* Length of name */
3576
3577
3578 if (!ImplicitClasses || !Printers)
3579 return;
3580
3581 /*
3582 * Loop through all available printers and create classes as needed...
3583 */
3584
3585 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers), len = 0, offset = 0,
3586 update = 0, pclass = NULL, first = NULL;
3587 p != NULL;
3588 p = (cupsd_printer_t *)cupsArrayNext(Printers))
3589 {
3590 /*
3591 * Skip implicit classes...
3592 */
3593
3594 if (p->type & CUPS_PRINTER_IMPLICIT)
3595 {
3596 len = 0;
3597 continue;
3598 }
3599
3600 /*
3601 * If len == 0, get the length of this printer name up to the "@"
3602 * sign (if any).
3603 */
3604
3605 cupsArraySave(Printers);
3606
3607 if (len > 0 &&
3608 !strncasecmp(p->name, name + offset, len) &&
3609 (p->name[len] == '\0' || p->name[len] == '@'))
3610 {
3611 /*
3612 * We have more than one printer with the same name; see if
3613 * we have a class, and if this printer is a member...
3614 */
3615
3616 if (pclass && strcasecmp(pclass->name, name))
3617 {
3618 if (update)
3619 cupsdSetPrinterAttrs(pclass);
3620
3621 update = 0;
3622 pclass = NULL;
3623 }
3624
3625 if (!pclass && (pclass = cupsdFindDest(name)) == NULL)
3626 {
3627 /*
3628 * Need to add the class...
3629 */
3630
3631 pclass = cupsdAddPrinter(name);
3632 cupsArrayAdd(ImplicitPrinters, pclass);
3633
3634 pclass->type |= CUPS_PRINTER_IMPLICIT;
3635 pclass->accepting = 1;
3636 pclass->state = IPP_PRINTER_IDLE;
3637
3638 cupsdSetString(&pclass->location, p->location);
3639 cupsdSetString(&pclass->info, p->info);
3640
3641 cupsdSetString(&pclass->job_sheets[0], p->job_sheets[0]);
3642 cupsdSetString(&pclass->job_sheets[1], p->job_sheets[1]);
3643
3644 update = 1;
3645
3646 cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP | CUPSD_DIRTY_REMOTE);
3647
3648 cupsdLogMessage(CUPSD_LOG_DEBUG, "Added implicit class \"%s\"...",
3649 name);
3650 cupsdAddEvent(CUPSD_EVENT_PRINTER_ADDED, p, NULL,
3651 "Implicit class \'%s\' added by directory services.",
3652 name);
3653 }
3654
3655 if (first != NULL)
3656 {
3657 for (i = 0; i < pclass->num_printers; i ++)
3658 if (pclass->printers[i] == first)
3659 break;
3660
3661 if (i >= pclass->num_printers)
3662 {
3663 first->in_implicit_class = 1;
3664 cupsdAddPrinterToClass(pclass, first);
3665 }
3666
3667 first = NULL;
3668 }
3669
3670 for (i = 0; i < pclass->num_printers; i ++)
3671 if (pclass->printers[i] == p)
3672 break;
3673
3674 if (i >= pclass->num_printers)
3675 {
3676 p->in_implicit_class = 1;
3677 cupsdAddPrinterToClass(pclass, p);
3678 update = 1;
3679 }
3680 }
3681 else
3682 {
3683 /*
3684 * First time around; just get name length and mark it as first
3685 * in the list...
3686 */
3687
3688 if ((hptr = strchr(p->name, '@')) != NULL)
3689 len = hptr - p->name;
3690 else
3691 len = strlen(p->name);
3692
3693 if (len >= sizeof(name))
3694 {
3695 /*
3696 * If the printer name length somehow is greater than we normally allow,
3697 * skip this printer...
3698 */
3699
3700 len = 0;
3701 cupsArrayRestore(Printers);
3702 continue;
3703 }
3704
3705 strncpy(name, p->name, len);
3706 name[len] = '\0';
3707 offset = 0;
3708
3709 if ((first = (hptr ? cupsdFindDest(name) : p)) != NULL &&
3710 !(first->type & CUPS_PRINTER_IMPLICIT))
3711 {
3712 /*
3713 * Can't use same name as a local printer; add "Any" to the
3714 * front of the name, unless we have explicitly disabled
3715 * the "ImplicitAnyClasses"...
3716 */
3717
3718 if (ImplicitAnyClasses && len < (sizeof(name) - 4))
3719 {
3720 /*
3721 * Add "Any" to the class name...
3722 */
3723
3724 strcpy(name, "Any");
3725 strncpy(name + 3, p->name, len);
3726 name[len + 3] = '\0';
3727 offset = 3;
3728 }
3729 else
3730 {
3731 /*
3732 * Don't create an implicit class if we have a local printer
3733 * with the same name...
3734 */
3735
3736 len = 0;
3737 cupsArrayRestore(Printers);
3738 continue;
3739 }
3740 }
3741
3742 first = p;
3743 }
3744
3745 cupsArrayRestore(Printers);
3746 }
3747
3748 /*
3749 * Update the last printer class as needed...
3750 */
3751
3752 if (pclass && update)
3753 cupsdSetPrinterAttrs(pclass);
3754 }
3755
3756
3757 /*
3758 * 'send_cups_browse()' - Send new browsing information using the CUPS
3759 * protocol.
3760 */
3761
3762 static void
3763 send_cups_browse(cupsd_printer_t *p) /* I - Printer to send */
3764 {
3765 int i; /* Looping var */
3766 cups_ptype_t type; /* Printer type */
3767 cupsd_dirsvc_addr_t *b; /* Browse address */
3768 int bytes; /* Length of packet */
3769 char packet[1453], /* Browse data packet */
3770 uri[1024], /* Printer URI */
3771 location[1024], /* printer-location */
3772 info[1024], /* printer-info */
3773 make_model[1024],
3774 /* printer-make-and-model */
3775 air[1024]; /* auth-info-required */
3776 cupsd_netif_t *iface; /* Network interface */
3777
3778
3779 /*
3780 * Figure out the printer type value...
3781 */
3782
3783 type = p->type | CUPS_PRINTER_REMOTE;
3784
3785 if (!p->accepting)
3786 type |= CUPS_PRINTER_REJECTING;
3787
3788 if (p == DefaultPrinter)
3789 type |= CUPS_PRINTER_DEFAULT;
3790
3791 /*
3792 * Remove quotes from printer-info, printer-location, and
3793 * printer-make-and-model attributes...
3794 */
3795
3796 dequote(location, p->location, sizeof(location));
3797 dequote(info, p->info, sizeof(info));
3798
3799 if (p->make_model)
3800 dequote(make_model, p->make_model, sizeof(make_model));
3801 else if (p->type & CUPS_PRINTER_CLASS)
3802 {
3803 if (p->num_printers > 0 && p->printers[0]->make_model)
3804 strlcpy(make_model, p->printers[0]->make_model, sizeof(make_model));
3805 else
3806 strlcpy(make_model, "Local Printer Class", sizeof(make_model));
3807 }
3808 else if (p->raw)
3809 strlcpy(make_model, "Local Raw Printer", sizeof(make_model));
3810 else
3811 strlcpy(make_model, "Local System V Printer", sizeof(make_model));
3812
3813 if (get_auth_info_required(p, packet, sizeof(packet)))
3814 snprintf(air, sizeof(air), " auth-info-required=%s", packet);
3815 else
3816 air[0] = '\0';
3817
3818 /*
3819 * Send a packet to each browse address...
3820 */
3821
3822 for (i = NumBrowsers, b = Browsers; i > 0; i --, b ++)
3823 if (b->iface[0])
3824 {
3825 /*
3826 * Send the browse packet to one or more interfaces...
3827 */
3828
3829 if (!strcmp(b->iface, "*"))
3830 {
3831 /*
3832 * Send to all local interfaces...
3833 */
3834
3835 cupsdNetIFUpdate();
3836
3837 for (iface = (cupsd_netif_t *)cupsArrayFirst(NetIFList);
3838 iface;
3839 iface = (cupsd_netif_t *)cupsArrayNext(NetIFList))
3840 {
3841 /*
3842 * Only send to local, IPv4 interfaces...
3843 */
3844
3845 if (!iface->is_local || !iface->port ||
3846 iface->address.addr.sa_family != AF_INET)
3847 continue;
3848
3849 httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
3850 iface->hostname, iface->port,
3851 (p->type & CUPS_PRINTER_CLASS) ? "/classes/%s" :
3852 "/printers/%s",
3853 p->name);
3854 snprintf(packet, sizeof(packet), "%x %x %s \"%s\" \"%s\" \"%s\" %s%s\n",
3855 type, p->state, uri, location, info, make_model,
3856 p->browse_attrs ? p->browse_attrs : "", air);
3857
3858 bytes = strlen(packet);
3859
3860 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3861 "cupsdSendBrowseList: (%d bytes to \"%s\") %s", bytes,
3862 iface->name, packet);
3863
3864 iface->broadcast.ipv4.sin_port = htons(BrowsePort);
3865
3866 sendto(BrowseSocket, packet, bytes, 0,
3867 (struct sockaddr *)&(iface->broadcast),
3868 httpAddrLength(&(iface->broadcast)));
3869 }
3870 }
3871 else if ((iface = cupsdNetIFFind(b->iface)) != NULL)
3872 {
3873 /*
3874 * Send to the named interface using the IPv4 address...
3875 */
3876
3877 while (iface)
3878 if (strcmp(b->iface, iface->name))
3879 {
3880 iface = NULL;
3881 break;
3882 }
3883 else if (iface->address.addr.sa_family == AF_INET && iface->port)
3884 break;
3885 else
3886 iface = (cupsd_netif_t *)cupsArrayNext(NetIFList);
3887
3888 if (iface)
3889 {
3890 httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
3891 iface->hostname, iface->port,
3892 (p->type & CUPS_PRINTER_CLASS) ? "/classes/%s" :
3893 "/printers/%s",
3894 p->name);
3895 snprintf(packet, sizeof(packet),
3896 "%x %x %s \"%s\" \"%s\" \"%s\" %s%s\n",
3897 type, p->state, uri, location, info, make_model,
3898 p->browse_attrs ? p->browse_attrs : "", air);
3899
3900 bytes = strlen(packet);
3901
3902 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3903 "cupsdSendBrowseList: (%d bytes to \"%s\") %s", bytes,
3904 iface->name, packet);
3905
3906 iface->broadcast.ipv4.sin_port = htons(BrowsePort);
3907
3908 sendto(BrowseSocket, packet, bytes, 0,
3909 (struct sockaddr *)&(iface->broadcast),
3910 httpAddrLength(&(iface->broadcast)));
3911 }
3912 }
3913 }
3914 else
3915 {
3916 /*
3917 * Send the browse packet to the indicated address using
3918 * the default server name...
3919 */
3920
3921 snprintf(packet, sizeof(packet), "%x %x %s \"%s\" \"%s\" \"%s\" %s%s\n",
3922 type, p->state, p->uri, location, info, make_model,
3923 p->browse_attrs ? p->browse_attrs : "", air);
3924
3925 bytes = strlen(packet);
3926 cupsdLogMessage(CUPSD_LOG_DEBUG2,
3927 "cupsdSendBrowseList: (%d bytes) %s", bytes, packet);
3928
3929 if (sendto(BrowseSocket, packet, bytes, 0,
3930 (struct sockaddr *)&(b->to),
3931 httpAddrLength(&(b->to))) <= 0)
3932 {
3933 /*
3934 * Unable to send browse packet, so remove this address from the
3935 * list...
3936 */
3937
3938 cupsdLogMessage(CUPSD_LOG_ERROR,
3939 "cupsdSendBrowseList: sendto failed for browser "
3940 "%d - %s.",
3941 (int)(b - Browsers + 1), strerror(errno));
3942
3943 if (i > 1)
3944 memmove(b, b + 1, (i - 1) * sizeof(cupsd_dirsvc_addr_t));
3945
3946 b --;
3947 NumBrowsers --;
3948 }
3949 }
3950 }
3951
3952
3953 #ifdef HAVE_LDAP
3954 /*
3955 * 'ldap_search_rec()' - LDAP Search with reconnect
3956 */
3957
3958 static int /* O - Return code */
3959 ldap_search_rec(LDAP *ld, /* I - LDAP handler */
3960 char *base, /* I - Base dn */
3961 int scope, /* I - LDAP search scope */
3962 char *filter, /* I - Filter string */
3963 char *attrs[], /* I - Requested attributes */
3964 int attrsonly, /* I - Return only attributes? */
3965 LDAPMessage **res) /* I - LDAP handler */
3966 {
3967 int rc; /* Return code */
3968 LDAP *ldr; /* LDAP handler after reconnect */
3969
3970
3971 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
3972 rc = ldap_search_ext_s(ld, base, scope, filter, attrs, attrsonly, NULL, NULL,
3973 NULL, LDAP_NO_LIMIT, res);
3974 # else
3975 rc = ldap_search_s(ld, base, scope, filter, attrs, attrsonly, res);
3976 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
3977
3978 /*
3979 * If we have a connection problem try again...
3980 */
3981
3982 if (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR)
3983 {
3984 cupsdLogMessage(CUPSD_LOG_ERROR,
3985 "LDAP search failed with status %d: %s",
3986 rc, ldap_err2string(rc));
3987 cupsdLogMessage(CUPSD_LOG_INFO,
3988 "We try the LDAP search once again after reconnecting to "
3989 "the server");
3990 ldap_freeres(*res);
3991 ldr = ldap_reconnect();
3992
3993 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
3994 rc = ldap_search_ext_s(ldr, base, scope, filter, attrs, attrsonly, NULL,
3995 NULL, NULL, LDAP_NO_LIMIT, res);
3996 # else
3997 rc = ldap_search_s(ldr, base, scope, filter, attrs, attrsonly, res);
3998 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
3999 }
4000
4001 if (rc == LDAP_NO_SUCH_OBJECT)
4002 cupsdLogMessage(CUPSD_LOG_DEBUG,
4003 "ldap_search_rec: LDAP entry/object not found");
4004 else if (rc != LDAP_SUCCESS)
4005 cupsdLogMessage(CUPSD_LOG_ERROR,
4006 "ldap_search_rec: LDAP search failed with status %d: %s",
4007 rc, ldap_err2string(rc));
4008
4009 if (rc != LDAP_SUCCESS)
4010 ldap_freeres(*res);
4011
4012 return (rc);
4013 }
4014
4015
4016 /*
4017 * 'ldap_freeres()' - Free LDAPMessage
4018 */
4019
4020 static void
4021 ldap_freeres(LDAPMessage *entry) /* I - LDAP handler */
4022 {
4023 int rc; /* Return value */
4024
4025
4026 rc = ldap_msgfree(entry);
4027 if (rc == -1)
4028 cupsdLogMessage(CUPSD_LOG_WARN, "Can't free LDAPMessage!");
4029 else if (rc == 0)
4030 cupsdLogMessage(CUPSD_LOG_DEBUG2, "Freeing LDAPMessage was unnecessary");
4031 }
4032
4033
4034 /*
4035 * 'ldap_getval_char()' - Get first LDAP value and convert to string
4036 */
4037
4038 static int /* O - Return code */
4039 ldap_getval_firststring(
4040 LDAP *ld, /* I - LDAP handler */
4041 LDAPMessage *entry, /* I - LDAP message or search result */
4042 char *attr, /* I - the wanted attribute */
4043 char *retval, /* O - String to return */
4044 unsigned long maxsize) /* I - Max string size */
4045 {
4046 char *dn; /* LDAP DN */
4047 int rc = 0; /* Return code */
4048 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4049 struct berval **bval; /* LDAP value array */
4050 unsigned long size; /* String size */
4051
4052
4053 /*
4054 * Get value from LDAPMessage...
4055 */
4056
4057 if ((bval = ldap_get_values_len(ld, entry, attr)) == NULL)
4058 {
4059 rc = -1;
4060 dn = ldap_get_dn(ld, entry);
4061 cupsdLogMessage(CUPSD_LOG_WARN,
4062 "Failed to get LDAP value %s for %s!",
4063 attr, dn);
4064 ldap_memfree(dn);
4065 }
4066 else
4067 {
4068 /*
4069 * Check size and copy value into our string...
4070 */
4071
4072 size = maxsize;
4073 if (size < (bval[0]->bv_len + 1))
4074 {
4075 rc = -1;
4076 dn = ldap_get_dn(ld, entry);
4077 cupsdLogMessage(CUPSD_LOG_WARN,
4078 "Attribute %s is too big! (dn: %s)",
4079 attr, dn);
4080 ldap_memfree(dn);
4081 }
4082 else
4083 size = bval[0]->bv_len + 1;
4084
4085 strlcpy(retval, bval[0]->bv_val, size);
4086 ldap_value_free_len(bval);
4087 }
4088 # else
4089 char **value; /* LDAP value */
4090
4091 /*
4092 * Get value from LDAPMessage...
4093 */
4094
4095 if ((value = (char **)ldap_get_values(ld, entry, attr)) == NULL)
4096 {
4097 rc = -1;
4098 dn = ldap_get_dn(ld, entry);
4099 cupsdLogMessage(CUPSD_LOG_WARN, "Failed to get LDAP value %s for %s!",
4100 attr, dn);
4101 ldap_memfree(dn);
4102 }
4103 else
4104 {
4105 strlcpy(retval, *value, maxsize);
4106 ldap_value_free(value);
4107 }
4108 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4109
4110 return (rc);
4111 }
4112
4113
4114 /*
4115 * 'send_ldap_ou()' - Send LDAP ou registrations.
4116 */
4117
4118 static void
4119 send_ldap_ou(char *ou, /* I - Servername/ou to register */
4120 char *basedn, /* I - Our base dn */
4121 char *descstring) /* I - Description for ou */
4122 {
4123 int i; /* Looping var... */
4124 LDAPMod mods[3]; /* The 3 attributes we will be adding */
4125 LDAPMod *pmods[4]; /* Pointers to the 3 attributes + NULL */
4126 LDAPMessage *res, /* Search result token */
4127 *e; /* Current entry from search */
4128 int rc; /* LDAP status */
4129 int rcmod; /* LDAP status for modifications */
4130 char dn[1024], /* DN of the organizational unit we are adding */
4131 *desc[2], /* Change records */
4132 *ou_value[2];
4133 char old_desc[1024]; /* Old description */
4134 static const char * const objectClass_values[] =
4135 { /* The 2 objectClass's we use in */
4136 "top", /* our LDAP entries */
4137 "organizationalUnit",
4138 NULL
4139 };
4140 static const char * const ou_attrs[] =/* CUPS LDAP attributes */
4141 {
4142 "description",
4143 NULL
4144 };
4145
4146
4147 cupsdLogMessage(CUPSD_LOG_DEBUG2, "send_ldap_ou: %s", ou);
4148
4149 /*
4150 * Reconnect if LDAP Handle is invalid...
4151 */
4152
4153 if (!BrowseLDAPHandle)
4154 {
4155 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4156 "send_ldap_ou: LDAP Handle is invalid. Try reconnecting...");
4157 ldap_reconnect();
4158 return;
4159 }
4160
4161 /*
4162 * Prepare ldap search...
4163 */
4164
4165 snprintf(dn, sizeof(dn), "ou=%s, %s", ou, basedn);
4166 cupsdLogMessage(CUPSD_LOG_DEBUG2, "send_ldap_ou: dn=\"%s\"", dn);
4167
4168 ou_value[0] = ou;
4169 ou_value[1] = NULL;
4170 desc[0] = descstring;
4171 desc[1] = NULL;
4172
4173 mods[0].mod_type = "ou";
4174 mods[0].mod_values = ou_value;
4175 mods[1].mod_type = "description";
4176 mods[1].mod_values = desc;
4177 mods[2].mod_type = "objectClass";
4178 mods[2].mod_values = (char **)objectClass_values;
4179
4180 rc = ldap_search_rec(BrowseLDAPHandle, dn, LDAP_SCOPE_BASE, NULL,
4181 (char **)ou_attrs, 0, &res);
4182
4183 /*
4184 * If ldap search was not successfull then exit function...
4185 */
4186
4187 if (rc != LDAP_SUCCESS && rc != LDAP_NO_SUCH_OBJECT)
4188 return;
4189
4190 /*
4191 * Check if we need to insert or update the LDAP entry...
4192 */
4193
4194 if (ldap_count_entries(BrowseLDAPHandle, res) > 0 &&
4195 rc != LDAP_NO_SUCH_OBJECT)
4196 {
4197 /*
4198 * Printserver has already been registered, check if
4199 * modification is required...
4200 */
4201
4202 e = ldap_first_entry(BrowseLDAPHandle, res);
4203
4204 /*
4205 * Get the required values from this entry...
4206 */
4207
4208 if (ldap_getval_firststring(BrowseLDAPHandle, e, "description", old_desc,
4209 sizeof(old_desc)) == -1)
4210 old_desc[0] = '\0';
4211
4212 /*
4213 * Check if modification is required...
4214 */
4215
4216 if ( strcmp(desc[0], old_desc) == 0 )
4217 {
4218 /*
4219 * LDAP entry for the printer exists.
4220 * Printer has already been registered,
4221 * no modifications required...
4222 */
4223 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4224 "send_ldap_ou: No updates required for %s", ou);
4225 }
4226 else
4227 {
4228
4229 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4230 "send_ldap_ou: Replace entry for %s", ou);
4231
4232 for (i = 0; i < 3; i ++)
4233 {
4234 pmods[i] = mods + i;
4235 pmods[i]->mod_op = LDAP_MOD_REPLACE;
4236 }
4237 pmods[i] = NULL;
4238
4239 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4240 if ((rcmod = ldap_modify_ext_s(BrowseLDAPHandle, dn, pmods, NULL,
4241 NULL)) != LDAP_SUCCESS)
4242 # else
4243 if ((rcmod = ldap_modify_s(BrowseLDAPHandle, dn, pmods)) != LDAP_SUCCESS)
4244 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4245 {
4246 cupsdLogMessage(CUPSD_LOG_ERROR,
4247 "LDAP modify for %s failed with status %d: %s",
4248 ou, rcmod, ldap_err2string(rcmod));
4249 if (rcmod == LDAP_SERVER_DOWN)
4250 ldap_reconnect();
4251 }
4252 }
4253 }
4254 else
4255 {
4256 /*
4257 * Printserver has never been registered,
4258 * add registration...
4259 */
4260
4261 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4262 "send_ldap_ou: Add entry for %s", ou);
4263
4264 for (i = 0; i < 3; i ++)
4265 {
4266 pmods[i] = mods + i;
4267 pmods[i]->mod_op = LDAP_MOD_ADD;
4268 }
4269 pmods[i] = NULL;
4270
4271 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4272 if ((rcmod = ldap_add_ext_s(BrowseLDAPHandle, dn, pmods, NULL,
4273 NULL)) != LDAP_SUCCESS)
4274 # else
4275 if ((rcmod = ldap_add_s(BrowseLDAPHandle, dn, pmods)) != LDAP_SUCCESS)
4276 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4277 {
4278 cupsdLogMessage(CUPSD_LOG_ERROR,
4279 "LDAP add for %s failed with status %d: %s",
4280 ou, rcmod, ldap_err2string(rcmod));
4281 if (rcmod == LDAP_SERVER_DOWN)
4282 ldap_reconnect();
4283 }
4284 }
4285
4286 if (rc == LDAP_SUCCESS)
4287 ldap_freeres(res);
4288 }
4289
4290
4291 /*
4292 * 'send_ldap_browse()' - Send LDAP printer registrations.
4293 */
4294
4295 static void
4296 send_ldap_browse(cupsd_printer_t *p) /* I - Printer to register */
4297 {
4298 int i; /* Looping var... */
4299 LDAPMod mods[7]; /* The 7 attributes we will be adding */
4300 LDAPMod *pmods[8]; /* Pointers to the 7 attributes + NULL */
4301 LDAPMessage *res, /* Search result token */
4302 *e; /* Current entry from search */
4303 char *cn_value[2], /* Change records */
4304 *uri[2],
4305 *info[2],
4306 *location[2],
4307 *make_model[2],
4308 *type[2],
4309 typestring[255], /* String to hold printer-type */
4310 dn[1024]; /* DN of the printer we are adding */
4311 int rc; /* LDAP status */
4312 int rcmod; /* LDAP status for modifications */
4313 char old_uri[HTTP_MAX_URI], /* Printer URI */
4314 old_location[1024], /* Printer location */
4315 old_info[1024], /* Printer information */
4316 old_make_model[1024], /* Printer make and model */
4317 old_type_string[30]; /* Temporary type number */
4318 int old_type; /* Printer type */
4319 static const char * const objectClass_values[] =
4320 { /* The 3 objectClass's we use in */
4321 "top", /* our LDAP entries */
4322 "device",
4323 "cupsPrinter",
4324 NULL
4325 };
4326
4327
4328 cupsdLogMessage(CUPSD_LOG_DEBUG2, "send_ldap_browse: %s", p->name);
4329
4330 /*
4331 * Exit function if LDAP updates has been disabled...
4332 */
4333
4334 if (!BrowseLDAPUpdate)
4335 {
4336 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4337 "send_ldap_browse: Updates temporary disabled; "
4338 "skipping...");
4339 return;
4340 }
4341
4342 /*
4343 * Reconnect if LDAP Handle is invalid...
4344 */
4345
4346 if (!BrowseLDAPHandle)
4347 {
4348 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4349 "send_ldap_browse: LDAP Handle is invalid. Try "
4350 "reconnecting...");
4351 ldap_reconnect();
4352 return;
4353 }
4354
4355 /*
4356 * Everything in ldap is ** so we fudge around it...
4357 */
4358
4359 sprintf(typestring, "%u", p->type);
4360
4361 cn_value[0] = p->name;
4362 cn_value[1] = NULL;
4363 info[0] = p->info ? p->info : "Unknown";
4364 info[1] = NULL;
4365 location[0] = p->location ? p->location : "Unknown";
4366 location[1] = NULL;
4367 make_model[0] = p->make_model ? p->make_model : "Unknown";
4368 make_model[1] = NULL;
4369 type[0] = typestring;
4370 type[1] = NULL;
4371 uri[0] = p->uri;
4372 uri[1] = NULL;
4373
4374 /*
4375 * Get ldap entry for printer ...
4376 */
4377
4378 snprintf(dn, sizeof(dn), "cn=%s, ou=%s, %s", p->name, ServerName,
4379 BrowseLDAPDN);
4380 cupsdLogMessage(CUPSD_LOG_DEBUG2, "send_ldap_browse: dn=\"%s\"", dn);
4381
4382 rc = ldap_search_rec(BrowseLDAPHandle, dn, LDAP_SCOPE_BASE, NULL,
4383 (char **)ldap_attrs, 0, &res);
4384
4385 /*
4386 * If ldap search was not successfull then exit function
4387 * and temporary disable LDAP updates...
4388 */
4389
4390 if (rc != LDAP_SUCCESS && rc != LDAP_NO_SUCH_OBJECT)
4391 {
4392 if (BrowseLDAPUpdate &&
4393 (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR))
4394 {
4395 BrowseLDAPUpdate = FALSE;
4396 cupsdLogMessage(CUPSD_LOG_INFO,
4397 "LDAP update temporary disabled");
4398 }
4399
4400 return;
4401 }
4402
4403 /*
4404 * Fill modification array...
4405 */
4406
4407 mods[0].mod_type = "cn";
4408 mods[0].mod_values = cn_value;
4409 mods[1].mod_type = "printerDescription";
4410 mods[1].mod_values = info;
4411 mods[2].mod_type = "printerURI";
4412 mods[2].mod_values = uri;
4413 mods[3].mod_type = "printerLocation";
4414 mods[3].mod_values = location;
4415 mods[4].mod_type = "printerMakeAndModel";
4416 mods[4].mod_values = make_model;
4417 mods[5].mod_type = "printerType";
4418 mods[5].mod_values = type;
4419 mods[6].mod_type = "objectClass";
4420 mods[6].mod_values = (char **)objectClass_values;
4421
4422 /*
4423 * Check if we need to insert or update the LDAP entry...
4424 */
4425
4426 if (ldap_count_entries(BrowseLDAPHandle, res) > 0 &&
4427 rc != LDAP_NO_SUCH_OBJECT)
4428 {
4429 /*
4430 * Printer has already been registered, check if
4431 * modification is required...
4432 */
4433
4434 e = ldap_first_entry(BrowseLDAPHandle, res);
4435
4436 /*
4437 * Get the required values from this entry...
4438 */
4439
4440 if (ldap_getval_firststring(BrowseLDAPHandle, e, "printerDescription",
4441 old_info, sizeof(old_info)) == -1)
4442 old_info[0] = '\0';
4443
4444 if (ldap_getval_firststring(BrowseLDAPHandle, e, "printerLocation",
4445 old_location, sizeof(old_location)) == -1)
4446 old_info[0] = '\0';
4447
4448 if (ldap_getval_firststring(BrowseLDAPHandle, e, "printerMakeAndModel",
4449 old_make_model, sizeof(old_make_model)) == -1)
4450 old_info[0] = '\0';
4451
4452 if (ldap_getval_firststring(BrowseLDAPHandle, e, "printerType",
4453 old_type_string, sizeof(old_type_string)) == -1)
4454 old_info[0] = '\0';
4455
4456 old_type = atoi(old_type_string);
4457
4458 if (ldap_getval_firststring(BrowseLDAPHandle, e, "printerURI", old_uri,
4459 sizeof(old_uri)) == -1)
4460 old_info[0] = '\0';
4461
4462 /*
4463 * Check if modification is required...
4464 */
4465
4466 if (!strcmp(info[0], old_info) && !strcmp(uri[0], old_uri) &&
4467 !strcmp(location[0], old_location) &&
4468 !strcmp(make_model[0], old_make_model) && p->type == old_type)
4469 {
4470 /*
4471 * LDAP entry for the printer exists. Printer has already been registered,
4472 * no modifications required...
4473 */
4474
4475 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4476 "send_ldap_browse: No updates required for %s", p->name);
4477 }
4478 else
4479 {
4480 /*
4481 * LDAP entry for the printer exists. Printer has already been registered,
4482 * modify the current registration...
4483 */
4484
4485 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4486 "send_ldap_browse: Replace entry for %s", p->name);
4487
4488 for (i = 0; i < 7; i ++)
4489 {
4490 pmods[i] = mods + i;
4491 pmods[i]->mod_op = LDAP_MOD_REPLACE;
4492 }
4493 pmods[i] = NULL;
4494
4495 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4496 if ((rcmod = ldap_modify_ext_s(BrowseLDAPHandle, dn, pmods, NULL,
4497 NULL)) != LDAP_SUCCESS)
4498 # else
4499 if ((rcmod = ldap_modify_s(BrowseLDAPHandle, dn, pmods)) != LDAP_SUCCESS)
4500 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4501 {
4502 cupsdLogMessage(CUPSD_LOG_ERROR,
4503 "LDAP modify for %s failed with status %d: %s",
4504 p->name, rcmod, ldap_err2string(rcmod));
4505 if (rcmod == LDAP_SERVER_DOWN)
4506 ldap_reconnect();
4507 }
4508 }
4509 }
4510 else
4511 {
4512 /*
4513 * No LDAP entry exists for the printer. Printer has never been registered,
4514 * add the current registration...
4515 */
4516
4517 send_ldap_ou(ServerName, BrowseLDAPDN, "CUPS Server");
4518
4519 cupsdLogMessage(CUPSD_LOG_DEBUG2,
4520 "send_ldap_browse: Add entry for %s", p->name);
4521
4522 for (i = 0; i < 7; i ++)
4523 {
4524 pmods[i] = mods + i;
4525 pmods[i]->mod_op = LDAP_MOD_ADD;
4526 }
4527 pmods[i] = NULL;
4528
4529 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4530 if ((rcmod = ldap_add_ext_s(BrowseLDAPHandle, dn, pmods, NULL,
4531 NULL)) != LDAP_SUCCESS)
4532 # else
4533 if ((rcmod = ldap_add_s(BrowseLDAPHandle, dn, pmods)) != LDAP_SUCCESS)
4534 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4535 {
4536 cupsdLogMessage(CUPSD_LOG_ERROR,
4537 "LDAP add for %s failed with status %d: %s",
4538 p->name, rcmod, ldap_err2string(rcmod));
4539 if (rcmod == LDAP_SERVER_DOWN)
4540 ldap_reconnect();
4541 }
4542 }
4543
4544 if (rc == LDAP_SUCCESS)
4545 ldap_freeres(res);
4546 }
4547
4548
4549 /*
4550 * 'ldap_dereg_printer()' - Delete printer from directory
4551 */
4552
4553 static void
4554 ldap_dereg_printer(cupsd_printer_t *p) /* I - Printer to deregister */
4555 {
4556 char dn[1024]; /* DN of the printer */
4557 int rc; /* LDAP status */
4558
4559
4560 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_dereg_printer: Remove entry for %s",
4561 p->name);
4562
4563 /*
4564 * Reconnect if LDAP Handle is invalid...
4565 */
4566
4567 if (!BrowseLDAPHandle)
4568 {
4569 ldap_reconnect();
4570 return;
4571 }
4572
4573 /*
4574 * Get dn for printer and delete LDAP entry...
4575 */
4576
4577 snprintf(dn, sizeof(dn), "cn=%s, ou=%s, %s", p->name, ServerName,
4578 BrowseLDAPDN);
4579 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_dereg_printer: dn=\"%s\"", dn);
4580
4581 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4582 if ((rc = ldap_delete_ext_s(BrowseLDAPHandle, dn, NULL,
4583 NULL)) != LDAP_SUCCESS)
4584 # else
4585 if ((rc = ldap_delete_s(BrowseLDAPHandle, dn)) != LDAP_SUCCESS)
4586 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4587 {
4588 cupsdLogMessage(CUPSD_LOG_WARN,
4589 "LDAP delete for %s failed with status %d: %s",
4590 p->name, rc, ldap_err2string(rc));
4591
4592 /*
4593 * If we had a connection problem (connection timed out, etc.)
4594 * we should reconnect and try again to delete the entry...
4595 */
4596
4597 if (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR)
4598 {
4599 cupsdLogMessage(CUPSD_LOG_INFO,
4600 "Retry deleting LDAP entry for %s after a reconnect...", p->name);
4601 ldap_reconnect();
4602
4603 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4604 if ((rc = ldap_delete_ext_s(BrowseLDAPHandle, dn, NULL,
4605 NULL)) != LDAP_SUCCESS)
4606 # else
4607 if ((rc = ldap_delete_s(BrowseLDAPHandle, dn)) != LDAP_SUCCESS)
4608 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4609 cupsdLogMessage(CUPSD_LOG_WARN,
4610 "LDAP delete for %s failed with status %d: %s",
4611 p->name, rc, ldap_err2string(rc));
4612 }
4613 }
4614 }
4615
4616
4617 /*
4618 * 'ldap_dereg_ou()' - Remove the organizational unit.
4619 */
4620
4621 static void
4622 ldap_dereg_ou(char *ou, /* I - Organizational unit (servername) */
4623 char *basedn) /* I - Dase dn */
4624 {
4625 char dn[1024]; /* DN of the printer */
4626 int rc; /* LDAP status */
4627
4628
4629 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_dereg_ou: Remove entry for %s", ou);
4630
4631 /*
4632 * Reconnect if LDAP Handle is invalid...
4633 */
4634
4635 if (!BrowseLDAPHandle)
4636 {
4637 ldap_reconnect();
4638 return;
4639 }
4640
4641 /*
4642 * Get dn for printer and delete LDAP entry...
4643 */
4644
4645 snprintf(dn, sizeof(dn), "ou=%s, %s", ou, basedn);
4646 cupsdLogMessage(CUPSD_LOG_DEBUG2, "ldap_dereg_ou: dn=\"%s\"", dn);
4647
4648 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4649 if ((rc = ldap_delete_ext_s(BrowseLDAPHandle, dn, NULL,
4650 NULL)) != LDAP_SUCCESS)
4651 # else
4652 if ((rc = ldap_delete_s(BrowseLDAPHandle, dn)) != LDAP_SUCCESS)
4653 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4654 {
4655 cupsdLogMessage(CUPSD_LOG_WARN,
4656 "LDAP delete for %s failed with status %d: %s",
4657 ou, rc, ldap_err2string(rc));
4658
4659 /*
4660 * If we had a connection problem (connection timed out, etc.)
4661 * we should reconnect and try again to delete the entry...
4662 */
4663
4664 if (rc == LDAP_SERVER_DOWN || rc == LDAP_CONNECT_ERROR)
4665 {
4666 cupsdLogMessage(CUPSD_LOG_INFO,
4667 "Retry deleting LDAP entry for %s after a reconnect...", ou);
4668 ldap_reconnect();
4669 # if defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000
4670 if ((rc = ldap_delete_ext_s(BrowseLDAPHandle, dn, NULL,
4671 NULL)) != LDAP_SUCCESS)
4672 # else
4673 if ((rc = ldap_delete_s(BrowseLDAPHandle, dn)) != LDAP_SUCCESS)
4674 # endif /* defined(HAVE_OPENLDAP) && LDAP_API_VERSION > 3000 */
4675 cupsdLogMessage(CUPSD_LOG_WARN,
4676 "LDAP delete for %s failed with status %d: %s",
4677 ou, rc, ldap_err2string(rc));
4678 }
4679 }
4680 }
4681 #endif /* HAVE_LDAP */
4682
4683
4684 #ifdef HAVE_LIBSLP
4685 /*
4686 * 'send_slp_browse()' - Register the specified printer with SLP.
4687 */
4688
4689 static void
4690 send_slp_browse(cupsd_printer_t *p) /* I - Printer to register */
4691 {
4692 char srvurl[HTTP_MAX_URI], /* Printer service URI */
4693 attrs[8192], /* Printer attributes */
4694 finishings[1024], /* Finishings to support */
4695 make_model[IPP_MAX_NAME * 2],
4696 /* Make and model, quoted */
4697 location[IPP_MAX_NAME * 2],
4698 /* Location, quoted */
4699 info[IPP_MAX_NAME * 2], /* Info, quoted */
4700 *src, /* Pointer to original string */
4701 *dst; /* Pointer to destination string */
4702 ipp_attribute_t *authentication; /* uri-authentication-supported value */
4703 SLPError error; /* SLP error, if any */
4704
4705
4706 cupsdLogMessage(CUPSD_LOG_DEBUG, "send_slp_browse(%p = \"%s\")", p,
4707 p->name);
4708
4709 /*
4710 * Make the SLP service URL that conforms to the IANA
4711 * 'printer:' template.
4712 */
4713
4714 snprintf(srvurl, sizeof(srvurl), SLP_CUPS_SRVTYPE ":%s", p->uri);
4715
4716 cupsdLogMessage(CUPSD_LOG_DEBUG2, "Service URL = \"%s\"", srvurl);
4717
4718 /*
4719 * Figure out the finishings string...
4720 */
4721
4722 if (p->type & CUPS_PRINTER_STAPLE)
4723 strcpy(finishings, "staple");
4724 else
4725 finishings[0] = '\0';
4726
4727 if (p->type & CUPS_PRINTER_BIND)
4728 {
4729 if (finishings[0])
4730 strlcat(finishings, ",bind", sizeof(finishings));
4731 else
4732 strcpy(finishings, "bind");
4733 }
4734
4735 if (p->type & CUPS_PRINTER_PUNCH)
4736 {
4737 if (finishings[0])
4738 strlcat(finishings, ",punch", sizeof(finishings));
4739 else
4740 strcpy(finishings, "punch");
4741 }
4742
4743 if (p->type & CUPS_PRINTER_COVER)
4744 {
4745 if (finishings[0])
4746 strlcat(finishings, ",cover", sizeof(finishings));
4747 else
4748 strcpy(finishings, "cover");
4749 }
4750
4751 if (p->type & CUPS_PRINTER_SORT)
4752 {
4753 if (finishings[0])
4754 strlcat(finishings, ",sort", sizeof(finishings));
4755 else
4756 strcpy(finishings, "sort");
4757 }
4758
4759 if (!finishings[0])
4760 strcpy(finishings, "none");
4761
4762 /*
4763 * Quote any commas in the make and model, location, and info strings...
4764 */
4765
4766 for (src = p->make_model, dst = make_model;
4767 src && *src && dst < (make_model + sizeof(make_model) - 2);)
4768 {
4769 if (*src == ',' || *src == '\\' || *src == ')')
4770 *dst++ = '\\';
4771
4772 *dst++ = *src++;
4773 }
4774
4775 *dst = '\0';
4776
4777 if (!make_model[0])
4778 strcpy(make_model, "Unknown");
4779
4780 for (src = p->location, dst = location;
4781 src && *src && dst < (location + sizeof(location) - 2);)
4782 {
4783 if (*src == ',' || *src == '\\' || *src == ')')
4784 *dst++ = '\\';
4785
4786 *dst++ = *src++;
4787 }
4788
4789 *dst = '\0';
4790
4791 if (!location[0])
4792 strcpy(location, "Unknown");
4793
4794 for (src = p->info, dst = info;
4795 src && *src && dst < (info + sizeof(info) - 2);)
4796 {
4797 if (*src == ',' || *src == '\\' || *src == ')')
4798 *dst++ = '\\';
4799
4800 *dst++ = *src++;
4801 }
4802
4803 *dst = '\0';
4804
4805 if (!info[0])
4806 strcpy(info, "Unknown");
4807
4808 /*
4809 * Get the authentication value...
4810 */
4811
4812 authentication = ippFindAttribute(p->attrs, "uri-authentication-supported",
4813 IPP_TAG_KEYWORD);
4814
4815 /*
4816 * Make the SLP attribute string list that conforms to
4817 * the IANA 'printer:' template.
4818 */
4819
4820 snprintf(attrs, sizeof(attrs),
4821 "(printer-uri-supported=%s),"
4822 "(uri-authentication-supported=%s>),"
4823 #ifdef HAVE_SSL
4824 "(uri-security-supported=tls>),"
4825 #else
4826 "(uri-security-supported=none>),"
4827 #endif /* HAVE_SSL */
4828 "(printer-name=%s),"
4829 "(printer-location=%s),"
4830 "(printer-info=%s),"
4831 "(printer-more-info=%s),"
4832 "(printer-make-and-model=%s),"
4833 "(printer-type=%d),"
4834 "(charset-supported=utf-8),"
4835 "(natural-language-configured=%s),"
4836 "(natural-language-supported=de,en,es,fr,it),"
4837 "(color-supported=%s),"
4838 "(finishings-supported=%s),"
4839 "(sides-supported=one-sided%s),"
4840 "(multiple-document-jobs-supported=true)"
4841 "(ipp-versions-supported=1.0,1.1)",
4842 p->uri, authentication->values[0].string.text, p->name, location,
4843 info, p->uri, make_model, p->type, DefaultLanguage,
4844 p->type & CUPS_PRINTER_COLOR ? "true" : "false",
4845 finishings,
4846 p->type & CUPS_PRINTER_DUPLEX ?
4847 ",two-sided-long-edge,two-sided-short-edge" : "");
4848
4849 cupsdLogMessage(CUPSD_LOG_DEBUG2, "Attributes = \"%s\"", attrs);
4850
4851 /*
4852 * Register the printer with the SLP server...
4853 */
4854
4855 error = SLPReg(BrowseSLPHandle, srvurl, BrowseTimeout,
4856 SLP_CUPS_SRVTYPE, attrs, SLP_TRUE, slp_reg_callback, 0);
4857
4858 if (error != SLP_OK)
4859 cupsdLogMessage(CUPSD_LOG_ERROR, "SLPReg of \"%s\" failed with status %d!", p->name,
4860 error);
4861 }
4862
4863
4864 /*
4865 * 'slp_attr_callback()' - SLP attribute callback
4866 */
4867
4868 static SLPBoolean /* O - SLP_TRUE for success */
4869 slp_attr_callback(
4870 SLPHandle hslp, /* I - SLP handle */
4871 const char *attrlist, /* I - Attribute list */
4872 SLPError errcode, /* I - Parsing status for this attr */
4873 void *cookie) /* I - Current printer */
4874 {
4875 char *tmp = 0; /* Temporary string */
4876 cupsd_printer_t *p = (cupsd_printer_t*)cookie;
4877 /* Current printer */
4878
4879
4880 (void)hslp; /* anti-compiler-warning-code */
4881
4882 /*
4883 * Bail if there was an error
4884 */
4885
4886 if (errcode != SLP_OK)
4887 return (SLP_TRUE);
4888
4889 /*
4890 * Parse the attrlist to obtain things needed to build CUPS browse packet
4891 */
4892
4893 memset(p, 0, sizeof(cupsd_printer_t));
4894
4895 if (slp_get_attr(attrlist, "(printer-location=", &(p->location)))
4896 return (SLP_FALSE);
4897 if (slp_get_attr(attrlist, "(printer-info=", &(p->info)))
4898 return (SLP_FALSE);
4899 if (slp_get_attr(attrlist, "(printer-make-and-model=", &(p->make_model)))
4900 return (SLP_FALSE);
4901 if (!slp_get_attr(attrlist, "(printer-type=", &tmp))
4902 p->type = atoi(tmp);
4903 else
4904 p->type = CUPS_PRINTER_REMOTE;
4905
4906 cupsdClearString(&tmp);
4907
4908 return (SLP_TRUE);
4909 }
4910
4911
4912 /*
4913 * 'slp_dereg_printer()' - SLPDereg() the specified printer
4914 */
4915
4916 static void
4917 slp_dereg_printer(cupsd_printer_t *p) /* I - Printer */
4918 {
4919 char srvurl[HTTP_MAX_URI]; /* Printer service URI */
4920
4921
4922 cupsdLogMessage(CUPSD_LOG_DEBUG, "slp_dereg_printer: printer=\"%s\"", p->name);
4923
4924 if (!(p->type & CUPS_PRINTER_REMOTE))
4925 {
4926 /*
4927 * Make the SLP service URL that conforms to the IANA
4928 * 'printer:' template.
4929 */
4930
4931 snprintf(srvurl, sizeof(srvurl), SLP_CUPS_SRVTYPE ":%s", p->uri);
4932
4933 /*
4934 * Deregister the printer...
4935 */
4936
4937 SLPDereg(BrowseSLPHandle, srvurl, slp_reg_callback, 0);
4938 }
4939 }
4940
4941
4942 /*
4943 * 'slp_get_attr()' - Get an attribute from an SLP registration.
4944 */
4945
4946 static int /* O - 0 on success */
4947 slp_get_attr(const char *attrlist, /* I - Attribute list string */
4948 const char *tag, /* I - Name of attribute */
4949 char **valbuf) /* O - Value */
4950 {
4951 char *ptr1, /* Pointer into string */
4952 *ptr2; /* ... */
4953
4954
4955 cupsdClearString(valbuf);
4956
4957 if ((ptr1 = strstr(attrlist, tag)) != NULL)
4958 {
4959 ptr1 += strlen(tag);
4960
4961 if ((ptr2 = strchr(ptr1,')')) != NULL)
4962 {
4963 /*
4964 * Copy the value...
4965 */
4966
4967 *valbuf = calloc(ptr2 - ptr1 + 1, 1);
4968 strncpy(*valbuf, ptr1, ptr2 - ptr1);
4969
4970 /*
4971 * Dequote the value...
4972 */
4973
4974 for (ptr1 = *valbuf; *ptr1; ptr1 ++)
4975 if (*ptr1 == '\\' && ptr1[1])
4976 _cups_strcpy(ptr1, ptr1 + 1);
4977
4978 return (0);
4979 }
4980 }
4981
4982 return (-1);
4983 }
4984
4985
4986 /*
4987 * 'slp_reg_callback()' - Empty SLPRegReport.
4988 */
4989
4990 static void
4991 slp_reg_callback(SLPHandle hslp, /* I - SLP handle */
4992 SLPError errcode, /* I - Error code, if any */
4993 void *cookie) /* I - App data */
4994 {
4995 (void)hslp;
4996 (void)errcode;
4997 (void)cookie;
4998
4999 return;
5000 }
5001
5002
5003 /*
5004 * 'slp_url_callback()' - SLP service url callback
5005 */
5006
5007 static SLPBoolean /* O - TRUE = OK, FALSE = error */
5008 slp_url_callback(
5009 SLPHandle hslp, /* I - SLP handle */
5010 const char *srvurl, /* I - URL of service */
5011 unsigned short lifetime, /* I - Life of service */
5012 SLPError errcode, /* I - Existing error code */
5013 void *cookie) /* I - Pointer to service list */
5014 {
5015 slpsrvurl_t *s, /* New service entry */
5016 **head; /* Pointer to head of entry */
5017
5018
5019 /*
5020 * Let the compiler know we won't be using these vars...
5021 */
5022
5023 (void)hslp;
5024 (void)lifetime;
5025
5026 /*
5027 * Bail if there was an error
5028 */
5029
5030 if (errcode != SLP_OK)
5031 return (SLP_TRUE);
5032
5033 /*
5034 * Grab the head of the list...
5035 */
5036
5037 head = (slpsrvurl_t**)cookie;
5038
5039 /*
5040 * Allocate a *temporary* slpsrvurl_t to hold this entry.
5041 */
5042
5043 if ((s = (slpsrvurl_t *)calloc(1, sizeof(slpsrvurl_t))) == NULL)
5044 return (SLP_FALSE);
5045
5046 /*
5047 * Copy the SLP service URL...
5048 */
5049
5050 strlcpy(s->url, srvurl, sizeof(s->url));
5051
5052 /*
5053 * Link the SLP service URL into the head of the list
5054 */
5055
5056 if (*head)
5057 s->next = *head;
5058
5059 *head = s;
5060
5061 return (SLP_TRUE);
5062 }
5063 #endif /* HAVE_LIBSLP */
5064
5065
5066 /*
5067 * 'update_cups_browse()' - Update the browse lists using the CUPS protocol.
5068 */
5069
5070 static void
5071 update_cups_browse(void)
5072 {
5073 int i; /* Looping var */
5074 int auth; /* Authorization status */
5075 int len; /* Length of name string */
5076 int bytes; /* Number of bytes left */
5077 char packet[1541], /* Broadcast packet */
5078 *pptr; /* Pointer into packet */
5079 socklen_t srclen; /* Length of source address */
5080 http_addr_t srcaddr; /* Source address */
5081 char srcname[1024]; /* Source hostname */
5082 unsigned address[4]; /* Source address */
5083 unsigned type; /* Printer type */
5084 unsigned state; /* Printer state */
5085 char uri[HTTP_MAX_URI], /* Printer URI */
5086 host[HTTP_MAX_URI], /* Host portion of URI */
5087 resource[HTTP_MAX_URI], /* Resource portion of URI */
5088 info[IPP_MAX_NAME], /* Information string */
5089 location[IPP_MAX_NAME], /* Location string */
5090 make_model[IPP_MAX_NAME];/* Make and model string */
5091 int num_attrs; /* Number of attributes */
5092 cups_option_t *attrs; /* Attributes */
5093
5094
5095 /*
5096 * Read a packet from the browse socket...
5097 */
5098
5099 srclen = sizeof(srcaddr);
5100 if ((bytes = recvfrom(BrowseSocket, packet, sizeof(packet) - 1, 0,
5101 (struct sockaddr *)&srcaddr, &srclen)) < 0)
5102 {
5103 /*
5104 * "Connection refused" is returned under Linux if the destination port
5105 * or address is unreachable from a previous sendto(); check for the
5106 * error here and ignore it for now...
5107 */
5108
5109 if (errno != ECONNREFUSED && errno != EAGAIN)
5110 {
5111 cupsdLogMessage(CUPSD_LOG_ERROR, "Browse recv failed - %s.",
5112 strerror(errno));
5113 cupsdLogMessage(CUPSD_LOG_ERROR, "CUPS browsing turned off.");
5114
5115 #ifdef WIN32
5116 closesocket(BrowseSocket);
5117 #else
5118 close(BrowseSocket);
5119 #endif /* WIN32 */
5120
5121 cupsdRemoveSelect(BrowseSocket);
5122 BrowseSocket = -1;
5123
5124 BrowseLocalProtocols &= ~BROWSE_CUPS;
5125 BrowseRemoteProtocols &= ~BROWSE_CUPS;
5126 }
5127
5128 return;
5129 }
5130
5131 packet[bytes] = '\0';
5132
5133 /*
5134 * If we're about to sleep, ignore incoming browse packets.
5135 */
5136
5137 if (Sleeping)
5138 return;
5139
5140 /*
5141 * Figure out where it came from...
5142 */
5143
5144 #ifdef AF_INET6
5145 if (srcaddr.addr.sa_family == AF_INET6)
5146 {
5147 address[0] = ntohl(srcaddr.ipv6.sin6_addr.s6_addr32[0]);
5148 address[1] = ntohl(srcaddr.ipv6.sin6_addr.s6_addr32[1]);
5149 address[2] = ntohl(srcaddr.ipv6.sin6_addr.s6_addr32[2]);
5150 address[3] = ntohl(srcaddr.ipv6.sin6_addr.s6_addr32[3]);
5151 }
5152 else
5153 #endif /* AF_INET6 */
5154 {
5155 address[0] = 0;
5156 address[1] = 0;
5157 address[2] = 0;
5158 address[3] = ntohl(srcaddr.ipv4.sin_addr.s_addr);
5159 }
5160
5161 if (HostNameLookups)
5162 httpAddrLookup(&srcaddr, srcname, sizeof(srcname));
5163 else
5164 httpAddrString(&srcaddr, srcname, sizeof(srcname));
5165
5166 len = strlen(srcname);
5167
5168 /*
5169 * Do ACL stuff...
5170 */
5171
5172 if (BrowseACL)
5173 {
5174 if (httpAddrLocalhost(&srcaddr) || !strcasecmp(srcname, "localhost"))
5175 {
5176 /*
5177 * Access from localhost (127.0.0.1) is always allowed...
5178 */
5179
5180 auth = CUPSD_AUTH_ALLOW;
5181 }
5182 else
5183 {
5184 /*
5185 * Do authorization checks on the domain/address...
5186 */
5187
5188 switch (BrowseACL->order_type)
5189 {
5190 default :
5191 auth = CUPSD_AUTH_DENY; /* anti-compiler-warning-code */
5192 break;
5193
5194 case CUPSD_AUTH_ALLOW : /* Order Deny,Allow */
5195 auth = CUPSD_AUTH_ALLOW;
5196
5197 if (cupsdCheckAuth(address, srcname, len,
5198 BrowseACL->num_deny, BrowseACL->deny))
5199 auth = CUPSD_AUTH_DENY;
5200
5201 if (cupsdCheckAuth(address, srcname, len,
5202 BrowseACL->num_allow, BrowseACL->allow))
5203 auth = CUPSD_AUTH_ALLOW;
5204 break;
5205
5206 case CUPSD_AUTH_DENY : /* Order Allow,Deny */
5207 auth = CUPSD_AUTH_DENY;
5208
5209 if (cupsdCheckAuth(address, srcname, len,
5210 BrowseACL->num_allow, BrowseACL->allow))
5211 auth = CUPSD_AUTH_ALLOW;
5212
5213 if (cupsdCheckAuth(address, srcname, len,
5214 BrowseACL->num_deny, BrowseACL->deny))
5215 auth = CUPSD_AUTH_DENY;
5216 break;
5217 }
5218 }
5219 }
5220 else
5221 auth = CUPSD_AUTH_ALLOW;
5222
5223 if (auth == CUPSD_AUTH_DENY)
5224 {
5225 cupsdLogMessage(CUPSD_LOG_DEBUG,
5226 "update_cups_browse: Refused %d bytes from %s", bytes,
5227 srcname);
5228 return;
5229 }
5230
5231 cupsdLogMessage(CUPSD_LOG_DEBUG2,
5232 "update_cups_browse: (%d bytes from %s) %s", bytes,
5233 srcname, packet);
5234
5235 /*
5236 * Parse packet...
5237 */
5238
5239 if (sscanf(packet, "%x%x%1023s", &type, &state, uri) < 3)
5240 {
5241 cupsdLogMessage(CUPSD_LOG_WARN,
5242 "update_cups_browse: Garbled browse packet - %s", packet);
5243 return;
5244 }
5245
5246 strcpy(location, "Location Unknown");
5247 strcpy(info, "No Information Available");
5248 make_model[0] = '\0';
5249 num_attrs = 0;
5250 attrs = NULL;
5251
5252 if ((pptr = strchr(packet, '\"')) != NULL)
5253 {
5254 /*
5255 * Have extended information; can't use sscanf for it because not all
5256 * sscanf's allow empty strings with %[^\"]...
5257 */
5258
5259 for (i = 0, pptr ++;
5260 i < (sizeof(location) - 1) && *pptr && *pptr != '\"';
5261 i ++, pptr ++)
5262 location[i] = *pptr;
5263
5264 if (i)
5265 location[i] = '\0';
5266
5267 if (*pptr == '\"')
5268 pptr ++;
5269
5270 while (*pptr && isspace(*pptr & 255))
5271 pptr ++;
5272
5273 if (*pptr == '\"')
5274 {
5275 for (i = 0, pptr ++;
5276 i < (sizeof(info) - 1) && *pptr && *pptr != '\"';
5277 i ++, pptr ++)
5278 info[i] = *pptr;
5279
5280 info[i] = '\0';
5281
5282 if (*pptr == '\"')
5283 pptr ++;
5284
5285 while (*pptr && isspace(*pptr & 255))
5286 pptr ++;
5287
5288 if (*pptr == '\"')
5289 {
5290 for (i = 0, pptr ++;
5291 i < (sizeof(make_model) - 1) && *pptr && *pptr != '\"';
5292 i ++, pptr ++)
5293 make_model[i] = *pptr;
5294
5295 if (*pptr == '\"')
5296 pptr ++;
5297
5298 make_model[i] = '\0';
5299
5300 if (*pptr)
5301 num_attrs = cupsParseOptions(pptr, num_attrs, &attrs);
5302 }
5303 }
5304 }
5305
5306 DEBUG_puts(packet);
5307 DEBUG_printf(("type=%x, state=%x, uri=\"%s\"\n"
5308 "location=\"%s\", info=\"%s\", make_model=\"%s\"\n",
5309 type, state, uri, location, info, make_model));
5310
5311 /*
5312 * Pull the URI apart to see if this is a local or remote printer...
5313 */
5314
5315 if (is_local_queue(uri, host, sizeof(host), resource, sizeof(resource)))
5316 {
5317 cupsFreeOptions(num_attrs, attrs);
5318 return;
5319 }
5320
5321 /*
5322 * Do relaying...
5323 */
5324
5325 for (i = 0; i < NumRelays; i ++)
5326 if (cupsdCheckAuth(address, srcname, len, 1, &(Relays[i].from)))
5327 if (sendto(BrowseSocket, packet, bytes, 0,
5328 (struct sockaddr *)&(Relays[i].to),
5329 httpAddrLength(&(Relays[i].to))) <= 0)
5330 {
5331 cupsdLogMessage(CUPSD_LOG_ERROR,
5332 "update_cups_browse: sendto failed for relay %d - %s.",
5333 i + 1, strerror(errno));
5334 cupsFreeOptions(num_attrs, attrs);
5335 return;
5336 }
5337
5338 /*
5339 * Process the browse data...
5340 */
5341
5342 process_browse_data(uri, host, resource, (cups_ptype_t)type,
5343 (ipp_pstate_t)state, location, info, make_model,
5344 num_attrs, attrs);
5345 }
5346
5347
5348 /*
5349 * 'update_lpd()' - Update the LPD configuration as needed.
5350 */
5351
5352 static void
5353 update_lpd(int onoff) /* - 1 = turn on, 0 = turn off */
5354 {
5355 if (!LPDConfigFile)
5356 return;
5357
5358 #ifdef __APPLE__
5359 /*
5360 * Allow /etc/hostconfig CUPS_LPD service setting to override cupsd.conf
5361 * setting for backwards-compatibility.
5362 */
5363
5364 if (onoff && !get_hostconfig("CUPS_LPD"))
5365 onoff = 0;
5366 #endif /* __APPLE__ */
5367
5368 if (!strncmp(LPDConfigFile, "xinetd:///", 10))
5369 {
5370 /*
5371 * Enable/disable LPD via the xinetd.d config file for cups-lpd...
5372 */
5373
5374 char newfile[1024]; /* New cups-lpd.N file */
5375 cups_file_t *ofp, /* Original file pointer */
5376 *nfp; /* New file pointer */
5377 char line[1024]; /* Line from file */
5378
5379
5380 snprintf(newfile, sizeof(newfile), "%s.N", LPDConfigFile + 9);
5381
5382 if ((ofp = cupsFileOpen(LPDConfigFile + 9, "r")) == NULL)
5383 {
5384 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open \"%s\" - %s",
5385 LPDConfigFile + 9, strerror(errno));
5386 return;
5387 }
5388
5389 if ((nfp = cupsFileOpen(newfile, "w")) == NULL)
5390 {
5391 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create \"%s\" - %s",
5392 newfile, strerror(errno));
5393 cupsFileClose(ofp);
5394 return;
5395 }
5396
5397 /*
5398 * Copy all of the lines from the cups-lpd file...
5399 */
5400
5401 while (cupsFileGets(ofp, line, sizeof(line)))
5402 {
5403 if (line[0] == '{')
5404 {
5405 cupsFilePrintf(nfp, "%s\n", line);
5406 snprintf(line, sizeof(line), "\tdisable = %s",
5407 onoff ? "no" : "yes");
5408 }
5409 else if (!strstr(line, "disable ="))
5410 cupsFilePrintf(nfp, "%s\n", line);
5411 }
5412
5413 cupsFileClose(nfp);
5414 cupsFileClose(ofp);
5415 rename(newfile, LPDConfigFile + 9);
5416 }
5417 #ifdef __APPLE__
5418 else if (!strncmp(LPDConfigFile, "launchd:///", 11))
5419 {
5420 /*
5421 * Enable/disable LPD via the launchctl command...
5422 */
5423
5424 char *argv[5], /* Arguments for command */
5425 *envp[MAX_ENV]; /* Environment for command */
5426 int pid; /* Process ID */
5427
5428
5429 cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
5430 argv[0] = (char *)"launchctl";
5431 argv[1] = (char *)(onoff ? "load" : "unload");
5432 argv[2] = (char *)"-w";
5433 argv[3] = LPDConfigFile + 10;
5434 argv[4] = NULL;
5435
5436 cupsdStartProcess("/bin/launchctl", argv, envp, -1, -1, -1, -1, -1, 1,
5437 NULL, NULL, &pid);
5438 }
5439 #endif /* __APPLE__ */
5440 else
5441 cupsdLogMessage(CUPSD_LOG_INFO, "Unknown LPDConfigFile scheme!");
5442 }
5443
5444
5445 /*
5446 * 'update_polling()' - Read status messages from the poll daemons.
5447 */
5448
5449 static void
5450 update_polling(void)
5451 {
5452 char *ptr, /* Pointer to end of line in buffer */
5453 message[1024]; /* Pointer to message text */
5454 int loglevel; /* Log level for message */
5455
5456
5457 while ((ptr = cupsdStatBufUpdate(PollStatusBuffer, &loglevel,
5458 message, sizeof(message))) != NULL)
5459 {
5460 if (loglevel == CUPSD_LOG_INFO)
5461 cupsdLogMessage(CUPSD_LOG_INFO, "%s", message);
5462
5463 if (!strchr(PollStatusBuffer->buffer, '\n'))
5464 break;
5465 }
5466
5467 if (ptr == NULL && !PollStatusBuffer->bufused)
5468 {
5469 /*
5470 * All polling processes have died; stop polling...
5471 */
5472
5473 cupsdLogMessage(CUPSD_LOG_ERROR,
5474 "update_polling: all polling processes have exited!");
5475 cupsdStopPolling();
5476 }
5477 }
5478
5479
5480 /*
5481 * 'update_smb()' - Update the SMB configuration as needed.
5482 */
5483
5484 static void
5485 update_smb(int onoff) /* I - 1 = turn on, 0 = turn off */
5486 {
5487 if (!SMBConfigFile)
5488 return;
5489
5490 if (!strncmp(SMBConfigFile, "samba:///", 9))
5491 {
5492 /*
5493 * Enable/disable SMB via the specified smb.conf config file...
5494 */
5495
5496 char newfile[1024]; /* New smb.conf.N file */
5497 cups_file_t *ofp, /* Original file pointer */
5498 *nfp; /* New file pointer */
5499 char line[1024]; /* Line from file */
5500 int in_printers; /* In [printers] section? */
5501
5502
5503 snprintf(newfile, sizeof(newfile), "%s.N", SMBConfigFile + 8);
5504
5505 if ((ofp = cupsFileOpen(SMBConfigFile + 8, "r")) == NULL)
5506 {
5507 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open \"%s\" - %s",
5508 SMBConfigFile + 8, strerror(errno));
5509 return;
5510 }
5511
5512 if ((nfp = cupsFileOpen(newfile, "w")) == NULL)
5513 {
5514 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create \"%s\" - %s",
5515 newfile, strerror(errno));
5516 cupsFileClose(ofp);
5517 return;
5518 }
5519
5520 /*
5521 * Copy all of the lines from the smb.conf file...
5522 */
5523
5524 in_printers = 0;
5525
5526 while (cupsFileGets(ofp, line, sizeof(line)))
5527 {
5528 if (in_printers && strstr(line, "printable ="))
5529 snprintf(line, sizeof(line), " printable = %s",
5530 onoff ? "yes" : "no");
5531
5532 cupsFilePrintf(nfp, "%s\n", line);
5533
5534 if (line[0] == '[')
5535 in_printers = !strcmp(line, "[printers]");
5536 }
5537
5538 cupsFileClose(nfp);
5539 cupsFileClose(ofp);
5540 rename(newfile, SMBConfigFile + 8);
5541 }
5542 else
5543 cupsdLogMessage(CUPSD_LOG_INFO, "Unknown SMBConfigFile scheme!");
5544 }
5545
5546
5547 /*
5548 * End of "$Id: dirsvc.c 7933 2008-09-11 00:44:58Z mike $".
5549 */