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(
353                  rpcServer.getConf(), provider, rpcServer.saslProps, rpcServer.secretManager);
354          RpcServer.LOG.debug("Created SASL server with mechanism={}",
355              provider.getSaslAuthMethod().getAuthMethod());
356        }
357        RpcServer.LOG.debug("Read input token of size={} for processing by saslServer." +
358            "evaluateResponse()", saslToken.limit());
359        replyToken = saslServer.evaluateResponse(saslToken.hasArray()?
360            saslToken.array() : saslToken.toBytes());
361      } catch (IOException e) {
362        IOException sendToClient = e;
363        Throwable cause = e;
364        while (cause != null) {
365          if (cause instanceof InvalidToken) {
366            sendToClient = (InvalidToken) cause;
367            break;
368          }
369          cause = cause.getCause();
370        }
371        doRawSaslReply(SaslStatus.ERROR, null, sendToClient.getClass().getName(),
372          sendToClient.getLocalizedMessage());
373        this.rpcServer.metrics.authenticationFailure();
374        String clientIP = this.toString();
375        // attempting user could be null
376        RpcServer.AUDITLOG
377            .warn("{} {}: {}", RpcServer.AUTH_FAILED_FOR, clientIP, saslServer.getAttemptingUser());
378        throw e;
379      }
380      if (replyToken != null) {
381        if (RpcServer.LOG.isDebugEnabled()) {
382          RpcServer.LOG.debug("Will send token of size " + replyToken.length
383              + " from saslServer.");
384        }
385        doRawSaslReply(SaslStatus.SUCCESS, new BytesWritable(replyToken), null,
386            null);
387      }
388      if (saslServer.isComplete()) {
389        String qop = saslServer.getNegotiatedQop();
390        useWrap = qop != null && !"auth".equalsIgnoreCase(qop);
391        ugi = provider.getAuthorizedUgi(saslServer.getAuthorizationID(),
392            this.rpcServer.secretManager);
393        RpcServer.LOG.debug(
394            "SASL server context established. Authenticated client: {}. Negotiated QoP is {}",
395            ugi, qop);
396        this.rpcServer.metrics.authenticationSuccess();
397        RpcServer.AUDITLOG.info(RpcServer.AUTH_SUCCESSFUL_FOR + ugi);
398        saslContextEstablished = true;
399      }
400    }
401  }
402
403  private void processUnwrappedData(byte[] inBuf) throws IOException, InterruptedException {
404    ReadableByteChannel ch = Channels.newChannel(new ByteArrayInputStream(inBuf));
405    // Read all RPCs contained in the inBuf, even partial ones
406    while (true) {
407      int count;
408      if (unwrappedDataLengthBuffer.remaining() > 0) {
409        count = this.rpcServer.channelRead(ch, unwrappedDataLengthBuffer);
410        if (count <= 0 || unwrappedDataLengthBuffer.remaining() > 0)
411          return;
412      }
413
414      if (unwrappedData == null) {
415        unwrappedDataLengthBuffer.flip();
416        int unwrappedDataLength = unwrappedDataLengthBuffer.getInt();
417
418        if (unwrappedDataLength == RpcClient.PING_CALL_ID) {
419          if (RpcServer.LOG.isDebugEnabled())
420            RpcServer.LOG.debug("Received ping message");
421          unwrappedDataLengthBuffer.clear();
422          continue; // ping message
423        }
424        unwrappedData = ByteBuffer.allocate(unwrappedDataLength);
425      }
426
427      count = this.rpcServer.channelRead(ch, unwrappedData);
428      if (count <= 0 || unwrappedData.remaining() > 0)
429        return;
430
431      if (unwrappedData.remaining() == 0) {
432        unwrappedDataLengthBuffer.clear();
433        unwrappedData.flip();
434        processOneRpc(new SingleByteBuff(unwrappedData));
435        unwrappedData = null;
436      }
437    }
438  }
439
440  public void processOneRpc(ByteBuff buf) throws IOException,
441      InterruptedException {
442    if (connectionHeaderRead) {
443      processRequest(buf);
444    } else {
445      processConnectionHeader(buf);
446      this.connectionHeaderRead = true;
447      if (!authorizeConnection()) {
448        // Throw FatalConnectionException wrapping ACE so client does right thing and closes
449        // down the connection instead of trying to read non-existent retun.
450        throw new AccessDeniedException("Connection from " + this + " for service " +
451          connectionHeader.getServiceName() + " is unauthorized for user: " + ugi);
452      }
453      this.user = this.rpcServer.userProvider.create(this.ugi);
454    }
455  }
456
457  private boolean authorizeConnection() throws IOException {
458    try {
459      // If auth method is DIGEST, the token was obtained by the
460      // real user for the effective user, therefore not required to
461      // authorize real user. doAs is allowed only for simple or kerberos
462      // authentication
463      if (ugi != null && ugi.getRealUser() != null
464          && provider.supportsProtocolAuthentication()) {
465        ProxyUsers.authorize(ugi, this.getHostAddress(), this.rpcServer.conf);
466      }
467      this.rpcServer.authorize(ugi, connectionHeader, getHostInetAddress());
468      this.rpcServer.metrics.authorizationSuccess();
469    } catch (AuthorizationException ae) {
470      if (RpcServer.LOG.isDebugEnabled()) {
471        RpcServer.LOG.debug("Connection authorization failed: " + ae.getMessage(), ae);
472      }
473      this.rpcServer.metrics.authorizationFailure();
474      doRespond(getErrorResponse(ae.getMessage(), new AccessDeniedException(ae)));
475      return false;
476    }
477    return true;
478  }
479
480  // Reads the connection header following version
481  private void processConnectionHeader(ByteBuff buf) throws IOException {
482    if (buf.hasArray()) {
483      this.connectionHeader = ConnectionHeader.parseFrom(buf.array());
484    } else {
485      CodedInputStream cis = UnsafeByteOperations.unsafeWrap(
486          new ByteBuffByteInput(buf, 0, buf.limit()), 0, buf.limit()).newCodedInput();
487      cis.enableAliasing(true);
488      this.connectionHeader = ConnectionHeader.parseFrom(cis);
489    }
490    String serviceName = connectionHeader.getServiceName();
491    if (serviceName == null) throw new EmptyServiceNameException();
492    this.service = RpcServer.getService(this.rpcServer.services, serviceName);
493    if (this.service == null) throw new UnknownServiceException(serviceName);
494    setupCellBlockCodecs(this.connectionHeader);
495    RPCProtos.ConnectionHeaderResponse.Builder chrBuilder =
496        RPCProtos.ConnectionHeaderResponse.newBuilder();
497    setupCryptoCipher(this.connectionHeader, chrBuilder);
498    responseConnectionHeader(chrBuilder);
499    UserGroupInformation protocolUser = createUser(connectionHeader);
500    if (!useSasl) {
501      ugi = protocolUser;
502      if (ugi != null) {
503        ugi.setAuthenticationMethod(AuthenticationMethod.SIMPLE);
504      }
505      // audit logging for SASL authenticated users happens in saslReadAndProcess()
506      if (authenticatedWithFallback) {
507        RpcServer.LOG.warn("Allowed fallback to SIMPLE auth for {} connecting from {}",
508            ugi, getHostAddress());
509      }
510    } else {
511      // user is authenticated
512      ugi.setAuthenticationMethod(provider.getSaslAuthMethod().getAuthMethod());
513      //Now we check if this is a proxy user case. If the protocol user is
514      //different from the 'user', it is a proxy user scenario. However,
515      //this is not allowed if user authenticated with DIGEST.
516      if ((protocolUser != null)
517          && (!protocolUser.getUserName().equals(ugi.getUserName()))) {
518        if (!provider.supportsProtocolAuthentication()) {
519          // Not allowed to doAs if token authentication is used
520          throw new AccessDeniedException("Authenticated user (" + ugi
521              + ") doesn't match what the client claims to be ("
522              + protocolUser + ")");
523        } else {
524          // Effective user can be different from authenticated user
525          // for simple auth or kerberos auth
526          // The user is the real user. Now we create a proxy user
527          UserGroupInformation realUser = ugi;
528          ugi = UserGroupInformation.createProxyUser(protocolUser
529              .getUserName(), realUser);
530          // Now the user is a proxy user, set Authentication method Proxy.
531          ugi.setAuthenticationMethod(AuthenticationMethod.PROXY);
532        }
533      }
534    }
535    String version;
536    if (this.connectionHeader.hasVersionInfo()) {
537      // see if this connection will support RetryImmediatelyException
538      this.retryImmediatelySupported =
539          VersionInfoUtil.hasMinimumVersion(getVersionInfo(), 1, 2);
540      version = this.connectionHeader.getVersionInfo().getVersion();
541    } else {
542      version = "UNKNOWN";
543    }
544    RpcServer.AUDITLOG.info("Connection from {}:{}, version={}, sasl={}, ugi={}, service={}",
545        this.hostAddress, this.remotePort, version, this.useSasl, this.ugi, serviceName);
546  }
547
548  /**
549   * Send the response for connection header
550   */
551  private void responseConnectionHeader(RPCProtos.ConnectionHeaderResponse.Builder chrBuilder)
552      throws FatalConnectionException {
553    // Response the connection header if Crypto AES is enabled
554    if (!chrBuilder.hasCryptoCipherMeta()) return;
555    try {
556      byte[] connectionHeaderResBytes = chrBuilder.build().toByteArray();
557      // encrypt the Crypto AES cipher meta data with sasl server, and send to client
558      byte[] unwrapped = new byte[connectionHeaderResBytes.length + 4];
559      Bytes.putBytes(unwrapped, 0, Bytes.toBytes(connectionHeaderResBytes.length), 0, 4);
560      Bytes.putBytes(unwrapped, 4, connectionHeaderResBytes, 0, connectionHeaderResBytes.length);
561      byte[] wrapped = saslServer.wrap(unwrapped, 0, unwrapped.length);
562      BufferChain bc;
563      try (ByteBufferOutputStream response = new ByteBufferOutputStream(wrapped.length + 4);
564          DataOutputStream out = new DataOutputStream(response)) {
565        out.writeInt(wrapped.length);
566        out.write(wrapped);
567        bc = new BufferChain(response.getByteBuffer());
568      }
569      doRespond(() -> bc);
570    } catch (IOException ex) {
571      throw new UnsupportedCryptoException(ex.getMessage(), ex);
572    }
573  }
574
575  protected abstract void doRespond(RpcResponse resp) throws IOException;
576
577  /**
578   * @param buf
579   *          Has the request header and the request param and optionally
580   *          encoded data buffer all in this one array.
581   * @throws IOException
582   * @throws InterruptedException
583   */
584  protected void processRequest(ByteBuff buf) throws IOException,
585      InterruptedException {
586    long totalRequestSize = buf.limit();
587    int offset = 0;
588    // Here we read in the header. We avoid having pb
589    // do its default 4k allocation for CodedInputStream. We force it to use
590    // backing array.
591    CodedInputStream cis;
592    if (buf.hasArray()) {
593      cis = UnsafeByteOperations.unsafeWrap(buf.array(), 0, buf.limit()).newCodedInput();
594    } else {
595      cis = UnsafeByteOperations
596          .unsafeWrap(new ByteBuffByteInput(buf, 0, buf.limit()), 0, buf.limit()).newCodedInput();
597    }
598    cis.enableAliasing(true);
599    int headerSize = cis.readRawVarint32();
600    offset = cis.getTotalBytesRead();
601    Message.Builder builder = RequestHeader.newBuilder();
602    ProtobufUtil.mergeFrom(builder, cis, headerSize);
603    RequestHeader header = (RequestHeader) builder.build();
604    offset += headerSize;
605    int id = header.getCallId();
606    if (RpcServer.LOG.isTraceEnabled()) {
607      RpcServer.LOG.trace("RequestHeader " + TextFormat.shortDebugString(header)
608          + " totalRequestSize: " + totalRequestSize + " bytes");
609    }
610    // Enforcing the call queue size, this triggers a retry in the client
611    // This is a bit late to be doing this check - we have already read in the
612    // total request.
613    if ((totalRequestSize +
614        this.rpcServer.callQueueSizeInBytes.sum()) > this.rpcServer.maxQueueSizeInBytes) {
615      final ServerCall<?> callTooBig = createCall(id, this.service, null, null, null, null,
616        totalRequestSize, null, 0, this.callCleanup);
617      this.rpcServer.metrics.exception(RpcServer.CALL_QUEUE_TOO_BIG_EXCEPTION);
618      callTooBig.setResponse(null, null,  RpcServer.CALL_QUEUE_TOO_BIG_EXCEPTION,
619        "Call queue is full on " + this.rpcServer.server.getServerName() +
620        ", is hbase.ipc.server.max.callqueue.size too small?");
621      callTooBig.sendResponseIfReady();
622      return;
623    }
624    MethodDescriptor md = null;
625    Message param = null;
626    CellScanner cellScanner = null;
627    try {
628      if (header.hasRequestParam() && header.getRequestParam()) {
629        md = this.service.getDescriptorForType().findMethodByName(
630            header.getMethodName());
631        if (md == null)
632          throw new UnsupportedOperationException(header.getMethodName());
633        builder = this.service.getRequestPrototype(md).newBuilderForType();
634        cis.resetSizeCounter();
635        int paramSize = cis.readRawVarint32();
636        offset += cis.getTotalBytesRead();
637        if (builder != null) {
638          ProtobufUtil.mergeFrom(builder, cis, paramSize);
639          param = builder.build();
640        }
641        offset += paramSize;
642      } else {
643        // currently header must have request param, so we directly throw
644        // exception here
645        String msg = "Invalid request header: "
646            + TextFormat.shortDebugString(header)
647            + ", should have param set in it";
648        RpcServer.LOG.warn(msg);
649        throw new DoNotRetryIOException(msg);
650      }
651      if (header.hasCellBlockMeta()) {
652        buf.position(offset);
653        ByteBuff dup = buf.duplicate();
654        dup.limit(offset + header.getCellBlockMeta().getLength());
655        cellScanner = this.rpcServer.cellBlockBuilder.createCellScannerReusingBuffers(
656            this.codec, this.compressionCodec, dup);
657      }
658    } catch (Throwable t) {
659      InetSocketAddress address = this.rpcServer.getListenerAddress();
660      String msg = (address != null ? address : "(channel closed)")
661          + " is unable to read call parameter from client "
662          + getHostAddress();
663      RpcServer.LOG.warn(msg, t);
664
665      this.rpcServer.metrics.exception(t);
666
667      // probably the hbase hadoop version does not match the running hadoop
668      // version
669      if (t instanceof LinkageError) {
670        t = new DoNotRetryIOException(t);
671      }
672      // If the method is not present on the server, do not retry.
673      if (t instanceof UnsupportedOperationException) {
674        t = new DoNotRetryIOException(t);
675      }
676
677      ServerCall<?> readParamsFailedCall = createCall(id, this.service, null, null, null, null,
678        totalRequestSize, null, 0, this.callCleanup);
679      readParamsFailedCall.setResponse(null, null, t, msg + "; " + t.getMessage());
680      readParamsFailedCall.sendResponseIfReady();
681      return;
682    }
683
684    int timeout = 0;
685    if (header.hasTimeout() && header.getTimeout() > 0) {
686      timeout = Math.max(this.rpcServer.minClientRequestTimeout, header.getTimeout());
687    }
688    ServerCall<?> call = createCall(id, this.service, md, header, param, cellScanner, totalRequestSize,
689      this.addr, timeout, this.callCleanup);
690
691    if (!this.rpcServer.scheduler.dispatch(new CallRunner(this.rpcServer, call))) {
692      this.rpcServer.callQueueSizeInBytes.add(-1 * call.getSize());
693      this.rpcServer.metrics.exception(RpcServer.CALL_QUEUE_TOO_BIG_EXCEPTION);
694      call.setResponse(null, null, RpcServer.CALL_QUEUE_TOO_BIG_EXCEPTION,
695        "Call queue is full on " + this.rpcServer.server.getServerName() +
696            ", too many items queued ?");
697      call.sendResponseIfReady();
698    }
699  }
700
701  protected final RpcResponse getErrorResponse(String msg, Exception e) throws IOException {
702    ResponseHeader.Builder headerBuilder = ResponseHeader.newBuilder().setCallId(-1);
703    ServerCall.setExceptionResponse(e, msg, headerBuilder);
704    ByteBuffer headerBuf =
705        ServerCall.createHeaderAndMessageBytes(null, headerBuilder.build(), 0, null);
706    BufferChain buf = new BufferChain(headerBuf);
707    return () -> buf;
708  }
709
710  private void doBadPreambleHandling(String msg) throws IOException {
711    doBadPreambleHandling(msg, new FatalConnectionException(msg));
712  }
713
714  private void doBadPreambleHandling(String msg, Exception e) throws IOException {
715    SimpleRpcServer.LOG.warn(msg);
716    doRespond(getErrorResponse(msg, e));
717  }
718
719  protected final boolean processPreamble(ByteBuffer preambleBuffer) throws IOException {
720    assert preambleBuffer.remaining() == 6;
721    for (int i = 0; i < RPC_HEADER.length; i++) {
722      if (RPC_HEADER[i] != preambleBuffer.get()) {
723        doBadPreambleHandling(
724          "Expected HEADER=" + Bytes.toStringBinary(RPC_HEADER) + " but received HEADER=" +
725              Bytes.toStringBinary(preambleBuffer.array(), 0, RPC_HEADER.length) + " from " +
726              toString());
727        return false;
728      }
729    }
730    int version = preambleBuffer.get() & 0xFF;
731    byte authbyte = preambleBuffer.get();
732
733    if (version != SimpleRpcServer.CURRENT_VERSION) {
734      String msg = getFatalConnectionString(version, authbyte);
735      doBadPreambleHandling(msg, new WrongVersionException(msg));
736      return false;
737    }
738    this.provider = this.saslProviders.selectProvider(authbyte);
739    if (this.provider == null) {
740      String msg = getFatalConnectionString(version, authbyte);
741      doBadPreambleHandling(msg, new BadAuthException(msg));
742      return false;
743    }
744    // TODO this is a wart while simple auth'n doesn't go through sasl.
745    if (this.rpcServer.isSecurityEnabled && isSimpleAuthentication()) {
746      if (this.rpcServer.allowFallbackToSimpleAuth) {
747        this.rpcServer.metrics.authenticationFallback();
748        authenticatedWithFallback = true;
749      } else {
750        AccessDeniedException ae = new AccessDeniedException("Authentication is required");
751        doRespond(getErrorResponse(ae.getMessage(), ae));
752        return false;
753      }
754    }
755    if (!this.rpcServer.isSecurityEnabled && !isSimpleAuthentication()) {
756      doRawSaslReply(SaslStatus.SUCCESS, new IntWritable(SaslUtil.SWITCH_TO_SIMPLE_AUTH), null,
757        null);
758      provider = saslProviders.getSimpleProvider();
759      // client has already sent the initial Sasl message and we
760      // should ignore it. Both client and server should fall back
761      // to simple auth from now on.
762      skipInitialSaslHandshake = true;
763    }
764    useSasl = !(provider instanceof SimpleSaslServerAuthenticationProvider);
765    return true;
766  }
767
768  boolean isSimpleAuthentication() {
769    return Objects.requireNonNull(provider) instanceof SimpleSaslServerAuthenticationProvider;
770  }
771
772  public abstract boolean isConnectionOpen();
773
774  public abstract ServerCall<?> createCall(int id, BlockingService service, MethodDescriptor md,
775      RequestHeader header, Message param, CellScanner cellScanner, long size,
776      InetAddress remoteAddress, int timeout, CallCleanup reqCleanup);
777
778  private static class ByteBuffByteInput extends ByteInput {
779
780    private ByteBuff buf;
781    private int offset;
782    private int length;
783
784    ByteBuffByteInput(ByteBuff buf, int offset, int length) {
785      this.buf = buf;
786      this.offset = offset;
787      this.length = length;
788    }
789
790    @Override
791    public byte read(int offset) {
792      return this.buf.get(getAbsoluteOffset(offset));
793    }
794
795    private int getAbsoluteOffset(int offset) {
796      return this.offset + offset;
797    }
798
799    @Override
800    public int read(int offset, byte[] out, int outOffset, int len) {
801      this.buf.get(getAbsoluteOffset(offset), out, outOffset, len);
802      return len;
803    }
804
805    @Override
806    public int read(int offset, ByteBuffer out) {
807      int len = out.remaining();
808      this.buf.get(out, getAbsoluteOffset(offset), len);
809      return len;
810    }
811
812    @Override
813    public int size() {
814      return this.length;
815    }
816  }
817}