/*
 *  Do the function
 */
int main(int argc, char **argv) {

    /* Parse arguments */
    parseargs(argc, argv);

    /* Open the afm file */
    openafm();

    /* Create pfm in memory */
    initpfm();
    makeheader();
    makeextent();
    makekern();
    makecomposites();
    maketrailer();

    /* write out pfm from memory to file */
    writepfm();

    if (nbuffer)
	free(nbuffer);
    fclose(inf);
    fclose(outf);
    return 0;
}
Example #2
0
/*
 * Edit the message being collected on fp.
 * On return, make the edit file the new temp file.
 */
static void 
mesedit(int c, struct header *hp)
{
	sighandler_type sigint = safe_signal(SIGINT, SIG_IGN);
	FILE *nf = run_editor(collf, (off_t)-1, c, 0, hp, NULL, SEND_MBOX,
			sigint);

	if (nf != NULL) {
		if (hp) {
			rewind(nf);
			makeheader(nf, hp);
		} else {
			fseek(nf, 0L, SEEK_END);
			Fclose(collf);
			collf = nf;
		}
	}
	safe_signal(SIGINT, sigint);
}
Example #3
0
/*



   addrの値は、 htonl後の値である。


   return values:
   0 OK
   <0 Error

   uprocは、何かパケットがきたら返り値でしらせるので、
   uprocが何かうけとるたびにテストして、ackがきたらconnect成功、
   というようにしなければならない。ブロックする。
   
*/
int uconnect( int fd , unsigned long addr )
{

	int sr;
	char tmpdata[HEADERSIZE];

	CHECKFD(fd);

	/* 自分の設定をする */
	stb[fd].addr_dest = addr;
	
	/* connect用のパケットを送信。ヘッダのみ */
	makeheader( tmpdata, 
			   0 ,	/* seq */
			   ACK_NOUSE ,	/* ack */
			   0 ,	/* rst */
			   1 ,	/* syn */
			   0 ,	/* fin */
			   0 ,	/* ref */
			   0 	/* len */
	);
	sender( tmpdata, HEADERSIZE , addr );


	if( sr < 0 ){
		/* errnoはセットされてる */
		return -1;
	}

	/* ブロックして、返事がくるまで待つ */
	while(1){
		usleep(100*1000);
		fprintf( stderr, "c ");
		if( uproc() > 0 ){
			if( issockinited( fd ) ){
				break;
			}
		}
	}
	
	udptcp.errno = 0;
	return 0;
}
Example #4
0
FILE *
collect(struct header *hp, int printheaders, struct message *mp,
		char *quotefile, int doprefix, int tflag)
{
	FILE *fbuf;
	struct ignoretab *quoteig;
	int lc, cc, escape, eofcount;
	int c, t;
	char *linebuf = NULL, *cp, *quote = NULL;
	size_t linesize;
	char *tempMail = NULL;
	int getfields;
	sigset_t oset, nset;
	long count;
	enum sendaction	action;
	sighandler_type	savedtop;
	const char tildehelp[] =
"-------------------- ~ ESCAPES ----------------------------\n\
~~              Quote a single tilde\n\
~@ [file ...]   Edit attachment list\n\
~b users        Add users to \"blind\" cc list\n\
~c users        Add users to cc list\n\
~d              Read in dead.letter\n\
~e              Edit the message buffer\n\
~f messages     Read in messages without indenting lines\n\
~F messages     Same as ~f, but keep all header lines\n\
~h              Prompt for to list, subject, cc, and \"blind\" cc list\n\
~r file         Read a file into the message buffer\n\
~p              Print the message buffer\n\
~q              Abort message composition and save text to dead.letter\n\
~m messages     Read in messages with each line indented\n\
~M messages     Same as ~m, but keep all header lines\n\
~s subject      Set subject\n\
~t users        Add users to to list\n\
~v              Invoke display editor on message\n\
~w file         Write message onto file\n\
~x              Abort message composition and discard text written so far\n\
~!command       Invoke the shell\n\
~:command       Execute a regular command\n\
-----------------------------------------------------------\n";

	(void) &escape;
	(void) &eofcount;
	(void) &getfields;
	(void) &tempMail;
	(void) &tflag;
	(void) &quote;

	collf = NULL;
	/*
	 * Start catching signals from here, but we're still die on interrupts
	 * until we're in the main loop.
	 */
	sigemptyset(&nset);
	sigaddset(&nset, SIGINT);
	sigaddset(&nset, SIGHUP);
	sigprocmask(SIG_BLOCK, &nset, &oset);
	handlerpush(collint);
	if ((saveint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
		safe_signal(SIGINT, collint);
	if ((savehup = safe_signal(SIGHUP, SIG_IGN)) != SIG_IGN)
		safe_signal(SIGHUP, collhup);
	savetstp = safe_signal(SIGTSTP, collstop);
	savettou = safe_signal(SIGTTOU, collstop);
	savettin = safe_signal(SIGTTIN, collstop);
	if (sigsetjmp(collabort, 1)) {
		if (tempMail != NULL) {
			rm(tempMail);
			Ftfree(&tempMail);
		}
		goto err;
	}
	if (sigsetjmp(colljmp, 1)) {
		if (tempMail != NULL) {
			rm(tempMail);
			Ftfree(&tempMail);
		}
		goto err;
	}
	sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);

	noreset++;
	if ((collf = Ftemp(&tempMail, "Rs", "w+", 0600, 1)) == NULL) {
		perror(catgets(catd, CATSET, 51, "temporary mail file"));
		goto err;
	}
	unlink(tempMail);
	Ftfree(&tempMail);

	if ((cp = value("MAILX_HEAD")) != NULL) {
		if (is_a_tty[0])
			putesc(cp, stdout);
		putesc(cp, collf);
	}

	/*
	 * If we are going to prompt for a subject,
	 * refrain from printing a newline after
	 * the headers (since some people mind).
	 */
	getfields = 0;
	if (!tflag) {
		t = GTO|GSUBJECT|GCC|GNL;
		if (value("fullnames"))
			t |= GCOMMA;
		if (hp->h_subject == NULL && value("interactive") != NULL &&
			    (value("ask") != NULL || value("asksub") != NULL))
			t &= ~GNL, getfields |= GSUBJECT;
		if (hp->h_to == NULL && value("interactive") != NULL)
			t &= ~GNL, getfields |= GTO;
		if (value("bsdcompat") == NULL && value("askatend") == NULL &&
				value("interactive")) {
			if (hp->h_bcc == NULL && value("askbcc"))
				t &= ~GNL, getfields |= GBCC;
			if (hp->h_cc == NULL && value("askcc"))
				t &= ~GNL, getfields |= GCC;
		}
		if (printheaders) {
			puthead(hp, stdout, t, SEND_TODISP, CONV_NONE,
					NULL, NULL);
			fflush(stdout);
		}
	}

	/*
	 * Quote an original message
	 */
	if (mp != NULL && (doprefix || (quote = value("quote")) != NULL)) {
		quoteig = allignore;
		action = SEND_QUOTE;
		if (doprefix) {
			quoteig = fwdignore;
			if ((cp = value("fwdheading")) == NULL)
				cp = "-------- Original Message --------";
			if (*cp) {
				fprintf(collf, "%s\n", cp);
				fprintf(stdout, "%s\n", cp);
			}
		} else if (strcmp(quote, "noheading") == 0) {
			/*EMPTY*/;
		} else if (strcmp(quote, "headers") == 0) {
			quoteig = ignore;
		} else if (strcmp(quote, "allheaders") == 0) {
			quoteig = NULL;
			action = SEND_QUOTE_ALL;
		} else {
			cp = hfield("from", mp);
			if (cp != NULL) {
				mime_write(cp, strlen(cp),
						collf, CONV_FROMHDR, TD_NONE,
						NULL, (size_t) 0,
						NULL, NULL);
				mime_write(cp, strlen(cp),
						stdout, CONV_FROMHDR, TD_NONE,
						NULL, (size_t) 0,
						NULL, NULL);
				fwrite(catgets(catd, CATSET, 52,
					" wrote:\n\n"), sizeof(char), 9, collf);
				fwrite(catgets(catd, CATSET, 52,
					" wrote:\n\n"), sizeof(char), 9, stdout);
			}
		}
		cp = value("indentprefix");
		if (cp != NULL && *cp == '\0')
			cp = "\t";
		send(mp, collf, quoteig, doprefix ? NULL : cp, action, NULL);
		send(mp, stdout, quoteig, doprefix ? NULL : cp, action, NULL);
	}

	if ((cp = value("escape")) != NULL)
		escape = *cp;
	else
		escape = ESCAPE;
	eofcount = 0;
	hadintr = 0;

	if (!sigsetjmp(colljmp, 1)) {
		if (getfields)
			grabh(hp, getfields, 1);
		if (quotefile != NULL) {
			if (include_file(NULL, quotefile, &lc, &cc, 1) != 0)
				goto err;
		}
	} else {
		/*
		 * Come here for printing the after-signal message.
		 * Duplicate messages won't be printed because
		 * the write is aborted if we get a SIGTTOU.
		 */
cont:
		if (hadintr) {
			fflush(stdout);
			fprintf(stderr, catgets(catd, CATSET, 53,
				"\n(Interrupt -- one more to kill letter)\n"));
		} else {
			printf(catgets(catd, CATSET, 54, "(continue)\n"));
			fflush(stdout);
		}
	}
	if (value("interactive") == NULL && tildeflag <= 0 && !is_a_tty[0] &&
			!tflag) {
		/*
		 * No tilde escapes, interrupts not expected. Copy
		 * standard input the simple way.
		 */
		linebuf = srealloc(linebuf, linesize = BUFSIZ);
		while ((count = fread(linebuf, sizeof *linebuf,
						linesize, stdin)) > 0) {
			if (fwrite(linebuf, sizeof *linebuf,
						count, collf) != count)
				goto err;
		}
		goto out;
	}
	for (;;) {
		colljmp_p = 1;
		count = readline(stdin, &linebuf, &linesize);
		colljmp_p = 0;
		if (count < 0) {
			if (value("interactive") != NULL &&
			    value("ignoreeof") != NULL && ++eofcount < 25) {
				printf(catgets(catd, CATSET, 55,
					"Use \".\" to terminate letter\n"));
				continue;
			}
			break;
		}
		if (tflag && count == 0) {
			rewind(collf);
			if (makeheader(collf, hp) != OKAY)
				goto err;
			rewind(collf);
			tflag = 0;
			continue;
		}
		eofcount = 0;
		hadintr = 0;
		if (linebuf[0] == '.' && linebuf[1] == '\0' &&
		    value("interactive") != NULL &&
		    (value("dot") != NULL || value("ignoreeof") != NULL))
			break;
		if (linebuf[0] != escape || (value("interactive") == NULL &&
					tildeflag == 0 ||
					tildeflag < 0)) {
			if (putline(collf, linebuf, count) < 0)
				goto err;
			continue;
		}
		c = linebuf[1];
		switch (c) {
		default:
			/*
			 * On double escape, just send the single one.
			 * Otherwise, it's an error.
			 */
			if (c == escape) {
				if (putline(collf, &linebuf[1], count - 1) < 0)
					goto err;
				else
					break;
			}
			printf(catgets(catd, CATSET, 56,
					"Unknown tilde escape.\n"));
			break;
#ifdef	DEBUG_COMMANDS
		case 'C':
			/*
			 * Dump core.
			 */
			core(NULL);
			break;
#endif	/* DEBUG_COMMANDS */
		case '!':
			/*
			 * Shell escape, send the balance of the
			 * line to sh -c.
			 */
			shell(&linebuf[2]);
			break;
		case ':':
		case '_':
			/*
			 * Escape to command mode, but be nice!
			 */
			inhook = 0;
			execute(&linebuf[2], 1, count - 2);
			goto cont;
		case '.':
			/*
			 * Simulate end of file on input.
			 */
			goto out;
		case 'x':
			/*
			 * Same as 'q', but no dead.letter saving.
			 */
			hadintr++;
			collint(0);
			exit(1);
			/*NOTREACHED*/
		case 'q':
			/*
			 * Force a quit of sending mail.
			 * Act like an interrupt happened.
			 */
			hadintr++;
			collint(SIGINT);
			exit(1);
			/*NOTREACHED*/
		case 'h':
			/*
			 * Grab a bunch of headers.
			 */
			do
				grabh(hp, GTO|GSUBJECT|GCC|GBCC,
						value("bsdcompat") != NULL &&
						value("bsdorder") != NULL);
			while (hp->h_to == NULL);
			goto cont;
		case 'H':
			/*
			 * Grab extra headers.
			 */
			do
				grabh(hp, GEXTRA, 0);
			while (check_from_and_sender(hp->h_from, hp->h_sender));
			goto cont;
		case 't':
			/*
			 * Add to the To list.
			 */
			while ((hp->h_to = checkaddrs(cat(hp->h_to,
					sextract(&linebuf[2], GTO|GFULL))))
				== NULL);
			break;
		case 's':
			/*
			 * Set the Subject list.
			 */
			cp = &linebuf[2];
			while (whitechar(*cp & 0377))
				cp++;
			hp->h_subject = savestr(cp);
			break;
		case '@':
			/*
			 * Edit the attachment list.
			 */
			if (linebuf[2] != '\0')
				hp->h_attach = append_attachments(hp->h_attach,
						&linebuf[2]);
			else
				hp->h_attach = edit_attachments(hp->h_attach);
			break;
		case 'c':
			/*
			 * Add to the CC list.
			 */
			hp->h_cc = checkaddrs(cat(hp->h_cc,
				sextract(&linebuf[2], GCC|GFULL)));
			break;
		case 'b':
			/*
			 * Add stuff to blind carbon copies list.
			 */
			hp->h_bcc = checkaddrs(cat(hp->h_bcc,
				sextract(&linebuf[2], GBCC|GFULL)));
			break;
		case 'd':
			strncpy(linebuf + 2, getdeadletter(), linesize - 2);
			linebuf[linesize-1]='\0';
			/*FALLTHRU*/
		case 'r':
		case '<':
			/*
			 * Invoke a file:
			 * Search for the file name,
			 * then open it and copy the contents to collf.
			 */
			cp = &linebuf[2];
			while (whitechar(*cp & 0377))
				cp++;
			if (*cp == '\0') {
				printf(catgets(catd, CATSET, 57,
						"Interpolate what file?\n"));
				break;
			}
			if (*cp == '!') {
				insertcommand(collf, cp + 1);
				break;
			}
			cp = expand(cp);
			if (cp == NULL)
				break;
			if (is_dir(cp)) {
				printf(catgets(catd, CATSET, 58,
						"%s: Directory\n"), cp);
				break;
			}
			if ((fbuf = Fopen(cp, "r")) == NULL) {
				perror(cp);
				break;
			}
			printf(catgets(catd, CATSET, 59, "\"%s\" "), cp);
			fflush(stdout);
			if (include_file(fbuf, cp, &lc, &cc, 0) != 0)
				goto err;
			printf(catgets(catd, CATSET, 60, "%d/%d\n"), lc, cc);
			break;
		case 'i':
			/*
			 * Insert an environment variable into the file.
			 */
			cp = &linebuf[2];
			while (whitechar(*cp & 0377))
				cp++;
			if ((cp = value(cp)) == NULL || *cp == '\0')
				break;
			if (is_a_tty[0])
				putesc(cp, stdout);
			putesc(cp, collf);
			break;
		case 'a':
		case 'A':
			/*
			 * Insert the contents of a signature variable.
			 */
			if ((cp = value(c == 'a' ? "sign" : "Sign")) != NULL &&
					*cp != '\0') {
				if (is_a_tty[0])
					putesc(cp, stdout);
				putesc(cp, collf);
			}
			break;
		case 'w':
			/*
			 * Write the message on a file.
			 */
			cp = &linebuf[2];
			while (blankchar(*cp & 0377))
				cp++;
			if (*cp == '\0') {
				fprintf(stderr, catgets(catd, CATSET, 61,
						"Write what file!?\n"));
				break;
			}
			if ((cp = expand(cp)) == NULL)
				break;
			rewind(collf);
			exwrite(cp, collf, 1);
			break;
		case 'm':
		case 'M':
		case 'f':
		case 'F':
			/*
			 * Interpolate the named messages, if we
			 * are in receiving mail mode.  Does the
			 * standard list processing garbage.
			 * If ~f is given, we don't shift over.
			 */
			if (forward(linebuf + 2, collf, c) < 0)
				goto err;
			goto cont;
		case '?':
			fputs(tildehelp, stdout);
			break;
		case 'p':
			/*
			 * Print out the current state of the
			 * message without altering anything.
			 */
			print_collf(collf, hp);
			goto cont;
		case '|':
			/*
			 * Pipe message through command.
			 * Collect output as new message.
			 */
			rewind(collf);
			mespipe(&linebuf[2]);
			goto cont;
		case 'v':
		case 'e':
			/*
			 * Edit the current message.
			 * 'e' means to use EDITOR
			 * 'v' means to use VISUAL
			 */
			rewind(collf);
			mesedit(c, value("editheaders") ? hp : NULL);
			goto cont;
		}
	}
	goto out;
err:
	if (collf != NULL) {
		Fclose(collf);
		collf = NULL;
	}
out:
	if (collf != NULL) {
		if ((cp = value("MAILX_TAIL")) != NULL) {
			if (is_a_tty[0])
				putesc(cp, stdout);
			fflush(collf);
			putesc(cp, collf);
		}
		rewind(collf);
	}
	handlerpop();
	noreset--;
	sigemptyset(&nset);
	sigaddset(&nset, SIGINT);
	sigaddset(&nset, SIGHUP);
#ifndef OLDBUG
	sigprocmask(SIG_BLOCK, &nset, (sigset_t *)NULL);
#else
	sigprocmask(SIG_BLOCK, &nset, &oset);
#endif
	safe_signal(SIGINT, saveint);
	safe_signal(SIGHUP, savehup);
	safe_signal(SIGTSTP, savetstp);
	safe_signal(SIGTTOU, savettou);
	safe_signal(SIGTTIN, savettin);
	sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
	return collf;
}
Example #5
0
int mbtransfer (char *ziel)
//*************************************************************************
//
//  TRANSFER-Prozedur
//  (wird fuer jedes transferierte File einzeln aufgerufen)
//
//*************************************************************************
{
  char name[20];
  strcpy(name, "mbtransfer");
  lastfunc(name);
  char *line = b->line;
  int findex;
  FILE *oldf, *newf;
  char usermail = 0;
  int retwert = NO;
  int nocp; //no-copy flag
  char oldsubject[101];
  unsigned long int oldfpos;
  char oldmsgty;
  char oldmailfname[10];
  time_t oldmsgtime;
  char old_ziel[DIRLEN+1];
  int old_usermail;
  char oldboardname[10];
  char oldmailpath[FNAMELEN+1];
  char zielcall[CALLEN+1];
  char newcall[CALLEN+1];
  int gleichesboard = NO;
  unsigned long nummer;
#ifdef USERLT
  short int old_lt;
#endif

#ifdef DEBUG_FWD
  trace(report, "mbtransfer", "ziel: %s", ziel);
#endif
  strupr(ziel);

  nexttoken(ziel, zielcall, CALLEN);
  strcpy(oldmailpath, b->mailpath);
  if (sema_test("sendlock") || m.disable)
  {
    putf(ms(m_sendnotpossible));
    return NO;
  }
  if (mbcallok(zielcall))
  { // Use newcall
    if (get_newcall(zielcall, newcall))
    {
      strcpy(zielcall, newcall);
      putf(ms(m_usingnewcall), newcall);
    }
  }
  char *bbuf = (char *) t_malloc(sizeof(tvar_t) - sizeof(task_t), "tran");
  char *oldfname;
  oldfname = (char *) t_malloc(sizeof(char) * (FNAMELEN+1), "tra2");
  if (! bbuf || ! oldfname)
    return NO;
  memcpy(bbuf, (char *) b + sizeof(task_t), sizeof(tvar_t) - sizeof(task_t));
  strlwr(b->mailpath);
  strcpy(oldfname, b->mailpath);
  strcpy(oldmailfname, b->mailfname);
  oldmsgtime = filename2time(b->mailfname);
  if ((oldf = s_fopen(oldfname, "srt")) != NULL)
  {
    fgets(b->line, BUFLEN - 1, oldf);    // Befehlszeile einlesen
    mbsend_parse(line, 0);
    if (b->mailtype == 'A'
        || (b->mailtype == 'B' && b->eraseinfo == 'T'))
    {
      retwert = NIL;
      s_fclose(oldf);
      goto error_exit;
    }
    oldmsgty = b->conttype;              // save mailflags ...(conttype)
    fgets(b->line, BUFLEN - 1, oldf);    // Forwardzeile vernichten
    fgets(b->line, BUFLEN - 1, oldf);    // Read-Zeile
    fgets(oldsubject, BETREFFLEN, oldf); // Betreff
    cut_blank(oldsubject);               // Newline entfernen
    if (mbcallok(zielcall)) *b->at = 0;  // Verteiler loeschen -> Neubestimmen
    strcpy(old_ziel, b->ziel);
#ifdef USERLT
    old_lt = b->lifetime;
    b->lifetime = 0;
#endif
    old_usermail = b->usermail;
    mbsend_parse(ziel, 2);
    if (! stricmp(b->ziel, b->mailpath+strlen(b->mailpath)-strlen(b->ziel)-8))
    {
      retwert = NIL;
      s_fclose(oldf);
      goto error_exit;
    }
    b->conttype = oldmsgty;              // set mailflags again.. (conttype)
    if (b->mailtype == 'B' && ! old_usermail)
      strcpy(b->ziel, old_ziel);
    weiterleiten(1, b->zielboard);
    waitfor(e_ticsfull);
    findex = finddir(b->zielboard, b->sysop);
    if (findex && !(strlen(b->zielboard)==1 && !b->sysop))
    {
      if (xmkdir(b->boardpath))
      {
        trace(serious, name, "mkdir %s error", b->boardpath);
        s_fclose(oldf);
        goto error_exit;
      }
      nocp = ! strcmp(b->herkunft, b->logincall) || b->sysop;
             //kein "CP " wenn Sysop!
      if (nocp || b->mailtype == 'B')
        strcpy(b->betreff, oldsubject);
      else
        sprintf(b->betreff, "CP %s: %.67s", b->logincall, oldsubject);
      //Bei Nicht-Bulletin BID neu generieren bzw. wenn BID fehlt
      if (b->mailtype != 'B'|| ! *b->bid) strcpy(b->bid, newbid());
      make_mask(b->mailpath, b->boardfullname);
      strcpy(b->mask, b->mailpath);
      // Ursprungsboardnamen aus b->mailpath holen und mit ziel vergleichen
      strcpy(oldboardname, b->boardname);
      oldmailpath[strlen(oldmailpath)-8] = 0;
      if (finddir(oldmailpath,0) > 0)
      {
        if (! strcmp(ziel, b->boardname))
          gleichesboard = YES;
      }
      else
        gleichesboard = NO;
      strcpy(b->boardname,oldboardname); // b->boardname wieder herstellen
      // bei Usermail oder gleichem Board zum Sortieren
      // Filezeit/-namen neu setzen
      if (mbcallok(zielcall) || gleichesboard)
      {
        strcpy(b->mailfname, time2filename(0));
      }
      else
        strcpy(b->mailfname, oldmailfname);
      if (! strstr(b->mailpath, "*.*"))
        trace(fatal, name, "mask %s", b->mailpath);
      strcpy(strstr(b->mailpath, "*.*"), b->mailfname);
      strlwr(b->mailpath);
      if ((newf = s_fopen(b->mailpath, "sw+t")) != NULL)
      {
        s_fsetopt(newf, 1);
#ifdef USERLT
        set_boardlife_max(old_lt);
        b->lifetime = old_lt;
#endif
        writeheader(newf, 1);
        if (b->mailtype != 'B')
        {
          if (fgets(b->line, BUFLEN - 1, oldf))
          {
            do
            { // fputs(line,f); skip old R-lines
              waitfor(e_ticsfull);
              fgets(b->line, BUFLEN - 1, oldf);
            }
            while (! feof(oldf) && *line == 'R' && line[1] == ':');
          }
          fprintf(newf, "%s\n", makeheader(1));
          fprintf(newf, "X-Transfer: %s by %s @ %s\n",
                  datestr(ad_time(), 12), b->logincall, m.boxadress);
          fprintf(newf, "X-Original-Date: %s\n", datestr(oldmsgtime, 10));
          do
          {
            if((   ! strncasecmp(line, "from", 4)
                || ! strncmp(line, "de: ", 4)
                || ! strncmp(line, "de ", 3)
                || ! strncmp(line, "fm ", 3)) && ! nocp)
              fprintf(newf, "X-Originally %s", line);
            else if ((   ! strncasecmp(line, "to: ", 4)
                      || ! strncasecmp(line, "to ", 3)) && ! nocp)
              fprintf(newf, "X-Originally %s", line);
            else if (! strncmp(line, "X-MID: ", 7))
              fprintf(newf, "X-Old-MID: %s", line + 7);
            else if (! strncmp(line, "X-BID: ", 7))
              fprintf(newf, "X-Old-BID: %s", line + 7);
            else fputs(line, newf);
            waitfor(e_ticsfull);
            fgets(b->line, BUFLEN - 1, oldf);
          }
          while (! feof(oldf) && *line != LF);
          fputc(LF, newf);
        }
        //Files binaer behandeln
        oldfpos = ftell(oldf);
        s_fclose(oldf);
        s_fclose(newf);
        writemailflags();
        if ((oldf = s_fopen(oldfname, "srb")) != NULL)
        {
          if ((newf = s_fopen(b->mailpath, "sab")) != NULL) //append to file
          {
            fseek(oldf, oldfpos, SEEK_SET);
            do
            { //oe3dzw: Transferroutine transparent
              int len;
              len = fread(line, 1, 255, oldf);
              if (len) fwrite(line, 1, len, newf);
              waitfor(e_ticsfull);
            }
            while (! feof(oldf));
            if (b->binstart)  //bei binaeren Mails offset neu berechnen
            {
              b->binstart += ftell(newf) - ftell(oldf);
              if (b->binstart < 0)
                trace(serious, name, "offset %ld in %s", b->binstart, b->mailpath);
            }
            s_fclose(newf);
            if (b->binstart) writelines(); //Neuen Binstart speichern
            if (b->bytes)
            {
              if (old_usermail || gleichesboard)
                nummer = appenddirlist(1);
              else
                nummer = appenddirlist(0); //change old CHECKLINE
              if (b->usermail)
              {
                add_fwdfile("", get_fdelay(b->herkunft), 0);
                sprintf(b->line, "%s %lu", b->herkunft, nummer);
                mbtalk("\001", b->zielboard, b->line);
                trigger_ufwd(b->zielboard);
              }
              else
              {
                handle fh;
                char found;
                if (old_usermail)
                  add_fwdfile("", get_fdelay(b->herkunft), 0);
                else
                  add_fwdfile("", get_fdelay(b->herkunft), 1);
                if (findex > 0)
                  tree[findex - 1].newestmail = oldmsgtime;
                if ((fh = s_open(CHECKNAME, "sr+b")) != EOF)
                {
                  seek_fname(fh, b->mailfname, &found, 1);
                  long pos = ltell(fh);
                  if (found)
                  {
                    _read(fh, b->line, BLEN);
                    sprintf(b->line + 15, "%-8s", b->boardname);
                    b->line[23] = '~';
#ifdef USERLT
                    char nlt[4];
                    sprintf(nlt, "%3.3d", b->boardlife_max);
                    memcpy(b->line + 51, nlt, 3);
#endif
                    lseek(fh, -(LBLEN), SEEK_CUR);
                    _write(fh, b->line, BLEN);
                  }
                  s_close(fh);
                  if (found && (fh = s_open(CHECKNUMNAME, "sr+b")) != EOF)
                  {
                    lseek(fh, 2*(pos >> 6), SEEK_SET); //2* da 32bit!
                    _write(fh, &nummer, 4); // 4Byte=32 bit
                    s_close(fh);
                  }
                }
                else
                  trace(serious, name, "check");
              }
              inc_mailgot(b->boardname);
              writemailflags();
              retwert = OK;
Example #6
0
int main(int argc, char * * argv)
{
  int flag1=1; //indicates that the first node has been created and that head should be preserved 
  int flag2=0; //indicates that the consequential node has been created and the list should be linked
  int ctr=0;  //ctr variables
  int ctr1=0; //^
  int ctr2=0; //^
  int i=0;  //^
  char *str = malloc(1000*sizeof(char)); //free at the end
  size_t size=1000; //max number of chacracters read from the input file at once
  char *filename = argv[1]; //input file name
  FILE *fptr = fopen(filename,"r");
  FILE *out; //output file ptr
  int c[256]={0}; //Stores the chars read from input file here
  int val[256]={0}; //Stores the chars' frequencies here  (Could've just used one array also)
  Node *head=NULL;
  Node *prev=NULL;
  Node *treenode=NULL;
  Node *tree = NULL; //huffman tree
  char *str1=malloc(sizeof(char*));  //free at the end
  char **codes = malloc(256*sizeof(char*));  //free at the end
  char *byte = malloc(sizeof(char*)); //Byte used to write to the output file,  //free at the end

  //mallocing memory for individual blocks of the array that will store binary codes
  for(i=0;i<256;i++)
    {
      codes[i] = malloc(sizeof(char*));
    }


  //Reading file, counting characters and making character-frequency table
  while(fgets(str,size,fptr) != NULL)
    {
      while(*(str+ctr) != '\n' && *(str+ctr) != '\0') //to stop when newline is encountered and to exclude null 
	{
	  c[(int)*(str+ctr)]=(*(str+ctr));
	  val[(int)*(str+ctr)]= val[(int)*(str+ctr)] + 1;
	  ctr++;
	}
      if(*(str+ctr) == '\n' || *(str+ctr) == '\0')
	{
	  c[(int)*(str+ctr)]=(*(str+ctr));
	  val[(int)*(str+ctr)]= val[(int)*(str+ctr)] + 1;
	}
	    ctr=0;
    }  
  fclose(fptr); //Closing file for now; Reopened later when we write compressed characters to the output file


  //Making linked list from character frequency table
  for(ctr=0 ;ctr<256;ctr++)
    {
      if(c[ctr]!=0)
	{
	  ctr1 = findsmallest(val);
	  treenode = createNode(c[ctr1],val[ctr1]);
	  val[ctr1]=0; //removing the smallest value from the frequency array by making it 0
	  if(flag2==1)
	    {
	      prev->next=treenode; //linking the list
	      prev=prev->next;
	    }
	  if(flag1==1)
	    {
	      head=treenode; //preserving head node
	      prev=head; //assigning the head node to prev so that the nodes can be linked
	      flag1=0;
	      flag2=1;
	    }
	  ctr2++; //number of nodes in the linked list
	}
    }

  treenode=head; //reassigning the head of the linked list to treenode

  
  //Now creating the Huffman tree from the linked list
  tree=createHuff(treenode,ctr2);


  //Assigning codes to each character in the input file
  assigncode(tree,str1,codes);

  //Writing huffman tree header and the binary code to an output file
  fptr = fopen(filename,"r");
  strcat(filename,".huff"); //naming output file as per the naming convention
  out = fopen(filename,"w+");
  ctr = 0;


  //First making the header and writing it to an output file
  makeheader(tree,out);
  fprintf(out,"0%d\n",tree->val);

  //Now writing binary code to the same output file
  writebinarypath(fptr,out,byte,str,codes);

  //Closing files opened
  fclose(fptr);
  fclose(out);

  //freeing previously allocated memory

  free(str);
  free(str1);
  free(byte);

  //freeing the codes array that stored binary codes for each character in the input file
  for(i=0;i<256;i++)
    {
      free(codes[i]);
    }
  free(codes);

  //freeing the huffman tree
  Destroy_tree(tree);

  return 0;
}
Example #7
0
/*
   頻繁に呼びだされる、I/Oする関数。パケットの内容を見て、

   return values:

   いくつのパケットを受信したか。
   
 */
int uproc(void)
{
	fd_set rfd , wfd;
	int a;
	int rcount =0;
	int i;
	
	int read_ok ;
	int write_more;	
	while(1){
		struct timeval tm;
		tm.tv_sec = 0;
		tm.tv_usec = 0;
		
		FD_ZERO( &rfd );
		FD_ZERO( &wfd );

		FD_SET(  udptcp.mainsockfd , &rfd);
		FD_SET(  udptcp.mainsockfd , &wfd );

		a = select( 100 , &rfd , &wfd , (fd_set*)0 , &tm );

		read_ok = 0;
		write_more = 0;

		/* 書きこみ可能 */
		if( FD_ISSET( udptcp.mainsockfd , &wfd )){
			int i,sr;
			unsigned long start,end,datalen;
			char buf[SEGMENTSIZ+HEADERSIZE];

			for(i=0;i<MAXCON;i++){
				/* start からendまで書きこみたい。長さは適切になってい */
				/* る。 */

				if( stb[i].use == 0 ) continue;

				getwfdpart( i , &start, &end ,SEGMENTSIZ );
				datalen = end-start;
				if( datalen >0 ){
					fprintf( stderr, "send_start:%d len:%d\n" , start,datalen );
					makeheader( buf ,
					   start ,
					   ACK_NOUSE ,
					   0 , 0 , 0 , 0 ,
						datalen );
					bcopy( stb[i].wb+start ,buf + HEADERSIZE ,
						  datalen);

					/* 送信 */
					sr = sender( buf , datalen +HEADERSIZE , stb[i].addr_dest );
					if( sr != ( datalen+HEADERSIZE) ){
						break;
					} else {
						/* ちゃんと送れたからバッファを更新 */
						setsend( i, start , end );
					}
				}
			}

			write_more = 0;		/* 今はいつでもwrite_more = 0 PENDING */
		}

		/* 読みこみ可能 */
		if( FD_ISSET( udptcp.mainsockfd  , &rfd )){
			int n;
			char buf[SEGMENTSIZ+HEADERSIZE];
			struct sockaddr_in sin;
			int clilen;
			read_ok = 1;

			n = recvfrom( udptcp.mainsockfd ,
						 buf , sizeof( buf ) , 0 , (struct sockaddr*)&sin , &clilen);
			if( n< 0 ) continue;
			fprintf( stderr , "recvfrom addr:%x\n", sin.sin_addr.s_addr );
			if( n > 0 ){
				
				/* パケットを読みこむことができた。 ackフィールドにデータがある場合はackの処理をする。
				 データが0xffffffffの場合はデータである。*/
				int index;
			   	unsigned long seq , ack;
			   	unsigned char rst,syn,fin,ref;
			   	unsigned long length;
				getheader( buf , &seq , &ack , &rst , &syn , &fin , &ref ,&length );

				
				/* 対応するindexをポートの情報から得る。ないときは */
				/* accept待ち行列に追加する。 */
				index = getindexbyaddr( sin.sin_addr.s_addr );
			
				if( syn ){
					/* SYNである。 */
					if( index == -1 ){
						fprintf( stderr, "SYN!\n");
						/* 今までにないアドレスだ(サーバーにとっては当然)。
						   accept待ちソケットをついか */
						for(i=3;i<MAXCON;i++){
							if( stb[i].use == 0 ){
								bzero( &stb[i] , sizeof( stb[0] ) );
								newsock(i);
								stb[i].acceptwait = 1;
								stb[i].read_syn = 1;	/* synがきたから */
								stb[i].addr_dest = sin.sin_addr.s_addr;
								break;
							}
						}
						if( i == MAXCON ){
							/* これ以上何もできないからパケットを捨てる。
							   クライアントからはサーバーが応答しないように見える
							   から、タイムアウトすることだろう。*/
						} else {
							/* SYNをかえす */
							makeheader( buf , 0 , 0, 0 , 1 , 0, 0 ,0 );/*ACK->0*/
							sender( buf , HEADERSIZE , sin.sin_addr.s_addr );		   
						}
						
						
					} else {
						/* 今までに存在していたソケットにSYNがきたら、 */
						/* それはクライアントでは当然である */
						if( ack == ACK_NOUSE ){
							/* ACK_NOUSEはデータ送信のときにつかうのでSYNは2回こない.
							 そんな誤ったデータはすてる*/
							fprintf( stderr , "Bad SYN code\n");
						} else {
							/* SYNのACKであるからsenderしない */
							stb[index].read_syn = 1;
							fprintf( stderr , "fd%d read_syn on!\n",index );
						}
					}
				} else if( ack == ACK_NOUSE ){
					/* データである。*/
					int i;
					if( index == -1 ){
						/* 存在しないソケットにたいしてデータがくることはない。 */
						fprintf( stderr, "Bad Data\n" );
					} else {
						/* すでに確立しているコネクションのためのデータだから、readbufにくわえる。 */
						int ret = addrb( index , buf + HEADERSIZE ,seq , length );
						if( ret == 0 ){
							/* 読みこみ成功したからACKかえす。
							 長さもそのまま返す。*/
							makeheader( buf , 0xffffffff , seq , 0 , 0, 0 ,0 ,length );
							sender( buf , HEADERSIZE , sin.sin_addr.s_addr );
						} else {
							/* 失敗したからACKかえさない(再送させんと) */
						}
					}
				} else {
					/* ACKである. */
					/* ACKをうけとったら、 ACKの値をもつwritebufがあるか検索 */
					if( index == -1 ){
						/* 存在しないソケットにACKきても意味なし。無視する */
						fprintf( stderr , "Bad ack code %\n" );
					} else{
						/* そのまま返ってきた長さがここに生かされる。
						   ACKパケットの場合だけ、length分のデータをもたない */
						setack( index , ack, length );
					}
				}
			}
			rcount ++;
			fprintf( stderr, "R ");
		}

		/* もう読みこむものがなくなって、書きこむものもなくなったら返す */
		if( read_ok == 0 && write_more == 0 ){
/*			fprintf( stderr , "%d %d\n" , read_ok , write_more );*/
			break;
		}
	}

	return rcount;
}