-
-
Notifications
You must be signed in to change notification settings - Fork 332
/
SentryCrashFileUtils.c
582 lines (529 loc) · 16 KB
/
SentryCrashFileUtils.c
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
// Adapted from: https://github.com/kstenerud/KSCrash
//
// SentryCrashFileUtils.c
//
// Created by Karl Stenerud on 2012-01-28.
//
// Copyright (c) 2012 Karl Stenerud. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall remain in place
// in this source code.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "SentryCrashFileUtils.h"
#include "SentryAsyncSafeLog.h"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
/** Buffer size to use in the "writeFmt" functions.
* If the formatted output length would exceed this value, it is truncated.
*/
#ifndef SentryCrashFU_WriteFmtBufferSize
# define SentryCrashFU_WriteFmtBufferSize 1024
#endif
// ============================================================================
#pragma mark - Utility -
// ============================================================================
static bool
canDeletePath(const char *path)
{
const char *lastComponent = strrchr(path, '/');
if (lastComponent == NULL) {
lastComponent = path;
} else {
lastComponent++;
}
if (strcmp(lastComponent, ".") == 0) {
return false;
}
if (strcmp(lastComponent, "..") == 0) {
return false;
}
return true;
}
static int
dirContentsCount(const char *path)
{
int count = 0;
DIR *dir = opendir(path);
if (dir == NULL) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Error reading directory %s: %s", path, strerror(errno));
return 0;
}
while (readdir(dir)) {
count++;
}
closedir(dir);
return count;
}
static void
dirContents(const char *path, char ***entries, int *count)
{
DIR *dir = NULL;
char **entryList = NULL;
int entryCount = dirContentsCount(path);
if (entryCount <= 0) {
goto done;
}
dir = opendir(path);
if (dir == NULL) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Error reading directory %s: %s", path, strerror(errno));
goto done;
}
entryList = calloc((unsigned)entryCount, sizeof(char *));
if (entryList != NULL) {
struct dirent *ent;
int index = 0;
while ((ent = readdir(dir))) {
if (index >= entryCount) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Contents of %s have been mutated", path);
goto done;
}
entryList[index] = strdup(ent->d_name);
index++;
}
}
done:
if (dir != NULL) {
closedir(dir);
}
if (entryList == NULL) {
entryCount = 0;
}
*entries = entryList;
*count = entryCount;
}
static void
freeDirListing(char **entries, int count)
{
if (entries != NULL) {
for (int i = 0; i < count; i++) {
char *ptr = entries[i];
if (ptr != NULL) {
free(ptr);
}
}
free(entries);
}
}
static bool
deletePathContents(const char *path, bool deleteTopLevelPathAlso)
{
struct stat statStruct = { 0 };
if (stat(path, &statStruct) != 0) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not stat %s: %s", path, strerror(errno));
return false;
}
if (S_ISDIR(statStruct.st_mode)) {
char **entries = NULL;
int entryCount = 0;
dirContents(path, &entries, &entryCount);
int bufferLength = SentryCrashFU_MAX_PATH_LENGTH;
char *pathBuffer = malloc((unsigned)bufferLength);
snprintf(pathBuffer, bufferLength, "%s/", path);
char *pathPtr = pathBuffer + strlen(pathBuffer);
int pathRemainingLength = bufferLength - (int)(pathPtr - pathBuffer);
for (int i = 0; i < entryCount; i++) {
char *entry = entries[i];
if (entry != NULL && canDeletePath(entry)) {
strncpy(pathPtr, entry, pathRemainingLength);
deletePathContents(pathBuffer, true);
}
}
free(pathBuffer);
freeDirListing(entries, entryCount);
if (deleteTopLevelPathAlso) {
sentrycrashfu_removeFile(path, false);
}
} else if (S_ISREG(statStruct.st_mode)) {
sentrycrashfu_removeFile(path, false);
} else {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not delete %s: Not a regular file.", path);
return false;
}
return true;
}
// ============================================================================
#pragma mark - API -
// ============================================================================
const char *
sentrycrashfu_lastPathEntry(const char *const path)
{
if (path == NULL) {
return NULL;
}
char *lastFile = strrchr(path, '/');
return lastFile == NULL ? path : lastFile + 1;
}
bool
sentrycrashfu_writeBytesToFD(const int fd, const char *const bytes, int length)
{
const char *pos = bytes;
while (length > 0) {
int bytesWritten = (int)write(fd, pos, (unsigned)length);
if (bytesWritten == -1) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not write to fd %d: %s", fd, strerror(errno));
return false;
}
length -= bytesWritten;
pos += bytesWritten;
}
return true;
}
bool
sentrycrashfu_readBytesFromFD(const int fd, char *const bytes, int length)
{
char *pos = bytes;
while (length > 0) {
int bytesRead = (int)read(fd, pos, (unsigned)length);
if (bytesRead == -1) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not write to fd %d: %s", fd, strerror(errno));
return false;
}
length -= bytesRead;
pos += bytesRead;
}
return true;
}
bool
sentrycrashfu_readEntireFile(const char *const path, char **data, int *length, int maxLength)
{
bool isSuccessful = false;
int bytesRead = 0;
char *mem = NULL;
int fd = -1;
int bytesToRead = maxLength;
fd = open(path, O_RDONLY);
if (fd < 0) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not open %s: %s", path, strerror(errno));
goto done;
}
struct stat st;
if (fstat(fd, &st) < 0) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not fstat %s: %s", path, strerror(errno));
goto done;
}
if (bytesToRead == 0 || bytesToRead >= (int)st.st_size) {
bytesToRead = (int)st.st_size;
} else if (bytesToRead > 0) {
if (lseek(fd, -bytesToRead, SEEK_END) < 0) {
SENTRY_ASYNC_SAFE_LOG_ERROR(
"Could not seek to %d from end of %s: %s", -bytesToRead, path, strerror(errno));
goto done;
}
}
mem = malloc((unsigned)bytesToRead + 1);
if (mem == NULL) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Out of memory");
goto done;
}
if (!sentrycrashfu_readBytesFromFD(fd, mem, bytesToRead)) {
goto done;
}
bytesRead = bytesToRead;
mem[bytesRead] = '\0';
isSuccessful = true;
done:
if (fd >= 0) {
close(fd);
}
if (!isSuccessful && mem != NULL) {
free(mem);
mem = NULL;
}
*data = mem;
if (length != NULL) {
*length = bytesRead;
}
return isSuccessful;
}
bool
sentrycrashfu_writeStringToFD(const int fd, const char *const string)
{
if (*string != 0) {
int bytesToWrite = (int)strlen(string);
const char *pos = string;
while (bytesToWrite > 0) {
int bytesWritten = (int)write(fd, pos, (unsigned)bytesToWrite);
if (bytesWritten == -1) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not write to fd %d: %s", fd, strerror(errno));
return false;
}
bytesToWrite -= bytesWritten;
pos += bytesWritten;
}
return true;
}
return false;
}
bool
sentrycrashfu_writeFmtToFD(const int fd, const char *const fmt, ...)
{
if (*fmt != 0) {
va_list args;
va_start(args, fmt);
bool result = sentrycrashfu_writeFmtArgsToFD(fd, fmt, args);
va_end(args);
return result;
}
return false;
}
bool
sentrycrashfu_writeFmtArgsToFD(const int fd, const char *const fmt, va_list args)
{
if (*fmt != 0) {
char buffer[SentryCrashFU_WriteFmtBufferSize];
vsnprintf(buffer, sizeof(buffer), fmt, args);
return sentrycrashfu_writeStringToFD(fd, buffer);
}
return false;
}
int
sentrycrashfu_readLineFromFD(const int fd, char *const buffer, const int maxLength)
{
char *end = buffer + maxLength - 1;
*end = 0;
char *ch;
for (ch = buffer; ch < end; ch++) {
int bytesRead = (int)read(fd, ch, 1);
if (bytesRead < 0) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not read from fd %d: %s", fd, strerror(errno));
return -1;
} else if (bytesRead == 0 || *ch == '\n') {
break;
}
}
*ch = 0;
return (int)(ch - buffer);
}
bool
sentrycrashfu_makePath(const char *absolutePath)
{
bool isSuccessful = false;
char *pathCopy = strdup(absolutePath);
for (char *ptr = pathCopy + 1; *ptr != '\0'; ptr++) {
if (*ptr == '/') {
*ptr = '\0';
if (mkdir(pathCopy, S_IRWXU) < 0 && errno != EEXIST) {
SENTRY_ASYNC_SAFE_LOG_ERROR(
"Could not create directory %s: %s", pathCopy, strerror(errno));
goto done;
}
*ptr = '/';
}
}
if (mkdir(pathCopy, S_IRWXU) < 0 && errno != EEXIST) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not create directory %s: %s", pathCopy, strerror(errno));
goto done;
}
isSuccessful = true;
done:
free(pathCopy);
return isSuccessful;
}
bool
sentrycrashfu_removeFile(const char *path, bool mustExist)
{
if (remove(path) < 0) {
if (mustExist || errno != ENOENT) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not delete %s: %s", path, strerror(errno));
}
return false;
}
return true;
}
bool
sentrycrashfu_deleteContentsOfPath(const char *path)
{
if (!canDeletePath(path)) {
return false;
}
return deletePathContents(path, false);
}
bool
sentrycrashfu_openBufferedWriter(SentryCrashBufferedWriter *writer, const char *const path,
char *writeBuffer, int writeBufferLength)
{
writer->buffer = writeBuffer;
writer->bufferLength = writeBufferLength;
writer->position = 0;
writer->fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
if (writer->fd < 0) {
SENTRY_ASYNC_SAFE_LOG_ERROR(
"Could not open crash report file %s: %s", path, strerror(errno));
return false;
}
return true;
}
void
sentrycrashfu_closeBufferedWriter(SentryCrashBufferedWriter *writer)
{
if (writer->fd > 0) {
sentrycrashfu_flushBufferedWriter(writer);
close(writer->fd);
writer->fd = -1;
}
}
bool
sentrycrashfu_writeBufferedWriter(
SentryCrashBufferedWriter *writer, const char *restrict const data, const int length)
{
if (length > writer->bufferLength - writer->position) {
sentrycrashfu_flushBufferedWriter(writer);
}
if (length > writer->bufferLength) {
return sentrycrashfu_writeBytesToFD(writer->fd, data, length);
}
memcpy(writer->buffer + writer->position, data, length);
writer->position += length;
return true;
}
bool
sentrycrashfu_flushBufferedWriter(SentryCrashBufferedWriter *writer)
{
if (writer->fd > 0 && writer->position > 0) {
if (!sentrycrashfu_writeBytesToFD(writer->fd, writer->buffer, writer->position)) {
return false;
}
writer->position = 0;
}
return true;
}
static inline bool
isReadBufferEmpty(SentryCrashBufferedReader *reader)
{
return reader->dataEndPos == reader->dataStartPos;
}
static bool
fillReadBuffer(SentryCrashBufferedReader *reader)
{
if (reader->dataStartPos > 0) {
memmove(reader->buffer, reader->buffer + reader->dataStartPos, reader->dataStartPos);
reader->dataEndPos -= reader->dataStartPos;
reader->dataStartPos = 0;
reader->buffer[reader->dataEndPos] = '\0';
}
int bytesToRead = reader->bufferLength - reader->dataEndPos;
if (bytesToRead <= 0) {
return true;
}
int bytesRead = (int)read(reader->fd, reader->buffer + reader->dataEndPos, (size_t)bytesToRead);
if (bytesRead < 0) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not read: %s", strerror(errno));
return false;
} else {
reader->dataEndPos += bytesRead;
reader->buffer[reader->dataEndPos] = '\0';
}
return true;
}
int
sentrycrashfu_readBufferedReader(SentryCrashBufferedReader *reader, char *dstBuffer, int byteCount)
{
int bytesRemaining = byteCount;
int bytesConsumed = 0;
char *pDst = dstBuffer;
while (bytesRemaining > 0) {
int bytesInReader = reader->dataEndPos - reader->dataStartPos;
if (bytesInReader <= 0) {
if (!fillReadBuffer(reader)) {
break;
}
bytesInReader = reader->dataEndPos - reader->dataStartPos;
if (bytesInReader <= 0) {
break;
}
}
int bytesToCopy = bytesInReader <= bytesRemaining ? bytesInReader : bytesRemaining;
char *pSrc = reader->buffer + reader->dataStartPos;
memcpy(pDst, pSrc, bytesToCopy);
pDst += bytesToCopy;
reader->dataStartPos += bytesToCopy;
bytesConsumed += bytesToCopy;
bytesRemaining -= bytesToCopy;
}
return bytesConsumed;
}
bool
sentrycrashfu_readBufferedReaderUntilChar(
SentryCrashBufferedReader *reader, int ch, char *dstBuffer, int *length)
{
int bytesRemaining = *length;
int bytesConsumed = 0;
char *pDst = dstBuffer;
while (bytesRemaining > 0) {
int bytesInReader = reader->dataEndPos - reader->dataStartPos;
int bytesToCopy = bytesInReader <= bytesRemaining ? bytesInReader : bytesRemaining;
char *pSrc = reader->buffer + reader->dataStartPos;
char *pChar = strchr(pSrc, ch);
bool isFound = pChar != NULL;
if (isFound) {
int bytesToChar = (int)(pChar - pSrc) + 1;
if (bytesToChar < bytesToCopy) {
bytesToCopy = bytesToChar;
}
}
memcpy(pDst, pSrc, bytesToCopy);
pDst += bytesToCopy;
reader->dataStartPos += bytesToCopy;
bytesConsumed += bytesToCopy;
bytesRemaining -= bytesToCopy;
if (isFound) {
*length = bytesConsumed;
return true;
}
if (bytesRemaining > 0) {
fillReadBuffer(reader);
if (isReadBufferEmpty(reader)) {
break;
}
}
}
*length = bytesConsumed;
return false;
}
bool
sentrycrashfu_openBufferedReader(SentryCrashBufferedReader *reader, const char *const path,
char *readBuffer, int readBufferLength)
{
readBuffer[0] = '\0';
readBuffer[readBufferLength - 1] = '\0';
reader->buffer = readBuffer;
reader->bufferLength = readBufferLength - 1;
reader->dataStartPos = 0;
reader->dataEndPos = 0;
reader->fd = open(path, O_RDONLY);
if (reader->fd < 0) {
SENTRY_ASYNC_SAFE_LOG_ERROR("Could not open file %s: %s", path, strerror(errno));
return false;
}
fillReadBuffer(reader);
return true;
}
void
sentrycrashfu_closeBufferedReader(SentryCrashBufferedReader *reader)
{
if (reader->fd > 0) {
close(reader->fd);
reader->fd = -1;
}
}