home *** CD-ROM | disk | FTP | other *** search
/ Unix System Administration Handbook 1997 October / usah_oct97.iso / news / cnews.tar / contrib / snntp / netio.c < prev    next >
C/C++ Source or Header  |  1994-08-28  |  2KB  |  85 lines

  1. /*
  2.  * tgets, tputs - fgets & fputs that cope with the Internet's whacko
  3.  * CRLF end of line convention and dot-hiding.
  4.  */
  5.  
  6. #include <stdio.h>
  7. #include <ctype.h>
  8. #include <string.h>
  9.  
  10. #define YES 1
  11. #define NO 0
  12.  
  13. extern int hooting;
  14.  
  15. int                /* EOF or strlen(line) */
  16. tgets(line, size, fi)        /* fgets from TCP */
  17. register char *line;
  18. int size;
  19. FILE *fi;
  20. {
  21.     register char *cr, *from, *to;
  22.  
  23.     *line = '\0';
  24.     if (fgets(line, size, fi) == NULL)
  25.         return EOF;
  26.  
  27.     /* expose hidden dot */
  28.     if (line[0] == '.' && (line[1] == '\r' || line[1] == '\n')) {
  29.         strncpy(line, ".\n", size);
  30.         return EOF;
  31.     }
  32.     if (line[0] == '.' && line[1] == '.')
  33.         for (to = line, from = line + 1; (*to++ = *from++) != '\0'; )
  34.             ;
  35.  
  36.     /* convert \r\n -> \n */
  37.     cr = strchr(line, '\n');
  38.     if (cr == NULL)
  39.         return strlen(line);
  40.     if (cr > line && cr[-1] == '\r') {
  41.         *cr = '\0';
  42.         *--cr = '\n';
  43.     }
  44.     if (hooting)
  45.         (void) fprintf(stderr, "<<< %s", line);
  46.     return cr + 1 - line;
  47. }
  48.  
  49. /*
  50.  * minor bug: there is only on wasnl flag for all streams, not one per stream.
  51.  * it hasn't mattered yet.
  52.  */
  53. int
  54. tputs(line, fo)                /* fputs to TCP */
  55. register char *line;
  56. register FILE *fo;
  57. {
  58.     register char *nl;
  59.     static int wasnl = YES;        /* true if last byte was newline */
  60.  
  61.     if (hooting)
  62.         (void) fprintf(stderr, ">>> %s", line);
  63.     for (; *line != '\0'; line = nl + 1) {
  64.         /* we may be in the middle of a line here */
  65.         if (wasnl) {
  66.             /* we are at the start of a line here */
  67.             if (line[0] == '.')
  68.                 (void) putc('.', fo);
  69.         }
  70.         wasnl = NO;
  71.         nl = strchr(line, '\n');
  72.         if (nl == NULL) {
  73.             (void) fputs(line, fo);
  74.             break;
  75.         }
  76.         if (nl > line)
  77.             (void) fwrite(line, 1, nl - line, fo);
  78.         (void) fwrite("\r\n", 1, 2, fo);
  79.         wasnl = YES;
  80.         if (fflush(fo) == EOF)
  81.             return EOF;
  82.     }
  83.     return 0;
  84. }
  85.