
/*
Eagles Bulletin Board System
Copyright (C) 1994, Ray Rocker, rrrocker@rock.b11.ingr.com
                                rock@seabass.st.usm.edu
                                72673.2105@compuserve.com

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "server.h"
#include <ctype.h>

/* For the bbs name and tempfile */
extern SERVERDATA server;

is_valid_address(addr)
char *addr;
{
  if (*addr == '\0') return 0;   /* blank */
  while (*addr) {
    if (!isalnum(*addr) && strchr(".%!@:;-_+[]", *addr) == NULL)
      return 0;
    addr++;
  }
  return 1;
}

LONG
mail_file_to_outside(fname, title, is_binary)
char *fname;
char *title;
int is_binary;
{
  FILE *fp;
  ACCOUNT acct;
  PATH execbuf;
  int rc;
  char *base;

  if ((fp = fopen(fname, "r")) == NULL) return S_NOTFOUND;
  fclose(fp);

  if (local_bbs_owninfo(&acct) != S_OK) return S_SYSERR;

  if (!is_valid_address(acct.email)) return S_INVALID;

  if ((fp = fopen(server.tempfile, "w")) == NULL) return S_SYSERR;

  /* Write headers! */
  fprintf(fp, "Subject: %s (fwd)\n", title);
  fprintf(fp, "To: %s\n", acct.email);
  fprintf(fp, "X-Forwarded-By: %s (%s)\n", acct.userid, acct.username);
  fprintf(fp, "X-Disclaimer: %s is not responsible for the contents of this message.\n", server.name);  

  fprintf(fp, "\n*** Forwarded file follows ***\n\n");

  fflush(fp);
  if (is_binary) {
    fclose(fp);
    base = strrchr(fname, '/');
    if (base) base++;
    else base = fname;
    strcpy(execbuf, server.encodebin);
    strcat(execbuf, " ");
    strcat(execbuf, base);
    rc = execute(execbuf, NULL, fname, server.tempfile, "/dev/null", NULL, 1);
  }
  else {
    rc = append_file(fileno(fp), fname);
    fclose(fp);
  }
  
  if (rc != 0) {
    unlink(server.tempfile);
    return S_SYSERR;
  }

  strcpy(execbuf, server.mailbin);
  strcat(execbuf, " ");
  strcat(execbuf, acct.email);

  bbslog(3, "FORWARD '%s' to %s by %s\n", title, acct.email, acct.userid);

  rc = execute(execbuf, NULL, server.tempfile, "/dev/null", "/dev/null", NULL);

  unlink(server.tempfile);
  return (rc == 0 ? S_OK : S_SYSERR);
}
