Skip to content

Commit 8d1526d

Browse files
committed
working on client ssl network
1 parent fe40ead commit 8d1526d

10 files changed

Lines changed: 187 additions & 103 deletions

File tree

rlib-logger-impl/src/main/java/com/ss/rlib/logger/impl/DefaultLoggerFactory.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -117,11 +117,7 @@ private void write(@NotNull LoggerLevel level, @NotNull String resultMessage) {
117117
listeners.forEachInReadLockR(resultMessage, LoggerListener::println);
118118
writers.forEachInReadLockR(resultMessage, DefaultLoggerFactory::append);
119119

120-
try {
121-
System.err.write((resultMessage + "\n").getBytes());
122-
} catch (IOException e) {
123-
throw new RuntimeException(e);
124-
}
120+
System.err.println(resultMessage);
125121

126122
if (!level.isForceFlush()) {
127123
return;

rlib-network/src/main/java/com/ss/rlib/network/packet/WritablePacket.java

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package com.ss.rlib.network.packet;
22

3+
import com.ss.rlib.logger.api.LoggerManager;
34
import org.jetbrains.annotations.NotNull;
45

6+
import java.nio.BufferOverflowException;
57
import java.nio.ByteBuffer;
68

79
/**
@@ -105,10 +107,19 @@ default void writeShort(@NotNull ByteBuffer buffer, int value) {
105107
* @param string the string for writing.
106108
*/
107109
default void writeString(@NotNull ByteBuffer buffer, @NotNull String string) {
108-
writeInt(buffer, string.length());
110+
try {
109111

110-
for (int i = 0, length = string.length(); i < length; i++) {
111-
buffer.putChar(string.charAt(i));
112+
writeInt(buffer, string.length());
113+
114+
for (int i = 0, length = string.length(); i < length; i++) {
115+
buffer.putChar(string.charAt(i));
116+
}
117+
118+
} catch (BufferOverflowException ex) {
119+
LoggerManager.getLogger(WritablePacket.class)
120+
.error("Cannot write a string to buffer because the string is too long." +
121+
" String length: " + string.length() + ", buffer: " + buffer);
122+
throw ex;
112123
}
113124
}
114125

rlib-network/src/main/java/com/ss/rlib/network/packet/impl/AbstractPacketReader.java

Lines changed: 44 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -34,16 +34,16 @@ public abstract class AbstractPacketReader<R extends ReadablePacket, C extends C
3434

3535
private static final Logger LOGGER = LoggerManager.getLogger(AbstractPacketReader.class);
3636

37-
private final CompletionHandler<Integer, Void> readHandler = new CompletionHandler<>() {
37+
private final CompletionHandler<Integer, ByteBuffer> readHandler = new CompletionHandler<>() {
3838

3939
@Override
40-
public void completed(@NotNull Integer result, @Nullable Void attachment) {
41-
handleReadData(result);
40+
public void completed(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) {
41+
handleReceivedData(receivedBytes, readingBuffer);
4242
}
4343

4444
@Override
45-
public void failed(@NotNull Throwable exc, @Nullable Void attachment) {
46-
handleFailedRead(exc);
45+
public void failed(@NotNull Throwable exc, @NotNull ByteBuffer readingBuffer) {
46+
handleFailedReceiving(exc, readingBuffer);
4747
}
4848
};
4949

@@ -96,7 +96,9 @@ public void startRead() {
9696

9797
LOGGER.debug(channel, ch -> "Start waiting for new data from channel \"" + getRemoteAddress(ch) + "\"");
9898

99-
channel.read(getBufferToReadFromChannel(), null, readHandler);
99+
var buffer = getBufferToReadFromChannel();
100+
101+
channel.read(buffer, buffer, readHandler);
100102
}
101103

102104
/**
@@ -118,24 +120,24 @@ protected int readPackets(@NotNull ByteBuffer receivedBuffer) {
118120
*/
119121
protected int readPackets(@NotNull ByteBuffer receivedBuffer, @NotNull ByteBuffer pendingBuffer) {
120122

121-
LOGGER.debug(receivedBuffer, buf -> "Start reading packets from received buffer: " + buf);
123+
LOGGER.debug(receivedBuffer, buf -> "Start reading packets from received buffer " + buf);
122124

123125
var waitedBytes = pendingBuffer.position();
124126
var bufferToRead = receivedBuffer;
125127
var tempPendingBuffer = getTempPendingBuffer();
126128

127-
// if we have read mapped buffer it means that we are reading a really big packet now
129+
// if we have a temp buffer it means that we are reading a really big packet now
128130
if (tempPendingBuffer != null) {
129131

130132
if (tempPendingBuffer.remaining() < receivedBuffer.remaining()) {
131133
reAllocTempBuffers(tempPendingBuffer.flip(), tempPendingBuffer.capacity());
132134
tempPendingBuffer = notNull(getTempPendingBuffer());
133135
}
134136

135-
LOGGER.debugNullable(
137+
LOGGER.debug(
136138
receivedBuffer,
137139
tempPendingBuffer,
138-
(buf, mappedBuf) -> "Put received buffer: " + buf + " to read mapped buffer: " + mappedBuf
140+
(buf, mappedBuf) -> "Put received buffer " + buf + " to read mapped buffer " + mappedBuf
139141
);
140142

141143
bufferToRead = BufferUtils.putToAndFlip(tempPendingBuffer, receivedBuffer);
@@ -149,8 +151,8 @@ else if (waitedBytes > 0) {
149151
LOGGER.debug(
150152
pendingBuffer,
151153
receivedBuffer,
152-
(penBuf, buf) -> "Pending buffer: " + penBuf + " is too small to append received buffer: " +
153-
buf + ", allocate mapped buffer for this"
154+
(penBuf, buf) -> "Pending buffer " + penBuf + " is too small to append received buffer " +
155+
buf + ", will allocate new temp buffer for this"
154156
);
155157

156158
allocTempBuffers(pendingBuffer.flip(), pendingBuffer.capacity());
@@ -264,23 +266,29 @@ else if (packetLength > tempPendingBuffer.capacity()) {
264266
LOGGER.debug(
265267
channel,
266268
readPackets,
267-
(ch, count) -> "Read " + count + " packet(s) from buffered data of " + getRemoteAddress(ch) + ", " +
269+
(ch, count) -> "Read " + count + " packets from received buffer of " + getRemoteAddress(ch) + ", " +
268270
"but 1 packet is still waiting for receiving additional data."
269271
);
270272

273+
receivedBuffer.clear();
271274
return readPackets;
272275
}
273276

274277
R packet = createPacketFor(bufferToRead, positionBeforeRead, packetLength, dataLength);
275278

276279
if (packet != null) {
277280
LOGGER.debug(packet, pck -> "Created instance of packet to read data: " + pck);
278-
packet.read(connection, bufferToRead, dataLength);
279-
readPacketHandler.accept(packet);
280-
LOGGER.debug(packet, pck -> "Read data of packet: " + pck);
281+
282+
if (packet.read(connection, bufferToRead, dataLength)) {
283+
readPacketHandler.accept(packet);
284+
} else {
285+
LOGGER.error("Packet " + packet + " was read incorrectly");
286+
}
287+
288+
LOGGER.debug(packet, pck -> "Finished reading data of packet: " + pck);
281289
readPackets++;
282290
} else {
283-
LOGGER.warning("Cannot create any instance of packet to read data.");
291+
LOGGER.warning("Cannot create any instance of packet to read data");
284292
}
285293

286294
bufferToRead.position(endPosition);
@@ -301,9 +309,13 @@ else if (packetLength > tempPendingBuffer.capacity()) {
301309
freeTempBuffers();
302310
}
303311

304-
LOGGER.debug(channel, readPackets,
305-
(ch, count) -> "Read " + count + " packet(s) from buffered data of " + getRemoteAddress(ch) + ".");
312+
LOGGER.debug(
313+
channel,
314+
readPackets,
315+
(ch, count) -> "Read " + count + " packets from received buffer of " + getRemoteAddress(ch) + "."
316+
);
306317

318+
receivedBuffer.clear();
307319
return readPackets;
308320
}
309321

@@ -393,32 +405,30 @@ protected void freeTempBuffers() {
393405
}
394406

395407
/**
396-
* Handle read data.
408+
* Handle received data.
397409
*
398-
* @param result the count of read bytes.
410+
* @param receivedBytes the count of received bytes.
411+
* @param readingBuffer the currently reading buffer.
399412
*/
400-
protected void handleReadData(@NotNull Integer result) {
413+
protected void handleReceivedData(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) {
401414
updateActivityFunction.run();
402415

403-
if (result == -1) {
416+
if (receivedBytes == -1) {
404417
connection.close();
405418
return;
406419
}
407420

408421
LOGGER.debug(
409-
result,
422+
receivedBytes,
410423
channel,
411424
(bytes, ch) -> "Received " + bytes + " bytes from channel \"" + NetworkUtils.getRemoteAddress(ch) + "\""
412425
);
413426

414-
var readBuffer = getBufferToReadFromChannel();
415-
readBuffer.flip();
427+
readingBuffer.flip();
416428
try {
417-
readPackets(readBuffer);
429+
readPackets(readingBuffer);
418430
} catch (Exception e) {
419431
LOGGER.error(e);
420-
} finally {
421-
readBuffer.clear();
422432
}
423433

424434
if (isReading.compareAndSet(true, false)) {
@@ -427,13 +437,14 @@ protected void handleReadData(@NotNull Integer result) {
427437
}
428438

429439
/**
430-
* Handle the exception during reading data.
440+
* Handle the exception during receiving data.
431441
*
432-
* @param exception the exception.
442+
* @param exception the exception.
443+
* @param readingBuffer the currently reading buffer.
433444
*/
434-
protected void handleFailedRead(@NotNull Throwable exception) {
445+
protected void handleFailedReceiving(@NotNull Throwable exception, @NotNull ByteBuffer readingBuffer) {
435446
if (exception instanceof AsynchronousCloseException) {
436-
LOGGER.warning(connection, cn -> "Connection " + cn.getRemoteAddress() + " was closed.");
447+
LOGGER.info(connection, cn -> "Connection " + cn.getRemoteAddress() + " was closed.");
437448
} else {
438449
LOGGER.error(exception);
439450
connection.close();

rlib-network/src/main/java/com/ss/rlib/network/packet/impl/AbstractPacketWriter.java

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,8 @@ public void writeNextPacket() {
9999
if (resultBuffer.limit() != 0) {
100100
writingBuffer = resultBuffer;
101101

102-
LOGGER.debug(channel,
102+
LOGGER.debug(
103+
channel,
103104
resultBuffer,
104105
(ch, buf) -> "Write to channel \"" + getRemoteAddress(ch) + "\" data:\n" + hexDump(buf)
105106
);
@@ -121,13 +122,15 @@ public void writeNextPacket() {
121122
W resultPacket = (W) packet;
122123

123124
var expectedLength = packet.getExpectedLength();
124-
var totalSize = getTotalSize(packet, expectedLength);
125+
var totalSize = expectedLength == -1 ? -1 : getTotalSize(packet, expectedLength);
125126

126127
// if the packet is too big to use a write buffer
127128
if (expectedLength != -1 && totalSize > firstWriteBuffer.capacity()) {
128-
firstWriteTempBuffer = bufferAllocator.takeBuffer(totalSize);
129-
secondWriteTempBuffer = bufferAllocator.takeBuffer(totalSize);
130-
return serialize(resultPacket, expectedLength, totalSize, firstWriteTempBuffer, secondWriteTempBuffer);
129+
var first = bufferAllocator.takeBuffer(totalSize);
130+
var second = bufferAllocator.takeBuffer(totalSize);
131+
firstWriteTempBuffer = first;
132+
secondWriteTempBuffer = second;
133+
return serialize(resultPacket, expectedLength, totalSize, first, second);
131134
} else {
132135
return serialize(resultPacket, expectedLength, totalSize, firstWriteBuffer, secondWriteBuffer);
133136
}
@@ -254,22 +257,29 @@ protected boolean onAfterWrite(
254257
}
255258

256259
protected @NotNull ByteBuffer writeHeader(@NotNull ByteBuffer buffer, int position, int value, int headerSize) {
260+
try {
261+
262+
switch (headerSize) {
263+
case 1:
264+
buffer.put(position, (byte) value);
265+
break;
266+
case 2:
267+
buffer.putShort(position, (short) value);
268+
break;
269+
case 4:
270+
buffer.putInt(position, value);
271+
break;
272+
default:
273+
throw new IllegalStateException("Wrong packet's header size: " + headerSize);
274+
}
257275

258-
switch (headerSize) {
259-
case 1:
260-
buffer.put(position, (byte) value);
261-
break;
262-
case 2:
263-
buffer.putShort(position, (short) value);
264-
break;
265-
case 4:
266-
buffer.putInt(position, value);
267-
break;
268-
default:
269-
throw new IllegalStateException("Wrong packet's header size: " + headerSize);
270-
}
276+
return buffer;
271277

272-
return buffer;
278+
} catch (IndexOutOfBoundsException ex) {
279+
LOGGER.error("Cannot write header by position " + position + " with header size " + headerSize +
280+
" to buffer " + buffer);
281+
throw ex;
282+
}
273283
}
274284

275285
protected @NotNull ByteBuffer writeHeader(@NotNull ByteBuffer buffer, int value, int headerSize) {

rlib-network/src/main/java/com/ss/rlib/network/packet/impl/AbstractReadablePacket.java

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import lombok.NoArgsConstructor;
88
import org.jetbrains.annotations.NotNull;
99

10+
import java.nio.BufferUnderflowException;
1011
import java.nio.ByteBuffer;
1112

1213
/**
@@ -133,12 +134,29 @@ protected int readShort(@NotNull ByteBuffer buffer) {
133134
protected @NotNull String readString(@NotNull ByteBuffer buffer) {
134135

135136
var length = readInt(buffer);
136-
var array = new char[length];
137+
try {
137138

138-
for (int i = 0; i < length; i++) {
139-
array[i] = buffer.getChar();
140-
}
139+
var requiredRemainingBytes = length * 2;
140+
141+
if (requiredRemainingBytes > buffer.remaining()) {
142+
throw new IllegalStateException("Found too long string " + length + " from buffer " + buffer);
143+
}
144+
145+
var array = new char[length];
141146

142-
return new String(array);
147+
for (int i = 0; i < length; i++) {
148+
array[i] = buffer.getChar();
149+
}
150+
151+
return new String(array);
152+
153+
} catch (OutOfMemoryError ex) {
154+
LOGGER.error("Cannot read too long \"" + length + "\" string by memory reason");
155+
throw ex;
156+
} catch (BufferUnderflowException ex) {
157+
LOGGER.error("Cannot read string because buffer doesn't contains enough data. " +
158+
"Expected string length " + length + ", buffer " + buffer);
159+
throw ex;
160+
}
143161
}
144162
}

rlib-network/src/main/java/com/ss/rlib/network/packet/impl/AbstractSSLPacketReader.java

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,14 +64,14 @@ protected AbstractSSLPacketReader(
6464
}
6565

6666
@Override
67-
protected void handleReadData(@NotNull Integer result) {
67+
protected void handleReceivedData(@NotNull Integer receivedBytes, @NotNull ByteBuffer readingBuffer) {
6868

69-
if (result == -1) {
70-
doHandshake(getBufferToReadFromChannel(), -1);
69+
if (receivedBytes == -1) {
70+
doHandshake(readingBuffer, -1);
7171
return;
7272
}
7373

74-
super.handleReadData(result);
74+
super.handleReceivedData(receivedBytes, readingBuffer);
7575
}
7676

7777
@Override
@@ -209,10 +209,7 @@ protected int decryptAndRead(@NotNull ByteBuffer receivedBuffer) {
209209
LOGGER.debug(receivedBuffer, buf -> "Try to decrypt data:\n" + hexDump(buf));
210210
result = sslEngine.unwrap(receivedBuffer, sslDataBuffer.clear());
211211
} catch (SSLException e) {
212-
if (e.getCause() instanceof BadPaddingException) {
213-
increaseNetworkBuffer();
214-
return SKIP_READ_PACKETS;
215-
}
212+
var handshakeStatus = sslEngine.getHandshakeStatus();
216213
throw new IllegalStateException(e);
217214
}
218215

@@ -229,10 +226,18 @@ protected int decryptAndRead(@NotNull ByteBuffer receivedBuffer) {
229226
closeConnection();
230227
return SKIP_READ_PACKETS;
231228
default:
229+
230+
if (receivedBuffer.position() > 0) {
231+
receivedBuffer.compact();
232+
return total;
233+
}
234+
232235
throw new IllegalStateException("Invalid SSL status: " + result.getStatus());
233236
}
234237
}
235238

239+
receivedBuffer.clear();
240+
236241
return total;
237242
}
238243

0 commit comments

Comments
 (0)