Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFCCCC
enum { NO_FILE_POS_VALUES = 3 };

errno_t opener(FILE* file, int *width, int *height, int *data_offset) {
  int file_w;
  int file_h;
  int file_o;
  int rc;
  fpos_t offset;

  memset(&offset, 0, sizeof(offset));

  if (file == NULL) { return EINVAL; }
  if (fscanf(file, "%i %i %i", &file_w, &file_h, &file_o)  != NO_FILE_POS_VALUES) { return EIO; }
  if ((rc = fsetpos(file, &offset)) != 0 ) { return rc; }

  *width = file_w;
  *height = file_h;
  *data_offset = file_o;

  return 0;
}

int main(void) {
  int width;
  int height;
  int data_offset;
  FILE *file;
  /* ... */

  file = fopen("myfile", "rb");
  if (opener(file, &width, &height, &data_offset) != 0 ) { return 0; }

  /* ... */
}

However, because However, since only the return value of a getposfgetpos() call is valid to be used with setposfsetpos(), passing an fpos_t value that was created in any other way instead may not work. It is possible that the position will be set to an arbitrary location in the file.

...

Code Block
bgColor#CCCCFF
enum { NO_FILE_POS_VALUES = 3 };

errno_t opener(FILE* file, int *width, int *height, int *data_offset) {
  int file_w;
  int file_h;
  int file_o;
  int rc;
  fpos_t offset;

  if (file == NULL) { return EINVAL; }
  if ((rc = fgetpos(file, &offset)) != 0 ) { return rc; }
  if (fscanf(file, "%i %i %i", &file_w, &file_h, &file_o)  != NO_FILE_POS_VALUES) { return EIO; }
  if ((rc = fsetpos(file, &offset)) != 0 ) { return rc; }

  *width = file_w;
  *height = file_h;
  *data_offset = file_o;

  return 0;
}

int main(void) {
  int width;
  int height;
  int data_offset;
  FILE *file;
  /* ... */

  file = fopen("myfile", "rb");
  if (opener(file, &width, &height, &data_offset) != 0 ) { return 0; }

  /* ... */
}

Risk Assessment

The misuse of fsetpos() could move a file stream read to a undesired location in the file. If this location held input from the user, the user would then gain control of the variables being read from the file.

...