summaryrefslogtreecommitdiff
path: root/src/main/kotlin/RFC822Parser.kt
blob: 4a6ce7472cfb6154988815b19b1bb048f07a7dab (plain)
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
import kotlinx.coroutines.MainScope
import java.io.ByteArrayOutputStream
import java.io.File

suspend fun main() {
    val io = Protocol.IO.FromStreams(File("samplemail.txt").inputStream(), ByteArrayOutputStream())
    val rfc = RFC822Parser()
    rfc.executeAsync(MainScope(), io).join()
    println(rfc.headers)
    println("Content: ${rfc.content.decodeToString()}")
}

class RFC822Parser() : Protocol() {

    class Header(val field: String, val value: ByteArray)

    private val _headers = mutableListOf<Header>()
    val headers: List<Header> get() = _headers
    lateinit var content: ByteArray
        private set

    override suspend fun IO.execute() {
        while (parseField()) Unit
        content = readAll()
    }

    private suspend fun IO.parseField(): Boolean {
        val read = readUntil(CRLF)
        if (read.contentEquals(CRLF)) {
            return false
        }
        val indexOfColon = read.indexOf(':'.code.toByte())
        if (indexOfColon == -1) {
            throw IllegalStateException("Expected : in MIME header")
        }
        val headerField = read.sliceArray(0 until indexOfColon).decodeToString().trim()
        var data = read.sliceArray(indexOfColon + 1 until read.size)
        while (true) {
            val nextLine = readUntil(CRLF)
            if (nextLine.isNotEmpty() && isWhitespaceCharacter(nextLine[0])) {
                val oldSize = data.size
                data = data.copyOf(oldSize + nextLine.size)
                nextLine.copyInto(data, oldSize)
            } else {
                pushBack(CRLF)
                pushBack(nextLine)
                break
            }
        }
        _headers.add(Header(headerField, data))
        return true
    }

    fun isWhitespaceCharacter(char: Byte): Boolean {
        val char = char.toInt().toChar()
        return char == ' ' || char == '\t'
    }
}