/*
 *      Copyright (c) 2023, an unpublished work by CodeSecure, Inc.
 *                      ALL RIGHTS RESERVED
 *
 *      Copyright (c) 2014-2023, an unpublished work by GrammaTech, Inc.
 *                      ALL RIGHTS RESERVED
 *
 *      This software is furnished under a license and may be used and
 *      copied only in accordance with the terms of such license and the       
 *      inclusion of the above copyright notice.  This software or any
 *      other copies thereof may not be provided or otherwise made
 *      available to any other person.  Title to and ownership of the
 *      software is retained by CodeSecure, Inc.
 */

/* use_iolibrary.c
 *
 * Uses functions from iolibrary.h in various ways: some safe, some unsafe.
 */

#include "iolibrary.h"
#include <string.h>

int getstring(char *fname, size_t chars, char *buf){
  FILE *f;
  char *s;

  f = open_a_file(fname);
  if (!f) {return -1;}
  s = read_string_from_file(buf, chars, f);
  close_a_file(f);
  if (!s) { return -1;}
  else {return (int) strlen(s);}
}


int main(){
  int i;
  char  a[50];
  char *b;
  char *c;
  size_t s;

  if (getstring("myfile.txt", 40, a) == -1) {return -1;}

  print_important_data(a);   /* 'a' is tainted, so this is bad */

  i = sanitized_size(a);
  if (i == -1) {return -1;}
  b = malloc(i);
  if (!b){ return -1;}
  if (!sanitize_file_string(a,b)){free(b); return -1;}

  print_important_data(b);  /* 'b' is sanitized, so this is ok */


  s = strlen(a) + strlen(b) + 1; 
  if (s <= strlen(a)) {free(b); return -1;}

  c = malloc(s);
  if (!c) {free(b); return -1;}
  strcpy(c,a);
  strcat(c,b);

  print_important_data(c);  /* 'c' is tainted by a, so this is bad */

  free(b);
  free(c);
  return 0;
}
