text:
import pytest
import numpy as np
from gamtools import main
try:
    from unittest.mock import patch
except ImportError:
    from mock import patch

def test_no_args():
    with pytest.raises(SystemExit) as error_msg:
        print(main.parser.parse_args([]))

def test_fixed_threshold():

    args = main.parser.parse_args(['call_windows', '-x', '4', '/dev/null'])

    fitting_result = args.fitting_function(np.arange(100))

    assert fitting_result['coverage_threshold'] == 4
    assert fitting_result['params'] is None

def test_fixed_threshold_5():

    args = main.parser.parse_args(['call_windows', '-x', '5', '/dev/null'])

    fitting_result = args.fitting_function(np.arange(100))

    assert fitting_result['coverage_threshold'] == 5.0
    assert fitting_result['params'] is None

def test_fixed_threshold_process_nps():

    args = main.parser.parse_args(['process_nps', '-g', '/dev/null', '-x', '4', '/dev/null'])

    fitting_result = args.fitting_function(np.arange(100))

    assert fitting_result['coverage_threshold'] == 4
    assert fitting_result['params'] is None

def test_min_threshold_none():

    args = main.parser.parse_args(['call_windows', '/dev/null'])

    assert args.min_read_threshold is None

def test_min_threshold_3():

    args = main.parser.parse_args(['call_windows', '/dev/null', '--min-read-threshold', '3'])

    assert args.min_read_threshold == 3


text:
/**
 * WooCommerce Smart Coupons
 */
/**
 * Imports
 */
.woocommerce .coupon-container,
.woocommerce-page .coupon-container {
  margin: 0;
  box-shadow: none; }
  .woocommerce .coupon-container.medium,
  .woocommerce-page .coupon-container.medium {
    line-height: inherit;
    padding: 0.6180469716em; }

.woocommerce .generated_coupon_summary,
.woocommerce-page .generated_coupon_summary {
  margin: 0; }

.woocommerce .coupon-content.small,
.woocommerce-page .coupon-content.small {
  padding: 0.6180469716em 1.41575em; }

.woocommerce .coupon-content .coupon-expire,
.woocommerce .coupon-content .discount-info,
.woocommerce-page .coupon-content .coupon-expire,
.woocommerce-page .coupon-content .discount-info {
  font-family: inherit; }

.woocommerce #coupons_list,
.woocommerce-page #coupons_list {
  margin-bottom: 1.618em; }

.sd-buttons-transparent.woocommerce .coupon-container, .sd-buttons-transparent.woocommerce-page .coupon-container {
  background: transparent !important;
  padding: 0; }

@media (min-width: 768px) {
  .sc_info_box {
    width: 41.1764705882%;
    float: right;
    margin-right: 0;
    padding-left: 2.0833333333%;
    padding-right: 2.0833333333%; }
  .page-template-template-fullwidth-php .sc_info_box {
    width: 39.1304347826%;
    float: right;
    margin-right: 0;
    margin-left: 0; } }

redpajama_set_name: RedPajamaGithub


text:
package forklift.consumer;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import forklift.connectors.ConnectorException;
import forklift.connectors.ForkliftMessage;
import forklift.controller.KafkaController;
import forklift.message.MessageStream;
import forklift.message.KafkaMessage;

public class KafkaTopicConsumerTests {

    private String topic;
    private KafkaController controller;
    private MessageStream messageStream;
    private KafkaTopicConsumer consumer;

    @BeforeEach
    public void setup() {
        this.topic = "testTopic";
        this.controller = mock(KafkaController.class);
        when(controller.isRunning()).thenReturn(true);
        this.messageStream = mock(MessageStream.class);
        when(controller.getMessageStream()).thenReturn(this.messageStream);
        consumer = new KafkaTopicConsumer(topic, controller);
    }

    @Test
    public void receiveTimeoutTest() throws InterruptedException, ConnectorException {
        long timeout = 100;
        when(messageStream.nextRecord(this.topic, timeout)).thenReturn(null);
        ForkliftMessage result = consumer.receive(timeout);
        assertEquals(null, result);
    }

    @Test
    public void receiveMessageTest() throws InterruptedException, ConnectorException {
        KafkaMessage message = mock(KafkaMessage.class);
        long timeout = 100;
        when(messageStream.nextRecord(this.topic, timeout)).thenReturn(message);
        ForkliftMessage result = consumer.receive(timeout);
        assertEquals(message, result);
    }

    @Test
    public void receiveWithControllerNotRunning() throws ConnectorException {
        when(this.controller.isRunning()).thenReturn(false);
        assertThrows(ConnectorException.class, () -> {
            consumer.receive(100);
        });
    }
}


text:
// Copyright 2011-2016 Google LLC
//
// 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.

package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.TagContainer;

import com.google.security.zynamics.binnavi.Database.Interfaces.IDatabase;
import com.google.security.zynamics.binnavi.Gui.Actions.CActionProxy;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Actions.CAddTagAction;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractMenuBuilder;
import com.google.security.zynamics.binnavi.Tagging.CTag;
import com.google.security.zynamics.zylib.types.trees.ITreeNode;

import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JTree;

/**
 * Builds context menus for tag container nodes.
 */
public final class CTagContainerNodeMenuBuilder extends CAbstractMenuBuilder {
  /**
   * Database where the tags are stored.
   */
  private final IDatabase m_database;

  /**
   * Creates a new menu builder.
   *
   * @param projectTree Project tree of the main window.
   * @param database Database where the tags are stored.
   */
  public CTagContainerNodeMenuBuilder(final JTree projectTree, final IDatabase database) {
    super(projectTree);

    m_database = database;
  }

  @Override
  protected void createMenu(final JComponent menu) {
    final ITreeNode<CTag> rootNode = m_database.getContent().getViewTagManager().getRootTag();

    menu.add(new JMenuItem(CActionProxy.proxy(new CAddTagAction(getParent(), m_database
        .getContent().getViewTagManager(), rootNode, "New Tag"))));
  }

  @Override
  protected JMenu getMenu() {
    final JMenu menu = new JMenu("Tagging");

    menu.setMnemonic("HK_MENU_TAGGING".charAt(0));

    return menu;
  }
}


text:
package main

import (
	"fmt"
	"github.com/vladshub/hydra-node/control"
	"github.com/vladshub/hydra-node/discovery"
	"github.com/vladshub/hydra-node/players"
)

func main() {

	// 1. Register to mDns, consul, etcd ....
	// 2. Create an control interface
	// 2.1.  gRPC interface
	// 2.2.  HTTP interface
	// 3. File System Manager
	// 3.1. Mount ability
	// 3.1.1. NFS
	// 3.1.1. SMB
	// 3.1.1. ?
	// 5. Create player
	// 5.1. omxplayer
	// 6. Attach player to control interface

	// Setup our service export
	disc, err := discovery.DiscoveryFuctory("mDNS", "Hydra Client", "Hydra")
	if err != nil {
		panic(err)
	}
	err = disc.Register()

	if err != nil {
		panic(err)
	}

	player, err := players.PlayerFactory("OmxPlayer")
	if err != nil {
		panic(err)
	}

	control, err := control.ControlFactory("HttpControl", player, nil)
	if err != nil {
		panic(err)
	}

	control.Listen("0.0.0.0:8080")
	fmt.Println("Done")
	// Setup HTTP server
	//	router := gin.Default()

}


text:
@class DVTStackBacktrace, NSString;

@interface IDEEditorContext_DoNothingObject : NSObject <DVTInvalidation>
{
}

+ (void)initialize;
- (void)doNothing;
- (void)primitiveInvalidate;

// Remaining properties
@property(retain) DVTStackBacktrace *creationBacktrace;
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) DVTStackBacktrace *invalidationBacktrace;
@property(readonly) Class superclass;
@property(readonly, nonatomic, getter=isValid) BOOL valid;

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>M-Index</title>
<meta name="date" content="2016-02-25">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

B C D F G I L M N P R S T U V W

M

MatrixSet - Class in net.jibini.glutils.utils

Utility for handling projection, view,
 and model matrices.

MatrixSet() - Constructor for class net.jibini.glutils.utils.MatrixSet

Creates new matrices and sets identity.

MeshRenderer - Class in net.jibini.glutils

Renders interleaved vertices compliantly.

MeshRenderer() - Constructor for class net.jibini.glutils.MeshRenderer

Creates vertex array and vertex buffer objects.

model - Variable in class net.jibini.glutils.utils.MatrixSet

Application model matrix.

MODEL_UNIFORM - Static variable in class net.jibini.glutils.GLUtils

Name of the model matrix shader uniform.

B C D F G I L M N P R S T U V W

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
__author__ = 'Ulric Qin'
from rrd.store import db

class Bean(object):
    _tbl = ''
    _id = 'id'
    _cols = ''
    _db = db

    @classmethod
    def insert(cls, data=None):
        if not data:
            raise ValueError('argument data is invalid')

        size = len(data)
        keys = data.keys()
        safe_keys = ['`%s`' % k for k in keys]
        sql = 'INSERT INTO `%s`(%s) VALUES(%s)' % (cls._tbl, ','.join(safe_keys), '%s' + ',%s' * (size - 1))
        last_id = cls._db.insert(sql, [data[key] for key in keys])
        return last_id

    @classmethod
    def delete(cls, where=None, params=None):
        sql = 'DELETE FROM `%s`' % cls._tbl
        if not where:
            return cls._db.update(sql)

        sql += ' WHERE ' + where
        return cls._db.update(sql, params)

    @classmethod
    def delete_one(cls, pk=None):
        sql = 'DELETE FROM `%s` WHERE %s = %%s' % (cls._tbl, cls._id)
        return cls._db.update(sql, [pk])

    @classmethod
    def update(cls, clause=None, params=None):
        sql = 'UPDATE `%s` SET %s' % (cls._tbl, clause)
        return cls._db.update(sql, params)

    @classmethod
    def update_dict(cls, data=None, where='', params=None):
        if not data:
            raise ValueError('argument data is invalid')

        size = len(data)
        keys = data.keys()
        safe_keys = ['`%s`' % k for k in keys]
        values = [data[key] for key in keys]
        arr = ['%s=%%s' % key for key in safe_keys]
        if not where:
            return cls.update(','.join(arr), values)
        else:
            values.extend(params)
            return cls.update(', '.join(arr) + ' WHERE ' + where, values)

    @classmethod
    def select(cls, cols=None, where=None, params=None, order=None, limit=None, page=None, offset=None):
        if cols is None:
            cols = cls._cols

        if params is None:
            params = []

        sql = 'SELECT %s FROM `%s`' % (cols, cls._tbl)

        if where:
            sql = '%s WHERE %s' % (sql, where)

        if order:
            sql = '%s ORDER BY %s' % (sql, order)

        if limit is not None:
            sql = '%s LIMIT %s' % (sql, limit)

        if offset is not None:
            sql = '%s OFFSET %s' % (sql, offset)

        if page is not None:
            offset = (int(page) - 1) * int(limit)
            if offset < 0:
                offset = 0
            sql = '%s OFFSET %s' % (sql, offset)

        return cls._db.query_all(sql, params)

    @classmethod
    def select_vs(cls, where=None, params=None, order=None, limit=None, page=None, offset=None):
        rows = cls.select(where=where, params=params, order=order, limit=limit, page=page, offset=offset)
        return [cls(*row) for row in rows]

    @classmethod
    def read(cls, where=None, params=None):
        vs = cls.select_vs(where=where, params=params)
        if vs:
            return vs[0]
        else:
            return None

    @classmethod
    def get(cls, id_val):
        if not id_val:
            return None

        return cls.read('%s = %%s' % cls._id, [id_val])

    @classmethod
    def column(cls, col=None, where=None, params=None, order=None, limit=None, page=None, offset=None):
        rows = cls.select(col, where, params, order, limit, page, offset)
        return [row[0] for row in rows]

    @classmethod
    def total(cls, where=None, params=None):
        sql = 'SELECT COUNT(1) FROM `%s`' % cls._tbl
        if not where:
            ret = cls._db.query_column(sql)
            return ret[0]

        sql += ' WHERE ' + where
        ret = cls._db.query_column(sql, params)
        return ret[0]

    @classmethod
    def exists(cls, where=None, params=None):
        return cls.total(where, params) > 0


text:
package io.dropwizard.jobs;

import io.dropwizard.jobs.annotations.On;

@On("${onTestJob}")
public class OnTestJobAlternativeConfiguration extends AbstractJob {

    public OnTestJobAlternativeConfiguration() {
        super(1);
    }

}


text:
package sql

import (
	"fmt"

	"github.com/cockroachdb/cockroach/sql/parser"
	"github.com/cockroachdb/cockroach/sql/sqlbase"
)

// upsertExcludedTable is the name of a synthetic table used in an upsert's set
// expressions to refer to the values that would be inserted for a row if it
// didn't conflict.
// Example: `INSERT INTO kv VALUES (1, 2) ON CONFLICT (k) DO UPDATE SET v = excluded.v`
const upsertExcludedTable = "excluded"

type upsertHelper struct {
	p                  *planner
	qvals              qvalMap
	evalExprs          []parser.TypedExpr
	sourceInfo         *dataSourceInfo
	excludedSourceInfo *dataSourceInfo
	allExprsIdentity   bool
}

var _ tableUpsertEvaler = (*upsertHelper)(nil)

func (p *planner) makeUpsertHelper(
	tableDesc *sqlbase.TableDescriptor,
	insertCols []sqlbase.ColumnDescriptor,
	updateCols []sqlbase.ColumnDescriptor,
	updateExprs parser.UpdateExprs,
	upsertConflictIndex *sqlbase.IndexDescriptor,
) (*upsertHelper, error) {
	defaultExprs, err := makeDefaultExprs(updateCols, &p.parser, &p.evalCtx)
	if err != nil {
		return nil, err
	}

	untupledExprs := make(parser.Exprs, 0, len(updateExprs))
	i := 0
	for _, updateExpr := range updateExprs {
		if updateExpr.Tuple {
			if t, ok := updateExpr.Expr.(*parser.Tuple); ok {
				for _, e := range t.Exprs {
					typ := updateCols[i].Type.ToDatumType()
					e := fillDefault(e, typ, i, defaultExprs)
					untupledExprs = append(untupledExprs, e)
					i++
				}
			}
		} else {
			typ := updateCols[i].Type.ToDatumType()
			e := fillDefault(updateExpr.Expr, typ, i, defaultExprs)
			untupledExprs = append(untupledExprs, e)
			i++
		}
	}

	allExprsIdentity := true
	for i, expr := range untupledExprs {
		qn, ok := expr.(*parser.QualifiedName)
		if !ok {
			allExprsIdentity = false
			break
		}
		if err := qn.NormalizeColumnName(); err != nil {
			return nil, err
		}
		if qn.Base != upsertExcludedTable || qn.Column() != updateCols[i].Name {
			allExprsIdentity = false
			break
		}
	}

	sourceInfo := newSourceInfoForSingleTable(tableDesc.Name, makeResultColumns(tableDesc.Columns))
	excludedSourceInfo := newSourceInfoForSingleTable(upsertExcludedTable, makeResultColumns(insertCols))

	var evalExprs []parser.TypedExpr
	qvals := make(qvalMap)
	sources := multiSourceInfo{sourceInfo, excludedSourceInfo}
	for _, expr := range untupledExprs {
		normExpr, err := p.analyzeExpr(expr, sources, qvals, parser.NoTypePreference, false, "")
		if err != nil {
			return nil, err
		}
		evalExprs = append(evalExprs, normExpr)
	}

	helper := &upsertHelper{
		p:                  p,
		qvals:              qvals,
		evalExprs:          evalExprs,
		sourceInfo:         sourceInfo,
		excludedSourceInfo: excludedSourceInfo,
		allExprsIdentity:   allExprsIdentity,
	}

	return helper, nil
}

func (uh *upsertHelper) expand() error {
	for _, evalExpr := range uh.evalExprs {
		if err := uh.p.expandSubqueryPlans(evalExpr); err != nil {
			return err
		}
	}
	return nil
}

func (uh *upsertHelper) start() error {
	for _, evalExpr := range uh.evalExprs {
		if err := uh.p.startSubqueryPlans(evalExpr); err != nil {
			return err
		}
	}
	return nil
}

// eval returns the values for the update case of an upsert, given the row
// that would have been inserted and the existing (conflicting) values.
func (uh *upsertHelper) eval(
	insertRow parser.DTuple, existingRow parser.DTuple,
) (parser.DTuple, error) {
	uh.qvals.populateQVals(uh.sourceInfo, existingRow)
	uh.qvals.populateQVals(uh.excludedSourceInfo, insertRow)

	var err error
	ret := make([]parser.Datum, len(uh.evalExprs))
	for i, evalExpr := range uh.evalExprs {
		ret[i], err = evalExpr.Eval(&uh.p.evalCtx)
		if err != nil {
			return nil, err
		}
	}
	return ret, nil
}

func (uh *upsertHelper) isIdentityEvaler() bool {
	return uh.allExprsIdentity
}

// upsertExprsAndIndex returns the upsert conflict index and the (possibly
// synthetic) SET expressions used when a row conflicts.
func upsertExprsAndIndex(
	tableDesc *sqlbase.TableDescriptor,
	onConflict parser.OnConflict,
	insertCols []sqlbase.ColumnDescriptor,
) (parser.UpdateExprs, *sqlbase.IndexDescriptor, error) {
	if onConflict.IsUpsertAlias() {
		// The UPSERT syntactic sugar is the same as the longhand specifying the
		// primary index as the conflict index and SET expressions for the columns
		// in insertCols minus any columns in the conflict index. Example:
		// `UPSERT INTO abc VALUES (1, 2, 3)` is syntactic sugar for
		// `INSERT INTO abc VALUES (1, 2, 3) ON CONFLICT a DO UPDATE SET b = 2, c = 3`.
		conflictIndex := &tableDesc.PrimaryIndex
		indexColSet := make(map[sqlbase.ColumnID]struct{}, len(conflictIndex.ColumnIDs))
		for _, colID := range conflictIndex.ColumnIDs {
			indexColSet[colID] = struct{}{}
		}
		updateExprs := make(parser.UpdateExprs, 0, len(insertCols))
		for _, c := range insertCols {
			if _, ok := indexColSet[c.ID]; !ok {
				names := parser.QualifiedNames{&parser.QualifiedName{Base: parser.Name(c.Name)}}
				expr := &parser.QualifiedName{
					Base:     upsertExcludedTable,
					Indirect: parser.Indirection{parser.NameIndirection(c.Name)},
				}
				if err := expr.NormalizeColumnName(); err != nil {
					return nil, nil, err
				}
				updateExprs = append(updateExprs, &parser.UpdateExpr{Names: names, Expr: expr})
			}
		}
		return updateExprs, conflictIndex, nil
	}

	indexMatch := func(index sqlbase.IndexDescriptor) bool {
		if !index.Unique {
			return false
		}
		if len(index.ColumnNames) != len(onConflict.Columns) {
			return false
		}
		for i, colName := range index.ColumnNames {
			if colName != onConflict.Columns[i] {
				return false
			}
		}
		return true
	}

	if indexMatch(tableDesc.PrimaryIndex) {
		return onConflict.Exprs, &tableDesc.PrimaryIndex, nil
	}
	for _, index := range tableDesc.Indexes {
		if indexMatch(index) {
			return onConflict.Exprs, &index, nil
		}
	}
	return nil, nil, fmt.Errorf("there is no unique or exclusion constraint matching the ON CONFLICT specification")
}


text:
<?php namespace Kironuniversity\Curriculum\Models;

use Model;

/**
 * TeachingMethod Model
 */
class TeachingMethod extends Model
{

    /**
     * @var string The database table used by the model.
     */
    public $table = 'teaching_method';

    /**
     * @var array Guarded fields
     */
    protected $guarded = ['*'];

    /**
     * @var array Fillable fields
     */
    protected $fillable = [];

    /**
     * @var array Relations
     */
    public $hasOne = [];
    public $hasMany = [];
    public $belongsTo = [];
    public $belongsToMany = [];
    public $morphTo = [];
    public $morphOne = [];
    public $morphMany = [];
    public $attachOne = [];
    public $attachMany = [];

}


text:
#include "includes.h"

#include "common.h"
#include "crypto/ms_funcs.h"
#include "crypto/sha1.h"
#include "crypto/tls.h"
#include "eap_common/chap.h"
#include "eap_common/eap_ttls.h"
#include "mschapv2.h"
#include "eap_i.h"
#include "eap_tls_common.h"
#include "eap_config.h"

#define EAP_TTLS_VERSION 0

static void eap_ttls_deinit(struct eap_sm *sm, void *priv);

struct eap_ttls_data {
	struct eap_ssl_data ssl;

	int ttls_version;

	const struct eap_method *phase2_method;
	void *phase2_priv;
	int phase2_success;
	int phase2_start;

	enum phase2_types {
		EAP_TTLS_PHASE2_EAP,
		EAP_TTLS_PHASE2_MSCHAPV2,
		EAP_TTLS_PHASE2_MSCHAP,
		EAP_TTLS_PHASE2_PAP,
		EAP_TTLS_PHASE2_CHAP
	} phase2_type;
	struct eap_method_type phase2_eap_type;
	struct eap_method_type *phase2_eap_types;
	size_t num_phase2_eap_types;

	u8 auth_response[MSCHAPV2_AUTH_RESPONSE_LEN];
	int auth_response_valid;
	u8 master_key[MSCHAPV2_MASTER_KEY_LEN];	/* MSCHAPv2 master key */
	u8 ident;
	int resuming;				/* starting a resumed session */
	int reauth;					/* reauthentication */
	u8 *key_data;
	u8 *session_id;
	size_t id_len;

	struct wpabuf *pending_phase2_req;

#ifdef EAP_TNC
	int ready_for_tnc;
	int tnc_started;
#endif							/* EAP_TNC */
};

static void *eap_ttls_init(struct eap_sm *sm)
{
	struct eap_ttls_data *data;
	struct eap_peer_config *config = eap_get_config(sm);
	char *selected;

	data = os_zalloc(sizeof(*data));
	if (data == NULL) {
		return NULL;
	}
	data->ttls_version = EAP_TTLS_VERSION;
	selected = "EAP";
	data->phase2_type = EAP_TTLS_PHASE2_EAP;

	if (config && config->phase2) {
		if (os_strstr(config->phase2, "autheap=")) {
			selected = "EAP";
			data->phase2_type = EAP_TTLS_PHASE2_EAP;
		} else if (os_strstr(config->phase2, "auth=MSCHAPV2")) {
			selected = "MSCHAPV2";
			data->phase2_type = EAP_TTLS_PHASE2_MSCHAPV2;
		} else if (os_strstr(config->phase2, "auth=MSCHAP")) {
			selected = "MSCHAP";
			data->phase2_type = EAP_TTLS_PHASE2_MSCHAP;
		} else if (os_strstr(config->phase2, "auth=PAP")) {
			selected = "PAP";
			data->phase2_type = EAP_TTLS_PHASE2_PAP;
		} else if (os_strstr(config->phase2, "auth=CHAP")) {
			selected = "CHAP";
			data->phase2_type = EAP_TTLS_PHASE2_CHAP;
		}
	}
	wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase2 type: %s", selected);

	if (data->phase2_type == EAP_TTLS_PHASE2_EAP) {
		if (eap_peer_select_phase2_methods(config, "autheap=", &data->phase2_eap_types, &data->num_phase2_eap_types)
			< 0) {
			eap_ttls_deinit(sm, data);
			return NULL;
		}

		data->phase2_eap_type.vendor = EAP_VENDOR_IETF;
		data->phase2_eap_type.method = EAP_TYPE_NONE;
	}

	if (eap_peer_tls_ssl_init(sm, &data->ssl, config, EAP_TYPE_TTLS)) {
		wpa_printf(MSG_INFO, "EAP-TTLS: Failed to initialize SSL.");
		eap_ttls_deinit(sm, data);
		return NULL;
	}

	return data;
}

static void eap_ttls_phase2_eap_deinit(struct eap_sm *sm, struct eap_ttls_data *data)
{
	if (data->phase2_priv && data->phase2_method) {
		data->phase2_method->deinit(sm, data->phase2_priv);
		data->phase2_method = NULL;
		data->phase2_priv = NULL;
	}
}

static void eap_ttls_free_key(struct eap_ttls_data *data)
{
	if (data->key_data) {
		bin_clear_free(data->key_data, EAP_TLS_KEY_LEN + EAP_EMSK_LEN);
		data->key_data = NULL;
	}
}

static void eap_ttls_deinit(struct eap_sm *sm, void *priv)
{
	struct eap_ttls_data *data = priv;
	if (data == NULL) {
		return;
	}
	eap_ttls_phase2_eap_deinit(sm, data);
	os_free(data->phase2_eap_types);
	eap_peer_tls_ssl_deinit(sm, &data->ssl);
	eap_ttls_free_key(data);
	os_free(data->session_id);
	wpabuf_free(data->pending_phase2_req);
	os_free(data);
}

static u8 *eap_ttls_avp_hdr(u8 *avphdr, u32 avp_code, u32 vendor_id, int mandatory, size_t len)
{
	struct ttls_avp_vendor *avp;
	u8 flags;
	size_t hdrlen;

	avp = (struct ttls_avp_vendor *)avphdr;
	flags = mandatory ? AVP_FLAGS_MANDATORY : 0;
	if (vendor_id) {
		flags |= AVP_FLAGS_VENDOR;
		hdrlen = sizeof(*avp);
		avp->vendor_id = host_to_be32(vendor_id);
	} else {
		hdrlen = sizeof(struct ttls_avp);
	}

	avp->avp_code = host_to_be32(avp_code);
	avp->avp_length = host_to_be32((flags << 24) | (u32)(hdrlen + len));

	return avphdr + hdrlen;
}

static u8 *eap_ttls_avp_add(u8 *start, u8 *avphdr, u32 avp_code, u32 vendor_id, int mandatory, const u8 *data, size_t len)
{
	u8 *pos;
	pos = eap_ttls_avp_hdr(avphdr, avp_code, vendor_id, mandatory, len);
	os_memcpy(pos, data, len);
	pos += len;
	AVP_PAD(start, pos);
	return pos;
}

static int eap_ttls_avp_encapsulate(struct wpabuf **resp, u32 avp_code, int mandatory)
{
	struct wpabuf *msg;
	u8 *avp, *pos;

	msg = wpabuf_alloc(sizeof(struct ttls_avp) + wpabuf_len(*resp) + 4);
	if (msg == NULL) {
		wpabuf_free(*resp);
		*resp = NULL;
		return -1;
	}

	avp = wpabuf_mhead(msg);
	pos = eap_ttls_avp_hdr(avp, avp_code, 0, mandatory, wpabuf_len(*resp));
	os_memcpy(pos, wpabuf_head(*resp), wpabuf_len(*resp));
	pos += wpabuf_len(*resp);
	AVP_PAD(avp, pos);
	wpabuf_free(*resp);
	wpabuf_put(msg, pos - avp);
	*resp = msg;
	return 0;
}

static int eap_ttls_v0_derive_key(struct eap_sm *sm, struct eap_ttls_data *data)
{
	eap_ttls_free_key(data);
	data->key_data = eap_peer_tls_derive_key(sm, &data->ssl, "ttls keying material", EAP_TLS_KEY_LEN + EAP_EMSK_LEN);
	if (!data->key_data) {
		wpa_printf(MSG_INFO, "EAP-TTLS: Failed to derive key");
		return -1;
	}

	wpa_hexdump_key(MSG_DEBUG, "EAP-TTLS: Derived key", data->key_data, EAP_TLS_KEY_LEN);
	wpa_hexdump_key(MSG_DEBUG, "EAP-TTLS: Derived EMSK", data->key_data + EAP_TLS_KEY_LEN, EAP_EMSK_LEN);

	os_free(data->session_id);
	data->session_id = eap_peer_tls_derive_session_id(sm, &data->ssl, EAP_TYPE_TTLS, &data->id_len);
	if (data->session_id) {
		wpa_hexdump(MSG_DEBUG, "EAP-TTLS: Derived Session-Id", data->session_id, data->id_len);
	} else {
		wpa_printf(MSG_ERROR, "EAP-TTLS: Failed to derive Session-Id");
	}

	return 0;
}

static u8 *eap_ttls_implicit_challenge(struct eap_sm *sm, struct eap_ttls_data *data, size_t len)
{
	return eap_peer_tls_derive_key(sm, &data->ssl, "ttls challenge", len);
}

static void eap_ttls_phase2_select_eap_method(struct eap_ttls_data *data, u8 method)
{
	size_t i;
	for (i = 0; i < data->num_phase2_eap_types; i++) {
		if (data->phase2_eap_types[i].vendor != EAP_VENDOR_IETF || data->phase2_eap_types[i].method != method) {
			continue;
		}

		data->phase2_eap_type.vendor = data->phase2_eap_types[i].vendor;
		data->phase2_eap_type.method = data->phase2_eap_types[i].method;
		wpa_printf(MSG_DEBUG, "EAP-TTLS: Selected " "Phase 2 EAP vendor %d method %d", data->phase2_eap_type.vendor, data->phase2_eap_type.method);
		break;
	}
}

static int eap_ttls_phase2_eap_process(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, struct eap_hdr *hdr, size_t len, struct wpabuf **resp)
{
	struct wpabuf msg;
	struct eap_method_ret iret;

	os_memset(&iret, 0, sizeof(iret));
	wpabuf_set(&msg, hdr, len);
	*resp = data->phase2_method->process(sm, data->phase2_priv, &iret, &msg);
	if ((iret.methodState == METHOD_DONE || iret.methodState == METHOD_MAY_CONT) && (iret.decision == DECISION_UNCOND_SUCC || iret.decision == DECISION_COND_SUCC || iret.decision == DECISION_FAIL)) {
		ret->methodState = iret.methodState;
		ret->decision = iret.decision;
	}

	return 0;
}

static int eap_ttls_phase2_request_eap_method(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, struct eap_hdr *hdr, size_t len, u8 method, struct wpabuf **resp)
{
#ifdef EAP_TNC
	if (data->tnc_started && data->phase2_method && data->phase2_priv && method == EAP_TYPE_TNC && data->phase2_eap_type.method == EAP_TYPE_TNC) {
		return eap_ttls_phase2_eap_process(sm, data, ret, hdr, len, resp);
	}

	if (data->ready_for_tnc && !data->tnc_started && method == EAP_TYPE_TNC) {
		wpa_printf(MSG_DEBUG, "EAP-TTLS: Start TNC after completed " "EAP method");
		data->tnc_started = 1;
	}

	if (data->tnc_started) {
		if (data->phase2_eap_type.vendor != EAP_VENDOR_IETF || data->phase2_eap_type.method == EAP_TYPE_TNC) {
			wpa_printf(MSG_DEBUG, "EAP-TTLS: Unexpected EAP " "type %d for TNC", method);
			return -1;
		}

		data->phase2_eap_type.vendor = EAP_VENDOR_IETF;
		data->phase2_eap_type.method = method;
		wpa_printf(MSG_DEBUG, "EAP-TTLS: Selected " "Phase 2 EAP vendor %d method %d (TNC)", data->phase2_eap_type.vendor, data->phase2_eap_type.method);

		if (data->phase2_type == EAP_TTLS_PHASE2_EAP) {
			eap_ttls_phase2_eap_deinit(sm, data);
		}
	}
#endif							/* EAP_TNC */

	if (data->phase2_eap_type.vendor == EAP_VENDOR_IETF && data->phase2_eap_type.method == EAP_TYPE_NONE) {
		eap_ttls_phase2_select_eap_method(data, method);
	}

	if (method != data->phase2_eap_type.method || method == EAP_TYPE_NONE) {
		if (eap_peer_tls_phase2_nak(data->phase2_eap_types, data->num_phase2_eap_types, hdr, resp)) {
			return -1;
		}
		return 0;
	}

	if (data->phase2_priv == NULL) {
		data->phase2_method = eap_peer_get_eap_method(EAP_VENDOR_IETF, method);
		if (data->phase2_method) {
			sm->init_phase2 = 1;
			data->phase2_priv = data->phase2_method->init(sm);
			sm->init_phase2 = 0;
		}
	}
	if (data->phase2_priv == NULL || data->phase2_method == NULL) {
		wpa_printf(MSG_INFO, "EAP-TTLS: failed to initialize " "Phase 2 EAP method %d", method);
		return -1;
	}

	return eap_ttls_phase2_eap_process(sm, data, ret, hdr, len, resp);
}

static int eap_ttls_phase2_request_eap(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, struct eap_hdr *hdr, struct wpabuf **resp)
{
	size_t len = be_to_host16(hdr->length);
	u8 *pos;
	struct eap_peer_config *config = eap_get_config(sm);

	if (len <= sizeof(struct eap_hdr)) {
		wpa_printf(MSG_INFO, "EAP-TTLS: too short " "Phase 2 request (len=%lu)", (unsigned long)len);
		return -1;
	}
	pos = (u8 *)(hdr + 1);
	wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase 2 EAP Request: type=%d", *pos);
	switch (*pos) {
	case EAP_TYPE_IDENTITY:
		*resp = eap_sm_buildIdentity(sm, hdr->identifier, 1);
		break;
	default:
		if (eap_ttls_phase2_request_eap_method(sm, data, ret, hdr, len, *pos, resp) < 0) {
			return -1;
		}
		break;
	}

	if (*resp == NULL && (config->pending_req_identity || config->pending_req_password || config->pending_req_otp)) {
		return 0;
	}

	if (*resp == NULL) {
		return -1;
	}

	wpa_hexdump_buf(MSG_DEBUG, "EAP-TTLS: AVP encapsulate EAP Response", *resp);
	return eap_ttls_avp_encapsulate(resp, RADIUS_ATTR_EAP_MESSAGE, 1);
}

static int eap_ttls_phase2_request_mschapv2(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, struct wpabuf **resp)
{
#ifdef EAP_MSCHAPv2
	struct wpabuf *msg;
	u8 *buf, *pos, *challenge, *peer_challenge;
	const u8 *identity, *password;
	size_t identity_len, password_len;
	int pwhash;

	wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase 2 MSCHAPV2 Request");

	identity = eap_get_config_identity(sm, &identity_len);
	password = eap_get_config_password2(sm, &password_len, &pwhash);
	if (identity == NULL || password == NULL) {
		return -1;
	}

	msg = wpabuf_alloc(identity_len + 1000);
	if (msg == NULL) {
		wpa_printf(MSG_ERROR, "EAP-TTLS/MSCHAPV2: Failed to allocate memory");
		return -1;
	}
	pos = buf = wpabuf_mhead(msg);

	/* User-Name */
	pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_USER_NAME, 0, 1, identity, identity_len);

	/* MS-CHAP-Challenge */
	challenge = eap_ttls_implicit_challenge(sm, data, EAP_TTLS_MSCHAPV2_CHALLENGE_LEN + 1);
	if (challenge == NULL) {
		wpabuf_free(msg);
		wpa_printf(MSG_ERROR, "EAP-TTLS/MSCHAPV2: Failed to derive " "implicit challenge");
		return -1;
	}

	pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_MS_CHAP_CHALLENGE, RADIUS_VENDOR_ID_MICROSOFT, 1, challenge, EAP_TTLS_MSCHAPV2_CHALLENGE_LEN);

	/* MS-CHAP2-Response */
	pos = eap_ttls_avp_hdr(pos, RADIUS_ATTR_MS_CHAP2_RESPONSE, RADIUS_VENDOR_ID_MICROSOFT, 1, EAP_TTLS_MSCHAPV2_RESPONSE_LEN);
	data->ident = challenge[EAP_TTLS_MSCHAPV2_CHALLENGE_LEN];
	*pos++ = data->ident;
	*pos++ = 0;					/* Flags */
	if (os_get_random(pos, EAP_TTLS_MSCHAPV2_CHALLENGE_LEN) < 0) {
		os_free(challenge);
		wpabuf_free(msg);
		wpa_printf(MSG_ERROR, "EAP-TTLS/MSCHAPV2: Failed to get " "random data for peer challenge");
		return -1;
	}
	peer_challenge = pos;
	pos += EAP_TTLS_MSCHAPV2_CHALLENGE_LEN;
	os_memset(pos, 0, 8);		/* Reserved, must be zero */
	pos += 8;
	if (mschapv2_derive_response(identity, identity_len, password, password_len, pwhash, challenge, peer_challenge, pos, data->auth_response, data->master_key)) {
		os_free(challenge);
		wpabuf_free(msg);
		wpa_printf(MSG_ERROR, "EAP-TTLS/MSCHAPV2: Failed to derive " "response");
		return -1;
	}
	data->auth_response_valid = 1;

	pos += 24;
	os_free(challenge);
	AVP_PAD(buf, pos);

	wpabuf_put(msg, pos - buf);
	*resp = msg;

	return 0;
#else							/* EAP_MSCHAPv2 */
	wpa_printf(MSG_ERROR, "EAP-TTLS: MSCHAPv2 not included in the build");
	return -1;
#endif							/* EAP_MSCHAPv2 */
}

static int eap_ttls_phase2_request_mschap(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, struct wpabuf **resp)
{
	struct wpabuf *msg;
	u8 *buf, *pos, *challenge;
	const u8 *identity, *password;
	size_t identity_len, password_len;
	int pwhash;

	wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase 2 MSCHAP Request");

	identity = eap_get_config_identity(sm, &identity_len);
	password = eap_get_config_password2(sm, &password_len, &pwhash);
	if (identity == NULL || password == NULL) {
		return -1;
	}

	msg = wpabuf_alloc(identity_len + 1000);
	if (msg == NULL) {
		wpa_printf(MSG_ERROR, "EAP-TTLS/MSCHAP: Failed to allocate memory");
		return -1;
	}
	pos = buf = wpabuf_mhead(msg);

	/* User-Name */
	pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_USER_NAME, 0, 1, identity, identity_len);

	/* MS-CHAP-Challenge */
	challenge = eap_ttls_implicit_challenge(sm, data, EAP_TTLS_MSCHAP_CHALLENGE_LEN + 1);
	if (challenge == NULL) {
		wpabuf_free(msg);
		wpa_printf(MSG_ERROR, "EAP-TTLS/MSCHAP: Failed to derive " "implicit challenge");
		return -1;
	}

	pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_MS_CHAP_CHALLENGE, RADIUS_VENDOR_ID_MICROSOFT, 1, challenge, EAP_TTLS_MSCHAP_CHALLENGE_LEN);

	/* MS-CHAP-Response */
	pos = eap_ttls_avp_hdr(pos, RADIUS_ATTR_MS_CHAP_RESPONSE, RADIUS_VENDOR_ID_MICROSOFT, 1, EAP_TTLS_MSCHAP_RESPONSE_LEN);
	data->ident = challenge[EAP_TTLS_MSCHAP_CHALLENGE_LEN];
	*pos++ = data->ident;
	*pos++ = 1;					/* Flags: Use NT style passwords */
	os_memset(pos, 0, 24);		/* LM-Response */
	pos += 24;
	if (pwhash) {
		challenge_response(challenge, password, pos);	/* NT-Response */
		wpa_hexdump_key(MSG_DEBUG, "EAP-TTLS: MSCHAP password hash", password, 16);
	} else {
		nt_challenge_response(challenge, password, password_len, pos);	/* NT-Response */
		wpa_hexdump_ascii_key(MSG_DEBUG, "EAP-TTLS: MSCHAP password", password, password_len);
	}
	wpa_hexdump(MSG_DEBUG, "EAP-TTLS: MSCHAP implicit challenge", challenge, EAP_TTLS_MSCHAP_CHALLENGE_LEN);
	wpa_hexdump(MSG_DEBUG, "EAP-TTLS: MSCHAP response", pos, 24);
	pos += 24;
	os_free(challenge);
	AVP_PAD(buf, pos);

	wpabuf_put(msg, pos - buf);
	*resp = msg;

	/* EAP-TTLS/MSCHAP does not provide tunneled success
	 * notification, so assume that Phase2 succeeds. */
	ret->methodState = METHOD_DONE;
	ret->decision = DECISION_COND_SUCC;

	return 0;
}

static int eap_ttls_phase2_request_pap(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, struct wpabuf **resp)
{
	struct wpabuf *msg;
	u8 *buf, *pos;
	size_t pad;
	const u8 *identity, *password;
	size_t identity_len, password_len;

	wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase 2 PAP Request");

	identity = eap_get_config_identity(sm, &identity_len);
	password = eap_get_config_password(sm, &password_len);
	if (identity == NULL || password == NULL) {
		return -1;
	}

	msg = wpabuf_alloc(identity_len + password_len + 100);
	if (msg == NULL) {
		wpa_printf(MSG_ERROR, "EAP-TTLS/PAP: Failed to allocate memory");
		return -1;
	}
	pos = buf = wpabuf_mhead(msg);

	/* User-Name */
	pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_USER_NAME, 0, 1, identity, identity_len);

	/* User-Password; in RADIUS, this is encrypted, but EAP-TTLS encrypts
	 * the data, so no separate encryption is used in the AVP itself.
	 * However, the password is padded to obfuscate its length. */
	pad = password_len == 0 ? 16 : (16 - (password_len & 15)) & 15;
	pos = eap_ttls_avp_hdr(pos, RADIUS_ATTR_USER_PASSWORD, 0, 1, password_len + pad);
	os_memcpy(pos, password, password_len);
	pos += password_len;
	os_memset(pos, 0, pad);
	pos += pad;
	AVP_PAD(buf, pos);

	wpabuf_put(msg, pos - buf);
	*resp = msg;

	/* EAP-TTLS/PAP does not provide tunneled success notification,
	 * so assume that Phase2 succeeds. */
	ret->methodState = METHOD_DONE;
	ret->decision = DECISION_COND_SUCC;

	return 0;
}

static int eap_ttls_phase2_request_chap(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, struct wpabuf **resp)
{
	struct wpabuf *msg;
	u8 *buf, *pos, *challenge;
	const u8 *identity, *password;
	size_t identity_len, password_len;

	wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase 2 CHAP Request");

	identity = eap_get_config_identity(sm, &identity_len);
	password = eap_get_config_password(sm, &password_len);
	if (identity == NULL || password == NULL) {
		return -1;
	}

	msg = wpabuf_alloc(identity_len + 1000);
	if (msg == NULL) {
		wpa_printf(MSG_ERROR, "EAP-TTLS/CHAP: Failed to allocate memory");
		return -1;
	}
	pos = buf = wpabuf_mhead(msg);

	/* User-Name */
	pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_USER_NAME, 0, 1, identity, identity_len);

	/* CHAP-Challenge */
	challenge = eap_ttls_implicit_challenge(sm, data, EAP_TTLS_CHAP_CHALLENGE_LEN + 1);
	if (challenge == NULL) {
		wpabuf_free(msg);
		wpa_printf(MSG_ERROR, "EAP-TTLS/CHAP: Failed to derive " "implicit challenge");
		return -1;
	}

	pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_CHAP_CHALLENGE, 0, 1, challenge, EAP_TTLS_CHAP_CHALLENGE_LEN);

	/* CHAP-Password */
	pos = eap_ttls_avp_hdr(pos, RADIUS_ATTR_CHAP_PASSWORD, 0, 1, 1 + EAP_TTLS_CHAP_PASSWORD_LEN);
	data->ident = challenge[EAP_TTLS_CHAP_CHALLENGE_LEN];
	*pos++ = data->ident;

	/* MD5(Ident + Password + Challenge) */
	chap_md5(data->ident, password, password_len, challenge, EAP_TTLS_CHAP_CHALLENGE_LEN, pos);

	wpa_hexdump_ascii(MSG_DEBUG, "EAP-TTLS: CHAP username", identity, identity_len);
	wpa_hexdump_ascii_key(MSG_DEBUG, "EAP-TTLS: CHAP password", password, password_len);
	wpa_hexdump(MSG_DEBUG, "EAP-TTLS: CHAP implicit challenge", challenge, EAP_TTLS_CHAP_CHALLENGE_LEN);
	wpa_hexdump(MSG_DEBUG, "EAP-TTLS: CHAP password", pos, EAP_TTLS_CHAP_PASSWORD_LEN);
	pos += EAP_TTLS_CHAP_PASSWORD_LEN;
	os_free(challenge);
	AVP_PAD(buf, pos);

	wpabuf_put(msg, pos - buf);
	*resp = msg;

	/* EAP-TTLS/CHAP does not provide tunneled success
	 * notification, so assume that Phase2 succeeds. */
	ret->methodState = METHOD_DONE;
	ret->decision = DECISION_COND_SUCC;

	return 0;
}

static int eap_ttls_phase2_request(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, struct eap_hdr *hdr, struct wpabuf **resp)
{
	int res = 0;
	size_t len;
	enum phase2_types phase2_type = data->phase2_type;

#ifdef EAP_TNC
	if (data->tnc_started) {
		wpa_printf(MSG_DEBUG, "EAP-TTLS: Processing TNC");
		phase2_type = EAP_TTLS_PHASE2_EAP;
	}
#endif							/* EAP_TNC */

	if (phase2_type == EAP_TTLS_PHASE2_MSCHAPV2 || phase2_type == EAP_TTLS_PHASE2_MSCHAP || phase2_type == EAP_TTLS_PHASE2_PAP || phase2_type == EAP_TTLS_PHASE2_CHAP) {
		if (eap_get_config_identity(sm, &len) == NULL) {
			wpa_printf(MSG_INFO, "EAP-TTLS: Identity not configured");
			eap_sm_request_identity(sm);
			if (eap_get_config_password(sm, &len) == NULL) {
				eap_sm_request_password(sm);
			}
			return 0;
		}

		if (eap_get_config_password(sm, &len) == NULL) {
			wpa_printf(MSG_INFO, "EAP-TTLS: Password not configured");
			eap_sm_request_password(sm);
			return 0;
		}
	}

	switch (phase2_type) {
	case EAP_TTLS_PHASE2_EAP:
		res = eap_ttls_phase2_request_eap(sm, data, ret, hdr, resp);
		break;
	case EAP_TTLS_PHASE2_MSCHAPV2:
		res = eap_ttls_phase2_request_mschapv2(sm, data, ret, resp);
		break;
	case EAP_TTLS_PHASE2_MSCHAP:
		res = eap_ttls_phase2_request_mschap(sm, data, ret, resp);
		break;
	case EAP_TTLS_PHASE2_PAP:
		res = eap_ttls_phase2_request_pap(sm, data, ret, resp);
		break;
	case EAP_TTLS_PHASE2_CHAP:
		res = eap_ttls_phase2_request_chap(sm, data, ret, resp);
		break;
	default:
		wpa_printf(MSG_ERROR, "EAP-TTLS: Phase 2 - Unknown");
		res = -1;
		break;
	}

	if (res < 0) {
		ret->methodState = METHOD_DONE;
		ret->decision = DECISION_FAIL;
	}

	return res;
}

struct ttls_parse_avp {
	u8 *mschapv2;
	u8 *eapdata;
	size_t eap_len;
	int mschapv2_error;
};

static int eap_ttls_parse_attr_eap(const u8 *dpos, size_t dlen, struct ttls_parse_avp *parse)
{
	wpa_printf(MSG_DEBUG, "EAP-TTLS: AVP - EAP Message");
	if (parse->eapdata == NULL) {
		parse->eapdata = os_malloc(dlen);
		if (parse->eapdata == NULL) {
			wpa_printf(MSG_WARNING, "EAP-TTLS: Failed to allocate " "memory for Phase 2 EAP data");
			return -1;
		}
		os_memcpy(parse->eapdata, dpos, dlen);
		parse->eap_len = dlen;
	} else {
		u8 *neweap = os_realloc(parse->eapdata, parse->eap_len + dlen);
		if (neweap == NULL) {
			wpa_printf(MSG_WARNING, "EAP-TTLS: Failed to allocate " "memory for Phase 2 EAP data");
			return -1;
		}
		os_memcpy(neweap + parse->eap_len, dpos, dlen);
		parse->eapdata = neweap;
		parse->eap_len += dlen;
	}

	return 0;
}

static int eap_ttls_parse_avp(u8 *pos, size_t left, struct ttls_parse_avp *parse)
{
	struct ttls_avp *avp;
	u32 avp_code, avp_length, vendor_id = 0;
	u8 avp_flags, *dpos;
	size_t dlen;

	avp = (struct ttls_avp *)pos;
	avp_code = be_to_host32(avp->avp_code);
	avp_length = be_to_host32(avp->avp_length);
	avp_flags = (avp_length >> 24) & 0xff;
	avp_length &= 0xffffff;
	wpa_printf(MSG_DEBUG, "EAP-TTLS: AVP: code=%d flags=0x%02x " "length=%d", (int)avp_code, avp_flags, (int)avp_length);

	if (avp_length > left) {
		wpa_printf(MSG_WARNING, "EAP-TTLS: AVP overflow " "(len=%d, left=%lu) - dropped", (int)avp_length, (unsigned long)left);
		return -1;
	}

	if (avp_length < sizeof(*avp)) {
		wpa_printf(MSG_WARNING, "EAP-TTLS: Invalid AVP length %d", avp_length);
		return -1;
	}

	dpos = (u8 *)(avp + 1);
	dlen = avp_length - sizeof(*avp);
	if (avp_flags & AVP_FLAGS_VENDOR) {
		if (dlen < 4) {
			wpa_printf(MSG_WARNING, "EAP-TTLS: Vendor AVP " "underflow");
			return -1;
		}
		vendor_id = WPA_GET_BE32(dpos);
		wpa_printf(MSG_DEBUG, "EAP-TTLS: AVP vendor_id %d", (int)vendor_id);
		dpos += 4;
		dlen -= 4;
	}

	wpa_hexdump(MSG_DEBUG, "EAP-TTLS: AVP data", dpos, dlen);

	if (vendor_id == 0 && avp_code == RADIUS_ATTR_EAP_MESSAGE) {
		if (eap_ttls_parse_attr_eap(dpos, dlen, parse) < 0) {
			return -1;
		}
	} else if (vendor_id == 0 && avp_code == RADIUS_ATTR_REPLY_MESSAGE) {
		/* This is an optional message that can be displayed to
		 * the user. */
		wpa_hexdump_ascii(MSG_DEBUG, "EAP-TTLS: AVP - Reply-Message", dpos, dlen);
	} else if (vendor_id == RADIUS_VENDOR_ID_MICROSOFT && avp_code == RADIUS_ATTR_MS_CHAP2_SUCCESS) {
		wpa_hexdump_ascii(MSG_DEBUG, "EAP-TTLS: MS-CHAP2-Success", dpos, dlen);
		if (dlen != 43) {
			wpa_printf(MSG_WARNING, "EAP-TTLS: Unexpected " "MS-CHAP2-Success length " "(len=%lu, expected 43)", (unsigned long)dlen);
			return -1;
		}
		parse->mschapv2 = dpos;
	} else if (vendor_id == RADIUS_VENDOR_ID_MICROSOFT && avp_code == RADIUS_ATTR_MS_CHAP_ERROR) {
		wpa_hexdump_ascii(MSG_DEBUG, "EAP-TTLS: MS-CHAP-Error", dpos, dlen);
		parse->mschapv2_error = 1;
	} else if (avp_flags & AVP_FLAGS_MANDATORY) {
		wpa_printf(MSG_WARNING, "EAP-TTLS: Unsupported mandatory AVP " "code %d vendor_id %d - dropped", (int)avp_code, (int)vendor_id);
		return -1;
	} else {
		wpa_printf(MSG_DEBUG, "EAP-TTLS: Ignoring unsupported AVP " "code %d vendor_id %d", (int)avp_code, (int)vendor_id);
	}

	return avp_length;
}

static int eap_ttls_parse_avps(struct wpabuf *in_decrypted, struct ttls_parse_avp *parse)
{
	u8 *pos;
	size_t left, pad;
	int avp_length;

	pos = wpabuf_mhead(in_decrypted);
	left = wpabuf_len(in_decrypted);
	wpa_hexdump(MSG_DEBUG, "EAP-TTLS: Decrypted Phase 2 AVPs", pos, left);
	if (left < sizeof(struct ttls_avp)) {
		wpa_printf(MSG_WARNING, "EAP-TTLS: Too short Phase 2 AVP frame" " len=%lu expected %lu or more - dropped", (unsigned long)left, (unsigned long)sizeof(struct ttls_avp));
		return -1;
	}

	/* Parse AVPs */
	os_memset(parse, 0, sizeof(*parse));

	while (left > 0) {
		avp_length = eap_ttls_parse_avp(pos, left, parse);
		if (avp_length < 0) {
			return -1;
		}

		pad = (4 - (avp_length & 3)) & 3;
		pos += avp_length + pad;
		if (left < avp_length + pad) {
			left = 0;
		} else {
			left -= avp_length + pad;
		}
	}

	return 0;
}

static u8 *eap_ttls_fake_identity_request(void)
{
	struct eap_hdr *hdr;
	u8 *buf;

	wpa_printf(MSG_DEBUG, "EAP-TTLS: empty data in beginning of " "Phase 2 - use fake EAP-Request Identity");
	buf = os_malloc(sizeof(*hdr) + 1);
	if (buf == NULL) {
		wpa_printf(MSG_WARNING, "EAP-TTLS: failed to allocate " "memory for fake EAP-Identity Request");
		return NULL;
	}

	hdr = (struct eap_hdr *)buf;
	hdr->code = EAP_CODE_REQUEST;
	hdr->identifier = 0;
	hdr->length = host_to_be16(sizeof(*hdr) + 1);
	buf[sizeof(*hdr)] = EAP_TYPE_IDENTITY;

	return buf;
}

static int eap_ttls_encrypt_response(struct eap_sm *sm, struct eap_ttls_data *data, struct wpabuf *resp, u8 identifier, struct wpabuf **out_data)
{
	if (resp == NULL) {
		return 0;
	}

	wpa_hexdump_buf_key(MSG_DEBUG, "EAP-TTLS: Encrypting Phase 2 data", resp);
	if (eap_peer_tls_encrypt(sm, &data->ssl, EAP_TYPE_TTLS, data->ttls_version, identifier, resp, out_data)) {
		wpa_printf(MSG_INFO, "EAP-TTLS: Failed to encrypt a Phase 2 " "frame");
		wpabuf_free(resp);
		return -1;
	}
	wpabuf_free(resp);

	return 0;
}

static int eap_ttls_process_phase2_eap(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, struct ttls_parse_avp *parse, struct wpabuf **resp)
{
	struct eap_hdr *hdr;
	size_t len;

	if (parse->eapdata == NULL) {
		wpa_printf(MSG_WARNING, "EAP-TTLS: No EAP Message in the " "packet - dropped");
		return -1;
	}

	wpa_hexdump(MSG_DEBUG, "EAP-TTLS: Phase 2 EAP", parse->eapdata, parse->eap_len);
	hdr = (struct eap_hdr *)parse->eapdata;

	if (parse->eap_len < sizeof(*hdr)) {
		wpa_printf(MSG_WARNING, "EAP-TTLS: Too short Phase 2 EAP " "frame (len=%lu, expected %lu or more) - dropped", (unsigned long)parse->eap_len, (unsigned long)sizeof(*hdr));
		return -1;
	}
	len = be_to_host16(hdr->length);
	if (len > parse->eap_len) {
		wpa_printf(MSG_INFO, "EAP-TTLS: Length mismatch in Phase 2 " "EAP frame (EAP hdr len=%lu, EAP data len in " "AVP=%lu)", (unsigned long)len, (unsigned long)parse->eap_len);
		return -1;
	}
	wpa_printf(MSG_DEBUG, "EAP-TTLS: received Phase 2: code=%d " "identifier=%d length=%lu", hdr->code, hdr->identifier, (unsigned long)len);
	switch (hdr->code) {
	case EAP_CODE_REQUEST:
		if (eap_ttls_phase2_request(sm, data, ret, hdr, resp)) {
			wpa_printf(MSG_INFO, "EAP-TTLS: Phase2 Request " "processing failed");
			return -1;
		}
		break;
	default:
		wpa_printf(MSG_INFO, "EAP-TTLS: Unexpected code=%d in " "Phase 2 EAP header", hdr->code);
		return -1;
	}

	return 0;
}

static int eap_ttls_process_phase2_mschapv2(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, struct ttls_parse_avp *parse)
{
#ifdef EAP_MSCHAPv2
	if (parse->mschapv2_error) {
		wpa_printf(MSG_DEBUG, "EAP-TTLS/MSCHAPV2: Received " "MS-CHAP-Error - failed");
		ret->methodState = METHOD_DONE;
		ret->decision = DECISION_FAIL;
		/* Reply with empty data to ACK error */
		return 1;
	}

	if (parse->mschapv2 == NULL) {
#ifdef EAP_TNC
		if (data->phase2_success && parse->eapdata) {
			/*
			 * Allow EAP-TNC to be started after successfully
			 * completed MSCHAPV2.
			 */
			return 1;
		}
#endif							/* EAP_TNC */
		wpa_printf(MSG_WARNING, "EAP-TTLS: no MS-CHAP2-Success AVP " "received for Phase2 MSCHAPV2");
		return -1;
	}
	if (parse->mschapv2[0] != data->ident) {
		wpa_printf(MSG_WARNING, "EAP-TTLS: Ident mismatch for Phase 2 " "MSCHAPV2 (received Ident 0x%02x, expected 0x%02x)", parse->mschapv2[0], data->ident);
		return -1;
	}
	if (!data->auth_response_valid || mschapv2_verify_auth_response(data->auth_response, parse->mschapv2 + 1, 42)) {
		wpa_printf(MSG_WARNING, "EAP-TTLS: Invalid authenticator " "response in Phase 2 MSCHAPV2 success request");
		return -1;
	}

	wpa_printf(MSG_INFO, "EAP-TTLS: Phase 2 MSCHAPV2 " "authentication succeeded");
	ret->methodState = METHOD_DONE;
	ret->decision = DECISION_UNCOND_SUCC;
	data->phase2_success = 1;

	/*
	 * Reply with empty data; authentication server will reply
	 * with EAP-Success after this.
	 */
	return 1;
#else							/* EAP_MSCHAPv2 */
	wpa_printf(MSG_ERROR, "EAP-TTLS: MSCHAPv2 not included in the build");
	return -1;
#endif							/* EAP_MSCHAPv2 */
}

#ifdef EAP_TNC
static int eap_ttls_process_tnc_start(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, struct ttls_parse_avp *parse, struct wpabuf **resp)
{
	/* TNC uses inner EAP method after non-EAP TTLS phase 2. */
	if (parse->eapdata == NULL) {
		wpa_printf(MSG_INFO, "EAP-TTLS: Phase 2 received " "unexpected tunneled data (no EAP)");
		return -1;
	}

	if (!data->ready_for_tnc) {
		wpa_printf(MSG_INFO, "EAP-TTLS: Phase 2 received " "EAP after non-EAP, but not ready for TNC");
		return -1;
	}

	wpa_printf(MSG_DEBUG, "EAP-TTLS: Start TNC after completed " "non-EAP method");
	data->tnc_started = 1;

	if (eap_ttls_process_phase2_eap(sm, data, ret, parse, resp) < 0) {
		return -1;
	}

	return 0;
}
#endif							/* EAP_TNC */

static int eap_ttls_process_decrypted(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, u8 identifier, struct ttls_parse_avp *parse, struct wpabuf *in_decrypted, struct wpabuf **out_data)
{
	struct wpabuf *resp = NULL;
	struct eap_peer_config *config = eap_get_config(sm);
	int res;
	enum phase2_types phase2_type = data->phase2_type;

#ifdef EAP_TNC
	if (data->tnc_started) {
		phase2_type = EAP_TTLS_PHASE2_EAP;
	}
#endif							/* EAP_TNC */

	switch (phase2_type) {
	case EAP_TTLS_PHASE2_EAP:
		if (eap_ttls_process_phase2_eap(sm, data, ret, parse, &resp) < 0) {
			return -1;
		}
		break;
	case EAP_TTLS_PHASE2_MSCHAPV2:
		res = eap_ttls_process_phase2_mschapv2(sm, data, ret, parse);
#ifdef EAP_TNC
		if (res == 1 && parse->eapdata && data->phase2_success) {
			/*
			 * TNC may be required as the next
			 * authentication method within the tunnel.
			 */
			ret->methodState = METHOD_MAY_CONT;
			data->ready_for_tnc = 1;
			if (eap_ttls_process_tnc_start(sm, data, ret, parse, &resp) == 0) {
				break;
			}
		}
#endif							/* EAP_TNC */
		return res;
	case EAP_TTLS_PHASE2_MSCHAP:
	case EAP_TTLS_PHASE2_PAP:
	case EAP_TTLS_PHASE2_CHAP:
#ifdef EAP_TNC
		if (eap_ttls_process_tnc_start(sm, data, ret, parse, &resp) < 0) {
			return -1;
		}
		break;
#else							/* EAP_TNC */
		/* EAP-TTLS/{MSCHAP,PAP,CHAP} should not send any TLS tunneled
		 * requests to the supplicant */
		wpa_printf(MSG_INFO, "EAP-TTLS: Phase 2 received unexpected " "tunneled data");
		return -1;
#endif							/* EAP_TNC */
	}

	if (resp) {
		if (eap_ttls_encrypt_response(sm, data, resp, identifier, out_data) < 0) {
			return -1;
		}
	} else if (config->pending_req_identity || config->pending_req_password || config->pending_req_otp || config->pending_req_new_password) {
		wpabuf_free(data->pending_phase2_req);
		data->pending_phase2_req = wpabuf_dup(in_decrypted);
	}

	return 0;
}

static int eap_ttls_implicit_identity_request(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, u8 identifier, struct wpabuf **out_data)
{
	int retval = 0;
	struct eap_hdr *hdr;
	struct wpabuf *resp;

	hdr = (struct eap_hdr *)eap_ttls_fake_identity_request();
	if (hdr == NULL) {
		ret->methodState = METHOD_DONE;
		ret->decision = DECISION_FAIL;
		return -1;
	}

	resp = NULL;
	if (eap_ttls_phase2_request(sm, data, ret, hdr, &resp)) {
		wpa_printf(MSG_INFO, "EAP-TTLS: Phase2 Request " "processing failed");
		retval = -1;
	} else {
		struct eap_peer_config *config = eap_get_config(sm);
		if (resp == NULL && (config->pending_req_identity || config->pending_req_password || config->pending_req_otp || config->pending_req_new_password)) {
			/*
			 * Use empty buffer to force implicit request
			 * processing when EAP request is re-processed after
			 * user input.
			 */
			wpabuf_free(data->pending_phase2_req);
			data->pending_phase2_req = wpabuf_alloc(0);
		}

		retval = eap_ttls_encrypt_response(sm, data, resp, identifier, out_data);
	}

	os_free(hdr);

	if (retval < 0) {
		ret->methodState = METHOD_DONE;
		ret->decision = DECISION_FAIL;
	}

	return retval;
}

static int eap_ttls_phase2_start(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, u8 identifier, struct wpabuf **out_data)
{
	data->phase2_start = 0;

	/*
	 * EAP-TTLS does not use Phase2 on fast re-auth; this must be done only
	 * if TLS part was indeed resuming a previous session. Most
	 * Authentication Servers terminate EAP-TTLS before reaching this
	 * point, but some do not. Make wpa_supplicant stop phase 2 here, if
	 * needed.
	 */
	if (data->reauth && tls_connection_resumed(sm->ssl_ctx, data->ssl.conn)) {
		wpa_printf(MSG_DEBUG, "EAP-TTLS: Session resumption - " "skip phase 2");
		*out_data = eap_peer_tls_build_ack(identifier, EAP_TYPE_TTLS, data->ttls_version);
		ret->methodState = METHOD_DONE;
		ret->decision = DECISION_UNCOND_SUCC;
		data->phase2_success = 1;
		return 0;
	}

	return eap_ttls_implicit_identity_request(sm, data, ret, identifier, out_data);
}

static int eap_ttls_decrypt(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, u8 identifier, const struct wpabuf *in_data, struct wpabuf **out_data)
{
	struct wpabuf *in_decrypted = NULL;
	int retval = 0;
	struct ttls_parse_avp parse;

	os_memset(&parse, 0, sizeof(parse));

	wpa_printf(MSG_DEBUG, "EAP-TTLS: received %lu bytes encrypted data for" " Phase 2", in_data ? (unsigned long)wpabuf_len(in_data) : 0);

	if (data->pending_phase2_req) {
		wpa_printf(MSG_DEBUG, "EAP-TTLS: Pending Phase 2 request - " "skip decryption and use old data");
		/* Clear TLS reassembly state. */
		eap_peer_tls_reset_input(&data->ssl);

		in_decrypted = data->pending_phase2_req;
		data->pending_phase2_req = NULL;
		if (wpabuf_len(in_decrypted) == 0) {
			wpabuf_free(in_decrypted);
			return eap_ttls_implicit_identity_request(sm, data, ret, identifier, out_data);
		}
		goto continue_req;
	}

	if ((in_data == NULL || wpabuf_len(in_data) == 0) && data->phase2_start) {
		return eap_ttls_phase2_start(sm, data, ret, identifier, out_data);
	}

	if (in_data == NULL || wpabuf_len(in_data) == 0) {
		/* Received TLS ACK - requesting more fragments */
		return eap_peer_tls_encrypt(sm, &data->ssl, EAP_TYPE_TTLS, data->ttls_version, identifier, NULL, out_data);
	}

	retval = eap_peer_tls_decrypt(sm, &data->ssl, in_data, &in_decrypted);
	if (retval) {
		goto done;
	}

continue_req:
	data->phase2_start = 0;

	if (eap_ttls_parse_avps(in_decrypted, &parse) < 0) {
		retval = -1;
		goto done;
	}

	retval = eap_ttls_process_decrypted(sm, data, ret, identifier, &parse, in_decrypted, out_data);

done:
	wpabuf_free(in_decrypted);
	os_free(parse.eapdata);

	if (retval < 0) {
		ret->methodState = METHOD_DONE;
		ret->decision = DECISION_FAIL;
	}

	return retval;
}

static int eap_ttls_process_handshake(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret, u8 identifier, const struct wpabuf *in_data, struct wpabuf **out_data)
{
	int res;

	res = eap_peer_tls_process_helper(sm, &data->ssl, EAP_TYPE_TTLS, data->ttls_version, identifier, in_data, out_data);

	if (tls_connection_established(sm->ssl_ctx, data->ssl.conn)) {
		wpa_printf(MSG_DEBUG, "EAP-TTLS: TLS done, proceed to " "Phase 2");
		if (data->resuming) {
			wpa_printf(MSG_DEBUG, "EAP-TTLS: fast reauth - may " "skip Phase 2");
			ret->decision = DECISION_COND_SUCC;
			ret->methodState = METHOD_MAY_CONT;
		}
		data->phase2_start = 1;
		eap_ttls_v0_derive_key(sm, data);

		if (*out_data == NULL || wpabuf_len(*out_data) == 0) {
			if (eap_ttls_decrypt(sm, data, ret, identifier, NULL, out_data)) {
				wpa_printf(MSG_WARNING, "EAP-TTLS: " "failed to process early " "start for Phase 2");
			}
			res = 0;
		}
		data->resuming = 0;
	}

	if (res == 2) {
		/*
		 * Application data included in the handshake message.
		 */
		wpabuf_free(data->pending_phase2_req);
		data->pending_phase2_req = *out_data;
		*out_data = NULL;
		res = eap_ttls_decrypt(sm, data, ret, identifier, in_data, out_data);
	}

	return res;
}

static void eap_ttls_check_auth_status(struct eap_sm *sm, struct eap_ttls_data *data, struct eap_method_ret *ret)
{
	if (ret->methodState == METHOD_DONE) {
		ret->allowNotifications = FALSE;
		if (ret->decision == DECISION_UNCOND_SUCC || ret->decision == DECISION_COND_SUCC) {
			wpa_printf(MSG_DEBUG, "EAP-TTLS: Authentication " "completed successfully");
			data->phase2_success = 1;
#ifdef EAP_TNC
			if (!data->ready_for_tnc && !data->tnc_started) {
				/*
				 * TNC may be required as the next
				 * authentication method within the tunnel.
				 */
				ret->methodState = METHOD_MAY_CONT;
				data->ready_for_tnc = 1;
			}
#endif							/* EAP_TNC */
		}
	} else if (ret->methodState == METHOD_MAY_CONT && (ret->decision == DECISION_UNCOND_SUCC || ret->decision == DECISION_COND_SUCC)) {
		wpa_printf(MSG_DEBUG, "EAP-TTLS: Authentication " "completed successfully (MAY_CONT)");
		data->phase2_success = 1;
	}
}

static struct wpabuf *eap_ttls_process(struct eap_sm *sm, void *priv, struct eap_method_ret *ret, const struct wpabuf *reqData)
{
	size_t left;
	int res;
	u8 flags, id;
	struct wpabuf *resp;
	const u8 *pos;
	struct eap_ttls_data *data = priv;
	struct wpabuf msg;

	pos = eap_peer_tls_process_init(sm, &data->ssl, EAP_TYPE_TTLS, ret, reqData, &left, &flags);
	if (pos == NULL) {
		return NULL;
	}
	id = eap_get_id(reqData);

	if (flags & EAP_TLS_FLAGS_START) {
		wpa_printf(MSG_DEBUG, "EAP-TTLS: Start (server ver=%d, own " "ver=%d)", flags & EAP_TLS_VERSION_MASK, data->ttls_version);

		/* RFC 5281, Ch. 9.2:
		 * "This packet MAY contain additional information in the form
		 * of AVPs, which may provide useful hints to the client"
		 * For now, ignore any potential extra data.
		 */
		left = 0;
	}

	wpabuf_set(&msg, pos, left);

	resp = NULL;
	if (tls_connection_established(sm->ssl_ctx, data->ssl.conn) && !data->resuming) {
		res = eap_ttls_decrypt(sm, data, ret, id, &msg, &resp);
	} else {
		res = eap_ttls_process_handshake(sm, data, ret, id, &msg, &resp);
	}

	eap_ttls_check_auth_status(sm, data, ret);

	/* FIX: what about res == -1? Could just move all error processing into
	 * the other functions and get rid of this res==1 case here. */
	if (res == 1) {
		wpabuf_free(resp);
		return eap_peer_tls_build_ack(id, EAP_TYPE_TTLS, data->ttls_version);
	}
	return resp;
}

static Boolean eap_ttls_has_reauth_data(struct eap_sm *sm, void *priv)
{
	struct eap_ttls_data *data = priv;
	return tls_connection_established(sm->ssl_ctx, data->ssl.conn) && data->phase2_success;
}

static void eap_ttls_deinit_for_reauth(struct eap_sm *sm, void *priv)
{
	struct eap_ttls_data *data = priv;
	wpabuf_free(data->pending_phase2_req);
	data->pending_phase2_req = NULL;
#ifdef EAP_TNC
	data->ready_for_tnc = 0;
	data->tnc_started = 0;
#endif							/* EAP_TNC */
}

static void *eap_ttls_init_for_reauth(struct eap_sm *sm, void *priv)
{
	struct eap_ttls_data *data = priv;
	eap_ttls_free_key(data);
	os_free(data->session_id);
	data->session_id = NULL;
	if (eap_peer_tls_reauth_init(sm, &data->ssl)) {
		os_free(data);
		return NULL;
	}
	if (data->phase2_priv && data->phase2_method && data->phase2_method->init_for_reauth) {
		data->phase2_method->init_for_reauth(sm, data->phase2_priv);
	}
	data->phase2_start = 0;
	data->phase2_success = 0;
	data->resuming = 1;
	data->reauth = 1;
	return priv;
}

static int eap_ttls_get_status(struct eap_sm *sm, void *priv, char *buf, size_t buflen, int verbose)
{
	struct eap_ttls_data *data = priv;
	int len, ret;

	len = eap_peer_tls_status(sm, &data->ssl, buf, buflen, verbose);
	ret = os_snprintf(buf + len, buflen - len, "EAP-TTLSv%d Phase2 method=", data->ttls_version);
	if (os_snprintf_error(buflen - len, ret)) {
		return len;
	}
	len += ret;
	switch (data->phase2_type) {
	case EAP_TTLS_PHASE2_EAP:
		ret = os_snprintf(buf + len, buflen - len, "EAP-%s\n", data->phase2_method ? data->phase2_method->name : "?");
		break;
	case EAP_TTLS_PHASE2_MSCHAPV2:
		ret = os_snprintf(buf + len, buflen - len, "MSCHAPV2\n");
		break;
	case EAP_TTLS_PHASE2_MSCHAP:
		ret = os_snprintf(buf + len, buflen - len, "MSCHAP\n");
		break;
	case EAP_TTLS_PHASE2_PAP:
		ret = os_snprintf(buf + len, buflen - len, "PAP\n");
		break;
	case EAP_TTLS_PHASE2_CHAP:
		ret = os_snprintf(buf + len, buflen - len, "CHAP\n");
		break;
	default:
		ret = 0;
		break;
	}
	if (os_snprintf_error(buflen - len, ret)) {
		return len;
	}
	len += ret;

	return len;
}

static Boolean eap_ttls_isKeyAvailable(struct eap_sm *sm, void *priv)
{
	struct eap_ttls_data *data = priv;
	return data->key_data != NULL && data->phase2_success;
}

static u8 *eap_ttls_getKey(struct eap_sm *sm, void *priv, size_t *len)
{
	struct eap_ttls_data *data = priv;
	u8 *key;

	if (data->key_data == NULL || !data->phase2_success) {
		return NULL;
	}

	key = os_malloc(EAP_TLS_KEY_LEN);
	if (key == NULL) {
		return NULL;
	}

	*len = EAP_TLS_KEY_LEN;
	os_memcpy(key, data->key_data, EAP_TLS_KEY_LEN);

	return key;
}

static u8 *eap_ttls_get_session_id(struct eap_sm *sm, void *priv, size_t *len)
{
	struct eap_ttls_data *data = priv;
	u8 *id;

	if (data->session_id == NULL || !data->phase2_success) {
		return NULL;
	}

	id = os_malloc(data->id_len);
	if (id == NULL) {
		return NULL;
	}

	*len = data->id_len;
	os_memcpy(id, data->session_id, data->id_len);

	return id;
}

static u8 *eap_ttls_get_emsk(struct eap_sm *sm, void *priv, size_t *len)
{
	struct eap_ttls_data *data = priv;
	u8 *key;

	if (data->key_data == NULL) {
		return NULL;
	}

	key = os_malloc(EAP_EMSK_LEN);
	if (key == NULL) {
		return NULL;
	}

	*len = EAP_EMSK_LEN;
	os_memcpy(key, data->key_data + EAP_TLS_KEY_LEN, EAP_EMSK_LEN);

	return key;
}

int eap_peer_ttls_register(void)
{
	struct eap_method *eap;
	int ret;

	eap = eap_peer_method_alloc(EAP_PEER_METHOD_INTERFACE_VERSION, EAP_VENDOR_IETF, EAP_TYPE_TTLS, "TTLS");
	if (eap == NULL) {
		return -1;
	}

	eap->init = eap_ttls_init;
	eap->deinit = eap_ttls_deinit;
	eap->process = eap_ttls_process;
	eap->isKeyAvailable = eap_ttls_isKeyAvailable;
	eap->getKey = eap_ttls_getKey;
	eap->getSessionId = eap_ttls_get_session_id;
	eap->get_status = eap_ttls_get_status;
	eap->has_reauth_data = eap_ttls_has_reauth_data;
	eap->deinit_for_reauth = eap_ttls_deinit_for_reauth;
	eap->init_for_reauth = eap_ttls_init_for_reauth;
	eap->get_emsk = eap_ttls_get_emsk;

	ret = eap_peer_method_register(eap);
	if (ret) {
		eap_peer_method_free(eap);
	}
	return ret;
}


text:
package Collections.NonLinear.Tree;

import Collections.NonLinear.Tree.Interfaces.HeapADT;

/**
 * Created by aluno on 1/5/16.
 * @param <T>
 */
public class LinkedHeap<T> extends LinkedBinaryTree<T> implements HeapADT<T> {

    public LinkedHeap() {
     super();
    }

    public LinkedHeap(T element) {
        super(element);
    }

    @Override
    public void addElement(T obj) {

    }

    @Override
    public T removeMin() {
        return null;
    }

    @Override
    public T findMin() {
        return null;
    }
}


text:
<?php

if( !function_exists( "info_bar_theme_free_trial" ) ) {
	function info_bar_theme_free_trial( $atts, $content = null ){
		$style_id = $settings_encoded = $load_on_refresh = '';
		extract(shortcode_atts(array(
			'style_id'			=> '',
			'settings_encoded'	=> '',
	    ), $atts));

		$settings = base64_decode( $settings_encoded );
		$style_settings = unserialize( $settings );

		foreach($style_settings as $key => $setting){
			$style_settings[$key] = apply_filters('smile_render_setting',$setting);
		}

		unset($style_settings['style_id']);

		//	Generate UID
		$uid 		= uniqid();
		$uid_class	= 'content-'.$uid;

		//	Individual style variables
		$individual_vars = array(
			'uid'				=> $uid,
			'uid_class'			=> $uid_class,
			'style_class' 		=> 'cp-free-trial'
		);

		global $cp_form_vars;

		/**
		 * Merge short code variables arrays
		 *
		 * @array 	$individual_vars		Individual style EXTRA short code variables
		 * @array 	$style_settings			Individual style short code variables
		 * @array 	$cp_form_vars			CP Form global short code variables
		 */
		$all = array_merge(
			$individual_vars,
			$style_settings,
			$cp_form_vars,
			$atts
		);

		//	Extract short code variables
		$a = shortcode_atts( $all, $style_settings );

		/** = Before filter
		 *-----------------------------------------------------------*/
		apply_filters_ref_array( 'cp_ib_global_before', array( $a ) );

		$el_class = $info_bar_size_style = $close_class = '';

		/**
		 * 	Move Form to Next Line
		 *
		 */
		$cp_info_bar_body_class = '';

		if( $a['on_success'] == "redirect" ){
			$on_success_action = $a['redirect_url'];
		} elseif( $a['on_success'] == "message" ) {
			$on_success_action = $a['success_message'] ;
		} else {
			$on_success_action = "Close";
		}

		$button_css = "background:".$a['button_bg_color'].";";

		//info bar image
		$info_bar_image 		= apply_filters( 'cp_get_info_bar_image_url', $a );

		//info bar image alt text
		$info_bar_alt 		= apply_filters( 'cp_get_info_bar_image_alt', $a );

		$imageStyle		    = cp_add_css( 'max-width', $a['image_size'], 'px');
		$imageStyle		   .= cp_add_css( 'width', $a['image_size'], 'px');

		$img_class ='';
		if( $a['image_displayon_mobile'] ) {
			$img_class .= 'cp_ifb_hide_img';
		}

		//ob_start();
		?>

			<img style="<?php echo esc_attr($imageStyle); ?>" src="<?php echo esc_attr( $info_bar_image ); ?>" class="cp-image <?php echo esc_attr( $img_class );?>" <?php echo $info_bar_alt ;?> >

            <div class="cp-msg-container <?php echo ( trim( $a['infobar_title'] ) == "" ? "cp-empty" : '' );  ?>">
                <?php echo do_shortcode( html_entity_decode( stripcslashes( $a['infobar_title'] ) ) ); ?>

			<div class="cp-info-bar-desc-container <?php echo ( trim( $a['infobar_description'] ) == "" ? "cp-empty" : '' );  ?>">

<?php echo do_shortcode( html_entity_decode( stripcslashes( $a['infobar_description'] ) ) ); ?>

        		<?php
             		/**
					 * Embed CP Form
					 */
					apply_filters_ref_array('cp_get_form', array( $a ) );
				?>

<?php

    /** = After filter
	 *-----------------------------------------------------------*/
	apply_filters_ref_array( 'cp_ib_global_after', array( $a ) );

	return ob_get_clean();

	}
}


text:
<?php

/**
 * DO NOT EDIT!
 * This file was automatically generated via bin/generate-validator-spec.php.
 */

namespace AmpProject\Validator\Spec\AttributeList;

use AmpProject\Html\Attribute;
use AmpProject\Validator\Spec\AttributeList;
use AmpProject\Validator\Spec\Identifiable;
use AmpProject\Validator\Spec\SpecRule;

/**
 * Attribute list class AmpFacebook.
 *
 * @package ampproject/amp-toolbox.
 *
 * @property-read array<bool> $dataHref
 */
final class AmpFacebook extends AttributeList implements Identifiable
{
    /**
     * ID of the attribute list.
     *
     * @var string
     */
    const ID = 'amp-facebook';

    /**
     * Array of attributes.
     *
     * @var array<array>
     */
    const ATTRIBUTES = [
        Attribute::DATA_HREF => [
            SpecRule::MANDATORY => true,
        ],
    ];
}


text:
"""
Copyright (c) 2011, 2012, Regents of the University of California
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

 - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the
   distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
"""
"""
Generic driver for XML sources.  Uses an XSLT transform to transform
the data into sMAP-XML.

@author Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
"""

from twisted.internet import defer, threads
from twisted.python import log

import time
from lxml import etree
import urllib2
import urlparse

from smap import util, core
from smap.driver import FetchDriver
from smap.contrib import dtutil

class XMLDriver(FetchDriver):
    """Driver for generic XML documents.  They are expected to be in
    sMAP-XML format, which is basically the smap definitions directly
    mapped into XML.  To make this easier, you can apply an XSLT
    transformation to your document before processing with this
    module.

    Parameters:

    Xslt: path of XSLT stylesheet used to transform document.
        Optional if the source is already in sMAP-XML
    Timefmt = python strptime string used to parse the time in the
        document.  XSLTv1 doesn't have much in the way of time processing
        and anyways it's a pain to use.
    """
    def setup(self, opts):
        FetchDriver.setup(self, opts)      # set up the getter
        self.xslt = opts.get('Xslt', None) # transformation to be applied
        self.timefmt = opts.get("Timeformat", None)
        self.timezone = opts.get("Timezone", 'UTC')
        self.ignore_time = opts.get('IgnoreTimestamps', False)
        if self.xslt:
            with open(self.xslt, "r") as fp:
                self.xslt = etree.XSLT(etree.XML(fp.read()))

    def parse_val(self, ts, val):
        if ts['Properties']['ReadingType'] == 'long':
            return int(val)
        elif ts['Properties']['ReadingType'] == 'double':
            return float(val)
        else:
            return val

    def parse_time(self, ts, val):
        if self.timefmt == None:
            return int(val)
        else:
            return dtutil.dt2ts(dtutil.strptime_tz(val, self.timefmt,
                                                   self.timezone))

    def make_jsonts(self, xmlts):
        """Transform a sMAP-XML Properties and Metadata section into json
        """
        ts = {
            'Properties': {'UnitofMeasure': ''},
            'Metadata': {},
            'Readings': []
            }
        for c in xmlts.getchildren():
            if c.tag == 'Properties':
                for p in c.getchildren():
                    if p.text != None: ts['Properties'][p.tag] = p.text
            elif c.tag == 'Metadata':
                for cat in c.getchildren():
                    for field in cat.getchildren():
                        f = ts['Metadata'].get(cat.tag, {})
                        f[field.tag] = field.text
                        ts['Metadata'][cat.tag] = f
        if not 'Timezone' in ts['Properties']:
            ts['Properties']['Timezone'] = self.timezone
        return ts

    def process(self, data):
        # maybe transform to smap-xml
        data = etree.XML(data)
        if self.xslt:
            data = self.xslt(data)

        for xmlts in data.getroot().getchildren():
            if not 'path' in xmlts.attrib:
                log.err("skipping timeseries: no path attribute")
                continue

            # maybe make/add a new timeseries if we haven't seen this one before
            path = xmlts.attrib['path']
            ts = self.get_timeseries(path)
            if not ts:
                ts = self.make_jsonts(xmlts)
                ts['uuid'] = self.uuid(path)
                ts = core.Timeseries(ts, None)
                self.add_timeseries(path, ts)

        for xmlts in data.getroot().getchildren():
            if not 'path' in xmlts.attrib:
                continue
            # add all of the readings
            path = xmlts.attrib['path']
            for r in xmlts.find('Readings').getchildren():
                try:
                    if not self.ignore_time:
                        rtime = self.parse_time(ts, r.find("Timestamp").text)
                    else:
                        rtime = time.time()
                    rval = self.parse_val(ts, r.find("Value").text)
                except (ValueError, TypeError), e:
                    log.err()
                    continue
                self._add(path, rtime, rval)


text:
const Int_t    gkDummyRunBeg = 0;
const Int_t    gkDummyRunEnd = 999999999;
AliCDBStorage *gStorLoc      = 0;

//_____________________________________________________________________________
TMap* CreateDCSAliasMap(Int_t entries) {
  // Creates a DCS structure
  // The structure is the following:
  //   TMap (key --> value)
  //     <DCSAlias> --> <valueList>
  //     <DCSAlias> is a string
  //     <valueList> is a TObjArray of AliDCSValue
  //     An AliDCSValue consists of timestamp and a value in form of a AliSimpleValue

  // Each contains 1000 values randomly generated by TRandom::Gaus + 5*nAlias

  TMap* aliasMap = new TMap;
  aliasMap->SetOwner(1);

  TRandom random;

  for(int nAlias=0;nAlias<entries;nAlias++)
  {
    TObjArray* valueSet = new TObjArray;
    valueSet->SetOwner(1);

    TString aliasName="DCSAlias";
    aliasName += nAlias;
    //printf("\n\n alias: %s\n\n",aliasName.Data());

    for (int timeStamp=0;timeStamp<1000;timeStamp+=10)
    {
      AliDCSValue* dcsVal = new AliDCSValue((Float_t) (random.Gaus()+5*nAlias), timeStamp);
      //printf("%s\n",dcsVal->ToString().Data());
      valueSet->Add(dcsVal);
    }
    aliasMap->Add(new TObjString(aliasName), valueSet);
  }

  return aliasMap;
}

//_____________________________________________________________________________
AliCDBMetaData *CreateMetaObject(const char *objectClassName)
{

  AliCDBMetaData *md1= new AliCDBMetaData();
  md1->SetObjectClassName(objectClassName);
  md1->SetResponsible("Frederick Kramer");
  md1->SetBeamPeriod(1);
  md1->SetAliRootVersion("05-26-00b"); //root version
  md1->SetComment("Ideal DCS DP CDB object");

  return md1;

}

//_____________________________________________________________________________
void StoreObject(const char* cdbPath, AliTRDSensorArray* object, AliCDBMetaData* metaData)
{

  AliCDBId id1(cdbPath,gkDummyRunBeg,gkDummyRunEnd);
  gStorLoc->Put(object,id1,metaData);

}

//_____________________________________________________________________________
void AliTRDCreateDummyCDB_DP()
{

  cout << endl
       << "TRD :: Creating dummy CDB for the runs "
       << gkDummyRunBeg
       << " -- "
       << gkDummyRunEnd
       << endl;

  AliCDBManager *man = AliCDBManager::Instance();
  gStorLoc = man->GetStorage("local://$ALICE_ROOT/OCDB");
  if (!gStorLoc) {
    return;
  }

  AliCDBMetaData *metaData = 0;
  TObjArray* list = AliTRDSensorArray::GetList();

  if (list == 0x0) {
    printf("Error during AliTRDSensorArray::GetList\n");
    printf("DCS will not be processing\n");
  }

  Int_t nEntries = list->GetEntries();
  printf("%d alias loaded\n", nEntries);

  Bool_t* results = new Bool_t [nEntries];
  Int_t*  nGraph  = new Int_t [nEntries];
  TMap* dcsAliasMap = CreateDCSAliasMap(nEntries);

  for (Int_t iAlias = 0; iAlias < nEntries; iAlias++) {

    AliTRDSensorArray * oneTRDDCS = (AliTRDSensorArray *)list->At(iAlias);

    oneTRDDCS->SetStartTime(TTimeStamp (1000000000));
    oneTRDDCS->SetEndTime(TTimeStamp (2000000000));
    printf("Processing DCS : \"%s\"\n", oneTRDDCS->GetStoreName().Data());

    TMap * map;
    map = oneTRDDCS->ExtractDCS(dcsAliasMap);
    nGraph[iAlias] = map->GetEntries();
    oneTRDDCS->SetGraph(map);

    char ocdbpath[256];
    sprintf(ocdbpath, "TRD/Calib/%s", oneTRDDCS->GetStoreName().Data());
    metaData = CreateMetaObject(oneTRDDCS->GetStoreName().Data());

    StoreObject(ocdbpath, oneTRDDCS, metaData);
  }

}


text:
/**
 * 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.
 */

#ifndef __STOUT_OS_CLOSE_HPP__
#define __STOUT_OS_CLOSE_HPP__

#include <unistd.h>

#include <stout/error.hpp>
#include <stout/nothing.hpp>
#include <stout/try.hpp>

namespace os {

inline Try<Nothing> close(int fd)
{
  if (::close(fd) != 0) {
    return ErrnoError();
  }

  return Nothing();
}

} // namespace os {

#endif // __STOUT_OS_CLOSE_HPP__


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="malow.gladiatus.activities.MainActivity"
    android:id="@+id/character_info_main_frame">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/character_info_main_view"></LinearLayout>

</RelativeLayout>


text:
package com.github.springclips.repositories;

import org.springframework.data.repository.Repository;

import java.io.Serializable;

public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
    <S extends T> S save(S entity);
    T findOne(ID id);
    Iterable<T> findAll();
    void delete(ID id);
}


text:
<app-header></app-header>
<app-main-nav></app-main-nav>

        <router-outlet></router-outlet>

<app-footer></app-footer>


text:
/*
 * Zed Attack Proxy (ZAP) and its related class files.
 *
 * ZAP is an HTTP/HTTPS proxy for assessing web application security.
 *
 * 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.
 */

package org.zaproxy.zap.spider;

import org.zaproxy.zap.spider.filters.FetchFilter.FetchStatus;

/**
 * The listener interface for receiving spider related events. The class that is interested in
 * processing a spider event implements this interface, and the object created with that class is
 * registered with a component using the component's
 * addSpiderListener method. When  the spider event occurs, that object's appropriate
 * method is invoked.
 */
public interface SpiderListener {

	/**
	 * Event triggered when the Spider progress has changed.
	 *
	 * @param percentageComplete the percentage complete
	 * @param numberCrawled the number of pages crawled
	 * @param numberToCrawl the number of pages left to crawl
	 */
	void spiderProgress(int percentageComplete, int numberCrawled, int numberToCrawl);

	/**
	 * Event triggered when a new uri was found. The status parameter says if the URI
	 * was skipped according to any skip rule or it was processed.
	 *
	 * @param uri the uri
	 * @param method the method used for accessing the uri
	 * @param status the {@link FetchStatus} stating if this uri will be processed, and, if not,
	 *            stating the reason of the filtering
	 */
	void foundURI(String uri, String method, FetchStatus status);

	/**
	 * Notifies that a new {@link SpiderTask}'s result is available.
	 *
	 * @param spiderTaskResult the result of the spider task.
	 */
	void notifySpiderTaskResult(SpiderTaskResult spiderTaskResult);

	/**
	 * Event triggered when the spider is finished. This event is triggered either when the spider
	 * has completed scanning a website, in which case the parameter successful is
	 * true , either when it was stopped by an user in which case the
	 * successful parameter is false.
	 *
	 * @param successful

	 *
true - when the spider has scanned a website completely and finished by its
	 *            own

	 *
false - when the spider was stopped by the user

	 *

	 */
	void spiderComplete(boolean successful);

}


text:
import * as Promise from "bluebird";
import {CacheEntity, RenderingCache} from "./server-cache";
import {EntityQueryBuilder, EntityReadDb, QueryBuilder} from "./entity-db";

export class CacheQueryBuilder implements QueryBuilder<CacheQueryBuilder> {
    private db: EntityReadDb;
    private query: EntityQueryBuilder;
    private cache: RenderingCache;

    constructor(cache: RenderingCache, db: EntityReadDb, level: number) {
        this.cache = cache;
        this.db = db;
        this.query = db.find(level);
    }

    public run(): Promise<CacheEntity[]> {
        return this.query.run().then(entities => this.cache.addEntities(entities));
    }

    public idIn(ids: number[]): CacheQueryBuilder {
        this.query.idIn(ids);
        return this;
    }

    public implementsType(type: string): CacheQueryBuilder {
        this.query.implementsType(type);
        return this;
    }

    public valueEquals(type: string, field: string, value: (any | string | boolean | number)): CacheQueryBuilder {
        this.query.valueEquals(type, field, value);
        return this;
    }

    public valueIn(type: string, field: string, values: Array<any | string | boolean | number>): CacheQueryBuilder {
        this.query.valueIn(type, field, values);
        return this;
    }

    public arrayContains(type: string, field: string, value: (any | string | boolean | number)): CacheQueryBuilder {
        this.query.arrayContains(type, field, value);
        return this;
    }

    public arrayContainsAny(type: string, field: string, values: Array<any | string | boolean | number>): CacheQueryBuilder {
        this.query.arrayContainsAny(type, field, values);
        return this;
    }
}


text:
package com.facebook.buck.eden;

import com.facebook.buck.io.unixsocket.UnixDomainSocket;
import com.facebook.eden.thrift.EdenError;
import com.facebook.eden.thrift.EdenService;
import com.facebook.eden.thrift.MountInfo;
import com.facebook.thrift.TException;
import com.facebook.thrift.protocol.TBinaryProtocol;
import com.facebook.thrift.protocol.TProtocol;
import com.facebook.thrift.transport.TSocket;
import com.facebook.thrift.transport.TTransport;
import com.facebook.thrift.transport.TTransportException;
import com.google.common.annotations.VisibleForTesting;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;

import javax.annotation.Nullable;

/**
 * Client of Eden's fbthrift API. Note that there should be at most one Eden client per machine,
 * though it may have zero or more mount points.
 */
public final class EdenClient {
  /**
   * Instances of {@link com.facebook.eden.thrift.EdenService.Client} are not thread-safe, so we
   * create them via a {@link ThreadLocal} rather than create a new client for each Thrift call.
   */
  private final ThreadLocal<EdenService.Client> clientFactory;

  /**
   * @param clientFactory creates one Thrift client per thread through which Eden Thrift API calls
   *     should be made.
   */
  private EdenClient(ThreadLocal<EdenService.Client> clientFactory) {
    this.clientFactory = clientFactory;
  }

  @VisibleForTesting
  EdenClient(final EdenService.Client client) {
    this(new ThreadLocal<EdenService.Client>() {
      @Override
      protected EdenService.Client initialValue() {
        return client;
      }
    });
  }

  public static Optional<EdenClient> newInstance() {
    // The default path for the Eden socket is ~/local/.eden/socket.
    Path socketFile = Paths.get(
        System.getProperty("user.home"),
        "local/.eden/socket");
    return newInstance(socketFile);
  }

  private static Optional<EdenClient> newInstance(final Path socketFile) {
    ThreadLocal<EdenService.Client> clientFactory = new ThreadLocal<EdenService.Client>() {
      /**
       * @return {@code null} if there is no instance of Eden to connect to because this method
       *     cannot throw checked exceptions to signal a failure.
       */
      @Override
      @Nullable
      protected EdenService.Client initialValue() {
        TTransport transport;
        try {
          UnixDomainSocket socket = UnixDomainSocket.createSocketWithPath(socketFile);
          transport = new TSocket(socket);
        } catch (IOException | TTransportException e) {
          return null;
        }
        // No need to invoke transport.open() because the UnixDomainSocket is already connected.
        TProtocol protocol = new TBinaryProtocol(transport);
        return new EdenService.Client(protocol);
      }
    };

    // We forcibly try to create an EdenService.Client as a way of verifying that `socketFile` is a
    // valid UNIX domain socket for talking to Eden. If this is not the case, then we should not
    // return a new EdenClient.
    EdenService.Client client = clientFactory.get();
    if (client != null) {
      return Optional.of(new EdenClient(clientFactory));
    } else {
      return Optional.empty();
    }
  }

  public List<MountInfo> getMountInfos() throws EdenError, TException {
    return clientFactory.get().listMounts();
  }

  /**
   * @return an Eden mount point if {@code projectRoot} is backed by Eden or {@code null}.
   */
  @Nullable
  public EdenMount getMountFor(Path projectRoot) throws EdenError, TException {
    for (MountInfo info : getMountInfos()) {
      // Note that we cannot use Paths.get() here because that will break unit tests where we mix
      // java.nio.file.Path and Jimfs Path objects.
      Path mountPoint = projectRoot.getFileSystem().getPath(info.mountPoint);
      if (projectRoot.startsWith(mountPoint)) {
        return new EdenMount(clientFactory, mountPoint, projectRoot);
      }
    }
    return null;
  }
}