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