/*
**++
**  FACILITY:
**      NEWSUTIL3
**
**  ABSTRACT:
**      This module contain common support routines used by all other modules
**      of NEWS *and* NNTP_SERVER.
**
**  VERSION:
**	V6.1b10 11-Sep-1996	Mark Martinec   mark.martinec@ijs.si
**	  - rewrite gen_id() to generate a non-talking unique message id
**	    and to avoid reading record #1 of groups file where
**	    an undocumented field was used as a sequence number.
**	    Now works the same for NNTP client and full ANU server.
**	V6.1b10 12-Sep-1996	Mark Martinec   mark.martinec@ijs.si
**	  - split module NEWSUTILITY.C into NEWSUTIL[1,2,3].C
**	    because of its size (4800 lines) which made testing tedious.
**	    Also split revision history comments.
**	    NEWSUTIL1 - handles mostly application code, file i/o,
**	                groups and items-related data structures, NNTP, ...
**	    NEWSUTIL2 - more general-purpose routines, formatting,
**	                SMG, error handling, ...
**	    NEWSUTIL3 - support routines needed by NEWS and NNTP_SERVER
**	                (like gen_id() and its support routines)
**--
**/

#ifdef vaxc
#module NEWSUTIL3 "V6.2"
#endif

#define _NEWSUTIL3_C
#define module_name "NEWSUTIL3"

#include "newsinclude.h"
#include "newsextern.h"

#include "md5.h"


/*
 * This is a simplified version of base64 encoding with the modification
 * that instead of '/' (strongly discouraged by RFC1036) we use '$'.
 *
 * It only handles strings of inp_l bytes where inp_l is a multiple of 3.
 * Output buffer must hold space for at least inp_l/3*4 + 1 characters.
 * The '\0'-terminated resulting string is stored in the caller's buffer.
 * Function returns the output string length.
 *
 * The code is stolen from the GNU uuencode and adapted.
 */
int base64_encode(const unsigned char *inp, int inp_l, char *out)
{ static const char uu_base64[64] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
    'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
    'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
    'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
    'w', 'x', 'y', 'z', '0', '1', '2', '3',
    '4', '5', '6', '7', '8', '9', '+', '$'
  };
  const unsigned char *p;
  int out_l = 0;
  unsigned char ch;

  for (p = inp; inp_l > 2; inp_l -= 3, p += 3) {
    ch = *p >> 2;
    out[out_l++] = uu_base64[ch & 077];
    ch = ((*p << 4) & 060) | ((p[1] >> 4) & 017);
    ch = uu_base64[ch & 077];
    out[out_l++] = ch;
    ch = ((p[1] << 2) & 074) | ((p[2] >> 6) & 03);
    out[out_l++] = uu_base64[ch & 077];
    ch = p[2] & 077;
    out[out_l++] = uu_base64[ch & 077];
    }
  out[out_l] = '\0';  return out_l;
}

/*
 * Test the message digest function md5_buffer() on a known string.
 */
int test_md5()
{
  static const unsigned char test_md5buffer[16] = {
    0x79, 0xC2, 0x54, 0x07, 0xEC, 0x57, 0xA1, 0xA2,
    0xC0, 0x13, 0x01, 0xC6, 0xFD, 0xB1, 0x22, 0xB5 };
  static const char test_string[] = "This is a *TEST* string +0123+ !!!";
  unsigned char md5buffer[16];
  int cnt, ok=1;

  md5_buffer(test_string, strlen(test_string), md5buffer);
  for (cnt = 0; cnt < 16; ++cnt)
    if (md5buffer[cnt] != test_md5buffer[cnt]) ok = 0;
  if (!ok) printf("MD5 test failed!\n");
  return ok;
}

/*
 * Collect random environmental noise, digest it into a 128-bit number
 * and returns it in the caller-provided 16-byte buffer.
 */
void get_environment_noise(unsigned char *md5buffer)
{ unsigned short iosb[4];
  char timbuf[8];
  int status;
  static char str[60+8];
  static const struct {
    unsigned short buflen;
    unsigned short itmcod;
    void           *bufadr;
    unsigned short *retlen; } jpilst[13] = {
      {4, JPI$_PID,       &str[ 0], 0},
      {4, JPI$_BUFIO,     &str[ 4], 0},
      {4, JPI$_DIRIO,     &str[ 8], 0},
      {4, JPI$_PAGFILCNT, &str[12], 0},
      {4, JPI$_PAGEFLTS,  &str[16], 0},
      {4, JPI$_PPGCNT,    &str[20], 0},
      {4, JPI$_FREPTECNT, &str[24], 0},
      {4, JPI$_FREP0VA,   &str[28], 0},
      {4, JPI$_PAGFILLOC, &str[32], 0},
      {4, JPI$_CPUTIM,    &str[36], 0},
      {8, JPI$_LOGINTIM,  &str[40], 0},
      {12,JPI$_USERNAME,  &str[48], 0},
      {0,0,0,0}             /* 60 */
    };
  _c$cks(sys$getjpiw(0,0,0,jpilst,iosb,0,0));
  _c$cks(iosb[0]);
  _c$cks(sys$gettim(timbuf));
  memcpy(&str[60],timbuf,8);
  md5_buffer(str, sizeof(str), md5buffer);    /* digest into a 128-bit number */
}

/*
 *  gen_id
 *
 *  Generate a unique message id of the form <num@internet.address> ;
 *  Num is 21-character string collected from environment noise.
 *  Returns a pointer to the statically allocated string.
 */
char *gen_id()
{
  unsigned char md5buffer[16];
  char out[9/3*4 + 1];    /* resulting 12-char string of base64 encoded bytes */
  static char genid[IDLEN];

  get_environment_noise(md5buffer);
  (void) base64_encode(md5buffer,9,out);  /* take only the first 9*8= 72 bits */
  sprintf(genid,"<%s@%.*s>", out, (IDLEN-1)-2-12-1, news_node);
  return genid;
}
