Skip to content

Fix potential crash in #177 #178

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Dec 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Sources/Segment/Errors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public enum AnalyticsError: Error {
case storageUnableToWrite(String)
case storageUnableToRename(String)
case storageUnableToOpen(String)
case storageUnableToClose(String)
case storageInvalid(String)
case storageUnknown(Error)

Expand Down Expand Up @@ -41,6 +42,8 @@ extension Analytics {
return AnalyticsError.storageUnableToOpen(path)
case .unableToWrite(let path):
return AnalyticsError.storageUnableToWrite(path)
case .unableToClose(let path):
return AnalyticsError.storageUnableToClose(path)
}
}

Expand Down
56 changes: 35 additions & 21 deletions Sources/Segment/Utilities/OutputFileStream.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ internal class OutputFileStream {
case unableToOpen(String)
case unableToWrite(String)
case unableToCreate(String)
case unableToClose(String)
}

var filePointer: UnsafeMutablePointer<FILE>? = nil
var fileHandle: FileHandle? = nil
let fileURL: URL

init(fileURL: URL) throws {
Expand All @@ -49,36 +50,49 @@ internal class OutputFileStream {

/// Open simply opens the file, no attempt at creation is made.
func open() throws {
if filePointer != nil { return }
let path = fileURL.path
path.withCString { file in
filePointer = fopen(file, "w")
if fileHandle != nil { return }
do {
fileHandle = try FileHandle(forWritingTo: fileURL)
} catch {
throw OutputStreamError.unableToOpen(fileURL.path)
}
guard filePointer != nil else { throw OutputStreamError.unableToOpen(path) }
}

func write(_ data: Data) throws {
guard let string = String(data: data, encoding: .utf8) else { return }
try write(string)
guard data.isEmpty == false else { return }
if #available(macOS 10.15.4, iOS 13.4, macCatalyst 13.4, tvOS 13.4, watchOS 13.4, *) {
do {
try fileHandle?.write(contentsOf: data)
} catch {
throw OutputStreamError.unableToWrite(fileURL.path)
}
} else {
// Fallback on earlier versions
fileHandle?.write(data)
}
}

func write(_ string: String) throws {
guard string.isEmpty == false else { return }
_ = try string.utf8.withContiguousStorageIfAvailable { str in
if let baseAddr = str.baseAddress {
fwrite(baseAddr, 1, str.count, filePointer)
} else {
throw OutputStreamError.unableToWrite(fileURL.path)
}
if ferror(filePointer) != 0 {
throw OutputStreamError.unableToWrite(fileURL.path)
}
if let data = string.data(using: .utf8) {
try write(data)
}
}

func close() {
fclose(filePointer)
filePointer = nil
func close() throws {
do {
let existing = fileHandle
fileHandle = nil
if #available(tvOS 13.0, *) {
try existing?.synchronize() // this might be overkill, but JIC.
try existing?.close()
} else {
// Fallback on earlier versions
existing?.synchronizeFile()
existing?.closeFile()
}
} catch {
throw OutputStreamError.unableToClose(fileURL.path)
}
}
}

3 changes: 2 additions & 1 deletion Sources/Segment/Utilities/Storage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -321,10 +321,11 @@ extension Storage {
let fileEnding = "],\"sentAt\":\"\(sentAt)\",\"writeKey\":\"\(writeKey)\"}"
do {
try outputStream.write(fileEnding)
try outputStream.close()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any chance this should be in a finally block?

Copy link
Contributor Author

@bsneed bsneed Nov 30, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No because it throws and we'd need to have another identical catch in the finally block. ... and it's all synchronous anyway.

} catch {
analytics?.reportInternalError(error)
}
outputStream.close()

self.outputStream = nil

let tempFile = file.appendingPathExtension(Storage.tempExtension)
Expand Down
13 changes: 10 additions & 3 deletions Tests/Segment-Tests/Analytics_Tests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -533,16 +533,23 @@ final class Analytics_Tests: XCTestCase {
}

func testRequestFactory() {
let config = Configuration(writeKey: "test").requestFactory { request in
let config = Configuration(writeKey: "testSequential").requestFactory { request in
XCTAssertEqual(request.value(forHTTPHeaderField: "Accept-Encoding"), "gzip")
XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "application/json; charset=utf-8")
XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Basic test")
XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Basic testSequential")
XCTAssertTrue(request.value(forHTTPHeaderField: "User-Agent")!.contains("analytics-ios/"))
return request
}.errorHandler { error in
XCTFail("\(error)")
switch error {
case AnalyticsError.networkServerRejected(_):
// we expect this one; it's a bogus writekey
break;
default:
XCTFail("\(error)")
}
}
let analytics = Analytics(configuration: config)
analytics.storage.hardReset(doYouKnowHowToUseThis: true)
let outputReader = OutputReaderPlugin()
analytics.add(plugin: outputReader)

Expand Down