xref: /aosp_15_r20/external/libcups/scheduler/conf.c (revision 5e7646d21f1134fb0638875d812ef646c12ab91e)
1 /*
2  * Configuration routines for the CUPS scheduler.
3  *
4  * Copyright © 2007-2018 by Apple Inc.
5  * Copyright © 1997-2007 by Easy Software Products, all rights reserved.
6  *
7  * Licensed under Apache License v2.0.  See the file "LICENSE" for more
8  * information.
9  */
10 
11 /*
12  * Include necessary headers...
13  */
14 
15 #include "cupsd.h"
16 #include <stdarg.h>
17 #include <grp.h>
18 #include <sys/utsname.h>
19 #ifdef HAVE_ASL_H
20 #  include <asl.h>
21 #elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
22 #  define SD_JOURNAL_SUPPRESS_LOCATION
23 #  include <systemd/sd-journal.h>
24 #endif /* HAVE_ASL_H */
25 #include <syslog.h>
26 
27 #ifdef HAVE_LIBPAPER
28 #  include <paper.h>
29 #endif /* HAVE_LIBPAPER */
30 
31 
32 /*
33  * Possibly missing network definitions...
34  */
35 
36 #ifndef INADDR_NONE
37 #  define INADDR_NONE	0xffffffff
38 #endif /* !INADDR_NONE */
39 
40 
41 /*
42  * Configuration variable structure...
43  */
44 
45 typedef enum
46 {
47   CUPSD_VARTYPE_INTEGER,		/* Integer option */
48   CUPSD_VARTYPE_TIME,			/* Time interval option */
49   CUPSD_VARTYPE_STRING,			/* String option */
50   CUPSD_VARTYPE_BOOLEAN,		/* Boolean option */
51   CUPSD_VARTYPE_PATHNAME,		/* File/directory name option */
52   CUPSD_VARTYPE_PERM			/* File/directory permissions */
53 } cupsd_vartype_t;
54 
55 typedef struct
56 {
57   const char		*name;		/* Name of variable */
58   void			*ptr;		/* Pointer to variable */
59   cupsd_vartype_t	type;		/* Type (int, string, address) */
60 } cupsd_var_t;
61 
62 
63 /*
64  * Local globals...
65  */
66 
67 static const cupsd_var_t	cupsd_vars[] =
68 {
69   { "AutoPurgeJobs", 		&JobAutoPurge,		CUPSD_VARTYPE_BOOLEAN },
70 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
71   { "BrowseDNSSDSubTypes",	&DNSSDSubTypes,		CUPSD_VARTYPE_STRING },
72 #endif /* HAVE_DNSSD || HAVE_AVAHI */
73   { "BrowseWebIF",		&BrowseWebIF,		CUPSD_VARTYPE_BOOLEAN },
74   { "Browsing",			&Browsing,		CUPSD_VARTYPE_BOOLEAN },
75   { "Classification",		&Classification,	CUPSD_VARTYPE_STRING },
76   { "ClassifyOverride",		&ClassifyOverride,	CUPSD_VARTYPE_BOOLEAN },
77   { "DefaultLanguage",		&DefaultLanguage,	CUPSD_VARTYPE_STRING },
78   { "DefaultLeaseDuration",	&DefaultLeaseDuration,	CUPSD_VARTYPE_TIME },
79   { "DefaultPaperSize",		&DefaultPaperSize,	CUPSD_VARTYPE_STRING },
80   { "DefaultPolicy",		&DefaultPolicy,		CUPSD_VARTYPE_STRING },
81   { "DefaultShared",		&DefaultShared,		CUPSD_VARTYPE_BOOLEAN },
82   { "DirtyCleanInterval",	&DirtyCleanInterval,	CUPSD_VARTYPE_TIME },
83 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
84   { "DNSSDHostName",		&DNSSDHostName,		CUPSD_VARTYPE_STRING },
85 #endif /* HAVE_DNSSD || HAVE_AVAHI */
86   { "ErrorPolicy",		&ErrorPolicy,		CUPSD_VARTYPE_STRING },
87   { "FilterLimit",		&FilterLimit,		CUPSD_VARTYPE_INTEGER },
88   { "FilterNice",		&FilterNice,		CUPSD_VARTYPE_INTEGER },
89 #ifdef HAVE_GSSAPI
90   { "GSSServiceName",		&GSSServiceName,	CUPSD_VARTYPE_STRING },
91 #endif /* HAVE_GSSAPI */
92 #ifdef HAVE_ONDEMAND
93   { "IdleExitTimeout",		&IdleExitTimeout,	CUPSD_VARTYPE_TIME },
94 #endif /* HAVE_ONDEMAND */
95   { "JobKillDelay",		&JobKillDelay,		CUPSD_VARTYPE_TIME },
96   { "JobRetryLimit",		&JobRetryLimit,		CUPSD_VARTYPE_INTEGER },
97   { "JobRetryInterval",		&JobRetryInterval,	CUPSD_VARTYPE_TIME },
98   { "KeepAlive",		&KeepAlive,		CUPSD_VARTYPE_BOOLEAN },
99 #ifdef HAVE_LAUNCHD
100   { "LaunchdTimeout",		&IdleExitTimeout,	CUPSD_VARTYPE_TIME },
101 #endif /* HAVE_LAUNCHD */
102   { "LimitRequestBody",		&MaxRequestSize,	CUPSD_VARTYPE_INTEGER },
103   { "ListenBackLog",		&ListenBackLog,		CUPSD_VARTYPE_INTEGER },
104   { "LogDebugHistory",		&LogDebugHistory,	CUPSD_VARTYPE_INTEGER },
105   { "MaxActiveJobs",		&MaxActiveJobs,		CUPSD_VARTYPE_INTEGER },
106   { "MaxClients",		&MaxClients,		CUPSD_VARTYPE_INTEGER },
107   { "MaxClientsPerHost",	&MaxClientsPerHost,	CUPSD_VARTYPE_INTEGER },
108   { "MaxCopies",		&MaxCopies,		CUPSD_VARTYPE_INTEGER },
109   { "MaxEvents",		&MaxEvents,		CUPSD_VARTYPE_INTEGER },
110   { "MaxHoldTime",		&MaxHoldTime,		CUPSD_VARTYPE_TIME },
111   { "MaxJobs",			&MaxJobs,		CUPSD_VARTYPE_INTEGER },
112   { "MaxJobsPerPrinter",	&MaxJobsPerPrinter,	CUPSD_VARTYPE_INTEGER },
113   { "MaxJobsPerUser",		&MaxJobsPerUser,	CUPSD_VARTYPE_INTEGER },
114   { "MaxJobTime",		&MaxJobTime,		CUPSD_VARTYPE_TIME },
115   { "MaxLeaseDuration",		&MaxLeaseDuration,	CUPSD_VARTYPE_TIME },
116   { "MaxLogSize",		&MaxLogSize,		CUPSD_VARTYPE_INTEGER },
117   { "MaxRequestSize",		&MaxRequestSize,	CUPSD_VARTYPE_INTEGER },
118   { "MaxSubscriptions",		&MaxSubscriptions,	CUPSD_VARTYPE_INTEGER },
119   { "MaxSubscriptionsPerJob",	&MaxSubscriptionsPerJob,	CUPSD_VARTYPE_INTEGER },
120   { "MaxSubscriptionsPerPrinter",&MaxSubscriptionsPerPrinter,	CUPSD_VARTYPE_INTEGER },
121   { "MaxSubscriptionsPerUser",	&MaxSubscriptionsPerUser,	CUPSD_VARTYPE_INTEGER },
122   { "MultipleOperationTimeout",	&MultipleOperationTimeout,	CUPSD_VARTYPE_TIME },
123   { "PageLogFormat",		&PageLogFormat,		CUPSD_VARTYPE_STRING },
124   { "PreserveJobFiles",		&JobFiles,		CUPSD_VARTYPE_TIME },
125   { "PreserveJobHistory",	&JobHistory,		CUPSD_VARTYPE_TIME },
126   { "ReloadTimeout",		&ReloadTimeout,		CUPSD_VARTYPE_TIME },
127   { "RIPCache",			&RIPCache,		CUPSD_VARTYPE_STRING },
128   { "RootCertDuration",		&RootCertDuration,	CUPSD_VARTYPE_TIME },
129   { "ServerAdmin",		&ServerAdmin,		CUPSD_VARTYPE_STRING },
130   { "ServerName",		&ServerName,		CUPSD_VARTYPE_STRING },
131   { "StrictConformance",	&StrictConformance,	CUPSD_VARTYPE_BOOLEAN },
132   { "Timeout",			&Timeout,		CUPSD_VARTYPE_TIME },
133   { "WebInterface",		&WebInterface,		CUPSD_VARTYPE_BOOLEAN }
134 };
135 static const cupsd_var_t	cupsfiles_vars[] =
136 {
137   { "AccessLog",		&AccessLog,		CUPSD_VARTYPE_STRING },
138   { "CacheDir",			&CacheDir,		CUPSD_VARTYPE_STRING },
139   { "ConfigFilePerm",		&ConfigFilePerm,	CUPSD_VARTYPE_PERM },
140 #ifdef HAVE_SSL
141   { "CreateSelfSignedCerts",	&CreateSelfSignedCerts,	CUPSD_VARTYPE_BOOLEAN },
142 #endif /* HAVE_SSL */
143   { "DataDir",			&DataDir,		CUPSD_VARTYPE_STRING },
144   { "DocumentRoot",		&DocumentRoot,		CUPSD_VARTYPE_STRING },
145   { "ErrorLog",			&ErrorLog,		CUPSD_VARTYPE_STRING },
146   { "FileDevice",		&FileDevice,		CUPSD_VARTYPE_BOOLEAN },
147   { "FontPath",			&FontPath,		CUPSD_VARTYPE_STRING },
148   { "LogFilePerm",		&LogFilePerm,		CUPSD_VARTYPE_PERM },
149   { "LPDConfigFile",		&LPDConfigFile,		CUPSD_VARTYPE_STRING },
150   { "PageLog",			&PageLog,		CUPSD_VARTYPE_STRING },
151   { "Printcap",			&Printcap,		CUPSD_VARTYPE_STRING },
152   { "RemoteRoot",		&RemoteRoot,		CUPSD_VARTYPE_STRING },
153   { "RequestRoot",		&RequestRoot,		CUPSD_VARTYPE_STRING },
154   { "ServerBin",		&ServerBin,		CUPSD_VARTYPE_PATHNAME },
155 #ifdef HAVE_SSL
156   { "ServerKeychain",		&ServerKeychain,	CUPSD_VARTYPE_PATHNAME },
157 #endif /* HAVE_SSL */
158   { "ServerRoot",		&ServerRoot,		CUPSD_VARTYPE_PATHNAME },
159   { "SMBConfigFile",		&SMBConfigFile,		CUPSD_VARTYPE_STRING },
160   { "StateDir",			&StateDir,		CUPSD_VARTYPE_STRING },
161   { "SyncOnClose",		&SyncOnClose,		CUPSD_VARTYPE_BOOLEAN },
162 #ifdef HAVE_AUTHORIZATION_H
163   { "SystemGroupAuthKey",	&SystemGroupAuthKey,	CUPSD_VARTYPE_STRING },
164 #endif /* HAVE_AUTHORIZATION_H */
165   { "TempDir",			&TempDir,		CUPSD_VARTYPE_PATHNAME }
166 };
167 
168 static int		default_auth_type = CUPSD_AUTH_AUTO;
169 					/* Default AuthType, if not specified */
170 
171 static const unsigned	ones[4] =
172 			{
173 			  0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff
174 			};
175 static const unsigned	zeros[4] =
176 			{
177 			  0x00000000, 0x00000000, 0x00000000, 0x00000000
178 			};
179 
180 
181 /*
182  * Local functions...
183  */
184 
185 static http_addrlist_t	*get_address(const char *value, int defport);
186 static int		get_addr_and_mask(const char *value, unsigned *ip,
187 			                  unsigned *mask);
188 static void		mime_error_cb(void *ctx, const char *message);
189 static int		parse_aaa(cupsd_location_t *loc, char *line,
190 			          char *value, int linenum);
191 static int		parse_fatal_errors(const char *s);
192 static int		parse_groups(const char *s, int linenum);
193 static int		parse_protocols(const char *s);
194 static int		parse_variable(const char *filename, int linenum,
195 			               const char *line, const char *value,
196 			               size_t num_vars,
197 			               const cupsd_var_t *vars);
198 static int		read_cupsd_conf(cups_file_t *fp);
199 static int		read_cups_files_conf(cups_file_t *fp);
200 static int		read_location(cups_file_t *fp, char *name, int linenum);
201 static int		read_policy(cups_file_t *fp, char *name, int linenum);
202 static void		set_policy_defaults(cupsd_policy_t *pol);
203 
204 
205 /*
206  * 'cupsdAddAlias()' - Add a host alias.
207  */
208 
209 void
cupsdAddAlias(cups_array_t * aliases,const char * name)210 cupsdAddAlias(cups_array_t *aliases,	/* I - Array of aliases */
211               const char   *name)	/* I - Name to add */
212 {
213   cupsd_alias_t	*a;			/*  New alias */
214   size_t	namelen;		/* Length of name */
215 
216 
217   namelen = strlen(name);
218 
219   if ((a = (cupsd_alias_t *)malloc(sizeof(cupsd_alias_t) + namelen)) == NULL)
220     return;
221 
222   a->namelen = namelen;
223   memcpy(a->name, name, namelen + 1);	/* OK since a->name is allocated */
224 
225   cupsArrayAdd(aliases, a);
226 }
227 
228 
229 /*
230  * 'cupsdCheckPermissions()' - Fix the mode and ownership of a file or directory.
231  */
232 
233 int					/* O - 0 on success, -1 on error, 1 on warning */
cupsdCheckPermissions(const char * filename,const char * suffix,mode_t mode,uid_t user,gid_t group,int is_dir,int create_dir)234 cupsdCheckPermissions(
235     const char *filename,		/* I - File/directory name */
236     const char *suffix,			/* I - Additional file/directory name */
237     mode_t     mode,			/* I - Permissions */
238     uid_t      user,			/* I - Owner */
239     gid_t      group,			/* I - Group */
240     int        is_dir,			/* I - 1 = directory, 0 = file */
241     int        create_dir)		/* I - 1 = create directory, -1 = create w/o logging, 0 = not */
242 {
243   int		dir_created = 0;	/* Did we create a directory? */
244   char		pathname[1024];		/* File name with prefix */
245   struct stat	fileinfo;		/* Stat buffer */
246   int		is_symlink;		/* Is "filename" a symlink? */
247 
248 
249  /*
250   * Prepend the given root to the filename before testing it...
251   */
252 
253   if (suffix)
254   {
255     snprintf(pathname, sizeof(pathname), "%s/%s", filename, suffix);
256     filename = pathname;
257   }
258 
259  /*
260   * See if we can stat the file/directory...
261   */
262 
263   if (lstat(filename, &fileinfo))
264   {
265     if (errno == ENOENT && create_dir)
266     {
267       if (create_dir > 0)
268 	cupsdLogMessage(CUPSD_LOG_DEBUG, "Creating missing directory \"%s\"",
269 			filename);
270 
271       if (mkdir(filename, mode))
272       {
273         if (create_dir > 0)
274 	  cupsdLogMessage(CUPSD_LOG_ERROR,
275 			  "Unable to create directory \"%s\" - %s", filename,
276 			  strerror(errno));
277         else
278 #ifdef HAVE_SYSTEMD_SD_JOURNAL_H
279 	  sd_journal_print(LOG_ERR, "Unable to create directory \"%s\" - %s", filename, strerror(errno));
280 #else
281 	  syslog(LOG_ERR, "Unable to create directory \"%s\" - %s", filename, strerror(errno));
282 #endif /* HAVE_SYSTEMD_SD_JOURNAL_H */
283 
284         return (-1);
285       }
286 
287       dir_created      = 1;
288       fileinfo.st_mode = mode | S_IFDIR;
289     }
290     else
291       return (create_dir ? -1 : 1);
292   }
293 
294   if ((is_symlink = S_ISLNK(fileinfo.st_mode)) != 0)
295   {
296     if (stat(filename, &fileinfo))
297     {
298       cupsdLogMessage(CUPSD_LOG_ERROR, "\"%s\" is a bad symlink - %s",
299                       filename, strerror(errno));
300       return (-1);
301     }
302   }
303 
304  /*
305   * Make sure it's a regular file or a directory as needed...
306   */
307 
308   if (!dir_created && !is_dir && !S_ISREG(fileinfo.st_mode))
309   {
310     cupsdLogMessage(CUPSD_LOG_ERROR, "\"%s\" is not a regular file.", filename);
311     return (-1);
312   }
313 
314   if (!dir_created && is_dir && !S_ISDIR(fileinfo.st_mode))
315   {
316     if (create_dir >= 0)
317       cupsdLogMessage(CUPSD_LOG_ERROR, "\"%s\" is not a directory.", filename);
318     else
319 #ifdef HAVE_SYSTEMD_SD_JOURNAL_H
320       sd_journal_print(LOG_ERR, "\"%s\" is not a directory.", filename);
321 #else
322       syslog(LOG_ERR, "\"%s\" is not a directory.", filename);
323 #endif /* HAVE_SYSTEMD_SD_JOURNAL_H */
324 
325     return (-1);
326   }
327 
328  /*
329   * If the filename is a symlink, do not change permissions (STR #2937)...
330   */
331 
332   if (is_symlink)
333     return (0);
334 
335  /*
336   * Fix owner, group, and mode as needed...
337   */
338 
339   if (dir_created || fileinfo.st_uid != user || fileinfo.st_gid != group)
340   {
341     if (create_dir >= 0)
342       cupsdLogMessage(CUPSD_LOG_DEBUG, "Repairing ownership of \"%s\"",
343                       filename);
344 
345     if (chown(filename, user, group) && !getuid())
346     {
347       if (create_dir >= 0)
348 	cupsdLogMessage(CUPSD_LOG_ERROR,
349 			"Unable to change ownership of \"%s\" - %s", filename,
350 			strerror(errno));
351       else
352 #ifdef HAVE_SYSTEMD_SD_JOURNAL_H
353 	sd_journal_print(LOG_ERR, "Unable to change ownership of \"%s\" - %s", filename, strerror(errno));
354 #else
355 	syslog(LOG_ERR, "Unable to change ownership of \"%s\" - %s", filename, strerror(errno));
356 #endif /* HAVE_SYSTEMD_SD_JOURNAL_H */
357 
358       return (1);
359     }
360   }
361 
362   if (dir_created || (fileinfo.st_mode & 07777) != mode)
363   {
364     if (create_dir >= 0)
365       cupsdLogMessage(CUPSD_LOG_DEBUG, "Repairing access permissions of \"%s\"",
366 		      filename);
367 
368     if (chmod(filename, mode))
369     {
370       if (create_dir >= 0)
371 	cupsdLogMessage(CUPSD_LOG_ERROR,
372 			"Unable to change permissions of \"%s\" - %s", filename,
373 			strerror(errno));
374       else
375 #ifdef HAVE_SYSTEMD_SD_JOURNAL_H
376 	sd_journal_print(LOG_ERR, "Unable to change permissions of \"%s\" - %s", filename, strerror(errno));
377 #else
378 	syslog(LOG_ERR, "Unable to change permissions of \"%s\" - %s", filename, strerror(errno));
379 #endif /* HAVE_SYSTEMD_SD_JOURNAL_H */
380 
381       return (1);
382     }
383   }
384 
385  /*
386   * Everything is OK...
387   */
388 
389   return (0);
390 }
391 
392 
393 /*
394  * 'cupsdDefaultAuthType()' - Get the default AuthType.
395  *
396  * When the default_auth_type is "auto", this function tries to get the GSS
397  * credentials for the server.  If that succeeds we use Kerberos authentication,
398  * otherwise we do a fallback to Basic authentication against the local user
399  * accounts.
400  */
401 
402 int					/* O - Default AuthType value */
cupsdDefaultAuthType(void)403 cupsdDefaultAuthType(void)
404 {
405 #ifdef HAVE_GSSAPI
406   OM_uint32	major_status,		/* Major status code */
407 		minor_status;		/* Minor status code */
408   gss_name_t	server_name;		/* Server name */
409   gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
410 					/* Service name token */
411   char		buf[1024];		/* Service name buffer */
412 #endif /* HAVE_GSSAPI */
413 
414 
415  /*
416   * If we have already determined the correct default AuthType, use it...
417   */
418 
419   if (default_auth_type != CUPSD_AUTH_AUTO)
420     return (default_auth_type);
421 
422 #ifdef HAVE_GSSAPI
423 #  ifdef __APPLE__
424  /*
425   * If the weak-linked GSSAPI/Kerberos library is not present, don't try
426   * to use it...
427   */
428 
429   if (&gss_init_sec_context == NULL)
430     return (default_auth_type = CUPSD_AUTH_BASIC);
431 #  endif /* __APPLE__ */
432 
433  /*
434   * Try to obtain the server's GSS credentials (GSSServiceName@servername).  If
435   * that fails we must use Basic...
436   */
437 
438   snprintf(buf, sizeof(buf), "%s@%s", GSSServiceName, ServerName);
439 
440   token.value  = buf;
441   token.length = strlen(buf);
442   server_name  = GSS_C_NO_NAME;
443   major_status = gss_import_name(&minor_status, &token,
444 	 			 GSS_C_NT_HOSTBASED_SERVICE,
445 				 &server_name);
446 
447   memset(&token, 0, sizeof(token));
448 
449   if (GSS_ERROR(major_status))
450   {
451     cupsdLogGSSMessage(CUPSD_LOG_DEBUG, major_status, minor_status,
452 		       "cupsdDefaultAuthType: gss_import_name(%s) failed", buf);
453     return (default_auth_type = CUPSD_AUTH_BASIC);
454   }
455 
456   major_status = gss_display_name(&minor_status, server_name, &token, NULL);
457 
458   if (GSS_ERROR(major_status))
459   {
460     cupsdLogGSSMessage(CUPSD_LOG_DEBUG, major_status, minor_status,
461                        "cupsdDefaultAuthType: gss_display_name(%s) failed",
462                        buf);
463     return (default_auth_type = CUPSD_AUTH_BASIC);
464   }
465 
466   cupsdLogMessage(CUPSD_LOG_DEBUG,
467                   "cupsdDefaultAuthType: Attempting to acquire Kerberos "
468                   "credentials for %s...", (char *)token.value);
469 
470   ServerCreds  = GSS_C_NO_CREDENTIAL;
471   major_status = gss_acquire_cred(&minor_status, server_name, GSS_C_INDEFINITE,
472 				  GSS_C_NO_OID_SET, GSS_C_ACCEPT,
473 				  &ServerCreds, NULL, NULL);
474   if (GSS_ERROR(major_status))
475   {
476     cupsdLogGSSMessage(CUPSD_LOG_DEBUG, major_status, minor_status,
477                        "cupsdDefaultAuthType: gss_acquire_cred(%s) failed",
478                        (char *)token.value);
479     gss_release_name(&minor_status, &server_name);
480     gss_release_buffer(&minor_status, &token);
481     return (default_auth_type = CUPSD_AUTH_BASIC);
482   }
483 
484   cupsdLogMessage(CUPSD_LOG_DEBUG,
485                   "cupsdDefaultAuthType: Kerberos credentials acquired "
486                   "successfully for %s.", (char *)token.value);
487 
488   gss_release_name(&minor_status, &server_name);
489   gss_release_buffer(&minor_status, &token);
490 
491   HaveServerCreds = 1;
492 
493   return (default_auth_type = CUPSD_AUTH_NEGOTIATE);
494 
495 #else
496  /*
497   * No Kerberos support compiled in so just use Basic all the time...
498   */
499 
500   return (default_auth_type = CUPSD_AUTH_BASIC);
501 #endif /* HAVE_GSSAPI */
502 }
503 
504 
505 /*
506  * 'cupsdFreeAliases()' - Free all of the alias entries.
507  */
508 
509 void
cupsdFreeAliases(cups_array_t * aliases)510 cupsdFreeAliases(cups_array_t *aliases)	/* I - Array of aliases */
511 {
512   cupsd_alias_t	*a;			/* Current alias */
513 
514 
515   for (a = (cupsd_alias_t *)cupsArrayFirst(aliases);
516        a;
517        a = (cupsd_alias_t *)cupsArrayNext(aliases))
518     free(a);
519 
520   cupsArrayDelete(aliases);
521 }
522 
523 
524 /*
525  * 'cupsdReadConfiguration()' - Read the cupsd.conf file.
526  */
527 
528 int					/* O - 1 on success, 0 otherwise */
cupsdReadConfiguration(void)529 cupsdReadConfiguration(void)
530 {
531   int		i;			/* Looping var */
532   cups_file_t	*fp;			/* Configuration file */
533   int		status;			/* Return status */
534   char		temp[1024],		/* Temporary buffer */
535 		mimedir[1024],		/* MIME directory */
536 		*slash;			/* Directory separator */
537   cups_lang_t	*language;		/* Language */
538   struct passwd	*user;			/* Default user */
539   struct group	*group;			/* Default group */
540   char		*old_serverroot,	/* Old ServerRoot */
541 		*old_requestroot;	/* Old RequestRoot */
542   int		old_remote_port;	/* Old RemotePort */
543   const char	*tmpdir;		/* TMPDIR environment variable */
544   struct stat	tmpinfo;		/* Temporary directory info */
545   cupsd_policy_t *p;			/* Policy */
546 
547 
548  /*
549   * Save the old root paths...
550   */
551 
552   old_serverroot = NULL;
553   cupsdSetString(&old_serverroot, ServerRoot);
554   old_requestroot = NULL;
555   cupsdSetString(&old_requestroot, RequestRoot);
556 
557  /*
558   * Reset the server configuration data...
559   */
560 
561   cupsdDeleteAllLocations();
562 
563   cupsdDeleteAllListeners();
564 
565   old_remote_port = RemotePort;
566   RemotePort      = 0;
567 
568  /*
569   * String options...
570   */
571 
572   cupsdFreeAliases(ServerAlias);
573   ServerAlias = NULL;
574 
575   cupsdClearString(&ServerName);
576   cupsdClearString(&ServerAdmin);
577   cupsdSetString(&ServerBin, CUPS_SERVERBIN);
578   cupsdSetString(&RequestRoot, CUPS_REQUESTS);
579   cupsdSetString(&CacheDir, CUPS_CACHEDIR);
580   cupsdSetString(&DataDir, CUPS_DATADIR);
581   cupsdSetString(&DocumentRoot, CUPS_DOCROOT);
582   cupsdSetString(&AccessLog, CUPS_LOGDIR "/access_log");
583   cupsdClearString(&ErrorLog);
584   cupsdSetString(&PageLog, CUPS_LOGDIR "/page_log");
585   cupsdSetString(&PageLogFormat,
586                  "%p %u %j %T %P %C %{job-billing} "
587 		 "%{job-originating-host-name} %{job-name} %{media} %{sides}");
588   cupsdSetString(&Printcap, CUPS_DEFAULT_PRINTCAP);
589   cupsdSetString(&FontPath, CUPS_FONTPATH);
590   cupsdSetString(&RemoteRoot, "remroot");
591   cupsdSetStringf(&ServerHeader, "CUPS/%d.%d IPP/2.1", CUPS_VERSION_MAJOR,
592                   CUPS_VERSION_MINOR);
593   cupsdSetString(&StateDir, CUPS_STATEDIR);
594 
595   if (!strcmp(CUPS_DEFAULT_PRINTCAP, "/etc/printers.conf"))
596     PrintcapFormat = PRINTCAP_SOLARIS;
597   else if (!strcmp(CUPS_DEFAULT_PRINTCAP,
598                    "/Library/Preferences/org.cups.printers.plist"))
599     PrintcapFormat = PRINTCAP_PLIST;
600   else
601     PrintcapFormat = PRINTCAP_BSD;
602 
603   strlcpy(temp, ConfigurationFile, sizeof(temp));
604   if ((slash = strrchr(temp, '/')) != NULL)
605     *slash = '\0';
606 
607   cupsdSetString(&ServerRoot, temp);
608 
609   cupsdClearString(&Classification);
610   ClassifyOverride  = 0;
611 
612 #ifdef HAVE_SSL
613 #  ifdef HAVE_GNUTLS
614   cupsdSetString(&ServerKeychain, "ssl");
615 #  else
616   cupsdSetString(&ServerKeychain, "/Library/Keychains/System.keychain");
617 #  endif /* HAVE_GNUTLS */
618 
619   _httpTLSSetOptions(_HTTP_TLS_NONE, _HTTP_TLS_1_0, _HTTP_TLS_MAX);
620 #endif /* HAVE_SSL */
621 
622   language = cupsLangDefault();
623 
624   if (!strcmp(language->language, "C") || !strcmp(language->language, "POSIX"))
625     cupsdSetString(&DefaultLanguage, "en");
626   else
627     cupsdSetString(&DefaultLanguage, language->language);
628 
629   cupsdClearString(&DefaultPaperSize);
630 
631   cupsdSetString(&RIPCache, "128m");
632 
633   cupsdSetString(&TempDir, NULL);
634 
635 #ifdef HAVE_GSSAPI
636   cupsdSetString(&GSSServiceName, CUPS_DEFAULT_GSSSERVICENAME);
637 
638   if (HaveServerCreds)
639   {
640     OM_uint32	minor_status;		/* Minor status code */
641 
642     gss_release_cred(&minor_status, &ServerCreds);
643 
644     HaveServerCreds = 0;
645   }
646 
647   ServerCreds = GSS_C_NO_CREDENTIAL;
648 #endif /* HAVE_GSSAPI */
649 
650  /*
651   * Find the default user...
652   */
653 
654   if ((user = getpwnam(CUPS_DEFAULT_USER)) != NULL)
655     User = user->pw_uid;
656   else
657   {
658    /*
659     * Use the (historical) NFS nobody user ID (-2 as a 16-bit twos-
660     * complement number...)
661     */
662 
663     User = 65534;
664   }
665 
666   endpwent();
667 
668  /*
669   * Find the default group...
670   */
671 
672   group = getgrnam(CUPS_DEFAULT_GROUP);
673   endgrent();
674 
675   if (group)
676     Group = group->gr_gid;
677   else
678   {
679    /*
680     * Fallback to group "nobody"...
681     */
682 
683     group = getgrnam("nobody");
684     endgrent();
685 
686     if (group)
687       Group = group->gr_gid;
688     else
689     {
690      /*
691       * Use the (historical) NFS nobody group ID (-2 as a 16-bit twos-
692       * complement number...)
693       */
694 
695       Group = 65534;
696     }
697   }
698 
699  /*
700   * Numeric options...
701   */
702 
703   AccessLogLevel           = CUPSD_ACCESSLOG_ACTIONS;
704   ConfigFilePerm           = CUPS_DEFAULT_CONFIG_FILE_PERM;
705   FatalErrors              = parse_fatal_errors(CUPS_DEFAULT_FATAL_ERRORS);
706   default_auth_type        = CUPSD_AUTH_BASIC;
707 #ifdef HAVE_SSL
708   CreateSelfSignedCerts    = TRUE;
709   DefaultEncryption        = HTTP_ENCRYPT_REQUIRED;
710 #endif /* HAVE_SSL */
711   DirtyCleanInterval       = DEFAULT_KEEPALIVE;
712   JobKillDelay             = DEFAULT_TIMEOUT;
713   JobRetryLimit            = 5;
714   JobRetryInterval         = 300;
715   FileDevice               = FALSE;
716   FilterLevel              = 0;
717   FilterLimit              = 0;
718   FilterNice               = 0;
719   HostNameLookups          = FALSE;
720   KeepAlive                = TRUE;
721   ListenBackLog            = SOMAXCONN;
722   LogDebugHistory          = 200;
723   LogFilePerm              = CUPS_DEFAULT_LOG_FILE_PERM;
724   LogLevel                 = CUPSD_LOG_WARN;
725   LogTimeFormat            = CUPSD_TIME_STANDARD;
726   MaxClients               = 100;
727   MaxClientsPerHost        = 0;
728   MaxLogSize               = 1024 * 1024;
729   MaxRequestSize           = 0;
730   MultipleOperationTimeout = 900;
731   NumSystemGroups          = 0;
732   ReloadTimeout	           = DEFAULT_KEEPALIVE;
733   RootCertDuration         = 300;
734   Sandboxing               = CUPSD_SANDBOXING_STRICT;
735   StrictConformance        = FALSE;
736   SyncOnClose              = FALSE;
737   Timeout                  = 900;
738   WebInterface             = CUPS_DEFAULT_WEBIF;
739 
740   BrowseLocalProtocols     = parse_protocols(CUPS_DEFAULT_BROWSE_LOCAL_PROTOCOLS);
741   BrowseWebIF              = FALSE;
742   Browsing                 = CUPS_DEFAULT_BROWSING;
743   DefaultShared            = CUPS_DEFAULT_DEFAULT_SHARED;
744 
745 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
746   cupsdSetString(&DNSSDSubTypes, "_cups,_print");
747   cupsdClearString(&DNSSDHostName);
748 #endif /* HAVE_DNSSD || HAVE_AVAHI */
749 
750   cupsdSetString(&LPDConfigFile, CUPS_DEFAULT_LPD_CONFIG_FILE);
751   cupsdSetString(&SMBConfigFile, CUPS_DEFAULT_SMB_CONFIG_FILE);
752 
753   cupsdSetString(&ErrorPolicy, "stop-printer");
754 
755   JobHistory          = DEFAULT_HISTORY;
756   JobFiles            = DEFAULT_FILES;
757   JobAutoPurge        = 0;
758   MaxHoldTime         = 0;
759   MaxJobs             = 500;
760   MaxActiveJobs       = 0;
761   MaxJobsPerUser      = 0;
762   MaxJobsPerPrinter   = 0;
763   MaxJobTime          = 3 * 60 * 60;	/* 3 hours */
764   MaxCopies           = CUPS_DEFAULT_MAX_COPIES;
765 
766   cupsdDeleteAllPolicies();
767   cupsdClearString(&DefaultPolicy);
768 
769 #ifdef HAVE_AUTHORIZATION_H
770   cupsdSetString(&SystemGroupAuthKey, CUPS_DEFAULT_SYSTEM_AUTHKEY);
771 #endif /* HAVE_AUTHORIZATION_H */
772 
773   MaxSubscriptions           = 100;
774   MaxSubscriptionsPerJob     = 0;
775   MaxSubscriptionsPerPrinter = 0;
776   MaxSubscriptionsPerUser    = 0;
777   DefaultLeaseDuration       = 86400;
778   MaxLeaseDuration           = 0;
779 
780 #ifdef HAVE_ONDEMAND
781   IdleExitTimeout = 60;
782 #endif /* HAVE_ONDEMAND */
783 
784  /*
785   * Setup environment variables...
786   */
787 
788   cupsdInitEnv();
789 
790  /*
791   * Read the cups-files.conf file...
792   */
793 
794   if ((fp = cupsFileOpen(CupsFilesFile, "r")) != NULL)
795   {
796     status = read_cups_files_conf(fp);
797 
798     cupsFileClose(fp);
799 
800     if (!status)
801     {
802       if (TestConfigFile)
803         printf("\"%s\" contains errors.\n", CupsFilesFile);
804       else
805 #ifdef HAVE_SYSTEMD_SD_JOURNAL_H
806 	sd_journal_print(LOG_ERR, "Unable to read \"%s\" due to errors.", CupsFilesFile);
807 #else
808         syslog(LOG_LPR, "Unable to read \"%s\" due to errors.", CupsFilesFile);
809 #endif /* HAVE_SYSTEMD_SD_JOURNAL_H */
810 
811       return (0);
812     }
813   }
814   else if (errno == ENOENT)
815     cupsdLogMessage(CUPSD_LOG_INFO, "No %s, using defaults.", CupsFilesFile);
816   else
817   {
818 #ifdef HAVE_SYSTEMD_SD_JOURNAL_H
819     sd_journal_print(LOG_ERR, "Unable to open \"%s\" - %s", CupsFilesFile, strerror(errno));
820 #else
821     syslog(LOG_LPR, "Unable to open \"%s\" - %s", CupsFilesFile, strerror(errno));
822 #endif /* HAVE_SYSTEMD_SD_JOURNAL_H */
823 
824     return (0);
825   }
826 
827   if (!ErrorLog)
828     cupsdSetString(&ErrorLog, CUPS_LOGDIR "/error_log");
829 
830  /*
831   * Read the cupsd.conf file...
832   */
833 
834   if ((fp = cupsFileOpen(ConfigurationFile, "r")) == NULL)
835   {
836 #ifdef HAVE_SYSTEMD_SD_JOURNAL_H
837     sd_journal_print(LOG_ERR, "Unable to open \"%s\" - %s", ConfigurationFile, strerror(errno));
838 #else
839     syslog(LOG_LPR, "Unable to open \"%s\" - %s", ConfigurationFile, strerror(errno));
840 #endif /* HAVE_SYSTEMD_SD_JOURNAL_H */
841 
842     return (0);
843   }
844 
845   status = read_cupsd_conf(fp);
846 
847   cupsFileClose(fp);
848 
849   if (!status)
850   {
851     if (TestConfigFile)
852       printf("\"%s\" contains errors.\n", ConfigurationFile);
853     else
854 #ifdef HAVE_SYSTEMD_SD_JOURNAL_H
855       sd_journal_print(LOG_ERR, "Unable to read \"%s\" due to errors.", ConfigurationFile);
856 #else
857       syslog(LOG_LPR, "Unable to read \"%s\" due to errors.", ConfigurationFile);
858 #endif /* HAVE_SYSTEMD_SD_JOURNAL_H */
859 
860     return (0);
861   }
862 
863   RunUser = getuid();
864 
865   cupsdLogMessage(CUPSD_LOG_INFO, "Remote access is %s.",
866                   RemotePort ? "enabled" : "disabled");
867 
868   if (!RemotePort)
869     BrowseLocalProtocols = 0;		/* Disable sharing - no remote access */
870 
871  /*
872   * See if the ServerName is an IP address...
873   */
874 
875   if (ServerName)
876   {
877     if (!ServerAlias)
878       ServerAlias = cupsArrayNew(NULL, NULL);
879 
880     cupsdAddAlias(ServerAlias, ServerName);
881     cupsdLogMessage(CUPSD_LOG_DEBUG, "Added auto ServerAlias %s", ServerName);
882   }
883   else
884   {
885     if (gethostname(temp, sizeof(temp)))
886     {
887       cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to get hostname: %s",
888                       strerror(errno));
889       strlcpy(temp, "localhost", sizeof(temp));
890     }
891 
892     cupsdSetString(&ServerName, temp);
893 
894     if (!ServerAlias)
895       ServerAlias = cupsArrayNew(NULL, NULL);
896 
897     cupsdAddAlias(ServerAlias, temp);
898     cupsdLogMessage(CUPSD_LOG_DEBUG, "Added auto ServerAlias %s", temp);
899 
900     if (HostNameLookups || RemotePort)
901     {
902       struct hostent	*host;		/* Host entry to get FQDN */
903 
904       if ((host = gethostbyname(temp)) != NULL)
905       {
906         if (_cups_strcasecmp(temp, host->h_name))
907         {
908 	  cupsdSetString(&ServerName, host->h_name);
909 	  cupsdAddAlias(ServerAlias, host->h_name);
910           cupsdLogMessage(CUPSD_LOG_DEBUG, "Added auto ServerAlias %s",
911 	                  host->h_name);
912 	}
913 
914         if (host->h_aliases)
915 	{
916           for (i = 0; host->h_aliases[i]; i ++)
917 	    if (_cups_strcasecmp(temp, host->h_aliases[i]))
918 	    {
919 	      cupsdAddAlias(ServerAlias, host->h_aliases[i]);
920 	      cupsdLogMessage(CUPSD_LOG_DEBUG, "Added auto ServerAlias %s",
921 	                      host->h_aliases[i]);
922 	    }
923 	}
924       }
925     }
926 
927    /*
928     * Make sure we have the base hostname added as an alias, too!
929     */
930 
931     if ((slash = strchr(temp, '.')) != NULL)
932     {
933       *slash = '\0';
934       cupsdAddAlias(ServerAlias, temp);
935       cupsdLogMessage(CUPSD_LOG_DEBUG, "Added auto ServerAlias %s", temp);
936     }
937   }
938 
939   for (slash = ServerName; isdigit(*slash & 255) || *slash == '.'; slash ++);
940 
941   ServerNameIsIP = !*slash;
942 
943  /*
944   * Make sure ServerAdmin is initialized...
945   */
946 
947   if (!ServerAdmin)
948     cupsdSetStringf(&ServerAdmin, "root@%s", ServerName);
949 
950  /*
951   * Use the default system group if none was supplied in cupsd.conf...
952   */
953 
954   if (NumSystemGroups == 0)
955   {
956     if (!parse_groups(CUPS_DEFAULT_SYSTEM_GROUPS, 0))
957     {
958      /*
959       * Find the group associated with GID 0...
960       */
961 
962       group = getgrgid(0);
963       endgrent();
964 
965       if (group != NULL)
966 	cupsdSetString(&SystemGroups[0], group->gr_name);
967       else
968 	cupsdSetString(&SystemGroups[0], "unknown");
969 
970       SystemGroupIDs[0] = 0;
971       NumSystemGroups   = 1;
972     }
973   }
974 
975  /*
976   * Make sure ConfigFilePerm and LogFilePerm have sane values...
977   */
978 
979   ConfigFilePerm &= 0664;
980   LogFilePerm    &= 0664;
981 
982  /*
983   * Open the system log for cupsd if necessary...
984   */
985 
986   if (!LogStderr)
987   {
988     if (!strcmp(AccessLog, "stderr"))
989       cupsdSetString(&AccessLog, "syslog");
990 
991     if (!strcmp(ErrorLog, "stderr"))
992       cupsdSetString(&ErrorLog, "syslog");
993 
994     if (!strcmp(PageLog, "stderr"))
995       cupsdSetString(&PageLog, "syslog");
996   }
997 
998 #if defined(HAVE_VSYSLOG) && !defined(HAVE_ASL_H) && !defined(HAVE_SYSTEMD_SD_JOURNAL_H)
999   if (!strcmp(AccessLog, "syslog") ||
1000       !strcmp(ErrorLog, "syslog") ||
1001       !strcmp(PageLog, "syslog"))
1002     openlog("cupsd", LOG_PID | LOG_NOWAIT | LOG_NDELAY, LOG_LPR);
1003 #endif /* HAVE_VSYSLOG && !HAVE_ASL_H && !HAVE_SYSTEMD_SD_JOURNAL_H */
1004 
1005  /*
1006   * Log the configuration file that was used...
1007   */
1008 
1009   cupsdLogMessage(CUPSD_LOG_INFO, "Loaded configuration file \"%s\"",
1010                   ConfigurationFile);
1011 
1012  /*
1013   * Validate the Group and SystemGroup settings - they cannot be the same,
1014   * otherwise the CGI programs will be able to authenticate as root without
1015   * a password!
1016   */
1017 
1018   if (!RunUser)
1019   {
1020     for (i = 0; i < NumSystemGroups; i ++)
1021       if (Group == SystemGroupIDs[i])
1022         break;
1023 
1024     if (i < NumSystemGroups)
1025     {
1026      /*
1027       * Log the error and reset the group to a safe value...
1028       */
1029 
1030       cupsdLogMessage(CUPSD_LOG_ERROR,
1031                       "Group and SystemGroup cannot use the same groups.");
1032       if (FatalErrors & (CUPSD_FATAL_CONFIG | CUPSD_FATAL_PERMISSIONS))
1033         return (0);
1034 
1035       cupsdLogMessage(CUPSD_LOG_INFO, "Resetting Group to \"nobody\"...");
1036 
1037       group = getgrnam("nobody");
1038       endgrent();
1039 
1040       if (group != NULL)
1041 	Group = group->gr_gid;
1042       else
1043       {
1044        /*
1045 	* Use the (historical) NFS nobody group ID (-2 as a 16-bit twos-
1046 	* complement number...)
1047 	*/
1048 
1049 	Group = 65534;
1050       }
1051     }
1052   }
1053 
1054  /*
1055   * Check that we have at least one listen/port line; if not, report this
1056   * as an error and exit!
1057   */
1058 
1059   if (cupsArrayCount(Listeners) == 0)
1060   {
1061    /*
1062     * No listeners!
1063     */
1064 
1065     cupsdLogMessage(CUPSD_LOG_EMERG,
1066                     "No valid Listen or Port lines were found in the "
1067 		    "configuration file.");
1068 
1069    /*
1070     * Commit suicide...
1071     */
1072 
1073     cupsdEndProcess(getpid(), 0);
1074   }
1075 
1076  /*
1077   * Set the default locale using the language and charset...
1078   */
1079 
1080   cupsdSetStringf(&DefaultLocale, "%s.UTF-8", DefaultLanguage);
1081 
1082  /*
1083   * Update all relative filenames to include the full path from ServerRoot...
1084   */
1085 
1086   if (DocumentRoot[0] != '/')
1087     cupsdSetStringf(&DocumentRoot, "%s/%s", ServerRoot, DocumentRoot);
1088 
1089   if (RequestRoot[0] != '/')
1090     cupsdSetStringf(&RequestRoot, "%s/%s", ServerRoot, RequestRoot);
1091 
1092   if (ServerBin[0] != '/')
1093     cupsdSetStringf(&ServerBin, "%s/%s", ServerRoot, ServerBin);
1094 
1095   if (StateDir[0] != '/')
1096     cupsdSetStringf(&StateDir, "%s/%s", ServerRoot, StateDir);
1097 
1098   if (CacheDir[0] != '/')
1099     cupsdSetStringf(&CacheDir, "%s/%s", ServerRoot, CacheDir);
1100 
1101 #ifdef HAVE_SSL
1102   if (!_cups_strcasecmp(ServerKeychain, "internal"))
1103     cupsdClearString(&ServerKeychain);
1104   else if (ServerKeychain[0] != '/')
1105     cupsdSetStringf(&ServerKeychain, "%s/%s", ServerRoot, ServerKeychain);
1106 
1107   cupsdLogMessage(CUPSD_LOG_DEBUG, "Using keychain \"%s\" for server name \"%s\".", ServerKeychain ? ServerKeychain : "internal", ServerName);
1108   if (!CreateSelfSignedCerts)
1109     cupsdLogMessage(CUPSD_LOG_DEBUG, "Self-signed TLS certificate generation is disabled.");
1110   cupsSetServerCredentials(ServerKeychain, ServerName, CreateSelfSignedCerts);
1111 #endif /* HAVE_SSL */
1112 
1113  /*
1114   * Make sure that directories and config files are owned and
1115   * writable by the user and group in the cupsd.conf file...
1116   */
1117 
1118   snprintf(temp, sizeof(temp), "%s/rss", CacheDir);
1119 
1120   if ((cupsdCheckPermissions(RequestRoot, NULL, 0710, RunUser,
1121 			     Group, 1, 1) < 0 ||
1122        cupsdCheckPermissions(CacheDir, NULL, 0770, RunUser,
1123 			     Group, 1, 1) < 0 ||
1124        cupsdCheckPermissions(temp, NULL, 0775, RunUser,
1125 			     Group, 1, 1) < 0 ||
1126        cupsdCheckPermissions(StateDir, NULL, 0755, RunUser,
1127 			     Group, 1, 1) < 0 ||
1128        cupsdCheckPermissions(StateDir, "certs", RunUser ? 0711 : 0511, User,
1129 			     SystemGroupIDs[0], 1, 1) < 0 ||
1130        cupsdCheckPermissions(ServerRoot, NULL, 0755, RunUser,
1131 			     Group, 1, 0) < 0 ||
1132        cupsdCheckPermissions(ServerRoot, "ppd", 0755, RunUser,
1133 			     Group, 1, 1) < 0 ||
1134        cupsdCheckPermissions(ServerRoot, "ssl", 0700, RunUser,
1135 			     Group, 1, 0) < 0 ||
1136        cupsdCheckPermissions(ConfigurationFile, NULL, ConfigFilePerm, RunUser,
1137 			     Group, 0, 0) < 0 ||
1138        cupsdCheckPermissions(CupsFilesFile, NULL, ConfigFilePerm, RunUser,
1139 			     Group, 0, 0) < 0 ||
1140        cupsdCheckPermissions(ServerRoot, "classes.conf", 0600, RunUser,
1141 			     Group, 0, 0) < 0 ||
1142        cupsdCheckPermissions(ServerRoot, "printers.conf", 0600, RunUser,
1143 			     Group, 0, 0) < 0 ||
1144        cupsdCheckPermissions(ServerRoot, "passwd.md5", 0600, User,
1145 			     Group, 0, 0) < 0) &&
1146       (FatalErrors & CUPSD_FATAL_PERMISSIONS))
1147     return (0);
1148 
1149  /*
1150   * Update TempDir to the default if it hasn't been set already...
1151   */
1152 
1153 #ifdef __APPLE__
1154   if (TempDir && !RunUser &&
1155       (!strncmp(TempDir, "/private/tmp", 12) || !strncmp(TempDir, "/tmp", 4)))
1156   {
1157     cupsdLogMessage(CUPSD_LOG_ERROR, "Cannot use %s for TempDir.", TempDir);
1158     cupsdClearString(&TempDir);
1159   }
1160 #endif /* __APPLE__ */
1161 
1162   if (!TempDir)
1163   {
1164 #ifdef __APPLE__
1165     if ((tmpdir = getenv("TMPDIR")) != NULL &&
1166         strncmp(tmpdir, "/private/tmp", 12) && strncmp(tmpdir, "/tmp", 4))
1167 #else
1168     if ((tmpdir = getenv("TMPDIR")) != NULL)
1169 #endif /* __APPLE__ */
1170     {
1171      /*
1172       * TMPDIR is defined, see if it is OK for us to use...
1173       */
1174 
1175       if (stat(tmpdir, &tmpinfo))
1176         cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to access TMPDIR (%s): %s",
1177 	                tmpdir, strerror(errno));
1178       else if (!S_ISDIR(tmpinfo.st_mode))
1179         cupsdLogMessage(CUPSD_LOG_ERROR, "TMPDIR (%s) is not a directory.",
1180 	                tmpdir);
1181       else if ((tmpinfo.st_uid != User || !(tmpinfo.st_mode & S_IWUSR)) &&
1182                (tmpinfo.st_gid != Group || !(tmpinfo.st_mode & S_IWGRP)) &&
1183 	       !(tmpinfo.st_mode & S_IWOTH))
1184         cupsdLogMessage(CUPSD_LOG_ERROR,
1185 	                "TMPDIR (%s) has the wrong permissions.", tmpdir);
1186       else
1187         cupsdSetString(&TempDir, tmpdir);
1188     }
1189   }
1190 
1191   if (!TempDir)
1192   {
1193     cupsdLogMessage(CUPSD_LOG_INFO, "Using default TempDir of %s/tmp...",
1194 		    RequestRoot);
1195     cupsdSetStringf(&TempDir, "%s/tmp", RequestRoot);
1196   }
1197 
1198   setenv("TMPDIR", TempDir, 1);
1199 
1200  /*
1201   * Make sure the temporary directory has the right permissions...
1202   */
1203 
1204   if (!strncmp(TempDir, RequestRoot, strlen(RequestRoot)) ||
1205       access(TempDir, 0))
1206   {
1207    /*
1208     * Update ownership and permissions if the CUPS temp directory
1209     * is under the spool directory or does not exist...
1210     */
1211 
1212     if (cupsdCheckPermissions(TempDir, NULL, 01770, RunUser, Group, 1, 1) < 0 &&
1213 	(FatalErrors & CUPSD_FATAL_PERMISSIONS))
1214       return (0);
1215   }
1216 
1217  /*
1218   * Update environment variables...
1219   */
1220 
1221   cupsdUpdateEnv();
1222 
1223   /*
1224    * Validate the default error policy...
1225    */
1226 
1227   if (strcmp(ErrorPolicy, "retry-current-job") &&
1228       strcmp(ErrorPolicy, "abort-job") &&
1229       strcmp(ErrorPolicy, "retry-job") &&
1230       strcmp(ErrorPolicy, "stop-printer"))
1231   {
1232     cupsdLogMessage(CUPSD_LOG_ALERT, "Invalid ErrorPolicy \"%s\", resetting to \"stop-printer\".", ErrorPolicy);
1233     cupsdSetString(&ErrorPolicy, "stop-printer");
1234   }
1235 
1236  /*
1237   * Update default paper size setting as needed...
1238   */
1239 
1240   if (!DefaultPaperSize)
1241   {
1242 #ifdef HAVE_LIBPAPER
1243     char	*paper_result;		/* Paper size name from libpaper */
1244 
1245     if ((paper_result = systempapername()) != NULL)
1246       cupsdSetString(&DefaultPaperSize, paper_result);
1247     else
1248 #endif /* HAVE_LIBPAPER */
1249     if (!DefaultLanguage ||
1250         !_cups_strcasecmp(DefaultLanguage, "C") ||
1251         !_cups_strcasecmp(DefaultLanguage, "POSIX") ||
1252 	!_cups_strcasecmp(DefaultLanguage, "en") ||
1253 	!_cups_strncasecmp(DefaultLanguage, "en.", 3) ||
1254 	!_cups_strncasecmp(DefaultLanguage, "en_US", 5) ||
1255 	!_cups_strncasecmp(DefaultLanguage, "en_CA", 5) ||
1256 	!_cups_strncasecmp(DefaultLanguage, "fr_CA", 5))
1257     {
1258      /*
1259       * These are the only locales that will default to "letter" size...
1260       */
1261 
1262       cupsdSetString(&DefaultPaperSize, "Letter");
1263     }
1264     else
1265       cupsdSetString(&DefaultPaperSize, "A4");
1266   }
1267 
1268  /*
1269   * Update classification setting as needed...
1270   */
1271 
1272   if (Classification && !_cups_strcasecmp(Classification, "none"))
1273     cupsdClearString(&Classification);
1274 
1275   if (Classification)
1276     cupsdLogMessage(CUPSD_LOG_INFO, "Security set to \"%s\"", Classification);
1277 
1278  /*
1279   * Check the MaxClients setting, and then allocate memory for it...
1280   */
1281 
1282   if (MaxClients > (MaxFDs / 3) || MaxClients <= 0)
1283   {
1284     if (MaxClients > 0)
1285       cupsdLogMessage(CUPSD_LOG_INFO,
1286                       "MaxClients limited to 1/3 (%d) of the file descriptor "
1287 		      "limit (%d)...",
1288                       MaxFDs / 3, MaxFDs);
1289 
1290     MaxClients = MaxFDs / 3;
1291   }
1292 
1293   cupsdLogMessage(CUPSD_LOG_INFO, "Configured for up to %d clients.",
1294                   MaxClients);
1295 
1296  /*
1297   * Check the MaxActiveJobs setting; limit to 1/3 the available
1298   * file descriptors, since we need a pipe for each job...
1299   */
1300 
1301   if (MaxActiveJobs > (MaxFDs / 3))
1302     MaxActiveJobs = MaxFDs / 3;
1303 
1304  /*
1305   * Update the MaxClientsPerHost value, as needed...
1306   */
1307 
1308   if (MaxClientsPerHost <= 0)
1309     MaxClientsPerHost = MaxClients;
1310 
1311   if (MaxClientsPerHost > MaxClients)
1312     MaxClientsPerHost = MaxClients;
1313 
1314   cupsdLogMessage(CUPSD_LOG_INFO,
1315                   "Allowing up to %d client connections per host.",
1316                   MaxClientsPerHost);
1317 
1318  /*
1319   * Update the default policy, as needed...
1320   */
1321 
1322   if (DefaultPolicy)
1323     DefaultPolicyPtr = cupsdFindPolicy(DefaultPolicy);
1324   else
1325     DefaultPolicyPtr = NULL;
1326 
1327   if (!DefaultPolicyPtr)
1328   {
1329     cupsd_location_t	*po;		/* New policy operation */
1330 
1331 
1332     if (DefaultPolicy)
1333       cupsdLogMessage(CUPSD_LOG_ERROR, "Default policy \"%s\" not found.",
1334                       DefaultPolicy);
1335 
1336     cupsdSetString(&DefaultPolicy, "default");
1337 
1338     if ((DefaultPolicyPtr = cupsdFindPolicy("default")) != NULL)
1339       cupsdLogMessage(CUPSD_LOG_INFO,
1340                       "Using policy \"default\" as the default.");
1341     else
1342     {
1343       cupsdLogMessage(CUPSD_LOG_INFO,
1344                       "Creating CUPS default administrative policy:");
1345 
1346       DefaultPolicyPtr = p = cupsdAddPolicy("default");
1347 
1348       cupsdLogMessage(CUPSD_LOG_INFO, "<Policy default>");
1349 
1350       cupsdLogMessage(CUPSD_LOG_INFO, "JobPrivateAccess default");
1351       cupsdAddString(&(p->job_access), "@OWNER");
1352       cupsdAddString(&(p->job_access), "@SYSTEM");
1353 
1354       cupsdLogMessage(CUPSD_LOG_INFO, "JobPrivateValues default");
1355       cupsdAddString(&(p->job_attrs), "job-name");
1356       cupsdAddString(&(p->job_attrs), "job-originating-host-name");
1357       cupsdAddString(&(p->job_attrs), "job-originating-user-name");
1358       cupsdAddString(&(p->job_attrs), "phone");
1359 
1360       cupsdLogMessage(CUPSD_LOG_INFO, "SubscriptionPrivateAccess default");
1361       cupsdAddString(&(p->sub_access), "@OWNER");
1362       cupsdAddString(&(p->sub_access), "@SYSTEM");
1363 
1364       cupsdLogMessage(CUPSD_LOG_INFO, "SubscriptionPrivateValues default");
1365       cupsdAddString(&(p->job_attrs), "notify-events");
1366       cupsdAddString(&(p->job_attrs), "notify-pull-method");
1367       cupsdAddString(&(p->job_attrs), "notify-recipient-uri");
1368       cupsdAddString(&(p->job_attrs), "notify-subscriber-user-name");
1369       cupsdAddString(&(p->job_attrs), "notify-user-data");
1370 
1371       cupsdLogMessage(CUPSD_LOG_INFO,
1372                       "<Limit Create-Job Print-Job Print-URI Validate-Job>");
1373       cupsdLogMessage(CUPSD_LOG_INFO, "Order Deny,Allow");
1374 
1375       po = cupsdAddPolicyOp(p, NULL, IPP_CREATE_JOB);
1376       po->order_type = CUPSD_AUTH_ALLOW;
1377 
1378       cupsdAddPolicyOp(p, po, IPP_PRINT_JOB);
1379       cupsdAddPolicyOp(p, po, IPP_PRINT_URI);
1380       cupsdAddPolicyOp(p, po, IPP_VALIDATE_JOB);
1381 
1382       cupsdLogMessage(CUPSD_LOG_INFO, "</Limit>");
1383 
1384       cupsdLogMessage(CUPSD_LOG_INFO,
1385                       "<Limit Send-Document Send-URI Cancel-Job Hold-Job "
1386                       "Release-Job Restart-Job Purge-Jobs "
1387 		      "Set-Job-Attributes Create-Job-Subscription "
1388 		      "Renew-Subscription Cancel-Subscription "
1389 		      "Get-Notifications Reprocess-Job Cancel-Current-Job "
1390 		      "Suspend-Current-Job Resume-Job "
1391 		      "Cancel-My-Jobs Close-Job CUPS-Move-Job "
1392 		      "CUPS-Authenticate-Job CUPS-Get-Document>");
1393       cupsdLogMessage(CUPSD_LOG_INFO, "Order Deny,Allow");
1394 
1395       po = cupsdAddPolicyOp(p, NULL, IPP_SEND_DOCUMENT);
1396       po->order_type = CUPSD_AUTH_ALLOW;
1397       po->level      = CUPSD_AUTH_USER;
1398 
1399       cupsdAddName(po, "@OWNER");
1400       cupsdAddName(po, "@SYSTEM");
1401       cupsdLogMessage(CUPSD_LOG_INFO, "Require user @OWNER @SYSTEM");
1402 
1403       cupsdAddPolicyOp(p, po, IPP_SEND_URI);
1404       cupsdAddPolicyOp(p, po, IPP_CANCEL_JOB);
1405       cupsdAddPolicyOp(p, po, IPP_HOLD_JOB);
1406       cupsdAddPolicyOp(p, po, IPP_RELEASE_JOB);
1407       cupsdAddPolicyOp(p, po, IPP_RESTART_JOB);
1408       cupsdAddPolicyOp(p, po, IPP_PURGE_JOBS);
1409       cupsdAddPolicyOp(p, po, IPP_SET_JOB_ATTRIBUTES);
1410       cupsdAddPolicyOp(p, po, IPP_CREATE_JOB_SUBSCRIPTION);
1411       cupsdAddPolicyOp(p, po, IPP_RENEW_SUBSCRIPTION);
1412       cupsdAddPolicyOp(p, po, IPP_CANCEL_SUBSCRIPTION);
1413       cupsdAddPolicyOp(p, po, IPP_GET_NOTIFICATIONS);
1414       cupsdAddPolicyOp(p, po, IPP_REPROCESS_JOB);
1415       cupsdAddPolicyOp(p, po, IPP_CANCEL_CURRENT_JOB);
1416       cupsdAddPolicyOp(p, po, IPP_SUSPEND_CURRENT_JOB);
1417       cupsdAddPolicyOp(p, po, IPP_RESUME_JOB);
1418       cupsdAddPolicyOp(p, po, IPP_CANCEL_MY_JOBS);
1419       cupsdAddPolicyOp(p, po, IPP_CLOSE_JOB);
1420       cupsdAddPolicyOp(p, po, CUPS_MOVE_JOB);
1421       cupsdAddPolicyOp(p, po, CUPS_AUTHENTICATE_JOB);
1422       cupsdAddPolicyOp(p, po, CUPS_GET_DOCUMENT);
1423 
1424       cupsdLogMessage(CUPSD_LOG_INFO, "</Limit>");
1425 
1426       cupsdLogMessage(CUPSD_LOG_INFO,
1427                       "<Limit Pause-Printer Resume-Printer "
1428                       "Set-Printer-Attributes Enable-Printer "
1429 		      "Disable-Printer Pause-Printer-After-Current-Job "
1430 		      "Hold-New-Jobs Release-Held-New-Jobs "
1431 		      "Deactivate-Printer Activate-Printer Restart-Printer "
1432 		      "Shutdown-Printer Startup-Printer Promote-Job "
1433 		      "Schedule-Job-After Cancel-Jobs CUPS-Add-Printer "
1434 		      "CUPS-Delete-Printer CUPS-Add-Class CUPS-Delete-Class "
1435 		      "CUPS-Accept-Jobs CUPS-Reject-Jobs CUPS-Set-Default>");
1436       cupsdLogMessage(CUPSD_LOG_INFO, "Order Deny,Allow");
1437       cupsdLogMessage(CUPSD_LOG_INFO, "AuthType Default");
1438 
1439       po = cupsdAddPolicyOp(p, NULL, IPP_PAUSE_PRINTER);
1440       po->order_type = CUPSD_AUTH_ALLOW;
1441       po->type       = CUPSD_AUTH_DEFAULT;
1442       po->level      = CUPSD_AUTH_USER;
1443 
1444       cupsdAddName(po, "@SYSTEM");
1445       cupsdLogMessage(CUPSD_LOG_INFO, "Require user @SYSTEM");
1446 
1447       cupsdAddPolicyOp(p, po, IPP_RESUME_PRINTER);
1448       cupsdAddPolicyOp(p, po, IPP_SET_PRINTER_ATTRIBUTES);
1449       cupsdAddPolicyOp(p, po, IPP_ENABLE_PRINTER);
1450       cupsdAddPolicyOp(p, po, IPP_DISABLE_PRINTER);
1451       cupsdAddPolicyOp(p, po, IPP_PAUSE_PRINTER_AFTER_CURRENT_JOB);
1452       cupsdAddPolicyOp(p, po, IPP_HOLD_NEW_JOBS);
1453       cupsdAddPolicyOp(p, po, IPP_RELEASE_HELD_NEW_JOBS);
1454       cupsdAddPolicyOp(p, po, IPP_DEACTIVATE_PRINTER);
1455       cupsdAddPolicyOp(p, po, IPP_ACTIVATE_PRINTER);
1456       cupsdAddPolicyOp(p, po, IPP_RESTART_PRINTER);
1457       cupsdAddPolicyOp(p, po, IPP_SHUTDOWN_PRINTER);
1458       cupsdAddPolicyOp(p, po, IPP_STARTUP_PRINTER);
1459       cupsdAddPolicyOp(p, po, IPP_PROMOTE_JOB);
1460       cupsdAddPolicyOp(p, po, IPP_SCHEDULE_JOB_AFTER);
1461       cupsdAddPolicyOp(p, po, IPP_CANCEL_JOBS);
1462       cupsdAddPolicyOp(p, po, CUPS_ADD_PRINTER);
1463       cupsdAddPolicyOp(p, po, CUPS_DELETE_PRINTER);
1464       cupsdAddPolicyOp(p, po, CUPS_ADD_CLASS);
1465       cupsdAddPolicyOp(p, po, CUPS_DELETE_CLASS);
1466       cupsdAddPolicyOp(p, po, CUPS_ACCEPT_JOBS);
1467       cupsdAddPolicyOp(p, po, CUPS_REJECT_JOBS);
1468       cupsdAddPolicyOp(p, po, CUPS_SET_DEFAULT);
1469 
1470       cupsdLogMessage(CUPSD_LOG_INFO, "</Limit>");
1471 
1472       cupsdLogMessage(CUPSD_LOG_INFO, "<Limit All>");
1473       cupsdLogMessage(CUPSD_LOG_INFO, "Order Deny,Allow");
1474 
1475       po = cupsdAddPolicyOp(p, NULL, IPP_ANY_OPERATION);
1476       po->order_type = CUPSD_AUTH_ALLOW;
1477 
1478       cupsdLogMessage(CUPSD_LOG_INFO, "</Limit>");
1479       cupsdLogMessage(CUPSD_LOG_INFO, "</Policy>");
1480     }
1481   }
1482 
1483   if (LogLevel >= CUPSD_LOG_DEBUG2)
1484   {
1485     cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdReadConfiguration: NumPolicies=%d",
1486 		    cupsArrayCount(Policies));
1487     for (i = 0, p = (cupsd_policy_t *)cupsArrayFirst(Policies);
1488 	 p;
1489 	 i ++, p = (cupsd_policy_t *)cupsArrayNext(Policies))
1490     {
1491       int		j;		/* Looping var */
1492       cupsd_location_t	*loc;		/* Current location */
1493 
1494       cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdReadConfiguration: Policies[%d]=\"%s\"", i, p->name);
1495 
1496       for (j = 0, loc = (cupsd_location_t *)cupsArrayFirst(p->ops); loc; j ++, loc = (cupsd_location_t *)cupsArrayNext(p->ops))
1497       {
1498         cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdReadConfiguration:     ops[%d]=%s", j, ippOpString(loc->op));
1499       }
1500     }
1501   }
1502 
1503  /*
1504   * If we are doing a full reload or the server root has changed, flush
1505   * the jobs, printers, etc. and start from scratch...
1506   */
1507 
1508   if (NeedReload == RELOAD_ALL ||
1509       old_remote_port != RemotePort ||
1510       !old_serverroot || !ServerRoot || strcmp(old_serverroot, ServerRoot) ||
1511       !old_requestroot || !RequestRoot || strcmp(old_requestroot, RequestRoot))
1512   {
1513     mime_type_t	*type;			/* Current type */
1514     char	mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE];
1515 					/* MIME type name */
1516 
1517 
1518     cupsdLogMessage(CUPSD_LOG_INFO, "Full reload is required.");
1519 
1520    /*
1521     * Free all memory...
1522     */
1523 
1524     cupsdDeleteAllSubscriptions();
1525     cupsdFreeAllJobs();
1526     cupsdDeleteAllPrinters();
1527 
1528     DefaultPrinter = NULL;
1529 
1530     if (MimeDatabase != NULL)
1531       mimeDelete(MimeDatabase);
1532 
1533     if (NumMimeTypes)
1534     {
1535       for (i = 0; i < NumMimeTypes; i ++)
1536 	_cupsStrFree(MimeTypes[i]);
1537 
1538       free(MimeTypes);
1539     }
1540 
1541    /*
1542     * Read the MIME type and conversion database...
1543     */
1544 
1545     snprintf(temp, sizeof(temp), "%s/filter", ServerBin);
1546     snprintf(mimedir, sizeof(mimedir), "%s/mime", DataDir);
1547 
1548     MimeDatabase = mimeNew();
1549     mimeSetErrorCallback(MimeDatabase, mime_error_cb, NULL);
1550 
1551     MimeDatabase = mimeLoadTypes(MimeDatabase, mimedir);
1552     MimeDatabase = mimeLoadTypes(MimeDatabase, ServerRoot);
1553     MimeDatabase = mimeLoadFilters(MimeDatabase, mimedir, temp);
1554     MimeDatabase = mimeLoadFilters(MimeDatabase, ServerRoot, temp);
1555 
1556     if (!MimeDatabase)
1557     {
1558       cupsdLogMessage(CUPSD_LOG_EMERG,
1559                       "Unable to load MIME database from \"%s\" or \"%s\".",
1560 		      mimedir, ServerRoot);
1561       if (FatalErrors & CUPSD_FATAL_CONFIG)
1562         return (0);
1563     }
1564 
1565     cupsdLogMessage(CUPSD_LOG_INFO,
1566                     "Loaded MIME database from \"%s\" and \"%s\": %d types, "
1567 		    "%d filters...", mimedir, ServerRoot,
1568 		    mimeNumTypes(MimeDatabase), mimeNumFilters(MimeDatabase));
1569 
1570    /*
1571     * Create a list of MIME types for the document-format-supported
1572     * attribute...
1573     */
1574 
1575     NumMimeTypes = mimeNumTypes(MimeDatabase);
1576     if (!mimeType(MimeDatabase, "application", "octet-stream"))
1577       NumMimeTypes ++;
1578 
1579     if ((MimeTypes = calloc((size_t)NumMimeTypes, sizeof(const char *))) == NULL)
1580     {
1581       cupsdLogMessage(CUPSD_LOG_ERROR,
1582                       "Unable to allocate memory for %d MIME types.",
1583 		      NumMimeTypes);
1584       NumMimeTypes = 0;
1585     }
1586     else
1587     {
1588       for (i = 0, type = mimeFirstType(MimeDatabase);
1589 	   type;
1590 	   i ++, type = mimeNextType(MimeDatabase))
1591       {
1592 	snprintf(mimetype, sizeof(mimetype), "%s/%s", type->super, type->type);
1593 
1594 	MimeTypes[i] = _cupsStrAlloc(mimetype);
1595       }
1596 
1597       if (i < NumMimeTypes)
1598 	MimeTypes[i] = _cupsStrAlloc("application/octet-stream");
1599     }
1600 
1601     if (LogLevel == CUPSD_LOG_DEBUG2)
1602     {
1603       mime_filter_t	*filter;	/* Current filter */
1604 
1605 
1606       for (type = mimeFirstType(MimeDatabase);
1607            type;
1608 	   type = mimeNextType(MimeDatabase))
1609 	cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdReadConfiguration: type %s/%s",
1610 		        type->super, type->type);
1611 
1612       for (filter = mimeFirstFilter(MimeDatabase);
1613            filter;
1614 	   filter = mimeNextFilter(MimeDatabase))
1615 	cupsdLogMessage(CUPSD_LOG_DEBUG2,
1616 	                "cupsdReadConfiguration: filter %s/%s to %s/%s %d %s",
1617 		        filter->src->super, filter->src->type,
1618 		        filter->dst->super, filter->dst->type,
1619 		        filter->cost, filter->filter);
1620     }
1621 
1622    /*
1623     * Load banners...
1624     */
1625 
1626     snprintf(temp, sizeof(temp), "%s/banners", DataDir);
1627     cupsdLoadBanners(temp);
1628 
1629    /*
1630     * Load printers and classes...
1631     */
1632 
1633     cupsdLoadAllPrinters();
1634     cupsdLoadAllClasses();
1635 
1636     cupsdCreateCommonData();
1637 
1638    /*
1639     * Update the printcap file as needed...
1640     */
1641 
1642     if (Printcap && *Printcap && access(Printcap, 0))
1643       cupsdWritePrintcap();
1644 
1645    /*
1646     * Load queued jobs...
1647     */
1648 
1649     cupsdLoadAllJobs();
1650 
1651    /*
1652     * Load subscriptions...
1653     */
1654 
1655     cupsdLoadAllSubscriptions();
1656 
1657     cupsdLogMessage(CUPSD_LOG_INFO, "Full reload complete.");
1658   }
1659   else
1660   {
1661    /*
1662     * Not a full reload, so recreate the common printer attributes...
1663     */
1664 
1665     cupsdCreateCommonData();
1666 
1667    /*
1668     * Update all jobs as needed...
1669     */
1670 
1671     cupsdUpdateJobs();
1672 
1673    /*
1674     * Update all printers as needed...
1675     */
1676 
1677     cupsdUpdatePrinters();
1678     cupsdMarkDirty(CUPSD_DIRTY_PRINTCAP);
1679 
1680     cupsdLogMessage(CUPSD_LOG_INFO, "Partial reload complete.");
1681   }
1682 
1683  /*
1684   * Reset the reload state...
1685   */
1686 
1687   NeedReload = RELOAD_NONE;
1688 
1689   cupsdClearString(&old_serverroot);
1690   cupsdClearString(&old_requestroot);
1691 
1692   return (1);
1693 }
1694 
1695 
1696 /*
1697  * 'get_address()' - Get an address + port number from a line.
1698  */
1699 
1700 static http_addrlist_t *		/* O - Pointer to list if address good, NULL if bad */
get_address(const char * value,int defport)1701 get_address(const char  *value,		/* I - Value string */
1702 	    int         defport)	/* I - Default port */
1703 {
1704   char			buffer[1024],	/* Hostname + port number buffer */
1705 			defpname[255],	/* Default port name */
1706 			*hostname,	/* Hostname or IP */
1707 			*portname;	/* Port number or name */
1708   http_addrlist_t	*addrlist;	/* Address list */
1709 
1710 
1711  /*
1712   * Check for an empty value...
1713   */
1714 
1715   if (!*value)
1716   {
1717     cupsdLogMessage(CUPSD_LOG_ERROR, "Bad (empty) address.");
1718     return (NULL);
1719   }
1720 
1721  /*
1722   * Grab a hostname and port number; if there is no colon and the port name
1723   * is only digits, then we have a port number by itself...
1724   */
1725 
1726   strlcpy(buffer, value, sizeof(buffer));
1727 
1728   if ((portname = strrchr(buffer, ':')) != NULL && !strchr(portname, ']'))
1729   {
1730     *portname++ = '\0';
1731     hostname = buffer;
1732   }
1733   else
1734   {
1735     for (portname = buffer; isdigit(*portname & 255); portname ++);
1736 
1737     if (*portname)
1738     {
1739      /*
1740       * Use the default port...
1741       */
1742 
1743       sprintf(defpname, "%d", defport);
1744       portname = defpname;
1745       hostname = buffer;
1746     }
1747     else
1748     {
1749      /*
1750       * The buffer contains just a port number...
1751       */
1752 
1753       portname = buffer;
1754       hostname = NULL;
1755     }
1756   }
1757 
1758   if (hostname && !strcmp(hostname, "*"))
1759     hostname = NULL;
1760 
1761  /*
1762   * Now lookup the address using httpAddrGetList()...
1763   */
1764 
1765   if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portname)) == NULL)
1766     cupsdLogMessage(CUPSD_LOG_ERROR, "Hostname lookup for \"%s\" failed.",
1767                     hostname ? hostname : "(nil)");
1768 
1769   return (addrlist);
1770 }
1771 
1772 
1773 /*
1774  * 'get_addr_and_mask()' - Get an IP address and netmask.
1775  */
1776 
1777 static int				/* O - 1 on success, 0 on failure */
get_addr_and_mask(const char * value,unsigned * ip,unsigned * mask)1778 get_addr_and_mask(const char *value,	/* I - String from config file */
1779                   unsigned   *ip,	/* O - Address value */
1780 		  unsigned   *mask)	/* O - Mask value */
1781 {
1782   int		i, j,			/* Looping vars */
1783 		family,			/* Address family */
1784 		ipcount;		/* Count of fields in address */
1785   unsigned	ipval;			/* Value */
1786   const char	*maskval,		/* Pointer to start of mask value */
1787 		*ptr,			/* Pointer into value */
1788 		*ptr2;			/* ... */
1789 
1790 
1791  /*
1792   * Get the address...
1793   */
1794 
1795   ip[0]   = ip[1]   = ip[2]   = ip[3]   = 0x00000000;
1796   mask[0] = mask[1] = mask[2] = mask[3] = 0xffffffff;
1797 
1798   if ((maskval = strchr(value, '/')) != NULL)
1799     maskval ++;
1800   else
1801     maskval = value + strlen(value);
1802 
1803 #ifdef AF_INET6
1804  /*
1805   * Check for an IPv6 address...
1806   */
1807 
1808   if (*value == '[')
1809   {
1810    /*
1811     * Parse hexadecimal IPv6/IPv4 address...
1812     */
1813 
1814     family  = AF_INET6;
1815 
1816     for (i = 0, ptr = value + 1; *ptr && i < 8; i ++)
1817     {
1818       if (*ptr == ']')
1819         break;
1820       else if (!strncmp(ptr, "::", 2))
1821       {
1822         for (ptr2 = strchr(ptr + 2, ':'), j = 0;
1823 	     ptr2;
1824 	     ptr2 = strchr(ptr2 + 1, ':'), j ++);
1825 
1826         i = 6 - j;
1827 	ptr += 2;
1828       }
1829       else if (isdigit(*ptr & 255) && strchr(ptr + 1, '.') && i >= 6)
1830       {
1831        /*
1832         * Read IPv4 dotted quad...
1833         */
1834 
1835 	unsigned val[4] = { 0, 0, 0, 0 };
1836 					/* IPv4 address values */
1837 
1838 	ipcount = sscanf(ptr, "%u.%u.%u.%u", val + 0, val + 1, val + 2,
1839 	                 val + 3);
1840 
1841        /*
1842 	* Range check the IP numbers...
1843 	*/
1844 
1845 	for (i = 0; i < ipcount; i ++)
1846 	  if (val[i] > 255)
1847 	    return (0);
1848 
1849        /*
1850 	* Merge everything into a 32-bit IPv4 address in ip[3]...
1851 	*/
1852 
1853 	ip[3] = ((((((unsigned)val[0] << 8) | (unsigned)val[1]) << 8) |
1854 	         (unsigned)val[2]) << 8) | (unsigned)val[3];
1855 
1856 	if (ipcount < 4)
1857 	  mask[3] = (0xffffffff << (32 - 8 * ipcount)) & 0xffffffff;
1858 
1859        /*
1860         * If the leading words are all 0's then this is an IPv4 address...
1861         */
1862 
1863         if (!val[0] && !val[1] && !val[2])
1864 	  family  = AF_INET;
1865 
1866         while (isdigit(*ptr & 255) || *ptr == '.')
1867           ptr ++;
1868 	break;
1869       }
1870       else if (isxdigit(*ptr & 255))
1871       {
1872         ipval = strtoul(ptr, (char **)&ptr, 16);
1873 
1874 	if (*ptr == ':' && ptr[1] != ':')
1875 	  ptr ++;
1876 
1877 	if (ipval > 0xffff)
1878 	  return (0);
1879 
1880         if (i & 1)
1881           ip[i / 2] |= ipval;
1882 	else
1883           ip[i / 2] |= ipval << 16;
1884       }
1885       else
1886         return (0);
1887     }
1888 
1889     if (*ptr != ']')
1890       return (0);
1891 
1892     ptr ++;
1893 
1894     if (*ptr && *ptr != '/')
1895       return (0);
1896   }
1897   else
1898 #endif /* AF_INET6 */
1899   {
1900    /*
1901     * Parse dotted-decimal IPv4 address...
1902     */
1903 
1904     unsigned val[4] = { 0, 0, 0, 0 };	/* IPv4 address values */
1905 
1906 
1907     family  = AF_INET;
1908     ipcount = sscanf(value, "%u.%u.%u.%u", val + 0, val + 1, val + 2, val + 3);
1909 
1910    /*
1911     * Range check the IP numbers...
1912     */
1913 
1914     for (i = 0; i < ipcount; i ++)
1915       if (val[i] > 255)
1916         return (0);
1917 
1918    /*
1919     * Merge everything into a 32-bit IPv4 address in ip[3]...
1920     */
1921 
1922     ip[3] = ((((((unsigned)val[0] << 8) | (unsigned)val[1]) << 8) |
1923              (unsigned)val[2]) << 8) | (unsigned)val[3];
1924 
1925     if (ipcount < 4)
1926       mask[3] = (0xffffffff << (32 - 8 * ipcount)) & 0xffffffff;
1927   }
1928 
1929   if (*maskval)
1930   {
1931    /*
1932     * Get the netmask value(s)...
1933     */
1934 
1935     memset(mask, 0, sizeof(unsigned) * 4);
1936 
1937     if (strchr(maskval, '.'))
1938     {
1939      /*
1940       * Get dotted-decimal mask...
1941       */
1942 
1943       if (family != AF_INET)
1944         return (0);
1945 
1946       if (sscanf(maskval, "%u.%u.%u.%u", mask + 0, mask + 1, mask + 2,
1947                  mask + 3) != 4)
1948         return (0);
1949 
1950       mask[3] |= (((((unsigned)mask[0] << 8) | (unsigned)mask[1]) << 8) |
1951                   (unsigned)mask[2]) << 8;
1952       mask[0] = mask[1] = mask[2] = 0;
1953     }
1954     else
1955     {
1956      /*
1957       * Get address/bits format...
1958       */
1959 
1960       i = atoi(maskval);
1961 
1962 #ifdef AF_INET6
1963       if (family == AF_INET6)
1964       {
1965         if (i > 128)
1966 	  return (0);
1967 
1968         i = 128 - i;
1969 
1970 	if (i <= 96)
1971 	  mask[0] = 0xffffffff;
1972 	else
1973 	  mask[0] = (0xffffffff << (i - 96)) & 0xffffffff;
1974 
1975 	if (i <= 64)
1976 	  mask[1] = 0xffffffff;
1977 	else if (i >= 96)
1978 	  mask[1] = 0;
1979 	else
1980 	  mask[1] = (0xffffffff << (i - 64)) & 0xffffffff;
1981 
1982 	if (i <= 32)
1983 	  mask[2] = 0xffffffff;
1984 	else if (i >= 64)
1985 	  mask[2] = 0;
1986 	else
1987 	  mask[2] = (0xffffffff << (i - 32)) & 0xffffffff;
1988 
1989 	if (i == 0)
1990 	  mask[3] = 0xffffffff;
1991 	else if (i >= 32)
1992 	  mask[3] = 0;
1993 	else
1994 	  mask[3] = (0xffffffff << i) & 0xffffffff;
1995       }
1996       else
1997 #endif /* AF_INET6 */
1998       {
1999         if (i > 32)
2000 	  return (0);
2001 
2002         mask[0] = 0xffffffff;
2003         mask[1] = 0xffffffff;
2004         mask[2] = 0xffffffff;
2005 
2006 	if (i < 32)
2007           mask[3] = (0xffffffff << (32 - i)) & 0xffffffff;
2008 	else
2009 	  mask[3] = 0xffffffff;
2010       }
2011     }
2012   }
2013 
2014   cupsdLogMessage(CUPSD_LOG_DEBUG2,
2015                   "get_addr_and_mask(value=\"%s\", "
2016                   "ip=[%08x:%08x:%08x:%08x], mask=[%08x:%08x:%08x:%08x])",
2017              value, ip[0], ip[1], ip[2], ip[3], mask[0], mask[1], mask[2],
2018 	     mask[3]);
2019 
2020  /*
2021   * Check for a valid netmask; no fallback like in CUPS 1.1.x!
2022   */
2023 
2024   if ((ip[0] & ~mask[0]) != 0 ||
2025       (ip[1] & ~mask[1]) != 0 ||
2026       (ip[2] & ~mask[2]) != 0 ||
2027       (ip[3] & ~mask[3]) != 0)
2028     return (0);
2029 
2030   return (1);
2031 }
2032 
2033 
2034 /*
2035  * 'mime_error_cb()' - Log a MIME error.
2036  */
2037 
2038 static void
mime_error_cb(void * ctx,const char * message)2039 mime_error_cb(void       *ctx,		/* I - Context pointer (unused) */
2040               const char *message)	/* I - Message */
2041 {
2042   (void)ctx;
2043 
2044   cupsdLogMessage(CUPSD_LOG_ERROR, "%s", message);
2045 }
2046 
2047 
2048 /*
2049  * 'parse_aaa()' - Parse authentication, authorization, and access control lines.
2050  */
2051 
2052 static int				/* O - 1 on success, 0 on failure */
parse_aaa(cupsd_location_t * loc,char * line,char * value,int linenum)2053 parse_aaa(cupsd_location_t *loc,	/* I - Location */
2054           char             *line,	/* I - Line from file */
2055 	  char             *value,	/* I - Start of value data */
2056 	  int              linenum)	/* I - Current line number */
2057 {
2058   char		*valptr;		/* Pointer into value */
2059   unsigned	ip[4],			/* IP address components */
2060  		mask[4];		/* IP netmask components */
2061 
2062 
2063   if (!_cups_strcasecmp(line, "Encryption"))
2064   {
2065    /*
2066     * "Encryption xxx" - set required encryption level...
2067     */
2068 
2069     if (!_cups_strcasecmp(value, "never"))
2070       loc->encryption = HTTP_ENCRYPT_NEVER;
2071     else if (!_cups_strcasecmp(value, "always"))
2072     {
2073       cupsdLogMessage(CUPSD_LOG_ERROR,
2074                       "Encryption value \"%s\" on line %d of %s is invalid in this "
2075 		      "context. Using \"required\" instead.", value, linenum, ConfigurationFile);
2076 
2077       loc->encryption = HTTP_ENCRYPT_REQUIRED;
2078     }
2079     else if (!_cups_strcasecmp(value, "required"))
2080       loc->encryption = HTTP_ENCRYPT_REQUIRED;
2081     else if (!_cups_strcasecmp(value, "ifrequested"))
2082       loc->encryption = HTTP_ENCRYPT_IF_REQUESTED;
2083     else
2084     {
2085       cupsdLogMessage(CUPSD_LOG_ERROR,
2086                       "Unknown Encryption value %s on line %d of %s.", value, linenum, ConfigurationFile);
2087       return (0);
2088     }
2089   }
2090   else if (!_cups_strcasecmp(line, "Order"))
2091   {
2092    /*
2093     * "Order Deny,Allow" or "Order Allow,Deny"...
2094     */
2095 
2096     if (!_cups_strncasecmp(value, "deny", 4))
2097       loc->order_type = CUPSD_AUTH_ALLOW;
2098     else if (!_cups_strncasecmp(value, "allow", 5))
2099       loc->order_type = CUPSD_AUTH_DENY;
2100     else
2101     {
2102       cupsdLogMessage(CUPSD_LOG_ERROR, "Unknown Order value %s on line %d of %s.",
2103 	              value, linenum, ConfigurationFile);
2104       return (0);
2105     }
2106   }
2107   else if (!_cups_strcasecmp(line, "Allow") || !_cups_strcasecmp(line, "Deny"))
2108   {
2109    /*
2110     * Allow [From] host/ip...
2111     * Deny [From] host/ip...
2112     */
2113 
2114     while (*value)
2115     {
2116       if (!_cups_strncasecmp(value, "from", 4))
2117       {
2118        /*
2119 	* Strip leading "from"...
2120 	*/
2121 
2122 	value += 4;
2123 
2124 	while (_cups_isspace(*value))
2125 	  value ++;
2126 
2127         if (!*value)
2128 	  break;
2129       }
2130 
2131      /*
2132       * Find the end of the value...
2133       */
2134 
2135       for (valptr = value; *valptr && !_cups_isspace(*valptr); valptr ++);
2136 
2137       while (_cups_isspace(*valptr))
2138         *valptr++ = '\0';
2139 
2140      /*
2141       * Figure out what form the allow/deny address takes:
2142       *
2143       *    All
2144       *    None
2145       *    *.domain.com
2146       *    .domain.com
2147       *    host.domain.com
2148       *    nnn.*
2149       *    nnn.nnn.*
2150       *    nnn.nnn.nnn.*
2151       *    nnn.nnn.nnn.nnn
2152       *    nnn.nnn.nnn.nnn/mm
2153       *    nnn.nnn.nnn.nnn/mmm.mmm.mmm.mmm
2154       */
2155 
2156       if (!_cups_strcasecmp(value, "all"))
2157       {
2158        /*
2159 	* All hosts...
2160 	*/
2161 
2162 	if (!_cups_strcasecmp(line, "Allow"))
2163 	  cupsdAddIPMask(&(loc->allow), zeros, zeros);
2164 	else
2165 	  cupsdAddIPMask(&(loc->deny), zeros, zeros);
2166       }
2167       else if (!_cups_strcasecmp(value, "none"))
2168       {
2169        /*
2170 	* No hosts...
2171 	*/
2172 
2173 	if (!_cups_strcasecmp(line, "Allow"))
2174 	  cupsdAddIPMask(&(loc->allow), ones, zeros);
2175 	else
2176 	  cupsdAddIPMask(&(loc->deny), ones, zeros);
2177       }
2178 #ifdef AF_INET6
2179       else if (value[0] == '*' || value[0] == '.' ||
2180 	       (!isdigit(value[0] & 255) && value[0] != '['))
2181 #else
2182       else if (value[0] == '*' || value[0] == '.' || !isdigit(value[0] & 255))
2183 #endif /* AF_INET6 */
2184       {
2185        /*
2186 	* Host or domain name...
2187 	*/
2188 
2189 	if (value[0] == '*')
2190 	  value ++;
2191 
2192 	if (!_cups_strcasecmp(line, "Allow"))
2193 	  cupsdAddNameMask(&(loc->allow), value);
2194 	else
2195 	  cupsdAddNameMask(&(loc->deny), value);
2196       }
2197       else
2198       {
2199        /*
2200 	* One of many IP address forms...
2201 	*/
2202 
2203 	if (!get_addr_and_mask(value, ip, mask))
2204 	{
2205 	  cupsdLogMessage(CUPSD_LOG_ERROR, "Bad netmask value %s on line %d of %s.",
2206 			  value, linenum, ConfigurationFile);
2207 	  return (0);
2208 	}
2209 
2210 	if (!_cups_strcasecmp(line, "Allow"))
2211 	  cupsdAddIPMask(&(loc->allow), ip, mask);
2212 	else
2213 	  cupsdAddIPMask(&(loc->deny), ip, mask);
2214       }
2215 
2216      /*
2217       * Advance to next value...
2218       */
2219 
2220       value = valptr;
2221     }
2222   }
2223   else if (!_cups_strcasecmp(line, "AuthType"))
2224   {
2225    /*
2226     * AuthType {none,basic,digest,basicdigest,negotiate,default}
2227     */
2228 
2229     if (!_cups_strcasecmp(value, "none"))
2230     {
2231       loc->type  = CUPSD_AUTH_NONE;
2232       loc->level = CUPSD_AUTH_ANON;
2233     }
2234     else if (!_cups_strcasecmp(value, "basic"))
2235     {
2236       loc->type = CUPSD_AUTH_BASIC;
2237 
2238       if (loc->level == CUPSD_AUTH_ANON)
2239 	loc->level = CUPSD_AUTH_USER;
2240     }
2241     else if (!_cups_strcasecmp(value, "default"))
2242     {
2243       loc->type = CUPSD_AUTH_DEFAULT;
2244 
2245       if (loc->level == CUPSD_AUTH_ANON)
2246 	loc->level = CUPSD_AUTH_USER;
2247     }
2248     else if (!_cups_strcasecmp(value, "negotiate"))
2249     {
2250       loc->type = CUPSD_AUTH_NEGOTIATE;
2251 
2252       if (loc->level == CUPSD_AUTH_ANON)
2253 	loc->level = CUPSD_AUTH_USER;
2254     }
2255     else
2256     {
2257       cupsdLogMessage(CUPSD_LOG_WARN,
2258                       "Unknown authorization type %s on line %d of %s.",
2259 	              value, linenum, ConfigurationFile);
2260       return (0);
2261     }
2262   }
2263   else if (!_cups_strcasecmp(line, "AuthClass"))
2264   {
2265    /*
2266     * AuthClass anonymous, user, system, group
2267     */
2268 
2269     if (!_cups_strcasecmp(value, "anonymous"))
2270     {
2271       loc->type  = CUPSD_AUTH_NONE;
2272       loc->level = CUPSD_AUTH_ANON;
2273 
2274       cupsdLogMessage(CUPSD_LOG_WARN,
2275                       "\"AuthClass %s\" is deprecated; consider removing "
2276 		      "it from line %d.",
2277 	              value, linenum);
2278     }
2279     else if (!_cups_strcasecmp(value, "user"))
2280     {
2281       loc->level = CUPSD_AUTH_USER;
2282 
2283       cupsdLogMessage(CUPSD_LOG_WARN,
2284                       "\"AuthClass %s\" is deprecated; consider using "
2285 		      "\"Require valid-user\" on line %d of %s.",
2286 	              value, linenum, ConfigurationFile);
2287     }
2288     else if (!_cups_strcasecmp(value, "group"))
2289     {
2290       loc->level = CUPSD_AUTH_GROUP;
2291 
2292       cupsdLogMessage(CUPSD_LOG_WARN,
2293                       "\"AuthClass %s\" is deprecated; consider using "
2294 		      "\"Require user @groupname\" on line %d of %s.",
2295 	              value, linenum, ConfigurationFile);
2296     }
2297     else if (!_cups_strcasecmp(value, "system"))
2298     {
2299       loc->level = CUPSD_AUTH_GROUP;
2300 
2301       cupsdAddName(loc, "@SYSTEM");
2302 
2303       cupsdLogMessage(CUPSD_LOG_WARN,
2304                       "\"AuthClass %s\" is deprecated; consider using "
2305 		      "\"Require user @SYSTEM\" on line %d of %s.",
2306 	              value, linenum, ConfigurationFile);
2307     }
2308     else
2309     {
2310       cupsdLogMessage(CUPSD_LOG_WARN,
2311                       "Unknown authorization class %s on line %d of %s.",
2312 	              value, linenum, ConfigurationFile);
2313       return (0);
2314     }
2315   }
2316   else if (!_cups_strcasecmp(line, "AuthGroupName"))
2317   {
2318     cupsdAddName(loc, value);
2319 
2320     cupsdLogMessage(CUPSD_LOG_WARN,
2321                     "\"AuthGroupName %s\" directive is deprecated; consider "
2322 		    "using \"Require user @%s\" on line %d of %s.",
2323 		    value, value, linenum, ConfigurationFile);
2324   }
2325   else if (!_cups_strcasecmp(line, "Require"))
2326   {
2327    /*
2328     * Apache synonym for AuthClass and AuthGroupName...
2329     *
2330     * Get initial word:
2331     *
2332     *     Require valid-user
2333     *     Require group names
2334     *     Require user names
2335     */
2336 
2337     for (valptr = value; !_cups_isspace(*valptr) && *valptr; valptr ++);
2338 
2339     if (*valptr)
2340       *valptr++ = '\0';
2341 
2342     if (!_cups_strcasecmp(value, "valid-user") ||
2343         !_cups_strcasecmp(value, "user"))
2344       loc->level = CUPSD_AUTH_USER;
2345     else if (!_cups_strcasecmp(value, "group"))
2346       loc->level = CUPSD_AUTH_GROUP;
2347     else
2348     {
2349       cupsdLogMessage(CUPSD_LOG_WARN, "Unknown Require type %s on line %d of %s.",
2350 	              value, linenum, ConfigurationFile);
2351       return (0);
2352     }
2353 
2354    /*
2355     * Get the list of names from the line...
2356     */
2357 
2358     for (value = valptr; *value;)
2359     {
2360       while (_cups_isspace(*value))
2361 	value ++;
2362 
2363 #ifdef HAVE_AUTHORIZATION_H
2364       if (!strncmp(value, "@AUTHKEY(", 9))
2365       {
2366        /*
2367 	* Grab "@AUTHKEY(name)" value...
2368 	*/
2369 
2370         for (valptr = value + 9; *valptr != ')' && *valptr; valptr ++);
2371 
2372 	if (*valptr)
2373 	  *valptr++ = '\0';
2374       }
2375       else
2376 #endif /* HAVE_AUTHORIZATION_H */
2377       if (*value == '\"' || *value == '\'')
2378       {
2379        /*
2380 	* Grab quoted name...
2381 	*/
2382 
2383         for (valptr = value + 1; *valptr != *value && *valptr; valptr ++);
2384 
2385 	value ++;
2386       }
2387       else
2388       {
2389        /*
2390 	* Grab literal name.
2391 	*/
2392 
2393         for (valptr = value; !_cups_isspace(*valptr) && *valptr; valptr ++);
2394       }
2395 
2396       if (*valptr)
2397 	*valptr++ = '\0';
2398 
2399       cupsdAddName(loc, value);
2400 
2401       for (value = valptr; _cups_isspace(*value); value ++);
2402     }
2403   }
2404   else if (!_cups_strcasecmp(line, "Satisfy"))
2405   {
2406     if (!_cups_strcasecmp(value, "all"))
2407       loc->satisfy = CUPSD_AUTH_SATISFY_ALL;
2408     else if (!_cups_strcasecmp(value, "any"))
2409       loc->satisfy = CUPSD_AUTH_SATISFY_ANY;
2410     else
2411     {
2412       cupsdLogMessage(CUPSD_LOG_WARN, "Unknown Satisfy value %s on line %d of %s.",
2413                       value, linenum, ConfigurationFile);
2414       return (0);
2415     }
2416   }
2417   else
2418     return (0);
2419 
2420   return (1);
2421 }
2422 
2423 
2424 /*
2425  * 'parse_fatal_errors()' - Parse FatalErrors values in a string.
2426  */
2427 
2428 static int				/* O - FatalErrors bits */
parse_fatal_errors(const char * s)2429 parse_fatal_errors(const char *s)	/* I - FatalErrors string */
2430 {
2431   int	fatal;				/* FatalErrors bits */
2432   char	value[1024],			/* Value string */
2433 	*valstart,			/* Pointer into value */
2434 	*valend;			/* End of value */
2435 
2436 
2437  /*
2438   * Empty FatalErrors line yields NULL pointer...
2439   */
2440 
2441   if (!s)
2442     return (CUPSD_FATAL_NONE);
2443 
2444  /*
2445   * Loop through the value string,...
2446   */
2447 
2448   strlcpy(value, s, sizeof(value));
2449 
2450   fatal = CUPSD_FATAL_NONE;
2451 
2452   for (valstart = value; *valstart;)
2453   {
2454    /*
2455     * Get the current space/comma-delimited kind name...
2456     */
2457 
2458     for (valend = valstart; *valend; valend ++)
2459       if (_cups_isspace(*valend) || *valend == ',')
2460 	break;
2461 
2462     if (*valend)
2463       *valend++ = '\0';
2464 
2465    /*
2466     * Add the error to the bitmask...
2467     */
2468 
2469     if (!_cups_strcasecmp(valstart, "all"))
2470       fatal = CUPSD_FATAL_ALL;
2471     else if (!_cups_strcasecmp(valstart, "browse"))
2472       fatal |= CUPSD_FATAL_BROWSE;
2473     else if (!_cups_strcasecmp(valstart, "-browse"))
2474       fatal &= ~CUPSD_FATAL_BROWSE;
2475     else if (!_cups_strcasecmp(valstart, "config"))
2476       fatal |= CUPSD_FATAL_CONFIG;
2477     else if (!_cups_strcasecmp(valstart, "-config"))
2478       fatal &= ~CUPSD_FATAL_CONFIG;
2479     else if (!_cups_strcasecmp(valstart, "listen"))
2480       fatal |= CUPSD_FATAL_LISTEN;
2481     else if (!_cups_strcasecmp(valstart, "-listen"))
2482       fatal &= ~CUPSD_FATAL_LISTEN;
2483     else if (!_cups_strcasecmp(valstart, "log"))
2484       fatal |= CUPSD_FATAL_LOG;
2485     else if (!_cups_strcasecmp(valstart, "-log"))
2486       fatal &= ~CUPSD_FATAL_LOG;
2487     else if (!_cups_strcasecmp(valstart, "permissions"))
2488       fatal |= CUPSD_FATAL_PERMISSIONS;
2489     else if (!_cups_strcasecmp(valstart, "-permissions"))
2490       fatal &= ~CUPSD_FATAL_PERMISSIONS;
2491     else if (_cups_strcasecmp(valstart, "none"))
2492       cupsdLogMessage(CUPSD_LOG_ERROR,
2493                       "Unknown FatalErrors kind \"%s\" ignored.", valstart);
2494 
2495     for (valstart = valend; *valstart; valstart ++)
2496       if (!_cups_isspace(*valstart) || *valstart != ',')
2497 	break;
2498   }
2499 
2500   return (fatal);
2501 }
2502 
2503 
2504 /*
2505  * 'parse_groups()' - Parse system group names in a string.
2506  */
2507 
2508 static int				/* O - 1 on success, 0 on failure */
parse_groups(const char * s,int linenum)2509 parse_groups(const char *s,		/* I - Space-delimited groups */
2510              int        linenum)        /* I - Line number in cups-files.conf */
2511 {
2512   int		status;			/* Return status */
2513   char		value[1024],		/* Value string */
2514 		*valstart,		/* Pointer into value */
2515 		*valend,		/* End of value */
2516 		quote;			/* Quote character */
2517   struct group	*group;			/* Group */
2518 
2519 
2520  /*
2521   * Make a copy of the string and parse out the groups...
2522   */
2523 
2524   strlcpy(value, s, sizeof(value));
2525 
2526   status   = 1;
2527   valstart = value;
2528 
2529   while (*valstart && NumSystemGroups < MAX_SYSTEM_GROUPS)
2530   {
2531     if (*valstart == '\'' || *valstart == '\"')
2532     {
2533      /*
2534       * Scan quoted name...
2535       */
2536 
2537       quote = *valstart++;
2538 
2539       for (valend = valstart; *valend; valend ++)
2540 	if (*valend == quote)
2541 	  break;
2542     }
2543     else
2544     {
2545      /*
2546       * Scan space or comma-delimited name...
2547       */
2548 
2549       for (valend = valstart; *valend; valend ++)
2550 	if (_cups_isspace(*valend) || *valend == ',')
2551 	  break;
2552     }
2553 
2554     if (*valend)
2555       *valend++ = '\0';
2556 
2557     group = getgrnam(valstart);
2558     if (group)
2559     {
2560       cupsdSetString(SystemGroups + NumSystemGroups, valstart);
2561       SystemGroupIDs[NumSystemGroups] = group->gr_gid;
2562 
2563       NumSystemGroups ++;
2564     }
2565     else
2566     {
2567       if (linenum)
2568         cupsdLogMessage(CUPSD_LOG_ERROR, "Unknown SystemGroup \"%s\" on line %d of %s.", valstart, linenum, CupsFilesFile);
2569       else
2570         cupsdLogMessage(CUPSD_LOG_ERROR, "Unknown default SystemGroup \"%s\".", valstart);
2571 
2572       status = 0;
2573     }
2574 
2575     endgrent();
2576 
2577     valstart = valend;
2578 
2579     while (*valstart == ',' || _cups_isspace(*valstart))
2580       valstart ++;
2581   }
2582 
2583   return (status);
2584 }
2585 
2586 
2587 /*
2588  * 'parse_protocols()' - Parse browse protocols in a string.
2589  */
2590 
2591 static int				/* O - Browse protocol bits */
parse_protocols(const char * s)2592 parse_protocols(const char *s)		/* I - Space-delimited protocols */
2593 {
2594   int	protocols;			/* Browse protocol bits */
2595   char	value[1024],			/* Value string */
2596 	*valstart,			/* Pointer into value */
2597 	*valend;			/* End of value */
2598 
2599 
2600  /*
2601   * Empty protocol line yields NULL pointer...
2602   */
2603 
2604   if (!s)
2605     return (0);
2606 
2607  /*
2608   * Loop through the value string,...
2609   */
2610 
2611   strlcpy(value, s, sizeof(value));
2612 
2613   protocols = 0;
2614 
2615   for (valstart = value; *valstart;)
2616   {
2617    /*
2618     * Get the current space/comma-delimited protocol name...
2619     */
2620 
2621     for (valend = valstart; *valend; valend ++)
2622       if (_cups_isspace(*valend) || *valend == ',')
2623 	break;
2624 
2625     if (*valend)
2626       *valend++ = '\0';
2627 
2628    /*
2629     * Add the protocol to the bitmask...
2630     */
2631 
2632     if (!_cups_strcasecmp(valstart, "dnssd") ||
2633 	!_cups_strcasecmp(valstart, "dns-sd") ||
2634 	!_cups_strcasecmp(valstart, "bonjour"))
2635       protocols |= BROWSE_DNSSD;
2636     else if (!_cups_strcasecmp(valstart, "all"))
2637       protocols |= BROWSE_ALL;
2638     else if (_cups_strcasecmp(valstart, "none"))
2639       cupsdLogMessage(CUPSD_LOG_ERROR,
2640                       "Unknown browse protocol \"%s\" ignored.", valstart);
2641 
2642     for (valstart = valend; *valstart; valstart ++)
2643       if (!_cups_isspace(*valstart) || *valstart != ',')
2644 	break;
2645   }
2646 
2647   return (protocols);
2648 }
2649 
2650 
2651 /*
2652  * 'parse_variable()' - Parse a variable line.
2653  */
2654 
2655 static int				/* O - 1 on success, 0 on failure */
parse_variable(const char * filename,int linenum,const char * line,const char * value,size_t num_vars,const cupsd_var_t * vars)2656 parse_variable(
2657     const char        *filename,	/* I - Name of configuration file */
2658     int               linenum,		/* I - Line in configuration file */
2659     const char        *line,		/* I - Line from configuration file */
2660     const char        *value,		/* I - Value from configuration file */
2661     size_t            num_vars,		/* I - Number of variables */
2662     const cupsd_var_t *vars)		/* I - Variables */
2663 {
2664   size_t		i;		/* Looping var */
2665   const cupsd_var_t	*var;		/* Variables */
2666   char			temp[1024];	/* Temporary string */
2667 
2668 
2669   for (i = num_vars, var = vars; i > 0; i --, var ++)
2670     if (!_cups_strcasecmp(line, var->name))
2671       break;
2672 
2673   if (i == 0)
2674   {
2675    /*
2676     * Unknown directive!  Output an error message and continue...
2677     */
2678 
2679     if (!value)
2680       cupsdLogMessage(CUPSD_LOG_ERROR, "Missing value for %s on line %d of %s.",
2681 		      line, linenum, filename);
2682     else
2683       cupsdLogMessage(CUPSD_LOG_ERROR, "Unknown directive %s on line %d of %s.",
2684 		      line, linenum, filename);
2685 
2686     return (0);
2687   }
2688 
2689   switch (var->type)
2690   {
2691     case CUPSD_VARTYPE_INTEGER :
2692 	if (!value)
2693 	{
2694 	  cupsdLogMessage(CUPSD_LOG_ERROR,
2695 			  "Missing integer value for %s on line %d of %s.",
2696 			  line, linenum, filename);
2697           return (0);
2698 	}
2699 	else if (!isdigit(*value & 255))
2700 	{
2701 	  cupsdLogMessage(CUPSD_LOG_ERROR,
2702 			  "Bad integer value for %s on line %d of %s.",
2703 			  line, linenum, filename);
2704           return (0);
2705 	}
2706 	else
2707 	{
2708 	  int	n;		/* Number */
2709 	  char	*units;		/* Units */
2710 
2711 	  n = strtol(value, &units, 0);
2712 
2713 	  if (units && *units)
2714 	  {
2715 	    if (tolower(units[0] & 255) == 'g')
2716 	      n *= 1024 * 1024 * 1024;
2717 	    else if (tolower(units[0] & 255) == 'm')
2718 	      n *= 1024 * 1024;
2719 	    else if (tolower(units[0] & 255) == 'k')
2720 	      n *= 1024;
2721 	    else if (tolower(units[0] & 255) == 't')
2722 	      n *= 262144;
2723 	    else
2724 	    {
2725 	      cupsdLogMessage(CUPSD_LOG_ERROR,
2726 			      "Unknown integer value for %s on line %d of %s.",
2727 			      line, linenum, filename);
2728 	      return (0);
2729 	    }
2730 	  }
2731 
2732 	  if (n < 0)
2733 	  {
2734 	    cupsdLogMessage(CUPSD_LOG_ERROR,
2735 			    "Bad negative integer value for %s on line %d of "
2736 			    "%s.", line, linenum, filename);
2737 	    return (0);
2738 	  }
2739 	  else
2740 	  {
2741 	    *((int *)var->ptr) = n;
2742 	  }
2743 	}
2744 	break;
2745 
2746     case CUPSD_VARTYPE_PERM :
2747 	if (!value)
2748 	{
2749 	  cupsdLogMessage(CUPSD_LOG_ERROR,
2750 			  "Missing permissions value for %s on line %d of %s.",
2751 			  line, linenum, filename);
2752           return (0);
2753 	}
2754 	else if (!isdigit(*value & 255))
2755 	{
2756 	 /* TODO: Add chmod UGO syntax support */
2757 	  cupsdLogMessage(CUPSD_LOG_ERROR,
2758 			  "Bad permissions value for %s on line %d of %s.",
2759 			  line, linenum, filename);
2760           return (0);
2761 	}
2762 	else
2763 	{
2764 	  int n = strtol(value, NULL, 8);
2765 					/* Permissions value */
2766 
2767 	  if (n < 0)
2768 	  {
2769 	    cupsdLogMessage(CUPSD_LOG_ERROR,
2770 			    "Bad negative permissions value for %s on line %d of "
2771 			    "%s.", line, linenum, filename);
2772 	    return (0);
2773 	  }
2774 	  else
2775 	  {
2776 	    *((mode_t *)var->ptr) = (mode_t)n;
2777 	  }
2778 	}
2779 	break;
2780 
2781     case CUPSD_VARTYPE_TIME :
2782 	if (!value)
2783 	{
2784 	  cupsdLogMessage(CUPSD_LOG_ERROR,
2785 			  "Missing time interval value for %s on line %d of "
2786 			  "%s.", line, linenum, filename);
2787 	  return (0);
2788 	}
2789 	else if (!_cups_strncasecmp(line, "PreserveJob", 11) &&
2790 		 (!_cups_strcasecmp(value, "true") ||
2791 		  !_cups_strcasecmp(value, "on") ||
2792 		  !_cups_strcasecmp(value, "enabled") ||
2793 		  !_cups_strcasecmp(value, "yes")))
2794 	{
2795 	  *((int *)var->ptr) = INT_MAX;
2796 	}
2797 	else if (!_cups_strcasecmp(value, "false") ||
2798 		 !_cups_strcasecmp(value, "off") ||
2799 		 !_cups_strcasecmp(value, "disabled") ||
2800 		 !_cups_strcasecmp(value, "no"))
2801 	{
2802 	  *((int *)var->ptr) = 0;
2803 	}
2804 	else if (!isdigit(*value & 255))
2805 	{
2806 	  cupsdLogMessage(CUPSD_LOG_ERROR,
2807 			  "Unknown time interval value for %s on line %d of "
2808 			  "%s.", line, linenum, filename);
2809           return (0);
2810 	}
2811 	else
2812 	{
2813 	  double	n;		/* Number */
2814 	  char		*units;		/* Units */
2815 
2816 	  n = strtod(value, &units);
2817 
2818 	  if (units && *units)
2819 	  {
2820 	    if (tolower(units[0] & 255) == 'w')
2821 	      n *= 7 * 24 * 60 * 60;
2822 	    else if (tolower(units[0] & 255) == 'd')
2823 	      n *= 24 * 60 * 60;
2824 	    else if (tolower(units[0] & 255) == 'h')
2825 	      n *= 60 * 60;
2826 	    else if (tolower(units[0] & 255) == 'm')
2827 	      n *= 60;
2828 	    else
2829 	    {
2830 	      cupsdLogMessage(CUPSD_LOG_ERROR,
2831 			      "Unknown time interval value for %s on line "
2832 			      "%d of %s.", line, linenum, filename);
2833 	      return (0);
2834 	    }
2835 	  }
2836 
2837 	  if (n < 0.0 || n > INT_MAX)
2838 	  {
2839 	    cupsdLogMessage(CUPSD_LOG_ERROR,
2840 			    "Bad time value for %s on line %d of %s.",
2841 			    line, linenum, filename);
2842 	    return (0);
2843 	  }
2844 	  else
2845 	  {
2846 	    *((int *)var->ptr) = (int)n;
2847 	  }
2848 	}
2849 	break;
2850 
2851     case CUPSD_VARTYPE_BOOLEAN :
2852 	if (!value)
2853 	{
2854 	  cupsdLogMessage(CUPSD_LOG_ERROR,
2855 			  "Missing boolean value for %s on line %d of %s.",
2856 			  line, linenum, filename);
2857 	  return (0);
2858 	}
2859 	else if (!_cups_strcasecmp(value, "true") ||
2860 		 !_cups_strcasecmp(value, "on") ||
2861 		 !_cups_strcasecmp(value, "enabled") ||
2862 		 !_cups_strcasecmp(value, "yes") ||
2863 		 atoi(value) != 0)
2864 	{
2865 	  *((int *)var->ptr) = TRUE;
2866 	}
2867 	else if (!_cups_strcasecmp(value, "false") ||
2868 		 !_cups_strcasecmp(value, "off") ||
2869 		 !_cups_strcasecmp(value, "disabled") ||
2870 		 !_cups_strcasecmp(value, "no") ||
2871 		 !_cups_strcasecmp(value, "0"))
2872 	{
2873 	  *((int *)var->ptr) = FALSE;
2874 	}
2875 	else
2876 	{
2877 	  cupsdLogMessage(CUPSD_LOG_ERROR,
2878 			  "Unknown boolean value %s on line %d of %s.",
2879 			  value, linenum, filename);
2880 	  return (0);
2881 	}
2882 	break;
2883 
2884     case CUPSD_VARTYPE_PATHNAME :
2885 	if (!value)
2886 	{
2887 	  cupsdLogMessage(CUPSD_LOG_ERROR,
2888 			  "Missing pathname value for %s on line %d of %s.",
2889 			  line, linenum, filename);
2890 	  return (0);
2891 	}
2892 
2893 	if (value[0] == '/')
2894 	  strlcpy(temp, value, sizeof(temp));
2895 	else
2896 	  snprintf(temp, sizeof(temp), "%s/%s", ServerRoot, value);
2897 
2898 	if (access(temp, 0) && _cups_strcasecmp(value, "internal") && _cups_strcasecmp(line, "ServerKeychain"))
2899 	{
2900 	  cupsdLogMessage(CUPSD_LOG_ERROR,
2901 			  "File or directory for \"%s %s\" on line %d of %s "
2902 			  "does not exist.", line, value, linenum, filename);
2903 	  return (0);
2904 	}
2905 
2906 	cupsdSetString((char **)var->ptr, temp);
2907 	break;
2908 
2909     case CUPSD_VARTYPE_STRING :
2910 	cupsdSetString((char **)var->ptr, value);
2911 	break;
2912   }
2913 
2914   return (1);
2915 }
2916 
2917 
2918 /*
2919  * 'read_cupsd_conf()' - Read the cupsd.conf configuration file.
2920  */
2921 
2922 static int				/* O - 1 on success, 0 on failure */
read_cupsd_conf(cups_file_t * fp)2923 read_cupsd_conf(cups_file_t *fp)	/* I - File to read from */
2924 {
2925   int			linenum;	/* Current line number */
2926   char			line[HTTP_MAX_BUFFER],
2927 					/* Line from file */
2928 			temp[HTTP_MAX_BUFFER],
2929 					/* Temporary buffer for value */
2930 			*value;		/* Pointer to value */
2931   int			valuelen;	/* Length of value */
2932   http_addrlist_t	*addrlist,	/* Address list */
2933 			*addr;		/* Current address */
2934 
2935 
2936  /*
2937   * Loop through each line in the file...
2938   */
2939 
2940   linenum = 0;
2941 
2942   while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
2943   {
2944    /*
2945     * Decode the directive...
2946     */
2947 
2948     if (!_cups_strcasecmp(line, "<Location") && value)
2949     {
2950      /*
2951       * <Location path>
2952       */
2953 
2954       linenum = read_location(fp, value, linenum);
2955       if (linenum == 0)
2956 	return (0);
2957     }
2958     else if (!_cups_strcasecmp(line, "<Policy") && value)
2959     {
2960      /*
2961       * <Policy name>
2962       */
2963 
2964       linenum = read_policy(fp, value, linenum);
2965       if (linenum == 0)
2966 	return (0);
2967     }
2968     else if (!_cups_strcasecmp(line, "FaxRetryInterval") && value)
2969     {
2970       JobRetryInterval = atoi(value);
2971       cupsdLogMessage(CUPSD_LOG_WARN,
2972 		      "FaxRetryInterval is deprecated; use "
2973 		      "JobRetryInterval on line %d of %s.", linenum, ConfigurationFile);
2974     }
2975     else if (!_cups_strcasecmp(line, "FaxRetryLimit") && value)
2976     {
2977       JobRetryLimit = atoi(value);
2978       cupsdLogMessage(CUPSD_LOG_WARN,
2979 		      "FaxRetryLimit is deprecated; use "
2980 		      "JobRetryLimit on line %d of %s.", linenum, ConfigurationFile);
2981     }
2982 #ifdef HAVE_SSL
2983     else if (!_cups_strcasecmp(line, "SSLOptions"))
2984     {
2985      /*
2986       * SSLOptions [AllowRC4] [AllowSSL3] [AllowDH] [DenyCBC] [DenyTLS1.0] [None]
2987       */
2988 
2989       int	options = _HTTP_TLS_NONE,/* SSL/TLS options */
2990 		min_version = _HTTP_TLS_1_0,
2991 		max_version = _HTTP_TLS_MAX;
2992 
2993       if (value)
2994       {
2995         char	*start,			/* Start of option */
2996 		*end;			/* End of option */
2997 
2998 	for (start = value; *start; start = end)
2999 	{
3000 	 /*
3001 	  * Find end of keyword...
3002 	  */
3003 
3004 	  end = start;
3005 	  while (*end && !_cups_isspace(*end))
3006 	    end ++;
3007 
3008 	  if (*end)
3009 	    *end++ = '\0';
3010 
3011          /*
3012 	  * Compare...
3013 	  */
3014 
3015 	  if (!_cups_strcasecmp(start, "AllowRC4"))
3016 	    options |= _HTTP_TLS_ALLOW_RC4;
3017 	  else if (!_cups_strcasecmp(start, "AllowSSL3"))
3018 	    min_version = _HTTP_TLS_SSL3;
3019 	  else if (!_cups_strcasecmp(start, "AllowDH"))
3020 	    options |= _HTTP_TLS_ALLOW_DH;
3021 	  else if (!_cups_strcasecmp(start, "DenyCBC"))
3022 	    options |= _HTTP_TLS_DENY_CBC;
3023 	  else if (!_cups_strcasecmp(start, "DenyTLS1.0"))
3024 	    min_version = _HTTP_TLS_1_1;
3025 	  else if (!_cups_strcasecmp(start, "MaxTLS1.0"))
3026 	    max_version = _HTTP_TLS_1_0;
3027 	  else if (!_cups_strcasecmp(start, "MaxTLS1.1"))
3028 	    max_version = _HTTP_TLS_1_1;
3029 	  else if (!_cups_strcasecmp(start, "MaxTLS1.2"))
3030 	    max_version = _HTTP_TLS_1_2;
3031 	  else if (!_cups_strcasecmp(start, "MaxTLS1.3"))
3032 	    max_version = _HTTP_TLS_1_3;
3033 	  else if (!_cups_strcasecmp(start, "MinTLS1.0"))
3034 	    min_version = _HTTP_TLS_1_0;
3035 	  else if (!_cups_strcasecmp(start, "MinTLS1.1"))
3036 	    min_version = _HTTP_TLS_1_1;
3037 	  else if (!_cups_strcasecmp(start, "MinTLS1.2"))
3038 	    min_version = _HTTP_TLS_1_2;
3039 	  else if (!_cups_strcasecmp(start, "MinTLS1.3"))
3040 	    min_version = _HTTP_TLS_1_3;
3041 	  else if (!_cups_strcasecmp(start, "None"))
3042 	    options = _HTTP_TLS_NONE;
3043 	  else if (_cups_strcasecmp(start, "NoEmptyFragments"))
3044 	    cupsdLogMessage(CUPSD_LOG_WARN, "Unknown SSL option %s at line %d.", start, linenum);
3045         }
3046       }
3047 
3048       _httpTLSSetOptions(options, min_version, max_version);
3049     }
3050 #endif /* HAVE_SSL */
3051     else if ((!_cups_strcasecmp(line, "Port") || !_cups_strcasecmp(line, "Listen")
3052 #ifdef HAVE_SSL
3053              || !_cups_strcasecmp(line, "SSLPort") || !_cups_strcasecmp(line, "SSLListen")
3054 #endif /* HAVE_SSL */
3055 	     ) && value)
3056     {
3057      /*
3058       * Add listening address(es) to the list...
3059       */
3060 
3061       cupsd_listener_t	*lis;		/* New listeners array */
3062 
3063 
3064      /*
3065       * Get the address list...
3066       */
3067 
3068       addrlist = get_address(value, IPP_PORT);
3069 
3070       if (!addrlist)
3071       {
3072         cupsdLogMessage(CUPSD_LOG_ERROR, "Bad %s address %s at line %d.", line,
3073 	                value, linenum);
3074         continue;
3075       }
3076 
3077      /*
3078       * Add each address...
3079       */
3080 
3081       for (addr = addrlist; addr; addr = addr->next)
3082       {
3083        /*
3084         * See if this address is already present...
3085 	*/
3086 
3087         for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
3088 	     lis;
3089 	     lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
3090           if (httpAddrEqual(&(addr->addr), &(lis->address)) &&
3091 	      httpAddrPort(&(addr->addr)) == httpAddrPort(&(lis->address)))
3092 	    break;
3093 
3094         if (lis)
3095 	{
3096 #ifdef HAVE_ONDEMAND
3097 	  if (!lis->on_demand)
3098 #endif /* HAVE_ONDEMAND */
3099 	  {
3100 	    httpAddrString(&lis->address, temp, sizeof(temp));
3101 	    cupsdLogMessage(CUPSD_LOG_WARN,
3102 			    "Duplicate listen address \"%s\" ignored.", temp);
3103 	  }
3104 
3105           continue;
3106 	}
3107 
3108        /*
3109         * Allocate another listener...
3110 	*/
3111 
3112         if (!Listeners)
3113 	  Listeners = cupsArrayNew(NULL, NULL);
3114 
3115 	if (!Listeners)
3116 	{
3117           cupsdLogMessage(CUPSD_LOG_ERROR,
3118 	                  "Unable to allocate %s at line %d - %s.",
3119 	                  line, linenum, strerror(errno));
3120           break;
3121 	}
3122 
3123         if ((lis = calloc(1, sizeof(cupsd_listener_t))) == NULL)
3124 	{
3125           cupsdLogMessage(CUPSD_LOG_ERROR,
3126 	                  "Unable to allocate %s at line %d - %s.",
3127 	                  line, linenum, strerror(errno));
3128           break;
3129 	}
3130 
3131         cupsArrayAdd(Listeners, lis);
3132 
3133        /*
3134         * Copy the current address and log it...
3135 	*/
3136 
3137 	memcpy(&(lis->address), &(addr->addr), sizeof(lis->address));
3138 	lis->fd = -1;
3139 
3140 #ifdef HAVE_SSL
3141         if (!_cups_strcasecmp(line, "SSLPort") || !_cups_strcasecmp(line, "SSLListen"))
3142           lis->encryption = HTTP_ENCRYPT_ALWAYS;
3143 #endif /* HAVE_SSL */
3144 
3145 	httpAddrString(&lis->address, temp, sizeof(temp));
3146 
3147 #ifdef AF_LOCAL
3148         if (lis->address.addr.sa_family == AF_LOCAL)
3149           cupsdLogMessage(CUPSD_LOG_INFO, "Listening to %s (Domain)", temp);
3150 	else
3151 #endif /* AF_LOCAL */
3152 	cupsdLogMessage(CUPSD_LOG_INFO, "Listening to %s:%d (IPv%d)", temp,
3153                         httpAddrPort(&(lis->address)),
3154 			httpAddrFamily(&(lis->address)) == AF_INET ? 4 : 6);
3155 
3156         if (!httpAddrLocalhost(&(lis->address)))
3157 	  RemotePort = httpAddrPort(&(lis->address));
3158       }
3159 
3160      /*
3161       * Free the list...
3162       */
3163 
3164       httpAddrFreeList(addrlist);
3165     }
3166     else if (!_cups_strcasecmp(line, "BrowseProtocols") ||
3167              !_cups_strcasecmp(line, "BrowseLocalProtocols"))
3168     {
3169      /*
3170       * "BrowseProtocols name [... name]"
3171       * "BrowseLocalProtocols name [... name]"
3172       */
3173 
3174       int protocols = parse_protocols(value);
3175 
3176       if (protocols < 0)
3177       {
3178 	cupsdLogMessage(CUPSD_LOG_ERROR,
3179 	                "Unknown browse protocol \"%s\" on line %d of %s.",
3180 	                value, linenum, ConfigurationFile);
3181         break;
3182       }
3183 
3184       BrowseLocalProtocols = protocols;
3185     }
3186     else if (!_cups_strcasecmp(line, "DefaultAuthType") && value)
3187     {
3188      /*
3189       * DefaultAuthType {basic,digest,basicdigest,negotiate}
3190       */
3191 
3192       if (!_cups_strcasecmp(value, "none"))
3193 	default_auth_type = CUPSD_AUTH_NONE;
3194       else if (!_cups_strcasecmp(value, "basic"))
3195 	default_auth_type = CUPSD_AUTH_BASIC;
3196       else if (!_cups_strcasecmp(value, "negotiate"))
3197         default_auth_type = CUPSD_AUTH_NEGOTIATE;
3198       else if (!_cups_strcasecmp(value, "auto"))
3199         default_auth_type = CUPSD_AUTH_AUTO;
3200       else
3201       {
3202 	cupsdLogMessage(CUPSD_LOG_WARN,
3203 	                "Unknown default authorization type %s on line %d of %s.",
3204 	                value, linenum, ConfigurationFile);
3205 	if (FatalErrors & CUPSD_FATAL_CONFIG)
3206 	  return (0);
3207       }
3208     }
3209 #ifdef HAVE_SSL
3210     else if (!_cups_strcasecmp(line, "DefaultEncryption"))
3211     {
3212      /*
3213       * DefaultEncryption {Never,IfRequested,Required}
3214       */
3215 
3216       if (!value || !_cups_strcasecmp(value, "never"))
3217 	DefaultEncryption = HTTP_ENCRYPT_NEVER;
3218       else if (!_cups_strcasecmp(value, "required"))
3219 	DefaultEncryption = HTTP_ENCRYPT_REQUIRED;
3220       else if (!_cups_strcasecmp(value, "ifrequested"))
3221 	DefaultEncryption = HTTP_ENCRYPT_IF_REQUESTED;
3222       else
3223       {
3224 	cupsdLogMessage(CUPSD_LOG_WARN,
3225 	                "Unknown default encryption %s on line %d of %s.",
3226 	                value, linenum, ConfigurationFile);
3227 	if (FatalErrors & CUPSD_FATAL_CONFIG)
3228 	  return (0);
3229       }
3230     }
3231 #endif /* HAVE_SSL */
3232     else if (!_cups_strcasecmp(line, "HostNameLookups") && value)
3233     {
3234      /*
3235       * Do hostname lookups?
3236       */
3237 
3238       if (!_cups_strcasecmp(value, "off") || !_cups_strcasecmp(value, "no") ||
3239           !_cups_strcasecmp(value, "false"))
3240         HostNameLookups = 0;
3241       else if (!_cups_strcasecmp(value, "on") || !_cups_strcasecmp(value, "yes") ||
3242           !_cups_strcasecmp(value, "true"))
3243         HostNameLookups = 1;
3244       else if (!_cups_strcasecmp(value, "double"))
3245         HostNameLookups = 2;
3246       else
3247 	cupsdLogMessage(CUPSD_LOG_WARN, "Unknown HostNameLookups %s on line %d of %s.",
3248 	                value, linenum, ConfigurationFile);
3249     }
3250     else if (!_cups_strcasecmp(line, "AccessLogLevel") && value)
3251     {
3252      /*
3253       * Amount of logging to do to access log...
3254       */
3255 
3256       if (!_cups_strcasecmp(value, "all"))
3257         AccessLogLevel = CUPSD_ACCESSLOG_ALL;
3258       else if (!_cups_strcasecmp(value, "actions"))
3259         AccessLogLevel = CUPSD_ACCESSLOG_ACTIONS;
3260       else if (!_cups_strcasecmp(value, "config"))
3261         AccessLogLevel = CUPSD_ACCESSLOG_CONFIG;
3262       else if (!_cups_strcasecmp(value, "none"))
3263         AccessLogLevel = CUPSD_ACCESSLOG_NONE;
3264       else
3265         cupsdLogMessage(CUPSD_LOG_WARN, "Unknown AccessLogLevel %s on line %d of %s.",
3266 	                value, linenum, ConfigurationFile);
3267     }
3268     else if (!_cups_strcasecmp(line, "LogLevel") && value)
3269     {
3270      /*
3271       * Amount of logging to do to error log...
3272       */
3273 
3274       if (!_cups_strcasecmp(value, "debug2"))
3275         LogLevel = CUPSD_LOG_DEBUG2;
3276       else if (!_cups_strcasecmp(value, "debug"))
3277         LogLevel = CUPSD_LOG_DEBUG;
3278       else if (!_cups_strcasecmp(value, "info"))
3279         LogLevel = CUPSD_LOG_INFO;
3280       else if (!_cups_strcasecmp(value, "notice"))
3281         LogLevel = CUPSD_LOG_NOTICE;
3282       else if (!_cups_strcasecmp(value, "warn"))
3283         LogLevel = CUPSD_LOG_WARN;
3284       else if (!_cups_strcasecmp(value, "error"))
3285         LogLevel = CUPSD_LOG_ERROR;
3286       else if (!_cups_strcasecmp(value, "crit"))
3287         LogLevel = CUPSD_LOG_CRIT;
3288       else if (!_cups_strcasecmp(value, "alert"))
3289         LogLevel = CUPSD_LOG_ALERT;
3290       else if (!_cups_strcasecmp(value, "emerg"))
3291         LogLevel = CUPSD_LOG_EMERG;
3292       else if (!_cups_strcasecmp(value, "none"))
3293         LogLevel = CUPSD_LOG_NONE;
3294       else
3295         cupsdLogMessage(CUPSD_LOG_WARN, "Unknown LogLevel %s on line %d of %s.",
3296 	                value, linenum, ConfigurationFile);
3297     }
3298     else if (!_cups_strcasecmp(line, "LogTimeFormat") && value)
3299     {
3300      /*
3301       * Amount of logging to do to error log...
3302       */
3303 
3304       if (!_cups_strcasecmp(value, "standard"))
3305         LogTimeFormat = CUPSD_TIME_STANDARD;
3306       else if (!_cups_strcasecmp(value, "usecs"))
3307         LogTimeFormat = CUPSD_TIME_USECS;
3308       else
3309         cupsdLogMessage(CUPSD_LOG_WARN, "Unknown LogTimeFormat %s on line %d of %s.",
3310 	                value, linenum, ConfigurationFile);
3311     }
3312     else if (!_cups_strcasecmp(line, "ServerTokens") && value)
3313     {
3314      /*
3315       * Set the string used for the Server header...
3316       */
3317 
3318       struct utsname plat;		/* Platform info */
3319 
3320 
3321       uname(&plat);
3322 
3323       if (!_cups_strcasecmp(value, "ProductOnly"))
3324 	cupsdSetString(&ServerHeader, "CUPS IPP");
3325       else if (!_cups_strcasecmp(value, "Major"))
3326 	cupsdSetStringf(&ServerHeader, "CUPS/%d IPP/2", CUPS_VERSION_MAJOR);
3327       else if (!_cups_strcasecmp(value, "Minor"))
3328 	cupsdSetStringf(&ServerHeader, "CUPS/%d.%d IPP/2.1", CUPS_VERSION_MAJOR,
3329 	                CUPS_VERSION_MINOR);
3330       else if (!_cups_strcasecmp(value, "Minimal"))
3331 	cupsdSetString(&ServerHeader, CUPS_MINIMAL " IPP/2.1");
3332       else if (!_cups_strcasecmp(value, "OS"))
3333 	cupsdSetStringf(&ServerHeader, CUPS_MINIMAL " (%s %s) IPP/2.1",
3334 	                plat.sysname, plat.release);
3335       else if (!_cups_strcasecmp(value, "Full"))
3336 	cupsdSetStringf(&ServerHeader, CUPS_MINIMAL " (%s %s; %s) IPP/2.1",
3337 	                plat.sysname, plat.release, plat.machine);
3338       else if (!_cups_strcasecmp(value, "None"))
3339 	cupsdSetString(&ServerHeader, "");
3340       else
3341 	cupsdLogMessage(CUPSD_LOG_WARN, "Unknown ServerTokens %s on line %d of %s.",
3342                         value, linenum, ConfigurationFile);
3343     }
3344     else if (!_cups_strcasecmp(line, "ServerAlias") && value)
3345     {
3346      /*
3347       * ServerAlias name [... name]
3348       */
3349 
3350       if (!ServerAlias)
3351         ServerAlias = cupsArrayNew(NULL, NULL);
3352 
3353       for (; *value;)
3354       {
3355         for (valuelen = 0; value[valuelen]; valuelen ++)
3356 	  if (_cups_isspace(value[valuelen]) || value[valuelen] == ',')
3357 	    break;
3358 
3359         if (value[valuelen])
3360         {
3361 	  value[valuelen] = '\0';
3362 	  valuelen ++;
3363 	}
3364 
3365 	cupsdAddAlias(ServerAlias, value);
3366 
3367         for (value += valuelen; *value; value ++)
3368 	  if (!_cups_isspace(*value) || *value != ',')
3369 	    break;
3370       }
3371     }
3372     else if (!_cups_strcasecmp(line, "AccessLog") ||
3373              !_cups_strcasecmp(line, "CacheDir") ||
3374              !_cups_strcasecmp(line, "ConfigFilePerm") ||
3375              !_cups_strcasecmp(line, "DataDir") ||
3376              !_cups_strcasecmp(line, "DocumentRoot") ||
3377              !_cups_strcasecmp(line, "ErrorLog") ||
3378              !_cups_strcasecmp(line, "FatalErrors") ||
3379              !_cups_strcasecmp(line, "FileDevice") ||
3380              !_cups_strcasecmp(line, "FontPath") ||
3381              !_cups_strcasecmp(line, "Group") ||
3382              !_cups_strcasecmp(line, "LogFilePerm") ||
3383              !_cups_strcasecmp(line, "LPDConfigFile") ||
3384              !_cups_strcasecmp(line, "PageLog") ||
3385              !_cups_strcasecmp(line, "PassEnv") ||
3386              !_cups_strcasecmp(line, "Printcap") ||
3387              !_cups_strcasecmp(line, "PrintcapFormat") ||
3388              !_cups_strcasecmp(line, "RemoteRoot") ||
3389              !_cups_strcasecmp(line, "RequestRoot") ||
3390              !_cups_strcasecmp(line, "ServerBin") ||
3391              !_cups_strcasecmp(line, "ServerCertificate") ||
3392              !_cups_strcasecmp(line, "ServerKey") ||
3393              !_cups_strcasecmp(line, "ServerKeychain") ||
3394              !_cups_strcasecmp(line, "ServerRoot") ||
3395              !_cups_strcasecmp(line, "SetEnv") ||
3396              !_cups_strcasecmp(line, "SMBConfigFile") ||
3397              !_cups_strcasecmp(line, "StateDir") ||
3398              !_cups_strcasecmp(line, "SystemGroup") ||
3399              !_cups_strcasecmp(line, "SystemGroupAuthKey") ||
3400              !_cups_strcasecmp(line, "TempDir") ||
3401 	     !_cups_strcasecmp(line, "User"))
3402     {
3403       cupsdLogMessage(CUPSD_LOG_INFO,
3404 		      "Please move \"%s%s%s\" on line %d of %s to the %s file; "
3405 		      "this will become an error in a future release.",
3406 		      line, value ? " " : "", value ? value : "", linenum,
3407 		      ConfigurationFile, CupsFilesFile);
3408     }
3409     else
3410       parse_variable(ConfigurationFile, linenum, line, value,
3411                      sizeof(cupsd_vars) / sizeof(cupsd_vars[0]), cupsd_vars);
3412   }
3413 
3414   return (1);
3415 }
3416 
3417 
3418 /*
3419  * 'read_cups_files_conf()' - Read the cups-files.conf configuration file.
3420  */
3421 
3422 static int				/* O - 1 on success, 0 on failure */
read_cups_files_conf(cups_file_t * fp)3423 read_cups_files_conf(cups_file_t *fp)	/* I - File to read from */
3424 {
3425   int		i,			/* Looping var */
3426 		linenum;		/* Current line number */
3427   char		line[HTTP_MAX_BUFFER],	/* Line from file */
3428 		*value;			/* Value from line */
3429   struct group	*group;			/* Group */
3430   static const char * const prohibited_env[] =
3431   {					/* Prohibited environment variables */
3432     "APPLE_LANGUAGE",
3433     "AUTH_DOMAIN",
3434     "AUTH_INFO_REQUIRED",
3435     "AUTH_NEGOTIATE",
3436     "AUTH_PASSWORD",
3437     "AUTH_UID",
3438     "AUTH_USERNAME",
3439     "CHARSET",
3440     "CLASS",
3441     "CLASSIFICATION",
3442     "CONTENT_TYPE",
3443     "CUPS_CACHEDIR",
3444     "CUPS_DATADIR",
3445     "CUPS_DOCROOT",
3446     "CUPS_FILETYPE",
3447     "CUPS_FONTPATH",
3448     "CUPS_MAX_MESSAGE",
3449     "CUPS_REQUESTROOT",
3450     "CUPS_SERVERBIN",
3451     "CUPS_SERVERROOT",
3452     "CUPS_STATEDIR",
3453     "DEVICE_URI",
3454     "FINAL_CONTENT_TYPE",
3455     "HOME",
3456     "LANG",
3457     "PPD",
3458     "PRINTER",
3459     "PRINTER_INFO",
3460     "PRINTER_LOCATION",
3461     "PRINTER_STATE_REASONS",
3462     "RIP_CACHE",
3463     "SERVER_ADMIN",
3464     "SOFTWARE",
3465     "TMPDIR",
3466     "USER"
3467   };
3468 
3469 
3470  /*
3471   * Loop through each line in the file...
3472   */
3473 
3474   linenum = 0;
3475 
3476   while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
3477   {
3478     if (!_cups_strcasecmp(line, "FatalErrors"))
3479       FatalErrors = parse_fatal_errors(value);
3480     else if (!_cups_strcasecmp(line, "Group") && value)
3481     {
3482      /*
3483       * Group ID to run as...
3484       */
3485 
3486       if (isdigit(value[0]))
3487         Group = (gid_t)atoi(value);
3488       else
3489       {
3490         endgrent();
3491 	group = getgrnam(value);
3492 
3493 	if (group != NULL)
3494 	  Group = group->gr_gid;
3495 	else
3496 	{
3497 	  cupsdLogMessage(CUPSD_LOG_ERROR,
3498 	                  "Unknown Group \"%s\" on line %d of %s.", value,
3499 	                  linenum, CupsFilesFile);
3500 	  if (FatalErrors & CUPSD_FATAL_CONFIG)
3501 	    return (0);
3502 	}
3503       }
3504     }
3505     else if (!_cups_strcasecmp(line, "PassEnv") && value)
3506     {
3507      /*
3508       * PassEnv variable [... variable]
3509       */
3510 
3511       int valuelen;			/* Length of variable name */
3512 
3513       for (; *value;)
3514       {
3515         for (valuelen = 0; value[valuelen]; valuelen ++)
3516 	  if (_cups_isspace(value[valuelen]) || value[valuelen] == ',')
3517 	    break;
3518 
3519         if (value[valuelen])
3520         {
3521 	  value[valuelen] = '\0';
3522 	  valuelen ++;
3523 	}
3524 
3525         for (i = 0; i < (int)(sizeof(prohibited_env) / sizeof(prohibited_env[0])); i ++)
3526         {
3527           if (!strcmp(value, prohibited_env[i]))
3528           {
3529 	    cupsdLogMessage(CUPSD_LOG_ERROR, "Environment variable \"%s\" cannot be passed through on line %d of %s.", value, linenum, CupsFilesFile);
3530 
3531 	    if (FatalErrors & CUPSD_FATAL_CONFIG)
3532 	      return (0);
3533 	    else
3534 	      break;
3535           }
3536 	}
3537 
3538         if (i >= (int)(sizeof(prohibited_env) / sizeof(prohibited_env[0])))
3539           cupsdSetEnv(value, NULL);
3540 
3541         for (value += valuelen; *value; value ++)
3542 	  if (!_cups_isspace(*value) || *value != ',')
3543 	    break;
3544       }
3545     }
3546     else if (!_cups_strcasecmp(line, "PrintcapFormat") && value)
3547     {
3548      /*
3549       * Format of printcap file?
3550       */
3551 
3552       if (!_cups_strcasecmp(value, "bsd"))
3553         PrintcapFormat = PRINTCAP_BSD;
3554       else if (!_cups_strcasecmp(value, "plist"))
3555         PrintcapFormat = PRINTCAP_PLIST;
3556       else if (!_cups_strcasecmp(value, "solaris"))
3557         PrintcapFormat = PRINTCAP_SOLARIS;
3558       else
3559       {
3560 	cupsdLogMessage(CUPSD_LOG_ERROR,
3561 	                "Unknown PrintcapFormat \"%s\" on line %d of %s.",
3562 	                value, linenum, CupsFilesFile);
3563         if (FatalErrors & CUPSD_FATAL_CONFIG)
3564           return (0);
3565       }
3566     }
3567     else if (!_cups_strcasecmp(line, "Sandboxing") && value)
3568     {
3569      /*
3570       * Level of sandboxing?
3571       */
3572 
3573       if (!_cups_strcasecmp(value, "off") && getuid())
3574         Sandboxing = CUPSD_SANDBOXING_OFF;
3575       else if (!_cups_strcasecmp(value, "relaxed"))
3576         Sandboxing = CUPSD_SANDBOXING_RELAXED;
3577       else if (!_cups_strcasecmp(value, "strict"))
3578         Sandboxing = CUPSD_SANDBOXING_STRICT;
3579       else
3580       {
3581 	cupsdLogMessage(CUPSD_LOG_ERROR,
3582 	                "Unknown Sandboxing \"%s\" on line %d of %s.",
3583 	                value, linenum, CupsFilesFile);
3584         if (FatalErrors & CUPSD_FATAL_CONFIG)
3585           return (0);
3586       }
3587     }
3588     else if (!_cups_strcasecmp(line, "SetEnv") && value)
3589     {
3590      /*
3591       * SetEnv variable value
3592       */
3593 
3594       char *valueptr;			/* Pointer to environment variable value */
3595 
3596       for (valueptr = value; *valueptr && !isspace(*valueptr & 255); valueptr ++);
3597 
3598       if (*valueptr)
3599       {
3600        /*
3601         * Found a value...
3602 	*/
3603 
3604         while (isspace(*valueptr & 255))
3605 	  *valueptr++ = '\0';
3606 
3607         for (i = 0; i < (int)(sizeof(prohibited_env) / sizeof(prohibited_env[0])); i ++)
3608         {
3609           if (!strcmp(value, prohibited_env[i]))
3610           {
3611 	    cupsdLogMessage(CUPSD_LOG_ERROR, "Environment variable \"%s\" cannot be set  on line %d of %s.", value, linenum, CupsFilesFile);
3612 
3613 	    if (FatalErrors & CUPSD_FATAL_CONFIG)
3614 	      return (0);
3615 	    else
3616 	      break;
3617           }
3618 	}
3619 
3620         if (i >= (int)(sizeof(prohibited_env) / sizeof(prohibited_env[0])))
3621 	  cupsdSetEnv(value, valueptr);
3622       }
3623       else
3624         cupsdLogMessage(CUPSD_LOG_ERROR,
3625 	                "Missing value for SetEnv directive on line %d of %s.",
3626 	                linenum, ConfigurationFile);
3627     }
3628     else if (!_cups_strcasecmp(line, "SystemGroup") && value)
3629     {
3630      /*
3631       * SystemGroup (admin) group(s)...
3632       */
3633 
3634       if (!parse_groups(value, linenum))
3635       {
3636         if (FatalErrors & CUPSD_FATAL_CONFIG)
3637           return (0);
3638       }
3639     }
3640     else if (!_cups_strcasecmp(line, "User") && value)
3641     {
3642      /*
3643       * User ID to run as...
3644       */
3645 
3646       if (isdigit(value[0] & 255))
3647       {
3648         int uid = atoi(value);
3649 
3650 	if (!uid)
3651 	{
3652 	  cupsdLogMessage(CUPSD_LOG_ERROR,
3653 	                  "Will not use User 0 as specified on line %d of %s "
3654 			  "for security reasons.  You must use a non-"
3655 			  "privileged account instead.",
3656 	                  linenum, CupsFilesFile);
3657           if (FatalErrors & CUPSD_FATAL_CONFIG)
3658             return (0);
3659         }
3660         else
3661 	  User = (uid_t)atoi(value);
3662       }
3663       else
3664       {
3665         struct passwd *p;	/* Password information */
3666 
3667         endpwent();
3668 	p = getpwnam(value);
3669 
3670 	if (p)
3671 	{
3672 	  if (!p->pw_uid)
3673 	  {
3674 	    cupsdLogMessage(CUPSD_LOG_ERROR,
3675 	                    "Will not use User %s (UID=0) as specified on line "
3676 			    "%d of %s for security reasons.  You must use a "
3677 			    "non-privileged account instead.",
3678 	                    value, linenum, CupsFilesFile);
3679 	    if (FatalErrors & CUPSD_FATAL_CONFIG)
3680 	      return (0);
3681 	  }
3682 	  else
3683 	    User = p->pw_uid;
3684 	}
3685 	else
3686 	{
3687 	  cupsdLogMessage(CUPSD_LOG_ERROR,
3688 	                  "Unknown User \"%s\" on line %d of %s.",
3689 	                  value, linenum, CupsFilesFile);
3690           if (FatalErrors & CUPSD_FATAL_CONFIG)
3691             return (0);
3692         }
3693       }
3694     }
3695     else if (!_cups_strcasecmp(line, "ServerCertificate") ||
3696              !_cups_strcasecmp(line, "ServerKey"))
3697     {
3698       cupsdLogMessage(CUPSD_LOG_INFO,
3699 		      "The \"%s\" directive on line %d of %s is no longer "
3700 		      "supported; this will become an error in a future "
3701 		      "release.",
3702 		      line, linenum, CupsFilesFile);
3703     }
3704     else if (!parse_variable(CupsFilesFile, linenum, line, value,
3705 			     sizeof(cupsfiles_vars) / sizeof(cupsfiles_vars[0]),
3706 			     cupsfiles_vars) &&
3707 	     (FatalErrors & CUPSD_FATAL_CONFIG))
3708       return (0);
3709   }
3710 
3711   return (1);
3712 }
3713 
3714 
3715 /*
3716  * 'read_location()' - Read a <Location path> definition.
3717  */
3718 
3719 static int				/* O - New line number or 0 on error */
read_location(cups_file_t * fp,char * location,int linenum)3720 read_location(cups_file_t *fp,		/* I - Configuration file */
3721               char        *location,	/* I - Location name/path */
3722 	      int         linenum)	/* I - Current line number */
3723 {
3724   cupsd_location_t	*loc,		/* New location */
3725 			*parent;	/* Parent location */
3726   char			line[HTTP_MAX_BUFFER],
3727 					/* Line buffer */
3728 			*value,		/* Value for directive */
3729 			*valptr;	/* Pointer into value */
3730 
3731 
3732   if ((parent = cupsdFindLocation(location)) != NULL)
3733     cupsdLogMessage(CUPSD_LOG_WARN, "Duplicate <Location %s> on line %d of %s.",
3734                     location, linenum, ConfigurationFile);
3735   else if ((parent = cupsdNewLocation(location)) == NULL)
3736     return (0);
3737   else
3738   {
3739     cupsdAddLocation(parent);
3740 
3741     parent->limit = CUPSD_AUTH_LIMIT_ALL;
3742   }
3743 
3744   loc = parent;
3745 
3746   while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
3747   {
3748    /*
3749     * Decode the directive...
3750     */
3751 
3752     if (!_cups_strcasecmp(line, "</Location>"))
3753       return (linenum);
3754     else if (!_cups_strcasecmp(line, "<Limit") ||
3755              !_cups_strcasecmp(line, "<LimitExcept"))
3756     {
3757       if (!value)
3758       {
3759         cupsdLogMessage(CUPSD_LOG_ERROR, "Syntax error on line %d of %s.", linenum, ConfigurationFile);
3760         if (FatalErrors & CUPSD_FATAL_CONFIG)
3761 	  return (0);
3762         else
3763 	  continue;
3764       }
3765 
3766       if ((loc = cupsdCopyLocation(parent)) == NULL)
3767         return (0);
3768 
3769       cupsdAddLocation(loc);
3770 
3771       loc->limit = 0;
3772       while (*value)
3773       {
3774         for (valptr = value; !isspace(*valptr & 255) && *valptr; valptr ++);
3775 
3776 	if (*valptr)
3777 	  *valptr++ = '\0';
3778 
3779         if (!strcmp(value, "ALL"))
3780 	  loc->limit = CUPSD_AUTH_LIMIT_ALL;
3781 	else if (!strcmp(value, "GET"))
3782 	  loc->limit |= CUPSD_AUTH_LIMIT_GET;
3783 	else if (!strcmp(value, "HEAD"))
3784 	  loc->limit |= CUPSD_AUTH_LIMIT_HEAD;
3785 	else if (!strcmp(value, "OPTIONS"))
3786 	  loc->limit |= CUPSD_AUTH_LIMIT_OPTIONS;
3787 	else if (!strcmp(value, "POST"))
3788 	  loc->limit |= CUPSD_AUTH_LIMIT_POST;
3789 	else if (!strcmp(value, "PUT"))
3790 	  loc->limit |= CUPSD_AUTH_LIMIT_PUT;
3791 	else if (!strcmp(value, "TRACE"))
3792 	  loc->limit |= CUPSD_AUTH_LIMIT_TRACE;
3793 	else
3794 	  cupsdLogMessage(CUPSD_LOG_WARN, "Unknown request type %s on line %d of %s.",
3795 	                  value, linenum, ConfigurationFile);
3796 
3797         for (value = valptr; isspace(*value & 255); value ++);
3798       }
3799 
3800       if (!_cups_strcasecmp(line, "<LimitExcept"))
3801         loc->limit = CUPSD_AUTH_LIMIT_ALL ^ loc->limit;
3802 
3803       parent->limit &= ~loc->limit;
3804     }
3805     else if (!_cups_strcasecmp(line, "</Limit>") ||
3806              !_cups_strcasecmp(line, "</LimitExcept>"))
3807       loc = parent;
3808     else if (!value)
3809     {
3810       cupsdLogMessage(CUPSD_LOG_ERROR, "Missing value on line %d of %s.", linenum, ConfigurationFile);
3811       if (FatalErrors & CUPSD_FATAL_CONFIG)
3812 	return (0);
3813     }
3814     else if (!parse_aaa(loc, line, value, linenum))
3815     {
3816       cupsdLogMessage(CUPSD_LOG_ERROR,
3817                       "Unknown Location directive %s on line %d of %s.",
3818 	              line, linenum, ConfigurationFile);
3819       if (FatalErrors & CUPSD_FATAL_CONFIG)
3820 	return (0);
3821     }
3822   }
3823 
3824   cupsdLogMessage(CUPSD_LOG_ERROR,
3825                   "Unexpected end-of-file at line %d while reading location.",
3826                   linenum);
3827 
3828   return ((FatalErrors & CUPSD_FATAL_CONFIG) ? 0 : linenum);
3829 }
3830 
3831 
3832 /*
3833  * 'read_policy()' - Read a <Policy name> definition.
3834  */
3835 
3836 static int				/* O - New line number or 0 on error */
read_policy(cups_file_t * fp,char * policy,int linenum)3837 read_policy(cups_file_t *fp,		/* I - Configuration file */
3838             char        *policy,	/* I - Location name/path */
3839 	    int         linenum)	/* I - Current line number */
3840 {
3841   int			i;		/* Looping var */
3842   cupsd_policy_t	*pol;		/* Policy */
3843   cupsd_location_t	*op;		/* Policy operation */
3844   int			num_ops;	/* Number of IPP operations */
3845   ipp_op_t		ops[100];	/* Operations */
3846   char			line[HTTP_MAX_BUFFER],
3847 					/* Line buffer */
3848 			*value,		/* Value for directive */
3849 			*valptr;	/* Pointer into value */
3850 
3851 
3852  /*
3853   * Create the policy...
3854   */
3855 
3856   if ((pol = cupsdFindPolicy(policy)) != NULL)
3857     cupsdLogMessage(CUPSD_LOG_WARN, "Duplicate <Policy %s> on line %d of %s.",
3858                     policy, linenum, ConfigurationFile);
3859   else if ((pol = cupsdAddPolicy(policy)) == NULL)
3860     return (0);
3861 
3862  /*
3863   * Read from the file...
3864   */
3865 
3866   op      = NULL;
3867   num_ops = 0;
3868 
3869   while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
3870   {
3871    /*
3872     * Decode the directive...
3873     */
3874 
3875     if (!_cups_strcasecmp(line, "</Policy>"))
3876     {
3877       if (op)
3878         cupsdLogMessage(CUPSD_LOG_WARN,
3879 	                "Missing </Limit> before </Policy> on line %d of %s.",
3880 	                linenum, ConfigurationFile);
3881 
3882       set_policy_defaults(pol);
3883 
3884       return (linenum);
3885     }
3886     else if (!_cups_strcasecmp(line, "<Limit") && !op)
3887     {
3888       if (!value)
3889       {
3890         cupsdLogMessage(CUPSD_LOG_ERROR, "Syntax error on line %d of %s.", linenum, ConfigurationFile);
3891         if (FatalErrors & CUPSD_FATAL_CONFIG)
3892 	  return (0);
3893         else
3894 	  continue;
3895       }
3896 
3897      /*
3898       * Scan for IPP operation names...
3899       */
3900 
3901       num_ops = 0;
3902 
3903       while (*value)
3904       {
3905         for (valptr = value; !isspace(*valptr & 255) && *valptr; valptr ++);
3906 
3907 	if (*valptr)
3908 	  *valptr++ = '\0';
3909 
3910         if (num_ops < (int)(sizeof(ops) / sizeof(ops[0])))
3911 	{
3912 	  if (!_cups_strcasecmp(value, "All"))
3913 	    ops[num_ops ++] = IPP_ANY_OPERATION;
3914 	  else if ((ops[num_ops] = ippOpValue(value)) == IPP_BAD_OPERATION)
3915 	    cupsdLogMessage(CUPSD_LOG_ERROR, "Bad IPP operation name \"%s\" on line %d of %s.", value, linenum, ConfigurationFile);
3916           else
3917 	    num_ops ++;
3918 	}
3919 	else
3920 	  cupsdLogMessage(CUPSD_LOG_ERROR,
3921 	                  "Too many operations listed on line %d of %s.",
3922 	                  linenum, ConfigurationFile);
3923 
3924         for (value = valptr; isspace(*value & 255); value ++);
3925       }
3926 
3927      /*
3928       * If none are specified, apply the policy to all operations...
3929       */
3930 
3931       if (num_ops == 0)
3932       {
3933         ops[0]  = IPP_ANY_OPERATION;
3934 	num_ops = 1;
3935       }
3936 
3937      /*
3938       * Add a new policy for the first operation...
3939       */
3940 
3941       op = cupsdAddPolicyOp(pol, NULL, ops[0]);
3942     }
3943     else if (!_cups_strcasecmp(line, "</Limit>") && op)
3944     {
3945      /*
3946       * Finish the current operation limit...
3947       */
3948 
3949       if (num_ops > 1)
3950       {
3951        /*
3952         * Copy the policy to the other operations...
3953 	*/
3954 
3955         for (i = 1; i < num_ops; i ++)
3956 	  cupsdAddPolicyOp(pol, op, ops[i]);
3957       }
3958 
3959       op = NULL;
3960     }
3961     else if (!value)
3962     {
3963       cupsdLogMessage(CUPSD_LOG_ERROR, "Missing value on line %d of %s.", linenum, ConfigurationFile);
3964       if (FatalErrors & CUPSD_FATAL_CONFIG)
3965 	return (0);
3966     }
3967     else if (!_cups_strcasecmp(line, "JobPrivateAccess") ||
3968 	     !_cups_strcasecmp(line, "JobPrivateValues") ||
3969 	     !_cups_strcasecmp(line, "SubscriptionPrivateAccess") ||
3970 	     !_cups_strcasecmp(line, "SubscriptionPrivateValues"))
3971     {
3972       if (op)
3973       {
3974         cupsdLogMessage(CUPSD_LOG_ERROR,
3975 	                "%s directive must appear outside <Limit>...</Limit> "
3976 			"on line %d of %s.", line, linenum, ConfigurationFile);
3977 	if (FatalErrors & CUPSD_FATAL_CONFIG)
3978 	  return (0);
3979       }
3980       else
3981       {
3982        /*
3983         * Pull out whitespace-delimited values...
3984 	*/
3985 
3986 	while (*value)
3987 	{
3988 	 /*
3989 	  * Find the end of the current value...
3990 	  */
3991 
3992 	  for (valptr = value; !isspace(*valptr & 255) && *valptr; valptr ++);
3993 
3994 	  if (*valptr)
3995 	    *valptr++ = '\0';
3996 
3997          /*
3998 	  * Save it appropriately...
3999 	  */
4000 
4001 	  if (!_cups_strcasecmp(line, "JobPrivateAccess"))
4002 	  {
4003 	   /*
4004 	    * JobPrivateAccess {all|default|user/group list|@@ACL}
4005 	    */
4006 
4007             if (!_cups_strcasecmp(value, "default"))
4008 	    {
4009 	      cupsdAddString(&(pol->job_access), "@OWNER");
4010 	      cupsdAddString(&(pol->job_access), "@SYSTEM");
4011 	    }
4012 	    else
4013 	      cupsdAddString(&(pol->job_access), value);
4014 	  }
4015 	  else if (!_cups_strcasecmp(line, "JobPrivateValues"))
4016 	  {
4017 	   /*
4018 	    * JobPrivateValues {all|none|default|attribute list}
4019 	    */
4020 
4021 	    if (!_cups_strcasecmp(value, "default"))
4022 	    {
4023 	      cupsdAddString(&(pol->job_attrs), "job-name");
4024 	      cupsdAddString(&(pol->job_attrs), "job-originating-host-name");
4025 	      cupsdAddString(&(pol->job_attrs), "job-originating-user-name");
4026 	      cupsdAddString(&(pol->job_attrs), "phone");
4027 	    }
4028 	    else
4029 	      cupsdAddString(&(pol->job_attrs), value);
4030 	  }
4031 	  else if (!_cups_strcasecmp(line, "SubscriptionPrivateAccess"))
4032 	  {
4033 	   /*
4034 	    * SubscriptionPrivateAccess {all|default|user/group list|@@ACL}
4035 	    */
4036 
4037             if (!_cups_strcasecmp(value, "default"))
4038 	    {
4039 	      cupsdAddString(&(pol->sub_access), "@OWNER");
4040 	      cupsdAddString(&(pol->sub_access), "@SYSTEM");
4041 	    }
4042 	    else
4043 	      cupsdAddString(&(pol->sub_access), value);
4044 	  }
4045 	  else /* if (!_cups_strcasecmp(line, "SubscriptionPrivateValues")) */
4046 	  {
4047 	   /*
4048 	    * SubscriptionPrivateValues {all|none|default|attribute list}
4049 	    */
4050 
4051 	    if (!_cups_strcasecmp(value, "default"))
4052 	    {
4053 	      cupsdAddString(&(pol->sub_attrs), "notify-events");
4054 	      cupsdAddString(&(pol->sub_attrs), "notify-pull-method");
4055 	      cupsdAddString(&(pol->sub_attrs), "notify-recipient-uri");
4056 	      cupsdAddString(&(pol->sub_attrs), "notify-subscriber-user-name");
4057 	      cupsdAddString(&(pol->sub_attrs), "notify-user-data");
4058 	    }
4059 	    else
4060 	      cupsdAddString(&(pol->sub_attrs), value);
4061 	  }
4062 
4063 	 /*
4064 	  * Find the next string on the line...
4065 	  */
4066 
4067 	  for (value = valptr; isspace(*value & 255); value ++);
4068 	}
4069       }
4070     }
4071     else if (!op)
4072     {
4073       cupsdLogMessage(CUPSD_LOG_ERROR,
4074                       "Missing <Limit ops> directive before %s on line %d of %s.",
4075                       line, linenum, ConfigurationFile);
4076       if (FatalErrors & CUPSD_FATAL_CONFIG)
4077 	return (0);
4078     }
4079     else if (!parse_aaa(op, line, value, linenum))
4080     {
4081       cupsdLogMessage(CUPSD_LOG_ERROR,
4082 		      "Unknown Policy Limit directive %s on line %d of %s.",
4083 		      line, linenum, ConfigurationFile);
4084 
4085       if (FatalErrors & CUPSD_FATAL_CONFIG)
4086 	return (0);
4087     }
4088   }
4089 
4090   cupsdLogMessage(CUPSD_LOG_ERROR,
4091                   "Unexpected end-of-file at line %d while reading policy "
4092                   "\"%s\".", linenum, policy);
4093 
4094   return ((FatalErrors & CUPSD_FATAL_CONFIG) ? 0 : linenum);
4095 }
4096 
4097 
4098 /*
4099  * 'set_policy_defaults()' - Set default policy values as needed.
4100  */
4101 
4102 static void
set_policy_defaults(cupsd_policy_t * pol)4103 set_policy_defaults(cupsd_policy_t *pol)/* I - Policy */
4104 {
4105   cupsd_location_t	*op;		/* Policy operation */
4106 
4107 
4108  /*
4109   * Verify that we have an explicit policy for Validate-Job, Cancel-Jobs,
4110   * Cancel-My-Jobs, Close-Job, and CUPS-Get-Document, which ensures that
4111   * upgrades do not introduce new security issues...
4112   *
4113   * CUPS STR #4659: Allow a lone <Limit All> policy.
4114   */
4115 
4116   if (cupsArrayCount(pol->ops) > 1)
4117   {
4118     if ((op = cupsdFindPolicyOp(pol, IPP_VALIDATE_JOB)) == NULL ||
4119 	op->op == IPP_ANY_OPERATION)
4120     {
4121       if ((op = cupsdFindPolicyOp(pol, IPP_PRINT_JOB)) != NULL &&
4122 	  op->op != IPP_ANY_OPERATION)
4123       {
4124        /*
4125 	* Add a new limit for Validate-Job using the Print-Job limit as a
4126 	* template...
4127 	*/
4128 
4129 	cupsdLogMessage(CUPSD_LOG_WARN, "No limit for Validate-Job defined in policy %s - using Print-Job's policy.", pol->name);
4130 
4131 	cupsdAddPolicyOp(pol, op, IPP_VALIDATE_JOB);
4132       }
4133       else
4134 	cupsdLogMessage(CUPSD_LOG_WARN, "No limit for Validate-Job defined in policy %s and no suitable template found.", pol->name);
4135     }
4136 
4137     if ((op = cupsdFindPolicyOp(pol, IPP_CANCEL_JOBS)) == NULL ||
4138 	op->op == IPP_ANY_OPERATION)
4139     {
4140       if ((op = cupsdFindPolicyOp(pol, IPP_PAUSE_PRINTER)) != NULL &&
4141 	  op->op != IPP_ANY_OPERATION)
4142       {
4143        /*
4144 	* Add a new limit for Cancel-Jobs using the Pause-Printer limit as a
4145 	* template...
4146 	*/
4147 
4148 	cupsdLogMessage(CUPSD_LOG_WARN, "No limit for Cancel-Jobs defined in policy %s - using Pause-Printer's policy.", pol->name);
4149 
4150 	cupsdAddPolicyOp(pol, op, IPP_CANCEL_JOBS);
4151       }
4152       else
4153 	cupsdLogMessage(CUPSD_LOG_WARN, "No limit for Cancel-Jobs defined in policy %s and no suitable template found.", pol->name);
4154     }
4155 
4156     if ((op = cupsdFindPolicyOp(pol, IPP_CANCEL_MY_JOBS)) == NULL ||
4157 	op->op == IPP_ANY_OPERATION)
4158     {
4159       if ((op = cupsdFindPolicyOp(pol, IPP_SEND_DOCUMENT)) != NULL &&
4160 	  op->op != IPP_ANY_OPERATION)
4161       {
4162        /*
4163 	* Add a new limit for Cancel-My-Jobs using the Send-Document limit as
4164 	* a template...
4165 	*/
4166 
4167 	cupsdLogMessage(CUPSD_LOG_WARN, "No limit for Cancel-My-Jobs defined in policy %s - using Send-Document's policy.", pol->name);
4168 
4169 	cupsdAddPolicyOp(pol, op, IPP_CANCEL_MY_JOBS);
4170       }
4171       else
4172 	cupsdLogMessage(CUPSD_LOG_WARN, "No limit for Cancel-My-Jobs defined in policy %s and no suitable template found.", pol->name);
4173     }
4174 
4175     if ((op = cupsdFindPolicyOp(pol, IPP_CLOSE_JOB)) == NULL ||
4176 	op->op == IPP_ANY_OPERATION)
4177     {
4178       if ((op = cupsdFindPolicyOp(pol, IPP_SEND_DOCUMENT)) != NULL &&
4179 	  op->op != IPP_ANY_OPERATION)
4180       {
4181        /*
4182 	* Add a new limit for Close-Job using the Send-Document limit as a
4183 	* template...
4184 	*/
4185 
4186 	cupsdLogMessage(CUPSD_LOG_WARN, "No limit for Close-Job defined in policy %s - using Send-Document's policy.", pol->name);
4187 
4188 	cupsdAddPolicyOp(pol, op, IPP_CLOSE_JOB);
4189       }
4190       else
4191 	cupsdLogMessage(CUPSD_LOG_WARN, "No limit for Close-Job defined in policy %s and no suitable template found.", pol->name);
4192     }
4193 
4194     if ((op = cupsdFindPolicyOp(pol, CUPS_GET_DOCUMENT)) == NULL ||
4195 	op->op == IPP_ANY_OPERATION)
4196     {
4197       if ((op = cupsdFindPolicyOp(pol, IPP_SEND_DOCUMENT)) != NULL &&
4198 	  op->op != IPP_ANY_OPERATION)
4199       {
4200        /*
4201 	* Add a new limit for CUPS-Get-Document using the Send-Document
4202 	* limit as a template...
4203 	*/
4204 
4205 	cupsdLogMessage(CUPSD_LOG_WARN, "No limit for CUPS-Get-Document defined in policy %s - using Send-Document's policy.", pol->name);
4206 
4207 	cupsdAddPolicyOp(pol, op, CUPS_GET_DOCUMENT);
4208       }
4209       else
4210 	cupsdLogMessage(CUPSD_LOG_WARN, "No limit for CUPS-Get-Document defined in policy %s and no suitable template found.", pol->name);
4211     }
4212   }
4213 
4214  /*
4215   * Verify we have JobPrivateAccess, JobPrivateValues,
4216   * SubscriptionPrivateAccess, and SubscriptionPrivateValues in the policy.
4217   */
4218 
4219   if (!pol->job_access)
4220   {
4221     cupsdLogMessage(CUPSD_LOG_WARN, "No JobPrivateAccess defined in policy %s - using defaults.", pol->name);
4222     cupsdAddString(&(pol->job_access), "@OWNER");
4223     cupsdAddString(&(pol->job_access), "@SYSTEM");
4224   }
4225 
4226   if (!pol->job_attrs)
4227   {
4228     cupsdLogMessage(CUPSD_LOG_WARN, "No JobPrivateValues defined in policy %s - using defaults.", pol->name);
4229     cupsdAddString(&(pol->job_attrs), "job-name");
4230     cupsdAddString(&(pol->job_attrs), "job-originating-host-name");
4231     cupsdAddString(&(pol->job_attrs), "job-originating-user-name");
4232     cupsdAddString(&(pol->job_attrs), "phone");
4233   }
4234 
4235   if (!pol->sub_access)
4236   {
4237     cupsdLogMessage(CUPSD_LOG_WARN, "No SubscriptionPrivateAccess defined in policy %s - using defaults.", pol->name);
4238     cupsdAddString(&(pol->sub_access), "@OWNER");
4239     cupsdAddString(&(pol->sub_access), "@SYSTEM");
4240   }
4241 
4242   if (!pol->sub_attrs)
4243   {
4244     cupsdLogMessage(CUPSD_LOG_WARN, "No SubscriptionPrivateValues defined in policy %s - using defaults.", pol->name);
4245     cupsdAddString(&(pol->sub_attrs), "notify-events");
4246     cupsdAddString(&(pol->sub_attrs), "notify-pull-method");
4247     cupsdAddString(&(pol->sub_attrs), "notify-recipient-uri");
4248     cupsdAddString(&(pol->sub_attrs), "notify-subscriber-user-name");
4249     cupsdAddString(&(pol->sub_attrs), "notify-user-data");
4250   }
4251 }
4252