xref: /freebsd/usr.sbin/lpr/common_source/ctlinfo.c (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * ------+---------+---------+---------+---------+---------+---------+---------*
5  * Copyright (c) 2001,2011  - Garance Alistair Drosehn <gad@FreeBSD.org>.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *   1. Redistributions of source code must retain the above copyright
12  *      notice, this list of conditions and the following disclaimer.
13  *   2. Redistributions in binary form must reproduce the above copyright
14  *      notice, this list of conditions and the following disclaimer in the
15  *      documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * The views and conclusions contained in the software and documentation
30  * are those of the authors and should not be interpreted as representing
31  * official policies, either expressed or implied, of the FreeBSD Project.
32  *
33  * ------+---------+---------+---------+---------+---------+---------+---------*
34  */
35 
36 #include "lp.cdefs.h"		/* A cross-platform version of <sys/cdefs.h> */
37 /*
38  * ctlinfo - This collection of routines will know everything there is to
39  * know about the information inside a control file ('cf*') which is used
40  * to describe a print job in lpr & friends.  The eventual goal is that it
41  * will be the ONLY source file to know what's inside these control-files.
42  */
43 
44 /*
45  * Some define's useful for debugging.
46  * TRIGGERTEST_FNAME and DEBUGREADCF_FNAME, allow us to do testing on
47  * a per-spool-directory basis.
48  */
49 /* #define TRIGGERTEST_FNAME "LpdTestRenameTF" */
50 /* #define DEBUGREADCF_FNAME "LpdDebugReadCF" */
51 /* #define LEAVE_TMPCF_FILES 1 */
52 
53 #include <sys/types.h>
54 #include <sys/stat.h>
55 #include <ctype.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <limits.h>
59 #include <netdb.h>
60 #include <pwd.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <syslog.h>
65 #include <unistd.h>
66 #include "ctlinfo.h"
67 
68 struct cjprivate {
69 	struct cjobinfo pub;
70 	char	*cji_buff;		/* buffer for getline */
71 	char	*cji_eobuff;		/* last byte IN the buffer */
72 	FILE	*cji_fstream;
73 	int	 cji_buffsize;		/* # bytes in the buffer */
74 	int	 cji_dumpit;
75 };
76 
77 /*
78  * All the following take a parameter of 'int', but expect values in the
79  * range of unsigned char.  Define wrappers which take values of type 'char',
80  * whether signed or unsigned, and ensure they end up in the right range.
81  */
82 #define	isdigitch(Anychar) isdigit((u_char)(Anychar))
83 #define	islowerch(Anychar) islower((u_char)(Anychar))
84 #define	isupperch(Anychar) isupper((u_char)(Anychar))
85 #define	tolowerch(Anychar) tolower((u_char)(Anychar))
86 
87 #define	OTHER_USERID_CHARS  "-_"	/* special chars valid in a userid */
88 
89 #define roundup(x, y)   ((((x)+((y)-1))/(y))*(y))
90 
91 /*
92  * This has to be large enough to fit the maximum length of a single line
93  * in a control-file, including the leading 'command id', a trailing '\n'
94  * and ending '\0'.  The max size of an 'U'nlink line, for instance, is
95  * 1 ('U') + PATH_MAX (filename) + 2 ('\n\0').  The maximum 'H'ost line is
96  * 1 ('H') + NI_MAXHOST (remote hostname) + 2 ('\n\0').  Other lines can be
97  * even longer than those.  So, pick some nice, large, arbitrary value.
98  */
99 #define CTI_LINEMAX  PATH_MAX+NI_MAXHOST+5
100 
101 extern const char	*from_host;	/* client's machine name */
102 extern const char	*from_ip;	/* client machine's IP address */
103 
104 __BEGIN_DECLS
105 void		 ctl_dumpcji(FILE *_dbg_stream, const char *_heading,
106 		    struct cjobinfo *_cjinf);
107 static char	*ctl_getline(struct cjobinfo *_cjinf);
108 static void	 ctl_rewindcf(struct cjobinfo *_cjinf);
109 char		*ctl_rmjob(const char *_ptrname, const char *_cfname);
110 __END_DECLS
111 
112 /*
113  * Here are some things which might be needed when compiling this under
114  * platforms other than FreeBSD.
115  */
116 #ifndef __FreeBSD__
117 #   ifndef NAME_MAX
118 #	define NAME_MAX	255
119 #   endif
120 #   ifndef NI_MAXHOST
121 #	define NI_MAXHOST	1025
122 #   endif
123 #   ifndef PATH_MAX
124 #	define PATH_MAX	1024
125 #   endif
126 __BEGIN_DECLS
127 char		*strdup(const char *_src);
128 size_t		 strlcpy(char *_dst, const char *_src, size_t _siz);
129 __END_DECLS
130 #endif
131 
132 /*
133  *	Control-files (cf*) have the following format.
134  *
135  *	Each control-file describes a single job.  It will list one or more
136  *	"datafiles" (df*) which should be copied to some printer.  Usually
137  *	there is only one datafile per job.  For the curious, RFC 1179 is an
138  *	informal and out-of-date description of lpr/lpd circa 1990.
139  *
140  *	Each line in the file gives an attribute of the job as a whole, or one
141  *	of the datafiles in the job, or a "command" indicating something to do
142  *	with one of the datafiles.  Each line starts with an 'id' that indicates
143  *	what that line is there for.  The 'id' is historically a single byte,
144  *	but may be multiple bytes (obviously it would be best if multi-byte ids
145  *	started with some letter not already used as a single-byte id!).
146  *	After the 'id', the remainder of the line will be the value of the
147  *	indicated attribute, or a name of the datafile to be operated on.
148  *
149  *	In the following lists of ids, the ids with a '!' in front of them are
150  *	NOT explicitly supported by this version of lpd, or at least "not yet
151  *	supported".  They are only listed for reference purposes, so people
152  *	won't be tempted to reuse the same id for a different purpose.
153  *
154  *	The following are attributes of the job which should not appear more
155  *	than once in a control file.  Only the 'H' and 'P' lines are required
156  *	by the RFC, but some implementations of lpr won't even get that right.
157  *
158  *	! A   - [used by lprNG]
159  *	  B   - As far as I know, this is never used as a single-byte id.
160  *		Therefore, I intend to use it for multi-byte id codes.
161  *	  C   - "class name" to display on banner page (this is sometimes
162  *		used to hold options for print filters)
163  *	! D   - [in lprNG, "timestamp" of when the job was submitted]
164  *	! E   - "environment variables" to set [some versions of linux]
165  *	  H   - "host name" of machine where the original 'lpr' was done
166  *	  I   - "indent", the amount to indent output
167  *	  J   - "job name" to display on banner page
168  *	  L   - "literal" user's name as it should be displayed on the
169  *		banner page (it is the existence of an 'L' line which
170  *		indicates that a job should have a banner page).
171  *	  M   - "mail", userid to mail to when done printing (with email
172  *		going to 'M'@'H', so to speak).
173  *	  P   - "person", the user's login name (e.g. for accounting)
174  *	! Q   - [used by lprNG for queue-name]
175  *	  R   - "resolution" in dpi, for some laser printer queues
176  *	  T   - "title" for files sent thru 'pr'
177  *	  W   - "width" to use for printing plain-text files
178  *	  Z   - In BSD, "locale" to use for datafiles sent thru 'pr'.
179  *		(this BSD usage should move to a different id...)
180  *		[in lprNG - this line holds the "Z options"]
181  *	  1   - "R font file" for files sent thru troff
182  *	  2   - "I font file" for files sent thru troff
183  *	  3   - "B font file" for files sent thru troff
184  *	  4   - "S font file" for files sent thru troff
185  *
186  *	The following are attributes attached to a datafile, and thus may
187  *	appear multiple times in a control file (once per datafile):
188  *
189  *	  N   - "name" of file (for display purposes, used by 'lpq')
190  *	  S   - "stat() info" used for symbolic link ('lpr -s')
191  *		security checks.
192  *
193  *	The following indicate actions to take on a given datafile.  The same
194  *	datafile may appear on more than one "print this file" command in the
195  *	control file.  Note that ALL ids with lowercase letters are expected
196  *	to be actions to "print this file":
197  *
198  *	  c   - "file name", cifplot file to print.  This action appears
199  *		when the user has requested 'lpr -c'.
200  *	  d   - "file name", dvi file to print, user requested 'lpr -d'
201  *	  f   - "file name", a plain-text file to print = "standard"
202  *	  g   - "file name", plot(1G) file to print, ie 'lpr -g'
203  *	  l   - "file name", text file with control chars which should
204  *		be printed literally, ie 'lpr -l'  (note: some printers
205  *		take this id as a request to print a postscript file,
206  *		and because of *that* some OS's use 'l' to indicate
207  *		that a datafile is a postscript file)
208  *	  n   - "file name", ditroff(1) file to print, ie 'lpr -n'
209  *	  o   - "file name", a postscript file to print.  This id is
210  *		described in the original RFC, but not much has been
211  *		done with it.  This 'lpr' does not generate control
212  *		lines with 'o'-actions, but lpd's printjob processing
213  *		will treat it the same as 'l'.
214  *	  p   - "file name", text file to print with pr(1), ie 'lpr -p'
215  *	  t   - "file name", troff(1) file to print, ie 'lpr -t'
216  *	  v   - "file name", plain raster file to print
217  *
218  *	  U   - "file name" of datafile to unlink (ie, remove file
219  *		from spool directory.  To be done in a 'Pass 2',
220  *		AFTER having processed all datafiles in the job).
221  *
222  */
223 
224 void
225 ctl_freeinf(struct cjobinfo *cjinf)
226 {
227 #define FREESTR(xStr) \
228 	if (xStr != NULL) { \
229 		free(xStr); \
230 		xStr = NULL;\
231 	}
232 
233 	struct cjprivate *cpriv;
234 
235 	if (cjinf == NULL)
236 		return;
237 	cpriv = cjinf->cji_priv;
238 	if ((cpriv == NULL) || (cpriv != cpriv->pub.cji_priv)) {
239 		syslog(LOG_ERR, "in ctl_freeinf(%p): invalid cjinf (cpriv %p)",
240 		    (void *)cjinf, (void *)cpriv);
241 		return;
242 	}
243 
244 	FREESTR(cpriv->pub.cji_accthost);
245 	FREESTR(cpriv->pub.cji_acctuser);
246 	FREESTR(cpriv->pub.cji_class);
247 	FREESTR(cpriv->pub.cji_curqueue);
248 	/* [cpriv->pub.cji_fname is part of cpriv-malloced area] */
249 	FREESTR(cpriv->pub.cji_jobname);
250 	FREESTR(cpriv->pub.cji_mailto);
251 	FREESTR(cpriv->pub.cji_headruser);
252 
253 	if (cpriv->cji_fstream != NULL) {
254 		fclose(cpriv->cji_fstream);
255 		cpriv->cji_fstream = NULL;
256 	}
257 
258 	cjinf->cji_priv = NULL;
259 	free(cpriv);
260 #undef FREESTR
261 }
262 
263 #ifdef DEBUGREADCF_FNAME
264 static FILE *ctl_dbgfile = NULL;
265 static struct stat ctl_dbgstat;
266 #endif
267 static int ctl_dbgline = 0;
268 
269 struct cjobinfo *
270 ctl_readcf(const char *ptrname, const char *cfname)
271 {
272 	int id;
273 	char *lbuff;
274 	void *cstart;
275 	FILE *cfile;
276 	struct cjprivate *cpriv;
277 	struct cjobinfo *cjinf;
278 	size_t msize, sroom, sroom2;
279 
280 	cfile = fopen(cfname, "r");
281 	if (cfile == NULL) {
282 		syslog(LOG_ERR, "%s: ctl_readcf error fopen(%s): %s",
283 		    ptrname, cfname, strerror(errno));
284 		return NULL;
285 	}
286 
287 	sroom = roundup(sizeof(struct cjprivate), 8);
288 	sroom2 = sroom + strlen(cfname) + 1;
289 	sroom2 = roundup(sroom2, 8);
290 	msize = sroom2 + CTI_LINEMAX;
291 	msize = roundup(msize, 8);
292 	cstart = malloc(msize);
293 	if (cstart == NULL) {
294 		fclose(cfile);
295 		return NULL;
296 	}
297 	memset(cstart, 0, msize);
298 	cpriv = (struct cjprivate *)cstart;
299 	cpriv->pub.cji_priv = cpriv;
300 
301 	cpriv->pub.cji_fname = (char *)cstart + sroom;
302 	strcpy(cpriv->pub.cji_fname, cfname);
303 	cpriv->cji_buff = (char *)cstart + sroom2;
304 	cpriv->cji_buffsize = (int)(msize - sroom2);
305 	cpriv->cji_eobuff = (char *)cstart + msize - 1;
306 
307 	cpriv->cji_fstream = cfile;
308 	cpriv->pub.cji_curqueue = strdup(ptrname);
309 
310 	ctl_dbgline = 0;
311 #ifdef DEBUGREADCF_FNAME
312 	ctl_dbgfile = NULL;
313 	id = stat(DEBUGREADCF_FNAME, &ctl_dbgstat);
314 	if (id != -1) {
315 		/* the file exists in this spool directory, write some simple
316 		 * debugging info to it */
317 		ctl_dbgfile = fopen(DEBUGREADCF_FNAME, "a");
318 		if (ctl_dbgfile != NULL) {
319 			fprintf(ctl_dbgfile, "%s: s=%p r=%ld e=%p %p->%s\n",
320 			    ptrname, (void *)cpriv, (long)sroom,
321 			    cpriv->cji_eobuff, cpriv->pub.cji_fname,
322 			    cpriv->pub.cji_fname);
323 		}
324 	}
325 #endif
326 	/*
327 	 * Copy job-attribute values from control file to the struct of
328 	 * "public" information.  In some cases, it is invalid for the
329 	 * value to be a null-string, so that is ignored.
330 	 */
331 	cjinf = &(cpriv->pub);
332 	lbuff = ctl_getline(cjinf);
333 	while (lbuff != NULL) {
334 		id = *lbuff++;
335 		switch (id) {
336 		case 'C':
337 			cpriv->pub.cji_class = strdup(lbuff);
338 			break;
339 		case 'H':
340 			if (*lbuff == '\0')
341 				break;
342 			cpriv->pub.cji_accthost = strdup(lbuff);
343 			break;
344 		case 'J':
345 			cpriv->pub.cji_jobname = strdup(lbuff);
346 			break;
347 		case 'L':
348 			cpriv->pub.cji_headruser = strdup(lbuff);
349 			break;
350 		case 'M':
351 			/*
352 			 * No valid mail-to address would start with a minus.
353 			 * If this one does, it is probably some trickster who
354 			 * is trying to trigger options on sendmail.  Ignore.
355 			 */
356 			if (*lbuff == '-')
357 				break;
358 			if (*lbuff == '\0')
359 				break;
360 			cpriv->pub.cji_mailto = strdup(lbuff);
361 			break;
362 		case 'P':
363 			if (*lbuff == '\0')
364 				break;
365 			/* The userid must not start with a minus sign */
366 			if (*lbuff == '-')
367 				*lbuff = '_';
368 			cpriv->pub.cji_acctuser = strdup(lbuff);
369 			break;
370 		default:
371 			if (islower(id)) {
372 				cpriv->pub.cji_dfcount++;
373 			}
374 			break;
375 		}
376 		lbuff = ctl_getline(cjinf);
377 	}
378 
379 	/* the 'H'ost and 'P'erson fields are *always* supposed to be there */
380 	if (cpriv->pub.cji_accthost == NULL)
381 		cpriv->pub.cji_accthost = strdup(".na.");
382 	if (cpriv->pub.cji_acctuser == NULL)
383 		cpriv->pub.cji_acctuser = strdup(".na.");
384 
385 #ifdef DEBUGREADCF_FNAME
386 	if (ctl_dbgfile != NULL) {
387 		if (cpriv->cji_dumpit)
388 			ctl_dumpcji(ctl_dbgfile, "end readcf", &(cpriv->pub));
389 		fclose(ctl_dbgfile);
390 		ctl_dbgfile = NULL;
391 	}
392 #endif
393 	return &(cpriv->pub);
394 }
395 
396 /*
397  * This routine renames the temporary control file as received from some
398  * other (remote) host.  That file will almost always with `tfA*', because
399  * recvjob.c creates the file by changing `c' to `t' in the original name
400  * for the control file.  Now if you read the RFC, you would think that all
401  * control filenames start with `cfA*'.  However, it seems there are some
402  * implementations which send control filenames which start with `cf'
403  * followed by *any* letter, so this routine can not assume what the third
404  * letter will (or will not) be.  Sigh.
405  *
406  * So this will rewrite the temporary file to `rf*' (correcting any lines
407  * which need correcting), rename that `rf*' file to `cf*', and then remove
408  * the original `tf*' temporary file.
409  *
410  * The *main* purpose of this routine is to be paranoid about the contents
411  * of that control file.  It is partially meant to protect against people
412  * TRYING to cause trouble (perhaps after breaking into root of some host
413  * that this host will accept print jobs from).  The fact that we're willing
414  * to print jobs from some remote host does not mean that we should blindly
415  * do anything that host tells us to do.
416  *
417  * This is also meant to protect us from errors in other implementations of
418  * lpr, particularly since we may want to use some values from the control
419  * file as environment variables when it comes time to print, or as parameters
420  * to commands which will be exec'ed, or values in statistics records.
421  *
422  * This may also do some "conversions" between how different versions of
423  * lpr or lprNG define the contents of various lines in a control file.
424  *
425  * If there is an error, it returns a pointer to a descriptive error message.
426  * Error messages which are RETURNED (as opposed to syslog-ed) do not include
427  * the printer-queue name.  Let the caller add that if it is wanted.
428  */
429 char *
430 ctl_renametf(const char *ptrname, const char *tfname)
431 {
432 	int chk3rd, has_uc, newfd, nogood, res;
433 	FILE *newcf;
434 	struct cjobinfo *cjinf;
435 	char *lbuff, *slash, *cp;
436 	char tfname2[NAME_MAX+1], cfname2[NAME_MAX+1];
437 	char errm[CTI_LINEMAX];
438 
439 #ifdef TRIGGERTEST_FNAME
440 	struct stat tstat;
441 	res = stat(TRIGGERTEST_FNAME, &tstat);
442 	if (res == -1) {
443 		/*
444 		 * if the trigger file does NOT exist in this spool directory,
445 		 * then do the exact same steps that the pre-ctlinfo code had
446 		 * been doing.  Ie, very little.
447 		 */
448 		strlcpy(cfname2, tfname, sizeof(cfname2));
449 		cfname2[0] = 'c';
450 		res = link(tfname, cfname2);
451 		if (res < 0) {
452 			snprintf(errm, sizeof(errm),
453 			    "ctl_renametf error link(%s,%s): %s", tfname,
454 			    cfname2, strerror(errno));
455 			return strdup(errm);
456 		}
457 		unlink(tfname);
458 		return NULL;
459 	}
460 #endif
461 	cjinf = NULL;		/* in case of early jump to error_ret */
462 	newcf = NULL;		/* in case of early jump to error_ret */
463 	*errm = '\0';		/* in case of early jump to error_ret */
464 
465 	chk3rd = tfname[2];
466 	if ((tfname[0] != 't') || (tfname[1] != 'f') || (!isalpha(chk3rd))) {
467 		snprintf(errm, sizeof(errm),
468 		    "ctl_renametf invalid filename: %s", tfname);
469 		goto error_ret;
470 	}
471 
472 	cjinf = ctl_readcf(ptrname, tfname);
473 	if (cjinf == NULL) {
474 		snprintf(errm, sizeof(errm),
475 		    "ctl_renametf error cti_readcf(%s)", tfname);
476 		goto error_ret;
477 	}
478 
479 	/*
480 	 * This uses open+fdopen instead of fopen because that combination
481 	 * gives us greater control over file-creation issues.
482 	 */
483 	strlcpy(tfname2, tfname, sizeof(tfname2));
484 	tfname2[0] = 'r';		/* rf<letter><job><hostname> */
485 	newfd = open(tfname2, O_WRONLY|O_CREAT|O_TRUNC, 0660);
486 	if (newfd == -1) {
487 		snprintf(errm, sizeof(errm),
488 		    "ctl_renametf error open(%s): %s", tfname2,
489 		    strerror(errno));
490 		goto error_ret;
491 	}
492 	newcf = fdopen(newfd, "w");
493 	if (newcf == NULL) {
494 		close(newfd);
495 		snprintf(errm, sizeof(errm),
496 		    "ctl_renametf error fopen(%s): %s", tfname2,
497 		    strerror(errno));
498 		goto error_ret;
499 	}
500 
501 	/*
502 	 * Do extra sanity checks on some key job-attribute fields, and
503 	 * write them out first (thus making sure they are written in the
504 	 * order we generally expect them to be in).
505 	 */
506 	/*
507 	 * Some lpr implementations on PC's set a null-string for their
508 	 * hostname.  A MacOS 10 system which has not correctly setup
509 	 * /etc/hostconfig will claim a hostname of 'localhost'.  Anything
510 	 * with blanks in it would be an invalid value for hostname.  For
511 	 * any of these invalid hostname values, replace the given value
512 	 * with the name of the host that this job is coming from.
513 	 */
514 	nogood = 0;
515 	if (cjinf->cji_accthost == NULL)
516 		nogood = 1;
517 	else if (strcmp(cjinf->cji_accthost, ".na.") == 0)
518 		nogood = 1;
519 	else if (strcmp(cjinf->cji_accthost, "localhost") == 0)
520 		nogood = 1;
521 	else {
522 		for (cp = cjinf->cji_accthost; *cp != '\0'; cp++) {
523 			if (*cp <= ' ') {
524 				nogood = 1;
525 				break;
526 			}
527 		}
528 	}
529 	if (nogood)
530 		fprintf(newcf, "H%s\n", from_host);
531 	else
532 		fprintf(newcf, "H%s\n", cjinf->cji_accthost);
533 
534 	/*
535 	 * Now do some sanity checks on the 'P' (original userid) value.  Note
536 	 * that the 'P'erson line is the second line which is ALWAYS supposed
537 	 * to be present in a control file.
538 	 *
539 	 * There is no particularly good value to use for replacements, but
540 	 * at least make sure the value is something reasonable to use in
541 	 * environment variables and statistics records.  Again, some PC
542 	 * implementations send a null-string for a value.  Various Mac
543 	 * implementations will set whatever string the user has set for
544 	 * their 'Owner Name', which usually includes blanks, etc.
545 	 */
546 	nogood = 0;
547 	if (cjinf->cji_acctuser == NULL)
548 		nogood = 1;
549 	else if (strcmp(cjinf->cji_acctuser, ".na.") == 0)
550 		;			/* No further checks needed... */
551 	else {
552 		has_uc = 0;
553 		cp = cjinf->cji_acctuser;
554 		if (*cp == '-')
555 			*cp++ = '_';
556 		for (; *cp != '\0'; cp++) {
557 			if (islowerch(*cp) || isdigitch(*cp))
558 				continue;	/* Standard valid characters */
559 			if (strchr(OTHER_USERID_CHARS, *cp) != NULL)
560 				continue;	/* Some more valid characters */
561 			if (isupperch(*cp)) {
562 				has_uc = 1;	/* These may be valid... */
563 				continue;
564 			}
565 			*cp = '_';
566 		}
567 		/*
568 		 * Some Windows hosts send print jobs where the correct userid
569 		 * has been converted to uppercase, and that can cause trouble
570 		 * for sites that expect the correct value (for something like
571 		 * accounting).  On the other hand, some sites do use uppercase
572 		 * in their userids, so we can't blindly convert to lowercase.
573 		 */
574 		if (has_uc && (getpwnam(cjinf->cji_acctuser) == NULL)) {
575 			for (cp = cjinf->cji_acctuser; *cp != '\0'; cp++) {
576 				if (isupperch(*cp))
577 					*cp = tolowerch(*cp);
578 			}
579 		}
580 	}
581 	if (nogood)
582 		fprintf(newcf, "P%s\n", ".na.");
583 	else
584 		fprintf(newcf, "P%s\n", cjinf->cji_acctuser);
585 
586 	/* No need for sanity checks on class, jobname, "literal" user. */
587 	if (cjinf->cji_class != NULL)
588 		fprintf(newcf, "C%s\n", cjinf->cji_class);
589 	if (cjinf->cji_jobname != NULL)
590 		fprintf(newcf, "J%s\n", cjinf->cji_jobname);
591 	if (cjinf->cji_headruser != NULL)
592 		fprintf(newcf, "L%s\n", cjinf->cji_headruser);
593 
594 	/*
595 	 * This should probably add more sanity checks on mailto value.
596 	 * Note that if the mailto value is "wrong", then there's no good
597 	 * way to know what the "correct" value would be, and we should not
598 	 * semd email to some random address.  At least for now, just ignore
599 	 * any invalid values.
600 	 */
601 	nogood = 0;
602 	if (cjinf->cji_mailto == NULL)
603 		nogood = 1;
604 	else {
605 		for (cp = cjinf->cji_mailto; *cp != '\0'; cp++) {
606 			if (*cp <= ' ') {
607 				nogood = 1;
608 				break;
609 			}
610 		}
611 	}
612 	if (!nogood)
613 		fprintf(newcf, "M%s\n", cjinf->cji_mailto);
614 
615 	/*
616 	 * Now go thru the old control file, copying all information which
617 	 * hasn't already been written into the new file.
618 	 */
619 	ctl_rewindcf(cjinf);
620 	lbuff = ctl_getline(cjinf);
621 	while (lbuff != NULL) {
622 		switch (lbuff[0]) {
623 		case 'H':
624 		case 'P':
625 		case 'C':
626 		case 'J':
627 		case 'L':
628 		case 'M':
629 			/* already wrote values for these to the newcf */
630 			break;
631 		case 'N':
632 			/* see comments under 'U'... */
633 			if (cjinf->cji_dfcount == 0) {
634 				/* in this case, 'N's will be done in 'U' */
635 				break;
636 			}
637 			fprintf(newcf, "%s\n", lbuff);
638 			break;
639 		case 'U':
640 			/*
641 			 * check for the very common case where the remote
642 			 * host had to process 'lpr -s -r', but it did not
643 			 * remove the Unlink line from the control file.
644 			 * Such Unlink lines will legitimately have a '/' in
645 			 * them, but it is the original lpr host which would
646 			 * have done the unlink of such files, and not any
647 			 * host receiving that job.
648 			 */
649 			slash = strchr(lbuff, '/');
650 			if (slash != NULL) {
651 				break;		/* skip this line */
652 			}
653 			/*
654 			 * Okay, another kind of broken lpr implementation
655 			 * is one which send datafiles, and Unlink's those
656 			 * datafiles, but never includes any PRINT request
657 			 * for those files.  Experimentation shows that one
658 			 * copy of those datafiles should be printed with a
659 			 * format of 'f'.  If this is an example of such a
660 			 * screwed-up control file, fix it here.
661 			 */
662 			if (cjinf->cji_dfcount == 0) {
663 				lbuff++;
664 				if (strncmp(lbuff, "df", (size_t)2) == 0) {
665 					fprintf(newcf, "f%s\n", lbuff);
666 					fprintf(newcf, "U%s\n", lbuff);
667 					fprintf(newcf, "N%s\n", lbuff);
668 				}
669 				break;
670 			}
671 			fprintf(newcf, "%s\n", lbuff);
672 			break;
673 		default:
674 			fprintf(newcf, "%s\n", lbuff);
675 			break;
676 		}
677 		lbuff = ctl_getline(cjinf);
678 	}
679 
680 	ctl_freeinf(cjinf);
681 	cjinf = NULL;
682 
683 	res = fclose(newcf);
684 	newcf = NULL;
685 	if (res != 0) {
686 		snprintf(errm, sizeof(errm),
687 		    "ctl_renametf error fclose(%s): %s", tfname2,
688 		    strerror(errno));
689 		goto error_ret;
690 	}
691 
692 	strlcpy(cfname2, tfname, sizeof(cfname2));
693 	cfname2[0] = 'c';		/* rename new file to 'cfA*' */
694 	res = link(tfname2, cfname2);
695 	if (res != 0) {
696 		snprintf(errm, sizeof(errm),
697 		    "ctl_renametf error link(%s,%s): %s", tfname2, cfname2,
698 		    strerror(errno));
699 		goto error_ret;
700 	}
701 
702 	/* All the important work is done.  Now just remove temp files */
703 #ifdef LEAVE_TMPCF_FILES
704 	{
705 		struct stat tfstat;
706 		size_t size1;
707 		tfstat.st_size = 1;	/* certainly invalid value */
708 		res = stat(tfname, &tfstat);
709 		size1 = tfstat.st_size;
710 		tfstat.st_size = 2;	/* certainly invalid value */
711 		res = stat(tfname2, &tfstat);
712 		/*
713 		 * If the sizes do not match, or either stat call failed,
714 		 * then do not remove the temp files, but just move them
715 		 * out of the way.  This is so I can see what this routine
716 		 * had changed (and the files won't interfere with some
717 		 * later job coming in from the same host).  In this case,
718 		 * we don't care if we clobber some previous file.
719 		 */
720 		if (size1 != tfstat.st_size) {
721 			strlcpy(cfname2, tfname, sizeof(cfname2));
722 			strlcat(cfname2, "._T", sizeof(cfname2));
723 			rename(tfname, cfname2);
724 			strlcpy(cfname2, tfname2, sizeof(cfname2));
725 			strlcat(cfname2, "._T", sizeof(cfname2));
726 			rename(tfname2, cfname2);
727 			return NULL;
728 		}
729 	}
730 #endif
731 	unlink(tfname);
732 	unlink(tfname2);
733 
734 	return NULL;
735 
736 error_ret:
737 	if (cjinf != NULL)
738 		ctl_freeinf(cjinf);
739 	if (newcf != NULL)
740 		fclose(newcf);
741 
742 	if (*errm != '\0')
743 		return strdup(errm);
744 	return strdup("ctl_renametf internal (missed) error");
745 }
746 
747 void
748 ctl_rewindcf(struct cjobinfo *cjinf)
749 {
750 	struct cjprivate *cpriv;
751 
752 	if (cjinf == NULL)
753 		return;
754 	cpriv = cjinf->cji_priv;
755 	if ((cpriv == NULL) || (cpriv != cpriv->pub.cji_priv)) {
756 		syslog(LOG_ERR, "in ctl_rewindcf(%p): invalid cjinf (cpriv %p)",
757 		    (void *)cjinf, (void *)cpriv);
758 		return;
759 	}
760 
761 	rewind(cpriv->cji_fstream);		/* assume no errors... :-) */
762 }
763 
764 char *
765 ctl_rmjob(const char *ptrname, const char *cfname)
766 {
767 	struct cjobinfo	*cjinf;
768 	char *lbuff;
769 	char errm[CTI_LINEMAX];
770 
771 	cjinf = ctl_readcf(ptrname, cfname);
772 	if (cjinf == NULL) {
773 		snprintf(errm, sizeof(errm),
774 		    "ctl_renametf error cti_readcf(%s)", cfname);
775 		return strdup(errm);
776 	}
777 
778 	ctl_rewindcf(cjinf);
779 	lbuff = ctl_getline(cjinf);
780 	while (lbuff != NULL) {
781 		/* obviously we need to fill in the following... */
782 		switch (lbuff[0]) {
783 		case 'S':
784 			break;
785 		case 'U':
786 			break;
787 		default:
788 			break;
789 		}
790 		lbuff = ctl_getline(cjinf);
791 	}
792 
793 	ctl_freeinf(cjinf);
794 	cjinf = NULL;
795 
796 	return NULL;
797 }
798 
799 /*
800  * The following routine was originally written to pin down a bug.  It is
801  * no longer needed for that problem, but may be useful to keep around for
802  * other debugging.
803  */
804 void
805 ctl_dumpcji(FILE *dbg_stream, const char *heading, struct cjobinfo *cjinf)
806 {
807 #define PRINTSTR(xHdr,xStr) \
808 	astr = xStr; \
809 	ctl_dbgline++; \
810 	fprintf(dbg_stream, "%4d] %12s = ", ctl_dbgline, xHdr); \
811 	if (astr == NULL) \
812 		fprintf(dbg_stream, "NULL\n"); \
813 	else \
814 		fprintf(dbg_stream, "%p -> %s\n", astr, astr)
815 
816 	struct cjprivate *cpriv;
817 	char *astr;
818 
819 	if (cjinf == NULL) {
820 		fprintf(dbg_stream,
821 		    "ctl_dumpcji: ptr to cjobinfo for '%s' is NULL\n",
822 		    heading);
823 		return;
824 	}
825 	cpriv = cjinf->cji_priv;
826 
827 	fprintf(dbg_stream, "ctl_dumpcji: Dump '%s' of cjobinfo at %p->%p\n",
828 	    heading, (void *)cjinf, cpriv->cji_buff);
829 
830 	PRINTSTR("accthost.H", cpriv->pub.cji_accthost);
831 	PRINTSTR("acctuser.P", cpriv->pub.cji_acctuser);
832 	PRINTSTR("class.C", cpriv->pub.cji_class);
833 	PRINTSTR("cf-qname", cpriv->pub.cji_curqueue);
834 	PRINTSTR("cf-fname", cpriv->pub.cji_fname);
835 	PRINTSTR("jobname.J", cpriv->pub.cji_jobname);
836 	PRINTSTR("mailto.M", cpriv->pub.cji_mailto);
837 	PRINTSTR("headruser.L", cpriv->pub.cji_headruser);
838 
839 	ctl_dbgline++;
840 	fprintf(dbg_stream, "%4d] %12s = ", ctl_dbgline, "*cjprivate");
841 	if (cpriv->pub.cji_priv == NULL)
842 		fprintf(dbg_stream, "NULL !!\n");
843 	else
844 		fprintf(dbg_stream, "%p\n", (void *)cpriv->pub.cji_priv);
845 
846 	fprintf(dbg_stream, "|- - - - --> Dump '%s' complete\n", heading);
847 
848 	/* flush output for the benefit of anyone doing a 'tail -f' */
849 	fflush(dbg_stream);
850 
851 #undef PRINTSTR
852 }
853 
854 /*
855  * This routine reads in the next line from the control-file, and removes
856  * the trailing newline character.
857  *
858  * Historical note: Earlier versions of this routine did tab-expansion for
859  * ALL lines read in, which did not make any sense for most of the lines
860  * in a control file.  For the lines where tab-expansion is useful, it will
861  * now have to be done by the calling routine.
862  */
863 static char *
864 ctl_getline(struct cjobinfo *cjinf)
865 {
866 	char *strp, *nl;
867 	struct cjprivate *cpriv;
868 
869 	if (cjinf == NULL)
870 		return NULL;
871 	cpriv = cjinf->cji_priv;
872 	if ((cpriv == NULL) || (cpriv != cpriv->pub.cji_priv)) {
873 		syslog(LOG_ERR, "in ctl_getline(%p): invalid cjinf (cpriv %p)",
874 		    (void *)cjinf, (void *)cpriv);
875 		return NULL;
876 	}
877 
878 	errno = 0;
879 	strp = fgets(cpriv->cji_buff, cpriv->cji_buffsize, cpriv->cji_fstream);
880 	if (strp == NULL) {
881 		if (errno != 0)
882 			syslog(LOG_ERR, "%s: ctl_getline error fgets(%s): %s",
883 			    cpriv->pub.cji_curqueue, cpriv->pub.cji_fname,
884 			    strerror(errno));
885 		return NULL;
886 	}
887 	nl = strchr(strp, '\n');
888 	if (nl != NULL)
889 		*nl = '\0';
890 
891 #ifdef DEBUGREADCF_FNAME
892 	/* I'd like to find out if the previous work to expand tabs was ever
893 	 * really used, and if so, on what lines and for what reason.
894 	 * Yes, all this work probably means I'm obsessed about this 'tab'
895 	 * issue, but isn't programming a matter of obsession?
896 	 */
897 	{
898 		int tabcnt;
899 		char *ch;
900 
901 		tabcnt = 0;
902 		ch = strp;
903 		for (ch = strp; *ch != '\0'; ch++) {
904 			if (*ch == '\t')
905 				tabcnt++;
906 		}
907 
908 		if (tabcnt && (ctl_dbgfile != NULL)) {
909 			cpriv->cji_dumpit++;
910 			fprintf(ctl_dbgfile, "%s: tabs=%d '%s'\n",
911 			    cpriv->pub.cji_fname, tabcnt, cpriv->cji_buff);
912 		}
913 	}
914 #endif
915 	return strp;
916 }
917