1 #include "foxreport.h"
2 #include <stdint.h>
3 #include <stdio.h>
4 #include <string.h>
5 
6 /*
7  *
8  * INPUT: starting position of stream
9  * OUTPUT: New length of stream
10  *
11  * FUNCTION: Will look for the end of the stream by searching
12  *           for an "endstream" token, and, if found, will
13  *           return the estimated actual length of the
14  *           stream and restore the file pointer to
15  *           the beginning of the stream.
16  *
17  */
recoverStream(FILE * file,long int lastposition)18 uint32_t recoverStream (FILE *file, long int lastposition) {
19 
20     long int seekpos = lastposition;
21     uint8_t buffer[1024];
22     uint8_t *instance;
23     uint32_t bytesRead;
24 	uint32_t actualStrmLen;
25 
26     while (!feof(file)) {
27         if (fseek(file, seekpos, SEEK_SET) != 0) {
28             foxLog(FATAL, "%s: Can't seek to pos in file.\n", __func__);
29 			return 0;
30         }
31 
32         if ((bytesRead = fread(buffer, 1, 1024, file)) < 1024) {
33             if (!feof(file)) {
34                 foxLog(FATAL, "%s: Can't read from file.\n", __func__);
35 				return 0;
36 			}
37         }
38 
39         if ((instance = (uint8_t *)memmem(buffer, bytesRead, (const void *)"\nendstream\n", 11)) != NULL) {
40 
41 			actualStrmLen = seekpos - lastposition + (instance - buffer);
42 
43 			if (fseek(file, lastposition, SEEK_SET) != 0) {
44                 foxLog(FATAL, "%s: Can't seek to pos in file.\n", __func__);
45 				return 0;
46             }
47 
48             return actualStrmLen;
49         }
50 
51 		//Seek to 1024 - 10 bytes
52 		//This is in case endstream was on the buffer border
53         seekpos = seekpos + 1014;
54     }
55 
56 	//Failed to recover. Fail out.
57     foxLog(FATAL, "%s: Was unable to recover. Exiting.\n", __func__);
58 
59     return 0;
60 }
61