File: flip.c

package info (click to toggle)
flip 1.20-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster
  • size: 196 kB
  • sloc: ansic: 1,186; cpp: 172; makefile: 124; sh: 61
file content (635 lines) | stat: -rw-r--r-- 15,435 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
/* ::[[ @(#) flip.c 1.18 89/07/04 16:07:16 ]]:: */
#ifndef LINT
static char sccsid[]="::[[ @(#) flip.c 1.20 2008-07-26 ]]::";
#endif

/*
Copyright 1989 Rahul Dhesi, All rights reserved.

Checksum: 1217582374 (check or update with "brik")
*/

/*
Does newline conversions between **IX and MS-DOS conventions.  Uses a state
machine, so repeated conversions on the same file will do no harm.
Assumes the US ASCII character set in some places (search for 'ASCII').
*/

/* change contents of flip.h as needed */
#include "flip.h"

enum choices   { MSTOIX, IXTOMS, NEITHER };           /* conversion choices */
enum state     { NONE, SAWCR, SAWLF, SAWCRLF, SAWCTRLZ };

void usage PARMS ((void));
void give_help PARMS ((void));
void flip_exit PARMS ((int));
int getopt PARMS ((int argc, char **argv, char *options));
void doarg PARMS ((char *, enum choices));
int dofile PARMS ((char *, enum choices));
char *nextfile PARMS ((int, char *, int));
int ixtoms PARMS ((FILE *, FILE *));
int mstoix PARMS ((FILE *, FILE *));
void error PARMS ((char *, char *));
void setup_sigs PARMS ((void));
void cleanup PARMS ((int));
int mkstemp PARMS ((char *));

#ifdef STDINCLUDE
# include <stdlib.h>
# include <string.h>
#else
void *malloc PARMS ((int));
void exit PARMS ((int));
char *strcpy PARMS ((char *, char *));
#endif

#ifdef IX
#include <sys/types.h>
#include <sys/stat.h>		/* stat and chmod */
#include <unistd.h>
#endif

#ifdef NDEBUG
# define assert(c)
#else
# ifdef STDINCLUDE
#  include <assert.h>
# else
#  define assert(c)  if(!(c)) \
                  fprintf(stderr,"assert error %s:%d\n",__FILE__,__LINE__)
# endif /* STDINCLUDE */
#endif /* NDEBUG */

#ifdef USE_TABLE
char *bintab;
#endif

#ifdef USE_SIG
int got_sig;               /* will indicate if signal received */
#endif

char *myname = NULL;

int exitstat = 0;          /* exit status */
int verbose = 0;           /* set by -v option */
int touch = 0;             /* set by -t option */
int strip = 0;             /* set by -s option */
int bintoo = 0;            /* set by -b option */
int ztrunc = 0;            /* set by -z option */
int use_stdio = 0;	   /* set by "-" filename */

int main (argc, argv)
int argc;
char **argv;

{
   int option;
   extern int optind;
   int i;
   enum choices which = NEITHER;
#ifdef USE_TABLE
#define TABSIZ    256
   char table[TABSIZ];
#endif

#ifdef PICKNAME
   register char *p; /* temp pointer for finding our name */
   register char *arg0 = *argv;
#endif /* PICKNAME */

   SPEC_INIT            /* optional initialization */

#ifdef USE_SIG
   setup_sigs();
#endif

#ifdef PICKNAME
# define STRCMP(a,op,b)    (strcmp(a,b) op 0)
   p = arg0 + strlen(arg0);

   if (p != arg0) {     /* if program name is defined */
      while (p != arg0 && *p != '/' && *p != '\\')
         p--;
      assert ((p - arg0) <= strlen (arg0));
      if (p != arg0)
         p++;

      /* p now points to trailing name component, or nothing */
      myname = p;
      while (*p != '\0' && *p != '.') {   /* ASCII convert to lowercase */
         if (*p >= 'A' && *p <= 'Z') {
            *p = (*p - 'A' + 'a');
         }
         p++;
      }
      if (p != myname && *p == '.')
         *p = '\0';     /* remove trailing .exe or .com under MS-DOS etc. */

      if (STRCMP(myname,==,"toix"))
         which = MSTOIX;
      else if (STRCMP(myname,==,"toms"))
         which = IXTOMS;
   } else
   myname = "flip";
#else
   myname = "flip";
#endif /* PICKNAME */

argv[0] = myname;                /* for use by getopt */

#ifdef USE_TABLE
/* table to find out which characters are binary */
   for (i = 0;  i < TABSIZ;  i++) {
      if ( (i < 7) || (i > 13 && i < 26) || (i > 126)) /*ASCII binary chars*/
         table[i] = 1;
      else
         table[i] = 0;
   }
   bintab = table;
#endif /* USE_TABLE */

   if (argc < 2) {
      usage();
      flip_exit (1);
   }

   while ((option = getopt (argc, argv, "umhvtsbz")) != EOF) {
      switch (option) {
       case 'u': which = MSTOIX;  break;
       case 'm': which = IXTOMS; break;
       case 'h': give_help(); flip_exit (0);
       case 'v': verbose = 1;  break;
       case 't': touch = 1;  break;
       case 's': strip = 1;  break;
       case 'b': bintoo = 1;  break;
       case 'z': ztrunc = 1;  break;
       default:  usage(); flip_exit (1);
      }
   }

   switch (which) {
    case MSTOIX:
      /* printf ("converting to **ix format\n"); */
      break;
    case IXTOMS:
      /* printf ("converting to msdos format\n"); */
      break;
    default:
      fprintf (stderr, "%s: error: -u or -m is required\n", myname);
      flip_exit (1);
      break;
   }

   if (argc <= optind) {
      fprintf (stderr, "%s: error: filenames are needed\n", myname);
      flip_exit (1);
   }

   for (i = optind;  i < argc;  i++)
      doarg (argv[i], which);

   return (exitstat);
}


/*
Does conversion for one argument, calling dofile with wildcards
expanded.  Updates exitstat in case of error.
*/

void doarg (arg, which)
char *arg;
enum choices which;
{
#ifdef WILDCARD
   char *this_file;

   nextfile (0, arg, 0);
   while ((this_file = nextfile(1, (char *) NULL, 0)) != NULL) {
      exitstat |= dofile (this_file, which);
   }
#else
   exitstat |= dofile (arg, which);
#endif /* WILDCARD */
}

#ifdef USE_SIG
# include <signal.h>
#endif

FILE *outfile;       /* make it visible to both dofile and cleanup */

/*
Here we have filename and an option.  We call a different routine
for each type of conversion.  This way more types of conversions
can be easily added in the future.
*/

int dofile (fname, which)
char *fname;
enum choices which;
{
   FILE *infile;
   char tfname[PATHSIZE];
   SGFTIME timestamp;  /* save file timestamp here, restore later */
   int errstat = 0;
   char *p;             /* temp file ptr */
#ifdef IX
   struct stat ifilestat, ofilestat;
#endif

#ifdef USE_SIG
   if (got_sig)
      flip_exit (INT_EXIT);
#endif

   if(STRCMP(fname,==,"-"))
      use_stdio = 1;
   if(!use_stdio) {
      /* if writable, open for reading */
      if ((infile = fopen (fname, R_PL_B)) != NULL) {
         fclose (infile);
         infile = fopen (fname, RB);
#ifdef IX
	 if (stat (fname, &ifilestat)) {
	   /* can't get the file's permissions */
	   char *buf = malloc(strlen(fname)+strlen(myname)+3);
	   if (buf) {
	     sprintf(buf, "%s: %s", myname, fname);
	     perror(buf);
	   }
	   ifilestat.st_mode = 0644;
	   ifilestat.st_uid = geteuid();
	   ifilestat.st_gid = getegid();
	 }
#endif
      }
   } else {
      infile = stdin;
   }
	   
   if (infile == NULL) {
      error (fname, ": can't open");
      return (1);
   }
   if(use_stdio) {
     outfile = stdout;
   } else {
     /*
       to make temp file in same dir as original, we make p point to
       the filename component of fname, put '\0' there, and strcat the
       temp name to it */
     strcpy (tfname, fname);
     p = tfname + strlen(tfname);
     
     while (p != tfname && *p != '/' && *p != '\\')
       p--;
     if (p != tfname)
       p++;
     *p = '\0';

#define  TEMPLATE    "XXXXXX"
#ifdef IX
     strcat (tfname, TEMPLATE);

     {
       int fd = mkstemp(tfname);
       if (fd == -1 || (outfile = fdopen(fd, WB)) == NULL) {
	 fclose (infile);
	 error (fname, ": skipped, could not open temporary file");
	 return (1);
       }
     }
#else
     {
       char template[7];
       strcpy (template, TEMPLATE);
       strcat (tfname, mktemp (template));
     }

     outfile = fopen (tfname, WB);
     if (outfile == NULL) {
       fclose (infile);
       error (fname, ": skipped, could not open temporary file");
       return (1);
     }
#endif
   }

   if (!touch  &&  ! use_stdio)
      GETFT (infile, fname, timestamp);      /* save current timestamp */

   assert (which == IXTOMS || which == MSTOIX);

#ifdef BIGBUF
   setvbuf (infile,  (char *) NULL, _IOFBF, BIGBUF);
   setvbuf (outfile, (char *) NULL, _IOFBF, BIGBUF);
#endif /* BIGBUF */

   switch (which) {
    case IXTOMS:
      errstat = ixtoms (infile, outfile);
      break;
    case MSTOIX:
      errstat = mstoix (infile, outfile);
      break;
    case NEITHER:
      ;
   }

   fclose (infile);

   switch (errstat) {
    case ERRBINF:
      fclose (outfile);
      DELFILE (tfname);
      fprintf (stderr, "%s: binary file, not converted\n", fname);
      return (1);
      /* break; */  /* unreachable code */
#ifdef USE_SIG
    case ERRSIG:
      fclose (outfile);
      DELFILE (tfname);
      flip_exit (INT_EXIT);
      break;
#endif
    default:
      ;
   }

   assert (errstat == 0);

   if (!ferror(outfile) && fflush(outfile) != EOF && fclose(outfile) != EOF) {
      int moved;
      if (use_stdio)
	  goto stdio_skip;
#ifdef IX
      if (stat (tfname, &ofilestat)) {
	/* can't get the file's permissions */
	char *buf = malloc(strlen(tfname)+strlen(myname)+3);
	if (buf) {
	  sprintf(buf, "%s: %s", myname, tfname);
	  perror(buf);
	}
      }
      if (ifilestat.st_gid != ofilestat.st_gid ||
	  ifilestat.st_uid != ofilestat.st_uid)
	if (chown(tfname, ifilestat.st_uid, ifilestat.st_gid)) {
	  /* can't set the file's ownership */
	  char *buf = malloc(strlen(tfname)+strlen(myname)+3);
	  if (buf) {
	    sprintf(buf, "%s: %s", myname, tfname);
	    perror(buf);
	  }
	}
      if (ifilestat.st_mode != ofilestat.st_mode)
	if (chmod(tfname, ifilestat.st_mode)) {
	  /* can't set the file's permissions */
	  char *buf = malloc(strlen(tfname)+strlen(myname)+3);
	  if (buf) {
	    sprintf(buf, "%s: %s", myname, tfname);
	    perror(buf);
	  }
	}
#endif /* IX */


      stdio_skip:

      //      DELFILE (fname);
      if (!use_stdio) {
         moved = MVFILE (tfname, fname);
         if (moved == 0) {
            FILE *fptr;
            if (!touch && (fptr = fopen (fname, RB)) != NULL) {
               SETFT (fptr, fname, timestamp);
               fclose (fptr);
            }
            if (verbose) {
               printf ("%s\n", fname);
               fflush (stdout);
            }
            return (0);
         } else {
            error (fname, ": not converted, could not rename temp file");
            DELFILE (tfname);
            return (1);
         }
      }
   } else {
      fclose (outfile); /* outfile was not closed, so close it here */
      return (1);
   }
   return (1);			/* silences gcc warning */
}

/* convert from ms-dos to **ix format */
int mstoix (infile, outfile)
FILE *infile;           /* input file   */
FILE *outfile;          /* output file  */
{
   int c;
   enum state state = NONE;

   /* lone LF => unchanged, lone CR => unchanged,
      CR LF => LF, ^Z at end means EOF; ^Z elsewhere => unchanged */

   while (1) {       /* break out on EOF only */
      while ((c = getc (infile)) != EOF) {
#ifdef USE_SIG
         if (got_sig)
            return (ERRSIG);
#endif
         if (!bintoo && BINCHAR(c))
            return (ERRBINF);
         if (strip)
            STRIP(c);
         switch (c) {
          case LF:
            CHECK_BREAK
            putc (c, outfile); if (state == SAWCR) state = NONE; break;
          case CR:
            state = SAWCR; break;
          case CTRLZ:
            if (state == SAWCR) putc (CR, outfile);
            state = SAWCTRLZ; goto saweof;
          default:
            if (state == SAWCR) { state = NONE; putc (CR, outfile); }
            putc (c, outfile);
            break;
         }
      }
 saweof:
      /* exit outer loop only on EOF or ^Z as last char */
      if (
          (ztrunc && (state == SAWCTRLZ))
          || (c = getc (infile)) == EOF
         )
         break;
      else
         ungetc (c, infile);
      if (state == SAWCTRLZ)
         putc (CTRLZ, outfile);
   }
   return (0);
}

/* convert from **ix to ms-dos format */
int ixtoms (infile, outfile)
FILE *infile;           /* input file   */
FILE *outfile;          /* output file  */
{
   int c;
   enum state state = NONE;

   /* LF => CR LF, but leave CR LF alone */
   while ((c = getc (infile)) != EOF) {
#ifdef USE_SIG
      if (got_sig)
         return (ERRSIG);
#endif
      if (!bintoo && BINCHAR(c))
         return (ERRBINF);
      if (strip)
         STRIP(c);
      switch (c) {
       case LF:
         CHECK_BREAK
         if (state == SAWCR)
            state = NONE;
         else
            putc (CR, outfile);
         putc (LF, outfile);
         break;
       case CR:
         state = SAWCR; putc (c, outfile); break;
       case CTRLZ:
         if (ztrunc)
            return (0);
         /* FALL THROUGH */
       default:
         state = NONE; putc (c, outfile); break;
      }
   }
   return (0);
}

/* set up signal handler for selected signals */
#ifdef USE_SIG
void setup_sigs ()
{
# ifdef SIGPIPE
   if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
      signal (SIGPIPE, cleanup);
# endif
# ifdef SIGHUP
   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
      signal (SIGHUP, cleanup);
# endif
# ifdef SIGQUIT
   if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
      signal (SIGQUIT, cleanup);
# endif
# ifdef SIGINT
   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
      signal (SIGINT, cleanup);
# endif
# ifdef SIGTERM
   if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
      signal (SIGTERM, cleanup);
# endif
}

/* set flag on signal */
void cleanup(sig)
int sig;
{
   signal (sig, SIG_IGN);     /* needed for flaky System V Release 2 */
   got_sig = 1;
   signal (sig, cleanup);     /* ditto */
}
#endif /* USE_SIG */

#define  ERRSIZE     200

/* prints error message via perror */
void error (msg1, msg2)
char *msg1, *msg2;
{
   char buf[ERRSIZE];
   strcpy (buf, myname);
   strcat (buf, ": ");
   strcat (buf, msg1);
   strcat (buf, msg2);
   perror (buf);
   fflush (stderr);
}

/* gives brief usage message */
void usage()
{
   fprintf (stderr,
"usage:  %s [-u | -m] [other options] file ...  (or \"%s -h\" for more help)\n",
 myname, myname);
}

/* gives help screen */

void give_help()
{
printf ("\
File interchange program flip version " VERSION ".  Copyright 1989 Rahul Dhesi,\n\
All rights reserved.  Both noncommercial and commercial copying, use, and\n\
creation of derivative works are permitted in accordance with the\n\
requirements of the GNU license.  This program does newline conversions.\n");

printf ("\n\
   Usage:     flip -umhvtsbz file ...\n\
\n\
One of -u, -m, or -h is required;  others are optional.  See user manual.\n");

printf ("\n\
   -u     convert to **IX format (CR LF => LF, lone CR or LF unchanged,\n\
          trailing control Z removed, embedded control Z unchanged)\n\
   -m     convert to MS-DOS format (lone LF => CR LF, lone CR unchanged)\n\
   -h     give this help message\n\
   -v     be verbose, print filenames as they are processed\n\
   -t     touch files (don't preserve timestamps)\n\
   -s     strip high bit\n\
   -b     convert binary files too (else binary files are left unchanged)\n\
   -z     truncate file at first control Z encountered\n\
");
#ifdef PICKNAME
printf ("\n\
May be invoked as \"toix\" (same as \"flip -u\") or \"toms\" (same as \"flip -m\").\n\
");
#endif
return;
}

/* normal exits go through here -- atexit would be nice but not portable */
void flip_exit(stat)
int stat;
{
   SPEC_EXIT
   exit (stat);
}

/*
special code for **IX -- not in use because can't properly handle
SIGINT while /bin/mv is executing
*/

#ifdef NIX
# ifndef MVFILE
int MVFILE (src, dest)
char *dest;
char *src;
{
   char cmd[2 * PATHSIZE];
   sprintf (cmd, "/bin/mv %s %s", src, dest);
   return (system(cmd));
}
# endif /* MVFILE */
#endif /* NIX */