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