readStartupMessage reads the initial startup message from the client
(r io.Reader)
| 66 | maxMessageLength = 1 << 30 |
| 67 | ) |
| 68 | |
| 69 | // StartupMessage is the parsed initial message from a PostgreSQL client. Cancel |
| 70 | // credentials intentionally live outside Params: callers log ordinary startup |
| 71 | // fields such as user and application_name, but must never log a cancel key. |
| 72 | type StartupMessage struct { |
| 73 | Params map[string]string |
| 74 | SSLRequest bool |
| 75 | GSSENCRequest bool |
| 76 | CancelRequest bool |
| 77 | CancelCredentialsPresent bool |
| 78 | CancelPID int32 |
| 79 | CancelSecretKey int32 |
| 80 | } |
| 81 | |
| 82 | // ReadStartupMessage reads the initial startup message from the client. |
| 83 | func ReadStartupMessage(r io.Reader) (StartupMessage, error) { |
| 84 | // Read message length (4 bytes) |
| 85 | var length int32 |
| 86 | if err := binary.Read(r, binary.BigEndian, &length); err != nil { |
| 87 | return StartupMessage{}, fmt.Errorf("failed to read startup message length: %w", err) |
| 88 | } |
| 89 | |
| 90 | // Validate before allocating: minimum 8 = length field (4) + protocol |
| 91 | // version (4), which also guarantees remaining[:4] below is in range. |
| 92 | if length < 8 || length > maxStartupMessageLength { |
| 93 | return StartupMessage{}, fmt.Errorf("invalid startup message length: %d", length) |
| 94 | } |
| 95 | |
| 96 | // Read remaining bytes |
| 97 | remaining := make([]byte, length-4) |
| 98 | if _, err := io.ReadFull(r, remaining); err != nil { |
| 99 | return StartupMessage{}, fmt.Errorf("failed to read startup message body: %w", err) |
| 100 | } |
| 101 | |
| 102 | // Read protocol version (4 bytes) |
| 103 | protocolVersion := binary.BigEndian.Uint32(remaining[:4]) |
| 104 | |
| 105 | // Check for SSL request (80877103) |
| 106 | if protocolVersion == 80877103 { |
| 107 | return StartupMessage{SSLRequest: true}, nil |
| 108 | } |
| 109 | |
| 110 | // Check for GSSENCRequest (80877104, PostgreSQL 12+) |
| 111 | // JDBC drivers with gssEncMode=prefer send this before SSLRequest. |
| 112 | if protocolVersion == 80877104 { |
| 113 | return StartupMessage{GSSENCRequest: true}, nil |
| 114 | } |
| 115 | |
| 116 | // Check for cancel request (80877102) |
| 117 | // Format: 4 bytes length, 4 bytes request code, 4 bytes pid, 4 bytes secret key |
| 118 | if protocolVersion == 80877102 { |
| 119 | if len(remaining) >= 12 { |
| 120 | return StartupMessage{ |
| 121 | CancelRequest: true, |
| 122 | CancelCredentialsPresent: true, |
| 123 | CancelPID: int32(binary.BigEndian.Uint32(remaining[4:8])), |
| 124 | CancelSecretKey: int32(binary.BigEndian.Uint32(remaining[8:12])), |
| 125 | }, nil |