SeafHttpConnection.kt

/*

  Copyright (C) 2026 Sber

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project

  https://dochub.info

  The use of this product or its derivatives for any purpose cannot be a secret.


  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

  Maintainers:
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2026

  Contributors:
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2026
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2026
*/

package org.archtool.helper.git

import org.eclipse.jgit.transport.http.HttpConnection
import java.io.InputStream
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.ProtocolException
import java.net.Proxy
import java.net.URL
import java.security.SecureRandom
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.KeyManager
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import org.slf4j.LoggerFactory

class SeafHttpConnection : HttpConnection {
    val wrappedUrlConnection: HttpURLConnection

    constructor(url: URL, proxy: Proxy) {
        this.wrappedUrlConnection = url.openConnection(proxy) as HttpURLConnection
    }

    constructor(url: URL) {
        this.wrappedUrlConnection = url.openConnection() as HttpURLConnection
    }

    override fun getResponseCode(): Int {
        return wrappedUrlConnection.getResponseCode()
    }

    override fun getURL(): URL? {
        return wrappedUrlConnection.getURL()
    }

    override fun getResponseMessage(): String? {
        return wrappedUrlConnection.getResponseMessage()
    }

    override fun getHeaderFields(): MutableMap<String, MutableList<String>> {
        return wrappedUrlConnection.headerFields
    }

    override fun setRequestProperty(key: String, value: String) {
        wrappedUrlConnection.setRequestProperty(key, value)
    }

    @Throws(ProtocolException::class)
    override fun setRequestMethod(method: String) {
        wrappedUrlConnection.requestMethod = method
    }

    override fun setUseCaches(usecaches: Boolean) {
        wrappedUrlConnection.setUseCaches(usecaches)
    }

    override fun setConnectTimeout(timeout: Int) {
        wrappedUrlConnection.connectTimeout = timeout
    }

    override fun setReadTimeout(timeout: Int) {
        wrappedUrlConnection.readTimeout = timeout
    }

    override fun getContentType(): String? {
        return wrappedUrlConnection.contentType
    }

    override fun getInputStream(): InputStream? {
        return wrappedUrlConnection.getInputStream()
    }

    override fun getHeaderField(name: String): String? {
        return wrappedUrlConnection.getHeaderField(name)
    }

    override fun getHeaderFields(name: String): MutableList<String> {
        val m = wrappedUrlConnection.headerFields
        val fields = mapValuesToListIgnoreCase(name, m)
        return fields
    }

    private fun mapValuesToListIgnoreCase(
        keyName: String,
        m: MutableMap<String?, MutableList<String>?>
    ): MutableList<String> {
        val fields = mutableListOf<String>()
        m.entries
            .filter { e -> keyName.equals(e.key, ignoreCase = true) }
            .filter { e -> e.value != null }
            .forEach { e -> fields.addAll(e.value!!) }
        return fields
    }

    override fun getContentLength(): Int {
        return wrappedUrlConnection.contentLength
    }

    override fun setInstanceFollowRedirects(followRedirects: Boolean) {
        wrappedUrlConnection.setInstanceFollowRedirects(followRedirects)
    }

    override fun setDoOutput(dooutput: Boolean) {
        wrappedUrlConnection.setDoOutput(dooutput)
    }

    override fun setFixedLengthStreamingMode(contentLength: Int) {
        wrappedUrlConnection.setFixedLengthStreamingMode(contentLength)
    }

    override fun getOutputStream(): OutputStream? {
        return wrappedUrlConnection.getOutputStream()
    }

    override fun setChunkedStreamingMode(chunklen: Int) {
        wrappedUrlConnection.setChunkedStreamingMode(chunklen)
    }

    override fun getRequestMethod(): String {
        return wrappedUrlConnection.requestMethod
    }

    override fun usingProxy(): Boolean {
        return wrappedUrlConnection.usingProxy()
    }

    override fun connect() {
        wrappedUrlConnection.connect()
    }

    override fun setHostnameVerifier(hostnameverifier: HostnameVerifier?) {
        if (wrappedUrlConnection !is HttpsURLConnection) {
            log.warn(
                "Для работы с {} выбран режим отличный от https, не смогли настроить hostNameVerifier. " +
                        "Не страшно, если не планировалось использовать ssl. " +
                        "Если надо использовать ssl тогда надо поменять протокол на https",
                wrappedUrlConnection.url
            )
            return
        }
        wrappedUrlConnection.setHostnameVerifier(hostnameverifier)

    }

    override fun configure(km: Array<KeyManager>?, tm: Array<TrustManager>?, random: SecureRandom?) {
        if (wrappedUrlConnection !is HttpsURLConnection) {
            log.warn(
                "Для работы с {} выбран режим отличный от https, не смогли настроить sslFactory. " +
                        "Не страшно, если не планировалось использовать ssl. " +
                        "Если надо использовать ssl тогда надо поменять протокол на https",
                wrappedUrlConnection.url
            )
            return
        }
        val ctx = SSLContext.getInstance("TLS").apply {
            init(km, tm, random)
        }
        wrappedUrlConnection.sslSocketFactory = ctx.socketFactory
    }

    companion object {
        private val log = LoggerFactory.getLogger(SeafHttpConnection::class.java)
    }
}