<commit_before>/*
 * Copyright 2014 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "thrift/lib/cpp2/security/KerberosSASLHandshakeClient.h"

#include <gssapi/gssapi_generic.h>
#include <gssapi/gssapi_krb5.h>
#include <krb5.h>
#include <stdlib.h>
#include "folly/io/IOBuf.h"
#include "folly/io/Cursor.h"
#include "folly/Memory.h"
#include "thrift/lib/cpp/concurrency/Mutex.h"
#include "thrift/lib/cpp/transport/TSocketAddress.h"
#include "thrift/lib/cpp/util/kerberos/Krb5Util.h"
#include "thrift/lib/cpp/concurrency/Exception.h"
#include "thrift/lib/cpp/concurrency/FunctionRunner.h"
#include "thrift/lib/cpp2/security/KerberosSASLThreadManager.h"

extern "C" {
  #include <sys/types.h>
  #include <sys/socket.h>
  #include <netdb.h>
}

using namespace std;
using namespace apache::thrift;
using namespace folly;
using namespace apache::thrift::concurrency;
using namespace apache::thrift::krb5;
using apache::thrift::concurrency::FunctionRunner;
using apache::thrift::concurrency::TooManyPendingTasksException;

/**
 * Client functions.
 */
KerberosSASLHandshakeClient::KerberosSASLHandshakeClient() : phase_(INIT) {
  // Override the location of the conf file if it doesn't already exist.
  setenv("KRB5_CONFIG", "/etc/krb5-thrift.conf", 0);

  // Set required security properties, we can define setters for these if
  // they need to be modified later.
  requiredFlags_ =
    GSS_C_MUTUAL_FLAG |
    GSS_C_REPLAY_FLAG |
    GSS_C_SEQUENCE_FLAG |
    GSS_C_INTEG_FLAG |
    GSS_C_CONF_FLAG;

  context_ = GSS_C_NO_CONTEXT;
  targetName_ = GSS_C_NO_NAME;
  clientCreds_ = GSS_C_NO_CREDENTIAL;
  contextStatus_ = GSS_S_NO_CONTEXT;

  // Bitmask specifying a requirement for all security layers and max
  // buffer length from the protocol. If we ever allow different security layer
  // properties, this would need to become more dynamic.
  // Confidentiality=04, Integrity=02, None=01.
  // Select only one of them (server can support several, client chooses one)
  securityLayerBitmask_ = 0x04ffffff;
  securityLayerBitmaskBuffer_ = IOBuf::create(sizeof(securityLayerBitmask_));
  io::Appender b(securityLayerBitmaskBuffer_.get(), 0);
  b.writeBE(securityLayerBitmask_);
}

KerberosSASLHandshakeClient::~KerberosSASLHandshakeClient() {
  auto threadManager = SaslThreadManager::getThreadManager();
  // Copy locally since 'this' may not exist when the async function runs
  gss_ctx_id_t context = context_;
  gss_name_t target_name = targetName_;
  gss_cred_id_t client_creds = clientCreds_;
  try {
    threadManager->add(std::make_shared<FunctionRunner>([=] {
      KerberosSASLHandshakeClient::cleanUpState(
        context, target_name, client_creds);
    }));
  } catch (const TooManyPendingTasksException& e) {
    // If we can't do this async, do it inline, since we don't want to leak
    // memory.
    KerberosSASLHandshakeClient::cleanUpState(<commit_msg>Don't spawn cleanup thread manager if there is nothing to clean<commit_after>/*
 * Copyright 2014 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "thrift/lib/cpp2/security/KerberosSASLHandshakeClient.h"

#include <gssapi/gssapi_generic.h>
#include <gssapi/gssapi_krb5.h>
#include <krb5.h>
#include <stdlib.h>
#include "folly/io/IOBuf.h"
#include "folly/io/Cursor.h"
#include "folly/Memory.h"
#include "thrift/lib/cpp/concurrency/Mutex.h"
#include "thrift/lib/cpp/transport/TSocketAddress.h"
#include "thrift/lib/cpp/util/kerberos/Krb5Util.h"
#include "thrift/lib/cpp/concurrency/Exception.h"
#include "thrift/lib/cpp/concurrency/FunctionRunner.h"
#include "thrift/lib/cpp2/security/KerberosSASLThreadManager.h"

extern "C" {
  #include <sys/types.h>
  #include <sys/socket.h>
  #include <netdb.h>
}

using namespace std;
using namespace apache::thrift;
using namespace folly;
using namespace apache::thrift::concurrency;
using namespace apache::thrift::krb5;
using apache::thrift::concurrency::FunctionRunner;
using apache::thrift::concurrency::TooManyPendingTasksException;

/**
 * Client functions.
 */
KerberosSASLHandshakeClient::KerberosSASLHandshakeClient() : phase_(INIT) {
  // Override the location of the conf file if it doesn't already exist.
  setenv("KRB5_CONFIG", "/etc/krb5-thrift.conf", 0);

  // Set required security properties, we can define setters for these if
  // they need to be modified later.
  requiredFlags_ =
    GSS_C_MUTUAL_FLAG |
    GSS_C_REPLAY_FLAG |
    GSS_C_SEQUENCE_FLAG |
    GSS_C_INTEG_FLAG |
    GSS_C_CONF_FLAG;

  context_ = GSS_C_NO_CONTEXT;
  targetName_ = GSS_C_NO_NAME;
  clientCreds_ = GSS_C_NO_CREDENTIAL;
  contextStatus_ = GSS_S_NO_CONTEXT;

  // Bitmask specifying a requirement for all security layers and max
  // buffer length from the protocol. If we ever allow different security layer
  // properties, this would need to become more dynamic.
  // Confidentiality=04, Integrity=02, None=01.
  // Select only one of them (server can support several, client chooses one)
  securityLayerBitmask_ = 0x04ffffff;
  securityLayerBitmaskBuffer_ = IOBuf::create(sizeof(securityLayerBitmask_));
  io::Appender b(securityLayerBitmaskBuffer_.get(), 0);
  b.writeBE(securityLayerBitmask_);
}

KerberosSASLHandshakeClient::~KerberosSASLHandshakeClient() {
  // Copy locally since 'this' may not exist when the async function runs
  gss_ctx_id_t context = context_;
  gss_name_t target_name = targetName_;
  gss_cred_id_t client_creds = clientCreds_;
  // Check if we actually need to clean up.
  if (context == GSS_C_NO_CONTEXT &&
      target_name == GSS_C_NO_NAME &&
      client_creds == GSS_C_NO_CREDENTIAL) {
    return;
  }
  try {
    auto threadManager = SaslThreadManager::getThreadManager();
    threadManager->add(std::make_shared<FunctionRunner>([=] {
      KerberosSASLHandshakeClient::cleanUpState(
        context, target_name, client_creds);
    }));
  } catch (const TooManyPendingTasksException& e) {
    // If we can't do this async, do it inline, since we don't want to leak
    // memory.
    KerberosSASLHandshakeClient::cleanUpState(
{'fraction_non_alphanumeric': 0.10093696763202725, 'fraction_numerical': 0.007666098807495741, 'mean_word_length': 4.663183279742765, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4329725', 'n_tokens_mistral': 2329, 'n_tokens_neox': 2301, 'n_words': 611}