/*
 * Usenet header parsing and remembering.
 */

#include <stdio.h>
#include <ctype.h>
#ifndef AMIGA
#  include <sys/types.h>
#endif /* AMIGA */
#include "libc.h"
#include "news.h"
#include "headers.h"
#include "hdrint.h"

/*
 * Reset internal state of header parser.
 * (Empty the stomach of partially-digested headers.)
 */
void
hdrwretch()
{
	/* historical stub */
}

/*
 * Parse RFC822/850/1036 header into "hdrs".  Retain significant values.
 * Assumes ishdr has been called first.
 *
 * If a keyword matches one in hdrlst, store the value in *malloc'ed memory*
 * (N.B.).  freeheader() will free this memory.
 */

void hdrparse(hdrs, line, hdrlst)
register struct headers *hdrs;
register char *line;
struct hdrdef *hdrlst[];			/* headers of positive utility */
{
	register struct hdrdef **hpp;

	for (hpp = hdrlst; *hpp != NULL; hpp++)
		if (STREQN(line, (*hpp)->hdrnm, (int)(*hpp)->hdrlen) &&
			    (*hpp)->hdroff >= 0) {	/* paranoia */
			register char **ptrp = (char **)((char *)hdrs+(*hpp)->hdroff);

			nnfree(ptrp);	/* free prev. val. in this art. */
			*ptrp = strsave(skipsp(&line[(*hpp)->hdrlen]));
			if (*ptrp != NULL)
				trim(*ptrp);	/* cut trailing \n */
			break;
		}
}

/*
 * default missing header values
 *
 * If strsave ever returns NULL on failure, instead of exiting,
 * then the strsave calls need to check for failure.
 *
 * We support control message *backwards* compatibility: if no Control:
 * header exists and the newsgroup matches all.all.ctl, use the Subject:
 * as the control message.  Ugh.
 */

void hdrdeflt(hdrs)
register struct headers *hdrs;
{
	if (hdrs->h_ngs == NULL)
		hdrs->h_ngs = strsave(JUNK);
	if (hdrs->h_distr == NULL)
		hdrs->h_distr = strsave(DEFDIST);
	if (hdrs->h_msgid == NULL && hdrs->h_artid != NULL)	/* obs. art.id. */
		hdrs->h_msgid = strsave(hdrs->h_artid);
	if (hdrs->h_msgid == NULL)
		hdrs->h_msgid = strsave(DEFMSGID);
	if (hdrs->h_msgid[0] == '\0') {
		free(hdrs->h_msgid);
		hdrs->h_msgid = strsave(DEFMSGID);
	}
	if (hdrs->h_expiry == NULL)
		hdrs->h_expiry = strsave(DEFEXP);
	if (hdrs->h_expiry[0] == '\0') {
		free(hdrs->h_expiry);
		hdrs->h_expiry = strsave(DEFEXP);
	}
	if (hdrs->h_subj == NULL)
		hdrs->h_subj = strsave("");

	if (hdrs->h_ctlcmd == NULL && oldctl(hdrs))
		hdrs->h_ctlcmd = strsave(hdrs->h_subj);
}
