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