001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.ipc;
019
020import static org.apache.hadoop.hbase.HConstants.RPC_HEADER;
021
022import java.io.ByteArrayInputStream;
023import java.io.Closeable;
024import java.io.DataOutputStream;
025import java.io.IOException;
026import java.net.InetAddress;
027import java.net.InetSocketAddress;
028import java.nio.ByteBuffer;
029import java.nio.channels.Channels;
030import java.nio.channels.ReadableByteChannel;
031import java.security.GeneralSecurityException;
032import java.util.Objects;
033import java.util.Properties;
034
035import org.apache.commons.crypto.cipher.CryptoCipherFactory;
036import org.apache.commons.crypto.random.CryptoRandom;
037import org.apache.commons.crypto.random.CryptoRandomFactory;
038import org.apache.hadoop.hbase.CellScanner;
039import org.apache.hadoop.hbase.DoNotRetryIOException;
040import org.apache.yetus.audience.InterfaceAudience;
041import org.apache.hadoop.hbase.client.VersionInfoUtil;
042import org.apache.hadoop.hbase.codec.Codec;
043import org.apache.hadoop.hbase.io.ByteBufferOutputStream;
044import org.apache.hadoop.hbase.io.crypto.aes.CryptoAES;
045import org.apache.hadoop.hbase.ipc.RpcServer.CallCleanup;
046import org.apache.hadoop.hbase.nio.ByteBuff;
047import org.apache.hadoop.hbase.nio.SingleByteBuff;
048import org.apache.hadoop.hbase.security.AccessDeniedException;
049import org.apache.hadoop.hbase.security.HBaseSaslRpcServer;
050import org.apache.hadoop.hbase.security.SaslStatus;
051import org.apache.hadoop.hbase.security.SaslUtil;
052import org.apache.hadoop.hbase.security.User;
053import org.apache.hadoop.hbase.security.provider.SaslServerAuthenticationProvider;
054import org.apache.hadoop.hbase.security.provider.SaslServerAuthenticationProviders;
055import org.apache.hadoop.hbase.security.provider.SimpleSaslServerAuthenticationProvider;
056import org.apache.hbase.thirdparty.com.google.protobuf.BlockingService;
057import org.apache.hbase.thirdparty.com.google.protobuf.ByteInput;
058import org.apache.hbase.thirdparty.com.google.protobuf.ByteString;
059import org.apache.hbase.thirdparty.com.google.protobuf.CodedInputStream;
060import org.apache.hbase.thirdparty.com.google.protobuf.Descriptors.MethodDescriptor;
061import org.apache.hbase.thirdparty.com.google.protobuf.Message;
062import org.apache.hbase.thirdparty.com.google.protobuf.TextFormat;
063import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
064import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
065import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.VersionInfo;
066import org.apache.hadoop.hbase.shaded.protobuf.generated.RPCProtos;
067import org.apache.hadoop.hbase.shaded.protobuf.generated.RPCProtos.ConnectionHeader;
068import org.apache.hadoop.hbase.shaded.protobuf.generated.RPCProtos.RequestHeader;
069import org.apache.hadoop.hbase.shaded.protobuf.generated.RPCProtos.ResponseHeader;
070import org.apache.hadoop.hbase.shaded.protobuf.generated.RPCProtos.UserInformation;
071import org.apache.hadoop.hbase.util.Bytes;
072import org.apache.hadoop.io.BytesWritable;
073import org.apache.hadoop.io.IntWritable;
074import org.apache.hadoop.io.Writable;
075import org.apache.hadoop.io.WritableUtils;
076import org.apache.hadoop.io.compress.CompressionCodec;
077import org.apache.hadoop.security.UserGroupInformation;
078import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;
079import org.apache.hadoop.security.authorize.AuthorizationException;
080import org.apache.hadoop.security.authorize.ProxyUsers;
081import org.apache.hadoop.security.token.SecretManager.InvalidToken;
082
083/** Reads calls from a connection and queues them for handling. */
084@edu.umd.cs.findbugs.annotations.SuppressWarnings(
085    value="VO_VOLATILE_INCREMENT",
086    justification="False positive according to http://sourceforge.net/p/findbugs/bugs/1032/")
087@InterfaceAudience.Private
088abstract class ServerRpcConnection implements Closeable {
089  /**  */
090  protected final RpcServer rpcServer;
091  // If the connection header has been read or not.
092  protected boolean connectionHeaderRead = false;
093
094  protected CallCleanup callCleanup;
095
096  // Cache the remote host & port info so that even if the socket is
097  // disconnected, we can say where it used to connect to.
098  protected String hostAddress;
099  protected int remotePort;
100  protected InetAddress addr;
101  protected ConnectionHeader connectionHeader;
102
103  /**
104   * Codec the client asked use.
105   */
106  protected Codec codec;
107  /**
108   * Compression codec the client asked us use.
109   */
110  protected CompressionCodec compressionCodec;
111  protected BlockingService service;
112
113  protected SaslServerAuthenticationProvider provider;
114  protected boolean saslContextEstablished;
115  protected boolean skipInitialSaslHandshake;
116  private ByteBuffer unwrappedData;
117  // When is this set? FindBugs wants to know! Says NP
118  private ByteBuffer unwrappedDataLengthBuffer = ByteBuffer.allocate(4);
119  protected boolean useSasl;
120  protected HBaseSaslRpcServer saslServer;
121  protected CryptoAES cryptoAES;
122  protected boolean useWrap = false;
123  protected boolean useCryptoAesWrap = false;
124
125  // was authentication allowed with a fallback to simple auth
126  protected boolean authenticatedWithFallback;
127
128  protected boolean retryImmediatelySupported = false;
129
130  protected User user = null;
131  protected UserGroupInformation ugi = null;
132  protected SaslServerAuthenticationProviders saslProviders = null;
133
134  public ServerRpcConnection(RpcServer rpcServer) {
135    this.rpcServer = rpcServer;
136    this.callCleanup = null;
137    this.saslProviders = SaslServerAuthenticationProviders.getInstance(rpcServer.getConf());
138  }
139
140  @Override
141  public String toString() {
142    return getHostAddress() + ":" + remotePort;
143  }
144
145  public String getHostAddress() {
146    return hostAddress;
147  }
148
149  public InetAddress getHostInetAddress() {
150    return addr;
151  }
152
153  public int getRemotePort() {
154    return remotePort;
155  }
156
157  public VersionInfo getVersionInfo() {
158    if (connectionHeader.hasVersionInfo()) {
159      return connectionHeader.getVersionInfo();
160    }
161    return null;
162  }
163
164  private String getFatalConnectionString(final int version, final byte authByte) {
165    return "serverVersion=" + RpcServer.CURRENT_VERSION +
166        ", clientVersion=" + version + ", authMethod=" + authByte +
167        // The provider may be null if we failed to parse the header of the request
168        ", authName=" + (provider == null ? "unknown" : provider.getSaslAuthMethod().getName()) +
169        " from " + toString();
170  }
171
172  /**
173   * Set up cell block codecs
174   * @throws FatalConnectionException
175   */
176  private void setupCellBlockCodecs(final ConnectionHeader header)
177      throws FatalConnectionException {
178    // TODO: Plug in other supported decoders.
179    if (!header.hasCellBlockCodecClass()) return;
180    String className = header.getCellBlockCodecClass();
181    if (className == null || className.length() == 0) return;
182    try {
183      this.codec = (Codec)Class.forName(className).getDeclaredConstructor().newInstance();
184    } catch (Exception e) {
185      throw new UnsupportedCellCodecException(className, e);
186    }
187    if (!header.hasCellBlockCompressorClass()) return;
188    className = header.getCellBlockCompressorClass();
189    try {
190      this.compressionCodec =
191          (CompressionCodec)Class.forName(className).getDeclaredConstructor().newInstance();
192    } catch (Exception e) {
193      throw new UnsupportedCompressionCodecException(className, e);
194    }
195  }
196
197  /**
198   * Set up cipher for rpc encryption with Apache Commons Crypto
199   *
200   * @throws FatalConnectionException
201   */
202  private void setupCryptoCipher(final ConnectionHeader header,
203      RPCProtos.ConnectionHeaderResponse.Builder chrBuilder)
204      throws FatalConnectionException {
205    // If simple auth, return
206    if (saslServer == null) return;
207    // check if rpc encryption with Crypto AES
208    String qop = saslServer.getNegotiatedQop();
209    boolean isEncryption = SaslUtil.QualityOfProtection.PRIVACY
210        .getSaslQop().equalsIgnoreCase(qop);
211    boolean isCryptoAesEncryption = isEncryption && this.rpcServer.conf.getBoolean(
212        "hbase.rpc.crypto.encryption.aes.enabled", false);
213    if (!isCryptoAesEncryption) return;
214    if (!header.hasRpcCryptoCipherTransformation()) return;
215    String transformation = header.getRpcCryptoCipherTransformation();
216    if (transformation == null || transformation.length() == 0) return;
217     // Negotiates AES based on complete saslServer.
218     // The Crypto metadata need to be encrypted and send to client.
219    Properties properties = new Properties();
220    // the property for SecureRandomFactory
221    properties.setProperty(CryptoRandomFactory.CLASSES_KEY,
222        this.rpcServer.conf.get("hbase.crypto.sasl.encryption.aes.crypto.random",
223            "org.apache.commons.crypto.random.JavaCryptoRandom"));
224    // the property for cipher class
225    properties.setProperty(CryptoCipherFactory.CLASSES_KEY,
226        this.rpcServer.conf.get("hbase.rpc.crypto.encryption.aes.cipher.class",
227            "org.apache.commons.crypto.cipher.JceCipher"));
228
229    int cipherKeyBits = this.rpcServer.conf.getInt(
230        "hbase.rpc.crypto.encryption.aes.cipher.keySizeBits", 128);
231    // generate key and iv
232    if (cipherKeyBits % 8 != 0) {
233      throw new IllegalArgumentException("The AES cipher key size in bits" +
234          " should be a multiple of byte");
235    }
236    int len = cipherKeyBits / 8;
237    byte[] inKey = new byte[len];
238    byte[] outKey = new byte[len];
239    byte[] inIv = new byte[len];
240    byte[] outIv = new byte[len];
241
242    try {
243      // generate the cipher meta data with SecureRandom
244      CryptoRandom secureRandom = CryptoRandomFactory.getCryptoRandom(properties);
245      secureRandom.nextBytes(inKey);
246      secureRandom.nextBytes(outKey);
247      secureRandom.nextBytes(inIv);
248      secureRandom.nextBytes(outIv);
249
250      // create CryptoAES for server
251      cryptoAES = new CryptoAES(transformation, properties,
252          inKey, outKey, inIv, outIv);
253      // create SaslCipherMeta and send to client,
254      //  for client, the [inKey, outKey], [inIv, outIv] should be reversed
255      RPCProtos.CryptoCipherMeta.Builder ccmBuilder = RPCProtos.CryptoCipherMeta.newBuilder();
256      ccmBuilder.setTransformation(transformation);
257      ccmBuilder.setInIv(getByteString(outIv));
258      ccmBuilder.setInKey(getByteString(outKey));
259      ccmBuilder.setOutIv(getByteString(inIv));
260      ccmBuilder.setOutKey(getByteString(inKey));
261      chrBuilder.setCryptoCipherMeta(ccmBuilder);
262      useCryptoAesWrap = true;
263    } catch (GeneralSecurityException | IOException ex) {
264      throw new UnsupportedCryptoException(ex.getMessage(), ex);
265    }
266  }
267
268  private ByteString getByteString(byte[] bytes) {
269    // return singleton to reduce object allocation
270    return (bytes.length == 0) ? ByteString.EMPTY : ByteString.copyFrom(bytes);
271  }
272
273  private UserGroupInformation createUser(ConnectionHeader head) {
274    UserGroupInformation ugi = null;
275
276    if (!head.hasUserInfo()) {
277      return null;
278    }
279    UserInformation userInfoProto = head.getUserInfo();
280    String effectiveUser = null;
281    if (userInfoProto.hasEffectiveUser()) {
282      effectiveUser = userInfoProto.getEffectiveUser();
283    }
284    String realUser = null;
285    if (userInfoProto.hasRealUser()) {
286      realUser = userInfoProto.getRealUser();
287    }
288    if (effectiveUser != null) {
289      if (realUser != null) {
290        UserGroupInformation realUserUgi =
291            UserGroupInformation.createRemoteUser(realUser);
292        ugi = UserGroupInformation.createProxyUser(effectiveUser, realUserUgi);
293      } else {
294        ugi = UserGroupInformation.createRemoteUser(effectiveUser);
295      }
296    }
297    return ugi;
298  }
299
300  protected final void disposeSasl() {
301    if (saslServer != null) {
302      saslServer.dispose();
303      saslServer = null;
304    }
305  }
306
307  /**
308   * No protobuf encoding of raw sasl messages
309   */
310  protected final void doRawSaslReply(SaslStatus status, Writable rv,
311      String errorClass, String error) throws IOException {
312    BufferChain bc;
313    // In my testing, have noticed that sasl messages are usually
314    // in the ballpark of 100-200. That's why the initial capacity is 256.
315    try (ByteBufferOutputStream saslResponse = new ByteBufferOutputStream(256);
316        DataOutputStream  out = new DataOutputStream(saslResponse)) {
317      out.writeInt(status.state); // write status
318      if (status == SaslStatus.SUCCESS) {
319        rv.write(out);
320      } else {
321        WritableUtils.writeString(out, errorClass);
322        WritableUtils.writeString(out, error);
323      }
324      bc = new BufferChain(saslResponse.getByteBuffer());
325    }
326    doRespond(() -> bc);
327  }
328
329  public void saslReadAndProcess(ByteBuff saslToken) throws IOException,
330      InterruptedException {
331    if (saslContextEstablished) {
332      RpcServer.LOG.trace("Read input token of size={} for processing by saslServer.unwrap()",
333        saslToken.limit());
334      if (!useWrap) {
335        processOneRpc(saslToken);
336      } else {
337        byte[] b = saslToken.hasArray() ? saslToken.array() : saslToken.toBytes();
338        byte [] plaintextData;
339        if (useCryptoAesWrap) {
340          // unwrap with CryptoAES
341          plaintextData = cryptoAES.unwrap(b, 0, b.length);
342        } else {
343          plaintextData = saslServer.unwrap(b, 0, b.length);
344        }
345        processUnwrappedData(plaintextData);
346      }
347    } else {
348      byte[] replyToken;
349      try {
350        if (saslServer == null) {
351          saslServer =
352              new HBaseSaslRpcServer(provider, rpcServer.saslProps, rpcServer.secretManager);
353          RpcServer.LOG.debug("Created SASL server with mechanism={}",
354              provider.getSaslAuthMethod().getAuthMethod());
355        }
356        RpcServer.LOG.debug("Read input token of size={} for processing by saslServer." +
357            "evaluateResponse()", saslToken.limit());
358        replyToken = saslServer.evaluateResponse(saslToken.hasArray()?
359            saslToken.array() : saslToken.toBytes());
360      } catch (IOException e) {
361        IOException sendToClient = e;
362        Throwable cause = e;
363        while (cause != null) {
364          if (cause instanceof InvalidToken) {
365            sendToClient = (InvalidToken) cause;
366            break;
367          }
368          cause = cause.getCause();
369        }
370        doRawSaslReply(SaslStatus.ERROR, null, sendToClient.getClass().getName(),
371          sendToClient.getLocalizedMessage());
372        this.rpcServer.metrics.authenticationFailure();
373        String clientIP = this.toString();
374        // attempting user could be null
375        RpcServer.AUDITLOG
376            .warn("{} {}: {}", RpcServer.AUTH_FAILED_FOR, clientIP, saslServer.getAttemptingUser());
377        throw e;
378      }
379      if (replyToken != null) {
380        if (RpcServer.LOG.isDebugEnabled()) {
381          RpcServer.LOG.debug("Will send token of size " + replyToken.length
382              + " from saslServer.");
383        }
384        doRawSaslReply(SaslStatus.SUCCESS, new BytesWritable(replyToken), null,
385            null);
386      }
387      if (saslServer.isComplete()) {
388        String qop = saslServer.getNegotiatedQop();
389        useWrap = qop != null && !"auth".equalsIgnoreCase(qop);
390        ugi = provider.getAuthorizedUgi(saslServer.getAuthorizationID(),
391            this.rpcServer.secretManager);
392        RpcServer.LOG.debug(
393            "SASL server context established. Authenticated client: {}. Negotiated QoP is {}",
394            ugi, qop);
395        this.rpcServer.metrics.authenticationSuccess();
396        RpcServer.AUDITLOG.info(RpcServer.AUTH_SUCCESSFUL_FOR + ugi);
397        saslContextEstablished = true;
398      }
399    }
400  }
401
402  private void processUnwrappedData(byte[] inBuf) throws IOException, InterruptedException {
403    ReadableByteChannel ch = Channels.newChannel(new ByteArrayInputStream(inBuf));
404    // Read all RPCs contained in the inBuf, even partial ones
405    while (true) {
406      int count;
407      if (unwrappedDataLengthBuffer.remaining() > 0) {
408        count = this.rpcServer.channelRead(ch, unwrappedDataLengthBuffer);
409        if (count <= 0 || unwrappedDataLengthBuffer.remaining() > 0)
410          return;
411      }
412
413      if (unwrappedData == null) {
414        unwrappedDataLengthBuffer.flip();
415        int unwrappedDataLength = unwrappedDataLengthBuffer.getInt();
416
417        if (unwrappedDataLength == RpcClient.PING_CALL_ID) {
418          if (RpcServer.LOG.isDebugEnabled())
419            RpcServer.LOG.debug("Received ping message");
420          unwrappedDataLengthBuffer.clear();
421          continue; // ping message
422        }
423        unwrappedData = ByteBuffer.allocate(unwrappedDataLength);
424      }
425
426      count = this.rpcServer.channelRead(ch, unwrappedData);
427      if (count <= 0 || unwrappedData.remaining() > 0)
428        return;
429
430      if (unwrappedData.remaining() == 0) {
431        unwrappedDataLengthBuffer.clear();
432        unwrappedData.flip();
433        processOneRpc(new SingleByteBuff(unwrappedData));
434        unwrappedData = null;
435      }
436    }
437  }
438
439  public void processOneRpc(ByteBuff buf) throws IOException,
440      InterruptedException {
441    if (connectionHeaderRead) {
442      processRequest(buf);
443    } else {
444      processConnectionHeader(buf);
445      this.connectionHeaderRead = true;
446      if (!authorizeConnection()) {
447        // Throw FatalConnectionException wrapping ACE so client does right thing and closes
448        // down the connection instead of trying to read non-existent retun.
449        throw new AccessDeniedException("Connection from " + this + " for service " +
450          connectionHeader.getServiceName() + " is unauthorized for user: " + ugi);
451      }
452      this.user = this.rpcServer.userProvider.create(this.ugi);
453    }
454  }
455
456  private boolean authorizeConnection() throws IOException {
457    try {
458      // If auth method is DIGEST, the token was obtained by the
459      // real user for the effective user, therefore not required to
460      // authorize real user. doAs is allowed only for simple or kerberos
461      // authentication
462      if (ugi != null && ugi.getRealUser() != null
463          && provider.supportsProtocolAuthentication()) {
464        ProxyUsers.authorize(ugi, this.getHostAddress(), this.rpcServer.conf);
465      }
466      this.rpcServer.authorize(ugi, connectionHeader, getHostInetAddress());
467      this.rpcServer.metrics.authorizationSuccess();
468    } catch (AuthorizationException ae) {
469      if (RpcServer.LOG.isDebugEnabled()) {
470        RpcServer.LOG.debug("Connection authorization failed: " + ae.getMessage(), ae);
471      }
472      this.rpcServer.metrics.authorizationFailure();
473      doRespond(getErrorResponse(ae.getMessage(), new AccessDeniedException(ae)));
474      return false;
475    }
476    return true;
477  }
478
479  // Reads the connection header following version
480  private void processConnectionHeader(ByteBuff buf) throws IOException {
481    if (buf.hasArray()) {
482      this.connectionHeader = ConnectionHeader.parseFrom(buf.array());
483    } else {
484      CodedInputStream cis = UnsafeByteOperations.unsafeWrap(
485          new ByteBuffByteInput(buf, 0, buf.limit()), 0, buf.limit()).newCodedInput();
486      cis.enableAliasing(true);
487      this.connectionHeader = ConnectionHeader.parseFrom(cis);
488    }
489    String serviceName = connectionHeader.getServiceName();
490    if (serviceName == null) throw new EmptyServiceNameException();
491    this.service = RpcServer.getService(this.rpcServer.services, serviceName);
492    if (this.service == null) throw new UnknownServiceException(serviceName);
493    setupCellBlockCodecs(this.connectionHeader);
494    RPCProtos.ConnectionHeaderResponse.Builder chrBuilder =
495        RPCProtos.ConnectionHeaderResponse.newBuilder();
496    setupCryptoCipher(this.connectionHeader, chrBuilder);
497    responseConnectionHeader(chrBuilder);
498    UserGroupInformation protocolUser = createUser(connectionHeader);
499    if (!useSasl) {
500      ugi = protocolUser;
501      if (ugi != null) {
502        ugi.setAuthenticationMethod(AuthenticationMethod.SIMPLE);
503      }
504      // audit logging for SASL authenticated users happens in saslReadAndProcess()
505      if (authenticatedWithFallback) {
506        RpcServer.LOG.warn("Allowed fallback to SIMPLE auth for {} connecting from {}",
507            ugi, getHostAddress());
508      }
509    } else {
510      // user is authenticated
511      ugi.setAuthenticationMethod(provider.getSaslAuthMethod().getAuthMethod());
512      //Now we check if this is a proxy user case. If the protocol user is
513      //different from the 'user', it is a proxy user scenario. However,
514      //this is not allowed if user authenticated with DIGEST.
515      if ((protocolUser != null)
516          && (!protocolUser.getUserName().equals(ugi.getUserName()))) {
517        if (!provider.supportsProtocolAuthentication()) {
518          // Not allowed to doAs if token authentication is used
519          throw new AccessDeniedException("Authenticated user (" + ugi
520              + ") doesn't match what the client claims to be ("
521              + protocolUser + ")");
522        } else {
523          // Effective user can be different from authenticated user
524          // for simple auth or kerberos auth
525          // The user is the real user. Now we create a proxy user
526          UserGroupInformation realUser = ugi;
527          ugi = UserGroupInformation.createProxyUser(protocolUser
528              .getUserName(), realUser);
529          // Now the user is a proxy user, set Authentication method Proxy.
530          ugi.setAuthenticationMethod(AuthenticationMethod.PROXY);
531        }
532      }
533    }
534    String version;
535    if (this.connectionHeader.hasVersionInfo()) {
536      // see if this connection will support RetryImmediatelyException
537      this.retryImmediatelySupported =
538          VersionInfoUtil.hasMinimumVersion(getVersionInfo(), 1, 2);
539      version = this.connectionHeader.getVersionInfo().getVersion();
540    } else {
541      version = "UNKNOWN";
542    }
543    RpcServer.AUDITLOG.info("Connection from {}:{}, version={}, sasl={}, ugi={}, service={}",
544        this.hostAddress, this.remotePort, version, this.useSasl, this.ugi, serviceName);
545  }
546
547  /**
548   * Send the response for connection header
549   */
550  private void responseConnectionHeader(RPCProtos.ConnectionHeaderResponse.Builder chrBuilder)
551      throws FatalConnectionException {
552    // Response the connection header if Crypto AES is enabled
553    if (!chrBuilder.hasCryptoCipherMeta()) return;
554    try {
555      byte[] connectionHeaderResBytes = chrBuilder.build().toByteArray();
556      // encrypt the Crypto AES cipher meta data with sasl server, and send to client
557      byte[] unwrapped = new byte[connectionHeaderResBytes.length + 4];
558      Bytes.putBytes(unwrapped, 0, Bytes.toBytes(connectionHeaderResBytes.length), 0, 4);
559      Bytes.putBytes(unwrapped, 4, connectionHeaderResBytes, 0, connectionHeaderResBytes.length);
560      byte[] wrapped = saslServer.wrap(unwrapped, 0, unwrapped.length);
561      BufferChain bc;
562      try (ByteBufferOutputStream response = new ByteBufferOutputStream(wrapped.length + 4);
563          DataOutputStream out = new DataOutputStream(response)) {
564        out.writeInt(wrapped.length);
565        out.write(wrapped);
566        bc = new BufferChain(response.getByteBuffer());
567      }
568      doRespond(() -> bc);
569    } catch (IOException ex) {
570      throw new UnsupportedCryptoException(ex.getMessage(), ex);
571    }
572  }
573
574  protected abstract void doRespond(RpcResponse resp) throws IOException;
575
576  /**
577   * @param buf
578   *          Has the request header and the request param and optionally
579   *          encoded data buffer all in this one array.
580   * @throws IOException
581   * @throws InterruptedException
582   */
583  protected void processRequest(ByteBuff buf) throws IOException,
584      InterruptedException {
585    long totalRequestSize = buf.limit();
586    int offset = 0;
587    // Here we read in the header. We avoid having pb
588    // do its default 4k allocation for CodedInputStream. We force it to use
589    // backing array.
590    CodedInputStream cis;
591    if (buf.hasArray()) {
592      cis = UnsafeByteOperations.unsafeWrap(buf.array(), 0, buf.limit()).newCodedInput();
593    } else {
594      cis = UnsafeByteOperations
595          .unsafeWrap(new ByteBuffByteInput(buf, 0, buf.limit()), 0, buf.limit()).newCodedInput();
596    }
597    cis.enableAliasing(true);
598    int headerSize = cis.readRawVarint32();
599    offset = cis.getTotalBytesRead();
600    Message.Builder builder = RequestHeader.newBuilder();
601    ProtobufUtil.mergeFrom(builder, cis, headerSize);
602    RequestHeader header = (RequestHeader) builder.build();
603    offset += headerSize;
604    int id = header.getCallId();
605    if (RpcServer.LOG.isTraceEnabled()) {
606      RpcServer.LOG.trace("RequestHeader " + TextFormat.shortDebugString(header)
607          + " totalRequestSize: " + totalRequestSize + " bytes");
608    }
609    // Enforcing the call queue size, this triggers a retry in the client
610    // This is a bit late to be doing this check - we have already read in the
611    // total request.
612    if ((totalRequestSize +
613        this.rpcServer.callQueueSizeInBytes.sum()) > this.rpcServer.maxQueueSizeInBytes) {
614      final ServerCall<?> callTooBig = createCall(id, this.service, null, null, null, null,
615        totalRequestSize, null, 0, this.callCleanup);
616      this.rpcServer.metrics.exception(RpcServer.CALL_QUEUE_TOO_BIG_EXCEPTION);
617      callTooBig.setResponse(null, null,  RpcServer.CALL_QUEUE_TOO_BIG_EXCEPTION,
618        "Call queue is full on " + this.rpcServer.server.getServerName() +
619        ", is hbase.ipc.server.max.callqueue.size too small?");
620      callTooBig.sendResponseIfReady();
621      return;
622    }
623    MethodDescriptor md = null;
624    Message param = null;
625    CellScanner cellScanner = null;
626    try {
627      if (header.hasRequestParam() && header.getRequestParam()) {
628        md = this.service.getDescriptorForType().findMethodByName(
629            header.getMethodName());
630        if (md == null)
631          throw new UnsupportedOperationException(header.getMethodName());
632        builder = this.service.getRequestPrototype(md).newBuilderForType();
633        cis.resetSizeCounter();
634        int paramSize = cis.readRawVarint32();
635        offset += cis.getTotalBytesRead();
636        if (builder != null) {
637          ProtobufUtil.mergeFrom(builder, cis, paramSize);
638          param = builder.build();
639        }
640        offset += paramSize;
641      } else {
642        // currently header must have request param, so we directly throw
643        // exception here
644        String msg = "Invalid request header: "
645            + TextFormat.shortDebugString(header)
646            + ", should have param set in it";
647        RpcServer.LOG.warn(msg);
648        throw new DoNotRetryIOException(msg);
649      }
650      if (header.hasCellBlockMeta()) {
651        buf.position(offset);
652        ByteBuff dup = buf.duplicate();
653        dup.limit(offset + header.getCellBlockMeta().getLength());
654        cellScanner = this.rpcServer.cellBlockBuilder.createCellScannerReusingBuffers(
655            this.codec, this.compressionCodec, dup);
656      }
657    } catch (Throwable t) {
658      InetSocketAddress address = this.rpcServer.getListenerAddress();
659      String msg = (address != null ? address : "(channel closed)")
660          + " is unable to read call parameter from client "
661          + getHostAddress();
662      RpcServer.LOG.warn(msg, t);
663
664      this.rpcServer.metrics.exception(t);
665
666      // probably the hbase hadoop version does not match the running hadoop
667      // version
668      if (t instanceof LinkageError) {
669        t = new DoNotRetryIOException(t);
670      }
671      // If the method is not present on the server, do not retry.
672      if (t instanceof UnsupportedOperationException) {
673        t = new DoNotRetryIOException(t);
674      }
675
676      ServerCall<?> readParamsFailedCall = createCall(id, this.service, null, null, null, null,
677        totalRequestSize, null, 0, this.callCleanup);
678      readParamsFailedCall.setResponse(null, null, t, msg + "; " + t.getMessage());
679      readParamsFailedCall.sendResponseIfReady();
680      return;
681    }
682
683    int timeout = 0;
684    if (header.hasTimeout() && header.getTimeout() > 0) {
685      timeout = Math.max(this.rpcServer.minClientRequestTimeout, header.getTimeout());
686    }
687    ServerCall<?> call = createCall(id, this.service, md, header, param, cellScanner, totalRequestSize,
688      this.addr, timeout, this.callCleanup);
689
690    if (!this.rpcServer.scheduler.dispatch(new CallRunner(this.rpcServer, call))) {
691      this.rpcServer.callQueueSizeInBytes.add(-1 * call.getSize());
692      this.rpcServer.metrics.exception(RpcServer.CALL_QUEUE_TOO_BIG_EXCEPTION);
693      call.setResponse(null, null, RpcServer.CALL_QUEUE_TOO_BIG_EXCEPTION,
694        "Call queue is full on " + this.rpcServer.server.getServerName() +
695            ", too many items queued ?");
696      call.sendResponseIfReady();
697    }
698  }
699
700  protected final RpcResponse getErrorResponse(String msg, Exception e) throws IOException {
701    ResponseHeader.Builder headerBuilder = ResponseHeader.newBuilder().setCallId(-1);
702    ServerCall.setExceptionResponse(e, msg, headerBuilder);
703    ByteBuffer headerBuf =
704        ServerCall.createHeaderAndMessageBytes(null, headerBuilder.build(), 0, null);
705    BufferChain buf = new BufferChain(headerBuf);
706    return () -> buf;
707  }
708
709  private void doBadPreambleHandling(String msg) throws IOException {
710    doBadPreambleHandling(msg, new FatalConnectionException(msg));
711  }
712
713  private void doBadPreambleHandling(String msg, Exception e) throws IOException {
714    SimpleRpcServer.LOG.warn(msg);
715    doRespond(getErrorResponse(msg, e));
716  }
717
718  protected final boolean processPreamble(ByteBuffer preambleBuffer) throws IOException {
719    assert preambleBuffer.remaining() == 6;
720    for (int i = 0; i < RPC_HEADER.length; i++) {
721      if (RPC_HEADER[i] != preambleBuffer.get()) {
722        doBadPreambleHandling(
723          "Expected HEADER=" + Bytes.toStringBinary(RPC_HEADER) + " but received HEADER=" +
724              Bytes.toStringBinary(preambleBuffer.array(), 0, RPC_HEADER.length) + " from " +
725              toString());
726        return false;
727      }
728    }
729    int version = preambleBuffer.get() & 0xFF;
730    byte authbyte = preambleBuffer.get();
731
732    if (version != SimpleRpcServer.CURRENT_VERSION) {
733      String msg = getFatalConnectionString(version, authbyte);
734      doBadPreambleHandling(msg, new WrongVersionException(msg));
735      return false;
736    }
737    this.provider = this.saslProviders.selectProvider(authbyte);
738    if (this.provider == null) {
739      String msg = getFatalConnectionString(version, authbyte);
740      doBadPreambleHandling(msg, new BadAuthException(msg));
741      return false;
742    }
743    // TODO this is a wart while simple auth'n doesn't go through sasl.
744    if (this.rpcServer.isSecurityEnabled && isSimpleAuthentication()) {
745      if (this.rpcServer.allowFallbackToSimpleAuth) {
746        this.rpcServer.metrics.authenticationFallback();
747        authenticatedWithFallback = true;
748      } else {
749        AccessDeniedException ae = new AccessDeniedException("Authentication is required");
750        doRespond(getErrorResponse(ae.getMessage(), ae));
751        return false;
752      }
753    }
754    if (!this.rpcServer.isSecurityEnabled && !isSimpleAuthentication()) {
755      doRawSaslReply(SaslStatus.SUCCESS, new IntWritable(SaslUtil.SWITCH_TO_SIMPLE_AUTH), null,
756        null);
757      provider = saslProviders.getSimpleProvider();
758      // client has already sent the initial Sasl message and we
759      // should ignore it. Both client and server should fall back
760      // to simple auth from now on.
761      skipInitialSaslHandshake = true;
762    }
763    useSasl = !(provider instanceof SimpleSaslServerAuthenticationProvider);
764    return true;
765  }
766
767  boolean isSimpleAuthentication() {
768    return Objects.requireNonNull(provider) instanceof SimpleSaslServerAuthenticationProvider;
769  }
770
771  public abstract boolean isConnectionOpen();
772
773  public abstract ServerCall<?> createCall(int id, BlockingService service, MethodDescriptor md,
774      RequestHeader header, Message param, CellScanner cellScanner, long size,
775      InetAddress remoteAddress, int timeout, CallCleanup reqCleanup);
776
777  private static class ByteBuffByteInput extends ByteInput {
778
779    private ByteBuff buf;
780    private int offset;
781    private int length;
782
783    ByteBuffByteInput(ByteBuff buf, int offset, int length) {
784      this.buf = buf;
785      this.offset = offset;
786      this.length = length;
787    }
788
789    @Override
790    public byte read(int offset) {
791      return this.buf.get(getAbsoluteOffset(offset));
792    }
793
794    private int getAbsoluteOffset(int offset) {
795      return this.offset + offset;
796    }
797
798    @Override
799    public int read(int offset, byte[] out, int outOffset, int len) {
800      this.buf.get(getAbsoluteOffset(offset), out, outOffset, len);
801      return len;
802    }
803
804    @Override
805    public int read(int offset, ByteBuffer out) {
806      int len = out.remaining();
807      this.buf.get(out, getAbsoluteOffset(offset), len);
808      return len;
809    }
810
811    @Override
812    public int size() {
813      return this.length;
814    }
815  }
816}