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