• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

grpc / grpc-java / #19308

25 Jun 2024 06:38PM CUT coverage: 88.247% (-0.04%) from 88.291%
#19308

push

github

web-flow
okhttp: Workaround SSLSocket not noticing socket is closed (#11323)

Using --runs_per_test=1000, this changes the flake rate of TlsTest from
2% to 0%.

While I believe it is possible to write a reliable test for this
(including noticing the SSLSocket behavior), it was becoming too
invasive so I gave up.

Fixes #11012

Co-authored-by: Eric Anderson <ejona@google.com>

31212 of 35369 relevant lines covered (88.25%)

0.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.41
/../okhttp/src/main/java/io/grpc/okhttp/OkHttpServerTransport.java
1
/*
2
 * Copyright 2022 The gRPC Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package io.grpc.okhttp;
18

19
import static io.grpc.okhttp.OkHttpServerBuilder.MAX_CONNECTION_AGE_NANOS_DISABLED;
20
import static io.grpc.okhttp.OkHttpServerBuilder.MAX_CONNECTION_IDLE_NANOS_DISABLED;
21

22
import com.google.common.base.Preconditions;
23
import com.google.common.util.concurrent.Futures;
24
import com.google.common.util.concurrent.ListenableFuture;
25
import io.grpc.Attributes;
26
import io.grpc.InternalChannelz;
27
import io.grpc.InternalLogId;
28
import io.grpc.InternalStatus;
29
import io.grpc.Metadata;
30
import io.grpc.ServerStreamTracer;
31
import io.grpc.Status;
32
import io.grpc.internal.GrpcUtil;
33
import io.grpc.internal.KeepAliveEnforcer;
34
import io.grpc.internal.KeepAliveManager;
35
import io.grpc.internal.LogExceptionRunnable;
36
import io.grpc.internal.MaxConnectionIdleManager;
37
import io.grpc.internal.ObjectPool;
38
import io.grpc.internal.SerializingExecutor;
39
import io.grpc.internal.ServerTransport;
40
import io.grpc.internal.ServerTransportListener;
41
import io.grpc.internal.StatsTraceContext;
42
import io.grpc.internal.TransportTracer;
43
import io.grpc.okhttp.internal.framed.ErrorCode;
44
import io.grpc.okhttp.internal.framed.FrameReader;
45
import io.grpc.okhttp.internal.framed.FrameWriter;
46
import io.grpc.okhttp.internal.framed.Header;
47
import io.grpc.okhttp.internal.framed.HeadersMode;
48
import io.grpc.okhttp.internal.framed.Http2;
49
import io.grpc.okhttp.internal.framed.Settings;
50
import io.grpc.okhttp.internal.framed.Variant;
51
import java.io.IOException;
52
import java.net.Socket;
53
import java.net.SocketException;
54
import java.util.List;
55
import java.util.Locale;
56
import java.util.Map;
57
import java.util.TreeMap;
58
import java.util.concurrent.Executor;
59
import java.util.concurrent.ScheduledExecutorService;
60
import java.util.concurrent.ScheduledFuture;
61
import java.util.concurrent.TimeUnit;
62
import java.util.logging.Level;
63
import java.util.logging.Logger;
64
import javax.annotation.Nullable;
65
import javax.annotation.concurrent.GuardedBy;
66
import okio.Buffer;
67
import okio.BufferedSource;
68
import okio.ByteString;
69
import okio.Okio;
70

71
/**
72
 * OkHttp-based server transport.
73
 */
74
final class OkHttpServerTransport implements ServerTransport,
75
      ExceptionHandlingFrameWriter.TransportExceptionHandler, OutboundFlowController.Transport {
76
  private static final Logger log = Logger.getLogger(OkHttpServerTransport.class.getName());
1✔
77
  private static final int GRACEFUL_SHUTDOWN_PING = 0x1111;
78

79
  private static final long GRACEFUL_SHUTDOWN_PING_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(1);
1✔
80

81
  private static final int KEEPALIVE_PING = 0xDEAD;
82
  private static final ByteString HTTP_METHOD = ByteString.encodeUtf8(":method");
1✔
83
  private static final ByteString CONNECT_METHOD = ByteString.encodeUtf8("CONNECT");
1✔
84
  private static final ByteString POST_METHOD = ByteString.encodeUtf8("POST");
1✔
85
  private static final ByteString SCHEME = ByteString.encodeUtf8(":scheme");
1✔
86
  private static final ByteString PATH = ByteString.encodeUtf8(":path");
1✔
87
  private static final ByteString AUTHORITY = ByteString.encodeUtf8(":authority");
1✔
88
  private static final ByteString CONNECTION = ByteString.encodeUtf8("connection");
1✔
89
  private static final ByteString HOST = ByteString.encodeUtf8("host");
1✔
90
  private static final ByteString TE = ByteString.encodeUtf8("te");
1✔
91
  private static final ByteString TE_TRAILERS = ByteString.encodeUtf8("trailers");
1✔
92
  private static final ByteString CONTENT_TYPE = ByteString.encodeUtf8("content-type");
1✔
93
  private static final ByteString CONTENT_LENGTH = ByteString.encodeUtf8("content-length");
1✔
94

95
  private final Config config;
96
  private final Variant variant = new Http2();
1✔
97
  private final TransportTracer tracer;
98
  private final InternalLogId logId;
99
  private Socket socket;
100
  private ServerTransportListener listener;
101
  private Executor transportExecutor;
102
  private ScheduledExecutorService scheduledExecutorService;
103
  private Attributes attributes;
104
  private KeepAliveManager keepAliveManager;
105
  private MaxConnectionIdleManager maxConnectionIdleManager;
106
  private ScheduledFuture<?> maxConnectionAgeMonitor;
107
  private final KeepAliveEnforcer keepAliveEnforcer;
108

109
  private final Object lock = new Object();
1✔
110
  @GuardedBy("lock")
111
  private boolean abruptShutdown;
112
  @GuardedBy("lock")
113
  private boolean gracefulShutdown;
114
  @GuardedBy("lock")
115
  private boolean handshakeShutdown;
116
  @GuardedBy("lock")
117
  private InternalChannelz.Security securityInfo;
118
  @GuardedBy("lock")
119
  private ExceptionHandlingFrameWriter frameWriter;
120
  @GuardedBy("lock")
121
  private OutboundFlowController outboundFlow;
122
  @GuardedBy("lock")
1✔
123
  private final Map<Integer, StreamState> streams = new TreeMap<>();
124
  @GuardedBy("lock")
125
  private int lastStreamId;
126
  @GuardedBy("lock")
1✔
127
  private int goAwayStreamId = Integer.MAX_VALUE;
128
  /**
129
   * Indicates the transport is in go-away state: no new streams will be processed, but existing
130
   * streams may continue.
131
   */
132
  @GuardedBy("lock")
133
  private Status goAwayStatus;
134
  /** Non-{@code null} when gracefully shutting down and have not yet sent second GOAWAY. */
135
  @GuardedBy("lock")
136
  private ScheduledFuture<?> secondGoawayTimer;
137
  /** Non-{@code null} when waiting for forceful close GOAWAY to be sent. */
138
  @GuardedBy("lock")
139
  private ScheduledFuture<?> forcefulCloseTimer;
140
  @GuardedBy("lock")
1✔
141
  private Long gracefulShutdownPeriod = null;
142

143
  public OkHttpServerTransport(Config config, Socket bareSocket) {
1✔
144
    this.config = Preconditions.checkNotNull(config, "config");
1✔
145
    this.socket = Preconditions.checkNotNull(bareSocket, "bareSocket");
1✔
146

147
    tracer = config.transportTracerFactory.create();
1✔
148
    tracer.setFlowControlWindowReader(this::readFlowControlWindow);
1✔
149
    logId = InternalLogId.allocate(getClass(), socket.getRemoteSocketAddress().toString());
1✔
150
    transportExecutor = config.transportExecutorPool.getObject();
1✔
151
    scheduledExecutorService = config.scheduledExecutorServicePool.getObject();
1✔
152
    keepAliveEnforcer = new KeepAliveEnforcer(config.permitKeepAliveWithoutCalls,
1✔
153
        config.permitKeepAliveTimeInNanos, TimeUnit.NANOSECONDS);
154
  }
1✔
155

156
  public void start(ServerTransportListener listener) {
157
    this.listener = Preconditions.checkNotNull(listener, "listener");
1✔
158

159
    SerializingExecutor serializingExecutor = new SerializingExecutor(transportExecutor);
1✔
160
    serializingExecutor.execute(() -> startIo(serializingExecutor));
1✔
161
  }
1✔
162

163
  private void startIo(SerializingExecutor serializingExecutor) {
164
    try {
165
      // The socket implementation is lazily initialized, but had broken thread-safety 
166
      // for that laziness https://bugs.openjdk.org/browse/JDK-8278326. 
167
      // As a workaround, we lock to synchronize initialization with shutdown().
168
      synchronized (lock) {
1✔
169
        socket.setTcpNoDelay(true);
1✔
170
      }
1✔
171
      HandshakerSocketFactory.HandshakeResult result =
1✔
172
          config.handshakerSocketFactory.handshake(socket, Attributes.EMPTY);
1✔
173
      synchronized (lock) {
1✔
174
        if (socket.isClosed()) {
1✔
175
          // The wrapped socket may not handle the underlying socket being closed by shutdown(). In
176
          // particular, SSLSocket hangs future reads if the underlying socket is already closed at
177
          // this point, even if you call sslSocket.close() later.
178
          result.socket.close();
×
179
          throw new SocketException("Socket close raced with handshake");
×
180
        }
181
        this.socket = result.socket;
1✔
182
      }
1✔
183
      this.attributes = result.attributes;
1✔
184

185
      int maxQueuedControlFrames = 10000;
1✔
186
      AsyncSink asyncSink = AsyncSink.sink(serializingExecutor, this, maxQueuedControlFrames);
1✔
187
      asyncSink.becomeConnected(Okio.sink(socket), socket);
1✔
188
      FrameWriter rawFrameWriter = asyncSink.limitControlFramesWriter(
1✔
189
          variant.newWriter(Okio.buffer(asyncSink), false));
1✔
190
      FrameWriter writeMonitoringFrameWriter = new ForwardingFrameWriter(rawFrameWriter) {
1✔
191
        @Override
192
        public void synReply(boolean outFinished, int streamId, List<Header> headerBlock)
193
            throws IOException {
194
          keepAliveEnforcer.resetCounters();
1✔
195
          super.synReply(outFinished, streamId, headerBlock);
1✔
196
        }
1✔
197

198
        @Override
199
        public void headers(int streamId, List<Header> headerBlock) throws IOException {
200
          keepAliveEnforcer.resetCounters();
1✔
201
          super.headers(streamId, headerBlock);
1✔
202
        }
1✔
203

204
        @Override
205
        public void data(boolean outFinished, int streamId, Buffer source, int byteCount)
206
            throws IOException {
207
          keepAliveEnforcer.resetCounters();
1✔
208
          super.data(outFinished, streamId, source, byteCount);
1✔
209
        }
1✔
210
      };
211
      synchronized (lock) {
1✔
212
        this.securityInfo = result.securityInfo;
1✔
213

214
        // Handle FrameWriter exceptions centrally, since there are many callers. Note that
215
        // errors coming from rawFrameWriter are generally broken invariants/bugs, as AsyncSink
216
        // does not propagate syscall errors through the FrameWriter. But we handle the
217
        // AsyncSink failures with the same TransportExceptionHandler instance so it is all
218
        // mixed back together.
219
        frameWriter = new ExceptionHandlingFrameWriter(this, writeMonitoringFrameWriter);
1✔
220
        outboundFlow = new OutboundFlowController(this, frameWriter);
1✔
221

222
        // These writes will be queued in the serializingExecutor waiting for this function to
223
        // return.
224
        frameWriter.connectionPreface();
1✔
225
        Settings settings = new Settings();
1✔
226
        OkHttpSettingsUtil.set(settings,
1✔
227
            OkHttpSettingsUtil.INITIAL_WINDOW_SIZE, config.flowControlWindow);
228
        OkHttpSettingsUtil.set(settings,
1✔
229
            OkHttpSettingsUtil.MAX_HEADER_LIST_SIZE, config.maxInboundMetadataSize);
230
        frameWriter.settings(settings);
1✔
231
        if (config.flowControlWindow > Utils.DEFAULT_WINDOW_SIZE) {
1✔
232
          frameWriter.windowUpdate(
1✔
233
              Utils.CONNECTION_STREAM_ID, config.flowControlWindow - Utils.DEFAULT_WINDOW_SIZE);
234
        }
235
        frameWriter.flush();
1✔
236
      }
1✔
237

238
      if (config.keepAliveTimeNanos != GrpcUtil.KEEPALIVE_TIME_NANOS_DISABLED) {
1✔
239
        keepAliveManager = new KeepAliveManager(
1✔
240
            new KeepAlivePinger(), scheduledExecutorService, config.keepAliveTimeNanos,
241
            config.keepAliveTimeoutNanos, true);
242
        keepAliveManager.onTransportStarted();
1✔
243
      }
244

245
      if (config.maxConnectionIdleNanos != MAX_CONNECTION_IDLE_NANOS_DISABLED) {
1✔
246
        maxConnectionIdleManager = new MaxConnectionIdleManager(config.maxConnectionIdleNanos);
1✔
247
        maxConnectionIdleManager.start(this::shutdown, scheduledExecutorService);
1✔
248
      }
249

250
      if (config.maxConnectionAgeInNanos != MAX_CONNECTION_AGE_NANOS_DISABLED) {
1✔
251
        long maxConnectionAgeInNanos =
1✔
252
            (long) ((.9D + Math.random() * .2D) * config.maxConnectionAgeInNanos);
1✔
253
        maxConnectionAgeMonitor = scheduledExecutorService.schedule(
1✔
254
            new LogExceptionRunnable(() -> shutdown(config.maxConnectionAgeGraceInNanos)),
1✔
255
            maxConnectionAgeInNanos,
256
            TimeUnit.NANOSECONDS);
257
      }
258

259
      transportExecutor.execute(new FrameHandler(
1✔
260
          variant.newReader(Okio.buffer(Okio.source(socket)), false)));
1✔
261
    } catch (Error | IOException | RuntimeException ex) {
1✔
262
      synchronized (lock) {
1✔
263
        if (!handshakeShutdown) {
1✔
264
          log.log(Level.INFO, "Socket failed to handshake", ex);
1✔
265
        }
266
      }
1✔
267
      GrpcUtil.closeQuietly(socket);
1✔
268
      terminated();
1✔
269
    }
1✔
270
  }
1✔
271

272
  @Override
273
  public void shutdown() {
274
    shutdown(null);
1✔
275
  }
1✔
276

277
  private void shutdown(@Nullable Long gracefulShutdownPeriod) {
278
    synchronized (lock) {
1✔
279
      if (gracefulShutdown || abruptShutdown) {
1✔
280
        return;
1✔
281
      }
282
      gracefulShutdown = true;
1✔
283
      this.gracefulShutdownPeriod = gracefulShutdownPeriod;
1✔
284
      if (frameWriter == null) {
1✔
285
        handshakeShutdown = true;
1✔
286
        GrpcUtil.closeQuietly(socket);
1✔
287
      } else {
288
        // RFC7540 §6.8. Begin double-GOAWAY graceful shutdown. To wait one RTT we use a PING, but
289
        // we also set a timer to limit the upper bound in case the PING is excessively stalled or
290
        // the client is malicious.
291
        secondGoawayTimer = scheduledExecutorService.schedule(
1✔
292
            this::triggerGracefulSecondGoaway,
293
            GRACEFUL_SHUTDOWN_PING_TIMEOUT_NANOS, TimeUnit.NANOSECONDS);
294
        frameWriter.goAway(Integer.MAX_VALUE, ErrorCode.NO_ERROR, new byte[0]);
1✔
295
        frameWriter.ping(false, 0, GRACEFUL_SHUTDOWN_PING);
1✔
296
        frameWriter.flush();
1✔
297
      }
298
    }
1✔
299
  }
1✔
300

301
  private void triggerGracefulSecondGoaway() {
302
    synchronized (lock) {
1✔
303
      if (secondGoawayTimer == null) {
1✔
304
        return;
×
305
      }
306
      secondGoawayTimer.cancel(false);
1✔
307
      secondGoawayTimer = null;
1✔
308
      frameWriter.goAway(lastStreamId, ErrorCode.NO_ERROR, new byte[0]);
1✔
309
      goAwayStreamId = lastStreamId;
1✔
310
      if (streams.isEmpty()) {
1✔
311
        frameWriter.close();
1✔
312
      } else {
313
        frameWriter.flush();
1✔
314
      }
315
      if (gracefulShutdownPeriod != null) {
1✔
316
        forcefulCloseTimer = scheduledExecutorService.schedule(
1✔
317
            this::triggerForcefulClose, gracefulShutdownPeriod, TimeUnit.NANOSECONDS);
1✔
318
      }
319
    }
1✔
320
  }
1✔
321

322
  @Override
323
  public void shutdownNow(Status reason) {
324
    synchronized (lock) {
1✔
325
      if (frameWriter == null) {
1✔
326
        handshakeShutdown = true;
1✔
327
        GrpcUtil.closeQuietly(socket);
1✔
328
        return;
1✔
329
      }
330
    }
1✔
331
    abruptShutdown(ErrorCode.NO_ERROR, "", reason, true);
1✔
332
  }
1✔
333

334
  /**
335
   * Finish all active streams due to an IOException, then close the transport.
336
   */
337
  @Override
338
  public void onException(Throwable failureCause) {
339
    Preconditions.checkNotNull(failureCause, "failureCause");
1✔
340
    Status status = Status.UNAVAILABLE.withCause(failureCause);
1✔
341
    abruptShutdown(ErrorCode.INTERNAL_ERROR, "I/O failure", status, false);
1✔
342
  }
1✔
343

344
  private void abruptShutdown(
345
      ErrorCode errorCode, String moreDetail, Status reason, boolean rstStreams) {
346
    synchronized (lock) {
1✔
347
      if (abruptShutdown) {
1✔
348
        return;
1✔
349
      }
350
      abruptShutdown = true;
1✔
351
      goAwayStatus = reason;
1✔
352

353
      if (secondGoawayTimer != null) {
1✔
354
        secondGoawayTimer.cancel(false);
1✔
355
        secondGoawayTimer = null;
1✔
356
      }
357
      for (Map.Entry<Integer, StreamState> entry : streams.entrySet()) {
1✔
358
        if (rstStreams) {
1✔
359
          frameWriter.rstStream(entry.getKey(), ErrorCode.CANCEL);
1✔
360
        }
361
        entry.getValue().transportReportStatus(reason);
1✔
362
      }
1✔
363
      streams.clear();
1✔
364

365
      // RFC7540 §5.4.1. Attempt to inform the client what went wrong. We try to write the GOAWAY
366
      // _and then_ close our side of the connection. But place an upper-bound for how long we wait
367
      // for I/O with a timer, which forcefully closes the socket.
368
      frameWriter.goAway(lastStreamId, errorCode, moreDetail.getBytes(GrpcUtil.US_ASCII));
1✔
369
      goAwayStreamId = lastStreamId;
1✔
370
      frameWriter.close();
1✔
371
      forcefulCloseTimer = scheduledExecutorService.schedule(
1✔
372
          this::triggerForcefulClose, 1, TimeUnit.SECONDS);
373
    }
1✔
374
  }
1✔
375

376
  private void triggerForcefulClose() {
377
    // Safe to do unconditionally; no need to check if timer cancellation raced
378
    GrpcUtil.closeQuietly(socket);
1✔
379
  }
1✔
380

381
  private void terminated() {
382
    synchronized (lock) {
1✔
383
      if (forcefulCloseTimer != null) {
1✔
384
        forcefulCloseTimer.cancel(false);
1✔
385
        forcefulCloseTimer = null;
1✔
386
      }
387
    }
1✔
388
    if (keepAliveManager != null) {
1✔
389
      keepAliveManager.onTransportTermination();
1✔
390
    }
391
    if (maxConnectionIdleManager != null) {
1✔
392
      maxConnectionIdleManager.onTransportTermination();
1✔
393
    }
394

395
    if (maxConnectionAgeMonitor != null) {
1✔
396
      maxConnectionAgeMonitor.cancel(false);
1✔
397
    }
398
    transportExecutor = config.transportExecutorPool.returnObject(transportExecutor);
1✔
399
    scheduledExecutorService =
1✔
400
        config.scheduledExecutorServicePool.returnObject(scheduledExecutorService);
1✔
401
    listener.transportTerminated();
1✔
402
  }
1✔
403

404
  @Override
405
  public ScheduledExecutorService getScheduledExecutorService() {
406
    return scheduledExecutorService;
1✔
407
  }
408

409
  @Override
410
  public ListenableFuture<InternalChannelz.SocketStats> getStats() {
411
    synchronized (lock) {
1✔
412
      return Futures.immediateFuture(new InternalChannelz.SocketStats(
1✔
413
          tracer.getStats(),
1✔
414
          socket.getLocalSocketAddress(),
1✔
415
          socket.getRemoteSocketAddress(),
1✔
416
          Utils.getSocketOptions(socket),
1✔
417
          securityInfo));
418
    }
419
  }
420

421
  private TransportTracer.FlowControlWindows readFlowControlWindow() {
422
    synchronized (lock) {
1✔
423
      long local = outboundFlow == null ? -1 : outboundFlow.windowUpdate(null, 0);
1✔
424
      // connectionUnacknowledgedBytesRead is only readable by FrameHandler, so we provide a lower
425
      // bound.
426
      long remote = (long) (config.flowControlWindow * Utils.DEFAULT_WINDOW_UPDATE_RATIO);
1✔
427
      return new TransportTracer.FlowControlWindows(local, remote);
1✔
428
    }
429
  }
430

431
  @Override
432
  public InternalLogId getLogId() {
433
    return logId;
1✔
434
  }
435

436
  @Override
437
  public OutboundFlowController.StreamState[] getActiveStreams() {
438
    synchronized (lock) {
1✔
439
      OutboundFlowController.StreamState[] flowStreams =
1✔
440
          new OutboundFlowController.StreamState[streams.size()];
1✔
441
      int i = 0;
1✔
442
      for (StreamState stream : streams.values()) {
1✔
443
        flowStreams[i++] = stream.getOutboundFlowState();
1✔
444
      }
1✔
445
      return flowStreams;
1✔
446
    }
447
  }
448

449
  /**
450
   * Notify the transport that the stream was closed. Any frames for the stream must be enqueued
451
   * before calling.
452
   */
453
  void streamClosed(int streamId, boolean flush) {
454
    synchronized (lock) {
1✔
455
      streams.remove(streamId);
1✔
456
      if (streams.isEmpty()) {
1✔
457
        keepAliveEnforcer.onTransportIdle();
1✔
458
        if (maxConnectionIdleManager != null) {
1✔
459
          maxConnectionIdleManager.onTransportIdle();
1✔
460
        }
461
      }
462
      if (gracefulShutdown && streams.isEmpty()) {
1✔
463
        frameWriter.close();
1✔
464
      } else {
465
        if (flush) {
1✔
466
          frameWriter.flush();
1✔
467
        }
468
      }
469
    }
1✔
470
  }
1✔
471

472
  private static String asciiString(ByteString value) {
473
    // utf8() string is cached in ByteString, so we prefer it when the contents are ASCII. This
474
    // provides benefit if the header was reused via HPACK.
475
    for (int i = 0; i < value.size(); i++) {
1✔
476
      if (value.getByte(i) < 0) {
1✔
477
        return value.string(GrpcUtil.US_ASCII);
×
478
      }
479
    }
480
    return value.utf8();
1✔
481
  }
482

483
  private static int headerFind(List<Header> header, ByteString key, int startIndex) {
484
    for (int i = startIndex; i < header.size(); i++) {
1✔
485
      if (header.get(i).name.equals(key)) {
1✔
486
        return i;
1✔
487
      }
488
    }
489
    return -1;
1✔
490
  }
491

492
  private static boolean headerContains(List<Header> header, ByteString key) {
493
    return headerFind(header, key, 0) != -1;
1✔
494
  }
495

496
  private static void headerRemove(List<Header> header, ByteString key) {
497
    int i = 0;
1✔
498
    while ((i = headerFind(header, key, i)) != -1) {
1✔
499
      header.remove(i);
1✔
500
    }
501
  }
1✔
502

503
  /** Assumes that caller requires this field, so duplicates are treated as missing. */
504
  private static ByteString headerGetRequiredSingle(List<Header> header, ByteString key) {
505
    int i = headerFind(header, key, 0);
1✔
506
    if (i == -1) {
1✔
507
      return null;
1✔
508
    }
509
    if (headerFind(header, key, i + 1) != -1) {
1✔
510
      return null;
1✔
511
    }
512
    return header.get(i).value;
1✔
513
  }
514

515
  static final class Config {
516
    final List<? extends ServerStreamTracer.Factory> streamTracerFactories;
517
    final ObjectPool<Executor> transportExecutorPool;
518
    final ObjectPool<ScheduledExecutorService> scheduledExecutorServicePool;
519
    final TransportTracer.Factory transportTracerFactory;
520
    final HandshakerSocketFactory handshakerSocketFactory;
521
    final long keepAliveTimeNanos;
522
    final long keepAliveTimeoutNanos;
523
    final int flowControlWindow;
524
    final int maxInboundMessageSize;
525
    final int maxInboundMetadataSize;
526
    final long maxConnectionIdleNanos;
527
    final boolean permitKeepAliveWithoutCalls;
528
    final long permitKeepAliveTimeInNanos;
529
    final long maxConnectionAgeInNanos;
530
    final long maxConnectionAgeGraceInNanos;
531

532
    public Config(
533
        OkHttpServerBuilder builder,
534
        List<? extends ServerStreamTracer.Factory> streamTracerFactories) {
1✔
535
      this.streamTracerFactories = Preconditions.checkNotNull(
1✔
536
          streamTracerFactories, "streamTracerFactories");
537
      transportExecutorPool = Preconditions.checkNotNull(
1✔
538
          builder.transportExecutorPool, "transportExecutorPool");
539
      scheduledExecutorServicePool = Preconditions.checkNotNull(
1✔
540
          builder.scheduledExecutorServicePool, "scheduledExecutorServicePool");
541
      transportTracerFactory = Preconditions.checkNotNull(
1✔
542
          builder.transportTracerFactory, "transportTracerFactory");
543
      handshakerSocketFactory = Preconditions.checkNotNull(
1✔
544
          builder.handshakerSocketFactory, "handshakerSocketFactory");
545
      keepAliveTimeNanos = builder.keepAliveTimeNanos;
1✔
546
      keepAliveTimeoutNanos = builder.keepAliveTimeoutNanos;
1✔
547
      flowControlWindow = builder.flowControlWindow;
1✔
548
      maxInboundMessageSize = builder.maxInboundMessageSize;
1✔
549
      maxInboundMetadataSize = builder.maxInboundMetadataSize;
1✔
550
      maxConnectionIdleNanos = builder.maxConnectionIdleInNanos;
1✔
551
      permitKeepAliveWithoutCalls = builder.permitKeepAliveWithoutCalls;
1✔
552
      permitKeepAliveTimeInNanos = builder.permitKeepAliveTimeInNanos;
1✔
553
      maxConnectionAgeInNanos = builder.maxConnectionAgeInNanos;
1✔
554
      maxConnectionAgeGraceInNanos = builder.maxConnectionAgeGraceInNanos;
1✔
555
    }
1✔
556
  }
557

558
  /**
559
   * Runnable which reads frames and dispatches them to in flight calls.
560
   */
561
  class FrameHandler implements FrameReader.Handler, Runnable {
562
    private final OkHttpFrameLogger frameLogger =
1✔
563
        new OkHttpFrameLogger(Level.FINE, OkHttpServerTransport.class);
564
    private final FrameReader frameReader;
565
    private boolean receivedSettings;
566
    private int connectionUnacknowledgedBytesRead;
567

568
    public FrameHandler(FrameReader frameReader) {
1✔
569
      this.frameReader = frameReader;
1✔
570
    }
1✔
571

572
    @Override
573
    public void run() {
574
      String threadName = Thread.currentThread().getName();
1✔
575
      Thread.currentThread().setName("OkHttpServerTransport");
1✔
576
      try {
577
        frameReader.readConnectionPreface();
1✔
578
        if (!frameReader.nextFrame(this)) {
1✔
579
          connectionError(ErrorCode.INTERNAL_ERROR, "Failed to read initial SETTINGS");
1✔
580
          return;
1✔
581
        }
582
        if (!receivedSettings) {
1✔
583
          connectionError(ErrorCode.PROTOCOL_ERROR,
1✔
584
              "First HTTP/2 frame must be SETTINGS. RFC7540 section 3.5");
585
          return;
1✔
586
        }
587
        // Read until the underlying socket closes.
588
        while (frameReader.nextFrame(this)) {
1✔
589
          if (keepAliveManager != null) {
1✔
590
            keepAliveManager.onDataReceived();
1✔
591
          }
592
        }
593
        // frameReader.nextFrame() returns false when the underlying read encounters an IOException,
594
        // it may be triggered by the socket closing, in such case, the startGoAway() will do
595
        // nothing, otherwise, we finish all streams since it's a real IO issue.
596
        Status status;
597
        synchronized (lock) {
1✔
598
          status = goAwayStatus;
1✔
599
        }
1✔
600
        if (status == null) {
1✔
601
          status = Status.UNAVAILABLE.withDescription("TCP connection closed or IOException");
1✔
602
        }
603
        abruptShutdown(ErrorCode.INTERNAL_ERROR, "I/O failure", status, false);
1✔
604
      } catch (Throwable t) {
1✔
605
        log.log(Level.WARNING, "Error decoding HTTP/2 frames", t);
1✔
606
        abruptShutdown(ErrorCode.INTERNAL_ERROR, "Error in frame decoder",
1✔
607
            Status.INTERNAL.withDescription("Error decoding HTTP/2 frames").withCause(t), false);
1✔
608
      } finally {
609
        // Wait for the abrupt shutdown to be processed by AsyncSink and close the socket
610
        try {
611
          GrpcUtil.exhaust(socket.getInputStream());
1✔
612
        } catch (IOException ex) {
1✔
613
          // Unable to wait, so just proceed to tear-down. The socket is probably already closed so
614
          // the GOAWAY can't be sent anyway.
615
        }
1✔
616
        GrpcUtil.closeQuietly(socket);
1✔
617
        terminated();
1✔
618
        Thread.currentThread().setName(threadName);
1✔
619
      }
620
    }
1✔
621

622
    /**
623
     * Handle HTTP2 HEADER and CONTINUATION frames.
624
     */
625
    @Override
626
    public void headers(boolean outFinished,
627
        boolean inFinished,
628
        int streamId,
629
        int associatedStreamId,
630
        List<Header> headerBlock,
631
        HeadersMode headersMode) {
632
      frameLogger.logHeaders(
1✔
633
          OkHttpFrameLogger.Direction.INBOUND, streamId, headerBlock, inFinished);
634
      // streamId == 0 checking is in HTTP/2 decoder
635
      if ((streamId & 1) == 0) {
1✔
636
        // The server doesn't use PUSH_PROMISE, so all even streams are IDLE
637
        connectionError(ErrorCode.PROTOCOL_ERROR,
1✔
638
            "Clients cannot open even numbered streams. RFC7540 section 5.1.1");
639
        return;
1✔
640
      }
641
      boolean newStream;
642
      synchronized (lock) {
1✔
643
        if (streamId > goAwayStreamId) {
1✔
644
          return;
×
645
        }
646
        newStream = streamId > lastStreamId;
1✔
647
        if (newStream) {
1✔
648
          lastStreamId = streamId;
1✔
649
        }
650
      }
1✔
651

652
      int metadataSize = headerBlockSize(headerBlock);
1✔
653
      if (metadataSize > config.maxInboundMetadataSize) {
1✔
654
        respondWithHttpError(streamId, inFinished, 431, Status.Code.RESOURCE_EXHAUSTED,
1✔
655
            String.format(
1✔
656
                Locale.US,
657
                "Request metadata larger than %d: %d",
658
                config.maxInboundMetadataSize,
1✔
659
                metadataSize));
1✔
660
        return;
1✔
661
      }
662

663
      headerRemove(headerBlock, ByteString.EMPTY);
1✔
664

665
      ByteString httpMethod = null;
1✔
666
      ByteString scheme = null;
1✔
667
      ByteString path = null;
1✔
668
      ByteString authority = null;
1✔
669
      while (headerBlock.size() > 0 && headerBlock.get(0).name.getByte(0) == ':') {
1✔
670
        Header header = headerBlock.remove(0);
1✔
671
        if (HTTP_METHOD.equals(header.name) && httpMethod == null) {
1✔
672
          httpMethod = header.value;
1✔
673
        } else if (SCHEME.equals(header.name) && scheme == null) {
1✔
674
          scheme = header.value;
1✔
675
        } else if (PATH.equals(header.name) && path == null) {
1✔
676
          path = header.value;
1✔
677
        } else if (AUTHORITY.equals(header.name) && authority == null) {
1✔
678
          authority = header.value;
1✔
679
        } else {
680
          streamError(streamId, ErrorCode.PROTOCOL_ERROR,
1✔
681
              "Unexpected pseudo header. RFC7540 section 8.1.2.1");
682
          return;
1✔
683
        }
684
      }
1✔
685
      for (int i = 0; i < headerBlock.size(); i++) {
1✔
686
        if (headerBlock.get(i).name.getByte(0) == ':') {
1✔
687
          streamError(streamId, ErrorCode.PROTOCOL_ERROR,
1✔
688
              "Pseudo header not before regular headers. RFC7540 section 8.1.2.1");
689
          return;
1✔
690
        }
691
      }
692
      if (!CONNECT_METHOD.equals(httpMethod)
1✔
693
          && newStream
694
          && (httpMethod == null || scheme == null || path == null)) {
695
        streamError(streamId, ErrorCode.PROTOCOL_ERROR,
1✔
696
            "Missing required pseudo header. RFC7540 section 8.1.2.3");
697
        return;
1✔
698
      }
699
      if (headerContains(headerBlock, CONNECTION)) {
1✔
700
        streamError(streamId, ErrorCode.PROTOCOL_ERROR,
1✔
701
            "Connection-specific headers not permitted. RFC7540 section 8.1.2.2");
702
        return;
1✔
703
      }
704

705
      if (!newStream) {
1✔
706
        if (inFinished) {
1✔
707
          synchronized (lock) {
1✔
708
            StreamState stream = streams.get(streamId);
1✔
709
            if (stream == null) {
1✔
710
              streamError(streamId, ErrorCode.STREAM_CLOSED, "Received headers for closed stream");
×
711
              return;
×
712
            }
713
            if (stream.hasReceivedEndOfStream()) {
1✔
714
              streamError(streamId, ErrorCode.STREAM_CLOSED,
1✔
715
                  "Received HEADERS for half-closed (remote) stream. RFC7540 section 5.1");
716
              return;
1✔
717
            }
718
            // Ignore the trailers, but still half-close the stream
719
            stream.inboundDataReceived(new Buffer(), 0, 0, true);
1✔
720
            return;
1✔
721
          }
722
        } else {
723
          streamError(streamId, ErrorCode.PROTOCOL_ERROR,
1✔
724
              "Headers disallowed in the middle of the stream. RFC7540 section 8.1");
725
          return;
1✔
726
        }
727
      }
728

729
      if (authority == null) {
1✔
730
        int i = headerFind(headerBlock, HOST, 0);
1✔
731
        if (i != -1) {
1✔
732
          if (headerFind(headerBlock, HOST, i + 1) != -1) {
1✔
733
            respondWithHttpError(streamId, inFinished, 400, Status.Code.INTERNAL,
1✔
734
                "Multiple host headers disallowed. RFC7230 section 5.4");
735
            return;
1✔
736
          }
737
          authority = headerBlock.get(i).value;
1✔
738
        }
739
      }
740
      headerRemove(headerBlock, HOST);
1✔
741

742
      // Remove the leading slash of the path and get the fully qualified method name
743
      if (path.size() == 0 || path.getByte(0) != '/') {
1✔
744
        respondWithHttpError(streamId, inFinished, 404, Status.Code.UNIMPLEMENTED,
1✔
745
            "Expected path to start with /: " + asciiString(path));
1✔
746
        return;
1✔
747
      }
748
      String method = asciiString(path).substring(1);
1✔
749

750
      ByteString contentType = headerGetRequiredSingle(headerBlock, CONTENT_TYPE);
1✔
751
      if (contentType == null) {
1✔
752
        respondWithHttpError(streamId, inFinished, 415, Status.Code.INTERNAL,
1✔
753
            "Content-Type is missing or duplicated");
754
        return;
1✔
755
      }
756
      String contentTypeString = asciiString(contentType);
1✔
757
      if (!GrpcUtil.isGrpcContentType(contentTypeString)) {
1✔
758
        respondWithHttpError(streamId, inFinished, 415, Status.Code.INTERNAL,
1✔
759
            "Content-Type is not supported: " + contentTypeString);
760
        return;
1✔
761
      }
762

763
      if (!POST_METHOD.equals(httpMethod)) {
1✔
764
        respondWithHttpError(streamId, inFinished, 405, Status.Code.INTERNAL,
1✔
765
            "HTTP Method is not supported: " + asciiString(httpMethod));
1✔
766
        return;
1✔
767
      }
768

769
      ByteString te = headerGetRequiredSingle(headerBlock, TE);
1✔
770
      if (!TE_TRAILERS.equals(te)) {
1✔
771
        respondWithGrpcError(streamId, inFinished, Status.Code.INTERNAL,
1✔
772
            String.format("Expected header TE: %s, but %s is received. "
1✔
773
              + "Some intermediate proxy may not support trailers",
774
              asciiString(TE_TRAILERS), te == null ? "<missing>" : asciiString(te)));
1✔
775
        return;
1✔
776
      }
777
      headerRemove(headerBlock, CONTENT_LENGTH);
1✔
778

779
      Metadata metadata = Utils.convertHeaders(headerBlock);
1✔
780
      StatsTraceContext statsTraceCtx =
1✔
781
          StatsTraceContext.newServerContext(config.streamTracerFactories, method, metadata);
1✔
782
      synchronized (lock) {
1✔
783
        OkHttpServerStream.TransportState stream = new OkHttpServerStream.TransportState(
1✔
784
            OkHttpServerTransport.this,
785
            streamId,
786
            config.maxInboundMessageSize,
1✔
787
            statsTraceCtx,
788
            lock,
1✔
789
            frameWriter,
1✔
790
            outboundFlow,
1✔
791
            config.flowControlWindow,
1✔
792
            tracer,
1✔
793
            method);
794
        OkHttpServerStream streamForApp = new OkHttpServerStream(
1✔
795
            stream,
796
            attributes,
1✔
797
            authority == null ? null : asciiString(authority),
1✔
798
            statsTraceCtx,
799
            tracer);
1✔
800
        if (streams.isEmpty()) {
1✔
801
          keepAliveEnforcer.onTransportActive();
1✔
802
          if (maxConnectionIdleManager != null) {
1✔
803
            maxConnectionIdleManager.onTransportActive();
1✔
804
          }
805
        }
806
        streams.put(streamId, stream);
1✔
807
        listener.streamCreated(streamForApp, method, metadata);
1✔
808
        stream.onStreamAllocated();
1✔
809
        if (inFinished) {
1✔
810
          stream.inboundDataReceived(new Buffer(), 0, 0, inFinished);
1✔
811
        }
812
      }
1✔
813
    }
1✔
814

815
    private int headerBlockSize(List<Header> headerBlock) {
816
      // Calculate as defined for SETTINGS_MAX_HEADER_LIST_SIZE in RFC 7540 §6.5.2.
817
      long size = 0;
1✔
818
      for (int i = 0; i < headerBlock.size(); i++) {
1✔
819
        Header header = headerBlock.get(i);
1✔
820
        size += 32 + header.name.size() + header.value.size();
1✔
821
      }
822
      size = Math.min(size, Integer.MAX_VALUE);
1✔
823
      return (int) size;
1✔
824
    }
825

826
    /**
827
     * Handle an HTTP2 DATA frame.
828
     */
829
    @Override
830
    public void data(boolean inFinished, int streamId, BufferedSource in, int length,
831
                     int paddedLength)
832
        throws IOException {
833
      frameLogger.logData(
1✔
834
          OkHttpFrameLogger.Direction.INBOUND, streamId, in.getBuffer(), length, inFinished);
1✔
835
      if (streamId == 0) {
1✔
836
        connectionError(ErrorCode.PROTOCOL_ERROR,
1✔
837
            "Stream 0 is reserved for control messages. RFC7540 section 5.1.1");
838
        return;
1✔
839
      }
840
      if ((streamId & 1) == 0) {
1✔
841
        // The server doesn't use PUSH_PROMISE, so all even streams are IDLE
842
        connectionError(ErrorCode.PROTOCOL_ERROR,
1✔
843
            "Clients cannot open even numbered streams. RFC7540 section 5.1.1");
844
        return;
1✔
845
      }
846

847
      // Wait until the frame is complete. We only support 16 KiB frames, and the max permitted in
848
      // HTTP/2 is 16 MiB. This is verified in OkHttp's Http2 deframer, so we don't need to be
849
      // concerned with the window being exceeded at this point.
850
      in.require(length);
1✔
851

852
      synchronized (lock) {
1✔
853
        StreamState stream = streams.get(streamId);
1✔
854
        if (stream == null) {
1✔
855
          in.skip(length);
1✔
856
          streamError(streamId, ErrorCode.STREAM_CLOSED, "Received data for closed stream");
1✔
857
          return;
1✔
858
        }
859
        if (stream.hasReceivedEndOfStream()) {
1✔
860
          in.skip(length);
1✔
861
          streamError(streamId, ErrorCode.STREAM_CLOSED,
1✔
862
              "Received DATA for half-closed (remote) stream. RFC7540 section 5.1");
863
          return;
1✔
864
        }
865
        if (stream.inboundWindowAvailable() < paddedLength) {
1✔
866
          in.skip(length);
1✔
867
          streamError(streamId, ErrorCode.FLOW_CONTROL_ERROR,
1✔
868
              "Received DATA size exceeded window size. RFC7540 section 6.9");
869
          return;
1✔
870
        }
871
        Buffer buf = new Buffer();
1✔
872
        buf.write(in.getBuffer(), length);
1✔
873
        stream.inboundDataReceived(buf, length, paddedLength - length, inFinished);
1✔
874
      }
1✔
875

876
      // connection window update
877
      connectionUnacknowledgedBytesRead += paddedLength;
1✔
878
      if (connectionUnacknowledgedBytesRead
1✔
879
          >= config.flowControlWindow * Utils.DEFAULT_WINDOW_UPDATE_RATIO) {
1✔
880
        synchronized (lock) {
1✔
881
          frameWriter.windowUpdate(0, connectionUnacknowledgedBytesRead);
1✔
882
          frameWriter.flush();
1✔
883
        }
1✔
884
        connectionUnacknowledgedBytesRead = 0;
1✔
885
      }
886
    }
1✔
887

888
    @Override
889
    public void rstStream(int streamId, ErrorCode errorCode) {
890
      frameLogger.logRstStream(OkHttpFrameLogger.Direction.INBOUND, streamId, errorCode);
1✔
891
      // streamId == 0 checking is in HTTP/2 decoder
892

893
      if (!(ErrorCode.NO_ERROR.equals(errorCode)
1✔
894
            || ErrorCode.CANCEL.equals(errorCode)
1✔
895
            || ErrorCode.STREAM_CLOSED.equals(errorCode))) {
1✔
896
        log.log(Level.INFO, "Received RST_STREAM: " + errorCode);
×
897
      }
898
      Status status = GrpcUtil.Http2Error.statusForCode(errorCode.httpCode)
1✔
899
          .withDescription("RST_STREAM");
1✔
900
      synchronized (lock) {
1✔
901
        StreamState stream = streams.get(streamId);
1✔
902
        if (stream != null) {
1✔
903
          stream.inboundRstReceived(status);
1✔
904
          streamClosed(streamId, /*flush=*/ false);
1✔
905
        }
906
      }
1✔
907
    }
1✔
908

909
    @Override
910
    public void settings(boolean clearPrevious, Settings settings) {
911
      frameLogger.logSettings(OkHttpFrameLogger.Direction.INBOUND, settings);
1✔
912
      synchronized (lock) {
1✔
913
        boolean outboundWindowSizeIncreased = false;
1✔
914
        if (OkHttpSettingsUtil.isSet(settings, OkHttpSettingsUtil.INITIAL_WINDOW_SIZE)) {
1✔
915
          int initialWindowSize = OkHttpSettingsUtil.get(
1✔
916
              settings, OkHttpSettingsUtil.INITIAL_WINDOW_SIZE);
917
          outboundWindowSizeIncreased = outboundFlow.initialOutboundWindowSize(initialWindowSize);
1✔
918
        }
919

920
        // The changed settings are not finalized until SETTINGS acknowledgment frame is sent. Any
921
        // writes due to update in settings must be sent after SETTINGS acknowledgment frame,
922
        // otherwise it will cause a stream error (RST_STREAM).
923
        frameWriter.ackSettings(settings);
1✔
924
        frameWriter.flush();
1✔
925
        if (!receivedSettings) {
1✔
926
          receivedSettings = true;
1✔
927
          attributes = listener.transportReady(attributes);
1✔
928
        }
929

930
        // send any pending bytes / streams
931
        if (outboundWindowSizeIncreased) {
1✔
932
          outboundFlow.writeStreams();
1✔
933
        }
934
      }
1✔
935
    }
1✔
936

937
    @Override
938
    public void ping(boolean ack, int payload1, int payload2) {
939
      if (!keepAliveEnforcer.pingAcceptable()) {
1✔
940
        abruptShutdown(ErrorCode.ENHANCE_YOUR_CALM, "too_many_pings",
1✔
941
            Status.RESOURCE_EXHAUSTED.withDescription("Too many pings from client"), false);
1✔
942
        return;
1✔
943
      }
944
      long payload = (((long) payload1) << 32) | (payload2 & 0xffffffffL);
1✔
945
      if (!ack) {
1✔
946
        frameLogger.logPing(OkHttpFrameLogger.Direction.INBOUND, payload);
1✔
947
        synchronized (lock) {
1✔
948
          frameWriter.ping(true, payload1, payload2);
1✔
949
          frameWriter.flush();
1✔
950
        }
1✔
951
      } else {
952
        frameLogger.logPingAck(OkHttpFrameLogger.Direction.INBOUND, payload);
1✔
953
        if (KEEPALIVE_PING == payload) {
1✔
954
          return;
×
955
        }
956
        if (GRACEFUL_SHUTDOWN_PING == payload) {
1✔
957
          triggerGracefulSecondGoaway();
1✔
958
          return;
1✔
959
        }
960
        log.log(Level.INFO, "Received unexpected ping ack: " + payload);
×
961
      }
962
    }
1✔
963

964
    @Override
965
    public void ackSettings() {}
1✔
966

967
    @Override
968
    public void goAway(int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) {
969
      frameLogger.logGoAway(
1✔
970
          OkHttpFrameLogger.Direction.INBOUND, lastGoodStreamId, errorCode, debugData);
971
      String description = String.format("Received GOAWAY: %s '%s'", errorCode, debugData.utf8());
1✔
972
      Status status = GrpcUtil.Http2Error.statusForCode(errorCode.httpCode)
1✔
973
          .withDescription(description);
1✔
974
      if (!ErrorCode.NO_ERROR.equals(errorCode)) {
1✔
975
        log.log(
×
976
            Level.WARNING, "Received GOAWAY: {0} {1}", new Object[] {errorCode, debugData.utf8()});
×
977
      }
978
      synchronized (lock) {
1✔
979
        goAwayStatus = status;
1✔
980
      }
1✔
981
    }
1✔
982

983
    @Override
984
    public void pushPromise(int streamId, int promisedStreamId, List<Header> requestHeaders)
985
        throws IOException {
986
      frameLogger.logPushPromise(OkHttpFrameLogger.Direction.INBOUND,
1✔
987
          streamId, promisedStreamId, requestHeaders);
988
      // streamId == 0 checking is in HTTP/2 decoder.
989
      // The server doesn't use PUSH_PROMISE, so all even streams are IDLE, and odd streams are not
990
      // peer-initiated.
991
      connectionError(ErrorCode.PROTOCOL_ERROR,
1✔
992
          "PUSH_PROMISE only allowed on peer-initiated streams. RFC7540 section 6.6");
993
    }
1✔
994

995
    @Override
996
    public void windowUpdate(int streamId, long delta) {
997
      frameLogger.logWindowsUpdate(OkHttpFrameLogger.Direction.INBOUND, streamId, delta);
1✔
998
      // delta == 0 checking is in HTTP/2 decoder. And it isn't quite right, as it will always cause
999
      // a GOAWAY. RFC7540 section 6.9 says to use RST_STREAM if the stream id isn't 0. Doesn't
1000
      // matter much though.
1001
      synchronized (lock) {
1✔
1002
        if (streamId == Utils.CONNECTION_STREAM_ID) {
1✔
1003
          outboundFlow.windowUpdate(null, (int) delta);
1✔
1004
        } else {
1005
          StreamState stream = streams.get(streamId);
1✔
1006
          if (stream != null) {
1✔
1007
            outboundFlow.windowUpdate(stream.getOutboundFlowState(), (int) delta);
1✔
1008
          }
1009
        }
1010
      }
1✔
1011
    }
1✔
1012

1013
    @Override
1014
    public void priority(int streamId, int streamDependency, int weight, boolean exclusive) {
1015
      frameLogger.logPriority(
1✔
1016
          OkHttpFrameLogger.Direction.INBOUND, streamId, streamDependency, weight, exclusive);
1017
      // streamId == 0 checking is in HTTP/2 decoder.
1018
      // Ignore priority change.
1019
    }
1✔
1020

1021
    @Override
1022
    public void alternateService(int streamId, String origin, ByteString protocol, String host,
1023
        int port, long maxAge) {}
×
1024

1025
    /**
1026
     * Send GOAWAY to the server, then finish all streams and close the transport. RFC7540 §5.4.1.
1027
     */
1028
    private void connectionError(ErrorCode errorCode, String moreDetail) {
1029
      Status status = GrpcUtil.Http2Error.statusForCode(errorCode.httpCode)
1✔
1030
          .withDescription(String.format("HTTP2 connection error: %s '%s'", errorCode, moreDetail));
1✔
1031
      abruptShutdown(errorCode, moreDetail, status, false);
1✔
1032
    }
1✔
1033

1034
    /**
1035
     * Respond with RST_STREAM, making sure to kill the associated stream if it exists. Reason will
1036
     * rarely be seen. RFC7540 §5.4.2.
1037
     */
1038
    private void streamError(int streamId, ErrorCode errorCode, String reason) {
1039
      if (errorCode == ErrorCode.PROTOCOL_ERROR) {
1✔
1040
        log.log(
1✔
1041
            Level.FINE, "Responding with RST_STREAM {0}: {1}", new Object[] {errorCode, reason});
1042
      }
1043
      synchronized (lock) {
1✔
1044
        frameWriter.rstStream(streamId, errorCode);
1✔
1045
        frameWriter.flush();
1✔
1046
        StreamState stream = streams.get(streamId);
1✔
1047
        if (stream != null) {
1✔
1048
          stream.transportReportStatus(
1✔
1049
              Status.INTERNAL.withDescription(
1✔
1050
                  String.format("Responded with RST_STREAM %s: %s", errorCode, reason)));
1✔
1051
          streamClosed(streamId, /*flush=*/ false);
1✔
1052
        }
1053
      }
1✔
1054
    }
1✔
1055

1056
    private void respondWithHttpError(
1057
        int streamId, boolean inFinished, int httpCode, Status.Code statusCode, String msg) {
1058
      Metadata metadata = new Metadata();
1✔
1059
      metadata.put(InternalStatus.CODE_KEY, statusCode.toStatus());
1✔
1060
      metadata.put(InternalStatus.MESSAGE_KEY, msg);
1✔
1061
      List<Header> headers =
1✔
1062
          Headers.createHttpResponseHeaders(httpCode, "text/plain; charset=utf-8", metadata);
1✔
1063
      Buffer data = new Buffer().writeUtf8(msg);
1✔
1064

1065
      synchronized (lock) {
1✔
1066
        Http2ErrorStreamState stream =
1✔
1067
            new Http2ErrorStreamState(streamId, lock, outboundFlow, config.flowControlWindow);
1✔
1068
        if (streams.isEmpty()) {
1✔
1069
          keepAliveEnforcer.onTransportActive();
1✔
1070
          if (maxConnectionIdleManager != null) {
1✔
1071
            maxConnectionIdleManager.onTransportActive();
1✔
1072
          }
1073
        }
1074
        streams.put(streamId, stream);
1✔
1075
        if (inFinished) {
1✔
1076
          stream.inboundDataReceived(new Buffer(), 0, 0, true);
×
1077
        }
1078
        frameWriter.headers(streamId, headers);
1✔
1079
        outboundFlow.data(
1✔
1080
            /*outFinished=*/true, stream.getOutboundFlowState(), data, /*flush=*/true);
1✔
1081
        outboundFlow.notifyWhenNoPendingData(
1✔
1082
            stream.getOutboundFlowState(), () -> rstOkAtEndOfHttpError(stream));
1✔
1083
      }
1✔
1084
    }
1✔
1085

1086
    private void rstOkAtEndOfHttpError(Http2ErrorStreamState stream) {
1087
      synchronized (lock) {
1✔
1088
        if (!stream.hasReceivedEndOfStream()) {
1✔
1089
          frameWriter.rstStream(stream.streamId, ErrorCode.NO_ERROR);
1✔
1090
        }
1091
        streamClosed(stream.streamId, /*flush=*/ true);
1✔
1092
      }
1✔
1093
    }
1✔
1094

1095
    private void respondWithGrpcError(
1096
        int streamId, boolean inFinished, Status.Code statusCode, String msg) {
1097
      Metadata metadata = new Metadata();
1✔
1098
      metadata.put(InternalStatus.CODE_KEY, statusCode.toStatus());
1✔
1099
      metadata.put(InternalStatus.MESSAGE_KEY, msg);
1✔
1100
      List<Header> headers = Headers.createResponseTrailers(metadata, false);
1✔
1101

1102
      synchronized (lock) {
1✔
1103
        frameWriter.synReply(true, streamId, headers);
1✔
1104
        if (!inFinished) {
1✔
1105
          frameWriter.rstStream(streamId, ErrorCode.NO_ERROR);
1✔
1106
        }
1107
        frameWriter.flush();
1✔
1108
      }
1✔
1109
    }
1✔
1110
  }
1111

1112
  private final class KeepAlivePinger implements KeepAliveManager.KeepAlivePinger {
1✔
1113
    @Override
1114
    public void ping() {
1115
      synchronized (lock) {
×
1116
        frameWriter.ping(false, 0, KEEPALIVE_PING);
×
1117
        frameWriter.flush();
×
1118
      }
×
1119
      tracer.reportKeepAliveSent();
×
1120
    }
×
1121

1122
    @Override
1123
    public void onPingTimeout() {
1124
      synchronized (lock) {
×
1125
        goAwayStatus = Status.UNAVAILABLE
×
1126
            .withDescription("Keepalive failed. Considering connection dead");
×
1127
        GrpcUtil.closeQuietly(socket);
×
1128
      }
×
1129
    }
×
1130
  }
1131

1132
  interface StreamState {
1133
    /** Must be holding 'lock' when calling. */
1134
    void inboundDataReceived(Buffer frame, int dataLength, int paddingLength, boolean endOfStream);
1135

1136
    /** Must be holding 'lock' when calling. */
1137
    boolean hasReceivedEndOfStream();
1138

1139
    /** Must be holding 'lock' when calling. */
1140
    int inboundWindowAvailable();
1141

1142
    /** Must be holding 'lock' when calling. */
1143
    void transportReportStatus(Status status);
1144

1145
    /** Must be holding 'lock' when calling. */
1146
    void inboundRstReceived(Status status);
1147

1148
    OutboundFlowController.StreamState getOutboundFlowState();
1149
  }
1150

1151
  static class Http2ErrorStreamState implements StreamState, OutboundFlowController.Stream {
1152
    private final int streamId;
1153
    private final Object lock;
1154
    private final OutboundFlowController.StreamState outboundFlowState;
1155
    @GuardedBy("lock")
1156
    private int window;
1157
    @GuardedBy("lock")
1158
    private boolean receivedEndOfStream;
1159

1160
    Http2ErrorStreamState(
1161
        int streamId, Object lock, OutboundFlowController outboundFlow, int initialWindowSize) {
1✔
1162
      this.streamId = streamId;
1✔
1163
      this.lock = lock;
1✔
1164
      this.outboundFlowState = outboundFlow.createState(this, streamId);
1✔
1165
      this.window = initialWindowSize;
1✔
1166
    }
1✔
1167

1168
    @Override public void onSentBytes(int frameBytes) {}
1✔
1169

1170
    @Override public void inboundDataReceived(
1171
        Buffer frame, int dataLength, int paddingLength, boolean endOfStream) {
1172
      synchronized (lock) {
×
1173
        if (endOfStream) {
×
1174
          receivedEndOfStream = true;
×
1175
        }
1176
        window -= dataLength + paddingLength;
×
1177
        try {
1178
          frame.skip(frame.size()); // Recycle segments
×
1179
        } catch (IOException ex) {
×
1180
          throw new AssertionError(ex);
×
1181
        }
×
1182
      }
×
1183
    }
×
1184

1185
    @Override public boolean hasReceivedEndOfStream() {
1186
      synchronized (lock) {
1✔
1187
        return receivedEndOfStream;
1✔
1188
      }
1189
    }
1190

1191
    @Override public int inboundWindowAvailable() {
1192
      synchronized (lock) {
×
1193
        return window;
×
1194
      }
1195
    }
1196

1197
    @Override public void transportReportStatus(Status status) {}
×
1198

1199
    @Override public void inboundRstReceived(Status status) {}
×
1200

1201
    @Override public OutboundFlowController.StreamState getOutboundFlowState() {
1202
      synchronized (lock) {
1✔
1203
        return outboundFlowState;
1✔
1204
      }
1205
    }
1206
  }
1207
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc