1330449Seadler/*-
2330449Seadler * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3330449Seadler *
479746Sgad * ------+---------+---------+---------+---------+---------+---------+---------*
5220586Sgad * Copyright (c) 2001,2011  - Garance Alistair Drosehn <gad@FreeBSD.org>.
679746Sgad * All rights reserved.
779746Sgad *
879746Sgad * Redistribution and use in source and binary forms, with or without
979746Sgad * modification, are permitted provided that the following conditions
1079746Sgad * are met:
1179746Sgad *   1. Redistributions of source code must retain the above copyright
1279746Sgad *      notice, this list of conditions and the following disclaimer.
1379746Sgad *   2. Redistributions in binary form must reproduce the above copyright
1479746Sgad *      notice, this list of conditions and the following disclaimer in the
1579746Sgad *      documentation and/or other materials provided with the distribution.
1679746Sgad *
1779746Sgad * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1879746Sgad * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1979746Sgad * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2079746Sgad * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
2179746Sgad * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2279746Sgad * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2379746Sgad * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2479746Sgad * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2579746Sgad * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2679746Sgad * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2779746Sgad * SUCH DAMAGE.
2879746Sgad *
2979746Sgad * The views and conclusions contained in the software and documentation
3079746Sgad * are those of the authors and should not be interpreted as representing
3179746Sgad * official policies, either expressed or implied, of the FreeBSD Project.
3279746Sgad *
3379746Sgad * ------+---------+---------+---------+---------+---------+---------+---------*
3479746Sgad */
3579746Sgad
36117541Sgad#include "lp.cdefs.h"		/* A cross-platform version of <sys/cdefs.h> */
37117541Sgad__FBSDID("$FreeBSD: stable/11/usr.sbin/lpr/common_source/ctlinfo.c 330449 2018-03-05 07:26:05Z eadler $");
3879746Sgad
3979746Sgad/*
4079746Sgad * ctlinfo - This collection of routines will know everything there is to
4179746Sgad * know about the information inside a control file ('cf*') which is used
4279746Sgad * to describe a print job in lpr & friends.  The eventual goal is that it
4379746Sgad * will be the ONLY source file to know what's inside these control-files.
4479746Sgad */
4579746Sgad
4679746Sgad/*
4779746Sgad * Some define's useful for debuging.
4879746Sgad * TRIGGERTEST_FNAME and DEBUGREADCF_FNAME, allow us to do testing on
4979746Sgad * a per-spool-directory basis.
5079746Sgad */
5179746Sgad/* #define TRIGGERTEST_FNAME "LpdTestRenameTF" */
5279746Sgad/* #define DEBUGREADCF_FNAME "LpdDebugReadCF" */
5379746Sgad/* #define LEAVE_TMPCF_FILES 1 */
5479746Sgad
5579746Sgad#include <sys/types.h>
5679746Sgad#include <sys/stat.h>
5779746Sgad#include <ctype.h>
5879746Sgad#include <errno.h>
5979746Sgad#include <fcntl.h>
6079746Sgad#include <limits.h>
6179746Sgad#include <netdb.h>
62139462Sgad#include <pwd.h>
6379746Sgad#include <stdio.h>
6479746Sgad#include <stdlib.h>
6579746Sgad#include <string.h>
6679746Sgad#include <syslog.h>
6779746Sgad#include <unistd.h>
6879746Sgad#include "ctlinfo.h"
6979746Sgad
7079746Sgadstruct cjprivate {
7179746Sgad	struct cjobinfo pub;
7279746Sgad	char	*cji_buff;		/* buffer for getline */
7379746Sgad	char	*cji_eobuff;		/* last byte IN the buffer */
7479746Sgad	FILE	*cji_fstream;
7579746Sgad	int	 cji_buffsize;		/* # bytes in the buffer */
7679746Sgad	int	 cji_dumpit;
7779746Sgad};
7879746Sgad
79139462Sgad/*
80139462Sgad * All the following take a parameter of 'int', but expect values in the
81139462Sgad * range of unsigned char.  Define wrappers which take values of type 'char',
82139462Sgad * whether signed or unsigned, and ensure they end up in the right range.
83139462Sgad */
84139462Sgad#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
85139462Sgad#define	islowerch(Anychar) islower((u_char)(Anychar))
86139462Sgad#define	isupperch(Anychar) isupper((u_char)(Anychar))
87139462Sgad#define	tolowerch(Anychar) tolower((u_char)(Anychar))
88139462Sgad
89139462Sgad#define	OTHER_USERID_CHARS  "-_"	/* special chars valid in a userid */
90139462Sgad
9179746Sgad#define roundup(x, y)   ((((x)+((y)-1))/(y))*(y))
9279746Sgad
9379746Sgad/*
9479746Sgad * This has to be large enough to fit the maximum length of a single line
9579746Sgad * in a control-file, including the leading 'command id', a trailing '\n'
9679746Sgad * and ending '\0'.  The max size of an 'U'nlink line, for instance, is
9779746Sgad * 1 ('U') + PATH_MAX (filename) + 2 ('\n\0').  The maximum 'H'ost line is
9879746Sgad * 1 ('H') + NI_MAXHOST (remote hostname) + 2 ('\n\0').  Other lines can be
9979746Sgad * even longer than those.  So, pick some nice, large, arbitrary value.
10079746Sgad */
10179746Sgad#define CTI_LINEMAX  PATH_MAX+NI_MAXHOST+5
10279746Sgad
10379746Sgadextern const char	*from_host;	/* client's machine name */
10479746Sgadextern const char	*from_ip;	/* client machine's IP address */
10579746Sgad
10679746Sgad__BEGIN_DECLS
10779746Sgadvoid		 ctl_dumpcji(FILE *_dbg_stream, const char *_heading,
10879746Sgad		    struct cjobinfo *_cjinf);
10979746Sgadstatic char	*ctl_getline(struct cjobinfo *_cjinf);
11079746Sgadstatic void	 ctl_rewindcf(struct cjobinfo *_cjinf);
11179746Sgadchar		*ctl_rmjob(const char *_ptrname, const char *_cfname);
11279746Sgad__END_DECLS
11379746Sgad
11479746Sgad/*
11579746Sgad * Here are some things which might be needed when compiling this under
11679746Sgad * platforms other than FreeBSD.
11779746Sgad */
11879746Sgad#ifndef __FreeBSD__
11979746Sgad#   ifndef NAME_MAX
12079746Sgad#	define NAME_MAX	255
12179746Sgad#   endif
12279746Sgad#   ifndef NI_MAXHOST
12379746Sgad#	define NI_MAXHOST	1025
12479746Sgad#   endif
12579746Sgad#   ifndef PATH_MAX
12679746Sgad#	define PATH_MAX	1024
12779746Sgad#   endif
12879746Sgad__BEGIN_DECLS
12979746Sgadchar		*strdup(const char *_src);
13079746Sgadsize_t		 strlcpy(char *_dst, const char *_src, size_t _siz);
13179746Sgad__END_DECLS
13279746Sgad#endif
13379746Sgad
13479746Sgad/*
13579746Sgad *	Control-files (cf*) have the following format.
13679746Sgad *
13779746Sgad *	Each control-file describes a single job.  It will list one or more
13879746Sgad *	"datafiles" (df*) which should be copied to some printer.  Usually
13979746Sgad *	there is only one datafile per job.  For the curious, RFC 1179 is an
14079746Sgad *	informal and out-of-date description of lpr/lpd circa 1990.
14179746Sgad *
14279746Sgad *	Each line in the file gives an attribute of the job as a whole, or one
14379746Sgad *	of the datafiles in the job, or a "command" indicating something to do
14479746Sgad *	with one of the datafiles.  Each line starts with an 'id' that indicates
14579746Sgad *	what that line is there for.  The 'id' is historically a single byte,
14679746Sgad *	but may be multiple bytes (obviously it would be best if multi-byte ids
14779746Sgad *	started with some letter not already used as a single-byte id!).
14879746Sgad *	After the 'id', the remainder of the line will be the value of the
14979746Sgad *	indicated attribute, or a name of the datafile to be operated on.
15079746Sgad *
15179746Sgad *	In the following lists of ids, the ids with a '!' in front of them are
15279746Sgad *	NOT explicitly supported by this version of lpd, or at least "not yet
15379746Sgad *	supported".  They are only listed for reference purposes, so people
15479746Sgad *	won't be tempted to reuse the same id for a different purpose.
15579746Sgad *
15679746Sgad *	The following are attributes of the job which should not appear more
15779746Sgad *	than once in a control file.  Only the 'H' and 'P' lines are required
15879746Sgad *	by the RFC, but some implementations of lpr won't even get that right.
15979746Sgad *
16079746Sgad *	! A   - [used by lprNG]
16179746Sgad *	  B   - As far as I know, this is never used as a single-byte id.
16279746Sgad *		Therefore, I intend to use it for multi-byte id codes.
16379746Sgad *	  C   - "class name" to display on banner page (this is sometimes
16479746Sgad *		used to hold options for print filters)
16579746Sgad *	! D   - [in lprNG, "timestamp" of when the job was submitted]
16679746Sgad *	! E   - "environment variables" to set [some versions of linux]
16779746Sgad *	  H   - "host name" of machine where the original 'lpr' was done
16879746Sgad *	  I   - "indent", the amount to indent output
16979746Sgad *	  J   - "job name" to display on banner page
17079746Sgad *	  L   - "literal" user's name as it should be displayed on the
17179746Sgad *		banner page (it is the existence of an 'L' line which
17279746Sgad *		indicates that a job should have a banner page).
17379746Sgad *	  M   - "mail", userid to mail to when done printing (with email
17479746Sgad *		going to 'M'@'H', so to speak).
17579746Sgad *	  P   - "person", the user's login name (e.g. for accounting)
17679746Sgad *	! Q   - [used by lprNG for queue-name]
17779746Sgad *	  R   - "resolution" in dpi, for some laser printer queues
17879746Sgad *	  T   - "title" for files sent thru 'pr'
17979746Sgad *	  W   - "width" to use for printing plain-text files
18079746Sgad *	  Z   - In BSD, "locale" to use for datafiles sent thru 'pr'.
18179746Sgad *		(this BSD usage should move to a different id...)
18279746Sgad *		[in lprNG - this line holds the "Z options"]
18379746Sgad *	  1   - "R font file" for files sent thru troff
18479746Sgad *	  2   - "I font file" for files sent thru troff
18579746Sgad *	  3   - "B font file" for files sent thru troff
18679746Sgad *	  4   - "S font file" for files sent thru troff
18779746Sgad *
18879746Sgad *	The following are attributes attached to a datafile, and thus may
18979746Sgad *	appear multiple times in a control file (once per datafile):
19079746Sgad *
19179746Sgad *	  N   - "name" of file (for display purposes, used by 'lpq')
19279746Sgad *	  S   - "stat() info" used for symbolic link ('lpr -s')
19379746Sgad *		security checks.
19479746Sgad *
19579746Sgad *	The following indicate actions to take on a given datafile.  The same
19679746Sgad *	datafile may appear on more than one "print this file" command in the
19783684Sgad *	control file.  Note that ALL ids with lowercase letters are expected
19883684Sgad *	to be actions to "print this file":
19979746Sgad *
20083684Sgad *	  c   - "file name", cifplot file to print.  This action appears
20183684Sgad *		when the user has requested 'lpr -c'.
20283684Sgad *	  d   - "file name", dvi file to print, user requested 'lpr -d'
20383684Sgad *	  f   - "file name", a plain-text file to print = "standard"
20483684Sgad *	  g   - "file name", plot(1G) file to print, ie 'lpr -g'
20583684Sgad *	  l   - "file name", text file with control chars which should
20683684Sgad *		be printed literally, ie 'lpr -l'  (note: some printers
20786935Sgad *		take this id as a request to print a postscript file,
20886935Sgad *		and because of *that* some OS's use 'l' to indicate
20986935Sgad *		that a datafile is a postscript file)
21083684Sgad *	  n   - "file name", ditroff(1) file to print, ie 'lpr -n'
21183684Sgad *	  o   - "file name", a postscript file to print.  This id is
21283684Sgad *		described in the original RFC, but not much has been
21383684Sgad *		done with it.  This 'lpr' does not generate control
21483684Sgad *		lines with 'o'-actions, but lpd's printjob processing
21586935Sgad *		will treat it the same as 'l'.
21683684Sgad *	  p   - "file name", text file to print with pr(1), ie 'lpr -p'
21783684Sgad *	  t   - "file name", troff(1) file to print, ie 'lpr -t'
21879746Sgad *	  v   - "file name", plain raster file to print
21979746Sgad *
22079746Sgad *	  U   - "file name" of datafile to unlink (ie, remove file
22179746Sgad *		from spool directory.  To be done in a 'Pass 2',
22279746Sgad *		AFTER having processed all datafiles in the job).
22379746Sgad *
22479746Sgad */
22579746Sgad
22679746Sgadvoid
22779746Sgadctl_freeinf(struct cjobinfo *cjinf)
22879746Sgad{
22979746Sgad#define FREESTR(xStr) \
23079746Sgad	if (xStr != NULL) { \
23179746Sgad		free(xStr); \
23279746Sgad		xStr = NULL;\
23379746Sgad	}
23479746Sgad
23579746Sgad	struct cjprivate *cpriv;
23679746Sgad
23779746Sgad	if (cjinf == NULL)
23879746Sgad		return;
23979746Sgad	cpriv = cjinf->cji_priv;
24079746Sgad	if ((cpriv == NULL) || (cpriv != cpriv->pub.cji_priv)) {
24179746Sgad		syslog(LOG_ERR, "in ctl_freeinf(%p): invalid cjinf (cpriv %p)",
24295429Sgad		    (void *)cjinf, (void *)cpriv);
24379746Sgad		return;
24479746Sgad	}
24579746Sgad
24679746Sgad	FREESTR(cpriv->pub.cji_accthost);
24779746Sgad	FREESTR(cpriv->pub.cji_acctuser);
24879746Sgad	FREESTR(cpriv->pub.cji_class);
24979746Sgad	FREESTR(cpriv->pub.cji_curqueue);
25079746Sgad	/* [cpriv->pub.cji_fname is part of cpriv-malloced area] */
25179746Sgad	FREESTR(cpriv->pub.cji_jobname);
25279746Sgad	FREESTR(cpriv->pub.cji_mailto);
253220586Sgad	FREESTR(cpriv->pub.cji_headruser);
25479746Sgad
25579746Sgad	if (cpriv->cji_fstream != NULL) {
25679746Sgad		fclose(cpriv->cji_fstream);
25779746Sgad		cpriv->cji_fstream = NULL;
25879746Sgad	}
25979746Sgad
26079746Sgad	cjinf->cji_priv = NULL;
26179746Sgad	free(cpriv);
26279746Sgad#undef FREESTR
26379746Sgad}
26479746Sgad
26579746Sgad#ifdef DEBUGREADCF_FNAME
26679746Sgadstatic FILE *ctl_dbgfile = NULL;
26779746Sgadstatic struct stat ctl_dbgstat;
26879746Sgad#endif
26979746Sgadstatic int ctl_dbgline = 0;
27079746Sgad
27179746Sgadstruct cjobinfo *
27279746Sgadctl_readcf(const char *ptrname, const char *cfname)
27379746Sgad{
27479746Sgad	int id;
27579746Sgad	char *lbuff;
27679746Sgad	void *cstart;
27779746Sgad	FILE *cfile;
27879746Sgad	struct cjprivate *cpriv;
27979746Sgad	struct cjobinfo *cjinf;
28079746Sgad	size_t msize, sroom, sroom2;
28179746Sgad
28279746Sgad	cfile = fopen(cfname, "r");
28379746Sgad	if (cfile == NULL) {
28479746Sgad		syslog(LOG_ERR, "%s: ctl_readcf error fopen(%s): %s",
28579746Sgad		    ptrname, cfname, strerror(errno));
28679746Sgad		return NULL;
28779746Sgad	}
28879746Sgad
28979746Sgad	sroom = roundup(sizeof(struct cjprivate), 8);
29079746Sgad	sroom2 = sroom + strlen(cfname) + 1;
29179746Sgad	sroom2 = roundup(sroom2, 8);
29279746Sgad	msize = sroom2 + CTI_LINEMAX;
29379746Sgad	msize = roundup(msize, 8);
29479746Sgad	cstart = malloc(msize);
29579746Sgad	if (cstart == NULL)
29679746Sgad		return NULL;
29779746Sgad	memset(cstart, 0, msize);
29879746Sgad	cpriv = (struct cjprivate *)cstart;
29979746Sgad	cpriv->pub.cji_priv = cpriv;
30079746Sgad
30179746Sgad	cpriv->pub.cji_fname = (char *)cstart + sroom;
30279746Sgad	strcpy(cpriv->pub.cji_fname, cfname);
30379746Sgad	cpriv->cji_buff = (char *)cstart + sroom2;
30479746Sgad	cpriv->cji_buffsize = (int)(msize - sroom2);
30579746Sgad	cpriv->cji_eobuff = (char *)cstart + msize - 1;
30679746Sgad
30779746Sgad	cpriv->cji_fstream = cfile;
30879746Sgad	cpriv->pub.cji_curqueue = strdup(ptrname);
30979746Sgad
31079746Sgad	ctl_dbgline = 0;
31179746Sgad#ifdef DEBUGREADCF_FNAME
31279746Sgad	ctl_dbgfile = NULL;
31379746Sgad	id = stat(DEBUGREADCF_FNAME, &ctl_dbgstat);
31479746Sgad	if (id != -1) {
31579746Sgad		/* the file exists in this spool directory, write some simple
31679746Sgad		 * debugging info to it */
31779746Sgad		ctl_dbgfile = fopen(DEBUGREADCF_FNAME, "a");
31879746Sgad		if (ctl_dbgfile != NULL) {
31979746Sgad			fprintf(ctl_dbgfile, "%s: s=%p r=%ld e=%p %p->%s\n",
32095429Sgad			    ptrname, (void *)cpriv, (long)sroom,
32195429Sgad			    cpriv->cji_eobuff, cpriv->pub.cji_fname,
32295429Sgad			    cpriv->pub.cji_fname);
32379746Sgad		}
32479746Sgad	}
32579746Sgad#endif
32679746Sgad	/*
32779746Sgad	 * Copy job-attribute values from control file to the struct of
32879746Sgad	 * "public" information.  In some cases, it is invalid for the
32979746Sgad	 * value to be a null-string, so that is ignored.
33079746Sgad	 */
33179746Sgad	cjinf = &(cpriv->pub);
33279746Sgad	lbuff = ctl_getline(cjinf);
33379746Sgad	while (lbuff != NULL) {
33479746Sgad		id = *lbuff++;
33579746Sgad		switch (id) {
33679746Sgad		case 'C':
33779746Sgad			cpriv->pub.cji_class = strdup(lbuff);
33879746Sgad			break;
33979746Sgad		case 'H':
34079746Sgad			if (*lbuff == '\0')
34179746Sgad				break;
34279746Sgad			cpriv->pub.cji_accthost = strdup(lbuff);
34379746Sgad			break;
34479746Sgad		case 'J':
34579746Sgad			cpriv->pub.cji_jobname = strdup(lbuff);
34679746Sgad			break;
34779746Sgad		case 'L':
348220586Sgad			cpriv->pub.cji_headruser = strdup(lbuff);
34979746Sgad			break;
35079746Sgad		case 'M':
35179746Sgad			/*
35279746Sgad			 * No valid mail-to address would start with a minus.
35379746Sgad			 * If this one does, it is probably some trickster who
35479746Sgad			 * is trying to trigger options on sendmail.  Ignore.
35579746Sgad			 */
35679746Sgad			if (*lbuff == '-')
35779746Sgad				break;
35879746Sgad			if (*lbuff == '\0')
35979746Sgad				break;
36079746Sgad			cpriv->pub.cji_mailto = strdup(lbuff);
36179746Sgad			break;
36279746Sgad		case 'P':
36379746Sgad			if (*lbuff == '\0')
36479746Sgad				break;
365139462Sgad			/* The userid must not start with a minus sign */
366139462Sgad			if (*lbuff == '-')
367139462Sgad				*lbuff = '_';
36879746Sgad			cpriv->pub.cji_acctuser = strdup(lbuff);
36979746Sgad			break;
37079746Sgad		default:
37179746Sgad			if (islower(id)) {
37279746Sgad				cpriv->pub.cji_dfcount++;
37379746Sgad			}
37479746Sgad			break;
37579746Sgad		}
37679746Sgad		lbuff = ctl_getline(cjinf);
37779746Sgad	}
37879746Sgad
37979746Sgad	/* the 'H'ost and 'P'erson fields are *always* supposed to be there */
38079746Sgad	if (cpriv->pub.cji_accthost == NULL)
38179746Sgad		cpriv->pub.cji_accthost = strdup(".na.");
38279746Sgad	if (cpriv->pub.cji_acctuser == NULL)
38379746Sgad		cpriv->pub.cji_acctuser = strdup(".na.");
38479746Sgad
38579746Sgad#ifdef DEBUGREADCF_FNAME
38679746Sgad	if (ctl_dbgfile != NULL) {
38779746Sgad		if (cpriv->cji_dumpit)
38879746Sgad			ctl_dumpcji(ctl_dbgfile, "end readcf", &(cpriv->pub));
38979746Sgad		fclose(ctl_dbgfile);
39079746Sgad		ctl_dbgfile = NULL;
39179746Sgad	}
39279746Sgad#endif
39379746Sgad	return &(cpriv->pub);
39479746Sgad}
39579746Sgad
39679746Sgad/*
39779746Sgad * This routine renames the temporary control file as received from some
39887034Sgad * other (remote) host.  That file will almost always with `tfA*', because
39987034Sgad * recvjob.c creates the file by changing `c' to `t' in the original name
40087034Sgad * for the control file.  Now if you read the RFC, you would think that all
40187034Sgad * control filenames start with `cfA*'.  However, it seems there are some
40287034Sgad * implementations which send control filenames which start with `cf'
40387034Sgad * followed by *any* letter, so this routine can not assume what the third
40487034Sgad * letter will (or will not) be.  Sigh.
40579746Sgad *
40687034Sgad * So this will rewrite the temporary file to `rf*' (correcting any lines
40787034Sgad * which need correcting), rename that `rf*' file to `cf*', and then remove
40887034Sgad * the original `tf*' temporary file.
40987034Sgad *
41087034Sgad * The *main* purpose of this routine is to be paranoid about the contents
41179746Sgad * of that control file.  It is partially meant to protect against people
41279746Sgad * TRYING to cause trouble (perhaps after breaking into root of some host
41379746Sgad * that this host will accept print jobs from).  The fact that we're willing
41479746Sgad * to print jobs from some remote host does not mean that we should blindly
41579746Sgad * do anything that host tells us to do.
41679746Sgad *
41779746Sgad * This is also meant to protect us from errors in other implementations of
41879746Sgad * lpr, particularly since we may want to use some values from the control
41979746Sgad * file as environment variables when it comes time to print, or as parameters
42079746Sgad * to commands which will be exec'ed, or values in statistics records.
42179746Sgad *
42279746Sgad * This may also do some "conversions" between how different versions of
42379746Sgad * lpr or lprNG define the contents of various lines in a control file.
42479746Sgad *
42579746Sgad * If there is an error, it returns a pointer to a descriptive error message.
42679746Sgad * Error messages which are RETURNED (as opposed to syslog-ed) do not include
42779746Sgad * the printer-queue name.  Let the caller add that if it is wanted.
42879746Sgad */
42979746Sgadchar *
43079746Sgadctl_renametf(const char *ptrname, const char *tfname)
43179746Sgad{
432139462Sgad	int chk3rd, has_uc, newfd, nogood, res;
43379746Sgad	FILE *newcf;
43479746Sgad	struct cjobinfo *cjinf;
43579746Sgad	char *lbuff, *slash, *cp;
43679746Sgad	char tfname2[NAME_MAX+1], cfname2[NAME_MAX+1];
43779746Sgad	char errm[CTI_LINEMAX];
43879746Sgad
43979746Sgad#ifdef TRIGGERTEST_FNAME
44079746Sgad	struct stat tstat;
44179746Sgad	res = stat(TRIGGERTEST_FNAME, &tstat);
44279746Sgad	if (res == -1) {
44379746Sgad		/*
44479746Sgad		 * if the trigger file does NOT exist in this spool directory,
44579746Sgad		 * then do the exact same steps that the pre-ctlinfo code had
44679746Sgad		 * been doing.  Ie, very little.
44779746Sgad		 */
44879746Sgad		strlcpy(cfname2, tfname, sizeof(cfname2));
44979746Sgad		cfname2[0] = 'c';
45079746Sgad		res = link(tfname, cfname2);
45179746Sgad		if (res < 0) {
45279746Sgad			snprintf(errm, sizeof(errm),
45379746Sgad			    "ctl_renametf error link(%s,%s): %s", tfname,
45479746Sgad			    cfname2, strerror(errno));
45579746Sgad			return strdup(errm);
45679746Sgad		}
45779746Sgad		unlink(tfname);
45879746Sgad		return NULL;
45979746Sgad	}
46079746Sgad#endif
46179746Sgad	cjinf = NULL;		/* in case of early jump to error_ret */
46279746Sgad	newcf = NULL;		/* in case of early jump to error_ret */
46379746Sgad	*errm = '\0';		/* in case of early jump to error_ret */
46479746Sgad
46587034Sgad	chk3rd = tfname[2];
46687034Sgad	if ((tfname[0] != 't') || (tfname[1] != 'f') || (!isalpha(chk3rd))) {
46779746Sgad		snprintf(errm, sizeof(errm),
46879746Sgad		    "ctl_renametf invalid filename: %s", tfname);
46979746Sgad		goto error_ret;
47079746Sgad	}
47179746Sgad
47279746Sgad	cjinf = ctl_readcf(ptrname, tfname);
47379746Sgad	if (cjinf == NULL) {
47479746Sgad		snprintf(errm, sizeof(errm),
47579746Sgad		    "ctl_renametf error cti_readcf(%s)", tfname);
47679746Sgad		goto error_ret;
47779746Sgad	}
47879746Sgad
47979746Sgad	/*
48079746Sgad	 * This uses open+fdopen instead of fopen because that combination
48179746Sgad	 * gives us greater control over file-creation issues.
48279746Sgad	 */
48379746Sgad	strlcpy(tfname2, tfname, sizeof(tfname2));
48487034Sgad	tfname2[0] = 'r';		/* rf<letter><job><hostname> */
48579746Sgad	newfd = open(tfname2, O_WRONLY|O_CREAT|O_TRUNC, 0660);
48679746Sgad	if (newfd == -1) {
48779746Sgad		snprintf(errm, sizeof(errm),
48879746Sgad		    "ctl_renametf error open(%s): %s", tfname2,
48979746Sgad		    strerror(errno));
49079746Sgad		goto error_ret;
49179746Sgad	}
49279746Sgad	newcf = fdopen(newfd, "w");
49379746Sgad	if (newcf == NULL) {
49479746Sgad		close(newfd);
49579746Sgad		snprintf(errm, sizeof(errm),
49679746Sgad		    "ctl_renametf error fopen(%s): %s", tfname2,
49779746Sgad		    strerror(errno));
49879746Sgad		goto error_ret;
49979746Sgad	}
50079746Sgad
50179746Sgad	/*
50279746Sgad	 * Do extra sanity checks on some key job-attribute fields, and
50379746Sgad	 * write them out first (thus making sure they are written in the
50479746Sgad	 * order we generally expect them to be in).
50579746Sgad	 */
50679746Sgad	/*
50779746Sgad	 * Some lpr implementations on PC's set a null-string for their
50879746Sgad	 * hostname.  A MacOS 10 system which has not correctly setup
50979746Sgad	 * /etc/hostconfig will claim a hostname of 'localhost'.  Anything
51079746Sgad	 * with blanks in it would be an invalid value for hostname.  For
51179746Sgad	 * any of these invalid hostname values, replace the given value
51279746Sgad	 * with the name of the host that this job is coming from.
51379746Sgad	 */
51479746Sgad	nogood = 0;
51579746Sgad	if (cjinf->cji_accthost == NULL)
51679746Sgad		nogood = 1;
51779746Sgad	else if (strcmp(cjinf->cji_accthost, ".na.") == 0)
51879746Sgad		nogood = 1;
51979746Sgad	else if (strcmp(cjinf->cji_accthost, "localhost") == 0)
52079746Sgad		nogood = 1;
52179746Sgad	else {
52279746Sgad		for (cp = cjinf->cji_accthost; *cp != '\0'; cp++) {
52379746Sgad			if (*cp <= ' ') {
52479746Sgad				nogood = 1;
52579746Sgad				break;
52679746Sgad			}
52779746Sgad		}
52879746Sgad	}
52979746Sgad	if (nogood)
53079746Sgad		fprintf(newcf, "H%s\n", from_host);
53179746Sgad	else
53279746Sgad		fprintf(newcf, "H%s\n", cjinf->cji_accthost);
53379746Sgad
53479746Sgad	/*
53579746Sgad	 * Now do some sanity checks on the 'P' (original userid) value.  Note
53679746Sgad	 * that the 'P'erson line is the second line which is ALWAYS supposed
53779746Sgad	 * to be present in a control file.
53879746Sgad	 *
53979746Sgad	 * There is no particularly good value to use for replacements, but
54079746Sgad	 * at least make sure the value is something reasonable to use in
54179746Sgad	 * environment variables and statistics records.  Again, some PC
54279746Sgad	 * implementations send a null-string for a value.  Various Mac
54379746Sgad	 * implementations will set whatever string the user has set for
54479746Sgad	 * their 'Owner Name', which usually includes blanks, etc.
54579746Sgad	 */
54679746Sgad	nogood = 0;
54779746Sgad	if (cjinf->cji_acctuser == NULL)
54879746Sgad		nogood = 1;
549139462Sgad	else if (strcmp(cjinf->cji_acctuser, ".na.") == 0)
550139462Sgad		;			/* No further checks needed... */
55179746Sgad	else {
552139462Sgad		has_uc = 0;
553139462Sgad		cp = cjinf->cji_acctuser;
554139462Sgad		if (*cp == '-')
555139462Sgad			*cp++ = '_';
556139462Sgad		for (; *cp != '\0'; cp++) {
557139462Sgad			if (islowerch(*cp) || isdigitch(*cp))
558139462Sgad				continue;	/* Standard valid characters */
559139462Sgad			if (strchr(OTHER_USERID_CHARS, *cp) != NULL)
560139462Sgad				continue;	/* Some more valid characters */
561139462Sgad			if (isupperch(*cp)) {
562139462Sgad				has_uc = 1;	/* These may be valid... */
563139462Sgad				continue;
564139462Sgad			}
565139462Sgad			*cp = '_';
56679746Sgad		}
567139462Sgad		/*
568139462Sgad		 * Some Windows hosts send print jobs where the correct userid
569139462Sgad		 * has been converted to uppercase, and that can cause trouble
570139462Sgad		 * for sites that expect the correct value (for something like
571139462Sgad		 * accounting).  On the other hand, some sites do use uppercase
572139462Sgad		 * in their userids, so we can't blindly convert to lowercase.
573139462Sgad		 */
574139462Sgad		if (has_uc && (getpwnam(cjinf->cji_acctuser) == NULL)) {
575139462Sgad			for (cp = cjinf->cji_acctuser; *cp != '\0'; cp++) {
576139462Sgad				if (isupperch(*cp))
577139462Sgad					*cp = tolowerch(*cp);
578139462Sgad			}
579139462Sgad		}
58079746Sgad	}
58179746Sgad	if (nogood)
58279746Sgad		fprintf(newcf, "P%s\n", ".na.");
58379746Sgad	else
58479746Sgad		fprintf(newcf, "P%s\n", cjinf->cji_acctuser);
58579746Sgad
58679746Sgad	/* No need for sanity checks on class, jobname, "literal" user. */
58779746Sgad	if (cjinf->cji_class != NULL)
58879746Sgad		fprintf(newcf, "C%s\n", cjinf->cji_class);
58979746Sgad	if (cjinf->cji_jobname != NULL)
59079746Sgad		fprintf(newcf, "J%s\n", cjinf->cji_jobname);
591220586Sgad	if (cjinf->cji_headruser != NULL)
592220586Sgad		fprintf(newcf, "L%s\n", cjinf->cji_headruser);
59379746Sgad
59479746Sgad	/*
59579746Sgad	 * This should probably add more sanity checks on mailto value.
59679746Sgad	 * Note that if the mailto value is "wrong", then there's no good
59779746Sgad	 * way to know what the "correct" value would be, and we should not
59879746Sgad	 * semd email to some random address.  At least for now, just ignore
59979746Sgad	 * any invalid values.
60079746Sgad	 */
60179746Sgad	nogood = 0;
60279746Sgad	if (cjinf->cji_mailto == NULL)
60379746Sgad		nogood = 1;
60479746Sgad	else {
605116230Sgad		for (cp = cjinf->cji_mailto; *cp != '\0'; cp++) {
60679746Sgad			if (*cp <= ' ') {
60779746Sgad				nogood = 1;
60879746Sgad				break;
60979746Sgad			}
61079746Sgad		}
61179746Sgad	}
61279746Sgad	if (!nogood)
61379746Sgad		fprintf(newcf, "M%s\n", cjinf->cji_mailto);
61479746Sgad
61579746Sgad	/*
61679746Sgad	 * Now go thru the old control file, copying all information which
61779746Sgad	 * hasn't already been written into the new file.
61879746Sgad	 */
61979746Sgad	ctl_rewindcf(cjinf);
62079746Sgad	lbuff = ctl_getline(cjinf);
62179746Sgad	while (lbuff != NULL) {
62279746Sgad		switch (lbuff[0]) {
62379746Sgad		case 'H':
62479746Sgad		case 'P':
62579746Sgad		case 'C':
62679746Sgad		case 'J':
62779746Sgad		case 'L':
62879746Sgad		case 'M':
62979746Sgad			/* already wrote values for these to the newcf */
63079746Sgad			break;
63179746Sgad		case 'N':
63279746Sgad			/* see comments under 'U'... */
63379746Sgad			if (cjinf->cji_dfcount == 0) {
63479746Sgad				/* in this case, 'N's will be done in 'U' */
63579746Sgad				break;
63679746Sgad			}
63779746Sgad			fprintf(newcf, "%s\n", lbuff);
63879746Sgad			break;
63979746Sgad		case 'U':
64079746Sgad			/*
64179746Sgad			 * check for the very common case where the remote
64279746Sgad			 * host had to process 'lpr -s -r', but it did not
64379746Sgad			 * remove the Unlink line from the control file.
64479746Sgad			 * Such Unlink lines will legitimately have a '/' in
64579746Sgad			 * them, but it is the original lpr host which would
64679746Sgad			 * have done the unlink of such files, and not any
64779746Sgad			 * host receiving that job.
64879746Sgad			 */
64979746Sgad			slash = strchr(lbuff, '/');
65079746Sgad			if (slash != NULL) {
65179746Sgad				break;		/* skip this line */
65279746Sgad			}
65379746Sgad			/*
65479746Sgad			 * Okay, another kind of broken lpr implementation
65579746Sgad			 * is one which send datafiles, and Unlink's those
65679746Sgad			 * datafiles, but never includes any PRINT request
65779746Sgad			 * for those files.  Experimentation shows that one
65879746Sgad			 * copy of those datafiles should be printed with a
65979746Sgad			 * format of 'f'.  If this is an example of such a
66079746Sgad			 * screwed-up control file, fix it here.
66179746Sgad			 */
66279746Sgad			if (cjinf->cji_dfcount == 0) {
66379746Sgad				lbuff++;
66479746Sgad				if (strncmp(lbuff, "df", (size_t)2) == 0) {
66579746Sgad					fprintf(newcf, "f%s\n", lbuff);
66679746Sgad					fprintf(newcf, "U%s\n", lbuff);
66779746Sgad					fprintf(newcf, "N%s\n", lbuff);
66879746Sgad				}
66979746Sgad				break;
67079746Sgad			}
67179746Sgad			fprintf(newcf, "%s\n", lbuff);
67279746Sgad			break;
67379746Sgad		default:
67479746Sgad			fprintf(newcf, "%s\n", lbuff);
67579746Sgad			break;
67679746Sgad		}
67779746Sgad		lbuff = ctl_getline(cjinf);
67879746Sgad	}
67979746Sgad
68079746Sgad	ctl_freeinf(cjinf);
68179746Sgad	cjinf = NULL;
68279746Sgad
68379746Sgad	res = fclose(newcf);
68479746Sgad	newcf = NULL;
68579746Sgad	if (res != 0) {
68679746Sgad		snprintf(errm, sizeof(errm),
68779746Sgad		    "ctl_renametf error fclose(%s): %s", tfname2,
68879746Sgad		    strerror(errno));
68979746Sgad		goto error_ret;
69079746Sgad	}
69179746Sgad
69279746Sgad	strlcpy(cfname2, tfname, sizeof(cfname2));
69379746Sgad	cfname2[0] = 'c';		/* rename new file to 'cfA*' */
69479746Sgad	res = link(tfname2, cfname2);
69579746Sgad	if (res != 0) {
69679746Sgad		snprintf(errm, sizeof(errm),
69779746Sgad		    "ctl_renametf error link(%s,%s): %s", tfname2, cfname2,
69879746Sgad		    strerror(errno));
69979746Sgad		goto error_ret;
70079746Sgad	}
70179746Sgad
70279746Sgad	/* All the important work is done.  Now just remove temp files */
70379746Sgad#ifdef LEAVE_TMPCF_FILES
70479746Sgad	{
70579746Sgad		struct stat tfstat;
70679746Sgad		size_t size1;
70779746Sgad		tfstat.st_size = 1;	/* certainly invalid value */
70879746Sgad		res = stat(tfname, &tfstat);
70979746Sgad		size1 = tfstat.st_size;
71079746Sgad		tfstat.st_size = 2;	/* certainly invalid value */
71179746Sgad		res = stat(tfname2, &tfstat);
712116234Sgad		/*
713116234Sgad		 * If the sizes do not match, or either stat call failed,
714116234Sgad		 * then do not remove the temp files, but just move them
715116234Sgad		 * out of the way.  This is so I can see what this routine
716116234Sgad		 * had changed (and the files won't interfere with some
717116234Sgad		 * later job coming in from the same host).  In this case,
718116234Sgad		 * we don't care if we clobber some previous file.
71979746Sgad		 */
720116234Sgad		if (size1 != tfstat.st_size) {
721116234Sgad			strlcpy(cfname2, tfname, sizeof(cfname2));
722116234Sgad			strlcat(cfname2, "._T", sizeof(cfname2));
723116234Sgad			rename(tfname, cfname2);
724116234Sgad			strlcpy(cfname2, tfname2, sizeof(cfname2));
725116234Sgad			strlcat(cfname2, "._T", sizeof(cfname2));
726116234Sgad			rename(tfname2, cfname2);
72779746Sgad			return NULL;
728116234Sgad		}
72979746Sgad	}
73079746Sgad#endif
73179746Sgad	unlink(tfname);
73279746Sgad	unlink(tfname2);
73379746Sgad
73479746Sgad	return NULL;
73579746Sgad
73679746Sgaderror_ret:
73779746Sgad	if (cjinf != NULL)
73879746Sgad		ctl_freeinf(cjinf);
73979746Sgad	if (newcf != NULL)
74079746Sgad		fclose(newcf);
74179746Sgad
74279746Sgad	if (*errm != '\0')
74379746Sgad		return strdup(errm);
74479746Sgad	return strdup("ctl_renametf internal (missed) error");
74579746Sgad}
74679746Sgad
74779746Sgadvoid
74879746Sgadctl_rewindcf(struct cjobinfo *cjinf)
74979746Sgad{
75079746Sgad	struct cjprivate *cpriv;
75179746Sgad
75279746Sgad	if (cjinf == NULL)
75379746Sgad		return;
75479746Sgad	cpriv = cjinf->cji_priv;
75579746Sgad	if ((cpriv == NULL) || (cpriv != cpriv->pub.cji_priv)) {
75679746Sgad		syslog(LOG_ERR, "in ctl_rewindcf(%p): invalid cjinf (cpriv %p)",
75795429Sgad		    (void *)cjinf, (void *)cpriv);
75879746Sgad		return;
75979746Sgad	}
76079746Sgad
76179746Sgad	rewind(cpriv->cji_fstream);		/* assume no errors... :-) */
76279746Sgad}
76379746Sgad
76479746Sgadchar *
76579746Sgadctl_rmjob(const char *ptrname, const char *cfname)
76679746Sgad{
76779746Sgad	struct cjobinfo	*cjinf;
76879746Sgad	char *lbuff;
76979746Sgad	char errm[CTI_LINEMAX];
77079746Sgad
77179746Sgad	cjinf = ctl_readcf(ptrname, cfname);
77279746Sgad	if (cjinf == NULL) {
77379746Sgad		snprintf(errm, sizeof(errm),
77479746Sgad		    "ctl_renametf error cti_readcf(%s)", cfname);
77579746Sgad		return strdup(errm);
77679746Sgad	}
77779746Sgad
77879746Sgad	ctl_rewindcf(cjinf);
77979746Sgad	lbuff = ctl_getline(cjinf);
78079746Sgad	while (lbuff != NULL) {
78179746Sgad		/* obviously we need to fill in the following... */
78279746Sgad		switch (lbuff[0]) {
78379746Sgad		case 'S':
78479746Sgad			break;
78579746Sgad		case 'U':
78679746Sgad			break;
78779746Sgad		default:
78879746Sgad			break;
78979746Sgad		}
79079746Sgad		lbuff = ctl_getline(cjinf);
79179746Sgad	}
79279746Sgad
79379746Sgad	ctl_freeinf(cjinf);
79479746Sgad	cjinf = NULL;
79579746Sgad
79679746Sgad	return NULL;
79779746Sgad}
79879746Sgad
79979746Sgad/*
80079746Sgad * The following routine was originally written to pin down a bug.  It is
80179746Sgad * no longer needed for that problem, but may be useful to keep around for
80279746Sgad * other debugging.
80379746Sgad */
80479746Sgadvoid
80579746Sgadctl_dumpcji(FILE *dbg_stream, const char *heading, struct cjobinfo *cjinf)
80679746Sgad{
80779746Sgad#define PRINTSTR(xHdr,xStr) \
80879746Sgad	astr = xStr; \
80979746Sgad	ctl_dbgline++; \
81079746Sgad	fprintf(dbg_stream, "%4d] %12s = ", ctl_dbgline, xHdr); \
81179746Sgad	if (astr == NULL) \
81279746Sgad		fprintf(dbg_stream, "NULL\n"); \
81379746Sgad	else \
81479746Sgad		fprintf(dbg_stream, "%p -> %s\n", astr, astr)
81579746Sgad
81679746Sgad	struct cjprivate *cpriv;
81779746Sgad	char *astr;
81879746Sgad
81979746Sgad	if (cjinf == NULL) {
82079746Sgad		fprintf(dbg_stream,
82179746Sgad		    "ctl_dumpcji: ptr to cjobinfo for '%s' is NULL\n",
82279746Sgad		    heading);
82379746Sgad		return;
82479746Sgad	}
82579746Sgad	cpriv = cjinf->cji_priv;
82679746Sgad
82779746Sgad	fprintf(dbg_stream, "ctl_dumpcji: Dump '%s' of cjobinfo at %p->%p\n",
82895429Sgad	    heading, (void *)cjinf, cpriv->cji_buff);
82979746Sgad
83079746Sgad	PRINTSTR("accthost.H", cpriv->pub.cji_accthost);
83179746Sgad	PRINTSTR("acctuser.P", cpriv->pub.cji_acctuser);
83279746Sgad	PRINTSTR("class.C", cpriv->pub.cji_class);
83379746Sgad	PRINTSTR("cf-qname", cpriv->pub.cji_curqueue);
83479746Sgad	PRINTSTR("cf-fname", cpriv->pub.cji_fname);
83579746Sgad	PRINTSTR("jobname.J", cpriv->pub.cji_jobname);
83679746Sgad	PRINTSTR("mailto.M", cpriv->pub.cji_mailto);
837220586Sgad	PRINTSTR("headruser.L", cpriv->pub.cji_headruser);
83879746Sgad
83979746Sgad	ctl_dbgline++;
84079746Sgad	fprintf(dbg_stream, "%4d] %12s = ", ctl_dbgline, "*cjprivate");
84179746Sgad	if (cpriv->pub.cji_priv == NULL)
84279746Sgad		fprintf(dbg_stream, "NULL !!\n");
84379746Sgad	else
84495429Sgad		fprintf(dbg_stream, "%p\n", (void *)cpriv->pub.cji_priv);
84579746Sgad
84679746Sgad	fprintf(dbg_stream, "|- - - - --> Dump '%s' complete\n", heading);
84779746Sgad
84879746Sgad	/* flush output for the benefit of anyone doing a 'tail -f' */
84979746Sgad	fflush(dbg_stream);
85079746Sgad
85179746Sgad#undef PRINTSTR
85279746Sgad}
85379746Sgad
85479746Sgad/*
85579746Sgad * This routine reads in the next line from the control-file, and removes
85679746Sgad * the trailing newline character.
85779746Sgad *
85879746Sgad * Historical note: Earlier versions of this routine did tab-expansion for
85979746Sgad * ALL lines read in, which did not make any sense for most of the lines
86079746Sgad * in a control file.  For the lines where tab-expansion is useful, it will
86179746Sgad * now have to be done by the calling routine.
86279746Sgad */
86379746Sgadstatic char *
86479746Sgadctl_getline(struct cjobinfo *cjinf)
86579746Sgad{
86679746Sgad	char *strp, *nl;
86779746Sgad	struct cjprivate *cpriv;
86879746Sgad
86979746Sgad	if (cjinf == NULL)
87079746Sgad		return NULL;
87179746Sgad	cpriv = cjinf->cji_priv;
87279746Sgad	if ((cpriv == NULL) || (cpriv != cpriv->pub.cji_priv)) {
87379746Sgad		syslog(LOG_ERR, "in ctl_getline(%p): invalid cjinf (cpriv %p)",
87495429Sgad		    (void *)cjinf, (void *)cpriv);
87579746Sgad		return NULL;
87679746Sgad	}
87779746Sgad
87879746Sgad	errno = 0;
87979746Sgad	strp = fgets(cpriv->cji_buff, cpriv->cji_buffsize, cpriv->cji_fstream);
88079746Sgad	if (strp == NULL) {
88179746Sgad		if (errno != 0)
88279746Sgad			syslog(LOG_ERR, "%s: ctl_getline error fgets(%s): %s",
88379746Sgad			    cpriv->pub.cji_curqueue, cpriv->pub.cji_fname,
88479746Sgad			    strerror(errno));
88579746Sgad		return NULL;
88679746Sgad	}
88779746Sgad	nl = strchr(strp, '\n');
88879746Sgad	if (nl != NULL)
88979746Sgad		*nl = '\0';
89079746Sgad
89179746Sgad#ifdef DEBUGREADCF_FNAME
89279746Sgad	/* I'd like to find out if the previous work to expand tabs was ever
89379746Sgad	 * really used, and if so, on what lines and for what reason.
89479746Sgad	 * Yes, all this work probably means I'm obsessed about this 'tab'
89579746Sgad	 * issue, but isn't programming a matter of obsession?
89679746Sgad	 */
89779746Sgad	{
89879746Sgad		int tabcnt;
89979746Sgad		char *ch;
90079746Sgad
90179746Sgad		tabcnt = 0;
90279746Sgad		ch = strp;
90379746Sgad		for (ch = strp; *ch != '\0'; ch++) {
90479746Sgad			if (*ch == '\t')
90579746Sgad				tabcnt++;
90679746Sgad		}
90779746Sgad
90879746Sgad		if (tabcnt && (ctl_dbgfile != NULL)) {
90979746Sgad			cpriv->cji_dumpit++;
91079746Sgad			fprintf(ctl_dbgfile, "%s: tabs=%d '%s'\n",
91179746Sgad			    cpriv->pub.cji_fname, tabcnt, cpriv->cji_buff);
91279746Sgad		}
91379746Sgad	}
91479746Sgad#endif
91579746Sgad	return strp;
91679746Sgad}
917