Search code examples
pythonswiftinputstreamnsrange

Swift range exceeds data length


I have a python server that I write and read from, using the stream delegate. It works fine but when I start a match and the server sends data back it crashes.

Here's where it crashes:

func checkForMessages() {
    while true {
        if inputBuffer.length < 4 {
            print("buffer length\(inputBuffer.length)")
            print( MemoryLayout.size(ofValue: Int()))
            print("application quit here")
            return
        }
        var msgLength = (inputBuffer.bytes).load(as: UInt32.self)
        msgLength = UInt32(bigEndian: msgLength)
        print(inputBuffer.length)
        print(msgLength)
        if inputBuffer.length < msgLength {
            print("its returning here!")
            return
        }

        // ******Crashes on the line Below******

        let message: Data? = inputBuffer.subdata(with: NSRange(location: 4, length: Int(msgLength)))
        processMessage(message!)
        let amtRemaining: Int = inputBuffer.length - Int(msgLength) - 4
        if amtRemaining == 0 {
            inputBuffer = NSMutableData()
        }
        else {
            print("Creating input buffer of length \(amtRemaining)")
            inputBuffer = NSMutableData(bytes: inputBuffer.bytes + 4 + Int(msgLength), length: amtRemaining)
        }
    }
}

It crashes when setting "let message".

I have tried a couple of things like trying to mess with the range itself but I'm just not quite sure why its doing what its doing, I can post the server code used to send the message back if needed.


Solution

  • So the problem was fixed by replacing the following part of the code:

     if inputBuffer.length < msgLength {
            return
        }
    

    with

     if inputBuffer.length < msgLength + 4 {
            return
        }